From 236d332c056e9f55eae10279beb2e9e70d37849c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 11:49:03 -0800 Subject: [PATCH 1/3] fix(billing): reserve Sim's hosted model and tool keys for paid plans Free-plan payers without prepaid credits no longer run on Sim's hosted provider keys. One gate, mayUseHostedKey, now guards both hosted model keys (getApiKeyWithBYOK) and hosted tool keys (executeTool), replacing the per-tool requiresPaidPlan opt-in. BYOK keys and keys passed on the block keep working; a caller's own key on a hosted model is reported as BYOK so its usage is not billed. --- apps/docs/content/docs/platform/costs.mdx | 4 +- .../components/pricing-faq/pricing-faq.tsx | 2 +- .../comparison-table/comparison-data.ts | 4 ++ apps/sim/lib/api-key/byok.test.ts | 60 +++++++++++++++++++ apps/sim/lib/api-key/byok.ts | 52 ++++++++++------ apps/sim/lib/billing/core/chat-access.ts | 6 +- .../sim/lib/billing/core/hosted-key-access.ts | 51 ++++++++++++++++ apps/sim/tools/errors.ts | 13 ---- apps/sim/tools/image/generate.ts | 1 - apps/sim/tools/index.test.ts | 3 +- apps/sim/tools/index.ts | 56 ++++------------- apps/sim/tools/types.ts | 5 -- apps/sim/tools/video/falai.ts | 1 - 13 files changed, 167 insertions(+), 91 deletions(-) create mode 100644 apps/sim/lib/billing/core/hosted-key-access.ts diff --git a/apps/docs/content/docs/platform/costs.mdx b/apps/docs/content/docs/platform/costs.mdx index 31a95b8d67f..13a483821e9 100644 --- a/apps/docs/content/docs/platform/costs.mdx +++ b/apps/docs/content/docs/platform/costs.mdx @@ -21,6 +21,8 @@ A billable workflow run can include: | Hosted tools | Operation charges when using Sim-provided provider keys | | Sandbox runtime | Applicable runtime charges, such as a Pi sandbox | +Sim-hosted models and tools are available on paid plans. On the Free plan, add your own provider keys under **Settings → BYOK**; a run that needs a Sim-hosted key fails with an upgrade message instead. + With your own provider keys, you pay the provider directly for those calls. The workflow base charge and unrelated hosted-tool or sandbox usage still apply. Local Ollama or vLLM inference avoids an external model API charge, but still needs infrastructure and any enabled Sim run charge. For a simple uncached model call, with prices in USD per million tokens: @@ -86,7 +88,7 @@ Saved-key precedence is resolved separately for each provider: 1. Use that provider's workspace key pool when one is configured. 2. Otherwise, use its eligible organization key pool. -3. Otherwise, use the next available configured source, including a Sim-hosted key where supported. +3. Otherwise, use the next available configured source, including a Sim-hosted key where supported and your plan is paid. A workspace OpenAI key does not override the organization's Anthropic key. The settings page marks inherited providers so you can inspect inheritance before adding an override. A nonempty workspace pool is exclusive; a corrupt workspace key is not a reason to borrow an organization key. diff --git a/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx b/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx index 03a2e9cf267..51f00625798 100644 --- a/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx +++ b/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx @@ -20,7 +20,7 @@ const formatCredits = (credits: number) => credits.toLocaleString('en-US') const PRICING_FAQS = [ { question: 'Is Sim free?', - 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. Sim is also open source, so you can self-host it for free.`, + 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.`, }, { question: 'How much does Sim cost?', diff --git a/apps/sim/app/workspace/[workspaceId]/upgrade/components/comparison-table/comparison-data.ts b/apps/sim/app/workspace/[workspaceId]/upgrade/components/comparison-table/comparison-data.ts index d193aa30dac..badb0d3a16f 100644 --- a/apps/sim/app/workspace/[workspaceId]/upgrade/components/comparison-table/comparison-data.ts +++ b/apps/sim/app/workspace/[workspaceId]/upgrade/components/comparison-table/comparison-data.ts @@ -93,6 +93,10 @@ export const COMPARISON_SECTIONS: ComparisonSection[] = [ 'Custom', ], }, + { + label: 'Sim-hosted models & tools', + values: [false, true, true, true], + }, ], }, { diff --git a/apps/sim/lib/api-key/byok.test.ts b/apps/sim/lib/api-key/byok.test.ts index a675215ce24..9d569e8aeb6 100644 --- a/apps/sim/lib/api-key/byok.test.ts +++ b/apps/sim/lib/api-key/byok.test.ts @@ -29,6 +29,15 @@ const { mockGetRotatingApiKey } = vi.hoisted(() => ({ mockGetRotatingApiKey: vi.fn(), })) +const { mockMayUseHostedKey } = vi.hoisted(() => ({ + mockMayUseHostedKey: vi.fn(async () => true), +})) + +vi.mock('@/lib/billing/core/hosted-key-access', async (importOriginal) => ({ + ...(await importOriginal()), + mayUseHostedKey: mockMayUseHostedKey, +})) + vi.mock('@/providers/models', () => providersModelsMock) vi.mock('@/providers/utils', () => providersUtilsMock) @@ -357,6 +366,57 @@ describe('getApiKeyWithBYOK for TypeSafe', () => { }) }) +describe('getApiKeyWithBYOK for a payer without paid access', () => { + const HOSTED_MODEL = 'claude-fixture-hosted' + + beforeEach(() => { + resetDbChainMock() + setEnvFlags({ isHosted: true }) + mockGetHostedModels.mockReturnValue([HOSTED_MODEL]) + mockGetRotatingApiKey.mockReturnValue('platform-anthropic-key') + mockMayUseHostedKey.mockResolvedValue(false) + }) + + it("refuses Sim's key with a paid-plan error when the caller has no key of its own", async () => { + const workspaceId = uniqueWorkspaceId() + + await expect(getApiKeyWithBYOK('anthropic', HOSTED_MODEL, workspaceId)).rejects.toMatchObject({ + statusCode: 402, + message: expect.stringContaining('available on paid plans'), + }) + expect(mockMayUseHostedKey).toHaveBeenCalledWith(workspaceId) + expect(mockGetRotatingApiKey).not.toHaveBeenCalled() + }) + + it("serves the caller's own key as BYOK so its usage is never billed", async () => { + await expect( + getApiKeyWithBYOK('anthropic', HOSTED_MODEL, uniqueWorkspaceId(), 'caller-key') + ).resolves.toEqual({ apiKey: 'caller-key', isBYOK: true }) + expect(mockGetRotatingApiKey).not.toHaveBeenCalled() + }) + + it('runs a workspace BYOK key without consulting the plan', async () => { + dbChainMockFns.orderBy.mockResolvedValue([storedKey('own-key')]) + mockDecryptSecret.mockImplementation(async (encrypted: string) => ({ + decrypted: encrypted.replace('encrypted-', 'decrypted-'), + })) + + await expect( + getApiKeyWithBYOK('anthropic', HOSTED_MODEL, uniqueWorkspaceId()) + ).resolves.toEqual({ apiKey: 'decrypted-own-key', isBYOK: true, scope: 'workspace' }) + expect(mockMayUseHostedKey).not.toHaveBeenCalled() + }) + + it('refuses the hosted Fireworks pool the same way', async () => { + mockGetHostedModels.mockReturnValue(['fireworks/glm-fixture']) + + await expect( + getApiKeyWithBYOK('fireworks', 'fireworks/glm-fixture', uniqueWorkspaceId()) + ).rejects.toMatchObject({ statusCode: 402 }) + expect(mockGetRotatingApiKey).not.toHaveBeenCalled() + }) +}) + describe('getApiKeyWithBYOK for Fireworks', () => { const HOSTED_POOL_MODEL = 'fireworks/glm-5.2' diff --git a/apps/sim/lib/api-key/byok.ts b/apps/sim/lib/api-key/byok.ts index 6c41150b4f3..1c8f92ac84b 100644 --- a/apps/sim/lib/api-key/byok.ts +++ b/apps/sim/lib/api-key/byok.ts @@ -7,6 +7,10 @@ import { backoffWithJitter } from '@sim/utils/retry' import { and, asc, eq, notExists } from 'drizzle-orm' import { LRUCache } from 'lru-cache' import { isOrganizationBYOKEntitledCached } from '@/lib/api-key/byok-entitlement' +import { + HostedKeyRequiresPaidPlanError, + mayUseHostedKey, +} from '@/lib/billing/core/hosted-key-access' import { getRotatingApiKey } from '@/lib/core/config/api-keys' import { env } from '@/lib/core/config/env' import { isHosted } from '@/lib/core/config/env-flags' @@ -227,6 +231,29 @@ async function resolveBYOKKey( ) } +/** + * Serves a catalogued hosted model: Sim's key from `keyPool` when the workspace's payer may use it + * ({@link mayUseHostedKey}), otherwise the caller's own key. A caller's key is not Sim's, so it is + * reported as `isBYOK` and its usage is never billed. + */ +async function resolveHostedModelKey( + keyPool: string, + model: string, + workspaceId: string | undefined | null, + userProvidedKey: string | undefined +): Promise<{ apiKey: string; isBYOK: boolean }> { + if (!(await mayUseHostedKey(workspaceId))) { + if (userProvidedKey) return { apiKey: userProvidedKey, isBYOK: true } + throw new HostedKeyRequiresPaidPlanError(model) + } + try { + return { apiKey: getRotatingApiKey(keyPool), isBYOK: false } + } catch { + if (userProvidedKey) return { apiKey: userProvidedKey, isBYOK: true } + throw new Error(`No API key available for ${keyPool} ${model}`) + } +} + /** * Resolves credentials for the provider already selected by model routing. * Discovery lists must not override that provider and select a different key pool. @@ -274,15 +301,7 @@ export async function getApiKeyWithBYOK( if (isHosted) { const isModelHosted = getHostedModels().some((m) => m.toLowerCase() === model.toLowerCase()) if (isModelHosted) { - try { - const serverKey = getRotatingApiKey('fireworks') - return { apiKey: serverKey, isBYOK: false } - } catch (_error) { - if (userProvidedKey) { - return { apiKey: userProvidedKey, isBYOK: false } - } - throw new Error(`No API key available for fireworks ${model}`) - } + return resolveHostedModelKey('fireworks', model, workspaceId, userProvidedKey) } if (userProvidedKey) { @@ -440,15 +459,12 @@ export async function getApiKeyWithBYOK( logger.debug('No BYOK key found, falling back', { provider, model, workspaceId }) if (isModelHosted) { - try { - const serverKey = getRotatingApiKey(isGeminiModel ? 'gemini' : provider) - return { apiKey: serverKey, isBYOK: false } - } catch (_error) { - if (userProvidedKey) { - return { apiKey: userProvidedKey, isBYOK: false } - } - throw new Error(`No API key available for ${provider} ${model}`) - } + return resolveHostedModelKey( + isGeminiModel ? 'gemini' : provider, + model, + workspaceId, + userProvidedKey + ) } } } diff --git a/apps/sim/lib/billing/core/chat-access.ts b/apps/sim/lib/billing/core/chat-access.ts index 7e86759e023..f5623df2839 100644 --- a/apps/sim/lib/billing/core/chat-access.ts +++ b/apps/sim/lib/billing/core/chat-access.ts @@ -18,9 +18,9 @@ interface PaidAccessOptions { /** * Whether a payer may use a feature a hosted deployment reserves for paying payers: Chat, and - * hosted keys a tool marks `requiresPaidPlan`. A hosted deployment that bills withholds these from - * a payer on the free plan, unless that payer holds prepaid credits, which an admin grants to - * customers billed outside a subscription. + * Sim's hosted provider keys. A hosted deployment that bills withholds these from a payer on the + * free plan, unless that payer holds prepaid credits, which an admin grants to customers billed + * outside a subscription. * * The plan is the payer's entitled subscription (active or past due), so a canceled * plan reads as free; a blocked payer is refused by the usage check every caller runs next. diff --git a/apps/sim/lib/billing/core/hosted-key-access.ts b/apps/sim/lib/billing/core/hosted-key-access.ts new file mode 100644 index 00000000000..ce82cde328b --- /dev/null +++ b/apps/sim/lib/billing/core/hosted-key-access.ts @@ -0,0 +1,51 @@ +import { resolveWorkspaceBillingPayer } from '@/lib/billing/core/attribution' +import { payerHasPaidAccess } from '@/lib/billing/core/chat-access' +import type { UsageUpgradePayer } from '@/lib/billing/usage-upgrade' +import { isBillingEnabled, isHosted } from '@/lib/core/config/env-flags' +import { HttpError } from '@/lib/core/utils/http-error' + +/** + * Sim's hosted key was withheld because the run's payer is on the free plan. Carries a 402 so the + * run fails as the caller's plan, not as a Sim fault. + */ +export class HostedKeyRequiresPaidPlanError extends HttpError { + readonly statusCode = 402 + + /** @param subject - what asked for the key: a tool's name or a model id */ + constructor(subject: string) { + super( + `${subject} with Sim's hosted key is available on paid plans. Upgrade your plan, or add your own API key under Settings > BYOK.` + ) + this.name = 'HostedKeyRequiresPaidPlanError' + } +} + +/** + * Whether a run may spend on Sim's hosted provider keys, for models and tools alike: only a payer + * with paid access ({@link payerHasPaidAccess}) may. The payer is the run's admitted attribution, + * or the workspace's payer for a surface that carries none; a workspace without a payer, or a free + * payer whose credit balance cannot be read, is refused. + */ +export async function mayUseHostedKey( + workspaceId: string | null | undefined, + billingAttribution?: UsageUpgradePayer +): Promise { + if (!isHosted || !isBillingEnabled) return true + + let payer = billingAttribution ?? null + if (!payer && workspaceId) { + const workspacePayer = await resolveWorkspaceBillingPayer(workspaceId, { + onMissing: 'return-null', + }) + if (workspacePayer) { + payer = { + billingEntity: workspacePayer.organizationId + ? { type: 'organization', id: workspacePayer.organizationId } + : { type: 'user', id: workspacePayer.billedAccountUserId }, + payerSubscription: workspacePayer.payerSubscription, + } + } + } + + return payer !== null && payerHasPaidAccess(payer, { onBalanceUnavailable: 'deny' }) +} diff --git a/apps/sim/tools/errors.ts b/apps/sim/tools/errors.ts index 316d103f17e..8a8809258a7 100644 --- a/apps/sim/tools/errors.ts +++ b/apps/sim/tools/errors.ts @@ -17,19 +17,6 @@ export class HostedKeyRateLimitedError extends HttpError { } } -/** - * The tool's hosted key is reserved for paying payers and this run's payer is on the free plan. - * Carries a 402 so the run fails as the caller's plan, not as a Sim fault. - */ -export class HostedKeyRequiresPaidPlanError extends HttpError { - readonly statusCode = 402 - - constructor(message: string) { - super(message) - this.name = 'HostedKeyRequiresPaidPlanError' - } -} - /** No hosted keys are configured or available for this provider. */ export class HostedKeyUnavailableError extends HttpError { readonly statusCode = 503 diff --git a/apps/sim/tools/image/generate.ts b/apps/sim/tools/image/generate.ts index 19cc3927fc7..92fb806b3b5 100644 --- a/apps/sim/tools/image/generate.ts +++ b/apps/sim/tools/image/generate.ts @@ -129,7 +129,6 @@ export const imageGenerateTool: ImageGenerationToolConfig = { apiKeyParam: 'apiKey', byokProviderId: 'falai', exactCostSettlement: 'falai', - requiresPaidPlan: true, pricing: { type: 'custom', getCost: (_params, output) => { diff --git a/apps/sim/tools/index.test.ts b/apps/sim/tools/index.test.ts index 7020b8c3ced..a80897b5f00 100644 --- a/apps/sim/tools/index.test.ts +++ b/apps/sim/tools/index.test.ts @@ -7890,7 +7890,7 @@ describe('Hosted Key Injection', () => { } }) - describe('requiresPaidPlan', () => { + describe('hosted key paid access', () => { const PAID_ONLY_TOOL_ID = 'test_paid_only_hosting' beforeEach(() => { @@ -7912,7 +7912,6 @@ describe('Hosted Key Injection', () => { envKeyPrefix: 'TEST_HOSTED_KEY', apiKeyParam: 'apiKey', byokProviderId: 'falai', - requiresPaidPlan: true, pricing: { type: 'per_request', cost: 0.5 }, rateLimit: { mode: 'per_request', requestsPerMinute: 100 }, }, diff --git a/apps/sim/tools/index.ts b/apps/sim/tools/index.ts index 15fbf79284e..f75dac5edc5 100644 --- a/apps/sim/tools/index.ts +++ b/apps/sim/tools/index.ts @@ -11,12 +11,13 @@ import type { InternalSandboxProfile } from '@/lib/auth/internal' import { BILLING_ATTRIBUTION_HEADER, type BillingAttributionSnapshot, - resolveWorkspaceBillingPayer, serializeBillingAttributionHeader, } from '@/lib/billing/core/attribution' -import { payerHasPaidAccess } from '@/lib/billing/core/chat-access' -import type { UsageUpgradePayer } from '@/lib/billing/usage-upgrade' -import { isBillingEnabled, isHosted } from '@/lib/core/config/env-flags' +import { + HostedKeyRequiresPaidPlanError, + mayUseHostedKey, +} from '@/lib/billing/core/hosted-key-access' +import { isHosted } from '@/lib/core/config/env-flags' import { findDatabaseQueryError, getUserFacingErrorMessage, @@ -119,11 +120,7 @@ import { } from '@/executor/utils/resolved-secret-trace-registry' import type { ErrorInfo } from '@/tools/error-extractors' import { extractErrorMessage, redactErrorData } from '@/tools/error-extractors' -import { - HostedKeyRateLimitedError, - HostedKeyRequiresPaidPlanError, - HostedKeyUnavailableError, -} from '@/tools/errors' +import { HostedKeyRateLimitedError, HostedKeyUnavailableError } from '@/tools/errors' import { getOwnEnumerableDataEntries, prepareToolRequest, @@ -586,40 +583,6 @@ async function registerAssistantCredentialSecrets( } } -/** - * Refuses a `requiresPaidPlan` hosted key to a run whose payer lacks paid access. The payer is - * the run's admitted attribution, or the workspace's payer for a surface that carries none; a - * workspace without a payer, or a free payer whose credit balance cannot be read, is refused. - */ -async function assertPayerMayUseHostedKey( - tool: ToolDefinition, - workspaceId: string | undefined, - billingAttribution: BillingAttributionSnapshot | undefined -): Promise { - if (!isBillingEnabled) return - - let payer: UsageUpgradePayer | null = billingAttribution ?? null - if (!payer && workspaceId) { - const workspacePayer = await resolveWorkspaceBillingPayer(workspaceId, { - onMissing: 'return-null', - }) - if (workspacePayer) { - payer = { - billingEntity: workspacePayer.organizationId - ? { type: 'organization', id: workspacePayer.organizationId } - : { type: 'user', id: workspacePayer.billedAccountUserId }, - payerSubscription: workspacePayer.payerSubscription, - } - } - } - - if (payer && (await payerHasPaidAccess(payer, { onBalanceUnavailable: 'deny' }))) return - - throw new HostedKeyRequiresPaidPlanError( - `${tool.name} with Sim's hosted key is available on paid plans. Upgrade your plan, or add your own API key under Settings > BYOK.` - ) -} - /** Result from hosted key injection */ interface HostedKeyInjectionResult { isUsingHostedKey: boolean @@ -662,7 +625,8 @@ function applyCredentialParams( /** * Inject hosted API key if tool supports it and user didn't provide one. - * Checks BYOK workspace keys first, then uses the HostedKeyRateLimiter for round-robin key selection. + * Checks BYOK workspace keys first, refuses Sim's key to a payer without paid access, then uses the + * HostedKeyRateLimiter for round-robin key selection. * Returns whether a hosted (billable) key was injected and which env var it came from. */ async function injectHostedKeyIfNeeded( @@ -701,8 +665,8 @@ async function injectHostedKeyIfNeeded( } } - if (tool.hosting.requiresPaidPlan) { - await assertPayerMayUseHostedKey(tool, workspaceId, billingAttribution) + if (!(await mayUseHostedKey(workspaceId, billingAttribution))) { + throw new HostedKeyRequiresPaidPlanError(tool.name) } const rateLimiter = getHostedKeyRateLimiter() diff --git a/apps/sim/tools/types.ts b/apps/sim/tools/types.ts index 195737edcfa..6fb79bec7df 100644 --- a/apps/sim/tools/types.ts +++ b/apps/sim/tools/types.ts @@ -541,11 +541,6 @@ export interface ToolHostingConfig

> { apiKeyParam: string /** BYOK provider ID for workspace key lookup */ byokProviderId?: BYOKProviderId - /** - * Withholds the hosted key from a free-plan payer without prepaid credits. A workspace BYOK key - * or a key the user passes still runs; only Sim's own key is refused. - */ - requiresPaidPlan?: boolean /** * Bills the hosted charge again from the provider's exact receipt once it is recorded, for a * provider whose receipt arrives after the result. `falai` settles through fal's billing events. diff --git a/apps/sim/tools/video/falai.ts b/apps/sim/tools/video/falai.ts index 224511f5bd9..63f133c200d 100644 --- a/apps/sim/tools/video/falai.ts +++ b/apps/sim/tools/video/falai.ts @@ -80,7 +80,6 @@ export const falaiVideoTool: InternalToolConfig = { apiKeyParam: 'apiKey', byokProviderId: 'falai', exactCostSettlement: 'falai', - requiresPaidPlan: true, pricing: { type: 'custom', getCost: (_params, output) => { From 4e63c5917a26e7410ebd1dd7804bdfad778841db Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 12:05:34 -0800 Subject: [PATCH 2/3] fix(billing): judge the run's admitted payer for hosted model keys --- .../components/pricing-faq/pricing-faq.tsx | 2 +- .../executor/handlers/pi/core/keys.test.ts | 18 +++++++++++++-- apps/sim/executor/handlers/pi/core/keys.ts | 6 ++++- apps/sim/executor/handlers/pi/handler.ts | 1 + apps/sim/lib/api-key/byok.integration.ts | 2 +- apps/sim/lib/api-key/byok.test.ts | 10 +++++++-- apps/sim/lib/api-key/byok.ts | 22 ++++++++++++++----- apps/sim/providers/index.ts | 3 ++- 8 files changed, 50 insertions(+), 14 deletions(-) diff --git a/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx b/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx index 51f00625798..7cbc3413457 100644 --- a/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx +++ b/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx @@ -20,7 +20,7 @@ const formatCredits = (credits: number) => credits.toLocaleString('en-US') const PRICING_FAQS = [ { question: 'Is Sim free?', - 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.`, + 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.`, }, { question: 'How much does Sim cost?', diff --git a/apps/sim/executor/handlers/pi/core/keys.test.ts b/apps/sim/executor/handlers/pi/core/keys.test.ts index c7cc2921d95..236ac727860 100644 --- a/apps/sim/executor/handlers/pi/core/keys.test.ts +++ b/apps/sim/executor/handlers/pi/core/keys.test.ts @@ -67,7 +67,14 @@ describe('resolvePiModelKey', () => { workspaceId: 'ws-1', }) ).resolves.toEqual({ apiKey: 'sk-hosted', isBYOK: false }) - expect(mockGetApiKeyWithBYOK).toHaveBeenCalledWith('anthropic', 'claude', 'ws-1', undefined) + expect(mockGetApiKeyWithBYOK).toHaveBeenCalledWith( + 'anthropic', + 'claude', + 'ws-1', + undefined, + undefined, + undefined + ) }) it('Create PR falls back to a stored workspace key when the field is empty', async () => { @@ -110,7 +117,14 @@ describe('resolvePiModelKey', () => { workspaceId: 'ws-1', }) ).resolves.toEqual({ apiKey: 'sk-hosted', isBYOK: false }) - expect(mockGetApiKeyWithBYOK).toHaveBeenCalledWith('anthropic', 'claude', 'ws-1', undefined) + expect(mockGetApiKeyWithBYOK).toHaveBeenCalledWith( + 'anthropic', + 'claude', + 'ws-1', + undefined, + undefined, + undefined + ) }) }) diff --git a/apps/sim/executor/handlers/pi/core/keys.ts b/apps/sim/executor/handlers/pi/core/keys.ts index d9c129b9946..c470ee2f243 100644 --- a/apps/sim/executor/handlers/pi/core/keys.ts +++ b/apps/sim/executor/handlers/pi/core/keys.ts @@ -20,6 +20,7 @@ import type { CreateAgentSessionOptions } from '@earendil-works/pi-coding-agent' import { getApiKeyWithBYOK, getBYOKKey } from '@/lib/api-key/byok' +import type { UsageUpgradePayer } from '@/lib/billing/usage-upgrade' import { calculateBillableModelCost } from '@/providers/cost-policy' import type { PiSupportedProvider } from '@/providers/pi-provider-configs' import { @@ -49,6 +50,7 @@ interface ResolvePiModelKeyParams { mode: PiKeyMode workspaceId?: string apiKey?: string + billingAttribution?: UsageUpgradePayer } /** Resolves a usable API key for an already validated provider/model pair. */ @@ -79,7 +81,9 @@ export async function resolvePiModelKey(params: ResolvePiModelKeyParams): Promis providerId, params.model, params.workspaceId, - undefined + undefined, + undefined, + params.billingAttribution ) return { apiKey, isBYOK } } diff --git a/apps/sim/executor/handlers/pi/handler.ts b/apps/sim/executor/handlers/pi/handler.ts index ffd8cfbef4a..13eff86979b 100644 --- a/apps/sim/executor/handlers/pi/handler.ts +++ b/apps/sim/executor/handlers/pi/handler.ts @@ -232,6 +232,7 @@ export class PiBlockHandler implements BlockHandler { mode, workspaceId: ctx.workspaceId, apiKey: asRawString(inputs.apiKey), + billingAttribution: ctx.metadata.billingAttribution, }) const search = await this.resolveSearch(ctx, inputs, mode) diff --git a/apps/sim/lib/api-key/byok.integration.ts b/apps/sim/lib/api-key/byok.integration.ts index 09cfb31503b..5d0c1e39599 100644 --- a/apps/sim/lib/api-key/byok.integration.ts +++ b/apps/sim/lib/api-key/byok.integration.ts @@ -19,7 +19,7 @@ vi.mock('@sim/db', async () => { }) return { db: drizzle(fixture.client) } }) -vi.mock('@/lib/core/config/env-flags', () => ({ isHosted: true })) +vi.mock('@/lib/core/config/env-flags', () => ({ isHosted: true, isBillingEnabled: false })) vi.mock('@/providers/models', () => ({ getHostedModels: () => ['gpt-4.1-mini'] })) vi.mock('@/providers/utils', () => ({ PROVIDER_PLACEHOLDER_KEY: 'fixture-placeholder' })) vi.mock('@/lib/api-key/byok-entitlement', () => ({ diff --git a/apps/sim/lib/api-key/byok.test.ts b/apps/sim/lib/api-key/byok.test.ts index 9d569e8aeb6..52870ee0593 100644 --- a/apps/sim/lib/api-key/byok.test.ts +++ b/apps/sim/lib/api-key/byok.test.ts @@ -379,12 +379,18 @@ describe('getApiKeyWithBYOK for a payer without paid access', () => { it("refuses Sim's key with a paid-plan error when the caller has no key of its own", async () => { const workspaceId = uniqueWorkspaceId() + const attribution = { + billingEntity: { type: 'user' as const, id: 'free-payer' }, + payerSubscription: null, + } - await expect(getApiKeyWithBYOK('anthropic', HOSTED_MODEL, workspaceId)).rejects.toMatchObject({ + await expect( + getApiKeyWithBYOK('anthropic', HOSTED_MODEL, workspaceId, undefined, undefined, attribution) + ).rejects.toMatchObject({ statusCode: 402, message: expect.stringContaining('available on paid plans'), }) - expect(mockMayUseHostedKey).toHaveBeenCalledWith(workspaceId) + expect(mockMayUseHostedKey).toHaveBeenCalledWith(workspaceId, attribution) expect(mockGetRotatingApiKey).not.toHaveBeenCalled() }) diff --git a/apps/sim/lib/api-key/byok.ts b/apps/sim/lib/api-key/byok.ts index 1c8f92ac84b..0eb5eb3d7b3 100644 --- a/apps/sim/lib/api-key/byok.ts +++ b/apps/sim/lib/api-key/byok.ts @@ -11,6 +11,7 @@ import { HostedKeyRequiresPaidPlanError, mayUseHostedKey, } from '@/lib/billing/core/hosted-key-access' +import type { UsageUpgradePayer } from '@/lib/billing/usage-upgrade' import { getRotatingApiKey } from '@/lib/core/config/api-keys' import { env } from '@/lib/core/config/env' import { isHosted } from '@/lib/core/config/env-flags' @@ -232,7 +233,7 @@ async function resolveBYOKKey( } /** - * Serves a catalogued hosted model: Sim's key from `keyPool` when the workspace's payer may use it + * Serves a catalogued hosted model: Sim's key from `keyPool` when the run's payer may use it * ({@link mayUseHostedKey}), otherwise the caller's own key. A caller's key is not Sim's, so it is * reported as `isBYOK` and its usage is never billed. */ @@ -240,9 +241,10 @@ async function resolveHostedModelKey( keyPool: string, model: string, workspaceId: string | undefined | null, - userProvidedKey: string | undefined + userProvidedKey: string | undefined, + billingAttribution: UsageUpgradePayer | undefined ): Promise<{ apiKey: string; isBYOK: boolean }> { - if (!(await mayUseHostedKey(workspaceId))) { + if (!(await mayUseHostedKey(workspaceId, billingAttribution))) { if (userProvidedKey) return { apiKey: userProvidedKey, isBYOK: true } throw new HostedKeyRequiresPaidPlanError(model) } @@ -267,7 +269,8 @@ export async function getApiKeyWithBYOK( model: string, workspaceId: string | undefined | null, userProvidedKey?: string, - signal?: AbortSignal + signal?: AbortSignal, + billingAttribution?: UsageUpgradePayer ): Promise<{ apiKey: string; isBYOK: boolean; scope?: BYOKKeyScopeName }> { if (provider === 'ollama') { return { apiKey: 'empty', isBYOK: false } @@ -301,7 +304,13 @@ export async function getApiKeyWithBYOK( if (isHosted) { const isModelHosted = getHostedModels().some((m) => m.toLowerCase() === model.toLowerCase()) if (isModelHosted) { - return resolveHostedModelKey('fireworks', model, workspaceId, userProvidedKey) + return resolveHostedModelKey( + 'fireworks', + model, + workspaceId, + userProvidedKey, + billingAttribution + ) } if (userProvidedKey) { @@ -463,7 +472,8 @@ export async function getApiKeyWithBYOK( isGeminiModel ? 'gemini' : provider, model, workspaceId, - userProvidedKey + userProvidedKey, + billingAttribution ) } } diff --git a/apps/sim/providers/index.ts b/apps/sim/providers/index.ts index a5dc9e2e4d8..fc5fb806040 100644 --- a/apps/sim/providers/index.ts +++ b/apps/sim/providers/index.ts @@ -261,7 +261,8 @@ export async function executeProviderRequest( request.model, request.workspaceId, request.apiKey, - request.abortSignal + request.abortSignal, + runtimeContext?.executionContext?.metadata.billingAttribution ) resolvedRequest = { ...resolvedRequest, apiKey: result.apiKey } isBYOK = result.isBYOK From b3f24842d5d77e77566f0100073d16488ede18c5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 12:21:15 -0800 Subject: [PATCH 3/3] test(pi): give the handler fixture run metadata --- apps/sim/executor/handlers/pi/handler.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/sim/executor/handlers/pi/handler.test.ts b/apps/sim/executor/handlers/pi/handler.test.ts index 5c98a4037e8..b5493f04d72 100644 --- a/apps/sim/executor/handlers/pi/handler.test.ts +++ b/apps/sim/executor/handlers/pi/handler.test.ts @@ -115,6 +115,7 @@ function ctx(overrides: Partial = {}): ExecutionContext { workflowId: 'wf', workspaceId: 'ws', userId: 'user', + metadata: {}, resolvedSecretTraceRegistry: new ResolvedSecretTraceRegistry(), ...overrides, } as ExecutionContext