Skip to content

Commit 4e63c59

Browse files
committed
fix(billing): judge the run's admitted payer for hosted model keys
1 parent 236d332 commit 4e63c59

8 files changed

Lines changed: 50 additions & 14 deletions

File tree

‎apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ const formatCredits = (credits: number) => credits.toLocaleString('en-US')
2020
const PRICING_FAQS = [
2121
{
2222
question: 'Is Sim free?',
23-
answer: `Yes. The Free plan costs $0 and includes ${formatCredits(DEFAULT_FREE_CREDITS * CREDITS_PER_DOLLAR)} one-time credits, one workspace, and all ${INTEGRATION_COUNT_LABEL} integrations, with no credit card required. On Free, models and tools run on your own provider keys; Sim-hosted keys come with Pro and Max. Sim is also open source, so you can self-host it for free.`,
23+
answer: `Yes. The Free plan costs $0 and includes ${formatCredits(DEFAULT_FREE_CREDITS * CREDITS_PER_DOLLAR)} one-time credits, one workspace, and all ${INTEGRATION_COUNT_LABEL} integrations, with no credit card required. On Free, models and tools run on your own provider keys; Sim-hosted keys come with paid plans. Sim is also open source, so you can self-host it for free.`,
2424
},
2525
{
2626
question: 'How much does Sim cost?',

‎apps/sim/executor/handlers/pi/core/keys.test.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,14 @@ describe('resolvePiModelKey', () => {
6767
workspaceId: 'ws-1',
6868
})
6969
).resolves.toEqual({ apiKey: 'sk-hosted', isBYOK: false })
70-
expect(mockGetApiKeyWithBYOK).toHaveBeenCalledWith('anthropic', 'claude', 'ws-1', undefined)
70+
expect(mockGetApiKeyWithBYOK).toHaveBeenCalledWith(
71+
'anthropic',
72+
'claude',
73+
'ws-1',
74+
undefined,
75+
undefined,
76+
undefined
77+
)
7178
})
7279

7380
it('Create PR falls back to a stored workspace key when the field is empty', async () => {
@@ -110,7 +117,14 @@ describe('resolvePiModelKey', () => {
110117
workspaceId: 'ws-1',
111118
})
112119
).resolves.toEqual({ apiKey: 'sk-hosted', isBYOK: false })
113-
expect(mockGetApiKeyWithBYOK).toHaveBeenCalledWith('anthropic', 'claude', 'ws-1', undefined)
120+
expect(mockGetApiKeyWithBYOK).toHaveBeenCalledWith(
121+
'anthropic',
122+
'claude',
123+
'ws-1',
124+
undefined,
125+
undefined,
126+
undefined
127+
)
114128
})
115129
})
116130

‎apps/sim/executor/handlers/pi/core/keys.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import type { CreateAgentSessionOptions } from '@earendil-works/pi-coding-agent'
2222
import { getApiKeyWithBYOK, getBYOKKey } from '@/lib/api-key/byok'
23+
import type { UsageUpgradePayer } from '@/lib/billing/usage-upgrade'
2324
import { calculateBillableModelCost } from '@/providers/cost-policy'
2425
import type { PiSupportedProvider } from '@/providers/pi-provider-configs'
2526
import {
@@ -49,6 +50,7 @@ interface ResolvePiModelKeyParams {
4950
mode: PiKeyMode
5051
workspaceId?: string
5152
apiKey?: string
53+
billingAttribution?: UsageUpgradePayer
5254
}
5355

5456
/** Resolves a usable API key for an already validated provider/model pair. */
@@ -79,7 +81,9 @@ export async function resolvePiModelKey(params: ResolvePiModelKeyParams): Promis
7981
providerId,
8082
params.model,
8183
params.workspaceId,
82-
undefined
84+
undefined,
85+
undefined,
86+
params.billingAttribution
8387
)
8488
return { apiKey, isBYOK }
8589
}

‎apps/sim/executor/handlers/pi/handler.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,7 @@ export class PiBlockHandler implements BlockHandler {
232232
mode,
233233
workspaceId: ctx.workspaceId,
234234
apiKey: asRawString(inputs.apiKey),
235+
billingAttribution: ctx.metadata.billingAttribution,
235236
})
236237

237238
const search = await this.resolveSearch(ctx, inputs, mode)

