Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/docs/content/docs/platform/costs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 paid plans. Sim is also open source, so you can self-host it for free.`,
},
{
question: 'How much does Sim cost?',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ export const COMPARISON_SECTIONS: ComparisonSection[] = [
'Custom',
],
},
{
label: 'Sim-hosted models & tools',
values: [false, true, true, true],
},
],
},
{
Expand Down
18 changes: 16 additions & 2 deletions apps/sim/executor/handlers/pi/core/keys.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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
)
})
})

Expand Down
6 changes: 5 additions & 1 deletion apps/sim/executor/handlers/pi/core/keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -79,7 +81,9 @@ export async function resolvePiModelKey(params: ResolvePiModelKeyParams): Promis
providerId,
params.model,
params.workspaceId,
undefined
undefined,
undefined,
params.billingAttribution
)
return { apiKey, isBYOK }
}
Expand Down
1 change: 1 addition & 0 deletions apps/sim/executor/handlers/pi/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ function ctx(overrides: Partial<ExecutionContext> = {}): ExecutionContext {
workflowId: 'wf',
workspaceId: 'ws',
userId: 'user',
metadata: {},
resolvedSecretTraceRegistry: new ResolvedSecretTraceRegistry(),
...overrides,
} as ExecutionContext
Expand Down
1 change: 1 addition & 0 deletions apps/sim/executor/handlers/pi/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/api-key/byok.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => ({
Expand Down
66 changes: 66 additions & 0 deletions apps/sim/lib/api-key/byok.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof import('@/lib/billing/core/hosted-key-access')>()),
mayUseHostedKey: mockMayUseHostedKey,
}))

vi.mock('@/providers/models', () => providersModelsMock)

vi.mock('@/providers/utils', () => providersUtilsMock)
Expand Down Expand Up @@ -357,6 +366,63 @@ 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()
const attribution = {
billingEntity: { type: 'user' as const, id: 'free-payer' },
payerSubscription: null,
}

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, attribution)
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'

Expand Down
64 changes: 45 additions & 19 deletions apps/sim/lib/api-key/byok.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ 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 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'
Expand Down Expand Up @@ -227,6 +232,30 @@ async function resolveBYOKKey(
)
}

/**
* 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.
*/
async function resolveHostedModelKey(
keyPool: string,
model: string,
workspaceId: string | undefined | null,
userProvidedKey: string | undefined,
billingAttribution: UsageUpgradePayer | undefined
): Promise<{ apiKey: string; isBYOK: boolean }> {
if (!(await mayUseHostedKey(workspaceId, billingAttribution))) {
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.
Expand All @@ -240,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 }
Expand Down Expand Up @@ -274,15 +304,13 @@ 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,
billingAttribution
)
}

if (userProvidedKey) {
Expand Down Expand Up @@ -440,15 +468,13 @@ 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,
billingAttribution
)
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions apps/sim/lib/billing/core/chat-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
51 changes: 51 additions & 0 deletions apps/sim/lib/billing/core/hosted-key-access.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> {
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
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' })
}
3 changes: 2 additions & 1 deletion apps/sim/providers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 0 additions & 13 deletions apps/sim/tools/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading