Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
d823372
feat(ai): installation monthly ceiling and local per-model metering (…
raphaeltm Nov 17, 2026
0cab21c
fix(ai): address L13 review findings
raphaeltm Nov 17, 2026
443b32f
style: sort imports in L13 tests
raphaeltm Nov 17, 2026
8af2045
test(web): give the ceiling audit a valid compute usage mock
raphaeltm Nov 17, 2026
11e0532
test(web): fix unavailable-note test id and capture the budget sectio…
raphaeltm Nov 17, 2026
60bf78d
fix(web): readable Save button and unavailable-cap copy in budget set…
raphaeltm Nov 17, 2026
574e192
fix(ai): close L13 passthrough metering and cap recovery gaps
raphaeltm Nov 17, 2026
2912d05
refactor(ai): isolate passthrough funding admission
raphaeltm Nov 17, 2026
ca88e62
fix(web): attribute equal monthly caps to administrator
raphaeltm Nov 17, 2026
6e4df27
fix(web): honor monthly cap capability during onboarding
raphaeltm Nov 17, 2026
976bee9
docs: record L13 staging proof and cleanup
raphaeltm Nov 18, 2026
63509a3
fix(ai): refuse unknown ceilings and meter legacy function output
raphaeltm Nov 18, 2026
508f1e2
docs(ai): describe fail-closed ceiling reads
raphaeltm Nov 18, 2026
2583b99
fix(ai): meter complete fallback requests and remove arbitrary ceilin…
raphaeltm Nov 18, 2026
33aa806
fix(ai): return retryable outages for unreadable monthly spend
raphaeltm Nov 18, 2026
8a90974
fix(ai): bind local catalog prices to canonical provider endpoints
raphaeltm Nov 18, 2026
be77a19
refactor(ai): reuse linear URL path normalization
raphaeltm Nov 18, 2026
3079a15
test: stabilize liveness health probe budget assertion
raphaeltm Nov 18, 2026
f6bf633
test(ai): supply readable ceiling settings in protocol fixtures
raphaeltm Nov 18, 2026
8a9fe4b
fix(web): scope monthly budget warning to counted requests
raphaeltm Nov 18, 2026
a9a8e81
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 18, 2026
8fe5cbc
fix(ai): preserve monthly cap guidance in private operator turns
raphaeltm Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 9 additions & 11 deletions apps/api/src/durable-objects/sam-session/agent-loop.ts
Original file line number Diff line number Diff line change
@@ -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.
*
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down
31 changes: 27 additions & 4 deletions apps/api/src/durable-objects/sam-session/operator/agent.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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),
Expand All @@ -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;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
Expand Down
9 changes: 7 additions & 2 deletions apps/api/src/durable-objects/sam-session/operator/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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
);
}
19 changes: 7 additions & 12 deletions apps/api/src/routes/ai-proxy-admission.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
10 changes: 4 additions & 6 deletions apps/api/src/routes/ai-proxy-anthropic-support.ts
Original file line number Diff line number Diff line change
@@ -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`).
Expand Down Expand Up @@ -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(
Expand All @@ -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 {
Expand Down
10 changes: 8 additions & 2 deletions apps/api/src/routes/ai-proxy-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) ---
Expand Down Expand Up @@ -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) ---
Expand Down
22 changes: 10 additions & 12 deletions apps/api/src/routes/ai-proxy-passthrough-errors.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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(
Expand All @@ -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);
}
77 changes: 69 additions & 8 deletions apps/api/src/routes/ai-proxy-passthrough-prepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 }>;

Expand Down Expand Up @@ -85,7 +95,10 @@ interface PrepareProxyOptions {
requestTooLargeResponse: (maxBytes: number) => Response;
invalidBodyResponse?: (body: Record<string, unknown>) => 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;
}

Expand Down Expand Up @@ -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<Response | null> {
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
Expand Down Expand Up @@ -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,
Expand All @@ -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, {
Expand Down
Loading
Loading