‎apps/sim/lib/api-key/byok.integration.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ vi.mock('@sim/db', async () => {
1919
})
2020
return { db: drizzle(fixture.client) }
2121
})
22-
vi.mock('@/lib/core/config/env-flags', () => ({ isHosted: true }))
22+
vi.mock('@/lib/core/config/env-flags', () => ({ isHosted: true, isBillingEnabled: false }))
2323
vi.mock('@/providers/models', () => ({ getHostedModels: () => ['gpt-4.1-mini'] }))
2424
vi.mock('@/providers/utils', () => ({ PROVIDER_PLACEHOLDER_KEY: 'fixture-placeholder' }))
2525
vi.mock('@/lib/api-key/byok-entitlement', () => ({

‎apps/sim/lib/api-key/byok.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -379,12 +379,18 @@ describe('getApiKeyWithBYOK for a payer without paid access', () => {
379379

380380
it("refuses Sim's key with a paid-plan error when the caller has no key of its own", async () => {
381381
const workspaceId = uniqueWorkspaceId()
382+
const attribution = {
383+
billingEntity: { type: 'user' as const, id: 'free-payer' },
384+
payerSubscription: null,
385+
}
382386

383-
await expect(getApiKeyWithBYOK('anthropic', HOSTED_MODEL, workspaceId)).rejects.toMatchObject({
387+
await expect(
388+
getApiKeyWithBYOK('anthropic', HOSTED_MODEL, workspaceId, undefined, undefined, attribution)
389+
).rejects.toMatchObject({
384390
statusCode: 402,
385391
message: expect.stringContaining('available on paid plans'),
386392
})
387-
expect(mockMayUseHostedKey).toHaveBeenCalledWith(workspaceId)
393+
expect(mockMayUseHostedKey).toHaveBeenCalledWith(workspaceId, attribution)
388394
expect(mockGetRotatingApiKey).not.toHaveBeenCalled()
389395
})
390396

‎apps/sim/lib/api-key/byok.ts‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
HostedKeyRequiresPaidPlanError,
1212
mayUseHostedKey,
1313
} from '@/lib/billing/core/hosted-key-access'
14+
import type { UsageUpgradePayer } from '@/lib/billing/usage-upgrade'
1415
import { getRotatingApiKey } from '@/lib/core/config/api-keys'
1516
import { env } from '@/lib/core/config/env'
1617
import { isHosted } from '@/lib/core/config/env-flags'
@@ -232,17 +233,18 @@ async function resolveBYOKKey(
232233
}
233234

234235
/**
235-
* Serves a catalogued hosted model: Sim's key from `keyPool` when the workspace's payer may use it
236+
* Serves a catalogued hosted model: Sim's key from `keyPool` when the run's payer may use it
236237
* ({@link mayUseHostedKey}), otherwise the caller's own key. A caller's key is not Sim's, so it is
237238
* reported as `isBYOK` and its usage is never billed.
238239
*/
239240
async function resolveHostedModelKey(
240241
keyPool: string,
241242
model: string,
242243
workspaceId: string | undefined | null,
243-
userProvidedKey: string | undefined
244+
userProvidedKey: string | undefined,
245+
billingAttribution: UsageUpgradePayer | undefined
244246
): Promise<{ apiKey: string; isBYOK: boolean }> {
245-
if (!(await mayUseHostedKey(workspaceId))) {
247+
if (!(await mayUseHostedKey(workspaceId, billingAttribution))) {
246248
if (userProvidedKey) return { apiKey: userProvidedKey, isBYOK: true }
247249
throw new HostedKeyRequiresPaidPlanError(model)
248250
}
@@ -267,7 +269,8 @@ export async function getApiKeyWithBYOK(
267269
model: string,
268270
workspaceId: string | undefined | null,
269271
userProvidedKey?: string,
270-
signal?: AbortSignal
272+
signal?: AbortSignal,
273+
billingAttribution?: UsageUpgradePayer
271274
): Promise<{ apiKey: string; isBYOK: boolean; scope?: BYOKKeyScopeName }> {
272275
if (provider === 'ollama') {
273276
return { apiKey: 'empty', isBYOK: false }
@@ -301,7 +304,13 @@ export async function getApiKeyWithBYOK(
301304
if (isHosted) {
302305
const isModelHosted = getHostedModels().some((m) => m.toLowerCase() === model.toLowerCase())
303306
if (isModelHosted) {
304-
return resolveHostedModelKey('fireworks', model, workspaceId, userProvidedKey)
307+
return resolveHostedModelKey(
308+
'fireworks',
309+
model,
310+
workspaceId,
311+
userProvidedKey,
312+
billingAttribution
313+
)
305314
}
306315

307316
if (userProvidedKey) {
@@ -463,7 +472,8 @@ export async function getApiKeyWithBYOK(
463472
isGeminiModel ? 'gemini' : provider,
464473
model,
465474
workspaceId,
466-
userProvidedKey
475+
userProvidedKey,
476+
billingAttribution
467477
)
468478
}
469479
}

‎apps/sim/providers/index.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,8 @@ export async function executeProviderRequest(
261261
request.model,
262262
request.workspaceId,
263263
request.apiKey,
264-
request.abortSignal
264+
request.abortSignal,
265+
runtimeContext?.executionContext?.metadata.billingAttribution
265266
)
266267
resolvedRequest = { ...resolvedRequest, apiKey: result.apiKey }
267268
isBYOK = result.isBYOK

0 commit comments

Comments
 (0)