From 94d757e6581bb35a2be8fff3ae798ba2256f4a95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 02:36:31 +0000 Subject: [PATCH 01/11] task: plan L12 OpenAI-compatible endpoint landing --- ...26-11-17-l12-openai-compatible-endpoint.md | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 tasks/backlog/2026-11-17-l12-openai-compatible-endpoint.md diff --git a/tasks/backlog/2026-11-17-l12-openai-compatible-endpoint.md b/tasks/backlog/2026-11-17-l12-openai-compatible-endpoint.md new file mode 100644 index 0000000000..9f5210d399 --- /dev/null +++ b/tasks/backlog/2026-11-17-l12-openai-compatible-endpoint.md @@ -0,0 +1,28 @@ +# L12 — OpenAI-compatible LLM endpoint and AI proxy availability + +## Problem and scope +Land C12/C13 from sam/selfhost-pass-2 on fresh main (L3 #2733, L11 #2820, L5a #2751). An admin endpoint replaces Workers AI and SAM agent routing; proxy availability follows actual gateway configuration or explicit direct-upstream consent after authentication. Preserve current usage attribution and unrelated main changes. No self-host-only implementation. + +## Preflight and research +Classes: external-api-change, cross-component-change, business-logic-change, security-sensitive-change, docs-sync-change. Existing OpenAI chat protocol and guardedFetch are reused; no dependencies or model catalog changes. The integration version forces include_usage and moves fetch logic out of packages/ai-proxy; port selectively instead. Settings use the existing module-scoped AdminSettingsCache (bounded 60s TTL, shared single-flight, mutation generation fencing). Do not add an independent stale cache. L11 owns the capability predicate; no credential read on the unconfigured path, and no additional D1 read per call with a warm snapshot. A configured endpoint outage refuses routing rather than sending prompts to another provider. Bound settings work separately within title/diagnosis budgets. Existing L5a task documents credential parse resilience and the production custom-URL precheck; recheck read-only before C13. + +Data flow: Admin settings registry -> platform_settings/platform_credentials -> L11 capability -> worker endpoint adapter -> packages/ai-proxy target/fetch helpers -> Workers AI proxy, task-title and SAM agent consumers. Workspace callback -> lifecycle-auth -> availability -> model and budget admission -> guarded provider fetch. Agent-key proxies custom URLs or returns 404, retaining raw/JSON credential tolerance. + +Rule 74: condition is an operator-enabled proxy with an addressable gateway or explicit direct-upstream opt-in. Signal is presence of all gateway inputs, not AI_GATEWAY_ID alone. Divergence: gateway id set but account/token missing must require opt-in; healthy complete Cloudflare configuration remains available without settings reads. Tests cover divergence/convergence and 401 before availability. + +## Checklist and acceptance +- [ ] Reconfirm production custom-baseURL row count read-only; record count. +- [ ] Port endpoint definitions and shared target helpers on package seam; wire L11 capability and cached settings with bounded reads. +- [ ] Workers AI calls and SAM agent use endpoint first; configured settings failure refuses (503 proxy); Cloudflare unconfigured read-count regression. +- [ ] Wire title/diagnosis/project-model callers; fix F26 (bounded settings, no unused enforced, one cap predicate, no forced include_usage). +- [ ] Centralize proxy availability after auth; preserve #2674 unauthenticated 401. +- [ ] Direct-upstream paths; agent-key 404 when custom endpoint is not served, malformed-row controls. +- [ ] Split passthrough to <=500 lines, guard all 3 fetches, reduce outbound baseline by 3, redirect regression tests. +- [ ] Focused behavioral and cross-boundary tests with discriminating guards; lint/typecheck/test/build. +- [ ] Docs reflect settings and behavior, no unrelated spec edits. +- [ ] Draft PR, then complete candidate ready + CodeRabbit request; required local security, Cloudflare, performance and completion reviews. +- [ ] Check both staging leases, reserve and follow queue, deploy final candidate; live 401, SAM-mode chat, title generation, SAM agent, refused-private endpoint routing then reset settings; cleanup/release. +- [ ] Full CI and review gates pass, merge authorized by coordinator; channel PR/blocker/completion evidence; idea update with PR and commit. Coordinator monitors production deployment. + +## References +Idea 01M72M9AEB933ZY8269D376DKC; task 01M7KNA1CNRHWG13CMNB2SVMP5; coordinator 01M7JMXS2JRW6QQMB1356ENPM3; channel feature.selfhost-landing. Rules 18, 41, 60, 62, 74; L5a retained incident/production precheck in tasks/active/2026-11-15-l5-outbound-fetch-guard.md. From 6dac3881355c66fe8bd068cf42eba802d1d912e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 02:36:56 +0000 Subject: [PATCH 02/11] task: activate L12 landing plan --- .../2026-11-17-l12-openai-compatible-endpoint.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tasks/{backlog => active}/2026-11-17-l12-openai-compatible-endpoint.md (100%) diff --git a/tasks/backlog/2026-11-17-l12-openai-compatible-endpoint.md b/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md similarity index 100% rename from tasks/backlog/2026-11-17-l12-openai-compatible-endpoint.md rename to tasks/active/2026-11-17-l12-openai-compatible-endpoint.md From 778bc54fdf26a54176f0965850a304babf6b5822 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 02:38:23 +0000 Subject: [PATCH 03/11] refactor(ai): split passthrough preparation from forwarding --- .../routes/ai-proxy-passthrough-prepare.ts | 248 +++++++++++++++++ apps/api/src/routes/ai-proxy-passthrough.ts | 261 +----------------- 2 files changed, 263 insertions(+), 246 deletions(-) create mode 100644 apps/api/src/routes/ai-proxy-passthrough-prepare.ts diff --git a/apps/api/src/routes/ai-proxy-passthrough-prepare.ts b/apps/api/src/routes/ai-proxy-passthrough-prepare.ts new file mode 100644 index 0000000000..07a77c8726 --- /dev/null +++ b/apps/api/src/routes/ai-proxy-passthrough-prepare.ts @@ -0,0 +1,248 @@ +/** + * AI proxy passthrough routes — URL-path-based workspace auth. + * + * These routes embed the workspace callback token in the URL path instead of + * auth headers, so protocol auth headers can be reserved for upstream provider + * credentials that are resolved server-side. + * + * Routes: + * POST /ai/proxy/:wstoken/anthropic/v1/messages + * POST /ai/proxy/:wstoken/anthropic/v1/messages/count_tokens + * POST /ai/proxy/:wstoken/openai/v1/chat/completions + * + * The wstoken is verified as a workspace callback token to extract userId, + * 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 { DEFAULT_AI_PROXY_RATE_LIMIT_RPM, DEFAULT_AI_PROXY_RATE_LIMIT_WINDOW_SECONDS, DEFAULT_AI_PROXY_REQUEST_BODY_MAX_BYTES, type Dialect } from '@simple-agent-manager/shared'; +import { drizzle } from 'drizzle-orm/d1'; +import { type Context } from 'hono'; + +import * as schema from '../db/schema'; +import type { Env } from '../env'; + +import { parsePositiveInt } from '../lib/route-helpers'; +import { readRequestJsonRecord, RequestBodyTooLargeError } from '../lib/runtime-validation'; +import { checkRateLimit, createRateLimitKey, getCurrentWindowStart } from '../middleware/rate-limit'; +import { proxyRunUsageRecorder } from '../services/agent-run-usage'; +import { AIProxyAuthError, verifyAIProxyAuth } from '../services/ai-proxy-shared'; +import { checkAiUsageGate } from '../services/ai-token-budget'; + + +import type { PreloadedRuntimeRows } from '../services/workspace-runtime-assets'; +import { anthropicError, anthropicUsageGateError, openaiError, openaiUsageGateError } from './ai-proxy-passthrough-errors'; + +import { type ResolvedProxyUpstream, resolveProxyUpstream } from './ai-proxy-passthrough-upstream'; + +type ProxyContext = Context<{ Bindings: Env }>; + +interface PassthroughAuthResult { + userId: string; + workspaceId: string; + projectId: string | null; + chatSessionId?: string | null; + agentType?: string | null; + agentSessionId?: string | null; + runtimeRows?: PreloadedRuntimeRows; + agentCredentialReference?: string | null; + agentCredentialSource?: 'user' | 'project' | 'platform' | null; + agentCredentialProvider?: string | null; + agentProviderMode?: string | null; + agentCredentialGeneration: number; +} + +interface PreparedProxyRequest extends PassthroughAuthResult { + body: Record; + modelId: string; + upstream: ResolvedProxyUpstream; + /** Insights run usage hook for this request (`proxyRunUsageRecorder`). */ + recordRunUsage: (usage: MeasuredTokenUsage) => Promise; +} + +type PreparedProxyResult = + { ok: true; value: PreparedProxyRequest } | { ok: false; response: Response }; + +interface PrepareProxyOptions { + dialect: Dialect; + jsonContext: string; + disabledResponse: () => Response; + authErrorResponse: (error: AIProxyAuthError) => Response; + invalidTokenResponse: () => Response; + rateLimitResponse: (c: ProxyContext, resetAt: number) => Response; + invalidJsonResponse: () => Response; + requestTooLargeResponse: (maxBytes: number) => Response; + invalidBodyResponse?: (body: Record) => Response | null; + missingModelResponse: () => Response; + usageGateResponse: (reason: 'daily-token-budget' | 'monthly-cost-cap') => Response; + missingUpstreamResponse: () => Response; +} + +async function verifyPassthroughAuth(wstoken: string, env: Env): Promise { + const db = drizzle(env.DATABASE, { schema }); + return verifyAIProxyAuth(wstoken, env, db); +} + +async function checkPassthroughRateLimit( + env: Env, + userId: string +): Promise<{ allowed: boolean; remaining: number; resetAt: number; limit: number }> { + const rpmLimit = + parseInt(env.AI_PROXY_RATE_LIMIT_RPM || '', 10) || DEFAULT_AI_PROXY_RATE_LIMIT_RPM; + const windowSeconds = + parseInt(env.AI_PROXY_RATE_LIMIT_WINDOW_SECONDS || '', 10) || + DEFAULT_AI_PROXY_RATE_LIMIT_WINDOW_SECONDS; + const windowStart = getCurrentWindowStart(windowSeconds); + const rateLimitKey = createRateLimitKey('ai-proxy', userId, windowStart); + + const result = await checkRateLimit(env.KV, rateLimitKey, rpmLimit, windowSeconds); + return { ...result, allowed: result.allowed, limit: rpmLimit }; +} + +export function retryAfterSeconds(resetAt: number): string { + const retryAfter = resetAt - Math.floor(Date.now() / 1000); + return Math.max(1, retryAfter).toString(); +} + +function anthropicAuthErrorResponse(error: AIProxyAuthError): Response { + const errType = error.statusCode === 403 ? 'permission_error' : 'authentication_error'; + return anthropicError(error.message, errType, error.statusCode); +} + +export function anthropicProxyOptions( + jsonContext: string, + rateLimitResponse: PrepareProxyOptions['rateLimitResponse'] +): PrepareProxyOptions { + return { + dialect: 'anthropic', + jsonContext, + disabledResponse: () => anthropicError('AI proxy is disabled', 'api_error', 503), + authErrorResponse: anthropicAuthErrorResponse, + invalidTokenResponse: () => + anthropicError('Invalid or expired workspace token', 'authentication_error', 401), + rateLimitResponse, + invalidJsonResponse: () => + anthropicError('Invalid JSON in request body', 'invalid_request_error', 400), + requestTooLargeResponse: (maxBytes) => + anthropicError(`Request body exceeds ${maxBytes} bytes`, 'invalid_request_error', 413), + missingModelResponse: () => anthropicError('model is required', 'invalid_request_error', 400), + usageGateResponse: anthropicUsageGateError, + missingUpstreamResponse: () => + anthropicError('No compatible upstream credential configured.', 'authentication_error', 401), + }; +} + +export function openaiProxyOptions(jsonContext: string): PrepareProxyOptions { + return { + dialect: 'openai-compatible', + jsonContext, + disabledResponse: () => openaiError('AI proxy is disabled', 'service_unavailable', 503), + authErrorResponse: (error) => + openaiError(error.message, 'invalid_request_error', error.statusCode), + invalidTokenResponse: () => + openaiError('Invalid or expired workspace token', 'invalid_request_error', 401), + rateLimitResponse: (c, resetAt) => { + c.header('Retry-After', retryAfterSeconds(resetAt)); + return openaiError('Rate limit exceeded. Please try again later.', 'rate_limit_error', 429); + }, + invalidJsonResponse: () => openaiError('Invalid JSON body', 'invalid_request_error', 400), + requestTooLargeResponse: (maxBytes) => + openaiError(`Request body exceeds ${maxBytes} bytes`, 'invalid_request_error', 413), + invalidBodyResponse: (body) => + !Array.isArray(body.messages) || body.messages.length === 0 + ? openaiError('messages array is required', 'invalid_request_error', 400) + : null, + missingModelResponse: () => openaiError('model is required', 'invalid_request_error', 400), + usageGateResponse: openaiUsageGateError, + missingUpstreamResponse: () => + openaiError('No compatible upstream credential configured.', 'invalid_request_error', 401), + }; +} + +export async function prepareProxyRequest( + c: ProxyContext, + options: PrepareProxyOptions +): Promise { + if (c.env.AI_PROXY_ENABLED === 'false') { + return { ok: false, response: options.disabledResponse() }; + } + + const wstoken = c.req.param('wstoken'); + if (!wstoken) { + return { ok: false, response: options.invalidTokenResponse() }; + } + + let auth: PassthroughAuthResult; + try { + auth = await verifyPassthroughAuth(wstoken, c.env); + } catch (err) { + if (err instanceof AIProxyAuthError) { + return { ok: false, response: options.authErrorResponse(err) }; + } + return { ok: false, response: options.invalidTokenResponse() }; + } + + const { allowed, remaining, resetAt, limit } = await checkPassthroughRateLimit( + c.env, + auth.userId + ); + c.header('X-RateLimit-Limit', limit.toString()); + c.header('X-RateLimit-Remaining', remaining.toString()); + c.header('X-RateLimit-Reset', resetAt.toString()); + if (!allowed) { + return { ok: false, response: options.rateLimitResponse(c, resetAt) }; + } + + let body: Record; + try { + const maxBodyBytes = parsePositiveInt( + c.env.AI_PROXY_REQUEST_BODY_MAX_BYTES, + DEFAULT_AI_PROXY_REQUEST_BODY_MAX_BYTES + ); + body = await readRequestJsonRecord(c.req.raw, options.jsonContext, maxBodyBytes); + } catch (error) { + if (error instanceof RequestBodyTooLargeError) { + return { ok: false, response: options.requestTooLargeResponse(error.maxBytes) }; + } + return { ok: false, response: options.invalidJsonResponse() }; + } + + const invalidBodyResponse = options.invalidBodyResponse?.(body); + if (invalidBodyResponse) { + return { ok: false, response: invalidBodyResponse }; + } + + const modelId = typeof body.model === 'string' ? body.model : undefined; + if (!modelId) { + 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, + workspaceId: auth.workspaceId, + projectId: auth.projectId, + agentType: auth.agentType, + agentSessionId: auth.agentSessionId, + runtimeRows: auth.runtimeRows, + dialect: options.dialect, + }); + if (!upstream) { + return { ok: false, response: options.missingUpstreamResponse() }; + } + + // 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, { + model: modelId, + credentialReference: upstream.credentialReference, + credentialSource: upstream.credentialSource, + }); + return { ok: true, value: { ...auth, body, modelId, upstream, recordRunUsage } }; +} + diff --git a/apps/api/src/routes/ai-proxy-passthrough.ts b/apps/api/src/routes/ai-proxy-passthrough.ts index 3fd944f7dc..c02f43f443 100644 --- a/apps/api/src/routes/ai-proxy-passthrough.ts +++ b/apps/api/src/routes/ai-proxy-passthrough.ts @@ -14,49 +14,27 @@ * 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 { - DEFAULT_AI_PROXY_RATE_LIMIT_RPM, - DEFAULT_AI_PROXY_RATE_LIMIT_WINDOW_SECONDS, - DEFAULT_AI_PROXY_REQUEST_BODY_MAX_BYTES, - type Dialect, -} from '@simple-agent-manager/shared'; -import { drizzle } from 'drizzle-orm/d1'; + + + import { type Context, Hono } from 'hono'; -import * as schema from '../db/schema'; + import type { Env } from '../env'; import { log } from '../lib/logger'; -import { parsePositiveInt } from '../lib/route-helpers'; -import { readRequestJsonRecord, RequestBodyTooLargeError } from '../lib/runtime-validation'; -import { - checkRateLimit, - createRateLimitKey, - getCurrentWindowStart, -} from '../middleware/rate-limit'; -import { proxyRunUsageRecorder } from '../services/agent-run-usage'; -import { AIProxyAuthError, verifyAIProxyAuth } from '../services/ai-proxy-shared'; -import { checkAiUsageGate } from '../services/ai-token-budget'; -import { - attachUpstreamTokenUsageAccounting, - estimateInputTokensFromMessages, - optionalExecutionContext, -} from '../services/ai-token-usage-accounting'; + + + + + + +import { attachUpstreamTokenUsageAccounting, estimateInputTokensFromMessages, optionalExecutionContext } from '../services/ai-token-usage-accounting'; import { copyCredentialLimitHeaders } from '../services/credential-limit-events'; -import type { PreloadedRuntimeRows } from '../services/workspace-runtime-assets'; -import { - anthropicError, - anthropicUsageGateError, - credentialErrorHeaders, - openaiError, - openaiUsageGateError, -} from './ai-proxy-passthrough-errors'; + +import { anthropicError, credentialErrorHeaders, openaiError } from './ai-proxy-passthrough-errors'; +import { anthropicProxyOptions, openaiProxyOptions, prepareProxyRequest, retryAfterSeconds } from './ai-proxy-passthrough-prepare'; import { schedulePassthroughLimitHeaders } from './ai-proxy-passthrough-telemetry'; -import { - type ResolvedProxyUpstream, - resolveProxyUpstream, - trimTrailingSlashes, -} from './ai-proxy-passthrough-upstream'; +import { type ResolvedProxyUpstream, resolveProxyUpstream, trimTrailingSlashes } from './ai-proxy-passthrough-upstream'; const aiProxyPassthroughRoutes = new Hono<{ Bindings: Env }>(); type ProxyContext = Context<{ Bindings: Env }>; @@ -69,52 +47,6 @@ type ProxyContext = Context<{ Bindings: Env }>; // Shared: verify workspace token from URL path + rate limit + budget // ============================================================================= -interface PassthroughAuthResult { - userId: string; - workspaceId: string; - projectId: string | null; - chatSessionId?: string | null; - agentType?: string | null; - agentSessionId?: string | null; - runtimeRows?: PreloadedRuntimeRows; - agentCredentialReference?: string | null; - agentCredentialSource?: 'user' | 'project' | 'platform' | null; - agentCredentialProvider?: string | null; - agentProviderMode?: string | null; - agentCredentialGeneration: number; -} - -interface PreparedProxyRequest extends PassthroughAuthResult { - body: Record; - modelId: string; - upstream: ResolvedProxyUpstream; - /** Insights run usage hook for this request (`proxyRunUsageRecorder`). */ - recordRunUsage: (usage: MeasuredTokenUsage) => Promise; -} - -type PreparedProxyResult = - { ok: true; value: PreparedProxyRequest } | { ok: false; response: Response }; - -interface PrepareProxyOptions { - dialect: Dialect; - jsonContext: string; - disabledResponse: () => Response; - authErrorResponse: (error: AIProxyAuthError) => Response; - invalidTokenResponse: () => Response; - rateLimitResponse: (c: ProxyContext, resetAt: number) => Response; - invalidJsonResponse: () => Response; - requestTooLargeResponse: (maxBytes: number) => Response; - invalidBodyResponse?: (body: Record) => Response | null; - missingModelResponse: () => Response; - usageGateResponse: (reason: 'daily-token-budget' | 'monthly-cost-cap') => Response; - missingUpstreamResponse: () => Response; -} - -async function verifyPassthroughAuth(wstoken: string, env: Env): Promise { - const db = drizzle(env.DATABASE, { schema }); - return verifyAIProxyAuth(wstoken, env, db); -} - function trimLeadingSlashes(value: string): string { let start = 0; while (start < value.length && value.charCodeAt(start) === 47) start++; @@ -138,169 +70,6 @@ function buildUpstreamAuthHeaders(upstream: ResolvedProxyUpstream): Record { - const rpmLimit = - parseInt(env.AI_PROXY_RATE_LIMIT_RPM || '', 10) || DEFAULT_AI_PROXY_RATE_LIMIT_RPM; - const windowSeconds = - parseInt(env.AI_PROXY_RATE_LIMIT_WINDOW_SECONDS || '', 10) || - DEFAULT_AI_PROXY_RATE_LIMIT_WINDOW_SECONDS; - const windowStart = getCurrentWindowStart(windowSeconds); - const rateLimitKey = createRateLimitKey('ai-proxy', userId, windowStart); - - const result = await checkRateLimit(env.KV, rateLimitKey, rpmLimit, windowSeconds); - return { ...result, allowed: result.allowed, limit: rpmLimit }; -} - -function retryAfterSeconds(resetAt: number): string { - const retryAfter = resetAt - Math.floor(Date.now() / 1000); - return Math.max(1, retryAfter).toString(); -} - -function anthropicAuthErrorResponse(error: AIProxyAuthError): Response { - const errType = error.statusCode === 403 ? 'permission_error' : 'authentication_error'; - return anthropicError(error.message, errType, error.statusCode); -} - -function anthropicProxyOptions( - jsonContext: string, - rateLimitResponse: PrepareProxyOptions['rateLimitResponse'] -): PrepareProxyOptions { - return { - dialect: 'anthropic', - jsonContext, - disabledResponse: () => anthropicError('AI proxy is disabled', 'api_error', 503), - authErrorResponse: anthropicAuthErrorResponse, - invalidTokenResponse: () => - anthropicError('Invalid or expired workspace token', 'authentication_error', 401), - rateLimitResponse, - invalidJsonResponse: () => - anthropicError('Invalid JSON in request body', 'invalid_request_error', 400), - requestTooLargeResponse: (maxBytes) => - anthropicError(`Request body exceeds ${maxBytes} bytes`, 'invalid_request_error', 413), - missingModelResponse: () => anthropicError('model is required', 'invalid_request_error', 400), - usageGateResponse: anthropicUsageGateError, - missingUpstreamResponse: () => - anthropicError('No compatible upstream credential configured.', 'authentication_error', 401), - }; -} - -function openaiProxyOptions(jsonContext: string): PrepareProxyOptions { - return { - dialect: 'openai-compatible', - jsonContext, - disabledResponse: () => openaiError('AI proxy is disabled', 'service_unavailable', 503), - authErrorResponse: (error) => - openaiError(error.message, 'invalid_request_error', error.statusCode), - invalidTokenResponse: () => - openaiError('Invalid or expired workspace token', 'invalid_request_error', 401), - rateLimitResponse: (c, resetAt) => { - c.header('Retry-After', retryAfterSeconds(resetAt)); - return openaiError('Rate limit exceeded. Please try again later.', 'rate_limit_error', 429); - }, - invalidJsonResponse: () => openaiError('Invalid JSON body', 'invalid_request_error', 400), - requestTooLargeResponse: (maxBytes) => - openaiError(`Request body exceeds ${maxBytes} bytes`, 'invalid_request_error', 413), - invalidBodyResponse: (body) => - !Array.isArray(body.messages) || body.messages.length === 0 - ? openaiError('messages array is required', 'invalid_request_error', 400) - : null, - missingModelResponse: () => openaiError('model is required', 'invalid_request_error', 400), - usageGateResponse: openaiUsageGateError, - missingUpstreamResponse: () => - openaiError('No compatible upstream credential configured.', 'invalid_request_error', 401), - }; -} - -async function prepareProxyRequest( - c: ProxyContext, - options: PrepareProxyOptions -): Promise { - if (c.env.AI_PROXY_ENABLED === 'false') { - return { ok: false, response: options.disabledResponse() }; - } - - const wstoken = c.req.param('wstoken'); - if (!wstoken) { - return { ok: false, response: options.invalidTokenResponse() }; - } - - let auth: PassthroughAuthResult; - try { - auth = await verifyPassthroughAuth(wstoken, c.env); - } catch (err) { - if (err instanceof AIProxyAuthError) { - return { ok: false, response: options.authErrorResponse(err) }; - } - return { ok: false, response: options.invalidTokenResponse() }; - } - - const { allowed, remaining, resetAt, limit } = await checkPassthroughRateLimit( - c.env, - auth.userId - ); - c.header('X-RateLimit-Limit', limit.toString()); - c.header('X-RateLimit-Remaining', remaining.toString()); - c.header('X-RateLimit-Reset', resetAt.toString()); - if (!allowed) { - return { ok: false, response: options.rateLimitResponse(c, resetAt) }; - } - - let body: Record; - try { - const maxBodyBytes = parsePositiveInt( - c.env.AI_PROXY_REQUEST_BODY_MAX_BYTES, - DEFAULT_AI_PROXY_REQUEST_BODY_MAX_BYTES - ); - body = await readRequestJsonRecord(c.req.raw, options.jsonContext, maxBodyBytes); - } catch (error) { - if (error instanceof RequestBodyTooLargeError) { - return { ok: false, response: options.requestTooLargeResponse(error.maxBytes) }; - } - return { ok: false, response: options.invalidJsonResponse() }; - } - - const invalidBodyResponse = options.invalidBodyResponse?.(body); - if (invalidBodyResponse) { - return { ok: false, response: invalidBodyResponse }; - } - - const modelId = typeof body.model === 'string' ? body.model : undefined; - if (!modelId) { - 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, - workspaceId: auth.workspaceId, - projectId: auth.projectId, - agentType: auth.agentType, - agentSessionId: auth.agentSessionId, - runtimeRows: auth.runtimeRows, - dialect: options.dialect, - }); - if (!upstream) { - return { ok: false, response: options.missingUpstreamResponse() }; - } - - // 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, { - model: modelId, - credentialReference: upstream.credentialReference, - credentialSource: upstream.credentialSource, - }); - return { ok: true, value: { ...auth, body, modelId, upstream, recordRunUsage } }; -} - function buildJsonUpstreamHeaders(upstream: ResolvedProxyUpstream): Record { return { ...buildUpstreamAuthHeaders(upstream), From ad28af734c8c6df8491c69bbb41687a167cd9c57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 02:45:44 +0000 Subject: [PATCH 04/11] refactor(workspaces): split runtime callbacks by concern --- .../routes/workspaces/runtime-agent-key.ts | 477 ++++++ .../workspaces/runtime-callback-response.ts | 61 + .../routes/workspaces/runtime-git-token.ts | 472 ++++++ .../workspaces/runtime-message-helpers.ts | 472 ++++++ .../src/routes/workspaces/runtime-messages.ts | 148 ++ apps/api/src/routes/workspaces/runtime.ts | 1496 +---------------- 6 files changed, 1649 insertions(+), 1477 deletions(-) create mode 100644 apps/api/src/routes/workspaces/runtime-agent-key.ts create mode 100644 apps/api/src/routes/workspaces/runtime-callback-response.ts create mode 100644 apps/api/src/routes/workspaces/runtime-git-token.ts create mode 100644 apps/api/src/routes/workspaces/runtime-message-helpers.ts create mode 100644 apps/api/src/routes/workspaces/runtime-messages.ts diff --git a/apps/api/src/routes/workspaces/runtime-agent-key.ts b/apps/api/src/routes/workspaces/runtime-agent-key.ts new file mode 100644 index 0000000000..37bdfd3f8e --- /dev/null +++ b/apps/api/src/routes/workspaces/runtime-agent-key.ts @@ -0,0 +1,477 @@ +import { AI_PROXY_DEFAULT_MODEL_KV_KEY, type AIProxyConfig, DEFAULT_AI_PROXY_ANTHROPIC_MODEL, DEFAULT_AI_PROXY_MODEL, DEFAULT_AI_PROXY_OPENAI_MODEL, getAgentDefinition, HARNESS_CAPABILITIES, isValidAgentType, resolveHarnessDialect } from '@simple-agent-manager/shared'; +import { and, eq } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/d1'; +import { type Context, Hono } from 'hono'; + + +import * as schema from '../../db/schema'; +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; + +import { getCredentialEncryptionKey } from '../../lib/secrets'; + + +import { errors } from '../../middleware/error'; +import { AgentTypeBodySchema, jsonValidator } from '../../schemas'; + + +import { resolveSessionProfileCredentialContext } from '../../services/composable-credentials/profile-context'; + + + + + + + + + + +import { extractScalewaySecretKey } from '../../services/provider-credentials'; + +import { refuseHaltedRunAccount } from '../../services/run-agent-configuration'; +import { isAiProxyEnabled, PROXY_ELIGIBLE_AGENTS, requiresExplicitSamProvider } from '../../services/sam-ai-proxy-fallback'; + + +import { getDecryptedAgentKey, getDecryptedCredentialRecord } from '../credentials'; + +import { assertWorkspaceCallbackIdentityCurrent, assertWorkspaceCallbackResourceById, verifyWorkspaceCallbackAuth } from './_helpers'; +import { agentCredentialProviderFallback, credentialAttributionFromData, persistAgentCredentialAttribution, platformProxyAttribution } from './agent-credential-attribution'; + +import { callbackJsonWithJit } from './runtime-callback-response'; +function getProxyCapability(agentType: string) { + const capability = HARNESS_CAPABILITIES.find((entry) => entry.agentType === agentType); + if (!capability?.proxyRouteSegment || !capability.proxyProviderTag) return null; + return capability; +} + +function buildPassthroughInferenceConfig(input: { + agentType: string; + baseDomain: string; + defaultModel: string; +}) { + const capability = getProxyCapability(input.agentType); + if (!capability) return null; + return { + provider: capability.proxyProviderTag, + baseURL: `https://api.${input.baseDomain}/ai/proxy/{wstoken}/${capability.proxyRouteSegment}`, + model: input.defaultModel, + apiKeySource: 'callback-token' as const, + }; +} + +function buildPlatformInferenceConfig(input: { + agentType: string; + baseDomain: string; + defaultModel: string; +}) { + const capability = getProxyCapability(input.agentType); + if (!capability) return null; + const provider = + capability.proxyProviderTag === 'anthropic-passthrough' + ? 'anthropic-proxy' + : capability.usesOpencodeConfig + ? 'openai-compatible' + : 'openai-proxy'; + const routeSegment = capability.proxyRouteSegment === 'anthropic' ? 'anthropic' : 'v1'; + return { + provider, + baseURL: `https://api.${input.baseDomain}/ai/${routeSegment}`, + model: input.defaultModel, + apiKeySource: 'callback-token' as const, + }; +} + +const runtimeRoutes = new Hono<{ Bindings: Env }>(); +type RuntimeContext = Context<{ Bindings: Env }>; +runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async (c) => { + const workspaceId = c.req.param('id'); + await verifyWorkspaceCallbackAuth(c, workspaceId); + const body = c.req.valid('json'); + + const db = drizzle(c.env.DATABASE, { schema }); + + const workspace = await assertWorkspaceCallbackResourceById(c.env, workspaceId, 'agent_key'); + + // OpenCode always uses a user-supplied credential (zen/go/custom). It never + // routes through the SAM platform proxy, so it always requires a dedicated key. + const opencodeRequiresDedicatedCredential = body.agentType === 'opencode'; + + const encryptionKey = getCredentialEncryptionKey(c.env); + // The session's profile decides whether a personal profile pin applies; the AI + // proxy and provider-limit admission resolve the same context. + const profile = await resolveSessionProfileCredentialContext(db, { + workspaceId, + agentSessionId: body.agentSessionId, + }); + let credentialData = await getDecryptedAgentKey( + db, + workspace.userId, + body.agentType, + encryptionKey, + workspace.projectId, + profile + ); + let credentialProviderMode = 'direct'; + + // An account chosen for this run that can no longer be used (paused, removed) must stop + // the run here. Without this, "no credential" would continue to the platform proxy or a + // fallback below and run the chat on an account nobody chose for it. + if (!credentialData && profile?.runConfigurationId) { + await refuseHaltedRunAccount(db, { + workspaceId, + userId: workspace.userId, + projectId: workspace.projectId, + agentType: body.agentType, + encryptionKey, + profile, + }); + } + + // SECURITY: Never return raw platform-managed credentials to tenant workspaces. + // Platform credentials are control-plane secrets and must only be used via + // SAM-mediated proxy flows (callback-token auth), not injected into tenant + // containers as env vars or auth files. + if (credentialData?.credentialSource === 'platform') { + credentialData = null; + } + + // Cloud provider credential fallback: if no dedicated agent key, check if the agent + // definition specifies a cloud provider whose credential can be used instead. + const agentDef = isValidAgentType(body.agentType) + ? getAgentDefinition(body.agentType) + : undefined; + const fallbackCloudProvider = agentDef?.fallbackCloudProvider; + if (!credentialData && fallbackCloudProvider) { + const fallbackCredential = await getDecryptedCredentialRecord( + db, + workspace.userId, + fallbackCloudProvider, + encryptionKey + ); + if (fallbackCredential) { + const secretKey = extractScalewaySecretKey(fallbackCredential.credential); + if (secretKey) { + credentialData = { + credential: secretKey, + credentialKind: 'api-key', + credentialSource: 'user', + credentialScope: 'user', + credentialReference: fallbackCredential.credentialReference, + credentialProvider: fallbackCredential.credentialProvider, + }; + credentialProviderMode = 'fallback-cloud-provider'; + } else { + log.warn('agent_key.scaleway_credential_missing_secret_key', { + workspaceId, + userId: workspace.userId, + agentType: body.agentType, + }); + } + } + } + + if (credentialData && opencodeRequiresDedicatedCredential) { + const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { + workspaceId, + agentSessionId: body.agentSessionId, + agentType: body.agentType, + attribution: credentialAttributionFromData( + credentialData, + body.agentType, + credentialProviderMode + ), + }); + return callbackJsonWithJit(c, workspace, 'agent_key', { + apiKey: credentialData.credential, + credentialKind: credentialData.credentialKind, + credentialSource: credentialData.credentialSource, + credentialReference: credentialData.credentialReference, + credentialProvider: + credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), + providerMode: credentialProviderMode, + credentialGeneration: persistedAttribution?.credentialGeneration, + }); + } + + if (!credentialData && opencodeRequiresDedicatedCredential) { + log.info('agent_key.opencode_byo_provider_missing_credential', { + workspaceId, + userId: workspace.userId, + agentType: body.agentType, + }); + throw errors.notFound('Agent credential'); + } + + // AI proxy: when enabled and agent is eligible, return proxy config when the + // credential can be forwarded to the upstream provider. + // Two modes: + // - Claude/Codex with no user credential + providerMode='sam' → platform proxy (callback-token auth) + // - User has upstream-compatible credential → passthrough proxy (user credential + // forwarded via auth headers, wstoken in URL path for analytics/rate-limiting) + // Note: platform proxy fallback requires explicit provider selection. + // Without it, users with no credential get a 404 (agent not configured). + if (PROXY_ELIGIBLE_AGENTS.has(body.agentType) && isAiProxyEnabled(c.env)) { + const baseDomain = c.env.BASE_DOMAIN; + const isClaudeCode = body.agentType === 'claude-code'; + const isCodex = body.agentType === 'openai-codex'; + let explicitProviderMode: string | null | undefined; + const getExplicitProviderMode = async (): Promise => { + if (explicitProviderMode !== undefined) return explicitProviderMode; + const settingsRows = await db + .select({ providerMode: schema.agentSettings.providerMode }) + .from(schema.agentSettings) + .where( + and( + eq(schema.agentSettings.userId, workspace.userId), + eq(schema.agentSettings.agentType, body.agentType) + ) + ) + .limit(1); + explicitProviderMode = settingsRows[0]?.providerMode ?? null; + return explicitProviderMode; + }; + + // Resolve default model: KV (admin-set) > env var > shared constant + let defaultModel: string; + if (isClaudeCode) { + defaultModel = c.env.AI_PROXY_DEFAULT_ANTHROPIC_MODEL ?? DEFAULT_AI_PROXY_ANTHROPIC_MODEL; + } else if (isCodex) { + defaultModel = c.env.AI_PROXY_DEFAULT_OPENAI_MODEL ?? DEFAULT_AI_PROXY_OPENAI_MODEL; + } else { + defaultModel = c.env.AI_PROXY_DEFAULT_MODEL ?? DEFAULT_AI_PROXY_MODEL; + try { + const kvConfig = await c.env.KV.get(AI_PROXY_DEFAULT_MODEL_KV_KEY); + if (kvConfig) { + const parsed: AIProxyConfig = JSON.parse(kvConfig); + if (parsed.defaultModel) defaultModel = parsed.defaultModel; + } + } catch { + /* KV unavailable or corrupt data — use env/default */ + } + } + + // Claude Code/Codex explicit SAM mode must route through the SAM proxy, + // not through legacy platform agent credentials as user-style passthrough. + if ((isClaudeCode || isCodex) && credentialData?.credentialSource === 'platform') { + credentialData = null; + } + + if ( + credentialData && + credentialData.baseUrl && + credentialData.providerDialect && + resolveHarnessDialect(body.agentType, credentialData.providerDialect) && + !((isClaudeCode || isCodex) && credentialData.credentialKind === 'oauth-token') + ) { + // User has their own credential — use passthrough proxy routes. + // URL-path auth: wstoken embedded in URL, user credential in auth headers. + const inferenceConfig = buildPassthroughInferenceConfig({ + agentType: body.agentType, + baseDomain, + defaultModel, + }); + if (!inferenceConfig) { + throw errors.notFound('Agent credential'); + } + + log.info('agent_key.ai_proxy_passthrough', { + workspaceId, + userId: workspace.userId, + proxyBaseUrl: inferenceConfig.baseURL, + agentType: body.agentType, + }); + + // Track credential source on associated task + const taskRows = await db + .select({ id: schema.tasks.id }) + .from(schema.tasks) + .where(eq(schema.tasks.workspaceId, workspaceId)) + .limit(1); + const task = taskRows[0]; + if (task) { + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); + await db + .update(schema.tasks) + .set({ agentCredentialSource: credentialData.credentialSource }) + .where(eq(schema.tasks.id, task.id)); + } + + const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { + workspaceId, + agentSessionId: body.agentSessionId, + agentType: body.agentType, + attribution: credentialAttributionFromData( + credentialData, + body.agentType, + 'proxy-passthrough' + ), + }); + + return callbackJsonWithJit(c, workspace, 'agent_key', { + apiKey: '__sam_proxy__', + credentialKind: credentialData.credentialKind, + credentialSource: credentialData.credentialSource, + credentialReference: credentialData.credentialReference, + credentialProvider: + credentialData.credentialProvider ?? + credentialData.providerDialect ?? + agentCredentialProviderFallback(body.agentType), + providerMode: 'proxy-passthrough', + credentialGeneration: persistedAttribution?.credentialGeneration, + inferenceConfig, + }); + } + + if (credentialData?.baseUrl) { + log.warn('agent_key.ai_proxy_incompatible_passthrough_credential', { + workspaceId, + userId: workspace.userId, + agentType: body.agentType, + providerDialect: credentialData.providerDialect ?? null, + }); + throw errors.notFound('Agent credential'); + } + + if (credentialData) { + const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { + workspaceId, + agentSessionId: body.agentSessionId, + agentType: body.agentType, + attribution: credentialAttributionFromData( + credentialData, + body.agentType, + credentialProviderMode + ), + }); + return callbackJsonWithJit(c, workspace, 'agent_key', { + apiKey: credentialData.credential, + credentialKind: credentialData.credentialKind, + credentialSource: credentialData.credentialSource, + credentialReference: credentialData.credentialReference, + credentialProvider: + credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), + providerMode: credentialProviderMode, + credentialGeneration: persistedAttribution?.credentialGeneration, + }); + } + + // Claude Code and Codex require an explicit SAM provider selection before + // using platform proxy. OpenCode never reaches this block — it always + // requires a dedicated user credential and returns/throws above. + if (requiresExplicitSamProvider(body.agentType)) { + const providerMode = await getExplicitProviderMode(); + + if (providerMode !== 'sam') { + log.info('agent_key.no_credential_no_sam_provider', { + workspaceId, + userId: workspace.userId, + agentType: body.agentType, + providerMode, + }); + throw errors.notFound('Agent credential'); + } + } + + // Activate platform proxy. + // Auth via callback token in headers. + const inferenceConfig = buildPlatformInferenceConfig({ + agentType: body.agentType, + baseDomain, + defaultModel, + }); + if (!inferenceConfig) { + throw errors.notFound('Agent credential'); + } + + log.info('agent_key.ai_proxy_sam_provider', { + workspaceId, + userId: workspace.userId, + proxyBaseUrl: inferenceConfig.baseURL, + agentType: body.agentType, + }); + + // Track credential source on associated task + const taskRows = await db + .select({ id: schema.tasks.id }) + .from(schema.tasks) + .where(eq(schema.tasks.workspaceId, workspaceId)) + .limit(1); + const task = taskRows[0]; + if (task) { + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); + await db + .update(schema.tasks) + .set({ agentCredentialSource: 'platform' }) + .where(eq(schema.tasks.id, task.id)); + } + + const platformAttribution = platformProxyAttribution(body.agentType); + const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { + workspaceId, + agentSessionId: body.agentSessionId, + agentType: body.agentType, + attribution: platformAttribution, + }); + + return callbackJsonWithJit(c, workspace, 'agent_key', { + apiKey: '__platform_proxy__', + credentialKind: 'api-key' as const, + credentialSource: 'platform' as const, + credentialReference: platformAttribution.credentialReference, + credentialProvider: platformAttribution.credentialProvider, + providerMode: platformAttribution.providerMode, + credentialGeneration: persistedAttribution?.credentialGeneration, + inferenceConfig, + }); + } + + if (!credentialData) { + throw errors.notFound('Agent credential'); + } + + // Track credential source on associated task if applicable + if (credentialData.credentialSource === 'platform') { + const taskRows = await db + .select({ id: schema.tasks.id }) + .from(schema.tasks) + .where(eq(schema.tasks.workspaceId, workspaceId)) + .limit(1); + const task = taskRows[0]; + if (task) { + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); + await db + .update(schema.tasks) + .set({ agentCredentialSource: 'platform' }) + .where(eq(schema.tasks.id, task.id)); + } + } + + const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { + workspaceId, + agentSessionId: body.agentSessionId, + agentType: body.agentType, + attribution: credentialAttributionFromData( + credentialData, + body.agentType, + credentialProviderMode + ), + }); + + return callbackJsonWithJit(c, workspace, 'agent_key', { + apiKey: credentialData.credential, + credentialKind: credentialData.credentialKind, + credentialSource: credentialData.credentialSource, + credentialReference: credentialData.credentialReference, + credentialProvider: + credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), + providerMode: credentialProviderMode, + credentialGeneration: persistedAttribution?.credentialGeneration, + }); +}); + +/** + * POST /:id/agent-settings — VM agent callback to fetch user's agent settings. + * Uses workspace callback auth (same as agent-key). + */ + +export { runtimeRoutes as agentKeyRoutes }; diff --git a/apps/api/src/routes/workspaces/runtime-callback-response.ts b/apps/api/src/routes/workspaces/runtime-callback-response.ts new file mode 100644 index 0000000000..2151e43e38 --- /dev/null +++ b/apps/api/src/routes/workspaces/runtime-callback-response.ts @@ -0,0 +1,61 @@ + + + +import { type Context } from 'hono'; + + + +import type { Env } from '../../env'; + + + + + + + + + + + + + + + + + + + + + +import { assertProviderLimitCredentialPin } from '../../services/provider-limit-credential-pin'; + + +import { type WorkspaceDeletionCallbackKind } from '../../services/workspace-deletion-callback-signal'; + + + +import { assertWorkspaceCallbackIdentityCurrent, type WorkspaceCallbackIdentitySnapshot } from './_helpers'; + + +type RuntimeContext = Context<{ Bindings: Env }>; +export async function callbackJsonWithJit>( + c: RuntimeContext, + expected: WorkspaceCallbackIdentitySnapshot, + callback: WorkspaceDeletionCallbackKind, + body: T +) { + await assertWorkspaceCallbackIdentityCurrent(c.env, expected, callback); + if ( + callback === 'agent_key' && + body.credentialSource !== 'platform' && + typeof body.credentialReference === 'string' + ) + await assertProviderLimitCredentialPin( + c.env, + expected.workspaceId, + body.credentialReference, + expected + ); + return c.json(body); +} + diff --git a/apps/api/src/routes/workspaces/runtime-git-token.ts b/apps/api/src/routes/workspaces/runtime-git-token.ts new file mode 100644 index 0000000000..92370cbcec --- /dev/null +++ b/apps/api/src/routes/workspaces/runtime-git-token.ts @@ -0,0 +1,472 @@ + +import { eq } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/d1'; +import { type Context, Hono } from 'hono'; + + +import * as schema from '../../db/schema'; +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; + + + + +import { errors } from '../../middleware/error'; + + + + +import { getInstallationToken, getUserInstallationRepositories } from '../../services/github-app'; +import { GitHubCliPolicyError, resolveWorkspaceGitHubTokenOptions } from '../../services/github-cli-policy'; +import { getExternalInstallationId } from '../../services/github-installation-ids'; +import { backfillProjectGithubRepoId } from '../../services/github-repo-id-backfill'; +import { getGitHubUserAccessTokenForOwner } from '../../services/github-user-access-token'; +import { getProjectGitLabRepository, requireGitLabUserAccessTokenResultForOwner, verifyGitLabProjectAccess } from '../../services/gitlab'; + + + + + + + + + + + +import { assertRepositoryAccess } from '../projects/_helpers'; +import { assertWorkspaceAcceptsCallback, assertWorkspaceCallbackIdentityCurrent, verifyWorkspaceCallbackAuth } from './_helpers'; + + +import { callbackJsonWithJit } from './runtime-callback-response'; +const runtimeRoutes = new Hono<{ Bindings: Env }>(); +type RuntimeContext = Context<{ Bindings: Env }>; +async function verifyWorkspaceGitHubOwnerAccess(input: { + env: Env; + workspaceId: string; + projectId: string | null; + userId: string; + repository: string; + externalInstallationId: string; + githubRepoId: number | null; +}): Promise { + const accessToken = await getGitHubUserAccessTokenForOwner( + input.env, + input.userId, + 'workspace-git-token' + ); + if (!accessToken) { + log.warn('workspace_git_token_user_access_missing', { + workspaceId: input.workspaceId, + projectId: input.projectId, + userId: input.userId, + action: 'rejected', + }); + throw errors.forbidden('GitHub user token unavailable'); + } + + // Every git and gh credential exchange lands here, so pass env to use the + // pagination hint (GITHUB_REPO_ACCESS_CACHE_TTL_SECONDS). Every exchange + // still verifies current user access against GitHub; hints never grant access. + const verifiedRepo = await assertRepositoryAccess( + accessToken, + input.externalInstallationId, + input.repository, + input.userId, + 'project-access', + input.env + ); + + if (input.githubRepoId !== null && verifiedRepo.id !== input.githubRepoId) { + log.warn('workspace_git_token_repo_id_drift', { + workspaceId: input.workspaceId, + projectId: input.projectId, + userId: input.userId, + expectedRepoId: input.githubRepoId, + verifiedRepoId: verifiedRepo.id, + action: 'rejected', + }); + throw errors.forbidden('GitHub repository access has changed; repository ID no longer matches'); + } + + return verifiedRepo.id; +} + +/** + * Resolve numeric repository IDs for a project's additional Repository Access + * entries, re-verifying user∩app access at the token-mint boundary. Stored rows + * whose access has been revoked (or whose installation no longer exposes them) + * are dropped from the scope — an unselected/inaccessible repo simply never makes + * it into the minted token's `repository_ids`, so it fails clearly downstream. + * Failure to fetch the accessible set returns the empty set rather than throwing, + * so the primary-repo token still mints (additional repos degrade, never break + * the primary clone). + */ +async function resolveAdditionalRepositoryIds(input: { + env: Env; + db: ReturnType>; + workspaceId: string; + projectId: string; + userId: string; + externalInstallationId: string; +}): Promise { + const rows = await input.db + .select({ + repository: schema.projectGithubRepositories.repository, + githubRepoId: schema.projectGithubRepositories.githubRepoId, + }) + .from(schema.projectGithubRepositories) + .where(eq(schema.projectGithubRepositories.projectId, input.projectId)); + if (rows.length === 0) { + return []; + } + + const accessToken = await getGitHubUserAccessTokenForOwner( + input.env, + input.userId, + 'workspace-git-token' + ); + if (!accessToken) { + log.warn('workspace_git_token_additional_repos_user_access_missing', { + workspaceId: input.workspaceId, + projectId: input.projectId, + userId: input.userId, + action: 'additional_repos_skipped', + }); + return []; + } + + let accessibleById = new Map(); + try { + const repositories = await getUserInstallationRepositories( + accessToken, + input.externalInstallationId, + { + flow: 'project-access', + userId: input.userId, + installationId: input.externalInstallationId, + } + ); + accessibleById = new Map(repositories.map((r) => [r.fullName.toLowerCase(), r.id])); + } catch (err) { + log.warn('workspace_git_token_additional_repos_unavailable', { + workspaceId: input.workspaceId, + projectId: input.projectId, + userId: input.userId, + error: err instanceof Error ? err.message : String(err), + action: 'additional_repos_skipped', + }); + return []; + } + + const ids: number[] = []; + for (const row of rows) { + const accessibleId = accessibleById.get(row.repository.toLowerCase()); + if (accessibleId === undefined) { + log.warn('workspace_git_token_additional_repo_access_revoked', { + workspaceId: input.workspaceId, + projectId: input.projectId, + userId: input.userId, + repository: row.repository, + action: 'excluded_from_scope', + }); + continue; + } + // Prefer the live, rename-stable id from the accessible set. Stored ids can + // drift if the repo was deleted/recreated; the live id is authoritative. + ids.push(accessibleId); + } + return ids; +} + +runtimeRoutes.post('/:id/git-token', async (c) => { + const workspaceId = c.req.param('id'); + await verifyWorkspaceCallbackAuth(c, workspaceId); + + const db = drizzle(c.env.DATABASE, { schema }); + + // Look up workspace → project to determine repo provider + const workspaceRows = await db + .select({ + workspaceId: schema.workspaces.id, + installationId: schema.workspaces.installationId, + projectId: schema.workspaces.projectId, + chatSessionId: schema.workspaces.chatSessionId, + userId: schema.workspaces.userId, + status: schema.workspaces.status, + nodeId: schema.workspaces.nodeId, + nodeStatus: schema.nodes.status, + callbackGeneration: schema.workspaces.callbackGeneration, + }) + .from(schema.workspaces) + .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) + .where(eq(schema.workspaces.id, workspaceId)) + .limit(1); + + const workspace = await assertWorkspaceAcceptsCallback( + c.env, + workspaceRows[0], + workspaceId, + 'git_token' + ); + + // Look up the project to check repoProvider + let repoProvider = 'github'; + let artifactsRepoId: string | null = null; + let githubRepoId: number | null = null; + let repositoryName: string | null = null; + if (workspace.projectId) { + const projectRows = await db + .select({ + repoProvider: schema.projects.repoProvider, + artifactsRepoId: schema.projects.artifactsRepoId, + githubRepoId: schema.projects.githubRepoId, + repository: schema.projects.repository, + }) + .from(schema.projects) + .where(eq(schema.projects.id, workspace.projectId)) + .limit(1); + + const project = projectRows[0]; + if (project) { + repoProvider = project.repoProvider || 'github'; + artifactsRepoId = project.artifactsRepoId; + githubRepoId = project.githubRepoId; + repositoryName = project.repository; + } + } + + if (repoProvider === 'artifacts') { + // ─── Artifacts token ────────────────────────────────────────────── + if (c.env.ARTIFACTS_ENABLED !== 'true') { + throw errors.forbidden('Artifacts provider is not enabled'); + } + if (!c.env.ARTIFACTS || !artifactsRepoId) { + throw errors.internal('Artifacts binding or repo ID missing'); + } + + // Clamp the token TTL to a sane range: a negative/zero/NaN or excessively + // large configured value must not mint a token that never expires (or expires + // instantly). Default 1h; hard cap 24h. + const rawTtl = Number.parseInt(c.env.ARTIFACTS_TOKEN_TTL_SECONDS || '', 10); + const ttl = Number.isFinite(rawTtl) && rawTtl > 0 && rawTtl <= 86400 ? rawTtl : 3600; + // Use requested scope or default to 'write' (agents need push access) + const requestedScope = c.req.query('scope') === 'read' ? ('read' as const) : ('write' as const); + const repo = await c.env.ARTIFACTS.get(artifactsRepoId); + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); + const tokenResult = await repo.createToken(requestedScope, ttl); + + // Strip ?expires= suffix from token for git credential use + const tokenSecret = tokenResult.plaintext.split('?expires=')[0] || tokenResult.plaintext; + + // Prefer the stored project.repository as the clone URL: it is `created.remote` + // captured at project creation and is exactly what the VM agent cloned, so its + // host is guaranteed to match what git requests from the credential helper. The + // Artifacts binding's `get().remote` has been observed to come back empty on + // staging (unlike `create().remote`); when that happens an empty cloneUrl makes + // the VM agent default the credential host to github.com, which then fails to + // match the real Artifacts host and returns no credential (git fetch/push break). + const cloneUrl = repositoryName || repo.remote || ''; + if (!repo.remote) { + log.warn('workspace_git_token.artifacts_remote_empty', { + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + artifactsRepoId, + usedStoredRepository: !!repositoryName, + action: 'fell_back_to_stored_repository', + }); + } + if (!cloneUrl) { + log.error('workspace_git_token.artifacts_clone_url_missing', { + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + artifactsRepoId, + action: 'clone_url_empty', + }); + } + + return callbackJsonWithJit(c, workspace, 'git_token', { + token: tokenSecret, + expiresAt: tokenResult.expiresAt ?? tokenResult.expires_at, + cloneUrl, + }); + } + + if (repoProvider === 'gitlab') { + if (!workspace.projectId) { + throw errors.forbidden('GitLab workspace has no project'); + } + const metadata = await getProjectGitLabRepository(db, workspace.projectId); + if (!metadata) { + throw errors.forbidden('GitLab repository metadata is missing'); + } + if (metadata.userId !== workspace.userId) { + // The stored GitLab repo binding belongs to a different user than the + // workspace owner — vending the owner's OAuth token against another + // user's binding would cross a tenant boundary. Fail closed. + log.error('workspace_git_token.gitlab_user_mismatch', { + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + workspaceUserId: workspace.userId, + metadataUserId: metadata.userId, + action: 'rejected', + }); + throw errors.forbidden('GitLab repository is not linked for this workspace owner'); + } + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); + const tokenResult = await requireGitLabUserAccessTokenResultForOwner( + c.env, + workspace.userId, + 'workspace-git-token' + ); + const verified = await verifyGitLabProjectAccess( + c.env, + tokenResult.accessToken, + metadata.gitlabProjectId + ); + if ( + verified.host !== metadata.host || + verified.gitlabProjectId !== metadata.gitlabProjectId || + verified.pathWithNamespace !== metadata.pathWithNamespace + ) { + throw errors.forbidden('GitLab repository access has changed; repository no longer matches'); + } + + return callbackJsonWithJit(c, workspace, 'git_token', { + provider: 'gitlab', + token: tokenResult.accessToken, + expiresAt: tokenResult.accessTokenExpiresAt, + cloneUrl: metadata.httpUrlToRepo, + host: metadata.host, + username: 'oauth2', + repositoryPath: metadata.pathWithNamespace, + }); + } + + // ─── GitHub token (existing flow) ────────────────────────────────── + if (!workspace.installationId) { + throw errors.notFound('Workspace has no GitHub installation'); + } + // Scope the token to a single repo. Prefer the verified numeric repo ID; fall + // back to the repository name for legacy projects created before github_repo_id + // was backfilled (PR #1236). Both paths scope to exactly one repository, so the + // personal-installation leak fix is preserved. + const repoShortName = + repositoryName && repositoryName.includes('/') + ? (repositoryName.split('/').pop() ?? null) + : repositoryName; + if (!githubRepoId && !repoShortName) { + throw errors.forbidden('GitHub repository is not verified for this workspace'); + } + + const installations = await db + .select({ + installationId: schema.githubInstallations.installationId, + externalInstallationId: schema.githubInstallations.externalInstallationId, + userId: schema.githubInstallations.userId, + }) + .from(schema.githubInstallations) + .where(eq(schema.githubInstallations.id, workspace.installationId)) + .limit(1); + + const installation = installations[0]; + if (!installation) { + log.warn('workspace_git_token_installation_owner_mismatch', { + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + installationRowId: workspace.installationId, + expectedUserId: workspace.userId, + action: 'rejected', + }); + throw errors.notFound('GitHub installation'); + } + if (installation.userId !== workspace.userId) { + log.info('workspace_git_token_project_installation_shared', { + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + installationRowId: workspace.installationId, + workspaceUserId: workspace.userId, + installationOwnerUserId: installation.userId, + action: 'allowed_after_user_access_verification', + }); + } + + if (!repositoryName) { + throw errors.forbidden('GitHub repository is not verified for this workspace'); + } + + const verifiedRepoId = await verifyWorkspaceGitHubOwnerAccess({ + env: c.env, + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + userId: workspace.userId, + repository: repositoryName, + externalInstallationId: getExternalInstallationId(installation), + githubRepoId, + }); + + // Lazy self-heal: legacy projects created before the numeric repo id was + // captured have github_repo_id = null. Fetch + persist it now, BEFORE policy + // resolution, so custom GitHub CLI policies (which require the numeric id) work + // and scoping uses the rename-stable repositoryIds path. On any failure we fall + // through to the name-based fallback below (no regression). + if (!githubRepoId && repositoryName && workspace.projectId) { + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); + const backfill = await backfillProjectGithubRepoId(db, c.env, { + projectId: workspace.projectId, + repository: repositoryName, + externalInstallationId: getExternalInstallationId(installation), + }); + if (backfill.githubRepoId) { + githubRepoId = backfill.githubRepoId; + } + } + githubRepoId ??= verifiedRepoId; + + let tokenOptions = null; + try { + tokenOptions = await resolveWorkspaceGitHubTokenOptions(db, { + workspaceId: workspace.workspaceId, + userId: workspace.userId, + githubRepoId, + }); + } catch (err) { + if (err instanceof GitHubCliPolicyError) { + throw errors.forbidden('GitHub CLI policy prevents token minting'); + } + throw err; + } + // Additional Repository Access: same-installation repos selected in Project + // Settings. Re-verified at this boundary; revoked/inaccessible entries are + // dropped from the scope. Primary repo is always included implicitly. + const additionalRepoIds = + githubRepoId && workspace.projectId + ? await resolveAdditionalRepositoryIds({ + env: c.env, + db, + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + userId: workspace.userId, + externalInstallationId: getExternalInstallationId(installation), + }) + : []; + + const scopedTokenOptions = { + ...(tokenOptions ?? {}), + ...(githubRepoId + ? { repositoryIds: [githubRepoId, ...additionalRepoIds.filter((id) => id !== githubRepoId)] } + : { repositories: [repoShortName as string] }), + }; + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); + const token = await getInstallationToken( + getExternalInstallationId(installation), + c.env, + scopedTokenOptions + ); + return callbackJsonWithJit(c, workspace, 'git_token', { + token: token.token, + expiresAt: token.expiresAt, + }); +}); + + +export { runtimeRoutes as gitTokenRoutes }; diff --git a/apps/api/src/routes/workspaces/runtime-message-helpers.ts b/apps/api/src/routes/workspaces/runtime-message-helpers.ts new file mode 100644 index 0000000000..ab15e2d7ad --- /dev/null +++ b/apps/api/src/routes/workspaces/runtime-message-helpers.ts @@ -0,0 +1,472 @@ + +import { eq } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/d1'; +import { type Context } from 'hono'; +import * as v from 'valibot'; + +import * as schema from '../../db/schema'; +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { parsePositiveInt } from '../../lib/route-helpers'; + + + +import { errors } from '../../middleware/error'; +import { formatIssues, MessageBatchSchema } from '../../schemas'; + + + + + + + + + +import { nodeStatusTerminatesCallbacks } from '../../services/node-callback-auth'; +import { persistError } from '../../services/observability'; + + + + + + + + + + +import { safeParseJson, type WorkspaceCallbackIdentitySnapshot } from './_helpers'; + + +type RuntimeContext = Context<{ Bindings: Env }>; +type MessageBatchBody = v.InferOutput; +export const DEFAULT_MAX_MESSAGES_PAYLOAD_BYTES = 256 * 1024; +export const DEFAULT_MESSAGE_SIZE_THRESHOLD_BYTES = 102400; +export const ACTIVE_MESSAGE_WORKSPACE_STATUSES = new Set(['creating', 'running', 'recovery']); +export const VALID_MESSAGE_ROLES = new Set(['user', 'assistant', 'system', 'tool', 'thinking', 'plan']); + +export type MessageWorkspace = WorkspaceCallbackIdentitySnapshot & { + projectId: string | null; + chatSessionId: string | null; +}; + +export type MessageBatchPersistenceRouteResult = { + persisted: number; + duplicates: number; + limitReached?: boolean; + maxMessages?: number; + remainingCapacity?: number; +}; + +export type MessageRouteContext = { + workspaceId: string; + projectId: string; + sessionId: string; + messageCount: number; +}; + +export function waitUntilIfAvailable( + c: { executionCtx: { waitUntil(promise: Promise): void } }, + promise: Promise | void +): void { + if (!promise) return; + try { + c.executionCtx.waitUntil(promise); + } catch (err) { + if (!(err instanceof Error) || !err.message.includes('no ExecutionContext')) { + throw err; + } + } +} + +export async function readRequestBodyWithLimit(request: Request, maxBytes: number): Promise { + const contentLengthHeader = request.headers.get('content-length'); + if (contentLengthHeader) { + const contentLength = Number.parseInt(contentLengthHeader, 10); + if (!Number.isFinite(contentLength) || contentLength < 0) { + throw errors.badRequest('Invalid Content-Length header'); + } + if (contentLength > maxBytes) { + throw errors.badRequest(`Payload exceeds ${maxBytes} byte limit`); + } + } + + if (!request.body) { + return ''; + } + + const reader = request.body.getReader(); + const chunks: Uint8Array[] = []; + let totalBytes = 0; + let done = false; + + try { + while (!done) { + const read = await reader.read(); + done = read.done; + if (done) continue; + const { value } = read; + totalBytes += value.byteLength; + if (totalBytes > maxBytes) { + await reader.cancel(); + throw errors.badRequest(`Payload exceeds ${maxBytes} byte limit`); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + + const body = new Uint8Array(totalBytes); + let offset = 0; + for (const chunk of chunks) { + body.set(chunk, offset); + offset += chunk.byteLength; + } + return new TextDecoder().decode(body); +} + +export async function parseMessageBatchRequest(c: RuntimeContext): Promise { + const maxPayloadBytes = parsePositiveInt( + c.env.MAX_MESSAGES_PAYLOAD_BYTES as string, + DEFAULT_MAX_MESSAGES_PAYLOAD_BYTES + ); + const rawBody = await readRequestBodyWithLimit(c.req.raw, maxPayloadBytes); + + let parsed: unknown; + try { + parsed = JSON.parse(rawBody); + } catch { + throw errors.badRequest('Invalid JSON in request body'); + } + + const result = v.safeParse(MessageBatchSchema, parsed); + if (!result.success) { + throw errors.badRequest(formatIssues(result.issues)); + } + return result.output; +} + +export function resolveMaxMessageBytes(env: Env): number { + return env.MESSAGE_SIZE_THRESHOLD + ? Number.parseInt(env.MESSAGE_SIZE_THRESHOLD, 10) + : DEFAULT_MESSAGE_SIZE_THRESHOLD_BYTES; +} + +export function validateMessageEntry( + msg: MessageBatchBody['messages'][number], + maxMessageBytes: number +): void { + if (!msg.messageId) { + throw errors.badRequest('Each message must have a messageId string'); + } + if (!msg.sessionId) { + throw errors.badRequest('Each message must have a sessionId string'); + } + if (!msg.role || !VALID_MESSAGE_ROLES.has(msg.role)) { + throw errors.badRequest( + `Invalid role "${msg.role}". Must be one of: user, assistant, system, tool, thinking, plan` + ); + } + if (!msg.content) { + throw errors.badRequest('Each message must have non-empty content'); + } + if (msg.content.length > maxMessageBytes) { + throw errors.badRequest(`Individual message content exceeds ${maxMessageBytes} byte limit`); + } + if (!msg.timestamp) { + throw errors.badRequest('Each message must have a timestamp string'); + } +} + +export function validateMessageBatch(env: Env, body: MessageBatchBody): string { + if (body.messages.length === 0) { + throw errors.badRequest('messages array must not be empty'); + } + const maxMessagesPerBatch = parsePositiveInt(env.MAX_MESSAGES_PER_BATCH, 100); + if (body.messages.length > maxMessagesPerBatch) { + throw errors.badRequest(`Maximum ${maxMessagesPerBatch} messages per batch`); + } + + const firstMessage = body.messages[0]; + if (!firstMessage) { + throw errors.badRequest('messages array must not be empty'); + } + const maxMessageBytes = resolveMaxMessageBytes(env); + const sessionId = firstMessage.sessionId; + for (const msg of body.messages) { + validateMessageEntry(msg, maxMessageBytes); + if (msg.sessionId !== sessionId) { + throw errors.badRequest('All messages in a batch must target the same sessionId'); + } + } + return sessionId; +} + +export async function loadMessageWorkspace( + env: Env, + workspaceId: string +): Promise { + const db = drizzle(env.DATABASE, { schema }); + const workspaceRows = await db + .select({ + workspaceId: schema.workspaces.id, + userId: schema.workspaces.userId, + projectId: schema.workspaces.projectId, + chatSessionId: schema.workspaces.chatSessionId, + status: schema.workspaces.status, + nodeId: schema.workspaces.nodeId, + nodeStatus: schema.nodes.status, + callbackGeneration: schema.workspaces.callbackGeneration, + }) + .from(schema.workspaces) + .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) + .where(eq(schema.workspaces.id, workspaceId)) + .limit(1); + return workspaceRows[0] ?? null; +} + +export function terminalMessagePersistenceResponse( + c: RuntimeContext, + context: Omit & { projectId: string | null }, + status: string, + reason: string +): Response { + const logContext = { + ...context, + status, + reason, + action: 'dropped_terminal_resource', + }; + log.info('message_persistence.inactive_workspace', logContext); + return c.body(null, 204); +} + +export function maybeTerminalMessageWorkspaceResponse( + c: RuntimeContext, + workspace: MessageWorkspace | null, + workspaceId: string, + sessionId: string, + messageCount: number +): Response | null { + const context = { + workspaceId, + projectId: workspace?.projectId ?? null, + sessionId, + messageCount, + }; + if (!workspace) { + return terminalMessagePersistenceResponse(c, context, 'missing', 'workspace_missing'); + } + if (!ACTIVE_MESSAGE_WORKSPACE_STATUSES.has(workspace.status)) { + return terminalMessagePersistenceResponse(c, context, workspace.status, 'workspace_inactive'); + } + if ( + !workspace.nodeId || + !workspace.nodeStatus || + nodeStatusTerminatesCallbacks(workspace.nodeStatus) + ) { + return terminalMessagePersistenceResponse( + c, + context, + workspace.nodeStatus ?? 'missing', + 'workspace_node_terminal' + ); + } + return null; +} + +export function rejectMessageSessionMismatch( + c: RuntimeContext, + context: MessageRouteContext, + expectedSessionId: string +): never { + const logContext = { + ...context, + expectedSessionId, + receivedSessionId: context.sessionId, + action: 'rejected_batch', + }; + log.error('message_routing.session_mismatch', logContext); + waitUntilIfAvailable( + c, + persistError( + c.env.OBSERVABILITY_DATABASE, + { + source: 'api', + level: 'error', + message: `Message routing mismatch: workspace ${context.workspaceId} linked to session ${expectedSessionId}, but messages target ${context.sessionId}`, + context: logContext, + workspaceId: context.workspaceId, + }, + c.env + ) + ); + throw errors.badRequest( + `Session mismatch: workspace is linked to session ${expectedSessionId}, ` + + `but messages target session ${context.sessionId}` + ); +} + +export function rejectWorkspaceWithoutChatSession(c: RuntimeContext, context: MessageRouteContext): never { + const logContext = { + ...context, + providedSessionId: context.sessionId, + action: 'rejected_no_session_link', + }; + log.warn('message_routing.no_chat_session_linked', logContext); + waitUntilIfAvailable( + c, + persistError( + c.env.OBSERVABILITY_DATABASE, + { + source: 'api', + level: 'warn', + message: `Rejecting messages for workspace ${context.workspaceId}: no chatSessionId linked yet`, + context: logContext, + workspaceId: context.workspaceId, + }, + c.env + ) + ); + throw errors.conflict( + 'Workspace has no linked chat session yet — messages cannot be routed safely' + ); +} + +export function assertMessageWorkspaceAcceptsBatch( + c: RuntimeContext, + workspace: MessageWorkspace | null, + workspaceId: string, + sessionId: string, + messageCount: number +): asserts workspace is MessageWorkspace & { projectId: string; chatSessionId: string } { + if (!workspace) { + throw errors.notFound('Workspace'); + } + if (!workspace.projectId) { + throw errors.badRequest('Workspace is not linked to a project'); + } + + const context: MessageRouteContext = { + workspaceId, + projectId: workspace.projectId, + sessionId, + messageCount, + }; + if (workspace.chatSessionId && workspace.chatSessionId !== sessionId) { + rejectMessageSessionMismatch(c, context, workspace.chatSessionId); + } + if (!workspace.chatSessionId) { + rejectWorkspaceWithoutChatSession(c, context); + } +} + +export function toProjectDataMessages(body: MessageBatchBody) { + return body.messages.map((m) => ({ + messageId: m.messageId, + role: m.role, + content: m.content, + toolMetadata: m.toolMetadata ? safeParseJson(m.toolMetadata) : null, + timestamp: m.timestamp, + sequence: m.sequence, + origin: m.origin ?? null, + })); +} + +export function sessionLimitReachedResponse(c: RuntimeContext, context: MessageRouteContext): Response { + log.error('message_persistence.session_message_limit_exceeded', { + ...context, + action: 'rejected_session_message_limit', + }); + waitUntilIfAvailable( + c, + persistError( + c.env.OBSERVABILITY_DATABASE, + { + source: 'api', + level: 'error', + message: `Session ${context.sessionId} has reached the message limit`, + context: { ...context, action: 'rejected_session_message_limit' }, + workspaceId: context.workspaceId, + }, + c.env + ) + ); + return c.json( + { + error: 'SESSION_MESSAGE_LIMIT_EXCEEDED', + message: 'Session message limit reached; no additional messages can be persisted', + }, + 409 + ); +} + +export function handleMessagePersistenceError( + c: RuntimeContext, + context: MessageRouteContext, + err: unknown +): Response { + const message = err instanceof Error ? err.message : 'Failed to persist messages'; + if (message.includes('SESSION_MESSAGE_LIMIT_EXCEEDED') || message.includes('message limit')) { + return sessionLimitReachedResponse(c, context); + } + if (message.includes('not found') || message.includes('is stopped')) { + log.info('message_persistence.dropped_terminal_do_response', { + ...context, + error: message, + action: 'dropped_terminal_resource', + }); + return c.body(null, 204); + } + log.error('message_persistence.do_error_transient', { + ...context, + error: message, + action: 'rejected_transient', + }); + return c.json( + { error: 'SERVICE_UNAVAILABLE', message: 'Message persistence temporarily unavailable' }, + 503 + ); +} + +export function partialSessionLimitResponse( + c: RuntimeContext, + context: MessageRouteContext, + result: MessageBatchPersistenceRouteResult +): Response { + const logContext = { + ...context, + persisted: result.persisted, + duplicates: result.duplicates, + maxMessages: result.maxMessages, + remainingCapacity: result.remainingCapacity, + action: 'partial_persist_session_message_limit', + }; + log.error('message_persistence.session_message_limit_reached', logContext); + waitUntilIfAvailable( + c, + persistError( + c.env.OBSERVABILITY_DATABASE, + { + source: 'api', + level: 'error', + message: `Session ${context.sessionId} reached the message limit while persisting a batch`, + context: logContext, + workspaceId: context.workspaceId, + }, + c.env + ) + ); + return c.json( + { + error: 'SESSION_MESSAGE_LIMIT_EXCEEDED', + message: 'Session message limit reached; only part of the batch was persisted', + persisted: result.persisted, + duplicates: result.duplicates, + maxMessages: result.maxMessages, + remainingCapacity: result.remainingCapacity, + }, + 409 + ); +} + diff --git a/apps/api/src/routes/workspaces/runtime-messages.ts b/apps/api/src/routes/workspaces/runtime-messages.ts new file mode 100644 index 0000000000..f73679bdaa --- /dev/null +++ b/apps/api/src/routes/workspaces/runtime-messages.ts @@ -0,0 +1,148 @@ +import { MESSAGE_OUTBOX_INCARNATION_HEADER } from '@simple-agent-manager/shared'; + + +import { type Context, Hono } from 'hono'; +import * as v from 'valibot'; + + +import type { Env } from '../../env'; + + + + + + + + + + + + + + + + + + + +import * as projectDataService from '../../services/project-data'; + + + + +import { signalWorkspaceDeletionUnconfirmedCallback } from '../../services/workspace-deletion-callback-signal'; + + + +import { sameWorkspaceCallbackIdentity, verifyWorkspaceCallbackAuth } from './_helpers'; + + +import { type MessageBatchPersistenceRouteResult, type MessageRouteContext, parseMessageBatchRequest, validateMessageBatch, loadMessageWorkspace, terminalMessagePersistenceResponse, maybeTerminalMessageWorkspaceResponse, assertMessageWorkspaceAcceptsBatch, toProjectDataMessages, handleMessagePersistenceError, partialSessionLimitResponse } from './runtime-message-helpers'; +const runtimeRoutes = new Hono<{ Bindings: Env }>(); +type RuntimeContext = Context<{ Bindings: Env }>; +runtimeRoutes.post('/:id/messages', async (c) => { + const workspaceId = c.req.param('id'); + await verifyWorkspaceCallbackAuth(c, workspaceId); + + // Authenticate and resolve terminal state before reading an untrusted body. + // Late deletion callbacks are discarded without parsing or persisting payloads. + const workspace = await loadMessageWorkspace(c.env, workspaceId); + const preflightTerminalResponse = maybeTerminalMessageWorkspaceResponse( + c, + workspace, + workspaceId, + '', + 0 + ); + if (preflightTerminalResponse) { + await signalWorkspaceDeletionUnconfirmedCallback(c.env, workspaceId, 'messages'); + return preflightTerminalResponse; + } + + const body = await parseMessageBatchRequest(c); + const sessionId = validateMessageBatch(c.env, body); + + // Rule 49: re-read immediately before crossing into ProjectData. Deletion or + // reassignment that wins while the body is read must suppress all persistence. + const currentWorkspace = await loadMessageWorkspace(c.env, workspaceId); + const terminalResponse = maybeTerminalMessageWorkspaceResponse( + c, + currentWorkspace, + workspaceId, + sessionId, + body.messages.length + ); + if (terminalResponse) { + return terminalResponse; + } + if ( + !currentWorkspace || + !workspace || + !sameWorkspaceCallbackIdentity(currentWorkspace, workspace) + ) { + return terminalMessagePersistenceResponse( + c, + { + workspaceId, + projectId: currentWorkspace?.projectId ?? null, + sessionId, + messageCount: body.messages.length, + }, + currentWorkspace?.status ?? 'missing', + 'workspace_incarnation_changed' + ); + } + assertMessageWorkspaceAcceptsBatch( + c, + currentWorkspace, + workspaceId, + sessionId, + body.messages.length + ); + + // Delegate to ProjectData DO with structured error handling. + // On failure, return appropriate status codes so the VM agent outbox + // can distinguish transient (retry) from permanent (discard) errors. + const context: MessageRouteContext = { + workspaceId, + projectId: currentWorkspace.projectId, + sessionId, + messageCount: body.messages.length, + }; + let result: MessageBatchPersistenceRouteResult; + const outboxIncarnation = c.req.header(MESSAGE_OUTBOX_INCARNATION_HEADER); + try { + result = await projectDataService.persistMessageBatch( + c.env, + currentWorkspace.projectId, + sessionId, + toProjectDataMessages(body), + { + workspaceId, + callbackGeneration: currentWorkspace.callbackGeneration ?? null, + // This is transport identity, not an auth claim. Missing/malformed IDs + // retain the legacy per-message path instead of guessing about replay. + outboxIncarnation: v.is(v.pipe(v.string(), v.uuid()), outboxIncarnation) + ? outboxIncarnation.toLowerCase() + : undefined, + } + ); + } catch (err) { + return handleMessagePersistenceError(c, context, err); + } + + if (result.limitReached) { + return partialSessionLimitResponse(c, context, result); + } + + return c.json({ + persisted: result.persisted, + duplicates: result.duplicates, + }); +}); + +// Legacy compatibility endpoint for node-side bootstrap exchange. +// This route requires BOTH user session auth AND callback token auth +// (it was not in the original auth skip list in workspaces.ts). + +export { runtimeRoutes as messageRoutes }; diff --git a/apps/api/src/routes/workspaces/runtime.ts b/apps/api/src/routes/workspaces/runtime.ts index 94a75baf57..44e39bb67c 100644 --- a/apps/api/src/routes/workspaces/runtime.ts +++ b/apps/api/src/routes/workspaces/runtime.ts @@ -1,1116 +1,52 @@ -// FILE SIZE EXCEPTION: Workspace runtime routes — splitting credential resolution logic across files increases fragmentation risk. See .claude/rules/18-file-size-limits.md -import { - AI_PROXY_DEFAULT_MODEL_KV_KEY, - type AIProxyConfig, - type BootstrapTokenData, - DEFAULT_AGENT_PERMISSION_MODE, - DEFAULT_AI_PROXY_ANTHROPIC_MODEL, - DEFAULT_AI_PROXY_MODEL, - DEFAULT_AI_PROXY_OPENAI_MODEL, - getAgentDefinition, - HARNESS_CAPABILITIES, - isValidAgentType, - MESSAGE_OUTBOX_INCARNATION_HEADER, - resolveHarnessDialect, -} from '@simple-agent-manager/shared'; +import { type BootstrapTokenData, DEFAULT_AGENT_PERMISSION_MODE } from '@simple-agent-manager/shared'; import { and, eq } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; import { type Context, Hono } from 'hono'; -import * as v from 'valibot'; + import * as schema from '../../db/schema'; import type { Env } from '../../env'; -import { log } from '../../lib/logger'; -import { parsePositiveInt } from '../../lib/route-helpers'; + + import { getCredentialEncryptionKey } from '../../lib/secrets'; import { ulid } from '../../lib/ulid'; import { requireApproved, requireAuth } from '../../middleware/auth'; -import { errors } from '../../middleware/error'; -import { - AgentTypeBodySchema, - BootLogEntrySchema, - formatIssues, - jsonValidator, - MessageBatchSchema, -} from '../../schemas'; + +import { AgentTypeBodySchema, BootLogEntrySchema, jsonValidator } from '../../schemas'; import { appendBootLog } from '../../services/boot-log'; import { registerBootstrapTokenConsume } from '../../services/bootstrap'; -import { resolveSessionProfileCredentialContext } from '../../services/composable-credentials/profile-context'; -import { getInstallationToken, getUserInstallationRepositories } from '../../services/github-app'; -import { - GitHubCliPolicyError, - resolveWorkspaceGitHubTokenOptions, -} from '../../services/github-cli-policy'; -import { getExternalInstallationId } from '../../services/github-installation-ids'; -import { backfillProjectGithubRepoId } from '../../services/github-repo-id-backfill'; -import { getGitHubUserAccessTokenForOwner } from '../../services/github-user-access-token'; -import { - getProjectGitLabRepository, - requireGitLabUserAccessTokenResultForOwner, - verifyGitLabProjectAccess, -} from '../../services/gitlab'; -import { nodeStatusTerminatesCallbacks } from '../../services/node-callback-auth'; -import { persistError } from '../../services/observability'; -import { resolveProjectAgentDefault } from '../../services/project-agent-defaults'; -import * as projectDataService from '../../services/project-data'; -import { extractScalewaySecretKey } from '../../services/provider-credentials'; -import { assertProviderLimitCredentialPin } from '../../services/provider-limit-credential-pin'; -import { refuseHaltedRunAccount } from '../../services/run-agent-configuration'; -import { - isAiProxyEnabled, - PROXY_ELIGIBLE_AGENTS, - requiresExplicitSamProvider, -} from '../../services/sam-ai-proxy-fallback'; -import { - signalWorkspaceDeletionUnconfirmedCallback, - type WorkspaceDeletionCallbackKind, -} from '../../services/workspace-deletion-callback-signal'; -import { getWorkspaceRuntimeAssets } from '../../services/workspace-runtime-assets'; -import { getDecryptedAgentKey, getDecryptedCredentialRecord } from '../credentials'; -import { assertRepositoryAccess } from '../projects/_helpers'; -import { - assertWorkspaceAcceptsCallback, - assertWorkspaceCallbackIdentityCurrent, - assertWorkspaceCallbackResourceById, - safeParseJson, - sameWorkspaceCallbackIdentity, - verifyWorkspaceCallbackAuth, - type WorkspaceCallbackIdentitySnapshot, -} from './_helpers'; -import { - agentCredentialProviderFallback, - credentialAttributionFromData, - persistAgentCredentialAttribution, - platformProxyAttribution, -} from './agent-credential-attribution'; - -function getProxyCapability(agentType: string) { - const capability = HARNESS_CAPABILITIES.find((entry) => entry.agentType === agentType); - if (!capability?.proxyRouteSegment || !capability.proxyProviderTag) return null; - return capability; -} - -function buildPassthroughInferenceConfig(input: { - agentType: string; - baseDomain: string; - defaultModel: string; -}) { - const capability = getProxyCapability(input.agentType); - if (!capability) return null; - return { - provider: capability.proxyProviderTag, - baseURL: `https://api.${input.baseDomain}/ai/proxy/{wstoken}/${capability.proxyRouteSegment}`, - model: input.defaultModel, - apiKeySource: 'callback-token' as const, - }; -} - -function buildPlatformInferenceConfig(input: { - agentType: string; - baseDomain: string; - defaultModel: string; -}) { - const capability = getProxyCapability(input.agentType); - if (!capability) return null; - const provider = - capability.proxyProviderTag === 'anthropic-passthrough' - ? 'anthropic-proxy' - : capability.usesOpencodeConfig - ? 'openai-compatible' - : 'openai-proxy'; - const routeSegment = capability.proxyRouteSegment === 'anthropic' ? 'anthropic' : 'v1'; - return { - provider, - baseURL: `https://api.${input.baseDomain}/ai/${routeSegment}`, - model: input.defaultModel, - apiKeySource: 'callback-token' as const, - }; -} - -const runtimeRoutes = new Hono<{ Bindings: Env }>(); -type RuntimeContext = Context<{ Bindings: Env }>; -type MessageBatchBody = v.InferOutput; - -async function callbackJsonWithJit>( - c: RuntimeContext, - expected: WorkspaceCallbackIdentitySnapshot, - callback: WorkspaceDeletionCallbackKind, - body: T -) { - await assertWorkspaceCallbackIdentityCurrent(c.env, expected, callback); - if ( - callback === 'agent_key' && - body.credentialSource !== 'platform' && - typeof body.credentialReference === 'string' - ) - await assertProviderLimitCredentialPin( - c.env, - expected.workspaceId, - body.credentialReference, - expected - ); - return c.json(body); -} - -const DEFAULT_MAX_MESSAGES_PAYLOAD_BYTES = 256 * 1024; -const DEFAULT_MESSAGE_SIZE_THRESHOLD_BYTES = 102400; -const ACTIVE_MESSAGE_WORKSPACE_STATUSES = new Set(['creating', 'running', 'recovery']); -const VALID_MESSAGE_ROLES = new Set(['user', 'assistant', 'system', 'tool', 'thinking', 'plan']); - -type MessageWorkspace = WorkspaceCallbackIdentitySnapshot & { - projectId: string | null; - chatSessionId: string | null; -}; - -type MessageBatchPersistenceRouteResult = { - persisted: number; - duplicates: number; - limitReached?: boolean; - maxMessages?: number; - remainingCapacity?: number; -}; - -type MessageRouteContext = { - workspaceId: string; - projectId: string; - sessionId: string; - messageCount: number; -}; - -function waitUntilIfAvailable( - c: { executionCtx: { waitUntil(promise: Promise): void } }, - promise: Promise | void -): void { - if (!promise) return; - try { - c.executionCtx.waitUntil(promise); - } catch (err) { - if (!(err instanceof Error) || !err.message.includes('no ExecutionContext')) { - throw err; - } - } -} - -async function readRequestBodyWithLimit(request: Request, maxBytes: number): Promise { - const contentLengthHeader = request.headers.get('content-length'); - if (contentLengthHeader) { - const contentLength = Number.parseInt(contentLengthHeader, 10); - if (!Number.isFinite(contentLength) || contentLength < 0) { - throw errors.badRequest('Invalid Content-Length header'); - } - if (contentLength > maxBytes) { - throw errors.badRequest(`Payload exceeds ${maxBytes} byte limit`); - } - } - - if (!request.body) { - return ''; - } - - const reader = request.body.getReader(); - const chunks: Uint8Array[] = []; - let totalBytes = 0; - let done = false; - - try { - while (!done) { - const read = await reader.read(); - done = read.done; - if (done) continue; - const { value } = read; - totalBytes += value.byteLength; - if (totalBytes > maxBytes) { - await reader.cancel(); - throw errors.badRequest(`Payload exceeds ${maxBytes} byte limit`); - } - chunks.push(value); - } - } finally { - reader.releaseLock(); - } - - const body = new Uint8Array(totalBytes); - let offset = 0; - for (const chunk of chunks) { - body.set(chunk, offset); - offset += chunk.byteLength; - } - return new TextDecoder().decode(body); -} - -async function parseMessageBatchRequest(c: RuntimeContext): Promise { - const maxPayloadBytes = parsePositiveInt( - c.env.MAX_MESSAGES_PAYLOAD_BYTES as string, - DEFAULT_MAX_MESSAGES_PAYLOAD_BYTES - ); - const rawBody = await readRequestBodyWithLimit(c.req.raw, maxPayloadBytes); - - let parsed: unknown; - try { - parsed = JSON.parse(rawBody); - } catch { - throw errors.badRequest('Invalid JSON in request body'); - } - const result = v.safeParse(MessageBatchSchema, parsed); - if (!result.success) { - throw errors.badRequest(formatIssues(result.issues)); - } - return result.output; -} -export function resolveMaxMessageBytes(env: Env): number { - return env.MESSAGE_SIZE_THRESHOLD - ? Number.parseInt(env.MESSAGE_SIZE_THRESHOLD, 10) - : DEFAULT_MESSAGE_SIZE_THRESHOLD_BYTES; -} -function validateMessageEntry( - msg: MessageBatchBody['messages'][number], - maxMessageBytes: number -): void { - if (!msg.messageId) { - throw errors.badRequest('Each message must have a messageId string'); - } - if (!msg.sessionId) { - throw errors.badRequest('Each message must have a sessionId string'); - } - if (!msg.role || !VALID_MESSAGE_ROLES.has(msg.role)) { - throw errors.badRequest( - `Invalid role "${msg.role}". Must be one of: user, assistant, system, tool, thinking, plan` - ); - } - if (!msg.content) { - throw errors.badRequest('Each message must have non-empty content'); - } - if (msg.content.length > maxMessageBytes) { - throw errors.badRequest(`Individual message content exceeds ${maxMessageBytes} byte limit`); - } - if (!msg.timestamp) { - throw errors.badRequest('Each message must have a timestamp string'); - } -} -function validateMessageBatch(env: Env, body: MessageBatchBody): string { - if (body.messages.length === 0) { - throw errors.badRequest('messages array must not be empty'); - } - const maxMessagesPerBatch = parsePositiveInt(env.MAX_MESSAGES_PER_BATCH, 100); - if (body.messages.length > maxMessagesPerBatch) { - throw errors.badRequest(`Maximum ${maxMessagesPerBatch} messages per batch`); - } - const firstMessage = body.messages[0]; - if (!firstMessage) { - throw errors.badRequest('messages array must not be empty'); - } - const maxMessageBytes = resolveMaxMessageBytes(env); - const sessionId = firstMessage.sessionId; - for (const msg of body.messages) { - validateMessageEntry(msg, maxMessageBytes); - if (msg.sessionId !== sessionId) { - throw errors.badRequest('All messages in a batch must target the same sessionId'); - } - } - return sessionId; -} -async function loadMessageWorkspace( - env: Env, - workspaceId: string -): Promise { - const db = drizzle(env.DATABASE, { schema }); - const workspaceRows = await db - .select({ - workspaceId: schema.workspaces.id, - userId: schema.workspaces.userId, - projectId: schema.workspaces.projectId, - chatSessionId: schema.workspaces.chatSessionId, - status: schema.workspaces.status, - nodeId: schema.workspaces.nodeId, - nodeStatus: schema.nodes.status, - callbackGeneration: schema.workspaces.callbackGeneration, - }) - .from(schema.workspaces) - .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) - .where(eq(schema.workspaces.id, workspaceId)) - .limit(1); - return workspaceRows[0] ?? null; -} -function terminalMessagePersistenceResponse( - c: RuntimeContext, - context: Omit & { projectId: string | null }, - status: string, - reason: string -): Response { - const logContext = { - ...context, - status, - reason, - action: 'dropped_terminal_resource', - }; - log.info('message_persistence.inactive_workspace', logContext); - return c.body(null, 204); -} -function maybeTerminalMessageWorkspaceResponse( - c: RuntimeContext, - workspace: MessageWorkspace | null, - workspaceId: string, - sessionId: string, - messageCount: number -): Response | null { - const context = { - workspaceId, - projectId: workspace?.projectId ?? null, - sessionId, - messageCount, - }; - if (!workspace) { - return terminalMessagePersistenceResponse(c, context, 'missing', 'workspace_missing'); - } - if (!ACTIVE_MESSAGE_WORKSPACE_STATUSES.has(workspace.status)) { - return terminalMessagePersistenceResponse(c, context, workspace.status, 'workspace_inactive'); - } - if ( - !workspace.nodeId || - !workspace.nodeStatus || - nodeStatusTerminatesCallbacks(workspace.nodeStatus) - ) { - return terminalMessagePersistenceResponse( - c, - context, - workspace.nodeStatus ?? 'missing', - 'workspace_node_terminal' - ); - } - return null; -} -function rejectMessageSessionMismatch( - c: RuntimeContext, - context: MessageRouteContext, - expectedSessionId: string -): never { - const logContext = { - ...context, - expectedSessionId, - receivedSessionId: context.sessionId, - action: 'rejected_batch', - }; - log.error('message_routing.session_mismatch', logContext); - waitUntilIfAvailable( - c, - persistError( - c.env.OBSERVABILITY_DATABASE, - { - source: 'api', - level: 'error', - message: `Message routing mismatch: workspace ${context.workspaceId} linked to session ${expectedSessionId}, but messages target ${context.sessionId}`, - context: logContext, - workspaceId: context.workspaceId, - }, - c.env - ) - ); - throw errors.badRequest( - `Session mismatch: workspace is linked to session ${expectedSessionId}, ` + - `but messages target session ${context.sessionId}` - ); -} - -function rejectWorkspaceWithoutChatSession(c: RuntimeContext, context: MessageRouteContext): never { - const logContext = { - ...context, - providedSessionId: context.sessionId, - action: 'rejected_no_session_link', - }; - log.warn('message_routing.no_chat_session_linked', logContext); - waitUntilIfAvailable( - c, - persistError( - c.env.OBSERVABILITY_DATABASE, - { - source: 'api', - level: 'warn', - message: `Rejecting messages for workspace ${context.workspaceId}: no chatSessionId linked yet`, - context: logContext, - workspaceId: context.workspaceId, - }, - c.env - ) - ); - throw errors.conflict( - 'Workspace has no linked chat session yet — messages cannot be routed safely' - ); -} - -function assertMessageWorkspaceAcceptsBatch( - c: RuntimeContext, - workspace: MessageWorkspace | null, - workspaceId: string, - sessionId: string, - messageCount: number -): asserts workspace is MessageWorkspace & { projectId: string; chatSessionId: string } { - if (!workspace) { - throw errors.notFound('Workspace'); - } - if (!workspace.projectId) { - throw errors.badRequest('Workspace is not linked to a project'); - } - - const context: MessageRouteContext = { - workspaceId, - projectId: workspace.projectId, - sessionId, - messageCount, - }; - if (workspace.chatSessionId && workspace.chatSessionId !== sessionId) { - rejectMessageSessionMismatch(c, context, workspace.chatSessionId); - } - if (!workspace.chatSessionId) { - rejectWorkspaceWithoutChatSession(c, context); - } -} - -function toProjectDataMessages(body: MessageBatchBody) { - return body.messages.map((m) => ({ - messageId: m.messageId, - role: m.role, - content: m.content, - toolMetadata: m.toolMetadata ? safeParseJson(m.toolMetadata) : null, - timestamp: m.timestamp, - sequence: m.sequence, - origin: m.origin ?? null, - })); -} - -function sessionLimitReachedResponse(c: RuntimeContext, context: MessageRouteContext): Response { - log.error('message_persistence.session_message_limit_exceeded', { - ...context, - action: 'rejected_session_message_limit', - }); - waitUntilIfAvailable( - c, - persistError( - c.env.OBSERVABILITY_DATABASE, - { - source: 'api', - level: 'error', - message: `Session ${context.sessionId} has reached the message limit`, - context: { ...context, action: 'rejected_session_message_limit' }, - workspaceId: context.workspaceId, - }, - c.env - ) - ); - return c.json( - { - error: 'SESSION_MESSAGE_LIMIT_EXCEEDED', - message: 'Session message limit reached; no additional messages can be persisted', - }, - 409 - ); -} - -function handleMessagePersistenceError( - c: RuntimeContext, - context: MessageRouteContext, - err: unknown -): Response { - const message = err instanceof Error ? err.message : 'Failed to persist messages'; - if (message.includes('SESSION_MESSAGE_LIMIT_EXCEEDED') || message.includes('message limit')) { - return sessionLimitReachedResponse(c, context); - } - if (message.includes('not found') || message.includes('is stopped')) { - log.info('message_persistence.dropped_terminal_do_response', { - ...context, - error: message, - action: 'dropped_terminal_resource', - }); - return c.body(null, 204); - } - log.error('message_persistence.do_error_transient', { - ...context, - error: message, - action: 'rejected_transient', - }); - return c.json( - { error: 'SERVICE_UNAVAILABLE', message: 'Message persistence temporarily unavailable' }, - 503 - ); -} - -function partialSessionLimitResponse( - c: RuntimeContext, - context: MessageRouteContext, - result: MessageBatchPersistenceRouteResult -): Response { - const logContext = { - ...context, - persisted: result.persisted, - duplicates: result.duplicates, - maxMessages: result.maxMessages, - remainingCapacity: result.remainingCapacity, - action: 'partial_persist_session_message_limit', - }; - log.error('message_persistence.session_message_limit_reached', logContext); - waitUntilIfAvailable( - c, - persistError( - c.env.OBSERVABILITY_DATABASE, - { - source: 'api', - level: 'error', - message: `Session ${context.sessionId} reached the message limit while persisting a batch`, - context: logContext, - workspaceId: context.workspaceId, - }, - c.env - ) - ); - return c.json( - { - error: 'SESSION_MESSAGE_LIMIT_EXCEEDED', - message: 'Session message limit reached; only part of the batch was persisted', - persisted: result.persisted, - duplicates: result.duplicates, - maxMessages: result.maxMessages, - remainingCapacity: result.remainingCapacity, - }, - 409 - ); -} - -async function verifyWorkspaceGitHubOwnerAccess(input: { - env: Env; - workspaceId: string; - projectId: string | null; - userId: string; - repository: string; - externalInstallationId: string; - githubRepoId: number | null; -}): Promise { - const accessToken = await getGitHubUserAccessTokenForOwner( - input.env, - input.userId, - 'workspace-git-token' - ); - if (!accessToken) { - log.warn('workspace_git_token_user_access_missing', { - workspaceId: input.workspaceId, - projectId: input.projectId, - userId: input.userId, - action: 'rejected', - }); - throw errors.forbidden('GitHub user token unavailable'); - } - - // Every git and gh credential exchange lands here, so pass env to use the - // pagination hint (GITHUB_REPO_ACCESS_CACHE_TTL_SECONDS). Every exchange - // still verifies current user access against GitHub; hints never grant access. - const verifiedRepo = await assertRepositoryAccess( - accessToken, - input.externalInstallationId, - input.repository, - input.userId, - 'project-access', - input.env - ); - - if (input.githubRepoId !== null && verifiedRepo.id !== input.githubRepoId) { - log.warn('workspace_git_token_repo_id_drift', { - workspaceId: input.workspaceId, - projectId: input.projectId, - userId: input.userId, - expectedRepoId: input.githubRepoId, - verifiedRepoId: verifiedRepo.id, - action: 'rejected', - }); - throw errors.forbidden('GitHub repository access has changed; repository ID no longer matches'); - } - - return verifiedRepo.id; -} - -/** - * Resolve numeric repository IDs for a project's additional Repository Access - * entries, re-verifying user∩app access at the token-mint boundary. Stored rows - * whose access has been revoked (or whose installation no longer exposes them) - * are dropped from the scope — an unselected/inaccessible repo simply never makes - * it into the minted token's `repository_ids`, so it fails clearly downstream. - * Failure to fetch the accessible set returns the empty set rather than throwing, - * so the primary-repo token still mints (additional repos degrade, never break - * the primary clone). - */ -async function resolveAdditionalRepositoryIds(input: { - env: Env; - db: ReturnType>; - workspaceId: string; - projectId: string; - userId: string; - externalInstallationId: string; -}): Promise { - const rows = await input.db - .select({ - repository: schema.projectGithubRepositories.repository, - githubRepoId: schema.projectGithubRepositories.githubRepoId, - }) - .from(schema.projectGithubRepositories) - .where(eq(schema.projectGithubRepositories.projectId, input.projectId)); - if (rows.length === 0) { - return []; - } - - const accessToken = await getGitHubUserAccessTokenForOwner( - input.env, - input.userId, - 'workspace-git-token' - ); - if (!accessToken) { - log.warn('workspace_git_token_additional_repos_user_access_missing', { - workspaceId: input.workspaceId, - projectId: input.projectId, - userId: input.userId, - action: 'additional_repos_skipped', - }); - return []; - } - - let accessibleById = new Map(); - try { - const repositories = await getUserInstallationRepositories( - accessToken, - input.externalInstallationId, - { - flow: 'project-access', - userId: input.userId, - installationId: input.externalInstallationId, - } - ); - accessibleById = new Map(repositories.map((r) => [r.fullName.toLowerCase(), r.id])); - } catch (err) { - log.warn('workspace_git_token_additional_repos_unavailable', { - workspaceId: input.workspaceId, - projectId: input.projectId, - userId: input.userId, - error: err instanceof Error ? err.message : String(err), - action: 'additional_repos_skipped', - }); - return []; - } - - const ids: number[] = []; - for (const row of rows) { - const accessibleId = accessibleById.get(row.repository.toLowerCase()); - if (accessibleId === undefined) { - log.warn('workspace_git_token_additional_repo_access_revoked', { - workspaceId: input.workspaceId, - projectId: input.projectId, - userId: input.userId, - repository: row.repository, - action: 'excluded_from_scope', - }); - continue; - } - // Prefer the live, rename-stable id from the accessible set. Stored ids can - // drift if the repo was deleted/recreated; the live id is authoritative. - ids.push(accessibleId); - } - return ids; -} - -runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async (c) => { - const workspaceId = c.req.param('id'); - await verifyWorkspaceCallbackAuth(c, workspaceId); - const body = c.req.valid('json'); - - const db = drizzle(c.env.DATABASE, { schema }); - - const workspace = await assertWorkspaceCallbackResourceById(c.env, workspaceId, 'agent_key'); - - // OpenCode always uses a user-supplied credential (zen/go/custom). It never - // routes through the SAM platform proxy, so it always requires a dedicated key. - const opencodeRequiresDedicatedCredential = body.agentType === 'opencode'; - - const encryptionKey = getCredentialEncryptionKey(c.env); - // The session's profile decides whether a personal profile pin applies; the AI - // proxy and provider-limit admission resolve the same context. - const profile = await resolveSessionProfileCredentialContext(db, { - workspaceId, - agentSessionId: body.agentSessionId, - }); - let credentialData = await getDecryptedAgentKey( - db, - workspace.userId, - body.agentType, - encryptionKey, - workspace.projectId, - profile - ); - let credentialProviderMode = 'direct'; - - // An account chosen for this run that can no longer be used (paused, removed) must stop - // the run here. Without this, "no credential" would continue to the platform proxy or a - // fallback below and run the chat on an account nobody chose for it. - if (!credentialData && profile?.runConfigurationId) { - await refuseHaltedRunAccount(db, { - workspaceId, - userId: workspace.userId, - projectId: workspace.projectId, - agentType: body.agentType, - encryptionKey, - profile, - }); - } - - // SECURITY: Never return raw platform-managed credentials to tenant workspaces. - // Platform credentials are control-plane secrets and must only be used via - // SAM-mediated proxy flows (callback-token auth), not injected into tenant - // containers as env vars or auth files. - if (credentialData?.credentialSource === 'platform') { - credentialData = null; - } - - // Cloud provider credential fallback: if no dedicated agent key, check if the agent - // definition specifies a cloud provider whose credential can be used instead. - const agentDef = isValidAgentType(body.agentType) - ? getAgentDefinition(body.agentType) - : undefined; - const fallbackCloudProvider = agentDef?.fallbackCloudProvider; - if (!credentialData && fallbackCloudProvider) { - const fallbackCredential = await getDecryptedCredentialRecord( - db, - workspace.userId, - fallbackCloudProvider, - encryptionKey - ); - if (fallbackCredential) { - const secretKey = extractScalewaySecretKey(fallbackCredential.credential); - if (secretKey) { - credentialData = { - credential: secretKey, - credentialKind: 'api-key', - credentialSource: 'user', - credentialScope: 'user', - credentialReference: fallbackCredential.credentialReference, - credentialProvider: fallbackCredential.credentialProvider, - }; - credentialProviderMode = 'fallback-cloud-provider'; - } else { - log.warn('agent_key.scaleway_credential_missing_secret_key', { - workspaceId, - userId: workspace.userId, - agentType: body.agentType, - }); - } - } - } - - if (credentialData && opencodeRequiresDedicatedCredential) { - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - credentialProviderMode - ), - }); - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: credentialData.credential, - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), - providerMode: credentialProviderMode, - credentialGeneration: persistedAttribution?.credentialGeneration, - }); - } - - if (!credentialData && opencodeRequiresDedicatedCredential) { - log.info('agent_key.opencode_byo_provider_missing_credential', { - workspaceId, - userId: workspace.userId, - agentType: body.agentType, - }); - throw errors.notFound('Agent credential'); - } - - // AI proxy: when enabled and agent is eligible, return proxy config when the - // credential can be forwarded to the upstream provider. - // Two modes: - // - Claude/Codex with no user credential + providerMode='sam' → platform proxy (callback-token auth) - // - User has upstream-compatible credential → passthrough proxy (user credential - // forwarded via auth headers, wstoken in URL path for analytics/rate-limiting) - // Note: platform proxy fallback requires explicit provider selection. - // Without it, users with no credential get a 404 (agent not configured). - if (PROXY_ELIGIBLE_AGENTS.has(body.agentType) && isAiProxyEnabled(c.env)) { - const baseDomain = c.env.BASE_DOMAIN; - const isClaudeCode = body.agentType === 'claude-code'; - const isCodex = body.agentType === 'openai-codex'; - let explicitProviderMode: string | null | undefined; - const getExplicitProviderMode = async (): Promise => { - if (explicitProviderMode !== undefined) return explicitProviderMode; - const settingsRows = await db - .select({ providerMode: schema.agentSettings.providerMode }) - .from(schema.agentSettings) - .where( - and( - eq(schema.agentSettings.userId, workspace.userId), - eq(schema.agentSettings.agentType, body.agentType) - ) - ) - .limit(1); - explicitProviderMode = settingsRows[0]?.providerMode ?? null; - return explicitProviderMode; - }; - - // Resolve default model: KV (admin-set) > env var > shared constant - let defaultModel: string; - if (isClaudeCode) { - defaultModel = c.env.AI_PROXY_DEFAULT_ANTHROPIC_MODEL ?? DEFAULT_AI_PROXY_ANTHROPIC_MODEL; - } else if (isCodex) { - defaultModel = c.env.AI_PROXY_DEFAULT_OPENAI_MODEL ?? DEFAULT_AI_PROXY_OPENAI_MODEL; - } else { - defaultModel = c.env.AI_PROXY_DEFAULT_MODEL ?? DEFAULT_AI_PROXY_MODEL; - try { - const kvConfig = await c.env.KV.get(AI_PROXY_DEFAULT_MODEL_KV_KEY); - if (kvConfig) { - const parsed: AIProxyConfig = JSON.parse(kvConfig); - if (parsed.defaultModel) defaultModel = parsed.defaultModel; - } - } catch { - /* KV unavailable or corrupt data — use env/default */ - } - } - - // Claude Code/Codex explicit SAM mode must route through the SAM proxy, - // not through legacy platform agent credentials as user-style passthrough. - if ((isClaudeCode || isCodex) && credentialData?.credentialSource === 'platform') { - credentialData = null; - } - - if ( - credentialData && - credentialData.baseUrl && - credentialData.providerDialect && - resolveHarnessDialect(body.agentType, credentialData.providerDialect) && - !((isClaudeCode || isCodex) && credentialData.credentialKind === 'oauth-token') - ) { - // User has their own credential — use passthrough proxy routes. - // URL-path auth: wstoken embedded in URL, user credential in auth headers. - const inferenceConfig = buildPassthroughInferenceConfig({ - agentType: body.agentType, - baseDomain, - defaultModel, - }); - if (!inferenceConfig) { - throw errors.notFound('Agent credential'); - } - - log.info('agent_key.ai_proxy_passthrough', { - workspaceId, - userId: workspace.userId, - proxyBaseUrl: inferenceConfig.baseURL, - agentType: body.agentType, - }); - - // Track credential source on associated task - const taskRows = await db - .select({ id: schema.tasks.id }) - .from(schema.tasks) - .where(eq(schema.tasks.workspaceId, workspaceId)) - .limit(1); - const task = taskRows[0]; - if (task) { - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); - await db - .update(schema.tasks) - .set({ agentCredentialSource: credentialData.credentialSource }) - .where(eq(schema.tasks.id, task.id)); - } - - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - 'proxy-passthrough' - ), - }); - - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: '__sam_proxy__', - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? - credentialData.providerDialect ?? - agentCredentialProviderFallback(body.agentType), - providerMode: 'proxy-passthrough', - credentialGeneration: persistedAttribution?.credentialGeneration, - inferenceConfig, - }); - } - - if (credentialData?.baseUrl) { - log.warn('agent_key.ai_proxy_incompatible_passthrough_credential', { - workspaceId, - userId: workspace.userId, - agentType: body.agentType, - providerDialect: credentialData.providerDialect ?? null, - }); - throw errors.notFound('Agent credential'); - } - - if (credentialData) { - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - credentialProviderMode - ), - }); - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: credentialData.credential, - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), - providerMode: credentialProviderMode, - credentialGeneration: persistedAttribution?.credentialGeneration, - }); - } +import { resolveProjectAgentDefault } from '../../services/project-agent-defaults'; - // Claude Code and Codex require an explicit SAM provider selection before - // using platform proxy. OpenCode never reaches this block — it always - // requires a dedicated user credential and returns/throws above. - if (requiresExplicitSamProvider(body.agentType)) { - const providerMode = await getExplicitProviderMode(); - if (providerMode !== 'sam') { - log.info('agent_key.no_credential_no_sam_provider', { - workspaceId, - userId: workspace.userId, - agentType: body.agentType, - providerMode, - }); - throw errors.notFound('Agent credential'); - } - } - // Activate platform proxy. - // Auth via callback token in headers. - const inferenceConfig = buildPlatformInferenceConfig({ - agentType: body.agentType, - baseDomain, - defaultModel, - }); - if (!inferenceConfig) { - throw errors.notFound('Agent credential'); - } - log.info('agent_key.ai_proxy_sam_provider', { - workspaceId, - userId: workspace.userId, - proxyBaseUrl: inferenceConfig.baseURL, - agentType: body.agentType, - }); - // Track credential source on associated task - const taskRows = await db - .select({ id: schema.tasks.id }) - .from(schema.tasks) - .where(eq(schema.tasks.workspaceId, workspaceId)) - .limit(1); - const task = taskRows[0]; - if (task) { - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); - await db - .update(schema.tasks) - .set({ agentCredentialSource: 'platform' }) - .where(eq(schema.tasks.id, task.id)); - } - const platformAttribution = platformProxyAttribution(body.agentType); - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: platformAttribution, - }); - - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: '__platform_proxy__', - credentialKind: 'api-key' as const, - credentialSource: 'platform' as const, - credentialReference: platformAttribution.credentialReference, - credentialProvider: platformAttribution.credentialProvider, - providerMode: platformAttribution.providerMode, - credentialGeneration: persistedAttribution?.credentialGeneration, - inferenceConfig, - }); - } - - if (!credentialData) { - throw errors.notFound('Agent credential'); - } +import { getWorkspaceRuntimeAssets } from '../../services/workspace-runtime-assets'; - // Track credential source on associated task if applicable - if (credentialData.credentialSource === 'platform') { - const taskRows = await db - .select({ id: schema.tasks.id }) - .from(schema.tasks) - .where(eq(schema.tasks.workspaceId, workspaceId)) - .limit(1); - const task = taskRows[0]; - if (task) { - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); - await db - .update(schema.tasks) - .set({ agentCredentialSource: 'platform' }) - .where(eq(schema.tasks.id, task.id)); - } - } - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - credentialProviderMode - ), - }); +import { assertWorkspaceAcceptsCallback, assertWorkspaceCallbackIdentityCurrent, assertWorkspaceCallbackResourceById, verifyWorkspaceCallbackAuth } from './_helpers'; - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: credentialData.credential, - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), - providerMode: credentialProviderMode, - credentialGeneration: persistedAttribution?.credentialGeneration, - }); -}); -/** - * POST /:id/agent-settings — VM agent callback to fetch user's agent settings. - * Uses workspace callback auth (same as agent-key). - */ +import { callbackJsonWithJit } from './runtime-callback-response'; +import { agentKeyRoutes } from './runtime-agent-key'; +import { gitTokenRoutes } from './runtime-git-token'; +import { messageRoutes } from './runtime-messages'; +export { resolveMaxMessageBytes } from './runtime-message-helpers'; +const runtimeRoutes = new Hono<{ Bindings: Env }>(); +type RuntimeContext = Context<{ Bindings: Env }>; +runtimeRoutes.route('/', agentKeyRoutes); +runtimeRoutes.route('/', gitTokenRoutes); +runtimeRoutes.route('/', messageRoutes); runtimeRoutes.post('/:id/agent-settings', jsonValidator(AgentTypeBodySchema), async (c) => { const workspaceId = c.req.param('id'); await verifyWorkspaceCallbackAuth(c, workspaceId); @@ -1216,296 +152,6 @@ runtimeRoutes.get('/:id/runtime-assets', async (c) => { return c.json(assets); }); -runtimeRoutes.post('/:id/git-token', async (c) => { - const workspaceId = c.req.param('id'); - await verifyWorkspaceCallbackAuth(c, workspaceId); - - const db = drizzle(c.env.DATABASE, { schema }); - - // Look up workspace → project to determine repo provider - const workspaceRows = await db - .select({ - workspaceId: schema.workspaces.id, - installationId: schema.workspaces.installationId, - projectId: schema.workspaces.projectId, - chatSessionId: schema.workspaces.chatSessionId, - userId: schema.workspaces.userId, - status: schema.workspaces.status, - nodeId: schema.workspaces.nodeId, - nodeStatus: schema.nodes.status, - callbackGeneration: schema.workspaces.callbackGeneration, - }) - .from(schema.workspaces) - .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) - .where(eq(schema.workspaces.id, workspaceId)) - .limit(1); - - const workspace = await assertWorkspaceAcceptsCallback( - c.env, - workspaceRows[0], - workspaceId, - 'git_token' - ); - - // Look up the project to check repoProvider - let repoProvider = 'github'; - let artifactsRepoId: string | null = null; - let githubRepoId: number | null = null; - let repositoryName: string | null = null; - if (workspace.projectId) { - const projectRows = await db - .select({ - repoProvider: schema.projects.repoProvider, - artifactsRepoId: schema.projects.artifactsRepoId, - githubRepoId: schema.projects.githubRepoId, - repository: schema.projects.repository, - }) - .from(schema.projects) - .where(eq(schema.projects.id, workspace.projectId)) - .limit(1); - - const project = projectRows[0]; - if (project) { - repoProvider = project.repoProvider || 'github'; - artifactsRepoId = project.artifactsRepoId; - githubRepoId = project.githubRepoId; - repositoryName = project.repository; - } - } - - if (repoProvider === 'artifacts') { - // ─── Artifacts token ────────────────────────────────────────────── - if (c.env.ARTIFACTS_ENABLED !== 'true') { - throw errors.forbidden('Artifacts provider is not enabled'); - } - if (!c.env.ARTIFACTS || !artifactsRepoId) { - throw errors.internal('Artifacts binding or repo ID missing'); - } - - // Clamp the token TTL to a sane range: a negative/zero/NaN or excessively - // large configured value must not mint a token that never expires (or expires - // instantly). Default 1h; hard cap 24h. - const rawTtl = Number.parseInt(c.env.ARTIFACTS_TOKEN_TTL_SECONDS || '', 10); - const ttl = Number.isFinite(rawTtl) && rawTtl > 0 && rawTtl <= 86400 ? rawTtl : 3600; - // Use requested scope or default to 'write' (agents need push access) - const requestedScope = c.req.query('scope') === 'read' ? ('read' as const) : ('write' as const); - const repo = await c.env.ARTIFACTS.get(artifactsRepoId); - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); - const tokenResult = await repo.createToken(requestedScope, ttl); - - // Strip ?expires= suffix from token for git credential use - const tokenSecret = tokenResult.plaintext.split('?expires=')[0] || tokenResult.plaintext; - - // Prefer the stored project.repository as the clone URL: it is `created.remote` - // captured at project creation and is exactly what the VM agent cloned, so its - // host is guaranteed to match what git requests from the credential helper. The - // Artifacts binding's `get().remote` has been observed to come back empty on - // staging (unlike `create().remote`); when that happens an empty cloneUrl makes - // the VM agent default the credential host to github.com, which then fails to - // match the real Artifacts host and returns no credential (git fetch/push break). - const cloneUrl = repositoryName || repo.remote || ''; - if (!repo.remote) { - log.warn('workspace_git_token.artifacts_remote_empty', { - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - artifactsRepoId, - usedStoredRepository: !!repositoryName, - action: 'fell_back_to_stored_repository', - }); - } - if (!cloneUrl) { - log.error('workspace_git_token.artifacts_clone_url_missing', { - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - artifactsRepoId, - action: 'clone_url_empty', - }); - } - - return callbackJsonWithJit(c, workspace, 'git_token', { - token: tokenSecret, - expiresAt: tokenResult.expiresAt ?? tokenResult.expires_at, - cloneUrl, - }); - } - - if (repoProvider === 'gitlab') { - if (!workspace.projectId) { - throw errors.forbidden('GitLab workspace has no project'); - } - const metadata = await getProjectGitLabRepository(db, workspace.projectId); - if (!metadata) { - throw errors.forbidden('GitLab repository metadata is missing'); - } - if (metadata.userId !== workspace.userId) { - // The stored GitLab repo binding belongs to a different user than the - // workspace owner — vending the owner's OAuth token against another - // user's binding would cross a tenant boundary. Fail closed. - log.error('workspace_git_token.gitlab_user_mismatch', { - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - workspaceUserId: workspace.userId, - metadataUserId: metadata.userId, - action: 'rejected', - }); - throw errors.forbidden('GitLab repository is not linked for this workspace owner'); - } - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); - const tokenResult = await requireGitLabUserAccessTokenResultForOwner( - c.env, - workspace.userId, - 'workspace-git-token' - ); - const verified = await verifyGitLabProjectAccess( - c.env, - tokenResult.accessToken, - metadata.gitlabProjectId - ); - if ( - verified.host !== metadata.host || - verified.gitlabProjectId !== metadata.gitlabProjectId || - verified.pathWithNamespace !== metadata.pathWithNamespace - ) { - throw errors.forbidden('GitLab repository access has changed; repository no longer matches'); - } - - return callbackJsonWithJit(c, workspace, 'git_token', { - provider: 'gitlab', - token: tokenResult.accessToken, - expiresAt: tokenResult.accessTokenExpiresAt, - cloneUrl: metadata.httpUrlToRepo, - host: metadata.host, - username: 'oauth2', - repositoryPath: metadata.pathWithNamespace, - }); - } - - // ─── GitHub token (existing flow) ────────────────────────────────── - if (!workspace.installationId) { - throw errors.notFound('Workspace has no GitHub installation'); - } - // Scope the token to a single repo. Prefer the verified numeric repo ID; fall - // back to the repository name for legacy projects created before github_repo_id - // was backfilled (PR #1236). Both paths scope to exactly one repository, so the - // personal-installation leak fix is preserved. - const repoShortName = - repositoryName && repositoryName.includes('/') - ? (repositoryName.split('/').pop() ?? null) - : repositoryName; - if (!githubRepoId && !repoShortName) { - throw errors.forbidden('GitHub repository is not verified for this workspace'); - } - - const installations = await db - .select({ - installationId: schema.githubInstallations.installationId, - externalInstallationId: schema.githubInstallations.externalInstallationId, - userId: schema.githubInstallations.userId, - }) - .from(schema.githubInstallations) - .where(eq(schema.githubInstallations.id, workspace.installationId)) - .limit(1); - - const installation = installations[0]; - if (!installation) { - log.warn('workspace_git_token_installation_owner_mismatch', { - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - installationRowId: workspace.installationId, - expectedUserId: workspace.userId, - action: 'rejected', - }); - throw errors.notFound('GitHub installation'); - } - if (installation.userId !== workspace.userId) { - log.info('workspace_git_token_project_installation_shared', { - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - installationRowId: workspace.installationId, - workspaceUserId: workspace.userId, - installationOwnerUserId: installation.userId, - action: 'allowed_after_user_access_verification', - }); - } - - if (!repositoryName) { - throw errors.forbidden('GitHub repository is not verified for this workspace'); - } - - const verifiedRepoId = await verifyWorkspaceGitHubOwnerAccess({ - env: c.env, - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - userId: workspace.userId, - repository: repositoryName, - externalInstallationId: getExternalInstallationId(installation), - githubRepoId, - }); - - // Lazy self-heal: legacy projects created before the numeric repo id was - // captured have github_repo_id = null. Fetch + persist it now, BEFORE policy - // resolution, so custom GitHub CLI policies (which require the numeric id) work - // and scoping uses the rename-stable repositoryIds path. On any failure we fall - // through to the name-based fallback below (no regression). - if (!githubRepoId && repositoryName && workspace.projectId) { - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); - const backfill = await backfillProjectGithubRepoId(db, c.env, { - projectId: workspace.projectId, - repository: repositoryName, - externalInstallationId: getExternalInstallationId(installation), - }); - if (backfill.githubRepoId) { - githubRepoId = backfill.githubRepoId; - } - } - githubRepoId ??= verifiedRepoId; - - let tokenOptions = null; - try { - tokenOptions = await resolveWorkspaceGitHubTokenOptions(db, { - workspaceId: workspace.workspaceId, - userId: workspace.userId, - githubRepoId, - }); - } catch (err) { - if (err instanceof GitHubCliPolicyError) { - throw errors.forbidden('GitHub CLI policy prevents token minting'); - } - throw err; - } - // Additional Repository Access: same-installation repos selected in Project - // Settings. Re-verified at this boundary; revoked/inaccessible entries are - // dropped from the scope. Primary repo is always included implicitly. - const additionalRepoIds = - githubRepoId && workspace.projectId - ? await resolveAdditionalRepositoryIds({ - env: c.env, - db, - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - userId: workspace.userId, - externalInstallationId: getExternalInstallationId(installation), - }) - : []; - - const scopedTokenOptions = { - ...(tokenOptions ?? {}), - ...(githubRepoId - ? { repositoryIds: [githubRepoId, ...additionalRepoIds.filter((id) => id !== githubRepoId)] } - : { repositories: [repoShortName as string] }), - }; - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); - const token = await getInstallationToken( - getExternalInstallationId(installation), - c.env, - scopedTokenOptions - ); - return callbackJsonWithJit(c, workspace, 'git_token', { - token: token.token, - expiresAt: token.expiresAt, - }); -}); - runtimeRoutes.post('/:id/boot-log', jsonValidator(BootLogEntrySchema), async (c) => { const workspaceId = c.req.param('id'); await verifyWorkspaceCallbackAuth(c, workspaceId); @@ -1531,110 +177,6 @@ runtimeRoutes.post('/:id/boot-log', jsonValidator(BootLogEntrySchema), async (c) * Uses workspace callback auth. Accepts 1-100 messages per batch. * All messages must target the same sessionId. */ -runtimeRoutes.post('/:id/messages', async (c) => { - const workspaceId = c.req.param('id'); - await verifyWorkspaceCallbackAuth(c, workspaceId); - - // Authenticate and resolve terminal state before reading an untrusted body. - // Late deletion callbacks are discarded without parsing or persisting payloads. - const workspace = await loadMessageWorkspace(c.env, workspaceId); - const preflightTerminalResponse = maybeTerminalMessageWorkspaceResponse( - c, - workspace, - workspaceId, - '', - 0 - ); - if (preflightTerminalResponse) { - await signalWorkspaceDeletionUnconfirmedCallback(c.env, workspaceId, 'messages'); - return preflightTerminalResponse; - } - - const body = await parseMessageBatchRequest(c); - const sessionId = validateMessageBatch(c.env, body); - - // Rule 49: re-read immediately before crossing into ProjectData. Deletion or - // reassignment that wins while the body is read must suppress all persistence. - const currentWorkspace = await loadMessageWorkspace(c.env, workspaceId); - const terminalResponse = maybeTerminalMessageWorkspaceResponse( - c, - currentWorkspace, - workspaceId, - sessionId, - body.messages.length - ); - if (terminalResponse) { - return terminalResponse; - } - if ( - !currentWorkspace || - !workspace || - !sameWorkspaceCallbackIdentity(currentWorkspace, workspace) - ) { - return terminalMessagePersistenceResponse( - c, - { - workspaceId, - projectId: currentWorkspace?.projectId ?? null, - sessionId, - messageCount: body.messages.length, - }, - currentWorkspace?.status ?? 'missing', - 'workspace_incarnation_changed' - ); - } - assertMessageWorkspaceAcceptsBatch( - c, - currentWorkspace, - workspaceId, - sessionId, - body.messages.length - ); - - // Delegate to ProjectData DO with structured error handling. - // On failure, return appropriate status codes so the VM agent outbox - // can distinguish transient (retry) from permanent (discard) errors. - const context: MessageRouteContext = { - workspaceId, - projectId: currentWorkspace.projectId, - sessionId, - messageCount: body.messages.length, - }; - let result: MessageBatchPersistenceRouteResult; - const outboxIncarnation = c.req.header(MESSAGE_OUTBOX_INCARNATION_HEADER); - try { - result = await projectDataService.persistMessageBatch( - c.env, - currentWorkspace.projectId, - sessionId, - toProjectDataMessages(body), - { - workspaceId, - callbackGeneration: currentWorkspace.callbackGeneration ?? null, - // This is transport identity, not an auth claim. Missing/malformed IDs - // retain the legacy per-message path instead of guessing about replay. - outboxIncarnation: v.is(v.pipe(v.string(), v.uuid()), outboxIncarnation) - ? outboxIncarnation.toLowerCase() - : undefined, - } - ); - } catch (err) { - return handleMessagePersistenceError(c, context, err); - } - - if (result.limitReached) { - return partialSessionLimitResponse(c, context, result); - } - - return c.json({ - persisted: result.persisted, - duplicates: result.duplicates, - }); -}); - -// Legacy compatibility endpoint for node-side bootstrap exchange. -// This route requires BOTH user session auth AND callback token auth -// (it was not in the original auth skip list in workspaces.ts). runtimeRoutes.post('/:id/bootstrap-token', requireAuth(), requireApproved(), async (c) => { const workspaceId = c.req.param('id'); await verifyWorkspaceCallbackAuth(c, workspaceId); From 8bff7bd5dbde10d7ae9badca4b70bc1adc159353 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 03:10:06 +0000 Subject: [PATCH 05/11] feat(ai): route admin model endpoints and guard authenticated upstreams --- apps/api/package.json | 1 + .../sam-session/agent-loop-helpers.ts | 9 +- .../sam-session/agent-loop-llm.ts | 57 ++- .../durable-objects/sam-session/agent-loop.ts | 29 +- .../sam-session/operator/agent.ts | 9 +- .../sam-session/operator/model.ts | 91 +++- apps/api/src/routes/agents-catalog.ts | 3 +- apps/api/src/routes/ai-proxy-admission.ts | 12 +- apps/api/src/routes/ai-proxy-anthropic.ts | 16 +- .../routes/ai-proxy-passthrough-prepare.ts | 32 +- apps/api/src/routes/ai-proxy-passthrough.ts | 74 ++-- .../src/routes/ai-proxy-platform-billing.ts | 9 +- apps/api/src/routes/ai-proxy-upstream.ts | 62 ++- apps/api/src/routes/ai-proxy.ts | 12 +- apps/api/src/routes/usage.ts | 70 ++- .../routes/workspaces/runtime-agent-key.ts | 61 +-- .../workspaces/runtime-callback-response.ts | 38 +- .../routes/workspaces/runtime-git-token.ts | 44 +- .../workspaces/runtime-message-helpers.ts | 49 +-- .../src/routes/workspaces/runtime-messages.ts | 48 +-- apps/api/src/routes/workspaces/runtime.ts | 40 +- .../src/services/admin-setting-definitions.ts | 4 + .../src/services/admin-settings-registry.ts | 4 + .../api/src/services/ai-proxy-availability.ts | 11 + apps/api/src/services/ai-proxy-settings.ts | 23 + apps/api/src/services/ai-proxy-shared.ts | 26 +- apps/api/src/services/debug-agent-tools.ts | 24 +- apps/api/src/services/llm-chat-target.ts | 122 ++++++ .../api/src/services/llm-endpoint-settings.ts | 140 ++++++ .../src/services/outbound-fetch-settings.ts | 2 +- .../api/src/services/platform-capabilities.ts | 34 ++ .../src/services/profile-account-bindings.ts | 6 +- .../api/src/services/sam-ai-proxy-fallback.ts | 13 +- apps/api/src/services/task-title.ts | 4 +- .../tests/unit/ai-proxy-passthrough.test.ts | 88 ++++ .../omitted-worker-var-defaults.test.ts | 2 +- .../agent-loop-metering.test.ts | 37 +- .../agent-loop-payload-size.test.ts | 12 +- .../unit/routes/ai-proxy-accounting.test.ts | 10 +- .../unit/routes/ai-proxy-auth-order.test.ts | 33 ++ .../tests/unit/runtime-always-proxy.test.ts | 19 + .../unit/services/configurable-limits.test.ts | 14 +- .../tests/unit/services/llm-endpoint.test.ts | 291 +++++++++++++ .../tests/unit/services/task-title.test.ts | 4 + .../tests/unit/task-runner-do-service.test.ts | 5 + .../tests/unit/workspace-lifecycle.test.ts | 5 + .../docs/docs/guides/admin-settings.md | 33 +- .../docs/docs/reference/configuration.md | 400 ++++++++++-------- packages/ai-proxy/src/ai-billing.ts | 2 + packages/ai-proxy/src/ai-cost-pricing.ts | 49 +++ .../ai-proxy/src/ai-gateway-availability.ts | 78 ++++ packages/ai-proxy/src/ai-monthly-cost-cap.ts | 72 +++- packages/ai-proxy/src/ai-monthly-cost-cron.ts | 3 +- packages/ai-proxy/src/ai-proxy-shared.ts | 44 +- packages/ai-proxy/src/ai-token-budget.ts | 11 +- .../ai-proxy/src/ai-token-usage-accounting.ts | 93 +++- packages/ai-proxy/src/index.ts | 18 + packages/ai-proxy/src/llm-chat-target.ts | 91 ++++ .../tests/unit/ai-monthly-cost-cron.test.ts | 1 + .../tests/unit/ai-token-budget.test.ts | 18 +- .../unit/direct-upstream-metering.test.ts | 152 +++++++ .../outbound-fetch-baseline.json | 7 +- pnpm-lock.yaml | 15 + ...26-11-17-l12-openai-compatible-endpoint.md | 37 +- 64 files changed, 2209 insertions(+), 614 deletions(-) create mode 100644 apps/api/src/services/ai-proxy-availability.ts create mode 100644 apps/api/src/services/ai-proxy-settings.ts create mode 100644 apps/api/src/services/llm-chat-target.ts create mode 100644 apps/api/src/services/llm-endpoint-settings.ts create mode 100644 apps/api/tests/unit/routes/ai-proxy-auth-order.test.ts create mode 100644 apps/api/tests/unit/services/llm-endpoint.test.ts create mode 100644 packages/ai-proxy/src/ai-cost-pricing.ts create mode 100644 packages/ai-proxy/src/ai-gateway-availability.ts create mode 100644 packages/ai-proxy/src/llm-chat-target.ts create mode 100644 packages/ai-proxy/tests/unit/direct-upstream-metering.test.ts diff --git a/apps/api/package.json b/apps/api/package.json index c7c0fdc145..1acf01f86e 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -21,6 +21,7 @@ "deploy:staging": "wrangler deploy --env staging" }, "dependencies": { + "@ai-sdk/openai-compatible": "2.0.87", "@aws-sdk/client-s3": "catalog:", "@aws-sdk/s3-request-presigner": "catalog:", "@cloudflare/containers": "0.3.7", diff --git a/apps/api/src/durable-objects/sam-session/agent-loop-helpers.ts b/apps/api/src/durable-objects/sam-session/agent-loop-helpers.ts index bb8f0144cc..d4aa927b88 100644 --- a/apps/api/src/durable-objects/sam-session/agent-loop-helpers.ts +++ b/apps/api/src/durable-objects/sam-session/agent-loop-helpers.ts @@ -9,7 +9,6 @@ * locking, or handle captured async prerequisites; they are given inputs and * return outputs. */ -import type { Env } from '../../env'; import { expectJsonRecord } from '../../lib/runtime-validation'; import type { OpenAIMessage } from './payload-size'; import type { AnthropicToolDef, CollectedToolCall, MessageRow, SamSseEvent } from './types'; @@ -219,10 +218,4 @@ export function toOpenAIMessages(rows: MessageRow[]): OpenAIMessage[] { return messages; } -export function buildAnthropicGatewayUrl(env: Env): string { - const gatewayId = env.AI_GATEWAY_ID; - if (gatewayId) { - return `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/anthropic/v1/messages`; - } - return 'https://api.anthropic.com/v1/messages'; -} +export { buildAnthropicGatewayUrl } from '../../services/ai-proxy-shared'; diff --git a/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts b/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts index 63b4be9ae2..3275d99a69 100644 --- a/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts +++ b/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts @@ -1,14 +1,22 @@ /** * The model call for one agent-loop turn, split out of agent-loop.ts (rule 18). * - * Route by model prefix: claude-* to Anthropic (translated at the boundary), @cf/* and @hf/* to - * Workers AI, both through AI Gateway. + * Route order: an admin-configured OpenAI-compatible endpoint when one is set + * (services/llm-chat-target.ts), else by model prefix: claude-* to Anthropic (translated at the + * boundary), @cf/* and @hf/* to Workers AI through AI Gateway or the REST API. */ import { SAM_ANTHROPIC_VERSION, type SamConfig } from '@simple-agent-manager/shared'; import type { Env } from '../../env'; import { getCredentialEncryptionKey } from '../../lib/secrets'; -import { buildWorkersAIGatewayUrl } from '../../services/ai-proxy-shared'; +import { + type ChatCompletionsTarget, + chatTargetHeaders, + fetchChatTarget, + LlmUnavailableError, + resolveCloudflareWorkersAiTarget, +} from '../../services/llm-chat-target'; +import { aiGatewayOnlyHeaders } from '../../services/platform-capabilities'; import { getPlatformAgentCredential } from '../../services/platform-credentials'; import { buildAnthropicGatewayUrl, @@ -43,7 +51,8 @@ export async function callLLM( userId: string, conversationId: string, baseSystemPrompt: string, - tools: AnthropicToolDef[] + tools: AnthropicToolDef[], + endpoint: ChatCompletionsTarget | null ): Promise { const model = config.model; const systemPrompt = config.systemPromptAppend @@ -65,7 +74,17 @@ export async function callLLM( const timer = setTimeout(() => controller.abort(), timeoutMs); try { - if (isAnthropicModel(model)) { + if (endpoint) { + return await callOpenAIChatLLM( + endpoint, + systemPrompt, + messages, + openAITools, + aigMetadata, + config.maxTokens, + controller.signal + ); + } else if (isAnthropicModel(model)) { return await callAnthropicLLM( env, model, @@ -78,9 +97,10 @@ export async function callLLM( tools ); } else if (isWorkersAIModel(model)) { - return await callWorkersAILLM( - env, - model, + const target = resolveCloudflareWorkersAiTarget(env, model); + if (!target) throw new LlmUnavailableError('agent'); + return await callOpenAIChatLLM( + target, systemPrompt, messages, openAITools, @@ -150,7 +170,7 @@ async function callAnthropicLLM( 'x-api-key': apiKey, 'anthropic-version': SAM_ANTHROPIC_VERSION, 'content-type': 'application/json', - 'cf-aig-metadata': aigMetadata, + ...aiGatewayOnlyHeaders(env, { 'cf-aig-metadata': aigMetadata }), }, body: JSON.stringify({ model, @@ -163,10 +183,9 @@ async function callAnthropicLLM( }); } -/** Call Workers AI via AI Gateway (OpenAI-compatible). */ -async function callWorkersAILLM( - env: Env, - model: string, +/** Call an OpenAI-format chat completions target (Workers AI or an OpenAI-compatible endpoint). */ +async function callOpenAIChatLLM( + target: ChatCompletionsTarget, systemPrompt: string, messages: OpenAIMessage[], openAITools: OpenAITool[], @@ -174,20 +193,14 @@ async function callWorkersAILLM( maxTokens: number, signal: AbortSignal ): Promise { - const url = buildWorkersAIGatewayUrl(env); - const fullMessages: OpenAIMessage[] = [{ role: 'system', content: systemPrompt }, ...messages]; - return fetch(url, { + return fetchChatTarget(target, { method: 'POST', signal, - headers: { - Authorization: `Bearer ${env.CF_API_TOKEN}`, - 'Content-Type': 'application/json', - 'cf-aig-metadata': aigMetadata, - }, + headers: chatTargetHeaders(target, { 'cf-aig-metadata': aigMetadata }), body: JSON.stringify({ - model, + model: target.model, max_tokens: maxTokens, messages: fullMessages, tools: openAITools.length > 0 ? openAITools : undefined, 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 6aa29418c1..4d0e1c3897 100644 --- a/apps/api/src/durable-objects/sam-session/agent-loop.ts +++ b/apps/api/src/durable-objects/sam-session/agent-loop.ts @@ -1,3 +1,4 @@ +import { estimateInputTokensFromMessages } from '@simple-agent-manager/ai-proxy'; /** * Agent loop — unified OpenAI-format code path routed through AI Gateway. * @@ -21,6 +22,7 @@ import { log } from '../../lib/logger'; import { expectJsonRecord } from '../../lib/runtime-validation'; import { checkAiUsageGate } from '../../services/ai-token-budget'; import { attachTokenUsageAccounting } from '../../services/ai-token-usage-accounting'; +import { LlmUnavailableError, resolveOpenAICompatibleTarget } from '../../services/llm-chat-target'; import { encodeSseEvent, isAnthropicModel, @@ -58,7 +60,7 @@ export async function runAgentLoop( conversationId: string, historyRows: MessageRow[], userMessage: string, - config: SamConfig, + baseConfig: SamConfig, env: Env, userId: string, writer: WritableStreamDefaultWriter, @@ -82,6 +84,16 @@ export async function runAgentLoop( ]; const systemPrompt = options?.systemPrompt ?? SAM_SYSTEM_PROMPT; + let endpoint; + try { + endpoint = await resolveOpenAICompatibleTarget(env, 'agent', baseConfig.model); + } catch (err) { + if (!(err instanceof LlmUnavailableError)) throw err; + await writer.write(encodeSseEvent({ type: 'error', message: err.message })); + await writer.write(encodeSseEvent({ type: 'done' })); + return; + } + const config = endpoint ? { ...baseConfig, model: endpoint.model } : baseConfig; const tools = options?.tools ?? []; const executeToolFn = options?.executeTool ?? (async () => ({ error: 'No tool executor configured' })); @@ -91,7 +103,7 @@ export async function runAgentLoop( searchMessages, ...options?.toolContextExtras, }; - const useAnthropicParser = isAnthropicModel(config.model); + const useAnthropicParser = !endpoint && isAnthropicModel(config.model); const tokenUsageFormat = useAnthropicParser ? ('anthropic' as const) : ('openai' as const); // Workers AI models have smaller context windows, so use a tighter budget @@ -146,12 +158,21 @@ export async function runAgentLoop( userId, conversationId, systemPrompt, - tools + tools, + endpoint ); response = await attachTokenUsageAccounting(response, { env, userId, format: tokenUsageFormat, + estimateMissingUsage: endpoint !== null, + fallbackInputTokens: endpoint + ? estimateInputTokensFromMessages([ + { role: 'system', content: systemPrompt }, + ...llmMessages, + ]) + : undefined, + costModelId: endpoint ? undefined : config.model, executionCtx, }); } catch (fetchErr) { @@ -183,7 +204,7 @@ export async function runAgentLoop( const errorText = await response.text().catch(() => 'Unknown error'); log.error('sam.llm_error', { status: response.status, - body: errorText.slice(0, 500), + body: endpoint ? '[external endpoint body omitted]' : errorText.slice(0, 500), model: config.model, }); await writer.write( 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 714199e7f0..b703de7b6f 100644 --- a/apps/api/src/durable-objects/sam-session/operator/agent.ts +++ b/apps/api/src/durable-objects/sam-session/operator/agent.ts @@ -76,6 +76,11 @@ export async function runOperatorAgent(options: { metadata: JSON.stringify({ source: config.aigSource, userId, turnId: turn.id }), sessionAffinity: `sam-${turn.conversation_id}`, }); + const customEndpoint = + typeof model === 'object' && + model !== null && + 'provider' in model && + String(model.provider).startsWith('sam-openai-compatible'); assertCurrent(); let toolAttempted = false; let inferenceFailed = false; @@ -128,7 +133,7 @@ export async function runOperatorAgent(options: { maxSteps: config.maxTurns - startedSteps, ...(correcting ? { instructions: `${instructions}\n${GROUNDING_CORRECTION}` } : {}), modelSettings: { maxOutputTokens: config.maxTokens, maxRetries: 0 }, - providerOptions: operatorProviderOptions(config.model), + providerOptions: operatorProviderOptions(customEndpoint ? '' : config.model), // Same scheduling as generate(): a tool starts after its step, behind prepareStep's gates. eagerToolExecution: false, onChunk: (chunk) => { @@ -158,7 +163,7 @@ export async function runOperatorAgent(options: { if (step.finishReason === 'error') inferenceFailed = true; if (step.toolCalls.length > 0) toolAttempted = true; live?.stepFinished(step.toolCalls.length > 0); - await recordOperatorStepUsage(env, userId, config, catalogModel, step); + await recordOperatorStepUsage(env, userId, config, catalogModel, step, customEndpoint); }, }); const full = await output.getFullOutput(); 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 bb6fadeeb9..021338a966 100644 --- a/apps/api/src/durable-objects/sam-session/operator/model.ts +++ b/apps/api/src/durable-objects/sam-session/operator/model.ts @@ -1,15 +1,26 @@ +import type { MastraModelConfig } from '@mastra/core/llm'; import type { PlatformAIModel, SamConfig } from '@simple-agent-manager/shared'; import { drizzle } from 'drizzle-orm/d1'; import type { Env } from '../../../env'; import { log } from '../../../lib/logger'; import { resolveUpstreamAuth } from '../../../services/ai-billing'; -import { buildWorkersAIGatewayUrl } from '../../../services/ai-proxy-shared'; import { incrementProviderUsage, incrementTokenUsage } from '../../../services/ai-token-budget'; +import { + type ChatCompletionsTarget, + chatTargetHeaders, + fetchChatTarget, + LlmUnavailableError, + resolveCloudflareWorkersAiTarget, + resolveOpenAICompatibleTarget, +} from '../../../services/llm-chat-target'; +import { aiGatewayOnlyHeaders } from '../../../services/platform-capabilities'; import { buildAnthropicGatewayUrl } from '../agent-loop-helpers'; /** Provider ID of the OpenAI-compatible Workers AI route; also its providerOptions key. */ const WORKERS_AI_PROVIDER_ID = 'sam-workers-ai'; +/** Provider ID of an admin-configured OpenAI-compatible endpoint (no provider options). */ +const OPENAI_COMPATIBLE_PROVIDER_ID = 'sam-openai-compatible'; /** * The language model for one private turn, routed through the SAM AI Gateway. @@ -20,8 +31,11 @@ export async function resolveOperatorModel( env: Env, modelId: string, headers: { metadata: string; sessionAffinity: string } -) { +): Promise { const { ModelRouterLanguageModel, ModelsDevGateway } = await import('@mastra/core/llm'); + // An admin-configured OpenAI-compatible endpoint replaces the model route for the agent. + const endpoint = await resolveOpenAICompatibleTarget(env, 'agent', modelId); + if (endpoint) return openAICompatibleEndpointModel(endpoint, headers); if (modelId.startsWith('claude-')) { const auth = await resolveUpstreamAuth(env, drizzle(env.DATABASE)); const gateway = new ModelsDevGateway({ @@ -37,25 +51,63 @@ export async function resolveOperatorModel( providerId: 'anthropic', modelId, apiKey: auth.headers['x-api-key'] ?? '', - headers: { ...auth.headers, 'cf-aig-metadata': headers.metadata }, + headers: { + ...auth.headers, + ...aiGatewayOnlyHeaders(env, { 'cf-aig-metadata': headers.metadata }), + }, }); } if (modelId.startsWith('@cf/') || modelId.startsWith('@hf/')) { + const target = resolveCloudflareWorkersAiTarget(env, modelId); + if (!target) throw new LlmUnavailableError('agent'); return new ModelRouterLanguageModel({ providerId: WORKERS_AI_PROVIDER_ID, modelId, - url: buildWorkersAIGatewayUrl(env).replace(/\/chat\/completions$/, ''), + url: target.baseUrl, apiKey: env.CF_API_TOKEN, - headers: { - 'cf-aig-metadata': headers.metadata, - 'x-session-affinity': headers.sessionAffinity, - }, + headers: chatHeadersWithoutAuth(target, headers), api: 'chat', }); } throw new Error('Unsupported SAM model provider'); } +/** + * The chat model for an admin-configured endpoint. This is what `ModelRouterLanguageModel` builds + * for a `url` config (the same @ai-sdk/openai-compatible version, `chatModel`, structured + * outputs on), built directly because the router has no `fetch` option: every request, including + * each redirect hop, must go through the endpoint's guarded fetch (`fetchChatTarget`). + */ +async function openAICompatibleEndpointModel( + endpoint: ChatCompletionsTarget, + headers: { metadata: string; sessionAffinity: string } +): Promise { + const { createOpenAICompatible } = await import('@ai-sdk/openai-compatible'); + return createOpenAICompatible({ + name: OPENAI_COMPATIBLE_PROVIDER_ID, + baseURL: endpoint.baseUrl, + apiKey: endpoint.apiKey ?? undefined, + headers: chatHeadersWithoutAuth(endpoint, headers), + supportsStructuredOutputs: true, + fetch: (input, init) => + fetchChatTarget(endpoint, init ?? {}, input instanceof Request ? input.url : String(input)), + }).chatModel(endpoint.model); +} + +/** The router sets Authorization from apiKey; gateway attribution goes to Cloudflare only. */ +function chatHeadersWithoutAuth( + target: ChatCompletionsTarget, + headers: { metadata: string; sessionAffinity: string } +): Record { + const all = chatTargetHeaders(target, { + 'cf-aig-metadata': headers.metadata, + 'x-session-affinity': headers.sessionAffinity, + }); + return Object.fromEntries( + Object.entries(all).filter(([name]) => name !== 'Authorization' && name !== 'Content-Type') + ); +} + /** Model quirks live in one explicit boundary (compare `getTaskTitleModelControls`). */ export function operatorProviderOptions(modelId: string) { switch (modelId) { @@ -91,7 +143,8 @@ export async function recordOperatorStepUsage( userId: string, config: SamConfig, catalogModel: PlatformAIModel, - step: StepUsageInput + step: StepUsageInput, + customEndpoint = false ): Promise { const reportedInput = step.usage.inputTokens; const reportedOutput = step.usage.outputTokens; @@ -116,16 +169,22 @@ export async function recordOperatorStepUsage( env.KV, userId, { - providerId: anthropic ? 'anthropic' : 'workers-ai', - providerName: anthropic ? 'Anthropic' : 'Cloudflare Workers AI', - dialect: anthropic ? 'anthropic' : 'openai', + providerId: customEndpoint ? 'openai-compatible' : anthropic ? 'anthropic' : 'workers-ai', + providerName: customEndpoint + ? 'OpenAI-compatible endpoint' + : anthropic + ? 'Anthropic' + : 'Cloudflare Workers AI', + dialect: !customEndpoint && anthropic ? 'anthropic' : 'openai', }, input, output, env, - ((input - cached) * catalogModel.costPer1kInputTokens + - cached * cachedRate + - output * catalogModel.costPer1kOutputTokens) / - 1000 + customEndpoint + ? 0 + : ((input - cached) * catalogModel.costPer1kInputTokens + + cached * cachedRate + + output * catalogModel.costPer1kOutputTokens) / + 1000 ); } diff --git a/apps/api/src/routes/agents-catalog.ts b/apps/api/src/routes/agents-catalog.ts index 6b9a3dbc74..55799c1f1c 100644 --- a/apps/api/src/routes/agents-catalog.ts +++ b/apps/api/src/routes/agents-catalog.ts @@ -7,6 +7,7 @@ import { Hono } from 'hono'; import * as schema from '../db/schema'; import type { Env } from '../env'; import { getUserId, requireApproved, requireAuth } from '../middleware/auth'; +import { isAiProxyEnabled } from '../services/ai-proxy-availability'; const agentsCatalogRoutes = new Hono<{ Bindings: Env }>(); type AgentFallbackCredentialSource = 'platform-sam' | null; @@ -53,7 +54,7 @@ agentsCatalogRoutes.get('/', async (c) => { agentProviderSettings.map((s) => [s.agentType, s.providerMode as AgentProviderMode | null]) ); - const aiProxyEnabled = (c.env.AI_PROXY_ENABLED ?? 'true') !== 'false'; + const aiProxyEnabled = await isAiProxyEnabled(c.env); const agents: AgentInfo[] = AGENT_CATALOG.map((agent) => { const hasDedicatedKey = configuredAgents.has(agent.id); diff --git a/apps/api/src/routes/ai-proxy-admission.ts b/apps/api/src/routes/ai-proxy-admission.ts index 78487fed2b..66d1760e50 100644 --- a/apps/api/src/routes/ai-proxy-admission.ts +++ b/apps/api/src/routes/ai-proxy-admission.ts @@ -24,6 +24,7 @@ import { getCurrentWindowStart, } from '../middleware/rate-limit'; import { checkModelTierAllowance, describeModelTierDenial } from '../services/ai-model-tier-gate'; +import { isAiProxyEnabled } from '../services/ai-proxy-availability'; import { AIProxyAuthError, extractCallbackToken, @@ -71,10 +72,6 @@ export function aiProxyBodyParseError(c: AIProxyContext, error: unknown): Respon export async function prepareAIProxyRequest( c: AIProxyContext ): Promise { - if (c.env.AI_PROXY_ENABLED === 'false') { - return proxyJsonError(c, 'AI proxy is disabled', 'service_unavailable', 503); - } - const token = extractCallbackToken(c.req.header('Authorization'), undefined); if (!token) { return proxyJsonError( @@ -86,9 +83,9 @@ export async function prepareAIProxyRequest( } const db = drizzle(c.env.DATABASE, { schema }); + let auth; try { - const auth = await verifyAIProxyAuth(token, c.env, db); - return { ...auth, db }; + auth = await verifyAIProxyAuth(token, c.env, db); } catch (err) { if (err instanceof AIProxyAuthError) { return proxyJsonError( @@ -100,6 +97,9 @@ export async function prepareAIProxyRequest( } return proxyJsonError(c, 'Invalid or expired token', 'invalid_request_error', 401); } + if (!(await isAiProxyEnabled(c.env))) + return proxyJsonError(c, 'AI proxy is disabled', 'service_unavailable', 503); + return { ...auth, db }; } export async function enforceRateLimit( diff --git a/apps/api/src/routes/ai-proxy-anthropic.ts b/apps/api/src/routes/ai-proxy-anthropic.ts index 497cdf3df0..3ee57d2fb7 100644 --- a/apps/api/src/routes/ai-proxy-anthropic.ts +++ b/apps/api/src/routes/ai-proxy-anthropic.ts @@ -32,6 +32,7 @@ import { } from '../middleware/rate-limit'; import { proxyRunUsageRecorder } from '../services/agent-run-usage'; import { resolveUpstreamAuth } from '../services/ai-billing'; +import { isAiProxyEnabled } from '../services/ai-proxy-availability'; import { AIProxyAuthError, buildAIGatewayMetadata, @@ -66,11 +67,6 @@ const aiProxyAnthropicRoutes = new Hono<{ Bindings: Env }>(); // ============================================================================= aiProxyAnthropicRoutes.post('/messages', async (c) => { - // Kill switch - if (c.env.AI_PROXY_ENABLED === 'false') { - return anthropicError('AI proxy is disabled', 'api_error', 503); - } - // --- Auth: extract token from x-api-key or Authorization: Bearer --- const token = extractCallbackToken(c.req.header('Authorization'), c.req.header('x-api-key')); if (!token) { @@ -92,6 +88,8 @@ aiProxyAnthropicRoutes.post('/messages', async (c) => { } return anthropicError('Invalid or expired API key', 'authentication_error', 401); } + if (!(await isAiProxyEnabled(c.env))) + return anthropicError('AI proxy is disabled', 'api_error', 503); const { userId, workspaceId, projectId, chatSessionId } = auth; @@ -274,6 +272,7 @@ aiProxyAnthropicRoutes.post('/messages', async (c) => { env: c.env, userId, format: 'anthropic', + costModelId: modelId, fallbackInputTokens: estimateInputTokensFromMessages(body.messages), onMeasuredUsage: proxyRunUsageRecorder(c.env, auth, { model: modelId, @@ -299,11 +298,6 @@ aiProxyAnthropicRoutes.post('/messages', async (c) => { // ============================================================================= aiProxyAnthropicRoutes.post('/messages/count_tokens', async (c) => { - // Kill switch - if (c.env.AI_PROXY_ENABLED === 'false') { - return anthropicError('AI proxy is disabled', 'api_error', 503); - } - // --- Auth --- const token = extractCallbackToken(c.req.header('Authorization'), c.req.header('x-api-key')); if (!token) { @@ -325,6 +319,8 @@ aiProxyAnthropicRoutes.post('/messages/count_tokens', async (c) => { } return anthropicError('Invalid or expired API key', 'authentication_error', 401); } + if (!(await isAiProxyEnabled(c.env))) + return anthropicError('AI proxy is disabled', 'api_error', 503); const { userId, workspaceId, projectId, chatSessionId } = auth; diff --git a/apps/api/src/routes/ai-proxy-passthrough-prepare.ts b/apps/api/src/routes/ai-proxy-passthrough-prepare.ts index 07a77c8726..ce60665569 100644 --- a/apps/api/src/routes/ai-proxy-passthrough-prepare.ts +++ b/apps/api/src/routes/ai-proxy-passthrough-prepare.ts @@ -15,24 +15,35 @@ * from, or returned to, tenant workspaces. */ import type { MeasuredTokenUsage } from '@simple-agent-manager/ai-proxy'; -import { DEFAULT_AI_PROXY_RATE_LIMIT_RPM, DEFAULT_AI_PROXY_RATE_LIMIT_WINDOW_SECONDS, DEFAULT_AI_PROXY_REQUEST_BODY_MAX_BYTES, type Dialect } from '@simple-agent-manager/shared'; +import { + DEFAULT_AI_PROXY_RATE_LIMIT_RPM, + DEFAULT_AI_PROXY_RATE_LIMIT_WINDOW_SECONDS, + DEFAULT_AI_PROXY_REQUEST_BODY_MAX_BYTES, + type Dialect, +} from '@simple-agent-manager/shared'; import { drizzle } from 'drizzle-orm/d1'; import { type Context } from 'hono'; import * as schema from '../db/schema'; import type { Env } from '../env'; - import { parsePositiveInt } from '../lib/route-helpers'; import { readRequestJsonRecord, RequestBodyTooLargeError } from '../lib/runtime-validation'; -import { checkRateLimit, createRateLimitKey, getCurrentWindowStart } from '../middleware/rate-limit'; +import { + checkRateLimit, + createRateLimitKey, + getCurrentWindowStart, +} from '../middleware/rate-limit'; import { proxyRunUsageRecorder } from '../services/agent-run-usage'; +import { isAiProxyEnabled } from '../services/ai-proxy-availability'; import { AIProxyAuthError, verifyAIProxyAuth } from '../services/ai-proxy-shared'; import { checkAiUsageGate } from '../services/ai-token-budget'; - - import type { PreloadedRuntimeRows } from '../services/workspace-runtime-assets'; -import { anthropicError, anthropicUsageGateError, openaiError, openaiUsageGateError } from './ai-proxy-passthrough-errors'; - +import { + anthropicError, + anthropicUsageGateError, + openaiError, + openaiUsageGateError, +} from './ai-proxy-passthrough-errors'; import { type ResolvedProxyUpstream, resolveProxyUpstream } from './ai-proxy-passthrough-upstream'; type ProxyContext = Context<{ Bindings: Env }>; @@ -163,10 +174,6 @@ export async function prepareProxyRequest( c: ProxyContext, options: PrepareProxyOptions ): Promise { - if (c.env.AI_PROXY_ENABLED === 'false') { - return { ok: false, response: options.disabledResponse() }; - } - const wstoken = c.req.param('wstoken'); if (!wstoken) { return { ok: false, response: options.invalidTokenResponse() }; @@ -182,6 +189,8 @@ export async function prepareProxyRequest( return { ok: false, response: options.invalidTokenResponse() }; } + if (!(await isAiProxyEnabled(c.env))) return { ok: false, response: options.disabledResponse() }; + const { allowed, remaining, resetAt, limit } = await checkPassthroughRateLimit( c.env, auth.userId @@ -245,4 +254,3 @@ export async function prepareProxyRequest( }); return { ok: true, value: { ...auth, body, modelId, upstream, recordRunUsage } }; } - diff --git a/apps/api/src/routes/ai-proxy-passthrough.ts b/apps/api/src/routes/ai-proxy-passthrough.ts index c02f43f443..b9f20239f4 100644 --- a/apps/api/src/routes/ai-proxy-passthrough.ts +++ b/apps/api/src/routes/ai-proxy-passthrough.ts @@ -1,3 +1,4 @@ +import { guardedFetch } from '@simple-agent-manager/worker-core'; /** * AI proxy passthrough routes — URL-path-based workspace auth. * @@ -14,27 +15,30 @@ * workspaceId, and projectId. Upstream provider credentials are never accepted * from, or returned to, tenant workspaces. */ - - - import { type Context, Hono } from 'hono'; - import type { Env } from '../env'; import { log } from '../lib/logger'; - - - - - - -import { attachUpstreamTokenUsageAccounting, estimateInputTokensFromMessages, optionalExecutionContext } from '../services/ai-token-usage-accounting'; +import { + attachUpstreamTokenUsageAccounting, + estimateInputTokensFromMessages, + optionalExecutionContext, +} from '../services/ai-token-usage-accounting'; import { copyCredentialLimitHeaders } from '../services/credential-limit-events'; - +import { resolveOutboundMaxRedirects } from '../services/outbound-fetch-settings'; import { anthropicError, credentialErrorHeaders, openaiError } from './ai-proxy-passthrough-errors'; -import { anthropicProxyOptions, openaiProxyOptions, prepareProxyRequest, retryAfterSeconds } from './ai-proxy-passthrough-prepare'; +import { + anthropicProxyOptions, + openaiProxyOptions, + prepareProxyRequest, + retryAfterSeconds, +} from './ai-proxy-passthrough-prepare'; import { schedulePassthroughLimitHeaders } from './ai-proxy-passthrough-telemetry'; -import { type ResolvedProxyUpstream, resolveProxyUpstream, trimTrailingSlashes } from './ai-proxy-passthrough-upstream'; +import { + type ResolvedProxyUpstream, + resolveProxyUpstream, + trimTrailingSlashes, +} from './ai-proxy-passthrough-upstream'; const aiProxyPassthroughRoutes = new Hono<{ Bindings: Env }>(); type ProxyContext = Context<{ Bindings: Env }>; @@ -137,11 +141,15 @@ aiProxyPassthroughRoutes.post('/:wstoken/anthropic/v1/messages', async (c) => { const upstreamUrl = joinUpstreamUrl(upstream.baseUrl, 'v1/messages'); try { - const upstreamResponse = await fetch(upstreamUrl, { - method: 'POST', - headers: upstreamHeaders, - body: JSON.stringify(body), - }); + const upstreamResponse = await guardedFetch( + upstreamUrl, + { + method: 'POST', + headers: upstreamHeaders, + body: JSON.stringify(body), + }, + { maxRedirects: await resolveOutboundMaxRedirects(c.env) } + ); log.info('ai_proxy_passthrough.anthropic.response', { userId, @@ -227,11 +235,15 @@ aiProxyPassthroughRoutes.post('/:wstoken/anthropic/v1/messages/count_tokens', as const countTokensUrl = joinUpstreamUrl(upstream.baseUrl, 'v1/messages/count_tokens'); try { - const upstreamResponse = await fetch(countTokensUrl, { - method: 'POST', - headers: upstreamHeaders, - body: JSON.stringify(body), - }); + const upstreamResponse = await guardedFetch( + countTokensUrl, + { + method: 'POST', + headers: upstreamHeaders, + body: JSON.stringify(body), + }, + { maxRedirects: await resolveOutboundMaxRedirects(c.env) } + ); if (!upstreamResponse.ok) { log.error('ai_proxy_passthrough.anthropic.count_tokens_error', { @@ -309,11 +321,15 @@ aiProxyPassthroughRoutes.post('/:wstoken/openai/v1/chat/completions', async (c) }); try { - const upstreamResponse = await fetch(upstreamUrl, { - method: 'POST', - headers: upstreamHeaders, - body: JSON.stringify(body), - }); + const upstreamResponse = await guardedFetch( + upstreamUrl, + { + method: 'POST', + headers: upstreamHeaders, + body: JSON.stringify(body), + }, + { maxRedirects: await resolveOutboundMaxRedirects(c.env) } + ); log.info('ai_proxy_passthrough.openai.response', { userId, diff --git a/apps/api/src/routes/ai-proxy-platform-billing.ts b/apps/api/src/routes/ai-proxy-platform-billing.ts index e216874a9c..43c4823316 100644 --- a/apps/api/src/routes/ai-proxy-platform-billing.ts +++ b/apps/api/src/routes/ai-proxy-platform-billing.ts @@ -32,10 +32,7 @@ type OpenAIProxyCredential = AIProxyCredentialAttribution & { }; export function buildProxyMetadata( - auth: Pick< - AIProxyRequestContext, - 'userId' | 'workspaceId' | 'projectId' | 'chatSessionId' - >, + auth: Pick, body: Record, modelId: string ): string { @@ -147,7 +144,8 @@ export function accountingResponse( userId: string, estimatedInputTokens: number, /** Insights run usage hook (`proxyRunUsageRecorder`); receives measured usage only. */ - onMeasuredUsage?: (usage: MeasuredTokenUsage) => Promise + onMeasuredUsage?: (usage: MeasuredTokenUsage) => Promise, + metering: { costModelId?: string; estimateMissingUsage?: boolean } = {} ): Promise { let executionCtx: Pick | undefined; try { @@ -162,5 +160,6 @@ export function accountingResponse( fallbackInputTokens: estimatedInputTokens, executionCtx, onMeasuredUsage, + ...metering, }); } diff --git a/apps/api/src/routes/ai-proxy-upstream.ts b/apps/api/src/routes/ai-proxy-upstream.ts index 64d9691e1b..cbecf141eb 100644 --- a/apps/api/src/routes/ai-proxy-upstream.ts +++ b/apps/api/src/routes/ai-proxy-upstream.ts @@ -1,3 +1,4 @@ +export const customEndpointResponses = new WeakSet(); /** * AI proxy upstream forwarding — sends prepared requests to Workers AI, * Anthropic, or OpenAI through Cloudflare AI Gateway, translating Anthropic's @@ -18,8 +19,15 @@ import { } from '../services/ai-anthropic-translate'; import type { UpstreamAuth } from '../services/ai-billing'; import { resolveUnifiedBillingToken } from '../services/ai-billing'; -import { buildAnthropicGatewayUrl, buildWorkersAIGatewayUrl } from '../services/ai-proxy-shared'; +import { buildAnthropicGatewayUrl } from '../services/ai-proxy-shared'; import { copyCredentialLimitHeaders } from '../services/credential-limit-events'; +import { + chatTargetHeaders, + fetchChatTarget, + LlmUnavailableError, + resolveWorkersAiChatTarget, +} from '../services/llm-chat-target'; +import { aiGatewayOnlyHeaders, resolveAiGatewayId } from '../services/platform-capabilities'; const anthropicContentBlockSchema = v.variant('type', [ v.object({ type: v.literal('text'), text: v.string() }), @@ -45,7 +53,7 @@ const anthropicResponseSchema = v.object({ /** Build upstream URL for OpenAI chat completions via AI Gateway. */ function buildOpenAIUrl(env: Env): string { - const gatewayId = env.AI_GATEWAY_ID; + const gatewayId = resolveAiGatewayId(env); if (gatewayId) { return `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/openai/v1/chat/completions`; } @@ -55,7 +63,7 @@ function buildOpenAIUrl(env: Env): string { /** Build upstream URL for OpenAI Responses API via AI Gateway. */ function buildOpenAIResponsesUrl(env: Env): string { - const gatewayId = env.AI_GATEWAY_ID; + const gatewayId = resolveAiGatewayId(env); if (gatewayId) { return `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/openai/v1/responses`; } @@ -73,16 +81,30 @@ export async function forwardToWorkersAI( modelId: string, aigMetadata: string ): Promise { - const gatewayUrl = buildWorkersAIGatewayUrl(env); - const gatewayBody = { ...body, model: modelId }; + let target; + try { + target = await resolveWorkersAiChatTarget(env, 'aiProxy', modelId); + } catch (err) { + if (!(err instanceof LlmUnavailableError)) throw err; + return new Response( + JSON.stringify({ + error: { message: err.message, type: 'api_error', code: 'LLM_SETTINGS_UNAVAILABLE' }, + }), + { status: 503, headers: { 'Content-Type': 'application/json' } } + ); + } + if (!target) + return new Response( + JSON.stringify({ + error: { message: 'Model route is unavailable', code: 'FEATURE_UNAVAILABLE' }, + }), + { status: 404, headers: { 'Content-Type': 'application/json' } } + ); + const gatewayBody = { ...body, model: target.model }; - const response = await fetch(gatewayUrl, { + const response = await fetchChatTarget(target, { method: 'POST', - headers: { - Authorization: `Bearer ${env.CF_API_TOKEN}`, - 'Content-Type': 'application/json', - 'cf-aig-metadata': aigMetadata, - }, + headers: chatTargetHeaders(target, { 'cf-aig-metadata': aigMetadata }), body: JSON.stringify(gatewayBody), }); @@ -90,7 +112,10 @@ export async function forwardToWorkersAI( const errorText = await response.text(); log.error('ai_proxy.workers_ai_error', { status: response.status, - body: errorText.slice(0, 500), + body: + target.kind === 'openai-compatible' + ? '[external endpoint body omitted]' + : errorText.slice(0, 500), }); const errorHeaders = new Headers({ 'Content-Type': 'application/json' }); copyCredentialLimitHeaders(response.headers, errorHeaders); @@ -115,7 +140,12 @@ export async function forwardToWorkersAI( responseHeaders.set('X-Accel-Buffering', 'no'); } - return new Response(response.body, { status: response.status, headers: responseHeaders }); + const forwarded = new Response(response.body, { + status: response.status, + headers: responseHeaders, + }); + if (target.kind === 'openai-compatible') customEndpointResponses.add(forwarded); + return forwarded; } /** Forward request to Anthropic via AI Gateway (with format translation). */ @@ -136,7 +166,7 @@ export async function forwardToAnthropic( ...upstreamAuth.headers, 'anthropic-version': '2023-06-01', 'Content-Type': 'application/json', - 'cf-aig-metadata': aigMetadata, + ...aiGatewayOnlyHeaders(env, { 'cf-aig-metadata': aigMetadata }), }, body: JSON.stringify(anthropicRequest), }); @@ -215,7 +245,7 @@ export async function forwardToOpenAI( const headers: Record = { 'Content-Type': 'application/json', - 'cf-aig-metadata': aigMetadata, + ...aiGatewayOnlyHeaders(env, { 'cf-aig-metadata': aigMetadata }), }; if (cfToken) { headers['cf-aig-authorization'] = `Bearer ${cfToken}`; @@ -276,7 +306,7 @@ export async function forwardToOpenAIResponses( const headers: Record = { 'Content-Type': 'application/json', - 'cf-aig-metadata': aigMetadata, + ...aiGatewayOnlyHeaders(env, { 'cf-aig-metadata': aigMetadata }), }; if (cfToken) { headers['cf-aig-authorization'] = `Bearer ${cfToken}`; diff --git a/apps/api/src/routes/ai-proxy.ts b/apps/api/src/routes/ai-proxy.ts index 79bfdef891..1206ef80b2 100644 --- a/apps/api/src/routes/ai-proxy.ts +++ b/apps/api/src/routes/ai-proxy.ts @@ -1,3 +1,4 @@ +import { hasLocalAiCostMetering } from '@simple-agent-manager/ai-proxy'; /** * AI inference proxy — routes to Workers AI, Anthropic, or OpenAI via Cloudflare AI Gateway. * @@ -47,6 +48,7 @@ import { resolveOpenAIProxyCredential, schedulePlatformProxyLimitHeaders, } from './ai-proxy-platform-billing'; +import { customEndpointResponses } from './ai-proxy-upstream'; import { forwardToAnthropic, forwardToOpenAI, @@ -222,7 +224,12 @@ aiProxyRoutes.post('/chat/completions', async (c) => { model: modelId, credentialReference: attribution?.credentialReference ?? null, credentialSource: attribution?.credentialSource ?? null, - }) + }), + { + costModelId: customEndpointResponses.has(response) ? undefined : modelId, + estimateMissingUsage: + customEndpointResponses.has(response) || hasLocalAiCostMetering(c.env), + } ); } catch (err) { log.error('ai_proxy.fetch_error', { @@ -346,7 +353,8 @@ aiProxyRoutes.post('/responses', async (c) => { model: modelId, credentialReference: openaiCredential.credentialReference, credentialSource: openaiCredential.credentialSource, - }) + }), + { costModelId: modelId, estimateMissingUsage: hasLocalAiCostMetering(c.env) } ); } catch (err) { log.error('ai_proxy.responses.fetch_error', { diff --git a/apps/api/src/routes/usage.ts b/apps/api/src/routes/usage.ts index 329fbb51b8..343b232af4 100644 --- a/apps/api/src/routes/usage.ts +++ b/apps/api/src/routes/usage.ts @@ -1,3 +1,8 @@ +import { + getLocalMonthlyAiCostUsd, + hasLocalAiCostMetering, + resolveAiGatewayId, +} from '@simple-agent-manager/ai-proxy'; import type { UserAiBudgetResponse, UserAiUsageResponse, @@ -94,10 +99,15 @@ usageRoutes.get('/ai', requireAuth(), requireApproved(), async (c) => { const period = parseGatewayPeriod(c.req.query('period')); const periodBounds = getGatewayPeriodBounds(period); - const gatewayId = c.env.AI_GATEWAY_ID; + const gatewayId = resolveAiGatewayId(c.env); if (!gatewayId) { const providerMap = new Map(); - const localProviderUsage = await getProviderUsage(c.env.KV, userId, new Date(periodBounds.startDate), c.env); + const localProviderUsage = await getProviderUsage( + c.env.KV, + userId, + new Date(periodBounds.startDate), + c.env + ); let totalRequests = 0; let totalInputTokens = 0; let totalOutputTokens = 0; @@ -178,7 +188,12 @@ usageRoutes.get('/ai', requireAuth(), requireApproved(), async (c) => { } satisfies UserAiUsageResponse); } - const localProviderUsage = await getProviderUsage(c.env.KV, userId, new Date(periodBounds.startDate), c.env); + const localProviderUsage = await getProviderUsage( + c.env.KV, + userId, + new Date(periodBounds.startDate), + c.env + ); for (const entry of localProviderUsage) { mergeLocalProviderUsage(providerMap, entry); totalRequests += entry.requests; @@ -195,7 +210,9 @@ usageRoutes.get('/ai', requireAuth(), requireApproved(), async (c) => { cachedRequests, errorRequests, byModel: Array.from(modelMap.values()).sort((a, b) => b.costUsd - a.costUsd), - byProvider: Array.from(providerMap.values()).sort((a, b) => b.costUsd - a.costUsd || b.totalTokens - a.totalTokens), + byProvider: Array.from(providerMap.values()).sort( + (a, b) => b.costUsd - a.costUsd || b.totalTokens - a.totalTokens + ), byDay: Array.from(dayMap.values()).sort((a, b) => a.date.localeCompare(b.date)), period, periodLabel: getPeriodLabel(period), @@ -206,7 +223,7 @@ usageRoutes.get('/ai', requireAuth(), requireApproved(), async (c) => { function mergeLocalProviderUsage( map: Map, - entry: Awaited>[number], + entry: Awaited>[number] ): void { const key = `${entry.providerId}:${entry.dialect}`; const existing = map.get(key); @@ -253,8 +270,10 @@ usageRoutes.get('/ai/budget', requireAuth(), requireApproved(), async (c) => { const effectiveLimits = resolveEffectiveLimits(userSettings, c.env); // Get current month cost from AI Gateway (reuse the same aggregation) - let monthCostUsd = 0; - const gatewayId = c.env.AI_GATEWAY_ID; + let monthCostUsd = hasLocalAiCostMetering(c.env) + ? await getLocalMonthlyAiCostUsd(c.env.KV, userId, c.env) + : 0; + const gatewayId = resolveAiGatewayId(c.env); if (gatewayId) { const periodBounds = getGatewayPeriodBounds('current-month'); try { @@ -277,18 +296,23 @@ usageRoutes.get('/ai/budget', requireAuth(), requireApproved(), async (c) => { alertThresholdPercent: DEFAULT_AI_USAGE_ALERT_THRESHOLD_PERCENT, }; - const dailyInputPercent = effectiveLimits.dailyInputTokenLimit > 0 - ? Math.min(100, (dailyUsage.inputTokens / effectiveLimits.dailyInputTokenLimit) * 100) - : 0; - const dailyOutputPercent = effectiveLimits.dailyOutputTokenLimit > 0 - ? Math.min(100, (dailyUsage.outputTokens / effectiveLimits.dailyOutputTokenLimit) * 100) - : 0; - const monthlyCostPercent = settings.monthlyCostCapUsd !== null && settings.monthlyCostCapUsd > 0 - ? Math.min(100, (monthCostUsd / settings.monthlyCostCapUsd) * 100) - : null; - - const exceeded = dailyInputPercent >= 100 || dailyOutputPercent >= 100 - || (monthlyCostPercent !== null && monthlyCostPercent >= 100); + const dailyInputPercent = + effectiveLimits.dailyInputTokenLimit > 0 + ? Math.min(100, (dailyUsage.inputTokens / effectiveLimits.dailyInputTokenLimit) * 100) + : 0; + const dailyOutputPercent = + effectiveLimits.dailyOutputTokenLimit > 0 + ? Math.min(100, (dailyUsage.outputTokens / effectiveLimits.dailyOutputTokenLimit) * 100) + : 0; + const monthlyCostPercent = + settings.monthlyCostCapUsd !== null && settings.monthlyCostCapUsd > 0 + ? Math.min(100, (monthCostUsd / settings.monthlyCostCapUsd) * 100) + : null; + + const exceeded = + dailyInputPercent >= 100 || + dailyOutputPercent >= 100 || + (monthlyCostPercent !== null && monthlyCostPercent >= 100); const response: UserAiBudgetResponse = { settings, @@ -302,7 +326,8 @@ usageRoutes.get('/ai/budget', requireAuth(), requireApproved(), async (c) => { utilization: { dailyInputPercent: Math.round(dailyInputPercent * 10) / 10, dailyOutputPercent: Math.round(dailyOutputPercent * 10) / 10, - monthlyCostPercent: monthlyCostPercent !== null ? Math.round(monthlyCostPercent * 10) / 10 : null, + monthlyCostPercent: + monthlyCostPercent !== null ? Math.round(monthlyCostPercent * 10) / 10 : null, }, exceeded, }; @@ -330,7 +355,10 @@ usageRoutes.put('/ai/budget', requireAuth(), requireApproved(), async (c) => { try { settings = validateBudgetUpdate(body, c.env, adminAllowance); } catch (err) { - return c.json({ error: 'VALIDATION_ERROR', message: err instanceof Error ? err.message : String(err) }, 400); + return c.json( + { error: 'VALIDATION_ERROR', message: err instanceof Error ? err.message : String(err) }, + 400 + ); } await saveUserBudgetSettings(c.env.KV, userId, settings); diff --git a/apps/api/src/routes/workspaces/runtime-agent-key.ts b/apps/api/src/routes/workspaces/runtime-agent-key.ts index 37bdfd3f8e..93630f6d0d 100644 --- a/apps/api/src/routes/workspaces/runtime-agent-key.ts +++ b/apps/api/src/routes/workspaces/runtime-agent-key.ts @@ -1,42 +1,44 @@ -import { AI_PROXY_DEFAULT_MODEL_KV_KEY, type AIProxyConfig, DEFAULT_AI_PROXY_ANTHROPIC_MODEL, DEFAULT_AI_PROXY_MODEL, DEFAULT_AI_PROXY_OPENAI_MODEL, getAgentDefinition, HARNESS_CAPABILITIES, isValidAgentType, resolveHarnessDialect } from '@simple-agent-manager/shared'; +import { + AI_PROXY_DEFAULT_MODEL_KV_KEY, + type AIProxyConfig, + DEFAULT_AI_PROXY_ANTHROPIC_MODEL, + DEFAULT_AI_PROXY_MODEL, + DEFAULT_AI_PROXY_OPENAI_MODEL, + getAgentDefinition, + HARNESS_CAPABILITIES, + isValidAgentType, + resolveHarnessDialect, +} from '@simple-agent-manager/shared'; import { and, eq } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; -import { type Context, Hono } from 'hono'; - +import { Hono } from 'hono'; import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; - import { getCredentialEncryptionKey } from '../../lib/secrets'; - - import { errors } from '../../middleware/error'; import { AgentTypeBodySchema, jsonValidator } from '../../schemas'; - - import { resolveSessionProfileCredentialContext } from '../../services/composable-credentials/profile-context'; - - - - - - - - - - import { extractScalewaySecretKey } from '../../services/provider-credentials'; - import { refuseHaltedRunAccount } from '../../services/run-agent-configuration'; -import { isAiProxyEnabled, PROXY_ELIGIBLE_AGENTS, requiresExplicitSamProvider } from '../../services/sam-ai-proxy-fallback'; - - +import { + isAiProxyEnabled, + PROXY_ELIGIBLE_AGENTS, + requiresExplicitSamProvider, +} from '../../services/sam-ai-proxy-fallback'; import { getDecryptedAgentKey, getDecryptedCredentialRecord } from '../credentials'; - -import { assertWorkspaceCallbackIdentityCurrent, assertWorkspaceCallbackResourceById, verifyWorkspaceCallbackAuth } from './_helpers'; -import { agentCredentialProviderFallback, credentialAttributionFromData, persistAgentCredentialAttribution, platformProxyAttribution } from './agent-credential-attribution'; - +import { + assertWorkspaceCallbackIdentityCurrent, + assertWorkspaceCallbackResourceById, + verifyWorkspaceCallbackAuth, +} from './_helpers'; +import { + agentCredentialProviderFallback, + credentialAttributionFromData, + persistAgentCredentialAttribution, + platformProxyAttribution, +} from './agent-credential-attribution'; import { callbackJsonWithJit } from './runtime-callback-response'; function getProxyCapability(agentType: string) { const capability = HARNESS_CAPABILITIES.find((entry) => entry.agentType === agentType); @@ -82,7 +84,6 @@ function buildPlatformInferenceConfig(input: { } const runtimeRoutes = new Hono<{ Bindings: Env }>(); -type RuntimeContext = Context<{ Bindings: Env }>; runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async (c) => { const workspaceId = c.req.param('id'); await verifyWorkspaceCallbackAuth(c, workspaceId); @@ -170,7 +171,7 @@ runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async ( } } - if (credentialData && opencodeRequiresDedicatedCredential) { + if (credentialData && !credentialData.baseUrl && opencodeRequiresDedicatedCredential) { const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { workspaceId, agentSessionId: body.agentSessionId, @@ -210,7 +211,7 @@ runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async ( // forwarded via auth headers, wstoken in URL path for analytics/rate-limiting) // Note: platform proxy fallback requires explicit provider selection. // Without it, users with no credential get a 404 (agent not configured). - if (PROXY_ELIGIBLE_AGENTS.has(body.agentType) && isAiProxyEnabled(c.env)) { + if (PROXY_ELIGIBLE_AGENTS.has(body.agentType) && (await isAiProxyEnabled(c.env))) { const baseDomain = c.env.BASE_DOMAIN; const isClaudeCode = body.agentType === 'claude-code'; const isCodex = body.agentType === 'openai-codex'; @@ -425,7 +426,7 @@ runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async ( }); } - if (!credentialData) { + if (!credentialData || credentialData.baseUrl) { throw errors.notFound('Agent credential'); } diff --git a/apps/api/src/routes/workspaces/runtime-callback-response.ts b/apps/api/src/routes/workspaces/runtime-callback-response.ts index 2151e43e38..8ed582ff66 100644 --- a/apps/api/src/routes/workspaces/runtime-callback-response.ts +++ b/apps/api/src/routes/workspaces/runtime-callback-response.ts @@ -1,41 +1,12 @@ - - - import { type Context } from 'hono'; - - import type { Env } from '../../env'; - - - - - - - - - - - - - - - - - - - - - import { assertProviderLimitCredentialPin } from '../../services/provider-limit-credential-pin'; - - import { type WorkspaceDeletionCallbackKind } from '../../services/workspace-deletion-callback-signal'; - - - -import { assertWorkspaceCallbackIdentityCurrent, type WorkspaceCallbackIdentitySnapshot } from './_helpers'; - +import { + assertWorkspaceCallbackIdentityCurrent, + type WorkspaceCallbackIdentitySnapshot, +} from './_helpers'; type RuntimeContext = Context<{ Bindings: Env }>; export async function callbackJsonWithJit>( @@ -58,4 +29,3 @@ export async function callbackJsonWithJit>( ); return c.json(body); } - diff --git a/apps/api/src/routes/workspaces/runtime-git-token.ts b/apps/api/src/routes/workspaces/runtime-git-token.ts index 92370cbcec..ad44193ddd 100644 --- a/apps/api/src/routes/workspaces/runtime-git-token.ts +++ b/apps/api/src/routes/workspaces/runtime-git-token.ts @@ -1,45 +1,32 @@ - import { eq } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; -import { type Context, Hono } from 'hono'; - +import { Hono } from 'hono'; import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; - - - - import { errors } from '../../middleware/error'; - - - - import { getInstallationToken, getUserInstallationRepositories } from '../../services/github-app'; -import { GitHubCliPolicyError, resolveWorkspaceGitHubTokenOptions } from '../../services/github-cli-policy'; +import { + GitHubCliPolicyError, + resolveWorkspaceGitHubTokenOptions, +} from '../../services/github-cli-policy'; import { getExternalInstallationId } from '../../services/github-installation-ids'; import { backfillProjectGithubRepoId } from '../../services/github-repo-id-backfill'; import { getGitHubUserAccessTokenForOwner } from '../../services/github-user-access-token'; -import { getProjectGitLabRepository, requireGitLabUserAccessTokenResultForOwner, verifyGitLabProjectAccess } from '../../services/gitlab'; - - - - - - - - - - - +import { + getProjectGitLabRepository, + requireGitLabUserAccessTokenResultForOwner, + verifyGitLabProjectAccess, +} from '../../services/gitlab'; import { assertRepositoryAccess } from '../projects/_helpers'; -import { assertWorkspaceAcceptsCallback, assertWorkspaceCallbackIdentityCurrent, verifyWorkspaceCallbackAuth } from './_helpers'; - - +import { + assertWorkspaceAcceptsCallback, + assertWorkspaceCallbackIdentityCurrent, + verifyWorkspaceCallbackAuth, +} from './_helpers'; import { callbackJsonWithJit } from './runtime-callback-response'; const runtimeRoutes = new Hono<{ Bindings: Env }>(); -type RuntimeContext = Context<{ Bindings: Env }>; async function verifyWorkspaceGitHubOwnerAccess(input: { env: Env; workspaceId: string; @@ -468,5 +455,4 @@ runtimeRoutes.post('/:id/git-token', async (c) => { }); }); - export { runtimeRoutes as gitTokenRoutes }; diff --git a/apps/api/src/routes/workspaces/runtime-message-helpers.ts b/apps/api/src/routes/workspaces/runtime-message-helpers.ts index ab15e2d7ad..68328c4d8a 100644 --- a/apps/api/src/routes/workspaces/runtime-message-helpers.ts +++ b/apps/api/src/routes/workspaces/runtime-message-helpers.ts @@ -1,4 +1,3 @@ - import { eq } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; import { type Context } from 'hono'; @@ -8,41 +7,25 @@ import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { parsePositiveInt } from '../../lib/route-helpers'; - - - import { errors } from '../../middleware/error'; import { formatIssues, MessageBatchSchema } from '../../schemas'; - - - - - - - - - import { nodeStatusTerminatesCallbacks } from '../../services/node-callback-auth'; import { persistError } from '../../services/observability'; - - - - - - - - - - import { safeParseJson, type WorkspaceCallbackIdentitySnapshot } from './_helpers'; - type RuntimeContext = Context<{ Bindings: Env }>; type MessageBatchBody = v.InferOutput; export const DEFAULT_MAX_MESSAGES_PAYLOAD_BYTES = 256 * 1024; export const DEFAULT_MESSAGE_SIZE_THRESHOLD_BYTES = 102400; export const ACTIVE_MESSAGE_WORKSPACE_STATUSES = new Set(['creating', 'running', 'recovery']); -export const VALID_MESSAGE_ROLES = new Set(['user', 'assistant', 'system', 'tool', 'thinking', 'plan']); +export const VALID_MESSAGE_ROLES = new Set([ + 'user', + 'assistant', + 'system', + 'tool', + 'thinking', + 'plan', +]); export type MessageWorkspace = WorkspaceCallbackIdentitySnapshot & { projectId: string | null; @@ -78,7 +61,10 @@ export function waitUntilIfAvailable( } } -export async function readRequestBodyWithLimit(request: Request, maxBytes: number): Promise { +export async function readRequestBodyWithLimit( + request: Request, + maxBytes: number +): Promise { const contentLengthHeader = request.headers.get('content-length'); if (contentLengthHeader) { const contentLength = Number.parseInt(contentLengthHeader, 10); @@ -307,7 +293,10 @@ export function rejectMessageSessionMismatch( ); } -export function rejectWorkspaceWithoutChatSession(c: RuntimeContext, context: MessageRouteContext): never { +export function rejectWorkspaceWithoutChatSession( + c: RuntimeContext, + context: MessageRouteContext +): never { const logContext = { ...context, providedSessionId: context.sessionId, @@ -373,7 +362,10 @@ export function toProjectDataMessages(body: MessageBatchBody) { })); } -export function sessionLimitReachedResponse(c: RuntimeContext, context: MessageRouteContext): Response { +export function sessionLimitReachedResponse( + c: RuntimeContext, + context: MessageRouteContext +): Response { log.error('message_persistence.session_message_limit_exceeded', { ...context, action: 'rejected_session_message_limit', @@ -469,4 +461,3 @@ export function partialSessionLimitResponse( 409 ); } - diff --git a/apps/api/src/routes/workspaces/runtime-messages.ts b/apps/api/src/routes/workspaces/runtime-messages.ts index f73679bdaa..8c55035262 100644 --- a/apps/api/src/routes/workspaces/runtime-messages.ts +++ b/apps/api/src/routes/workspaces/runtime-messages.ts @@ -1,45 +1,25 @@ import { MESSAGE_OUTBOX_INCARNATION_HEADER } from '@simple-agent-manager/shared'; - - -import { type Context, Hono } from 'hono'; +import { Hono } from 'hono'; import * as v from 'valibot'; - import type { Env } from '../../env'; - - - - - - - - - - - - - - - - - - - import * as projectDataService from '../../services/project-data'; - - - - import { signalWorkspaceDeletionUnconfirmedCallback } from '../../services/workspace-deletion-callback-signal'; - - - import { sameWorkspaceCallbackIdentity, verifyWorkspaceCallbackAuth } from './_helpers'; - - -import { type MessageBatchPersistenceRouteResult, type MessageRouteContext, parseMessageBatchRequest, validateMessageBatch, loadMessageWorkspace, terminalMessagePersistenceResponse, maybeTerminalMessageWorkspaceResponse, assertMessageWorkspaceAcceptsBatch, toProjectDataMessages, handleMessagePersistenceError, partialSessionLimitResponse } from './runtime-message-helpers'; +import { + assertMessageWorkspaceAcceptsBatch, + handleMessagePersistenceError, + loadMessageWorkspace, + maybeTerminalMessageWorkspaceResponse, + type MessageBatchPersistenceRouteResult, + type MessageRouteContext, + parseMessageBatchRequest, + partialSessionLimitResponse, + terminalMessagePersistenceResponse, + toProjectDataMessages, + validateMessageBatch, +} from './runtime-message-helpers'; const runtimeRoutes = new Hono<{ Bindings: Env }>(); -type RuntimeContext = Context<{ Bindings: Env }>; runtimeRoutes.post('/:id/messages', async (c) => { const workspaceId = c.req.param('id'); await verifyWorkspaceCallbackAuth(c, workspaceId); diff --git a/apps/api/src/routes/workspaces/runtime.ts b/apps/api/src/routes/workspaces/runtime.ts index 44e39bb67c..945882ae23 100644 --- a/apps/api/src/routes/workspaces/runtime.ts +++ b/apps/api/src/routes/workspaces/runtime.ts @@ -1,49 +1,33 @@ -import { type BootstrapTokenData, DEFAULT_AGENT_PERMISSION_MODE } from '@simple-agent-manager/shared'; +import { + type BootstrapTokenData, + DEFAULT_AGENT_PERMISSION_MODE, +} from '@simple-agent-manager/shared'; import { and, eq } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; -import { type Context, Hono } from 'hono'; - +import { Hono } from 'hono'; import * as schema from '../../db/schema'; import type { Env } from '../../env'; - - import { getCredentialEncryptionKey } from '../../lib/secrets'; import { ulid } from '../../lib/ulid'; import { requireApproved, requireAuth } from '../../middleware/auth'; - import { AgentTypeBodySchema, BootLogEntrySchema, jsonValidator } from '../../schemas'; import { appendBootLog } from '../../services/boot-log'; import { registerBootstrapTokenConsume } from '../../services/bootstrap'; - - - - - - - - - import { resolveProjectAgentDefault } from '../../services/project-agent-defaults'; - - - - - - import { getWorkspaceRuntimeAssets } from '../../services/workspace-runtime-assets'; - - -import { assertWorkspaceAcceptsCallback, assertWorkspaceCallbackIdentityCurrent, assertWorkspaceCallbackResourceById, verifyWorkspaceCallbackAuth } from './_helpers'; - - -import { callbackJsonWithJit } from './runtime-callback-response'; +import { + assertWorkspaceAcceptsCallback, + assertWorkspaceCallbackIdentityCurrent, + assertWorkspaceCallbackResourceById, + verifyWorkspaceCallbackAuth, +} from './_helpers'; import { agentKeyRoutes } from './runtime-agent-key'; +import { callbackJsonWithJit } from './runtime-callback-response'; import { gitTokenRoutes } from './runtime-git-token'; import { messageRoutes } from './runtime-messages'; export { resolveMaxMessageBytes } from './runtime-message-helpers'; const runtimeRoutes = new Hono<{ Bindings: Env }>(); -type RuntimeContext = Context<{ Bindings: Env }>; runtimeRoutes.route('/', agentKeyRoutes); runtimeRoutes.route('/', gitTokenRoutes); runtimeRoutes.route('/', messageRoutes); diff --git a/apps/api/src/services/admin-setting-definitions.ts b/apps/api/src/services/admin-setting-definitions.ts index 95374fbed7..883d30d026 100644 --- a/apps/api/src/services/admin-setting-definitions.ts +++ b/apps/api/src/services/admin-setting-definitions.ts @@ -12,6 +12,7 @@ import type { NodeTunnelSettingName } from './admin-settings-node-tunnel-definit import { type OutboundSettingName } from './admin-settings-outbound-definitions'; import { type AgentEmailSettingName } from './agent-email/setting-definitions'; import { type AgentModelSettingKey } from './agent-models/settings-definition'; +import type { AiProxySettingName } from './ai-proxy-settings'; import { type ConnectorReadSettingName } from './connector-read-settings-definition'; import { CONNECTOR_DEFAULTS, @@ -21,6 +22,7 @@ import { import { type FleetOpsSettingName } from './fleet-ops/settings-definitions'; import { type InboxSettingName } from './inbox-settings-definition'; import { type LifecycleLatencySettingKey } from './lifecycle-latency/defaults'; +import type { LlmEndpointSettingName } from './llm-endpoint-settings'; import { type OperationsTelemetrySettingName } from './operations-telemetry-defaults'; import { type RuntimeSecretRequestSettingName } from './runtime-secret-request-settings-definition'; import { type WORKFLOW_DEFAULTS } from './workflow-defaults'; @@ -30,6 +32,8 @@ export type AdminSettingValue = boolean | number | string | readonly string[] | export type AdminSettingType = 'boolean' | 'integer' | 'string' | 'string-list' | 'enum'; export type AdminSettingName = + | LlmEndpointSettingName + | AiProxySettingName | DeploymentPublishJobSettingName | 'deployments.publishCallbackMaxBodyBytes' | 'chat.messageMergingEnabled' diff --git a/apps/api/src/services/admin-settings-registry.ts b/apps/api/src/services/admin-settings-registry.ts index f4020df480..c9f3c8aa77 100644 --- a/apps/api/src/services/admin-settings-registry.ts +++ b/apps/api/src/services/admin-settings-registry.ts @@ -10,6 +10,8 @@ import { NODE_TUNNEL_SETTINGS } from './admin-settings-node-tunnel-definitions'; import { OPERATIONS_TELEMETRY_SETTINGS } from './admin-settings-operations-telemetry-definitions'; import { OPERATOR_SETTINGS } from './admin-settings-operator-definitions'; import { OUTBOUND_SETTINGS } from './admin-settings-outbound-definitions'; +import { AI_PROXY_SETTINGS } from './ai-proxy-settings'; +import { llmEndpointSettingDefinitions } from './llm-endpoint-settings'; export { type AdminSettingDefinition, type AdminSettingName, @@ -26,6 +28,8 @@ export { OPERATOR_DEFAULTS, } from './admin-setting-definitions'; const definitions = [ + ...llmEndpointSettingDefinitions(), + ...AI_PROXY_SETTINGS, ...MESSAGE_MERGE_SETTINGS, ...DEPLOYMENT_PUBLISH_SETTINGS, ...CORE_SETTINGS, diff --git a/apps/api/src/services/ai-proxy-availability.ts b/apps/api/src/services/ai-proxy-availability.ts new file mode 100644 index 0000000000..5a9572decd --- /dev/null +++ b/apps/api/src/services/ai-proxy-availability.ts @@ -0,0 +1,11 @@ +import type { Env } from '../env'; +import { resolveAdminSetting } from './admin-settings-resolution'; +import { AI_PROXY_DIRECT_UPSTREAM_SETTING } from './ai-proxy-settings'; +import { resolveAiGatewayId } from './platform-capabilities'; + +/** Call only after authentication at HTTP entry points: absence must not leak config. */ +export async function isAiProxyEnabled(env: Env): Promise { + if (env.AI_PROXY_ENABLED === 'false') return false; + if (resolveAiGatewayId(env)) return true; + return (await resolveAdminSetting(env, AI_PROXY_DIRECT_UPSTREAM_SETTING)) === true; +} diff --git a/apps/api/src/services/ai-proxy-settings.ts b/apps/api/src/services/ai-proxy-settings.ts new file mode 100644 index 0000000000..f7543f6f49 --- /dev/null +++ b/apps/api/src/services/ai-proxy-settings.ts @@ -0,0 +1,23 @@ +/** + * Admin setting for the SAM AI proxy without Cloudflare AI Gateway (`ai-proxy-availability.ts`). + * Kept apart from the resolver so the settings registry imports no resolution code (no cycle). + */ +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_SETTINGS: readonly AdminSettingDefinition[] = [ + { + name: AI_PROXY_DIRECT_UPSTREAM_SETTING, + type: 'boolean', + 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).', + secret: false, + // Lets every approved user spend the platform key. + risky: true, + validate: (value) => typeof value === 'boolean', + }, +]; diff --git a/apps/api/src/services/ai-proxy-shared.ts b/apps/api/src/services/ai-proxy-shared.ts index 8a5e589507..8d0e510016 100644 --- a/apps/api/src/services/ai-proxy-shared.ts +++ b/apps/api/src/services/ai-proxy-shared.ts @@ -14,8 +14,32 @@ export { buildAnthropicCountTokensUrl, buildAnthropicGatewayUrl, buildWorkersAIGatewayUrl, - fetchWorkersAIChatCompletion, isAnthropicModel, readSafeGatewayErrorDiagnostic, WorkersAIGatewayError, } from '@simple-agent-manager/ai-proxy'; + +import { + fetchWorkersAIChatCompletion as fetchCompletion, + LlmUnavailableError, + type WorkersAIChatCompletionOptions, +} from '@simple-agent-manager/ai-proxy'; + +import type { Env } from '../env'; +import { resolveWorkersAiChatTargetWithin } from './llm-chat-target'; +import type { LlmPurpose } from './llm-endpoint-settings'; +/** Bind settings at the worker edge; package keeps the protocol and response parsing. */ +export async function fetchWorkersAIChatCompletion( + env: Env, + options: WorkersAIChatCompletionOptions & { purpose?: LlmPurpose } +) { + const signal = AbortSignal.timeout(options.timeoutMs); + const target = await resolveWorkersAiChatTargetWithin( + env, + options.purpose ?? 'taskTitle', + options.modelId, + options.timeoutMs + ); + if (!target) throw new LlmUnavailableError(options.purpose ?? 'taskTitle'); + return fetchCompletion(env, options, target, signal); +} diff --git a/apps/api/src/services/debug-agent-tools.ts b/apps/api/src/services/debug-agent-tools.ts index 53e2a1f644..3dbd1526dd 100644 --- a/apps/api/src/services/debug-agent-tools.ts +++ b/apps/api/src/services/debug-agent-tools.ts @@ -1,6 +1,5 @@ import type { Env } from '../env'; import { readResponseJson } from '../lib/runtime-validation'; -import { buildWorkersAIGatewayUrl } from './ai-proxy-shared'; import { type ChatMessage, type Completion, @@ -11,6 +10,12 @@ import { } from './debug-agent-common'; import { completionSchema, parseDebugToolArgs } from './debug-agent-parsing'; import { getDiagnosticIncidentByErrorId } from './diagnostic-incidents'; +import { + chatTargetHeaders, + fetchChatTarget, + LlmUnavailableError, + resolveWorkersAiChatTargetWithin, +} from './llm-chat-target'; import { getErrorTrends, getHealthSummary, @@ -196,21 +201,26 @@ export async function complete( const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), config.timeoutMs); try { - const response = await fetch(buildWorkersAIGatewayUrl(env), { + const target = await resolveWorkersAiChatTargetWithin( + env, + 'diagnosis', + config.model, + config.timeoutMs + ); + if (!target) throw new LlmUnavailableError('diagnosis'); + const response = await fetchChatTarget(target, { method: 'POST', signal: controller.signal, - headers: { - Authorization: `Bearer ${env.CF_API_TOKEN}`, - 'Content-Type': 'application/json', + headers: chatTargetHeaders(target, { 'cf-aig-metadata': JSON.stringify({ source: featureKey, modelId: config.model, stream: false, hasTools: true, }), - }, + }), body: JSON.stringify({ - model: config.model, + model: target.model, messages, tools: TOOLS, tool_choice: 'auto', diff --git a/apps/api/src/services/llm-chat-target.ts b/apps/api/src/services/llm-chat-target.ts new file mode 100644 index 0000000000..a85158bf73 --- /dev/null +++ b/apps/api/src/services/llm-chat-target.ts @@ -0,0 +1,122 @@ +/** Worker settings adapter. Protocol targets and guarded fetch live in packages/ai-proxy. */ +import { + type ChatCompletionsTarget, + chatTarget, + LlmUnavailableError, +} from '@simple-agent-manager/ai-proxy'; +import { classifyHost } from '@simple-agent-manager/worker-core'; + +import type { Env } from '../env'; +import { resolveAdminSettingDetailsMany } from './admin-settings-resolution'; +import { DEFAULT_CONFIG_READ_TIMEOUT_MS } from './config-read-deadline'; +import { withDeadline } from './fetch-timeout'; +import { + LLM_PURPOSE_MODEL_SETTING, + type LlmPurpose, + normalizeLlmBaseUrl, +} from './llm-endpoint-settings'; +import { outboundMaxRedirectsValue } from './outbound-fetch-settings'; +import { + hasCloudflareAccountApi, + resolveAiGatewayId, + resolveLlmEndpointCapability, +} from './platform-capabilities'; + +export type { LlmPurpose } from './llm-endpoint-settings'; +export { + type ChatCompletionsTarget, + chatTargetHeaders, + fetchChatTarget, + isCloudflareChatTarget, + LlmUnavailableError, +} from '@simple-agent-manager/ai-proxy'; + +function nonempty(value: unknown): string | null { + return typeof value === 'string' && value.trim() ? value.trim() : null; +} + +/** The capability reads the shared per-isolate settings snapshot, never the key on the default path. */ +export async function resolveOpenAICompatibleTarget( + env: Env, + purpose: LlmPurpose, + requestedModel: string | null = null +): Promise { + if (!(await resolveLlmEndpointCapability(env))) return null; + try { + // Re-read the URL with its key/model under the same mutation generation. + const details = await resolveAdminSettingDetailsMany(env, [ + 'llm.openAICompatible.baseUrl', + 'llm.openAICompatible.apiKey', + 'llm.openAICompatible.model', + LLM_PURPOSE_MODEL_SETTING[purpose], + 'llm.openAICompatible.allowPrivateNetwork', + 'outbound.maxRedirects', + ]); + const [baseUrl, key, fallbackModel, purposeModel, privateNetwork, redirects] = details.map( + (d) => d.value + ); + if (baseUrl === null) return null; // Admin reset the endpoint between the gate and batch. + if (typeof baseUrl !== 'string') throw new LlmUnavailableError(purpose, 'settings_unreadable'); + const model = nonempty(purposeModel) ?? nonempty(fallbackModel) ?? requestedModel; + // An explicitly configured route must never silently fall back to another provider. + if (!model) throw new LlmUnavailableError(purpose, 'not_configured'); + const normalized = normalizeLlmBaseUrl(baseUrl); + if (privateNetwork !== true && classifyHost(new URL(normalized).hostname) === 'private') { + throw new LlmUnavailableError(purpose, 'private_network_not_allowed'); + } + return { + ...chatTarget('openai-compatible', normalized, nonempty(key), model, privateNetwork === true), + maxRedirects: outboundMaxRedirectsValue(redirects), + }; + } catch (err) { + if (err instanceof LlmUnavailableError) throw err; + throw new LlmUnavailableError(purpose, 'settings_unreadable'); + } +} + +export function resolveCloudflareWorkersAiTarget( + env: Pick, + model: string +): ChatCompletionsTarget | null { + const gatewayId = resolveAiGatewayId(env); + if (gatewayId) + return chatTarget( + 'cloudflare-gateway', + `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/workers-ai/v1`, + env.CF_API_TOKEN, + model + ); + if (hasCloudflareAccountApi(env)) + return chatTarget( + 'cloudflare-api', + `https://api.cloudflare.com/client/v4/accounts/${env.CF_ACCOUNT_ID}/ai/v1`, + env.CF_API_TOKEN, + model + ); + return null; +} + +export async function resolveWorkersAiChatTarget(env: Env, purpose: LlmPurpose, model: string) { + return ( + (await resolveOpenAICompatibleTarget(env, purpose, model)) ?? + resolveCloudflareWorkersAiTarget(env, model) + ); +} + +/** Allocate at most a quarter of the caller's budget to settings, preserving time for inference. */ +export async function resolveWorkersAiChatTargetWithin( + env: Env, + purpose: LlmPurpose, + model: string, + timeoutMs: number +) { + try { + return await withDeadline( + () => resolveWorkersAiChatTarget(env, purpose, model), + Math.max(1, Math.min(DEFAULT_CONFIG_READ_TIMEOUT_MS, timeoutMs / 4)) + ); + } catch (err) { + if (err instanceof LlmUnavailableError) throw err; + throw new LlmUnavailableError(purpose, 'settings_unreadable'); + } +} diff --git a/apps/api/src/services/llm-endpoint-settings.ts b/apps/api/src/services/llm-endpoint-settings.ts new file mode 100644 index 0000000000..887cddc3c5 --- /dev/null +++ b/apps/api/src/services/llm-endpoint-settings.ts @@ -0,0 +1,140 @@ +/** + * Admin settings for an OpenAI-compatible endpoint that SAM's own LLM calls can use instead + * of Cloudflare AI Gateway and Workers AI (policy 9017df94: integration settings are + * admin-editable D1 settings, not Worker vars). + * + * Nothing changes until an admin sets `llm.openAICompatible.baseUrl`. The API key is stored + * encrypted in `platform_credentials` like every other secret admin setting. The dependency + * back to the registry is type-only; only the shared secret length floor is imported at runtime. + */ +import { classifyHost } from '@simple-agent-manager/worker-core'; + +import { type AdminSettingDefinition, type AdminSettingName } from './admin-setting-definitions'; + +/** Which control-plane caller is asking; each can use its own model on the endpoint. */ +export type LlmPurpose = 'agent' | 'taskTitle' | 'diagnosis' | 'aiProxy'; + +const LLM_ENDPOINT_SETTING_KEYS = [ + 'baseUrl', + 'apiKey', + 'model', + 'agentModel', + 'taskTitleModel', + 'diagnosisModel', + 'aiProxyModel', + 'allowPrivateNetwork', +] as const; + +type LlmEndpointSettingKey = (typeof LLM_ENDPOINT_SETTING_KEYS)[number]; +export type LlmEndpointSettingName = `llm.openAICompatible.${LlmEndpointSettingKey}`; + +/** Per-purpose model override, falling back to `llm.openAICompatible.model`. */ +export const LLM_PURPOSE_MODEL_SETTING: Readonly> = { + agent: 'llm.openAICompatible.agentModel', + taskTitle: 'llm.openAICompatible.taskTitleModel', + diagnosis: 'llm.openAICompatible.diagnosisModel', + aiProxy: 'llm.openAICompatible.aiProxyModel', +}; + +/** Longest accepted API key. */ +const MAX_API_KEY_LENGTH = 4096; + +/** Longest accepted model id; real ids are far shorter. */ +const MAX_MODEL_ID_LENGTH = 200; + +/** + * An OpenAI-compatible base URL such as `https://llm.example.com/v1`: HTTPS to any host but a + * metadata or link-local one; plain HTTP only to a private-network host, so the API key never + * crosses the internet unencrypted (lib/network-hosts.ts). No credentials, query or fragment: + * SAM appends `/chat/completions` itself. + */ +export function validLlmBaseUrl(value: unknown): boolean { + if (typeof value !== 'string' || value.trim().length === 0 || value.length > 2048) return false; + try { + const url = new URL(value.trim()); + return ( + !url.username && + !url.password && + !url.search && + !url.hash && + classifyHost(url.hostname) !== 'forbidden' && + (url.protocol === 'https:' || + (url.protocol === 'http:' && classifyHost(url.hostname) === 'private')) && + !/\/chat\/completions\/?$/.test(url.pathname) + ); + } catch { + return false; + } +} + +/** Normalized base URL without a trailing slash. Caller must have validated it. */ +export function normalizeLlmBaseUrl(value: string): string { + return value.trim().replace(/\/+$/, ''); +} + +function validModelId(value: unknown): boolean { + return ( + typeof value === 'string' && + value.trim().length > 0 && + value.trim().length <= MAX_MODEL_ID_LENGTH && + !/\s/.test(value.trim()) + ); +} + +const DESCRIPTIONS: Readonly> = { + baseUrl: + "OpenAI-compatible base URL (for example https://llm.example.com/v1) for SAM's own model calls: the SAM agent, project agents, task titles, the diagnosis runner and the AI proxy's Workers AI route. Empty keeps Cloudflare AI Gateway and Workers AI.", + apiKey: 'API key sent as a Bearer token to the OpenAI-compatible endpoint. Optional.', + model: 'Model id used on the OpenAI-compatible endpoint when no purpose-specific model is set.', + agentModel: 'Model id for the SAM agent and project agents on the OpenAI-compatible endpoint.', + taskTitleModel: 'Model id for generated task titles on the OpenAI-compatible endpoint.', + diagnosisModel: 'Model id for the diagnosis runner on the OpenAI-compatible endpoint.', + aiProxyModel: + "Model id that serves the AI proxy's Workers AI route (/ai/v1) on the OpenAI-compatible endpoint.", + allowPrivateNetwork: + 'Let SAM call an endpoint on this machine or its private network (loopback, 10/8, 172.16/12, 192.168/16, a Docker service name), such as a local model server. Off: such a base URL is refused when used. Cloud metadata addresses are refused either way.', +}; + +function definition(key: LlmEndpointSettingKey): AdminSettingDefinition { + const name: AdminSettingName = `llm.openAICompatible.${key}`; + const base = { + name, + type: 'string' as const, + defaultValue: null, + category: 'AI models' as const, + description: DESCRIPTIONS[key], + // Redirecting every control-plane model call is spend- and data-affecting. + risky: key === 'baseUrl' || key === 'apiKey', + }; + if (key === 'allowPrivateNetwork') { + // Reaching the operator's own network is a separate decision from "the URL is HTTP": a base + // URL on a private host is refused at use time unless this is on (llm-chat-target.ts). + return { + ...base, + type: 'boolean', + defaultValue: false, + risky: true, + secret: false, + validate: (value) => typeof value === 'boolean', + }; + } + if (key === 'apiKey') { + return { + ...base, + secret: true, + credential: { provider: 'openai-compatible', kind: 'api-key' }, + // Same floor as the OAuth secrets: a real key is never this short. + validate: (value) => + typeof value === 'string' && value.trim().length >= 8 && value.length <= MAX_API_KEY_LENGTH, + }; + } + return { + ...base, + secret: false, + validate: key === 'baseUrl' ? validLlmBaseUrl : validModelId, + }; +} + +export function llmEndpointSettingDefinitions(): AdminSettingDefinition[] { + return LLM_ENDPOINT_SETTING_KEYS.map(definition); +} diff --git a/apps/api/src/services/outbound-fetch-settings.ts b/apps/api/src/services/outbound-fetch-settings.ts index 21f4fc95e1..74a9c5af17 100644 --- a/apps/api/src/services/outbound-fetch-settings.ts +++ b/apps/api/src/services/outbound-fetch-settings.ts @@ -15,7 +15,7 @@ import { resolveAdminSettingDetailsMany } from './admin-settings-resolution'; const UNREADABLE_SETTING_MAX_REDIRECTS = 0; /** A resolved `outbound.maxRedirects` value, or the default when it is absent or out of range. */ -function outboundMaxRedirectsValue(value: unknown): number { +export function outboundMaxRedirectsValue(value: unknown): number { return typeof value === 'number' && Number.isInteger(value) && value >= 0 && diff --git a/apps/api/src/services/platform-capabilities.ts b/apps/api/src/services/platform-capabilities.ts index d32daf887f..775db811c3 100644 --- a/apps/api/src/services/platform-capabilities.ts +++ b/apps/api/src/services/platform-capabilities.ts @@ -1,3 +1,14 @@ +import { LlmUnavailableError } from '@simple-agent-manager/ai-proxy'; + +import { resolveD1BindingIdentity } from '../lib/d1-session'; +import { cache } from './admin-settings-resolution'; +import { validLlmBaseUrl } from './llm-endpoint-settings'; +export { + aiGatewayOnlyHeaders, + hasCloudflareAccountApi, + isMonthlyCostCapAvailable, + resolveAiGatewayId, +} from '@simple-agent-manager/ai-proxy'; /** * Which platform services this installation actually has. * @@ -65,3 +76,26 @@ export function publicPlatformCapabilities(env: CapabilityEnv): PublicPlatformCa agentModelCalls: capabilities.workersAi, }; } + +/** + * Endpoint capability is the configured base URL itself, from the existing module-scope TTL + * snapshot. Cloudflare's unconfigured path does one snapshot read per isolate TTL, zero key + * reads, and zero additional D1 reads per call. No second cache can outlive admin invalidation. + * Remember configuration across expired snapshots: an outage must not reroute private prompts. + */ +export async function resolveLlmEndpointCapability(env: Env): Promise { + const db = resolveD1BindingIdentity(env.DATABASE); + try { + const rows = await cache.read(db); + const row = rows.find((row) => row.key === 'llm.openAICompatible.baseUrl'); + if (!row) { + return null; + } + const value: unknown = row.value; + if (!validLlmBaseUrl(value)) throw new Error('Invalid endpoint configuration'); + return String(value); + } catch { + // Unknown configuration must not send prompts to a provider the operator may have replaced. + throw new LlmUnavailableError('aiProxy', 'settings_unreadable'); + } +} diff --git a/apps/api/src/services/profile-account-bindings.ts b/apps/api/src/services/profile-account-bindings.ts index 29d21253c4..932b25240e 100644 --- a/apps/api/src/services/profile-account-bindings.ts +++ b/apps/api/src/services/profile-account-bindings.ts @@ -193,7 +193,11 @@ export async function resolveProfileAccountBindings( case 'unknown': return { ...base, state: 'unknown' }; case 'none': - return samProxyFallbackAvailable(env, agentType, providerModes.get(agentType) ?? null) + return (await samProxyFallbackAvailable( + env, + agentType, + providerModes.get(agentType) ?? null + )) ? { ...base, state: 'sam_ai_proxy', poolId: SAM_AI_PROXY_POOL_ID } : { ...base, state: 'none' }; } diff --git a/apps/api/src/services/sam-ai-proxy-fallback.ts b/apps/api/src/services/sam-ai-proxy-fallback.ts index ce86bc2058..99c7b6a53e 100644 --- a/apps/api/src/services/sam-ai-proxy-fallback.ts +++ b/apps/api/src/services/sam-ai-proxy-fallback.ts @@ -15,9 +15,8 @@ export const PROXY_ELIGIBLE_AGENTS: ReadonlySet = new Set( ).map((capability) => capability.agentType) ); -export function isAiProxyEnabled(env: Pick): boolean { - return (env.AI_PROXY_ENABLED ?? 'true') !== 'false'; -} +import { isAiProxyEnabled } from './ai-proxy-availability'; +export { isAiProxyEnabled }; /** * Claude Code and Codex use the platform proxy only after the person explicitly chose SAM as the @@ -31,13 +30,13 @@ export function requiresExplicitSamProvider(agentType: string): boolean { * True when a run of `agentType` with no credential of its own would start on the platform proxy. * OpenCode is proxy-eligible for passthrough but always needs its own key, so it never qualifies. */ -export function samProxyFallbackAvailable( - env: Pick, +export async function samProxyFallbackAvailable( + env: Env, agentType: string, providerMode: string | null -): boolean { +): Promise { return ( - isAiProxyEnabled(env) && + (await isAiProxyEnabled(env)) && PROXY_ELIGIBLE_AGENTS.has(agentType) && requiresExplicitSamProvider(agentType) && providerMode === 'sam' diff --git a/apps/api/src/services/task-title.ts b/apps/api/src/services/task-title.ts index 2d2c2429af..0140a4f52f 100644 --- a/apps/api/src/services/task-title.ts +++ b/apps/api/src/services/task-title.ts @@ -21,7 +21,6 @@ * if Workers AI is slow, retrying immediately wastes more of the Worker's * 30-second wall-clock budget. */ - import { DEFAULT_TASK_TITLE_ERROR_DIAGNOSTIC_MAX_LENGTH, DEFAULT_TASK_TITLE_MAX_LENGTH, @@ -38,6 +37,7 @@ import { import type { Env } from '../env'; import { log } from '../lib/logger'; import { fetchWorkersAIChatCompletion, WorkersAIGatewayError } from './ai-proxy-shared'; +import { LlmUnavailableError } from './llm-chat-target'; /** * Build the system instructions for the title generation agent. @@ -263,6 +263,7 @@ async function fetchTaskTitle( ): Promise { const controls = getTaskTitleModelControls(modelId); return fetchWorkersAIChatCompletion(env, { + purpose: 'taskTitle', modelId, maxTokens: maxLength, timeoutMs, @@ -344,6 +345,7 @@ export async function generateTaskTitle( return truncateTitle(title, maxLength); } catch (err) { + if (err instanceof LlmUnavailableError) return truncateTitle(message, maxLength); const classified = classifyError(err); lastError = classified; diff --git a/apps/api/tests/unit/ai-proxy-passthrough.test.ts b/apps/api/tests/unit/ai-proxy-passthrough.test.ts index d0a48bda45..e79821135f 100644 --- a/apps/api/tests/unit/ai-proxy-passthrough.test.ts +++ b/apps/api/tests/unit/ai-proxy-passthrough.test.ts @@ -1,3 +1,6 @@ +vi.mock('../../src/services/outbound-fetch-settings', () => ({ + resolveOutboundMaxRedirects: async () => 3, +})); /** URL-path-based proxy auth routes and usage tracking. */ import { Hono } from 'hono'; import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -996,3 +999,88 @@ describe('stored configuration with a refused base URL (Anthropic passthrough)', expect(String(mockFetch.mock.calls[0]?.[0])).toContain('https://anthropic-alt.example/'); }); }); + +describe('L12 guarded redirects at every passthrough fetch site', () => { + const cases = [ + ['anthropic messages', ANTHROPIC_MESSAGES_PATH, 'claude-code', 'sk-ant-resolved-key'], + [ + 'anthropic count_tokens', + '/ai/proxy/valid-token/anthropic/v1/messages/count_tokens', + 'claude-code', + 'sk-ant-resolved-key', + ], + ['OpenAI chat', OPENAI_CHAT_COMPLETIONS_PATH, 'openai-codex', 'sk-resolved-openai'], + ] as const; + it.each(cases)( + '%s follows same-origin redirects, retaining the credential only there', + async (_name, path, agentType, key) => { + mockWorkspaceAuth(agentType); + mockAllowedRateLimit(); + mockFetch.mockResolvedValueOnce( + new Response(null, { status: 307, headers: { Location: '/same-origin' } }) + ); + mockSuccessfulFetch('{"choices":[],"usage":{"prompt_tokens":1,"completion_tokens":1}}'); + const response = await postJson(path, { + model: 'test-model', + messages: [{ role: 'user', content: 'private prompt' }], + }); + expect(response.status).toBe(200); + expect(mockFetch).toHaveBeenCalledTimes(2); + const [first, second] = mockFetch.mock.calls as [string, RequestInit][]; + expect(new URL(second[0]).origin).toBe(new URL(first[0]).origin); + expect([...new Headers(second[1].headers).values()].join(' ')).toContain(key); + expect(second[1].body).toBe(first[1].body); + expect(second[1].redirect).toBe('manual'); + } + ); + it.each(cases)( + '%s refuses private/metadata hops and cross-origin body replay', + async (_name, path, agentType) => { + for (const [location, status] of [ + ['http://127.0.0.1/private', 302], + ['https://169.254.169.254/latest/meta-data', 302], + ['https://attacker.example.org/collect', 307], + ] as const) { + mockFetch.mockReset(); + mockWorkspaceAuth(agentType); + mockAllowedRateLimit(); + mockFetch.mockResolvedValueOnce( + new Response(null, { status, headers: { Location: location } }) + ); + const response = await postJson(path, { + model: 'test-model', + messages: [{ role: 'user', content: 'private prompt' }], + }); + expect(response.status).toBe(502); + expect(mockFetch).toHaveBeenCalledTimes(1); + expect(await response.text()).not.toContain('private prompt'); + } + } + ); + it.each(cases)( + '%s strips credential headers on a cross-origin GET redirect', + async (_name, path, agentType, key) => { + mockWorkspaceAuth(agentType); + mockAllowedRateLimit(); + mockFetch.mockResolvedValueOnce( + new Response(null, { + status: 303, + headers: { Location: 'https://other.example.org/result' }, + }) + ); + mockSuccessfulFetch('{"choices":[]}'); + const response = await postJson(path, { + model: 'test-model', + messages: [{ role: 'user', content: 'private prompt' }], + }); + expect(response.status).toBe(200); + expect(mockFetch).toHaveBeenCalledTimes(2); + const [, init] = mockFetch.mock.calls[1] as [string, RequestInit]; + expect(init.method).toBe('GET'); + expect(init.body).toBeUndefined(); + expect(JSON.stringify(init.headers)).not.toContain(key); + expect(new Headers(init.headers).has('Authorization')).toBe(false); + expect(new Headers(init.headers).has('x-api-key')).toBe(false); + } + ); +}); diff --git a/apps/api/tests/unit/config/omitted-worker-var-defaults.test.ts b/apps/api/tests/unit/config/omitted-worker-var-defaults.test.ts index 835514ef5c..eba8ac61be 100644 --- a/apps/api/tests/unit/config/omitted-worker-var-defaults.test.ts +++ b/apps/api/tests/unit/config/omitted-worker-var-defaults.test.ts @@ -339,7 +339,7 @@ const READ_PATHS: readonly ReadPath[] = [ }, { label: 'resolveMaxMessageBytes', - sources: [`${API}/routes/workspaces/runtime.ts`], + sources: [`${API}/routes/workspaces/runtime-message-helpers.ts`], read: (env) => resolveMaxMessageBytes(asEnv(env)), }, { diff --git a/apps/api/tests/unit/durable-objects/agent-loop-metering.test.ts b/apps/api/tests/unit/durable-objects/agent-loop-metering.test.ts index 43345d59e1..a3e35e028e 100644 --- a/apps/api/tests/unit/durable-objects/agent-loop-metering.test.ts +++ b/apps/api/tests/unit/durable-objects/agent-loop-metering.test.ts @@ -1,3 +1,7 @@ +vi.mock('../../../src/services/platform-capabilities', async (original) => ({ + ...(await original()), + resolveLlmEndpointCapability: async () => null, +})); import type { SamConfig } from '@simple-agent-manager/shared'; import { describe, expect, it, vi } from 'vitest'; @@ -31,7 +35,10 @@ function makeEnv(overrides: Partial = {}): Env { } as unknown as Env; } -function createCollectingWriter(): { writer: WritableStreamDefaultWriter; output: string[] } { +function createCollectingWriter(): { + writer: WritableStreamDefaultWriter; + output: string[]; +} { const decoder = new TextDecoder(); const output: string[] = []; const writable = new WritableStream({ @@ -78,7 +85,7 @@ describe('runAgentLoop metering', () => { writer, vi.fn(), undefined, - { systemPrompt: 'system', tools: [], executeTool: async () => ({}) }, + { systemPrompt: 'system', tools: [], executeTool: async () => ({}) } ); await writer.close(); @@ -96,11 +103,21 @@ describe('runAgentLoop metering', () => { storedBudget = JSON.parse(value) as { inputTokens: number; outputTokens: number }; }); const env = makeEnv({ KV: { get: kvGet, put: kvPut } as unknown as KVNamespace }); - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sseResponse([ - JSON.stringify({ choices: [{ delta: { content: 'Hello' }, finish_reason: 'stop' }] }), - JSON.stringify({ choices: [{ delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 7, completion_tokens: 3 } }), - '[DONE]', - ]))); + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue( + sseResponse([ + JSON.stringify({ choices: [{ delta: { content: 'Hello' }, finish_reason: 'stop' }] }), + JSON.stringify({ + choices: [{ delta: {}, finish_reason: 'stop' }], + usage: { prompt_tokens: 7, completion_tokens: 3 }, + }), + '[DONE]', + ]) + ) + ); const waitUntilPromises: Promise[] = []; const { writer, output } = createCollectingWriter(); @@ -115,7 +132,11 @@ describe('runAgentLoop metering', () => { vi.fn(), undefined, { systemPrompt: 'system', tools: [], executeTool: async () => ({}) }, - { waitUntil: (promise) => { waitUntilPromises.push(promise); } }, + { + waitUntil: (promise) => { + waitUntilPromises.push(promise); + }, + } ); await Promise.all(waitUntilPromises); await writer.close(); diff --git a/apps/api/tests/unit/durable-objects/agent-loop-payload-size.test.ts b/apps/api/tests/unit/durable-objects/agent-loop-payload-size.test.ts index 17d33424c5..70c15b030a 100644 --- a/apps/api/tests/unit/durable-objects/agent-loop-payload-size.test.ts +++ b/apps/api/tests/unit/durable-objects/agent-loop-payload-size.test.ts @@ -1,3 +1,7 @@ +vi.mock('../../../src/services/platform-capabilities', async (original) => ({ + ...(await original()), + resolveLlmEndpointCapability: async () => null, +})); /** * Unit tests for agent loop payload size management. * @@ -217,7 +221,9 @@ describe('trimMessagesToFit', () => { const messages = []; for (let i = 0; i < 10; i++) { messages.push({ role: 'user' as const, content: `Question ${i}` }); - messages.push(assistantWithToolCall(`call_${i}`, 'get_session_messages', '{"sessionId":"abc"}')); + messages.push( + assistantWithToolCall(`call_${i}`, 'get_session_messages', '{"sessionId":"abc"}') + ); messages.push(toolResult(`call_${i}`, JSON.stringify({ data: 'x'.repeat(20_000) }))); } messages.push({ role: 'user' as const, content: 'Final question' }); @@ -233,7 +239,9 @@ describe('trimMessagesToFit', () => { const messages = []; for (let i = 0; i < 10; i++) { messages.push({ role: 'user' as const, content: `Question ${i}` }); - messages.push(assistantWithToolCall(`call_${i}`, 'get_session_messages', '{"sessionId":"abc"}')); + messages.push( + assistantWithToolCall(`call_${i}`, 'get_session_messages', '{"sessionId":"abc"}') + ); messages.push(toolResult(`call_${i}`, JSON.stringify({ data: 'x'.repeat(100_000) }))); } messages.push({ role: 'user' as const, content: 'Final question' }); diff --git a/apps/api/tests/unit/routes/ai-proxy-accounting.test.ts b/apps/api/tests/unit/routes/ai-proxy-accounting.test.ts index 1cd3327bc4..4ec1e466a4 100644 --- a/apps/api/tests/unit/routes/ai-proxy-accounting.test.ts +++ b/apps/api/tests/unit/routes/ai-proxy-accounting.test.ts @@ -1,3 +1,7 @@ +vi.mock('../../../src/services/platform-capabilities', async (original) => ({ + ...(await original()), + resolveLlmEndpointCapability: async () => null, +})); import { Hono } from 'hono'; import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -85,6 +89,7 @@ type TestEnv = { KV: { get: ReturnType }; AI_PROXY_ENABLED: string; AI_PROXY_ALLOWED_MODELS?: string; + AI_GATEWAY_ID: string; CF_ACCOUNT_ID: string; CF_API_TOKEN: string; AI_PROXY_REQUEST_BODY_MAX_BYTES?: string; @@ -100,6 +105,7 @@ function makeEnv(overrides: Partial = {}): TestEnv { KV: { get: vi.fn().mockResolvedValue(null) }, AI_PROXY_ENABLED: 'true', AI_PROXY_ALLOWED_MODELS: '@cf/test/model', + AI_GATEWAY_ID: 'gateway', CF_ACCOUNT_ID: 'acct', CF_API_TOKEN: 'cf-token', ...overrides, @@ -378,7 +384,7 @@ describe('OpenAI-compatible AI proxy token accounting', () => { expect(res.status).toBe(200); await res.text(); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; - expect(url).toBe('https://api.openai.com/v1/responses'); + expect(url).toBe('https://gateway.ai.cloudflare.com/v1/acct/gateway/openai/v1/responses'); expect(init.body).toBe(JSON.stringify({ model: 'gpt-4.1', input: 'Say hi' })); expectUsageIncrement(8, 3); }); @@ -413,7 +419,7 @@ describe('OpenAI-compatible AI proxy token accounting', () => { expect(res.status).toBe(200); await res.text(); const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit]; - expect(url).toBe('https://api.openai.com/v1/responses'); + expect(url).toBe('https://gateway.ai.cloudflare.com/v1/acct/gateway/openai/v1/responses'); expect(init.body).toBe(JSON.stringify({ model: 'gpt-6.1-sol', input: 'Use a tool', tools })); expectUsageIncrement(6, 2); }); diff --git a/apps/api/tests/unit/routes/ai-proxy-auth-order.test.ts b/apps/api/tests/unit/routes/ai-proxy-auth-order.test.ts new file mode 100644 index 0000000000..e3e28e880f --- /dev/null +++ b/apps/api/tests/unit/routes/ai-proxy-auth-order.test.ts @@ -0,0 +1,33 @@ +import { Hono } from 'hono'; +import { describe, expect, it, vi } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { aiProxyRoutes } from '../../../src/routes/ai-proxy'; +import { aiProxyAnthropicRoutes } from '../../../src/routes/ai-proxy-anthropic'; + +/** #2674: unauthenticated requests reveal neither the kill switch nor missing gateway state. */ +describe('combined AI routes authenticate before availability', () => { + it.each([ + ['/ai/v1/chat/completions', undefined], + ['/ai/v1/responses', undefined], + ['/ai/v1/chat/completions', 'false'], + ['/ai/v1/responses', 'false'], + ['/ai/anthropic/v1/messages', 'false'], + ['/ai/anthropic/v1/messages/count_tokens', undefined], + ])('%s remains 401 with AI_PROXY_ENABLED=%s and no gateway', async (path, enabled) => { + const app = new Hono<{ Bindings: Env }>(); + app.route('/ai/v1', aiProxyRoutes); + app.route('/ai/anthropic/v1', aiProxyAnthropicRoutes); + const prepare = vi.fn(() => { + throw new Error('Unauthenticated settings access'); + }); + const response = await app.request( + path, + { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }, + { DATABASE: { prepare }, AI_PROXY_ENABLED: enabled } as unknown as Env + ); + expect(response.status).toBe(401); + expect(await response.text()).not.toMatch(/disabled|gateway|directUpstream/i); + expect(prepare).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/tests/unit/runtime-always-proxy.test.ts b/apps/api/tests/unit/runtime-always-proxy.test.ts index efa2540847..6e4e3baa28 100644 --- a/apps/api/tests/unit/runtime-always-proxy.test.ts +++ b/apps/api/tests/unit/runtime-always-proxy.test.ts @@ -239,6 +239,8 @@ const mockEnv = { DATABASE: {} as D1Database, KV: { get: (...args: unknown[]) => mockKvGet(...args), put: vi.fn() }, AI_PROXY_ENABLED: 'true', + AI_GATEWAY_ID: 'gateway', + CF_ACCOUNT_ID: 'account', BASE_DOMAIN: 'example.com', JWT_PUBLIC_KEY: 'key', ENCRYPTION_KEY: 'test-key', @@ -322,6 +324,23 @@ beforeEach(async () => { afterEach(() => attributionSqlite?.close()); describe('runtime.ts always-proxy', () => { + it.each(['claude-code', 'openai-codex', 'opencode'])( + 'returns 404 for unproxied custom-baseURL %s credential, never the key', + async (agentType) => { + mockWorkspaceOnly(); + mockGetDecryptedAgentKey.mockResolvedValueOnce({ + credential: 'custom-private-key', + credentialKind: 'api-key', + credentialSource: 'user', + baseUrl: 'https://custom.example.com/v1', + providerDialect: agentType === 'claude-code' ? 'anthropic' : 'openai-compatible', + }); + const response = await postAgentKey(agentType, { AI_PROXY_ENABLED: 'false' }); + expect(response.status).toBe(404); + expect(await response.text()).not.toContain('custom-private-key'); + } + ); + it('authenticates message persistence before reading or validating the JSON body', async () => { const authError = Object.assign(new Error('Unauthorized'), { statusCode: 401, diff --git a/apps/api/tests/unit/services/configurable-limits.test.ts b/apps/api/tests/unit/services/configurable-limits.test.ts index 0e701a4257..8ec66f9337 100644 --- a/apps/api/tests/unit/services/configurable-limits.test.ts +++ b/apps/api/tests/unit/services/configurable-limits.test.ts @@ -278,10 +278,9 @@ describe('task submit — configurable MAX_TASK_MESSAGE_LENGTH', () => { // ============================================================================= describe('workspace messages — configurable MAX_MESSAGES_PER_BATCH', () => { - const runtimeSource = readFileSync( - resolve(process.cwd(), 'src/routes/workspaces/runtime.ts'), - 'utf8' - ); + const runtimeSource = ['runtime-message-helpers.ts', 'runtime-messages.ts'] + .map((file) => readFileSync(resolve(process.cwd(), 'src/routes/workspaces', file), 'utf8')) + .join('\n'); it('reads batch limit from MAX_MESSAGES_PER_BATCH env var', () => { expect(runtimeSource).toContain('env.MAX_MESSAGES_PER_BATCH'); @@ -306,10 +305,9 @@ describe('workspace messages — configurable MAX_MESSAGES_PER_BATCH', () => { // ============================================================================= describe('workspace messages — configurable MAX_MESSAGES_PAYLOAD_BYTES', () => { - const runtimeSource = readFileSync( - resolve(process.cwd(), 'src/routes/workspaces/runtime.ts'), - 'utf8' - ); + const runtimeSource = ['runtime-message-helpers.ts', 'runtime-messages.ts'] + .map((file) => readFileSync(resolve(process.cwd(), 'src/routes/workspaces', file), 'utf8')) + .join('\n'); it('reads payload size limit from MAX_MESSAGES_PAYLOAD_BYTES env var', () => { expect(runtimeSource).toContain('c.env.MAX_MESSAGES_PAYLOAD_BYTES'); diff --git a/apps/api/tests/unit/services/llm-endpoint.test.ts b/apps/api/tests/unit/services/llm-endpoint.test.ts new file mode 100644 index 0000000000..bd47f00448 --- /dev/null +++ b/apps/api/tests/unit/services/llm-endpoint.test.ts @@ -0,0 +1,291 @@ +import * as capabilities from '../../../src/services/platform-capabilities'; +import { resolveOperatorModel } from '../../../src/durable-objects/sam-session/operator/model'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { createRequestScopedD1 } from '../../../src/lib/d1-session'; +import { forwardToWorkersAI } from '../../../src/routes/ai-proxy-upstream'; +import { + __resetAdminSettingsCacheForTest, + invalidateAdminSettings, + updateAdminSettings, +} from '../../../src/services/admin-settings'; +import { isAiProxyEnabled } from '../../../src/services/ai-proxy-availability'; +import { fetchWorkersAIChatCompletion } from '../../../src/services/ai-proxy-shared'; +import { complete } from '../../../src/services/debug-agent-tools'; +import { resolveOpenAICompatibleTarget } from '../../../src/services/llm-chat-target'; +import { createAdminSettingsEnv } from '../../helpers/admin-settings-env'; + +let fixture: ReturnType; +let env: Env; +let calls: string[]; +let fetchMock: ReturnType; +beforeEach(() => { + fixture = createAdminSettingsEnv({ + AI_GATEWAY_ID: 'gateway', + CF_ACCOUNT_ID: 'account', + CF_API_TOKEN: 'cf-secret', + }); + env = fixture.env; + calls = []; + const original = env.DATABASE.prepare.bind(env.DATABASE); + vi.spyOn(env.DATABASE, 'prepare').mockImplementation((sql) => { + calls.push(sql); + return original(sql); + }); + fetchMock = vi.fn( + async () => + new Response(JSON.stringify({ choices: [{ message: { content: 'Working title' } }] }), { + headers: { 'Content-Type': 'application/json' }, + }) + ); + vi.stubGlobal('fetch', fetchMock); + __resetAdminSettingsCacheForTest(); +}); +afterEach(() => { + fixture.sqlite.close(); + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +async function configure(baseUrl = 'https://llm.example.com/v1') { + await updateAdminSettings(env, { + actorUserId: 'admin', + changes: [ + { name: 'llm.openAICompatible.baseUrl', value: baseUrl }, + { name: 'llm.openAICompatible.model', value: 'operator-model' }, + { name: 'llm.openAICompatible.apiKey', value: 'endpoint-secret' }, + ], + }); +} + +describe('L12 endpoint routing through real settings storage/cache', () => { + it('keeps URL and key from one generation when admin rotates between capability and settings reads', async () => { + await configure(); + let release!: () => void, entered!: () => void; + const paused = new Promise((resolve) => { + release = resolve; + }); + const ready = new Promise((resolve) => { + entered = resolve; + }); + const original = capabilities.resolveLlmEndpointCapability; + const gate = vi + .spyOn(capabilities, 'resolveLlmEndpointCapability') + .mockImplementationOnce(async (env) => { + const old = await original(env); + entered(); + await paused; + return old; + }); + const pending = resolveOpenAICompatibleTarget(env, 'agent', 'model'); + await ready; + await updateAdminSettings(env, { + actorUserId: 'admin', + changes: [ + { name: 'llm.openAICompatible.baseUrl', value: 'https://new-endpoint.example.org/v1' }, + { name: 'llm.openAICompatible.apiKey', value: 'new-endpoint-secret' }, + ], + }); + release(); + expect(await pending).toMatchObject({ + baseUrl: 'https://new-endpoint.example.org/v1', + apiKey: 'new-endpoint-secret', + }); + gate.mockRestore(); + }); + + it('routes the real SAM operator AI SDK model through the guarded endpoint fetch', async () => { + await configure(); + fetchMock.mockResolvedValueOnce( + new Response( + JSON.stringify({ + id: 'reply', + created: 1, + model: 'operator-model', + choices: [ + { index: 0, finish_reason: 'stop', message: { role: 'assistant', content: 'Hello' } }, + ], + usage: { prompt_tokens: 2, completion_tokens: 1 }, + }), + { headers: { 'Content-Type': 'application/json' } } + ) + ); + const model = await resolveOperatorModel(env, 'claude-original', { + metadata: 'private-user', + sessionAffinity: 'private-session', + }); + if ( + typeof model !== 'object' || + model === null || + !('doGenerate' in model) || + typeof model.doGenerate !== 'function' + ) + throw new Error('Expected SDK language model'); + await model.doGenerate({ + prompt: [{ role: 'user', content: [{ type: 'text', text: 'Hello' }] }], + maxOutputTokens: 16, + }); + const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; + expect(url).toBe('https://llm.example.com/v1/chat/completions'); + expect(JSON.parse(String(init.body))).toMatchObject({ model: 'operator-model' }); + expect(new Headers(init.headers).get('Authorization')).toBe('Bearer endpoint-secret'); + expect(new Headers(init.headers).get('cf-aig-metadata')).toBeNull(); + expect(new Headers(init.headers).get('x-session-affinity')).toBeNull(); + expect(init.redirect).toBe('manual'); + }); + + it('unconfigured Cloudflare calls read settings once per isolate TTL, never credentials, across request facades', async () => { + vi.useFakeTimers(); + const call = async () => { + const database = createRequestScopedD1(env.DATABASE); + await fetchWorkersAIChatCompletion( + { ...env, DATABASE: database }, + { + modelId: '@cf/test/model', + maxTokens: 64, + timeoutMs: 5000, + messages: [{ role: 'user', content: 'title' }], + metadata: {}, + responseLabel: 'test', + } + ); + }; + await Promise.all(Array.from({ length: 20 }, call)); + for (let i = 0; i < 10; i++) await call(); + expect(fetchMock).toHaveBeenCalledTimes(30); + expect(calls.filter((sql) => sql.includes('FROM platform_settings'))).toHaveLength(1); + expect(calls.filter((sql) => sql.includes('platform_credentials'))).toHaveLength(0); + await vi.advanceTimersByTimeAsync(60_001); + await call(); + expect(calls.filter((sql) => sql.includes('FROM platform_settings'))).toHaveLength(2); + }); + + it('real admin writer stores raw URL and per-purpose model; endpoint overrides Workers AI without metadata leakage', async () => { + await configure(); + await updateAdminSettings(env, { + actorUserId: 'admin', + changes: [{ name: 'llm.openAICompatible.taskTitleModel', value: 'title-model' }], + }); + calls.length = 0; + await fetchWorkersAIChatCompletion(env, { + purpose: 'taskTitle', + modelId: '@cf/model', + maxTokens: 64, + timeoutMs: 5000, + reasoningEffort: 'low', + chatTemplateKwargs: { enable_thinking: false }, + messages: [{ role: 'user', content: 'hello' }], + metadata: { userId: 'private-user' }, + responseLabel: 'title', + }); + const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; + expect(url).toBe('https://llm.example.com/v1/chat/completions'); + expect(new Headers(init.headers).get('Authorization')).toBe('Bearer endpoint-secret'); + expect(new Headers(init.headers).get('cf-aig-metadata')).toBeNull(); + expect(JSON.parse(String(init.body))).toMatchObject({ + model: 'title-model', + messages: [{ role: 'user', content: 'hello' }], + }); + expect(JSON.parse(String(init.body))).not.toHaveProperty('reasoning_effort'); + expect(JSON.parse(String(init.body))).not.toHaveProperty('chat_template_kwargs'); + expect(calls.filter((sql) => sql.includes('platform_credentials'))).toHaveLength(1); + await resolveOpenAICompatibleTarget(env, 'agent', 'claude-original'); + expect(calls.filter((sql) => sql.includes('platform_credentials'))).toHaveLength(1); + await updateAdminSettings(env, { + actorUserId: 'admin', + changes: [{ name: 'llm.openAICompatible.baseUrl', value: null }], + }); + expect(await resolveOpenAICompatibleTarget(env, 'agent', 'claude-original')).toBeNull(); + }); + + it('configured snapshot failure returns 503 without rerouting, including a cold isolate', async () => { + await configure(); + expect(await resolveOpenAICompatibleTarget(env, 'agent', 'claude-original')).toMatchObject({ + model: 'operator-model', + }); + __resetAdminSettingsCacheForTest(); + vi.spyOn(env.DATABASE, 'prepare').mockImplementation(() => { + throw new Error('database unavailable'); + }); + const result = await forwardToWorkersAI(env, { messages: [] }, '@cf/model', '{}'); + expect(result.status).toBe(503); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('refuses a private endpoint until the admin opts in, including redirects', async () => { + await configure('http://127.0.0.1:1234/v1'); + await expect( + resolveOpenAICompatibleTarget(env, 'taskTitle', '@cf/model') + ).rejects.toMatchObject({ reason: 'private_network_not_allowed' }); + expect(fetchMock).not.toHaveBeenCalled(); + await updateAdminSettings(env, { + actorUserId: 'admin', + changes: [{ name: 'llm.openAICompatible.allowPrivateNetwork', value: true }], + }); + expect(await resolveOpenAICompatibleTarget(env, 'agent', 'model')).toMatchObject({ + allowPrivateNetwork: true, + }); + }); + + it('preserves caller include_usage false and never forces it on', async () => { + await configure(); + await forwardToWorkersAI( + env, + { stream: true, stream_options: { include_usage: false } }, + '@cf/model', + 'secret-metadata' + ); + expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({ + stream_options: { include_usage: false }, + }); + }); + + it.each(['title', 'diagnosis'])( + '%s settings lookup uses at most one quarter of inference budget', + async (purpose) => { + vi.useFakeTimers(); + const statement = { all: () => new Promise(() => {}) }; + vi.spyOn(env.DATABASE, 'prepare').mockReturnValue(statement as never); + invalidateAdminSettings(env); + const options = { + modelId: '@cf/model', + maxTokens: 32, + timeoutMs: 400, + messages: [{ role: 'user' as const, content: 'hello' }], + metadata: {}, + responseLabel: 'title', + }; + const promise = + purpose === 'title' + ? fetchWorkersAIChatCompletion(env, options) + : complete( + env, + { model: '@cf/model', timeoutMs: 400 } as never, + 'diagnosis', + [{ role: 'user', content: 'hello' }], + 32 + ); + const assertion = expect(promise).rejects.toMatchObject({ reason: 'settings_unreadable' }); + await vi.advanceTimersByTimeAsync(101); + await assertion; + expect(fetchMock).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(5000); + } + ); +}); + +describe('L11 gateway condition vs ambient gateway ID', () => { + it('complete gateway config is available without settings reads; ID alone is not availability', async () => { + expect(await isAiProxyEnabled(env)).toBe(true); + expect(calls).toHaveLength(0); + const noAccount = { ...env, CF_ACCOUNT_ID: '' }; + expect(await isAiProxyEnabled(noAccount)).toBe(false); + await updateAdminSettings(env, { + actorUserId: 'admin', + changes: [{ name: 'aiProxy.directUpstreamEnabled', value: true }], + }); + expect(await isAiProxyEnabled(noAccount)).toBe(true); + expect(await isAiProxyEnabled({ ...noAccount, AI_PROXY_ENABLED: 'false' })).toBe(false); + }); +}); diff --git a/apps/api/tests/unit/services/task-title.test.ts b/apps/api/tests/unit/services/task-title.test.ts index 6624326f51..8a45c9bf66 100644 --- a/apps/api/tests/unit/services/task-title.test.ts +++ b/apps/api/tests/unit/services/task-title.test.ts @@ -1,3 +1,7 @@ +vi.mock('../../../src/services/platform-capabilities', async (original) => ({ + ...(await original()), + resolveLlmEndpointCapability: async () => null, +})); import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; diff --git a/apps/api/tests/unit/task-runner-do-service.test.ts b/apps/api/tests/unit/task-runner-do-service.test.ts index c7737aa4e3..40cc1bea96 100644 --- a/apps/api/tests/unit/task-runner-do-service.test.ts +++ b/apps/api/tests/unit/task-runner-do-service.test.ts @@ -27,6 +27,11 @@ const taskRunsSource = readFileSync(resolve(process.cwd(), 'src/routes/tasks/run const workspacesSource = [ readFileSync(resolve(process.cwd(), 'src/routes/workspaces/lifecycle.ts'), 'utf8'), readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime.ts'), 'utf8'), + readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime-agent-key.ts'), 'utf8'), + readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime-git-token.ts'), 'utf8'), + readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime-message-helpers.ts'), 'utf8'), + readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime-messages.ts'), 'utf8'), + readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime-callback-response.ts'), 'utf8'), ].join('\n'); const stuckTasksSource = readFileSync( resolve(process.cwd(), 'src/scheduled/stuck-tasks.ts'), diff --git a/apps/api/tests/unit/workspace-lifecycle.test.ts b/apps/api/tests/unit/workspace-lifecycle.test.ts index 0d6f48800b..60064c9352 100644 --- a/apps/api/tests/unit/workspace-lifecycle.test.ts +++ b/apps/api/tests/unit/workspace-lifecycle.test.ts @@ -81,6 +81,11 @@ const doSource = [ const routeSource = [ readFileSync(resolve(process.cwd(), 'src/routes/workspaces/lifecycle.ts'), 'utf8'), readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime.ts'), 'utf8'), + readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime-agent-key.ts'), 'utf8'), + readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime-git-token.ts'), 'utf8'), + readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime-message-helpers.ts'), 'utf8'), + readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime-messages.ts'), 'utf8'), + readFileSync(resolve(process.cwd(), 'src/routes/workspaces/runtime-callback-response.ts'), 'utf8'), ].join('\n'); // ============================================================================ diff --git a/apps/www/src/content/docs/docs/guides/admin-settings.md b/apps/www/src/content/docs/docs/guides/admin-settings.md index df06f484e2..9ef0c06d7f 100644 --- a/apps/www/src/content/docs/docs/guides/admin-settings.md +++ b/apps/www/src/content/docs/docs/guides/admin-settings.md @@ -316,16 +316,16 @@ given, and its reminders follow the current percentages. Listed under **Chat**. Bounds for the [run receipt](/docs/reference/api/#get-apiprojectsprojectidtaskstaskidreceipt) (`packages/operations/src/insights-receipt-settings-definition.ts`). -| Setting | Default | Range | What it limits | -| ---------------------------------------- | ------- | ----------- | ---------------------------------------------------------------------------------- | -| `insights.receiptMessageScanMaxRows` | 10,000 | 100–100,000 | Chat messages one receipt reads to count tool calls; a longer run shows a floor | -| `insights.receiptWaitingMaxQuestions` | 200 | 10–2,000 | Agent questions one receipt reads to measure time waiting on a person | -| `insights.receiptComparisonRuns` | 50 | 3–500 | Recent runs of the same skill or profile read to find the usual durations | -| `insights.receiptComparisonWindowDays` | 30 | 1–365 | Days back the receipt looks for runs to compare with | -| `insights.receiptComparisonMinRuns` | 3 | 1–50 | Fewest comparable runs before a duration is called slower than usual | -| `insights.receiptSlowFactorPercent` | 150 | 101–1,000 | Percentage of the usual duration at which a phase is listed as slow | -| `insights.receiptSlowMinSeconds` | 60 | 0–3,600 | Phases shorter than this are never listed as slowing a run down | -| `insights.receiptMemoryNearLimitPercent` | 90 | 50–100 | Peak memory at or above this share of the requested memory is listed as a slowdown | +| Setting | Default | Range | What it limits | +| ---------------------------------------- | ------- | ----------- | ---------------------------------------------------------------------------------------- | +| `insights.receiptMessageScanMaxRows` | 10,000 | 100–100,000 | Chat messages one receipt reads to count tool calls; a longer run shows a floor | +| `insights.receiptWaitingMaxQuestions` | 200 | 10–2,000 | Agent questions one receipt reads to measure time waiting on a person | +| `insights.receiptComparisonRuns` | 50 | 3–500 | Recent runs of the same skill or profile read to find the usual durations | +| `insights.receiptComparisonWindowDays` | 30 | 1–365 | Days back the receipt looks for runs to compare with | +| `insights.receiptComparisonMinRuns` | 3 | 1–50 | Fewest comparable runs before a duration is called slower than usual | +| `insights.receiptSlowFactorPercent` | 150 | 101–1,000 | Percentage of the usual duration at which a phase is listed as slow | +| `insights.receiptSlowMinSeconds` | 60 | 0–3,600 | Phases shorter than this are never listed as slowing a run down | +| `insights.receiptMemoryNearLimitPercent` | 90 | 50–100 | Peak memory at or above this share of the requested memory is listed as a slowdown | | `insights.receiptTokenRowsMax` | 64 | 8–1,000 | Token-usage rows (model × account × agent restart) one receipt reads; more shows a floor | ## Insights page @@ -1001,3 +1001,16 @@ bootstrap default. Bootstrap cannot depend on reading its own D1 override. Once available, the runtime deadline governs legacy platform configuration and session reads. Pending cache loads expire on deadline; late results cannot republish stale data. No deployment configuration is required. + +## Use an OpenAI-compatible model server + +Under **AI models**, set `llm.openAICompatible.baseUrl`, the model ID and optional API key. +The endpoint replaces Workers AI chat calls and the SAM agent's model route. Purpose-specific +model settings are available for agents, titles, diagnosis and the Workers AI proxy route. +Private hosts require the separate `allowPrivateNetwork` confirmation; metadata hosts are always +refused. Reset the base URL to restore normal routing. See the +[endpoint configuration reference](/docs/reference/configuration/#openai-compatible-model-endpoint) +for all keys, budgets, proxy availability and accounting limits. + + diff --git a/apps/www/src/content/docs/docs/reference/configuration.md b/apps/www/src/content/docs/docs/reference/configuration.md index c64cf13815..6f926e6507 100644 --- a/apps/www/src/content/docs/docs/reference/configuration.md +++ b/apps/www/src/content/docs/docs/reference/configuration.md @@ -59,7 +59,7 @@ These are Cloudflare Worker secrets, set during deployment. Pulumi auto-generate | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ENCRYPTION_KEY` | AES-256-GCM master key. Used for BetterAuth session cookies and user credential encryption unless a purpose-specific override below is set (auto-generated) | | `BETTER_AUTH_SECRET` | Optional purpose-specific override for BetterAuth session cookie signing/encryption. Falls back to `ENCRYPTION_KEY` when unset (`apps/api/src/lib/secrets.ts`) | -| `BOOTSTRAP_OWNER_EMAIL` | Optional installer-managed Worker secret restricting first administration to this verified login email. Unset preserves manual-install behavior. Set before enabling login; preserve across updates. Also the recovery path when no superadmin remains (self-hosting guide). | +| `BOOTSTRAP_OWNER_EMAIL` | Optional installer-managed Worker secret restricting first administration to this verified login email. Unset preserves manual-install behavior. Set before enabling login; preserve across updates. Also the recovery path when no superadmin remains (self-hosting guide). | | `CREDENTIAL_ENCRYPTION_KEY` | Optional purpose-specific override for AES-GCM encryption of user cloud/agent credentials. Falls back to `ENCRYPTION_KEY` when unset (`apps/api/src/lib/secrets.ts`) | | `JWT_PRIVATE_KEY` | RSA-2048 private key for signing tokens (auto-generated) | | `JWT_PUBLIC_KEY` | RSA-2048 public key for token verification (exposed via JWKS) | @@ -595,12 +595,12 @@ unauthenticated `/api/config/*` endpoints are marked `public`. Endpoints returni Direct node allocation and workspace creation use isolated NodeLifecycle Durable Object instances. These optional Worker runtime overrides accept positive integers; invalid or unset values use the defaults. -| Variable | Default | Description | -| -------------------------------------- | ----------------- | ---------------------------------------------------------------------------------------------------- | +| Variable | Default | Description | +| -------------------------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `NODE_PROVISIONING_REQUEST_TIMEOUT_MS` | `5000` (5 s) | Per-request budget for Cloudflare calls during allocation/reconciliation, also used for background readiness and workspace dispatch. The attempt's cancellation budget is the admin setting `operations.nodeProvisioningAttemptDeadlineMs` (default 60 s, never below this value). It cuts only the steps before a provider create starts and the node DNS record; a started create, the publish of its result, and the later readiness and workspace dispatch are not bounded by it, so an attempt can run longer than 60 s. | -| `NODE_PROVISIONING_RETRY_INTERVAL_MS` | `30000` (30 s) | Delay between durable provisioning attempts. | -| `NODE_PROVISIONING_MAX_AGE_MS` | `900000` (15 min) | Maximum provisioning intent age before retries stop. | -| `NODE_PROVISIONING_MAX_ATTEMPTS` | `30` | Maximum provisioning attempts before retries stop. | +| `NODE_PROVISIONING_RETRY_INTERVAL_MS` | `30000` (30 s) | Delay between durable provisioning attempts. | +| `NODE_PROVISIONING_MAX_AGE_MS` | `900000` (15 min) | Maximum provisioning intent age before retries stop. | +| `NODE_PROVISIONING_MAX_ATTEMPTS` | `30` | Maximum provisioning attempts before retries stop. | Reaching either the age or attempt limit stops allocation retries. Diagnostic publication then uses a separate retry budget with the same interval and attempt limit; the age limit applies only to allocation and reconciliation. The unresolved intent is retained for inspection. Empty provider inventory does not authorize another provider create request or establish cleanup proof. @@ -656,7 +656,7 @@ the saved snapshot and conversation for recovery on a fresh node. | `NODE_UNHEALTHY_PRESERVATION_TIMEOUT_MS` | `5000` (5 sec) | Per-node budget for attempting chat notices and sleep requests before cleanup proceeds. | | `NODE_UNHEALTHY_RETRY_MS` | `60000` (1 min) | Retry delay after provider deletion of an unhealthy node fails. | | `NODE_STOPPED_HANDOFF_SWEEP_BUDGET_MS` | `20000` (20 sec) | Wall-clock budget for each of the stopped-node handoff, destroying-node handoff, provider-deletion confirm and stranded-node retirement phases. Candidates not started within the budget remain eligible for the next sweep; handoff candidates rotate, so a page of failing candidates cannot hold the head of every sweep. | -| `NODE_STOPPED_HANDOFF_REQUEST_TIMEOUT_MS` | `5000` (5 sec) | Per-candidate provider/DNS deadline for unhealthy-node release, deployment-node cleanup and provider orphan reconciliation, capped by remaining sweep time (provider orphan reconciliation instead gives each phase the full deadline and starts no candidate after the sweep budget). Stopped/destroying handoff and stranded-node retirement use the admin setting `operations.nodeProviderDeletionRequestTimeoutMs` instead (see [Admin settings](/docs/guides/admin-settings/#provider-deletion-in-the-cleanup-cron)). Provider failures enter cleanup backoff. | +| `NODE_STOPPED_HANDOFF_REQUEST_TIMEOUT_MS` | `5000` (5 sec) | Per-candidate provider/DNS deadline for unhealthy-node release, deployment-node cleanup and provider orphan reconciliation, capped by remaining sweep time (provider orphan reconciliation instead gives each phase the full deadline and starts no candidate after the sweep budget). Stopped/destroying handoff and stranded-node retirement use the admin setting `operations.nodeProviderDeletionRequestTimeoutMs` instead (see [Admin settings](/docs/guides/admin-settings/#provider-deletion-in-the-cleanup-cron)). Provider failures enter cleanup backoff. | | `WORKSPACE_CLEANUP_SWEEP_LIMIT` | `50` | Max workspace candidates processed per cleanup phase per cron run. | | `NODE_AGENT_BACKGROUND_REQUEST_TIMEOUT_MS` | `5000` (5 s) | VM-agent request timeout for background sweeps. Deliberately far below the interactive `NODE_AGENT_REQUEST_TIMEOUT_MS` (30 s) so a sweep over unreachable nodes cannot exhaust the Worker's wall-clock budget. | | `WORKSPACE_DELETION_RETRY_BASE_MS` | `60000` (1 min) | Initial retry delay after a VM workspace deletion remains unconfirmed. | @@ -1096,7 +1096,7 @@ ProjectData stores a single prompt-delivery queue and checkpoint episodes keyed | `TASK_RUNNER_STEP_MAX_RETRIES` | `3` | Max retries per TaskRunner step before failing the task | | `TASK_RUNNER_RETRY_BASE_DELAY_MS` | `5000` | Base delay for TaskRunner retry backoff | | `TASK_RUNNER_RETRY_MAX_DELAY_MS` | `60000` | Maximum delay for TaskRunner retry backoff | -| `TASK_RUNNER_AGENT_POLL_INTERVAL_MS` | `5000` | TaskRunner D1 poll interval while waiting for a newly provisioned or explicitly pinned booting VM agent | +| `TASK_RUNNER_AGENT_POLL_INTERVAL_MS` | `5000` | TaskRunner D1 poll interval while waiting for a newly provisioned or explicitly pinned booting VM agent | | `TASK_RUNNER_AGENT_READY_TIMEOUT_MS` | `900000` (15 min) | TaskRunner max wait for a provisioned VM agent before failing the task | | `TASK_RUNNER_AGENT_READY_FRESHNESS_SKEW_MS` | `30000` | Timestamp skew tolerated between TaskRunner wait start, node heartbeat, and `/ready` signals | | `TASK_RUNNER_WORKSPACE_DISPATCH_TIMEOUT_MS` | `600000` (10 min) | Max wait for VM-agent workspace dispatch acknowledgement | @@ -1236,141 +1236,141 @@ An out-of-range weight makes the unit fail to load, which would take the slice h ## Durable Object Limits -| Variable | Default | Description | -| ---------------------------------------------------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `MAX_SESSIONS_PER_PROJECT` | `10000` | Max chat sessions per project | -| `MAX_MESSAGES_PER_SESSION` | `100000` | Max messages per chat session | -| `COMMENT_BODY_MAX_LENGTH` | `8000` | Max characters per message-anchored comment or reply body | -| `COMMENT_QUOTE_MAX_LENGTH` | `2000` | Max characters preserved from quoted message text | -| `COMMENT_IDEMPOTENCY_KEY_MAX_LENGTH` | `200` | Max `clientMutationId` length for message-anchored comment writes | -| `COMMENT_LIST_LIMIT_DEFAULT` | `100` | Default page size for comment thread lists | -| `COMMENT_LIST_LIMIT_MAX` | `500` | Max page size for comment thread lists | -| `COMMENT_THREADS_PER_SESSION_MAX` | `1000` | Max message-anchored comment threads per chat session | -| `COMMENT_REPLIES_PER_THREAD_MAX` | `200` | Max replies per message-anchored comment thread | -| `PROJECT_COMMENT_LIST_LIMIT` | `100` | Page size for the project-wide comment inbox | -| `PROJECT_COMMENT_LIST_MAX` | `300` | Max page size for the project-wide comment inbox | -| `PROJECT_COMMENT_LIST_MAX_BYTES` | `4000000` | Byte budget for one project-wide comment inbox response, so a few very long threads cannot exhaust the Durable Object RPC limit | -| `DOCUMENT_CARD_RAW_OUTPUT_MAX_BYTES` | `16384` | Max compact metadata bytes preserved for library document cards | -| `PROJECT_DATA_TOOL_METADATA_MAX_BYTES` | `131072` | Max stored `tool_metadata` bytes per message before oversized tool content is stripped into bounded metadata | -| `PROJECT_DATA_STORAGE_TELEMETRY_ENABLED` | `true` | Enables ProjectData `databaseSize` alarm measurement and D1 telemetry writes | -| `PROJECT_DATA_STORAGE_LIMIT_BYTES` | `10000000000` | Cloudflare SQLite-backed Durable Object storage limit used for ProjectData usage classification | -| `PROJECT_DATA_STORAGE_MEASURE_INTERVAL_MS` | `3600000` | Interval between full per-object ProjectData storage measurements. Each one appends a telemetry history row and evaluates the storage alerts; cleanup passes publish the latest size but never postpone it (`measureAndPersistProjectDataStorage`) | -| `PROJECT_DATA_STORAGE_ALERT_INTERVAL_MS` | `21600000` | Minimum interval between repeated ProjectData storage observability alerts of the same kind and status. Threshold (warning/critical/degraded) and cleanup-target-unreachable alerts are throttled separately (`maybePersistProjectDataStorageAlert`) | -| `PROJECT_DATA_STORAGE_NOTICE_RATIO` | `0.6` | ProjectData storage usage ratio classified as `notice` | -| `PROJECT_DATA_STORAGE_WARNING_RATIO` | `0.8` | ProjectData storage usage ratio classified as `warning` | -| `PROJECT_DATA_STORAGE_CRITICAL_RATIO` | `0.9` | ProjectData storage usage ratio classified as `critical` | -| `PROJECT_DATA_STORAGE_DEGRADED_RATIO` | `0.95` | ProjectData storage usage ratio classified as `degraded` | -| `PROJECT_DATA_STORAGE_EMERGENCY_TARGET_RATIO` | `0.9` | Target usage ratio for explicit superadmin ProjectData emergency purge calls | -| `PROJECT_DATA_STORAGE_EMERGENCY_BATCH_ROWS` | `500` | Oldest `activity_events` and `acp_session_events` rows deleted per table per emergency purge batch | -| `PROJECT_DATA_STORAGE_EMERGENCY_MAX_BATCHES` | `4` | Maximum emergency purge batches per explicit call | -| `PROJECT_DATA_STORAGE_GROWTH_LOOKBACK_DAYS` | `7` | Lookback window used to estimate ProjectData bytes/day growth and days to storage limit | -| `PROJECT_DATA_STORAGE_TELEMETRY_LIST_LIMIT_DEFAULT` | `50` | Default row count for admin ProjectData storage telemetry and history lists | -| `PROJECT_DATA_STORAGE_TELEMETRY_LIST_LIMIT_MAX` | `200` | Max accepted row count for admin ProjectData storage telemetry and history lists | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_ENABLED` | `true` | Enables automatic ProjectData cleanup that archives expandable `tool_metadata.content` payloads to private R2 before stripping them from old message rows. NOT sufficient on its own: setting `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_CUTOFF_CREATED_AT` arms the stricter approved-manifest plan, which additionally requires `_PLAN_ID`, `_MANIFEST_KEY`, `_MANIFEST_SHA256` and all four `_MAX_TOTAL_*` ceilings. With the cutoff set and any of those blank, cleanup is enabled but builds no plan; the refusal is logged as `project_data.tool_payload_cleanup.config_refused` with the unmet field names. | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_PLAN_ID` | _(empty)_ | Immutable operator plan identifier; required with a fixed cleanup cutoff and persisted with continuation state to reject configuration drift | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MANIFEST_KEY` | _(empty)_ | Immutable R2 root key for the verified row-level target manifest; required with a fixed cleanup cutoff | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MANIFEST_SHA256` | _(empty)_ | Expected SHA-256 of the approved target-manifest root; required with a fixed cleanup cutoff | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_BATCH_MANIFEST_MAX_BYTES` | `2000000` | Verified approved-plan batch-manifest read/write ceiling; included in the immutable exact-plan fingerprint | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_ROOT_MANIFEST_MAX_BYTES` | `1000000` | Verified approved-plan root-manifest read/write ceiling; included in the immutable exact-plan fingerprint | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_ROWS` | _(empty)_ | Hard cumulative approved target-row ceiling; required with a fixed cleanup cutoff | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_BYTES` | _(empty)_ | Hard cumulative approved projected-reclaim ceiling; required with a fixed cleanup cutoff | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_R2_OPERATIONS` | _(empty)_ | Hard cumulative R2 operation ceiling including manifest verification; exact execution transactionally charges the full per-pass allowance before external work and never refunds it | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_WALL_TIME_MS` | _(empty)_ | Hard cumulative cleanup wall-time ceiling; exact execution transactionally charges the full per-pass allowance before external work and never refunds it | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_PROJECT_IDS` | _(empty)_ | Optional comma-separated project allowlist for automatic cleanup; empty preserves cleanup eligibility for every project, while an emergency rollout can scope elevated budgets to exact projects. One variable, two meanings — see the note below | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_CUTOFF_CREATED_AT` | _(empty)_ | Optional fixed exclusive tool-message cutoff in epoch milliseconds; when set, the immutable verified manifest, cumulative ceilings, plan ID, and exactly one allowlisted project are required; invalid values fail closed | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_TRIGGER_RATIO` | `0.8` | ProjectData storage usage ratio that starts automatic tool payload archival cleanup even before the retention cadence is due | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_TARGET_RATIO` | `0.75` | ProjectData storage usage ratio below which automatic tool payload cleanup stops | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_BATCH_ROWS` | `500` | Maximum eligible tool-message candidates processed by one automatic cleanup alarm batch; ordinary selection may examine a larger physical row window bounded by `PROJECT_DATA_STORAGE_RELIEF_MEASURE_MAX_BATCH_ROWS` | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_BATCH_BYTES` | `2097152` | Legacy `tool_metadata` read budget per automatic pass; an ordinary retention pass may admit its first oversized candidate up to the archive metadata ceiling, while a fixed exact plan requires its row ceiling to fit this budget | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_ROW_BYTES` | `1048576` | Maximum single legacy `tool_metadata` row bytes read into JS by archival cleanup; larger rows fail closed unless the operator deliberately raises this limit | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MIN_SESSION_AGE_DAYS` | `7` | Legacy terminal-session age guard retained for storage telemetry compatibility; tool payload archival uses `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_RETENTION_DAYS` | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_RECHECK_MS` | `86400000` | Delay before the next automatic cleanup alarm batch when more candidates remain; daily by default | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_SESSIONS_PER_ALARM` | `25` | Deprecated legacy terminal-session cleanup knob retained for env compatibility; archival cleanup scans tool-message rows directly and is bounded by rows, bytes, and wall time instead | -| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_WALL_TIME_MS` | `20000` | Absolute wall-clock deadline shared by candidate processing and every R2 write/read-back operation in one cleanup pass | -| `PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_MAX_BATCH_ROWS` | `500` | Hard row cap for one explicit superadmin manual ProjectData tool payload archival cleanup pass | -| `PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_MAX_BATCH_BYTES` | `2097152` | Maximum configurable legacy `tool_metadata` read budget for one explicit manual pass; the ordinary-path first-row exception applies unless a fixed exact plan binds the row ceiling within this budget | -| `PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_MAX_WALL_TIME_MS` | `20000` | Hard wall-clock cap for one explicit manual cleanup pass | -| `PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_RECHECK_MS` | `86400000` | Persisted project-scoped cooldown after an explicit manual cleanup pass; daily by default | -| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_RETENTION_DAYS` | `5` | Message age before expandable tool payload JSON may be archived to private R2 and stripped from the ProjectData DO | -| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_INTERVAL_MS` | `86400000` | Cadence for the retention-driven ProjectData tool payload archival scan | -| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_R2_PREFIX` | `project-data/tool-payloads` | Private R2 prefix used for archived ProjectData tool payload JSON objects | -| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_WRITE_TIMEOUT_MS` | `5000` | Per-R2 write/read-back verification timeout for automatic archival cleanup; timeout leaves the original payload in ProjectData and defers retry | -| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_MAX_OPERATIONS` | `1500` | Maximum R2 PUT, GET, and body-read operations reserved by one cleanup pass | -| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_RETRY_DELAY_MS` | `300000` | Row-level retry deferral after retryable archive/write failures | -| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_CHUNK_BYTES` | `524288` | R2 chunk size used when archiving legacy tool payload metadata larger than one archive object slice | -| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_MAX_METADATA_BYTES` | `1900000` | Absolute bounded read cap for legacy oversized tool payload metadata; larger rows fail closed and remain in ProjectData | -| `PROJECT_DATA_STORAGE_RELIEF_MEASURE_BATCH_ROWS` | `500` | Default row budget for superadmin ProjectData relief measurement slices | -| `PROJECT_DATA_STORAGE_RELIEF_MEASURE_MAX_BATCH_ROWS` | `5000` | Maximum physical row window accepted for superadmin/preflight relief measurements and examined by one ordinary cleanup candidate-selection slice | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_ENABLED` | `false` | Enables the scheduled, read-only, fixed-cutoff ProjectData tool-payload relief preflight; requires the exact plan, project, and cutoff variables below | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_PLAN_ID` | _(empty)_ | Immutable operator plan identifier used to resume one preflight without mixing evidence from another run | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_PROJECT_ID` | _(empty)_ | Exact ProjectData project targeted by the enabled preflight | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_CUTOFF_CREATED_AT` | _(empty)_ | Fixed exclusive tool-message creation cutoff in epoch milliseconds; required while preflight is enabled | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_BATCH_ROWS` | `5000` | Maximum physical `chat_messages` rowid window examined by one preflight slice before eligibility filtering | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_INTERVAL_MS` | `300000` | Persisted minimum interval between preflight slices | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_BATCHES` | `100` | Overall claimed-attempt ceiling; an incomplete successful scan becomes truncated at the ceiling, while the final failed attempt becomes failed | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_ROWS` | `500000` | Overall physical `chat_messages` rows-examined ceiling for one preflight plan before eligibility filtering | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_BYTES` | `2000000000` | Overall projected net reclaimable-byte evidence ceiling for one preflight plan | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_LEASE_MS` | `60000` | D1 claim lease that prevents overlapping slices; must exceed the wall-time budget by the configured lease margin | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_WALL_TIME_MS` | `20000` | Absolute per-slice deadline shared by bounded ProjectData measurement and verified R2 manifest writes/read-backs; failures retain the prior cursor and fail closed for retry | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_SLICES_PER_RUN` | `1` | Maximum sequential, separately leased slices in one scheduled invocation; later slices bypass only that invocation's persisted cadence | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_RUN_WALL_TIME_MS` | `25000` | Aggregate invocation admission budget used to decide whether another full sequential slice can start; must exceed the per-slice wall-time budget by the return margin | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_LEASE_MARGIN_MS` | `5000` | Required lease headroom above the per-slice wall-time budget | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_RETURN_MARGIN_MS` | `500` | Required return headroom inside measurement, slice, and aggregate run budgets | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MEASUREMENT_WALL_TIME_MS` | `10000` | Explicit ProjectData measurement budget inside one slice; plus the return margin it must not exceed the slice wall budget | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_STATE_BYTES` | `1750000` | Combined D1 JSON byte ceiling for accumulated session and target-batch proof state in one preflight row | -| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_ERROR_MAX_LENGTH` | `1000` | Character ceiling for a persisted preflight failure diagnostic | -| `PROJECT_DATA_ARCHIVE_SHARDING_ENABLED` | `false` | Feature switch for exact archive read routing. It is disabled when unset; enabling it alone does not run the unscoped scheduled sweep | -| `PROJECT_DATA_ARCHIVE_GLOBAL_SWEEP_ENABLED` | `false` | Separate feature switch for the unscoped scheduled archive-sharding sweep. It is disabled when unset; scheduled global migration also requires exact archive routing to be enabled | +| Variable | Default | Description | +| ---------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `MAX_SESSIONS_PER_PROJECT` | `10000` | Max chat sessions per project | +| `MAX_MESSAGES_PER_SESSION` | `100000` | Max messages per chat session | +| `COMMENT_BODY_MAX_LENGTH` | `8000` | Max characters per message-anchored comment or reply body | +| `COMMENT_QUOTE_MAX_LENGTH` | `2000` | Max characters preserved from quoted message text | +| `COMMENT_IDEMPOTENCY_KEY_MAX_LENGTH` | `200` | Max `clientMutationId` length for message-anchored comment writes | +| `COMMENT_LIST_LIMIT_DEFAULT` | `100` | Default page size for comment thread lists | +| `COMMENT_LIST_LIMIT_MAX` | `500` | Max page size for comment thread lists | +| `COMMENT_THREADS_PER_SESSION_MAX` | `1000` | Max message-anchored comment threads per chat session | +| `COMMENT_REPLIES_PER_THREAD_MAX` | `200` | Max replies per message-anchored comment thread | +| `PROJECT_COMMENT_LIST_LIMIT` | `100` | Page size for the project-wide comment inbox | +| `PROJECT_COMMENT_LIST_MAX` | `300` | Max page size for the project-wide comment inbox | +| `PROJECT_COMMENT_LIST_MAX_BYTES` | `4000000` | Byte budget for one project-wide comment inbox response, so a few very long threads cannot exhaust the Durable Object RPC limit | +| `DOCUMENT_CARD_RAW_OUTPUT_MAX_BYTES` | `16384` | Max compact metadata bytes preserved for library document cards | +| `PROJECT_DATA_TOOL_METADATA_MAX_BYTES` | `131072` | Max stored `tool_metadata` bytes per message before oversized tool content is stripped into bounded metadata | +| `PROJECT_DATA_STORAGE_TELEMETRY_ENABLED` | `true` | Enables ProjectData `databaseSize` alarm measurement and D1 telemetry writes | +| `PROJECT_DATA_STORAGE_LIMIT_BYTES` | `10000000000` | Cloudflare SQLite-backed Durable Object storage limit used for ProjectData usage classification | +| `PROJECT_DATA_STORAGE_MEASURE_INTERVAL_MS` | `3600000` | Interval between full per-object ProjectData storage measurements. Each one appends a telemetry history row and evaluates the storage alerts; cleanup passes publish the latest size but never postpone it (`measureAndPersistProjectDataStorage`) | +| `PROJECT_DATA_STORAGE_ALERT_INTERVAL_MS` | `21600000` | Minimum interval between repeated ProjectData storage observability alerts of the same kind and status. Threshold (warning/critical/degraded) and cleanup-target-unreachable alerts are throttled separately (`maybePersistProjectDataStorageAlert`) | +| `PROJECT_DATA_STORAGE_NOTICE_RATIO` | `0.6` | ProjectData storage usage ratio classified as `notice` | +| `PROJECT_DATA_STORAGE_WARNING_RATIO` | `0.8` | ProjectData storage usage ratio classified as `warning` | +| `PROJECT_DATA_STORAGE_CRITICAL_RATIO` | `0.9` | ProjectData storage usage ratio classified as `critical` | +| `PROJECT_DATA_STORAGE_DEGRADED_RATIO` | `0.95` | ProjectData storage usage ratio classified as `degraded` | +| `PROJECT_DATA_STORAGE_EMERGENCY_TARGET_RATIO` | `0.9` | Target usage ratio for explicit superadmin ProjectData emergency purge calls | +| `PROJECT_DATA_STORAGE_EMERGENCY_BATCH_ROWS` | `500` | Oldest `activity_events` and `acp_session_events` rows deleted per table per emergency purge batch | +| `PROJECT_DATA_STORAGE_EMERGENCY_MAX_BATCHES` | `4` | Maximum emergency purge batches per explicit call | +| `PROJECT_DATA_STORAGE_GROWTH_LOOKBACK_DAYS` | `7` | Lookback window used to estimate ProjectData bytes/day growth and days to storage limit | +| `PROJECT_DATA_STORAGE_TELEMETRY_LIST_LIMIT_DEFAULT` | `50` | Default row count for admin ProjectData storage telemetry and history lists | +| `PROJECT_DATA_STORAGE_TELEMETRY_LIST_LIMIT_MAX` | `200` | Max accepted row count for admin ProjectData storage telemetry and history lists | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_ENABLED` | `true` | Enables automatic ProjectData cleanup that archives expandable `tool_metadata.content` payloads to private R2 before stripping them from old message rows. NOT sufficient on its own: setting `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_CUTOFF_CREATED_AT` arms the stricter approved-manifest plan, which additionally requires `_PLAN_ID`, `_MANIFEST_KEY`, `_MANIFEST_SHA256` and all four `_MAX_TOTAL_*` ceilings. With the cutoff set and any of those blank, cleanup is enabled but builds no plan; the refusal is logged as `project_data.tool_payload_cleanup.config_refused` with the unmet field names. | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_PLAN_ID` | _(empty)_ | Immutable operator plan identifier; required with a fixed cleanup cutoff and persisted with continuation state to reject configuration drift | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MANIFEST_KEY` | _(empty)_ | Immutable R2 root key for the verified row-level target manifest; required with a fixed cleanup cutoff | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MANIFEST_SHA256` | _(empty)_ | Expected SHA-256 of the approved target-manifest root; required with a fixed cleanup cutoff | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_BATCH_MANIFEST_MAX_BYTES` | `2000000` | Verified approved-plan batch-manifest read/write ceiling; included in the immutable exact-plan fingerprint | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_ROOT_MANIFEST_MAX_BYTES` | `1000000` | Verified approved-plan root-manifest read/write ceiling; included in the immutable exact-plan fingerprint | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_ROWS` | _(empty)_ | Hard cumulative approved target-row ceiling; required with a fixed cleanup cutoff | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_BYTES` | _(empty)_ | Hard cumulative approved projected-reclaim ceiling; required with a fixed cleanup cutoff | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_R2_OPERATIONS` | _(empty)_ | Hard cumulative R2 operation ceiling including manifest verification; exact execution transactionally charges the full per-pass allowance before external work and never refunds it | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_WALL_TIME_MS` | _(empty)_ | Hard cumulative cleanup wall-time ceiling; exact execution transactionally charges the full per-pass allowance before external work and never refunds it | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_PROJECT_IDS` | _(empty)_ | Optional comma-separated project allowlist for automatic cleanup; empty preserves cleanup eligibility for every project, while an emergency rollout can scope elevated budgets to exact projects. One variable, two meanings — see the note below | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_CUTOFF_CREATED_AT` | _(empty)_ | Optional fixed exclusive tool-message cutoff in epoch milliseconds; when set, the immutable verified manifest, cumulative ceilings, plan ID, and exactly one allowlisted project are required; invalid values fail closed | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_TRIGGER_RATIO` | `0.8` | ProjectData storage usage ratio that starts automatic tool payload archival cleanup even before the retention cadence is due | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_TARGET_RATIO` | `0.75` | ProjectData storage usage ratio below which automatic tool payload cleanup stops | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_BATCH_ROWS` | `500` | Maximum eligible tool-message candidates processed by one automatic cleanup alarm batch; ordinary selection may examine a larger physical row window bounded by `PROJECT_DATA_STORAGE_RELIEF_MEASURE_MAX_BATCH_ROWS` | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_BATCH_BYTES` | `2097152` | Legacy `tool_metadata` read budget per automatic pass; an ordinary retention pass may admit its first oversized candidate up to the archive metadata ceiling, while a fixed exact plan requires its row ceiling to fit this budget | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_ROW_BYTES` | `1048576` | Maximum single legacy `tool_metadata` row bytes read into JS by archival cleanup; larger rows fail closed unless the operator deliberately raises this limit | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MIN_SESSION_AGE_DAYS` | `7` | Legacy terminal-session age guard retained for storage telemetry compatibility; tool payload archival uses `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_RETENTION_DAYS` | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_RECHECK_MS` | `86400000` | Delay before the next automatic cleanup alarm batch when more candidates remain; daily by default | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_SESSIONS_PER_ALARM` | `25` | Deprecated legacy terminal-session cleanup knob retained for env compatibility; archival cleanup scans tool-message rows directly and is bounded by rows, bytes, and wall time instead | +| `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_WALL_TIME_MS` | `20000` | Absolute wall-clock deadline shared by candidate processing and every R2 write/read-back operation in one cleanup pass | +| `PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_MAX_BATCH_ROWS` | `500` | Hard row cap for one explicit superadmin manual ProjectData tool payload archival cleanup pass | +| `PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_MAX_BATCH_BYTES` | `2097152` | Maximum configurable legacy `tool_metadata` read budget for one explicit manual pass; the ordinary-path first-row exception applies unless a fixed exact plan binds the row ceiling within this budget | +| `PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_MAX_WALL_TIME_MS` | `20000` | Hard wall-clock cap for one explicit manual cleanup pass | +| `PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_RECHECK_MS` | `86400000` | Persisted project-scoped cooldown after an explicit manual cleanup pass; daily by default | +| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_RETENTION_DAYS` | `5` | Message age before expandable tool payload JSON may be archived to private R2 and stripped from the ProjectData DO | +| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_INTERVAL_MS` | `86400000` | Cadence for the retention-driven ProjectData tool payload archival scan | +| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_R2_PREFIX` | `project-data/tool-payloads` | Private R2 prefix used for archived ProjectData tool payload JSON objects | +| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_WRITE_TIMEOUT_MS` | `5000` | Per-R2 write/read-back verification timeout for automatic archival cleanup; timeout leaves the original payload in ProjectData and defers retry | +| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_MAX_OPERATIONS` | `1500` | Maximum R2 PUT, GET, and body-read operations reserved by one cleanup pass | +| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_RETRY_DELAY_MS` | `300000` | Row-level retry deferral after retryable archive/write failures | +| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_CHUNK_BYTES` | `524288` | R2 chunk size used when archiving legacy tool payload metadata larger than one archive object slice | +| `PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_MAX_METADATA_BYTES` | `1900000` | Absolute bounded read cap for legacy oversized tool payload metadata; larger rows fail closed and remain in ProjectData | +| `PROJECT_DATA_STORAGE_RELIEF_MEASURE_BATCH_ROWS` | `500` | Default row budget for superadmin ProjectData relief measurement slices | +| `PROJECT_DATA_STORAGE_RELIEF_MEASURE_MAX_BATCH_ROWS` | `5000` | Maximum physical row window accepted for superadmin/preflight relief measurements and examined by one ordinary cleanup candidate-selection slice | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_ENABLED` | `false` | Enables the scheduled, read-only, fixed-cutoff ProjectData tool-payload relief preflight; requires the exact plan, project, and cutoff variables below | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_PLAN_ID` | _(empty)_ | Immutable operator plan identifier used to resume one preflight without mixing evidence from another run | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_PROJECT_ID` | _(empty)_ | Exact ProjectData project targeted by the enabled preflight | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_CUTOFF_CREATED_AT` | _(empty)_ | Fixed exclusive tool-message creation cutoff in epoch milliseconds; required while preflight is enabled | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_BATCH_ROWS` | `5000` | Maximum physical `chat_messages` rowid window examined by one preflight slice before eligibility filtering | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_INTERVAL_MS` | `300000` | Persisted minimum interval between preflight slices | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_BATCHES` | `100` | Overall claimed-attempt ceiling; an incomplete successful scan becomes truncated at the ceiling, while the final failed attempt becomes failed | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_ROWS` | `500000` | Overall physical `chat_messages` rows-examined ceiling for one preflight plan before eligibility filtering | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_BYTES` | `2000000000` | Overall projected net reclaimable-byte evidence ceiling for one preflight plan | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_LEASE_MS` | `60000` | D1 claim lease that prevents overlapping slices; must exceed the wall-time budget by the configured lease margin | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_WALL_TIME_MS` | `20000` | Absolute per-slice deadline shared by bounded ProjectData measurement and verified R2 manifest writes/read-backs; failures retain the prior cursor and fail closed for retry | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_SLICES_PER_RUN` | `1` | Maximum sequential, separately leased slices in one scheduled invocation; later slices bypass only that invocation's persisted cadence | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_RUN_WALL_TIME_MS` | `25000` | Aggregate invocation admission budget used to decide whether another full sequential slice can start; must exceed the per-slice wall-time budget by the return margin | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_LEASE_MARGIN_MS` | `5000` | Required lease headroom above the per-slice wall-time budget | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_RETURN_MARGIN_MS` | `500` | Required return headroom inside measurement, slice, and aggregate run budgets | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MEASUREMENT_WALL_TIME_MS` | `10000` | Explicit ProjectData measurement budget inside one slice; plus the return margin it must not exceed the slice wall budget | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_STATE_BYTES` | `1750000` | Combined D1 JSON byte ceiling for accumulated session and target-batch proof state in one preflight row | +| `PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_ERROR_MAX_LENGTH` | `1000` | Character ceiling for a persisted preflight failure diagnostic | +| `PROJECT_DATA_ARCHIVE_SHARDING_ENABLED` | `false` | Feature switch for exact archive read routing. It is disabled when unset; enabling it alone does not run the unscoped scheduled sweep | +| `PROJECT_DATA_ARCHIVE_GLOBAL_SWEEP_ENABLED` | `false` | Separate feature switch for the unscoped scheduled archive-sharding sweep. It is disabled when unset; scheduled global migration also requires exact archive routing to be enabled | | `PROJECT_DATA_ARCHIVE_GLOBAL_SWEEP_INTERVAL_MS` | `86400000` | Persisted cadence gate for unscoped scheduled archive-sharding sweeps; the five-minute handler claims the cadence row only when due. Code fallback is daily; the checked-in `wrangler.toml` ships `540000` (9 min), normally claiming every second five-minute tick (~10 min; timing jitter can defer a claim). A claim migrates sessions within the `PROJECT_DATA_ARCHIVE_WALL_TIME_MS` per-tick bound (shipped 60000, checked between candidates and inside migrations) and `PROJECT_DATA_ARCHIVE_SWEEP_SESSIONS`, with compact migrations subject to the daily reservation budget (legacy migrations reserve nothing, so a zero allowance does not stop legacy sweeps). Roughly 144 claims/day targets ~72k copied rows/hour at the measured ~12k rows/tick, versus ~36k/hour at the previous 18-minute interval (~20-minute ticks). Refused, failed or budget-limited claims publish nothing | -| `PROJECT_DATA_ARCHIVE_SHARD_COUNT` | `128` | Deterministic archive-shard fanout used when assigning terminal sessions to ProjectData archive Durable Objects | -| `PROJECT_DATA_ARCHIVE_SWEEP_PROJECTS` | `1` | Maximum projects selected by one archive-sharding cron pass | -| `PROJECT_DATA_ARCHIVE_SWEEP_SESSIONS` | `10` | Most sessions one archive-sharding pass may copy (in-flight plus new candidates); candidates refused by the write budget or by the root object take no slot. The checked-in `wrangler.toml` ships `50`, a safety cap that `PROJECT_DATA_ARCHIVE_WALL_TIME_MS` reaches first | -| `PROJECT_DATA_ARCHIVE_SWEEP_MESSAGE_BUDGET` | `20000` | Cumulative `message_count` the operator-scoped canary packs into one run, and its SQL ceiling for unnamed sessions. The unscoped sweep does not use it: since the resumable cursor its only per-session selection limit is the ceiling derived from the daily write budget (`resolveSweepAffordability`). The checked-in `wrangler.toml` ships `10000` | -| `PROJECT_DATA_ARCHIVE_SESSION_GRACE_MS` | `604800000` | Minimum terminal-session age before archive-sharding may consider a session | -| `PROJECT_DATA_ARCHIVE_PRECOPY_REFUSAL_RETRY_MS` | `86400000` | How long a session the root object refused at prepare (pre-copy invariant, e.g. `active_session_state`) stays out of unscoped sweep selection; journal `frozen`/`precopy_refused`, location back at `root`; a named-session canary bypasses it | -| `PROJECT_DATA_ARCHIVE_FAILED_RETRY_DELAY_MS` | `3600000` | Minimum age of a `failed` archive journal before an unscoped sweep reclaims it, so `PROJECT_DATA_ARCHIVE_POISON_AFTER_ATTEMPTS` spans hours rather than consecutive cadence ticks; `0` disables it and a named-session canary bypasses it | -| `PROJECT_DATA_ARCHIVE_CHUNK_ROWS` | `500` | Maximum rows exported in one idempotent transcript archive chunk | -| `PROJECT_DATA_ARCHIVE_CHUNK_BYTES` | `16777216` | Maximum bytes exported in one archive chunk; clamped below Cloudflare's 32MiB RPC ceiling | -| `PROJECT_DATA_ARCHIVE_HASH_PAGE_ROWS` | `500` | Rows read per statement while streaming a session's terminal-version hash inside the ProjectData Durable Object; bounds object memory by page size instead of session size | -| `PROJECT_DATA_ARCHIVE_LEASE_MS` | `300000` | D1 CAS journal lease duration for archive-sharding work. Renewed at chunk, verification-page and phase boundaries once less than half remains (`renewLeaseIfDue`), and released when a migration pauses at the tick deadline | -| `PROJECT_DATA_ARCHIVE_WALL_TIME_MS` | `5000` | Wall-clock deadline for one archive-sharding cron pass, checked between candidates and inside a migration: a migration that has advanced pauses at the next copy chunk, R2 verification page or phase boundary and the next pass resumes it, so a pass runs up to this plus one in-flight RPC (the longest is an R2 verification page, bounded by `PROJECT_DATA_ARCHIVE_R2_TIMEOUT_MS`; the flip is an O(1) write-generation check). Code fallback 5 s; the checked-in `wrangler.toml` ships `60000` (about 6 small sessions or ~5k messages per pass) | -| `PROJECT_DATA_ARCHIVE_ROLLOUT_LIST_LIMIT_DEFAULT` | `25` | Default row limit for superadmin archive-sharding rollout inspection and failed/poisoned/frozen migration list endpoints | -| `PROJECT_DATA_ARCHIVE_ROLLOUT_LIST_LIMIT_MAX` | `100` | Maximum accepted row limit for D1-only superadmin archive-sharding rollout inspection endpoints. Frozen-intent DO inspection is capped separately. | -| `PROJECT_DATA_ARCHIVE_FROZEN_INTENT_INSPECTION_LIMIT_DEFAULT` | `5` | Default row limit for `GET /archive-sharding/frozen-intents`; each row may perform source and target ProjectData DO RPCs, so this endpoint intentionally has a smaller hot-object fan-out budget | -| `PROJECT_DATA_ARCHIVE_FROZEN_INTENT_INSPECTION_LIMIT_MAX` | `10` | Maximum accepted frozen-intent detail inspection limit; configured values above 10 are clamped to the reviewed hot-DO fan-out ceiling and request limits above the configured max are rejected | -| `PROJECT_DATA_ARCHIVE_MANUAL_CANARY_MAX_SESSIONS` | `5` | Maximum sessions a superadmin scoped manual archive-sharding canary request may select; default requests select one session and dry-run by default | -| `PROJECT_DATA_ARCHIVE_MANUAL_CANARY_MAX_WALL_TIME_MS` | `15000` | Maximum wall-clock budget accepted by the superadmin scoped manual archive-sharding canary endpoint | -| `PROJECT_DATA_ARCHIVE_ROLLOUT_WARNING_EXAMPLES_MAX` | `5` | Maximum malformed-row warning examples returned by archive rollout read/list endpoints | -| `PROJECT_DATA_ARCHIVE_ROLLOUT_WARNING_REASON_MAX_LENGTH` | `300` | Maximum characters per malformed-row warning reason returned by archive rollout read/list endpoints | -| `PROJECT_DATA_ARCHIVE_POISON_AFTER_ATTEMPTS` | `3` | Consecutive claims that fail without moving the migration forward before it is poisoned and the project circuit breaker opens. A claim that advanced (copied a chunk, verified a page, crossed a phase) and then failed keeps its phase, resets the count and resumes on the next pass, so a large session spanning many passes is not poisoned by an unrelated transient failure. Each opening sends every active superadmin one Operational Failure notification and records one `/admin/errors` entry (`alertProjectDataArchiveBreakerOpened`) | -| `PROJECT_DATA_ARCHIVE_R2_PREFIX` | `project-data/session-archives` | Private R2 prefix for terminal-session archive recovery chunks and manifests | -| `PROJECT_DATA_ARCHIVE_SEARCH_MAX_OWNERS` | `4` | Archive-shard owner batch size for one project-wide message-search continuation (maximum 64; invalid/out-of-range values use 4); callers continue until coverage is complete | -| `PROJECT_DATA_ARCHIVE_SEARCH_CONCURRENCY` | `4` | Concurrent archive-owner queries in one batch (maximum 16; invalid/out-of-range values use 4) | -| `PROJECT_DATA_ARCHIVE_SEARCH_REPAIR_SESSIONS` | `1` | Incomplete published archive sessions advanced per owner query (maximum 16); remaining repair stays explicit and resumable | -| `PROJECT_DATA_ARCHIVE_SEARCH_REPAIR_CHUNKS` | `1` | Immutable compact R2 chunks consumed per session repair step (maximum 64) | -| `PROJECT_DATA_ARCHIVE_SEARCH_CONTINUATION_TTL_MS` | `900000` | Lifetime of a signed, query-bound complete-history continuation (maximum 24 hours) | -| `PROJECT_DATA_ARCHIVE_SEARCH_CURSOR_MAX_BYTES` | `1048576` | Maximum continuation bytes accepted before decoding or emitted after signing (maximum 4 MiB) | -| `PROJECT_DATA_ARCHIVE_SEARCH_ERROR_LIMIT` | `20` | Maximum entries retained independently in each public execution- and index-error collection (maximum 100); full details remain in server logs | -| `PROJECT_DATA_SEARCH_FTS_CANDIDATE_LIMIT` | `2000` | Newest full-text matches ranked per ProjectData message search; when more match, results report `rootSearch.ftsCandidatesTruncated` | -| `PROJECT_DATA_SEARCH_FTS_SCAN_LIMIT` | `20000` | Full-text index entries inside a session's rowid span that a session-scoped search examines, newest first, to collect that session's newest matches; never smaller than `PROJECT_DATA_SEARCH_FTS_CANDIDATE_LIMIT` | -| `PROJECT_DATA_SEARCH_KEYWORD_SCAN_ROW_LIMIT` | `50000` | Newest raw messages the keyword fallback scans for not-yet-indexed text; older rows are reported as `rootSearch.keywordScanTruncated` | -| `PROJECT_DATA_ALARM_SECTION_GATING_ENABLED` | `true` | Run only the ProjectData alarm sections that are due each tick; `false` runs every section every tick | -| `PROJECT_DATA_ALARM_FULL_RUN_INTERVAL_MS` | `900000` | Maximum interval between ProjectData alarm ticks that run every section regardless of due times | -| `PROJECT_DATA_ALARM_DUE_TOLERANCE_MS` | `2000` | A ProjectData alarm section due within this many ms of the tick runs in that tick | -| `PROJECT_DATA_ALARM_SLOW_SECTION_MS` | `1000` | ProjectData alarm sections at or above this wall time log `project_data.alarm.section_slow` | -| `WORKSPACE_RESOURCE_RAW_RETENTION_DAYS` | `90` | Retention for immutable raw resource-history gzip chunks in the private archive R2 binding | -| `WORKSPACE_RESOURCE_SUMMARY_RETENTION_DAYS` | `180` | Retention for bounded D1 workspace resource summary rows | -| `WORKSPACE_RESOURCE_UNCOMPRESSED_MAX_BYTES` | `8388608` | Max decoded resource chunk JSON bytes accepted/read before rejecting detail payloads | -| `WORKSPACE_RESOURCE_METADATA_MAX_BYTES` | `8192` | Max `summary` or `completeness` JSON bytes stored in D1 for one resource chunk/summary | -| `WORKSPACE_RESOURCE_TOOL_NAME_MAX_BYTES` | `256` | Max UTF-8 bytes retained and returned for one resource-history tool name; longer metadata names are truncated at a complete Unicode character | -| `WORKSPACE_RESOURCE_UPLOAD_MAX_BYTES` | `2097152` | Max compressed resource-history chunk bytes accepted by the callback upload route | -| `WORKSPACE_RESOURCE_DETAIL_MAX_POINTS` | `720` | Max samples returned by one raw detail read after spike-preserving downsampling | -| `WORKSPACE_RESOURCE_LIST_LIMIT` | `24` | Max resource-history chunk index rows returned for one contextual read | -| `WORKSPACE_RESOURCE_TIMELINE_MAX_CHUNKS` | `1000` | Max chunks the session resource timeline lists; the oldest beyond it are left out and disclosed as `omittedChunkCount` | -| `WORKSPACE_RESOURCE_ROLLUP_BUCKET_MS` | `60000` | Width of each per-chunk rollup bucket computed on upload | -| `WORKSPACE_RESOURCE_ROLLUP_MAX_BUCKETS` | `60` | Max rollup buckets stored per chunk; the bucket width widens in whole multiples to fit | -| `WORKSPACE_RESOURCE_CLEANUP_BATCH_SIZE` | `50` | Max expired resource-history chunks and summaries processed per scheduled cleanup sweep | -| `WORKSPACE_RESOURCE_OBJECT_CLEANUP_LIMIT` | `5000` | Max resource-history R2 objects deleted when a project or workspace is deleted; deletion paginates until the prefix is empty or this safety budget is reached | +| `PROJECT_DATA_ARCHIVE_SHARD_COUNT` | `128` | Deterministic archive-shard fanout used when assigning terminal sessions to ProjectData archive Durable Objects | +| `PROJECT_DATA_ARCHIVE_SWEEP_PROJECTS` | `1` | Maximum projects selected by one archive-sharding cron pass | +| `PROJECT_DATA_ARCHIVE_SWEEP_SESSIONS` | `10` | Most sessions one archive-sharding pass may copy (in-flight plus new candidates); candidates refused by the write budget or by the root object take no slot. The checked-in `wrangler.toml` ships `50`, a safety cap that `PROJECT_DATA_ARCHIVE_WALL_TIME_MS` reaches first | +| `PROJECT_DATA_ARCHIVE_SWEEP_MESSAGE_BUDGET` | `20000` | Cumulative `message_count` the operator-scoped canary packs into one run, and its SQL ceiling for unnamed sessions. The unscoped sweep does not use it: since the resumable cursor its only per-session selection limit is the ceiling derived from the daily write budget (`resolveSweepAffordability`). The checked-in `wrangler.toml` ships `10000` | +| `PROJECT_DATA_ARCHIVE_SESSION_GRACE_MS` | `604800000` | Minimum terminal-session age before archive-sharding may consider a session | +| `PROJECT_DATA_ARCHIVE_PRECOPY_REFUSAL_RETRY_MS` | `86400000` | How long a session the root object refused at prepare (pre-copy invariant, e.g. `active_session_state`) stays out of unscoped sweep selection; journal `frozen`/`precopy_refused`, location back at `root`; a named-session canary bypasses it | +| `PROJECT_DATA_ARCHIVE_FAILED_RETRY_DELAY_MS` | `3600000` | Minimum age of a `failed` archive journal before an unscoped sweep reclaims it, so `PROJECT_DATA_ARCHIVE_POISON_AFTER_ATTEMPTS` spans hours rather than consecutive cadence ticks; `0` disables it and a named-session canary bypasses it | +| `PROJECT_DATA_ARCHIVE_CHUNK_ROWS` | `500` | Maximum rows exported in one idempotent transcript archive chunk | +| `PROJECT_DATA_ARCHIVE_CHUNK_BYTES` | `16777216` | Maximum bytes exported in one archive chunk; clamped below Cloudflare's 32MiB RPC ceiling | +| `PROJECT_DATA_ARCHIVE_HASH_PAGE_ROWS` | `500` | Rows read per statement while streaming a session's terminal-version hash inside the ProjectData Durable Object; bounds object memory by page size instead of session size | +| `PROJECT_DATA_ARCHIVE_LEASE_MS` | `300000` | D1 CAS journal lease duration for archive-sharding work. Renewed at chunk, verification-page and phase boundaries once less than half remains (`renewLeaseIfDue`), and released when a migration pauses at the tick deadline | +| `PROJECT_DATA_ARCHIVE_WALL_TIME_MS` | `5000` | Wall-clock deadline for one archive-sharding cron pass, checked between candidates and inside a migration: a migration that has advanced pauses at the next copy chunk, R2 verification page or phase boundary and the next pass resumes it, so a pass runs up to this plus one in-flight RPC (the longest is an R2 verification page, bounded by `PROJECT_DATA_ARCHIVE_R2_TIMEOUT_MS`; the flip is an O(1) write-generation check). Code fallback 5 s; the checked-in `wrangler.toml` ships `60000` (about 6 small sessions or ~5k messages per pass) | +| `PROJECT_DATA_ARCHIVE_ROLLOUT_LIST_LIMIT_DEFAULT` | `25` | Default row limit for superadmin archive-sharding rollout inspection and failed/poisoned/frozen migration list endpoints | +| `PROJECT_DATA_ARCHIVE_ROLLOUT_LIST_LIMIT_MAX` | `100` | Maximum accepted row limit for D1-only superadmin archive-sharding rollout inspection endpoints. Frozen-intent DO inspection is capped separately. | +| `PROJECT_DATA_ARCHIVE_FROZEN_INTENT_INSPECTION_LIMIT_DEFAULT` | `5` | Default row limit for `GET /archive-sharding/frozen-intents`; each row may perform source and target ProjectData DO RPCs, so this endpoint intentionally has a smaller hot-object fan-out budget | +| `PROJECT_DATA_ARCHIVE_FROZEN_INTENT_INSPECTION_LIMIT_MAX` | `10` | Maximum accepted frozen-intent detail inspection limit; configured values above 10 are clamped to the reviewed hot-DO fan-out ceiling and request limits above the configured max are rejected | +| `PROJECT_DATA_ARCHIVE_MANUAL_CANARY_MAX_SESSIONS` | `5` | Maximum sessions a superadmin scoped manual archive-sharding canary request may select; default requests select one session and dry-run by default | +| `PROJECT_DATA_ARCHIVE_MANUAL_CANARY_MAX_WALL_TIME_MS` | `15000` | Maximum wall-clock budget accepted by the superadmin scoped manual archive-sharding canary endpoint | +| `PROJECT_DATA_ARCHIVE_ROLLOUT_WARNING_EXAMPLES_MAX` | `5` | Maximum malformed-row warning examples returned by archive rollout read/list endpoints | +| `PROJECT_DATA_ARCHIVE_ROLLOUT_WARNING_REASON_MAX_LENGTH` | `300` | Maximum characters per malformed-row warning reason returned by archive rollout read/list endpoints | +| `PROJECT_DATA_ARCHIVE_POISON_AFTER_ATTEMPTS` | `3` | Consecutive claims that fail without moving the migration forward before it is poisoned and the project circuit breaker opens. A claim that advanced (copied a chunk, verified a page, crossed a phase) and then failed keeps its phase, resets the count and resumes on the next pass, so a large session spanning many passes is not poisoned by an unrelated transient failure. Each opening sends every active superadmin one Operational Failure notification and records one `/admin/errors` entry (`alertProjectDataArchiveBreakerOpened`) | +| `PROJECT_DATA_ARCHIVE_R2_PREFIX` | `project-data/session-archives` | Private R2 prefix for terminal-session archive recovery chunks and manifests | +| `PROJECT_DATA_ARCHIVE_SEARCH_MAX_OWNERS` | `4` | Archive-shard owner batch size for one project-wide message-search continuation (maximum 64; invalid/out-of-range values use 4); callers continue until coverage is complete | +| `PROJECT_DATA_ARCHIVE_SEARCH_CONCURRENCY` | `4` | Concurrent archive-owner queries in one batch (maximum 16; invalid/out-of-range values use 4) | +| `PROJECT_DATA_ARCHIVE_SEARCH_REPAIR_SESSIONS` | `1` | Incomplete published archive sessions advanced per owner query (maximum 16); remaining repair stays explicit and resumable | +| `PROJECT_DATA_ARCHIVE_SEARCH_REPAIR_CHUNKS` | `1` | Immutable compact R2 chunks consumed per session repair step (maximum 64) | +| `PROJECT_DATA_ARCHIVE_SEARCH_CONTINUATION_TTL_MS` | `900000` | Lifetime of a signed, query-bound complete-history continuation (maximum 24 hours) | +| `PROJECT_DATA_ARCHIVE_SEARCH_CURSOR_MAX_BYTES` | `1048576` | Maximum continuation bytes accepted before decoding or emitted after signing (maximum 4 MiB) | +| `PROJECT_DATA_ARCHIVE_SEARCH_ERROR_LIMIT` | `20` | Maximum entries retained independently in each public execution- and index-error collection (maximum 100); full details remain in server logs | +| `PROJECT_DATA_SEARCH_FTS_CANDIDATE_LIMIT` | `2000` | Newest full-text matches ranked per ProjectData message search; when more match, results report `rootSearch.ftsCandidatesTruncated` | +| `PROJECT_DATA_SEARCH_FTS_SCAN_LIMIT` | `20000` | Full-text index entries inside a session's rowid span that a session-scoped search examines, newest first, to collect that session's newest matches; never smaller than `PROJECT_DATA_SEARCH_FTS_CANDIDATE_LIMIT` | +| `PROJECT_DATA_SEARCH_KEYWORD_SCAN_ROW_LIMIT` | `50000` | Newest raw messages the keyword fallback scans for not-yet-indexed text; older rows are reported as `rootSearch.keywordScanTruncated` | +| `PROJECT_DATA_ALARM_SECTION_GATING_ENABLED` | `true` | Run only the ProjectData alarm sections that are due each tick; `false` runs every section every tick | +| `PROJECT_DATA_ALARM_FULL_RUN_INTERVAL_MS` | `900000` | Maximum interval between ProjectData alarm ticks that run every section regardless of due times | +| `PROJECT_DATA_ALARM_DUE_TOLERANCE_MS` | `2000` | A ProjectData alarm section due within this many ms of the tick runs in that tick | +| `PROJECT_DATA_ALARM_SLOW_SECTION_MS` | `1000` | ProjectData alarm sections at or above this wall time log `project_data.alarm.section_slow` | +| `WORKSPACE_RESOURCE_RAW_RETENTION_DAYS` | `90` | Retention for immutable raw resource-history gzip chunks in the private archive R2 binding | +| `WORKSPACE_RESOURCE_SUMMARY_RETENTION_DAYS` | `180` | Retention for bounded D1 workspace resource summary rows | +| `WORKSPACE_RESOURCE_UNCOMPRESSED_MAX_BYTES` | `8388608` | Max decoded resource chunk JSON bytes accepted/read before rejecting detail payloads | +| `WORKSPACE_RESOURCE_METADATA_MAX_BYTES` | `8192` | Max `summary` or `completeness` JSON bytes stored in D1 for one resource chunk/summary | +| `WORKSPACE_RESOURCE_TOOL_NAME_MAX_BYTES` | `256` | Max UTF-8 bytes retained and returned for one resource-history tool name; longer metadata names are truncated at a complete Unicode character | +| `WORKSPACE_RESOURCE_UPLOAD_MAX_BYTES` | `2097152` | Max compressed resource-history chunk bytes accepted by the callback upload route | +| `WORKSPACE_RESOURCE_DETAIL_MAX_POINTS` | `720` | Max samples returned by one raw detail read after spike-preserving downsampling | +| `WORKSPACE_RESOURCE_LIST_LIMIT` | `24` | Max resource-history chunk index rows returned for one contextual read | +| `WORKSPACE_RESOURCE_TIMELINE_MAX_CHUNKS` | `1000` | Max chunks the session resource timeline lists; the oldest beyond it are left out and disclosed as `omittedChunkCount` | +| `WORKSPACE_RESOURCE_ROLLUP_BUCKET_MS` | `60000` | Width of each per-chunk rollup bucket computed on upload | +| `WORKSPACE_RESOURCE_ROLLUP_MAX_BUCKETS` | `60` | Max rollup buckets stored per chunk; the bucket width widens in whole multiples to fit | +| `WORKSPACE_RESOURCE_CLEANUP_BATCH_SIZE` | `50` | Max expired resource-history chunks and summaries processed per scheduled cleanup sweep | +| `WORKSPACE_RESOURCE_OBJECT_CLEANUP_LIMIT` | `5000` | Max resource-history R2 objects deleted when a project or workspace is deleted; deletion paginates until the prefix is empty or this safety budget is reached | :::caution[One variable, two meanings] `PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_PROJECT_IDS` gates two different paths, and the same value has @@ -1664,16 +1664,14 @@ accepts (decimal, hex, octal, IPv4-mapped and other IPv6 embeddings). | Deployment-release registry lookups | Registry, token realm and every redirect must be HTTPS on a public host. | `packages/app-deployment/src/image-resolver-outbound.ts` | | `check_dns_status` | Follows only redirects that stay on the workspace's own origin, each re-checked; reports any other redirect with its status without requesting it, and reports failures as fixed categories, never raw error text. A private-domain install may reach its own private workspace host. | `routes/mcp/check-dns-status.ts` | -Until a later change moves them, the AI proxy's own calls to a credential's base URL still let the -runtime follow a redirect: the base URL itself is checked, but a public base URL that redirects -is not re-checked per hop. `guardedFetch`, used everywhere else above, never lets the runtime -follow a redirect. It checks every hop, keeps only `Accept`, +The AI proxy's three passthrough calls also use `guardedFetch` +(`routes/ai-proxy-passthrough.ts`). It checks every redirect hop and keeps only `Accept`, `Accept-Language`, `Content-Type`, `Content-Language` and `User-Agent` on a hop to another origin, and refuses a 307 or 308 that would carry a request body to another origin. -| Admin setting | Default | Meaning | -| ----------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -| `outbound.maxRedirects` | `3` | Redirect hops a guarded fetch follows, each re-checked, range 0–10. `0` refuses every redirect. Used by GitLab profile/API calls and `check_dns_status`. If settings cannot be read, no redirect is followed. Category **Operations**. | +| Admin setting | Default | Meaning | +| ----------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `outbound.maxRedirects` | `3` | Redirect hops a guarded fetch follows, each re-checked, range 0–10. `0` refuses every redirect. Used by AI proxy passthrough, admin LLM endpoints, GitLab profile/API calls and `check_dns_status`. If settings cannot be read, no redirect is followed. Category **Operations**. | GitLab sign-in and API requests refuse private and metadata hosts. OAuth code exchange and token refresh refuse redirects; profile and API requests follow only validated hops within the configured cap. Node control calls refuse redirects. Workspace previews preserve application redirects while refusing any redirect that exposes the SAM proxy token. @@ -1702,18 +1700,18 @@ The tunnel environment settings below are provisioning inputs: a VM keeps the tr Tunnel API retries and resource cleanup use **Admin → Settings → Operations** instead of deployment variables. These controls apply to subsequent calls and cleanup sweeps without redeploying: -| Admin setting | Default | Meaning | -| ----------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `vmTunnels.apiAttempts` | `3` | Provisioning attempts for transient GET/PUT/DELETE failures, range 1–10. Creation is never retried; cleanup uses one attempt per request. | -| `vmTunnels.apiRetryDelayMs` | `250` | Linear retry delay step in milliseconds, range 1–30000. | -| `vmTunnels.cleanupRequestTimeoutMs` | `10000` | Per-request background timeout, range 1–30000 ms, capped by `CF_API_TIMEOUT_MS`. | -| `vmTunnels.cleanupBatchSize` | `10` | Journal rows processed per sweep, range 1–100. | -| `vmTunnels.cleanupSweepBudgetMs` | `30000` | Cloudflare I/O deadline for the sweep, range 1–120000 ms. Cancels an in-flight request; D1 bookkeeping finishes afterward and remaining rows stay due. | -| `vmTunnels.cleanupBackoffBaseMs` | `60000` | Initial cleanup retry delay, range 1–86400000 ms. | -| `vmTunnels.cleanupBackoffMaxMs` | `3600000` | Maximum cleanup retry delay, range 1–604800000 ms. Ownership remains recorded until cleanup succeeds. | -| `vmTunnels.cleanupStuckAttempts` | `6` | Failed attempts before subsequent failures are logged at error severity, range 1–100. | +| Admin setting | Default | Meaning | +| ----------------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `vmTunnels.apiAttempts` | `3` | Provisioning attempts for transient GET/PUT/DELETE failures, range 1–10. Creation is never retried; cleanup uses one attempt per request. | +| `vmTunnels.apiRetryDelayMs` | `250` | Linear retry delay step in milliseconds, range 1–30000. | +| `vmTunnels.cleanupRequestTimeoutMs` | `10000` | Per-request background timeout, range 1–30000 ms, capped by `CF_API_TIMEOUT_MS`. | +| `vmTunnels.cleanupBatchSize` | `10` | Journal rows processed per sweep, range 1–100. | +| `vmTunnels.cleanupSweepBudgetMs` | `30000` | Cloudflare I/O deadline for the sweep, range 1–120000 ms. Cancels an in-flight request; D1 bookkeeping finishes afterward and remaining rows stay due. | +| `vmTunnels.cleanupBackoffBaseMs` | `60000` | Initial cleanup retry delay, range 1–86400000 ms. | +| `vmTunnels.cleanupBackoffMaxMs` | `3600000` | Maximum cleanup retry delay, range 1–604800000 ms. Ownership remains recorded until cleanup succeeds. | +| `vmTunnels.cleanupStuckAttempts` | `6` | Failed attempts before subsequent failures are logged at error severity, range 1–100. | | `vmTunnels.provisioningBudgetMs` | `20000` | Extra time a durable provisioning attempt (direct workspace or node creation) gets for tunnel setup, on top of the attempt budget `operations.nodeProvisioningAttemptDeadlineMs` (default 60000), range 1–120000 ms. Tunnel setup is resumable: an attempt that still runs out continues from its recorded progress on the next attempt. | -| `vmTunnels.pendingCreateSettleMs` | `900000` | How long cleanup keeps waiting for a tunnel or DNS create whose response was never observed, range 60000–86400000 ms. | +| `vmTunnels.pendingCreateSettleMs` | `900000` | How long cleanup keeps waiting for a tunnel or DNS create whose response was never observed, range 60000–86400000 ms. | If a Cloudflare create response is lost, cleanup retains the ownership journal and checks again at the capped backoff interval, even after finding no remaining resources. This prevents a delayed create from leaving an untracked tunnel or DNS record. Once `vmTunnels.pendingCreateSettleMs` has passed since the last unobserved create, a cleanup that finds and deletes everything left for that incarnation (or finds nothing) marks the row cleaned (`pendingCreateSettled` in `apps/api/src/services/node-tunnel-cleanup.ts`); at the defaults a stranded row is cleaned within about 30 minutes. Every failed or deadline-cut provisioning attempt records the tunnel step it stopped in and the cause, in the `node_provisioning.attempt_failed` / `node_provisioning.attempt_aborted` log and in the journal row's `last_error`. @@ -2020,7 +2018,7 @@ External analytics forwarding is off by default. When enabled, SAM forwards only | Optional Worker variable | Default | Meaning | | --------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `PROJECT_DATA_ARCHIVE_COMPACT_ENABLED` | `false` | Write new archives as compact SQLite + compressed R2; existing formats remain readable. | -| `PROJECT_DATA_ARCHIVE_DAILY_WRITE_BUDGET` | `250000` | Installation-wide daily allowance of ESTIMATE UNITS (not billed rows) for compact migrations; 0 pauses admission of new migrations. A migration reserves its whole estimate once, when it is journaled; resuming it on later passes charges nothing. The checked-in `wrangler.toml` and production GitHub Environment override ship `6000000` in lockstep. At factor 2, the measured fixture reserves 6476 units per 2100 raw rows; 72k rows/hour needs ~5.33M units/day. The previous 2400000 allowance could not sustain that target. This is a reservation ceiling, not billed usage; see the throughput and cost discussion above. | +| `PROJECT_DATA_ARCHIVE_DAILY_WRITE_BUDGET` | `250000` | Installation-wide daily allowance of ESTIMATE UNITS (not billed rows) for compact migrations; 0 pauses admission of new migrations. A migration reserves its whole estimate once, when it is journaled; resuming it on later passes charges nothing. The checked-in `wrangler.toml` and production GitHub Environment override ship `6000000` in lockstep. At factor 2, the measured fixture reserves 6476 units per 2100 raw rows; 72k rows/hour needs ~5.33M units/day. The previous 2400000 allowance could not sustain that target. This is a reservation ceiling, not billed usage; see the throughput and cost discussion above. | | `PROJECT_DATA_ARCHIVE_WRITE_ESTIMATE_FACTOR` | `32` | Safety multiplier applied to the row inventory `estimateArchiveWrites` already counts (rows, archived tool payloads, grouped rows, and 512-byte units of grouped FTS text, including source deletion) — NOT an independent amplification factor. The checked-in `wrangler.toml` ships `2`. Production measurement 2026-09-14: two `project_data_archive_write_budget` samples an hour apart give ~65,001 estimated writes per migration, i.e. ~8,000 inventory units at the then-shipped factor of 8; four isolated archive ticks billed 5,950/6,436/7,942/9,823 Durable Object rows. Billed rows per inventory unit therefore spans 0.74-1.23, and 2 exceeds the worst observed ratio by ~63%. Raising it does not make the work safer, only more expensive in budget terms: at 8 the same allowance bought 12 migrations/day while the hourly cadence allowed 24, so half the sweep ticks reclaimed nothing. Sample size is small (2 budget samples, 4 telemetry buckets) — re-measure before changing it. | | `PROJECT_DATA_ARCHIVE_R2_TIMEOUT_MS` | `10000` | R2 I/O deadline shared across each compact read/export/seal operation, in milliseconds. A chunk write gives each of its R2 calls its own deadline of this length. | | `PROJECT_DATA_ARCHIVE_BUDGET_RECEIPT_RETENTION_MS` | `604800000` | Unused reservation receipt retention (7 days); clamped to at least one UTC budget day. | @@ -2082,7 +2080,7 @@ Installation admins edit these at **Admin → Settings**. They use the existing | `deployments.buildContextStartTimeoutMs` | 10,000 | Bounds control-plane wait for source collection acceptance | | `deployments.buildContextMaxBytes` | 2 GiB | Maximum raw tar (including headers) and compressed bundle bytes | | `deployments.buildContextCollectTimeoutMs` | 120,000 | Source collection deadline | -| `deployments.buildContextUploadTtlSeconds` | 300 | Presigned upload/download URL lifetime | +| `deployments.buildContextUploadTtlSeconds` | 300 | Presigned upload/download URL lifetime | | `deployments.buildContextRetentionHours` | 48 | Minimum age before abandoned/terminal bundles are deleted | | `deployments.buildContextCleanupBudgetMs` | 10,000 | Work budget per daily cleanup pass | | `deployments.buildContextCleanupPageSize` | 250 | R2 listing page size; a persisted cursor resumes remaining pages | @@ -2093,21 +2091,21 @@ Collection has no file-count cutoff. For a 100,000-file context near 1.5 GiB, ta Edit runtime controls in **Admin → Settings**. Instant sessions always use Cloudflare; `deployments.buildExecutor` selects the VM-session executor. These controls are independent of the default-off context shadow probe. Keep the VM setting at `node` until staging validates Cloudflare publishing from a VM with unchanged source build/save counters and a served release; that validation remains pending. -| Runtime setting | Default | Meaning | -| ----------------------------------------- | --------- | --------------------------------------------------------------------------------------------------- | -| `deployments.buildExecutor` | `node` | VM build executor (`node` or `cloudflare`); explicit Cloudflare selection never silently falls back | -| `deployments.builderMaxConcurrent` | 6 | Platform reservations, clamped to the deployed class capacity; maximum 6 | -| `deployments.builderProjectMaxConcurrent` | 2 | Per-project reservations; maximum 2 | -| `deployments.builderReservationGraceMs` | 300,000 | Grace after the stored builder deadline before cron force-releases unconfirmed reservations with an alert; active jobs become unknown, and physical shutdown may remain unconfirmed | -| `deployments.builderDeadlineMs` | 1,200,000 | Absolute deadline after first admission; also capped by the overall publish-job deadline | -| `deployments.builderCapacityBackoffMs` | 30,000 | Delay before retrying platform capacity errors | -| `deployments.builderDrainLimit` | 6 | Maximum queued jobs considered per cron tick | -| `deployments.builderDaemonReadyTimeoutMs` | 60,000 | DinD readiness deadline | -| `deployments.publishCallbackMaxBodyBytes` | 1,048,576 | Maximum actual JSON bytes for authenticated publish events, image artifacts and release callbacks, for source and builder tokens. | -| `deployments.builderCallbackTimeoutMs` | 30,000 | Control-plane HTTP timeout; also controls bootstrap HTTP shutdown | -| `deployments.builderCallbackAttempts` | 3 | Maximum attempts for retryable callbacks | -| `deployments.builderCallbackRetryDelayMs` | 5,000 | Delay between retryable callbacks | -| `deployments.builderHeartbeatIntervalMs` | 15,000 | Builder liveness callback interval | +| Runtime setting | Default | Meaning | +| ----------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `deployments.buildExecutor` | `node` | VM build executor (`node` or `cloudflare`); explicit Cloudflare selection never silently falls back | +| `deployments.builderMaxConcurrent` | 6 | Platform reservations, clamped to the deployed class capacity; maximum 6 | +| `deployments.builderProjectMaxConcurrent` | 2 | Per-project reservations; maximum 2 | +| `deployments.builderReservationGraceMs` | 300,000 | Grace after the stored builder deadline before cron force-releases unconfirmed reservations with an alert; active jobs become unknown, and physical shutdown may remain unconfirmed | +| `deployments.builderDeadlineMs` | 1,200,000 | Absolute deadline after first admission; also capped by the overall publish-job deadline | +| `deployments.builderCapacityBackoffMs` | 30,000 | Delay before retrying platform capacity errors | +| `deployments.builderDrainLimit` | 6 | Maximum queued jobs considered per cron tick | +| `deployments.builderDaemonReadyTimeoutMs` | 60,000 | DinD readiness deadline | +| `deployments.publishCallbackMaxBodyBytes` | 1,048,576 | Maximum actual JSON bytes for authenticated publish events, image artifacts and release callbacks, for source and builder tokens. | +| `deployments.builderCallbackTimeoutMs` | 30,000 | Control-plane HTTP timeout; also controls bootstrap HTTP shutdown | +| `deployments.builderCallbackAttempts` | 3 | Maximum attempts for retryable callbacks | +| `deployments.builderCallbackRetryDelayMs` | 5,000 | Delay between retryable callbacks | +| `deployments.builderHeartbeatIntervalMs` | 15,000 | Builder liveness callback interval | Deployment topology is configured through GitHub Environment variables: @@ -2119,3 +2117,51 @@ Deployment topology is configured through GitHub Environment variables: The deploy generator mirrors actual class capacity into the Worker binding `DEPLOY_BUILDER_CLASS_MAX_INSTANCES`; do not set that binding independently. Builder images contain Docker, Compose and `sam-builder`; no installation or user credentials are baked into them. Each job receives only a job-and-attempt callback token and short-lived presigned URLs for its context and image keys. The control plane checks the builder against `VM_AGENT_REQUIRED_VERSION`, when configured, before accepting a job. Application builders have unrestricted internet egress. Package installation in Dockerfile `RUN` steps and direct presigned object transfers use normal TLS trust; there is no builder host allowlist, outbound proxy, or interception CA setting. Isolation relies on the dedicated microVM, one-job callback authority, and hard deadline. See the [security architecture](/docs/architecture/security/#application-build-executor). + +## OpenAI-compatible model endpoint + +A superadmin can set these keys under **Admin → Settings → AI models**. Reset +`llm.openAICompatible.baseUrl` to restore normal Cloudflare routing. No endpoint is enabled by +default (`services/llm-endpoint-settings.ts`). + +| Setting | Default | Meaning | +| ------------------------------------------ | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `llm.openAICompatible.baseUrl` | unset | OpenAI-style base URL, such as `https://llm.example.com/v1`; omit `/chat/completions`. Overrides Workers AI chat, task titles, diagnosis and SAM agent calls. | +| `llm.openAICompatible.apiKey` | unset | Optional Bearer key, encrypted in platform credentials and never returned by settings reads. | +| `llm.openAICompatible.model` | unset | Endpoint model ID; falls back to the caller's requested model. | +| `llm.openAICompatible.agentModel` | unset | Override for SAM and project agents. | +| `llm.openAICompatible.taskTitleModel` | unset | Override for title generation. | +| `llm.openAICompatible.diagnosisModel` | unset | Override for diagnosis. | +| `llm.openAICompatible.aiProxyModel` | unset | Override for the proxy's Workers AI chat route. | +| `llm.openAICompatible.allowPrivateNetwork` | `false` | Explicitly allow an operator endpoint on a private host. Metadata/link-local hosts remain forbidden. | +| `aiProxy.directUpstreamEnabled` | `false` | Enable platform and BYO AI proxy routes when no addressable Cloudflare AI Gateway exists. Requires a provider credential for platform calls. Ignored when a gateway is addressable. | + +Endpoint settings reuse the existing per-isolate settings cache (up to 60 seconds); a warm, +unconfigured Cloudflare call performs no additional D1 or credential reads. Admin changes +invalidate the local cache immediately. Unreadable configuration refuses the request instead of +sending prompts to another provider: the Workers AI proxy returns 503, and title generation falls +back to truncation. Title and diagnosis settings lookups receive at most one quarter of the +caller's inference time budget (`services/platform-capabilities.ts:resolveLlmEndpointCapability`, +`services/llm-chat-target.ts:resolveWorkersAiChatTargetWithin`). + +Configured endpoints receive their own model and key, with no Cloudflare attribution headers or +Workers AI template controls. Every redirect is validated; cross-origin body replay is refused and +credentials are stripped on cross-origin GET redirects. Streaming calls preserve the caller's +`stream_options.include_usage` choice. Missing usage is estimated for token budgets; estimates +are never presented as measured run usage (`packages/ai-proxy/src/llm-chat-target.ts`, +`packages/ai-proxy/src/ai-token-usage-accounting.ts`). + +Proxy routes authenticate before checking availability, so unauthenticated callers always get 401. Availability means the operator switch permits proxy calls and either a gateway ID **and +account ID** form an addressable gateway, or the admin explicitly enabled direct upstreams. A +standalone gateway ID is insufficient. Custom-baseURL credentials are returned to workspaces only +as a SAM proxy configuration; if the proxy does not serve them, agent-key returns 404 +(`services/ai-proxy-availability.ts:isAiProxyEnabled`, `routes/workspaces/runtime-agent-key.ts`). + +Daily token budgets apply to both routes. Without a gateway, SAM estimates platform model spend +from its catalog into the existing per-user budget counter, and the monthly cap reads that total; +the provider invoice remains authoritative. A missing local cost read refuses a capped call. +The KV fallback reads at most 31 days in parallel. With a gateway, the hourly gateway-log cache +remains the spend record. An operator endpoint's model has no catalog price and contributes zero +dollars to this cap, including on installations with a gateway; set spending limits at the +endpoint/provider as appropriate (`packages/ai-proxy/src/ai-monthly-cost-cap.ts`, +`packages/ai-proxy/src/ai-gateway-availability.ts:isMonthlyCostCapAvailable`). diff --git a/packages/ai-proxy/src/ai-billing.ts b/packages/ai-proxy/src/ai-billing.ts index 15769f5d5e..71d736e47f 100644 --- a/packages/ai-proxy/src/ai-billing.ts +++ b/packages/ai-proxy/src/ai-billing.ts @@ -15,6 +15,7 @@ import { } from '@simple-agent-manager/shared'; import { log } from '@simple-agent-manager/worker-core'; +import { resolveAiGatewayId } from './ai-gateway-availability'; import type { AiProxyEnv } from './env'; import type { AiProxyPorts } from './ports'; @@ -55,6 +56,7 @@ function isValidBillingMode(value: string): value is BillingMode { * Prefers the explicit CF_AIG_TOKEN, falls back to CF_API_TOKEN (already a Worker secret). */ export function resolveUnifiedBillingToken(env: AiProxyEnv): string | undefined { + if (!resolveAiGatewayId(env)) return undefined; return env.CF_AIG_TOKEN ?? env.CF_API_TOKEN ?? undefined; } diff --git a/packages/ai-proxy/src/ai-cost-pricing.ts b/packages/ai-proxy/src/ai-cost-pricing.ts new file mode 100644 index 0000000000..bf96f3ad51 --- /dev/null +++ b/packages/ai-proxy/src/ai-cost-pricing.ts @@ -0,0 +1,49 @@ +/** + * List-price estimate of one model call, from SAM's own price table (`PLATFORM_AI_MODELS`). + * + * Used where SAM is the only spend record: the SAM operator model, and the AI proxy on an + * installation without Cloudflare AI Gateway (`hasLocalAiCostMetering`). It misses provider + * discounts and batch rates and lags provider price changes until the catalog is updated; the + * provider invoice stays authoritative. Good enough for a per-user cap. + */ +import { PLATFORM_AI_MODELS, type PlatformAIModel } from '@simple-agent-manager/shared'; + +/** + * Anthropic bills a 5-minute prompt-cache write at 1.25x the base input price (Anthropic pricing, + * "Prompt caching"). The catalog carries no write price, so the multiplier lives here. + */ +export const ANTHROPIC_CACHE_WRITE_PRICE_MULTIPLIER = 1.25; + +export interface PricedTokenUsage { + /** Every prompt token, including the cached and cache-write ones below. */ + inputTokens: number; + outputTokens: number; + /** Prompt tokens read from the provider's cache (cached-input price). */ + cachedInputTokens?: number; + /** Prompt tokens written to the provider's cache (input price x the write multiplier). */ + cacheWriteInputTokens?: number; +} + +export function findPricedModel(modelId: string): PlatformAIModel | null { + return PLATFORM_AI_MODELS.find((model) => model.id === modelId) ?? null; +} + +function nonNegative(value: number | undefined): number { + return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0; +} + +/** USD for one call at catalog list prices. */ +export function priceModelUsageUsd(model: PlatformAIModel, usage: PricedTokenUsage): number { + const input = nonNegative(usage.inputTokens); + const cached = Math.min(input, nonNegative(usage.cachedInputTokens)); + const cacheWrite = Math.min(input - cached, nonNegative(usage.cacheWriteInputTokens)); + const uncached = input - cached - cacheWrite; + const cachedRate = model.costPer1kCachedInputTokens ?? model.costPer1kInputTokens; + return ( + (uncached * model.costPer1kInputTokens + + cached * cachedRate + + cacheWrite * model.costPer1kInputTokens * ANTHROPIC_CACHE_WRITE_PRICE_MULTIPLIER + + nonNegative(usage.outputTokens) * model.costPer1kOutputTokens) / + 1000 + ); +} diff --git a/packages/ai-proxy/src/ai-gateway-availability.ts b/packages/ai-proxy/src/ai-gateway-availability.ts new file mode 100644 index 0000000000..4a6879aef8 --- /dev/null +++ b/packages/ai-proxy/src/ai-gateway-availability.ts @@ -0,0 +1,78 @@ +/** + * Whether this installation can route AI calls through Cloudflare AI Gateway, and what follows + * from that. Pure functions of the environment; the worker's platform-capability module + * (`apps/api/src/services/platform-capabilities.ts`) re-exports them so there is one answer. + */ +import type { AiProxyEnv } from './env'; + +function present(value: string | undefined): boolean { + return typeof value === 'string' && value.trim().length > 0; +} + +/** Account-scoped Cloudflare REST API (Workers AI REST, Analytics SQL, Observability). */ +export function hasCloudflareAccountApi( + env: Partial> +): boolean { + return present(env.CF_ACCOUNT_ID) && present(env.CF_API_TOKEN); +} + +/** + * The AI Gateway id to route through, or null when the gateway cannot be addressed. + * + * `AI_GATEWAY_ID` alone is not the condition: `wrangler.toml` ships a default id, so a + * runtime with no Cloudflare account still has it set. Every gateway URL is + * `gateway.ai.cloudflare.com/v1///...`, so it also needs the account id. + */ +export function resolveAiGatewayId( + env: Partial> +): string | null { + const gatewayId = env.AI_GATEWAY_ID?.trim(); + if (!gatewayId || !present(env.CF_ACCOUNT_ID)) return null; + return gatewayId; +} + +/** + * Whether SAM prices AI calls itself (catalog list price x reported usage) and stores the result + * in the per-user `AiTokenBudgetCounter`. True exactly when there is no addressable AI Gateway: + * there the gateway's logs are the spend record (`runMonthlyCostAggregation`), and a second, + * co-equal record would disagree with it (rule 74). Without one SAM's own record is the only one. + */ +export function hasLocalAiCostMetering( + env: Partial> +): boolean { + return resolveAiGatewayId(env) === null; +} + +/** + * Whether a monthly AI dollar cap can be enforced here. + * + * - With an AI Gateway the month's spend comes from gateway logs, read by + * `runMonthlyCostAggregation` through the account API (gateway id, account id and API token all + * required). A gateway without the account API cannot be priced, so the cap is reported + * unavailable there rather than accepted and silently never enforced. + * - Without a gateway SAM meters platform-billed proxy calls and SAM agent calls itself + * (`hasLocalAiCostMetering`) and the cap reads that total (`getLocalMonthlyAiCostUsd`). Calls to + * a model with no catalog price (an operator's own endpoint model) count $0. + * + * Calls served by an admin-configured OpenAI-compatible endpoint never reach gateway logs, so on + * an installation with both, the cap counts only gateway-routed spend (documented in + * reference/configuration.md). Daily token budgets apply either way. + */ +export function isMonthlyCostCapAvailable( + env: Partial> +): boolean { + if (hasLocalAiCostMetering(env)) return true; + return hasCloudflareAccountApi(env); +} + +/** + * AI Gateway request headers (`cf-aig-metadata` attribution with user and workspace ids), or + * nothing when the call goes straight to the provider. Only the gateway reads them, so a + * direct call to OpenAI or Anthropic must not carry SAM's internal ids. + */ +export function aiGatewayOnlyHeaders( + env: Partial>, + headers: Record +): Record { + return resolveAiGatewayId(env) ? headers : {}; +} diff --git a/packages/ai-proxy/src/ai-monthly-cost-cap.ts b/packages/ai-proxy/src/ai-monthly-cost-cap.ts index 756338bce1..c0b7726d4f 100644 --- a/packages/ai-proxy/src/ai-monthly-cost-cap.ts +++ b/packages/ai-proxy/src/ai-monthly-cost-cap.ts @@ -5,6 +5,11 @@ import { AI_MONTHLY_COST_CACHE_KV_PREFIX } from '@simple-agent-manager/shared'; import { getUserBudgetSettings } from './ai-budget-settings'; +import { hasLocalAiCostMetering, isMonthlyCostCapAvailable } from './ai-gateway-availability'; +// Cycle with ai-token-budget.ts (it re-exports this module); both sides use the other's functions +// only inside function bodies, so evaluation order does not matter. +import { getProviderUsage } from './ai-token-budget'; +import type { AiProxyEnv } from './env'; // ============================================================================= // Monthly Cost Cap Enforcement (KV-cached, written by cron) @@ -29,18 +34,61 @@ export async function getCachedMonthlyCost( return Number.isNaN(parsed) ? null : parsed; } +export interface MonthlyCostCapCheck { + allowed: boolean; + costUsd: number; + capUsd: number | null; +} + +/** First instant of the current UTC month. */ +function currentUtcMonthStart(now = new Date()): Date { + return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)); +} + +/** + * This UTC month's AI spend that SAM priced itself (`hasLocalAiCostMetering`): the sum of the + * per-day `estimated_cost_usd` rows in the user's `AiTokenBudgetCounter` (KV fallback without the + * Durable Object). Only meaningful on an installation without AI Gateway. + */ +export async function getLocalMonthlyAiCostUsd( + kv: KVNamespace, + userId: string, + env: AiProxyEnv +): Promise { + // One DO RPC when available. Otherwise at most 31 independent daily KV reads in one + // wave; the calendar month is the hard bound (no unbounded-history fan-out). + const now = new Date(); + const entries = env.AI_TOKEN_BUDGET_COUNTER + ? await getProviderUsage(kv, userId, currentUtcMonthStart(now), env) + : ( + await Promise.all( + Array.from({ length: now.getUTCDate() }, (_, day) => { + const date = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), day + 1)); + return getProviderUsage(kv, userId, date, env, date); + }) + ) + ).flat(); + return entries.reduce((sum, entry) => sum + (entry.estimatedCostUsd || 0), 0); +} + /** * Check whether a user is within their monthly cost cap. * - * Reads from KV cache (written by hourly cron). If no cache exists, - * the check passes (fail-open) — the cron will populate it next run. + * With AI Gateway: reads the KV cache written by the hourly gateway-log cron. With no cache yet + * the check passes (fail-open); the cron fills it within the hour, and the daily token budget + * still applies. + * + * Without AI Gateway: reads SAM's own priced total for the month (`getLocalMonthlyAiCostUsd`), + * which every platform-billed proxy call and SAM agent call adds to after its response. A failed + * read refuses the call (fail closed): there is no cron to correct it later. * - * Returns { allowed, costUsd, capUsd } where capUsd is null if no cap is set. + * A gateway without the account API cannot be priced: not enforceable, no KV read. */ export async function checkMonthlyCostCap( kv: KVNamespace, - userId: string -): Promise<{ allowed: boolean; costUsd: number; capUsd: number | null }> { + userId: string, + env: AiProxyEnv +): Promise { const userSettings = await getUserBudgetSettings(kv, userId); const capUsd = userSettings?.monthlyCostCapUsd ?? null; @@ -49,6 +97,20 @@ export async function checkMonthlyCostCap( return { allowed: true, costUsd: 0, capUsd }; } + if (!isMonthlyCostCapAvailable(env)) { + return { allowed: true, costUsd: 0, capUsd }; + } + + if (hasLocalAiCostMetering(env)) { + let costUsd: number; + try { + costUsd = await getLocalMonthlyAiCostUsd(kv, userId, env); + } catch { + return { allowed: false, costUsd: 0, capUsd }; + } + return { allowed: costUsd < capUsd, costUsd, capUsd }; + } + const costUsd = await getCachedMonthlyCost(kv, userId); // No cache yet — fail-open until the hourly cron populates usage data. diff --git a/packages/ai-proxy/src/ai-monthly-cost-cron.ts b/packages/ai-proxy/src/ai-monthly-cost-cron.ts index 6297679204..69e071715d 100644 --- a/packages/ai-proxy/src/ai-monthly-cost-cron.ts +++ b/packages/ai-proxy/src/ai-monthly-cost-cron.ts @@ -10,6 +10,7 @@ import { } from '@simple-agent-manager/shared'; import { log } from '@simple-agent-manager/worker-core'; +import { resolveAiGatewayId } from './ai-gateway-availability'; import { type GatewayLogsPorts, getGatewayPeriodBounds, @@ -53,7 +54,7 @@ export async function runMonthlyCostAggregation( env: AiProxyEnv, ports: GatewayLogsPorts ): Promise { - const gatewayId = env.AI_GATEWAY_ID; + const gatewayId = resolveAiGatewayId(env); if (!gatewayId) { return { enabled: false, usersUpdated: 0, totalEntries: 0, errors: 0 }; } diff --git a/packages/ai-proxy/src/ai-proxy-shared.ts b/packages/ai-proxy/src/ai-proxy-shared.ts index 97da02bd27..11e9319a66 100644 --- a/packages/ai-proxy/src/ai-proxy-shared.ts +++ b/packages/ai-proxy/src/ai-proxy-shared.ts @@ -10,7 +10,14 @@ */ import { expectJsonRecord } from '@simple-agent-manager/worker-core'; +import { resolveAiGatewayId } from './ai-gateway-availability'; import type { AiProxyEnv } from './env'; +import { + type ChatCompletionsTarget, + chatTargetHeaders, + fetchChatTarget, + isCloudflareChatTarget, +} from './llm-chat-target'; // ============================================================================= // Model Validation @@ -61,7 +68,7 @@ export function buildAIGatewayMetadata(opts: { /** Build upstream URL for Anthropic Messages API via AI Gateway. */ export function buildAnthropicGatewayUrl(env: AiProxyEnv): string { - const gatewayId = env.AI_GATEWAY_ID; + const gatewayId = resolveAiGatewayId(env); if (gatewayId) { return `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/anthropic/v1/messages`; } @@ -71,7 +78,7 @@ export function buildAnthropicGatewayUrl(env: AiProxyEnv): string { /** Build upstream URL for Workers AI chat completions via AI Gateway. */ export function buildWorkersAIGatewayUrl(env: AiProxyEnv): string { - const gatewayId = env.AI_GATEWAY_ID; + const gatewayId = resolveAiGatewayId(env); if (gatewayId) { return `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/workers-ai/v1/chat/completions`; } @@ -196,24 +203,33 @@ export async function readSafeGatewayErrorDiagnostic( export async function fetchWorkersAIChatCompletion( env: AiProxyEnv, - options: WorkersAIChatCompletionOptions + options: WorkersAIChatCompletionOptions, + target?: ChatCompletionsTarget, + signal?: AbortSignal ): Promise { - const response = await fetch(buildWorkersAIGatewayUrl(env), { + const resolved = target ?? { + kind: 'cloudflare-gateway' as const, + url: buildWorkersAIGatewayUrl(env), + baseUrl: '', + apiKey: env.CF_API_TOKEN, + model: options.modelId, + allowPrivateNetwork: false, + }; + const cloudflare = isCloudflareChatTarget(resolved); + const response = await fetchChatTarget(resolved, { method: 'POST', - signal: AbortSignal.timeout(options.timeoutMs), - headers: { - Authorization: `Bearer ${env.CF_API_TOKEN}`, - 'Content-Type': 'application/json', - 'cf-aig-metadata': JSON.stringify(options.metadata), - }, + signal: signal ?? AbortSignal.timeout(options.timeoutMs), + headers: chatTargetHeaders(resolved, { 'cf-aig-metadata': JSON.stringify(options.metadata) }), body: JSON.stringify({ - model: options.modelId, + model: resolved.model, max_tokens: options.maxTokens, messages: options.messages, - ...(options.reasoningEffort !== undefined + ...(cloudflare && options.reasoningEffort !== undefined ? { reasoning_effort: options.reasoningEffort } : {}), - ...(options.chatTemplateKwargs ? { chat_template_kwargs: options.chatTemplateKwargs } : {}), + ...(cloudflare && options.chatTemplateKwargs + ? { chat_template_kwargs: options.chatTemplateKwargs } + : {}), }), }); @@ -237,7 +253,7 @@ export async function fetchWorkersAIChatCompletion( /** Build upstream URL for Anthropic token counting via AI Gateway. */ export function buildAnthropicCountTokensUrl(env: AiProxyEnv): string { - const gatewayId = env.AI_GATEWAY_ID; + const gatewayId = resolveAiGatewayId(env); if (gatewayId) { return `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/anthropic/v1/messages/count_tokens`; } diff --git a/packages/ai-proxy/src/ai-token-budget.ts b/packages/ai-proxy/src/ai-token-budget.ts index 21eb04c2c9..f81f50c8a5 100644 --- a/packages/ai-proxy/src/ai-token-budget.ts +++ b/packages/ai-proxy/src/ai-token-budget.ts @@ -1,3 +1,4 @@ +import { hasLocalAiCostMetering } from './ai-gateway-availability'; /** * Per-user daily token budget tracking. * @@ -365,7 +366,13 @@ export async function incrementProviderUsage( const ttl = parseInt(env?.AI_USAGE_BUDGET_TTL_SECONDS || '', 10) || DEFAULT_AI_USAGE_BUDGET_TTL_SECONDS; - await kv.put(key, JSON.stringify(existing), { expirationTtl: ttl }); + // Local monthly caps read these daily rows. Retain them through the end of their month + // plus the existing grace TTL; a later BYO write must not shorten a priced row's lifetime. + const now = new Date(); + const monthEnd = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1); + const retention = + env && hasLocalAiCostMetering(env) ? Math.ceil((monthEnd - now.getTime()) / 1000) + ttl : ttl; + await kv.put(key, JSON.stringify(existing), { expirationTtl: retention }); } export async function getProviderUsage( @@ -453,7 +460,7 @@ export async function checkAiUsageGate( return { allowed: false, reason: 'daily-token-budget', budget }; } - const monthlyCap = await checkMonthlyCostCap(kv, userId); + const monthlyCap = await checkMonthlyCostCap(kv, userId, env); if (!monthlyCap.allowed) { return { allowed: false, reason: 'monthly-cost-cap', monthlyCap }; } diff --git a/packages/ai-proxy/src/ai-token-usage-accounting.ts b/packages/ai-proxy/src/ai-token-usage-accounting.ts index cdcd194409..4389cb2787 100644 --- a/packages/ai-proxy/src/ai-token-usage-accounting.ts +++ b/packages/ai-proxy/src/ai-token-usage-accounting.ts @@ -1,6 +1,8 @@ import { log } from '@simple-agent-manager/worker-core'; import { maybeJsonRecord } from '@simple-agent-manager/worker-core'; +import { findPricedModel, priceModelUsageUsd } from './ai-cost-pricing'; +import { hasLocalAiCostMetering } from './ai-gateway-availability'; import { type AiProviderUsageAttribution, incrementProviderUsage, @@ -19,6 +21,7 @@ export interface ExtractedTokenUsage { cacheWriteTokens?: number; /** Reasoning tokens reported separately (OpenAI); also counted in `outputTokens`. */ reasoningTokens?: number; + outputBytes?: number; } /** @@ -38,6 +41,9 @@ export interface TokenUsageAccountingOptions { userId: string; format: TokenUsageFormat; fallbackInputTokens?: number; + /** Platform-billed catalog model; BYO and custom endpoints leave this unset. */ + costModelId?: string; + estimateMissingUsage?: boolean; provider?: AiProviderUsageAttribution; executionCtx?: Pick; /** @@ -56,6 +62,8 @@ export async function accountTokenUsageFromJson( options: TokenUsageAccountingOptions ): Promise { const usage = extractJsonTokenUsage(payload, options.format); + if (options.estimateMissingUsage && usage.outputTokens === undefined) + usage.outputBytes = jsonOutputByteLength(payload); await incrementExtractedUsage(usage, options); } @@ -64,8 +72,8 @@ export function accountTokenUsageFromStream( options: TokenUsageAccountingOptions ): void { scheduleTokenAccounting( - collectStreamTokenUsage(stream, options.format).then((usage) => - incrementExtractedUsage(usage, options) + collectStreamTokenUsage(stream, options.format, options.estimateMissingUsage === true).then( + (usage) => incrementExtractedUsage(usage, options) ), options ); @@ -99,7 +107,10 @@ export async function attachTokenUsageAccounting( } try { - await accountTokenUsageFromJson(payload, { ...options, fallbackInputTokens: undefined }); + await accountTokenUsageFromJson( + payload, + options.estimateMissingUsage ? options : { ...options, fallbackInputTokens: undefined } + ); } catch (err) { log.warn('ai_proxy.token_usage_increment_failed', { userId: options.userId, @@ -199,12 +210,13 @@ export function estimateInputTokensFromMessages(messages: unknown): number { export async function collectStreamTokenUsage( stream: ReadableStream, - format: TokenUsageFormat + format: TokenUsageFormat, + estimate = false ): Promise { const reader = stream.getReader(); const decoder = new TextDecoder(); let buffer = ''; - const usage: ExtractedTokenUsage = {}; + const usage: ExtractedTokenUsage = estimate ? { outputBytes: 0 } : {}; try { let keepReading = true; @@ -231,18 +243,41 @@ async function incrementExtractedUsage( options: TokenUsageAccountingOptions ): Promise { const inputTokens = usage.inputTokens ?? options.fallbackInputTokens ?? 0; - const outputTokens = usage.outputTokens ?? 0; + const outputTokens = + usage.outputTokens ?? + (options.estimateMissingUsage ? Math.ceil((usage.outputBytes ?? 0) / 3) : 0); if (inputTokens <= 0 && outputTokens <= 0) return; await incrementTokenUsage(options.env.KV, options.userId, inputTokens, outputTokens, options.env); - if (options.provider) { + const model = + options.costModelId && hasLocalAiCostMetering(options.env) + ? findPricedModel(options.costModelId) + : null; + const provider = + options.provider ?? + (model + ? { providerId: model.provider, providerName: model.provider, dialect: options.format } + : undefined); + if (provider) { + const cached = usage.cacheReadTokens ?? 0; + const writes = usage.cacheWriteTokens ?? 0; + const totalInput = options.format === 'anthropic' ? inputTokens + cached + writes : inputTokens; + const costUsd = model + ? priceModelUsageUsd(model, { + inputTokens: totalInput, + outputTokens, + cachedInputTokens: cached, + cacheWriteInputTokens: writes, + }) + : 0; await incrementProviderUsage( options.env.KV, options.userId, - options.provider, + provider, inputTokens, outputTokens, - options.env + options.env, + ...(options.costModelId ? ([costUsd] as const) : []) ); } // Budget accounting is the billing control and runs first; run usage is telemetry and must @@ -254,7 +289,10 @@ async function incrementExtractedUsage( * Hand the measured usage to `onMeasuredUsage` outside the response path: inside the request's * `waitUntil` when there is one, so a slow D1 write never adds latency to a proxied response. */ -function scheduleMeasuredUsage(usage: ExtractedTokenUsage, options: TokenUsageAccountingOptions): void { +function scheduleMeasuredUsage( + usage: ExtractedTokenUsage, + options: TokenUsageAccountingOptions +): void { if (!options.onMeasuredUsage) return; const pending = recordMeasuredUsage(usage, options); try { @@ -337,6 +375,41 @@ function applyStreamUsage( usage.outputTokens = jsonUsage.outputTokens ?? usage.outputTokens; usage.cacheReadTokens = jsonUsage.cacheReadTokens ?? usage.cacheReadTokens; usage.reasoningTokens = jsonUsage.reasoningTokens ?? usage.reasoningTokens; + if (usage.outputBytes !== undefined) { + usage.outputBytes += choicesOutputByteLength(record.choices, 'delta'); + if ( + typeof record.delta === 'string' && + [ + 'response.output_text.delta', + 'response.function_call_arguments.delta', + 'response.reasoning_text.delta', + ].includes(String(record.type)) + ) + usage.outputBytes += utf8ByteLength(record.delta); + } +} + +const UTF8 = new TextEncoder(); +function utf8ByteLength(text: string): number { + return UTF8.encode(text).byteLength; +} +/** Bytes of generated output in a chat completion's choices (`message`) or chunk (`delta`). */ +function choicesOutputByteLength(choices: unknown, field: 'message' | 'delta'): number { + if (!Array.isArray(choices)) return 0; + let bytes = 0; + for (const choice of choices) { + const part = maybeJsonRecord(maybeJsonRecord(choice)?.[field]); + if (!part) continue; + for (const key of ['content', 'reasoning_content', 'reasoning'] as const) { + if (typeof part[key] === 'string') bytes += utf8ByteLength(part[key]); + } + if (Array.isArray(part.tool_calls)) bytes += utf8ByteLength(JSON.stringify(part.tool_calls)); + } + return bytes; +} + +function jsonOutputByteLength(payload: unknown): number { + return choicesOutputByteLength(maybeJsonRecord(payload)?.choices, 'message'); } function isStreamingResponse(response: Response): boolean { diff --git a/packages/ai-proxy/src/index.ts b/packages/ai-proxy/src/index.ts index 775b68ba12..52345c160b 100644 --- a/packages/ai-proxy/src/index.ts +++ b/packages/ai-proxy/src/index.ts @@ -10,6 +10,14 @@ export { resolveUpstreamAuth, type UpstreamAuth, } from './ai-billing'; +export { findPricedModel, priceModelUsageUsd } from './ai-cost-pricing'; +export { + aiGatewayOnlyHeaders, + hasCloudflareAccountApi, + hasLocalAiCostMetering, + isMonthlyCostCapAvailable, + resolveAiGatewayId, +} from './ai-gateway-availability'; export { aggregateByDay, aggregateByModel, @@ -26,7 +34,9 @@ export { type UsageByProvider, } from './ai-gateway-logs'; export { checkModelTierAllowance, describeModelTierDenial } from './ai-model-tier-gate'; +export { getLocalMonthlyAiCostUsd } from './ai-monthly-cost-cap'; export { type MonthlyCostCronResult, runMonthlyCostAggregation } from './ai-monthly-cost-cron'; +export type { WorkersAIChatCompletionOptions, WorkersAIChatMessage } from './ai-proxy-shared'; export { buildAIGatewayMetadata, buildAnthropicCountTokensUrl, @@ -66,4 +76,12 @@ export { optionalExecutionContext, } from './ai-token-usage-accounting'; export { type AiProxyEnv } from './env'; +export { + type ChatCompletionsTarget, + chatTarget, + chatTargetHeaders, + fetchChatTarget, + isCloudflareChatTarget, + LlmUnavailableError, +} from './llm-chat-target'; export { type AiProxyPorts } from './ports'; diff --git a/packages/ai-proxy/src/llm-chat-target.ts b/packages/ai-proxy/src/llm-chat-target.ts new file mode 100644 index 0000000000..dcfc8822fe --- /dev/null +++ b/packages/ai-proxy/src/llm-chat-target.ts @@ -0,0 +1,91 @@ +import { guardedFetch } from '@simple-agent-manager/worker-core'; + +export interface ChatCompletionsTarget { + kind: 'openai-compatible' | 'cloudflare-gateway' | 'cloudflare-api'; + /** OpenAI-style base URL, without `/chat/completions`. */ + baseUrl: string; + /** The chat completions URL. */ + url: string; + /** Bearer token, or null when the endpoint takes none. */ + apiKey: string | null; + /** Model id to send. */ + model: string; + /** + * The admin opted in to this endpoint being on the private network + * (`llm.openAICompatible.allowPrivateNetwork`). Only meaningful for `openai-compatible`. + */ + allowPrivateNetwork: boolean; + /** Redirect hops the guarded fetch follows (`outbound.maxRedirects`). Only for `openai-compatible`. */ + maxRedirects?: number; +} + +/** + * No endpoint can serve this call. `not_configured` is a designed state (nothing is set up here); + * `settings_unreadable` means the endpoint settings could not be read, so the call was refused + * rather than sent to a provider the admin may have opted out of. + */ +export type LlmUnavailableReason = + 'not_configured' | 'settings_unreadable' | 'private_network_not_allowed'; + +const LLM_UNAVAILABLE_MESSAGES: Record = { + not_configured: + 'No language model is available on this installation. Configure an OpenAI-compatible endpoint in admin settings (AI models).', + settings_unreadable: + 'The language model settings could not be read, so the call was not sent. Try again shortly.', + private_network_not_allowed: + 'The configured language model endpoint is on a private network address. Turn on llm.openAICompatible.allowPrivateNetwork in admin settings (AI models) to allow it.', +}; + +export class LlmUnavailableError extends Error { + constructor( + readonly purpose: string, + readonly reason: LlmUnavailableReason = 'not_configured' + ) { + super(LLM_UNAVAILABLE_MESSAGES[reason]); + this.name = 'LlmUnavailableError'; + } +} + +export function isCloudflareChatTarget(target: ChatCompletionsTarget): boolean { + return target.kind !== 'openai-compatible'; +} + +export function chatTarget( + kind: ChatCompletionsTarget['kind'], + baseUrl: string, + apiKey: string | null, + model: string, + allowPrivateNetwork = false +): ChatCompletionsTarget { + return { kind, baseUrl, url: `${baseUrl}/chat/completions`, apiKey, model, allowPrivateNetwork }; +} + +/** + * Fetch for a chat target's URL (`url` is `target.url` or an AI SDK provider's request URL on the + * same base). An admin-configured endpoint goes through the guarded fetch: its host and every + * redirect hop are checked, and a private-network host needs the admin's opt-in. Cloudflare + * targets are fixed Cloudflare hosts and keep the plain fetch. + */ +export function fetchChatTarget( + target: ChatCompletionsTarget, + init: RequestInit, + url: string = target.url +): Promise { + // eslint-disable-next-line sam/no-unguarded-outbound-fetch -- Cloudflare chooses the fixed Workers AI endpoint for this target + if (isCloudflareChatTarget(target)) return fetch(url, init); + return guardedFetch(url, init, { + allowPrivateNetwork: target.allowPrivateNetwork, + maxRedirects: target.maxRedirects, + }); +} + +export function chatTargetHeaders( + target: ChatCompletionsTarget, + cloudflareHeaders: Record = {} +): Record { + return { + 'Content-Type': 'application/json', + ...(target.apiKey ? { Authorization: `Bearer ${target.apiKey}` } : {}), + ...(isCloudflareChatTarget(target) ? cloudflareHeaders : {}), + }; +} diff --git a/packages/ai-proxy/tests/unit/ai-monthly-cost-cron.test.ts b/packages/ai-proxy/tests/unit/ai-monthly-cost-cron.test.ts index a9c7027e31..13898f73ba 100644 --- a/packages/ai-proxy/tests/unit/ai-monthly-cost-cron.test.ts +++ b/packages/ai-proxy/tests/unit/ai-monthly-cost-cron.test.ts @@ -83,6 +83,7 @@ function createMockKV(failingKeys: Set = new Set()): KVNamespace & { function makeEnv(overrides: Partial = {}): Env { return { AI_GATEWAY_ID: 'gateway-1', + CF_ACCOUNT_ID: 'account-1', KV: createMockKV(), AI_MONTHLY_COST_CACHE_TTL_SECONDS: undefined, AI_MONTHLY_COST_AGGREGATION_MAX_PAGES: undefined, diff --git a/packages/ai-proxy/tests/unit/ai-token-budget.test.ts b/packages/ai-proxy/tests/unit/ai-token-budget.test.ts index 2d3dc87d75..3c2e016e39 100644 --- a/packages/ai-proxy/tests/unit/ai-token-budget.test.ts +++ b/packages/ai-proxy/tests/unit/ai-token-budget.test.ts @@ -145,7 +145,11 @@ describe('monthly cost cap', () => { }) ); - const result = await checkMonthlyCostCap(kv, 'user-cap'); + const result = await checkMonthlyCostCap(kv, 'user-cap', { + AI_GATEWAY_ID: 'gateway', + CF_ACCOUNT_ID: 'account', + CF_API_TOKEN: 'token', + } as never); expect(result).toEqual({ allowed: true, costUsd: 0, capUsd: 10 }); }); @@ -162,7 +166,11 @@ describe('monthly cost cap', () => { ); kv._store.set(buildMonthlyCostCacheKey('user-over-cap'), '10.000000'); - const result = await checkMonthlyCostCap(kv, 'user-over-cap'); + const result = await checkMonthlyCostCap(kv, 'user-over-cap', { + AI_GATEWAY_ID: 'gateway', + CF_ACCOUNT_ID: 'account', + CF_API_TOKEN: 'token', + } as never); expect(result).toEqual({ allowed: false, costUsd: 10, capUsd: 10 }); }); }); @@ -478,7 +486,11 @@ describe('checkAiUsageGate', () => { ); kv._store.set(buildMonthlyCostCacheKey('user-monthly'), '10.010000'); - const result = await checkAiUsageGate(kv, 'user-monthly', makeEnv()); + const result = await checkAiUsageGate( + kv, + 'user-monthly', + makeEnv({ AI_GATEWAY_ID: 'gateway', CF_ACCOUNT_ID: 'account', CF_API_TOKEN: 'token' }) + ); expect(result.allowed).toBe(false); if (!result.allowed) { expect(result.reason).toBe('monthly-cost-cap'); diff --git a/packages/ai-proxy/tests/unit/direct-upstream-metering.test.ts b/packages/ai-proxy/tests/unit/direct-upstream-metering.test.ts new file mode 100644 index 0000000000..941386ef6c --- /dev/null +++ b/packages/ai-proxy/tests/unit/direct-upstream-metering.test.ts @@ -0,0 +1,152 @@ +import { PLATFORM_AI_MODELS } from '@simple-agent-manager/shared'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { + hasLocalAiCostMetering, + isMonthlyCostCapAvailable, + resolveAiGatewayId, +} from '../../src/ai-gateway-availability'; +import { getLocalMonthlyAiCostUsd } from '../../src/ai-monthly-cost-cap'; +import { + buildBudgetSettingsKey, + checkMonthlyCostCap, + incrementProviderUsage, +} from '../../src/ai-token-budget'; +import { + accountTokenUsageFromJson, + accountTokenUsageFromStream, +} from '../../src/ai-token-usage-accounting'; +import type { AiProxyEnv } from '../../src/env'; + +function fixture() { + const rows = new Map(); + const expires = new Map(); + const kv = { + get: vi.fn(async (key: string, type?: string) => { + if ((expires.get(key) ?? Infinity) <= Date.now()) rows.delete(key); + const value = rows.get(key); + return value === undefined ? null : type === 'json' ? JSON.parse(value) : value; + }), + put: vi.fn(async (key: string, value: string, options?: { expirationTtl?: number }) => { + rows.set(key, value); + if (options?.expirationTtl) expires.set(key, Date.now() + options.expirationTtl * 1000); + }), + } as unknown as KVNamespace; + const env = { KV: kv } as AiProxyEnv; + return { rows, kv, env }; +} +afterEach(() => vi.useRealTimers()); + +describe('direct-upstream metering, without forced include_usage', () => { + it('retains day-one spend through month-end on TTL-expiring KV, including later unpriced writes', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-10-01T12:00:00Z')); + const { rows, kv, env } = fixture(); + rows.set(buildBudgetSettingsKey('user'), JSON.stringify({ monthlyCostCapUsd: 0.000001 })); + const model = PLATFORM_AI_MODELS.find( + (m) => m.provider === 'openai' && m.costPer1kOutputTokens > 0 + )!; + await accountTokenUsageFromJson( + { usage: { prompt_tokens: 100, completion_tokens: 100 } }, + { env, userId: 'user', format: 'openai', costModelId: model.id } + ); + const firstCost = await getLocalMonthlyAiCostUsd(kv, 'user', env); + expect(firstCost).toBeGreaterThan(0); + await incrementProviderUsage( + kv, + 'user', + { providerId: 'openai', providerName: 'OpenAI', dialect: 'openai' }, + 1, + 1, + env + ); + vi.setSystemTime(new Date('2026-10-31T23:59:00Z')); + expect(await getLocalMonthlyAiCostUsd(kv, 'user', env)).toBe(firstCost); + expect(await checkMonthlyCostCap(kv, 'user', env)).toMatchObject({ allowed: false }); + vi.setSystemTime(new Date('2026-11-01T00:00:00Z')); + expect(await checkMonthlyCostCap(kv, 'user', env)).toMatchObject({ allowed: true, costUsd: 0 }); + }); + + it('meters a platform response into the same local store that the monthly cap reads', async () => { + const { rows, kv, env } = fixture(); + rows.set(buildBudgetSettingsKey('user'), JSON.stringify({ monthlyCostCapUsd: 0.000001 })); + const model = PLATFORM_AI_MODELS.find( + (m) => m.provider === 'openai' && m.costPer1kOutputTokens > 0 + )!; + const measured = vi.fn(async () => {}); + await accountTokenUsageFromJson( + { usage: { prompt_tokens: 100, completion_tokens: 100 } }, + { env, userId: 'user', format: 'openai', costModelId: model.id, onMeasuredUsage: measured } + ); + expect(await checkMonthlyCostCap(kv, 'user', env)).toMatchObject({ + allowed: false, + capUsd: 0.000001, + }); + expect(measured).toHaveBeenCalledWith( + expect.objectContaining({ inputTokens: 100, outputTokens: 100 }) + ); + }); + + it('estimates missing stream usage for the budget without inventing measured run usage', async () => { + const { kv, env } = fixture(); + const pending: Promise[] = []; + const measured = vi.fn(async () => {}); + const text = 'data: {"choices":[{"delta":{"content":"twelve bytes"}}]}\n\ndata: [DONE]\n\n'; + const stream = new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode(text)); + c.close(); + }, + }); + accountTokenUsageFromStream(stream, { + env, + userId: 'user', + format: 'openai', + fallbackInputTokens: 10, + estimateMissingUsage: true, + onMeasuredUsage: measured, + executionCtx: { + waitUntil(p) { + pending.push(p); + }, + }, + }); + await Promise.all(pending); + expect(kv.put).toHaveBeenCalledWith( + expect.stringContaining('ai-budget:user:'), + expect.stringContaining('"outputTokens":4'), + expect.anything() + ); + expect(measured).not.toHaveBeenCalled(); + }); + + it('reads a day-31 KV month in parallel, with a bounded 31-read fallback', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-10-31T12:00:00Z')); + let active = 0, + maxActive = 0; + const kv = { + get: vi.fn(async () => { + active++; + maxActive = Math.max(maxActive, active); + await Promise.resolve(); + active--; + return null; + }), + } as unknown as KVNamespace; + expect(await getLocalMonthlyAiCostUsd(kv, 'user', {} as AiProxyEnv)).toBe(0); + expect(kv.get).toHaveBeenCalledTimes(31); + expect(maxActive).toBe(31); + }); + + it('does not mistake the ambient gateway ID for an addressable gateway, and uses one cap predicate', () => { + const env = { AI_GATEWAY_ID: 'sam' } as AiProxyEnv; + expect(resolveAiGatewayId(env)).toBeNull(); + expect(hasLocalAiCostMetering(env)).toBe(true); + expect(isMonthlyCostCapAvailable(env)).toBe(true); + expect(isMonthlyCostCapAvailable({ ...env, CF_ACCOUNT_ID: 'account' })).toBe(false); + expect( + isMonthlyCostCapAvailable({ ...env, CF_ACCOUNT_ID: 'account', CF_API_TOKEN: 'token' }) + ).toBe(true); + }); +}); diff --git a/packages/eslint-plugin-sam/outbound-fetch-baseline.json b/packages/eslint-plugin-sam/outbound-fetch-baseline.json index 84778237bf..1c18b09a43 100644 --- a/packages/eslint-plugin-sam/outbound-fetch-baseline.json +++ b/packages/eslint-plugin-sam/outbound-fetch-baseline.json @@ -1,14 +1,13 @@ { "apps/api/src/auth.ts": 2, "apps/api/src/durable-objects/codex-refresh-lock.ts": 1, - "apps/api/src/durable-objects/sam-session/agent-loop-llm.ts": 2, + "apps/api/src/durable-objects/sam-session/agent-loop-llm.ts": 1, "apps/api/src/durable-objects/sam-session/tools/get-ci-status.ts": 1, "apps/api/src/durable-objects/sam-session/tools/get-file-content.ts": 1, "apps/api/src/durable-objects/sam-session/tools/search-code.ts": 1, "apps/api/src/index.ts": 1, "apps/api/src/routes/ai-proxy-anthropic.ts": 2, - "apps/api/src/routes/ai-proxy-passthrough.ts": 3, - "apps/api/src/routes/ai-proxy-upstream.ts": 4, + "apps/api/src/routes/ai-proxy-upstream.ts": 3, "apps/api/src/routes/google-auth.ts": 1, "apps/api/src/routes/project-deployment.ts": 1, "apps/api/src/routes/projects/devcontainer-configs.ts": 3, @@ -16,14 +15,12 @@ "apps/api/src/services/agent-models/workers-ai.ts": 1, "apps/api/src/services/analytics-forward.ts": 3, "apps/api/src/services/artifacts/seed-readme.ts": 1, - "apps/api/src/services/debug-agent-tools.ts": 1, "apps/api/src/services/gcp-fetch.ts": 1, "apps/api/src/services/gcp-setup-transport.ts": 1, "apps/api/src/services/github-pull-request-branch.ts": 1, "apps/api/src/services/model-catalog.ts": 1, "apps/api/src/services/origin-ca-certificates.ts": 1, "apps/api/src/services/platform-config-validation.ts": 1, - "packages/ai-proxy/src/ai-proxy-shared.ts": 1, "packages/operations/src/pull-request-core.ts": 1, "packages/providers/src/provider-fetch.ts": 1, "packages/repo-hosting/src/github-oauth-refresh.ts": 1, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c85d97879e..688b569aa2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -237,6 +237,9 @@ importers: apps/api: dependencies: + '@ai-sdk/openai-compatible': + specifier: 2.0.87 + version: 2.0.87(zod@4.5.4) '@aws-sdk/client-s3': specifier: 'catalog:' version: 3.1141.0 @@ -1345,6 +1348,12 @@ packages: peerDependencies: zod: ^3.25.76 || ^4.1.8 + '@ai-sdk/openai-compatible@2.0.87': + resolution: {integrity: sha512-tge19iHFcU4r6QxlFmwIRU/ytd6RFjsXfMpEc9sLiS5+NnkUYLeh2mm4RzemdqrQS6uO0h0t4RD04CpbgjWXqw==} + engines: {node: '>=18'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + '@ai-sdk/provider-utils@4.0.62': resolution: {integrity: sha512-+FXkZ2e169zASBHP5HAakP0Iai3Eoa8zgh7bnuZExsek3N9HgGt/c7l1Oibdxb79vvsn5Mrg2Sjam80mR6bL8A==} engines: {node: '>=18.17'} @@ -10202,6 +10211,12 @@ snapshots: '@vercel/oidc': 3.2.0 zod: 4.5.4 + '@ai-sdk/openai-compatible@2.0.87(zod@4.5.4)': + dependencies: + '@ai-sdk/provider': 3.0.19 + '@ai-sdk/provider-utils': 4.0.62(zod@4.5.4) + zod: 4.5.4 + '@ai-sdk/provider-utils@4.0.62(zod@4.5.4)': dependencies: '@ai-sdk/provider': 3.0.19 diff --git a/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md b/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md index 9f5210d399..143d542b0f 100644 --- a/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md +++ b/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md @@ -1,28 +1,45 @@ # L12 — OpenAI-compatible LLM endpoint and AI proxy availability ## Problem and scope + Land C12/C13 from sam/selfhost-pass-2 on fresh main (L3 #2733, L11 #2820, L5a #2751). An admin endpoint replaces Workers AI and SAM agent routing; proxy availability follows actual gateway configuration or explicit direct-upstream consent after authentication. Preserve current usage attribution and unrelated main changes. No self-host-only implementation. ## Preflight and research -Classes: external-api-change, cross-component-change, business-logic-change, security-sensitive-change, docs-sync-change. Existing OpenAI chat protocol and guardedFetch are reused; no dependencies or model catalog changes. The integration version forces include_usage and moves fetch logic out of packages/ai-proxy; port selectively instead. Settings use the existing module-scoped AdminSettingsCache (bounded 60s TTL, shared single-flight, mutation generation fencing). Do not add an independent stale cache. L11 owns the capability predicate; no credential read on the unconfigured path, and no additional D1 read per call with a warm snapshot. A configured endpoint outage refuses routing rather than sending prompts to another provider. Bound settings work separately within title/diagnosis budgets. Existing L5a task documents credential parse resilience and the production custom-URL precheck; recheck read-only before C13. + +Classes: external-api-change, cross-component-change, business-logic-change, security-sensitive-change, docs-sync-change. Existing OpenAI chat protocol and guardedFetch are reused; no new resolved SDK version or model catalog changes (the already-transitive OpenAI-compatible SDK is now an explicit API dependency). The integration version forces include_usage and moves fetch logic out of packages/ai-proxy; port selectively instead. Settings use the existing module-scoped AdminSettingsCache (bounded 60s TTL, shared single-flight, mutation generation fencing). Endpoint URL/key resolution must use one atomic snapshot and one TTL; independent settings/credential caches cannot be combined across a remote rotation. L11 owns the capability predicate; no credential read on the unconfigured path, and no additional D1 read per call with a warm snapshot. A configured endpoint outage refuses routing rather than sending prompts to another provider. Bound settings work separately within title/diagnosis budgets. Existing L5a task documents credential parse resilience and the production custom-URL precheck; recheck read-only before C13. Data flow: Admin settings registry -> platform_settings/platform_credentials -> L11 capability -> worker endpoint adapter -> packages/ai-proxy target/fetch helpers -> Workers AI proxy, task-title and SAM agent consumers. Workspace callback -> lifecycle-auth -> availability -> model and budget admission -> guarded provider fetch. Agent-key proxies custom URLs or returns 404, retaining raw/JSON credential tolerance. -Rule 74: condition is an operator-enabled proxy with an addressable gateway or explicit direct-upstream opt-in. Signal is presence of all gateway inputs, not AI_GATEWAY_ID alone. Divergence: gateway id set but account/token missing must require opt-in; healthy complete Cloudflare configuration remains available without settings reads. Tests cover divergence/convergence and 401 before availability. +Rule 74: condition is an operator-enabled proxy with an addressable gateway or explicit direct-upstream opt-in. Signal is presence of all gateway address inputs, not AI_GATEWAY_ID alone. Divergence: gateway id set but account missing must require opt-in; healthy complete Cloudflare configuration remains available without settings reads. Tests cover divergence/convergence and 401 before availability. ## Checklist and acceptance -- [ ] Reconfirm production custom-baseURL row count read-only; record count. -- [ ] Port endpoint definitions and shared target helpers on package seam; wire L11 capability and cached settings with bounded reads. -- [ ] Workers AI calls and SAM agent use endpoint first; configured settings failure refuses (503 proxy); Cloudflare unconfigured read-count regression. -- [ ] Wire title/diagnosis/project-model callers; fix F26 (bounded settings, no unused enforced, one cap predicate, no forced include_usage). -- [ ] Centralize proxy availability after auth; preserve #2674 unauthenticated 401. -- [ ] Direct-upstream paths; agent-key 404 when custom endpoint is not served, malformed-row controls. -- [ ] Split passthrough to <=500 lines, guard all 3 fetches, reduce outbound baseline by 3, redirect regression tests. + +- [x] Reconfirm production custom-baseURL row count read-only; record count: 0 custom configs and 0 openai-compatible credentials, 2026-11-17 02:37 UTC. +- [x] Port endpoint definitions and shared target helpers on package seam; wire L11 capability and cached settings with bounded reads. +- [x] Workers AI calls and SAM agent use endpoint first; configured settings failure refuses (503 proxy); Cloudflare unconfigured read-count regression. +- [x] Wire title/diagnosis/project-model callers; fix F26 (bounded settings, no unused enforced, one cap predicate, no forced include_usage). +- [x] Centralize proxy availability after auth; preserve #2674 unauthenticated 401. +- [x] Direct-upstream paths; agent-key 404 when custom endpoint is not served, malformed-row controls. +- [x] Split passthrough to <=500 lines, guard all 3 fetches, reduce outbound baseline by 3, redirect regression tests. - [ ] Focused behavioral and cross-boundary tests with discriminating guards; lint/typecheck/test/build. -- [ ] Docs reflect settings and behavior, no unrelated spec edits. +- [x] Docs reflect settings and behavior, no unrelated spec edits. - [ ] Draft PR, then complete candidate ready + CodeRabbit request; required local security, Cloudflare, performance and completion reviews. - [ ] Check both staging leases, reserve and follow queue, deploy final candidate; live 401, SAM-mode chat, title generation, SAM agent, refused-private endpoint routing then reset settings; cleanup/release. - [ ] Full CI and review gates pass, merge authorized by coordinator; channel PR/blocker/completion evidence; idea update with PR and commit. Coordinator monitors production deployment. ## References + Idea 01M72M9AEB933ZY8269D376DKC; task 01M7KNA1CNRHWG13CMNB2SVMP5; coordinator 01M7JMXS2JRW6QQMB1356ENPM3; channel feature.selfhost-landing. Rules 18, 41, 60, 62, 74; L5a retained incident/production precheck in tasks/active/2026-11-15-l5-outbound-fetch-guard.md. + +## Implementation evidence (in progress) + +- Endpoint capability reads existing shared cache, 60s TTL; test proves 30 calls/fresh D1 facades =>1 snapshot read/0 credentials, then expiry =>2. Local rotation barrier passes; final atomic snapshot fix also covers writes from another isolate, whose invalidation generation is not visible locally. +- 10 endpoint tests pass, including actual SAM operator AI SDK doGenerate guarded-fetch extension; title/diagnosis settings timeout100ms of400ms budget, private endpoint refusal, coldoutage503, no forced include_usage. +- Three passthrough guards remove baseline3; shared/title/diagnosis/SAM forwarding delegation also lowers their baseline entries.43 passthrough tests pass including same-origin redirects, private/metadata refusals, cross-origin307 body refusal, cross-origin303 credential stripping at all3sites. +- Agent-key custom-baseUrl404 table includes Claude, Codex, OpenCode. Existing parser untouched; composable credential malformed-row suites must remain green. +- Local cap uses existing provider cost rows/DO, no new migrations. Unknown/custom endpoint model price0; preserve main measured run-usage callback, never label estimates as measured. KV fallback at most31 parallel reads, rows retained through month-end +existing graceTTL; TTL-expiring test proves day1 spend still caps atmonth-end then resets nextmonth. +- Root lint/typecheck/build62tasks passed before final rotation/retention fixes; latest package151tests pass. Fullroot suite currently running. +- Draft PR#2829. Initial task-only mainpush rejectedGH013 required check, taskrecord kept infeaturePR. Existing SAM-assigned workspace was already isolated outputbranch at fresh origin/main60a11bb27; no extra worktree necessary. +- Staging queues checked02:48UTC; primary reserved run44005681667 success, position3 turn04:03:57–04:13:57UTC, wake d39eaf5b-db90-4827-87a5-91edcf7bb58c at04:04. No deploy yet. +- Specialist early findings fixed: coldoutage fail-open, raw string URL parsing, OpenCode early keyreturn, authcatch mapping, URL/keyrotation, KVcostretention. Finalreviews pending. +- References: existing installed @mastra/core1.81 OpenAICompatibleConfig has no fetch extension; installed @ai-sdk/openai-compatible2.0.87 typed fetch extension and includeUsage defaultfalse verified before integration; official provider reference https://ai-sdk.dev/providers/openai-compatible-providers corroborates. Exact existing lockfile/API protocol reused; no modelcatalog changes. From d7c18e46a02c718be8775e8eb1d49cdc672ed45a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 03:35:37 +0000 Subject: [PATCH 06/11] fix(ai): cache endpoint credentials atomically across isolates --- .../src/services/admin-settings-resolution.ts | 21 +- apps/api/src/services/llm-chat-target.ts | 4 +- .../api/src/services/llm-endpoint-snapshot.ts | 110 ++++++++++ .../profile-account-pins-capability.test.ts | 3 + ...rovider-limit-platform-attribution.test.ts | 7 +- .../unit/durable-objects/sam-session.test.ts | 191 +++++++++++++----- .../unit/operations/account-usage.test.ts | 2 + .../tests/unit/routes/agents-catalog.test.ts | 2 + .../unit/routes/ai-proxy-model-tiers.test.ts | 2 +- .../admin-settings-foundation.test.ts | 4 +- .../tests/unit/services/ai-billing.test.ts | 2 + .../services/ai-proxy-auth-lifecycle.test.ts | 2 + .../debug-agent-completion-parsing.test.ts | 12 +- .../services/debug-agent-vertical.test.ts | 5 +- .../tests/unit/services/llm-endpoint.test.ts | 65 +++++- .../services/profile-account-bindings.test.ts | 6 +- apps/api/tests/unit/usage-ai.test.ts | 1 + .../tests/unit/usage-budget-routes.test.ts | 2 + .../docs/docs/reference/configuration.md | 6 +- packages/ai-proxy/src/ai-token-budget.ts | 3 +- .../quality/direct-dependency-evidence.json | 5 + ...26-11-17-l12-openai-compatible-endpoint.md | 6 +- 22 files changed, 379 insertions(+), 82 deletions(-) create mode 100644 apps/api/src/services/llm-endpoint-snapshot.ts diff --git a/apps/api/src/services/admin-settings-resolution.ts b/apps/api/src/services/admin-settings-resolution.ts index 373faede44..0996434d0b 100644 --- a/apps/api/src/services/admin-settings-resolution.ts +++ b/apps/api/src/services/admin-settings-resolution.ts @@ -35,11 +35,11 @@ export const cache = new AdminSettingsCache(); let generations = new WeakMap(); let generationClock = 0; let resetGeneration = 0; -function generationOf(db: D1Database): number { +export function adminSettingsGeneration(db: D1Database): number { return generations.get(db) ?? resetGeneration; } function assertGeneration(db: D1Database, generation: number): void { - if (generationOf(db) !== generation) throw new AdminSettingsUnavailableError(); + if (adminSettingsGeneration(db) !== generation) throw new AdminSettingsUnavailableError(); } export type CredentialRow = { provider: string; @@ -68,7 +68,7 @@ export async function credentialRows( if (attempt >= 3) throw new AdminSettingsUnavailableError(); const db = resolveD1BindingIdentity(env.DATABASE); if (!db || typeof db.prepare !== 'function') throw new AdminSettingsUnavailableError(); - const generation = generationOf(db); + const generation = adminSettingsGeneration(db); const ttlMs = adminSettingCacheMs(env, 'integration.github.clientSecret'); const useCache = !fresh && ttlMs > 0; const existing = credentialCache.get(db); @@ -111,7 +111,7 @@ export async function credentialRows( if (useCache && credentialCache.get(db) !== entry) return credentialRows(env, false, attempt + 1); if ( - generationOf(db) !== generation || + adminSettingsGeneration(db) !== generation || Date.now() >= entry.deadlineAt || (ttlMs > 0 && Date.now() >= entry.expiresAt) ) @@ -153,7 +153,7 @@ async function legacyKv( } if (attempt >= 3) throw new AdminSettingsUnavailableError(); const db = resolveD1BindingIdentity(env.DATABASE); - const generation = generationOf(db); + const generation = adminSettingsGeneration(db); let map = kvCache.get(db); if (!map) { map = new Map(); @@ -170,7 +170,7 @@ async function legacyKv( const value = await cached.promise; if (map.get(key) !== cached) return legacyKv(env, key, false, ttlMs, attempt + 1); if ( - generationOf(db) !== generation || + adminSettingsGeneration(db) !== generation || Date.now() >= Math.min(cached.expiresAt, cached.startedAt + ttlMs) ) throw new AdminSettingsUnavailableError(); @@ -188,7 +188,7 @@ async function legacyKv( const value = await entry.promise; if (useCache && map.get(key) !== entry) return legacyKv(env, key, false, ttlMs, attempt + 1); if ( - generationOf(db) !== generation || + adminSettingsGeneration(db) !== generation || Date.now() >= entry.deadlineAt || (ttlMs > 0 && Date.now() >= entry.expiresAt) ) @@ -372,7 +372,7 @@ export async function resolveAdminSettingDetailsMany( const primary = resolveD1BindingIdentity(env.DATABASE); const maxAge = Math.min(...names.map((name) => adminSettingCacheMs(env, name))); for (let attempt = 0; attempt < 3; attempt++) { - const generation = generationOf(primary); + const generation = adminSettingsGeneration(primary); try { const [rows, credentials] = await Promise.all([ cache.read(primary, options.fresh ?? false, maxAge, DEFAULT_CONFIG_READ_TIMEOUT_MS), @@ -383,10 +383,10 @@ export async function resolveAdminSettingDetailsMany( const values = await Promise.all( definitions.map((def) => resolved(env, def, rows, true, credentials)) ); - if (generationOf(primary) !== generation) continue; + if (adminSettingsGeneration(primary) !== generation) continue; return values; } catch { - if (generationOf(primary) !== generation) continue; + if (adminSettingsGeneration(primary) !== generation) continue; throw new AdminSettingsUnavailableError(); } } @@ -495,5 +495,4 @@ export async function readAdminSettings(env: Env, options: { fresh?: boolean } = } } export type AdminSettingsView = Awaited>; - export { adminSettingCacheMs } from './admin-settings-cache'; diff --git a/apps/api/src/services/llm-chat-target.ts b/apps/api/src/services/llm-chat-target.ts index a85158bf73..e8c7ef240d 100644 --- a/apps/api/src/services/llm-chat-target.ts +++ b/apps/api/src/services/llm-chat-target.ts @@ -7,7 +7,6 @@ import { import { classifyHost } from '@simple-agent-manager/worker-core'; import type { Env } from '../env'; -import { resolveAdminSettingDetailsMany } from './admin-settings-resolution'; import { DEFAULT_CONFIG_READ_TIMEOUT_MS } from './config-read-deadline'; import { withDeadline } from './fetch-timeout'; import { @@ -15,6 +14,7 @@ import { type LlmPurpose, normalizeLlmBaseUrl, } from './llm-endpoint-settings'; +import { resolveLlmEndpointSettings } from './llm-endpoint-snapshot'; import { outboundMaxRedirectsValue } from './outbound-fetch-settings'; import { hasCloudflareAccountApi, @@ -44,7 +44,7 @@ export async function resolveOpenAICompatibleTarget( if (!(await resolveLlmEndpointCapability(env))) return null; try { // Re-read the URL with its key/model under the same mutation generation. - const details = await resolveAdminSettingDetailsMany(env, [ + const details = await resolveLlmEndpointSettings(env, [ 'llm.openAICompatible.baseUrl', 'llm.openAICompatible.apiKey', 'llm.openAICompatible.model', diff --git a/apps/api/src/services/llm-endpoint-snapshot.ts b/apps/api/src/services/llm-endpoint-snapshot.ts new file mode 100644 index 0000000000..d5aa021129 --- /dev/null +++ b/apps/api/src/services/llm-endpoint-snapshot.ts @@ -0,0 +1,110 @@ +/** Joint endpoint URL/key snapshot: independent caches can mix remote admin generations. */ +import { log } from '@simple-agent-manager/worker-core'; +import * as v from 'valibot'; + +import type { Env } from '../env'; +import { resolveD1BindingIdentity } from '../lib/d1-session'; +import { ADMIN_SETTINGS_CACHE_MAX_MS, AdminSettingsUnavailableError } from './admin-settings-cache'; +import { type AdminSettingName } from './admin-settings-registry'; +import { adminSettingsGeneration, requiredDefinition, resolved } from './admin-settings-resolution'; +import { DEFAULT_CONFIG_READ_TIMEOUT_MS } from './config-read-deadline'; +import { withDeadline } from './fetch-timeout'; +import { INTEGRATION_CREDENTIAL_TYPE } from './platform-config-store'; + +const overrideSchema = v.object({ + key: v.string(), + value: v.string(), + updatedAt: v.string(), + updatedBy: v.nullable(v.string()), +}); +const credentialSchema = v.object({ + id: v.string(), + provider: v.string(), + kind: v.string(), + ciphertext: v.string(), + iv: v.string(), + updatedAt: v.string(), + updatedBy: v.nullable(v.string()), +}); +type Snapshot = { + rows: v.InferOutput[]; + credentials: v.InferOutput[]; +}; +type Entry = { generation: number; expiresAt: number; promise: Promise }; +const snapshots = new WeakMap(); + +async function load(env: Env, db: D1Database): Promise { + // D1 batch is transactional: both halves are from one primary snapshot, even when another + // isolate rotates the endpoint while this read is in flight. Only encrypted keys are cached. + const results = await db.batch([ + db.prepare( + 'SELECT key,value,updated_at AS updatedAt,updated_by AS updatedBy FROM platform_settings' + ), + db + .prepare( + 'SELECT id,provider,credential_kind AS kind,encrypted_token AS ciphertext,iv,updated_at AS updatedAt,COALESCE(updated_by,created_by) AS updatedBy FROM platform_credentials WHERE credential_type=? AND provider=? AND credential_kind=? AND is_enabled=1 ORDER BY updated_at DESC,created_at DESC' + ) + .bind(INTEGRATION_CREDENTIAL_TYPE, 'openai-compatible', 'api-key'), + ]); + if (results.length !== 2 || results.some((result) => !result.success)) + throw new AdminSettingsUnavailableError(); + const rows = v.safeParse(v.array(overrideSchema), results[0]?.results); + if (!rows.success) throw new AdminSettingsUnavailableError(); + const credentials: Snapshot['credentials'] = []; + for (const row of results[1]?.results ?? []) { + const parsed = v.safeParse(credentialSchema, row); + try { + if (!parsed.success) throw new AdminSettingsUnavailableError(); + // Validate/decrypt each candidate independently; a malformed legacy row cannot hide a + // later usable key. Never log parser/decryption messages carrying credential material. + await resolved(env, requiredDefinition('llm.openAICompatible.apiKey'), rows.output, true, [ + parsed.output, + ]); + credentials.push(parsed.output); + } catch { + log.warn('llm_endpoint.credential_row_skipped', { + credentialId: parsed.success ? parsed.output.id : undefined, + provider: 'openai-compatible', + kind: 'api-key', + reason: 'invalid_credential', + }); + } + } + // No key is a valid explicit setup; stored keys that cannot be read are an outage. + if ((results[1]?.results.length ?? 0) > 0 && credentials.length === 0) + throw new AdminSettingsUnavailableError(); + return { rows: rows.output, credentials }; +} + +/** One atomic batch per isolate TTL, shared across purposes and request-scoped D1 facades. */ +export async function resolveLlmEndpointSettings(env: Env, names: AdminSettingName[]) { + const db = resolveD1BindingIdentity(env.DATABASE); + for (let attempt = 0; attempt < 3; attempt++) { + const generation = adminSettingsGeneration(db); + let entry = snapshots.get(db); + if (!entry || entry.generation !== generation || Date.now() >= entry.expiresAt) { + entry = { + generation, + expiresAt: Date.now() + ADMIN_SETTINGS_CACHE_MAX_MS, + promise: withDeadline(() => load(env, db), DEFAULT_CONFIG_READ_TIMEOUT_MS), + }; + snapshots.set(db, entry); + } + try { + const snapshot = await entry.promise; + const values = await Promise.all( + names.map((name) => + resolved(env, requiredDefinition(name), snapshot.rows, true, snapshot.credentials) + ) + ); + if (generation !== adminSettingsGeneration(db)) continue; + if (Date.now() >= entry.expiresAt) throw new AdminSettingsUnavailableError(); + return values; + } catch (error) { + if (snapshots.get(db) === entry) snapshots.delete(db); + if (generation !== adminSettingsGeneration(db)) continue; + throw error; + } + } + throw new AdminSettingsUnavailableError(); +} diff --git a/apps/api/tests/integration/profile-account-pins-capability.test.ts b/apps/api/tests/integration/profile-account-pins-capability.test.ts index 4850cbf627..d3a6150a86 100644 --- a/apps/api/tests/integration/profile-account-pins-capability.test.ts +++ b/apps/api/tests/integration/profile-account-pins-capability.test.ts @@ -79,6 +79,9 @@ beforeEach(async () => { DATABASE: createSqliteD1(sqlite), ENCRYPTION_KEY, BASE_DOMAIN: 'sammy.party', + // These custom endpoint account-pin controls exercise the available proxy path. + CF_ACCOUNT_ID: 'account-test', + AI_GATEWAY_ID: 'gateway-test', KV: { get: vi.fn(async () => null), put: vi.fn(async () => {}) }, } as unknown as Env; diff --git a/apps/api/tests/integration/provider-limit-platform-attribution.test.ts b/apps/api/tests/integration/provider-limit-platform-attribution.test.ts index 212eb88de7..f7e7de3967 100644 --- a/apps/api/tests/integration/provider-limit-platform-attribution.test.ts +++ b/apps/api/tests/integration/provider-limit-platform-attribution.test.ts @@ -1,6 +1,4 @@ -import { - newProviderLimitWait, -} from '@simple-agent-manager/scheduler-core'; +import { newProviderLimitWait } from '@simple-agent-manager/scheduler-core'; import { AI_PROXY_BILLING_MODE_KV_KEY } from '@simple-agent-manager/shared'; import Database from 'better-sqlite3'; import { drizzle } from 'drizzle-orm/d1'; @@ -52,6 +50,9 @@ describe('platform quota attribution at real credential and callback boundaries' DATABASE: createSqliteD1(sqlite), ENCRYPTION_KEY: encryptionKey, BASE_DOMAIN: 'fixture.example', + CF_ACCOUNT_ID: 'account-test', + CF_API_TOKEN: 'cf-token-test', + AI_GATEWAY_ID: 'gateway-test', AI_PROXY_ENABLED: 'true', KV: { get: vi.fn(async (key: string) => (key === AI_PROXY_BILLING_MODE_KV_KEY ? mode : null)), 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 8c0adf31ef..d8183ffca1 100644 --- a/apps/api/tests/unit/durable-objects/sam-session.test.ts +++ b/apps/api/tests/unit/durable-objects/sam-session.test.ts @@ -38,7 +38,11 @@ import { } from '../../../src/durable-objects/sam-session/index'; import { executeTool } from '../../../src/durable-objects/sam-session/tools'; import { searchConversationHistory } from '../../../src/durable-objects/sam-session/tools/search-conversation-history'; -import type { CollectedToolCall, MessageRow, ToolContext } from '../../../src/durable-objects/sam-session/types'; +import type { + CollectedToolCall, + MessageRow, + ToolContext, +} from '../../../src/durable-objects/sam-session/types'; import { DEFAULT_SEARCH_QUERY_MAX_LENGTH, DEFAULT_SEARCH_QUERY_MAX_TERM_LENGTH, @@ -46,6 +50,13 @@ import { } from '../../../src/lib/search-query-limits'; import { createSqlStorage } from './sql-storage-test-utils'; +// These loop/protocol unit fixtures have no settings DB; real endpoint routing is +// exercised through the actual admin writer in llm-endpoint.test.ts. +vi.mock('../../../src/services/platform-capabilities', async (original) => ({ + ...(await original()), + resolveLlmEndpointCapability: vi.fn(async () => null), +})); + // Mock cloudflare:workers (vitest hoists vi.mock calls automatically) function makeBudgetKv(): KVNamespace { @@ -451,9 +462,13 @@ describe('search_conversation_history tool', () => { ═══════════════════════════════════════════════════════════════ */ /** Build a synthetic Anthropic SSE stream from events. */ -function buildAnthropicSseStream(events: Array>): ReadableStream { +function buildAnthropicSseStream( + events: Array> +): ReadableStream { const encoder = new TextEncoder(); - const lines = events.map((e) => `event: ${(e.type as string) || 'message'}\ndata: ${JSON.stringify(e)}\n\n`); + const lines = events.map( + (e) => `event: ${(e.type as string) || 'message'}\ndata: ${JSON.stringify(e)}\n\n` + ); const body = lines.join(''); return new ReadableStream({ start(controller) { @@ -495,7 +510,10 @@ function createCollectingWriter(): { let done = false; while (!done) { const result = await reader.read(); - if (result.done) { done = true; break; } + if (result.done) { + done = true; + break; + } buffer += decoder.decode(result.value, { stream: true }); const parts = buffer.split('\n\n'); buffer = parts.pop() || ''; @@ -503,10 +521,14 @@ function createCollectingWriter(): { if (!part.startsWith('data: ')) continue; try { events.push(JSON.parse(part.slice(6)) as Record); - } catch { /* ignore */ } + } catch { + /* ignore */ + } } } - } catch { /* stream may close */ } + } catch { + /* stream may close */ + } })(); return { writer, events }; @@ -522,7 +544,11 @@ describe('Agent Loop — Anthropic Streaming', () => { { type: 'message_start', message: { id: 'msg_1', role: 'assistant' } }, { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'Hello!' } }, - { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: ' How can I help?' } }, + { + type: 'content_block_delta', + index: 0, + delta: { type: 'text_delta', text: ' How can I help?' }, + }, { type: 'content_block_stop', index: 0 }, { type: 'message_delta', delta: { stop_reason: 'end_turn' } }, { type: 'message_stop' }, @@ -556,7 +582,7 @@ describe('Agent Loop — Anthropic Streaming', () => { writer, (_convId, role, content) => { persisted.push({ role, content }); - }, + } ); await writer.close(); await new Promise((r) => setTimeout(r, 50)); @@ -577,8 +603,16 @@ describe('Agent Loop — Anthropic Streaming', () => { it('emits tool_start, tool_result events for tool use response', async () => { const firstCallEvents = [ { type: 'message_start', message: { id: 'msg_2', role: 'assistant' } }, - { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'toolu_1', name: 'list_projects' } }, - { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '{}' } }, + { + type: 'content_block_start', + index: 0, + content_block: { type: 'tool_use', id: 'toolu_1', name: 'list_projects' }, + }, + { + type: 'content_block_delta', + index: 0, + delta: { type: 'input_json_delta', partial_json: '{}' }, + }, { type: 'content_block_stop', index: 0 }, { type: 'message_delta', delta: { stop_reason: 'tool_use' } }, { type: 'message_stop' }, @@ -587,7 +621,11 @@ describe('Agent Loop — Anthropic Streaming', () => { const secondCallEvents = [ { type: 'message_start', message: { id: 'msg_3', role: 'assistant' } }, { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, - { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'You have projects.' } }, + { + type: 'content_block_delta', + index: 0, + delta: { type: 'text_delta', text: 'You have projects.' }, + }, { type: 'content_block_stop', index: 0 }, { type: 'message_delta', delta: { stop_reason: 'end_turn' } }, { type: 'message_stop' }, @@ -629,7 +667,7 @@ describe('Agent Loop — Anthropic Streaming', () => { writer, (_convId, role, content) => { persisted.push({ role, content }); - }, + } ); await writer.close(); await new Promise((r) => setTimeout(r, 50)); @@ -671,29 +709,30 @@ describe('Agent Loop — Anthropic Streaming', () => { KV: makeBudgetKv(), } as unknown as Parameters[4]; - await runAgentLoop( - 'conv-3', - [], - 'Hello', - config, - mockEnv, - 'user-1', - writer, - () => { /* no-op */ }, - ); + await runAgentLoop('conv-3', [], 'Hello', config, mockEnv, 'user-1', writer, () => { + /* no-op */ + }); await writer.close(); await new Promise((r) => setTimeout(r, 50)); const errors = events.filter((e) => e.type === 'error'); expect(errors.length).toBe(1); - expect((errors[0]!.message as string)).toContain('401'); + expect(errors[0]!.message as string).toContain('401'); }); it('respects maxTurns limit', async () => { const toolUseEvents = [ { type: 'message_start', message: { id: 'msg_loop', role: 'assistant' } }, - { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'toolu_loop', name: 'list_projects' } }, - { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '{}' } }, + { + type: 'content_block_start', + index: 0, + content_block: { type: 'tool_use', id: 'toolu_loop', name: 'list_projects' }, + }, + { + type: 'content_block_delta', + index: 0, + delta: { type: 'input_json_delta', partial_json: '{}' }, + }, { type: 'content_block_stop', index: 0 }, { type: 'message_delta', delta: { stop_reason: 'tool_use' } }, { type: 'message_stop' }, @@ -719,22 +758,15 @@ describe('Agent Loop — Anthropic Streaming', () => { KV: makeBudgetKv(), } as unknown as Parameters[4]; - await runAgentLoop( - 'conv-4', - [], - 'Loop forever', - config, - mockEnv, - 'user-1', - writer, - () => { /* no-op */ }, - ); + await runAgentLoop('conv-4', [], 'Loop forever', config, mockEnv, 'user-1', writer, () => { + /* no-op */ + }); await writer.close(); await new Promise((r) => setTimeout(r, 50)); const errors = events.filter((e) => e.type === 'error'); expect(errors.length).toBe(1); - expect((errors[0]!.message as string)).toContain('Maximum tool iterations'); + expect(errors[0]!.message as string).toContain('Maximum tool iterations'); expect(fetchMock).toHaveBeenCalledTimes(3); }); @@ -742,19 +774,35 @@ describe('Agent Loop — Anthropic Streaming', () => { it('converts history rows to message format', async () => { const history: MessageRow[] = [ { - id: 'h1', conversation_id: 'c1', role: 'user', content: 'Previous question', - tool_calls_json: null, tool_call_id: null, created_at: '', sequence: 1, + id: 'h1', + conversation_id: 'c1', + role: 'user', + content: 'Previous question', + tool_calls_json: null, + tool_call_id: null, + created_at: '', + sequence: 1, }, { - id: 'h2', conversation_id: 'c1', role: 'assistant', content: 'Previous answer', - tool_calls_json: null, tool_call_id: null, created_at: '', sequence: 2, + id: 'h2', + conversation_id: 'c1', + role: 'assistant', + content: 'Previous answer', + tool_calls_json: null, + tool_call_id: null, + created_at: '', + sequence: 2, }, ]; const anthropicEvents = [ { type: 'message_start', message: { id: 'msg_hist', role: 'assistant' } }, { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, - { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'Response with context' } }, + { + type: 'content_block_delta', + index: 0, + delta: { type: 'text_delta', text: 'Response with context' }, + }, { type: 'content_block_stop', index: 0 }, { type: 'message_delta', delta: { stop_reason: 'end_turn' } }, { type: 'message_stop' }, @@ -777,7 +825,16 @@ describe('Agent Loop — Anthropic Streaming', () => { KV: makeBudgetKv(), } as unknown as Parameters[4]; - await runAgentLoop('conv-hist', history, 'New question', config, mockEnv, 'user-1', writer, () => {}); + await runAgentLoop( + 'conv-hist', + history, + 'New question', + config, + mockEnv, + 'user-1', + writer, + () => {} + ); await writer.close(); // Verify the fetch body includes history + new message (Anthropic format) @@ -838,7 +895,7 @@ describe('Agent Loop — OpenAI (Workers AI) Streaming', () => { writer, (_convId, role, content) => { persisted.push({ role, content }); - }, + } ); await writer.close(); await new Promise((r) => setTimeout(r, 50)); @@ -857,7 +914,10 @@ describe('Agent Loop — OpenAI (Workers AI) Streaming', () => { it('routes Workers AI requests to the correct gateway URL', async () => { const openAIChunks = [ - { id: 'chatcmpl-1', choices: [{ index: 0, delta: { content: 'Ok' }, finish_reason: 'stop' }] }, + { + id: 'chatcmpl-1', + choices: [{ index: 0, delta: { content: 'Ok' }, finish_reason: 'stop' }], + }, ]; const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce( @@ -895,14 +955,41 @@ describe('Agent Loop — OpenAI (Workers AI) Streaming', () => { it('handles Workers AI tool calls in OpenAI format', async () => { // First call: tool_calls in delta const firstCallChunks = [ - { id: 'chatcmpl-2', choices: [{ index: 0, delta: { role: 'assistant', content: null, tool_calls: [{ index: 0, id: 'call_1', type: 'function', function: { name: 'list_projects', arguments: '' } }] } }] }, - { id: 'chatcmpl-2', choices: [{ index: 0, delta: { tool_calls: [{ index: 0, function: { arguments: '{}' } }] } }] }, + { + id: 'chatcmpl-2', + choices: [ + { + index: 0, + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + index: 0, + id: 'call_1', + type: 'function', + function: { name: 'list_projects', arguments: '' }, + }, + ], + }, + }, + ], + }, + { + id: 'chatcmpl-2', + choices: [ + { index: 0, delta: { tool_calls: [{ index: 0, function: { arguments: '{}' } }] } }, + ], + }, { id: 'chatcmpl-2', choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] }, ]; // Second call: text response after tool result const secondCallChunks = [ - { id: 'chatcmpl-3', choices: [{ index: 0, delta: { content: 'Found your projects.' }, finish_reason: 'stop' }] }, + { + id: 'chatcmpl-3', + choices: [{ index: 0, delta: { content: 'Found your projects.' }, finish_reason: 'stop' }], + }, ]; const fetchMock = vi.spyOn(globalThis, 'fetch'); @@ -942,7 +1029,7 @@ describe('Agent Loop — OpenAI (Workers AI) Streaming', () => { writer, (_convId, role, content) => { persisted.push({ role, content }); - }, + } ); await writer.close(); await new Promise((r) => setTimeout(r, 50)); @@ -988,11 +1075,13 @@ describe('Agent Loop — Fetch Error Handling', () => { const errors = events.filter((e) => e.type === 'error'); expect(errors.length).toBe(1); - expect((errors[0]!.message as string)).toContain('Failed to reach AI service'); + expect(errors[0]!.message as string).toContain('Failed to reach AI service'); }); it('emits timeout error when fetch is aborted', async () => { - vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(new DOMException('The operation was aborted', 'AbortError')); + vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce( + new DOMException('The operation was aborted', 'AbortError') + ); const { writer, events } = createCollectingWriter(); @@ -1011,6 +1100,6 @@ describe('Agent Loop — Fetch Error Handling', () => { const errors = events.filter((e) => e.type === 'error'); expect(errors.length).toBe(1); - expect((errors[0]!.message as string)).toContain('timed out'); + expect(errors[0]!.message as string).toContain('timed out'); }); }); diff --git a/apps/api/tests/unit/operations/account-usage.test.ts b/apps/api/tests/unit/operations/account-usage.test.ts index 9355f183d6..3118dc2aae 100644 --- a/apps/api/tests/unit/operations/account-usage.test.ts +++ b/apps/api/tests/unit/operations/account-usage.test.ts @@ -168,6 +168,8 @@ describe('connector account monitoring', () => { env = { DATABASE: createSqliteD1(sqlite), BASE_DOMAIN: 'example.com', + CF_ACCOUNT_ID: 'account-test', + AI_GATEWAY_ID: 'gateway-test', KV: { get: vi.fn(async () => null) }, } as unknown as Env; }); diff --git a/apps/api/tests/unit/routes/agents-catalog.test.ts b/apps/api/tests/unit/routes/agents-catalog.test.ts index ed935ea952..9d2f5ea427 100644 --- a/apps/api/tests/unit/routes/agents-catalog.test.ts +++ b/apps/api/tests/unit/routes/agents-catalog.test.ts @@ -43,6 +43,8 @@ describe('GET /api/agents', () => { return { DATABASE: {} as D1Database, ENCRYPTION_KEY: 'test-encryption-key', + AI_GATEWAY_ID: 'test-gateway', + CF_ACCOUNT_ID: 'test-account', KV: { get: vi.fn(), put: vi.fn(), delete: vi.fn() } as unknown as KVNamespace, ...overrides, } as Env; diff --git a/apps/api/tests/unit/routes/ai-proxy-model-tiers.test.ts b/apps/api/tests/unit/routes/ai-proxy-model-tiers.test.ts index c3c3cd73ad..50038231e8 100644 --- a/apps/api/tests/unit/routes/ai-proxy-model-tiers.test.ts +++ b/apps/api/tests/unit/routes/ai-proxy-model-tiers.test.ts @@ -108,7 +108,7 @@ function upstreamResponse(url: string): Response { function makeEnv(overrides: Partial = {}): Env { const sqlite = new Database(':memory:'); - createSchemaTables(sqlite, [schema.users]); + createSchemaTables(sqlite, [schema.users, schema.platformSettings]); sqlite.prepare('INSERT INTO users (id, email) VALUES (?, ?)').run('user-1', 'user1@example.com'); return { DATABASE: createSqliteD1(sqlite), diff --git a/apps/api/tests/unit/services/admin-settings-foundation.test.ts b/apps/api/tests/unit/services/admin-settings-foundation.test.ts index e8cfd6cae9..5b45e0f96f 100644 --- a/apps/api/tests/unit/services/admin-settings-foundation.test.ts +++ b/apps/api/tests/unit/services/admin-settings-foundation.test.ts @@ -149,8 +149,8 @@ describe('Phase 1 settings registry', () => { it('publishes secret classification without secret values or credential implementation', () => { const secrets = ADMIN_SETTINGS_REGISTRY.filter((setting) => setting.secret); - expect(secrets).toHaveLength(4); - expect(new Set(secrets.map((setting) => setting.credential?.provider)).size).toBe(4); + expect(secrets).toHaveLength(5); + expect(new Set(secrets.map((setting) => setting.credential?.provider)).size).toBe(5); for (const secret of secrets) { expect(secret.defaultValue).toBeNull(); const metadata = publicAdminSettingDefinition(secret); diff --git a/apps/api/tests/unit/services/ai-billing.test.ts b/apps/api/tests/unit/services/ai-billing.test.ts index 07034ae783..901c81c701 100644 --- a/apps/api/tests/unit/services/ai-billing.test.ts +++ b/apps/api/tests/unit/services/ai-billing.test.ts @@ -28,6 +28,8 @@ function mockEnv(overrides: Partial<{ KV: KVNamespace; }> = {}) { return { + AI_GATEWAY_ID: 'test-gateway', + CF_ACCOUNT_ID: 'test-account', CF_AIG_TOKEN: overrides.CF_AIG_TOKEN ?? 'test-cf-token', CF_API_TOKEN: overrides.CF_API_TOKEN ?? 'test-cf-api-token', AI_PROXY_BILLING_MODE: overrides.AI_PROXY_BILLING_MODE, diff --git a/apps/api/tests/unit/services/ai-proxy-auth-lifecycle.test.ts b/apps/api/tests/unit/services/ai-proxy-auth-lifecycle.test.ts index b4b292552b..0a8844557a 100644 --- a/apps/api/tests/unit/services/ai-proxy-auth-lifecycle.test.ts +++ b/apps/api/tests/unit/services/ai-proxy-auth-lifecycle.test.ts @@ -36,6 +36,8 @@ beforeEach(() => { JWT_PRIVATE_KEY: keys.privateKey, JWT_PUBLIC_KEY: keys.publicKey, BASE_DOMAIN: 'example.test', + AI_GATEWAY_ID: 'test-gateway', + CF_ACCOUNT_ID: 'test-account', } as unknown as Env; }); diff --git a/apps/api/tests/unit/services/debug-agent-completion-parsing.test.ts b/apps/api/tests/unit/services/debug-agent-completion-parsing.test.ts index bdc29136d0..862ddc37b7 100644 --- a/apps/api/tests/unit/services/debug-agent-completion-parsing.test.ts +++ b/apps/api/tests/unit/services/debug-agent-completion-parsing.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; import { @@ -7,6 +7,13 @@ import { resolveDebugAgentConfig, type ToolCall, } from '../../../src/services/debug-agent'; +import { createAdminSettingsEnv } from '../../helpers/admin-settings-env'; + +let settings: ReturnType; +beforeEach(() => { + settings = createAdminSettingsEnv(); +}); +afterEach(() => settings.sqlite.close()); const mocks = vi.hoisted(() => ({ queryCloudflareLogs: vi.fn().mockResolvedValue({ @@ -27,6 +34,7 @@ vi.mock('../../../src/services/observability', async (importOriginal) => { function makeEnv(overrides?: Partial): Env { return { + ...settings.env, CF_API_TOKEN: 'server-token', CF_ACCOUNT_ID: 'account-1', ...overrides, @@ -81,6 +89,7 @@ describe('complete() — validated Completion response parsing', () => { const config = resolveDebugAgentConfig({} as Env); await expect(complete(makeEnv(), config, 'test-feature', [], 100)).rejects.toThrow(); + expect(fetchMock).toHaveBeenCalledTimes(1); }); it('throws for a tool_calls entry missing required fields', async () => { @@ -104,6 +113,7 @@ describe('complete() — validated Completion response parsing', () => { // function.arguments is missing — every downstream tool_calls consumer // (JSON.parse(call.function.arguments)) assumes it is always a string. await expect(complete(makeEnv(), config, 'test-feature', [], 100)).rejects.toThrow(); + expect(fetchMock).toHaveBeenCalledTimes(1); }); it('still throws the HTTP-status error before attempting to parse the body', async () => { diff --git a/apps/api/tests/unit/services/debug-agent-vertical.test.ts b/apps/api/tests/unit/services/debug-agent-vertical.test.ts index 43797e65e4..581e5acb65 100644 --- a/apps/api/tests/unit/services/debug-agent-vertical.test.ts +++ b/apps/api/tests/unit/services/debug-agent-vertical.test.ts @@ -2,9 +2,10 @@ import { DEFAULT_DEBUG_AGENT_DAILY_TOKEN_LIMIT } from '@simple-agent-manager/sha import Database from 'better-sqlite3'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import { platformSettings } from '../../../src/db/schema'; import type { Env } from '../../../src/env'; import { runDebugDiagnosis } from '../../../src/services/debug-agent'; -import { createSqliteD1 } from '../../helpers/sqlite-d1'; +import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; function createKv(): KVNamespace { const values = new Map(); @@ -21,6 +22,7 @@ describe('runDebugDiagnosis vertical slice', () => { it('redacts realistic observability evidence before the next model turn and persists output', async () => { const main = new Database(':memory:'); + createSchemaTables(main, [platformSettings]); main.exec(` CREATE TABLE debug_diagnoses ( id TEXT PRIMARY KEY, error_id TEXT, start_time TEXT NOT NULL, end_time TEXT NOT NULL, @@ -163,6 +165,7 @@ describe('runDebugDiagnosis vertical slice', () => { it('allows automated diagnosis to continue past the old two-turn token ceiling', async () => { const main = new Database(':memory:'); + createSchemaTables(main, [platformSettings]); main.exec(` CREATE TABLE debug_diagnoses ( id TEXT PRIMARY KEY, error_id TEXT, start_time TEXT NOT NULL, end_time TEXT NOT NULL, diff --git a/apps/api/tests/unit/services/llm-endpoint.test.ts b/apps/api/tests/unit/services/llm-endpoint.test.ts index bd47f00448..6c039cac81 100644 --- a/apps/api/tests/unit/services/llm-endpoint.test.ts +++ b/apps/api/tests/unit/services/llm-endpoint.test.ts @@ -1,7 +1,6 @@ -import * as capabilities from '../../../src/services/platform-capabilities'; -import { resolveOperatorModel } from '../../../src/durable-objects/sam-session/operator/model'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { resolveOperatorModel } from '../../../src/durable-objects/sam-session/operator/model'; import type { Env } from '../../../src/env'; import { createRequestScopedD1 } from '../../../src/lib/d1-session'; import { forwardToWorkersAI } from '../../../src/routes/ai-proxy-upstream'; @@ -14,7 +13,9 @@ import { isAiProxyEnabled } from '../../../src/services/ai-proxy-availability'; import { fetchWorkersAIChatCompletion } from '../../../src/services/ai-proxy-shared'; import { complete } from '../../../src/services/debug-agent-tools'; import { resolveOpenAICompatibleTarget } from '../../../src/services/llm-chat-target'; +import * as capabilities from '../../../src/services/platform-capabilities'; import { createAdminSettingsEnv } from '../../helpers/admin-settings-env'; +import { createSqliteD1 } from '../../helpers/sqlite-d1'; let fixture: ReturnType; let env: Env; @@ -60,6 +61,66 @@ async function configure(baseUrl = 'https://llm.example.com/v1') { } describe('L12 endpoint routing through real settings storage/cache', () => { + it('refuses all-corrupt stored endpoint keys but accepts a deliberately keyless endpoint', async () => { + await configure(); + fixture.sqlite.exec( + "UPDATE platform_credentials SET encrypted_token='bad-ciphertext',iv='bad-iv' WHERE provider='openai-compatible'" + ); + invalidateAdminSettings(env); + expect((await forwardToWorkersAI(env, { messages: [] }, '@cf/model', '{}')).status).toBe(503); + expect(fetchMock).not.toHaveBeenCalled(); + fixture.sqlite.exec("DELETE FROM platform_credentials WHERE provider='openai-compatible'"); + invalidateAdminSettings(env); + expect((await forwardToWorkersAI(env, { messages: [] }, '@cf/model', '{}')).status).toBe(200); + expect(new Headers(fetchMock.mock.calls[0]?.[1]?.headers).get('Authorization')).toBeNull(); + }); + + it('jointly caches URL and key across remote-isolate rotation even when credential caching is disabled', async () => { + vi.useFakeTimers(); + env.PLATFORM_CONFIG_CACHE_MS = '0'; + await configure(); + const batch = vi.spyOn(env.DATABASE, 'batch'); + const initial = await Promise.all( + Array.from({ length: 10 }, () => resolveOpenAICompatibleTarget(env, 'agent', 'model')) + ); + expect(initial.every((target) => target?.apiKey === 'endpoint-secret')).toBe(true); + expect(batch).toHaveBeenCalledTimes(1); + const remoteEnv = { ...env, DATABASE: createSqliteD1(fixture.sqlite) }; + await updateAdminSettings(remoteEnv, { + actorUserId: 'admin', + changes: [ + { name: 'llm.openAICompatible.baseUrl', value: 'https://new-endpoint.example.org/v1' }, + { name: 'llm.openAICompatible.apiKey', value: 'new-endpoint-secret' }, + ], + }); + expect(await resolveOpenAICompatibleTarget(env, 'agent', 'model')).toMatchObject({ + baseUrl: 'https://llm.example.com/v1', + apiKey: 'endpoint-secret', + }); + expect(batch).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(60_001); + expect(await resolveOpenAICompatibleTarget(env, 'agent', 'model')).toMatchObject({ + baseUrl: 'https://new-endpoint.example.org/v1', + apiKey: 'new-endpoint-secret', + }); + expect(batch).toHaveBeenCalledTimes(2); + }); + + it('skips a malformed unrelated credential and a corrupt endpoint candidate while retaining the valid endpoint key', async () => { + await configure(); + // Copy a real production-shaped row, then corrupt only its ciphertext; its newer date + // places it before the usable key. An unrelated raw credential is never decrypted here. + fixture.sqlite + .exec(`INSERT INTO platform_credentials (id,credential_type,provider,credential_kind,label,encrypted_token,iv,is_enabled,created_by,created_at,updated_at) + SELECT 'bad-endpoint',credential_type,provider,credential_kind,label,'bad-ciphertext','bad-iv',is_enabled,created_by,created_at,'2099-01-01' FROM platform_credentials LIMIT 1; + INSERT INTO platform_credentials (id,credential_type,provider,credential_kind,label,encrypted_token,iv,is_enabled,created_by,created_at,updated_at) + SELECT 'unrelated-raw',credential_type,'hetzner',credential_kind,label,'raw-cloud-key','bad-iv',is_enabled,created_by,created_at,'2099-01-01' FROM platform_credentials LIMIT 1`); + invalidateAdminSettings(env); + expect(await resolveOpenAICompatibleTarget(env, 'agent', 'model')).toMatchObject({ + apiKey: 'endpoint-secret', + }); + }); + it('keeps URL and key from one generation when admin rotates between capability and settings reads', async () => { await configure(); let release!: () => void, entered!: () => void; diff --git a/apps/api/tests/unit/services/profile-account-bindings.test.ts b/apps/api/tests/unit/services/profile-account-bindings.test.ts index 024e08ffbc..8e094584d3 100644 --- a/apps/api/tests/unit/services/profile-account-bindings.test.ts +++ b/apps/api/tests/unit/services/profile-account-bindings.test.ts @@ -99,7 +99,11 @@ describe('resolveProfileAccountBindings', () => { schema.credentials, schema.agentSettings, ]); - env = { DATABASE: createSqliteD1(sqlite) } as unknown as Env; + env = { + DATABASE: createSqliteD1(sqlite), + CF_ACCOUNT_ID: 'account-test', + AI_GATEWAY_ID: 'gateway-test', + } as unknown as Env; // owner: one Max account stored twice with identical ciphertext (a dual-write mirror). maxCipher = await cred('max', 'owner', 'Work Max', 'oauth-token', 'sk-ant-max'); diff --git a/apps/api/tests/unit/usage-ai.test.ts b/apps/api/tests/unit/usage-ai.test.ts index 7cd55a2745..79d876c491 100644 --- a/apps/api/tests/unit/usage-ai.test.ts +++ b/apps/api/tests/unit/usage-ai.test.ts @@ -45,6 +45,7 @@ testApp.route('/api/usage', usageRoutes); function makeEnv(overrides: Partial = {}): Env { return { AI_GATEWAY_ID: 'test-gateway', + CF_ACCOUNT_ID: 'account-test', ...overrides, } as Env; } diff --git a/apps/api/tests/unit/usage-budget-routes.test.ts b/apps/api/tests/unit/usage-budget-routes.test.ts index bf42d41dce..271c1b82c9 100644 --- a/apps/api/tests/unit/usage-budget-routes.test.ts +++ b/apps/api/tests/unit/usage-budget-routes.test.ts @@ -60,6 +60,8 @@ function makeEnv(overrides: Partial = {}): Env { return { KV: mockKV as unknown as KVNamespace, AI_GATEWAY_ID: 'test-gw', + CF_ACCOUNT_ID: 'test-account', + CF_API_TOKEN: 'test-api-token', AI_PROXY_DAILY_INPUT_TOKEN_LIMIT: undefined, AI_PROXY_DAILY_OUTPUT_TOKEN_LIMIT: undefined, ...overrides, diff --git a/apps/www/src/content/docs/docs/reference/configuration.md b/apps/www/src/content/docs/docs/reference/configuration.md index 6f926e6507..196570c1aa 100644 --- a/apps/www/src/content/docs/docs/reference/configuration.md +++ b/apps/www/src/content/docs/docs/reference/configuration.md @@ -2136,8 +2136,10 @@ default (`services/llm-endpoint-settings.ts`). | `llm.openAICompatible.allowPrivateNetwork` | `false` | Explicitly allow an operator endpoint on a private host. Metadata/link-local hosts remain forbidden. | | `aiProxy.directUpstreamEnabled` | `false` | Enable platform and BYO AI proxy routes when no addressable Cloudflare AI Gateway exists. Requires a provider credential for platform calls. Ignored when a gateway is addressable. | -Endpoint settings reuse the existing per-isolate settings cache (up to 60 seconds); a warm, -unconfigured Cloudflare call performs no additional D1 or credential reads. Admin changes +The endpoint capability reuses the existing per-isolate settings cache (up to 60 seconds); a warm, +unconfigured Cloudflare call performs no additional D1 or credential reads. Configured URL/key +pairs share one atomic D1 snapshot and TTL, so another isolate’s rotation cannot mix an old URL +with a new key (`services/llm-endpoint-snapshot.ts:resolveLlmEndpointSettings`). Admin changes invalidate the local cache immediately. Unreadable configuration refuses the request instead of sending prompts to another provider: the Workers AI proxy returns 503, and title generation falls back to truncation. Title and diagnosis settings lookups receive at most one quarter of the diff --git a/packages/ai-proxy/src/ai-token-budget.ts b/packages/ai-proxy/src/ai-token-budget.ts index f81f50c8a5..797d303c12 100644 --- a/packages/ai-proxy/src/ai-token-budget.ts +++ b/packages/ai-proxy/src/ai-token-budget.ts @@ -1,4 +1,3 @@ -import { hasLocalAiCostMetering } from './ai-gateway-availability'; /** * Per-user daily token budget tracking. * @@ -7,7 +6,6 @@ import { hasLocalAiCostMetering } from './ai-gateway-availability'; * environments, but it is no longer the primary counter because KV read-modify- * write updates are not atomic under concurrent requests. */ - import type { UserAiBudgetSettings } from '@simple-agent-manager/shared'; import { DEFAULT_AI_PROXY_DAILY_INPUT_TOKEN_LIMIT, @@ -17,6 +15,7 @@ import { import { log } from '@simple-agent-manager/worker-core'; import { getUserBudgetSettings } from './ai-budget-settings'; +import { hasLocalAiCostMetering } from './ai-gateway-availability'; import { checkMonthlyCostCap } from './ai-monthly-cost-cap'; import type { AiProxyEnv } from './env'; diff --git a/scripts/quality/direct-dependency-evidence.json b/scripts/quality/direct-dependency-evidence.json index 4dfa268d29..43796382ab 100644 --- a/scripts/quality/direct-dependency-evidence.json +++ b/scripts/quality/direct-dependency-evidence.json @@ -1,6 +1,11 @@ { "$schema": "./fixtures/supply-chain/direct-dependency-evidence.schema.json", "npm": { + "@ai-sdk/openai-compatible": { + "registryUrl": "https://www.npmjs.com/package/@ai-sdk/openai-compatible", + "homepageUrl": "https://ai-sdk.dev/providers/openai-compatible-providers", + "necessity": "Exposes the typed custom fetch extension for guarded OpenAI-compatible SAM endpoint calls; Mastra model routing has no such hook. Reuses the existing transitive 2.0.87 version with no new resolved SDK version; actual doGenerate is integration-tested." + }, "@astrojs/check": { "registryUrl": "https://www.npmjs.com/package/@astrojs/check", "necessity": "Validates Astro templates and embedded TypeScript." diff --git a/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md b/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md index 143d542b0f..b41ed9c8ff 100644 --- a/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md +++ b/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md @@ -33,13 +33,13 @@ Idea 01M72M9AEB933ZY8269D376DKC; task 01M7KNA1CNRHWG13CMNB2SVMP5; coordinator 01 ## Implementation evidence (in progress) -- Endpoint capability reads existing shared cache, 60s TTL; test proves 30 calls/fresh D1 facades =>1 snapshot read/0 credentials, then expiry =>2. Local rotation barrier passes; final atomic snapshot fix also covers writes from another isolate, whose invalidation generation is not visible locally. -- 10 endpoint tests pass, including actual SAM operator AI SDK doGenerate guarded-fetch extension; title/diagnosis settings timeout100ms of400ms budget, private endpoint refusal, coldoutage503, no forced include_usage. +- Endpoint capability reads existing shared cache, 60s TTL; test proves 30 calls/fresh D1 facades =>1 snapshot read/0 credentials, then expiry =>2. The atomic URL/key snapshot covers local mutation fencing and remote writes through another binding: oldpairuntilTTL, thennewpair. All-corrupt matching key rows refuse503; mixedbad+good and intentionally keyless endpoints remain usable. +- 13 endpoint tests pass, including actual SAM operator AI SDK doGenerate guarded-fetch extension; title/diagnosis settings timeout100ms of400ms budget, private endpoint refusal, coldoutage503, no forced include_usage. - Three passthrough guards remove baseline3; shared/title/diagnosis/SAM forwarding delegation also lowers their baseline entries.43 passthrough tests pass including same-origin redirects, private/metadata refusals, cross-origin307 body refusal, cross-origin303 credential stripping at all3sites. - Agent-key custom-baseUrl404 table includes Claude, Codex, OpenCode. Existing parser untouched; composable credential malformed-row suites must remain green. - Local cap uses existing provider cost rows/DO, no new migrations. Unknown/custom endpoint model price0; preserve main measured run-usage callback, never label estimates as measured. KV fallback at most31 parallel reads, rows retained through month-end +existing graceTTL; TTL-expiring test proves day1 spend still caps atmonth-end then resets nextmonth. - Root lint/typecheck/build62tasks passed before final rotation/retention fixes; latest package151tests pass. Fullroot suite currently running. - Draft PR#2829. Initial task-only mainpush rejectedGH013 required check, taskrecord kept infeaturePR. Existing SAM-assigned workspace was already isolated outputbranch at fresh origin/main60a11bb27; no extra worktree necessary. - Staging queues checked02:48UTC; primary reserved run44005681667 success, position3 turn04:03:57–04:13:57UTC, wake d39eaf5b-db90-4827-87a5-91edcf7bb58c at04:04. No deploy yet. -- Specialist early findings fixed: coldoutage fail-open, raw string URL parsing, OpenCode early keyreturn, authcatch mapping, URL/keyrotation, KVcostretention. Finalreviews pending. +- Specialist early findings fixed: coldoutage fail-open, raw string URL parsing, OpenCode early keyreturn, authcatch mapping, URL/keyrotation, KVcostretention. Finalreviews: performance+completion implementationPASS, CloudflarePASS, finalsecurityall-badkeyguardrecheckpending. - References: existing installed @mastra/core1.81 OpenAICompatibleConfig has no fetch extension; installed @ai-sdk/openai-compatible2.0.87 typed fetch extension and includeUsage defaultfalse verified before integration; official provider reference https://ai-sdk.dev/providers/openai-compatible-providers corroborates. Exact existing lockfile/API protocol reused; no modelcatalog changes. From 4b3d4083895eaaaa497a6cf1eacf166b5d522135 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 03:36:53 +0000 Subject: [PATCH 07/11] docs: record L12 validation and review evidence --- .../active/2026-11-17-l12-openai-compatible-endpoint.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md b/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md index b41ed9c8ff..989aac21ff 100644 --- a/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md +++ b/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md @@ -21,7 +21,7 @@ Rule 74: condition is an operator-enabled proxy with an addressable gateway or e - [x] Centralize proxy availability after auth; preserve #2674 unauthenticated 401. - [x] Direct-upstream paths; agent-key 404 when custom endpoint is not served, malformed-row controls. - [x] Split passthrough to <=500 lines, guard all 3 fetches, reduce outbound baseline by 3, redirect regression tests. -- [ ] Focused behavioral and cross-boundary tests with discriminating guards; lint/typecheck/test/build. +- [x] Focused behavioral and cross-boundary tests with discriminating guards; lint/typecheck/test/build (full collection plus all corrected-file reruns). - [x] Docs reflect settings and behavior, no unrelated spec edits. - [ ] Draft PR, then complete candidate ready + CodeRabbit request; required local security, Cloudflare, performance and completion reviews. - [ ] Check both staging leases, reserve and follow queue, deploy final candidate; live 401, SAM-mode chat, title generation, SAM agent, refused-private endpoint routing then reset settings; cleanup/release. @@ -33,7 +33,7 @@ Idea 01M72M9AEB933ZY8269D376DKC; task 01M7KNA1CNRHWG13CMNB2SVMP5; coordinator 01 ## Implementation evidence (in progress) -- Endpoint capability reads existing shared cache, 60s TTL; test proves 30 calls/fresh D1 facades =>1 snapshot read/0 credentials, then expiry =>2. The atomic URL/key snapshot covers local mutation fencing and remote writes through another binding: oldpairuntilTTL, thennewpair. All-corrupt matching key rows refuse503; mixedbad+good and intentionally keyless endpoints remain usable. +- Endpoint capability reads existing shared cache, 60s TTL; test proves 30 calls/fresh D1 facades =>1 snapshot read/0 credentials, then expiry =>2. The atomic URL/key snapshot covers local mutation fencing and remote writes through another binding: the old pair until TTL, then the new pair. All-corrupt matching key rows refuse503; mixed corrupt and good rows and intentionally keyless endpoints remain usable. - 13 endpoint tests pass, including actual SAM operator AI SDK doGenerate guarded-fetch extension; title/diagnosis settings timeout100ms of400ms budget, private endpoint refusal, coldoutage503, no forced include_usage. - Three passthrough guards remove baseline3; shared/title/diagnosis/SAM forwarding delegation also lowers their baseline entries.43 passthrough tests pass including same-origin redirects, private/metadata refusals, cross-origin307 body refusal, cross-origin303 credential stripping at all3sites. - Agent-key custom-baseUrl404 table includes Claude, Codex, OpenCode. Existing parser untouched; composable credential malformed-row suites must remain green. @@ -41,5 +41,8 @@ Idea 01M72M9AEB933ZY8269D376DKC; task 01M7KNA1CNRHWG13CMNB2SVMP5; coordinator 01 - Root lint/typecheck/build62tasks passed before final rotation/retention fixes; latest package151tests pass. Fullroot suite currently running. - Draft PR#2829. Initial task-only mainpush rejectedGH013 required check, taskrecord kept infeaturePR. Existing SAM-assigned workspace was already isolated outputbranch at fresh origin/main60a11bb27; no extra worktree necessary. - Staging queues checked02:48UTC; primary reserved run44005681667 success, position3 turn04:03:57–04:13:57UTC, wake d39eaf5b-db90-4827-87a5-91edcf7bb58c at04:04. No deploy yet. -- Specialist early findings fixed: coldoutage fail-open, raw string URL parsing, OpenCode early keyreturn, authcatch mapping, URL/keyrotation, KVcostretention. Finalreviews: performance+completion implementationPASS, CloudflarePASS, finalsecurityall-badkeyguardrecheckpending. +- Specialist early findings fixed: coldoutage fail-open, raw string URL parsing, OpenCode early keyreturn, authcatch mapping, URL/keyrotation, KVcostretention. All four required specialist reviews pass the implementation; final security review includes the all-corrupt-key guard. - References: existing installed @mastra/core1.81 OpenAICompatibleConfig has no fetch extension; installed @ai-sdk/openai-compatible2.0.87 typed fetch extension and includeUsage defaultfalse verified before integration; official provider reference https://ai-sdk.dev/providers/openai-compatible-providers corroborates. Exact existing lockfile/API protocol reused; no modelcatalog changes. + +- Full validation: all other package suites passed; API collected 16,476 tests in 1,079 files. All 62 failures came from 15 files loaded before corrections; a fresh combined rerun passed all 260 tests in those files (JSON success=true). Final merged-main analytics checks passed 62 tests. Root lint/typecheck/build passed 62 tasks; final cached checks after merging main are running. +- Added direct dependency audit evidence for the already-resolved SDK version. The latest main analytics change merged cleanly before candidate readiness. From 72e2370749449f64b5afa8b1eb602acc384217ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 03:46:44 +0000 Subject: [PATCH 08/11] refactor(api): reuse callback identity and credential response boundaries --- .../sam-session/agent-loop-llm.ts | 5 +- .../durable-objects/sam-session/agent-loop.ts | 3 +- .../sam-session/operator/model.ts | 10 +- .../routes/ai-proxy-passthrough-prepare.ts | 4 +- apps/api/src/routes/ai-proxy-passthrough.ts | 4 +- apps/api/src/routes/ai-proxy.ts | 2 +- apps/api/src/routes/workspaces/_helpers.ts | 23 +- .../routes/workspaces/runtime-agent-key.ts | 197 ++++++------------ .../routes/workspaces/runtime-git-token.ts | 14 +- .../workspaces/runtime-message-helpers.ts | 29 +-- apps/api/src/routes/workspaces/runtime.ts | 10 +- .../api/src/services/llm-endpoint-settings.ts | 5 +- apps/api/src/services/task-title.ts | 42 ++-- .../tests/unit/runtime-always-proxy.test.ts | 3 +- ...26-11-17-l12-openai-compatible-endpoint.md | 2 + 15 files changed, 130 insertions(+), 223 deletions(-) diff --git a/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts b/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts index 3275d99a69..5ee3c50880 100644 --- a/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts +++ b/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts @@ -51,8 +51,7 @@ export async function callLLM( userId: string, conversationId: string, baseSystemPrompt: string, - tools: AnthropicToolDef[], - endpoint: ChatCompletionsTarget | null + { tools, endpoint }: { tools: AnthropicToolDef[]; endpoint: ChatCompletionsTarget | null } ): Promise { const model = config.model; const systemPrompt = config.systemPromptAppend @@ -184,7 +183,7 @@ async function callAnthropicLLM( } /** Call an OpenAI-format chat completions target (Workers AI or an OpenAI-compatible endpoint). */ -async function callOpenAIChatLLM( +function callOpenAIChatLLM( target: ChatCompletionsTarget, systemPrompt: string, messages: OpenAIMessage[], 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 4d0e1c3897..9d66e127b3 100644 --- a/apps/api/src/durable-objects/sam-session/agent-loop.ts +++ b/apps/api/src/durable-objects/sam-session/agent-loop.ts @@ -158,8 +158,7 @@ export async function runAgentLoop( userId, conversationId, systemPrompt, - tools, - endpoint + { tools, endpoint } ); response = await attachTokenUsageAccounting(response, { env, 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 021338a966..dec14400a9 100644 --- a/apps/api/src/durable-objects/sam-session/operator/model.ts +++ b/apps/api/src/durable-objects/sam-session/operator/model.ts @@ -164,17 +164,15 @@ export async function recordOperatorStepUsage( const cached = Math.min(input, Math.max(0, step.usage.cachedInputTokens ?? 0)); const cachedRate = catalogModel.costPer1kCachedInputTokens ?? catalogModel.costPer1kInputTokens; const anthropic = config.model.startsWith('claude-'); + const providerId = anthropic ? 'anthropic' : 'workers-ai'; + const providerName = anthropic ? 'Anthropic' : 'Cloudflare Workers AI'; await incrementTokenUsage(env.KV, userId, input, output, env); await incrementProviderUsage( env.KV, userId, { - providerId: customEndpoint ? 'openai-compatible' : anthropic ? 'anthropic' : 'workers-ai', - providerName: customEndpoint - ? 'OpenAI-compatible endpoint' - : anthropic - ? 'Anthropic' - : 'Cloudflare Workers AI', + providerId: customEndpoint ? 'openai-compatible' : providerId, + providerName: customEndpoint ? 'OpenAI-compatible endpoint' : providerName, dialect: !customEndpoint && anthropic ? 'anthropic' : 'openai', }, input, diff --git a/apps/api/src/routes/ai-proxy-passthrough-prepare.ts b/apps/api/src/routes/ai-proxy-passthrough-prepare.ts index ce60665569..283a3b1cb1 100644 --- a/apps/api/src/routes/ai-proxy-passthrough-prepare.ts +++ b/apps/api/src/routes/ai-proxy-passthrough-prepare.ts @@ -99,9 +99,9 @@ async function checkPassthroughRateLimit( userId: string ): Promise<{ allowed: boolean; remaining: number; resetAt: number; limit: number }> { const rpmLimit = - parseInt(env.AI_PROXY_RATE_LIMIT_RPM || '', 10) || DEFAULT_AI_PROXY_RATE_LIMIT_RPM; + Number.parseInt(env.AI_PROXY_RATE_LIMIT_RPM || '', 10) || DEFAULT_AI_PROXY_RATE_LIMIT_RPM; const windowSeconds = - parseInt(env.AI_PROXY_RATE_LIMIT_WINDOW_SECONDS || '', 10) || + Number.parseInt(env.AI_PROXY_RATE_LIMIT_WINDOW_SECONDS || '', 10) || DEFAULT_AI_PROXY_RATE_LIMIT_WINDOW_SECONDS; const windowStart = getCurrentWindowStart(windowSeconds); const rateLimitKey = createRateLimitKey('ai-proxy', userId, windowStart); diff --git a/apps/api/src/routes/ai-proxy-passthrough.ts b/apps/api/src/routes/ai-proxy-passthrough.ts index b9f20239f4..cdc502591b 100644 --- a/apps/api/src/routes/ai-proxy-passthrough.ts +++ b/apps/api/src/routes/ai-proxy-passthrough.ts @@ -36,7 +36,6 @@ import { import { schedulePassthroughLimitHeaders } from './ai-proxy-passthrough-telemetry'; import { type ResolvedProxyUpstream, - resolveProxyUpstream, trimTrailingSlashes, } from './ai-proxy-passthrough-upstream'; @@ -404,5 +403,6 @@ export { aiProxyPassthroughRoutes, buildUpstreamAuthHeaders, joinUpstreamUrl, - resolveProxyUpstream, }; + +export { resolveProxyUpstream } from './ai-proxy-passthrough-upstream'; diff --git a/apps/api/src/routes/ai-proxy.ts b/apps/api/src/routes/ai-proxy.ts index 1206ef80b2..8b36f15e98 100644 --- a/apps/api/src/routes/ai-proxy.ts +++ b/apps/api/src/routes/ai-proxy.ts @@ -48,8 +48,8 @@ import { resolveOpenAIProxyCredential, schedulePlatformProxyLimitHeaders, } from './ai-proxy-platform-billing'; -import { customEndpointResponses } from './ai-proxy-upstream'; import { + customEndpointResponses, forwardToAnthropic, forwardToOpenAI, forwardToOpenAIResponses, diff --git a/apps/api/src/routes/workspaces/_helpers.ts b/apps/api/src/routes/workspaces/_helpers.ts index 1cbed71b77..be3d6628cf 100644 --- a/apps/api/src/routes/workspaces/_helpers.ts +++ b/apps/api/src/routes/workspaces/_helpers.ts @@ -91,22 +91,25 @@ export async function assertWorkspaceCallbackResourceById( return assertWorkspaceAcceptsCallback(env, workspace, workspaceId, callback, allowedStatuses); } +/** Shared projection keeps every callback's lifecycle and incarnation fence identical. */ +export const workspaceCallbackIdentityFields = { + workspaceId: schema.workspaces.id, + userId: schema.workspaces.userId, + projectId: schema.workspaces.projectId, + chatSessionId: schema.workspaces.chatSessionId, + status: schema.workspaces.status, + nodeId: schema.workspaces.nodeId, + nodeStatus: schema.nodes.status, + callbackGeneration: schema.workspaces.callbackGeneration, +}; + export async function loadWorkspaceCallbackIdentity( env: Env, workspaceId: string ): Promise { const db = drizzle(env.DATABASE, { schema }); const rows = await db - .select({ - workspaceId: schema.workspaces.id, - userId: schema.workspaces.userId, - projectId: schema.workspaces.projectId, - chatSessionId: schema.workspaces.chatSessionId, - status: schema.workspaces.status, - nodeId: schema.workspaces.nodeId, - nodeStatus: schema.nodes.status, - callbackGeneration: schema.workspaces.callbackGeneration, - }) + .select(workspaceCallbackIdentityFields) .from(schema.workspaces) .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) .where(eq(schema.workspaces.id, workspaceId)) diff --git a/apps/api/src/routes/workspaces/runtime-agent-key.ts b/apps/api/src/routes/workspaces/runtime-agent-key.ts index 93630f6d0d..9dad5d22fa 100644 --- a/apps/api/src/routes/workspaces/runtime-agent-key.ts +++ b/apps/api/src/routes/workspaces/runtime-agent-key.ts @@ -68,12 +68,9 @@ function buildPlatformInferenceConfig(input: { }) { const capability = getProxyCapability(input.agentType); if (!capability) return null; - const provider = - capability.proxyProviderTag === 'anthropic-passthrough' - ? 'anthropic-proxy' - : capability.usesOpencodeConfig - ? 'openai-compatible' - : 'openai-proxy'; + let provider = 'openai-proxy'; + if (capability.proxyProviderTag === 'anthropic-passthrough') provider = 'anthropic-proxy'; + else if (capability.usesOpencodeConfig) provider = 'openai-compatible'; const routeSegment = capability.proxyRouteSegment === 'anthropic' ? 'anthropic' : 'v1'; return { provider, @@ -114,6 +111,54 @@ runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async ( ); let credentialProviderMode = 'direct'; + const persistAttribution = ( + attribution: Parameters[2]['attribution'] + ) => + persistAgentCredentialAttribution(c.env, workspace, { + workspaceId, + agentSessionId: body.agentSessionId, + agentType: body.agentType, + attribution, + }); + const returnCredential = async ( + data: NonNullable, + providerMode: string, + inferenceConfig?: NonNullable> + ) => { + const persistedAttribution = await persistAttribution( + credentialAttributionFromData(data, body.agentType, providerMode) + ); + return callbackJsonWithJit(c, workspace, 'agent_key', { + apiKey: inferenceConfig ? '__sam_proxy__' : data.credential, + credentialKind: data.credentialKind, + credentialSource: data.credentialSource, + credentialReference: data.credentialReference, + credentialProvider: + data.credentialProvider ?? + (inferenceConfig ? data.providerDialect : undefined) ?? + agentCredentialProviderFallback(body.agentType), + providerMode, + credentialGeneration: persistedAttribution?.credentialGeneration, + ...(inferenceConfig ? { inferenceConfig } : {}), + }); + }; + const trackTaskCredentialSource = async ( + source: NonNullable['credentialSource'] + ) => { + const [task] = await db + .select({ id: schema.tasks.id }) + .from(schema.tasks) + .where(eq(schema.tasks.workspaceId, workspaceId)) + .limit(1); + if (task) { + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); + await db + .update(schema.tasks) + .set({ agentCredentialSource: source }) + .where(eq(schema.tasks.id, task.id)); + } + }; + // An account chosen for this run that can no longer be used (paused, removed) must stop // the run here. Without this, "no credential" would continue to the platform proxy or a // fallback below and run the chat on an account nobody chose for it. @@ -172,26 +217,7 @@ runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async ( } if (credentialData && !credentialData.baseUrl && opencodeRequiresDedicatedCredential) { - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - credentialProviderMode - ), - }); - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: credentialData.credential, - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), - providerMode: credentialProviderMode, - credentialGeneration: persistedAttribution?.credentialGeneration, - }); + return returnCredential(credentialData, credentialProviderMode); } if (!credentialData && opencodeRequiresDedicatedCredential) { @@ -282,45 +308,9 @@ runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async ( agentType: body.agentType, }); - // Track credential source on associated task - const taskRows = await db - .select({ id: schema.tasks.id }) - .from(schema.tasks) - .where(eq(schema.tasks.workspaceId, workspaceId)) - .limit(1); - const task = taskRows[0]; - if (task) { - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); - await db - .update(schema.tasks) - .set({ agentCredentialSource: credentialData.credentialSource }) - .where(eq(schema.tasks.id, task.id)); - } - - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - 'proxy-passthrough' - ), - }); + await trackTaskCredentialSource(credentialData.credentialSource); - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: '__sam_proxy__', - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? - credentialData.providerDialect ?? - agentCredentialProviderFallback(body.agentType), - providerMode: 'proxy-passthrough', - credentialGeneration: persistedAttribution?.credentialGeneration, - inferenceConfig, - }); + return returnCredential(credentialData, 'proxy-passthrough', inferenceConfig); } if (credentialData?.baseUrl) { @@ -334,26 +324,7 @@ runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async ( } if (credentialData) { - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - credentialProviderMode - ), - }); - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: credentialData.credential, - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), - providerMode: credentialProviderMode, - credentialGeneration: persistedAttribution?.credentialGeneration, - }); + return returnCredential(credentialData, credentialProviderMode); } // Claude Code and Codex require an explicit SAM provider selection before @@ -391,28 +362,10 @@ runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async ( agentType: body.agentType, }); - // Track credential source on associated task - const taskRows = await db - .select({ id: schema.tasks.id }) - .from(schema.tasks) - .where(eq(schema.tasks.workspaceId, workspaceId)) - .limit(1); - const task = taskRows[0]; - if (task) { - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); - await db - .update(schema.tasks) - .set({ agentCredentialSource: 'platform' }) - .where(eq(schema.tasks.id, task.id)); - } + await trackTaskCredentialSource('platform'); const platformAttribution = platformProxyAttribution(body.agentType); - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: platformAttribution, - }); + const persistedAttribution = await persistAttribution(platformAttribution); return callbackJsonWithJit(c, workspace, 'agent_key', { apiKey: '__platform_proxy__', @@ -432,42 +385,10 @@ runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async ( // Track credential source on associated task if applicable if (credentialData.credentialSource === 'platform') { - const taskRows = await db - .select({ id: schema.tasks.id }) - .from(schema.tasks) - .where(eq(schema.tasks.workspaceId, workspaceId)) - .limit(1); - const task = taskRows[0]; - if (task) { - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); - await db - .update(schema.tasks) - .set({ agentCredentialSource: 'platform' }) - .where(eq(schema.tasks.id, task.id)); - } + await trackTaskCredentialSource('platform'); } - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - credentialProviderMode - ), - }); - - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: credentialData.credential, - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), - providerMode: credentialProviderMode, - credentialGeneration: persistedAttribution?.credentialGeneration, - }); + return returnCredential(credentialData, credentialProviderMode); }); /** diff --git a/apps/api/src/routes/workspaces/runtime-git-token.ts b/apps/api/src/routes/workspaces/runtime-git-token.ts index ad44193ddd..9c20b56109 100644 --- a/apps/api/src/routes/workspaces/runtime-git-token.ts +++ b/apps/api/src/routes/workspaces/runtime-git-token.ts @@ -24,6 +24,7 @@ import { assertWorkspaceAcceptsCallback, assertWorkspaceCallbackIdentityCurrent, verifyWorkspaceCallbackAuth, + workspaceCallbackIdentityFields, } from './_helpers'; import { callbackJsonWithJit } from './runtime-callback-response'; const runtimeRoutes = new Hono<{ Bindings: Env }>(); @@ -122,7 +123,7 @@ async function resolveAdditionalRepositoryIds(input: { return []; } - let accessibleById = new Map(); + let accessibleById: Map; try { const repositories = await getUserInstallationRepositories( accessToken, @@ -174,15 +175,8 @@ runtimeRoutes.post('/:id/git-token', async (c) => { // Look up workspace → project to determine repo provider const workspaceRows = await db .select({ - workspaceId: schema.workspaces.id, + ...workspaceCallbackIdentityFields, installationId: schema.workspaces.installationId, - projectId: schema.workspaces.projectId, - chatSessionId: schema.workspaces.chatSessionId, - userId: schema.workspaces.userId, - status: schema.workspaces.status, - nodeId: schema.workspaces.nodeId, - nodeStatus: schema.nodes.status, - callbackGeneration: schema.workspaces.callbackGeneration, }) .from(schema.workspaces) .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) @@ -438,7 +432,7 @@ runtimeRoutes.post('/:id/git-token', async (c) => { : []; const scopedTokenOptions = { - ...(tokenOptions ?? {}), + ...tokenOptions, ...(githubRepoId ? { repositoryIds: [githubRepoId, ...additionalRepoIds.filter((id) => id !== githubRepoId)] } : { repositories: [repoShortName as string] }), diff --git a/apps/api/src/routes/workspaces/runtime-message-helpers.ts b/apps/api/src/routes/workspaces/runtime-message-helpers.ts index 68328c4d8a..2bb5daaeb5 100644 --- a/apps/api/src/routes/workspaces/runtime-message-helpers.ts +++ b/apps/api/src/routes/workspaces/runtime-message-helpers.ts @@ -1,9 +1,6 @@ -import { eq } from 'drizzle-orm'; -import { drizzle } from 'drizzle-orm/d1'; import { type Context } from 'hono'; import * as v from 'valibot'; -import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { parsePositiveInt } from '../../lib/route-helpers'; @@ -11,7 +8,11 @@ import { errors } from '../../middleware/error'; import { formatIssues, MessageBatchSchema } from '../../schemas'; import { nodeStatusTerminatesCallbacks } from '../../services/node-callback-auth'; import { persistError } from '../../services/observability'; -import { safeParseJson, type WorkspaceCallbackIdentitySnapshot } from './_helpers'; +import { + loadWorkspaceCallbackIdentity, + safeParseJson, + type WorkspaceCallbackIdentitySnapshot, +} from './_helpers'; type RuntimeContext = Context<{ Bindings: Env }>; type MessageBatchBody = v.InferOutput; @@ -188,27 +189,11 @@ export function validateMessageBatch(env: Env, body: MessageBatchBody): string { return sessionId; } -export async function loadMessageWorkspace( +export function loadMessageWorkspace( env: Env, workspaceId: string ): Promise { - const db = drizzle(env.DATABASE, { schema }); - const workspaceRows = await db - .select({ - workspaceId: schema.workspaces.id, - userId: schema.workspaces.userId, - projectId: schema.workspaces.projectId, - chatSessionId: schema.workspaces.chatSessionId, - status: schema.workspaces.status, - nodeId: schema.workspaces.nodeId, - nodeStatus: schema.nodes.status, - callbackGeneration: schema.workspaces.callbackGeneration, - }) - .from(schema.workspaces) - .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) - .where(eq(schema.workspaces.id, workspaceId)) - .limit(1); - return workspaceRows[0] ?? null; + return loadWorkspaceCallbackIdentity(env, workspaceId); } export function terminalMessagePersistenceResponse( diff --git a/apps/api/src/routes/workspaces/runtime.ts b/apps/api/src/routes/workspaces/runtime.ts index 945882ae23..f3611855d2 100644 --- a/apps/api/src/routes/workspaces/runtime.ts +++ b/apps/api/src/routes/workspaces/runtime.ts @@ -21,6 +21,7 @@ import { assertWorkspaceCallbackIdentityCurrent, assertWorkspaceCallbackResourceById, verifyWorkspaceCallbackAuth, + workspaceCallbackIdentityFields, } from './_helpers'; import { agentKeyRoutes } from './runtime-agent-key'; import { callbackJsonWithJit } from './runtime-callback-response'; @@ -86,16 +87,9 @@ runtimeRoutes.get('/:id/runtime', async (c) => { const workspaceRows = await db .select({ - workspaceId: schema.workspaces.id, - userId: schema.workspaces.userId, + ...workspaceCallbackIdentityFields, repository: schema.workspaces.repository, branch: schema.workspaces.branch, - projectId: schema.workspaces.projectId, - chatSessionId: schema.workspaces.chatSessionId, - status: schema.workspaces.status, - nodeId: schema.workspaces.nodeId, - nodeStatus: schema.nodes.status, - callbackGeneration: schema.workspaces.callbackGeneration, }) .from(schema.workspaces) .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) diff --git a/apps/api/src/services/llm-endpoint-settings.ts b/apps/api/src/services/llm-endpoint-settings.ts index 887cddc3c5..4891bab3df 100644 --- a/apps/api/src/services/llm-endpoint-settings.ts +++ b/apps/api/src/services/llm-endpoint-settings.ts @@ -69,7 +69,10 @@ export function validLlmBaseUrl(value: unknown): boolean { /** Normalized base URL without a trailing slash. Caller must have validated it. */ export function normalizeLlmBaseUrl(value: string): string { - return value.trim().replace(/\/+$/, ''); + const trimmed = value.trim(); + let end = trimmed.length; + while (end > 0 && trimmed[end - 1] === '/') end--; + return trimmed.slice(0, end); } function validModelId(value: unknown): boolean { diff --git a/apps/api/src/services/task-title.ts b/apps/api/src/services/task-title.ts index 0140a4f52f..4a7e133b60 100644 --- a/apps/api/src/services/task-title.ts +++ b/apps/api/src/services/task-title.ts @@ -279,6 +279,30 @@ async function fetchTaskTitle( }); } +function generatedTitleOrFallback( + rawTitle: string | null, + message: string, + maxLength: number, + modelId: string, + attempt: number +): string { + if (!rawTitle) { + log.warn('task_title.empty_response', { modelId, messageLength: message.length, attempt }); + return truncateTitle(message, maxLength); + } + const title = stripMarkdown(rawTitle); + if (!title) { + log.warn('task_title.empty_after_strip', { + modelId, + rawTitle, + messageLength: message.length, + attempt, + }); + return truncateTitle(message, maxLength); + } + return truncateTitle(title, maxLength); +} + /** * Generate a concise task title from a message using Workers AI via AI Gateway. * @@ -327,23 +351,7 @@ export async function generateTaskTitle( timeoutMs, errorDiagnosticMaxLength ); - if (!rawTitle) { - log.warn('task_title.empty_response', { modelId, messageLength: message.length, attempt }); - return truncateTitle(message, maxLength); - } - - const title = stripMarkdown(rawTitle); - if (!title) { - log.warn('task_title.empty_after_strip', { - modelId, - rawTitle, - messageLength: message.length, - attempt, - }); - return truncateTitle(message, maxLength); - } - - return truncateTitle(title, maxLength); + return generatedTitleOrFallback(rawTitle, message, maxLength, modelId, attempt); } catch (err) { if (err instanceof LlmUnavailableError) return truncateTitle(message, maxLength); const classified = classifyError(err); diff --git a/apps/api/tests/unit/runtime-always-proxy.test.ts b/apps/api/tests/unit/runtime-always-proxy.test.ts index 6e4e3baa28..e4cbb945f5 100644 --- a/apps/api/tests/unit/runtime-always-proxy.test.ts +++ b/apps/api/tests/unit/runtime-always-proxy.test.ts @@ -152,7 +152,8 @@ vi.mock('../../src/schemas', async (importOriginal) => { }; }); -vi.mock('../../src/routes/workspaces/_helpers', () => ({ +vi.mock('../../src/routes/workspaces/_helpers', async (importOriginal) => ({ + ...(await importOriginal()), assertWorkspaceAcceptsCallback: vi.fn(async (_env: unknown, workspace: unknown) => workspace), assertWorkspaceCallbackResourceById: vi.fn(async () => ({ workspaceId: 'test-workspace', diff --git a/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md b/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md index 989aac21ff..468264aaa9 100644 --- a/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md +++ b/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md @@ -46,3 +46,5 @@ Idea 01M72M9AEB933ZY8269D376DKC; task 01M7KNA1CNRHWG13CMNB2SVMP5; coordinator 01 - Full validation: all other package suites passed; API collected 16,476 tests in 1,079 files. All 62 failures came from 15 files loaded before corrections; a fresh combined rerun passed all 260 tests in those files (JSON success=true). Final merged-main analytics checks passed 62 tests. Root lint/typecheck/build passed 62 tasks; final cached checks after merging main are running. - Added direct dependency audit evidence for the already-resolved SDK version. The latest main analytics change merged cleanly before candidate readiness. + +- Final quality cleanup: consolidated existing callback identity projections and credential responses to address Sonar duplication without changing auth order or adding I/O. Security re-review passed with 108 callback/account tests; performance re-review passed with 123 tests. Title/endpoint cleanup passed 41 tests and raw SAM/proxy checks passed 134. Final root lint/typecheck/build passed all 62 tasks after these changes. Net non-test source growth is 1,064 lines, including mechanical split overhead. From b77bb6d36235809028faefe906e05944fe037bff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 03:49:22 +0000 Subject: [PATCH 09/11] docs: archive validated L12 implementation for release gates --- .../2026-11-17-l12-openai-compatible-endpoint.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) rename tasks/{active => archive}/2026-11-17-l12-openai-compatible-endpoint.md (94%) diff --git a/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md b/tasks/archive/2026-11-17-l12-openai-compatible-endpoint.md similarity index 94% rename from tasks/active/2026-11-17-l12-openai-compatible-endpoint.md rename to tasks/archive/2026-11-17-l12-openai-compatible-endpoint.md index 468264aaa9..25f24d3f3e 100644 --- a/tasks/active/2026-11-17-l12-openai-compatible-endpoint.md +++ b/tasks/archive/2026-11-17-l12-openai-compatible-endpoint.md @@ -23,7 +23,7 @@ Rule 74: condition is an operator-enabled proxy with an addressable gateway or e - [x] Split passthrough to <=500 lines, guard all 3 fetches, reduce outbound baseline by 3, redirect regression tests. - [x] Focused behavioral and cross-boundary tests with discriminating guards; lint/typecheck/test/build (full collection plus all corrected-file reruns). - [x] Docs reflect settings and behavior, no unrelated spec edits. -- [ ] Draft PR, then complete candidate ready + CodeRabbit request; required local security, Cloudflare, performance and completion reviews. +- [x] Draft PR, then complete candidate ready + CodeRabbit request; required local security, Cloudflare, performance and completion reviews. - [ ] Check both staging leases, reserve and follow queue, deploy final candidate; live 401, SAM-mode chat, title generation, SAM agent, refused-private endpoint routing then reset settings; cleanup/release. - [ ] Full CI and review gates pass, merge authorized by coordinator; channel PR/blocker/completion evidence; idea update with PR and commit. Coordinator monitors production deployment. @@ -48,3 +48,5 @@ Idea 01M72M9AEB933ZY8269D376DKC; task 01M7KNA1CNRHWG13CMNB2SVMP5; coordinator 01 - Added direct dependency audit evidence for the already-resolved SDK version. The latest main analytics change merged cleanly before candidate readiness. - Final quality cleanup: consolidated existing callback identity projections and credential responses to address Sonar duplication without changing auth order or adding I/O. Security re-review passed with 108 callback/account tests; performance re-review passed with 123 tests. Title/endpoint cleanup passed 41 tests and raw SAM/proxy checks passed 134. Final root lint/typecheck/build passed all 62 tasks after these changes. Net non-test source growth is 1,064 lines, including mechanical split overhead. + +- Archived at `/do` Phase 4 after final task-completion A–F PASS, with no critical/high implementation gaps. Release workflow gates (live staging, CI, CodeRabbit, merge, completion channel and idea update) remain pending and are tracked in PR #2829 and local `.do-state.md`; archive does not claim those gates passed. PR ready and CodeRabbit requested at 03:47 UTC, runtime candidate 72e237074. From 63e52bf3b70011943c509f4b6752756771fde255 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 04:21:13 +0000 Subject: [PATCH 10/11] test: preserve schema exports in account setup fixture --- .../unit/durable-objects/get-account-setup-status.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/api/tests/unit/durable-objects/get-account-setup-status.test.ts b/apps/api/tests/unit/durable-objects/get-account-setup-status.test.ts index 710021fa60..68c97e30c2 100644 --- a/apps/api/tests/unit/durable-objects/get-account-setup-status.test.ts +++ b/apps/api/tests/unit/durable-objects/get-account-setup-status.test.ts @@ -31,7 +31,8 @@ vi.mock('@simple-agent-manager/shared', async (importOriginal) => ({ resolvePolicyLimits: vi.fn().mockReturnValue({}), })); -vi.mock('../../../src/db/schema', () => ({ +vi.mock('../../../src/db/schema', async (importOriginal) => ({ + ...(await importOriginal()), credentials: { provider: 'credentials.provider', credentialType: 'credentials.credentialType', From 27a2436ccb17a7d34211af58a9ea248df9b9028a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 05:05:51 +0000 Subject: [PATCH 11/11] test: synchronize diagnosis races at actual model request --- .../tests/workers/diagnosis-runner-do.test.ts | 91 +++++++++++++------ 1 file changed, 62 insertions(+), 29 deletions(-) diff --git a/apps/api/tests/workers/diagnosis-runner-do.test.ts b/apps/api/tests/workers/diagnosis-runner-do.test.ts index 5e418048cc..6c4c69f333 100644 --- a/apps/api/tests/workers/diagnosis-runner-do.test.ts +++ b/apps/api/tests/workers/diagnosis-runner-do.test.ts @@ -1,5 +1,5 @@ import { applyD1Migrations, env, runDurableObjectAlarm, runInDurableObject } from 'cloudflare:test'; -import { beforeAll, describe, expect, it } from 'vitest'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import type { DiagnosisRunner } from '../../src/durable-objects/diagnosis-runner'; import { listDiagnosisEvents, reconcileDiagnosisRuns } from '../../src/services/diagnosis-runner'; @@ -32,20 +32,53 @@ async function seedRun(runId: string, userId: string): Promise { .run(); } -async function waitForModelAwait(runId: string): Promise { - for (let attempt = 0; attempt < 100; attempt++) { - const started = await env.DATABASE.prepare( - "SELECT 1 AS started FROM debug_diagnosis_run_events WHERE run_id=? AND step_key='model:1:started'" - ) - .bind(runId) - .first<{ started: number }>(); - if (started) return; - await new Promise((resolve) => setTimeout(resolve, 5)); +async function duringModelAwait( + runner: DurableObjectStub, + action: (instance: DiagnosisRunner) => Promise +): Promise { + // The full Workers pool has no AI binding/account credentials. Configure this DO's own + // gateway target, then suspend the actual network boundary, not the earlier audit event. + let owner!: DiagnosisRunner; + await runInDurableObject(runner, async (instance) => { + owner = instance; + instance.env = { + ...instance.env, + CF_ACCOUNT_ID: 'test-account', + CF_API_TOKEN: 'test-token', + AI_GATEWAY_ID: 'test-gateway', + }; + }); + let boundaryError: unknown; + const upstream = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + try { + expect(String(input)).toBe( + 'https://gateway.ai.cloudflare.com/v1/test-account/test-gateway/workers-ai/v1/chat/completions' + ); + expect(init?.method).toBe('POST'); + // Await the real terminal writer before releasing the model response. Run it in the + // model owner's I/O context: workerd forbids using test-context stubs from this DO. + await action(owner); + return Response.json({ + choices: [{ message: { content: 'Summary\nDeferred diagnosis completion' } }], + usage: { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 }, + }); + } catch (error) { + boundaryError = error; + throw error; + } + }); + vi.stubGlobal('fetch', upstream); + try { + await runDurableObjectAlarm(runner); + if (boundaryError) throw boundaryError; // The production alarm handles model errors itself. + expect(upstream).toHaveBeenCalledTimes(1); + } finally { + vi.unstubAllGlobals(); } - throw new Error('Diagnosis runner did not enter the model await'); } describe('DiagnosisRunner DO durability and fault injection', () => { + afterEach(() => vi.unstubAllGlobals()); it('starts idempotently and keeps one durable checkpoint/alarm after the 202 owner disappears', async () => { const runId = 'diagnosis-do-start-001'; await seedRun(runId, 'diagnosis-user-start'); @@ -142,15 +175,16 @@ describe('DiagnosisRunner DO durability and fault injection', () => { const runner = stub(runId); await runner.start(runId); - const alarm = runDurableObjectAlarm(runner); - await waitForModelAwait(runId); - await runner.cancel(runId); - expect( - await env.DATABASE.prepare('SELECT cancel_requested_at FROM debug_diagnosis_runs WHERE id=?') - .bind(runId) - .first<{ cancel_requested_at: string | null }>() - ).toMatchObject({ cancel_requested_at: expect.any(String) }); - await alarm; + await duringModelAwait(runner, async (instance) => { + await instance.cancel(runId); + expect( + await instance.env.DATABASE.prepare( + 'SELECT cancel_requested_at FROM debug_diagnosis_runs WHERE id=?' + ) + .bind(runId) + .first<{ cancel_requested_at: string | null }>() + ).toMatchObject({ cancel_requested_at: expect.any(String) }); + }); await runInDurableObject(runner, async (instance) => instance.alarm()); await runInDurableObject(runner, async (instance) => instance.alarm()); @@ -180,15 +214,14 @@ describe('DiagnosisRunner DO durability and fault injection', () => { const runner = stub(runId); await runner.start(runId); - const alarm = runDurableObjectAlarm(runner); - await waitForModelAwait(runId); - await env.DATABASE.prepare( - "UPDATE debug_diagnosis_runs SET deadline_at='2020-01-01T00:00:00.000Z',heartbeat_at='2020-01-01T00:00:00.000Z' WHERE id=?" - ) - .bind(runId) - .run(); - expect(await reconcileDiagnosisRuns(env)).toMatchObject({ terminalized: 1 }); - await alarm; + await duringModelAwait(runner, async (instance) => { + await instance.env.DATABASE.prepare( + "UPDATE debug_diagnosis_runs SET deadline_at='2020-01-01T00:00:00.000Z',heartbeat_at='2020-01-01T00:00:00.000Z' WHERE id=?" + ) + .bind(runId) + .run(); + expect(await reconcileDiagnosisRuns(instance.env)).toMatchObject({ terminalized: 1 }); + }); await runInDurableObject(runner, async (instance) => instance.alarm()); await runInDurableObject(runner, async (instance) => instance.alarm());