diff --git a/apps/api/src/durable-objects/sam-session/agent-loop.ts b/apps/api/src/durable-objects/sam-session/agent-loop.ts index 9d66e127b3..7381cfa260 100644 --- a/apps/api/src/durable-objects/sam-session/agent-loop.ts +++ b/apps/api/src/durable-objects/sam-session/agent-loop.ts @@ -1,4 +1,7 @@ -import { estimateInputTokensFromMessages } from '@simple-agent-manager/ai-proxy'; +import { + estimateInputTokensFromMessages, + monthlyCostCapMessage, +} from '@simple-agent-manager/ai-proxy'; /** * Agent loop — unified OpenAI-format code path routed through AI Gateway. * @@ -138,7 +141,7 @@ export async function runAgentLoop( const message = usageGate.reason === 'daily-token-budget' ? 'Daily token budget exceeded. Resets at midnight UTC.' - : 'Monthly cost cap exceeded. Adjust your cap in Settings > Usage.'; + : monthlyCostCapMessage(usageGate.monthlyCap); log.warn('sam.ai_usage_gate_denied', { userId, conversationId, @@ -151,15 +154,10 @@ export async function runAgentLoop( let response: Response; try { - response = await callLLM( - env, - config, - llmMessages, - userId, - conversationId, - systemPrompt, - { tools, endpoint } - ); + response = await callLLM(env, config, llmMessages, userId, conversationId, systemPrompt, { + tools, + endpoint, + }); response = await attachTokenUsageAccounting(response, { env, userId, diff --git a/apps/api/src/durable-objects/sam-session/operator/agent.ts b/apps/api/src/durable-objects/sam-session/operator/agent.ts index a371d88312..05ad99147c 100644 --- a/apps/api/src/durable-objects/sam-session/operator/agent.ts +++ b/apps/api/src/durable-objects/sam-session/operator/agent.ts @@ -1,8 +1,9 @@ +import type { MonthlyCostCapCheck } from '@simple-agent-manager/ai-proxy'; import { PLATFORM_AI_MODELS, resolveSamConfig } from '@simple-agent-manager/shared'; import type { Env } from '../../../env'; import { getTrustedApiOrigin } from '../../../lib/trusted-origins'; -import { checkAiUsageGate } from '../../../services/ai-token-budget'; +import { checkAiUsageGate,monthlyCostCapMessage } from '../../../services/ai-token-budget'; import { projectOperatorContext } from './context'; import { assertGroundedOperatorResponse, @@ -20,6 +21,14 @@ import { import { assertOperatorExecution, operatorTools } from './operations'; import type { OperatorStore, OperatorTurn } from './store'; +/** Only trusted budget recovery copy may cross the controller's error sanitization boundary. */ +export class OperatorMonthlyCostCapError extends Error { + override name = 'OperatorMonthlyCostCapError'; + constructor(cap: MonthlyCostCapCheck) { + super(monthlyCostCapMessage(cap)); + } +} + export const OPERATOR_INSTRUCTIONS = `You are SAM, the user's private account assistant. Use live platform operations for claims about projects and work. Always name the project and link to the source task/session. Distinguish accepted, running, agent-reported completion and independently verified results. Say when evidence is incomplete or stale. Questions about the current state of work (what is running, what changed, shipped or failed recently, what needs attention) MUST be answered from operations you call in this turn, never from conversation history. Earlier turns appear as sam_historical_turn_status records with a recordedAt time: they describe the past, may be months old and are never current status. Never write such records yourself; always answer in plain prose. Compare returned timestamps with the current time given at the end of these instructions, say how recent items are, and never call an item recent unless a returned timestamp shows it. @@ -91,6 +100,13 @@ export async function runOperatorAgent(options: { let toolAttempted = false; let inferenceFailed = false; let startedSteps = 0; + let monthlyDenial: OperatorMonthlyCostCapError | undefined; + // Mastra may wrap prepareStep failures or return them in full.error. Keep our own denial, + // never provider error text, and recheck the turn fence before exposing its recovery advice. + const rethrowFailure = (error: unknown): never => { + assertCurrent(); + throw monthlyDenial ?? error; + }; const instructions = `${OPERATOR_INSTRUCTIONS}\nPrivate unresolved receipt references (evidence only; not permission to retry): ${JSON.stringify(store.unresolvedActions(config.historyLoadLimit))}\n${REPLY_FORMAT}\n${currentTimeInstruction(new Date())}`; const agent = new Agent({ id: 'sam-account-operator', @@ -158,8 +174,14 @@ export async function runOperatorAgent(options: { await assertOperatorExecution(env, userId); assertCurrent(); const gate = await checkAiUsageGate(env.KV, userId, env); - if (!gate.allowed) throw new Error('SAM usage budget exhausted'); assertCurrent(); + if (!gate.allowed) { + if (gate.reason === 'monthly-cost-cap') { + monthlyDenial = new OperatorMonthlyCostCapError(gate.monthlyCap); + throw monthlyDenial; + } + throw new Error('SAM usage budget exhausted'); + } startedSteps++; return { toolChoice: correcting && stepNumber === 0 ? ('required' as const) : ('auto' as const), @@ -171,8 +193,9 @@ export async function runOperatorAgent(options: { live?.stepFinished(step.toolCalls.length > 0); await recordOperatorStepUsage(env, userId, config, catalogModel, step, customEndpoint); }, - }); - const full = await output.getFullOutput(); + }).catch(rethrowFailure); + const full = await output.getFullOutput().catch(rethrowFailure); + if (monthlyDenial) rethrowFailure(monthlyDenial); if (full.error) throw full.error; return full; }; diff --git a/apps/api/src/durable-objects/sam-session/operator/controller.ts b/apps/api/src/durable-objects/sam-session/operator/controller.ts index c500a464e0..1b3f0deb5e 100644 --- a/apps/api/src/durable-objects/sam-session/operator/controller.ts +++ b/apps/api/src/durable-objects/sam-session/operator/controller.ts @@ -7,7 +7,7 @@ import { parsePositiveInt } from '../../../lib/route-helpers'; import { OPERATOR_DEFAULTS } from '../../../services/admin-settings-registry'; import { getOperatorSettings, type OperatorSettings } from '../../../services/operator-settings'; import { handleActionRoute } from './action-routes'; -import { runOperatorAgent } from './agent'; +import { OperatorMonthlyCostCapError, runOperatorAgent } from './agent'; import { OperatorLive } from './live'; import { assertOperatorAccount, assertOperatorExecution } from './operations'; import { actionProjection, projectAccessCache } from './projection'; @@ -320,7 +320,9 @@ export class OperatorController { turn.id, 'interrupted', null, - 'SAM could not finish this turn. Review recorded actions before continuing; uncertain actions are not automatically repeated.' + error instanceof OperatorMonthlyCostCapError + ? error.message + : 'SAM could not finish this turn. Review recorded actions before continuing; uncertain actions are not automatically repeated.' ); } finally { clearTimeout(timer); diff --git a/apps/api/src/durable-objects/sam-session/operator/model.ts b/apps/api/src/durable-objects/sam-session/operator/model.ts index a8d58cd7f8..a1af3ea86b 100644 --- a/apps/api/src/durable-objects/sam-session/operator/model.ts +++ b/apps/api/src/durable-objects/sam-session/operator/model.ts @@ -18,7 +18,10 @@ import { resolveCloudflareWorkersAiTarget, resolveOpenAICompatibleTarget, } from '../../../services/llm-chat-target'; -import { aiGatewayOnlyHeaders } from '../../../services/platform-capabilities'; +import { + aiGatewayOnlyHeaders, + hasLocalAiCostMetering, +} from '../../../services/platform-capabilities'; import { buildAnthropicGatewayUrl } from '../agent-loop-helpers'; /** Provider ID of the OpenAI-compatible Workers AI route; also its providerOptions key. */ @@ -205,6 +208,8 @@ export async function recordOperatorStepUsage( : ((input - cached) * catalogModel.costPer1kInputTokens + cached * cachedRate + output * catalogModel.costPer1kOutputTokens) / - 1000 + 1000, + // Per-model breakdown only where SAM's own record is the spend record (ai-model-usage.ts). + !customEndpoint && hasLocalAiCostMetering(env) ? catalogModel.id : undefined ); } diff --git a/apps/api/src/routes/ai-proxy-admission.ts b/apps/api/src/routes/ai-proxy-admission.ts index 66d1760e50..d4f3460ab7 100644 --- a/apps/api/src/routes/ai-proxy-admission.ts +++ b/apps/api/src/routes/ai-proxy-admission.ts @@ -1,3 +1,4 @@ +import { monthlyCostCapMessage } from '@simple-agent-manager/ai-proxy'; /** * Request admission for the platform AI proxy (`routes/ai-proxy.ts`): authentication, request-size * limits, and every gate a request must pass before it may spend platform credentials. @@ -154,18 +155,12 @@ export async function enforceUsageGate( ); } - return proxyJsonError( - c, - 'Monthly cost cap exceeded. Adjust your cap in Settings > Usage.', - 'rate_limit_error', - 429, - { - monthlyCost: { - used: usageGate.monthlyCap.costUsd, - cap: usageGate.monthlyCap.capUsd, - }, - } - ); + return proxyJsonError(c, monthlyCostCapMessage(usageGate.monthlyCap), 'rate_limit_error', 429, { + monthlyCost: { + used: usageGate.monthlyCap.costUsd, + cap: usageGate.monthlyCap.capUsd, + }, + }); } export function validateAllowedModel(c: AIProxyContext, modelId: string): Response | null { diff --git a/apps/api/src/routes/ai-proxy-anthropic-support.ts b/apps/api/src/routes/ai-proxy-anthropic-support.ts index d2ab0d08d3..ff3857c9dc 100644 --- a/apps/api/src/routes/ai-proxy-anthropic-support.ts +++ b/apps/api/src/routes/ai-proxy-anthropic-support.ts @@ -1,3 +1,4 @@ +import { type MonthlyCostCapCheck,monthlyCostCapMessage } from '@simple-agent-manager/ai-proxy'; /** * Error shapes and platform-credential telemetry for the native Anthropic proxy * (`routes/ai-proxy-anthropic.ts`). @@ -50,7 +51,8 @@ export function anthropicProviderErrorHeaders(upstreamHeaders: Headers): Headers } export function anthropicUsageGateError( - reason: 'daily-token-budget' | 'monthly-cost-cap' + reason: 'daily-token-budget' | 'monthly-cost-cap', + cap?: MonthlyCostCapCheck ): Response { if (reason === 'daily-token-budget') { return anthropicError( @@ -60,11 +62,7 @@ export function anthropicUsageGateError( ); } - return anthropicError( - 'Monthly cost cap exceeded. Adjust your cap in Settings > Usage.', - 'rate_limit_error', - 429 - ); + return anthropicError(monthlyCostCapMessage(cap), 'rate_limit_error', 429); } export function anthropicBodyMaxBytes(c: AnthropicProxyContext): number { diff --git a/apps/api/src/routes/ai-proxy-anthropic.ts b/apps/api/src/routes/ai-proxy-anthropic.ts index 3ee57d2fb7..93c14a8188 100644 --- a/apps/api/src/routes/ai-proxy-anthropic.ts +++ b/apps/api/src/routes/ai-proxy-anthropic.ts @@ -151,7 +151,10 @@ aiProxyAnthropicRoutes.post('/messages', async (c) => { const usageGate = await checkAiUsageGate(c.env.KV, userId, c.env); if (!usageGate.allowed) { - return anthropicUsageGateError(usageGate.reason); + return anthropicUsageGateError( + usageGate.reason, + usageGate.reason === 'monthly-cost-cap' ? usageGate.monthlyCap : undefined + ); } // --- Resolve upstream auth (Unified Billing or platform key) --- @@ -381,7 +384,10 @@ aiProxyAnthropicRoutes.post('/messages/count_tokens', async (c) => { const usageGate = await checkAiUsageGate(c.env.KV, userId, c.env); if (!usageGate.allowed) { - return anthropicUsageGateError(usageGate.reason); + return anthropicUsageGateError( + usageGate.reason, + usageGate.reason === 'monthly-cost-cap' ? usageGate.monthlyCap : undefined + ); } // --- Resolve upstream auth (Unified Billing or platform key) --- diff --git a/apps/api/src/routes/ai-proxy-passthrough-errors.ts b/apps/api/src/routes/ai-proxy-passthrough-errors.ts index 8b59b14e77..e4cf847ebf 100644 --- a/apps/api/src/routes/ai-proxy-passthrough-errors.ts +++ b/apps/api/src/routes/ai-proxy-passthrough-errors.ts @@ -1,3 +1,5 @@ +import { type MonthlyCostCapCheck,monthlyCostCapMessage } from '@simple-agent-manager/ai-proxy'; + import { copyCredentialLimitHeaders } from '../services/credential-limit-events'; function jsonErrorHeaders(headers?: HeadersInit): Headers { @@ -37,7 +39,8 @@ export function openaiError( } export function anthropicUsageGateError( - reason: 'daily-token-budget' | 'monthly-cost-cap' + reason: 'daily-token-budget' | 'monthly-cost-cap', + cap?: MonthlyCostCapCheck ): Response { if (reason === 'daily-token-budget') { return anthropicError( @@ -47,21 +50,16 @@ export function anthropicUsageGateError( ); } - return anthropicError( - 'Monthly cost cap exceeded. Adjust your cap in Settings > Usage.', - 'rate_limit_error', - 429 - ); + return anthropicError(monthlyCostCapMessage(cap), 'rate_limit_error', 429); } -export function openaiUsageGateError(reason: 'daily-token-budget' | 'monthly-cost-cap'): Response { +export function openaiUsageGateError( + reason: 'daily-token-budget' | 'monthly-cost-cap', + cap?: MonthlyCostCapCheck +): Response { if (reason === 'daily-token-budget') { return openaiError('Daily token budget exceeded.', 'rate_limit_error', 429); } - return openaiError( - 'Monthly cost cap exceeded. Adjust your cap in Settings > Usage.', - 'rate_limit_error', - 429 - ); + return openaiError(monthlyCostCapMessage(cap), 'rate_limit_error', 429); } diff --git a/apps/api/src/routes/ai-proxy-passthrough-prepare.ts b/apps/api/src/routes/ai-proxy-passthrough-prepare.ts index 283a3b1cb1..13ad419e24 100644 --- a/apps/api/src/routes/ai-proxy-passthrough-prepare.ts +++ b/apps/api/src/routes/ai-proxy-passthrough-prepare.ts @@ -14,8 +14,14 @@ * workspaceId, and projectId. Upstream provider credentials are never accepted * from, or returned to, tenant workspaces. */ -import type { MeasuredTokenUsage } from '@simple-agent-manager/ai-proxy'; import { + findPricedModel, + hasLocalAiCostMetering, + type MeasuredTokenUsage, + type MonthlyCostCapCheck, +} from '@simple-agent-manager/ai-proxy'; +import { + AI_PROVIDER_BASE_URLS, DEFAULT_AI_PROXY_RATE_LIMIT_RPM, DEFAULT_AI_PROXY_RATE_LIMIT_WINDOW_SECONDS, DEFAULT_AI_PROXY_REQUEST_BODY_MAX_BYTES, @@ -44,7 +50,11 @@ import { openaiError, openaiUsageGateError, } from './ai-proxy-passthrough-errors'; -import { type ResolvedProxyUpstream, resolveProxyUpstream } from './ai-proxy-passthrough-upstream'; +import { + type ResolvedProxyUpstream, + resolveProxyUpstream, + trimTrailingSlashes, +} from './ai-proxy-passthrough-upstream'; type ProxyContext = Context<{ Bindings: Env }>; @@ -85,7 +95,10 @@ interface PrepareProxyOptions { requestTooLargeResponse: (maxBytes: number) => Response; invalidBodyResponse?: (body: Record) => Response | null; missingModelResponse: () => Response; - usageGateResponse: (reason: 'daily-token-budget' | 'monthly-cost-cap') => Response; + usageGateResponse: ( + reason: 'daily-token-budget' | 'monthly-cost-cap', + cap?: MonthlyCostCapCheck + ) => Response; missingUpstreamResponse: () => Response; } @@ -170,6 +183,56 @@ export function openaiProxyOptions(jsonContext: string): PrepareProxyOptions { }; } +/** A model id prices only its vendor's endpoint, not an arbitrary compatible alias. */ +function hasCanonicalCatalogPrice(upstream: ResolvedProxyUpstream, modelId: string): boolean { + const model = findPricedModel(modelId); + if (!model || model.provider === 'workers-ai') return false; + const dialect = model.provider === 'anthropic' ? 'anthropic' : 'openai-compatible'; + if (upstream.dialect !== dialect) return false; + try { + const actual = new URL(upstream.baseUrl); + const canonical = new URL(AI_PROVIDER_BASE_URLS[model.provider]); + return ( + !actual.username && + !actual.password && + !actual.search && + !actual.hash && + actual.origin === canonical.origin && + trimTrailingSlashes(actual.pathname) === trimTrailingSlashes(canonical.pathname) + ); + } catch { + return false; + } +} + +/** Admission depends on the resolved owner; locally funded calls must be priceable. */ +async function enforcePassthroughFunding( + c: ProxyContext, + userId: string, + modelId: string, + upstream: ResolvedProxyUpstream, + options: PrepareProxyOptions +): Promise { + const platformBilled = upstream.credentialSource === 'platform'; + if ( + platformBilled && + hasLocalAiCostMetering(c.env) && + !hasCanonicalCatalogPrice(upstream, modelId) + ) { + const message = + 'Model and upstream endpoint must match a catalog-priced provider to use an installation-funded credential.'; + return options.dialect === 'anthropic' + ? anthropicError(message, 'invalid_request_error', 400) + : openaiError(message, 'invalid_request_error', 400); + } + const usageGate = await checkAiUsageGate(c.env.KV, userId, c.env, { platformBilled }); + if (usageGate.allowed) return null; + return options.usageGateResponse( + usageGate.reason, + usageGate.reason === 'monthly-cost-cap' ? usageGate.monthlyCap : undefined + ); +} + export async function prepareProxyRequest( c: ProxyContext, options: PrepareProxyOptions @@ -226,11 +289,6 @@ export async function prepareProxyRequest( return { ok: false, response: options.missingModelResponse() }; } - const usageGate = await checkAiUsageGate(c.env.KV, auth.userId, c.env); - if (!usageGate.allowed) { - return { ok: false, response: options.usageGateResponse(usageGate.reason) }; - } - const upstream = await resolveProxyUpstream({ env: c.env, userId: auth.userId, @@ -245,6 +303,9 @@ export async function prepareProxyRequest( return { ok: false, response: options.missingUpstreamResponse() }; } + const fundingError = await enforcePassthroughFunding(c, auth.userId, modelId, upstream, options); + if (fundingError) return { ok: false, response: fundingError }; + // Insights run usage: the measured tokens go to this workspace's run, keyed by the credential // the proxy forwards with. const recordRunUsage = proxyRunUsageRecorder(c.env, auth, { diff --git a/apps/api/src/routes/ai-proxy-passthrough.ts b/apps/api/src/routes/ai-proxy-passthrough.ts index cdc502591b..b2a6cb4c75 100644 --- a/apps/api/src/routes/ai-proxy-passthrough.ts +++ b/apps/api/src/routes/ai-proxy-passthrough.ts @@ -1,3 +1,4 @@ +import { hasLocalAiCostMetering } from '@simple-agent-manager/ai-proxy'; import { guardedFetch } from '@simple-agent-manager/worker-core'; /** * AI proxy passthrough routes — URL-path-based workspace auth. @@ -22,6 +23,7 @@ import { log } from '../lib/logger'; import { attachUpstreamTokenUsageAccounting, estimateInputTokensFromMessages, + estimateInputTokensFromRequest, optionalExecutionContext, } from '../services/ai-token-usage-accounting'; import { copyCredentialLimitHeaders } from '../services/credential-limit-events'; @@ -34,10 +36,7 @@ import { retryAfterSeconds, } from './ai-proxy-passthrough-prepare'; import { schedulePassthroughLimitHeaders } from './ai-proxy-passthrough-telemetry'; -import { - type ResolvedProxyUpstream, - trimTrailingSlashes, -} from './ai-proxy-passthrough-upstream'; +import { type ResolvedProxyUpstream, trimTrailingSlashes } from './ai-proxy-passthrough-upstream'; const aiProxyPassthroughRoutes = new Hono<{ Bindings: Env }>(); type ProxyContext = Context<{ Bindings: Env }>; @@ -60,6 +59,15 @@ function joinUpstreamUrl(baseUrl: string, path: string): string { return `${trimTrailingSlashes(baseUrl)}/${trimLeadingSlashes(path)}`; } +/** + * A passthrough call served by a platform-owned credential spends the installation's money, so + * where SAM prices spend itself (no AI Gateway) it is priced into the monthly cap and ceiling like + * every other platform-billed call. A user's or project's own credential is their own spend. + */ +function platformCostModelId(upstream: ResolvedProxyUpstream, modelId: string): string | undefined { + return upstream.credentialSource === 'platform' ? modelId : undefined; +} + function buildUpstreamAuthHeaders(upstream: ResolvedProxyUpstream): Record { if ( upstream.capability.authStyle === 'bearer-token' || @@ -198,8 +206,14 @@ aiProxyPassthroughRoutes.post('/:wstoken/anthropic/v1/messages', async (c) => { env: c.env, userId, format: 'anthropic', - fallbackInputTokens: estimateInputTokensFromMessages(body.messages), + fallbackInputTokens: + upstream.credentialSource === 'platform' && hasLocalAiCostMetering(c.env) + ? estimateInputTokensFromRequest(body) + : estimateInputTokensFromMessages(body.messages), provider: upstream.provider, + costModelId: platformCostModelId(upstream, modelId), + estimateMissingUsage: + upstream.credentialSource === 'platform' && hasLocalAiCostMetering(c.env), onMeasuredUsage: prepared.value.recordRunUsage, executionCtx: optionalExecutionContext(() => c.executionCtx), headers: responseHeaders, @@ -382,8 +396,14 @@ aiProxyPassthroughRoutes.post('/:wstoken/openai/v1/chat/completions', async (c) env: c.env, userId, format: 'openai', - fallbackInputTokens: estimateInputTokensFromMessages(body.messages), + fallbackInputTokens: + upstream.credentialSource === 'platform' && hasLocalAiCostMetering(c.env) + ? estimateInputTokensFromRequest(body) + : estimateInputTokensFromMessages(body.messages), provider: upstream.provider, + costModelId: platformCostModelId(upstream, modelId), + estimateMissingUsage: + upstream.credentialSource === 'platform' && hasLocalAiCostMetering(c.env), onMeasuredUsage: prepared.value.recordRunUsage, executionCtx: optionalExecutionContext(() => c.executionCtx), headers: responseHeaders, @@ -399,10 +419,6 @@ aiProxyPassthroughRoutes.post('/:wstoken/openai/v1/chat/completions', async (c) } }); -export { - aiProxyPassthroughRoutes, - buildUpstreamAuthHeaders, - joinUpstreamUrl, -}; +export { aiProxyPassthroughRoutes, buildUpstreamAuthHeaders, joinUpstreamUrl }; export { resolveProxyUpstream } from './ai-proxy-passthrough-upstream'; diff --git a/apps/api/src/routes/ai-proxy-upstream.ts b/apps/api/src/routes/ai-proxy-upstream.ts index cbecf141eb..bb1d2e0302 100644 --- a/apps/api/src/routes/ai-proxy-upstream.ts +++ b/apps/api/src/routes/ai-proxy-upstream.ts @@ -7,6 +7,7 @@ export const customEndpointResponses = new WeakSet(); * Split out of ai-proxy.ts per .claude/rules/18-file-size-limits.md — pure * extraction, no behavior change. */ +import { AI_PROVIDER_BASE_URLS } from '@simple-agent-manager/shared'; import * as v from 'valibot'; import type { Env } from '../env'; @@ -58,7 +59,7 @@ function buildOpenAIUrl(env: Env): string { return `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/openai/v1/chat/completions`; } // Fallback: direct OpenAI API (no gateway monitoring) - return 'https://api.openai.com/v1/chat/completions'; + return `${AI_PROVIDER_BASE_URLS.openai}/chat/completions`; } /** Build upstream URL for OpenAI Responses API via AI Gateway. */ @@ -67,7 +68,7 @@ function buildOpenAIResponsesUrl(env: Env): string { if (gatewayId) { return `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/openai/v1/responses`; } - return 'https://api.openai.com/v1/responses'; + return `${AI_PROVIDER_BASE_URLS.openai}/responses`; } // ============================================================================= diff --git a/apps/api/src/routes/usage.ts b/apps/api/src/routes/usage.ts index 343b232af4..cf4896c38f 100644 --- a/apps/api/src/routes/usage.ts +++ b/apps/api/src/routes/usage.ts @@ -1,6 +1,8 @@ import { getLocalMonthlyAiCostUsd, + getLocalUsageBreakdown, hasLocalAiCostMetering, + isMonthlyCostCapAvailable, resolveAiGatewayId, } from '@simple-agent-manager/ai-proxy'; import type { @@ -31,11 +33,13 @@ import { } from '../services/ai-gateway-logs'; import { deleteUserBudgetSettings, + effectiveMonthlyCostCapUsd, getAdminAiAllowance, getProviderUsage, getTokenUsage, getUserBudgetSettings, resolveEffectiveLimits, + resolveMonthlyCostCeilingUsd, saveUserBudgetSettings, validateBudgetUpdate, } from '../services/ai-token-budget'; @@ -120,7 +124,19 @@ usageRoutes.get('/ai', requireAuth(), requireApproved(), async (c) => { totalCostUsd += entry.estimatedCostUsd; } - // Gateway not configured — return local proxy usage only, not an error. + // Gateway not configured: SAM's own records, not an error. A failed per-model read degrades + // to empty breakdowns, never a failed usage page. + const breakdown = await getLocalUsageBreakdown( + c.env, + userId, + new Date(periodBounds.startDate) + ).catch((err: unknown) => { + log.warn('usage.local_breakdown_failed', { + userId, + error: err instanceof Error ? err.message : String(err), + }); + return { byModel: [], byDay: [] }; + }); return c.json({ totalCostUsd, totalRequests, @@ -128,9 +144,9 @@ usageRoutes.get('/ai', requireAuth(), requireApproved(), async (c) => { totalOutputTokens, cachedRequests: 0, errorRequests: 0, - byModel: [], + byModel: breakdown.byModel, byProvider: Array.from(providerMap.values()).sort((a, b) => b.totalTokens - a.totalTokens), - byDay: [], + byDay: breakdown.byDay, period, periodLabel: getPeriodLabel(period), } satisfies UserAiUsageResponse); @@ -262,9 +278,10 @@ function mergeLocalProviderUsage( usageRoutes.get('/ai/budget', requireAuth(), requireApproved(), async (c) => { const userId = getUserId(c); - const [userSettings, dailyUsage] = await Promise.all([ + const [userSettings, dailyUsage, ceilingUsd] = await Promise.all([ getUserBudgetSettings(c.env.KV, userId), getTokenUsage(c.env.KV, userId, c.env), + resolveMonthlyCostCeilingUsd(c.env), ]); const effectiveLimits = resolveEffectiveLimits(userSettings, c.env); @@ -304,10 +321,14 @@ usageRoutes.get('/ai/budget', requireAuth(), requireApproved(), async (c) => { effectiveLimits.dailyOutputTokenLimit > 0 ? Math.min(100, (dailyUsage.outputTokens / effectiveLimits.dailyOutputTokenLimit) * 100) : 0; + // The same cap the gate enforces (checkMonthlyCostCap); a gateway without the account API + // cannot price spend, so there the cap has no utilization. + const capAvailable = isMonthlyCostCapAvailable(c.env); + const effectiveCapUsd = capAvailable + ? effectiveMonthlyCostCapUsd(settings.monthlyCostCapUsd, ceilingUsd) + : null; const monthlyCostPercent = - settings.monthlyCostCapUsd !== null && settings.monthlyCostCapUsd > 0 - ? Math.min(100, (monthCostUsd / settings.monthlyCostCapUsd) * 100) - : null; + effectiveCapUsd !== null ? Math.min(100, (monthCostUsd / effectiveCapUsd) * 100) : null; const exceeded = dailyInputPercent >= 100 || @@ -323,6 +344,7 @@ usageRoutes.get('/ai/budget', requireAuth(), requireApproved(), async (c) => { }, effectiveLimits, monthCostUsd, + monthlyCostCap: { available: capAvailable, ceilingUsd, effectiveCapUsd }, utilization: { dailyInputPercent: Math.round(dailyInputPercent * 10) / 10, dailyOutputPercent: Math.round(dailyOutputPercent * 10) / 10, @@ -348,12 +370,15 @@ usageRoutes.put('/ai/budget', requireAuth(), requireApproved(), async (c) => { return c.json({ error: 'INVALID_JSON', message: 'Invalid JSON body' }, 400); } - // Fetch admin allowance to enforce ceilings on user-set limits - const adminAllowance = await getAdminAiAllowance(c.env.KV, userId); + // Admin allowance (per user) and installation ceiling bound what the user may set. + const [adminAllowance, ceilingUsd] = await Promise.all([ + getAdminAiAllowance(c.env.KV, userId), + resolveMonthlyCostCeilingUsd(c.env), + ]); let settings; try { - settings = validateBudgetUpdate(body, c.env, adminAllowance); + settings = validateBudgetUpdate(body, c.env, adminAllowance, ceilingUsd); } catch (err) { return c.json( { error: 'VALIDATION_ERROR', message: err instanceof Error ? err.message : String(err) }, diff --git a/apps/api/src/services/ai-proxy-ports.ts b/apps/api/src/services/ai-proxy-ports.ts index 087d130def..5a75c6d367 100644 --- a/apps/api/src/services/ai-proxy-ports.ts +++ b/apps/api/src/services/ai-proxy-ports.ts @@ -4,7 +4,8 @@ import { drizzle } from 'drizzle-orm/d1'; import type { Env } from '../env'; import { getCredentialEncryptionKey } from '../lib/secrets'; -import { resolveAdminSetting } from './admin-settings-resolution'; +import { resolveAdminSetting, resolveAdminSettingDetails } from './admin-settings-resolution'; +import { AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING } from './ai-proxy-settings'; import { getPlatformAgentCredential } from './platform-credentials'; /** @@ -23,5 +24,19 @@ export function aiProxyPorts(env: Env, db?: ReturnType): AiProxy }, externalReadTimeoutMs: async () => Number(await resolveAdminSetting(env, 'performance.externalReadTimeoutMs')), + monthlyCostCeilingUsd: () => readMonthlyCostCeilingUsd(env), }; } + +/** + * Read the strict admin-settings snapshot (cached for at most 60 seconds). A failed read must + * remain a failure: defaulting to zero or retaining an older disabled/higher ceiling could spend + * beyond the operator's current limit. The package maps the failure to a retryable 503. + */ +async function readMonthlyCostCeilingUsd(env: Env): Promise { + const { value } = await resolveAdminSettingDetails( + env, + AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING + ); + return Number(value); +} diff --git a/apps/api/src/services/ai-proxy-settings.ts b/apps/api/src/services/ai-proxy-settings.ts index f7543f6f49..72c6ad6337 100644 --- a/apps/api/src/services/ai-proxy-settings.ts +++ b/apps/api/src/services/ai-proxy-settings.ts @@ -5,7 +5,10 @@ import type { AdminSettingDefinition } from './admin-setting-definitions'; export const AI_PROXY_DIRECT_UPSTREAM_SETTING = 'aiProxy.directUpstreamEnabled' as const; -export type AiProxySettingName = typeof AI_PROXY_DIRECT_UPSTREAM_SETTING; +export const AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING = + 'aiProxy.perUserMonthlyCostCeilingUsd' as const; +export type AiProxySettingName = + typeof AI_PROXY_DIRECT_UPSTREAM_SETTING | typeof AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING; export const AI_PROXY_SETTINGS: readonly AdminSettingDefinition[] = [ { @@ -14,10 +17,27 @@ export const AI_PROXY_SETTINGS: readonly AdminSettingDefinition[] = [ defaultValue: false, category: 'AI models', description: - 'Turn on the SAM AI proxy (SAM-managed "sam" provider mode and server-side custom-endpoint keys) on an installation without Cloudflare AI Gateway. Calls then go straight to Anthropic or OpenAI with the platform key stored in Admin, and SAM prices them from its own model price table for the monthly cost cap of each user. Any approved user can then spend the platform key, bounded only by the daily token budgets and the monthly cap each user sets for themselves, so also set a spend limit on the provider account. Ignored where an AI Gateway exists (the proxy is on there).', + 'Turn on the SAM AI proxy (SAM-managed "sam" provider mode and server-side custom-endpoint keys) on an installation without Cloudflare AI Gateway. Calls then go straight to Anthropic or OpenAI with the platform key stored in Admin, and SAM prices them from its own model price table for the monthly cost cap of each user. Any approved user can then spend the platform key, bounded only by the daily token budgets and the monthly cap each user sets for themselves, and by the installation monthly ceiling (aiProxy.perUserMonthlyCostCeilingUsd), so set that ceiling and a spend limit on the provider account. Ignored where an AI Gateway exists (the proxy is on there).', secret: false, // Lets every approved user spend the platform key. risky: true, validate: (value) => typeof value === 'boolean', }, + { + name: AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING, + type: 'integer', + defaultValue: 0, + category: 'AI models', + description: + 'Monthly AI spend ceiling for each user (not a total across users), in whole USD (0 = none). Applies where SAM prices AI calls itself, that is an installation without Cloudflare AI Gateway: no user can spend more than this in a UTC month, whatever monthly cap they set, and clearing their own cap does not remove it. Users cannot set a cap above it. Calls to a model with no catalog price count $0, so daily token limits remain the bound for those. Ignored where an AI Gateway exists (caps there are priced from gateway logs).', + secret: false, + risky: false, + // Representation bound only: the operator chooses the business limit in this setting. + range: { min: 0, max: Number.MAX_SAFE_INTEGER }, + validate: (value) => + typeof value === 'number' && + Number.isSafeInteger(value) && + value >= 0 && + value <= Number.MAX_SAFE_INTEGER, + }, ]; diff --git a/apps/api/src/services/ai-token-budget.ts b/apps/api/src/services/ai-token-budget.ts index dbdfd78327..a96a7788c3 100644 --- a/apps/api/src/services/ai-token-budget.ts +++ b/apps/api/src/services/ai-token-budget.ts @@ -1,10 +1,18 @@ // Moved to @simple-agent-manager/ai-proxy (worker modularization W5). Re-exported so the // worker's existing importers are unchanged. +import { + checkAiUsageGate as checkAiUsageGateWithPorts, + resolveMonthlyCostCeilingUsd as resolveCeiling, +} from '@simple-agent-manager/ai-proxy'; + +import type { Env } from '../env'; +import { aiProxyPorts } from './ai-proxy-ports'; + export { type AiProviderUsageAttribution, - checkAiUsageGate, consumeFeatureTokenBudget, deleteUserBudgetSettings, + effectiveMonthlyCostCapUsd, getAdminAiAllowance, getAiBudgetLimits, getFeatureTokenBudget, @@ -13,9 +21,29 @@ export { getUserBudgetSettings, incrementProviderUsage, incrementTokenUsage, + monthlyCostCapMessage, releaseFeatureTokenBudget, resolveEffectiveLimits, resolvePlatformDailyTokenLimits, saveUserBudgetSettings, validateBudgetUpdate, } from '@simple-agent-manager/ai-proxy'; + +/** + * Every pre-request AI usage limit, with the installation-wide monthly ceiling bound to this + * worker's admin settings. Every worker caller goes through here, so none can leave the ceiling + * out (rule 61); the ceiling is read only where SAM meters spend itself. + */ +export function checkAiUsageGate( + kv: KVNamespace, + userId: string, + env: Env, + options?: { platformBilled?: boolean } +) { + return checkAiUsageGateWithPorts(kv, userId, env, aiProxyPorts(env), options); +} + +/** The installation ceiling where it applies (null with an AI Gateway, or when unset). */ +export function resolveMonthlyCostCeilingUsd(env: Env): Promise { + return resolveCeiling(env, aiProxyPorts(env)); +} diff --git a/apps/api/src/services/ai-token-usage-accounting.ts b/apps/api/src/services/ai-token-usage-accounting.ts index 419e31ea8d..852e3d23ae 100644 --- a/apps/api/src/services/ai-token-usage-accounting.ts +++ b/apps/api/src/services/ai-token-usage-accounting.ts @@ -4,5 +4,6 @@ export { attachTokenUsageAccounting, attachUpstreamTokenUsageAccounting, estimateInputTokensFromMessages, + estimateInputTokensFromRequest, optionalExecutionContext, } from '@simple-agent-manager/ai-proxy'; diff --git a/apps/api/src/services/platform-capabilities.ts b/apps/api/src/services/platform-capabilities.ts index 775db811c3..95ee0be7a5 100644 --- a/apps/api/src/services/platform-capabilities.ts +++ b/apps/api/src/services/platform-capabilities.ts @@ -6,6 +6,7 @@ import { validLlmBaseUrl } from './llm-endpoint-settings'; export { aiGatewayOnlyHeaders, hasCloudflareAccountApi, + hasLocalAiCostMetering, isMonthlyCostCapAvailable, resolveAiGatewayId, } from '@simple-agent-manager/ai-proxy'; diff --git a/apps/api/tests/unit/ai-proxy-passthrough.test.ts b/apps/api/tests/unit/ai-proxy-passthrough.test.ts index e79821135f..1886d1e4fa 100644 --- a/apps/api/tests/unit/ai-proxy-passthrough.test.ts +++ b/apps/api/tests/unit/ai-proxy-passthrough.test.ts @@ -2,6 +2,7 @@ vi.mock('../../src/services/outbound-fetch-settings', () => ({ resolveOutboundMaxRedirects: async () => 3, })); /** URL-path-based proxy auth routes and usage tracking. */ +import { PLATFORM_AI_MODELS } from '@simple-agent-manager/shared'; import { Hono } from 'hono'; import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -10,6 +11,17 @@ vi.mock('../../src/services/provider-limit-credential-pin', () => ({ assertProviderLimitCredentialPin: vi.fn(async () => {}), })); +// L13 tests turn on direct upstream (no gateway); every other test keeps the real availability. +const proxyEnabledOverride = vi.hoisted(() => ({ value: undefined as boolean | undefined })); +vi.mock('../../src/services/ai-proxy-availability', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + isAiProxyEnabled: async (env: Parameters[0]) => + proxyEnabledOverride.value ?? actual.isAiProxyEnabled(env), + }; +}); + // --- Mock dependencies --- const mockVerifyAIProxyAuth = vi.fn(); @@ -1084,3 +1096,249 @@ describe('L12 guarded redirects at every passthrough fetch site', () => { } ); }); + +describe('L13: platform-owned passthrough credentials count toward the monthly cap and ceiling', () => { + const PRICED = PLATFORM_AI_MODELS.find( + (m) => m.provider === 'openai' && m.costPer1kOutputTokens > 0 + )!; + // No addressable gateway: SAM prices platform-billed spend itself. + const NO_GATEWAY = { AI_GATEWAY_ID: '', CF_ACCOUNT_ID: '' }; + beforeEach(() => { + proxyEnabledOverride.value = true; // aiProxy.directUpstreamEnabled + return () => { + proxyEnabledOverride.value = undefined; + }; + }); + + async function callWithSource( + source: string, + options: { + model?: string; + anthropic?: boolean; + stream?: boolean; + missingUsage?: boolean; + gateway?: boolean; + requestBody?: Record; + baseUrl?: string; + } = {} + ) { + const model = options.model ?? PRICED.id; + mockWorkspaceAuth(options.anthropic ? 'claude-code' : 'openai-codex'); + mockAllowedRateLimit(); + mockCheckTokenBudget.mockResolvedValue({ allowed: true }); + mockResolveForConsumer.mockImplementation((_db, _userId, _key, consumer) => + Promise.resolve({ + consumer, + configuration: { + settings: options.anthropic + ? { baseUrl: options.baseUrl ?? 'https://api.anthropic.com', dialect: 'anthropic' } + : { providerId: 'openai', providerName: 'OpenAI' }, + }, + credential: { + id: 'cred-test', + secret: options.anthropic + ? { kind: 'api-key', apiKey: 'sk-test' } + : { + kind: 'openai-compatible', + apiKey: 'sk-test', + baseUrl: options.baseUrl ?? 'https://api.openai.com/v1', + }, + }, + source, + }) + ); + const text = 'This generated output must be counted even without provider usage.'; + const payload = options.anthropic + ? { content: [{ type: 'text', text }] } + : { choices: [{ message: { content: text } }] }; + const usage = options.anthropic + ? { input_tokens: 1000, output_tokens: 1000 } + : { prompt_tokens: 1000, completion_tokens: 1000 }; + const responseBody = options.stream + ? options.anthropic + ? `event: content_block_delta\ndata: ${JSON.stringify({ type: 'content_block_delta', delta: { type: 'text_delta', text } })}\n\n` + : `data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\ndata: [DONE]\n\n` + : JSON.stringify(options.missingUsage ? payload : { ...payload, usage }); + mockFetch.mockResolvedValueOnce( + new Response(responseBody, { + status: 200, + headers: { 'Content-Type': options.stream ? 'text/event-stream' : 'application/json' }, + }) + ); + const res = await postJson( + options.anthropic ? ANTHROPIC_MESSAGES_PATH : OPENAI_CHAT_COMPLETIONS_PATH, + { + ...(options.anthropic ? anthropicMessagesBody(model) : openaiChatBody(model)), + stream: options.stream ?? false, + ...options.requestBody, + }, + {}, + options.gateway ? {} : NO_GATEWAY + ); + const copy = res.clone(); + await res.text(); + return copy; + } + + it.each(['user-attachment', 'project-attachment', 'platform'])( + 'passes resolved billing ownership to the gate: %s', + async (source) => { + const res = await callWithSource(source); + expect(res.status).toBe(200); + expect(mockCheckAiUsageGate.mock.calls[0]?.[4]).toEqual({ + platformBilled: source === 'platform', + }); + } + ); + + it('refuses an unpriced locally funded model before upstream fetch', async () => { + const res = await callWithSource('platform', { model: 'custom-unpriced-model' }); + expect(res.status).toBe(400); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it.each([ + ['https://custom-openai.example/v1', false], + ['https://api.openai.com/v1/alias', false], + ['https://api.anthropic.com/v1', false], + ['https://api.anthropic.com', true], + ])('refuses catalog price mismatches before forwarding (%s anthropic=%s)', async (baseUrl, anthropic) => { + // The configuration claims providerId=openai on OpenAI-compatible calls. That is not proof. + const res = await callWithSource('platform', { baseUrl, anthropic }); + expect(res.status).toBe(400); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it('accepts the canonical endpoint with normalized host, default port and trailing slashes', async () => { + expect((await callWithSource('platform', { baseUrl: 'https://API.OPENAI.COM:443/v1///' })).status).toBe(200); + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + + it('refuses a custom Anthropic endpoint even when its model has an Anthropic price', async () => { + const model = PLATFORM_AI_MODELS.find((m) => m.provider === 'anthropic')!.id; + const res = await callWithSource('platform', { + model, anthropic: true, baseUrl: 'https://custom-anthropic.example', + }); + expect(res.status).toBe(400); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it.each(['user-attachment', 'project-attachment', 'gateway'])( + 'keeps custom endpoint behavior for %s', async (source) => { + const res = await callWithSource(source === 'gateway' ? 'platform' : source, { + baseUrl: 'https://custom-openai.example/v1', gateway: source === 'gateway', + }); + expect(res.status).toBe(200); + expect(mockFetch).toHaveBeenCalledTimes(1); + } + ); + + it.each(['user-attachment', 'project-attachment'])( + 'keeps custom models for own-funded %s', + async (source) => { + expect((await callWithSource(source, { model: 'custom-unpriced-model' })).status).toBe(200); + expect(mockFetch).toHaveBeenCalledTimes(1); + } + ); + + it('keeps the gateway platform path unchanged for custom models', async () => { + expect( + (await callWithSource('platform', { model: 'custom-unpriced-model', gateway: true })).status + ).toBe(200); + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + + it.each([ + [false, false], + [false, true], + [true, false], + [true, true], + ])('estimates missing platform output, anthropic=%s stream=%s', async (anthropic, stream) => { + const model = anthropic + ? PLATFORM_AI_MODELS.find((m) => m.provider === 'anthropic')!.id + : PRICED.id; + expect( + (await callWithSource('platform', { model, anthropic, stream, missingUsage: true })).status + ).toBe(200); + expect(mockIncrementProviderUsage).toHaveBeenCalledTimes(1); + const args = mockIncrementProviderUsage.mock.calls[0]!; + expect(args[3]).toBeGreaterThan(0); + expect(args[4]).toBeGreaterThan(0); + expect(args[6]).toBeGreaterThan(0); + }); + + it.each([ + [false, false], [false, true], [true, false], [true, true], + ])('includes tool schemas and structured history in input fallback, anthropic=%s stream=%s', async (anthropic, stream) => { + const description = 'Detailed schema information. '.repeat(200); + const argumentsJson = JSON.stringify({ query: 'long historical tool input '.repeat(200) }); + const requestBody = anthropic + ? { + system: description, + tools: [{ name: 'lookup', description, input_schema: { type: 'object' } }], + messages: [{ role: 'assistant', content: [{ type: 'tool_use', id: 'call', name: 'lookup', input: { query: argumentsJson } }] }], + } + : { + tools: [{ type: 'function', function: { name: 'lookup', description, parameters: { type: 'object' } } }], + messages: [{ role: 'assistant', content: null, tool_calls: [{ id: 'call', type: 'function', function: { name: 'lookup', arguments: argumentsJson } }] }], + }; + const model = anthropic + ? PLATFORM_AI_MODELS.find((m) => m.provider === 'anthropic')!.id + : PRICED.id; + expect((await callWithSource('platform', { model, anthropic, stream, missingUsage: true, requestBody })).status).toBe(200); + const usage = mockIncrementProviderUsage.mock.calls[0]!; + expect(usage[3]).toBeGreaterThanOrEqual(Math.ceil(JSON.stringify(requestBody).length / 4)); + }); + + it.each(['user-attachment', 'project-attachment', 'gateway'])( + 'preserves previous streaming input estimation for %s', async (source) => { + await callWithSource(source === 'gateway' ? 'platform' : source, { + gateway: source === 'gateway', stream: true, missingUsage: true, + requestBody: { tools: [{ description: 'large tool schema '.repeat(200) }] }, + }); + expect(mockIncrementProviderUsage.mock.calls[0]?.[3]).toBe(1); + } + ); + + it('keeps measured input authoritative even with a larger tool schema', async () => { + await callWithSource('platform', { + requestBody: { tools: [{ description: 'large tool schema '.repeat(1000) }] }, + }); + expect(mockIncrementProviderUsage.mock.calls[0]?.[3]).toBe(1000); + }); + + it('prices a call served by a platform credential, with its catalog model', async () => { + await callWithSource('platform'); + expect(mockIncrementProviderUsage).toHaveBeenCalledTimes(1); + const args = mockIncrementProviderUsage.mock.calls[0]!; + expect(args[6]).toBeGreaterThan(0); + expect(args[7]).toBe(PRICED.id); + }); + + it("does not price a user's own credential (their own spend; control)", async () => { + await callWithSource('user-attachment'); + expect(mockIncrementProviderUsage).toHaveBeenCalledTimes(1); + expect(mockIncrementProviderUsage.mock.calls[0]).toHaveLength(6); + }); +}); + +describe('installation ceiling denial recovery through passthrough routes', () => { + it.each([ + [ANTHROPIC_MESSAGES_PATH, 'claude-code', anthropicMessagesBody()], + [OPENAI_CHAT_COMPLETIONS_PATH, 'openai-codex', openaiChatBody()], + ])('names administrator recovery for %s', async (path, agentType, body) => { + mockWorkspaceAuth(agentType as string); + mockAllowedRateLimit(); + mockCheckAiUsageGate.mockResolvedValue({ + allowed: false, + reason: 'monthly-cost-cap', + monthlyCap: { allowed: false, costUsd: 50, capUsd: 50, limitSource: 'administrator' }, + }); + const response = await postJson(path as string, body as Record); + expect(response.status).toBe(429); + const text = await response.text(); + expect(text).toContain('Contact your administrator'); + expect(text).not.toContain('Adjust your cap'); + expect(mockFetch).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/tests/unit/durable-objects/ai-token-budget-counter-model-usage.test.ts b/apps/api/tests/unit/durable-objects/ai-token-budget-counter-model-usage.test.ts new file mode 100644 index 0000000000..e987c78cd6 --- /dev/null +++ b/apps/api/tests/unit/durable-objects/ai-token-budget-counter-model-usage.test.ts @@ -0,0 +1,171 @@ +/** + * L13 local metering, through the real `AiTokenBudgetCounter` over SQLite: priced calls recorded by + * the real accounting path land in provider and per-model rows in one transaction, the usage page + * breakdown reads them, and the worker's usage gate blocks at the installation ceiling. + */ +import { getLocalMonthlyAiCostUsd, getLocalUsageBreakdown } from '@simple-agent-manager/ai-proxy'; +import { PLATFORM_AI_MODELS } from '@simple-agent-manager/shared'; +import Database from 'better-sqlite3'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ resolveAdminSettingDetails: vi.fn() })); +vi.mock('../../../src/services/admin-settings-resolution', () => ({ + resolveAdminSetting: vi.fn(), + resolveAdminSettingDetails: mocks.resolveAdminSettingDetails, +})); + +import { AiTokenBudgetCounter } from '../../../src/durable-objects/ai-token-budget-counter'; +import type { Env } from '../../../src/env'; +import { checkAiUsageGate, incrementProviderUsage } from '../../../src/services/ai-token-budget'; +import { attachTokenUsageAccounting } from '../../../src/services/ai-token-usage-accounting'; +import { createSqlStorage } from './sql-storage-test-utils'; + +const PRICED = PLATFORM_AI_MODELS.find( + (m) => m.provider === 'openai' && m.costPer1kOutputTokens > 0 +)!; +const OPENAI = { providerId: 'openai', providerName: 'OpenAI', dialect: 'openai' }; + +let db: Database.Database; +let counter: AiTokenBudgetCounter; +let env: Env; + +function makeKv(): KVNamespace { + const rows = new Map(); + return { + get: vi.fn(async (key: string, type?: string) => { + const value = rows.get(key); + return value === undefined ? null : type === 'json' ? JSON.parse(value) : value; + }), + put: vi.fn(async (key: string, value: string) => void rows.set(key, value)), + } as unknown as KVNamespace; +} + +beforeEach(() => { + db = new Database(':memory:'); + const ctx = { + storage: { + sql: createSqlStorage(db), + transactionSync: (fn: () => T) => db.transaction(fn)(), + }, + blockConcurrencyWhile: async (fn: () => Promise) => fn(), + }; + counter = new AiTokenBudgetCounter(ctx as never, {} as never); + // No AI_GATEWAY_ID / CF_ACCOUNT_ID: an installation without an addressable gateway. + env = { + KV: makeKv(), + DATABASE: {}, + AI_TOKEN_BUDGET_COUNTER: { idFromName: (name: string) => name, get: () => counter }, + } as unknown as Env; + mocks.resolveAdminSettingDetails.mockReset(); +}); +afterEach(() => db.close()); + +async function pricedResponse(userId: string) { + const response = new Response( + JSON.stringify({ usage: { prompt_tokens: 100_000, completion_tokens: 100_000 } }), + { headers: { 'content-type': 'application/json' } } + ); + await attachTokenUsageAccounting(response, { + env, + userId, + format: 'openai', + costModelId: PRICED.id, + }); +} + +describe('AiTokenBudgetCounter per-model rows', () => { + it('counts every concurrent priced call once, in provider and model rows alike', async () => { + await Promise.all(Array.from({ length: 25 }, () => pricedResponse('user'))); + + const monthCost = await getLocalMonthlyAiCostUsd(env.KV, 'user', env); + const { byModel, byDay } = await getLocalUsageBreakdown(env, 'user', new Date(0)); + expect(byModel).toHaveLength(1); + expect(byModel[0]).toMatchObject({ model: PRICED.id, provider: 'openai', requests: 25 }); + expect(byModel[0]!.inputTokens).toBe(25 * 100_000); + expect(byModel[0]!.costUsd).toBeCloseTo(monthCost, 9); + expect(monthCost).toBeGreaterThan(0); + expect(byDay).toHaveLength(1); + expect(byDay[0]!.requests).toBe(25); + }); + + it('records no model row for an unpriced (BYO or custom endpoint) call', async () => { + await incrementProviderUsage(env.KV, 'user', OPENAI, 10, 10, env); + const { byModel } = await getLocalUsageBreakdown(env, 'user', new Date(0)); + expect(byModel).toEqual([]); + const provider = await counter.getProviderUsage('1970-01-01'); + expect(provider).toHaveLength(1); + }); + + it('skips a malformed model row and keeps the good ones', async () => { + await pricedResponse('user'); + db.prepare( + `INSERT INTO ai_model_usage (budget_date, model_id, provider_id, requests, input_tokens, + output_tokens, estimated_cost_usd, updated_at) VALUES ('2026-01-01', 'bad', 'x', 1, 1, 1, 'NaN?', 0)` + ).run(); + const rows = await counter.getModelUsage('1970-01-01'); + expect(rows.map((row) => row.modelId)).toEqual([PRICED.id]); + }); + + it('returns no breakdown, without throwing, where the counter binding is absent', async () => { + const bare = { ...env, AI_TOKEN_BUDGET_COUNTER: undefined } as Env; + await expect(getLocalUsageBreakdown(bare, 'user', new Date(0))).resolves.toEqual({ + byModel: [], + byDay: [], + }); + }); +}); + +describe("the worker's usage gate reads the installation ceiling (F2)", () => { + it('refuses platform-funded admission while the strict ceiling snapshot is unreadable', async () => { + mocks.resolveAdminSettingDetails.mockRejectedValue(new Error('settings unavailable')); + await expect(checkAiUsageGate(env.KV, 'user', env)).rejects.toMatchObject({ + statusCode: 503, + error: 'SERVICE_UNAVAILABLE', + }); + // No accounted call or model row is produced while admission is unknown. + expect(await getLocalMonthlyAiCostUsd(env.KV, 'user', env)).toBe(0); + }); + + it('blocks a user who never set a cap once spend reaches the ceiling', async () => { + await pricedResponse('user'); + const spent = await getLocalMonthlyAiCostUsd(env.KV, 'user', env); + mocks.resolveAdminSettingDetails.mockResolvedValue({ value: Math.max(1, Math.floor(spent)) }); + expect(spent).toBeGreaterThanOrEqual(1); + + await expect(checkAiUsageGate(env.KV, 'user', env)).resolves.toMatchObject({ + allowed: false, + reason: 'monthly-cost-cap', + }); + expect(mocks.resolveAdminSettingDetails).toHaveBeenCalledWith( + env, + 'aiProxy.perUserMonthlyCostCeilingUsd' + ); + }); + + it('lets the same user through with no ceiling set (control)', async () => { + await pricedResponse('user'); + mocks.resolveAdminSettingDetails.mockResolvedValue({ value: 0 }); + await expect(checkAiUsageGate(env.KV, 'user', env)).resolves.toEqual({ allowed: true }); + }); +}); + +describe('gateway install: the worker gate never reads the ceiling (rule 60)', () => { + it('makes no admin-settings read and the same KV reads as before', async () => { + const gatewayEnv = { + ...env, + AI_GATEWAY_ID: 'gw', + CF_ACCOUNT_ID: 'acct', + CF_API_TOKEN: 'tok', + } as unknown as Env; + const getProviderUsage = vi.spyOn(counter, 'getProviderUsage'); + await expect(checkAiUsageGate(gatewayEnv.KV, 'user', gatewayEnv)).resolves.toEqual({ + allowed: true, + }); + expect(mocks.resolveAdminSettingDetails).not.toHaveBeenCalled(); + expect(getProviderUsage).not.toHaveBeenCalled(); + // settings (token budget), settings (monthly cap); daily usage goes to the DO counter. + expect( + vi.mocked(gatewayEnv.KV.get).mock.calls.map(([key]) => String(key).split(':')[0]) + ).toEqual(['ai-budget-settings', 'ai-budget-settings']); + }); +}); diff --git a/apps/api/tests/unit/durable-objects/sam-operator-budget-denial.test.ts b/apps/api/tests/unit/durable-objects/sam-operator-budget-denial.test.ts new file mode 100644 index 0000000000..24b4dbeafd --- /dev/null +++ b/apps/api/tests/unit/durable-objects/sam-operator-budget-denial.test.ts @@ -0,0 +1,152 @@ +import { createOpenAICompatible } from '@ai-sdk/openai-compatible'; +import { incrementProviderUsage } from '@simple-agent-manager/ai-proxy'; +import { DEFAULT_SAM_MODEL } from '@simple-agent-manager/shared'; +import Database from 'better-sqlite3'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import { OperatorController } from '../../../src/durable-objects/sam-session/operator/controller'; +import * as model from '../../../src/durable-objects/sam-session/operator/model'; +import type { Env } from '../../../src/env'; +import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; +import { createSqlStorage } from './sql-storage-test-utils'; + +const databases: Database.Database[] = []; +afterEach(() => { + vi.restoreAllMocks(); + databases.splice(0).forEach((db) => db.close()); +}); + +async function fixture(administrator: boolean | null, cancelDuringBudgetRead = false) { + const database = new Database(':memory:'); + const privateDatabase = new Database(':memory:'); + databases.push(database, privateDatabase); + createSchemaTables(database, [schema.users, schema.platformSettings]); + database.exec( + "INSERT INTO users(id,name,email,status,role) VALUES ('owner','Owner','owner@example.test','active','user')" + ); + if (administrator) + database + .prepare('INSERT INTO platform_settings(key,value,updated_at) VALUES (?,?,?)') + .run('aiProxy.perUserMonthlyCostCeilingUsd', '1', new Date().toISOString()); + const rows = new Map(); + let onSpendRead: (() => void) | undefined; + if (administrator === false) + rows.set('ai-budget-settings:owner', JSON.stringify({ monthlyCostCapUsd: 1 })); + const kv = { + get: async (key: string, type?: string) => { + if (key.startsWith('ai-provider-usage:')) onSpendRead?.(); + const value = rows.get(key) ?? null; + return value === null ? null : type === 'json' ? JSON.parse(value) : value; + }, + put: async (key: string, value: string) => { + rows.set(key, value); + }, + } as unknown as KVNamespace; + const env = { DATABASE: createSqliteD1(database), KV: kv, BASE_DOMAIN: 'example.test' } as Env; + if (administrator !== null) + await incrementProviderUsage( + kv, + 'owner', + { + providerId: 'openai', + providerName: 'OpenAI', + dialect: 'openai', + }, + 1, + 1, + env, + 2 + ); + const pending: Promise[] = []; + const ctx = { + storage: { + transactionSync: (fn: () => T) => privateDatabase.transaction(fn)(), + setAlarm: vi.fn(async () => undefined), + deleteAlarm: vi.fn(async () => undefined), + }, + waitUntil: (work: Promise) => { + pending.push(work); + }, + } as unknown as DurableObjectState; + const controller = new OperatorController(ctx, env, createSqlStorage(privateDatabase)); + controller.store.bindUser('owner'); + controller.store.setEnabled(true); + const provider = vi.fn(async () => { + throw new Error('PRIVATE PROVIDER DIAGNOSTIC'); + }); + const languageModel = createOpenAICompatible({ + name: 'budget-test', + baseURL: 'https://provider.example.test/v1', + apiKey: 'unused', + fetch: provider, + }).chatModel(DEFAULT_SAM_MODEL); + let release!: () => void; + const barrier = new Promise((resolve) => { + release = resolve; + }); + vi.spyOn(model, 'resolveOperatorModel').mockImplementation(async () => { + await barrier; + return languageModel; + }); + const request = (path: string, body?: unknown) => + new Request(`https://sam-session${path}`, { + method: body ? 'POST' : 'GET', + headers: { 'content-type': 'application/json', 'x-sam-user-id': 'owner' }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + const accepted = await controller.handle( + request('/turns', { requestKey: 'test', message: 'Hello' }) + ); + expect(accepted?.status).toBe(202); + const turn = controller.store.active()!; + const stream = await controller.handle(request(`/turns/${turn.id}/stream`)); + expect(stream?.status).toBe(200); + const streamed = stream!.text(); + if (cancelDuringBudgetRead) + onSpendRead = () => { + controller.store.setState(turn.id, 'cancelled', null, 'Cancelled by user'); + }; + release(); + await Promise.all(pending); + return { controller, request, provider, streamed: await streamed, turn }; +} + +describe('operator budget denial through real Mastra prepareStep and controller', () => { + it.each([true, false])( + 'persists monthly recovery advice for live-refetch clients, administrator=%s', + async (administrator) => { + const f = await fixture(administrator); + expect(f.provider).not.toHaveBeenCalled(); + expect(f.streamed).toContain('"type":"done","state":"interrupted"'); + const history = await f.controller.handle(f.request('/turns')); + const body = (await history!.json()) as { turns: Array<{ error: string }> }; + expect(body.turns[0]!.error).toContain( + administrator + ? 'Contact your administrator or wait until next month.' + : 'Adjust your cap in Settings > Usage.' + ); + expect(f.controller.store.turn(f.turn.id)?.error).toBe(body.turns[0]!.error); + } + ); + + it('keeps unexpected provider failures generic', async () => { + const f = await fixture(null); + expect(f.provider).toHaveBeenCalled(); + const history = await f.controller.handle(f.request('/turns')); + const body = (await history!.json()) as { turns: Array<{ error: string }> }; + expect(body.turns[0]!.error).toContain('SAM could not finish this turn.'); + expect(JSON.stringify(body)).not.toContain('PRIVATE PROVIDER DIAGNOSTIC'); + expect(f.streamed).not.toContain('PRIVATE PROVIDER DIAGNOSTIC'); + }); + + it('does not replace cancellation when a monthly budget read finishes after it', async () => { + const f = await fixture(true, true); + expect(f.provider).not.toHaveBeenCalled(); + expect(f.controller.store.turn(f.turn.id)).toMatchObject({ + state: 'cancelled', + error: 'Cancelled by user', + }); + expect(f.streamed).toContain('"type":"done","state":"cancelled"'); + }); +}); diff --git a/apps/api/tests/unit/durable-objects/sam-session.test.ts b/apps/api/tests/unit/durable-objects/sam-session.test.ts index 028efc4e6c..50bb01a601 100644 --- a/apps/api/tests/unit/durable-objects/sam-session.test.ts +++ b/apps/api/tests/unit/durable-objects/sam-session.test.ts @@ -57,6 +57,20 @@ vi.mock('../../../src/services/platform-capabilities', async (original) => ({ resolveLlmEndpointCapability: vi.fn(async () => null), })); +// These protocol fixtures have no settings DB. Supply a readable, disabled ceiling +// while keeping the real usage gate and all other settings resolution in place. +vi.mock('../../../src/services/admin-settings-resolution', async (original) => { + const actual = await original(); + return { + ...actual, + resolveAdminSettingDetails: vi.fn(async (env, key) => + key === 'aiProxy.perUserMonthlyCostCeilingUsd' + ? { value: 0 } + : actual.resolveAdminSettingDetails(env, key) + ), + }; +}); + // Mock cloudflare:workers (vitest hoists vi.mock calls automatically) function makeBudgetKv(): KVNamespace { diff --git a/apps/api/tests/unit/services/ai-proxy-ports.test.ts b/apps/api/tests/unit/services/ai-proxy-ports.test.ts index 7cbedc34a9..750b7f255f 100644 --- a/apps/api/tests/unit/services/ai-proxy-ports.test.ts +++ b/apps/api/tests/unit/services/ai-proxy-ports.test.ts @@ -7,6 +7,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; const mocks = vi.hoisted(() => ({ getPlatformAgentCredential: vi.fn(), resolveAdminSetting: vi.fn(), + resolveAdminSettingDetails: vi.fn(), drizzle: vi.fn(() => ({ handle: 'fresh' })), })); @@ -15,6 +16,7 @@ vi.mock('../../../src/services/platform-credentials', () => ({ })); vi.mock('../../../src/services/admin-settings-resolution', () => ({ resolveAdminSetting: mocks.resolveAdminSetting, + resolveAdminSettingDetails: mocks.resolveAdminSettingDetails, })); vi.mock('drizzle-orm/d1', () => ({ drizzle: mocks.drizzle })); @@ -72,4 +74,33 @@ describe('aiProxyPorts', () => { 'performance.externalReadTimeoutMs' ); }); + + it('reads the per-user monthly ceiling admin setting as a number', async () => { + mocks.resolveAdminSettingDetails.mockResolvedValueOnce({ value: 25 }); + + await expect(aiProxyPorts(env).monthlyCostCeilingUsd()).resolves.toBe(25); + expect(mocks.resolveAdminSettingDetails).toHaveBeenCalledWith( + env, + 'aiProxy.perUserMonthlyCostCeilingUsd' + ); + }); + + it.each([0, 25])( + 'does not reuse a previous ceiling of %s after a failed settings read', + async (value) => { + mocks.resolveAdminSettingDetails.mockResolvedValueOnce({ value }); + await aiProxyPorts(env).monthlyCostCeilingUsd(); + mocks.resolveAdminSettingDetails.mockRejectedValueOnce(new Error('settings unavailable')); + + await expect(aiProxyPorts(env).monthlyCostCeilingUsd()).rejects.toThrow( + 'settings unavailable' + ); + } + ); + + it('throws on a cold isolate with unreadable settings, rather than reporting no ceiling', async () => { + mocks.resolveAdminSettingDetails.mockRejectedValueOnce(new Error('settings unavailable')); + + await expect(aiProxyPorts(env).monthlyCostCeilingUsd()).rejects.toThrow('settings unavailable'); + }); }); diff --git a/apps/api/tests/unit/services/ai-proxy-settings.test.ts b/apps/api/tests/unit/services/ai-proxy-settings.test.ts new file mode 100644 index 0000000000..a7289f8f7c --- /dev/null +++ b/apps/api/tests/unit/services/ai-proxy-settings.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest'; + +import { + AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING, + AI_PROXY_SETTINGS, +} from '../../../src/services/ai-proxy-settings'; + +const ceiling = AI_PROXY_SETTINGS.find( + (setting) => setting.name === AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING +)!; + +describe('installation ceiling numeric representation', () => { + it('allows an operator to configure a ceiling above one million USD', () => { + expect(ceiling.validate(2_000_000)).toBe(true); + }); + + it('accepts zero (disabled) and the largest exactly representable integer', () => { + expect(ceiling.validate(0)).toBe(true); + expect(ceiling.validate(Number.MAX_SAFE_INTEGER)).toBe(true); + expect(ceiling.range).toEqual({ min: 0, max: Number.MAX_SAFE_INTEGER }); + }); + + it.each([-1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1])( + 'rejects non-whole, negative, or inexact values (%s)', + (value) => { + expect(ceiling.validate(value)).toBe(false); + } + ); +}); diff --git a/apps/api/tests/unit/usage-budget-routes.test.ts b/apps/api/tests/unit/usage-budget-routes.test.ts index 271c1b82c9..c0737b5a28 100644 --- a/apps/api/tests/unit/usage-budget-routes.test.ts +++ b/apps/api/tests/unit/usage-budget-routes.test.ts @@ -4,7 +4,7 @@ * Tests the route handlers' behavior: response shapes, error handling, * utilization calculation, and validation error forwarding. */ -import { describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; // --------------------------------------------------------------------------- // Mock KV @@ -43,6 +43,13 @@ vi.mock('../../src/middleware/auth', () => ({ getUserId: () => 'user-budget-1', })); +// Installation ceiling (admin setting), read only on installations without a gateway. +const mockResolveAdminSettingDetails = vi.fn(); +vi.mock('../../src/services/admin-settings-resolution', () => ({ + resolveAdminSetting: vi.fn(), + resolveAdminSettingDetails: (...args: unknown[]) => mockResolveAdminSettingDetails(...args), +})); + // Mock logger vi.mock('../../src/lib/logger', () => ({ log: { info: vi.fn(), error: vi.fn(), warn: vi.fn() }, @@ -73,6 +80,7 @@ describe('GET /api/usage/ai/budget', () => { kvStore.clear(); mockIterateGatewayLogs.mockReset(); vi.clearAllMocks(); + mockResolveAdminSettingDetails.mockResolvedValue({ value: 0 }); }); it('returns platform defaults when user has no custom settings', async () => { @@ -162,6 +170,7 @@ describe('GET /api/usage/ai/budget', () => { it('returns zero month cost when gateway is not configured', async () => { const resp = await testApp.request('/api/usage/ai/budget', {}, makeEnv({ AI_GATEWAY_ID: '' })); + expect(resp.status).toBe(200); const data = await resp.json(); expect(data.monthCostUsd).toBe(0); @@ -313,3 +322,67 @@ describe('DELETE /api/usage/ai/budget', () => { expect(data.success).toBe(true); }); }); + +describe('installation monthly ceiling (no AI Gateway)', () => { + // No addressable gateway and no counter binding: SAM prices spend itself (KV fallback). + const noGateway = () => makeEnv({ AI_GATEWAY_ID: '', CF_ACCOUNT_ID: '' } as Partial); + + beforeEach(() => { + kvStore.clear(); + vi.clearAllMocks(); + mockResolveAdminSettingDetails.mockResolvedValue({ value: 25 }); + }); + + it('GET reports the ceiling as the enforced cap when the user set none', async () => { + const resp = await testApp.request('/api/usage/ai/budget', {}, noGateway()); + expect(resp.status).toBe(200); + const data = await resp.json(); + expect(data.monthlyCostCap).toEqual({ available: true, ceilingUsd: 25, effectiveCapUsd: 25 }); + expect(data.utilization.monthlyCostPercent).toBe(0); + }); + + it('GET keeps a lower user cap', async () => { + kvStore.set('ai-budget-settings:user-budget-1', JSON.stringify({ monthlyCostCapUsd: 10 })); + const data = await (await testApp.request('/api/usage/ai/budget', {}, noGateway())).json(); + expect(data.monthlyCostCap.effectiveCapUsd).toBe(10); + }); + + it('PUT refuses a cap above the ceiling and stores nothing', async () => { + const resp = await testApp.request( + '/api/usage/ai/budget', + { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ monthlyCostCapUsd: 60 }), + }, + noGateway() + ); + expect(resp.status).toBe(400); + expect((await resp.json()).message).toMatch(/between 0\.01 and 25/); + expect(kvStore.has('ai-budget-settings:user-budget-1')).toBe(false); + }); + + it('PUT accepts a cap at the ceiling (owner control)', async () => { + const resp = await testApp.request( + '/api/usage/ai/budget', + { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ monthlyCostCapUsd: 25 }), + }, + noGateway() + ); + expect(resp.status).toBe(200); + }); + + it('a gateway installation never reads the ceiling', async () => { + mockIterateGatewayLogs.mockResolvedValue(undefined); + const data = await (await testApp.request('/api/usage/ai/budget', {}, makeEnv())).json(); + expect(data.monthlyCostCap).toEqual({ + available: true, + ceilingUsd: null, + effectiveCapUsd: null, + }); + expect(mockResolveAdminSettingDetails).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx b/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx index b6f56575d4..1e2c4ae518 100644 --- a/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx +++ b/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx @@ -1,5 +1,5 @@ import type { UserAiBudgetResponse } from '@simple-agent-manager/shared'; -import { Body, Card, CardTitle, SectionHeading, Spinner } from '@simple-agent-manager/ui'; +import { Body, Button, Card, CardTitle, SectionHeading, Spinner } from '@simple-agent-manager/ui'; import { Settings2, ShieldAlert } from 'lucide-react'; import { useCallback, useEffect, useState } from 'react'; @@ -22,15 +22,15 @@ function BudgetBar({ unit: string; }) { const pct = limit > 0 ? Math.min(100, (used / limit) * 100) : 0; + const format = unit === '$' ? formatCost : formatTokens; const barColor = pct >= 100 ? 'bg-danger' : pct >= 80 ? 'bg-warning' : 'bg-accent-emphasis'; return (
-
- {label} +
+ {label} - {unit === '$' ? formatCost(used) : formatTokens(used)} /{' '} - {unit === '$' ? formatCost(limit) : formatTokens(limit)} + {format(used)} / {format(limit)}