From d8233725a08f7229b448a900ae8240d92ad2b93b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 07:10:29 +0000 Subject: [PATCH 01/21] feat(ai): installation monthly ceiling and local per-model metering (L13) Self-host landing slice L13. Main already had local metering and the local monthly cap from L12; this adds the remaining pieces: - F2: aiProxy.monthlyCostCeilingUsd, a superadmin-only installation ceiling. Without an addressable AI Gateway the enforced cap is min(user cap, ceiling); clearing a cap keeps the ceiling, and a cap above it is refused. Gateway installs never read it (same 4 KV reads). - F26: one cap predicate (effectiveMonthlyCostCapUsd) for the gate, the budget page and validation. - Per-model, per-day rows in AiTokenBudgetCounter, written in the same transaction as the provider row, for the usage page without a gateway. - A malformed stored budget row no longer fails AI calls. Co-Authored-By: Claude Opus 5.5 --- .../sam-session/operator/model.ts | 9 +- apps/api/src/routes/usage.ts | 45 +++- apps/api/src/services/ai-proxy-ports.ts | 4 + apps/api/src/services/ai-proxy-settings.ts | 25 +- apps/api/src/services/ai-token-budget.ts | 24 +- .../api/src/services/platform-capabilities.ts | 1 + ...i-token-budget-counter-model-usage.test.ts | 136 +++++++++++ .../unit/services/ai-proxy-ports.test.ts | 7 + .../ai-usage/AiBudgetSettingsSection.tsx | 59 +++-- .../playwright/compute-usage-audit.spec.ts | 157 +++++++++---- .../light-mode-settings-cluster-audit.spec.ts | 18 +- .../marketing-shots-compute.spec.ts | 1 + .../monthly-cost-ceiling-audit.spec.ts | 176 ++++++++++++++ .../native-hardware-display.spec.ts | 1 + .../docs/docs/reference/configuration.md | 72 +++--- packages/ai-proxy/src/ai-budget-settings.ts | 69 +++++- packages/ai-proxy/src/ai-model-usage.ts | 108 +++++++++ packages/ai-proxy/src/ai-monthly-cost-cap.ts | 85 +++++-- .../ai-proxy/src/ai-token-budget-counter.ts | 57 ++++- packages/ai-proxy/src/ai-token-budget.ts | 21 +- .../ai-proxy/src/ai-token-usage-accounting.ts | 14 +- packages/ai-proxy/src/index.ts | 5 + packages/ai-proxy/src/ports.ts | 6 + .../tests/unit/ai-gateway-logs.test.ts | 5 +- .../tests/unit/ai-monthly-cost-cron.test.ts | 5 +- .../tests/unit/ai-token-budget.test.ts | 103 ++++++--- .../unit/direct-upstream-metering.test.ts | 12 +- .../tests/unit/monthly-cost-ceiling.test.ts | 215 ++++++++++++++++++ .../tests/unit/sam-provider-mode.test.ts | 105 +++++---- packages/shared/src/types/ai-usage.ts | 11 +- ...-local-ai-metering-installation-ceiling.md | 52 +++++ 31 files changed, 1392 insertions(+), 216 deletions(-) create mode 100644 apps/api/tests/unit/durable-objects/ai-token-budget-counter-model-usage.test.ts create mode 100644 apps/web/tests/playwright/monthly-cost-ceiling-audit.spec.ts create mode 100644 packages/ai-proxy/src/ai-model-usage.ts create mode 100644 packages/ai-proxy/tests/unit/monthly-cost-ceiling.test.ts create mode 100644 tasks/active/2026-11-17-l13-local-ai-metering-installation-ceiling.md 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/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..76f2ee430d 100644 --- a/apps/api/src/services/ai-proxy-ports.ts +++ b/apps/api/src/services/ai-proxy-ports.ts @@ -5,6 +5,7 @@ import { drizzle } from 'drizzle-orm/d1'; import type { Env } from '../env'; import { getCredentialEncryptionKey } from '../lib/secrets'; import { resolveAdminSetting } from './admin-settings-resolution'; +import { AI_PROXY_MONTHLY_COST_CEILING_SETTING } from './ai-proxy-settings'; import { getPlatformAgentCredential } from './platform-credentials'; /** @@ -23,5 +24,8 @@ export function aiProxyPorts(env: Env, db?: ReturnType): AiProxy }, externalReadTimeoutMs: async () => Number(await resolveAdminSetting(env, 'performance.externalReadTimeoutMs')), + // Per-isolate cached admin settings snapshot: at most one D1 read per cache TTL. + monthlyCostCeilingUsd: async () => + Number(await resolveAdminSetting(env, AI_PROXY_MONTHLY_COST_CEILING_SETTING)), }; } diff --git a/apps/api/src/services/ai-proxy-settings.ts b/apps/api/src/services/ai-proxy-settings.ts index f7543f6f49..9ec776118c 100644 --- a/apps/api/src/services/ai-proxy-settings.ts +++ b/apps/api/src/services/ai-proxy-settings.ts @@ -5,7 +5,12 @@ 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_MONTHLY_COST_CEILING_SETTING = 'aiProxy.monthlyCostCeilingUsd' as const; +export type AiProxySettingName = + typeof AI_PROXY_DIRECT_UPSTREAM_SETTING | typeof AI_PROXY_MONTHLY_COST_CEILING_SETTING; + +/** Largest installation ceiling an admin can enter, in whole USD (input sanity bound only). */ +export const MAX_AI_PROXY_MONTHLY_COST_CEILING_USD = 1_000_000; export const AI_PROXY_SETTINGS: readonly AdminSettingDefinition[] = [ { @@ -14,10 +19,26 @@ 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.monthlyCostCeilingUsd), 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_MONTHLY_COST_CEILING_SETTING, + type: 'integer', + defaultValue: 0, + category: 'AI models', + description: + 'Installation-wide monthly AI spend ceiling per user, 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, + range: { min: 0, max: MAX_AI_PROXY_MONTHLY_COST_CEILING_USD }, + validate: (value) => + typeof value === 'number' && + Number.isInteger(value) && + value >= 0 && + value <= MAX_AI_PROXY_MONTHLY_COST_CEILING_USD, + }, ]; diff --git a/apps/api/src/services/ai-token-budget.ts b/apps/api/src/services/ai-token-budget.ts index dbdfd78327..19d5d00c09 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, @@ -19,3 +27,17 @@ export { 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) { + return checkAiUsageGateWithPorts(kv, userId, env, aiProxyPorts(env)); +} + +/** 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/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/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..dcb9ff335f --- /dev/null +++ b/apps/api/tests/unit/durable-objects/ai-token-budget-counter-model-usage.test.ts @@ -0,0 +1,136 @@ +/** + * 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(() => ({ resolveAdminSetting: vi.fn() })); +vi.mock('../../../src/services/admin-settings-resolution', () => ({ + resolveAdminSetting: mocks.resolveAdminSetting, +})); + +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.resolveAdminSetting.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('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.resolveAdminSetting.mockResolvedValue(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.resolveAdminSetting).toHaveBeenCalledWith(env, 'aiProxy.monthlyCostCeilingUsd'); + }); + + it('lets the same user through with no ceiling set (control)', async () => { + await pricedResponse('user'); + mocks.resolveAdminSetting.mockResolvedValue(0); + await expect(checkAiUsageGate(env.KV, 'user', env)).resolves.toEqual({ allowed: true }); + }); +}); 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..904631e6d6 100644 --- a/apps/api/tests/unit/services/ai-proxy-ports.test.ts +++ b/apps/api/tests/unit/services/ai-proxy-ports.test.ts @@ -72,4 +72,11 @@ describe('aiProxyPorts', () => { 'performance.externalReadTimeoutMs' ); }); + + it('reads the installation monthly ceiling admin setting as a number', async () => { + mocks.resolveAdminSetting.mockResolvedValueOnce(25); + + await expect(aiProxyPorts(env).monthlyCostCeilingUsd()).resolves.toBe(25); + expect(mocks.resolveAdminSetting).toHaveBeenCalledWith(env, 'aiProxy.monthlyCostCeilingUsd'); + }); }); diff --git a/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx b/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx index b6f56575d4..aa787d4457 100644 --- a/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx +++ b/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx @@ -115,6 +115,13 @@ export function BudgetSettingsSection() { } } + const cap = budget?.monthlyCostCap; + const ceilingUsd = cap?.ceilingUsd ?? null; + // The installation ceiling, not the user's own cap, is what binds. + const capFromCeiling = + ceilingUsd !== null && + (budget?.settings.monthlyCostCapUsd == null || budget.settings.monthlyCostCapUsd > ceilingUsd); + if (loading) { return (
@@ -172,14 +179,20 @@ export function BudgetSettingsSection() { limit={budget.effectiveLimits.dailyOutputTokenLimit} unit="tokens" /> - {budget.settings.monthlyCostCapUsd !== null && ( + {cap?.effectiveCapUsd != null && ( )} + {cap && !cap.available && ( + + Monthly cost caps are not available on this installation: SAM cannot price AI spend + here. Daily token limits still apply. + + )} {budget.exceeded && (
-
- - setMonthlyCap(e.target.value)} - placeholder="No limit" - className="w-full px-3 py-2.5 min-h-[44px] rounded-md text-fg-primary text-sm tabular-nums focus:outline-none focus:ring-2 focus:ring-accent-primary" - /> -
+ {cap?.available !== false && ( +
+ + setMonthlyCap(e.target.value)} + placeholder={ceilingUsd !== null ? formatCost(ceilingUsd) : 'No limit'} + aria-describedby={ceilingUsd !== null ? 'monthlyCapCeiling' : undefined} + className="w-full px-3 py-2.5 min-h-[44px] rounded-md text-fg-primary text-sm tabular-nums focus:outline-none focus:ring-2 focus:ring-accent-primary" + /> + {ceilingUsd !== null && ( +

+ Your administrator limits everyone to {formatCost(ceilingUsd)} a month. You can + set a lower cap; leaving it empty uses that limit. +

+ )} +
+ )}