gemi 0.99.0 → 0.101.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/ai/AgentProvider.d.ts +11 -1
  2. package/dist/ai/AgentProvider.d.ts.map +1 -1
  3. package/dist/ai/CircuitStore.d.ts +59 -0
  4. package/dist/ai/CircuitStore.d.ts.map +1 -0
  5. package/dist/ai/FallbackProvider.d.ts +55 -1
  6. package/dist/ai/FallbackProvider.d.ts.map +1 -1
  7. package/dist/ai/Schema.d.ts +59 -5
  8. package/dist/ai/Schema.d.ts.map +1 -1
  9. package/dist/ai/index.d.ts +3 -1
  10. package/dist/ai/index.d.ts.map +1 -1
  11. package/dist/ai/index.js +13 -13
  12. package/dist/ai/index.js.map +7 -6
  13. package/dist/ai/providers/stream.d.ts.map +1 -1
  14. package/dist/chunk-4x41cmg3.js +9 -0
  15. package/dist/chunk-4x41cmg3.js.map +31 -0
  16. package/dist/{chunk-jv38q9n7.js → chunk-8v5z6646.js} +1 -1
  17. package/dist/{chunk-rc4z7ykq.js → chunk-d6prwkff.js} +1 -1
  18. package/dist/chunk-jyswmx60.js +6 -0
  19. package/dist/{chunk-x2kbwcc8.js.map → chunk-jyswmx60.js.map} +2 -2
  20. package/dist/{chunk-snsdztkj.js → chunk-pdvsc6jd.js} +1 -1
  21. package/dist/{chunk-x4wxfcfd.js → chunk-ztcsyeg7.js} +1 -1
  22. package/dist/facades/index.js +1 -1
  23. package/dist/http/index.js +1 -1
  24. package/dist/i18n/index.js +1 -1
  25. package/dist/kernel/index.js +1 -1
  26. package/dist/server/index.js +1 -1
  27. package/dist/services/index.js +1 -1
  28. package/package.json +1 -1
  29. package/dist/chunk-h15bd9vn.js +0 -9
  30. package/dist/chunk-h15bd9vn.js.map +0 -31
  31. package/dist/chunk-x2kbwcc8.js +0 -6
  32. /package/dist/{chunk-jv38q9n7.js.map → chunk-8v5z6646.js.map} +0 -0
  33. /package/dist/{chunk-rc4z7ykq.js.map → chunk-d6prwkff.js.map} +0 -0
  34. /package/dist/{chunk-snsdztkj.js.map → chunk-pdvsc6jd.js.map} +0 -0
  35. /package/dist/{chunk-x4wxfcfd.js.map → chunk-ztcsyeg7.js.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../ai/providers/errors.ts", "../ai/runtime.ts", "../ai/generate.ts", "../ai/signing.ts", "../ai/store/Nonces.ts", "../ai/store/Attachments.ts", "../ai/store/sse.ts", "../ai/Agent.ts", "../services/mcp/toAgentTools.ts", "../ai/ImageModel.ts", "../ai/providers/endpoints.ts", "../ai/providers/http.ts", "../ai/providers/images.ts", "../ai/ImageProvider.ts", "../ai/providers/fileRejection.ts", "../ai/providers/stream.ts", "../ai/providers/call.ts", "../ai/providers/capabilities.ts", "../ai/providers/request.ts", "../ai/AgentProvider.ts", "../ai/FallbackProvider.ts", "../ai/store/LiveRuns.ts", "../ai/store/FileOwners.ts", "../ai/store/Receipts.ts", "../ai/store/MemoryAgentStore.ts", "../ai/client/reducer.ts", "../ai/store/TurnJournal.ts", "../ai/AgentController.ts"],
3
+ "sources": ["../ai/providers/errors.ts", "../ai/runtime.ts", "../ai/generate.ts", "../ai/signing.ts", "../ai/store/Nonces.ts", "../ai/store/Attachments.ts", "../ai/store/sse.ts", "../ai/Agent.ts", "../services/mcp/toAgentTools.ts", "../ai/ImageModel.ts", "../ai/providers/endpoints.ts", "../ai/providers/http.ts", "../ai/providers/images.ts", "../ai/ImageProvider.ts", "../ai/providers/fileRejection.ts", "../ai/providers/stream.ts", "../ai/providers/call.ts", "../ai/providers/capabilities.ts", "../ai/providers/request.ts", "../ai/AgentProvider.ts", "../ai/CircuitStore.ts", "../ai/FallbackProvider.ts", "../ai/store/LiveRuns.ts", "../ai/store/FileOwners.ts", "../ai/store/Receipts.ts", "../ai/store/MemoryAgentStore.ts", "../ai/client/reducer.ts", "../ai/store/TurnJournal.ts", "../ai/AgentController.ts"],
4
4
  "sourcesContent": [
5
5
  "import type { AgentError } from \"../types\";\n\n/**\n * A non-2xx response, carried as an exception so the retry loop and\n * `normalizeError` can both read it.\n *\n * The body is kept parsed-if-possible and raw-if-not: OpenAI and Azure both\n * answer `{ error: { message, type, code } }` on a good day, and an HTML error\n * page from a proxy on a bad one, and the bad day is exactly when the text\n * matters.\n */\nexport class ProviderHttpError extends Error {\n readonly status: number;\n readonly body: unknown;\n readonly requestId?: string;\n\n constructor(status: number, body: unknown, requestId?: string) {\n super(`Provider request failed with status ${status}: ${describeBody(body)}`);\n this.name = \"ProviderHttpError\";\n this.status = status;\n this.body = body;\n this.requestId = requestId;\n }\n}\n\n/**\n * The request ran out of time. Its own class because it must not read as a\n * user abort: `stop()` means the person is done, and a timeout means the\n * network was, and only one of those is worth trying again.\n */\nexport class ProviderTimeoutError extends Error {\n readonly timeoutMs: number;\n\n constructor(timeoutMs: number) {\n super(`Provider request timed out after ${timeoutMs}ms`);\n this.name = \"ProviderTimeoutError\";\n this.timeoutMs = timeoutMs;\n }\n}\n\nfunction describeBody(body: unknown): string {\n const detail = errorBody(body);\n if (detail?.message) return detail.message;\n if (typeof body === \"string\") return body.slice(0, 500);\n return \"no error body\";\n}\n\ntype OpenAIErrorBody = { message?: string; type?: string; code?: string; param?: string };\n\nfunction errorBody(body: unknown): OpenAIErrorBody | null {\n if (!body || typeof body !== \"object\") return null;\n const wrapper = body as { error?: unknown };\n const inner = wrapper.error && typeof wrapper.error === \"object\" ? wrapper.error : body;\n const e = inner as OpenAIErrorBody & { innererror?: { code?: string } };\n if (typeof e.message !== \"string\" && typeof e.code !== \"string\" && typeof e.type !== \"string\") {\n return null;\n }\n // Azure hides the interesting code one level down when its content filter\n // fires, and the outer code is the useless `content_filter`.\n const code = e.innererror?.code ?? e.code;\n return { message: e.message, type: e.type, code, param: e.param };\n}\n\n/**\n * The HTTP status and request id of a provider failure, read off what was\n * thrown — server-side detail for `AgentRunResult.error`, never for a frame.\n *\n * By shape rather than by `instanceof ProviderHttpError`, so a custom provider\n * whose SDK throws its own error class with a `status` gets the same detail.\n * A `status` outside 100–599 is not an HTTP status and is ignored.\n */\nexport function httpErrorDetail(error: unknown): { status?: number; requestId?: string } {\n if (!error || typeof error !== \"object\") return {};\n const { status, requestId } = error as { status?: unknown; requestId?: unknown };\n return {\n ...(typeof status === \"number\" && status >= 100 && status <= 599 ? { status } : {}),\n ...(typeof requestId === \"string\" && requestId ? { requestId } : {}),\n };\n}\n\n/**\n * Provider failures onto `AgentErrorCode`.\n *\n * The contract an app is buying here is that it can branch on `rate_limited`\n * without knowing whose rate limit it was, and on `retryable` without knowing\n * which of the two APIs answered. So `retryable` is set from what is actually\n * true of the failure — a 429 from a spent quota is not retryable no matter\n * what its status code says, and neither is a request that will be too long\n * again next time.\n */\nexport function normalizeProviderError(error: unknown): AgentError {\n if (error instanceof ProviderTimeoutError) {\n return { code: \"provider_error\", message: error.message, retryable: true };\n }\n\n if (isAbort(error)) {\n return { code: \"aborted\", message: \"The request was aborted.\", retryable: false };\n }\n\n if (error instanceof ProviderHttpError) {\n return fromStatus(error.status, errorBody(error.body), error.message);\n }\n\n // `fetch` rejects with a TypeError for DNS failures, refused connections and\n // dropped sockets. Every one of those is worth another attempt.\n if (error instanceof TypeError) {\n return {\n code: \"provider_error\",\n message: `Could not reach the provider: ${error.message}`,\n retryable: true,\n };\n }\n\n if (error instanceof Error) {\n return { code: \"provider_error\", message: error.message, retryable: false };\n }\n\n return { code: \"unknown\", message: String(error), retryable: false };\n}\n\nfunction fromStatus(\n status: number,\n body: OpenAIErrorBody | null,\n fallbackMessage: string,\n): AgentError {\n const message = body?.message ?? fallbackMessage;\n const code = (body?.code ?? \"\").toLowerCase();\n const type = (body?.type ?? \"\").toLowerCase();\n const haystack = `${code} ${type} ${message}`.toLowerCase();\n\n if (status === 429) {\n // A spent quota answers 429 and will answer 429 for the rest of the month.\n // Retrying it is how a run turns one billing problem into `maxRetries`\n // billing problems and a much later error message.\n const outOfCredit = code === \"insufficient_quota\" || haystack.includes(\"quota\");\n return { code: \"rate_limited\", message, retryable: !outOfCredit };\n }\n\n if (status >= 500 || status === 408 || status === 409) {\n return { code: \"provider_error\", message, retryable: true };\n }\n\n if (isContextLength(haystack)) {\n return { code: \"context_length_exceeded\", message, retryable: false };\n }\n\n if (isContentFilter(haystack)) {\n return { code: \"content_filtered\", message, retryable: false };\n }\n\n // A schema the API refused. It is our request that is wrong, so the run\n // should surface it as a tool problem rather than a generic outage.\n if (body?.param?.startsWith(\"tools\") || haystack.includes(\"invalid schema for function\")) {\n return { code: \"invalid_tool_input\", message, retryable: false };\n }\n\n return { code: \"provider_error\", message, retryable: false };\n}\n\nfunction isContextLength(haystack: string): boolean {\n return (\n haystack.includes(\"context_length_exceeded\") ||\n haystack.includes(\"maximum context length\") ||\n haystack.includes(\"context window\") ||\n haystack.includes(\"reduce the length\")\n );\n}\n\nfunction isContentFilter(haystack: string): boolean {\n return (\n haystack.includes(\"content_filter\") ||\n haystack.includes(\"content_policy_violation\") ||\n haystack.includes(\"responsibleaipolicyviolation\") ||\n haystack.includes(\"content management policy\")\n );\n}\n\nfunction isAbort(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const e = error as { name?: string; code?: string };\n return e.name === \"AbortError\" || e.code === \"ABORT_ERR\";\n}\n",
6
6
  "import type { ProviderStreamParams } from \"./AgentProvider\";\nimport { supportsStrict, type Schema } from \"./Schema\";\nimport type { AgentError, AgentMessage, Usage } from \"./types\";\n\n/**\n * What one model call needs, whether the agent loop makes it or `generate` does.\n *\n * Moved out of `Agent.ts` rather than copied when `generate` arrived (#594).\n * `generate` is the agent's step without the loop around it — assemble one\n * call, read the stream, parse the answer — so each of these would otherwise\n * exist twice, and the two copies of \"how is a structured answer parsed\" or\n * \"how is usage summed\" are exactly the kind that drift apart unnoticed.\n *\n * Internal. Nothing here is exported from `gemi/ai`.\n */\n\n// --- aborting --------------------------------------------------------------\n\nexport class RunAborted extends Error {\n constructor() {\n super(\"The run was stopped\");\n this.name = \"RunAborted\";\n }\n}\n\nexport function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(new RunAborted());\n }\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(new RunAborted());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n\n// --- usage -----------------------------------------------------------------\n\nexport function emptyUsage(): Usage {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n}\n\nexport function addUsage(total: Usage, next: Usage | undefined): Usage {\n if (!next) return total;\n const merged: Usage = {\n inputTokens: total.inputTokens + (next.inputTokens ?? 0),\n outputTokens: total.outputTokens + (next.outputTokens ?? 0),\n totalTokens: total.totalTokens + (next.totalTokens ?? 0),\n };\n if (next.reasoningTokens !== undefined || total.reasoningTokens !== undefined) {\n merged.reasoningTokens = (total.reasoningTokens ?? 0) + (next.reasoningTokens ?? 0);\n }\n if (next.cachedInputTokens !== undefined || total.cachedInputTokens !== undefined) {\n merged.cachedInputTokens = (total.cachedInputTokens ?? 0) + (next.cachedInputTokens ?? 0);\n }\n if (next.imageInputTokens !== undefined || total.imageInputTokens !== undefined) {\n merged.imageInputTokens = (total.imageInputTokens ?? 0) + (next.imageInputTokens ?? 0);\n }\n if (next.imageOutputTokens !== undefined || total.imageOutputTokens !== undefined) {\n merged.imageOutputTokens = (total.imageOutputTokens ?? 0) + (next.imageOutputTokens ?? 0);\n }\n return merged;\n}\n\n// --- structured output -----------------------------------------------------\n\n/**\n * The best parse of a JSON document that is still arriving.\n *\n * Exists so a UI can bind fields before the object closes. It closes whatever\n * brackets are open and drops a trailing key with no value; when even that does\n * not parse it gives up and returns an empty object rather than throwing,\n * because a snapshot is a convenience and a run must not die for one.\n */\nexport function bestEffortParse(text: string): any {\n if (!text.trim()) return {};\n try {\n return JSON.parse(text);\n } catch {\n // fall through to repair\n }\n const closers: string[] = [];\n let inString = false;\n let escaped = false;\n for (const char of text) {\n if (inString) {\n if (escaped) escaped = false;\n else if (char === \"\\\\\") escaped = true;\n else if (char === '\"') inString = false;\n continue;\n }\n if (char === '\"') inString = true;\n else if (char === \"{\") closers.push(\"}\");\n else if (char === \"[\") closers.push(\"]\");\n else if (char === \"}\" || char === \"]\") closers.pop();\n }\n let repaired = text;\n if (inString) repaired += '\"';\n repaired = repaired.replace(/[,:]\\s*$/, \"\");\n const suffix = closers.reverse().join(\"\");\n try {\n return JSON.parse(repaired + suffix);\n } catch {\n // A trailing `\"key\":` leaves a property with no value; drop the key too.\n try {\n return JSON.parse(repaired.replace(/,?\\s*\"[^\"]*\"\\s*$/, \"\") + suffix);\n } catch {\n return {};\n }\n }\n}\n/**\n * The `output` parameter a provider is sent for a schema.\n *\n * `strict` is read off the schema, never chosen: an `s.json()` node anywhere in\n * it has no spelling in strict mode, so a schema containing one is sent\n * non-strict and the provider does not answer 400.\n */\nexport function outputFormat(schema: Schema<any>): NonNullable<ProviderStreamParams[\"output\"]> {\n return { name: \"output\", schema: schema.toJSONSchema(), strict: supportsStrict(schema) };\n}\n\n/**\n * A finished structured answer, checked against its schema.\n *\n * The failure is an `AgentError` with `code: \"invalid_output\"` rather than the\n * schema's own `errors: string[]`, so a caller branches on a code the way it\n * does for `invalid_tool_input`, and the list is joined into the message for a\n * person — or a retry prompt — to read.\n *\n * `bestEffortParse`, not `JSON.parse`, for the reason the agent loop has always\n * used it: the text is the whole answer by now, so the repair has nothing to\n * close, and a document that still does not parse comes back `{}` and fails the\n * schema with a message naming what is missing, instead of a `SyntaxError`\n * position nobody can act on. A cut-off answer never reaches here — see the\n * `length` checks in both callers — because a repaired prefix can pass a loose\n * schema and look finished.\n */\nexport function parseOutput<T>(\n schema: Schema<T>,\n text: string,\n): { ok: true; value: T } | { ok: false; error: AgentError } {\n const parsed = schema.safeParse(bestEffortParse(text));\n if (parsed.ok === true) return { ok: true, value: parsed.value };\n return {\n ok: false,\n error: {\n code: \"invalid_output\",\n message: `The model's structured answer did not match the output schema: ${parsed.errors.join(\", \")}`,\n retryable: true,\n },\n };\n}\n\n// --- building the assistant message ----------------------------------------\n\n/**\n * Resolves a string built by repeated concatenation, in place.\n *\n * `text = text + delta`, run once per streamed token, does not build a string —\n * it builds a rope: a tree of pointers to every fragment, which the engine\n * flattens only when something needs the characters contiguously. A message\n * that nothing reads before it is persisted therefore keeps all of its\n * fragments alive, and the tree costs several times the text.\n *\n * Measured on Bun 1.x, 600 deltas of six characters (a ~450-token answer, 3.5 KB\n * of ASCII): held as a rope, 18.7 KB. Resolved, 3.5 KB — half the UTF-16 size,\n * because a flat ASCII string is stored one byte per character and a rope\n * cannot be. That is 5.3x, and it is paid by every message a store keeps and\n * every run the live registry holds.\n *\n * Indexing is what forces the resolution: `text[0]` cannot be answered without\n * the characters, so the engine collapses the tree and drops the fragments.\n * Nothing is allocated and nothing is copied, which is why this is not\n * `split(\"\").join(\"\")` — that measures the same but allocates one string per\n * character to get there.\n *\n * DO NOT DELETE THIS AS A NO-OP. It reads like one and it is not; the value is\n * the side effect on the receiver. If a future engine does not resolve on\n * index, this silently becomes a real no-op and memory returns to what it is\n * today — a safe failure, which is why it is written as a hint rather than as a\n * round trip through an encoder that would also mangle a lone surrogate.\n */\nexport function resolveRope(text: string): string {\n if (text.length > 0) void text[0];\n return text;\n}\n\nexport function appendText(message: AgentMessage, type: \"text\" | \"reasoning\", delta: string) {\n const last = message.content[message.content.length - 1];\n if (last && last.type === type) {\n (last as { text?: string }).text = ((last as { text?: string }).text ?? \"\") + delta;\n return;\n }\n message.content.push(\n type === \"text\" ? { type: \"text\", text: delta } : { type: \"reasoning\", text: delta },\n );\n}\n\n/**\n * Reasoning is accumulated per ITEM, not per message, and the item's id is kept.\n *\n * This used to go through `appendText`, which merges on the part *type* alone\n * and has nowhere to put an id. Both halves of that were wrong and neither was\n * visible in the transcript:\n *\n * - `request.ts` drops a reasoning item with no id, deliberately — the id is\n * the API's handle on the stored reasoning and a fabricated one would look\n * like continuity that is not there. So an id dropped here meant reasoning\n * was never sent back at all: on a two-step run the model re-derived its\n * own argument from nothing, and the prompt cache (which keys on the\n * literal item) missed every time. Measured against the live Responses API\n * in `live/live.test.ts`: the second call's input carried zero reasoning\n * items.\n * - a step that produces two reasoning items was flattening them into one\n * part, so even with an id there would have been one id for two items'\n * text.\n *\n * A part with no id is still appended rather than dropped: the text is what a\n * UI renders, and a provider that reports no item id (Azure does not always)\n * should still show its thinking. It just cannot be echoed back, which is the\n * bargain `reasoningItem` already documents.\n */\nexport function appendReasoning(message: AgentMessage, id: string | undefined, delta: string) {\n const last = message.content[message.content.length - 1];\n if (last && last.type === \"reasoning\" && last.id === id) {\n last.text = (last.text ?? \"\") + delta;\n return;\n }\n message.content.push(\n id ? { type: \"reasoning\", id, text: delta } : { type: \"reasoning\", text: delta },\n );\n}\n",
@@ -17,12 +17,13 @@
17
17
  "import type { AgentError, Usage } from \"../types\";\nimport type { ProviderTarget } from \"./endpoints\";\nimport { normalizeProviderError } from \"./errors\";\nimport { requestWithRetry, type FetchLike } from \"./http\";\n\n/**\n * One image call, retried where retrying is free and not where it costs a render.\n *\n * MEASURED against a `gpt-image-2` deployment, api-version `preview`, and every\n * decision in this file comes from one of these rather than from documentation —\n * which disagreed with the endpoint on three separate points:\n *\n * 200 {base}/images/generations low, 1024x1024, png 15.0s\n * 200 {base}/images/generations low, 1024x1024, png, transparent 14.6s\n * 400 {base}/images/generations high, 1536x1024, webp\n * → \"Invalid value: 'webp'. Supported values are: 'png' and 'jpeg'.\"\n * 200 {base}/images/generations high, 1536x1024, png 117.8s\n * 200 {base}/images/edits low, one image[], no mask, no size 13.7s\n * → answered size \"1254x1254\", which is neither what was asked for\n * nor a multiple of 16\n * 200 {base}/images/edits low, one image[], mask, 1024x1024 14.0s\n * 200 {base}/images/edits low, two image[], 1024x1024 20.2s\n *\n * The documentation was wrong that `webp` is accepted, wrong that this model\n * cannot do transparency, and wrong about the `usage` field names. The response\n * shape, verbatim:\n *\n * { \"created\": 1790519365, \"background\": \"opaque\", \"output_format\": \"png\",\n * \"quality\": \"low\", \"size\": \"1024x1024\",\n * \"data\": [{ \"b64_json\": \"…\" }],\n * \"usage\": { \"input_tokens\": 15,\n * \"input_tokens_details\": { \"image_tokens\": 0, \"text_tokens\": 15 },\n * \"output_tokens\": 196,\n * \"output_tokens_details\": { \"image_tokens\": 196, \"text_tokens\": 0 },\n * \"total_tokens\": 211 } }\n *\n * There is no `revised_prompt` in any of the five successful responses. See\n * `ImageModel` for why the field is not on the public result type.\n */\nexport type ImagesEndpoint = {\n generationsUrl: string;\n editsUrl: string;\n /** Async for the same reason the Responses endpoint's is: Entra tokens expire\n * mid-conversation, so the credential is read per request. */\n headers: () => Promise<Record<string, string>>;\n timeoutMs: number;\n maxRetries: number;\n fetchImpl?: FetchLike;\n};\n\n/**\n * Longer than the Responses default, because here the timer bounds the work.\n *\n * A `high` / 1536x1024 render measured 117.8 seconds against a 120_000 default —\n * two seconds of headroom. That is not a timeout, it is a coin flip, and losing\n * it used to mean three renders billed (see `RequestOptions.retryTimeouts`). 300\n * seconds is chosen to clear the measured worst case with room for a busier\n * resource and a larger size, and an app that knows its own ceiling sets\n * `timeoutMs` in config.\n */\nexport const DEFAULT_IMAGE_TIMEOUT_MS = 300_000;\n\nexport function imagesEndpoint(target: ProviderTarget): ImagesEndpoint {\n return {\n generationsUrl: `${target.base}/images/generations${target.query}`,\n editsUrl: `${target.base}/images/edits${target.query}`,\n headers: target.headers,\n timeoutMs: target.timeoutMs,\n maxRetries: target.maxRetries,\n };\n}\n\n/**\n * What an image call failed with, as a normalized code rather than a vendor body.\n *\n * A one-shot call throws where the streaming path emits an `error` event — a\n * promise has nowhere else to put it, and a caller awaiting bytes should not have\n * to check a union. The normalized `AgentError` is carried so an app can branch\n * on `rate_limited` exactly as it would for a text call.\n *\n * The vendor's own body is on `cause` and deliberately NOT in `message`. Inside a\n * tool a throw becomes a tool result the model reads (#446), and a provider error\n * body is not something to hand a model verbatim when a sentence will do.\n */\nexport class ImageRequestError extends Error {\n readonly code: AgentError[\"code\"];\n readonly retryable: boolean;\n\n constructor(error: AgentError, options: { cause?: unknown } = {}) {\n super(error.message, options);\n this.name = \"ImageRequestError\";\n this.code = error.code;\n this.retryable = error.retryable;\n }\n}\n\n/** The JSON body of a generation. Vendor field names, built by `ImageModel`. */\nexport type ImageGenerationRequest = {\n model: string;\n prompt: string;\n size?: string;\n quality?: string;\n background?: string;\n output_format?: string;\n output_compression?: number;\n};\n\n/** What every image call answers, before `ImageModel` gives it a public shape. */\nexport type ImageResponse = {\n /** Decoded from `b64_json`. */\n bytes: Uint8Array;\n mimeType: string;\n /** Read off the response, never assumed — an edit with no `size` answered\n * `1254x1254`. */\n size: string;\n background?: string;\n usage: Usage;\n};\n\nconst MIME_BY_FORMAT: Record<string, string> = {\n png: \"image/png\",\n jpeg: \"image/jpeg\",\n};\n\n/**\n * The vendor's `usage` onto gemi's.\n *\n * Separate from `toUsage` in `stream.ts` rather than shared with it. The three\n * totals have the same names, so sharing looked right; the details objects do\n * not. `toUsage` reads `output_tokens_details.reasoning_tokens` and\n * `input_tokens_details.cached_tokens`, and this endpoint sends `image_tokens`\n * and `text_tokens` in both — so reusing it silently discards the only part of\n * this payload that is specific to images, which is the part `imageInputTokens`\n * exists for.\n */\nexport function toImageUsage(raw: any): Usage {\n const inputTokens = Number(raw?.input_tokens ?? 0);\n const outputTokens = Number(raw?.output_tokens ?? 0);\n const usage: Usage = {\n inputTokens,\n outputTokens,\n totalTokens: Number(raw?.total_tokens ?? inputTokens + outputTokens),\n };\n const inImages = raw?.input_tokens_details?.image_tokens;\n if (typeof inImages === \"number\") usage.imageInputTokens = inImages;\n const outImages = raw?.output_tokens_details?.image_tokens;\n if (typeof outImages === \"number\") usage.imageOutputTokens = outImages;\n return usage;\n}\n\nfunction decodeBase64(b64: string): Uint8Array {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\nfunction parseImageResponse(json: any): ImageResponse {\n const first = json?.data?.[0];\n const b64 = first?.b64_json;\n if (typeof b64 !== \"string\" || b64.length === 0) {\n // Not an assertion for its own sake: the endpoint has a `url` response mode\n // for other models, and a deployment that answered with one would otherwise\n // reach the caller as an empty Blob.\n throw new ImageRequestError({\n code: \"provider_error\",\n message: \"The provider answered an image call with no base64 image data.\",\n retryable: false,\n });\n }\n\n const format = typeof json.output_format === \"string\" ? json.output_format : \"png\";\n return {\n bytes: decodeBase64(b64),\n mimeType: MIME_BY_FORMAT[format] ?? `image/${format}`,\n size: typeof json.size === \"string\" ? json.size : \"\",\n ...(typeof json.background === \"string\" ? { background: json.background } : {}),\n usage: toImageUsage(json.usage),\n };\n}\n\ntype CallOptions = { signal?: AbortSignal };\n\nasync function post(\n url: string,\n init: RequestInit,\n endpoint: ImagesEndpoint,\n options: CallOptions,\n): Promise<ImageResponse> {\n let response: Response;\n try {\n response = await requestWithRetry(url, init, {\n maxRetries: endpoint.maxRetries,\n timeoutMs: endpoint.timeoutMs,\n // The whole point. A timeout here means the render probably happened and\n // we hung up; retrying pays for it again. 429 and 5xx are still retried.\n retryTimeouts: false,\n signal: options.signal,\n fetchImpl: endpoint.fetchImpl,\n });\n } catch (error) {\n // An abort is the caller's own doing and must stay recognisable as one —\n // `stop()` is not a provider failure.\n if (options.signal?.aborted) throw error;\n throw new ImageRequestError(normalizeProviderError(error), { cause: error });\n }\n\n return parseImageResponse(await response.json());\n}\n\nexport async function generateImage(\n endpoint: ImagesEndpoint,\n body: ImageGenerationRequest,\n options: CallOptions = {},\n): Promise<ImageResponse> {\n return await post(\n endpoint.generationsUrl,\n {\n method: \"POST\",\n headers: { ...(await endpoint.headers()), \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n endpoint,\n options,\n );\n}\n\n/**\n * An edit, as multipart.\n *\n * `image[]` repeated once per input, measured — two parts reported 2048 input\n * image tokens against 1024 for one. No `content-type` header, for the reason\n * `uploadFile` gives: the boundary is generated with the body, and setting the\n * header by hand fails with a parser error that names nothing useful.\n */\nexport async function editImage(\n endpoint: ImagesEndpoint,\n form: FormData,\n options: CallOptions = {},\n): Promise<ImageResponse> {\n return await post(\n endpoint.editsUrl,\n { method: \"POST\", headers: await endpoint.headers(), body: form },\n endpoint,\n options,\n );\n}\n",
18
18
  "import {\n azureTarget,\n openAITarget,\n type AzureConfig,\n type ProviderConfig,\n} from \"./providers/endpoints\";\nimport { normalizeProviderError } from \"./providers/errors\";\nimport {\n DEFAULT_IMAGE_TIMEOUT_MS,\n editImage,\n generateImage,\n imagesEndpoint,\n type ImageGenerationRequest,\n type ImageResponse,\n type ImagesEndpoint,\n} from \"./providers/images\";\nimport type { AgentError } from \"./types\";\n\n/**\n * A provider that makes images, separate from the one that makes text.\n *\n * WHY NOT A METHOD ON `AgentProvider`. `provider.generateImage(...)` was the\n * requested shape and it does not survive two facts about this codebase.\n *\n * First, `AgentProvider` is abstract with `stream` and `upload`, and a third\n * abstract member breaks every implementor — including gemi's own `FakeProvider`\n * (duck-typed) and `RecordingProvider` (hand-implements all five members). A\n * capability that only one vendor surface has should not be a hole punched in the\n * interface every other surface has to fill.\n *\n * Second, and this is the real one: an image deployment would have to lie about\n * itself. `capabilities` is computed in the constructor from the model id, and\n * `capabilitiesForModel` deliberately grants an unrecognised id *every*\n * capability — so `AzureOpenAIProvider.model(\"gpt-image-2\")` claims structured\n * output, reasoning and tool search, and exposes a `stream()` that is callable\n * and broken. Splitting the hierarchy makes the wrong call unspellable instead\n * of merely wrong, which is the same reasoning `ScopedAttachments` is built on.\n *\n * What the two hierarchies *do* share is the part worth sharing: which host,\n * which credential, and Azure's api-version fork. That is `providers/endpoints.ts`\n * and neither class reimplements it.\n */\nexport abstract class ImageProvider {\n /** The model, or on Azure the model the deployment serves. */\n abstract readonly model: string;\n\n /** For autocomplete only; any string is accepted, because a model released\n * next Tuesday must not need a gemi release to use. */\n static models(): readonly string[] {\n return [];\n }\n\n protected abstract endpoint(): ImagesEndpoint;\n\n /** What goes in the body's `model`. The deployment, on Azure. */\n protected modelName(): string {\n return this.model;\n }\n\n async generate(params: ImageProviderParams): Promise<ImageResponse> {\n return await generateImage(this.endpoint(), this.body(params), { signal: params.signal });\n }\n\n /**\n * An edit. `images` is required and non-empty — see `ImageModel.edit` for why\n * that is a separate method rather than an optional field on `generate`.\n */\n async edit(params: ImageProviderEditParams): Promise<ImageResponse> {\n const form = new FormData();\n for (const [key, value] of Object.entries(this.body(params))) {\n if (value !== undefined) form.set(key, String(value));\n }\n // Repeated `image[]`, measured: two parts reported 2048 input image tokens\n // against 1024 for one, so each part is read as its own image rather than\n // the last one winning.\n for (const image of params.images) form.append(\"image[]\", image, image.name);\n if (params.mask) form.set(\"mask\", params.mask, params.mask.name);\n return await editImage(this.endpoint(), form, { signal: params.signal });\n }\n\n /**\n * Maps gemi's params onto the vendor's field names.\n *\n * On the base class rather than in each subclass: OpenAI and Azure take the\n * same body, and the only difference is that Azure's `model` names a\n * deployment — which `modelName()` answers.\n */\n protected body(params: ImageProviderParams): ImageGenerationRequest {\n return {\n model: this.modelName(),\n prompt: params.prompt,\n ...(params.size ? { size: params.size } : {}),\n ...(params.quality ? { quality: params.quality } : {}),\n ...(params.background ? { background: params.background } : {}),\n ...(params.format ? { output_format: params.format } : {}),\n ...(params.compression !== undefined ? { output_compression: params.compression } : {}),\n };\n }\n\n /** As `AgentProvider.normalizeError`, so an app branches on `rate_limited`\n * without caring which surface produced it. */\n normalizeError(error: unknown): AgentError {\n return normalizeProviderError(error);\n }\n}\n\nexport type ImageProviderParams = {\n prompt: string;\n size?: string;\n quality?: string;\n background?: string;\n format?: string;\n compression?: number;\n signal?: AbortSignal;\n};\n\nexport type ImageProviderEditParams = ImageProviderParams & {\n images: File[];\n mask?: File;\n};\n\n/**\n * Autocomplete, not a gate — and short on purpose. These are the image models\n * with a Responses-era `/images` surface; `gpt-image-2` is the one measured.\n */\nconst OPENAI_IMAGE_MODELS = [\"gpt-image-2\", \"gpt-image-1.5\", \"gpt-image-1\"] as const;\n\nexport class OpenAIImageProvider extends ImageProvider {\n readonly model: string;\n protected readonly config: ProviderConfig;\n\n constructor(model: string, config: ProviderConfig = {}) {\n super();\n this.model = model;\n this.config = config;\n }\n\n static model(model: string, config?: ProviderConfig): OpenAIImageProvider {\n return new OpenAIImageProvider(model, config);\n }\n\n static models(): readonly string[] {\n return OPENAI_IMAGE_MODELS;\n }\n\n protected endpoint(): ImagesEndpoint {\n return imagesEndpoint(openAITarget(this.config, { timeoutMs: DEFAULT_IMAGE_TIMEOUT_MS }));\n }\n}\n\n/**\n * Azure's image surface, which is the same resource and credential as its chat\n * surface — an app that already configured `AZURE_OPENAI_*` for an agent writes\n * only the deployment name here.\n *\n * `.model()`, not `.deployment()`, for the symmetry `AzureOpenAIProvider` keeps:\n * apps name a model and `AzureConfig.deployment` is the override for a resource\n * whose deployment is called something else.\n */\nexport class AzureOpenAIImageProvider extends ImageProvider {\n readonly model: string;\n protected readonly config: AzureConfig;\n\n constructor(model: string, config: AzureConfig = {}) {\n super();\n this.model = model;\n this.config = config;\n }\n\n static model(model: string, config?: AzureConfig): AzureOpenAIImageProvider {\n return new AzureOpenAIImageProvider(model, config);\n }\n\n static models(): readonly string[] {\n return OPENAI_IMAGE_MODELS;\n }\n\n protected modelName(): string {\n return this.config.deployment ?? this.model;\n }\n\n protected endpoint(): ImagesEndpoint {\n return imagesEndpoint(azureTarget(this.config, { timeoutMs: DEFAULT_IMAGE_TIMEOUT_MS }));\n }\n}\n",
19
19
  "import type { AgentMessage } from \"../types\";\nimport { ProviderHttpError } from \"./errors\";\nimport type { ResponsesInputItem, ResponsesRequest } from \"./request\";\n\n/**\n * A stored file the provider will not read, and what to do about it (#684).\n *\n * THE FAILURE. A `FilePart` lives in the thread's history and goes back up on\n * every request. If the provider refuses its `file_id` — an id from the wrong\n * upload purpose, a file that was deleted or expired, a resource that no longer\n * owns it — the turn that added it fails with a 400, and so does every turn\n * after it, because the history that holds the part is the history every turn\n * sends. The user's only way out was a new thread.\n *\n * THE FIX. When a 400 names a file block of the request, that block is swapped\n * for a line of text saying the attachment could not be read, and the request\n * is sent again. The model is told, so it can tell the user rather than answer\n * as though it had read the file. `Agent` is told too (a `file-rejected`\n * provider event), and marks the stored part `providerRejected` so later turns\n * send the note instead of the id and do not pay for a failed request first.\n *\n * WHAT A REFUSAL LOOKS LIKE, MEASURED against a live Azure resource (gpt-6-sol,\n * `/openai/v1`, `api-version=preview`, 2026-10-01). Each body is recorded in\n * `__fixtures__` and the tests read those files:\n *\n * A `user_data` id (`azure-error-file-id-prefix.json`): `param` points at the\n * block, `input[2].content[1].file_id`, and the message says `Expected an\n * ID that begins with 'assistant'`. With TWO such ids in one request only\n * the first is named, which is why more than one retry is allowed below.\n * An id that does not exist, or a file that was deleted\n * (`azure-error-files-not-found.json`, `azure-error-file-deleted.json`):\n * `param: null`, and the message lists every missing id at once —\n * `Files [assistant-…, assistant-…] were not found due to ownership\n * verification failure.` So the ids are read out of the message, by\n * matching the ids the request actually sent rather than by parsing the\n * sentence, which also covers OpenAI's wording without having measured it.\n * The right id in the wrong block (`azure-error-file-type.json`): `param:\n * \"input\"` and `… but got .png.`, naming neither the block nor the id. The\n * block is found by the extension and the block type the message names,\n * and only when that settles on exactly one file: guessing between two\n * would hide a file that was fine.\n *\n * Anything else is left alone and fails the turn as it did before. In\n * particular a refusal that names no file in this request is not retried: a\n * retry is only worth sending when something about the request has changed.\n */\n\n/** What the request builder knew about each file id it sent, for the note. */\nexport type SentFile = { name?: string; mimeType?: string };\n\n/**\n * How many times one call may be re-sent for a rejected file. Each retry has to\n * take out a file the previous ones did not, so this bounds requests, not\n * files: Azure names one bad block per 400 (`param` holds a single path), and\n * a thread that picked up several `user_data` ids before #682 would otherwise\n * clear one per turn and fail every turn until it ran out.\n */\nexport const MAX_FILE_REJECTION_RETRIES = 3;\n\n/** The file ids in a history, with the name each was attached under. */\nexport function sentFiles(messages: AgentMessage[]): Map<string, SentFile> {\n const files = new Map<string, SentFile>();\n for (const message of messages) {\n for (const part of message.content ?? []) {\n if (part.type !== \"file\" || !part.fileId || files.has(part.fileId)) continue;\n files.set(part.fileId, { name: part.name, mimeType: part.mimeType });\n }\n }\n return files;\n}\n\n/**\n * The file ids a provider error blames, among the ones `body` sent.\n *\n * Empty when the error is not a 400/404 from the API, or names nothing in this\n * request — which is the signal not to retry.\n */\nexport function rejectedFileIds(\n body: ResponsesRequest,\n error: unknown,\n files: Map<string, SentFile> = new Map(),\n): string[] {\n if (!(error instanceof ProviderHttpError)) return [];\n if (error.status !== 400 && error.status !== 404) return [];\n const detail = errorDetail(error.body);\n if (!detail) return [];\n\n const blocks = fileBlocks(body.input);\n if (blocks.length === 0) return [];\n\n // 1. The block, by its path. The most precise answer there is.\n const path = /^input\\[(\\d+)\\]\\.content\\[(\\d+)\\]\\.file_id$/.exec(detail.param ?? \"\");\n if (path) {\n const item = body.input[Number(path[1])];\n const block = contentOf(item)[Number(path[2])];\n const id = block && typeof block.file_id === \"string\" ? block.file_id : undefined;\n if (id) return [id];\n }\n\n // 2. The ids, by name. Matched against what was sent, so a message that\n // mentions an id this request never held cannot blame one that it did.\n const message = detail.message ?? \"\";\n const named = unique(blocks.map((block) => block.fileId).filter((id) => mentions(message, id)));\n if (named.length > 0) return named;\n\n // 3. The wrong block for the file's type. No id and no path, so it has to be\n // worked out, and it is only worth doing when the answer is unambiguous.\n const wrongType =\n /Expected (image type|context stuffing file type) to be a supported format:.*but got \\.([a-z0-9]+)\\.?\\s*$/is.exec(\n message,\n );\n if (wrongType) {\n const blockType = wrongType[1]!.toLowerCase() === \"image type\" ? \"input_image\" : \"input_file\";\n const extension = wrongType[2]!.toLowerCase();\n const candidates = unique(\n blocks.filter((block) => block.type === blockType).map((block) => block.fileId),\n );\n const byName = candidates.filter((id) =>\n (files.get(id)?.name ?? \"\").trim().toLowerCase().endsWith(`.${extension}`),\n );\n if (byName.length === 1) return byName;\n if (byName.length === 0 && candidates.length === 1) return candidates;\n }\n\n return [];\n}\n\n/**\n * `body` with every block holding one of `fileIds` replaced by a note.\n *\n * A copy: the caller's body is what was sent, and the next attempt is a\n * different request.\n */\nexport function withoutFiles(\n body: ResponsesRequest,\n fileIds: Set<string>,\n files: Map<string, SentFile> = new Map(),\n): ResponsesRequest {\n return {\n ...body,\n input: body.input.map((item) => {\n const content = contentOf(item);\n if (!content.some((block) => isRejected(block, fileIds))) return item;\n return {\n ...item,\n content: content.map((block) =>\n isRejected(block, fileIds)\n ? { type: \"input_text\", text: unreadableNote(files.get(String(block.file_id))?.name) }\n : block,\n ),\n };\n }),\n };\n}\n\n/**\n * What the model reads where the file would have been.\n *\n * It says the file was not read, so the model does not describe a document it\n * never saw, and it says the provider refused it, so \"please re-upload it\" is\n * the obvious next step rather than something the model has to guess at. The\n * name is JSON-quoted for the reason `attachmentLine` gives: it is the user's,\n * and can hold anything.\n */\nexport function unreadableNote(name: string | undefined): string {\n const label = name ? `attachment ${JSON.stringify(name)}` : \"an attachment\";\n return `[${label} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`;\n}\n\nfunction isRejected(block: Record<string, unknown>, fileIds: Set<string>): boolean {\n return typeof block.file_id === \"string\" && fileIds.has(block.file_id);\n}\n\nfunction contentOf(item: ResponsesInputItem | undefined): Record<string, unknown>[] {\n const content = item?.content;\n return Array.isArray(content) ? (content as Record<string, unknown>[]) : [];\n}\n\nfunction fileBlocks(input: ResponsesInputItem[]): { type: string; fileId: string }[] {\n const out: { type: string; fileId: string }[] = [];\n for (const item of input) {\n for (const block of contentOf(item)) {\n if (typeof block.file_id === \"string\" && block.file_id) {\n out.push({ type: String(block.type), fileId: block.file_id });\n }\n }\n }\n return out;\n}\n\nfunction errorDetail(body: unknown): { message?: string; param?: string } | null {\n if (!body || typeof body !== \"object\") return null;\n const wrapper = body as { error?: unknown };\n const inner = (wrapper.error && typeof wrapper.error === \"object\" ? wrapper.error : body) as {\n message?: unknown;\n param?: unknown;\n };\n return {\n message: typeof inner.message === \"string\" ? inner.message : undefined,\n param: typeof inner.param === \"string\" ? inner.param : undefined,\n };\n}\n\n/** `id` as a whole token in `message`, so `file-ab` is not blamed for `file-abc`. */\nfunction mentions(message: string, id: string): boolean {\n const escaped = id.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(^|[^A-Za-z0-9_-])${escaped}($|[^A-Za-z0-9_-])`).test(message);\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)];\n}\n",
20
- "import type { ProviderEvent } from \"../AgentProvider\";\nimport type { Usage } from \"../types\";\n\n/**\n * The Responses SSE stream to `ProviderEvent`.\n *\n * Also a pure function over chunks, for the same reason the request builder is:\n * everything that breaks here breaks on a byte boundary or a malformed frame,\n * and neither needs a network to reproduce. The tests drive it with recorded\n * fixture strings, including one fed a byte at a time.\n */\n\nexport type SSEMessage = { event: string; data: string; id?: string };\n\n/**\n * Chunks to SSE messages.\n *\n * Written out rather than reached for as a one-liner because every shortcut\n * here is a bug that only shows up under load. A frame split across two chunks\n * is the normal case, not the edge case — TCP has no idea what an event is.\n * Multi-line `data:` is spec, comment lines beginning with `:` are what\n * keepalives look like, and a `\\r\\n` stream is what you get through some\n * proxies.\n */\nexport async function* sseMessages(\n chunks: AsyncIterable<string> | Iterable<string>,\n): AsyncGenerator<SSEMessage> {\n let buffer = \"\";\n let event = \"\";\n let data: string[] = [];\n let id: string | undefined;\n\n const dispatch = (): SSEMessage | null => {\n if (data.length === 0 && !event) return null;\n const message: SSEMessage = { event, data: data.join(\"\\n\"), id };\n event = \"\";\n data = [];\n id = undefined;\n // A frame with a name but no data is legal and carries nothing we want.\n return message.data ? message : null;\n };\n\n const handleLine = (rawLine: string): SSEMessage | null => {\n // Trailing CR from a `\\r\\n` stream. Stripping it here rather than\n // normalizing the whole buffer keeps a CR that lands on a chunk boundary\n // from being counted as a line ending of its own.\n const line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n if (line === \"\") return dispatch();\n // Keepalive. Servers send these so idle connections survive proxies, and a\n // parser that treats one as data corrupts the next real frame.\n if (line.startsWith(\":\")) return null;\n\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n\n if (field === \"event\") event = value;\n else if (field === \"data\") data.push(value);\n else if (field === \"id\") id = value;\n return null;\n };\n\n for await (const chunk of chunks as AsyncIterable<string>) {\n buffer += chunk;\n let newline = buffer.indexOf(\"\\n\");\n while (newline !== -1) {\n const line = buffer.slice(0, newline);\n buffer = buffer.slice(newline + 1);\n const message = handleLine(line);\n if (message) yield message;\n newline = buffer.indexOf(\"\\n\");\n }\n }\n\n // A stream that ends without its final blank line still has one frame in it.\n if (buffer.length > 0) {\n const message = handleLine(buffer);\n if (message) yield message;\n }\n const last = dispatch();\n if (last) yield last;\n}\n\ntype ParseOptions = {\n /**\n * Set when the agent declared an `output` schema. The same\n * `response.output_text.delta` carries prose in one case and the JSON of the\n * final answer in the other, and only the caller knows which it asked for.\n */\n structuredOutput?: boolean;\n};\n\ntype PendingCall = { callId: string; name: string; namespace?: string; done: boolean };\n\nexport async function* parseResponsesStream(\n chunks: AsyncIterable<string> | Iterable<string>,\n options: ParseOptions = {},\n): AsyncGenerator<ProviderEvent> {\n // Keyed by `item_id`, because the argument deltas name the item and not the\n // call, and the call id is what the rest of gemi pairs results on.\n const calls = new Map<string, PendingCall>();\n const searchesReported = new Set<string>();\n let finished = false;\n\n for await (const message of sseMessages(chunks)) {\n if (message.data === \"[DONE]\") break;\n\n let payload: Record<string, any>;\n try {\n payload = JSON.parse(message.data);\n } catch {\n // A frame we cannot read is not a reason to abandon a stream that is\n // otherwise fine; the terminal event is what decides how this ended.\n continue;\n }\n\n // The event name is duplicated in the payload's own `type`. Preferring the\n // payload means a gateway that drops the `event:` line still parses, and\n // the two never disagree in practice.\n const type: string = typeof payload.type === \"string\" ? payload.type : message.event;\n\n switch (type) {\n case \"response.output_text.delta\": {\n const delta = String(payload.delta ?? \"\");\n if (!delta) break;\n yield options.structuredOutput\n ? { type: \"output-delta\", delta }\n : { type: \"text-delta\", delta };\n break;\n }\n\n // Two names for the same thing across model generations: the summary\n // stream and, on models that expose it, the reasoning text itself.\n case \"response.reasoning_summary_text.delta\":\n case \"response.reasoning_text.delta\": {\n const delta = String(payload.delta ?? \"\");\n if (!delta) break;\n yield { type: \"reasoning-delta\", delta, id: payload.item_id };\n break;\n }\n\n case \"response.output_item.added\": {\n const item = payload.item as Record<string, any> | undefined;\n if (!item) break;\n if (item.type === \"function_call\") {\n const itemId = String(item.id ?? payload.item_id ?? item.call_id ?? \"\");\n calls.set(itemId, {\n callId: String(item.call_id ?? itemId),\n // FLAT, and pinned by a test against the recorded stream. A call to\n // a function inside a namespace comes back as\n // `{name:\"getOrder\", namespace:\"crm\"}` — not `\"crm.getOrder\"` — so\n // the name is already the registry key `Agent` looks tools up by,\n // and qualifying it here would break every lookup. The namespace is\n // carried alongside rather than folded in, because a name that is\n // sometimes qualified is a name nothing can match on.\n name: String(item.name ?? \"\"),\n namespace: typeof item.namespace === \"string\" && item.namespace\n ? item.namespace\n : undefined,\n done: false,\n });\n }\n break;\n }\n\n case \"response.function_call_arguments.delta\": {\n const call = calls.get(String(payload.item_id ?? \"\"));\n if (!call) break;\n const argsDelta = String(payload.delta ?? \"\");\n if (!argsDelta) break;\n yield {\n type: \"tool-call-delta\",\n toolCallId: call.callId,\n name: call.name,\n argsDelta,\n // Spread rather than `namespace: call.namespace`: a flat tool has no\n // namespace, and an explicit `undefined` is a key a consumer has to\n // remember to check for.\n ...(call.namespace ? { namespace: call.namespace } : {}),\n };\n break;\n }\n\n case \"response.function_call_arguments.done\": {\n const itemId = String(payload.item_id ?? \"\");\n const call = calls.get(itemId);\n if (!call) break;\n call.done = true;\n yield {\n type: \"tool-call\",\n toolCallId: call.callId,\n name: call.name,\n args: String(payload.arguments ?? \"\"),\n ...(call.namespace ? { namespace: call.namespace } : {}),\n };\n break;\n }\n\n case \"response.output_item.done\": {\n const item = payload.item as Record<string, any> | undefined;\n if (!item) break;\n\n if (item.type === \"function_call\") {\n const itemId = String(item.id ?? payload.item_id ?? item.call_id ?? \"\");\n const call = calls.get(itemId);\n // Belt and braces: a call whose arguments never got a `done` event\n // still has to reach the agent, or the loop waits for a step that\n // will not arrive.\n if (call?.done) break;\n const namespace =\n (typeof item.namespace === \"string\" ? item.namespace : \"\") || call?.namespace;\n yield {\n type: \"tool-call\",\n toolCallId: String(item.call_id ?? itemId),\n name: String(item.name ?? call?.name ?? \"\"),\n args: String(item.arguments ?? \"\"),\n ...(namespace ? { namespace } : {}),\n };\n if (call) call.done = true;\n break;\n }\n\n if (item.type === \"tool_search_call\" || item.type === \"tool_search_output\") {\n // The call and its output are one thing to a user — \"went looking,\n // found these\" — so they collapse into one event. Two mechanisms do\n // that, and which one fires depends on what the server sent:\n //\n // 1. THE PAIR IS LINKED. The documented shape puts\n // `tool_search_call_id` on the output item, naming the call item's\n // id, so both sides key the same and the second one is dropped.\n //\n // 2. THE PAIR IS NOT LINKED, which is what the live API actually\n // sends. In `__fixtures__/openai-tool-search.sse` the call is\n // `tsc_08945…`, the output is `tso_08945…`, `call_id` is null on\n // both and neither carries `tool_search_call_id` — so there is\n // nothing to pair them on. What collapses them there is the\n // `found` check below: only the OUTPUT item carries a `tools`\n // array, and the call item carries the query it ran\n // (`arguments.paths`), which is not a result and is not reported\n // as one.\n //\n // That second one used to be load-bearing and unwritten — the dedup\n // key was doing nothing and the length check was doing all the work\n // by accident. Both are tested now: \"the tool_search call and its\n // output collapse into one event\" in `stream.test.ts` covers (1), and\n // \"nothing in the recording links the search call to its output\"\n // plus \"reports one event from the real stream, despite that\" in\n // `recordings.test.ts` cover (2).\n const found = toolSearchReport(item);\n if (found.loaded.length === 0 && found.namespaces.length === 0) break;\n const key = String(item.tool_search_call_id ?? item.id ?? \"\");\n if (searchesReported.has(key)) break;\n searchesReported.add(key);\n yield { type: \"tool-search\", ...found };\n }\n break;\n }\n\n // A refusal is the model declining, and it arrives as its own item rather\n // than as an HTTP status. Reporting it as text would put the refusal in\n // the transcript as if it were an answer.\n case \"response.refusal.done\": {\n yield {\n type: \"error\",\n error: {\n code: \"content_filtered\",\n message: String(payload.refusal ?? \"The model refused to answer.\"),\n retryable: false,\n },\n };\n break;\n }\n\n case \"response.completed\": {\n finished = true;\n yield { type: \"finish\", reason: \"stop\", usage: toUsage(payload.response?.usage) };\n break;\n }\n\n /**\n * Two very different endings share this frame, and the old code called\n * both of them \"stop\".\n *\n * `max_output_tokens` is a truncated answer. `content_filter` is Azure\n * blocking the request — verified against\n * `__fixtures__/azure-content-filtered.sse`, where a prompt that trips\n * the filter answers HTTP 200, streams a polite refusal, and ends\n * `response.incomplete` with `incomplete_details.reason` of\n * `content_filter`. Reporting that as a clean stop tells the agent the\n * model finished talking, which is exactly the mistake `content_filtered`\n * exists to prevent: the run reads as a normal answer, the loop takes\n * another step, and nothing anywhere says the content was blocked.\n *\n * The detail comes off Azure's `content_filters` array rather than off\n * the frame, because `incomplete_details` carries the word\n * `content_filter` and nothing else — no category, no severity.\n */\n case \"response.incomplete\": {\n finished = true;\n const usage = toUsage(payload.response?.usage);\n const reason = payload.response?.incomplete_details?.reason;\n if (reason === \"content_filter\") {\n yield {\n type: \"error\",\n error: {\n code: \"content_filtered\",\n message: describeContentFilters(payload.response?.content_filters),\n retryable: false,\n },\n };\n yield { type: \"finish\", reason: \"error\", usage };\n break;\n }\n yield {\n type: \"finish\",\n reason: reason === \"max_output_tokens\" ? \"length\" : \"stop\",\n usage,\n };\n break;\n }\n\n case \"response.failed\":\n case \"error\": {\n finished = true;\n const raw = payload.response?.error ?? payload.error ?? payload;\n yield { type: \"error\", error: normalizeStreamError(raw) };\n yield { type: \"finish\", reason: \"error\", usage: toUsage(payload.response?.usage) };\n break;\n }\n }\n\n if (finished) return;\n }\n\n // The connection closed with no terminal event: a dropped socket, a proxy\n // timing out, a process going away mid-answer. Reporting it as a clean stop\n // would tell the agent the model finished talking, and it did not — so this\n // is an error, and a retryable one, because the same request usually works.\n if (!finished) {\n yield {\n type: \"error\",\n error: {\n code: \"provider_error\",\n message: \"The provider stream ended without a terminal event.\",\n retryable: true,\n },\n };\n yield { type: \"finish\", reason: \"error\", usage: emptyUsage() };\n }\n}\n\n/**\n * What a tool search actually pulled in.\n *\n * The entries of `tool_search_output.tools` are NAMESPACES, not functions:\n *\n * [{type:\"namespace\", name:\"crm\", tools:[{type:\"function\", name:\"listOrders\"},\n * {type:\"function\", name:\"getOrder\"}]}]\n *\n * — verified against `__fixtures__/openai-tool-search.sse`. Reading `name` off\n * the top level, which is what this did, reported `loaded: [\"crm\"]` for a\n * search that loaded `listOrders` and `getOrder`. The names it reported were\n * not names of tools, and nothing downstream could tell, because a namespace\n * name is a plausible tool name.\n *\n * BOTH HALVES ARE REPORTED. \"Searched crm, loaded getOrder\" is the sentence a\n * UI wants, and neither field can be recovered from the other: flattening to\n * `crm.getOrder` would invent a name the model never used (calls come back with\n * a flat `name` — see the `function_call` branch above), and dropping the\n * namespace throws away the only description of the *group*, which is the thing\n * the model actually chose between.\n *\n * The shape is read structurally rather than off `type === \"namespace\"`: an\n * entry with a `tools` array is a group whatever it calls itself, and the\n * hand-written fixtures that predate the recording use `results:[{name}]` with\n * no `type` at all.\n */\ntype ToolSearchReport = { loaded: string[]; namespaces: string[] };\n\nfunction toolSearchReport(item: Record<string, any>): ToolSearchReport {\n const loaded: string[] = [];\n const namespaces: string[] = [];\n collectToolNames(item.results ?? item.tools ?? item.loaded ?? item.output, loaded, namespaces, 0);\n return { loaded: unique(loaded), namespaces: unique(namespaces) };\n}\n\nfunction collectToolNames(\n raw: unknown,\n loaded: string[],\n namespaces: string[],\n depth: number,\n): void {\n // Nesting is one level deep today and a namespace of namespaces is not a\n // thing. The cap is here so a payload that disagrees costs a truncated event\n // rather than a blown stack in the middle of someone's stream.\n if (!Array.isArray(raw) || depth > 4) return;\n for (const entry of raw) {\n if (typeof entry === \"string\") {\n loaded.push(entry);\n continue;\n }\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Record<string, any>;\n const name =\n typeof e.name === \"string\" ? e.name : typeof e.tool_name === \"string\" ? e.tool_name : \"\";\n const children = e.tools ?? e.functions;\n if (Array.isArray(children)) {\n if (name) namespaces.push(name);\n collectToolNames(children, loaded, namespaces, depth + 1);\n continue;\n }\n if (name) loaded.push(name);\n }\n}\n\nfunction unique(names: string[]): string[] {\n return names.filter((name, index) => names.indexOf(name) === index);\n}\n\n/**\n * Azure's `content_filters`, read only where it means something.\n *\n * IT DOES NOT MAP ONTO `content_filtered` ON ITS OWN, and that is the decision\n * worth writing down: the array is on EVERY Azure response — `azure-text.sse`,\n * a recording of \"say hi\", carries it on `response.created`,\n * `response.in_progress` and `response.completed`, with `blocked:false` and\n * every category `severity:\"safe\"`. Treating its presence as a filter hit would\n * report every single Azure call as content-filtered, and treating any\n * `filtered:true` inside it as one would report a *warning* as a block. What is\n * authoritative about the outcome is `incomplete_details.reason`; this array is\n * authoritative only about the DETAIL, which is why it is read for a message\n * and for nothing else.\n *\n * OpenAI sends no such array. It signals a block by refusing in-band\n * (`response.refusal.done`, handled above) or by rejecting the request, so\n * nothing here needs a provider flag — an absent array just yields the generic\n * sentence.\n */\nfunction describeContentFilters(raw: unknown): string {\n const generic = \"The provider's content filter blocked this request.\";\n if (!Array.isArray(raw)) return generic;\n const hits: string[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Record<string, any>;\n const results = e.content_filter_results;\n if (!results || typeof results !== \"object\") continue;\n for (const [category, detail] of Object.entries(results as Record<string, any>)) {\n if (detail && typeof detail === \"object\" && detail.filtered === true) {\n // The source matters as much as the category: a `prompt` hit means the\n // user's own words were blocked and rewording works, a `completion` hit\n // means the model's answer was, and retrying the same prompt will not.\n hits.push(`${category} (${String(e.source_type ?? \"unknown\")})`);\n }\n }\n }\n return hits.length === 0 ? generic : `${generic} Categories: ${unique(hits).join(\", \")}.`;\n}\n\nfunction normalizeStreamError(raw: any) {\n const message = typeof raw?.message === \"string\" ? raw.message : \"The provider stream failed.\";\n const code = String(raw?.code ?? \"\").toLowerCase();\n if (code === \"rate_limit_exceeded\") {\n return { code: \"rate_limited\" as const, message, retryable: true };\n }\n if (code === \"context_length_exceeded\") {\n return { code: \"context_length_exceeded\" as const, message, retryable: false };\n }\n if (code.includes(\"content_filter\")) {\n return { code: \"content_filtered\" as const, message, retryable: false };\n }\n // Mid-stream failures are overwhelmingly transient — the request was accepted,\n // so it was not malformed.\n return { code: \"provider_error\" as const, message, retryable: true };\n}\n\nexport function emptyUsage(): Usage {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n}\n\nexport function toUsage(raw: any): Usage {\n if (!raw) return emptyUsage();\n const inputTokens = Number(raw.input_tokens ?? 0);\n const outputTokens = Number(raw.output_tokens ?? 0);\n const usage: Usage = {\n inputTokens,\n outputTokens,\n totalTokens: Number(raw.total_tokens ?? inputTokens + outputTokens),\n };\n const reasoning = raw.output_tokens_details?.reasoning_tokens;\n if (typeof reasoning === \"number\") usage.reasoningTokens = reasoning;\n const cached = raw.input_tokens_details?.cached_tokens;\n if (typeof cached === \"number\") usage.cachedInputTokens = cached;\n return usage;\n}\n\n/** A `ReadableStream` of bytes to the string chunks the parser wants. Split out\n * so the parser never has to know it came from a socket. */\nexport async function* decodeChunks(\n body: ReadableStream<Uint8Array> | null,\n): AsyncGenerator<string> {\n if (!body) return;\n const reader = body.getReader();\n const decoder = new TextDecoder();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n // `stream: true` matters: a multi-byte character can land across two\n // reads, and decoding each read on its own turns it into two U+FFFDs.\n if (value) yield decoder.decode(value, { stream: true });\n }\n const tail = decoder.decode();\n if (tail) yield tail;\n } finally {\n reader.releaseLock();\n }\n}\n",
20
+ "import type { ProviderEvent } from \"../AgentProvider\";\nimport type { FinishReason, Usage } from \"../types\";\n\n/**\n * The Responses SSE stream to `ProviderEvent`.\n *\n * Also a pure function over chunks, for the same reason the request builder is:\n * everything that breaks here breaks on a byte boundary or a malformed frame,\n * and neither needs a network to reproduce. The tests drive it with recorded\n * fixture strings, including one fed a byte at a time.\n */\n\nexport type SSEMessage = { event: string; data: string; id?: string };\n\n/**\n * Chunks to SSE messages.\n *\n * Written out rather than reached for as a one-liner because every shortcut\n * here is a bug that only shows up under load. A frame split across two chunks\n * is the normal case, not the edge case — TCP has no idea what an event is.\n * Multi-line `data:` is spec, comment lines beginning with `:` are what\n * keepalives look like, and a `\\r\\n` stream is what you get through some\n * proxies.\n */\nexport async function* sseMessages(\n chunks: AsyncIterable<string> | Iterable<string>,\n): AsyncGenerator<SSEMessage> {\n let buffer = \"\";\n let event = \"\";\n let data: string[] = [];\n let id: string | undefined;\n\n const dispatch = (): SSEMessage | null => {\n if (data.length === 0 && !event) return null;\n const message: SSEMessage = { event, data: data.join(\"\\n\"), id };\n event = \"\";\n data = [];\n id = undefined;\n // A frame with a name but no data is legal and carries nothing we want.\n return message.data ? message : null;\n };\n\n const handleLine = (rawLine: string): SSEMessage | null => {\n // Trailing CR from a `\\r\\n` stream. Stripping it here rather than\n // normalizing the whole buffer keeps a CR that lands on a chunk boundary\n // from being counted as a line ending of its own.\n const line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n if (line === \"\") return dispatch();\n // Keepalive. Servers send these so idle connections survive proxies, and a\n // parser that treats one as data corrupts the next real frame.\n if (line.startsWith(\":\")) return null;\n\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n\n if (field === \"event\") event = value;\n else if (field === \"data\") data.push(value);\n else if (field === \"id\") id = value;\n return null;\n };\n\n for await (const chunk of chunks as AsyncIterable<string>) {\n buffer += chunk;\n let newline = buffer.indexOf(\"\\n\");\n while (newline !== -1) {\n const line = buffer.slice(0, newline);\n buffer = buffer.slice(newline + 1);\n const message = handleLine(line);\n if (message) yield message;\n newline = buffer.indexOf(\"\\n\");\n }\n }\n\n // A stream that ends without its final blank line still has one frame in it.\n if (buffer.length > 0) {\n const message = handleLine(buffer);\n if (message) yield message;\n }\n const last = dispatch();\n if (last) yield last;\n}\n\ntype ParseOptions = {\n /**\n * Set when the agent declared an `output` schema. The same\n * `response.output_text.delta` carries prose in one case and the JSON of the\n * final answer in the other, and only the caller knows which it asked for.\n */\n structuredOutput?: boolean;\n};\n\ntype PendingCall = { callId: string; name: string; namespace?: string; done: boolean };\n\nexport async function* parseResponsesStream(\n chunks: AsyncIterable<string> | Iterable<string>,\n options: ParseOptions = {},\n): AsyncGenerator<ProviderEvent> {\n // Keyed by `item_id`, because the argument deltas name the item and not the\n // call, and the call id is what the rest of gemi pairs results on.\n const calls = new Map<string, PendingCall>();\n const searchesReported = new Set<string>();\n let finished = false;\n // What the vendor says answered (#741): `response.model` on the lifecycle\n // frames. Kept from every frame that has it, so a stream that dies after\n // `response.created` still says who it was talking to.\n let responseModel: string | undefined;\n const ended = (reason: FinishReason, usage: Usage): ProviderEvent => ({\n type: \"finish\",\n reason,\n usage,\n ...(responseModel ? { model: responseModel } : {}),\n });\n\n for await (const message of sseMessages(chunks)) {\n if (message.data === \"[DONE]\") break;\n\n let payload: Record<string, any>;\n try {\n payload = JSON.parse(message.data);\n } catch {\n // A frame we cannot read is not a reason to abandon a stream that is\n // otherwise fine; the terminal event is what decides how this ended.\n continue;\n }\n\n // The event name is duplicated in the payload's own `type`. Preferring the\n // payload means a gateway that drops the `event:` line still parses, and\n // the two never disagree in practice.\n const type: string = typeof payload.type === \"string\" ? payload.type : message.event;\n\n const model = payload.response?.model;\n if (typeof model === \"string\" && model) responseModel = model;\n\n switch (type) {\n case \"response.output_text.delta\": {\n const delta = String(payload.delta ?? \"\");\n if (!delta) break;\n yield options.structuredOutput\n ? { type: \"output-delta\", delta }\n : { type: \"text-delta\", delta };\n break;\n }\n\n // Two names for the same thing across model generations: the summary\n // stream and, on models that expose it, the reasoning text itself.\n case \"response.reasoning_summary_text.delta\":\n case \"response.reasoning_text.delta\": {\n const delta = String(payload.delta ?? \"\");\n if (!delta) break;\n yield { type: \"reasoning-delta\", delta, id: payload.item_id };\n break;\n }\n\n case \"response.output_item.added\": {\n const item = payload.item as Record<string, any> | undefined;\n if (!item) break;\n if (item.type === \"function_call\") {\n const itemId = String(item.id ?? payload.item_id ?? item.call_id ?? \"\");\n calls.set(itemId, {\n callId: String(item.call_id ?? itemId),\n // FLAT, and pinned by a test against the recorded stream. A call to\n // a function inside a namespace comes back as\n // `{name:\"getOrder\", namespace:\"crm\"}` — not `\"crm.getOrder\"` — so\n // the name is already the registry key `Agent` looks tools up by,\n // and qualifying it here would break every lookup. The namespace is\n // carried alongside rather than folded in, because a name that is\n // sometimes qualified is a name nothing can match on.\n name: String(item.name ?? \"\"),\n namespace: typeof item.namespace === \"string\" && item.namespace\n ? item.namespace\n : undefined,\n done: false,\n });\n }\n break;\n }\n\n case \"response.function_call_arguments.delta\": {\n const call = calls.get(String(payload.item_id ?? \"\"));\n if (!call) break;\n const argsDelta = String(payload.delta ?? \"\");\n if (!argsDelta) break;\n yield {\n type: \"tool-call-delta\",\n toolCallId: call.callId,\n name: call.name,\n argsDelta,\n // Spread rather than `namespace: call.namespace`: a flat tool has no\n // namespace, and an explicit `undefined` is a key a consumer has to\n // remember to check for.\n ...(call.namespace ? { namespace: call.namespace } : {}),\n };\n break;\n }\n\n case \"response.function_call_arguments.done\": {\n const itemId = String(payload.item_id ?? \"\");\n const call = calls.get(itemId);\n if (!call) break;\n call.done = true;\n yield {\n type: \"tool-call\",\n toolCallId: call.callId,\n name: call.name,\n args: String(payload.arguments ?? \"\"),\n ...(call.namespace ? { namespace: call.namespace } : {}),\n };\n break;\n }\n\n case \"response.output_item.done\": {\n const item = payload.item as Record<string, any> | undefined;\n if (!item) break;\n\n if (item.type === \"function_call\") {\n const itemId = String(item.id ?? payload.item_id ?? item.call_id ?? \"\");\n const call = calls.get(itemId);\n // Belt and braces: a call whose arguments never got a `done` event\n // still has to reach the agent, or the loop waits for a step that\n // will not arrive.\n if (call?.done) break;\n const namespace =\n (typeof item.namespace === \"string\" ? item.namespace : \"\") || call?.namespace;\n yield {\n type: \"tool-call\",\n toolCallId: String(item.call_id ?? itemId),\n name: String(item.name ?? call?.name ?? \"\"),\n args: String(item.arguments ?? \"\"),\n ...(namespace ? { namespace } : {}),\n };\n if (call) call.done = true;\n break;\n }\n\n if (item.type === \"tool_search_call\" || item.type === \"tool_search_output\") {\n // The call and its output are one thing to a user — \"went looking,\n // found these\" — so they collapse into one event. Two mechanisms do\n // that, and which one fires depends on what the server sent:\n //\n // 1. THE PAIR IS LINKED. The documented shape puts\n // `tool_search_call_id` on the output item, naming the call item's\n // id, so both sides key the same and the second one is dropped.\n //\n // 2. THE PAIR IS NOT LINKED, which is what the live API actually\n // sends. In `__fixtures__/openai-tool-search.sse` the call is\n // `tsc_08945…`, the output is `tso_08945…`, `call_id` is null on\n // both and neither carries `tool_search_call_id` — so there is\n // nothing to pair them on. What collapses them there is the\n // `found` check below: only the OUTPUT item carries a `tools`\n // array, and the call item carries the query it ran\n // (`arguments.paths`), which is not a result and is not reported\n // as one.\n //\n // That second one used to be load-bearing and unwritten — the dedup\n // key was doing nothing and the length check was doing all the work\n // by accident. Both are tested now: \"the tool_search call and its\n // output collapse into one event\" in `stream.test.ts` covers (1), and\n // \"nothing in the recording links the search call to its output\"\n // plus \"reports one event from the real stream, despite that\" in\n // `recordings.test.ts` cover (2).\n const found = toolSearchReport(item);\n if (found.loaded.length === 0 && found.namespaces.length === 0) break;\n const key = String(item.tool_search_call_id ?? item.id ?? \"\");\n if (searchesReported.has(key)) break;\n searchesReported.add(key);\n yield { type: \"tool-search\", ...found };\n }\n break;\n }\n\n // A refusal is the model declining, and it arrives as its own item rather\n // than as an HTTP status. Reporting it as text would put the refusal in\n // the transcript as if it were an answer.\n case \"response.refusal.done\": {\n yield {\n type: \"error\",\n error: {\n code: \"content_filtered\",\n message: String(payload.refusal ?? \"The model refused to answer.\"),\n retryable: false,\n },\n };\n break;\n }\n\n case \"response.completed\": {\n finished = true;\n yield ended(\"stop\", toUsage(payload.response?.usage));\n break;\n }\n\n /**\n * Two very different endings share this frame, and the old code called\n * both of them \"stop\".\n *\n * `max_output_tokens` is a truncated answer. `content_filter` is Azure\n * blocking the request — verified against\n * `__fixtures__/azure-content-filtered.sse`, where a prompt that trips\n * the filter answers HTTP 200, streams a polite refusal, and ends\n * `response.incomplete` with `incomplete_details.reason` of\n * `content_filter`. Reporting that as a clean stop tells the agent the\n * model finished talking, which is exactly the mistake `content_filtered`\n * exists to prevent: the run reads as a normal answer, the loop takes\n * another step, and nothing anywhere says the content was blocked.\n *\n * The detail comes off Azure's `content_filters` array rather than off\n * the frame, because `incomplete_details` carries the word\n * `content_filter` and nothing else — no category, no severity.\n */\n case \"response.incomplete\": {\n finished = true;\n const usage = toUsage(payload.response?.usage);\n const reason = payload.response?.incomplete_details?.reason;\n if (reason === \"content_filter\") {\n yield {\n type: \"error\",\n error: {\n code: \"content_filtered\",\n message: describeContentFilters(payload.response?.content_filters),\n retryable: false,\n },\n };\n yield ended(\"error\", usage);\n break;\n }\n yield ended(reason === \"max_output_tokens\" ? \"length\" : \"stop\", usage);\n break;\n }\n\n case \"response.failed\":\n case \"error\": {\n finished = true;\n const raw = payload.response?.error ?? payload.error ?? payload;\n yield { type: \"error\", error: normalizeStreamError(raw) };\n yield ended(\"error\", toUsage(payload.response?.usage));\n break;\n }\n }\n\n if (finished) return;\n }\n\n // The connection closed with no terminal event: a dropped socket, a proxy\n // timing out, a process going away mid-answer. Reporting it as a clean stop\n // would tell the agent the model finished talking, and it did not — so this\n // is an error, and a retryable one, because the same request usually works.\n if (!finished) {\n yield {\n type: \"error\",\n error: {\n code: \"provider_error\",\n message: \"The provider stream ended without a terminal event.\",\n retryable: true,\n },\n };\n yield ended(\"error\", emptyUsage());\n }\n}\n\n/**\n * What a tool search actually pulled in.\n *\n * The entries of `tool_search_output.tools` are NAMESPACES, not functions:\n *\n * [{type:\"namespace\", name:\"crm\", tools:[{type:\"function\", name:\"listOrders\"},\n * {type:\"function\", name:\"getOrder\"}]}]\n *\n * — verified against `__fixtures__/openai-tool-search.sse`. Reading `name` off\n * the top level, which is what this did, reported `loaded: [\"crm\"]` for a\n * search that loaded `listOrders` and `getOrder`. The names it reported were\n * not names of tools, and nothing downstream could tell, because a namespace\n * name is a plausible tool name.\n *\n * BOTH HALVES ARE REPORTED. \"Searched crm, loaded getOrder\" is the sentence a\n * UI wants, and neither field can be recovered from the other: flattening to\n * `crm.getOrder` would invent a name the model never used (calls come back with\n * a flat `name` — see the `function_call` branch above), and dropping the\n * namespace throws away the only description of the *group*, which is the thing\n * the model actually chose between.\n *\n * The shape is read structurally rather than off `type === \"namespace\"`: an\n * entry with a `tools` array is a group whatever it calls itself, and the\n * hand-written fixtures that predate the recording use `results:[{name}]` with\n * no `type` at all.\n */\ntype ToolSearchReport = { loaded: string[]; namespaces: string[] };\n\nfunction toolSearchReport(item: Record<string, any>): ToolSearchReport {\n const loaded: string[] = [];\n const namespaces: string[] = [];\n collectToolNames(item.results ?? item.tools ?? item.loaded ?? item.output, loaded, namespaces, 0);\n return { loaded: unique(loaded), namespaces: unique(namespaces) };\n}\n\nfunction collectToolNames(\n raw: unknown,\n loaded: string[],\n namespaces: string[],\n depth: number,\n): void {\n // Nesting is one level deep today and a namespace of namespaces is not a\n // thing. The cap is here so a payload that disagrees costs a truncated event\n // rather than a blown stack in the middle of someone's stream.\n if (!Array.isArray(raw) || depth > 4) return;\n for (const entry of raw) {\n if (typeof entry === \"string\") {\n loaded.push(entry);\n continue;\n }\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Record<string, any>;\n const name =\n typeof e.name === \"string\" ? e.name : typeof e.tool_name === \"string\" ? e.tool_name : \"\";\n const children = e.tools ?? e.functions;\n if (Array.isArray(children)) {\n if (name) namespaces.push(name);\n collectToolNames(children, loaded, namespaces, depth + 1);\n continue;\n }\n if (name) loaded.push(name);\n }\n}\n\nfunction unique(names: string[]): string[] {\n return names.filter((name, index) => names.indexOf(name) === index);\n}\n\n/**\n * Azure's `content_filters`, read only where it means something.\n *\n * IT DOES NOT MAP ONTO `content_filtered` ON ITS OWN, and that is the decision\n * worth writing down: the array is on EVERY Azure response — `azure-text.sse`,\n * a recording of \"say hi\", carries it on `response.created`,\n * `response.in_progress` and `response.completed`, with `blocked:false` and\n * every category `severity:\"safe\"`. Treating its presence as a filter hit would\n * report every single Azure call as content-filtered, and treating any\n * `filtered:true` inside it as one would report a *warning* as a block. What is\n * authoritative about the outcome is `incomplete_details.reason`; this array is\n * authoritative only about the DETAIL, which is why it is read for a message\n * and for nothing else.\n *\n * OpenAI sends no such array. It signals a block by refusing in-band\n * (`response.refusal.done`, handled above) or by rejecting the request, so\n * nothing here needs a provider flag — an absent array just yields the generic\n * sentence.\n */\nfunction describeContentFilters(raw: unknown): string {\n const generic = \"The provider's content filter blocked this request.\";\n if (!Array.isArray(raw)) return generic;\n const hits: string[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Record<string, any>;\n const results = e.content_filter_results;\n if (!results || typeof results !== \"object\") continue;\n for (const [category, detail] of Object.entries(results as Record<string, any>)) {\n if (detail && typeof detail === \"object\" && detail.filtered === true) {\n // The source matters as much as the category: a `prompt` hit means the\n // user's own words were blocked and rewording works, a `completion` hit\n // means the model's answer was, and retrying the same prompt will not.\n hits.push(`${category} (${String(e.source_type ?? \"unknown\")})`);\n }\n }\n }\n return hits.length === 0 ? generic : `${generic} Categories: ${unique(hits).join(\", \")}.`;\n}\n\nfunction normalizeStreamError(raw: any) {\n const message = typeof raw?.message === \"string\" ? raw.message : \"The provider stream failed.\";\n const code = String(raw?.code ?? \"\").toLowerCase();\n if (code === \"rate_limit_exceeded\") {\n return { code: \"rate_limited\" as const, message, retryable: true };\n }\n if (code === \"context_length_exceeded\") {\n return { code: \"context_length_exceeded\" as const, message, retryable: false };\n }\n if (code.includes(\"content_filter\")) {\n return { code: \"content_filtered\" as const, message, retryable: false };\n }\n // Mid-stream failures are overwhelmingly transient — the request was accepted,\n // so it was not malformed.\n return { code: \"provider_error\" as const, message, retryable: true };\n}\n\nexport function emptyUsage(): Usage {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n}\n\nexport function toUsage(raw: any): Usage {\n if (!raw) return emptyUsage();\n const inputTokens = Number(raw.input_tokens ?? 0);\n const outputTokens = Number(raw.output_tokens ?? 0);\n const usage: Usage = {\n inputTokens,\n outputTokens,\n totalTokens: Number(raw.total_tokens ?? inputTokens + outputTokens),\n };\n const reasoning = raw.output_tokens_details?.reasoning_tokens;\n if (typeof reasoning === \"number\") usage.reasoningTokens = reasoning;\n const cached = raw.input_tokens_details?.cached_tokens;\n if (typeof cached === \"number\") usage.cachedInputTokens = cached;\n return usage;\n}\n\n/** A `ReadableStream` of bytes to the string chunks the parser wants. Split out\n * so the parser never has to know it came from a socket. */\nexport async function* decodeChunks(\n body: ReadableStream<Uint8Array> | null,\n): AsyncGenerator<string> {\n if (!body) return;\n const reader = body.getReader();\n const decoder = new TextDecoder();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n // `stream: true` matters: a multi-byte character can land across two\n // reads, and decoding each read on its own turns it into two U+FFFDs.\n if (value) yield decoder.decode(value, { stream: true });\n }\n const tail = decoder.decode();\n if (tail) yield tail;\n } finally {\n reader.releaseLock();\n }\n}\n",
21
21
  "import type { ProviderEvent } from \"../AgentProvider\";\nimport type { ProviderTarget } from \"./endpoints\";\nimport { httpErrorDetail, normalizeProviderError } from \"./errors\";\nimport {\n MAX_FILE_REJECTION_RETRIES,\n rejectedFileIds,\n withoutFiles,\n type SentFile,\n} from \"./fileRejection\";\nimport { requestWithRetry, type FetchLike } from \"./http\";\nimport type { ResponsesRequest } from \"./request\";\nimport { decodeChunks, emptyUsage, parseResponsesStream } from \"./stream\";\n\n/**\n * The parts of a call that differ between OpenAI and Azure, and nothing else.\n *\n * Two classes, one request path: the differences are a URL, a header and when\n * the credential is read, so those are what gets passed in. Everything below\n * this line — retries, decoding, event translation, what an error looks like —\n * is identical, and duplicating it into the Azure class is how the two would\n * start behaving differently by accident.\n */\nexport type ResponsesEndpoint = {\n responsesUrl: string;\n filesUrl: string;\n /** Async because Entra tokens expire mid-conversation, so the credential has\n * to be read per request rather than per provider. */\n headers: () => Promise<Record<string, string>>;\n timeoutMs: number;\n maxRetries: number;\n fetchImpl?: FetchLike;\n};\n\n/**\n * The Responses paths for a resolved vendor.\n *\n * The two URLs are all that distinguishes this from any other call to the same\n * host, which is why the host, the credential and the api-version are worked out\n * by `providers/endpoints.ts` and appended to here rather than resolved twice.\n * Files are resource-scoped rather than deployment-scoped on Azure — an upload\n * is not addressed to a model — and the deployment goes in the body's `model`,\n * which `buildResponsesRequest` already does.\n */\nexport function responsesEndpoint(target: ProviderTarget): ResponsesEndpoint {\n return {\n responsesUrl: `${target.base}/responses${target.query}`,\n filesUrl: `${target.base}/files${target.query}`,\n headers: target.headers,\n timeoutMs: target.timeoutMs,\n maxRetries: target.maxRetries,\n };\n}\n\n/**\n * Errors reach the consumer as events, not exceptions.\n *\n * A `ProviderStream` that threw would make every caller wrap its `for await`,\n * and would lose the deltas already yielded — the agent needs the text it got\n * before the socket died, because the user has already read it.\n */\nexport async function* streamResponses(\n endpoint: ResponsesEndpoint,\n body: ResponsesRequest,\n params: {\n signal?: AbortSignal;\n structuredOutput: boolean;\n /** The file ids `body` sends, with their names — for the note that\n * replaces a file the provider refuses. See `providers/fileRejection.ts`. */\n files?: Map<string, SentFile>;\n },\n): AsyncGenerator<ProviderEvent> {\n let response: Response | undefined;\n let request = body;\n const rejected = new Set<string>();\n for (let attempt = 0; response === undefined; attempt++) {\n try {\n response = await requestWithRetry(\n endpoint.responsesUrl,\n {\n method: \"POST\",\n headers: { ...(await endpoint.headers()), \"content-type\": \"application/json\" },\n body: JSON.stringify(request),\n },\n {\n maxRetries: endpoint.maxRetries,\n timeoutMs: endpoint.timeoutMs,\n signal: params.signal,\n fetchImpl: endpoint.fetchImpl,\n },\n );\n } catch (error) {\n // A stored file the provider will not read fails this request and, left\n // in, every later one in the thread (#684). Take it out and ask again,\n // as long as the error blames a file this attempt still sent.\n const blamed =\n attempt < MAX_FILE_REJECTION_RETRIES\n ? rejectedFileIds(request, error, params.files).filter((id) => !rejected.has(id))\n : [];\n if (blamed.length > 0) {\n const reason = normalizeProviderError(error).message;\n for (const fileId of blamed) {\n rejected.add(fileId);\n yield { type: \"file-rejected\", fileId, message: reason, ...httpErrorDetail(error) };\n }\n request = withoutFiles(request, new Set(blamed), params.files);\n continue;\n }\n const normalized = normalizeProviderError(error);\n // An abort is not a failure to report: the run was stopped on purpose, and\n // `Agent` is already writing the ending. Saying so twice would put an error\n // in a transcript the user closed themselves.\n if (normalized.code !== \"aborted\") {\n yield { type: \"error\", error: normalized, ...httpErrorDetail(error) };\n }\n yield {\n type: \"finish\",\n reason: normalized.code === \"aborted\" ? \"aborted\" : \"error\",\n usage: emptyUsage(),\n };\n return;\n }\n }\n\n try {\n yield* parseResponsesStream(decodeChunks(response.body), {\n structuredOutput: params.structuredOutput,\n });\n } catch (error) {\n const normalized = normalizeProviderError(error);\n if (normalized.code === \"aborted\") {\n yield { type: \"finish\", reason: \"aborted\", usage: emptyUsage() };\n return;\n }\n yield { type: \"error\", error: normalized };\n yield { type: \"finish\", reason: \"error\", usage: emptyUsage() };\n }\n}\n\n/**\n * What a file is uploaded *for*, which decides where its id is accepted.\n *\n * The two providers disagree, and each refuses the other's answer.\n *\n * OpenAI: `user_data`. This is a file a person attached to a message, not a\n * corpus for a retrieval store, and the purpose is what decides which of the\n * two the file can be used for.\n *\n * Azure: `assistants`. MEASURED (gpt-6-sol deployment, `/openai/v1`,\n * `api-version=preview`, 2026-10-01, #682): Azure accepts a `user_data` upload\n * and answers a `file-…` id, and then its Responses API refuses that id in both\n * `input_file` and `input_image` with `400 Invalid\n * 'input[0].content[0].file_id': 'file-…'. Expected an ID that begins with\n * 'assistant'.` The same files uploaded as `assistants` come back as\n * `assistant-…` ids (`expires_at: null`) and work: pdf, txt, md and csv as\n * `input_file`, png as `input_image` with real vision.\n */\nexport type UploadPurpose = \"user_data\" | \"assistants\";\n\n/**\n * Uploads an attachment and returns the id a `FilePart` carries.\n *\n * The purpose is the caller's because it is a property of the provider, not of\n * the file — see `UploadPurpose`.\n */\nexport async function uploadFile(\n endpoint: ResponsesEndpoint,\n file: File,\n purpose: UploadPurpose = \"user_data\",\n): Promise<string> {\n const form = new FormData();\n form.set(\"purpose\", purpose);\n form.set(\"file\", file);\n\n const response = await requestWithRetry(\n endpoint.filesUrl,\n {\n method: \"POST\",\n // No content-type: the boundary is generated with the body, and setting\n // the header by hand is how multipart uploads fail with a parser error\n // that names nothing useful.\n headers: await endpoint.headers(),\n body: form,\n },\n {\n maxRetries: endpoint.maxRetries,\n timeoutMs: endpoint.timeoutMs,\n fetchImpl: endpoint.fetchImpl,\n },\n );\n\n const json = (await response.json()) as { id?: string };\n if (!json?.id) throw new Error(\"The provider accepted the upload but returned no file id.\");\n return json.id;\n}\n",
22
22
  "import type { ProviderCapabilities } from \"../AgentProvider\";\n\n/**\n * What a model can do, read off its id.\n *\n * Hardcoding `true` was never an option — `reasoning: { effort }` is a 400 on\n * gpt-4o, and `defer_loading` is a 400 on anything that predates tool search —\n * but neither is a table lookup that only answers for ids we shipped knowing\n * about.\n *\n * SO AN UNKNOWN ID GETS EVERY CAPABILITY. That is the whole point: a model\n * released next Tuesday must be usable by writing its name, not by waiting for\n * a gemi release. The default is chosen for how it fails, not for how often it\n * is right. Guessing high fails loudly and once — the API rejects the request\n * and names the parameter it disliked, and the fix is one line of config.\n * Guessing low fails silently and forever: reasoning is dropped, every deferred\n * schema is inlined, and the only symptom is a bigger bill and a worse answer.\n * Unknown ids also skew new rather than old, because nobody invents the name of\n * a model that already shipped.\n *\n * The named families below exist to make the *known-old* cases right, which is\n * the only place a guess can be wrong in the quiet direction.\n *\n * Note what an answer of `false` does and does not buy. `reasoning: false` and\n * `toolSearch: false` change the request, because both are optimizations and\n * the run is identical without them. `structuredOutput: false` does not: it is\n * reported honestly for a caller that wants to branch on it, but the request\n * builder still sends the schema, because an agent that declared an `output`\n * has an app waiting on a typed result and dropping the parameter would answer\n * prose forever with nothing to branch on. See `request.ts`.\n *\n * `fileInput` IS DELIBERATELY STILL ONE FLAG, and this was reopened rather than\n * inherited. Splitting it into \"reads images\" and \"reads documents\" was the\n * obvious answer to #488, so it was measured before it was written: gpt-5.4 and\n * gpt-4o were each sent an uploaded PNG as `input_image` and an uploaded PDF as\n * `input_file`, and all four calls returned 200 with the right answer (the\n * transcript is in `request.ts`, above `IMAGE_EXTENSIONS`). The two abilities\n * did not come apart on either model, so there is nothing here for a second\n * flag to describe.\n *\n * Adding it anyway would be worse than none. Every guess in this file is a\n * guess about an id nobody has run yet, and the guess is high on purpose; a\n * second flag does not describe the world more finely, it doubles the number of\n * ways that guess can be wrong quietly, and the wrong-quiet direction is the\n * one with no error message. The split earns its place the day a model answers\n * 200 to one of those two calls and 400 to the other — and that call is cheap\n * to repeat, which is why the recipe is written down rather than the conclusion\n * alone.\n */\nexport function capabilitiesForModel(model: string): ProviderCapabilities {\n const id = normalizeModelId(model);\n\n // Everything before the tool-era models. Listed by prefix because these names\n // are closed sets now — nothing new will be called `gpt-3.5-*`.\n if (id.startsWith(\"gpt-3.5\") || id.startsWith(\"text-\") || id.startsWith(\"davinci\")) {\n return {\n reasoning: false,\n structuredOutput: false,\n fileInput: false,\n parallelToolCalls: true,\n toolSearch: false,\n };\n }\n\n const family = parseFamily(id);\n\n // o1 reasons but takes its tool calls one at a time; o3/o4 do not have that\n // restriction. Both predate tool search.\n if (family?.kind === \"o\") {\n return {\n reasoning: true,\n structuredOutput: true,\n fileInput: true,\n parallelToolCalls: family.major > 1,\n toolSearch: supportsToolSearch(family),\n };\n }\n\n if (family?.kind === \"gpt\") {\n return {\n // gpt-4 and gpt-4o are strong models with no reasoning parameter at all.\n reasoning: family.major >= 5,\n // Strict `json_schema` landed with gpt-4o; plain gpt-4 only has json_object.\n structuredOutput: family.major > 4 || id.startsWith(\"gpt-4o\") || id.startsWith(\"gpt-4.1\"),\n fileInput: family.major > 4 || id.startsWith(\"gpt-4o\") || id.startsWith(\"gpt-4.1\"),\n parallelToolCalls: true,\n toolSearch: supportsToolSearch(family),\n };\n }\n\n return {\n reasoning: true,\n structuredOutput: true,\n fileInput: true,\n parallelToolCalls: true,\n toolSearch: true,\n };\n}\n\n/**\n * Tool search, by generation.\n *\n * MEASURED, not read off a changelog. Every id below was sent a request\n * carrying `{type:\"tool_search\"}` plus one `namespace` of deferred functions,\n * against `https://api.openai.com/v1/responses`:\n *\n * accepted (200): gpt-5.6-terra, gpt-5.5, gpt-5.4, gpt-5.4-mini,\n * gpt-5.3-codex, gpt-5.2\n * rejected (400): gpt-5.1, gpt-5, gpt-5-mini, gpt-4.1, gpt-4o, o4-mini, o3\n *\n * with the rejection reading, verbatim,\n * `Tool 'tool_search' is not supported with gpt-5.1.` — recorded as\n * `__fixtures__/openai-error-tool-search-unsupported.json`.\n *\n * So the boundary is the *minor* number, and the whole-major rule this used to\n * carry (`major >= 5`) was wrong in the expensive direction for four shipped\n * models: gpt-5, gpt-5-mini and gpt-5.1 would have had `defer_loading` and a\n * `tool_search` tool put in every request and answered 400 on all of them.\n * Reading the minor is the only way to be right here, because gpt-5 and gpt-5.4\n * differ by a decimal point and by this capability.\n *\n * The o-series keeps its `major >= 5` guard rather than being hardcoded false:\n * o1 through o4 are all measured rejections above, and an o5 that does not\n * exist gets the same benefit-of-the-doubt an unknown id gets, for the reason\n * in the module comment.\n */\nfunction supportsToolSearch(family: Family): boolean {\n if (family.kind === \"o\") return family.major >= 5;\n return family.major > 5 || (family.major === 5 && family.minor >= 2);\n}\n\n/**\n * Azure deployment names are chosen by whoever ran the ARM template, so half of\n * them look nothing like a model id. That is not a special case here: an\n * unrecognizable deployment name lands on the same all-true default as an\n * unrecognized model, for the same reason.\n */\nfunction normalizeModelId(model: string): string {\n return model.trim().toLowerCase();\n}\n\nexport type Family = { kind: \"gpt\" | \"o\"; major: number; minor: number };\n\n/**\n * Reads the generation out of `gpt-5.4-mini-2025-01-01` or `o3-mini`.\n *\n * The minor number is read as well as the major, and it is load-bearing: tool\n * search arrived at gpt-5.2, so `gpt-5` and `gpt-5.4` are two different answers\n * to the same question and a major-only reading gets one of them wrong. An id\n * with no minor — `gpt-5`, `gpt-4o`, `o3` — is minor 0, which is what it is.\n *\n * Exported for its own test: the classification is what the guards below are\n * really about, and it is the only place they are observable — two ids can\n * classify differently and still land on the same capability answer today.\n */\nexport function parseFamily(id: string): Family | null {\n const gpt = /^gpt-(\\d+)(?:\\.(\\d+))?/.exec(id);\n if (gpt?.[1]) return { kind: \"gpt\", major: Number(gpt[1]), minor: Number(gpt[2] ?? 0) };\n // `o1`, `o3-mini`, `o4-mini`. The boundary is what keeps an id whose leading\n // digits are not a generation out of this family — `o200k-base` is a\n // tokenizer, not an o-series model, and `/^o(\\d+)/` alone reads it as\n // generation 200. (`omni-moderation` never gets this far: `m` is not a\n // digit.) Both land on the unknown default today, so the boundary is only\n // visible in the classification — which is where a future rule keyed on\n // `major` would read it.\n const o = /^o(\\d+)(?:[-.]|$)/.exec(id);\n // The o-series never had a minor: `o3-mini` is a size, not a point release.\n if (o?.[1]) return { kind: \"o\", major: Number(o[1]), minor: 0 };\n return null;\n}\n",
23
23
  "import type {\n ProviderCapabilities,\n ProviderStreamParams,\n ProviderToolNamespace,\n ProviderToolSpec,\n} from \"../AgentProvider\";\nimport { ATTACHMENT_ID_PREFIX } from \"../store/Attachments\";\nimport { unreadableNote } from \"./fileRejection\";\nimport type { AgentMessage, FilePart, ToolResultPart } from \"../types\";\n\n/**\n * Building the request body is a pure function, on purpose.\n *\n * Everything hard about this provider is in here — item ordering, tool-call\n * pairing, what a denied call looks like on the wire — and none of it needs a\n * socket to be wrong. So it is separated from the class that posts it, and the\n * tests assert the object rather than mocking `fetch` and reading a string.\n */\n\n// The wire shapes, typed loosely on purpose: these mirror OpenAI's schema, and\n// a precise mirror is a second thing to keep in sync for no checking we would\n// actually get — the API is the authority and it answers in HTTP.\nexport type ResponsesInputItem = Record<string, unknown>;\nexport type ResponsesTool = Record<string, unknown>;\n\nexport type ResponsesRequest = {\n model: string;\n input: ResponsesInputItem[];\n stream: true;\n instructions?: string;\n tools?: ResponsesTool[];\n parallel_tool_calls?: boolean;\n text?: { format: Record<string, unknown> };\n reasoning?: { effort: string; summary?: \"auto\" };\n temperature?: number;\n max_output_tokens?: number;\n};\n\nexport function buildResponsesRequest(\n params: ProviderStreamParams,\n ctx: { model: string; capabilities: ProviderCapabilities },\n): ResponsesRequest {\n const { capabilities } = ctx;\n\n const body: ResponsesRequest = {\n model: ctx.model,\n input: toResponsesInput(params.messages, capabilities),\n stream: true,\n };\n\n if (params.systemPrompt) body.instructions = params.systemPrompt;\n\n const tools = toResponsesTools(params.tools, capabilities);\n if (tools.length > 0) {\n body.tools = tools;\n if (!capabilities.parallelToolCalls) body.parallel_tool_calls = false;\n }\n\n // Deliberately NOT gated on `capabilities.structuredOutput`. An agent that\n // declares `output` has a typed result its app is going to read, and dropping\n // the parameter does not degrade that gracefully — it produces prose, which\n // arrives as `text-delta`, so the app sees no output part, no error and\n // nothing to branch on. That is the silent-forever failure `capabilities.ts`\n // argues against: send it and let the API answer 400, which is loud, happens\n // once, and names the parameter it disliked. `reasoning` is dropped below\n // because it is an optimization; an output schema is the answer's shape.\n if (params.output) {\n body.text = {\n format: {\n type: \"json_schema\",\n name: params.output.name,\n schema: params.output.schema,\n strict: params.output.strict,\n },\n };\n }\n\n // Dropped rather than refused: a model that cannot reason should still answer\n // an agent that asked it to, because `reasoning` is the agent's preference\n // and the provider is where preferences meet reality.\n if (params.reasoning && capabilities.reasoning) {\n // `summary: \"auto\"` is not decoration — without it the stream carries no\n // reasoning text at all, and `ReasoningPart` would have nothing to hold.\n // Except at `\"none\"`, where there is no reasoning to summarize: the effort\n // is sent on its own, so turning reasoning off is not also a request for a\n // summary of it.\n body.reasoning =\n params.reasoning === \"none\"\n ? { effort: \"none\" }\n : { effort: params.reasoning, summary: \"auto\" };\n }\n\n if (typeof params.temperature === \"number\") body.temperature = params.temperature;\n if (typeof params.maxOutputTokens === \"number\") body.max_output_tokens = params.maxOutputTokens;\n\n return body;\n}\n\n// --- messages ------------------------------------------------------------\n\n/**\n * `AgentMessage[]` to Responses input items.\n *\n * Order is preserved *within* a message, not just between messages: a message\n * that holds reasoning, then a tool call, then its result has to arrive in that\n * order, because the API validates the pairing positionally. So text and file\n * parts are buffered into one message item and that buffer is flushed the\n * moment a non-message item appears, rather than emitting all the text first\n * and all the calls after.\n */\nexport function toResponsesInput(\n messages: AgentMessage[],\n capabilities: ProviderCapabilities,\n): ResponsesInputItem[] {\n const items: ResponsesInputItem[] = [];\n\n for (const message of messages) {\n const role = message.role;\n let buffer: Record<string, unknown>[] = [];\n\n const flush = () => {\n if (buffer.length === 0) return;\n items.push({ type: \"message\", role, content: buffer });\n buffer = [];\n };\n\n for (const part of message.content ?? []) {\n switch (part.type) {\n case \"text\": {\n if (!part.text) break;\n buffer.push(textContent(role, part.text));\n break;\n }\n case \"output\": {\n // A structured answer is still the assistant's text as far as the\n // history is concerned; re-serializing it is what lets a follow-up\n // turn refer to what was decided.\n if (part.partial) break;\n buffer.push(textContent(role, JSON.stringify(part.value)));\n break;\n }\n case \"file\": {\n // Neither `input_file` nor `input_image` is legal on an output role.\n // An assistant message holding a file is a bug upstream, and sending\n // it anyway turns that bug into a 400 halfway through a conversation.\n // The attachment line goes with it: `output_text` saying \"here is a\n // file\" on the assistant's side would be the model told it produced\n // something it did not.\n if (role === \"assistant\") break;\n const attachmentId = attachmentIdOf(part);\n // A model that cannot read files still gets the line. The file is\n // gemi's either way, and a tool can take it by id even though the\n // model cannot look at it — dropping the line too would leave the\n // model unaware the user attached anything, which is the storage-only\n // failure this line exists to fix.\n if (!capabilities.fileInput) {\n if (attachmentId) buffer.push(textContent(role, attachmentLine(part, false)));\n break;\n }\n // NOT A PROVIDER FILE ID. There are two ids now — `POST /chat/files`\n // answers `fileId` (the provider's) and `attachmentId` (ours) — and\n // putting the wrong one here is the mistake the shapes invite. Left\n // alone it is an error from the vendor about a file it has never heard\n // of, arriving mid-conversation and naming nothing a reader can act\n // on. (Which error is NOT MEASURED: no request was made with a bogus\n // `file_id` to find out whether it is a 400 or a 404, or whether the\n // part is dropped and the rest of the turn proceeds. The guard does\n // not depend on the answer — it is worth having on the shapes alone —\n // so this comment names the failure rather than a status code nobody\n // checked.)\n if (part.fileId?.startsWith(ATTACHMENT_ID_PREFIX)) {\n throw new Error(\n `FilePart.fileId holds a gemi attachment id (${part.fileId}). That field is the *provider's* file id, from \\`fileId\\` on the upload response; the \\`attachmentId\\` goes in \\`FilePart.attachmentId\\`, is shown to the model as text, and is resolved by a tool through \\`ctx.attachments\\`.`,\n );\n }\n // A storage-only upload has no provider id, and that is a legal part\n // now: the model is told the file exists and is not shown it. What\n // is still refused is a part with NEITHER id — nothing to show and\n // nothing to name. The emptiness check is `!part.fileId` rather than\n // a prefix test because `undefined?.startsWith` is `undefined`, and\n // `file_id: undefined` reaches the vendor as surely as a wrong string.\n if (!part.fileId && !attachmentId) {\n throw new Error(\n \"FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_…`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.\",\n );\n }\n // Refused once already (#684): the id would be refused again, and the\n // request with it. The model is told the file is there and was not\n // read, and is given the attachment id when there is one, since the\n // stored copy is still readable by a tool.\n if (part.providerRejected) {\n if (attachmentId) buffer.push(textContent(role, attachmentLine(part, false)));\n buffer.push(textContent(role, unreadableNote(part.name)));\n break;\n }\n if (attachmentId) buffer.push(textContent(role, attachmentLine(part, !!part.fileId)));\n if (part.fileId) buffer.push(fileContent(part));\n break;\n }\n case \"reasoning\": {\n flush();\n const item = reasoningItem(part);\n if (item) items.push(item);\n break;\n }\n case \"tool-call\": {\n // A partial call is UI state — the arguments were still streaming\n // when this was written down, so what it holds is not what the model\n // asked for. Sending it would create the dangling call the API\n // rejects. If it did acquire a result (a stop landing mid-arguments\n // does exactly that), `reconcileToolPairs` drops that half too.\n if (part.partial) break;\n flush();\n items.push({\n type: \"function_call\",\n call_id: part.toolCallId,\n name: String(part.name),\n arguments: JSON.stringify(part.input ?? {}),\n });\n break;\n }\n case \"tool-result\": {\n flush();\n items.push({\n type: \"function_call_output\",\n call_id: part.toolCallId,\n output: toolResultOutput(part),\n });\n break;\n }\n }\n }\n\n flush();\n }\n\n return reconcileToolPairs(items);\n}\n\n/** What is sent for a call whose result never made it into the history. */\nconst NO_RESULT_RECORDED = \"No result was recorded for this tool call. Assume it did not complete.\";\n\n/**\n * Every `function_call` has exactly one `function_call_output`, and no output\n * stands alone.\n *\n * The loop above skips a `tool-call` marked `partial` — its arguments were\n * still streaming, so it is UI state rather than something the model did — but\n * a partial call can still acquire a result: `stop()` gives every call in\n * flight a `denied`/`stopped` result, and a call whose arguments were mid-flight\n * is exactly the one carrying `partial`. Emitting that result on its own is a\n * 400 (\"no tool call found for function call output\"), and because the history\n * is persisted it is a 400 on every subsequent turn — the thread is bricked,\n * which is the failure `denied` exists to prevent.\n *\n * So the invariant is enforced here rather than assumed part-by-part: an\n * unpartnered output is dropped, a repeated one is dropped, and a call left\n * dangling by a crash between the call and its result gets a synthetic output\n * saying so. Fabricating that line is the lesser evil — it is true, the model\n * can read it, and the alternative is a conversation that can never be\n * continued.\n *\n * A repeated *call* is dropped for the same reason in the other direction. The\n * API happens to accept two `function_call`s under one id, so this is not a\n * 400 — it is the model reading the same call twice, on every turn, for the\n * rest of the conversation. The way it arises is a store that appended the\n * amended copy of a message instead of replacing it; the store contract now\n * says upsert, and this is the guard for a store that did not read it.\n */\nfunction reconcileToolPairs(items: ResponsesInputItem[]): ResponsesInputItem[] {\n const called = new Set<string>();\n const answered = new Set<string>();\n const kept: ResponsesInputItem[] = [];\n\n for (const item of items) {\n if (item.type === \"function_call\") {\n const callId = String(item.call_id);\n if (called.has(callId)) continue;\n called.add(callId);\n } else if (item.type === \"function_call_output\") {\n const callId = String(item.call_id);\n // Positional: the output has to come *after* its call, which is what the\n // API checks, so a call seen later in the history does not rescue it.\n if (!called.has(callId) || answered.has(callId)) continue;\n answered.add(callId);\n }\n kept.push(item);\n }\n\n if (answered.size === called.size) return kept;\n\n const out: ResponsesInputItem[] = [];\n for (const item of kept) {\n out.push(item);\n if (item.type !== \"function_call\") continue;\n const callId = String(item.call_id);\n if (answered.has(callId)) continue;\n answered.add(callId);\n out.push({ type: \"function_call_output\", call_id: callId, output: NO_RESULT_RECORDED });\n }\n return out;\n}\n\nfunction textContent(role: AgentMessage[\"role\"], text: string): Record<string, unknown> {\n return { type: role === \"assistant\" ? \"output_text\" : \"input_text\", text };\n}\n\n/**\n * `FilePart.attachmentId`, if it is one.\n *\n * In stateless mode the history arrives from the browser and only the turn\n * itself is checked at the door (`toClientTurn`), so a part posted back as\n * history can hold anything here. A value that is not a gemi id is treated as\n * absent rather than refused: it names nothing a tool could resolve, and\n * refusing it would fail every later turn of a conversation over a field the\n * model could not have used.\n */\nfunction attachmentIdOf(part: FilePart): string | undefined {\n const id = part.attachmentId;\n return typeof id === \"string\" && id.startsWith(ATTACHMENT_ID_PREFIX) ? id : undefined;\n}\n\n/**\n * The line that tells the model an attachment's id, sent just before the file\n * block it labels (or alone, when there is no file block to send).\n *\n * WHY A LINE AT ALL. A model that has seen a user's image has no id to put in\n * a tool's arguments unless it is told one. Whatever it writes there instead\n * is answered by `ctx.attachments.file()` with `AttachmentNotFoundError` —\n * correctly, for an id that was never obtainable. For a storage-only upload\n * this line is all the model gets: without it, it does not know a file exists.\n *\n * WHY THIS FORMAT. `[attachment id=\"…\" name=\"…\" mimeType=\"…\"]`, each value\n * JSON-quoted. The filename is the user's and can hold spaces, quotes, `]` or\n * a newline; JSON quoting means none of them can end a field, end the bracket,\n * or start a second line that reads as another attachment, so the id a model\n * copies out is exactly the id. The unquoted form (`[attachment gemi_att_… my\n * photo.png image/png]`) looks tidier and is ambiguous as soon as a name has a\n * space. A key with no value is left out rather than written as `name=\"\"`.\n *\n * WHY IT SAYS WHEN THE FILE IS NOT SHOWN. A storage-only upload, or any file\n * sent to a model without `fileInput`, has no block beside the line. Left\n * unsaid, a line that names `photo.png` invites the model to describe a\n * picture it never saw.\n */\nfunction attachmentLine(part: FilePart, shown: boolean): string {\n const fields = [`id=${JSON.stringify(part.attachmentId)}`];\n if (part.name) fields.push(`name=${JSON.stringify(part.name)}`);\n if (part.mimeType) fields.push(`mimeType=${JSON.stringify(part.mimeType)}`);\n const line = `attachment ${fields.join(\" \")}`;\n return shown\n ? `[${line}]`\n : `[${line} — its contents are not shown to you; a tool can read the file by this id]`;\n}\n\n/**\n * An attachment onto the content block that can carry it.\n *\n * `input_file` is the document path and `input_image` is the vision one, and\n * they are not interchangeable in either direction — the API refuses the wrong\n * pairing with a 400 rather than degrading. So this branch is not a nicety\n * about how well an image is read; it decides whether the turn happens at all.\n * What was measured, on which models, with the verbatim rejections, is recorded\n * above `IMAGE_EXTENSIONS`.\n *\n * `file_id` is the same field on both blocks, so nothing about the upload\n * changes: `uploadFile` posts once (with the provider's purpose — see\n * `UploadPurpose`) and the id it returns is legal in either. `detail` is deliberately not sent on the image\n * block — it is optional, the API defaults it, and a `FilePart` carries no\n * signal that would justify choosing anything but that default.\n *\n * SVG is the case the `image/` prefix gets wrong. `image/svg+xml` is an image\n * MIME type, and .svg is on the API's *document* list and off its image list —\n * so a prefix test alone sends it to the one block that is guaranteed to refuse\n * it. It is routed by what the API calls it, not by what the MIME type calls\n * it.\n *\n * WHEN `mimeType` IS ABSENT OR EMPTY the file name decides, and if that settles\n * nothing the part is sent as `input_file`. Both halves matter.\n *\n * The name branch is NOT a rescue for un-typed legacy rows, and deleting it as\n * one would break a live upload. The browser path has always written the field:\n * `useChat.uploadFile` has stored `data.mimeType ?? file.type` since the module\n * landed (`git log -S mimeType -- ai/useChat.tsx` bottoms out at d940676e), so\n * there is no history of `undefined` MIME types to point at, and a backfill\n * would not make this branch dead. What it is actually for is the two cases\n * that still leave nothing to read. `File.type` is the EMPTY STRING, not\n * absent, for a file the browser cannot type — so `?? file.type` stores `\"\"`\n * and this branch fires on a perfectly current upload — and a `FilePart`\n * assembled by a server-side caller may set neither field, because the type\n * marks both optional.\n *\n * The name is also the right thing to fall back to rather than merely the last\n * thing left: the server classifies by the STORED FILE NAME'S EXTENSION, not by\n * the bytes and not by the upload's `Content-Type` (measured; the transcript is\n * below). And what it rescues is not a cosmetic degradation — an image part\n * that lands on `input_file` 400s, and because that part lives in stored\n * history and goes back up on every request, it 400s every remaining turn of\n * the thread. `useChat.uploadFile` fills `name` from the local `File` and the\n * file is uploaded under that same name, so such a part almost always still\n * says `.png`.\n *\n * Falling back to `input_file` past that is the conservative half — a part with\n * neither a MIME type nor a usable name is much more likely to be the document\n * it has always been sent as than an image, and this way a nameless document\n * keeps working instead of being newly broken to rescue a nameless image.\n *\n * PRECEDENCE, since two orderings are otherwise indistinguishable: the MIME\n * type classifies and the name is consulted only when there is none. A stated\n * type is a stated fact and a name is a convention, so a `.pdf` named\n * `image/png` goes to the image block. `request.test.ts` pins this with a case\n * where the two disagree, because a name-first `fileContent` passes every case\n * where they agree.\n */\nfunction fileContent(part: FilePart): Record<string, unknown> {\n const mimeType = part.mimeType?.trim().toLowerCase() ?? \"\";\n // `\"\"` rather than `undefined` is the shape to expect from a browser that\n // could not type the file: `useChat.uploadFile` writes `data.mimeType ??\n // file.type`, and `File.type` is the empty string, not absent. Both land on\n // the name.\n const isImage = mimeType\n ? mimeType.startsWith(\"image/\") && mimeType !== \"image/svg+xml\"\n : hasImageExtension(part.name);\n return { type: isImage ? \"input_image\" : \"input_file\", file_id: part.fileId };\n}\n\nfunction hasImageExtension(name: string | undefined): boolean {\n const match = /\\.([a-z0-9]+)$/.exec(name?.trim().toLowerCase() ?? \"\");\n return match?.[1] !== undefined && IMAGE_EXTENSIONS.has(match[1]);\n}\n\n/**\n * Which block takes what, and whether the wrong one merely reads badly.\n *\n * MEASURED, not read off the API reference. Three attachments were uploaded to\n * `https://api.openai.com/v1/files` with `purpose: \"user_data\"` — a 64x64 PNG\n * of four solid quadrants (red, green, blue, yellow), a one-page PDF whose only\n * word is BANANA, and a 64x64 SVG — and each was then sent to\n * `https://api.openai.com/v1/responses` in both content blocks:\n *\n * PNG as `{type:\"input_image\", file_id}` — 200. Asked which quadrant was\n * red, gpt-5.4 answered `\"top-left\"` and gpt-4o `\"The red quadrant is the\n * top-left.\"` Both correct. SO AN UPLOADED IMAGE IS REAL VISION INPUT, and\n * `file_id` is all `input_image` needs; sending `detail:\"auto\"` alongside\n * it changed nothing, so it is left off.\n * PNG as `{type:\"input_file\", file_id}` — 400, verbatim: `Invalid input:\n * Expected context stuffing file type to be a supported format: .art, .bat,\n * … .pdf, … .svg, … .yml but got .png.` (~90 extensions, elided.) This is\n * the finding that mattered: what gemi shipped was not \"an image the model\n * reads poorly\", it was a request that never ran.\n * PDF as `{type:\"input_file\", file_id}` — 200, `\"BANANA\"` on gpt-5.4 and\n * gpt-4o both.\n * PDF as `{type:\"input_image\", file_id}` — 400, verbatim: `Invalid input:\n * Expected image type to be a supported format: .jpeg, .jpg, .png, .gif,\n * .webp but got .pdf.` So the refusal is symmetric: neither block tolerates\n * the other's content.\n * SVG as `{type:\"input_image\", file_id}` — 400, `… but got .svg.`\n * SVG as `{type:\"input_file\", file_id}` — 400, but a different one:\n * `You uploaded an invalid file. Please try again with a different file`,\n * with no format list. .svg is on the document list and off the image one,\n * so routing accepted it and the pipeline behind it did not. An SVG fails\n * both ways today; it is sent as `input_file` because that is where the API\n * says it belongs, which is the only branch that can start working without\n * another change here.\n *\n * AND THE DISCRIMINATOR IS THE FILE NAME, NOT THE BYTES AND NOT THE UPLOAD'S\n * `Content-Type`. The same PNG bytes uploaded under the name `quadrants.txt`\n * with `type: \"text/plain\"` were refused as `input_image` with `… but got\n * .txt.`, and as `input_file` with `The file you uploaded is badly formatted or\n * corrupted. Please fix the file and try again.` (code `invalid_file`) — routed\n * by the extension, then failed on the bytes. That is why the name is what a\n * part with no `mimeType` falls back to: it is what the server will judge by.\n *\n * The extensions below are transcribed from the image rejection above.\n *\n * A closed list is right *here* and wrong one line up. This set is only\n * consulted when there is no MIME type to read, which is a guess either way, so\n * it guesses the conservative direction: a format the API adds later goes on\n * being sent as `input_file`, exactly as it is today. The MIME branch stays\n * open (`image/` prefix) for the opposite reason — a declared `image/avif`\n * belongs in the image block the moment the API takes one, and being wrong\n * there is a 400 that names the format, which is loud and fixes itself.\n */\nconst IMAGE_EXTENSIONS = new Set([\"jpeg\", \"jpg\", \"png\", \"gif\", \"webp\"]);\n\n/**\n * Reasoning goes back exactly as it came.\n *\n * Reshaping it — flattening the summary into text, renaming the item, dropping\n * the id — costs two things that are hard to see and expensive to have lost:\n * the prompt cache, which keys on the literal item, and on a reasoning model\n * the thread of the model's own argument across turns.\n *\n * An item with no id is dropped instead. The id is the API's handle on stored\n * reasoning, and an item without one is not a reasoning item the API can\n * resolve — sending a summary under a fabricated id would be worse than\n * sending nothing, because it would look like continuity that is not there.\n */\nfunction reasoningItem(part: { id?: string; text?: string }): ResponsesInputItem | null {\n if (!part.id) return null;\n const item: ResponsesInputItem = { type: \"reasoning\", id: part.id };\n item.summary = part.text ? [{ type: \"summary_text\", text: part.text }] : [];\n return item;\n}\n\n/**\n * Every tool call gets an output, including the ones that never ran.\n *\n * The API rejects a history containing a `function_call` with no matching\n * `function_call_output`, so a denial cannot be expressed by omission — and a\n * conversation where the user said no has to stay continuable, which is the\n * whole reason `denied` exists in the first place.\n *\n * What is sent is prose rather than a status enum, because the reader is a\n * language model: it has to be able to tell \"the user refused this\" from \"this\n * blew up\", and those two lead to genuinely different next moves — apologize\n * and ask, versus try another way.\n *\n * STILL A STRING, AFTER #490, AND THAT IS THE DESIGN. A tool that produces a\n * file the model has to look at does not put it here: the run appends an\n * input-role message carrying a `FilePart` after the call settles, which is the\n * `input_file` shape a user's own upload already takes and which the branch\n * above already builds every day.\n *\n * The alternative was a `function_call_output` whose `output` is a content\n * array with an image block in it, and it was not chosen because NOBODY HAS\n * MEASURED WHETHER THE API ACCEPTS ONE. No request was made with an image block\n * in a `function_call_output`, so whether it is taken, ignored, or a 400 is\n * unknown, and the one thing that is certain is that finding out costs a\n * conversation each time it is wrong — a rejected history is rejected on every\n * subsequent turn, not just the one that built it. Going through a route that\n * is exercised on every vision request costs nothing to be sure of. If someone\n * does measure it and it works, the tool result becomes the tidier home for a\n * file and this comment is the place to say so.\n */\nexport function toolResultOutput(part: ToolResultPart): string {\n if (part.status === \"ok\") {\n return typeof part.output === \"string\" ? part.output : JSON.stringify(part.output ?? null);\n }\n\n if (part.status === \"denied\") {\n const reason = part.reason ? ` Reason given: ${part.reason}` : \"\";\n if (part.cause === \"stopped\") {\n return `The run was stopped before this tool call could complete, so it did not run.${reason}`;\n }\n if (part.cause === \"interrupted\") {\n // Not \"it did not run\": the server went down while it was running, so it\n // may have done some or all of its work (saved a page, sent an email)\n // with nobody left to record the result. A model told it did not run\n // does it again.\n return `The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${reason}`;\n }\n return `The user declined this tool call, so it did not run.${reason}`;\n }\n\n return `The tool call failed and produced no result. Error (${part.error?.code ?? \"unknown\"}): ${\n part.error?.message ?? \"no message\"\n }`;\n}\n\n// --- tools ---------------------------------------------------------------\n\nfunction isNamespace(\n entry: ProviderToolSpec | ProviderToolNamespace,\n): entry is ProviderToolNamespace {\n return Array.isArray((entry as ProviderToolNamespace).tools);\n}\n\n/**\n * Tools and namespaces onto the Responses `tools` array.\n *\n * Without tool search the grouping has nothing to do — a namespace exists to be\n * searched — so it is flattened away and every schema is sent inline with\n * `deferred` ignored. That is the promise `capabilities.toolSearch` makes:\n * deferral is a token optimization, and an optimization that changed which\n * tools the model can reach would not be one.\n */\nexport function toResponsesTools(\n tools: (ProviderToolSpec | ProviderToolNamespace)[] | undefined,\n capabilities: ProviderCapabilities,\n): ResponsesTool[] {\n if (!tools || tools.length === 0) return [];\n\n if (!capabilities.toolSearch) {\n const flat: ResponsesTool[] = [];\n for (const entry of tools) {\n if (isNamespace(entry)) {\n for (const tool of entry.tools) flat.push(functionTool(tool, false));\n } else {\n flat.push(functionTool(entry, false));\n }\n }\n return flat;\n }\n\n const out: ResponsesTool[] = [];\n let anyDeferred = false;\n\n for (const entry of tools) {\n if (isNamespace(entry)) {\n const inner = entry.tools.map((tool) => {\n if (tool.deferred) anyDeferred = true;\n return functionTool(tool, true);\n });\n out.push({\n type: \"namespace\",\n name: entry.name,\n description: entry.description,\n tools: inner,\n });\n } else {\n if (entry.deferred) anyDeferred = true;\n out.push(functionTool(entry, true));\n }\n }\n\n // Without this the deferred schemas are unreachable: the model is shown a\n // name and a description and given no way to ask for the rest, which is worse\n // than not deferring at all. Added only when something is actually deferred,\n // so an agent that defers nothing does not pay for a tool it cannot use.\n if (anyDeferred) out.push({ type: \"tool_search\" });\n\n return out;\n}\n\nfunction functionTool(tool: ProviderToolSpec, allowDeferred: boolean): ResponsesTool {\n const spec: ResponsesTool = {\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n strict: tool.strict,\n };\n if (allowDeferred && tool.deferred) spec.defer_loading = true;\n return spec;\n}\n",
24
- "import type { ReasoningEffort } from \"./Agent\";\nimport {\n responsesEndpoint,\n streamResponses,\n uploadFile,\n type ResponsesEndpoint,\n} from \"./providers/call\";\nimport { capabilitiesForModel } from \"./providers/capabilities\";\nimport {\n azureTarget,\n openAITarget,\n type AzureConfig,\n type ProviderConfig,\n} from \"./providers/endpoints\";\nimport { normalizeProviderError } from \"./providers/errors\";\nimport { sentFiles } from \"./providers/fileRejection\";\nimport { buildResponsesRequest } from \"./providers/request\";\nimport type { JSONSchema } from \"./Schema\";\nimport type { AgentError, AgentMessage, FinishReason, Usage } from \"./types\";\n\n/**\n * A provider makes one model call. It does not run the tool loop.\n *\n * The split matters: approvals, `maxSteps`, deferred tools, skill loading and\n * persistence are all provider-independent, and putting them in the provider\n * would mean writing them again for the second provider. So the provider's\n * whole job is to translate gemi's messages into a request, and the response\n * stream back into `ProviderEvent`s. Everything above that lives in `Agent`.\n *\n * v1 targets OpenAI's Responses API — native reasoning items and strict\n * structured output without reassembling them by hand. The interface is kept\n * free of anything Responses-specific so a Chat Completions provider (for older\n * Azure deployments and OpenAI-compatible gateways) can be added later without\n * touching Agent, Controller or the client.\n */\n\n/** What a provider will actually honour, so `Agent` can drop the rest rather\n * than have a request rejected at runtime. */\nexport type ProviderCapabilities = {\n reasoning: boolean;\n structuredOutput: boolean;\n fileInput: boolean;\n parallelToolCalls: boolean;\n /**\n * Tool search, and with it deferred loading. Only recent models have it, so a\n * provider that answers `false` is sent every schema inline and the agent\n * runs identically — deferral is a token optimization, and an optimization\n * that changed behaviour when unavailable would not be one.\n */\n toolSearch: boolean;\n};\n\n/** A tool as the model is shown it: schema only, no implementation. */\nexport type ProviderToolSpec = {\n name: string;\n description: string;\n parameters: JSONSchema;\n strict: boolean;\n /** `defer_loading`: send the name and description, withhold the schema until\n * the model searches for it. Ignored when `capabilities.toolSearch` is\n * false. */\n deferred?: boolean;\n};\n\n/** Tools grouped for search. Flattened back to a list by a provider without\n * tool search, since the grouping exists to be searched. */\nexport type ProviderToolNamespace = {\n name: string;\n description: string;\n tools: ProviderToolSpec[];\n};\n\nexport interface ProviderStreamParams {\n messages: AgentMessage[];\n systemPrompt?: string;\n tools?: (ProviderToolSpec | ProviderToolNamespace)[];\n /** Set when the agent declares an `output` schema; the provider turns it into\n * whatever its own strict-JSON parameter is. `strict` comes from the schema —\n * false when it contains an `s.json()` node, which strict mode cannot\n * express — and is required rather than defaulted so that a new caller has to\n * answer it instead of inheriting a 400. */\n output?: { name: string; schema: JSONSchema; strict: boolean };\n /** Optional: silently dropped by a provider whose `capabilities.reasoning`\n * is false, since a model that cannot reason should not fail a request. */\n reasoning?: ReasoningEffort;\n temperature?: number;\n maxOutputTokens?: number;\n signal?: AbortSignal;\n}\n\n/**\n * The events of a single model call. Deliberately smaller than\n * `AgentStreamEvent`: no run, message, tool-result or approval events, because\n * a provider knows about none of those.\n */\nexport type ProviderEvent =\n | { type: \"text-delta\"; delta: string }\n | { type: \"reasoning-delta\"; delta: string; id?: string }\n /** Arguments arrive as JSON fragments; the provider passes them through and\n * `Agent` assembles and validates against the tool's schema. */\n | {\n type: \"tool-call-delta\";\n toolCallId: string;\n name: string;\n argsDelta: string;\n namespace?: string;\n }\n /**\n * `name` IS FLAT AND STAYS FLAT. This was an open question and the API has\n * answered it: a call to a function that lives inside a namespace comes back\n * as `{name: \"getOrder\", namespace: \"crm\"}`, not as `\"crm.getOrder\"` —\n * recorded in `providers/__fixtures__/openai-tool-search.sse` and pinned by\n * a test that reads that file. So `name` is already the key `Agent`'s tool\n * registry is built on, which is what makes tool names having to be globally\n * unique within an agent (see `ToolNamespace`) the right rule rather than an\n * inconvenience.\n *\n * `namespace` is carried beside it, absent for a tool that was listed bare.\n * It is provenance, not identity: it says which group the model chose to\n * look in, which is worth recording next to the call and is worthless for\n * finding the tool. Folding it into `name` would make a name that is\n * sometimes qualified and sometimes not, and nothing could match on that.\n */\n | { type: \"tool-call\"; toolCallId: string; name: string; args: string; namespace?: string }\n /**\n * The model went looking for a deferred tool and pulled its schema in. Worth\n * surfacing rather than swallowing: it is a step the user paid for, and the\n * pause before it is otherwise unexplained.\n *\n * TWO FIELDS, not one. `loaded` is the function names — `[\"listOrders\",\n * \"getOrder\"]` — and `namespaces` is the groups they came out of —\n * `[\"crm\"]`. Search results arrive as a tree of namespaces containing\n * functions, so a single flat list has to pick one level and throw the other\n * away, and both levels are worth saying: \"searched crm, loaded getOrder\"\n * reads better than either half, and the group is the thing the model\n * actually chose between.\n *\n * `namespaces` is required rather than optional because the parser always\n * knows the answer, and an optional field would let a future provider forget\n * to fill it in silently. Empty means the search returned bare functions.\n */\n | { type: \"tool-search\"; loaded: string[]; namespaces: string[] }\n | { type: \"output-delta\"; delta: string }\n | { type: \"finish\"; reason: FinishReason; usage: Usage }\n /**\n * `status` and `requestId` describe the HTTP response the error came from,\n * when there was one. They are for the server's record of the run\n * (`AgentRunResult.error`) and are never written to a client frame; leave\n * them out for an error that was not a response.\n */\n /**\n * The provider refused a stored file (`fileId` is the provider's id) and the\n * call was sent again with a note in the file's place, so the turn goes on.\n * `Agent` marks the stored `FilePart` `providerRejected`, which makes later\n * requests send the note instead of the id — otherwise the same refusal\n * costs a failed request on every turn of the thread (#684). `message` is\n * the provider's, for the log. A provider that never retries need not send\n * this; `Agent` treats its absence as nothing having been rejected.\n */\n | { type: \"file-rejected\"; fileId: string; message: string; status?: number; requestId?: string }\n | { type: \"error\"; error: AgentError; status?: number; requestId?: string };\n\nexport type ProviderStream = AsyncIterable<ProviderEvent>;\n\n/**\n * Re-exported rather than declared here. What these configure is the *vendor*,\n * not the Responses API, and the images path resolves the same host, credential\n * and api-version from the same fields — see `providers/endpoints.ts` for why\n * that resolution lives in one place and what happens when it does not.\n */\nexport type { AzureConfig, ProviderConfig } from \"./providers/endpoints\";\n\nexport abstract class AgentProvider {\n abstract readonly model: string;\n abstract readonly capabilities: ProviderCapabilities;\n\n /** The model ids this provider knows about — for autocomplete only; any\n * string is still accepted, because a new model must not require a gemi\n * release to use. */\n static models(): readonly string[] {\n return [];\n }\n\n abstract stream(params: ProviderStreamParams): ProviderStream;\n\n /**\n * Uploads a file and returns the id a `FilePart` carries. Message history\n * therefore holds provider file ids, which is the trade for getting vision\n * and PDF input without gemi owning a storage story in v1.\n */\n abstract upload(file: File): Promise<string>;\n\n /**\n * Maps a provider's error body onto the normalized codes, so an app can\n * branch on `rate_limited` without knowing whose rate limit it was.\n *\n * Shared rather than abstract-in-practice: Azure answers the same error\n * envelope as OpenAI, and the one place it differs — the content filter's\n * code, buried in `innererror` — is handled by reading both.\n */\n normalizeError(error: unknown): AgentError {\n return normalizeProviderError(error);\n }\n}\n\n/**\n * Autocomplete, not a gate. Every id here was confirmed present in\n * `GET https://api.openai.com/v1/models`; any other string is still accepted,\n * because a model released next Tuesday must not need a gemi release to use —\n * see `capabilitiesForModel` for what an unrecognized id is assumed to do.\n *\n * Ordered newest first, and deliberately short. `/v1/models` answers with\n * ninety-odd chat ids once the dated snapshots and the `-codex`, `-pro`,\n * `-chat-latest`, `-search-api` and `-nano` variants are counted; a list that\n * tried to be complete would be stale within the month and would bury the\n * handful of names anyone actually types. Snapshot-pinned ids\n * (`gpt-5.4-2026-03-05`) are left out for the same reason and work identically.\n *\n * The Azure provider returns this same list, which is a small lie it has always\n * told: a resource serves the deployments someone created, not the catalogue.\n * `AzureConfig.deployment` is the escape hatch, and an unrecognized deployment\n * name lands on the same capable default as an unrecognized model.\n */\nconst OPENAI_MODELS = [\n \"gpt-5.5\",\n \"gpt-5.4\",\n \"gpt-5.4-mini\",\n \"gpt-5.4-nano\",\n \"gpt-5.2\",\n \"gpt-5.1\",\n \"gpt-5\",\n \"gpt-5-mini\",\n \"gpt-5-nano\",\n \"gpt-4.1\",\n \"gpt-4.1-mini\",\n \"gpt-4.1-nano\",\n \"gpt-4o\",\n \"gpt-4o-mini\",\n \"o4-mini\",\n \"o3\",\n \"o3-mini\",\n] as const;\n\nexport class OpenAIProvider extends AgentProvider {\n readonly model: string;\n readonly capabilities: ProviderCapabilities;\n protected readonly config: ProviderConfig;\n\n constructor(model: string, config: ProviderConfig = {}) {\n super();\n this.model = model;\n this.capabilities = capabilitiesForModel(model);\n this.config = config;\n }\n\n /** Config defaults come from gemi's config (`ai.openai`), so an app that has\n * set `OPENAI_API_KEY` writes only the model name. */\n static model(model: string, config?: ProviderConfig): OpenAIProvider {\n return new OpenAIProvider(model, config);\n }\n\n static models(): readonly string[] {\n return OPENAI_MODELS;\n }\n\n stream(params: ProviderStreamParams): ProviderStream {\n const body = buildResponsesRequest(params, {\n model: this.model,\n capabilities: this.capabilities,\n });\n return streamResponses(this.endpoint(), body, {\n signal: params.signal,\n // The request carries the schema whenever the agent declared one, so the\n // parser has to read the answer as one too — a model that ignored the\n // parameter answers 400, not prose.\n structuredOutput: Boolean(params.output),\n files: sentFiles(params.messages),\n });\n }\n\n upload(file: File): Promise<string> {\n return uploadFile(this.endpoint(), file);\n }\n\n protected endpoint(): ResponsesEndpoint {\n return responsesEndpoint(openAITarget(this.config));\n }\n}\n\n/**\n * Its own class rather than a flag on `OpenAIProvider`: Azure names the\n * deployment rather than the model, pins an api-version, authenticates with an\n * `api-key` header or an Entra token, and puts the resource in the host. One\n * class carrying both shapes means every field is conditionally meaningful.\n *\n * (It used to put the deployment in the URL as well. It does not: the Responses\n * API serves no such path — see `azureBase` for the measurements.)\n *\n * The API stays symmetrical — `.model()`, not `.deployment()`. Apps name a\n * model; mapping that onto a deployment is this class's problem, and an app\n * that named its deployment differently overrides it in config.\n */\nexport class AzureOpenAIProvider extends AgentProvider {\n readonly model: string;\n readonly capabilities: ProviderCapabilities;\n protected readonly config: AzureConfig;\n\n constructor(model: string, config: AzureConfig = {}) {\n super();\n this.model = model;\n // Read off the model, not the deployment: a deployment called `prod` says\n // nothing, and an unrecognized name lands on the all-capabilities default\n // anyway. See `capabilitiesForModel`.\n this.capabilities = capabilitiesForModel(model);\n this.config = config;\n }\n\n /** Defaults from gemi's config (`ai.azure`). */\n static model(model: string, config?: AzureConfig): AzureOpenAIProvider {\n return new AzureOpenAIProvider(model, config);\n }\n\n static models(): readonly string[] {\n return OPENAI_MODELS;\n }\n\n stream(params: ProviderStreamParams): ProviderStream {\n const body = buildResponsesRequest(params, {\n model: this.deployment(),\n capabilities: this.capabilities,\n });\n return streamResponses(this.endpoint(), body, {\n signal: params.signal,\n // The request carries the schema whenever the agent declared one, so the\n // parser has to read the answer as one too — a model that ignored the\n // parameter answers 400, not prose.\n structuredOutput: Boolean(params.output),\n files: sentFiles(params.messages),\n });\n }\n\n /** `assistants`, not OpenAI's `user_data`: Azure's Responses API refuses a\n * `user_data` id outright (#682). See `UploadPurpose`. */\n upload(file: File): Promise<string> {\n return uploadFile(this.endpoint(), file, \"assistants\");\n }\n\n protected deployment(): string {\n return this.config.deployment ?? this.model;\n }\n\n protected endpoint(): ResponsesEndpoint {\n return responsesEndpoint(azureTarget(this.config));\n }\n}\n",
25
- "import type { ReasoningEffort } from \"./Agent\";\nimport {\n AgentProvider,\n type ProviderCapabilities,\n type ProviderEvent,\n type ProviderStream,\n type ProviderStreamParams,\n} from \"./AgentProvider\";\nimport { httpErrorDetail } from \"./providers/errors\";\nimport { addUsage, emptyUsage } from \"./runtime\";\nimport type { AgentError, Usage } from \"./types\";\n\n/**\n * An ordered chain of providers (#666): the primary, then the fallbacks.\n *\n * It is a provider itself, so `Agent`, `generate()` and the controller take it\n * where they take any other, and nothing above the provider learns there is a\n * chain. That is the point: the alternative was a `providers: [...]` option on\n * `Agent`, and every place that reads `config.provider` would have had to\n * answer \"which one?\".\n *\n * THE ONE RULE THAT SHAPES EVERYTHING: no fallback once output has reached the\n * consumer. A leg that has streamed a word, a reasoning summary or a tool call\n * has been seen — by the user, and by `Agent`, which already appended it to the\n * message — and a second model starting over would put two answers in one\n * message. So a leg's events are held back until its first content event, and\n * from that event on the leg is committed and a later error is final.\n *\n * Reasoning commits too, not only text, tool calls and structured output. It is\n * streamed to the client like text is, and a reasoning item is tied to the\n * deployment that wrote it: sending one leg's item back to another on the next\n * turn is a request the vendor may refuse. Holding reasoning back until the\n * answer starts would hide minutes of \"thinking\" from the UI on every call.\n */\n\n/** One leg of a chain. */\nexport type FallbackEntry = {\n provider: AgentProvider;\n /**\n * How long this leg has to produce its FIRST event, in milliseconds. Past\n * that it is abandoned (its request aborted) and the next leg is tried. Once\n * any event has arrived, this deadline is off and the leg's own request\n * timeout applies — a slow answer that has started is not a dead one.\n *\n * Omitted: no deadline of the chain's own.\n */\n timeoutMs?: number;\n /**\n * Overrides `ProviderStreamParams.reasoning` for this leg. Models in one\n * chain take different effort values (#658), so the agent's single setting\n * is right for at most one of them. Dropped, as usual, by a provider whose\n * `capabilities.reasoning` is false.\n */\n reasoning?: ReasoningEffort;\n};\n\n/** What `fallbackOn` is told besides the normalized error. */\nexport type FallbackFailure = {\n /** The leg's position in the chain this provider was built with (after `from()`). */\n index: number;\n model: string;\n /** The HTTP status of the failed response, when there was one. */\n status?: number;\n requestId?: string;\n /** True when the leg produced nothing within its `timeoutMs`. */\n timedOut: boolean;\n};\n\n/** One leg's report, for `onUsage`. Called once per leg that was tried. */\nexport type FallbackUsage = {\n /** The leg's position in this provider's chain. */\n index: number;\n /** The leg's configured model. */\n model: string;\n /** 1 for the first leg tried in this call, 2 for the first fallback, and so on. */\n attempt: number;\n /**\n * What the leg reported, including a failed leg that billed tokens (a\n * content filter does). Absent when the leg never reported usage: it timed\n * out, threw, or was abandoned.\n */\n usage?: Usage;\n /** `ok`: this leg answered (the call may still have failed after output). */\n outcome: \"ok\" | \"fallback\" | \"failed\" | \"aborted\";\n error?: AgentError;\n};\n\nexport type FallbackOptions = {\n /**\n * Whether a failure moves on to the next leg. Default: `error.retryable`,\n * which `normalizeError` sets for a 429 that is not a spent quota, a 5xx, a\n * 408/409, a timeout and a network failure — and not for a request that would\n * fail the same way on any model (context length, a bad tool schema).\n *\n * Never asked about the last leg, about a user abort, or about a failure\n * after output.\n */\n fallbackOn?: (error: AgentError, failure: FallbackFailure) => boolean;\n /** Per-leg usage. An exception thrown here is swallowed: accounting must not\n * fail the call it is accounting for. */\n onUsage?: (report: FallbackUsage) => void;\n};\n\n/** Every event that is content a consumer shows or stores. The first one commits its leg. */\nfunction isContent(event: ProviderEvent): boolean {\n switch (event.type) {\n case \"text-delta\":\n case \"reasoning-delta\":\n case \"tool-call-delta\":\n case \"tool-call\":\n case \"tool-search\":\n case \"output-delta\":\n return true;\n default:\n return false;\n }\n}\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\nexport class FallbackProvider extends AgentProvider {\n /** The first leg's model: the one the chain is named after in logs. */\n readonly model: string;\n /**\n * The intersection of every leg's capabilities. A tool or a structured output\n * one leg cannot handle would otherwise be found the day the primary is down,\n * which is the worst day to find it. `Agent` drops what is false here, so a\n * chain behaves the same whichever leg answers.\n */\n readonly capabilities: ProviderCapabilities;\n readonly entries: readonly FallbackEntry[];\n private readonly options: FallbackOptions;\n\n constructor(entries: readonly FallbackEntry[], options: FallbackOptions = {}) {\n super();\n if (entries.length === 0) {\n throw new Error(\"FallbackProvider needs at least one provider.\");\n }\n for (const entry of entries) {\n if (entry.timeoutMs !== undefined && !(entry.timeoutMs > 0)) {\n throw new Error(\n `FallbackProvider: timeoutMs for ${entry.provider.model} must be a positive number, got ${entry.timeoutMs}.`,\n );\n }\n }\n this.entries = [...entries];\n this.options = options;\n this.model = entries[0]!.provider.model;\n this.capabilities = intersect(entries.map((entry) => entry.provider.capabilities));\n }\n\n static chain(entries: readonly FallbackEntry[], options?: FallbackOptions): FallbackProvider {\n return new FallbackProvider(entries, options);\n }\n\n /**\n * The same chain entered at `index`. For work that should never reach the\n * primary — a cheap text task on an expensive chain — without a second chain\n * to keep in step. Same options; `index` in reports counts from the new start.\n */\n from(index: number): FallbackProvider {\n if (!Number.isInteger(index) || index < 0 || index >= this.entries.length) {\n throw new RangeError(\n `FallbackProvider.from(${index}): the chain has ${this.entries.length} entries.`,\n );\n }\n return new FallbackProvider(this.entries.slice(index), this.options);\n }\n\n /** The leg at `index` on its own, with its reasoning and timeout. What `evalChain` runs. */\n leg(index: number): FallbackProvider {\n const entry = this.from(index).entries[0]!;\n return new FallbackProvider([entry], this.options);\n }\n\n /**\n * To the first leg only. A provider's file id is not portable (#443): an id\n * from one OpenAI account or Azure resource means nothing to another, so\n * uploading to every leg would cost N uploads for ids nobody could choose\n * between. Legs on the same Azure resource share its files, which is the\n * common chain; a chain across accounts should keep files out of the\n * fallback path or store them with gemi.\n */\n upload(file: File): Promise<string> {\n return this.entries[0]!.provider.upload(file);\n }\n\n normalizeError(error: unknown): AgentError {\n return this.entries[0]!.provider.normalizeError(error);\n }\n\n stream(params: ProviderStreamParams): ProviderStream {\n return this.run(params);\n }\n\n private async *run(params: ProviderStreamParams): AsyncGenerator<ProviderEvent> {\n // What the abandoned legs billed. Added to the closing `finish`, so the\n // run's usage is what the call cost rather than what the winning leg cost.\n let billed: Usage | undefined;\n const outer = params.signal;\n\n for (let index = 0; index < this.entries.length; index++) {\n const entry = this.entries[index]!;\n const last = index === this.entries.length - 1;\n const attempt = index + 1;\n const model = entry.provider.model;\n\n const leg = new AbortController();\n const onAbort = () => leg.abort(outer?.reason);\n if (outer?.aborted) leg.abort(outer.reason);\n else outer?.addEventListener(\"abort\", onAbort, { once: true });\n\n const held: ProviderEvent[] = [];\n let committed = false;\n let finished = false;\n let usage: Usage | undefined;\n let failure: { error: AgentError; status?: number; requestId?: string } | undefined;\n let timedOut = false;\n let iterator: AsyncIterator<ProviderEvent> | undefined;\n let done = false;\n\n const closing = (event: Extract<ProviderEvent, { type: \"finish\" }>) => {\n const merged = billed ? addUsage(addUsage(emptyUsage(), billed), event.usage) : event.usage;\n billed = undefined;\n return { ...event, usage: merged };\n };\n\n try {\n iterator = entry.provider\n .stream({\n ...params,\n ...(entry.reasoning !== undefined ? { reasoning: entry.reasoning } : {}),\n signal: leg.signal,\n })\n [Symbol.asyncIterator]();\n\n let first = true;\n for (;;) {\n const next =\n first && entry.timeoutMs !== undefined\n ? await withDeadline(iterator.next(), entry.timeoutMs)\n : await iterator.next();\n if (next === TIMED_OUT) {\n timedOut = true;\n failure = {\n error: {\n code: \"provider_error\",\n message: `${model} sent nothing within ${entry.timeoutMs}ms.`,\n retryable: true,\n },\n };\n break;\n }\n first = false;\n if (next.done) {\n done = true;\n break;\n }\n const event = next.value;\n\n if (committed) {\n if (event.type === \"finish\") {\n usage = addUsage(usage ?? emptyUsage(), event.usage);\n finished = true;\n yield closing(event);\n } else {\n if (event.type === \"error\") failure = { error: event.error };\n yield event;\n }\n continue;\n }\n\n if (isContent(event)) {\n committed = true;\n yield* held.splice(0);\n yield event;\n continue;\n }\n\n if (event.type === \"error\") {\n failure = {\n error: event.error,\n ...(event.status !== undefined ? { status: event.status } : {}),\n ...(event.requestId !== undefined ? { requestId: event.requestId } : {}),\n };\n } else if (event.type === \"finish\") {\n usage = addUsage(usage ?? emptyUsage(), event.usage);\n if (event.reason === \"error\" && !failure) {\n failure = {\n error: {\n code: \"provider_error\",\n message: `${model} ended the call with an error and did not say which.`,\n retryable: false,\n },\n };\n }\n }\n held.push(event);\n }\n } catch (thrown) {\n // A custom provider is allowed to throw rather than send an error event;\n // the built-in ones never do. It reads the same either way.\n const error = entry.provider.normalizeError(thrown);\n if (committed) {\n if (error.code !== \"aborted\") {\n yield { type: \"error\", error, ...httpErrorDetail(thrown) };\n }\n this.report({ index, model, attempt, usage, outcome: outcomeOf(error), error });\n yield closing({\n type: \"finish\",\n reason: error.code === \"aborted\" ? \"aborted\" : \"error\",\n usage: emptyUsage(),\n });\n return;\n }\n failure = { error, ...httpErrorDetail(thrown) };\n } finally {\n outer?.removeEventListener(\"abort\", onAbort);\n // Abandoned (timed out, fell back, or the consumer stopped reading):\n // stop its request and let it go without waiting for it to agree.\n if (!done) {\n leg.abort();\n void iterator?.return?.()?.catch(() => {});\n }\n }\n\n if (committed) {\n if (!finished && billed) {\n // The leg ended without a closing frame; the abandoned legs' cost\n // still has to be told to someone.\n yield { type: \"finish\", reason: failure ? \"error\" : \"stop\", usage: billed };\n billed = undefined;\n }\n this.report({\n index,\n model,\n attempt,\n usage,\n outcome: failure ? outcomeOf(failure.error) : \"ok\",\n ...(failure ? { error: failure.error } : {}),\n });\n return;\n }\n\n // The consumer stopped the run. Not a failure of this leg, and certainly\n // not one to answer by asking the next model.\n if (outer?.aborted) {\n this.report({ index, model, attempt, usage, outcome: \"aborted\" });\n yield closing({ type: \"finish\", reason: \"aborted\", usage: usage ?? emptyUsage() });\n return;\n }\n\n if (!failure) {\n // Answered with nothing: a finish and no content. That is an answer.\n this.report({ index, model, attempt, usage, outcome: \"ok\" });\n for (const event of held) yield event.type === \"finish\" ? closing(event) : event;\n return;\n }\n\n const fallback =\n !last &&\n failure.error.code !== \"aborted\" &&\n this.shouldFallBack(failure.error, {\n index,\n model,\n timedOut,\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n ...(failure.requestId !== undefined ? { requestId: failure.requestId } : {}),\n });\n\n this.report({\n index,\n model,\n attempt,\n usage,\n outcome: fallback ? \"fallback\" : outcomeOf(failure.error),\n error: failure.error,\n });\n\n if (fallback) {\n if (usage) billed = addUsage(billed ?? emptyUsage(), usage);\n continue;\n }\n\n // Final: say what this leg said, in its order, and close the call.\n let sawError = false;\n let closingFinish: Extract<ProviderEvent, { type: \"finish\" }> | undefined;\n for (const event of held) {\n if (event.type === \"finish\") {\n closingFinish = event;\n continue;\n }\n if (event.type === \"error\") sawError = true;\n yield event;\n }\n if (!sawError && failure.error.code !== \"aborted\") {\n yield {\n type: \"error\",\n error: failure.error,\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n ...(failure.requestId !== undefined ? { requestId: failure.requestId } : {}),\n };\n }\n yield closing({\n type: \"finish\",\n reason: failure.error.code === \"aborted\" ? \"aborted\" : (closingFinish?.reason ?? \"error\"),\n usage: usage ?? emptyUsage(),\n });\n return;\n }\n }\n\n private shouldFallBack(error: AgentError, failure: FallbackFailure): boolean {\n const decide = this.options.fallbackOn ?? ((e: AgentError) => e.retryable);\n try {\n return decide(error, failure);\n } catch {\n return false;\n }\n }\n\n private report(report: FallbackUsage): void {\n if (report.usage === undefined) delete report.usage;\n try {\n this.options.onUsage?.(report);\n } catch {\n // See `FallbackOptions.onUsage`.\n }\n }\n}\n\nfunction outcomeOf(error: AgentError): FallbackUsage[\"outcome\"] {\n return error.code === \"aborted\" ? \"aborted\" : \"failed\";\n}\n\nfunction intersect(all: ProviderCapabilities[]): ProviderCapabilities {\n return {\n reasoning: all.every((c) => c.reasoning),\n structuredOutput: all.every((c) => c.structuredOutput),\n fileInput: all.every((c) => c.fileInput),\n parallelToolCalls: all.every((c) => c.parallelToolCalls),\n toolSearch: all.every((c) => c.toolSearch),\n };\n}\n\nfunction withDeadline<T>(promise: Promise<T>, ms: number): Promise<T | typeof TIMED_OUT> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), ms);\n });\n return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));\n}\n\n// --- evalChain ------------------------------------------------------------\n\nexport type EvalChainResult<T> = {\n index: number;\n model: string;\n /** One per sample that resolved, in sample order. */\n results: T[];\n /** One per sample that threw, with the sample number it came from. */\n errors: { sample: number; error: unknown }[];\n};\n\n/**\n * Runs `fixture` against every leg on its own — no fallback between them —\n * `samples` times each, and returns the outcomes per leg. For comparing the\n * models in a chain before reordering it: the fixture builds an `Agent` (or\n * calls `generate()`) with the provider it is handed and returns whatever is\n * worth comparing.\n *\n * Legs run one after another and samples in sequence, so a rate limit on one\n * leg does not skew another's numbers.\n */\nexport async function evalChain<T>(\n chain: FallbackProvider,\n fixture: (provider: AgentProvider, context: { index: number; sample: number }) => Promise<T>,\n options: { samples?: number } = {},\n): Promise<EvalChainResult<T>[]> {\n const samples = options.samples ?? 1;\n if (!Number.isInteger(samples) || samples < 1) {\n throw new RangeError(`evalChain: samples must be a positive integer, got ${samples}.`);\n }\n const out: EvalChainResult<T>[] = [];\n for (let index = 0; index < chain.entries.length; index++) {\n const provider = chain.leg(index);\n const result: EvalChainResult<T> = { index, model: provider.model, results: [], errors: [] };\n for (let sample = 0; sample < samples; sample++) {\n try {\n result.results.push(await fixture(provider, { index, sample }));\n } catch (error) {\n result.errors.push({ sample, error });\n }\n }\n out.push(result);\n }\n return out;\n}\n",
24
+ "import type { ReasoningEffort } from \"./Agent\";\nimport {\n responsesEndpoint,\n streamResponses,\n uploadFile,\n type ResponsesEndpoint,\n} from \"./providers/call\";\nimport { capabilitiesForModel } from \"./providers/capabilities\";\nimport {\n azureTarget,\n openAITarget,\n type AzureConfig,\n type ProviderConfig,\n} from \"./providers/endpoints\";\nimport { normalizeProviderError } from \"./providers/errors\";\nimport { sentFiles } from \"./providers/fileRejection\";\nimport { buildResponsesRequest } from \"./providers/request\";\nimport type { JSONSchema } from \"./Schema\";\nimport type { AgentError, AgentMessage, FinishReason, Usage } from \"./types\";\n\n/**\n * A provider makes one model call. It does not run the tool loop.\n *\n * The split matters: approvals, `maxSteps`, deferred tools, skill loading and\n * persistence are all provider-independent, and putting them in the provider\n * would mean writing them again for the second provider. So the provider's\n * whole job is to translate gemi's messages into a request, and the response\n * stream back into `ProviderEvent`s. Everything above that lives in `Agent`.\n *\n * v1 targets OpenAI's Responses API — native reasoning items and strict\n * structured output without reassembling them by hand. The interface is kept\n * free of anything Responses-specific so a Chat Completions provider (for older\n * Azure deployments and OpenAI-compatible gateways) can be added later without\n * touching Agent, Controller or the client.\n */\n\n/** What a provider will actually honour, so `Agent` can drop the rest rather\n * than have a request rejected at runtime. */\nexport type ProviderCapabilities = {\n reasoning: boolean;\n structuredOutput: boolean;\n fileInput: boolean;\n parallelToolCalls: boolean;\n /**\n * Tool search, and with it deferred loading. Only recent models have it, so a\n * provider that answers `false` is sent every schema inline and the agent\n * runs identically — deferral is a token optimization, and an optimization\n * that changed behaviour when unavailable would not be one.\n */\n toolSearch: boolean;\n};\n\n/** A tool as the model is shown it: schema only, no implementation. */\nexport type ProviderToolSpec = {\n name: string;\n description: string;\n parameters: JSONSchema;\n strict: boolean;\n /** `defer_loading`: send the name and description, withhold the schema until\n * the model searches for it. Ignored when `capabilities.toolSearch` is\n * false. */\n deferred?: boolean;\n};\n\n/** Tools grouped for search. Flattened back to a list by a provider without\n * tool search, since the grouping exists to be searched. */\nexport type ProviderToolNamespace = {\n name: string;\n description: string;\n tools: ProviderToolSpec[];\n};\n\nexport interface ProviderStreamParams {\n messages: AgentMessage[];\n systemPrompt?: string;\n tools?: (ProviderToolSpec | ProviderToolNamespace)[];\n /** Set when the agent declares an `output` schema; the provider turns it into\n * whatever its own strict-JSON parameter is. `strict` comes from the schema —\n * false when it contains an `s.json()` node, which strict mode cannot\n * express — and is required rather than defaulted so that a new caller has to\n * answer it instead of inheriting a 400. */\n output?: { name: string; schema: JSONSchema; strict: boolean };\n /** Optional: silently dropped by a provider whose `capabilities.reasoning`\n * is false, since a model that cannot reason should not fail a request. */\n reasoning?: ReasoningEffort;\n temperature?: number;\n maxOutputTokens?: number;\n signal?: AbortSignal;\n}\n\n/**\n * The events of a single model call. Deliberately smaller than\n * `AgentStreamEvent`: no run, message, tool-result or approval events, because\n * a provider knows about none of those.\n */\nexport type ProviderEvent =\n | { type: \"text-delta\"; delta: string }\n | { type: \"reasoning-delta\"; delta: string; id?: string }\n /** Arguments arrive as JSON fragments; the provider passes them through and\n * `Agent` assembles and validates against the tool's schema. */\n | {\n type: \"tool-call-delta\";\n toolCallId: string;\n name: string;\n argsDelta: string;\n namespace?: string;\n }\n /**\n * `name` IS FLAT AND STAYS FLAT. This was an open question and the API has\n * answered it: a call to a function that lives inside a namespace comes back\n * as `{name: \"getOrder\", namespace: \"crm\"}`, not as `\"crm.getOrder\"` —\n * recorded in `providers/__fixtures__/openai-tool-search.sse` and pinned by\n * a test that reads that file. So `name` is already the key `Agent`'s tool\n * registry is built on, which is what makes tool names having to be globally\n * unique within an agent (see `ToolNamespace`) the right rule rather than an\n * inconvenience.\n *\n * `namespace` is carried beside it, absent for a tool that was listed bare.\n * It is provenance, not identity: it says which group the model chose to\n * look in, which is worth recording next to the call and is worthless for\n * finding the tool. Folding it into `name` would make a name that is\n * sometimes qualified and sometimes not, and nothing could match on that.\n */\n | { type: \"tool-call\"; toolCallId: string; name: string; args: string; namespace?: string }\n /**\n * The model went looking for a deferred tool and pulled its schema in. Worth\n * surfacing rather than swallowing: it is a step the user paid for, and the\n * pause before it is otherwise unexplained.\n *\n * TWO FIELDS, not one. `loaded` is the function names — `[\"listOrders\",\n * \"getOrder\"]` — and `namespaces` is the groups they came out of —\n * `[\"crm\"]`. Search results arrive as a tree of namespaces containing\n * functions, so a single flat list has to pick one level and throw the other\n * away, and both levels are worth saying: \"searched crm, loaded getOrder\"\n * reads better than either half, and the group is the thing the model\n * actually chose between.\n *\n * `namespaces` is required rather than optional because the parser always\n * knows the answer, and an optional field would let a future provider forget\n * to fill it in silently. Empty means the search returned bare functions.\n */\n | { type: \"tool-search\"; loaded: string[]; namespaces: string[] }\n | { type: \"output-delta\"; delta: string }\n /**\n * `model` is the model the vendor says produced the response (`response.model`\n * on the Responses API), which is not always the one asked for: an Azure\n * deployment name answers with the model behind it, and an alias like\n * `gpt-5.4` with a dated snapshot. Absent when the vendor did not say — a\n * request that failed before any response, or a provider that does not know.\n * Optional so a custom provider need not fill it in (#741).\n */\n | { type: \"finish\"; reason: FinishReason; usage: Usage; model?: string }\n /**\n * `status` and `requestId` describe the HTTP response the error came from,\n * when there was one. They are for the server's record of the run\n * (`AgentRunResult.error`) and are never written to a client frame; leave\n * them out for an error that was not a response.\n */\n /**\n * The provider refused a stored file (`fileId` is the provider's id) and the\n * call was sent again with a note in the file's place, so the turn goes on.\n * `Agent` marks the stored `FilePart` `providerRejected`, which makes later\n * requests send the note instead of the id — otherwise the same refusal\n * costs a failed request on every turn of the thread (#684). `message` is\n * the provider's, for the log. A provider that never retries need not send\n * this; `Agent` treats its absence as nothing having been rejected.\n */\n | { type: \"file-rejected\"; fileId: string; message: string; status?: number; requestId?: string }\n | { type: \"error\"; error: AgentError; status?: number; requestId?: string };\n\nexport type ProviderStream = AsyncIterable<ProviderEvent>;\n\n/**\n * Re-exported rather than declared here. What these configure is the *vendor*,\n * not the Responses API, and the images path resolves the same host, credential\n * and api-version from the same fields — see `providers/endpoints.ts` for why\n * that resolution lives in one place and what happens when it does not.\n */\nexport type { AzureConfig, ProviderConfig } from \"./providers/endpoints\";\n\nexport abstract class AgentProvider {\n abstract readonly model: string;\n abstract readonly capabilities: ProviderCapabilities;\n\n /** The model ids this provider knows about — for autocomplete only; any\n * string is still accepted, because a new model must not require a gemi\n * release to use. */\n static models(): readonly string[] {\n return [];\n }\n\n abstract stream(params: ProviderStreamParams): ProviderStream;\n\n /**\n * Uploads a file and returns the id a `FilePart` carries. Message history\n * therefore holds provider file ids, which is the trade for getting vision\n * and PDF input without gemi owning a storage story in v1.\n */\n abstract upload(file: File): Promise<string>;\n\n /**\n * Maps a provider's error body onto the normalized codes, so an app can\n * branch on `rate_limited` without knowing whose rate limit it was.\n *\n * Shared rather than abstract-in-practice: Azure answers the same error\n * envelope as OpenAI, and the one place it differs — the content filter's\n * code, buried in `innererror` — is handled by reading both.\n */\n normalizeError(error: unknown): AgentError {\n return normalizeProviderError(error);\n }\n}\n\n/**\n * Autocomplete, not a gate. Every id here was confirmed present in\n * `GET https://api.openai.com/v1/models`; any other string is still accepted,\n * because a model released next Tuesday must not need a gemi release to use —\n * see `capabilitiesForModel` for what an unrecognized id is assumed to do.\n *\n * Ordered newest first, and deliberately short. `/v1/models` answers with\n * ninety-odd chat ids once the dated snapshots and the `-codex`, `-pro`,\n * `-chat-latest`, `-search-api` and `-nano` variants are counted; a list that\n * tried to be complete would be stale within the month and would bury the\n * handful of names anyone actually types. Snapshot-pinned ids\n * (`gpt-5.4-2026-03-05`) are left out for the same reason and work identically.\n *\n * The Azure provider returns this same list, which is a small lie it has always\n * told: a resource serves the deployments someone created, not the catalogue.\n * `AzureConfig.deployment` is the escape hatch, and an unrecognized deployment\n * name lands on the same capable default as an unrecognized model.\n */\nconst OPENAI_MODELS = [\n \"gpt-5.5\",\n \"gpt-5.4\",\n \"gpt-5.4-mini\",\n \"gpt-5.4-nano\",\n \"gpt-5.2\",\n \"gpt-5.1\",\n \"gpt-5\",\n \"gpt-5-mini\",\n \"gpt-5-nano\",\n \"gpt-4.1\",\n \"gpt-4.1-mini\",\n \"gpt-4.1-nano\",\n \"gpt-4o\",\n \"gpt-4o-mini\",\n \"o4-mini\",\n \"o3\",\n \"o3-mini\",\n] as const;\n\nexport class OpenAIProvider extends AgentProvider {\n readonly model: string;\n readonly capabilities: ProviderCapabilities;\n protected readonly config: ProviderConfig;\n\n constructor(model: string, config: ProviderConfig = {}) {\n super();\n this.model = model;\n this.capabilities = capabilitiesForModel(model);\n this.config = config;\n }\n\n /** Config defaults come from gemi's config (`ai.openai`), so an app that has\n * set `OPENAI_API_KEY` writes only the model name. */\n static model(model: string, config?: ProviderConfig): OpenAIProvider {\n return new OpenAIProvider(model, config);\n }\n\n static models(): readonly string[] {\n return OPENAI_MODELS;\n }\n\n stream(params: ProviderStreamParams): ProviderStream {\n const body = buildResponsesRequest(params, {\n model: this.model,\n capabilities: this.capabilities,\n });\n return streamResponses(this.endpoint(), body, {\n signal: params.signal,\n // The request carries the schema whenever the agent declared one, so the\n // parser has to read the answer as one too — a model that ignored the\n // parameter answers 400, not prose.\n structuredOutput: Boolean(params.output),\n files: sentFiles(params.messages),\n });\n }\n\n upload(file: File): Promise<string> {\n return uploadFile(this.endpoint(), file);\n }\n\n protected endpoint(): ResponsesEndpoint {\n return responsesEndpoint(openAITarget(this.config));\n }\n}\n\n/**\n * Its own class rather than a flag on `OpenAIProvider`: Azure names the\n * deployment rather than the model, pins an api-version, authenticates with an\n * `api-key` header or an Entra token, and puts the resource in the host. One\n * class carrying both shapes means every field is conditionally meaningful.\n *\n * (It used to put the deployment in the URL as well. It does not: the Responses\n * API serves no such path — see `azureBase` for the measurements.)\n *\n * The API stays symmetrical — `.model()`, not `.deployment()`. Apps name a\n * model; mapping that onto a deployment is this class's problem, and an app\n * that named its deployment differently overrides it in config.\n */\nexport class AzureOpenAIProvider extends AgentProvider {\n readonly model: string;\n readonly capabilities: ProviderCapabilities;\n protected readonly config: AzureConfig;\n\n constructor(model: string, config: AzureConfig = {}) {\n super();\n this.model = model;\n // Read off the model, not the deployment: a deployment called `prod` says\n // nothing, and an unrecognized name lands on the all-capabilities default\n // anyway. See `capabilitiesForModel`.\n this.capabilities = capabilitiesForModel(model);\n this.config = config;\n }\n\n /** Defaults from gemi's config (`ai.azure`). */\n static model(model: string, config?: AzureConfig): AzureOpenAIProvider {\n return new AzureOpenAIProvider(model, config);\n }\n\n static models(): readonly string[] {\n return OPENAI_MODELS;\n }\n\n stream(params: ProviderStreamParams): ProviderStream {\n const body = buildResponsesRequest(params, {\n model: this.deployment(),\n capabilities: this.capabilities,\n });\n return streamResponses(this.endpoint(), body, {\n signal: params.signal,\n // The request carries the schema whenever the agent declared one, so the\n // parser has to read the answer as one too — a model that ignored the\n // parameter answers 400, not prose.\n structuredOutput: Boolean(params.output),\n files: sentFiles(params.messages),\n });\n }\n\n /** `assistants`, not OpenAI's `user_data`: Azure's Responses API refuses a\n * `user_data` id outright (#682). See `UploadPurpose`. */\n upload(file: File): Promise<string> {\n return uploadFile(this.endpoint(), file, \"assistants\");\n }\n\n protected deployment(): string {\n return this.config.deployment ?? this.model;\n }\n\n protected endpoint(): ResponsesEndpoint {\n return responsesEndpoint(azureTarget(this.config));\n }\n}\n",
25
+ "/**\n * Where a `FallbackProvider` keeps its circuit state (#742): which legs have\n * failed enough in a row to be skipped for a while.\n *\n * IN-PROCESS BY DEFAULT, AND ON PURPOSE. The breaker exists so one process\n * stops paying a dead primary's timeout on every call; each instance learning\n * that on its own costs `failures` slow calls per instance per cool-down, which\n * is small next to what it saves. Sharing the state would save those few calls\n * at the price of a store round trip on every model call, and the store gemi\n * already shares between instances (`LockStore`, #738/#739) cannot express this\n * model without approximating it: it has no way to read or reset a counter, so\n * \"N failures in a row, reset by a success\" becomes \"N failures in a window\",\n * and the single half-open probe becomes every instance probing at once. An\n * app that wants shared state implements this interface over its own store.\n *\n * ### The model\n *\n * A key is **closed** until `policy.failures` failures are recorded in a row,\n * then **open** for `policy.cooldownMs`: `allow` says no. After the cool-down\n * the next `allow` lets ONE call through as a probe (half-open) and says no to\n * everyone else while it runs. The probe's success closes the circuit, its\n * failure opens it again for another cool-down, and a probe that never reports\n * back (its caller stopped reading) is given up on after `cooldownMs`.\n */\nexport type CircuitPolicy = {\n /** Failures in a row that open the circuit. */\n failures: number;\n /** How long an open circuit stays open, in milliseconds. */\n cooldownMs: number;\n};\n\n/**\n * What a leg's call came to, for the breaker:\n *\n * - `success`: the leg answered, or started to (output reached the consumer).\n * - `failure`: it failed in a way the chain falls back on.\n * - `none`: neither says anything about the leg's health — the user aborted,\n * or the request was refused for a reason any model would refuse it for.\n */\nexport type CircuitOutcome = \"success\" | \"failure\" | \"none\";\n\nexport type CircuitState = \"closed\" | \"open\" | \"half-open\";\n\nexport interface CircuitStore {\n /** Whether a call may go to `key` now. A `true` in the half-open state makes\n * that call the probe, so call it only when the leg will then be tried. */\n allow(key: string, policy: CircuitPolicy): boolean | Promise<boolean>;\n /** Records how an allowed call went. Resolves to the state the key moved to,\n * or `undefined` when it did not change. */\n record(\n key: string,\n outcome: CircuitOutcome,\n policy: CircuitPolicy,\n ): CircuitState | undefined | Promise<CircuitState | undefined>;\n}\n\ntype Entry = {\n failures: number;\n /** Set while open or half-open: when the cool-down ends. */\n openUntil?: number;\n /** Set while a half-open probe is out: when it is given up on. */\n probeUntil?: number;\n};\n\n/** The default `CircuitStore`: a map in this process. */\nexport class MemoryCircuitStore implements CircuitStore {\n private readonly entries = new Map<string, Entry>();\n\n constructor(private readonly now: () => number = Date.now) {}\n\n allow(key: string, policy: CircuitPolicy): boolean {\n const entry = this.entries.get(key);\n if (entry?.openUntil === undefined) return true;\n const now = this.now();\n if (now < entry.openUntil) return false;\n if (entry.probeUntil !== undefined && now < entry.probeUntil) return false;\n entry.probeUntil = now + policy.cooldownMs;\n return true;\n }\n\n record(key: string, outcome: CircuitOutcome, policy: CircuitPolicy): CircuitState | undefined {\n const entry = this.entries.get(key) ?? { failures: 0 };\n const wasOpen = entry.openUntil !== undefined;\n\n if (outcome === \"success\") {\n this.entries.delete(key);\n return wasOpen ? \"closed\" : undefined;\n }\n if (outcome === \"none\") {\n // A probe that learned nothing frees the slot for the next call.\n delete entry.probeUntil;\n return undefined;\n }\n\n entry.failures += 1;\n this.entries.set(key, entry);\n // Half-open: one failure is enough. Closed: `failures` in a row.\n if (wasOpen || entry.failures >= policy.failures) {\n entry.openUntil = this.now() + policy.cooldownMs;\n delete entry.probeUntil;\n return wasOpen ? undefined : \"open\";\n }\n return undefined;\n }\n\n /** The state of `key` right now, for tests and dashboards. */\n state(key: string): CircuitState {\n const entry = this.entries.get(key);\n if (entry?.openUntil === undefined) return \"closed\";\n return this.now() < entry.openUntil ? \"open\" : \"half-open\";\n }\n}\n",
26
+ "import type { ReasoningEffort } from \"./Agent\";\nimport {\n AgentProvider,\n type ProviderCapabilities,\n type ProviderEvent,\n type ProviderStream,\n type ProviderStreamParams,\n} from \"./AgentProvider\";\nimport {\n type CircuitOutcome,\n type CircuitPolicy,\n type CircuitState,\n type CircuitStore,\n MemoryCircuitStore,\n} from \"./CircuitStore\";\nimport { httpErrorDetail } from \"./providers/errors\";\nimport { addUsage, emptyUsage } from \"./runtime\";\nimport type { AgentError, Usage } from \"./types\";\n\n/**\n * An ordered chain of providers (#666): the primary, then the fallbacks.\n *\n * It is a provider itself, so `Agent`, `generate()` and the controller take it\n * where they take any other, and nothing above the provider learns there is a\n * chain. That is the point: the alternative was a `providers: [...]` option on\n * `Agent`, and every place that reads `config.provider` would have had to\n * answer \"which one?\".\n *\n * THE ONE RULE THAT SHAPES EVERYTHING: no fallback once output has reached the\n * consumer. A leg that has streamed a word, a reasoning summary or a tool call\n * has been seen — by the user, and by `Agent`, which already appended it to the\n * message — and a second model starting over would put two answers in one\n * message. So a leg's events are held back until its first content event, and\n * from that event on the leg is committed and a later error is final.\n *\n * Reasoning commits too, not only text, tool calls and structured output. It is\n * streamed to the client like text is, and a reasoning item is tied to the\n * deployment that wrote it: sending one leg's item back to another on the next\n * turn is a request the vendor may refuse. Holding reasoning back until the\n * answer starts would hide minutes of \"thinking\" from the UI on every call.\n */\n\n/** One leg of a chain. */\nexport type FallbackEntry = {\n provider: AgentProvider;\n /**\n * How long this leg has to produce its FIRST event, in milliseconds. Past\n * that it is abandoned (its request aborted) and the next leg is tried. Once\n * any event has arrived, this deadline is off and the leg's own request\n * timeout applies — a slow answer that has started is not a dead one.\n *\n * Omitted: no deadline of the chain's own.\n */\n timeoutMs?: number;\n /**\n * Overrides `ProviderStreamParams.reasoning` for this leg. Models in one\n * chain take different effort values (#658), so the agent's single setting\n * is right for at most one of them. Dropped, as usual, by a provider whose\n * `capabilities.reasoning` is false.\n */\n reasoning?: ReasoningEffort;\n /**\n * The name this leg's circuit is kept under (#742). Default: the provider's\n * `model`. Set it when two legs share a model name (one model on two Azure\n * resources), or to share a leg's circuit between chains on purpose.\n */\n circuitKey?: string;\n};\n\n/** What `fallbackOn` is told besides the normalized error. */\nexport type FallbackFailure = {\n /** The leg's position in the chain this provider was built with (after `from()`). */\n index: number;\n model: string;\n /** The HTTP status of the failed response, when there was one. */\n status?: number;\n requestId?: string;\n /** True when the leg produced nothing within its `timeoutMs`. */\n timedOut: boolean;\n};\n\n/** One leg's report, for `onUsage`. Called once per leg that was tried. */\nexport type FallbackUsage = {\n /** The leg's position in this provider's chain. */\n index: number;\n /** The leg's configured model. */\n model: string;\n /**\n * The model the vendor says answered (`finish.model`): the snapshot behind an\n * alias, or the model behind an Azure deployment name. Absent when the leg\n * never got that far or its provider does not report it (#741).\n */\n responseModel?: string;\n /** 1 for the first leg tried in this call, 2 for the next one tried, and so\n * on. A leg skipped by an open circuit is not tried and not counted. */\n attempt: number;\n /**\n * What the leg reported, including a failed leg that billed tokens (a\n * content filter does). Absent when the leg never reported usage: it timed\n * out, threw, or was abandoned.\n */\n usage?: Usage;\n /** `ok`: this leg answered (the call may still have failed after output). */\n outcome: \"ok\" | \"fallback\" | \"failed\" | \"aborted\";\n error?: AgentError;\n};\n\nexport type FallbackOptions = {\n /**\n * Whether a failure moves on to the next leg. Default: `error.retryable`,\n * which `normalizeError` sets for a 429 that is not a spent quota, a 5xx, a\n * 408/409, a timeout and a network failure — and not for a request that would\n * fail the same way on any model (context length, a bad tool schema).\n *\n * Never asked about the last leg, about a user abort, or about a failure\n * after output.\n */\n fallbackOn?: (error: AgentError, failure: FallbackFailure) => boolean;\n /** Per-leg usage. An exception thrown here is swallowed: accounting must not\n * fail the call it is accounting for. */\n onUsage?: (report: FallbackUsage) => void;\n /**\n * Skip a leg that keeps failing (#742). Off when omitted; `{}` turns it on\n * with the defaults. See `FallbackCircuit`.\n */\n circuit?: FallbackCircuit;\n};\n\n/**\n * A circuit breaker per leg. A leg whose calls fail `failures` times in a row,\n * in a way the chain falls back on (a timeout, a 5xx, a 429 — whatever\n * `fallbackOn` says yes to), is skipped for `cooldownMs`, so a dead primary\n * stops costing its `timeoutMs` on every call. After the cool-down one call\n * tries it again: an answer closes the circuit, a failure opens it for another\n * cool-down.\n *\n * The last leg is never skipped, so a chain always tries something, and its\n * failures are not counted (it is never asked `fallbackOn`). A leg that started\n * answering counts as a success even if it failed later: it is up.\n */\nexport type FallbackCircuit = {\n /** Failures in a row that open a leg's circuit. Default 3. */\n failures?: number;\n /** How long an open circuit skips its leg, in milliseconds. Default 30 000. */\n cooldownMs?: number;\n /**\n * Where the state lives. Default: a `MemoryCircuitStore` made for this chain,\n * shared with the chains `from()` and `leg()` derive from it, and with no\n * other — so a circuit is per process. See `CircuitStore` for why.\n */\n store?: CircuitStore;\n /** Told when a leg's circuit opens or closes. Exceptions are swallowed. */\n onStateChange?: (change: FallbackCircuitChange) => void;\n};\n\nexport type FallbackCircuitChange = {\n index: number;\n model: string;\n key: string;\n state: CircuitState;\n};\n\n/** Every event that is content a consumer shows or stores. The first one commits its leg. */\nfunction isContent(event: ProviderEvent): boolean {\n switch (event.type) {\n case \"text-delta\":\n case \"reasoning-delta\":\n case \"tool-call-delta\":\n case \"tool-call\":\n case \"tool-search\":\n case \"output-delta\":\n return true;\n default:\n return false;\n }\n}\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\nexport class FallbackProvider extends AgentProvider {\n /** The first leg's model: the one the chain is named after in logs. */\n readonly model: string;\n /**\n * The intersection of every leg's capabilities. A tool or a structured output\n * one leg cannot handle would otherwise be found the day the primary is down,\n * which is the worst day to find it. `Agent` drops what is false here, so a\n * chain behaves the same whichever leg answers.\n */\n readonly capabilities: ProviderCapabilities;\n readonly entries: readonly FallbackEntry[];\n private readonly options: FallbackOptions;\n private readonly circuit:\n | {\n policy: CircuitPolicy;\n store: CircuitStore;\n onStateChange?: (change: FallbackCircuitChange) => void;\n }\n | undefined;\n\n constructor(entries: readonly FallbackEntry[], options: FallbackOptions = {}) {\n super();\n if (entries.length === 0) {\n throw new Error(\"FallbackProvider needs at least one provider.\");\n }\n for (const entry of entries) {\n if (entry.timeoutMs !== undefined && !(entry.timeoutMs > 0)) {\n throw new Error(\n `FallbackProvider: timeoutMs for ${entry.provider.model} must be a positive number, got ${entry.timeoutMs}.`,\n );\n }\n }\n this.entries = [...entries];\n const circuit = options.circuit;\n if (circuit) {\n const failures = circuit.failures ?? 3;\n const cooldownMs = circuit.cooldownMs ?? 30_000;\n if (!Number.isInteger(failures) || failures < 1) {\n throw new Error(\n `FallbackProvider: circuit.failures must be a positive integer, got ${failures}.`,\n );\n }\n if (!(cooldownMs > 0)) {\n throw new Error(\n `FallbackProvider: circuit.cooldownMs must be a positive number, got ${cooldownMs}.`,\n );\n }\n const keys = new Set<string>();\n for (const entry of entries) {\n const key = circuitKey(entry);\n if (keys.has(key)) {\n throw new Error(\n `FallbackProvider: two legs share the circuit key \"${key}\". ` +\n \"Give one of them a `circuitKey`.\",\n );\n }\n keys.add(key);\n }\n // Made here, once, and written back into the options, so `from()` and\n // `leg()` — which pass the options on — share it rather than each\n // starting with every circuit closed.\n const store = circuit.store ?? new MemoryCircuitStore();\n this.options = { ...options, circuit: { ...circuit, store } };\n this.circuit = {\n policy: { failures, cooldownMs },\n store,\n ...(circuit.onStateChange ? { onStateChange: circuit.onStateChange } : {}),\n };\n } else {\n this.options = options;\n this.circuit = undefined;\n }\n this.model = entries[0]!.provider.model;\n this.capabilities = intersect(entries.map((entry) => entry.provider.capabilities));\n }\n\n static chain(entries: readonly FallbackEntry[], options?: FallbackOptions): FallbackProvider {\n return new FallbackProvider(entries, options);\n }\n\n /**\n * The same chain entered at `index`. For work that should never reach the\n * primary — a cheap text task on an expensive chain — without a second chain\n * to keep in step. Same options; `index` in reports counts from the new start.\n */\n from(index: number): FallbackProvider {\n if (!Number.isInteger(index) || index < 0 || index >= this.entries.length) {\n throw new RangeError(\n `FallbackProvider.from(${index}): the chain has ${this.entries.length} entries.`,\n );\n }\n return new FallbackProvider(this.entries.slice(index), this.options);\n }\n\n /** The leg at `index` on its own, with its reasoning and timeout. What `evalChain` runs. */\n leg(index: number): FallbackProvider {\n const entry = this.from(index).entries[0]!;\n return new FallbackProvider([entry], this.options);\n }\n\n /**\n * To the first leg only. A provider's file id is not portable (#443): an id\n * from one OpenAI account or Azure resource means nothing to another, so\n * uploading to every leg would cost N uploads for ids nobody could choose\n * between. Legs on the same Azure resource share its files, which is the\n * common chain; a chain across accounts should keep files out of the\n * fallback path or store them with gemi.\n */\n upload(file: File): Promise<string> {\n return this.entries[0]!.provider.upload(file);\n }\n\n normalizeError(error: unknown): AgentError {\n return this.entries[0]!.provider.normalizeError(error);\n }\n\n stream(params: ProviderStreamParams): ProviderStream {\n return this.run(params);\n }\n\n private async *run(params: ProviderStreamParams): AsyncGenerator<ProviderEvent> {\n // What the abandoned legs billed. Added to the closing `finish`, so the\n // run's usage is what the call cost rather than what the winning leg cost.\n let billed: Usage | undefined;\n const outer = params.signal;\n\n let attempt = 0;\n\n for (let index = 0; index < this.entries.length; index++) {\n const entry = this.entries[index]!;\n const last = index === this.entries.length - 1;\n const model = entry.provider.model;\n\n // An open circuit skips the leg without a request. Never the last one.\n if (this.circuit && !last && !(await this.allow(entry))) continue;\n attempt += 1;\n // What this leg's call says about its health, told to the breaker once.\n // Before anything is yielded for it, so a consumer that stops reading\n // does not leave a half-open probe hanging until it is given up on.\n let told = false;\n const tell = async (outcome: CircuitOutcome) => {\n if (told) return;\n told = true;\n await this.record(index, entry, outcome);\n };\n\n const leg = new AbortController();\n const onAbort = () => leg.abort(outer?.reason);\n if (outer?.aborted) leg.abort(outer.reason);\n else outer?.addEventListener(\"abort\", onAbort, { once: true });\n\n const held: ProviderEvent[] = [];\n let committed = false;\n let finished = false;\n let usage: Usage | undefined;\n let responseModel: string | undefined;\n let failure: { error: AgentError; status?: number; requestId?: string } | undefined;\n let timedOut = false;\n let iterator: AsyncIterator<ProviderEvent> | undefined;\n let done = false;\n\n const closing = (event: Extract<ProviderEvent, { type: \"finish\" }>) => {\n const merged = billed ? addUsage(addUsage(emptyUsage(), billed), event.usage) : event.usage;\n billed = undefined;\n return { ...event, usage: merged };\n };\n\n try {\n iterator = entry.provider\n .stream({\n ...params,\n ...(entry.reasoning !== undefined ? { reasoning: entry.reasoning } : {}),\n signal: leg.signal,\n })\n [Symbol.asyncIterator]();\n\n let first = true;\n for (;;) {\n const next =\n first && entry.timeoutMs !== undefined\n ? await withDeadline(iterator.next(), entry.timeoutMs)\n : await iterator.next();\n if (next === TIMED_OUT) {\n timedOut = true;\n failure = {\n error: {\n code: \"provider_error\",\n message: `${model} sent nothing within ${entry.timeoutMs}ms.`,\n retryable: true,\n },\n };\n break;\n }\n first = false;\n if (next.done) {\n done = true;\n break;\n }\n const event = next.value;\n\n if (event.type === \"finish\" && event.model) responseModel = event.model;\n\n if (committed) {\n if (event.type === \"finish\") {\n usage = addUsage(usage ?? emptyUsage(), event.usage);\n finished = true;\n yield closing(event);\n } else {\n if (event.type === \"error\") failure = { error: event.error };\n yield event;\n }\n continue;\n }\n\n if (isContent(event)) {\n committed = true;\n await tell(\"success\");\n yield* held.splice(0);\n yield event;\n continue;\n }\n\n if (event.type === \"error\") {\n failure = {\n error: event.error,\n ...(event.status !== undefined ? { status: event.status } : {}),\n ...(event.requestId !== undefined ? { requestId: event.requestId } : {}),\n };\n } else if (event.type === \"finish\") {\n usage = addUsage(usage ?? emptyUsage(), event.usage);\n if (event.reason === \"error\" && !failure) {\n failure = {\n error: {\n code: \"provider_error\",\n message: `${model} ended the call with an error and did not say which.`,\n retryable: false,\n },\n };\n }\n }\n held.push(event);\n }\n } catch (thrown) {\n // A custom provider is allowed to throw rather than send an error event;\n // the built-in ones never do. It reads the same either way.\n const error = entry.provider.normalizeError(thrown);\n if (committed) {\n if (error.code !== \"aborted\") {\n yield { type: \"error\", error, ...httpErrorDetail(thrown) };\n }\n this.report({\n index,\n model,\n responseModel,\n attempt,\n usage,\n outcome: outcomeOf(error),\n error,\n });\n yield closing({\n type: \"finish\",\n reason: error.code === \"aborted\" ? \"aborted\" : \"error\",\n usage: emptyUsage(),\n ...(responseModel ? { model: responseModel } : {}),\n });\n return;\n }\n failure = { error, ...httpErrorDetail(thrown) };\n } finally {\n outer?.removeEventListener(\"abort\", onAbort);\n // Abandoned (timed out, fell back, or the consumer stopped reading):\n // stop its request and let it go without waiting for it to agree.\n if (!done) {\n leg.abort();\n void iterator?.return?.()?.catch(() => {});\n }\n }\n\n if (committed) {\n if (!finished && billed) {\n // The leg ended without a closing frame; the abandoned legs' cost\n // still has to be told to someone.\n yield { type: \"finish\", reason: failure ? \"error\" : \"stop\", usage: billed };\n billed = undefined;\n }\n this.report({\n index,\n model,\n responseModel,\n attempt,\n usage,\n outcome: failure ? outcomeOf(failure.error) : \"ok\",\n ...(failure ? { error: failure.error } : {}),\n });\n return;\n }\n\n // The consumer stopped the run. Not a failure of this leg, and certainly\n // not one to answer by asking the next model.\n if (outer?.aborted) {\n await tell(\"none\");\n this.report({ index, model, responseModel, attempt, usage, outcome: \"aborted\" });\n yield closing({\n type: \"finish\",\n reason: \"aborted\",\n usage: usage ?? emptyUsage(),\n ...(responseModel ? { model: responseModel } : {}),\n });\n return;\n }\n\n if (!failure) {\n // Answered with nothing: a finish and no content. That is an answer.\n await tell(\"success\");\n this.report({ index, model, responseModel, attempt, usage, outcome: \"ok\" });\n for (const event of held) yield event.type === \"finish\" ? closing(event) : event;\n return;\n }\n\n const fallback =\n !last &&\n failure.error.code !== \"aborted\" &&\n this.shouldFallBack(failure.error, {\n index,\n model,\n timedOut,\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n ...(failure.requestId !== undefined ? { requestId: failure.requestId } : {}),\n });\n\n // A leg's failure counts against it only when the chain moves on from\n // it: a request any model would refuse says nothing about this one. The\n // last leg is never asked, so its failures are not counted.\n await tell(fallback ? \"failure\" : \"none\");\n this.report({\n index,\n model,\n responseModel,\n attempt,\n usage,\n outcome: fallback ? \"fallback\" : outcomeOf(failure.error),\n error: failure.error,\n });\n\n if (fallback) {\n if (usage) billed = addUsage(billed ?? emptyUsage(), usage);\n continue;\n }\n\n // Final: say what this leg said, in its order, and close the call.\n let sawError = false;\n let closingFinish: Extract<ProviderEvent, { type: \"finish\" }> | undefined;\n for (const event of held) {\n if (event.type === \"finish\") {\n closingFinish = event;\n continue;\n }\n if (event.type === \"error\") sawError = true;\n yield event;\n }\n if (!sawError && failure.error.code !== \"aborted\") {\n yield {\n type: \"error\",\n error: failure.error,\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n ...(failure.requestId !== undefined ? { requestId: failure.requestId } : {}),\n };\n }\n yield closing({\n type: \"finish\",\n reason: failure.error.code === \"aborted\" ? \"aborted\" : (closingFinish?.reason ?? \"error\"),\n usage: usage ?? emptyUsage(),\n ...(responseModel ? { model: responseModel } : {}),\n });\n return;\n }\n }\n\n private async allow(entry: FallbackEntry): Promise<boolean> {\n if (!this.circuit) return true;\n try {\n return await this.circuit.store.allow(circuitKey(entry), this.circuit.policy);\n } catch {\n // A breaker that cannot be read must not stop the primary being tried.\n return true;\n }\n }\n\n private async record(index: number, entry: FallbackEntry, outcome: CircuitOutcome) {\n if (!this.circuit) return;\n const key = circuitKey(entry);\n let state: CircuitState | undefined;\n try {\n state = await this.circuit.store.record(key, outcome, this.circuit.policy);\n } catch {\n return;\n }\n if (!state) return;\n try {\n this.circuit.onStateChange?.({ index, model: entry.provider.model, key, state });\n } catch {\n // Same rule as `onUsage`.\n }\n }\n\n private shouldFallBack(error: AgentError, failure: FallbackFailure): boolean {\n const decide = this.options.fallbackOn ?? ((e: AgentError) => e.retryable);\n try {\n return decide(error, failure);\n } catch {\n return false;\n }\n }\n\n private report(report: FallbackUsage): void {\n if (report.usage === undefined) delete report.usage;\n if (report.responseModel === undefined) delete report.responseModel;\n try {\n this.options.onUsage?.(report);\n } catch {\n // See `FallbackOptions.onUsage`.\n }\n }\n}\n\nfunction circuitKey(entry: FallbackEntry): string {\n return entry.circuitKey ?? entry.provider.model;\n}\n\nfunction outcomeOf(error: AgentError): FallbackUsage[\"outcome\"] {\n return error.code === \"aborted\" ? \"aborted\" : \"failed\";\n}\n\nfunction intersect(all: ProviderCapabilities[]): ProviderCapabilities {\n return {\n reasoning: all.every((c) => c.reasoning),\n structuredOutput: all.every((c) => c.structuredOutput),\n fileInput: all.every((c) => c.fileInput),\n parallelToolCalls: all.every((c) => c.parallelToolCalls),\n toolSearch: all.every((c) => c.toolSearch),\n };\n}\n\nfunction withDeadline<T>(promise: Promise<T>, ms: number): Promise<T | typeof TIMED_OUT> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), ms);\n });\n return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));\n}\n\n// --- evalChain ------------------------------------------------------------\n\nexport type EvalChainResult<T> = {\n index: number;\n model: string;\n /** One per sample that resolved, in sample order. */\n results: T[];\n /** One per sample that threw, with the sample number it came from. */\n errors: { sample: number; error: unknown }[];\n};\n\n/**\n * Runs `fixture` against every leg on its own — no fallback between them —\n * `samples` times each, and returns the outcomes per leg. For comparing the\n * models in a chain before reordering it: the fixture builds an `Agent` (or\n * calls `generate()`) with the provider it is handed and returns whatever is\n * worth comparing.\n *\n * Legs run one after another and samples in sequence, so a rate limit on one\n * leg does not skew another's numbers.\n */\nexport async function evalChain<T>(\n chain: FallbackProvider,\n fixture: (provider: AgentProvider, context: { index: number; sample: number }) => Promise<T>,\n options: { samples?: number } = {},\n): Promise<EvalChainResult<T>[]> {\n const samples = options.samples ?? 1;\n if (!Number.isInteger(samples) || samples < 1) {\n throw new RangeError(`evalChain: samples must be a positive integer, got ${samples}.`);\n }\n const out: EvalChainResult<T>[] = [];\n for (let index = 0; index < chain.entries.length; index++) {\n const provider = chain.leg(index);\n const result: EvalChainResult<T> = { index, model: provider.model, results: [], errors: [] };\n for (let sample = 0; sample < samples; sample++) {\n try {\n result.results.push(await fixture(provider, { index, sample }));\n } catch (error) {\n result.errors.push({ sample, error });\n }\n }\n out.push(result);\n }\n return out;\n}\n",
26
27
  "import type { AgentRun } from \"../Agent\";\nimport type { LiveRuns } from \"../AgentController\";\nimport type { AgentStreamEvent, AgentStreamFrame } from \"../types\";\n\n/** Long enough that a refresh, a tab restore or a flaky mobile connection still\n * lands on the tail; short enough that a finished run is not resident for the\n * rest of the day. */\nconst DEFAULT_TTL_MS = 60 * 1000;\n\n/**\n * The oldest an entry may get, ended or not, unless its run's own time limit is\n * longer. See `MemoryLiveRuns.maxAgeMs`.\n *\n * Six times the agent's default `maxRunDurationMs`, so it never races a\n * deadline: a run that honours its limit has ended and been evicted on the\n * `ttlMs` clock long before this. What reaches it is a run that could not be\n * stopped by its deadline, e.g. one wedged in an `onMessage` that never settles.\n */\nconst DEFAULT_MAX_AGE_MS = 60 * 60 * 1000;\n\n/** The longest delay `setTimeout` keeps; past it the runtime fires in ~1ms. */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n\n/**\n * How many frames are kept per run.\n *\n * The window has to be bounded or it is a memory leak with a long fuse: a\n * server that never restarts holding every token of every conversation it ever\n * streamed.\n *\n * It was 512 on the reasoning that a reattaching client only needs seconds of\n * catch-up. That is true of the *reattaching* client and false of the one that\n * never left: a frame is roughly a token, so 512 is a four-hundred-word answer,\n * and a reader that falls behind a longer one by more than that is cut off with\n * a 410 mid-stream. On a slow connection — the case reattachment exists for —\n * that is not exotic.\n *\n * 4096 covers essentially any single answer. It is affordable because of two\n * measured facts, and it would not have been before either:\n *\n * - `drain` no longer copies the window per wake, so a reader costs the same\n * whatever the window's size. Measured at 64 readers on a 2000-frame run:\n * 1106 ms of CPU at 4096 before, 425 ms after, and 468 ms at 512 — i.e. the\n * size stopped being a term in the cost.\n * - the entries are pointers to frames the run is holding anyway, so the\n * window costs 8 bytes each, not the frame. Eight times more of them is\n * ~28 KB per run, and a thousand concurrent runs is tens of megabytes.\n *\n * Both would change if the run's own buffer ever became bounded — then this\n * window owns the frames, and its size is their size.\n */\nconst DEFAULT_MAX_FRAMES = 4096;\n\n/**\n * A cursor older than anything still buffered.\n *\n * Deliberately an error rather than \"here is the tail I still have\". A client\n * that asked for frame 12 and silently got frame 300 onwards has a transcript\n * with a hole in it and no way to know — it will render a half-message, or an\n * `awaiting-input` for a tool call it never saw. Saying so lets the client do\n * the only correct thing, which is to reload the thread from the store.\n */\nexport class FrameCursorEvictedError extends Error {\n readonly code = \"frame_cursor_evicted\";\n\n constructor(\n readonly runId: string,\n readonly requested: number,\n readonly oldest: number,\n ) {\n super(\n `Frame ${requested} of run ${runId} has been evicted; the oldest frame ` +\n `still buffered is ${oldest}. Reload the thread instead of resuming.`,\n );\n }\n}\n\n/**\n * No run under that id in *this* process.\n *\n * Which is the honest answer, and the one worth being loud about: the run may\n * well be alive on the box next door. See the note on `MemoryLiveRuns` — behind\n * a round-robin load balancer this is what a refresh hits roughly (n-1)/n of\n * the time, and an explicit miss is the difference between a bug someone finds\n * in an hour and one that presents as \"reattach sometimes does nothing\".\n */\nexport class LiveRunNotFoundError extends Error {\n readonly code = \"live_run_not_found\";\n\n constructor(readonly runId: string) {\n super(`No live run ${runId} in this process.`);\n }\n}\n\nexport type RegisterParams = {\n threadId?: string;\n /**\n * Who started the run, as an opaque key (`AgentController.runOwner` makes it\n * `user:<id>`), or `null`/absent for a run nobody in particular owns: an\n * anonymous turn, or one the server started itself (#442).\n *\n * Recorded so `attach` and `stop` can tell the caller from the owner without a\n * store round trip: a `threadId`, a `runId` and a client-minted `clientRunId`\n * are all handles a third party can come to hold, and none of them says whose\n * run it is. An owned run answers only the same key; an unowned one answers\n * whoever holds a handle, which is what every run did before this existed.\n */\n owner?: string | null;\n /**\n * The client's own name for this run, minted before the run had one.\n *\n * `runId` does not reach the client until `run-start`, and a stateless first\n * turn has no `threadId` either, so for the length of a network round trip\n * plus the provider's time to first token there is nothing for `/stop` to\n * name — which is exactly the window a user cancels in. `useChat` sends a\n * `clientRunId` with every turn it starts; recording it here is what makes\n * that window stoppable.\n */\n clientRunId?: string;\n /**\n * Called once per frame, in order, off the buffering path.\n *\n * The controller's `on*` hooks hang off this. It is a callback rather than a\n * second `run.frames()` subscription because every extra subscriber is\n * another consumer of a generator whose multi-subscriber behaviour we do not\n * own, and one pump is one thing to reason about.\n */\n onEvent?: (event: AgentStreamEvent) => void | Promise<void>;\n /** Reported failures: a hook that threw, or a run whose frame iterator did.\n * Injectable so tests can assert on it instead of reading stderr. */\n onInternalError?: (error: unknown) => void;\n /**\n * The run's own time limit (`Agent.maxRunDurationMs`), when the caller knows\n * it. The entry's age ceiling is never shorter than this plus `ttlMs`, so a\n * run allowed two hours is not cut off at `maxAgeMs`; `null` is a run with no\n * limit, and its entry has no ceiling either. Omitted, the ceiling is\n * `maxAgeMs`.\n */\n maxRunDurationMs?: number | null;\n};\n\ntype Entry = {\n run: AgentRun;\n threadId?: string;\n /** See `RegisterParams.owner`. `null` is unowned. */\n owner: string | null;\n clientRunId?: string;\n /** A contiguous window of the run's frames, oldest first. */\n frames: AgentStreamFrame[];\n lastSeq: number;\n /**\n * The lowest `seq` still obtainable, or 0 while nothing has been dropped.\n *\n * Not derivable from `frames[0].seq`, which is what this used to compare\n * against. `seq` starts at 1, so a run that has evicted nothing still has an\n * oldest frame of 1, and a cursor of 0 — the \"I have no transcript yet\"\n * cursor that `replay` itself picks for a run registered but not yet pumped —\n * read as older than the buffer. A ten-frame run in a five-hundred-frame\n * window answered a refresh with 410, which is both false and unactionable:\n * refreshing right after sending is the case `/attach` exists to serve.\n */\n lostBefore: number;\n ended: boolean;\n /**\n * Dropped from the map while its run was still going (the age ceiling).\n * Readers finish on it as they would on `ended`, and the pump stops\n * buffering frames nobody can read any more.\n */\n evicted: boolean;\n evictAt: ReturnType<typeof setTimeout> | null;\n /** The age ceiling's timer. See `maxAgeMs`. */\n expireAt: ReturnType<typeof setTimeout> | null;\n wake: Set<() => void>;\n /**\n * Bumped on every push and on the end.\n *\n * A reader cannot just park on \"wake me when something happens\": it suspends\n * at every `yield` while its consumer reads, and anything that arrives during\n * that suspension notifies an empty waiter set — so the reader parks *after*\n * the event it was waiting for and never hears another. The version it read\n * before scanning is what closes that window: if it moved, there is more to\n * scan and the wait is skipped.\n */\n version: number;\n};\n\n/**\n * The runs currently in flight in this process, and their recent frames.\n *\n * PER-PROCESS IS NOT AN IMPLEMENTATION SHORTCUT THAT A BETTER STORE FIXES. A\n * running generator lives in one process, and a second server cannot attach to\n * it — no amount of Redis moves an in-flight async iterator across a socket.\n * Reattachment therefore needs the request to land where the run is: one\n * server, sticky routing, or a proxy that forwards by `runId`. Worth saying out\n * loud, because the failure mode behind a round-robin load balancer is a\n * refresh that usually works.\n *\n * `find` and `replay` are built so that failure is an explicit miss — a 404\n * naming the run, a 410 naming the cursor — and never an SSE stream that opens,\n * says nothing and closes. An empty stream is indistinguishable from a run that\n * finished quietly, which is exactly the confusion this is supposed to avoid.\n */\nexport class MemoryLiveRuns implements LiveRuns {\n ttlMs: number;\n readonly maxFrames: number;\n /**\n * The oldest an entry may get, counted from `register`, whether or not its\n * run has ended. Default one hour; `null` turns the ceiling off.\n *\n * Eviction normally runs on the `ttlMs` clock, which starts when the run\n * ends — so a run that never ends was never evicted, and its entry, its\n * frames and everything the run closes over stayed in the map for the life\n * of the process (#455). The agent's `maxRunDurationMs` is what ends such a\n * run now; this is the backstop for one that still does not end. When it\n * fires the run is stopped (a no-op for one that has ended) and the entry is\n * evicted `ttlMs` later, ended or not, so a reader attached to it gets the\n * stopped run's last frames and then a closed stream rather than a hang.\n *\n * Per entry it is never shorter than the run's own limit plus `ttlMs`, when\n * the registering caller passes one (`AgentController` does). Read at\n * `register`, so changing it affects runs registered afterwards.\n */\n maxAgeMs: number | null;\n\n private runs = new Map<string, Entry>();\n /** Thread to the most recently registered run for it. */\n private byThread = new Map<string, string>();\n /** The client's pre-`run-start` name for a run, to the run. */\n private byClientRun = new Map<string, string>();\n\n constructor(params: { ttlMs?: number; maxFrames?: number; maxAgeMs?: number | null } = {}) {\n this.ttlMs = params.ttlMs ?? DEFAULT_TTL_MS;\n this.maxFrames = params.maxFrames ?? DEFAULT_MAX_FRAMES;\n this.maxAgeMs = params.maxAgeMs === undefined ? DEFAULT_MAX_AGE_MS : params.maxAgeMs;\n }\n\n /**\n * Takes ownership of a run: starts buffering its frames and holds it until\n * `ttlMs` past the end.\n *\n * Settles once the run's last frame has been buffered and every `onEvent` it\n * led to has settled, and never rejects. The hooks run on a chain of their\n * own (see `pump`), so a frame's hook can be called well after the frame\n * arrived — after the run, too — and whoever needs to wait for the app's\n * code has only this to wait on: by the time a hook is called it is too late\n * to start waiting for it.\n */\n register(run: AgentRun, params: RegisterParams = {}): Promise<void> {\n const entry: Entry = {\n run: run as AgentRun,\n threadId: params.threadId,\n owner: params.owner ?? null,\n clientRunId: params.clientRunId,\n frames: [],\n lastSeq: -1,\n lostBefore: 0,\n ended: false,\n evicted: false,\n evictAt: null,\n expireAt: null,\n wake: new Set(),\n version: 0,\n };\n this.runs.set(run.runId, entry);\n if (params.threadId) {\n this.byThread.set(params.threadId, run.runId);\n }\n if (params.clientRunId) {\n this.byClientRun.set(params.clientRunId, run.runId);\n }\n this.scheduleExpiry(entry, params.maxRunDurationMs);\n return this.pump(entry, params);\n }\n\n /**\n * The run a client named before the server had named it.\n *\n * Deliberately not folded into `find`, whose parameter is part of the\n * read-side `LiveRuns` interface an app may already implement — widening that\n * parameter would break every such implementation, and this lookup is only\n * ever asked by `/stop`.\n */\n findByClientRunId(clientRunId: string): string | null {\n const runId = this.byClientRun.get(clientRunId);\n return runId && this.runs.has(runId) ? runId : null;\n }\n\n /** What the client asks after a refresh: is anything still going here? */\n async find(params: { threadId: string }): Promise<{ runId: string; seq: number } | null> {\n const runId = this.byThread.get(params.threadId);\n if (!runId) {\n return null;\n }\n const entry = this.runs.get(runId);\n if (!entry) {\n return null;\n }\n // `seq` is the last frame emitted, not the next one: it is the same number\n // the transport puts in `Last-Event-ID`, so a client can compare the two\n // without knowing which end of the range each one means.\n return { runId, seq: entry.lastSeq };\n }\n\n get(runId: string): AgentRun | null {\n return this.runs.get(runId)?.run ?? null;\n }\n\n /** Who started the run (see `RegisterParams.owner`); `null` for an unowned\n * run and for one this process does not hold. */\n ownerOf(runId: string): string | null {\n return this.runs.get(runId)?.owner ?? null;\n }\n\n /**\n * Whether `caller` may read or stop the run: an unowned run (and one this\n * process does not hold) answers anyone, an owned one only its owner. A\n * caller with no key (`null`, an anonymous request) is not the owner of\n * anything.\n */\n mayAccess(runId: string, caller: string | null): boolean {\n const owner = this.ownerOf(runId);\n return owner === null || owner === caller;\n }\n\n /** Whether the run is still going, as opposed to ended and kept for `ttlMs`,\n * or not here at all. */\n isRunning(runId: string): boolean {\n const entry = this.runs.get(runId);\n return !!entry && !entry.ended && !entry.evicted;\n }\n\n /**\n * The buffered frames from `from` onwards, followed by live ones until the\n * run ends.\n *\n * Throws before returning anything, so an evicted cursor and an unknown run\n * are still HTTP statuses rather than events on a stream that already\n * committed to a 200.\n *\n * `from` omitted means \"start wherever you still can\", not \"start at 0\".\n * These are genuinely different requests: a client that names a cursor is\n * telling us where its transcript ends, and handing it a later frame leaves\n * an invisible hole — that is the 410. A client with no cursor at all — the\n * browser reattaching on mount, which is the case `/attach` exists for — has\n * no transcript to put a hole in, and refusing it the tail because the run is\n * older than the buffer would 410 every run past `maxFrames`, i.e. every run\n * long enough to be worth reattaching to.\n */\n replay(runId: string, from?: number): AsyncIterable<AgentStreamFrame> {\n const entry = this.runs.get(runId);\n if (!entry) {\n throw new LiveRunNotFoundError(runId);\n }\n if (from !== undefined && from < entry.lostBefore) {\n throw new FrameCursorEvictedError(runId, from, entry.lostBefore);\n }\n const oldest = entry.frames[0]?.seq;\n // With nothing buffered — a run registered but not yet pumped — `lastSeq`\n // is -1 and this is 0, which is the same answer by another route.\n return this.drain(entry, runId, from ?? oldest ?? entry.lastSeq + 1);\n }\n\n /** Test seam: drops everything and cancels the pending eviction timers. */\n clear(): void {\n for (const entry of this.runs.values()) {\n if (entry.evictAt) {\n clearTimeout(entry.evictAt);\n }\n if (entry.expireAt) {\n clearTimeout(entry.expireAt);\n }\n // Marked ended before waking: a reader parked on `wait` would otherwise\n // come back, find the entry unfinished, and park again forever.\n entry.ended = true;\n this.notify(entry);\n }\n this.runs.clear();\n this.byThread.clear();\n this.byClientRun.clear();\n }\n\n get size(): number {\n return this.runs.size;\n }\n\n private async pump(entry: Entry, params: RegisterParams): Promise<void> {\n // Hooks run on their own chain: they stay in order relative to each other,\n // and a slow one never stalls the buffer a reattaching client reads from.\n let hooks = Promise.resolve();\n try {\n for await (const frame of entry.run.frames()) {\n // Evicted by the age ceiling with the run still going: nobody can\n // reach this entry any more, so its frames are not kept. The hooks\n // below still hear them — they are the app's, and the run is not over.\n if (entry.evicted) {\n const onEvent = params.onEvent;\n if (onEvent) {\n hooks = hooks.then(() => onEvent(frame.event)).catch((err) => report(params, err));\n }\n continue;\n }\n entry.frames.push(frame);\n entry.lastSeq = frame.seq;\n if (entry.frames.length > this.maxFrames) {\n const dropped = entry.frames.shift();\n if (dropped) entry.lostBefore = dropped.seq + 1;\n }\n this.notify(entry);\n const onEvent = params.onEvent;\n if (onEvent) {\n hooks = hooks.then(() => onEvent(frame.event)).catch((err) => report(params, err));\n }\n }\n } catch (err) {\n // The run's own iterator failed. There is nothing left to replay, so the\n // entry ends here; whoever is attached sees the stream close.\n report(params, err);\n } finally {\n entry.ended = true;\n if (entry.expireAt) {\n clearTimeout(entry.expireAt);\n entry.expireAt = null;\n }\n this.notify(entry);\n // Eviction is scheduled off the ttl clock, BEFORE the hook chain is\n // awaited. `hooks` is app code — `onAwaitingInput` is documented as the\n // place to notify an approver, i.e. network I/O — and a `fetch` with no\n // timeout never rejects, it just never settles. Awaiting it first made\n // retention conditional on app code: one hanging hook pinned its entry,\n // its 512 frames, the run and everything the run closes over in the map\n // for the life of the process, and `find` kept answering with a run that\n // ended hours ago. Retention is this class's job and belongs on its own\n // clock. A hook still pending when the timer fires simply outlives the\n // entry, which is fine — it holds no reference the map needed.\n this.scheduleEviction(entry);\n await hooks;\n }\n }\n\n private async *drain(\n entry: Entry,\n runId: string,\n from: number,\n ): AsyncGenerator<AgentStreamFrame, void, void> {\n let cursor = from;\n while (true) {\n const seen = entry.version;\n // The window is contiguous and ordered, so a reader's position in it is\n // arithmetic, not a search. This used to copy the whole window on every\n // wake and scan it for frames past the cursor, which is O(window) per\n // frame per reader — invisible at a 512-frame cap and the reason the cap\n // could not be raised. Indexing makes the window's size stop mattering.\n for (;;) {\n if (cursor < entry.lostBefore) {\n // The window rolled past this reader mid-stream. Same reasoning as\n // the pre-flight check: a gap the client cannot see is worse than a\n // stream that stops and says why. Re-checked inside the loop rather\n // than once per wake, because a yield suspends this reader for as\n // long as its consumer takes and the pump keeps running.\n throw new FrameCursorEvictedError(runId, cursor, entry.lostBefore);\n }\n const frames = entry.frames;\n const oldest = frames[0]?.seq;\n if (oldest === undefined) {\n break;\n }\n // Clamped rather than treated as a gap: a cursor below the first seq\n // that ever existed is \"from the beginning\", not a lost position.\n const index = Math.max(0, cursor - oldest);\n if (index >= frames.length) {\n break;\n }\n const frame = frames[index]!;\n yield frame;\n cursor = frame.seq + 1;\n }\n if ((entry.ended && cursor > entry.lastSeq) || entry.evicted) {\n return;\n }\n await this.wait(entry, seen);\n }\n }\n\n private wait(entry: Entry, seen: number): Promise<void> {\n if (entry.version !== seen) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => entry.wake.add(resolve));\n }\n\n private notify(entry: Entry): void {\n entry.version++;\n const waiters = Array.from(entry.wake);\n entry.wake.clear();\n for (const resolve of waiters) {\n resolve();\n }\n }\n\n private scheduleEviction(entry: Entry): void {\n if (entry.evictAt) {\n return;\n }\n const timer = setTimeout(() => {\n const runId = entry.run.runId;\n if (!entry.ended) {\n // The age ceiling, with the run still going. Its frames are released\n // here because the pump of a run that has not ended still holds the\n // entry, and readers are told to finish (see `drain`), since `ended`\n // may never come. An ended entry keeps both: a reader still behind on\n // it finishes the tail it was reading, as it always has.\n entry.evicted = true;\n entry.frames = [];\n }\n if (this.runs.get(runId) === entry) this.runs.delete(runId);\n if (entry.threadId && this.byThread.get(entry.threadId) === runId) {\n this.byThread.delete(entry.threadId);\n }\n if (entry.clientRunId && this.byClientRun.get(entry.clientRunId) === runId) {\n this.byClientRun.delete(entry.clientRunId);\n }\n // Anyone still draining is holding an ended entry; wake them so they see\n // `ended` and finish rather than hanging on a promise nothing resolves.\n this.notify(entry);\n }, this.ttlMs);\n // A finished run must not be the reason a process stays up.\n (timer as { unref?: () => void }).unref?.();\n entry.evictAt = timer;\n }\n\n /**\n * The age ceiling: stops the run and starts the `ttlMs` eviction clock at\n * `maxAgeMs` after `register`, whether or not the run has ended. See\n * `maxAgeMs`.\n */\n private scheduleExpiry(entry: Entry, runLimit: number | null | undefined): void {\n if (this.maxAgeMs === null || runLimit === null) return;\n const ceiling =\n runLimit === undefined ? this.maxAgeMs : Math.max(this.maxAgeMs, runLimit + this.ttlMs);\n if (!Number.isFinite(ceiling) || ceiling > MAX_TIMER_MS) return;\n const timer = setTimeout(() => {\n entry.expireAt = null;\n if (entry.ended) return;\n try {\n entry.run.stop({\n reason: `The run was still going ${Math.round(ceiling / 1000)}s after it started, past the live-run registry's age limit.`,\n });\n } catch {\n // A run whose `stop` throws is evicted all the same.\n }\n this.scheduleEviction(entry);\n }, ceiling);\n // Like the eviction timer: never the reason a process stays up.\n (timer as { unref?: () => void }).unref?.();\n entry.expireAt = timer;\n }\n}\n\n/**\n * The process-wide default, shared by every `AgentController` that does not\n * bring its own. One map per process is the whole point — see the class note.\n */\nexport const liveRuns = new MemoryLiveRuns();\n\n/**\n * Hands `err` to `onInternalError`, which is app code too: one that throws is\n * dropped rather than rejecting the hook chain, and with it `register`'s\n * promise, which says it never rejects.\n */\nfunction report(params: RegisterParams, err: unknown): void {\n try {\n params.onInternalError?.(err);\n } catch {\n // Nothing is left to tell.\n }\n}\n",
27
28
  "/**\n * WHO UPLOADED A PROVIDER FILE (#443).\n *\n * A provider's file id (`file-…`) is scoped to the OpenAI/Azure org, not to\n * any user of the app: the vendor will hand the document to whichever request\n * names it. So an id is a bearer token for the file, and ids leak — a shared\n * transcript, a log line, a browser history entry. Before this, a user who\n * learned another user's id could put it in their own `turn.files` and have\n * the model read the other user's document.\n *\n * `AgentController.upload` now records the id with the uploader's owner key\n * (the same `runOwner(req)` that owns a run, #442), and `stream` refuses a\n * turn naming an id recorded for anyone else with a 403.\n *\n * A record is `{ owner, name, mimeType, size, createdAt }`, keyed by the\n * provider's id. `owner: null` is an anonymous upload and is unowned: it\n * answers whoever holds the id, exactly as every id did before this existed.\n */\nexport type FileOwnerRecord = {\n /** `runOwner(req)` at upload: `user:<id>` by default, `null` for anonymous. */\n owner: string | null;\n name?: string;\n mimeType?: string;\n size?: number;\n createdAt: string;\n};\n\n/**\n * Where the records live. Two methods so an app can put them in its own table:\n *\n * class DbFileOwners implements FileOwners {\n * async record(fileId, record) { await db.agentFile.create({ data: { fileId, ...record } }) }\n * async get(fileId) { return db.agentFile.findUnique({ where: { fileId } }) }\n * }\n *\n * `get` answers `null` for an id it has no record of. What the controller does\n * with that is `AgentController.requireKnownFiles`.\n */\nexport interface FileOwners {\n record(fileId: string, record: FileOwnerRecord): Promise<void>;\n get(fileId: string): Promise<FileOwnerRecord | null>;\n}\n\n/**\n * The default: records last as long as the process, like `MemoryAgentStore`\n * and `MemoryAttachmentStore`. Bounded, oldest first, so an upload loop cannot\n * grow it without end; an evicted id reads as unknown.\n *\n * A record is never overwritten: the first owner of an id keeps it, so a\n * second `record` for the same id (which a provider never mints, but a buggy\n * or hostile override could forward) cannot move a file to another user.\n */\nexport class MemoryFileOwners implements FileOwners {\n private readonly records = new Map<string, FileOwnerRecord>();\n\n constructor(private readonly maxEntries = 100_000) {}\n\n async record(fileId: string, record: FileOwnerRecord): Promise<void> {\n if (this.records.has(fileId)) return;\n this.records.set(fileId, { ...record });\n while (this.records.size > this.maxEntries) {\n const oldest = this.records.keys().next().value;\n if (oldest === undefined) break;\n this.records.delete(oldest);\n }\n }\n\n async get(fileId: string): Promise<FileOwnerRecord | null> {\n const record = this.records.get(fileId);\n return record ? { ...record } : null;\n }\n}\n\nexport const defaultFileOwners = new MemoryFileOwners();\n",
28
29
  "import { app } from \"../../foundation/app\";\nimport { RedisManager } from \"../../services/redis/RedisManager\";\nimport type { ToolResultPart } from \"../types\";\n\n/**\n * EXECUTION RECEIPTS: what makes an approved tool run at most once (#458).\n *\n * A pending call's signature stops an approval being forged, and its spent\n * nonce (`NonceStore`, #445) stops it being *accepted* twice. Neither records\n * what the approved tool did. So a retried submit whose response was lost, a\n * proxy retry, or an answer that reaches two instances whose nonce stores are\n * not shared, either runs `execute` again for a tool that already charged a\n * card, or is refused and the user is told their approval was not used when\n * it was.\n *\n * A receipt store closes that. Before an approved tool runs, the run claims a\n * deterministic execution id (an HMAC, under its own HKDF-derived key, of the\n * call the signature covers: issuing run, tool call id, tool name, canonical\n * input, nesting path and subject). The claim answers one of three things:\n *\n * claimed — nobody has run it: run it, then `complete` with its result.\n * replay — it already ran: the stored result is returned as the call's\n * result, and the tool is not run.\n * blocked — a claim is held but no result recorded: another instance is\n * running it right now, or the process that was running it died.\n * The call gets a `tool_error` result the model can read, and the\n * tool is not run. Not knowing whether a side effect happened is\n * exactly the case where running it again is wrong.\n *\n * Opt-in: `AgentController.receipts` (or `receipts` on `Agent.stream`). Without\n * a store an approved tool runs exactly as before.\n *\n * Implementations:\n *\n * MemoryReceiptStore — one process, lost on restart.\n * RedisReceiptStore — on the app's Redis; shared and atomic.\n * your own — e.g. a table keyed by the execution id:\n *\n * CREATE TABLE agent_tool_receipts (\n * id text PRIMARY KEY,\n * result jsonb, -- NULL while the call is running\n * expires_at timestamptz NOT NULL\n * );\n *\n * class DbReceiptStore implements ReceiptStore {\n * async claim(id, expiresAt) {\n * const inserted = await db.$executeRaw`\n * INSERT INTO agent_tool_receipts (id, expires_at)\n * VALUES (${id}, ${new Date(expiresAt)})\n * ON CONFLICT (id) DO NOTHING`;\n * if (inserted === 1) return { status: \"claimed\" };\n * const [row] = await db.$queryRaw`\n * SELECT result FROM agent_tool_receipts WHERE id = ${id}`;\n * return row?.result ? { status: \"replay\", result: row.result } : { status: \"blocked\" };\n * }\n * async complete(id, result) {\n * await db.$executeRaw`\n * UPDATE agent_tool_receipts SET result = ${result} WHERE id = ${id}`;\n * }\n * async release(id) {\n * await db.$executeRaw`\n * DELETE FROM agent_tool_receipts WHERE id = ${id} AND result IS NULL`;\n * }\n * }\n * // and, from a cron: DELETE FROM agent_tool_receipts WHERE expires_at < now()\n *\n * A receipt only has to outlive the token it answers: past `expiresAt` the\n * signature fails verification on its own, so the call cannot be presented\n * again and the receipt may be dropped.\n */\nexport interface ReceiptStore {\n /**\n * Claims `executionId` until `expiresAt` (epoch milliseconds), if nobody has.\n * Must be atomic across every process sharing the store: two concurrent\n * claims never both answer `claimed`.\n *\n * A rejection refuses the answer, as a `NonceStore` that throws does: an\n * idempotency guard that runs the tool anyway when its store is down is not\n * a guard.\n */\n claim(executionId: string, expiresAt: number): Promise<ReceiptClaim>;\n /**\n * Records the result of a claimed execution, kept until `expiresAt`. Called\n * once the tool's result is known, which may be after the run that claimed\n * it was stopped. A rejection is logged; the claim then stays held, so a\n * replay is `blocked` rather than run again.\n */\n complete(executionId: string, result: ToolResultPart, expiresAt: number): Promise<void>;\n /**\n * Drops a claim that never ran: the answer was refused after it was claimed\n * (its nonce was already spent). A recorded result is never released.\n */\n release(executionId: string): Promise<void>;\n}\n\nexport type ReceiptClaim =\n | { status: \"claimed\" }\n | { status: \"replay\"; result: ToolResultPart }\n | { status: \"blocked\" };\n\ntype MemoryReceipt = { result?: ToolResultPart; expiresAt: number };\n\n/**\n * The in-process store. Holds each receipt until its token expires, swept\n * amortized O(1) per claim. Results are copied in and out, so a caller that\n * edits the part it was handed cannot change what a replay returns.\n */\nexport class MemoryReceiptStore implements ReceiptStore {\n private readonly receipts = new Map<string, MemoryReceipt>();\n private sweepAt = 1024;\n /** Injectable for tests. */\n constructor(private readonly now: () => number = Date.now) {}\n\n async claim(executionId: string, expiresAt: number): Promise<ReceiptClaim> {\n const now = this.now();\n if (this.receipts.size >= this.sweepAt) this.sweep(now);\n const existing = this.receipts.get(executionId);\n if (existing && existing.expiresAt > now) {\n return existing.result\n ? { status: \"replay\", result: structuredClone(existing.result) }\n : { status: \"blocked\" };\n }\n this.receipts.set(executionId, { expiresAt });\n return { status: \"claimed\" };\n }\n\n async complete(executionId: string, result: ToolResultPart, expiresAt: number): Promise<void> {\n this.receipts.set(executionId, { result: structuredClone(result), expiresAt });\n }\n\n async release(executionId: string): Promise<void> {\n const existing = this.receipts.get(executionId);\n if (existing && !existing.result) this.receipts.delete(executionId);\n }\n\n get size(): number {\n return this.receipts.size;\n }\n\n private sweep(now: number) {\n for (const [id, receipt] of this.receipts) {\n if (receipt.expiresAt <= now) this.receipts.delete(id);\n }\n this.sweepAt = Math.max(1024, this.receipts.size * 2);\n }\n}\n\n/** The slice of Bun's `RedisClient` this store needs: `send(command, args)`. */\nexport interface ReceiptRedisClient {\n send(command: string, args: string[]): Promise<any>;\n}\n\nexport interface RedisReceiptStoreOptions {\n /**\n * Client to run against. Defaults to the app's shared client from\n * `RedisServiceProvider`, resolved on first use.\n */\n client?: ReceiptRedisClient;\n /** Key namespace. Defaults to `gemi:ai:receipt`. */\n prefix?: string;\n}\n\nconst PENDING = \"pending\";\nconst DONE = \"done:\";\n\n/** `SET NX`, and on a miss the value that was there, in one round trip. */\nconst CLAIM_SCRIPT = `\nif redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end\nlocal held = redis.call('GET', KEYS[1])\nif not held then return ARGV[1] end\nreturn held`;\n\n/** Deletes the key only while it is an unfinished claim. */\nconst RELEASE_SCRIPT = `\nif redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end\nreturn 0`;\n\n/**\n * Receipts in Redis, shared by every instance of the app. A claim is a\n * `SET ... NX` run in a script with the read that follows a miss, so claiming\n * is atomic; `PX` drops each key at the token's expiry.\n *\n * ```ts\n * const receipts = new RedisReceiptStore();\n *\n * class ChatController extends AgentController<typeof chat> {\n * agent = chat;\n * receipts = receipts;\n * }\n * ```\n */\nexport class RedisReceiptStore implements ReceiptStore {\n private readonly injectedClient?: ReceiptRedisClient;\n private readonly prefix: string;\n\n constructor(options: RedisReceiptStoreOptions = {}) {\n this.injectedClient = options.client;\n this.prefix = options.prefix ?? \"gemi:ai:receipt\";\n }\n\n async claim(executionId: string, expiresAt: number): Promise<ReceiptClaim> {\n const reply = await this.client.send(\"EVAL\", [\n CLAIM_SCRIPT,\n \"1\",\n this.key(executionId),\n PENDING,\n ttl(expiresAt),\n ]);\n // Anything else the script did not return (a client that maps an odd\n // reply to `null`, say) is `blocked`: never a reason to run the tool.\n if (reply === \"claimed\") return { status: \"claimed\" };\n const held = String(reply ?? \"\");\n if (held.startsWith(DONE)) {\n return { status: \"replay\", result: JSON.parse(held.slice(DONE.length)) as ToolResultPart };\n }\n return { status: \"blocked\" };\n }\n\n async complete(executionId: string, result: ToolResultPart, expiresAt: number): Promise<void> {\n await this.client.send(\"SET\", [\n this.key(executionId),\n DONE + JSON.stringify(result),\n \"PX\",\n ttl(expiresAt),\n ]);\n }\n\n async release(executionId: string): Promise<void> {\n await this.client.send(\"EVAL\", [RELEASE_SCRIPT, \"1\", this.key(executionId), PENDING]);\n }\n\n private key(executionId: string) {\n return `${this.prefix}:${executionId}`;\n }\n\n private get client(): ReceiptRedisClient {\n if (this.injectedClient) return this.injectedClient;\n const container = app();\n const client = container.bound(RedisManager) ? container.make(RedisManager).client : undefined;\n if (!client) {\n throw new Error(\n \"RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).\",\n );\n }\n return client;\n }\n}\n\n/** At least 1ms: `PX 0` is an error. */\nfunction ttl(expiresAt: number): string {\n return String(Math.max(1, Math.ceil(expiresAt - Date.now())));\n}\n",
@@ -31,7 +32,7 @@
31
32
  "import type { AgentStore } from \"../AgentController\";\nimport { applyFrame, type ChatState, initialChatState } from \"../client/reducer\";\nimport type {\n AgentMessage,\n AgentStreamFrame,\n NestedRun,\n ToolCallPart,\n ToolResultPart,\n} from \"../types\";\n\n/**\n * A threaded turn, written to the store while it runs (#617).\n *\n * The controller used to store a turn once, when its run ended. A process that\n * died mid-run (a restart, a crash, a deploy) left the thread without the turn\n * at all, not even the user's message, while the run's tools may already have\n * written durable changes. Neither the app nor the model could tell a turn that\n * never happened from one that was lost.\n *\n * So a turn is now written as it goes, through the store's own upsert:\n *\n * - **Finished messages** (`finish`), as the run reports them: the user's turn\n * before the model is asked anything, each assistant message as it closes,\n * an earlier message a turn amended. The run's own objects, so they are\n * exactly what the end-of-run write stores.\n * - **The message in progress** (`frame`), at the points worth keeping: when it\n * opens, when a tool call's arguments are complete, when a tool result\n * lands, and a whole message the run injected. It is assembled from the\n * run's frames by the client reducer (the code every client already renders\n * a live run with) and stored with no `finishReason` and the run's id in\n * `runId`, which is what lets a later reader see that its run is gone.\n * Text deltas are not a checkpoint: a store write per token is not worth\n * the text a crash would lose.\n *\n * Every write is an upsert by message id, so writing a message twice, or a\n * retried start writing the same turn again, leaves one copy. Writes go out one\n * at a time and in order, off the run's path: a slow store does not slow the\n * model, and a message's in-progress copy can never land after its finished\n * one. A write that fails is reported and the run carries on, as a hook\n * failure does; the end-of-run write stores everything again anyway.\n */\nexport class TurnJournal {\n private chain: Promise<void> = Promise.resolve();\n /** Ids whose finished copy has been queued. An in-progress copy of one of\n * these is stale by definition and is never written after it. */\n private readonly done = new Set<string>();\n private closed = false;\n private state: ChatState;\n private runId: string | undefined;\n\n constructor(\n private readonly store: AgentStore,\n private readonly threadId: string,\n /** The history the run starts from, so a tool result that lands on an\n * earlier turn's message checkpoints the whole message, not a stub of it. */\n history: AgentMessage[],\n private readonly report: (error: unknown) => void,\n ) {\n this.state = initialChatState({ messages: history });\n }\n\n /** A message the run has finished. Queued as it is, and final. */\n finish(message: AgentMessage): void {\n if (this.closed) return;\n this.done.add(message.id);\n this.write(() => [snapshot(message)]);\n }\n\n /** One frame of the run, in order. Writes the message it touched when the\n * frame is a checkpoint. */\n frame(frame: AgentStreamFrame): void {\n if (this.closed) return;\n const event = frame.event;\n if (event.type === \"run-start\") this.runId = event.runId;\n this.state = applyFrame(this.state, frame);\n\n switch (event.type) {\n case \"message\":\n // Complete when it is made (see the event), so it is written whole. Not\n // marked done: the run reports it again once the message above it\n // closes, and that copy is the one that stays.\n this.write(() => [snapshot(event.message)]);\n return;\n case \"tool-call\":\n if (event.part.partial) return;\n this.checkpoint(event.messageId);\n return;\n case \"message-start\":\n case \"tool-result\":\n this.checkpoint(event.messageId);\n return;\n default:\n return;\n }\n }\n\n /**\n * The run is over and its transcript is about to be written whole: nothing\n * more is queued after this. `messages` are the ones that write will hold,\n * so a frame still on its way cannot put an in-progress copy of one of them\n * back.\n */\n close(messages: AgentMessage[] = []): void {\n this.closed = true;\n for (const message of messages) this.done.add(message.id);\n }\n\n /** Settles once every queued write has. Never rejects. */\n settled(): Promise<void> {\n return this.chain;\n }\n\n private checkpoint(messageId: string): void {\n if (this.done.has(messageId)) return;\n const message = this.state.messages.find((held) => held.id === messageId);\n if (!message) return;\n const runId = this.runId;\n this.write(() => {\n const copy = snapshot(message);\n // Stamped only on a message still being written: the run's id is the\n // thing a reader checks for liveness, and a finished message has nothing\n // to check.\n if (copy.finishReason === undefined && runId) copy.runId = runId;\n return [copy];\n });\n }\n\n /**\n * Queues one write. The copy is taken now, before anything else can change\n * the message, and a copy that fails (a tool output that is not plain data)\n * costs that one write, not the journal: the end-of-run write still stores\n * the message.\n */\n private write(copy: () => AgentMessage[]): void {\n let messages: AgentMessage[];\n try {\n messages = copy();\n } catch (error) {\n this.report(error);\n return;\n }\n this.chain = this.chain\n .then(() => this.store.appendMessages(this.threadId, messages))\n .catch((error) => this.report(error));\n }\n}\n\n/**\n * A copy the run cannot change under the store. The run keeps writing to its\n * own objects (a tool result onto the message that made the call), and a store\n * that holds references, as `MemoryAgentStore` does, would otherwise show a\n * reader a message that changes after it was written.\n */\nfunction snapshot(message: AgentMessage): AgentMessage {\n return structuredClone(message);\n}\n\n/**\n * The thread as it stands, with every message a dead run left unfinished\n * marked as such.\n *\n * An assistant message with no `finishReason` is either still being written or\n * was being written by a run that is gone. `isLive` tells the two apart by the\n * message's `runId`; a message without one belongs to no run and is gone too.\n * Each gone one is closed as `interrupted`:\n *\n * - its own `finishReason`, so a UI shows \"cut off\" rather than a cursor that\n * never stops;\n * - a `denied` result with `cause: \"interrupted\"` for every tool call it left\n * without one, so the history stays valid for the provider (a call with no\n * output is a 400) and the model reads what happened to it;\n * - the same reason on any sub-run under its tool calls that never finished,\n * which would otherwise draw a cursor of its own.\n *\n * `settled` is the messages that changed, for the caller to write back. Running\n * this again on its own output changes nothing, which is what makes it safe to\n * run on every read.\n */\nexport async function settleInterrupted(\n messages: AgentMessage[],\n isLive: (runId: string) => boolean | Promise<boolean>,\n): Promise<{ messages: AgentMessage[]; settled: AgentMessage[] }> {\n const settled: AgentMessage[] = [];\n let resolved: Set<string> | null = null;\n const out = messages.slice();\n\n for (let at = 0; at < out.length; at++) {\n const message = out[at]!;\n if (message.role !== \"assistant\" || message.finishReason !== undefined) continue;\n if (message.runId && (await isLive(message.runId))) continue;\n\n // Computed once, and only for a thread that has something to settle,\n // which is almost never.\n resolved ??= new Set(\n messages.flatMap((held) =>\n held.content.flatMap((part) => (part.type === \"tool-result\" ? [part.toolCallId] : [])),\n ),\n );\n\n const content = message.content.map((part) =>\n part.type === \"tool-call\" ? closeCall(part as ToolCallPart) : part,\n );\n for (const part of message.content) {\n if (part.type !== \"tool-call\" || resolved.has(part.toolCallId)) continue;\n const result: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n name: part.name,\n status: \"denied\",\n cause: \"interrupted\",\n };\n content.push(result);\n }\n const closed: AgentMessage = { ...message, content, finishReason: \"interrupted\" };\n out[at] = closed;\n settled.push(closed);\n }\n\n return { messages: out, settled };\n}\n\n/** A call as a dead run left it: its arguments are all there will ever be,\n * and a sub-run under it that never finished is interrupted too. */\nfunction closeCall(part: ToolCallPart): ToolCallPart {\n const { partial: _partial, ...call } = part;\n if (!call.nested?.some((run) => run.finishReason === undefined)) return call as ToolCallPart;\n return { ...call, nested: call.nested.map(closeRun) } as ToolCallPart;\n}\n\nfunction closeRun(run: NestedRun): NestedRun {\n if (run.finishReason !== undefined) return run;\n return {\n ...run,\n finishReason: \"interrupted\",\n messages: run.messages.map((message) =>\n message.role === \"assistant\" && message.finishReason === undefined\n ? {\n ...message,\n finishReason: \"interrupted\" as const,\n content: message.content.map((part) =>\n part.type === \"tool-call\" ? closeCall(part as ToolCallPart) : part,\n ),\n }\n : message,\n ),\n };\n}\n",
32
33
  "import { Storage } from \"../facades/Storage\";\nimport { Controller } from \"../http/Controller\";\nimport { refusal, RequestBreakerError } from \"../http/Error\";\nimport { HttpRequest } from \"../http/HttpRequest\";\nimport { mediaType } from \"../http/mediaType\";\nimport { refusalKindForStatus } from \"../http/refusal\";\nimport type { MiddlewareInput } from \"../http/middlewareList\";\nimport type { AgentContext, AgentRun, AgentRunResult, AnyAgent, ToolShapesOf } from \"./Agent\";\nimport { injectedMessageIds } from \"./Agent\";\nimport {\n type Attachment,\n ATTACHMENT_ID_PREFIX,\n type AttachmentDestination,\n attachmentObjectName,\n type AttachmentScope,\n type AttachmentStorage,\n type AttachmentStore,\n defaultAttachmentStore,\n newAttachmentId,\n ScopedAttachments,\n} from \"./store/Attachments\";\nimport {\n FrameCursorEvictedError,\n liveRuns as defaultLiveRuns,\n LiveRunNotFoundError,\n MemoryLiveRuns,\n} from \"./store/LiveRuns\";\nimport {\n defaultFileOwners,\n type FileOwnerRecord,\n type FileOwners,\n MemoryFileOwners,\n} from \"./store/FileOwners\";\nimport {\n defaultNonceStore,\n MemoryNonceStore,\n type NonceRedisClient,\n type NonceStore,\n RedisNonceStore,\n type RedisNonceStoreOptions,\n} from \"./store/Nonces\";\nimport {\n MemoryReceiptStore,\n type ReceiptClaim,\n type ReceiptRedisClient,\n type ReceiptStore,\n RedisReceiptStore,\n type RedisReceiptStoreOptions,\n} from \"./store/Receipts\";\nimport { defaultAgentStore, MemoryAgentStore } from \"./store/MemoryAgentStore\";\nimport { normalizeProviderError, ProviderHttpError } from \"./providers/errors\";\nimport { redactError, unredactedError } from \"./redact\";\nimport type { ErrorRedactionInfo } from \"./redact\";\nimport { sseResponse } from \"./store/sse\";\nimport { settleInterrupted, TurnJournal } from \"./store/TurnJournal\";\nimport type {\n AgentError,\n AgentMessage,\n AgentStreamEvent,\n ClientTurn,\n PendingToolCall,\n ToolShapes,\n} from \"./types\";\n\n// --- storage -------------------------------------------------------------\n\n/**\n * Where conversations live.\n *\n * Stateless is the default and nothing here is required to hold a conversation:\n * the client can carry its own history, and a pending approval travels in it\n * safely because the server signed it. What a store buys is a conversation that\n * survives the browser — and, with `/attach`, one whose interrupted turn is\n * still there after a refresh.\n */\nexport interface AgentStore {\n /**\n * Where a `threadId` comes from. `ApiRouter.agent()` mounts no route for\n * this: the app writes one, calls it here, and hands the id to `useChat` —\n * the mount is the app's because it is where ownership gets recorded, and a\n * store that holds no user cannot do that for it. An id that did not come out\n * of here is `null` from `loadThread` and a 404 from the controller, unless\n * the store's ids are the client's by design (`MemoryAgentStore`'s\n * `clientOwnedIds`).\n */\n createThread(params: { userId?: string | number }): Promise<{ threadId: string }>;\n /**\n * The history, or `null` for a thread the store does not have.\n *\n * `null` and `[]` are different answers and the controller acts on the\n * difference: an empty array is a conversation with nothing in it yet, and a\n * turn on it runs; `null` is a 404 before anything runs. A store that answers\n * `[]` for an id it has never seen turns an expired or mistyped thread into a\n * fresh conversation with no signal, and persists the next turn under the\n * dead id. Only a store whose ids are minted by the client should do that,\n * and then on purpose — see `MemoryAgentStore`'s `clientOwnedIds`.\n */\n loadThread(threadId: string): Promise<AgentMessage[] | null>;\n /**\n * Upsert by message id: replace a message the thread already holds, append\n * one it does not, and keep the order the thread had. Called with a thread\n * `loadThread` just found; must not create one.\n *\n * The name says append because that is what almost every call is, but a\n * turn that resolves a pending call reports the earlier assistant message\n * again — same id, now with the result attached — and a store that only\n * appends ends up with both versions. A table keyed by message id has the\n * lookup already but still needs an insert-or-update rather than a plain\n * insert, which would fail on the key; a store that is a list has to look\n * before it pushes.\n *\n * It is also called while a turn runs, not only when it ends (#617): with the\n * user's message as the run starts, with the assistant message in progress\n * (no `finishReason`, the run's id in `runId`) as it opens and at each tool\n * call and result, and with each message again once it is finished. The\n * same message arrives several times, and the last write is the one to\n * keep. Calls for one run never overlap: each waits for the one before.\n */\n appendMessages(threadId: string, messages: AgentMessage[]): Promise<void>;\n /**\n * Delete these messages from the thread; ids it does not hold are ignored.\n *\n * What a threaded `regenerate` needs (#451): the server owns the history,\n * so the answer being replaced has to leave the store, or the model reads\n * `user: X, assistant: A, user: X` and writes a follow-up instead of a new\n * answer. The controller calls it under the thread's lock with the last user\n * turn and everything after it, then runs that turn again.\n *\n * Optional so a store written before it still compiles; without it a turn\n * with `regenerate: true` on a thread is a 501 `regenerate_unsupported`.\n */\n removeMessages?(threadId: string, messageIds: string[]): Promise<void>;\n}\n\n/** The default: conversations last as long as the process. */\nexport { defaultAgentStore, MemoryAgentStore };\n\n/** The attachment half of the same story. See `store/Attachments.ts`. */\nexport {\n type Attachment,\n type AttachmentDestination,\n AttachmentNotFoundError,\n type AttachmentScope,\n type AttachmentStorage,\n type AttachmentStore,\n defaultAttachmentStore,\n InvalidAttachmentScopeError,\n MemoryAttachmentStore,\n type PutAttachmentParams,\n ScopedAttachments,\n type ToolAttachmentPut,\n type ToolAttachmentRecord,\n type ToolAttachments,\n} from \"./store/Attachments\";\n\n/**\n * The runs currently in flight, and their frames.\n *\n * A run outlives the request that started it, so something has to hold it while\n * no one is listening, and hold what it emitted meanwhile so a returning client\n * can catch up rather than start over. That is all this is: a per-process map\n * plus a bounded buffer.\n *\n * Per-process is not an implementation shortcut that a better store fixes — a\n * running generator lives in one process, and a second server cannot attach to\n * it. Reattachment therefore needs the request to land where the run is: one\n * server, sticky routing, or a proxy that forwards by `runId`. Worth saying out\n * loud, because the failure mode behind a round-robin load balancer is a\n * refresh that usually works.\n *\n * This is the read side, which is all `attach` and `stop` need. Registering a\n * run and replaying its buffer are on `MemoryLiveRuns`, the only implementation\n * there can be — see the note there for why a second one would not help.\n */\nexport interface LiveRuns {\n /** What the client asks after a refresh: is anything still going here? */\n find(params: { threadId: string }): Promise<{ runId: string; seq: number } | null>;\n get(runId: string): AgentRun | null;\n /** Kept for a short while after `run-end`, so a refresh a second late still\n * sees the tail instead of an empty screen. */\n ttlMs: number;\n}\n\nexport {\n FrameCursorEvictedError,\n LiveRunNotFoundError,\n MemoryLiveRuns,\n defaultLiveRuns as liveRuns,\n};\n\n/** Who uploaded each provider file id (#443). See `store/FileOwners.ts`. */\nexport { defaultFileOwners, type FileOwnerRecord, type FileOwners, MemoryFileOwners };\n/** Where approved tools' executions are recorded (#458). See `store/Receipts.ts`. */\nexport {\n MemoryReceiptStore,\n type ReceiptClaim,\n type ReceiptRedisClient,\n type ReceiptStore,\n RedisReceiptStore,\n type RedisReceiptStoreOptions,\n};\n/** Where answered calls' nonces are spent (#445). See `store/Nonces.ts`. */\nexport {\n defaultNonceStore,\n MemoryNonceStore,\n type NonceRedisClient,\n type NonceStore,\n RedisNonceStore,\n type RedisNonceStoreOptions,\n};\n\n// --- controller ----------------------------------------------------------\n\nexport type AgentHookContext = {\n req: HttpRequest<any, any>;\n runId: string;\n threadId?: string;\n};\n\n/** What `AgentController.attachmentLimits` answers. Both optional. */\nexport type AttachmentLimits = {\n /** The largest file accepted, in bytes. */\n maxBytes?: number;\n /** `<input accept>` entries: `\".pdf\"`, `\"image/*\"`, `\"text/csv\"`. */\n accept?: string[];\n};\n\n/**\n * What `POST /<path>/files` answers.\n *\n * TWO IDS, AND THEY ARE NOT INTERCHANGEABLE. `fileId` is the *provider's* id and\n * means exactly what it always meant — the value a `FilePart` carries so the\n * model can see the file. `attachmentId` is *gemi's*, and is the handle a tool\n * resolves through `ScopedAttachments` to get the bytes back. A file can have\n * both, and usually does.\n *\n * `fileId` stays first and stays named that on purpose: `useChat.uploadFile`\n * already reads it, apps already put it in a `FilePart`, and renaming it or\n * folding the two into one id would break vision for every existing app while\n * looking like a tidier API. The two ids exist because there are two systems\n * holding the file.\n *\n * Both are optional, and `destination` says which to expect: `provider` has no\n * `attachmentId` (nothing was kept), `storage` has no `fileId` (the provider\n * never saw it, so there is nothing for a `FilePart` to point at), `both` has\n * both.\n *\n * `destination` ALONE IS NOT ENOUGH TO SAY WHY AN ID IS MISSING, which is why\n * `downgraded` is here. An upload that reached a route with no authentication\n * and no `threadId` answers `destination: \"provider\"` — truthfully, that is\n * where the bytes went — and so does a controller that deliberately returns\n * `\"provider\"` from `attachmentDestination`. Those two answers were byte\n * identical, and they are the opposite situations: one is the app's policy\n * working, the other is the app's policy silently not applying because the\n * server could not tell who was calling. The server logs the second one once\n * per process; the client saw nothing at all. `downgraded` is the difference,\n * carried in the answer so a client — or an integration test — can assert on\n * it.\n */\nexport type UploadResult = {\n /** The provider's id, for a `FilePart`. Absent when the file never went there. */\n fileId?: string;\n /** gemi's id, for a tool. Absent when nothing was kept — see `attachmentScope`. */\n attachmentId?: string;\n name: string;\n mimeType: string;\n size: number;\n destination: AttachmentDestination;\n /**\n * Set only when the app's policy asked for a copy and the request had no\n * subject to file it under, so the upload fell back to the provider alone.\n * Absent when `destination` is what the app actually chose.\n *\n * A string rather than `true` because there is exactly one reason today and\n * there will be more (a store that refused the write, say), and a boolean\n * that later needs a reason beside it is two fields where one would have\n * done.\n */\n downgraded?: \"no_scope\";\n};\n\n/**\n * `Controller.kind` is typed as the literal `\"controller\"`, so a subclass that\n * declares a `kind` of its own fails the static-side check (TS2417). Widening\n * it belongs in `http/Controller.ts`, which this slice does not own; erasing\n * the static side of the base here is the smaller change and costs nothing —\n * `Controller.kind` has no reader, in this package or out of it.\n */\nconst ControllerBase = Controller as new () => Controller;\n\n/**\n * The thread a `stream` is setting up on, to the setup ahead of it. Module\n * level because the controller is constructed per request, so nothing on it\n * can be seen by the next request; keyed by thread rather than held on\n * `liveRuns` because it guards the controller's protocol, not the frames. An\n * entry is removed once the last setup queued on it releases.\n */\nconst threadLocks = new Map<string, Promise<void>>();\n\n/**\n * Each run to the promise that its transcript has been stored. Weak, so a run\n * the map has evicted is not kept alive here for a promise nobody will ask for.\n */\nconst persisted = new WeakMap<AgentRun, Promise<void>>();\n\n/**\n * Turns read but not yet registered, by the client's name for them.\n *\n * A run can be stopped from `register` on, and named from `run-start` on. What\n * `/stop` could not reach was a turn still waiting its place on the thread —\n * which is where a user who sent twice and thought better of it presses stop,\n * and the wait is now as long as the old run's unwind. Falling through to\n * `threadId` there found the old run, already stopping, said `stopped: true`,\n * and the queued turn started anyway: unwatched, billing, and with no handle\n * left on the client that had let go of it. The entry is marked rather than\n * removed, because the turn itself is what answers once its wait is over.\n */\nconst pendingTurns = new Map<string, { cancelled: boolean; owner: string | null }>();\n\n// --- limits (#444) -------------------------------------------------------\n\n/** `AgentController.maxBodyBytes`'s default. */\nexport const DEFAULT_MAX_BODY_BYTES = 4 * 1024 * 1024;\n/** `AgentController.maxHistoryMessages`'s default. */\nexport const DEFAULT_MAX_HISTORY_MESSAGES = 1000;\n/** `AgentController.maxConcurrentRuns`'s default. */\nexport const DEFAULT_MAX_CONCURRENT_RUNS = 5;\n/** The cap on `attach` and `stop` bodies, which carry ids and nothing else. */\nconst SMALL_BODY_BYTES = 64 * 1024;\n\nconst noop = () => {};\n\n/**\n * The runs each `runLimitKey` has going, by lane: a thread is one lane however\n * many turns are queued or superseding on it, and a stateless turn is a lane\n * of its own. A lane is held from the moment its turn is admitted until its\n * last run ends.\n */\nclass RunSlots {\n private byKey = new Map<string, Map<string, number>>();\n\n /**\n * Admits a turn in `lane` for `key`, or answers `null` when `key` already\n * holds `limit` other lanes. Synchronous, so two turns arriving together\n * cannot both see the last free slot. The function it returns frees the\n * turn's hold; calling it twice is harmless.\n */\n take(key: string, lane: string, limit: number): (() => void) | null {\n let lanes = this.byKey.get(key);\n if (!lanes?.has(lane) && (lanes?.size ?? 0) >= limit) {\n return null;\n }\n if (!lanes) {\n lanes = new Map();\n this.byKey.set(key, lanes);\n }\n lanes.set(lane, (lanes.get(lane) ?? 0) + 1);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = this.byKey.get(key);\n const count = (current?.get(lane) ?? 1) - 1;\n if (!current) return;\n if (count > 0) {\n current.set(lane, count);\n } else {\n current.delete(lane);\n if (current.size === 0) this.byKey.delete(key);\n }\n };\n }\n}\n\n/**\n * Slots are counted per `liveRuns` registry rather than per process: the\n * registry is what holds the runs being counted, and an app (or a test) with\n * two registries has two sets of runs.\n */\nconst runSlots = new WeakMap<object, RunSlots>();\nfunction runSlotsFor(liveRuns: object): RunSlots {\n let slots = runSlots.get(liveRuns);\n if (!slots) {\n slots = new RunSlots();\n runSlots.set(liveRuns, slots);\n }\n return slots;\n}\n\n/**\n * The key that carries `Body` on the instance type.\n *\n * A `declare const` unique symbol, so it exists only in the type layer — the\n * same device `Schema.ts` uses for its output type, and for the same reason: a\n * real property would be one an app could see, serialise or depend on.\n */\ndeclare const BODY: unique symbol;\n\n/**\n * What `authorizeRequest` is told about the request, per route.\n *\n * A union on `route` because `body` exists on only two of them: `stream` and\n * `upload` carry the client's `body` option, `attach` and `stop` carry none.\n * Typing it optional everywhere would make every reader of `body.pageId` on\n * `stream` write a check for a case that cannot happen there; narrowing on\n * `route` says which case it is. An override written against the older\n * `{ route; threadId? }` shape still accepts every member.\n */\nexport type AuthorizeRequestParams<Body extends object = Record<string, unknown>> =\n | { route: \"stream\" | \"upload\"; threadId?: string; body: Body }\n | { route: \"attach\" | \"stop\"; threadId?: string; body?: undefined };\n\nexport abstract class AgentController<\n A extends AnyAgent = AnyAgent,\n /**\n * The extra fields `useChat`'s `body` option sends with every turn, as they\n * arrive in `instructions()` and on `ctx.body`.\n *\n * Declaring it also types the client: `useChat` reads it back off the route\n * through `AgentRouteRPC`, so a `body` the controller does not expect is a\n * compile error at the call site rather than an `undefined` three layers\n * into a tool. It types the shape, not the contents — see `instructions`.\n *\n * Constrained to `object`, not `Record<string, unknown>`: an `interface` gets\n * no implicit index signature, so the tighter bound refused\n * `interface PageBody { pageId: string }` with a `TS2344` that names the\n * constraint and not the reason. An interface is how most apps write a request\n * shape, and turning that into a puzzle about `type` versus `interface` is a\n * poor first impression of the feature.\n */\n Body extends object = Record<string, unknown>,\n> extends ControllerBase {\n static kind = \"agent-controller\" as const;\n\n /**\n * `Body`, in a position nothing can shorten away.\n *\n * It has to appear on the instance type for `AgentRouteRPC` to infer it, and\n * `instructions`'s second parameter is not a safe place to leave that job:\n * TypeScript's parameter-wise inference stops at the shorter signature, so a\n * controller overriding `instructions(req)` — which is every override written\n * before this existed, since that was the only signature — supplied no\n * candidate and silently fell back to the open record. The client-side\n * checking then vanished on the most ordinary upgrade path, with nothing to\n * read.\n *\n * `declare` so it emits no field: there is no value here, only a type for\n * `infer B` to find. Optional and never assigned, so no subclass has to\n * mention it.\n */\n declare readonly [BODY]?: Body;\n\n /** The agent this controller serves. A property rather than a constructor\n * argument so `Router.agent(ChatController)` can take the class, matching how\n * every other controller is mounted. */\n abstract agent: A;\n\n /**\n * Defaults to the process-wide `MemoryAgentStore`.\n *\n * Whatever you put here, make it something that outlives the request: this\n * controller is constructed fresh for every call, so `store = new\n * MemoryAgentStore()` written here is an empty store on every turn and a\n * threaded conversation silently reads back nothing. Assign a module-level\n * instance, or a store whose state is somewhere else entirely.\n */\n store: AgentStore = defaultAgentStore;\n\n /**\n * Defaults to the process-wide map. Overridable so a test — or an app running\n * two agents that must not see each other's runs — can hold its own; not so\n * that it can be moved off the process, which is not a thing that can be\n * done. See `MemoryLiveRuns`.\n */\n liveRuns: MemoryLiveRuns = defaultLiveRuns;\n\n /**\n * Where attachment *records* live — the row that says which bytes, whose, and\n * under what id. Defaults to the process-wide `MemoryAttachmentStore`, with\n * the same warning `store` carries: assign something that outlives the\n * request, because this controller is constructed per call.\n */\n attachments: AttachmentStore = defaultAttachmentStore;\n\n /**\n * Where an attachment's *bytes* live. Defaults to the app's configured\n * `FileStorage` through the `Storage` facade, which resolves the driver per\n * call out of the container — so an app that configured S3 gets S3 here\n * without saying so twice.\n *\n * Overridable mostly for tests and for an app that keeps user uploads in a\n * different bucket from everything else.\n */\n attachmentStorage: AttachmentStorage = Storage;\n\n /**\n * Who uploaded each provider file id (#443). `upload` records the id under\n * `runOwner(req)`, and `stream` refuses a turn whose files name an id\n * recorded for another owner with a 403 `{ error: { kind: \"permission\",\n * message, status } }`. Defaults to the process-wide `MemoryFileOwners`; the\n * same warning as `store` applies — assign something that outlives the\n * request. An app with several processes, or that wants the binding to\n * survive a restart, gives it a table (see `FileOwners`).\n */\n fileOwners: FileOwners = defaultFileOwners;\n\n /**\n * Where the nonce of each answered approval or question is spent, which is\n * what makes a signed answer single-use (#445). On a stateless chat the\n * client carries its history and can rewind it to before a result existed;\n * the spent nonce is then the only thing that refuses the replayed answer.\n *\n * Defaults to the process-wide `MemoryNonceStore`, which is exact for one\n * instance and forgets on restart. An app running several instances (or\n * behind a load balancer whose affinity is best effort) assigns a shared\n * store, built once at module scope like `store`:\n *\n * const nonces = new RedisNonceStore();\n * class ChatController extends AgentController<typeof chat> {\n * nonces = nonces;\n * }\n *\n * or its own `NonceStore` over a table keyed by the nonce. In production a\n * stateless turn served with the in-memory default logs a warning once.\n */\n nonces: NonceStore = defaultNonceStore;\n\n /**\n * Where approved tools' executions are claimed and their results recorded,\n * so that an approval runs its tool at most once (#458). Off by default.\n *\n * The nonce makes an answer single-use; it does not remember what the tool\n * did. So a retried submit whose response was lost is refused (\"already\n * used\") although the tool acted, and an answer that reaches two instances\n * with unshared nonce stores runs the tool twice. With a receipt store the\n * first presentation claims the execution and records its result; a later\n * one gets that result back without running anything, and one that arrives\n * while the first is still running gets a `tool_error` result for the model.\n *\n * Assign one built at module scope, like `nonces`, shared by every instance:\n *\n * const receipts = new RedisReceiptStore();\n * class ChatController extends AgentController<typeof chat> {\n * receipts = receipts;\n * }\n *\n * or your own `ReceiptStore` over a table (see `store/Receipts.ts`).\n * `MemoryReceiptStore` is exact for one instance only.\n */\n receipts?: ReceiptStore;\n\n /**\n * Whether a turn may name a provider file id that `fileOwners` has no record\n * of. `false` by default, which is what keeps the change additive: an id\n * uploaded before the upgrade, before a restart (with the in-memory default),\n * on another process, or by the app outside `upload` still works, as every id\n * did before. An id that IS recorded for someone else is refused either way.\n *\n * Set it to `true` once `fileOwners` is durable and shared, to make the\n * binding complete: then an id is usable only by the owner it was recorded\n * for, or by anyone when it was recorded as anonymous. On a stateless chat\n * the client carries its history, so this also refuses a file a tool attached\n * earlier in the conversation; a strict app keeps its chats on a thread.\n */\n protected requireKnownFiles = false;\n\n /**\n * How long the request that started a run is held open for its hooks, in\n * milliseconds, once the run has settled. The run itself is not bounded\n * here — the request is held for as long as it runs — only the app's code\n * still going after it, from `onMessage` to an `onAwaitingInput` queued\n * behind a slow `onToolCall`.\n *\n * The hooks read the user from that request (`ctx.req.ctx().user`,\n * `Auth.user()`, a policied query), so the request stays open until they are\n * done; but a hook that never settles — a `fetch` with no timeout — would\n * then hold the store, the user and `onRequestEnd` forever, one per turn. Past\n * this the request ends anyway: `onRequestEnd` runs, the user is released,\n * and the hook runs on without one. Thirty seconds is far past a healthy\n * write or notification, so a hook that reaches it is hung rather than slow.\n * Raise it for a hook that is legitimately longer; `Infinity` holds the\n * request until the hooks are done, however long that is.\n */\n protected hookHoldMs = 30_000;\n\n /**\n * Appended to the agent's static instructions for this request — the user's\n * name, tenant, today's date.\n *\n * `body` is what `useChat`'s `body` option sent, with the four keys the wire\n * format owns removed. It is the only way to read it here: this controller\n * consumes the request body itself, so `await req.input()` answers `Body\n * already used` and takes the whole turn down with it.\n *\n * It is client-controlled, exactly like any request body. `Body` types what\n * arrives, it does not check it — a client can send anything, and a tenant id\n * read from here is the client's claim about which tenant it wants, not the\n * middleware's finding about who it is.\n */\n instructions(req: HttpRequest<any, any>, extra: { body: Body }): string | Promise<string> | void {\n void req;\n void extra;\n }\n\n /**\n * What every tool of this turn's run gets as `ctx.context` — the user, the\n * tenant, functions the tools call back into. See `AgentContext`.\n *\n * The run is not given the request, so this is where the request's facts\n * become the run's: read the user the middleware authenticated here, and a\n * tool reads it from `ctx.context` instead of reaching for `req`. Runs after\n * `authorizeRequest()`, once per turn, and before anything is asked of the\n * model.\n *\n * The default is `{}`. An app that gives `AgentContext` a required field must\n * override this: the type of the default cannot see the app's declaration,\n * so forgetting is a tool that finds the field missing, not a compile error.\n *\n * Values from `body` are the client's claim, exactly as in `instructions()`;\n * putting one here does not make it any more trustworthy, only easier to\n * mistake for something the server decided.\n */\n context(req: HttpRequest<any, any>, extra: { body: Body }): AgentContext | Promise<AgentContext> {\n void req;\n void extra;\n return {} as AgentContext;\n }\n\n /**\n * Refuse a turn that arrives without a `threadId`, with a 400\n * `thread_required`, before anything runs.\n *\n * A stateless turn is otherwise open to any caller the route's middleware\n * lets through: the client carries the history, so the model runs, and is\n * billed, as a general-purpose chat. An app whose tools resolve their subject\n * from the thread can make them refuse such a turn, but the model has still\n * been paid for by then.\n *\n * It governs `stream` only. `upload` can still reach the provider without a\n * thread (a `provider` destination); refuse that in `authorizeRequest`.\n */\n protected requireThread = false;\n\n /**\n * The largest JSON body `stream` reads, in bytes (#444). Default 4 MB.\n *\n * A turn is a few kilobytes; even a long stateless chat carrying its whole\n * history is well under a megabyte, since files travel by id and not inline.\n * Without a cap the route read whatever arrived (the production server\n * accepts up to 10 GB), parsed it, and sent it to the provider at the app's\n * expense. A body over it is refused with a 413 `{ error: { kind, message,\n * status, code: \"body_too_large\" } }` before it is parsed, and before\n * `authorizeRequest`. Checked against `Content-Length` when there is one and\n * against the bytes read otherwise, so a chunked body cannot get past it.\n * `attach` and `stop` carry only ids and are held to 64 KB. `Infinity` turns\n * it off.\n */\n protected maxBodyBytes = DEFAULT_MAX_BODY_BYTES;\n\n /**\n * The most messages a stateless turn's client-carried history may hold\n * (#444). Default 1000. A longer one is a 413 `history_too_long` before\n * anything runs. Only `body.messages` counts: a threaded turn reads its\n * history from the store, which the client does not write. Every message is\n * sent to the model on every step, so this bounds what one turn can be billed\n * for as much as `maxBodyBytes` does. `Infinity` turns it off.\n */\n protected maxHistoryMessages = DEFAULT_MAX_HISTORY_MESSAGES;\n\n /**\n * How many runs one caller may have going at once in this process (#444).\n * Default 5. A run outlives the request that started it (so `attach` can\n * find it), which means a client can post a turn and disconnect and the run\n * still bills up to `maxSteps` model calls; without a cap, a thousand posts\n * were a thousand runs.\n *\n * Counted per `runLimitKey` (by default `runOwner`, the authenticated user),\n * and per conversation rather than per request: every turn on one thread is\n * one slot, because a thread holds one run at a time and a new turn there\n * supersedes the old one rather than adding to it. So a user resending\n * mid-answer is never refused; a user with five chats answering at once and\n * starting a sixth is, with a 429 `{ error: { kind: \"rate_limit\", message,\n * status, code: \"too_many_runs\" } }`, after `authorizeRequest` and before the\n * model is asked anything. A slot is freed when the run ends (stopped, timed\n * out, or finished). `Infinity` turns it off.\n */\n protected maxConcurrentRuns = DEFAULT_MAX_CONCURRENT_RUNS;\n\n /**\n * Who `maxConcurrentRuns` counts a turn against (#444). The default is\n * `runOwner`'s answer, the authenticated user; `null` is not counted.\n *\n * An anonymous turn is therefore not limited by default, because there is\n * nothing sound to count it under: a client address is the proxy's unless\n * `GEMI_TRUST_PROXY` is set, which would put every visitor in one bucket, and\n * the session cookie is the visitor's to drop. An app that serves anonymous\n * chats returns its own key here (`ip:${clientIp(req)}` behind a trusted\n * proxy, say), sets `requireThread`, or puts `RateLimitMiddleware` on the\n * route.\n */\n protected runLimitKey(\n req: HttpRequest<any, any>,\n params: { owner: string | null; threadId?: string },\n ): string | null | Promise<string | null> {\n void req;\n return params.owner;\n }\n\n /**\n * Decides whether this caller may use this route, on every one of the four:\n * `stream`, `attach`, `stop` and `upload` (#542). Throw a request breaker\n * (`InsufficientPermissionsError`, say) to refuse; return to let it through.\n *\n * It runs before the route does any work of its own: on `stream`, ahead of\n * the thread's lock and load, `instructions()` and the provider, so a refused\n * turn is not charged for, waits behind no run and does not learn whether its\n * thread exists; on `attach`, before a live run's frames are read.\n *\n * `threadId` is the one the client sent, taken on trust and not yet checked\n * against the store — which is what makes this the place to check that the\n * caller owns it. A thread-scoped app that checks it here on every route\n * keeps a thread's live answer, its stop button and its attachments to its\n * owner. It is `undefined` when the request names no thread: a stateless\n * turn, an upload without one, a stop by `runId` or `clientRunId`.\n *\n * `body` is the client's `body` option — the same object `instructions()`,\n * `context()` and `attachmentScope()` get — on the two routes that carry it,\n * `stream` and `upload` (#603). A chat with no thread and no user names its\n * subject there (a page id, say), and this is where to check that the caller\n * may touch it. `attach` and `stop` carry no body, so it is absent on them;\n * narrow on `route` to read it. Like `threadId` it is the client's claim,\n * unchecked.\n */\n protected authorizeRequest(\n req: HttpRequest<any, any>,\n params: AuthorizeRequestParams<Body>,\n ): void | Promise<void> {\n void req;\n void params;\n }\n\n /**\n * WHO OWNS A RUN THIS REQUEST STARTS, and who a request to `attach` or `stop`\n * one is (#442). An opaque key, compared with `===`; `null` is nobody.\n *\n * `stream` records it on the run, and from then on the run answers only that\n * key: `attach` to it, `stop` of it (by `runId`, `threadId` or `clientRunId`,\n * including a turn still waiting its place), and a turn on its thread that\n * would supersede it while it is still going are each refused with a 403\n * `{ error: { kind: \"permission\", message, status } }` for any other caller.\n * That holds whatever `authorizeRequest` says, which is the point: every\n * handle on a run is one a third party can come to hold (a shared link, a\n * log line, a guessable `clientRunId`), and none of them says whose it is.\n *\n * THE DEFAULT IS THE AUTHENTICATED USER, `user:<id>`, and `null` without one.\n * A `null` owner records an unowned run, which answers whoever holds a\n * handle — exactly what every run did before this existed. So:\n *\n * - an anonymous turn starts an unowned run; its `threadId` stays the\n * capability. `sessionId()` is not used as a fallback: it is a cookie the\n * visitor writes, it can be minted between the turn and the reattach (a\n * view visited in between), and a mismatch would lock a visitor out of\n * their own run. An app with its own anonymous identity returns it here.\n * - a run started by an authenticated user cannot be read or stopped by an\n * anonymous request, nor by another user.\n * - a run the server starts itself (registered on `liveRuns` with no\n * `owner`) is unowned.\n *\n * Override it for anything wider than a user — a thread shared by a team\n * returns `team:<id>` (from the user, never from the body) — or `null` to\n * turn the check off. Whatever it reads must be present on all of `stream`,\n * `attach` and `stop`, the same rule `attachmentScope` states: guard the three\n * routes with the same middleware.\n *\n * It is also the `subject` every pending call of the run is signed for\n * (#447): an approval or answer is accepted only on a turn whose `runOwner`\n * is the one the question was asked of. So it must answer the same on the\n * turn that asks and the turn that answers.\n */\n protected runOwner(req: HttpRequest<any, any>): string | null | Promise<string | null> {\n const user = req.ctx?.()?.user;\n const userId = user?.id ?? user?.publicId;\n if (userId !== undefined && userId !== null && String(userId) !== \"\") {\n return `user:${String(userId)}`;\n }\n return null;\n }\n\n /**\n * `POST /<path>` — one route for every client turn. A first message, an\n * approval, an answer to a question and a client tool's result are all just\n * the next turn, so none of them gets an endpoint of its own.\n */\n async stream(req: HttpRequest<any, any> = new HttpRequest()): Promise<Response> {\n const parsed = await readJsonBody(req, this.maxBodyBytes);\n if (parsed.error) {\n // Before anything is registered or charged for. A run started off a body\n // we could not read would answer nothing, at the user's expense.\n return invalidRequest(parsed);\n }\n const body = parsed.body;\n const threadId = typeof body.threadId === \"string\" ? body.threadId : undefined;\n const parsedTurn = toClientTurn(body);\n if (parsedTurn.error) {\n return invalidRequest({ body: {}, error: parsedTurn.error });\n }\n // Reassigned by a regenerate: the turn run again is the one the store holds.\n let turn = parsedTurn.turn;\n // Replace the thread's last answer rather than answer after it (#451). Only\n // meaningful on a thread: a stateless client trims its own history.\n const regenerate = threadId !== undefined && body.regenerate === true;\n const clientRunId = typeof body.clientRunId === \"string\" ? body.clientRunId : undefined;\n // The app's fields, separated once and handed to every method that reads\n // them — `authorizeRequest`, `instructions`, `context`, `attachmentScope` —\n // so none of them can disagree about what the client sent. They cannot read\n // it themselves: `readJsonBody` has consumed the request's body by now.\n const extraBody = appBody<Body>(body);\n\n // Before `pendingTurns`, so a refused turn leaves nothing for `/stop` to\n // find. It does not yield, unlike `authorizeRequest` below.\n if (this.requireThread && !threadId) {\n return jsonResponse(400, {\n code: \"thread_required\",\n message: \"This agent takes a turn only on a thread: send a threadId.\",\n });\n }\n\n if (regenerate && !this.store.removeMessages) {\n return jsonResponse(501, {\n code: \"regenerate_unsupported\",\n message:\n \"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore.\",\n });\n }\n\n // The client's history is the only part of a stateless turn whose size the\n // client chooses and the model is billed for on every step (#444). A\n // threaded turn's `messages` are ignored, so they are not counted.\n if (\n !threadId &&\n Array.isArray(body.messages) &&\n body.messages.length > this.maxHistoryMessages\n ) {\n return limitResponse(\n 413,\n \"history_too_long\",\n `The conversation has ${body.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`,\n );\n }\n\n // Who this run will belong to. Read before `pending` exists, so a stop that\n // finds the pending turn can already be checked against it. See `runOwner`.\n const owner = await this.runOwner(req);\n\n // From here until `register`, the only thing `/stop` can find this turn by.\n // See `pendingTurns`.\n const pending = clientRunId ? { cancelled: false, owner } : null;\n if (pending) {\n pendingTurns.set(clientRunId, pending);\n }\n\n // The whole of the stateless/threaded difference, in one expression: with a\n // thread the server owns the history, without one the client carries it.\n // Nothing else below branches on it, which is why stateless keeps working\n // even for an app that never configures a store.\n //\n // The `threadId` is the client's, and nothing here checks that this caller\n // owns it — `AgentStore` cannot, since it holds no user. A `threadId` is\n // therefore a capability and has to be unguessable (`createThread` mints a\n // uuid) and, for anything that matters, checked: override `authorizeRequest()`\n // or give it a `store` that scopes by `req.user`. The framework's job is to make\n // sure the route is behind the router's middleware in the first place,\n // which `ApiRouter.agent()` now does.\n //\n // Everything from the load on happens inside `start`, which on a thread\n // runs under the thread's lock once the previous run's transcript is in the\n // store — the load has to come after that, or it reads a history the old\n // answer is missing from. `instructions()` follows the load in there rather\n // than running ahead of the lock, so that a dead thread is still a 404\n // before the app's own work is spent on it; the cost is that a turn queued\n // behind this one waits for `instructions()` as well.\n // The run `start` registered, if it got that far: its end is what frees\n // this turn's `maxConcurrentRuns` slot.\n let started: AgentRun | null = null;\n // What a regenerate took out of the thread, kept until the run replacing\n // it has started.\n let removed: AgentMessage[] = [];\n const start = async (): Promise<Response> => {\n try {\n return await startRun();\n } finally {\n // A regenerate that never started its run — stopped while it waited,\n // or a throw from the app's hooks — puts back what it took out, since\n // no new answer is coming to replace it. Still under the thread's lock,\n // and appended at the end, which is where it was: it was the tail.\n if (threadId && removed.length > 0 && (started as AgentRun | null) === null) {\n await this.store\n .appendMessages(threadId, removed)\n .catch((err) => this.reportHookFailure(err));\n }\n }\n };\n const startRun = async (): Promise<Response> => {\n let messages: AgentMessage[];\n if (threadId) {\n const history = await this.store.loadThread(threadId);\n if (!history) {\n // Before `instructions()` and before the run: nothing has been\n // charged for, and the client has to learn that its thread is gone —\n // expired, mistyped, or on an instance that no longer exists — rather\n // than see it answered as an empty conversation and have this turn\n // persisted under the dead id.\n //\n // That ordering is deliberate. An ownership check belongs in\n // `authorizeRequest()`, which has already run; one left in\n // `instructions()` has not, so a caller holding a uuid learns whether\n // it is live here without the app's say. The id is unguessable, so\n // the load stays above `instructions()`, whose own work (a database\n // read, typically) would otherwise be spent on a thread that is gone.\n // Move it below and that work is spent on every dead id instead.\n return jsonResponse(404, {\n code: \"thread_not_found\",\n message: `Thread ${threadId} does not exist here, or has expired.`,\n });\n }\n // A message a dead run left unfinished is closed here, and written\n // back, before the run is handed the history: the model then reads it\n // as interrupted, and its open calls have results. Under the thread's\n // lock and after the previous run's transcript is stored, so the only\n // unfinished message left is one no run in this process owns.\n messages = await this.settleThread(threadId, history, { write: true });\n if (regenerate) {\n const cut = regenerationCut(messages);\n if (!cut) {\n return jsonResponse(409, {\n code: \"nothing_to_regenerate\",\n message: `Thread ${threadId} has no user turn to answer again.`,\n });\n }\n // The last user turn and everything after it leave the store, and the\n // turn is run again from what the store held — not from the client's\n // copy, which may be stale or carry local ids. The user message comes\n // back under a new id when the run reports it. Under the thread's\n // lock and after the previous run's transcript is stored, so nothing\n // writes the removed answer back. Each removed message takes its\n // `usage` with it: the thread never holds both answers' costs.\n removed = messages.slice(cut.index);\n await this.store.removeMessages!(\n threadId,\n removed.map((message) => message.id),\n );\n messages = messages.slice(0, cut.index);\n // The stored turn, under the client's `localId` for it: the message\n // is minted again, and the client has to be told the new id (#466).\n turn = turn?.localId ? { ...cut.turn, localId: turn.localId } : cut.turn;\n }\n } else {\n messages = Array.isArray(body.messages) ? (body.messages as AgentMessage[]) : [];\n warnInMemoryNonces(this.nonces);\n }\n\n const instructions = (await this.instructions(req, { body: extraBody })) || undefined;\n const context = await this.context(req, { body: extraBody });\n // Above the cancel check, not below it, and that placement is the whole\n // reason this is a separate statement rather than an argument on the call\n // below: the comment on that check says nothing yields between it and\n // `register`, and an `await` for the app's `attachmentScope()` — a\n // database read, in any app that has one — is exactly the yield a stop\n // would land in and be missed.\n const attachments = await this.attachmentsFor(req, threadId, { body: extraBody });\n\n if (pending?.cancelled) {\n // Stopped while it waited. Nothing has been asked of the model and\n // nothing registered, so there is no run to end and nothing charged\n // for. Checked after the last `await` above, so that a stop landing\n // during it is not missed: from here to `register` nothing yields.\n return stoppedBeforeStart();\n }\n\n // Only a threaded turn has anywhere to be written as it runs. See\n // `TurnJournal`.\n const journal = threadId\n ? new TurnJournal(this.store, threadId, messages, (err) => this.reportHookFailure(err))\n : null;\n\n // Chosen here rather than by the run, so the hook context exists before\n // the run does: `redactError` below is handed it, and the run may call\n // it for its first frame.\n const runId = `run_${crypto.randomUUID()}`;\n const ctx: AgentHookContext = { req, runId, threadId };\n\n const run = this.agent.stream({\n runId,\n messages,\n turn,\n threadId,\n // The run reports each message as it finishes it, the user's turn\n // first and before the model is asked anything. Only the store hears\n // about it here: the app's `onMessage` still runs after the run, in\n // `notifyRun`, as it always has.\n ...(journal ? { onMessage: (message: AgentMessage) => journal.finish(message) } : {}),\n instructions,\n // Built from this request once, here, and the only thing the run knows\n // about who asked. The run has no request of its own — see\n // `AgentContext` — so a tool that needs the user reads it from this.\n context,\n // Resolved once, above, and handed to every tool of the run as\n // `ctx.attachments`. It is derived from the request — the user the\n // middleware authenticated, or the thread — and never from anything the\n // model can write, which is the property that makes an attachment id\n // safe to give a model at all. `null` for a request with no subject:\n // tools still get an object, and it throws with a sentence naming\n // `attachmentScope()`.\n attachments,\n // The same object `instructions()` was handed, so the two cannot\n // disagree about what the client sent — and carried on the run\n // because a run outlives the request that started it. By the time a\n // tool executes, the body is long gone.\n // Cast because `Body` is constrained to `object` so an `interface` can be\n // used, and an interface has no index signature to satisfy\n // `Record<string, unknown>`. The value is a parsed JSON object either\n // way; the constraint is about what an app may declare, not about what\n // arrives.\n body: extraBody as Record<string, unknown>,\n // What the client, and for a tool's exception the model, is told about\n // a failure. See `redactError`.\n redactError: (error, info) => this.redactError(error, info, ctx),\n // Where answers' nonces are spent. See `nonces`.\n nonces: this.nonces,\n // Where approved tools' executions are recorded. See `receipts`.\n receipts: this.receipts,\n // The principal its pending calls are bound to (#447): an answer is\n // only accepted from the same `runOwner` the question was asked of.\n subject: owner,\n }) as AgentRun;\n\n // Registered before the response is built: the run is now owned by the\n // process rather than by this request, which is the property `/attach`\n // depends on and the reason a dropped connection no longer cancels\n // anything.\n const eventHooks = this.liveRuns.register(run, {\n threadId,\n // Who may attach to it and stop it from now on. See `runOwner`.\n owner,\n // The client's handle on a run it started, which is the only one that\n // exists before `run-start` reaches it. See `RegisterParams`.\n clientRunId,\n onEvent: (event) => this.dispatchEvent(event, ctx),\n onInternalError: (err) => this.reportHookFailure(err),\n // So the registry's age ceiling never cuts short a run its agent\n // allowed to be longer. See `MemoryLiveRuns.maxAgeMs`.\n maxRunDurationMs: this.agent.maxRunDurationMs,\n });\n\n started = run;\n if (journal) this.follow(run, journal);\n\n // Kept, not just fired: the next turn on this thread has to know when\n // this one's transcript is in the store. See `withThread`. The request\n // waits for more than the thread does — the hooks as well — so that\n // `onMessage` still finds the user who sent the message; the thread\n // waits only for the store, so a slow hook is not a slow next turn.\n const { stored, hooks } = this.persistRun(run, ctx, eventHooks, journal);\n persisted.set(run, stored);\n // Registered now, while the request is certainly open: `waitUntil` is\n // ignored once it has ended, and the run settling can end it before a\n // single hook has been called.\n req.ctx?.()?.waitUntil(hooks);\n\n return run.toResponse();\n };\n\n try {\n // After `pending` is registered, not before: the app's check is a yield —\n // a database read, typically — and a stop pressed during it has to find\n // this turn. Before the thread's lock, which ends the thread's previous\n // run, so a refused or stopped turn does not end it either.\n await this.authorizeRequest(req, { route: \"stream\", threadId, body: extraBody });\n // After the app's check, so a caller it refuses does not learn which ids\n // are someone's; before the thread's lock, so a refused turn supersedes\n // nothing. The client's history only counts without a thread: with one,\n // `body.messages` is ignored and the history comes from the store.\n const foreign = await this.foreignFile(\n [...(turn?.files ?? []), ...(threadId ? [] : clientHistoryFiles(body.messages))],\n owner,\n );\n if (foreign) {\n return foreign;\n }\n if (pending?.cancelled) {\n return stoppedBeforeStart();\n }\n // After the app's check, so a refused caller spends no slot; before the\n // thread's lock, so a turn over the limit waits behind nothing. No yield\n // between the count and the take: see `RunSlots.take`.\n const limitKey = await this.runLimitKey(req, { owner, threadId });\n const release =\n limitKey === null\n ? noop\n : runSlotsFor(this.liveRuns).take(\n limitKey,\n threadId ? `thread:${threadId}` : `run:${crypto.randomUUID()}`,\n this.maxConcurrentRuns,\n );\n if (!release) {\n return limitResponse(\n 429,\n \"too_many_runs\",\n `You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`,\n );\n }\n try {\n return threadId ? await this.withThread(threadId, owner, start) : await start();\n } finally {\n // A turn that never started a run (a dead thread, stopped while it\n // waited, a throw) frees its slot now; one that did, when the run ends.\n const run = started as AgentRun | null;\n if (run) {\n run.result().then(release, release);\n } else {\n release();\n }\n }\n } finally {\n if (pending && pendingTurns.get(clientRunId) === pending) {\n pendingTurns.delete(clientRunId);\n }\n }\n }\n\n /**\n * A thread holds one run at a time; a new turn on it ends the old one first.\n *\n * Since a dropped connection no longer stops a run, a user who sends again\n * mid-answer used to leave the first run going. It could not see the new\n * turn, the new run's `loadThread` could not see its answer, and both\n * appended when they finished — in whichever order the model returned them,\n * so the thread read `user2, assistant2, user1, assistant1`. `byThread` then\n * named the second run while the first was still live and unstoppable by\n * `threadId`.\n *\n * Stopping the old run and waiting for its transcript to land is chosen over\n * refusing the new turn with a 409, because sending again *is* the stop: it\n * is what `useChat.send` means, and a client that has to poll `/stop` until\n * the run is really gone before it may post the turn it has already shown is\n * a worse client for no better thread. The cost is that the new turn waits\n * for the old run to unwind, which is as long as its slowest tool in flight —\n * and that wait is the thing that puts `assistant1` before `user2`.\n *\n * The wait is on `persistRun`'s `stored`, not on `run.result()`. `result()`\n * settling is the transcript being final, not stored: `appendMessages` runs\n * after it, and a `loadThread` in that gap reads a history the old answer is\n * missing from, which is the original bug by a shorter route. It is also\n * *only* that: `stored` settles once the transcript is stored, and the app's\n * hooks run on in `hooks`, which holds the old run's request and not the\n * thread, so a slow `onMessage` is not a slow thread and a hung one is not a\n * hung thread.\n *\n * The lock around it is what makes a *third* turn wait for the second rather\n * than for the first. Two turns arriving together both see the same live\n * run, both stop it, both wait for it, and both start — the same race, one\n * message later. Under the lock the later one finds the earlier one\n * registered and stops that instead. Per process, like `LiveRuns`, and for\n * the same reason: the run it guards lives here.\n */\n private async withThread(\n threadId: string,\n owner: string | null,\n fn: () => Promise<Response>,\n ): Promise<Response> {\n const previous = threadLocks.get(threadId) ?? Promise.resolve();\n let release!: () => void;\n const held = new Promise<void>((resolve) => {\n release = resolve;\n });\n const tail = previous.then(() => held);\n threadLocks.set(threadId, tail);\n await previous;\n try {\n const live = await this.liveRuns.find({ threadId });\n if (\n live &&\n this.liveRuns.isRunning(live.runId) &&\n !this.liveRuns.mayAccess(live.runId, owner)\n ) {\n // Superseding is a stop, and someone else's run is not this caller's to\n // stop (#442). Only while it is still going: an ended run is kept for\n // `ttlMs` but a turn after it touches nothing of it. Whether this caller\n // may post on the thread at all is `authorizeRequest`'s question.\n return notYourRun();\n }\n const run = live ? this.liveRuns.get(live.runId) : null;\n if (run) {\n // A run that already ended is still `find`-able for `ttlMs`; stopping\n // it is a no-op and waiting on it is the append it may still be doing.\n run.stop({ reason: \"superseded by a later turn on this thread\" });\n await persisted.get(run);\n }\n return await fn();\n } finally {\n release();\n if (threadLocks.get(threadId) === tail) {\n threadLocks.delete(threadId);\n }\n }\n }\n\n /**\n * `POST /<path>/attach` — subscribe to a run already in progress, from a\n * cursor. This is a read of a live run, not a continuation of a stopped one:\n * the work never paused, the listener changed.\n *\n * The cursor is `from`, else the client's `cursor`, else `Last-Event-ID`,\n * else the oldest frame still buffered — and it is honoured only for the run\n * the client's `runId` names. A cursor the buffer has dropped is a 410 naming\n * what survives; *no* cursor is the tail, because a page reattaching on mount\n * has no transcript to leave a hole in. See `resolveCursor`.\n */\n async attach(req: HttpRequest<any, any> = new HttpRequest()): Promise<Response> {\n const parsed = await readJsonBody(req, SMALL_BODY_BYTES);\n if (parsed.error) {\n return invalidRequest(parsed);\n }\n const body = parsed.body;\n const threadId =\n typeof body.threadId === \"string\" ? body.threadId : searchParam(req, \"threadId\");\n\n if (!threadId) {\n return jsonResponse(400, {\n code: \"invalid_request\",\n message: \"attach needs a threadId: it is the handle that survives a refresh.\",\n });\n }\n\n // Before the lookup: a refused caller learns neither whether a run is live\n // on the thread nor any frame of it.\n await this.authorizeRequest(req, { route: \"attach\", threadId });\n\n // The store is not consulted. This route answers whether a run is in\n // flight here, and a run it finds was started on a thread `stream` had\n // already loaded; a miss is `no_live_run` whether or not the thread exists,\n // because a client that gets one re-reads the thread anyway (see\n // `onAttachMiss`) and learns there. The thread's own 404 is `stream`'s,\n // where a turn would otherwise be persisted under it.\n const live = await this.liveRuns.find({ threadId });\n if (live && !this.liveRuns.mayAccess(live.runId, await this.runOwner(req))) {\n // Another caller's run (#442): none of its frames, ended or not.\n return notYourRun();\n }\n if (!live) {\n // An explicit miss, not a 200 with an empty stream. See `MemoryLiveRuns`:\n // behind a round-robin load balancer this is the common case, and it has\n // to be visible as one.\n return jsonResponse(404, {\n code: \"no_live_run\",\n message: `No run in progress for thread ${threadId} in this process.`,\n });\n }\n\n // A cursor is only a number if you know which run it counts within: `seq`\n // restarts at zero in every run, so honouring a cursor from run_1 against a\n // live run_2 would skip that many frames off the head of a run this client\n // has seen nothing of. `runId` is the client saying which run its cursor\n // means; naming one that is not live forfeits the cursor and takes the\n // tail, which is as close to the start as the buffer can offer.\n //\n // Only a MISMATCH forfeits. An absent `runId` is not a wrong answer, it is\n // an older question: `from` and `Last-Event-ID` predate the pairing and\n // carry no run, and an `EventSource` reconnecting on its own will never\n // grow one. Those keep resuming exactly as before.\n const cursorRunId = typeof body.runId === \"string\" ? body.runId : undefined;\n const cursor = cursorRunId && cursorRunId !== live.runId ? undefined : resolveCursor(req, body);\n\n try {\n return sseResponse(this.liveRuns.replay(live.runId, cursor));\n } catch (err) {\n if (err instanceof FrameCursorEvictedError) {\n // 410 rather than 404: the run is there, the position is not. A client\n // that gets this reloads the thread instead of resuming into a hole.\n return jsonResponse(410, {\n code: err.code,\n message: err.message,\n oldestSeq: err.oldest,\n });\n }\n if (err instanceof LiveRunNotFoundError) {\n // Lost the race with eviction between `find` and `replay`.\n return jsonResponse(404, { code: err.code, message: err.message });\n }\n throw err;\n }\n }\n\n /**\n * `POST /<path>/stop` — the explicit cancel. Since a dropped connection no\n * longer stops a run, this and a later turn on the same thread are the only\n * things that do, and it is why stopping cannot be a client-side concern:\n * the tool loop is here, and a client that stops reading has not stopped\n * step four from charging a card.\n *\n * Returns as soon as the run is aborted, not when it has finished unwinding.\n * The terminal events — the stopped tool results, the aborted message — go\n * out on the run's own stream, so whoever is watching it sees the ending,\n * and `onMessage` records it whether anyone is watching or not.\n *\n * Answers `{ stopped }` normally, and a `Response` only to reject a request\n * it could not read — the union is the error, not a second success shape.\n */\n async stop(\n req: HttpRequest<any, any> = new HttpRequest(),\n ): Promise<{ stopped: boolean } | Response> {\n const parsed = await readJsonBody(req, SMALL_BODY_BYTES);\n if (parsed.error) {\n // `{ stopped: false }` would be the wrong answer as well as the wrong\n // status: it means \"there was nothing to stop\", and the truth is that we\n // could not tell what to stop. A client that believes the first one stops\n // asking, and the run keeps going.\n return invalidRequest(parsed);\n }\n const body = parsed.body;\n\n await this.authorizeRequest(req, {\n route: \"stop\",\n threadId: typeof body.threadId === \"string\" ? body.threadId : undefined,\n });\n\n // Three handles, most specific first, because which ones the client has\n // depends on how far the run got. `runId` is the server's own and settles\n // it. `clientRunId` covers the window before `run-start`, when the client\n // has nothing else for a stateless first turn — and, before that, a turn\n // that has not become a run yet because it is waiting its place on the\n // thread, which is ended where it waits. `threadId` is the fallback for a\n // client that did not start this run at all — one that attached to it,\n // whose replayed tail carried no `run-start`.\n const caller = await this.runOwner(req);\n let runId = typeof body.runId === \"string\" ? body.runId : undefined;\n if (!runId && typeof body.clientRunId === \"string\") {\n runId = this.liveRuns.findByClientRunId(body.clientRunId) ?? undefined;\n if (!runId) {\n const pending = pendingTurns.get(body.clientRunId);\n if (pending) {\n // A `clientRunId` is the client's own choice and only as unguessable\n // as it made it, so the turn it names is checked like a run (#442).\n if (pending.owner !== null && pending.owner !== caller) {\n return notYourRun();\n }\n // Not on to `threadId`: that names the run this turn is queued\n // behind, which is already stopping, and answering for it would\n // leave this one to start.\n pending.cancelled = true;\n return { stopped: true };\n }\n }\n }\n if (!runId && typeof body.threadId === \"string\") {\n runId = (await this.liveRuns.find({ threadId: body.threadId }))?.runId;\n }\n\n const run = runId ? this.liveRuns.get(runId) : null;\n if (!run) {\n // Already finished, already evicted, or never here. Not an error: the\n // caller wanted the run stopped and it is not running.\n return { stopped: false };\n }\n if (!this.liveRuns.mayAccess(run.runId, caller)) {\n // Someone else's run, by whichever handle (#442). See `runOwner`.\n return notYourRun();\n }\n\n run.stop({ reason: typeof body.reason === \"string\" ? body.reason : undefined });\n\n // Deliberately not awaiting `run.result()`. Unwinding means letting tools\n // in flight settle into `denied` results and finalizing the assistant\n // message, which can take as long as the slowest tool — and a stop button\n // that spins for twenty seconds is a stop button people press twice.\n return { stopped: true };\n }\n\n /**\n * WHO A SCOPE BELONGS TO, and the one question in this file whose wrong\n * answer is a data leak rather than a bug.\n *\n * An attachment id given to the model comes back *from* the model, and what\n * the model writes is a function of everything it read — the user's text, a\n * tool's output, a document someone uploaded. So the id is untrusted in\n * exactly the way a request body is, and the scope it resolves under must come\n * from the server's own knowledge of the request. Nothing that reaches this\n * method may be readable or writable by the model: `req` is the HTTP request,\n * and `threadId` is the client's handle, not the model's.\n *\n * THE DEFAULT IS THE AUTHENTICATED USER, falling back to the thread, falling\n * back to `null`.\n *\n * - `user:<id>` when the request is authenticated. `req.ctx().user` is what\n * `AuthenticationMiddleware` and the `Auth` facade put there, so an agent\n * route behind `middlewares = [\"auth\"]` — which `ApiRouter.agent()` makes\n * the default posture — has a subject without the app writing anything.\n * - `thread:<id>` for an unauthenticated chat that has a thread. A `threadId`\n * is minted by `createThread` as a uuid and is documented as a capability,\n * and `upload` only passes one here that `store.loadThread` finds;\n * an anonymous support widget has nothing better, and scoping to the\n * conversation is strictly narrower than scoping to nothing.\n * - `null` otherwise, which means no attachment id is minted at all. There is\n * no third fallback on purpose. `sessionId()` is the tempting one and it is\n * the wrong one: it is a cookie the visitor writes, documented as *not a\n * credential*, so scoping to it is scoping to a value the caller chooses —\n * which is not a scope, it is a lookup key with extra steps.\n *\n * WHAT THIS DEFAULT GETS WRONG, since it will get something wrong for someone:\n * it is per user, not per conversation, so a user's own upload from one thread\n * resolves in another thread of theirs. That is the loose direction, and it is\n * chosen because the tight one breaks the flow the framework actually ships —\n * `useChat.uploadFile` posts a file before any thread exists, so a per-thread\n * default would make the first upload of every conversation unresolvable. An\n * app that wants per-conversation isolation returns\n * `{ key: \\`user:${id}:thread:${threadId}\\` }` here and has it; an app with\n * tenants returns `{ key: \\`org:${orgId}\\` }` and has that. What the default\n * must never be is broader than a user, and it is not.\n *\n * WHATEVER THIS READS MUST BE PRESENT ON EVERY AGENT ROUTE, and the default\n * reads `req.ctx().user`, which is present only where authentication\n * middleware ran. `agent()` mounts four routes and `.middleware()` guards\n * them individually, so `middleware({ stream: \"auth\" })` — the example in\n * `ApiRouter.agent`'s own doc — leaves `POST /chat/files` unauthenticated.\n * The upload then files the record under `thread:<id>` (or nothing at all)\n * while the run that follows, on the guarded route, resolves under\n * `user:<id>`, and every id minted on upload is a miss for the rest of the\n * conversation. It fails as `AttachmentNotFoundError`, worded identically to\n * an id the model invented, which is the point of that error and is also why\n * this particular misconfiguration is invisible. Guard `upload` and `stream`\n * together, or derive the key from something both of them have.\n *\n * gemi does not detect the skew for you, and the reason is the module's whole\n * premise: noticing that an id exists under a *different* scope requires\n * looking it up without one, and an unscoped read is the thing that must not\n * exist here — not even behind a `console.warn`. So the answer is the\n * documentation you are reading and the identical error, not a probe.\n *\n * THE BODY, AND THE ONE RULE FOR READING IT (#603). The third argument is the\n * client's `body` option — what `instructions()` gets — on both routes that\n * resolve a scope: `stream`, and `upload`, where `useChat.uploadFile` sends\n * the same option beside the file. It exists for the chat that has neither a\n * user nor a thread, a stateless page builder say, whose subject is only in\n * the body:\n *\n * protected async attachmentScope(req, threadId, { body }) {\n * const scope = await super.attachmentScope(req, threadId);\n * if (scope) return scope;\n * if (typeof body.pageId !== \"string\") return null;\n * const page = await Page.findFirst({ where: { publicId: body.pageId } });\n * return page ? { key: `page:${page.publicId}` } : null;\n * }\n *\n * The `typeof` line is not tidiness. `Body` types the shape, not the contents,\n * and to an ORM `{ publicId: undefined }` is no filter at all: a request that\n * leaves `pageId` out would find the first page in the table and be filed\n * under it, along with every other request that leaves it out.\n *\n * A body field is a value the caller chose, which is exactly what the\n * `sessionId()` paragraph above refuses. What separates the keys this may be\n * built from is not whether the client sent them — `threadId` is sent by the\n * client too — but WHETHER THE VALUE IS AN UNGUESSABLE CAPABILITY WHOSE\n * EXISTENCE THE SERVER CHECKS. A page `publicId` that is looked up, as above,\n * is one, on the same footing as a `threadId` that `loadThread` finds: holding\n * it is what entitles the caller to the page, and an id nobody minted resolves\n * to nothing. `body.orgId` in an app with users is NOT one, and passing the\n * body is precisely what makes `` { key: `org:${body.orgId}` } `` spellable: an\n * org id is enumerable and the caller may not belong to that org, so that is\n * every tenant's files handed to whoever types another tenant's id. A tenant\n * comes from `req.ctx().user`, never from here. And a value interpolated\n * without being looked up is the `sessionId()` mistake again, however\n * unguessable it looks — an anonymous caller then mints a fresh scope per\n * request. Look it up, and key on what the lookup returned.\n *\n * The same skew rule as above applies to the body, and more quietly: the key\n * must come out the same on `upload` and on `stream`. `useChat` sends the one\n * `body` option to both, so a key derived from a field that stays put for the\n * whole conversation — the page, not the selected element — agrees by\n * construction. One derived from a field that changes between the upload and\n * the turn does not, and fails as that same `AttachmentNotFoundError`.\n *\n * The third argument is new, and the method keeps its first two, so an\n * override written as `attachmentScope(req, threadId)` works unchanged; one\n * that calls `super.attachmentScope(req, threadId)` may leave it off too.\n *\n * The key is opaque and compared with `===`. It is never sent to the client\n * and never shown to the model.\n */\n protected attachmentScope(\n req: HttpRequest<any, any>,\n threadId?: string,\n extra?: { body: Body },\n ): AttachmentScope | null | Promise<AttachmentScope | null> {\n void extra;\n const user = req.ctx()?.user;\n const userId = user?.id ?? user?.publicId;\n if (userId !== undefined && userId !== null && String(userId) !== \"\") {\n return { key: `user:${String(userId)}` };\n }\n if (threadId) {\n return { key: `thread:${threadId}` };\n }\n return null;\n }\n\n /**\n * WHAT THIS ROUTE ACCEPTS AT ALL: a size ceiling and a list of types (#683).\n * Checked once per upload, after `authorizeRequest` and before anything is\n * stored or sent to the provider, and a file outside them is answered **422**\n * with `{ error: { code, message } }` — `file_too_large` or\n * `unsupported_file_type` — which `useChat().attach()` rejects with as an\n * `AttachError`, so a composer can mark the one file.\n *\n * `accept` reads like an `<input accept>`: `\".pdf\"` matches the file name's\n * extension, `\"image/*\"` a type family, `\"text/csv\"` one type. A file\n * matching any entry is accepted. Left out (or `null` returned, the default)\n * means no limit of that kind, which is how the route behaved before.\n *\n * Here rather than in `attachmentDestination`, which an app could throw from\n * to the same end: a throw there is a 500 unless the app builds the response\n * itself, and the provider's own refusal only arrives after the bytes were\n * stored. A limit is a rule about the file, so it is answered before either.\n *\n * protected attachmentLimits() {\n * return { maxBytes: 10 * 1024 * 1024, accept: [\".pdf\", \"image/*\"] };\n * }\n */\n protected attachmentLimits(\n req: HttpRequest<any, any>,\n ): AttachmentLimits | null | Promise<AttachmentLimits | null> {\n void req;\n return null;\n }\n\n /**\n * WHERE ONE FILE'S BYTES SHOULD GO. Called once per upload, with the file in\n * hand.\n *\n * The model needs to perceive a file only for vision or document reading; a\n * tool needs the bytes only to forward them. Those are different needs and\n * they were being answered the same way, because `upload` sent everything to\n * the vendor unconditionally — which is a cost and a data-minimisation problem\n * as much as a capability one. A CSV that exists to be imported belongs in\n * storage and not at the provider; an image the model must look at and no tool\n * will forward is the reverse.\n *\n * THE DEFAULT IS `\"both\"`, AND THE JUSTIFICATION IS THE FAILURE MODE, not the\n * hit rate. A mimeType table was the obvious alternative — images and PDFs to\n * the provider, everything else to storage — and it is wrong in the quiet\n * direction. Getting `\"both\"` wrong sends a file to a vendor that did not need\n * it: it costs money, it is visible on an invoice and in the vendor's file\n * list, and it is corrected by overriding one method. Getting `\"storage\"`\n * wrong drops the file out of the model's view with no error anywhere; the\n * model answers as though the image were not there, which is indistinguishable\n * from a bad prompt, and the developer debugs their instructions for an\n * afternoon. Being wrong on the invoice beats being wrong in a way that\n * presents as \"the AI is stupid\".\n *\n * `\"both\"` is also what keeps this change additive: every upload that reached\n * the provider before still reaches it, and storage is added underneath. An\n * app that never asks for an attachment id sees no difference except a second\n * copy it owns.\n *\n * A client may ask, per file, for `\"storage\"` under a `\"both\"` policy — the\n * one direction that only ever removes the vendor. It may not ask for\n * anything else, including `\"provider\"`, which would let a form field decide\n * that the app does not keep its own copy. See `narrowDestination`.\n */\n protected attachmentDestination(\n file: File,\n req: HttpRequest<any, any>,\n ): AttachmentDestination | Promise<AttachmentDestination> {\n void file;\n void req;\n return \"both\";\n }\n\n /**\n * The attachment handle for this request — the object a tool is given.\n *\n * `null` when `attachmentScope` says the request has no subject, and a caller\n * that gets `null` must not fall back to anything: there is no unscoped handle\n * to fall back to, which is the point.\n *\n * Issue #490 hangs `ctx.attachments` off this.\n */\n protected async attachmentsFor(\n req: HttpRequest<any, any>,\n threadId?: string,\n extra: { body: Body } = { body: {} as Body },\n ): Promise<ScopedAttachments | null> {\n const scope = await this.attachmentScope(req, threadId, extra);\n if (!scope) {\n return null;\n }\n return new ScopedAttachments(this.attachments, this.attachmentStorage, scope);\n }\n\n /**\n * `POST /<path>/files` — takes an attachment and answers the handles for it.\n *\n * `fileId` IS STILL IN THE ANSWER AND STILL MEANS THE SAME THING: the\n * provider's id for the file, the thing a `FilePart` carries, unchanged. It\n * has to stay, because it is what makes vision work and what\n * `useChat.uploadFile` already reads; `attachmentId` is added beside it rather\n * than in place of it. The two are not interchangeable, and swapping them\n * would reach the vendor as a file id it has never issued — so\n * `toResponsesInput` rejects a `gemi_att_` prefix in `FilePart.fileId` with a\n * sentence saying so, rather than leaving it to whatever the vendor answers\n * (not measured).\n *\n * `fileId` is absent exactly when the file did not go to the provider, which\n * only happens when the app or the client asked for that. `attachmentId` is\n * absent when there was no scope to file the record under — see\n * `attachmentScope` — and the answer then carries `downgraded: \"no_scope\"`,\n * which is the only thing separating that case from a controller that chose\n * `\"provider\"` on purpose. Both answer `destination: \"provider\"`, because both\n * are true about where the bytes went.\n *\n * ORDER: storage first, then the provider. If the second one fails the request\n * fails either way, so the only question is where the orphan is left, and an\n * orphan in our own bucket is ours to sweep on a schedule we set, while an\n * orphan at the vendor sits under a retention policy that is not ours.\n */\n async upload(req: HttpRequest<any, any> = new HttpRequest()): Promise<UploadResult> {\n const form = await req.rawRequest.formData();\n const file = form.get(\"file\");\n if (!(file instanceof Blob)) {\n throw new Error(\"upload expects a multipart body with a `file` field.\");\n }\n const name = file instanceof File && file.name ? file.name : \"upload\";\n const mimeType = file.type || \"application/octet-stream\";\n\n // The client's `body` option, as one JSON part beside the file (#603), so\n // `authorizeRequest` and `attachmentScope` see here what they see on\n // `stream`. Read off the form already parsed: the request's body is\n // consumed, and an override cannot read it again. A malformed part is\n // refused before anything else runs, as a malformed turn is on `stream`.\n const extraBody = uploadAppBody<Body>(form.get(\"body\"));\n\n // The client's thread, read here only so an unauthenticated chat has\n // something to scope to. It is the client's own handle — `stream` already\n // takes it on trust for the whole conversation — and it is not the model's:\n // this is a form field on an HTTP request the user's browser made, not a\n // tool argument.\n //\n // It is only passed on if the store knows it. `stream` answers\n // `thread_not_found` for an id it has never seen, and this route must not\n // be looser: an invented id would otherwise be a scope, and an anonymous\n // caller could keep writing to storage by sending a fresh one each time.\n const threadField = form.get(\"threadId\");\n // The field as sent, before the store is asked about it, so a refused\n // caller does not learn whether the thread exists.\n await this.authorizeRequest(req, {\n route: \"upload\",\n threadId: typeof threadField === \"string\" && threadField.length > 0 ? threadField : undefined,\n body: extraBody,\n });\n // Before the thread is looked up, the policy is asked, or a byte is kept:\n // a file this route never takes costs nothing past this line.\n const refusal = limitRefusal(await this.attachmentLimits(req), file, name, mimeType);\n if (refusal) {\n throw new LimitedUploadError(refusal.code, refusal.message);\n }\n\n const threadId =\n typeof threadField === \"string\" &&\n threadField.length > 0 &&\n (await this.store.loadThread(threadField)) !== null\n ? threadField\n : undefined;\n\n // Who the provider's copy will belong to (#443): the same key that owns a\n // run this caller starts, so the turn that names the file finds it its own.\n const owner = await this.runOwner(req);\n const recordOwner = (fileId: string) =>\n this.fileOwners.record(fileId, {\n owner,\n name,\n mimeType,\n size: file.size,\n createdAt: new Date().toISOString(),\n });\n\n const policy = await this.attachmentDestination(file as File, req);\n const destination = narrowDestination(policy, form.get(\"destination\"));\n\n const scope = await this.attachmentScope(req, threadId, { body: extraBody });\n\n // The app's policy wanted a copy of these bytes and the request has no\n // subject to file them under. Recorded rather than merely warned about,\n // because the answer has to be able to tell the client that what it is\n // getting is not the policy — see `UploadResult.downgraded`.\n const downgraded = destination !== \"provider\" && !scope;\n if (downgraded) {\n if (destination === \"storage\") {\n // Bytes were asked to be kept and there is nobody to keep them for.\n // Storing them anyway files them under a scope every caller shares, and\n // answering nothing is an upload that silently did not happen. Neither\n // is an answer; this is.\n throw new Error(\n 'This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: \"auth\" })`), send a `threadId` with the upload, or override `attachmentScope()`.',\n );\n }\n // Policy said `both` and the request has no subject: fall through to the\n // provider alone, which is exactly what this route did before attachments\n // existed. Downgrading rather than throwing is what keeps an\n // unauthenticated chat working across the upgrade — but a downgrade nobody\n // is told about is the failure mode this file keeps arguing against, so it\n // is warned once per process on the server and marked `downgraded` in the\n // answer, so the client can tell this apart from a deliberate\n // provider-only policy.\n warnUnscopedUploadOnce();\n }\n\n if (destination === \"provider\" || !scope) {\n // Identical to the pre-attachment behaviour, down to the answer's\n // `fileId` — plus `downgraded` when this path was not the app's choice.\n const fileId = await providerUpload(this.agent.provider, file as File);\n await recordOwner(fileId);\n const answer: UploadResult = {\n fileId,\n name,\n mimeType,\n size: file.size,\n destination: \"provider\",\n };\n if (downgraded) {\n answer.downgraded = \"no_scope\";\n }\n return answer;\n }\n\n const attachmentId = newAttachmentId();\n const objectName = await this.attachmentStorage.put({\n name: attachmentObjectName(attachmentId, name),\n body: file,\n contentType: mimeType,\n });\n\n const fileId =\n destination === \"both\" ? await providerUpload(this.agent.provider, file as File) : undefined;\n if (fileId) {\n await recordOwner(fileId);\n }\n\n const record: Attachment = {\n id: attachmentId,\n scopeKey: scope.key,\n fileId,\n objectName,\n name,\n mimeType,\n size: file.size,\n createdAt: new Date().toISOString(),\n destination,\n };\n await this.attachments.put(scope, record);\n\n return { fileId, attachmentId, name, mimeType, size: file.size, destination };\n }\n\n /**\n * The 403 for a turn naming a provider file id that is not this caller's, or\n * `null` when every id may be used (#443). See `fileOwners`.\n *\n * Only `fileId` is checked: an `attachmentId` is resolved under the request's\n * own scope, so another user's is already a not-found (`ScopedAttachments`).\n * An entry carrying the caller's own `attachmentId` beside a foreign `fileId`\n * is refused all the same — the `fileId` is what reaches the provider.\n */\n private async foreignFile(\n files: { fileId?: string }[],\n caller: string | null,\n ): Promise<Response | null> {\n const ids = new Set(\n files.map((file) => file.fileId).filter((id): id is string => typeof id === \"string\"),\n );\n for (const fileId of ids) {\n const record = await this.fileOwners.get(fileId);\n if (record ? record.owner !== null && record.owner !== caller : this.requireKnownFiles) {\n // The same sentence for a file that is someone else's and, in strict\n // mode, one nobody recorded: which of the two it is would tell a caller\n // probing ids that the id exists.\n return notYourFile();\n }\n }\n return null;\n }\n\n /**\n * Protected, not private: these exist to be overridden. `onMessage` fires for\n * every completed message, user and assistant alike, and is the intended\n * persistence point for an app that is not using `store`.\n *\n * Every hook runs inside the request that started the run, which is held\n * open for them — after the run, and after a client that left — so\n * `ctx.req.ctx().user` is the user who sent the turn. See `hookHoldMs` for\n * how long a hook that does not finish keeps it.\n */\n protected onMessage(message: AgentMessage, ctx: AgentHookContext): void | Promise<void> {\n void message;\n void ctx;\n }\n\n protected onToolCall(\n call: { toolCallId: string; name: string; input: unknown },\n ctx: AgentHookContext,\n ): void | Promise<void> {\n void call;\n void ctx;\n }\n\n /** Fires before the stream ends `awaiting-input` — where to notify whoever\n * has to approve, if they are not the person watching the stream. */\n protected onAwaitingInput(\n pending: PendingToolCall[],\n ctx: AgentHookContext,\n ): void | Promise<void> {\n void pending;\n void ctx;\n }\n\n /**\n * What the client is told about a failure: the run's `error` frame, and the\n * result of a tool that threw, which the model reads too and the store\n * keeps. Return the error to send.\n *\n * The default (`redactError` from `gemi/ai`) keeps `code`, `retryable` and\n * `toolCallId` and replaces every message gemi did not write with a fixed\n * sentence for its code: a provider's error body names resources,\n * deployments and request ids, and an exception's text can be a connection\n * string. A tool that throws a `ToolError` keeps its message. The full\n * detail is in `info` (`info.failure` for the run, `info.cause` for a\n * tool), in the log, on `result().error`, and in `onError`, which is handed\n * the unredacted error.\n *\n * Override it to show more, for instance everything in development:\n *\n * protected redactError(error, info, ctx) {\n * if (process.env.NODE_ENV === \"development\") return error;\n * return super.redactError(error, info, ctx);\n * }\n *\n * Only the `AgentError` fields of what it returns are sent. One that throws\n * is reported and the default is used instead.\n */\n protected redactError(\n error: AgentError,\n info: ErrorRedactionInfo,\n ctx: AgentHookContext,\n ): AgentError {\n void ctx;\n return redactError(error, info);\n }\n\n /**\n * A failure on the run's stream, unredacted: the provider's own message,\n * and the HTTP `status` and `requestId` when there were any. The client was\n * sent `redactError`'s copy.\n */\n protected onError(error: AgentError, ctx: AgentHookContext): void | Promise<void> {\n void error;\n void ctx;\n }\n\n protected onStreamComplete(\n result: AgentRunResult<ToolShapesOf<A[\"tools\"]>, any>,\n ctx: AgentHookContext,\n ): void | Promise<void> {\n void result;\n void ctx;\n }\n\n /**\n * WHAT HAPPENS WHEN A HOOK THROWS: it is reported and the run carries on.\n *\n * The alternative is to fail the run, and that trade is not close. These\n * hooks are an app's persistence and notification points; the run is a model\n * call the user has already been charged for and whose tools may already have\n * charged a card. Letting a failed `INSERT` in `onMessage` abort a generation\n * mid-sentence loses the answer as well as the row, and the user cannot\n * retry into a better outcome. So the answer survives and the failure is\n * logged.\n *\n * It is logged rather than routed to `onError`: `onError` is itself a hook,\n * and a hook that throws inside the handler for hooks that throw is a loop.\n * Override this to send it somewhere with a pager attached.\n */\n protected reportHookFailure(error: unknown): void {\n console.error(\"[gemi/ai] agent controller hook failed\", error);\n }\n\n private async dispatchEvent(event: AgentStreamEvent, ctx: AgentHookContext): Promise<void> {\n switch (event.type) {\n case \"tool-call\":\n // Skipped while the arguments are still streaming: a hook that fires\n // per token would fire with a half-parsed input, which is worse than\n // firing late. And skipped for a re-sent frame, which carries a parked\n // sub-run's record on a call this hook has already seen — once per call\n // is the contract, and a run that re-parks would otherwise fire it for\n // a call some earlier run made.\n if (!event.part.partial && !event.resent) {\n await this.onToolCall(\n {\n toolCallId: event.part.toolCallId,\n name: String(event.part.name),\n input: event.part.input,\n },\n ctx,\n );\n }\n return;\n case \"awaiting-input\":\n await this.onAwaitingInput(event.pending as PendingToolCall[], ctx);\n return;\n case \"error\":\n // The frame carries the redacted copy; the hook is server-side and\n // gets what it was made from.\n await this.onError(unredactedError(event.error), ctx);\n return;\n default:\n return;\n }\n }\n\n /**\n * The thread as a client should see it: the store's history, with any\n * assistant message a dead run left unfinished marked `interrupted` (#617).\n *\n * For the app's own route that hands a thread to `useChat` (or a native\n * session) as its initial messages. A message whose run is still going here\n * is left as it is, still being written, so the client attaches to it. `null`\n * for a thread the store does not have, as `loadThread` answers.\n *\n * It does not write: the next turn on the thread settles the same messages\n * the same way and stores them then, under the thread's lock.\n */\n async readThread(threadId: string): Promise<AgentMessage[] | null> {\n const history = await this.store.loadThread(threadId);\n return history ? await this.settleThread(threadId, history, { write: false }) : null;\n }\n\n /**\n * Whether the run that was writing a message is still going, so the message\n * is in progress rather than interrupted.\n *\n * The default asks this process's `liveRuns`, which is the whole answer on a\n * single instance: a run lives in the process that started it, and a run\n * that is not there died with an earlier one. A finished run still within\n * `ttlMs` counts as live, since its final write may not have landed yet.\n *\n * Behind several instances it is not the whole answer. A run on another\n * instance is not in this map, so its message reads as interrupted here\n * until that run's own writes replace it. Knowing better needs a lasting\n * record of running runs (#459); override this to consult one.\n */\n protected isRunLive(runId: string, threadId: string): boolean | Promise<boolean> {\n void threadId;\n return this.liveRuns.get(runId) !== null;\n }\n\n private async settleThread(\n threadId: string,\n history: AgentMessage[],\n { write }: { write: boolean },\n ): Promise<AgentMessage[]> {\n const { messages, settled } = await settleInterrupted(history, (runId) =>\n this.isRunLive(runId, threadId),\n );\n if (write && settled.length > 0) {\n try {\n await this.store.appendMessages(threadId, settled);\n } catch (err) {\n // The run still gets the settled history. The store keeps the\n // unfinished copy, and the next turn settles it the same way again.\n this.reportHookFailure(err);\n }\n }\n return messages;\n }\n\n /**\n * Feeds the run's frames to its journal as they are emitted.\n *\n * A subscriber of its own on `run.frames()` rather than a ride on the\n * `onEvent` chain: that chain waits for the app's hooks, and a slow\n * `onToolCall` must not be what decides whether a tool call was stored\n * before the process died. `frames()` is a read of the run's own buffer, the\n * one `toResponse` already reads beside `liveRuns`, so a third reader costs a\n * cursor and nothing else.\n */\n private follow(run: AgentRun, journal: TurnJournal): void {\n void (async () => {\n try {\n for await (const frame of run.frames()) journal.frame(frame);\n } catch (err) {\n this.reportHookFailure(err);\n }\n })();\n }\n\n /**\n * Runs after the stream is over, whether or not anyone was still watching it.\n *\n * The messages come from `result()` rather than from the event stream because\n * assembling a message out of deltas is the agent's job and doing it twice is\n * how the two copies drift. It also means a stopped run persists the same way\n * a finished one does: `stop()` finalizes the transcript, so by the time this\n * resolves there is a valid history to store.\n *\n * `stored` settles when the transcript is in the store, not when the app is\n * done with it. The next turn on this thread waits on that (see\n * `withThread`), and the hooks are the app's: an `onMessage` that writes to\n * something slow would make every later turn wait for it, once per message\n * of the old run, and one that never settles — which `safely` cannot catch —\n * would hold the thread, and every turn queued on it, behind an open\n * connection each. So the hooks run on after it on their own, reported the\n * same way.\n *\n * `hooks` settles once they have too, and every event-stream hook the run\n * led to (`eventHooks`), or after `hookHoldMs` of them, and is what the\n * request that started the run is held open for. Separate from\n * `stored` for the reason above, and it has to exist from the start: by the\n * time the hooks are called the run has settled, and the request with it,\n * unless something was already holding it. Neither rejects.\n */\n private persistRun(\n run: AgentRun,\n ctx: AgentHookContext,\n eventHooks: Promise<void>,\n journal: TurnJournal | null = null,\n ): { stored: Promise<void>; hooks: Promise<void> } {\n // Assigned before `stored` settles, on every path, so `hooks` below reads\n // the chain this run actually started.\n let notified: Promise<void> = Promise.resolve();\n\n const stored = (async () => {\n let result: AgentRunResult<ToolShapes, unknown>;\n try {\n result = await run.result();\n } catch (err) {\n // What was written while it ran stays: it is the most the store can\n // know about a run that did not settle, and the next read marks it\n // interrupted once the run is gone.\n journal?.close();\n await journal?.settled();\n notified = this.safely(() =>\n this.onError(\n {\n code: \"unknown\",\n message: err instanceof Error ? err.message : String(err),\n retryable: false,\n },\n ctx,\n ),\n );\n return;\n }\n\n const messages = result.messages as AgentMessage[];\n\n // The writes made while it ran land first, then the transcript whole: the\n // same messages under the same ids, now final, so this replaces every\n // in-progress copy rather than adding to them.\n journal?.close(messages);\n await journal?.settled();\n\n if (ctx.threadId && messages.length > 0) {\n try {\n await this.store.appendMessages(ctx.threadId, messages);\n } catch (err) {\n this.reportHookFailure(err);\n }\n }\n\n notified = this.notifyRun(result, messages, ctx);\n })();\n\n // The bound starts once the run has settled, not with the run: a long run\n // is not a hung hook. `eventHooks` is in it because the event-stream hooks\n // are chained (see `MemoryLiveRuns.register`): an `onAwaitingInput` queued\n // behind a slow `onToolCall` is called after the run, and after every hook\n // above, and has nothing else to hold the request for it.\n const hooks = stored.then(() =>\n within(\n Promise.all([notified, eventHooks]).then(() => {}),\n this.hookHoldMs,\n ),\n );\n return { stored, hooks };\n }\n\n /** The hooks on a finished run, in order. Never rejects: see `safely`. */\n private async notifyRun(\n result: AgentRunResult<ToolShapes, unknown>,\n messages: AgentMessage[],\n ctx: AgentHookContext,\n ): Promise<void> {\n for (const message of messages) {\n await this.safely(() => this.onMessage(message, ctx));\n }\n\n await this.safely(() => this.onStreamComplete(result as any, ctx));\n }\n\n private async safely(fn: () => void | Promise<void>): Promise<void> {\n try {\n await fn();\n } catch (err) {\n this.reportHookFailure(err);\n }\n }\n}\n\n// --- request plumbing ----------------------------------------------------\n\n/**\n * The keys of the turn envelope itself, which `useChat` puts in the same JSON\n * object as an app's `body`.\n *\n * Listed so `appBody` can take them back out. Sharing one object was the right\n * wire choice — a nested `body` field would be a second envelope for every\n * client, including the Swift and Kotlin ones — but it does mean the app's\n * fields and the framework's are mixed together on arrival, and handing an app\n * `turn` and `messages` would invite reading them. They are this module's to\n * change; an app that depended on their shape would break on a release that\n * never mentioned them.\n */\nconst ENVELOPE_KEYS = [\"turn\", \"clientRunId\", \"threadId\", \"messages\", \"regenerate\"] as const;\n\n/**\n * The turn's own fields, which `toClientTurn` reads off the top level when the\n * body carries no `turn` object. Reserved in that form and only that form —\n * with an envelope present, a top-level `text` is the app's.\n */\nconst BARE_TURN_KEYS = [\"text\", \"files\", \"toolResults\"] as const;\n\n/**\n * An app's own fields, out of the parsed turn body.\n *\n * A fresh object rather than a `delete` on the parsed one. Nothing reads the\n * body after this today — `turn`, `threadId`, `clientRunId` and `messages` are\n * all pulled out above — so this is not load-bearing and no test pins it. It is\n * how a helper that takes a parsed body should behave regardless: the next\n * reader to move a line above this one should not have to know that the body\n * was quietly hollowed out.\n */\nfunction appBody<Body extends object>(\n body: Record<string, any>,\n reserved: readonly string[] = hasTurnEnvelope(body)\n ? ENVELOPE_KEYS\n : [...ENVELOPE_KEYS, ...BARE_TURN_KEYS],\n): Body {\n const extra: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(body)) {\n if (reserved.includes(key)) continue;\n // `JSON.parse` produces `__proto__` as an own property, and `Object.entries`\n // hands it over like any other. Assigning it with `[]` goes through\n // `Object.prototype`'s setter and changes the prototype of the object an app\n // is about to read — from a value the client chose. `defineProperty` writes\n // the key itself, which is what \"the fields the client sent\" means.\n Object.defineProperty(extra, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n return extra as Body;\n}\n\n/**\n * The app's fields from an upload's `body` form part — the JSON of\n * `useChat`'s `body` option — in the shape `stream` hands out.\n *\n * One JSON part rather than a form field per key: a form field is a string, so\n * `{ count: 3 }` would arrive as `\"3\"` and `Body` would lie on this route and\n * not the other. A missing part is `{}`, as a turn with no app fields is.\n *\n * Only the envelope's four names are taken back out, not the bare-turn ones:\n * `useChat` always sends a `turn` envelope, so on `stream` an app's `text` is\n * the app's, and it has to be here as well.\n *\n * Anything else — a file where the JSON should be, JSON that does not parse,\n * JSON that is not an object — is a 400, not `{}`. Read as empty, the scope\n * would quietly resolve to `null` and the upload downgrade, and the reason\n * would be a missing page rather than a broken client.\n */\nfunction uploadAppBody<Body extends object>(part: FormDataEntryValue | null): Body {\n if (part === null) {\n return {} as Body;\n }\n let parsed: unknown;\n if (typeof part === \"string\") {\n try {\n parsed = JSON.parse(part);\n } catch {\n throw new InvalidUploadError(\"The upload's `body` field is not valid JSON.\");\n }\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new InvalidUploadError(\"The upload's `body` field must be a JSON object.\");\n }\n return appBody<Body>(parsed as Record<string, any>, ENVELOPE_KEYS);\n}\n\n/**\n * A 400 from `upload`, which answers `UploadResult` and so rejects by throwing.\n * The payload is the shape `stream`'s own 400s have, so a client reads both the\n * same way.\n */\nclass InvalidUploadError extends RequestBreakerError {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidUploadError\";\n this.payload = {\n api: { status: 400, data: { error: { code: \"invalid_request\", message } } },\n view: {},\n };\n }\n}\n\n/**\n * The provider's upload, with a refusal of THE FILE answered as the client's\n * problem rather than the server's.\n *\n * A vendor that will not take a file answers 4xx, and before this that left\n * `upload` as an unhandled `ProviderHttpError`: a 500 that tells the person\n * attaching the file nothing about the file. MEASURED on Azure (#682,\n * 2026-10-01): with `purpose: \"user_data\"` a `.docx` was refused with `400\n * Unsupported extension: .docx. Supported extensions: .txt, .md, .pdf, …`; with\n * `assistants` the `.docx` is accepted (and read in a turn), and an `.exe` is\n * refused with `400 Invalid extension exe. Supported formats: \"c\", \"cpp\", …`.\n * Either sentence is exactly what the person needs to read, so it is passed\n * through as the message.\n *\n * Only the statuses that are about the request body: 400, 413, 415 and 422. A\n * 401/403 is our key, a 429/5xx is the vendor's day, and both stay server\n * errors — a person cannot fix either by picking another file.\n */\nasync function providerUpload(provider: { upload(file: File): Promise<string> }, file: File) {\n try {\n return await provider.upload(file);\n } catch (error) {\n if (error instanceof ProviderHttpError && REJECTED_FILE_STATUSES.has(error.status)) {\n throw new RejectedUploadError(normalizeProviderError(error).message);\n }\n throw error;\n }\n}\n\nconst REJECTED_FILE_STATUSES = new Set([400, 413, 415, 422]);\n\n/** A 422 from `upload` for a file outside `attachmentLimits`. */\nclass LimitedUploadError extends RequestBreakerError {\n constructor(code: \"file_too_large\" | \"unsupported_file_type\", message: string) {\n super(message);\n this.name = \"LimitedUploadError\";\n this.payload = {\n api: { status: 422, data: { error: { code, message } } },\n view: {},\n };\n }\n}\n\n/** Why `file` is outside `limits`, or `null` when it is not. Exported for the\n * tests; the route is the only caller. */\nexport function limitRefusal(\n limits: AttachmentLimits | null | undefined,\n file: Blob,\n name: string,\n mimeType: string,\n): { code: \"file_too_large\" | \"unsupported_file_type\"; message: string } | null {\n if (!limits) return null;\n const { maxBytes, accept } = limits;\n if (typeof maxBytes === \"number\" && file.size > maxBytes) {\n return {\n code: \"file_too_large\",\n message: `${JSON.stringify(name)} is ${formatBytes(file.size)}; the limit is ${formatBytes(maxBytes)}.`,\n };\n }\n if (\n accept &&\n accept.length > 0 &&\n !accept.some((entry) => acceptMatches(entry, name, mimeType))\n ) {\n return {\n code: \"unsupported_file_type\",\n message: `${JSON.stringify(name)} is not a type this chat accepts. Accepted: ${accept.join(\", \")}.`,\n };\n }\n return null;\n}\n\nfunction acceptMatches(entry: string, name: string, mimeType: string): boolean {\n const rule = entry.trim().toLowerCase();\n if (!rule) return false;\n if (rule.startsWith(\".\")) return name.toLowerCase().endsWith(rule);\n const type = mimeType.toLowerCase().split(\";\")[0]!.trim();\n if (rule.endsWith(\"/*\")) return type.startsWith(rule.slice(0, -1));\n return type === rule;\n}\n\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n const units = [\"KB\", \"MB\", \"GB\"];\n let value = bytes / 1024;\n let unit = 0;\n while (value >= 1024 && unit < units.length - 1) {\n value /= 1024;\n unit++;\n }\n return `${Math.round(value * 10) / 10} ${units[unit]}`;\n}\n\n/**\n * A 422 from `upload`: the provider would not take this file. `code` is\n * `unsupported_file_type` when the vendor said the type was the problem (an\n * extension or format allow-list) and `file_rejected` otherwise, so\n * a composer can mark the one chip without parsing English. Same payload shape\n * as `InvalidUploadError`.\n */\nclass RejectedUploadError extends RequestBreakerError {\n constructor(message: string) {\n super(message);\n this.name = \"RejectedUploadError\";\n const code =\n /(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(\n message,\n )\n ? \"unsupported_file_type\"\n : \"file_rejected\";\n this.payload = {\n api: { status: 422, data: { error: { code, message } } },\n view: {},\n };\n }\n}\n\n/**\n * A body, or the reason there is not one.\n *\n * Deliberately one shape with an optional `error` rather than a discriminated\n * union on `ok`: this package compiles with `strict: false`, and without\n * `strictNullChecks` TypeScript will not narrow a union by a boolean\n * discriminant — `if (!parsed.ok)` leaves `parsed.message` an error. A field\n * that is either set or not needs no narrowing to read.\n */\ntype ParsedBody = {\n body: Record<string, any>;\n error?: string;\n /** Which HTTP error the rejection is. A missing one is the 400. */\n status?: number;\n code?: string;\n};\n\n/**\n * The body, as JSON — or a reason it is not.\n *\n * Read off the raw request rather than through `req.input()`: that path also\n * accepts `+json` types and answers its failures as a thrown refusal, while\n * these routes are held to `application/json` alone (below) and answer with\n * a `{ code, message }` body of their own.\n *\n * Matching the type by prefix is not the same as ignoring it. A body that\n * arrives as anything other than `application/json` is a 415, and the reason\n * is not tidiness: a cross-site `<form enctype=\"text/plain\">` can be made to\n * concatenate its one field into valid JSON, and a JSON parser that reads\n * whatever it is handed turns that form into a turn on someone else's\n * conversation. Insisting on `application/json` is what makes these routes\n * non-simple requests — the browser will not send one cross-origin without a\n * preflight — and that holds whether or not the app's cookies are `SameSite`\n * and whether or not `CSRFMiddleware` is mounted. Only a request that carries a\n * body is held to this; a bodiless POST has no type to check and stays `{}`.\n *\n * The three cases are kept apart deliberately. NO body is a real request — a\n * reattach, or a turn that just lets the model continue — and reads as `{}`. A\n * body that will not parse, or that parses to something other than an object,\n * is a failed request and has to say so: folding it into `{}` made a truncated\n * proxy response or a mis-serialized client indistinguishable from an empty\n * turn, so `stream` billed a model call with no history and no turn and threw\n * the user's actual message away. That presents as the model hallucinating\n * rather than as an error, which is the expensive way to debug it. Pre-flight\n * failures stay ordinary HTTP errors and never reach the event stream.\n *\n * An array counts as malformed even though `typeof [] === \"object\"`: nothing\n * downstream reads a positional body, so `[1,2,3]` could only ever have run as\n * an empty turn.\n */\nasync function readJsonBody(req: HttpRequest<any, any>, maxBytes: number): Promise<ParsedBody> {\n const raw = req?.rawRequest;\n if (!raw || raw.method === \"GET\" || raw.method === \"HEAD\" || !raw.body) {\n return { body: {} };\n }\n\n if (!isJsonContentType(raw.headers.get(\"Content-Type\"))) {\n // Before the body is read: nothing in a body about to be refused is worth\n // the bytes, and the refusal must not depend on what they were.\n return {\n body: {},\n status: 415,\n code: \"unsupported_media_type\",\n error: \"The request body must be sent as application/json.\",\n };\n }\n\n // Before a byte is read when the client declared its length, and while\n // reading when it did not (#444).\n const declared = Number(raw.headers.get(\"Content-Length\"));\n if (Number.isFinite(declared) && declared > maxBytes) {\n return bodyTooLarge(maxBytes);\n }\n\n let text: string;\n try {\n const read = await readCapped(raw, maxBytes);\n if (read === null) {\n return bodyTooLarge(maxBytes);\n }\n text = read;\n } catch {\n // A body that stopped arriving mid-flight. Same class of failure as one\n // that arrived truncated, and the same answer.\n return { body: {}, error: \"The request body could not be read.\" };\n }\n\n if (!text.trim()) {\n return { body: {} };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { body: {}, error: \"The request body is not valid JSON.\" };\n }\n\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return { body: {}, error: \"The request body must be a JSON object.\" };\n }\n\n return { body: parsed as Record<string, any> };\n}\n\n/**\n * Media types compare case-insensitively and may carry parameters, so the\n * comparison is on the lowercased type with its parameters cut off, and\n * `Application/JSON; charset=utf-8` passes. It is an equality on that type\n * rather than a prefix, so `application/json-seq` and the other types that\n * merely begin with those bytes do not. None of the three types a browser will\n * send without a preflight — `text/plain`, `application/x-www-form-urlencoded`,\n * `multipart/form-data` — does either, and neither does no type at all, which\n * is what a hand-written `fetch` with a string body and no header ends up\n * sending as `text/plain`.\n */\nfunction isJsonContentType(value: string | null): boolean {\n return mediaType(value) === \"application/json\";\n}\n\n/**\n * The body as text, or `null` once more than `maxBytes` of it has arrived, at\n * which point the rest is not read. A limit that is not finite reads it all.\n */\nasync function readCapped(raw: Request, maxBytes: number): Promise<string | null> {\n if (!Number.isFinite(maxBytes) || !raw.body) {\n return await raw.text();\n }\n const reader = raw.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > maxBytes) {\n await reader.cancel().catch(noop);\n return null;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return new TextDecoder().decode(bytes);\n}\n\nfunction bodyTooLarge(maxBytes: number): ParsedBody {\n return {\n body: {},\n status: 413,\n code: \"body_too_large\",\n error: `The request body is larger than this agent accepts (${maxBytes} bytes).`,\n };\n}\n\n/**\n * A refusal for one of #444's limits: the `{ kind, message, status }` every\n * refusal has (#686), plus the `code` the agent routes' own errors carry, so a\n * client can tell the limits apart without reading the message.\n */\nfunction limitResponse(status: number, code: string, message: string): Response {\n return jsonResponse(status, {\n ...refusal(refusalKindForStatus(status), message, status),\n code,\n });\n}\n\nfunction invalidRequest(parsed: ParsedBody): Response {\n if (parsed.status === 413) {\n return limitResponse(413, parsed.code ?? \"body_too_large\", parsed.error ?? \"\");\n }\n return jsonResponse(parsed.status ?? 400, {\n code: parsed.code ?? \"invalid_request\",\n message: parsed.error,\n });\n}\n\n/**\n * Whether the turn arrived in a `turn` object of its own, rather than spread\n * across the top level of the body.\n *\n * Both forms are accepted, and which one it is decides what belongs to the app:\n * a top-level `text` is the user's message in the bare form and an app's own\n * field in the enveloped one. `toClientTurn` and `appBody` have to agree about\n * that, so they ask the same question here rather than each testing it.\n */\nfunction hasTurnEnvelope(body: Record<string, any>): boolean {\n return Boolean(body.turn) && typeof body.turn === \"object\";\n}\n\n/**\n * The client's turn, accepting both `{ turn: {...} }` and the flattened\n * `{ text, files, toolResults }` — the second is what a hand-written `fetch`\n * writes, and refusing it buys nothing.\n *\n * `turn` is `undefined` for an empty turn, which is a real request:\n * reattaching to a conversation and letting the model continue is a turn with\n * nothing in it. `error` is a turn that is refused with a 400 before anything\n * runs — see `toTurnFiles`.\n */\nfunction toClientTurn(body: Record<string, any>): { turn?: ClientTurn; error?: string } {\n const source = hasTurnEnvelope(body) ? body.turn : body;\n const turn: ClientTurn = {};\n if (typeof source.text === \"string\") {\n turn.text = source.text;\n }\n if (Array.isArray(source.files)) {\n const files = toTurnFiles(source.files);\n if (typeof files === \"string\") {\n return { error: files };\n }\n turn.files = files;\n }\n if (Array.isArray(source.toolResults)) {\n turn.toolResults = source.toolResults;\n }\n if (Object.keys(turn).length === 0) return {};\n // Envelope only: in the bare form the top level is shared with the app's own\n // fields, and an app that already sends a `localId` of its own would lose it\n // to the turn. `null` and `\"\"` read as absent, as they do for `files`.\n if (\n source === body.turn &&\n source.localId !== undefined &&\n source.localId !== null &&\n source.localId !== \"\"\n ) {\n const { localId } = source;\n if (typeof localId !== \"string\") return { error: \"turn.localId must be a string.\" };\n // Echoed back on the stream and nothing else, so the only thing to bound\n // is what one frame carries.\n if (localId.length > MAX_LOCAL_ID_LENGTH) {\n return { error: `turn.localId is longer than ${MAX_LOCAL_ID_LENGTH} characters.` };\n }\n turn.localId = localId;\n }\n return { turn };\n}\n\n/** How long `turn.localId` may be. Comfortably above `local_<uuid>`. */\nconst MAX_LOCAL_ID_LENGTH = 200;\n\n/**\n * `turn.files`, checked field by field, or the sentence refusing it.\n *\n * REFUSED, NOT FILTERED. Every entry becomes a `FilePart` in a user message,\n * and on a thread that message is stored before the provider sees it. An entry\n * the request builder cannot send — no id at all, or a gemi id in `fileId` —\n * then throws from `toResponsesInput` on this turn and on every turn after it,\n * because every later turn re-sends the history: one bad upload bricks the\n * thread. Dropping the entry instead is quieter and worse — the model answers\n * about a file it was never given, with nothing saying so. A 400 here is the\n * one place the client can still do something about it.\n *\n * Scoping is what makes a foreign `attachmentId` harmless (`ScopedAttachments`\n * answers the same not-found for another tenant's id as for an invented one),\n * so the id is not signed or looked up here. What this checks is the shape a\n * crash would come from: strings where strings go, the prefix on\n * `attachmentId`, at least one id. Unknown fields are dropped rather than\n * refused, since `attach()` answers more than a `FilePart` holds (`downgraded`)\n * and passing its answer on whole is the documented use. `null` and `\"\"` read\n * as absent, for every field: `null` is what a serializer that writes\n * `undefined` as `null` means, and `\"\"` is what a form field left blank sends.\n * Neither can be an id, so refusing `attachmentId: \"\"` for its prefix would\n * turn a blank into an error the entry's `fileId` does not deserve.\n */\nfunction toTurnFiles(raw: unknown[]): NonNullable<ClientTurn[\"files\"]> | string {\n const files: NonNullable<ClientTurn[\"files\"]> = [];\n for (const [index, entry] of raw.entries()) {\n const where = `turn.files[${index}]`;\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n return `${where} must be an object.`;\n }\n const fields: Record<string, string> = {};\n for (const key of [\"fileId\", \"attachmentId\", \"name\", \"mimeType\"] as const) {\n const value = (entry as Record<string, unknown>)[key];\n if (value === undefined || value === null || value === \"\") continue;\n if (typeof value !== \"string\") {\n return `${where}.${key} must be a string.`;\n }\n fields[key] = value;\n }\n const { fileId, attachmentId, name, mimeType } = fields;\n if (fileId?.startsWith(ATTACHMENT_ID_PREFIX)) {\n return `${where}.fileId holds a gemi attachment id (${fileId}). \\`fileId\\` is the provider's id from the upload response; put this one in \\`attachmentId\\`.`;\n }\n if (attachmentId !== undefined && !attachmentId.startsWith(ATTACHMENT_ID_PREFIX)) {\n return `${where}.attachmentId is not a gemi attachment id: it must start with \"${ATTACHMENT_ID_PREFIX}\".`;\n }\n if (!fileId && !attachmentId) {\n return `${where} has neither a \\`fileId\\` nor an \\`attachmentId\\`. Send the ids the upload response answered.`;\n }\n files.push({\n ...(fileId ? { fileId } : {}),\n ...(attachmentId ? { attachmentId } : {}),\n ...(name !== undefined ? { name } : {}),\n ...(mimeType !== undefined ? { mimeType } : {}),\n });\n }\n return files;\n}\n\n/**\n * Where to resume from, or `undefined` for \"wherever you still can\".\n *\n * An explicit `from` wins, because a client that tracked its own position knows\n * something the transport does not. Otherwise `Last-Event-ID` — the browser\n * sends it on its own when an `EventSource` reconnects, and the frames put\n * `seq` in `id:` precisely so that header is already the right question. It\n * names the last event *received*, so the resume point is one past it.\n *\n * With neither, the answer is `undefined` and NOT 0. A client reattaching on\n * mount is a fresh POST from a page that has just loaded: no `Last-Event-ID`,\n * and no cursor of its own, because the only handle it was given is the\n * `threadId`. Reading that as \"resume from frame 0\" asked `replay` for a frame\n * every run longer than `maxFrames` has already evicted, so the mount-time\n * reattach — the one case `/attach` exists for — 410'd on exactly the long runs\n * it was meant to rescue, and the documented remedy of reloading the thread\n * does not help because the store is only written at run end. `undefined` means\n * the tail, which is all such a client can use anyway.\n */\nfunction resolveCursor(req: HttpRequest<any, any>, body: Record<string, any>): number | undefined {\n if (typeof body.from === \"number\" && Number.isFinite(body.from)) {\n return Math.max(0, Math.floor(body.from));\n }\n // `cursor` is what `useChat` actually sends, and it counts the other way:\n // `from` is the frame to resume AT, `cursor` the last frame the client\n // APPLIED — the same convention as `Last-Event-ID`, and the same `+ 1`. A\n // client that has applied nothing sends -1, which is not a position but the\n // absence of one, so it falls through to the tail rather than asking for\n // frame 0 and 410ing on precisely the long runs `/attach` exists to rescue.\n if (typeof body.cursor === \"number\" && Number.isFinite(body.cursor)) {\n const applied = Math.floor(body.cursor);\n if (applied >= 0) {\n return applied + 1;\n }\n return undefined;\n }\n const header = req?.rawRequest?.headers?.get(\"Last-Event-ID\");\n if (header) {\n const seq = Number.parseInt(header, 10);\n if (Number.isFinite(seq)) {\n return Math.max(0, seq + 1);\n }\n }\n return undefined;\n}\n\nfunction searchParam(req: HttpRequest<any, any>, key: string): string | undefined {\n const value = req?.search?.get(key);\n return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Where a threaded regenerate cuts the history: at the last message the user\n * wrote, with the turn that wrote it. A file a tool showed is a user-role\n * message too, but it is part of the answer being replaced, so it is stepped\n * over (`injectedMessageIds`, the test `historyForProvider` uses).\n */\nfunction regenerationCut(\n messages: AgentMessage[],\n): { index: number; turn: ClientTurn } | null {\n const injected = injectedMessageIds(messages);\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index]!;\n if (message.role !== \"user\" || injected.has(message.id)) continue;\n let text = \"\";\n const files: NonNullable<ClientTurn[\"files\"]> = [];\n for (const part of message.content) {\n if (part.type === \"text\") text += part.text;\n if (part.type === \"file\") {\n files.push({\n ...(part.fileId ? { fileId: part.fileId } : {}),\n ...(part.attachmentId ? { attachmentId: part.attachmentId } : {}),\n ...(part.name ? { name: part.name } : {}),\n ...(part.mimeType ? { mimeType: part.mimeType } : {}),\n });\n }\n }\n if (!text && files.length === 0) continue;\n return {\n index,\n turn: { ...(text ? { text } : {}), ...(files.length > 0 ? { files } : {}) },\n };\n }\n return null;\n}\n\n/** A turn `/stop` ended while it waited, before anything ran or was charged. */\nfunction stoppedBeforeStart(): Response {\n return jsonResponse(409, {\n code: \"stopped\",\n message: \"The turn was stopped before it started.\",\n });\n}\n\n/**\n * The refusal for a run that belongs to another caller (#442), in the shape\n * every other refusal has (`{ kind, message, status }`, #686), so `useChat` and\n * the client guards classify it as `permission` without matching on text.\n */\nfunction notYourRun(): Response {\n return jsonResponse(\n 403,\n refusal(\"permission\", \"This run belongs to someone else.\", 403) as Record<string, unknown>,\n );\n}\n\n/** The refusal for a turn naming another owner's provider file (#443). Same\n * shape as `notYourRun`. */\nfunction notYourFile(): Response {\n return jsonResponse(\n 403,\n refusal(\n \"permission\",\n \"A file in this turn was uploaded by someone else.\",\n 403,\n ) as Record<string, unknown>,\n );\n}\n\n/**\n * The file parts of a stateless chat's history, which the client carries and\n * may have written anything into. Read defensively: the history is not\n * validated anywhere else before the run, and a malformed one is the run's\n * problem, not this check's.\n */\nfunction clientHistoryFiles(messages: unknown): { fileId?: string }[] {\n if (!Array.isArray(messages)) return [];\n const files: { fileId?: string }[] = [];\n for (const message of messages) {\n const content = (message as { content?: unknown } | null)?.content;\n if (!Array.isArray(content)) continue;\n for (const part of content) {\n if (part && typeof part === \"object\" && typeof part.fileId === \"string\") {\n files.push({ fileId: part.fileId });\n }\n }\n }\n return files;\n}\n\nfunction jsonResponse(status: number, error: Record<string, unknown>): Response {\n return new Response(JSON.stringify({ error }), {\n status,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\n// --- attachments ---------------------------------------------------------\n\n/**\n * Reads the client's `destination` field and applies it to the app's policy.\n *\n * THE ONLY THING A CLIENT MAY ASK FOR IS \"DO NOT SEND THIS TO THE VENDOR\", and\n * that is the entire permitted vocabulary: a `storage` hint under a `both`\n * policy, or a hint that agrees with the policy and changes nothing. Everything\n * else throws.\n *\n * The rule here used to be \"a hint may narrow, never widen\", counting\n * destinations, and counting is what made it wrong in one direction.\n * `both → provider` is fewer destinations and reads as narrowing, but what it\n * removes is *gemi's own copy*, while the third party still gets the file. That\n * is not a client declining exposure, it is a client overriding the app's\n * retention decision from a field in a multipart body: an app that keeps every\n * upload because a tool has to forward it — or because an auditor asked — loses\n * the copy, mints no `attachmentId`, records nothing, and gets no warning\n * either, since the bytes did reach the provider exactly as policy said. The\n * two directions are not alike, because only one of them reduces who ends up\n * holding the file.\n *\n * What is left is defensible on its own terms: `storage` keeps bytes off a\n * vendor the app was willing to send them to, which is a thing the client is\n * entitled to ask for and which cannot hurt anyone if the client is lying. A UI\n * that knows this CSV exists to be imported and will never be read by the model\n * is the case that makes a hint worth having at all. The policy hook is the\n * ceiling; the hint may only take the vendor out from under it.\n *\n * A hint the policy does not permit throws rather than being ignored. Ignoring\n * it is the shape of this bug that never gets found: the client believes it kept\n * a file off the vendor, the file went anyway, and nothing anywhere says so.\n */\nfunction narrowDestination(\n policy: AttachmentDestination,\n hint: FormDataEntryValue | null,\n): AttachmentDestination {\n if (typeof hint !== \"string\" || hint.length === 0) {\n return policy;\n }\n if (hint !== \"both\" && hint !== \"provider\" && hint !== \"storage\") {\n throw new Error(\n `Unknown attachment destination \"${hint}\". Expected \"both\", \"provider\" or \"storage\".`,\n );\n }\n if (hint === policy || (policy === \"both\" && hint === \"storage\")) {\n return hint;\n }\n if (policy === \"both\" && hint === \"provider\") {\n throw new Error(\n 'This upload asked for the \"provider\" destination under a \"both\" policy. A client may ask for \"storage\", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file — that is the app\\'s retention decision. Change `attachmentDestination()` if this file should not be kept.',\n );\n }\n throw new Error(\n `This upload asked for the \"${hint}\" destination, but the server's policy for it is \"${policy}\", and a client hint may only ask for \"storage\" under a \"both\" policy. Change \\`attachmentDestination()\\` if the file really should go there.`,\n );\n}\n\n/**\n * Said once per process, not once per upload.\n *\n * The condition is a property of how the app is wired — an agent route with no\n * authentication and no `threadId` on its uploads — so it is either true for\n * every request or false for every request. Logging it per request would put a\n * line in the log for every file anyone ever uploads, which is how a warning\n * stops being read.\n */\nlet warnedAboutUnscopedUpload = false;\nfunction warnUnscopedUploadOnce(): void {\n if (warnedAboutUnscopedUpload) return;\n warnedAboutUnscopedUpload = true;\n console.warn(\n \"[gemi/ai] An upload had no attachment scope, so its bytes were sent to the model provider only and no attachment id was minted — a tool cannot forward this file. Guard the route with auth, send a `threadId` with the upload, or override `attachmentScope()`.\",\n );\n}\n\n// --- routing -------------------------------------------------------------\n//\n// `agent()` itself belongs on ApiRouter next to `resource()`, which is the\n// method it works like: one call, several routes, all of them the controller's.\n// The types are declared here because they are the ai module's contract, not\n// the router's.\n//\n// class Api extends ApiRouter {\n// routes = {\n// \"/chat\": this.agent(ChatAgentController),\n// };\n// }\n//\n// POST /chat → stream every client turn\n// POST /chat/attach → attach reattach to a run in progress\n// POST /chat/stop → stop explicit cancel\n// POST /chat/files → upload attachments\n//\n// Mounting under a single path is what gives the client one key to name. The\n// agent's tool types ride along on `AgentRoute`, so `useChat(\"/chat\")` gets them\n// out of the existing `RPC` interface — no second augmentation to generate, and\n// renaming the route moves the client key with it.\n\nexport type AgentRouteMethod = \"stream\" | \"attach\" | \"stop\" | \"upload\";\n\nexport type AgentMiddlewareConfig = Partial<Record<AgentRouteMethod, MiddlewareInput>>;\n\nexport type AgentRoute<T extends new () => AgentController<any, any>> = {\n __internal_brand: \"AgentRoute\";\n controller: T;\n middleware(config: AgentMiddlewareConfig): AgentRoute<T>;\n};\n\n/** What `CreateRPC` should produce for an agent route: enough for the client to\n * type its messages, and nothing that drags server code into the bundle. */\nexport type AgentRouteRPC<T extends new () => AgentController<any, any>> = {\n __agent: true;\n tools: InstanceType<T>[\"agent\"] extends AnyAgent\n ? ToolShapesOf<InstanceType<T>[\"agent\"][\"tools\"]>\n : ToolShapes;\n output: unknown;\n /**\n * The controller's `Body`, so `useChat` can check what it sends against what\n * the controller declared.\n *\n * Read off the phantom key rather than by matching the class, which is what\n * made this fail: `Body` used to reach the instance type only through\n * `instructions`'s second parameter, and a controller overriding\n * `instructions(req)` — the pre-existing signature, so every existing\n * override — gave inference nothing to work with and got the open record.\n */\n body: InstanceType<T> extends { [BODY]?: infer B } ? B : Record<string, unknown>;\n};\n\n/** The longest delay `setTimeout` keeps; past it the runtime fires in ~1ms. */\nconst MAX_TIMEOUT_MS = 2 ** 31 - 1;\n\n/**\n * Settles when `work` does or after `ms`, whichever is first, and never\n * rejects. For how long the request waits on the app's code, not for the code\n * itself, which runs on either way.\n *\n * An `ms` a timer cannot hold — `Infinity` is what \"no bound\" reads as — is\n * no bound. Handed to `setTimeout` it would fire at once, and the request\n * would end before the hooks it was raised for.\n */\nfunction within(work: Promise<void>, ms: number): Promise<void> {\n const settled = work.then(\n () => {},\n () => {},\n );\n if (!(ms <= MAX_TIMEOUT_MS)) {\n return settled;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, ms);\n });\n return Promise.race([settled, timeout]).finally(() => clearTimeout(timer));\n}\n\nlet warnedInMemoryNonces = false;\n\n/**\n * Once per process, in production: a stateless chat whose answers are spent\n * only in this process's memory. Correct for a single instance, which is why\n * it is a warning; with several, a rewound history replays an approval once\n * per instance (#445).\n */\nfunction warnInMemoryNonces(nonces: NonceStore): void {\n if (warnedInMemoryNonces || process.env.NODE_ENV !== \"production\") return;\n if (!(nonces instanceof MemoryNonceStore)) return;\n warnedInMemoryNonces = true;\n console.warn(\n \"[gemi/ai] A stateless agent chat is spending approval nonces in process memory. \" +\n \"With more than one instance a replayed approval is accepted once per instance. \" +\n \"Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.\",\n );\n}\n"
33
34
  ],
34
- "mappings": ";2cAWO,CAAM,KAA0B,AAAM,JAClC,EACA,AACA,KAET,WAAW,CAAC,EAAgB,EAAe,EAAoB,CAC7D,MAAM,uCAAuC,MAAW,GAAa,CAAI,GAAG,EAC5E,KAAK,KAAO,oBACZ,KAAK,OAAS,EACd,KAAK,KAAO,EACZ,KAAK,UAAY,EAErB,CAOO,MAAM,WAA6B,KAAM,CACrC,UAET,WAAW,CAAC,EAAmB,CAC7B,MAAM,oCAAoC,KAAa,EACvD,KAAK,KAAO,uBACZ,KAAK,UAAY,EAErB,CAEA,SAAS,EAAY,CAAC,EAAuB,CAC3C,IAAM,EAAS,GAAU,CAAI,EAC7B,GAAI,GAAQ,QAAS,OAAO,EAAO,QACnC,GAAI,OAAO,IAAS,SAAU,OAAO,EAAK,MAAM,EAAG,GAAG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