gemi 0.235.0 → 0.236.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.
- package/dist/ai/client/conformance.d.ts +4 -2
- package/dist/ai/client/conformance.d.ts.map +1 -1
- package/dist/ai/client/index.js +72 -6
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/client/reducer.d.ts.map +1 -1
- package/dist/ai/index.js +3 -3
- package/dist/ai/index.js.map +3 -3
- package/dist/ai/providers/call.d.ts +1 -1
- package/dist/ai/types.d.ts +5 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/useChat.d.ts +35 -0
- package/dist/ai/useChat.d.ts.map +1 -1
- package/dist/{chunk-2hw8sr4d.js → chunk-3nhgh3qx.js} +1 -1
- package/dist/{chunk-2hw8sr4d.js.map → chunk-3nhgh3qx.js.map} +1 -1
- package/dist/chunk-4800w7qx.js.map +2 -2
- package/dist/{chunk-1yws1nvb.js → chunk-7rxj3x6v.js} +2 -2
- package/dist/{chunk-1yws1nvb.js.map → chunk-7rxj3x6v.js.map} +1 -1
- package/dist/{chunk-t5gbp0yr.js → chunk-dav7mv8t.js} +2 -2
- package/dist/{chunk-t5gbp0yr.js.map → chunk-dav7mv8t.js.map} +3 -3
- package/dist/{chunk-9359fg6r.js → chunk-eca9n9cz.js} +1 -1
- package/dist/{chunk-9359fg6r.js.map → chunk-eca9n9cz.js.map} +1 -1
- package/dist/{chunk-adfkz2kf.js → chunk-vbdtbcrn.js} +1 -1
- package/dist/chunks/{RealtimeClient-C5Zh3fD6.js → RealtimeClient-DRVodyn1.js} +2 -2
- package/dist/chunks/{RealtimeClient-C5Zh3fD6.js.map → RealtimeClient-DRVodyn1.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-bbbE-N3t.js → ThemeProvider-1WtAS7dH.js} +4 -4
- package/dist/chunks/{ThemeProvider-bbbE-N3t.js.map → ThemeProvider-1WtAS7dH.js.map} +1 -1
- package/dist/chunks/{fetchFileRequest-JXhnEi-R.js → fetchFileRequest-CVCelZqS.js} +2 -2
- package/dist/chunks/{fetchFileRequest-JXhnEi-R.js.map → fetchFileRequest-CVCelZqS.js.map} +1 -1
- package/dist/chunks/{live-CApTRvmK.js → live-twEh9Qwt.js} +3 -3
- package/dist/chunks/{live-CApTRvmK.js.map → live-twEh9Qwt.js.map} +1 -1
- package/dist/chunks/{mutationExtras-C2qSSZ2Q.js → mutationExtras-CM77Ur-9.js} +2 -2
- package/dist/chunks/{mutationExtras-C2qSSZ2Q.js.map → mutationExtras-CM77Ur-9.js.map} +1 -1
- package/dist/chunks/{subscriptionStream-DQLW7dTW.js → subscriptionStream-DQp1Krwi.js} +2 -2
- package/dist/chunks/{subscriptionStream-DQLW7dTW.js.map → subscriptionStream-DQp1Krwi.js.map} +1 -1
- package/dist/client/chunkLoadRecovery.d.ts +1 -1
- package/dist/client/index.js +4 -4
- package/dist/client/index.js.map +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/mcp/http/callers.d.ts +1 -1
- package/dist/testing/index.js +2 -2
- package/package.json +1 -1
- /package/dist/{chunk-adfkz2kf.js.map → chunk-vbdtbcrn.js.map} +0 -0
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
"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\nexport function 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",
|
|
10
10
|
"import { ProviderHttpError } from \"./errors\";\nimport { errorDetail } from \"./fileRejection\";\nimport type { ResponsesRequest } from \"./request\";\n\n/**\n * A replayed reasoning item the API no longer has, and the one retry it gets.\n *\n * Reasoning goes back to the Responses API by id (`request.ts`,\n * `reasoningItem`), and the API looks the id up in what it stored. When the\n * lookup fails the whole request is refused, `400 Item with id 'rs_…' not\n * found.`, and because the id lives in the thread, so is every later turn.\n * `toResponsesInput` already leaves out the reasoning of a message whose\n * response never completed, which is the case seen in practice; this is the\n * net under everything that rule does not know about (an item the vendor\n * expired, a thread moved to another resource or deployment).\n *\n * The request is sent again once, with every reasoning item taken out rather\n * than only the one named: Azure names a single id per refusal, and a thread\n * with two stale items would otherwise spend its retry on the first and fail\n * on the second. Reasoning is continuity and a cache hit, never content the\n * answer depends on, and `request.ts` already sends a history without it\n * whenever a part has no id, so the retried request is one the API accepts.\n *\n * Only for a refusal that names a reasoning item this request actually sent:\n * any other 400 fails the call as before.\n */\nexport function withoutStaleReasoning(body: unknown, error: unknown): ResponsesRequest | null {\n if (!(error instanceof ProviderHttpError)) return null;\n if (error.status !== 400 && error.status !== 404) return null;\n const input = (body as Partial<ResponsesRequest> | null)?.input;\n if (!Array.isArray(input)) return null;\n const message = errorDetail(error.body)?.message ?? \"\";\n const named = /Item with id '([^']+)' not found/i.exec(message)?.[1];\n if (!named) return null;\n const isReasoning = (item: Record<string, unknown>) => item?.type === \"reasoning\";\n if (!input.some((item) => isReasoning(item) && item.id === named)) return null;\n return {\n ...(body as ResponsesRequest),\n input: input.filter((item) => !isReasoning(item)),\n };\n}\n",
|
|
11
11
|
"import type { ProviderEvent } from \"../AgentProvider\";\nimport type { FinishReason, Usage } from \"../types\";\nimport { streamErrorDetail } from \"./errors\";\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 /** See the Messages parser's. Never called here: a Responses stream reports\n * its usage only on its terminal frame. */\n onUsage?: (usage: Usage) => void;\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 // The query of the last `tool_search_call`, held for the output that follows\n // it: the live API links the two by nothing but order (see below), and the\n // event is reported off the output, which does not carry the query.\n let searchArguments: unknown;\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 if (item.type === \"tool_search_call\" && item.arguments !== undefined) {\n searchArguments = item.arguments;\n }\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 // The query rides along so the search can be replayed (#776). Taken\n // and cleared, so a second search in the same response does not\n // report the first one's query.\n const query = searchArguments;\n searchArguments = undefined;\n yield {\n type: \"tool-search\",\n ...found,\n ...(query !== undefined && query !== null ? { arguments: query } : {}),\n };\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), ...streamErrorDetail(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",
|
|
12
|
-
"import { Log } from \"../../facades/Log\";\nimport type { ProviderEvent } from \"../AgentProvider\";\nimport type { ProviderTarget } from \"./endpoints\";\nimport {\n httpErrorDetail,\n ProviderHttpError,\n normalizeProviderError,\n ProviderStreamDurationError,\n ProviderStreamIdleError,\n ProviderTimeoutError,\n ProviderToolArgumentsRunawayError,\n ProviderToolArgumentsTooLongError,\n} from \"./errors\";\nimport {\n MAX_FILE_REJECTION_RETRIES,\n rejectedFileIds,\n withoutFiles,\n type SentFile,\n} from \"./fileRejection\";\nimport { addUsage, isContentEvent } from \"../runtime\";\nimport type { AgentError, ProviderErrorDetail, ToolArgumentsTooLong, Usage } from \"../types\";\nimport {\n backoffDelayMs,\n boundedBody,\n requestWithRetry,\n waitUnlessAborted,\n type FetchLike,\n type RequestOptions,\n patienceApplies,\n patientDelayMs,\n type ProviderRetryPolicy,\n} from \"./http\";\nimport type { ResponsesRequest } from \"./request\";\nimport { withoutStaleReasoning } from \"./staleReasoning\";\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 /** See `ProviderConfig.streamIdleTimeoutMs`. Absent or `0` is off. */\n streamIdleTimeoutMs?: number;\n /** See `ProviderConfig.streamMaxDurationMs`. Absent or `0` is off. */\n streamMaxDurationMs?: number;\n /** See `ProviderConfig.maxToolArgumentChars`. Absent or `0` is off. */\n maxToolArgumentChars?: number;\n /** See `ProviderConfig.maxToolArgumentWhitespace`. Absent or `0` is off. */\n maxToolArgumentWhitespace?: number;\n maxRetries: number;\n /** See `ProviderConfig.retry`. */\n retry?: ProviderRetryPolicy;\n fetchImpl?: FetchLike;\n /** Injected by the tests, with `random`, so a backoff can be asserted on\n * without waiting for it. See `RequestOptions`. */\n sleep?: RequestOptions[\"sleep\"];\n random?: () => number;\n now?: () => number;\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 streamIdleTimeoutMs: target.streamIdleTimeoutMs,\n streamMaxDurationMs: target.streamMaxDurationMs,\n maxToolArgumentChars: target.maxToolArgumentChars,\n maxToolArgumentWhitespace: target.maxToolArgumentWhitespace,\n maxRetries: target.maxRetries,\n ...(target.retry ? { retry: target.retry } : {}),\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 *\n * A STREAM THAT DIES BEFORE ITS FIRST CONTENT EVENT IS ASKED AGAIN (#946).\n * `requestWithRetry` covers a request that fails before a response arrives;\n * this covers the one whose response started and then broke while its body was\n * being read: the socket closed, the stream ended with no terminal frame, or\n * the provider sent a `response.failed` / `error` frame that reads as\n * retryable. Measured in fager: one such drop on the first step lost a whole\n * build, and the same request a second later worked.\n *\n * Nothing the user could have seen is repeated. Until the first content event\n * (`isContentEvent`) the only things a Responses stream yields are an error and\n * a finish, and those are held back; from the first content event on, the call\n * is committed and a later failure ends it as before. The retries use the\n * endpoint's `maxRetries` and the same backoff as the request retry, and an\n * abort during the wait ends the call at once. The usage a dropped attempt\n * reported is added to the call's closing `finish`, because it was billed.\n *\n * A STREAM THAT GOES SILENT IS CUT (#1167). With `streamIdleTimeoutMs` set, a\n * body that sends nothing for that long errors with a `ProviderStreamIdleError`\n * and the attempt's request is aborted, which releases the socket. From there it\n * is a broken stream like any other: retryable, so asked again before the first\n * content event, and the call's error after it (nothing is repeated). The\n * caller's signal still wins: an abort while waiting ends the call as aborted.\n *\n * A STREAM THAT KEEPS TRICKLING IS CUT TOO (#1169). `streamMaxDurationMs`\n * bounds an attempt's stream by the wall clock, which no chunk resets, and\n * `maxToolArgumentChars` bounds the argument text of one unfinished tool call.\n * Both abort the attempt with a retryable error, like the idle limit.\n *\n * A CALL THAT RUNS AWAY IN WHITE SPACE ENDS AT ONCE (#1334). With\n * `maxToolArgumentWhitespace` set, a tool call whose arguments end in a longer\n * run of white space outside strings has stopped writing, whatever it keeps\n * streaming. If its arguments are whole JSON, the attempt is aborted and the\n * call is finished as written: a `tool-call` with the trimmed arguments, then\n * a `stop` finish with the usage the stream had reported so far (none, on the\n * Responses API, where it comes with the terminal frame). Otherwise it is cut\n * like a call past `maxToolArgumentChars`, with a\n * `ProviderToolArgumentsRunawayError` whose detail carries `whitespace`.\n * Either way one warning is logged.\n *\n * AN ATTEMPT THAT STREAMED ONLY UNFINISHED TOOL-CALL ARGUMENTS IS NOT\n * COMMITTED (#1169). `tool-call-delta` is yielded as it arrives, so a UI can\n * show a call filling in, but until a text, reasoning, output, tool-search or\n * completed `tool-call` event the attempt can still be asked again: the call\n * never completed and never ran, so nothing the model said has been acted on.\n * Before the retry a `tool-call-discard` event names the partial calls, so\n * the consumer drops them; the next attempt's calls get new ids. Any retryable\n * break counts, not only the limits above. Once retries are spent, the partial\n * calls stay and the call ends with the error, as before.\n */\nexport async function* streamResponses<Body extends object = ResponsesRequest>(\n endpoint: ResponsesEndpoint,\n body: Body,\n params: {\n signal?: AbortSignal;\n structuredOutput: boolean;\n /** See `ProviderStreamParams.retryToolArgumentsTooLong`. */\n retryToolArgumentsTooLong?: 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 * Responses bodies only: without it a refused file fails the call. */\n files?: Map<string, SentFile>;\n /**\n * The SSE parser. Defaults to the Responses one; the Anthropic provider\n * passes `parseMessagesStream`, and everything else here (retries, the\n * stream limits, holding back until the first content event) is shared.\n */\n parse?: (\n chunks: AsyncIterable<string>,\n options: { structuredOutput: boolean; onUsage?: (usage: Usage) => void },\n ) => AsyncIterable<ProviderEvent>;\n },\n): AsyncGenerator<ProviderEvent> {\n const parse = params.parse ?? parseResponsesStream;\n let request = body;\n const rejected = new Set<string>();\n let fileAttempts = 0;\n // Once per call: see `providers/staleReasoning.ts`.\n let reasoningStripped = false;\n const maxStreamRetries = Math.max(0, endpoint.maxRetries);\n const random = endpoint.random ?? Math.random;\n // What the attempts that were dropped before their first content event\n // reported as used. Folded into whichever `finish` closes the call.\n let dropped: Usage | undefined;\n const closing = (event: Extract<ProviderEvent, { type: \"finish\" }>): ProviderEvent => {\n if (!dropped) return event;\n const usage = addUsage(addUsage(emptyUsage(), dropped), event.usage);\n dropped = undefined;\n return { ...event, usage };\n };\n // With what the attempt used so far (#1353): a stopped call is billed too.\n const aborted = (usage?: Usage): ProviderEvent =>\n closing({ type: \"finish\", reason: \"aborted\", usage: usage ?? emptyUsage() });\n /** What the call has used, the dropped attempts' and this one's so far. */\n const soFar = (usage: Usage): Usage => addUsage(addUsage(emptyUsage(), dropped ?? emptyUsage()), usage);\n\n const idleMs = endpoint.streamIdleTimeoutMs ?? 0;\n const maxMs = endpoint.streamMaxDurationMs ?? 0;\n const maxArgs = endpoint.maxToolArgumentChars ?? 0;\n const maxSpace = endpoint.maxToolArgumentWhitespace ?? 0;\n const now = endpoint.now ?? Date.now;\n const startedAt = now();\n\n for (let streamAttempt = 0; ; streamAttempt++) {\n // Per attempt, so an idle timeout can abort this attempt's request (and\n // release its socket) without touching the caller's signal.\n const attempt = new AbortController();\n const signal = params.signal ? AbortSignal.any([params.signal, attempt.signal]) : attempt.signal;\n let response: Response | undefined;\n while (response === undefined) {\n try {\n // The request retries inside `requestWithRetry`, and its `retry`\n // events are yielded as they happen, not after it settles: they exist\n // to say the call is waiting, while it is (#1192).\n const retries: ProviderEvent[] = [];\n let wake: () => void = () => {};\n const pending = 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,\n fetchImpl: endpoint.fetchImpl,\n sleep: endpoint.sleep,\n random: endpoint.random,\n now: endpoint.now,\n startedAt,\n ...(endpoint.retry ? { retry: endpoint.retry } : {}),\n onRetry: (info) => {\n retries.push({ type: \"retry\", ...info, phase: \"request\" });\n wake();\n },\n },\n );\n const settled = pending.then(\n () => true,\n () => true,\n );\n for (;;) {\n const woken = new Promise<false>((resolve) => (wake = () => resolve(false)));\n const done = await Promise.race([settled, woken]);\n yield* retries.splice(0);\n if (done) break;\n }\n response = await pending;\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 responses = request as unknown as ResponsesRequest;\n const blamed =\n params.files && fileAttempts < MAX_FILE_REJECTION_RETRIES\n ? rejectedFileIds(responses, error, params.files).filter((id) => !rejected.has(id))\n : [];\n if (blamed.length > 0) {\n fileAttempts++;\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(responses, new Set(blamed), params.files) as unknown as Body;\n continue;\n }\n // A replayed reasoning item the API no longer has fails this request\n // and every later one in the thread. Asked again once without the\n // reasoning items, which the answer does not depend on.\n const stripped = reasoningStripped ? null : withoutStaleReasoning(request, error);\n if (stripped) {\n reasoningStripped = true;\n request = stripped as unknown as Body;\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 aborted();\n return;\n }\n yield { type: \"error\", error: normalized, ...httpErrorDetail(error) };\n yield closing({ type: \"finish\", reason: \"error\", usage: emptyUsage() });\n return;\n }\n }\n\n const held: ProviderEvent[] = [];\n let committed = false;\n let failure: AgentError | undefined;\n let streamTimedOut = false;\n // The call this attempt was cut at, when `maxToolArgumentChars` ended it.\n let cut: ToolArgumentsTooLong | undefined;\n // The tool calls this attempt has yielded argument deltas for, with how\n // much text each has streamed. Before `committed`, these are the only\n // things the consumer has seen, and a retry discards them.\n const partial = new Map<string, ArgumentScan>();\n // The usage the stream reported so far: for a call ended as a runaway,\n // cut, broken or stopped (#1353), and for the `usage` events.\n let usageSoFar: Usage | undefined;\n // The whole call's, as `usage` and the closing `finish` count it.\n const withUsage = (): { usage?: Usage } => (usageSoFar ? { usage: soFar(usageSoFar) } : {});\n // A runaway call whose arguments were whole JSON, finished as written.\n let finished: Extract<ProviderEvent, { type: \"tool-call\" }> | undefined;\n try {\n const body = boundedBody(\n response.body,\n { idleMs, maxMs },\n {\n idle: () => {\n const error = new ProviderStreamIdleError(idleMs);\n attempt.abort(error);\n return error;\n },\n max: () => {\n const error = new ProviderStreamDurationError(maxMs);\n attempt.abort(error);\n return error;\n },\n },\n );\n for await (const event of parse(decodeChunks(body), {\n structuredOutput: params.structuredOutput,\n onUsage: (usage) => (usageSoFar = usage),\n })) {\n // The parser's count is this attempt's; the call's includes the\n // attempts dropped before it. Sent at once, committed or not: it\n // replaces rather than adds, and a dropped attempt is billed anyway,\n // so a consumer that stops before the first content (the whole input\n // is billed by then) still holds the count.\n if (event.type === \"usage\") {\n usageSoFar = event.usage;\n yield { type: \"usage\", usage: soFar(event.usage) };\n continue;\n }\n if (event.type === \"tool-call-delta\") {\n let scan = partial.get(event.toolCallId);\n if (!scan) partial.set(event.toolCallId, (scan = newScan()));\n scanArguments(scan, event.argsDelta, maxSpace > 0);\n const chars = scan.chars;\n if (maxSpace > 0 && scan.space > maxSpace) {\n const args = scan.text.trimEnd();\n const whole = isJson(args);\n warnRunaway(event.name, event.toolCallId, chars, scan.space, maxSpace, whole);\n if (!whole) {\n const error = new ProviderToolArgumentsRunawayError(\n maxSpace,\n event.name,\n event.toolCallId,\n chars,\n scan.space,\n );\n attempt.abort(error);\n throw error;\n }\n partial.delete(event.toolCallId);\n finished = {\n type: \"tool-call\",\n toolCallId: event.toolCallId,\n name: event.name,\n args,\n ...(event.namespace ? { namespace: event.namespace } : {}),\n };\n break;\n }\n if (maxArgs > 0 && chars > maxArgs) {\n const error = new ProviderToolArgumentsTooLongError(\n maxArgs,\n event.name,\n event.toolCallId,\n chars,\n );\n attempt.abort(error);\n throw error;\n }\n yield event;\n continue;\n }\n if (event.type === \"tool-call\") partial.delete(event.toolCallId);\n if (committed) {\n yield event.type === \"finish\" ? closing(event) : event;\n continue;\n }\n if (isContentEvent(event)) {\n committed = true;\n yield* held.splice(0);\n yield event;\n continue;\n }\n if (event.type === \"error\") failure = event.error;\n held.push(event);\n }\n // Let go of the runaway's body (the loop released its lock), so the\n // provider stops sending whatever the fetch does with the abort below.\n if (finished) await body?.cancel().catch(() => {});\n } catch (error) {\n streamTimedOut = error instanceof ProviderTimeoutError;\n const normalized = normalizeProviderError(error);\n if (normalized.code === \"aborted\" || params.signal?.aborted) {\n yield aborted(usageSoFar);\n return;\n }\n if (error instanceof ProviderToolArgumentsTooLongError) cut = error.detail;\n if (committed) {\n // The cut call is named after earlier content too (#1326), so the agent\n // can answer it with the tool's error. A committed attempt is never\n // asked again, so `retryToolArgumentsTooLong` does not apply here.\n yield { type: \"error\", error: normalized, ...(cut ? { toolArgumentsTooLong: cut } : {}), ...withUsage() };\n yield closing({ type: \"finish\", reason: \"error\", usage: usageSoFar ?? emptyUsage() });\n return;\n }\n failure = normalized;\n held.push(\n { type: \"error\", error: normalized, ...(cut ? { toolArgumentsTooLong: cut } : {}), ...withUsage() },\n { type: \"finish\", reason: \"error\", usage: usageSoFar ?? emptyUsage() },\n );\n }\n if (finished) {\n // The runaway call, finished as written: content, so it commits the\n // attempt, and the answer ends with it. Calls still streaming beside it\n // never finished and are taken back. The loop has let go of the body;\n // the abort releases the connection.\n attempt.abort();\n if (!committed) yield* held.splice(0);\n yield finished;\n if (partial.size > 0) yield { type: \"tool-call-discard\", toolCallIds: [...partial.keys()] };\n yield closing({ type: \"finish\", reason: \"stop\", usage: usageSoFar ?? emptyUsage() });\n return;\n }\n if (committed) return;\n\n let detail: ProviderErrorDetail = {};\n for (const event of held) if (event.type === \"error\") detail = httpErrorDetail(event);\n // Past `maxRetries`, a patience budget asks again too (#1258), for the\n // failures its `on` names (#1291). A cut call the caller sends back to the\n // model itself is not asked again at all: the same request comes out as\n // long again, which is what the limit is there to stop.\n const delayMs =\n !failure?.retryable || params.signal?.aborted || (cut && params.retryToolArgumentsTooLong === false)\n ? undefined\n : streamAttempt < maxStreamRetries\n ? backoffDelayMs(streamAttempt, random)\n : endpoint.retry &&\n patienceApplies(endpoint.retry, failure, {\n ...(detail.status !== undefined ? { status: detail.status } : {}),\n timedOut: streamTimedOut,\n ...(cut ? { toolArgumentsTooLong: cut } : {}),\n })\n ? patientDelayMs(\n endpoint.retry,\n streamAttempt - maxStreamRetries,\n failure.retryAfter,\n now() - startedAt,\n random,\n )\n : undefined;\n if (delayMs !== undefined) {\n let attemptUsage: Usage | undefined;\n for (const event of held) {\n if (event.type === \"finish\") attemptUsage = addUsage(attemptUsage ?? emptyUsage(), event.usage);\n }\n if (attemptUsage) dropped = addUsage(dropped ?? emptyUsage(), attemptUsage);\n const used = attemptUsage && attemptUsage.totalTokens > 0 ? { usage: attemptUsage } : {};\n if (partial.size > 0) yield { type: \"tool-call-discard\", toolCallIds: [...partial.keys()] };\n const elapsedMs = now() - startedAt;\n yield {\n type: \"retry\",\n attempt: streamAttempt + 1,\n maxRetries: maxStreamRetries,\n error: failure,\n ...detail,\n ...used,\n phase: \"stream\",\n timedOut: streamTimedOut,\n ...(cut ? { toolArgumentsTooLong: cut } : {}),\n delayMs,\n elapsedMs,\n ...(endpoint.retry\n ? { remainingMs: Math.max(0, endpoint.retry.patienceMs - elapsedMs - delayMs) }\n : {}),\n };\n // What the call has used, dropped attempts included, for a consumer\n // that stops during the wait: the next attempt's count starts again.\n if (dropped && dropped.totalTokens > 0) yield { type: \"usage\", usage: soFar(emptyUsage()) };\n try {\n await waitUnlessAborted(delayMs, params.signal, endpoint.sleep);\n } catch {\n yield aborted();\n return;\n }\n continue;\n }\n\n for (const event of held) yield event.type === \"finish\" ? closing(event) : event;\n return;\n }\n}\n\n/** One tool call's arguments as they stream in, read just far enough to tell\n * white space inside a string from white space between tokens (#1334). */\ntype ArgumentScan = {\n chars: number;\n /** The arguments so far; kept only while `maxToolArgumentWhitespace` is on. */\n text: string;\n inString: boolean;\n escaped: boolean;\n /** The run of white space outside strings the arguments end in. */\n space: number;\n};\n\nfunction newScan(): ArgumentScan {\n return { chars: 0, text: \"\", inString: false, escaped: false, space: 0 };\n}\n\nfunction scanArguments(scan: ArgumentScan, delta: string, track: boolean): void {\n scan.chars += delta.length;\n if (!track) return;\n scan.text += delta;\n for (const ch of delta) {\n if (scan.inString) {\n if (scan.escaped) scan.escaped = false;\n else if (ch === \"\\\\\") scan.escaped = true;\n else if (ch === '\"') scan.inString = false;\n } else if (ch === \" \" || ch === \"\\n\" || ch === \"\\r\" || ch === \"\\t\") {\n scan.space++;\n continue;\n } else if (ch === '\"') {\n scan.inString = true;\n }\n scan.space = 0;\n }\n}\n\nfunction isJson(text: string): boolean {\n try {\n JSON.parse(text);\n return true;\n } catch {\n return false;\n }\n}\n\n/** One structured warning per runaway call, through the app's logger when\n * there is one, as the agent's own warnings are. */\nfunction warnRunaway(\n tool: string,\n toolCallId: string,\n chars: number,\n whitespace: number,\n limit: number,\n whole: boolean,\n): void {\n const message = `[gemi/ai] tool call \"${tool}\" ran away in white space (more than ${limit} characters, maxToolArgumentWhitespace); ${\n whole ? \"its arguments were whole JSON, so it was finished as written\" : \"its arguments were not whole JSON, so it was cut\"\n }`;\n const metadata = { tool, toolCallId, chars, whitespace, limit, whole };\n let logged = false;\n try {\n Log.warning(message, metadata);\n logged = true;\n } catch {\n // No application to resolve a logger from.\n }\n if (!logged || process.env.NODE_ENV === \"development\") console.warn(message, metadata);\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 /** `null` for Anthropic's Files API, which takes no purpose. */\n purpose: UploadPurpose | null = \"user_data\",\n): Promise<string> {\n const form = new FormData();\n if (purpose) 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\n/**\n * Deletes a file `uploadFile` sent (#1165): `DELETE {base}/files/{id}{query}`,\n * with the same resolved host, headers and api-version as the upload, so the\n * URL is built from `filesUrl` rather than worked out again.\n *\n * A 404 resolves: the file is already gone (deleted earlier, expired at the\n * vendor, or a retried delete whose first answer was lost), which is the state\n * the caller asked for.\n */\nexport async function deleteFile(endpoint: ResponsesEndpoint, fileId: string): Promise<void> {\n const at = endpoint.filesUrl.indexOf(\"?\");\n const path = at === -1 ? endpoint.filesUrl : endpoint.filesUrl.slice(0, at);\n const query = at === -1 ? \"\" : endpoint.filesUrl.slice(at);\n try {\n const response = await requestWithRetry(\n `${path}/${encodeURIComponent(fileId)}${query}`,\n { method: \"DELETE\", headers: await endpoint.headers() },\n {\n maxRetries: endpoint.maxRetries,\n timeoutMs: endpoint.timeoutMs,\n fetchImpl: endpoint.fetchImpl,\n ...(endpoint.sleep ? { sleep: endpoint.sleep } : {}),\n ...(endpoint.random ? { random: endpoint.random } : {}),\n },\n );\n await response.body?.cancel();\n } catch (error) {\n if (error instanceof ProviderHttpError && error.status === 404) return;\n throw error;\n }\n}\n",
|
|
13
|
-
"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, ToolSearchRecord } 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 tool_choice?:\n | string\n | { type: \"function\"; name: string }\n | { type: \"allowed_tools\"; mode: \"auto\" | \"required\"; tools: { type: \"function\"; name: string }[] };\n text?: { format: Record<string, unknown> };\n reasoning?: { effort: string; summary?: \"auto\" };\n temperature?: number;\n max_output_tokens?: number;\n prompt_cache_key?: string;\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, params.tools),\n stream: true,\n };\n\n // After the conversation, so the prefix the cache holds ends before it\n // (#1345). A developer message: it is the app speaking, not the user.\n if (params.trailingContext) {\n body.input.push({\n role: \"developer\",\n content: [{ type: \"input_text\", text: params.trailingContext }],\n });\n }\n\n if (params.systemPrompt) body.instructions = params.systemPrompt;\n\n // A step held to some of the tools (#1345): the full list goes out and\n // `allowed_tools` names what this call may use, so the tool list (the\n // start of the cached prefix) stays the same. It names functions only: a\n // list with namespaces or tool search is narrowed instead, as before.\n let tools = toResponsesTools(params.tools, capabilities);\n let allowed: string[] | undefined;\n if (params.allowedTools) {\n if (tools.every((tool) => tool.type === \"function\")) {\n allowed = params.allowedTools;\n } else {\n tools = toResponsesTools(narrowTools(params.tools ?? [], params.allowedTools), capabilities);\n }\n }\n if (tools.length > 0) {\n body.tools = tools;\n if (!capabilities.parallelToolCalls) body.parallel_tool_calls = false;\n const choice = params.toolChoice;\n if (allowed && choice !== \"none\" && typeof choice !== \"object\") {\n body.tool_choice = {\n type: \"allowed_tools\",\n mode: choice === \"required\" ? \"required\" : \"auto\",\n tools: allowed.map((name) => ({ type: \"function\", name })),\n };\n } else if (choice !== undefined) {\n body.tool_choice = typeof choice === \"string\" ? choice : { type: \"function\", name: choice.name };\n }\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 if (params.promptCacheKey) body.prompt_cache_key = params.promptCacheKey;\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 tools?: (ProviderToolSpec | ProviderToolNamespace)[],\n): ResponsesInputItem[] {\n const items: ResponsesInputItem[] = [];\n // What this request's tools can resolve a namespaced call or a search\n // against. Empty without tool search: the tools are then sent flat (see\n // `toResponsesTools`), there is no namespace for a call to name, and a\n // search item would be one for a tool the request does not have.\n const namespaces = new Map<string, ProviderToolNamespace>();\n if (capabilities.toolSearch) {\n for (const entry of tools ?? []) if (isNamespace(entry)) namespaces.set(entry.name, entry);\n }\n\n for (const message of messages) {\n const role = message.role;\n const replayReasoning = !UNFINISHED_RESPONSE.has(message.finishReason);\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 assertFilePart(part, attachmentId);\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 if (!replayReasoning) break;\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 // `Array.isArray` rather than truthiness: in stateless mode this\n // field came back from the browser, and a turn must not throw on it.\n if (capabilities.toolSearch && Array.isArray(part.toolSearches)) {\n for (const search of part.toolSearches) {\n items.push(...toolSearchItems(search, tools ?? []));\n }\n }\n const call: ResponsesInputItem = {\n type: \"function_call\",\n call_id: part.toolCallId,\n name: String(part.name),\n arguments: JSON.stringify(part.input ?? {}),\n };\n // Back the way the model made it (#776). Without the namespace this\n // is a call to a top-level function the tools do not list, and the\n // model, reading its own history, stopped making sense after one.\n // Dropped only when this request has no such namespace — a provider\n // without tool search, or an agent whose tools changed since — where\n // naming it would be a call into nothing.\n if (part.namespace && namespaces.has(part.namespace)) call.namespace = part.namespace;\n items.push(call);\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 */\nexport function 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 */\nexport function 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 return { type: isImageFile(part) ? \"input_image\" : \"input_file\", file_id: part.fileId };\n}\n\n/** Whether a file part goes to the image block. See `fileContent`. */\nexport function isImageFile(part: FilePart): boolean {\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 return mimeType\n ? mimeType.startsWith(\"image/\") && mimeType !== \"image/svg+xml\"\n : hasImageExtension(part.name);\n}\n\n/**\n * The two file parts no request can carry: a gemi attachment id in `fileId`,\n * and a part with neither id. See the `file` case in `toResponsesInput`.\n */\nexport function assertFilePart(part: FilePart, attachmentId: string | undefined): void {\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 now:\n // the model is told the file exists and is not shown it. What is still\n // refused is a part with NEITHER id — nothing to show and nothing to name.\n // The emptiness check is `!part.fileId` rather than a prefix test because\n // `undefined?.startsWith` is `undefined`, and `file_id: undefined` reaches\n // 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}\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 * The finish reasons of a message whose model response may never have\n * completed, and whose reasoning is therefore not replayed.\n *\n * A reasoning item goes back by id, and the API resolves that id against the\n * response it stored. A response the stream broke off (a dropped socket,\n * `streamMaxDurationMs`, a stop, a process that died mid-step) was never\n * completed, so it was never stored: replaying its `rs_…` id is answered\n * `400 Item with id 'rs_…' not found.`, and since the id is in the thread, so\n * is every later turn. Measured in fager on Azure (gpt-6.1-sol): a main step\n * cut by `streamMaxDurationMs` after its reasoning had started, then every\n * following turn of that thread failed with exactly that 400.\n *\n * The text and tool calls of such a message still go back: they are sent by\n * value, not by id. Only the reasoning, which is the one part the API looks\n * up, is left out. When the step did complete and only the run failed later\n * (a tool, a limit), this drops reasoning that was in fact retrievable, which\n * costs one turn's prompt-cache hit on that item and nothing else. The other\n * direction is a thread that can no longer be answered.\n */\nconst UNFINISHED_RESPONSE = new Set<string | undefined>([\"error\", \"aborted\", \"interrupted\"]);\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 // The tool's `toModel` projection when it has one (#1061): the client got\n // the whole output, the model reads what the tool chose to show it.\n const output = part.modelOutput !== undefined ? part.modelOutput : part.output;\n return typeof output === \"string\" ? output : JSON.stringify(output ?? null);\n }\n\n if (part.status === \"running\") {\n // The same text on every request until the job settles, so the prompt\n // cache holds: no age, no progress. The `<jobs>` block says how it is\n // going. \"Do not start it again\" is the line that matters; without a\n // result to read, a model repeats the call.\n const summary =\n part.job?.summary === undefined ? \"\" : ` Started with: ${JSON.stringify(part.job.summary)}.`;\n return `Started background job ${part.job?.id ?? \"(unknown)\"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${summary}`;\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 if (part.cause === \"denied-earlier\") {\n return `The user already declined this tool call earlier in this conversation, so it did not run and they were not asked again. Do not ask for it again; carry on without 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/**\n * A tool search the model ran, back onto the wire as the pair the API sent:\n * a `tool_search_call` with the query, then a `tool_search_output` with what\n * it loaded (#776).\n *\n * Why at all: the API's own guide for tool search without\n * `previous_response_id` is to pass every earlier item back, the search pair\n * included, and a deferred tool is loaded for the model by the output item\n * in its history. Without the pair the model reads calls to tools nothing in\n * its context ever loaded.\n *\n * The shape is the hosted one: `execution: \"server\"`, `call_id: null`, no\n * item ids. The ids are left out so the history does not depend on the\n * vendor's stored items, which a `FallbackProvider` leg on another resource\n * does not have. Measured on Azure (gpt-5.4): this pair, the pair with the\n * original ids, and the pair without `call_id` were all accepted.\n *\n * The output is rebuilt from this request's tools rather than stored, using\n * the same `functionTool` the `tools` array uses, so it matches what the API\n * returned for the same tools (`__fixtures__/openai-tool-search.sse`).\n * Namespaces and functions the agent no longer has are left out, and a search\n * that would load nothing is not replayed at all.\n */\nfunction toolSearchItems(\n search: ToolSearchRecord,\n tools: (ProviderToolSpec | ProviderToolNamespace)[],\n): ResponsesInputItem[] {\n const loaded = new Set(stringsOf(search?.loaded));\n const namespaces = stringsOf(search?.namespaces);\n const wanted = new Set(namespaces);\n const found: ResponsesTool[] = [];\n\n for (const entry of tools) {\n if (isNamespace(entry)) {\n if (!wanted.has(entry.name)) continue;\n // A search that named the group but listed no functions loaded all of\n // it; otherwise only the functions it listed.\n const inner = entry.tools.filter((tool) => loaded.size === 0 || loaded.has(tool.name));\n if (inner.length === 0) continue;\n found.push({\n type: \"namespace\",\n name: entry.name,\n description: entry.description,\n tools: inner.map((tool) => functionTool(tool, true)),\n });\n } else if (entry.deferred && loaded.has(entry.name)) {\n found.push(functionTool(entry, true));\n }\n }\n\n if (found.length === 0) return [];\n const query =\n search.arguments && typeof search.arguments === \"object\"\n ? search.arguments\n : { paths: namespaces.length > 0 ? namespaces : [...loaded] };\n return [\n {\n type: \"tool_search_call\",\n call_id: null,\n execution: \"server\",\n status: \"completed\",\n arguments: query,\n },\n {\n type: \"tool_search_output\",\n call_id: null,\n execution: \"server\",\n status: \"completed\",\n tools: found,\n },\n ];\n}\n\nfunction stringsOf(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === \"string\") : [];\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\n/** `tools` cut to the names in `allowed`: a namespace keeps the members named. */\nfunction narrowTools(\n tools: (ProviderToolSpec | ProviderToolNamespace)[],\n allowed: readonly string[],\n): (ProviderToolSpec | ProviderToolNamespace)[] {\n const wanted = new Set(allowed);\n return tools.flatMap((tool): (ProviderToolSpec | ProviderToolNamespace)[] => {\n if (!isNamespace(tool)) return wanted.has(tool.name) ? [tool] : [];\n const members = tool.tools.filter((member) => wanted.has(member.name));\n return members.length > 0 ? [{ ...tool, tools: members }] : [];\n });\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",
|
|
12
|
+
"import { Log } from \"../../facades/Log\";\nimport type { ProviderEvent } from \"../AgentProvider\";\nimport type { ProviderTarget } from \"./endpoints\";\nimport {\n httpErrorDetail,\n ProviderHttpError,\n normalizeProviderError,\n ProviderStreamDurationError,\n ProviderStreamIdleError,\n ProviderTimeoutError,\n ProviderToolArgumentsRunawayError,\n ProviderToolArgumentsTooLongError,\n} from \"./errors\";\nimport {\n MAX_FILE_REJECTION_RETRIES,\n rejectedFileIds,\n withoutFiles,\n type SentFile,\n} from \"./fileRejection\";\nimport { addUsage, isContentEvent } from \"../runtime\";\nimport type { AgentError, ProviderErrorDetail, ToolArgumentsTooLong, Usage } from \"../types\";\nimport {\n backoffDelayMs,\n boundedBody,\n requestWithRetry,\n waitUnlessAborted,\n type FetchLike,\n type RequestOptions,\n patienceApplies,\n patientDelayMs,\n type ProviderRetryPolicy,\n} from \"./http\";\nimport type { ResponsesRequest } from \"./request\";\nimport { withoutStaleReasoning } from \"./staleReasoning\";\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 /** See `ProviderConfig.streamIdleTimeoutMs`. Absent or `0` is off. */\n streamIdleTimeoutMs?: number;\n /** See `ProviderConfig.streamMaxDurationMs`. Absent or `0` is off. */\n streamMaxDurationMs?: number;\n /** See `ProviderConfig.maxToolArgumentChars`. Absent or `0` is off. */\n maxToolArgumentChars?: number;\n /** See `ProviderConfig.maxToolArgumentWhitespace`. Absent or `0` is off. */\n maxToolArgumentWhitespace?: number;\n maxRetries: number;\n /** See `ProviderConfig.retry`. */\n retry?: ProviderRetryPolicy;\n fetchImpl?: FetchLike;\n /** Injected by the tests, with `random`, so a backoff can be asserted on\n * without waiting for it. See `RequestOptions`. */\n sleep?: RequestOptions[\"sleep\"];\n random?: () => number;\n now?: () => number;\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 streamIdleTimeoutMs: target.streamIdleTimeoutMs,\n streamMaxDurationMs: target.streamMaxDurationMs,\n maxToolArgumentChars: target.maxToolArgumentChars,\n maxToolArgumentWhitespace: target.maxToolArgumentWhitespace,\n maxRetries: target.maxRetries,\n ...(target.retry ? { retry: target.retry } : {}),\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 *\n * A STREAM THAT DIES BEFORE ITS FIRST CONTENT EVENT IS ASKED AGAIN (#946).\n * `requestWithRetry` covers a request that fails before a response arrives;\n * this covers the one whose response started and then broke while its body was\n * being read: the socket closed, the stream ended with no terminal frame, or\n * the provider sent a `response.failed` / `error` frame that reads as\n * retryable. Measured in an app: one such drop on the first step lost a whole\n * build, and the same request a second later worked.\n *\n * Nothing the user could have seen is repeated. Until the first content event\n * (`isContentEvent`) the only things a Responses stream yields are an error and\n * a finish, and those are held back; from the first content event on, the call\n * is committed and a later failure ends it as before. The retries use the\n * endpoint's `maxRetries` and the same backoff as the request retry, and an\n * abort during the wait ends the call at once. The usage a dropped attempt\n * reported is added to the call's closing `finish`, because it was billed.\n *\n * A STREAM THAT GOES SILENT IS CUT (#1167). With `streamIdleTimeoutMs` set, a\n * body that sends nothing for that long errors with a `ProviderStreamIdleError`\n * and the attempt's request is aborted, which releases the socket. From there it\n * is a broken stream like any other: retryable, so asked again before the first\n * content event, and the call's error after it (nothing is repeated). The\n * caller's signal still wins: an abort while waiting ends the call as aborted.\n *\n * A STREAM THAT KEEPS TRICKLING IS CUT TOO (#1169). `streamMaxDurationMs`\n * bounds an attempt's stream by the wall clock, which no chunk resets, and\n * `maxToolArgumentChars` bounds the argument text of one unfinished tool call.\n * Both abort the attempt with a retryable error, like the idle limit.\n *\n * A CALL THAT RUNS AWAY IN WHITE SPACE ENDS AT ONCE (#1334). With\n * `maxToolArgumentWhitespace` set, a tool call whose arguments end in a longer\n * run of white space outside strings has stopped writing, whatever it keeps\n * streaming. If its arguments are whole JSON, the attempt is aborted and the\n * call is finished as written: a `tool-call` with the trimmed arguments, then\n * a `stop` finish with the usage the stream had reported so far (none, on the\n * Responses API, where it comes with the terminal frame). Otherwise it is cut\n * like a call past `maxToolArgumentChars`, with a\n * `ProviderToolArgumentsRunawayError` whose detail carries `whitespace`.\n * Either way one warning is logged.\n *\n * AN ATTEMPT THAT STREAMED ONLY UNFINISHED TOOL-CALL ARGUMENTS IS NOT\n * COMMITTED (#1169). `tool-call-delta` is yielded as it arrives, so a UI can\n * show a call filling in, but until a text, reasoning, output, tool-search or\n * completed `tool-call` event the attempt can still be asked again: the call\n * never completed and never ran, so nothing the model said has been acted on.\n * Before the retry a `tool-call-discard` event names the partial calls, so\n * the consumer drops them; the next attempt's calls get new ids. Any retryable\n * break counts, not only the limits above. Once retries are spent, the partial\n * calls stay and the call ends with the error, as before.\n */\nexport async function* streamResponses<Body extends object = ResponsesRequest>(\n endpoint: ResponsesEndpoint,\n body: Body,\n params: {\n signal?: AbortSignal;\n structuredOutput: boolean;\n /** See `ProviderStreamParams.retryToolArgumentsTooLong`. */\n retryToolArgumentsTooLong?: 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 * Responses bodies only: without it a refused file fails the call. */\n files?: Map<string, SentFile>;\n /**\n * The SSE parser. Defaults to the Responses one; the Anthropic provider\n * passes `parseMessagesStream`, and everything else here (retries, the\n * stream limits, holding back until the first content event) is shared.\n */\n parse?: (\n chunks: AsyncIterable<string>,\n options: { structuredOutput: boolean; onUsage?: (usage: Usage) => void },\n ) => AsyncIterable<ProviderEvent>;\n },\n): AsyncGenerator<ProviderEvent> {\n const parse = params.parse ?? parseResponsesStream;\n let request = body;\n const rejected = new Set<string>();\n let fileAttempts = 0;\n // Once per call: see `providers/staleReasoning.ts`.\n let reasoningStripped = false;\n const maxStreamRetries = Math.max(0, endpoint.maxRetries);\n const random = endpoint.random ?? Math.random;\n // What the attempts that were dropped before their first content event\n // reported as used. Folded into whichever `finish` closes the call.\n let dropped: Usage | undefined;\n const closing = (event: Extract<ProviderEvent, { type: \"finish\" }>): ProviderEvent => {\n if (!dropped) return event;\n const usage = addUsage(addUsage(emptyUsage(), dropped), event.usage);\n dropped = undefined;\n return { ...event, usage };\n };\n // With what the attempt used so far (#1353): a stopped call is billed too.\n const aborted = (usage?: Usage): ProviderEvent =>\n closing({ type: \"finish\", reason: \"aborted\", usage: usage ?? emptyUsage() });\n /** What the call has used, the dropped attempts' and this one's so far. */\n const soFar = (usage: Usage): Usage => addUsage(addUsage(emptyUsage(), dropped ?? emptyUsage()), usage);\n\n const idleMs = endpoint.streamIdleTimeoutMs ?? 0;\n const maxMs = endpoint.streamMaxDurationMs ?? 0;\n const maxArgs = endpoint.maxToolArgumentChars ?? 0;\n const maxSpace = endpoint.maxToolArgumentWhitespace ?? 0;\n const now = endpoint.now ?? Date.now;\n const startedAt = now();\n\n for (let streamAttempt = 0; ; streamAttempt++) {\n // Per attempt, so an idle timeout can abort this attempt's request (and\n // release its socket) without touching the caller's signal.\n const attempt = new AbortController();\n const signal = params.signal ? AbortSignal.any([params.signal, attempt.signal]) : attempt.signal;\n let response: Response | undefined;\n while (response === undefined) {\n try {\n // The request retries inside `requestWithRetry`, and its `retry`\n // events are yielded as they happen, not after it settles: they exist\n // to say the call is waiting, while it is (#1192).\n const retries: ProviderEvent[] = [];\n let wake: () => void = () => {};\n const pending = 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,\n fetchImpl: endpoint.fetchImpl,\n sleep: endpoint.sleep,\n random: endpoint.random,\n now: endpoint.now,\n startedAt,\n ...(endpoint.retry ? { retry: endpoint.retry } : {}),\n onRetry: (info) => {\n retries.push({ type: \"retry\", ...info, phase: \"request\" });\n wake();\n },\n },\n );\n const settled = pending.then(\n () => true,\n () => true,\n );\n for (;;) {\n const woken = new Promise<false>((resolve) => (wake = () => resolve(false)));\n const done = await Promise.race([settled, woken]);\n yield* retries.splice(0);\n if (done) break;\n }\n response = await pending;\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 responses = request as unknown as ResponsesRequest;\n const blamed =\n params.files && fileAttempts < MAX_FILE_REJECTION_RETRIES\n ? rejectedFileIds(responses, error, params.files).filter((id) => !rejected.has(id))\n : [];\n if (blamed.length > 0) {\n fileAttempts++;\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(responses, new Set(blamed), params.files) as unknown as Body;\n continue;\n }\n // A replayed reasoning item the API no longer has fails this request\n // and every later one in the thread. Asked again once without the\n // reasoning items, which the answer does not depend on.\n const stripped = reasoningStripped ? null : withoutStaleReasoning(request, error);\n if (stripped) {\n reasoningStripped = true;\n request = stripped as unknown as Body;\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 aborted();\n return;\n }\n yield { type: \"error\", error: normalized, ...httpErrorDetail(error) };\n yield closing({ type: \"finish\", reason: \"error\", usage: emptyUsage() });\n return;\n }\n }\n\n const held: ProviderEvent[] = [];\n let committed = false;\n let failure: AgentError | undefined;\n let streamTimedOut = false;\n // The call this attempt was cut at, when `maxToolArgumentChars` ended it.\n let cut: ToolArgumentsTooLong | undefined;\n // The tool calls this attempt has yielded argument deltas for, with how\n // much text each has streamed. Before `committed`, these are the only\n // things the consumer has seen, and a retry discards them.\n const partial = new Map<string, ArgumentScan>();\n // The usage the stream reported so far: for a call ended as a runaway,\n // cut, broken or stopped (#1353), and for the `usage` events.\n let usageSoFar: Usage | undefined;\n // The whole call's, as `usage` and the closing `finish` count it.\n const withUsage = (): { usage?: Usage } => (usageSoFar ? { usage: soFar(usageSoFar) } : {});\n // A runaway call whose arguments were whole JSON, finished as written.\n let finished: Extract<ProviderEvent, { type: \"tool-call\" }> | undefined;\n try {\n const body = boundedBody(\n response.body,\n { idleMs, maxMs },\n {\n idle: () => {\n const error = new ProviderStreamIdleError(idleMs);\n attempt.abort(error);\n return error;\n },\n max: () => {\n const error = new ProviderStreamDurationError(maxMs);\n attempt.abort(error);\n return error;\n },\n },\n );\n for await (const event of parse(decodeChunks(body), {\n structuredOutput: params.structuredOutput,\n onUsage: (usage) => (usageSoFar = usage),\n })) {\n // The parser's count is this attempt's; the call's includes the\n // attempts dropped before it. Sent at once, committed or not: it\n // replaces rather than adds, and a dropped attempt is billed anyway,\n // so a consumer that stops before the first content (the whole input\n // is billed by then) still holds the count.\n if (event.type === \"usage\") {\n usageSoFar = event.usage;\n yield { type: \"usage\", usage: soFar(event.usage) };\n continue;\n }\n if (event.type === \"tool-call-delta\") {\n let scan = partial.get(event.toolCallId);\n if (!scan) partial.set(event.toolCallId, (scan = newScan()));\n scanArguments(scan, event.argsDelta, maxSpace > 0);\n const chars = scan.chars;\n if (maxSpace > 0 && scan.space > maxSpace) {\n const args = scan.text.trimEnd();\n const whole = isJson(args);\n warnRunaway(event.name, event.toolCallId, chars, scan.space, maxSpace, whole);\n if (!whole) {\n const error = new ProviderToolArgumentsRunawayError(\n maxSpace,\n event.name,\n event.toolCallId,\n chars,\n scan.space,\n );\n attempt.abort(error);\n throw error;\n }\n partial.delete(event.toolCallId);\n finished = {\n type: \"tool-call\",\n toolCallId: event.toolCallId,\n name: event.name,\n args,\n ...(event.namespace ? { namespace: event.namespace } : {}),\n };\n break;\n }\n if (maxArgs > 0 && chars > maxArgs) {\n const error = new ProviderToolArgumentsTooLongError(\n maxArgs,\n event.name,\n event.toolCallId,\n chars,\n );\n attempt.abort(error);\n throw error;\n }\n yield event;\n continue;\n }\n if (event.type === \"tool-call\") partial.delete(event.toolCallId);\n if (committed) {\n yield event.type === \"finish\" ? closing(event) : event;\n continue;\n }\n if (isContentEvent(event)) {\n committed = true;\n yield* held.splice(0);\n yield event;\n continue;\n }\n if (event.type === \"error\") failure = event.error;\n held.push(event);\n }\n // Let go of the runaway's body (the loop released its lock), so the\n // provider stops sending whatever the fetch does with the abort below.\n if (finished) await body?.cancel().catch(() => {});\n } catch (error) {\n streamTimedOut = error instanceof ProviderTimeoutError;\n const normalized = normalizeProviderError(error);\n if (normalized.code === \"aborted\" || params.signal?.aborted) {\n yield aborted(usageSoFar);\n return;\n }\n if (error instanceof ProviderToolArgumentsTooLongError) cut = error.detail;\n if (committed) {\n // The cut call is named after earlier content too (#1326), so the agent\n // can answer it with the tool's error. A committed attempt is never\n // asked again, so `retryToolArgumentsTooLong` does not apply here.\n yield { type: \"error\", error: normalized, ...(cut ? { toolArgumentsTooLong: cut } : {}), ...withUsage() };\n yield closing({ type: \"finish\", reason: \"error\", usage: usageSoFar ?? emptyUsage() });\n return;\n }\n failure = normalized;\n held.push(\n { type: \"error\", error: normalized, ...(cut ? { toolArgumentsTooLong: cut } : {}), ...withUsage() },\n { type: \"finish\", reason: \"error\", usage: usageSoFar ?? emptyUsage() },\n );\n }\n if (finished) {\n // The runaway call, finished as written: content, so it commits the\n // attempt, and the answer ends with it. Calls still streaming beside it\n // never finished and are taken back. The loop has let go of the body;\n // the abort releases the connection.\n attempt.abort();\n if (!committed) yield* held.splice(0);\n yield finished;\n if (partial.size > 0) yield { type: \"tool-call-discard\", toolCallIds: [...partial.keys()] };\n yield closing({ type: \"finish\", reason: \"stop\", usage: usageSoFar ?? emptyUsage() });\n return;\n }\n if (committed) return;\n\n let detail: ProviderErrorDetail = {};\n for (const event of held) if (event.type === \"error\") detail = httpErrorDetail(event);\n // Past `maxRetries`, a patience budget asks again too (#1258), for the\n // failures its `on` names (#1291). A cut call the caller sends back to the\n // model itself is not asked again at all: the same request comes out as\n // long again, which is what the limit is there to stop.\n const delayMs =\n !failure?.retryable || params.signal?.aborted || (cut && params.retryToolArgumentsTooLong === false)\n ? undefined\n : streamAttempt < maxStreamRetries\n ? backoffDelayMs(streamAttempt, random)\n : endpoint.retry &&\n patienceApplies(endpoint.retry, failure, {\n ...(detail.status !== undefined ? { status: detail.status } : {}),\n timedOut: streamTimedOut,\n ...(cut ? { toolArgumentsTooLong: cut } : {}),\n })\n ? patientDelayMs(\n endpoint.retry,\n streamAttempt - maxStreamRetries,\n failure.retryAfter,\n now() - startedAt,\n random,\n )\n : undefined;\n if (delayMs !== undefined) {\n let attemptUsage: Usage | undefined;\n for (const event of held) {\n if (event.type === \"finish\") attemptUsage = addUsage(attemptUsage ?? emptyUsage(), event.usage);\n }\n if (attemptUsage) dropped = addUsage(dropped ?? emptyUsage(), attemptUsage);\n const used = attemptUsage && attemptUsage.totalTokens > 0 ? { usage: attemptUsage } : {};\n if (partial.size > 0) yield { type: \"tool-call-discard\", toolCallIds: [...partial.keys()] };\n const elapsedMs = now() - startedAt;\n yield {\n type: \"retry\",\n attempt: streamAttempt + 1,\n maxRetries: maxStreamRetries,\n error: failure,\n ...detail,\n ...used,\n phase: \"stream\",\n timedOut: streamTimedOut,\n ...(cut ? { toolArgumentsTooLong: cut } : {}),\n delayMs,\n elapsedMs,\n ...(endpoint.retry\n ? { remainingMs: Math.max(0, endpoint.retry.patienceMs - elapsedMs - delayMs) }\n : {}),\n };\n // What the call has used, dropped attempts included, for a consumer\n // that stops during the wait: the next attempt's count starts again.\n if (dropped && dropped.totalTokens > 0) yield { type: \"usage\", usage: soFar(emptyUsage()) };\n try {\n await waitUnlessAborted(delayMs, params.signal, endpoint.sleep);\n } catch {\n yield aborted();\n return;\n }\n continue;\n }\n\n for (const event of held) yield event.type === \"finish\" ? closing(event) : event;\n return;\n }\n}\n\n/** One tool call's arguments as they stream in, read just far enough to tell\n * white space inside a string from white space between tokens (#1334). */\ntype ArgumentScan = {\n chars: number;\n /** The arguments so far; kept only while `maxToolArgumentWhitespace` is on. */\n text: string;\n inString: boolean;\n escaped: boolean;\n /** The run of white space outside strings the arguments end in. */\n space: number;\n};\n\nfunction newScan(): ArgumentScan {\n return { chars: 0, text: \"\", inString: false, escaped: false, space: 0 };\n}\n\nfunction scanArguments(scan: ArgumentScan, delta: string, track: boolean): void {\n scan.chars += delta.length;\n if (!track) return;\n scan.text += delta;\n for (const ch of delta) {\n if (scan.inString) {\n if (scan.escaped) scan.escaped = false;\n else if (ch === \"\\\\\") scan.escaped = true;\n else if (ch === '\"') scan.inString = false;\n } else if (ch === \" \" || ch === \"\\n\" || ch === \"\\r\" || ch === \"\\t\") {\n scan.space++;\n continue;\n } else if (ch === '\"') {\n scan.inString = true;\n }\n scan.space = 0;\n }\n}\n\nfunction isJson(text: string): boolean {\n try {\n JSON.parse(text);\n return true;\n } catch {\n return false;\n }\n}\n\n/** One structured warning per runaway call, through the app's logger when\n * there is one, as the agent's own warnings are. */\nfunction warnRunaway(\n tool: string,\n toolCallId: string,\n chars: number,\n whitespace: number,\n limit: number,\n whole: boolean,\n): void {\n const message = `[gemi/ai] tool call \"${tool}\" ran away in white space (more than ${limit} characters, maxToolArgumentWhitespace); ${\n whole ? \"its arguments were whole JSON, so it was finished as written\" : \"its arguments were not whole JSON, so it was cut\"\n }`;\n const metadata = { tool, toolCallId, chars, whitespace, limit, whole };\n let logged = false;\n try {\n Log.warning(message, metadata);\n logged = true;\n } catch {\n // No application to resolve a logger from.\n }\n if (!logged || process.env.NODE_ENV === \"development\") console.warn(message, metadata);\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 /** `null` for Anthropic's Files API, which takes no purpose. */\n purpose: UploadPurpose | null = \"user_data\",\n): Promise<string> {\n const form = new FormData();\n if (purpose) 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\n/**\n * Deletes a file `uploadFile` sent (#1165): `DELETE {base}/files/{id}{query}`,\n * with the same resolved host, headers and api-version as the upload, so the\n * URL is built from `filesUrl` rather than worked out again.\n *\n * A 404 resolves: the file is already gone (deleted earlier, expired at the\n * vendor, or a retried delete whose first answer was lost), which is the state\n * the caller asked for.\n */\nexport async function deleteFile(endpoint: ResponsesEndpoint, fileId: string): Promise<void> {\n const at = endpoint.filesUrl.indexOf(\"?\");\n const path = at === -1 ? endpoint.filesUrl : endpoint.filesUrl.slice(0, at);\n const query = at === -1 ? \"\" : endpoint.filesUrl.slice(at);\n try {\n const response = await requestWithRetry(\n `${path}/${encodeURIComponent(fileId)}${query}`,\n { method: \"DELETE\", headers: await endpoint.headers() },\n {\n maxRetries: endpoint.maxRetries,\n timeoutMs: endpoint.timeoutMs,\n fetchImpl: endpoint.fetchImpl,\n ...(endpoint.sleep ? { sleep: endpoint.sleep } : {}),\n ...(endpoint.random ? { random: endpoint.random } : {}),\n },\n );\n await response.body?.cancel();\n } catch (error) {\n if (error instanceof ProviderHttpError && error.status === 404) return;\n throw error;\n }\n}\n",
|
|
13
|
+
"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, ToolSearchRecord } 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 tool_choice?:\n | string\n | { type: \"function\"; name: string }\n | { type: \"allowed_tools\"; mode: \"auto\" | \"required\"; tools: { type: \"function\"; name: string }[] };\n text?: { format: Record<string, unknown> };\n reasoning?: { effort: string; summary?: \"auto\" };\n temperature?: number;\n max_output_tokens?: number;\n prompt_cache_key?: string;\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, params.tools),\n stream: true,\n };\n\n // After the conversation, so the prefix the cache holds ends before it\n // (#1345). A developer message: it is the app speaking, not the user.\n if (params.trailingContext) {\n body.input.push({\n role: \"developer\",\n content: [{ type: \"input_text\", text: params.trailingContext }],\n });\n }\n\n if (params.systemPrompt) body.instructions = params.systemPrompt;\n\n // A step held to some of the tools (#1345): the full list goes out and\n // `allowed_tools` names what this call may use, so the tool list (the\n // start of the cached prefix) stays the same. It names functions only: a\n // list with namespaces or tool search is narrowed instead, as before.\n let tools = toResponsesTools(params.tools, capabilities);\n let allowed: string[] | undefined;\n if (params.allowedTools) {\n if (tools.every((tool) => tool.type === \"function\")) {\n allowed = params.allowedTools;\n } else {\n tools = toResponsesTools(narrowTools(params.tools ?? [], params.allowedTools), capabilities);\n }\n }\n if (tools.length > 0) {\n body.tools = tools;\n if (!capabilities.parallelToolCalls) body.parallel_tool_calls = false;\n const choice = params.toolChoice;\n if (allowed && choice !== \"none\" && typeof choice !== \"object\") {\n body.tool_choice = {\n type: \"allowed_tools\",\n mode: choice === \"required\" ? \"required\" : \"auto\",\n tools: allowed.map((name) => ({ type: \"function\", name })),\n };\n } else if (choice !== undefined) {\n body.tool_choice = typeof choice === \"string\" ? choice : { type: \"function\", name: choice.name };\n }\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 if (params.promptCacheKey) body.prompt_cache_key = params.promptCacheKey;\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 tools?: (ProviderToolSpec | ProviderToolNamespace)[],\n): ResponsesInputItem[] {\n const items: ResponsesInputItem[] = [];\n // What this request's tools can resolve a namespaced call or a search\n // against. Empty without tool search: the tools are then sent flat (see\n // `toResponsesTools`), there is no namespace for a call to name, and a\n // search item would be one for a tool the request does not have.\n const namespaces = new Map<string, ProviderToolNamespace>();\n if (capabilities.toolSearch) {\n for (const entry of tools ?? []) if (isNamespace(entry)) namespaces.set(entry.name, entry);\n }\n\n for (const message of messages) {\n const role = message.role;\n const replayReasoning = !UNFINISHED_RESPONSE.has(message.finishReason);\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 assertFilePart(part, attachmentId);\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 if (!replayReasoning) break;\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 // `Array.isArray` rather than truthiness: in stateless mode this\n // field came back from the browser, and a turn must not throw on it.\n if (capabilities.toolSearch && Array.isArray(part.toolSearches)) {\n for (const search of part.toolSearches) {\n items.push(...toolSearchItems(search, tools ?? []));\n }\n }\n const call: ResponsesInputItem = {\n type: \"function_call\",\n call_id: part.toolCallId,\n name: String(part.name),\n arguments: JSON.stringify(part.input ?? {}),\n };\n // Back the way the model made it (#776). Without the namespace this\n // is a call to a top-level function the tools do not list, and the\n // model, reading its own history, stopped making sense after one.\n // Dropped only when this request has no such namespace — a provider\n // without tool search, or an agent whose tools changed since — where\n // naming it would be a call into nothing.\n if (part.namespace && namespaces.has(part.namespace)) call.namespace = part.namespace;\n items.push(call);\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 */\nexport function 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 */\nexport function 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 return { type: isImageFile(part) ? \"input_image\" : \"input_file\", file_id: part.fileId };\n}\n\n/** Whether a file part goes to the image block. See `fileContent`. */\nexport function isImageFile(part: FilePart): boolean {\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 return mimeType\n ? mimeType.startsWith(\"image/\") && mimeType !== \"image/svg+xml\"\n : hasImageExtension(part.name);\n}\n\n/**\n * The two file parts no request can carry: a gemi attachment id in `fileId`,\n * and a part with neither id. See the `file` case in `toResponsesInput`.\n */\nexport function assertFilePart(part: FilePart, attachmentId: string | undefined): void {\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 now:\n // the model is told the file exists and is not shown it. What is still\n // refused is a part with NEITHER id — nothing to show and nothing to name.\n // The emptiness check is `!part.fileId` rather than a prefix test because\n // `undefined?.startsWith` is `undefined`, and `file_id: undefined` reaches\n // 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}\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 * The finish reasons of a message whose model response may never have\n * completed, and whose reasoning is therefore not replayed.\n *\n * A reasoning item goes back by id, and the API resolves that id against the\n * response it stored. A response the stream broke off (a dropped socket,\n * `streamMaxDurationMs`, a stop, a process that died mid-step) was never\n * completed, so it was never stored: replaying its `rs_…` id is answered\n * `400 Item with id 'rs_…' not found.`, and since the id is in the thread, so\n * is every later turn. Measured in an app on Azure (gpt-6.1-sol): a main step\n * cut by `streamMaxDurationMs` after its reasoning had started, then every\n * following turn of that thread failed with exactly that 400.\n *\n * The text and tool calls of such a message still go back: they are sent by\n * value, not by id. Only the reasoning, which is the one part the API looks\n * up, is left out. When the step did complete and only the run failed later\n * (a tool, a limit), this drops reasoning that was in fact retrievable, which\n * costs one turn's prompt-cache hit on that item and nothing else. The other\n * direction is a thread that can no longer be answered.\n */\nconst UNFINISHED_RESPONSE = new Set<string | undefined>([\"error\", \"aborted\", \"interrupted\"]);\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 // The tool's `toModel` projection when it has one (#1061): the client got\n // the whole output, the model reads what the tool chose to show it.\n const output = part.modelOutput !== undefined ? part.modelOutput : part.output;\n return typeof output === \"string\" ? output : JSON.stringify(output ?? null);\n }\n\n if (part.status === \"running\") {\n // The same text on every request until the job settles, so the prompt\n // cache holds: no age, no progress. The `<jobs>` block says how it is\n // going. \"Do not start it again\" is the line that matters; without a\n // result to read, a model repeats the call.\n const summary =\n part.job?.summary === undefined ? \"\" : ` Started with: ${JSON.stringify(part.job.summary)}.`;\n return `Started background job ${part.job?.id ?? \"(unknown)\"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${summary}`;\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 if (part.cause === \"denied-earlier\") {\n return `The user already declined this tool call earlier in this conversation, so it did not run and they were not asked again. Do not ask for it again; carry on without 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/**\n * A tool search the model ran, back onto the wire as the pair the API sent:\n * a `tool_search_call` with the query, then a `tool_search_output` with what\n * it loaded (#776).\n *\n * Why at all: the API's own guide for tool search without\n * `previous_response_id` is to pass every earlier item back, the search pair\n * included, and a deferred tool is loaded for the model by the output item\n * in its history. Without the pair the model reads calls to tools nothing in\n * its context ever loaded.\n *\n * The shape is the hosted one: `execution: \"server\"`, `call_id: null`, no\n * item ids. The ids are left out so the history does not depend on the\n * vendor's stored items, which a `FallbackProvider` leg on another resource\n * does not have. Measured on Azure (gpt-5.4): this pair, the pair with the\n * original ids, and the pair without `call_id` were all accepted.\n *\n * The output is rebuilt from this request's tools rather than stored, using\n * the same `functionTool` the `tools` array uses, so it matches what the API\n * returned for the same tools (`__fixtures__/openai-tool-search.sse`).\n * Namespaces and functions the agent no longer has are left out, and a search\n * that would load nothing is not replayed at all.\n */\nfunction toolSearchItems(\n search: ToolSearchRecord,\n tools: (ProviderToolSpec | ProviderToolNamespace)[],\n): ResponsesInputItem[] {\n const loaded = new Set(stringsOf(search?.loaded));\n const namespaces = stringsOf(search?.namespaces);\n const wanted = new Set(namespaces);\n const found: ResponsesTool[] = [];\n\n for (const entry of tools) {\n if (isNamespace(entry)) {\n if (!wanted.has(entry.name)) continue;\n // A search that named the group but listed no functions loaded all of\n // it; otherwise only the functions it listed.\n const inner = entry.tools.filter((tool) => loaded.size === 0 || loaded.has(tool.name));\n if (inner.length === 0) continue;\n found.push({\n type: \"namespace\",\n name: entry.name,\n description: entry.description,\n tools: inner.map((tool) => functionTool(tool, true)),\n });\n } else if (entry.deferred && loaded.has(entry.name)) {\n found.push(functionTool(entry, true));\n }\n }\n\n if (found.length === 0) return [];\n const query =\n search.arguments && typeof search.arguments === \"object\"\n ? search.arguments\n : { paths: namespaces.length > 0 ? namespaces : [...loaded] };\n return [\n {\n type: \"tool_search_call\",\n call_id: null,\n execution: \"server\",\n status: \"completed\",\n arguments: query,\n },\n {\n type: \"tool_search_output\",\n call_id: null,\n execution: \"server\",\n status: \"completed\",\n tools: found,\n },\n ];\n}\n\nfunction stringsOf(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === \"string\") : [];\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\n/** `tools` cut to the names in `allowed`: a namespace keeps the members named. */\nfunction narrowTools(\n tools: (ProviderToolSpec | ProviderToolNamespace)[],\n allowed: readonly string[],\n): (ProviderToolSpec | ProviderToolNamespace)[] {\n const wanted = new Set(allowed);\n return tools.flatMap((tool): (ProviderToolSpec | ProviderToolNamespace)[] => {\n if (!isNamespace(tool)) return wanted.has(tool.name) ? [tool] : [];\n const members = tool.tools.filter((member) => wanted.has(member.name));\n return members.length > 0 ? [{ ...tool, tools: members }] : [];\n });\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",
|
|
14
14
|
"import type {\n ProviderCapabilities,\n ProviderStreamParams,\n ProviderToolNamespace,\n ProviderToolSpec,\n} from \"../AgentProvider\";\nimport type { JSONSchema } from \"../Schema\";\nimport type { AgentMessage, FilePart, ReasoningPart } from \"../types\";\nimport { unreadableNote } from \"./fileRejection\";\nimport {\n assertFilePart,\n attachmentIdOf,\n attachmentLine,\n isImageFile,\n toolResultOutput,\n} from \"./request\";\n\n/**\n * `ProviderStreamParams` to a Messages API body (`POST /v1/messages`), as a\n * pure function, for the reason `request.ts` gives: everything that can be\n * wrong here is wrong without a socket.\n *\n * The shapes follow Anthropic's API reference. What differs from the\n * Responses builder, and why:\n *\n * - Roles alternate and a tool result is a `user` block. gemi keeps a step's\n * calls and their results on one assistant message; here the calls stay in\n * the assistant turn and the results open the user turn right after it.\n * - `max_tokens` is required, so a call without `maxOutputTokens` sends\n * `DEFAULT_MAX_TOKENS`.\n * - `temperature` is never sent. On API version `2026-10-21` (see\n * `ANTHROPIC_VERSION`) it is a 400 on every model, whatever its value.\n * - `promptCacheKey` has no Anthropic counterpart: the cache keys on the\n * prefix itself, so it is not sent. Caching is asked for with `cache_control`\n * breakpoints instead; see `withCacheBreakpoints`.\n */\n\nexport type MessagesBlock = Record<string, unknown>;\nexport type MessagesMessage = { role: \"user\" | \"assistant\"; content: MessagesBlock[] };\nexport type MessagesTool = Record<string, unknown>;\n\nexport type MessagesRequest = {\n model: string;\n max_tokens: number;\n messages: MessagesMessage[];\n stream: true;\n system?: MessagesBlock[];\n tools?: MessagesTool[];\n tool_choice?: { type: \"auto\" | \"any\" | \"none\" | \"tool\"; name?: string; disable_parallel_tool_use?: boolean };\n thinking?:\n | {\n type: \"adaptive\";\n display?: \"summarized\";\n block_binding?: { prefix_mismatch_behavior: \"drop_block\" };\n }\n | { type: \"between_tools\" };\n output_config?: {\n effort?: string;\n format?: { type: \"json_schema\"; schema: JSONSchema };\n };\n};\n\n/**\n * Sent when the agent sets no `maxOutputTokens`. Every current Claude model\n * takes 64K or more (128K on the 4.6-and-later families, 64K on Haiku 4.5), and\n * the request is streamed, so a high cap costs nothing until it is used; a low\n * one cuts an answer off mid-thought.\n */\nexport const DEFAULT_MAX_TOKENS = 64_000;\n\nexport function buildMessagesRequest(\n params: ProviderStreamParams,\n ctx: {\n /** What the request names: the model id, or a Foundry deployment. */\n model: string;\n /** The model id, which the per-model rules below read. */\n modelId: string;\n capabilities: ProviderCapabilities;\n forcedToolChoice: boolean;\n /** Whether `thinking.block_binding` can be sent (it needs a beta header\n * that Anthropic's API takes and Foundry is not known to). */\n blockBinding: boolean;\n },\n): MessagesRequest {\n const body: MessagesRequest = {\n model: ctx.model,\n max_tokens: params.maxOutputTokens ?? DEFAULT_MAX_TOKENS,\n messages: toMessages(params.messages, ctx.capabilities),\n stream: true,\n };\n\n // A strict schema goes as `output_config.format`, unless it is over the\n // compiler's limits, in which case it is asked for like a loose one.\n const output = params.output;\n const strict = !!output?.strict && !overSchemaLimits(output.schema);\n\n const loose = output && !strict ? looseOutputInstruction(output.schema) : undefined;\n const system = [params.systemPrompt, loose].filter(Boolean);\n if (system.length > 0) body.system = [{ type: \"text\", text: system.join(\"\\n\\n\") }];\n\n const reasoning = ctx.capabilities.reasoning ? params.reasoning : undefined;\n if (reasoning === \"none\") {\n // Off where the model has a switch for it: Claude Sonnet 5.5 takes\n // `between_tools` at effort `high` or below. Claude Opus 5.5 and the\n // other 5.x models cannot turn thinking off (`disabled` is a 400), so\n // there `none` is the lowest effort and the model still thinks.\n if (/^claude-sonnet-5-5(?:-\\d{8})?$/.test(ctx.modelId)) body.thinking = { type: \"between_tools\" };\n body.output_config = { effort: \"low\" };\n } else if (reasoning) {\n body.thinking = { type: \"adaptive\", display: \"summarized\" };\n body.output_config = { effort: effortOf(reasoning, ctx.modelId) };\n } else if (ctx.capabilities.reasoning && repliesWithThinking(body.messages)) {\n // No effort was asked for, but the model thought anyway (adaptive\n // thinking is the default on the 5.x models) and its blocks are being sent\n // back. `thinking` is made explicit, which is what it already was, so\n // the binding below can be set on it.\n body.thinking = { type: \"adaptive\" };\n }\n\n // PRESERVED THINKING. A thinking block is bound to the conversation that\n // produced it, and `Agent` edits conversations: `contextWindow` and\n // compaction cut the start of the history, `activeTools` narrows the tools\n // and `prepareStep` the instructions from one step to the next. On the\n // models that check (Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable and Mythos 5.1\n // and 5.2), a block sent back after such an edit is a 400 for accounts\n // created from 2026-08-31 (on every account for Mythos 5.1 and the 5.2\n // models). `drop_block` has the API drop those blocks instead: the step\n // loses that reasoning and runs. Where the binding cannot be sent, the\n // provider strips the blocks and asks once more on that 400\n // (`thinkingMismatch`).\n if (body.thinking?.type === \"adaptive\" && ctx.blockBinding) {\n body.thinking.block_binding = { prefix_mismatch_behavior: \"drop_block\" };\n }\n\n if (output && strict) {\n body.output_config = {\n ...body.output_config,\n format: { type: \"json_schema\", schema: toClaudeSchema(output.schema) },\n };\n }\n\n const tools = toMessagesTools(params.tools);\n if (tools.length > 0) {\n body.tools = tools;\n // Forced choice works with adaptive thinking; only manual budgeted\n // thinking, which is never sent, refuses it.\n const choice = toolChoice(params.toolChoice, ctx.forcedToolChoice);\n if (!ctx.capabilities.parallelToolCalls) choice.disable_parallel_tool_use = true;\n if (params.toolChoice !== undefined || choice.disable_parallel_tool_use) body.tool_choice = choice;\n }\n\n return withTrailingContext(withCacheBreakpoints(body), params.trailingContext);\n}\n\n/**\n * `trailingContext` after the conversation (#1345), added once the cache\n * breakpoints are placed: the last one stays on the block before it, so the\n * prefix the cache holds is the same whatever the text says. A text block at\n * the end of the last user message (after its tool results, which the API\n * wants first), or a user message of its own after an assistant one.\n */\nfunction withTrailingContext(body: MessagesRequest, text: string | undefined): MessagesRequest {\n if (!text) return body;\n const block: MessagesBlock = { type: \"text\", text };\n const last = body.messages.at(-1);\n if (last?.role === \"user\") last.content = [...last.content, block];\n else body.messages.push({ role: \"user\", content: [block] });\n return body;\n}\n\nfunction repliesWithThinking(messages: MessagesMessage[]): boolean {\n return messages.some((message) =>\n message.content.some((block) => block.type === \"thinking\" || block.type === \"redacted_thinking\"),\n );\n}\n\n/** The beta header `thinking.block_binding` needs. */\nexport const THINKING_BINDING_BETA = \"thinking-binding-controls-2026-08-01\";\n\n/**\n * The request edits that answer a 400 once, with what to change.\n *\n * - `thinking`: a thinking block was bound to a different conversation (see\n * PRESERVED THINKING above) and the binding was not sent. The blocks are\n * stripped and the request asked again, which keeps the text and tool calls\n * and loses only the reasoning, as `drop_block` would.\n * - `schema`: `Schema is too complex for compilation.` The answer is asked for\n * in the system prompt instead, as for a loose schema.\n */\nexport function recoverableRequestError(message: string): \"thinking\" | \"schema\" | undefined {\n if (/bound to a different conversation|Invalid `signature` in `thinking` block/i.test(message)) {\n return \"thinking\";\n }\n if (/schema is too complex/i.test(message)) return \"schema\";\n return undefined;\n}\n\n/** The request without any thinking block, for the `thinking` retry. */\nexport function withoutThinkingBlocks(body: MessagesRequest): MessagesRequest {\n const messages: MessagesMessage[] = [];\n for (const message of body.messages) {\n const content = message.content.filter(\n (block) => block.type !== \"thinking\" && block.type !== \"redacted_thinking\",\n );\n if (content.length === 0) continue;\n const last = messages.at(-1);\n if (last?.role === message.role) last.content.push(...content);\n else messages.push({ role: message.role, content });\n }\n return { ...body, messages };\n}\n\n/**\n * gemi's effort onto `output_config.effort` (`low` … `max`). `minimal` and\n * `none` have no counterpart and are `low`. `xhigh` is `high` on the 4.6\n * models, which predate it. Anything else is sent as written, so a new level\n * works without a gemi release.\n */\nfunction effortOf(reasoning: string, modelId: string): string {\n if (reasoning === \"none\" || reasoning === \"minimal\") return \"low\";\n if (reasoning === \"xhigh\" && /^claude-(?:opus|sonnet)-4-6(?:-|$)/.test(modelId)) return \"high\";\n return reasoning;\n}\n\n/**\n * Prompt caching. The cache holds a prefix in render order (`tools`, then\n * `system`, then `messages`) up to a block marked `cache_control`, so three\n * breakpoints cover what an agent repeats: the last tool (the tool list), the\n * system prompt, and the last block of the last message, which the next step\n * extends, so it reads this step's prefix back. That is three of the four\n * allowed. A prefix under the model's minimum is not cached and costs nothing\n * extra: 512 tokens on Opus 5.5 and 5, Sonnet 5.5, Haiku 5.5 and Fable 5.x,\n * 1024 on Sonnet 5, Opus 4.8 and Sonnet 4.6, up to 4096 on Opus 4.6 and Haiku\n * 4.5. A cache write costs 1.25x input.\n *\n * Thinking blocks cannot carry `cache_control`, so the last message's\n * breakpoint goes on its last block that can.\n */\nfunction withCacheBreakpoints(body: MessagesRequest): MessagesRequest {\n const mark = (block: MessagesBlock | MessagesTool | undefined) => {\n if (block) block.cache_control = { type: \"ephemeral\" };\n };\n mark(body.tools?.at(-1));\n mark(body.system?.at(-1));\n const last = body.messages.at(-1)?.content ?? [];\n mark([...last].reverse().find((b) => b.type !== \"thinking\" && b.type !== \"redacted_thinking\"));\n return body;\n}\n\n// --- structured output ---------------------------------------------------\n\n/**\n * Keywords structured outputs refuse, per Anthropic's JSON schema limits:\n * numeric and string length constraints, and array constraints beyond\n * `minItems` 0 or 1.\n */\nconst UNSUPPORTED_KEYWORDS = new Set([\n \"minimum\",\n \"maximum\",\n \"exclusiveMinimum\",\n \"exclusiveMaximum\",\n \"multipleOf\",\n \"minLength\",\n \"maxLength\",\n \"maxItems\",\n \"uniqueItems\",\n]);\n\n/** The string formats structured outputs take. */\nconst SUPPORTED_FORMATS = new Set([\n \"date-time\",\n \"time\",\n \"date\",\n \"duration\",\n \"email\",\n \"hostname\",\n \"uri\",\n \"ipv4\",\n \"ipv6\",\n \"uuid\",\n]);\n\n/** Regex features structured outputs refuse: backreferences, lookaround and\n * word boundaries. */\nconst UNSUPPORTED_PATTERN = /\\\\[1-9]|\\(\\?<?[=!]|\\\\[bB]/;\n\nconst SCHEMA_MAPS = new Set([\"properties\", \"patternProperties\", \"$defs\", \"definitions\"]);\n\n/**\n * The agent's schema as structured outputs takes it, transformed the way\n * Anthropic's SDKs transform one: a constraint the API refuses (the keywords\n * above, a `minItems` over 1, a string `format` outside the supported list, a\n * `pattern` with backreferences, lookaround or `\\b`) is removed and written\n * into the node's `description` instead (`{minimum: 100}`), so the model still\n * reads it; and every object gets `additionalProperties: false`, which the API\n * requires. Nothing is lost: `Agent` validates the answer against the agent's\n * own schema, constraints included.\n */\nexport function toClaudeSchema(schema: JSONSchema): JSONSchema {\n const transform = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(transform);\n if (!isObject(node)) return node;\n const out: Record<string, unknown> = {};\n const moved: string[] = [];\n for (const [key, value] of Object.entries(node)) {\n const refused =\n UNSUPPORTED_KEYWORDS.has(key) ||\n (key === \"minItems\" && typeof value === \"number\" && value > 1) ||\n (key === \"format\" && typeof value === \"string\" && !SUPPORTED_FORMATS.has(value)) ||\n (key === \"pattern\" && typeof value === \"string\" && UNSUPPORTED_PATTERN.test(value));\n if (refused) {\n moved.push(`${key}: ${JSON.stringify(value)}`);\n continue;\n }\n // These map names to schemas; a property named `minimum` is kept.\n out[key] =\n SCHEMA_MAPS.has(key) && isObject(value)\n ? Object.fromEntries(Object.entries(value).map(([name, sub]) => [name, transform(sub)]))\n : transform(value);\n }\n if (moved.length > 0) {\n const note = `{${moved.join(\", \")}}`;\n out.description = typeof out.description === \"string\" ? `${out.description} ${note}` : note;\n }\n if (out.type === \"object\" || isObject(out.properties)) out.additionalProperties = false;\n return out;\n };\n return transform(schema) as JSONSchema;\n}\n\n/**\n * Whether a schema is over the structured-output compiler's limits: 24\n * optional properties and 16 union-typed ones (`anyOf` or a type array)\n * across the request. Tools are not sent strict, so the output schema is the\n * only one counted. Over either, the API answers `Schema is too complex for\n * compilation.`; the answer is asked for like a loose schema's instead.\n */\nfunction overSchemaLimits(schema: JSONSchema): boolean {\n let optional = 0;\n let unions = 0;\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) return node.forEach(visit);\n if (!isObject(node)) return;\n if (Array.isArray(node.anyOf) || Array.isArray(node.type)) unions++;\n if (isObject(node.properties)) {\n const required = new Set(Array.isArray(node.required) ? node.required : []);\n optional += Object.keys(node.properties).filter((name) => !required.has(name)).length;\n }\n for (const [key, value] of Object.entries(node)) {\n if (SCHEMA_MAPS.has(key) && isObject(value)) Object.values(value).forEach(visit);\n else visit(value);\n }\n };\n visit(schema);\n return optional > 24 || unions > 16;\n}\n\n/**\n * A schema that is not `strict` holds a free-form node (`s.json()`), which\n * structured outputs cannot express (every object needs `additionalProperties:\n * false`). It is not sent as `output_config.format`, which would be a 400;\n * the model is asked for the JSON in the system prompt instead, and `Agent`\n * validates what comes back. Schemas over the compiler's limits go the same\n * way (`overSchemaLimits`).\n */\nfunction looseOutputInstruction(schema: JSONSchema): string {\n return `Answer with only a JSON value (no prose, no code fence) that matches this JSON schema:\\n${JSON.stringify(schema)}`;\n}\n\n/**\n * gemi's `toolChoice` onto `tool_choice`.\n *\n * `\"required\"` is `any` and `{ name }` is `tool`, on the models that take them.\n * Claude Opus 5.5, Claude Sonnet 5.5 and Claude Fable 5.1 answer both with a\n * 400 (`tool_choice: type \"tool\" and \"any\" are not supported for this model.`),\n * so on those, and on any id `supportsForcedToolChoice` does not know, the\n * choice is sent as `auto`: the step still runs, and the prompt that asked for\n * the tool still asks for it. Failing the step instead would fail every step a\n * `prepareStep` forces, with no setting to turn it off.\n */\nfunction toolChoice(\n choice: ProviderStreamParams[\"toolChoice\"],\n forced: boolean,\n): NonNullable<MessagesRequest[\"tool_choice\"]> {\n if (choice === \"none\") return { type: \"none\" };\n if (choice === \"required\") return forced ? { type: \"any\" } : { type: \"auto\" };\n if (choice && typeof choice === \"object\") {\n return forced ? { type: \"tool\", name: choice.name } : { type: \"auto\" };\n }\n return { type: \"auto\" };\n}\n\n// --- messages ------------------------------------------------------------\n\n/**\n * `AgentMessage[]` to alternating `user` / `assistant` messages.\n *\n * Parts are laid out in order, each with the role it has on this API: the\n * assistant's text and tool calls are `assistant`, a tool result is `user`, and\n * the user's own words and files are `user`. Consecutive blocks of one role\n * are one message, which is what the API wants and what a step that called\n * three tools needs: three `tool_use` blocks in one turn, three `tool_result`\n * blocks in the next.\n *\n * Tool results are not placed where they sit in gemi's message but right after\n * the turn that made their calls, first in the user turn, in call order: the\n * API requires every `tool_use` to be answered in the very next message, with\n * the results before anything else in it. A step's calls are answered where\n * the step is known to be over: at the next message, or, when gemi kept the\n * next step on the same message, at the first block after a tool result. The\n * pairing rules are those of\n * `reconcileToolPairs` in `request.ts`, and for the same reasons: a repeated\n * call or result is dropped, a result for a call this history does not hold is\n * dropped, and a call left without a result gets one saying so.\n */\nexport function toMessages(\n messages: AgentMessage[],\n capabilities: ProviderCapabilities,\n): MessagesMessage[] {\n // `step-end` marks where a step's calls are known to be done: a new\n // message, or a tool result (the next step's blocks can share the message).\n const blocks: ({ role: \"user\" | \"assistant\"; block: MessagesBlock } | \"step-end\")[] = [];\n const results = new Map<string, MessagesBlock>();\n\n for (const message of messages) {\n // A system-role message in the history is the app's, not the user's, but\n // `messages` takes only two roles; it is sent as user text.\n const role = message.role === \"assistant\" ? \"assistant\" : \"user\";\n blocks.push(\"step-end\");\n for (const part of message.content ?? []) {\n switch (part.type) {\n case \"text\": {\n // The assistant's text goes back exactly as the model wrote it,\n // whitespace-only blocks included (the \"\\n\\n\" before a tool call):\n // anything else is an edit to the turn. Only an empty string, which\n // the API refuses, is left out. A user's blank text is noise.\n const keep = role === \"assistant\" ? !!part.text : !!part.text?.trim();\n if (keep) blocks.push({ role, block: { type: \"text\", text: part.text } });\n break;\n }\n case \"output\": {\n if (part.partial) break;\n // The model's own text when the part kept it; re-serializing the\n // value would change its whitespace and number formatting.\n const text = part.text ?? JSON.stringify(part.value);\n blocks.push({ role, block: { type: \"text\", text } });\n break;\n }\n case \"file\": {\n if (role === \"assistant\") break;\n for (const block of fileBlocks(part, capabilities)) blocks.push({ role, block });\n break;\n }\n case \"reasoning\": {\n // Claude's own thinking goes back as it came, signature and all,\n // empty ones included. Another provider's reasoning (a Responses\n // item id) means nothing here and is left out.\n const block = role === \"assistant\" ? thinkingBlock(part) : undefined;\n if (block) blocks.push({ role, block });\n break;\n }\n case \"tool-call\": {\n if (part.partial) break;\n blocks.push({\n role: \"assistant\",\n block: {\n type: \"tool_use\",\n id: part.toolCallId,\n name: String(part.name),\n input: isObject(part.input) ? part.input : {},\n },\n });\n break;\n }\n case \"tool-result\": {\n blocks.push(\"step-end\");\n if (results.has(part.toolCallId)) break;\n results.set(part.toolCallId, {\n type: \"tool_result\",\n tool_use_id: part.toolCallId,\n content: toolResultOutput(part),\n ...(part.status === \"error\" ? { is_error: true } : {}),\n });\n break;\n }\n }\n }\n }\n\n const out: MessagesMessage[] = [];\n const push = (role: \"user\" | \"assistant\", block: MessagesBlock) => {\n const last = out[out.length - 1];\n if (last && last.role === role) last.content.push(block);\n else out.push({ role, content: [block] });\n };\n const called = new Set<string>();\n // The calls of the assistant turn being written, answered when it ends.\n let open: string[] = [];\n let stepEnded = false;\n const answer = () => {\n for (const id of open) push(\"user\", results.get(id) ?? noResult(id));\n open = [];\n stepEnded = false;\n };\n\n for (const entry of blocks) {\n if (entry === \"step-end\") {\n stepEnded = true;\n continue;\n }\n const { role, block } = entry;\n // Anything after a finished step's calls, in either role, comes after\n // their results.\n if (stepEnded || role === \"user\") answer();\n if (block.type === \"tool_use\") {\n const id = String(block.id);\n if (called.has(id)) continue;\n called.add(id);\n open.push(id);\n }\n push(role, block);\n }\n answer();\n\n // The API wants a user turn first, and on the 4.6-and-later models it\n // refuses a history that ends on the assistant (that is a prefill). Both\n // happen when an app starts a run from a trimmed or assistant-authored\n // history. The turns added are fixed text, so the prefix stays the same\n // from one step to the next.\n if (out[0]?.role === \"assistant\") {\n out.unshift({ role: \"user\", content: [{ type: \"text\", text: HISTORY_STARTS_HERE }] });\n }\n if (out.at(-1)?.role === \"assistant\") {\n out.push({ role: \"user\", content: [{ type: \"text\", text: CONTINUE }] });\n }\n return out;\n}\n\nconst HISTORY_STARTS_HERE = \"(The conversation continues from an earlier point.)\";\nconst CONTINUE = \"Continue.\";\n\nconst NO_RESULT_RECORDED = \"No result was recorded for this tool call. Assume it did not complete.\";\n\nfunction noResult(toolUseId: string): MessagesBlock {\n return { type: \"tool_result\", tool_use_id: toolUseId, content: NO_RESULT_RECORDED };\n}\n\n/** A reasoning part this provider wrote, back as its block; else nothing. */\nfunction thinkingBlock(part: ReasoningPart): MessagesBlock | undefined {\n const meta = part.providerMetadata?.anthropic;\n if (!isObject(meta)) return undefined;\n if (meta.type === \"thinking\" && typeof meta.signature === \"string\") {\n return { type: \"thinking\", thinking: part.text ?? \"\", signature: meta.signature };\n }\n if (meta.type === \"redacted_thinking\" && typeof meta.data === \"string\") {\n return { type: \"redacted_thinking\", data: meta.data };\n }\n return undefined;\n}\n\n/**\n * A file part as the model is told about it, with the rules of the `file` case\n * in `toResponsesInput`: the attachment line when the part has an attachment\n * id, and the file itself when the model can read it.\n *\n * Files go by Files API id (`source: {type: \"file\"}`): an image as an `image`\n * block, a PDF or plain text as a `document`. Those are the types the API\n * reads; any other file is not shown (it would be a 400), and the model is told\n * so. Without `fileInput` it is the attachment line alone.\n */\nfunction fileBlocks(part: FilePart, capabilities: ProviderCapabilities): MessagesBlock[] {\n const attachmentId = attachmentIdOf(part);\n const line = (shown: boolean): MessagesBlock[] =>\n attachmentId ? [{ type: \"text\", text: attachmentLine(part, shown) }] : [];\n if (!capabilities.fileInput) return line(false);\n assertFilePart(part, attachmentId);\n if (!part.fileId) return line(false);\n const kind = part.providerRejected ? undefined : fileKind(part);\n if (!kind) return [...line(false), { type: \"text\", text: unreadableNote(part.name) }];\n return [...line(true), { type: kind, source: { type: \"file\", file_id: part.fileId } }];\n}\n\nconst IMAGE_TYPES = new Set([\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\"]);\n\nfunction fileKind(part: FilePart): \"image\" | \"document\" | undefined {\n const mimeType = part.mimeType?.trim().toLowerCase() ?? \"\";\n if (isImageFile(part)) return !mimeType || IMAGE_TYPES.has(mimeType) ? \"image\" : undefined;\n if (mimeType) return mimeType === \"application/pdf\" || mimeType === \"text/plain\" ? \"document\" : undefined;\n return /\\.(pdf|txt)$/i.test(part.name ?? \"\") ? \"document\" : undefined;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\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 onto the `tools` array, flat: this provider reports no tool search\n * (`capabilitiesForClaude`), so a namespace is flattened and a deferred tool\n * is sent whole, exactly as `toResponsesTools` does for a model without it.\n *\n * `strict` is not sent. Anthropic's strict tool use allows at most 20 strict\n * tools and 24 optional parameters across them per request, and refuses\n * numeric and length constraints, so passing gemi's flag through would turn an\n * agent with many tools into a 400. `Agent` validates every call's arguments\n * against the tool's schema either way.\n *\n * `eager_input_streaming` is on for every tool: the request is always\n * streamed, and without it the API buffers each argument until it is whole, so\n * a tool that writes a file sends nothing for as long as the model writes it.\n * It also gives up the API's own validation of the arguments, which `Agent`\n * does anyway.\n */\nexport function toMessagesTools(\n tools: (ProviderToolSpec | ProviderToolNamespace)[] | undefined,\n): MessagesTool[] {\n const out: MessagesTool[] = [];\n for (const entry of tools ?? []) {\n for (const tool of isNamespace(entry) ? entry.tools : [entry]) {\n out.push({\n name: tool.name,\n description: tool.description,\n input_schema: tool.parameters,\n eager_input_streaming: true,\n });\n }\n }\n return out;\n}\n",
|
|
15
15
|
"import type { ProviderEvent } from \"../AgentProvider\";\nimport type { AgentError, FinishReason, Usage } from \"../types\";\nimport { streamErrorDetail } from \"./errors\";\nimport { emptyUsage, sseMessages } from \"./stream\";\n\n/**\n * The Messages API SSE stream to `ProviderEvent`, a pure function over chunks\n * like `parseResponsesStream`, driven in the tests by the hand-written\n * fixtures in `__fixtures__/anthropic-*.sse`.\n *\n * The event flow, from Anthropic's streaming reference: `message_start` (the\n * model and the input usage), then per content block `content_block_start`,\n * its `content_block_delta`s and `content_block_stop`, then `message_delta`\n * (the stop reason, and usage that is CUMULATIVE, not an increment) and\n * `message_stop`. `ping` frames come at any time, an `error` frame can replace\n * the rest, and unknown event types are to be ignored.\n *\n * Thinking is `reasoning-delta`s with no id. A `thinking` block's text streams\n * as it comes, and at its stop one more, empty delta carries the signature as\n * `providerMetadata.anthropic`, which closes the part. A `redacted_thinking`\n * block is one empty delta carrying its `data`. `anthropicRequest.ts` turns\n * those parts back into the blocks, unchanged, as the API requires.\n */\n\ntype ParseOptions = {\n /** The agent asked for an `output` schema, so text is the answer's JSON. */\n structuredOutput?: boolean;\n /**\n * Told the usage so far each time the stream reports it (`message_start`,\n * `message_delta`), so a caller that stops reading before `message_stop`\n * (a tool call that ran away in white space, #1334) still has it.\n */\n onUsage?: (usage: Usage) => void;\n};\n\ntype OpenBlock = { type: string; id?: string; name?: string; args: string; signature: string };\n\nexport async function* parseMessagesStream(\n chunks: AsyncIterable<string> | Iterable<string>,\n options: ParseOptions = {},\n): AsyncGenerator<ProviderEvent> {\n const blocks = new Map<number, OpenBlock>();\n // Calls whose arguments are not whole JSON, held until the stop reason says\n // whether they were cut off.\n const held: OpenBlock[] = [];\n let model: string | undefined;\n let usage: RawUsage = {};\n let stopReason: string | undefined;\n let stopDetails: Record<string, any> | undefined;\n let finished = false;\n\n const ended = (reason: FinishReason): ProviderEvent => ({\n type: \"finish\",\n reason,\n usage: toAnthropicUsage(usage),\n ...(model ? { model } : {}),\n });\n\n for await (const message of sseMessages(chunks)) {\n let payload: Record<string, any>;\n try {\n payload = JSON.parse(message.data);\n } catch {\n continue;\n }\n const type: string = typeof payload.type === \"string\" ? payload.type : message.event;\n\n switch (type) {\n case \"message_start\": {\n const start = payload.message ?? {};\n if (typeof start.model === \"string\" && start.model) model = start.model;\n usage = mergeUsage(usage, start.usage);\n options.onUsage?.(toAnthropicUsage(usage));\n yield { type: \"usage\", usage: toAnthropicUsage(usage) };\n break;\n }\n\n case \"content_block_start\": {\n const index = Number(payload.index);\n const block = payload.content_block ?? {};\n const open: OpenBlock = {\n type: String(block.type ?? \"\"),\n id: typeof block.id === \"string\" ? block.id : undefined,\n name: typeof block.name === \"string\" ? block.name : undefined,\n args: \"\",\n signature: typeof block.signature === \"string\" ? block.signature : \"\",\n };\n blocks.set(index, open);\n // Redacted thinking arrives whole: encrypted, nothing to show, and\n // sent back as it came.\n if (open.type === \"redacted_thinking\") {\n yield {\n type: \"reasoning-delta\",\n delta: \"\",\n providerMetadata: { anthropic: { type: \"redacted_thinking\", data: String(block.data ?? \"\") } },\n };\n }\n // A text block opens empty in every recorded shape, but the field is\n // there, so a gateway that sends it whole is read.\n if (open.type === \"text\" && typeof block.text === \"string\" && block.text) {\n yield textEvent(block.text, options);\n }\n break;\n }\n\n case \"content_block_delta\": {\n const block = blocks.get(Number(payload.index));\n const delta = payload.delta ?? {};\n if (!block) break;\n if (delta.type === \"text_delta\") {\n const text = String(delta.text ?? \"\");\n if (text) yield textEvent(text, options);\n } else if (delta.type === \"thinking_delta\") {\n const text = String(delta.thinking ?? \"\");\n if (text) yield { type: \"reasoning-delta\", delta: text };\n } else if (delta.type === \"signature_delta\") {\n block.signature += String(delta.signature ?? \"\");\n } else if (delta.type === \"input_json_delta\" && block.type === \"tool_use\") {\n const fragment = String(delta.partial_json ?? \"\");\n if (!fragment) break;\n block.args += fragment;\n yield {\n type: \"tool-call-delta\",\n toolCallId: block.id ?? \"\",\n name: block.name ?? \"\",\n argsDelta: fragment,\n };\n }\n break;\n }\n\n case \"content_block_stop\": {\n const index = Number(payload.index);\n const block = blocks.get(index);\n blocks.delete(index);\n // The signature closes the thinking part, and is what lets it be sent\n // back (see `ReasoningPart.providerMetadata`). A block with no text\n // (`display: \"omitted\"`) still becomes a part: it has to go back too.\n if (block?.type === \"thinking\") {\n yield {\n type: \"reasoning-delta\",\n delta: \"\",\n providerMetadata: { anthropic: { type: \"thinking\", signature: block.signature } },\n };\n }\n if (block?.type === \"tool_use\") {\n // A call with no arguments streams no delta at all; its input is\n // the empty object.\n block.args ||= \"{}\";\n // A block is stopped even when `max_tokens` cut it off, and then its\n // arguments are a prefix of the JSON. Such a call must not be\n // emitted whole, or it would run; it is held for `message_stop`.\n if (isJson(block.args)) yield toolCall(block);\n else held.push(block);\n }\n break;\n }\n\n case \"message_delta\": {\n if (typeof payload.delta?.stop_reason === \"string\") stopReason = payload.delta.stop_reason;\n if (payload.delta?.stop_details) stopDetails = payload.delta.stop_details;\n usage = mergeUsage(usage, payload.usage);\n options.onUsage?.(toAnthropicUsage(usage));\n yield { type: \"usage\", usage: toAnthropicUsage(usage) };\n break;\n }\n\n case \"message_stop\": {\n finished = true;\n // A refusal is the model's safety classifier declining, on HTTP 200.\n // Ending it `stop` would read as an answer, which is the mistake\n // `content_filtered` exists to prevent (as with OpenAI's refusal item).\n if (stopReason === \"refusal\") {\n yield { type: \"error\", error: refusalError(stopDetails) };\n yield ended(\"error\");\n break;\n }\n const reason = finishReasonOf(stopReason);\n // Cut off: the held calls never finished, so they are discarded (the\n // agent forgets them and the client removes their partial parts) and\n // the call ends `length`. Otherwise a held call is the model's own\n // malformed JSON, passed on for `Agent` to report against the tool.\n if (held.length > 0 && reason === \"length\") {\n yield { type: \"tool-call-discard\", toolCallIds: held.map((b) => b.id ?? \"\") };\n } else {\n for (const block of held) yield toolCall(block);\n }\n yield ended(reason);\n break;\n }\n\n case \"error\": {\n finished = true;\n const raw = payload.error ?? payload;\n yield { type: \"error\", error: anthropicStreamError(raw), ...streamErrorDetail(raw) };\n yield ended(\"error\");\n break;\n }\n }\n\n if (finished) return;\n }\n\n // No `message_stop`: the connection closed under the answer. Retryable, as\n // in `parseResponsesStream`.\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\");\n}\n\nfunction toolCall(block: OpenBlock): ProviderEvent {\n return { type: \"tool-call\", toolCallId: block.id ?? \"\", name: block.name ?? \"\", args: block.args };\n}\n\nfunction isJson(text: string): boolean {\n try {\n JSON.parse(text);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction textEvent(delta: string, options: ParseOptions): ProviderEvent {\n return options.structuredOutput ? { type: \"output-delta\", delta } : { type: \"text-delta\", delta };\n}\n\n/**\n * `stop_reason` onto gemi's finish reasons. `max_tokens` is a truncated answer,\n * and so is `model_context_window_exceeded` (the answer ran into the context\n * window rather than the cap). Everything else that ends a turn normally\n * (`end_turn`, `tool_use`, `stop_sequence`, and `pause_turn`, which only\n * server tools produce) is `stop`; `Agent` reads the tool calls themselves.\n */\nfunction finishReasonOf(stopReason: string | undefined): FinishReason {\n if (stopReason === \"max_tokens\" || stopReason === \"model_context_window_exceeded\") return \"length\";\n return \"stop\";\n}\n\nfunction refusalError(details: Record<string, any> | undefined): AgentError {\n const explanation = typeof details?.explanation === \"string\" ? details.explanation : \"\";\n const category = typeof details?.category === \"string\" ? ` (${details.category})` : \"\";\n return {\n code: \"content_filtered\",\n message: explanation || `The model declined to answer${category}.`,\n retryable: false,\n };\n}\n\n/**\n * An `error` frame, which arrives on a 200: the request was accepted and the\n * failure came later, so it is retryable unless its type says the request\n * itself is wrong. `overloaded_error` is the one seen most, the 529 of a\n * streamed call.\n */\nexport function anthropicStreamError(raw: any): AgentError {\n const type = String(raw?.type ?? \"\").toLowerCase();\n const message = typeof raw?.message === \"string\" ? raw.message : \"The provider stream failed.\";\n if (type === \"rate_limit_error\") return { code: \"rate_limited\", message, retryable: true };\n if (type === \"invalid_request_error\" || type === \"request_too_large\") {\n const tooLong = /prompt is too long|request_too_large/i.test(`${type} ${message}`);\n return {\n code: tooLong ? \"context_length_exceeded\" : \"provider_error\",\n message,\n retryable: false,\n };\n }\n if (\n type === \"authentication_error\" ||\n type === \"permission_error\" ||\n type === \"billing_error\" ||\n type === \"not_found_error\"\n ) {\n return { code: \"provider_error\", message, retryable: false };\n }\n return { code: \"provider_error\", message, retryable: true };\n}\n\ntype RawUsage = {\n input_tokens?: number;\n output_tokens?: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n /** From `output_tokens_details.thinking_tokens`, part of `output_tokens`. */\n thinking_tokens?: number;\n};\n\n/** The latest value of each field: `message_delta` usage is cumulative. */\nfunction mergeUsage(total: RawUsage, raw: any): RawUsage {\n if (!raw || typeof raw !== \"object\") return total;\n const next = { ...total };\n for (const key of [\n \"input_tokens\",\n \"output_tokens\",\n \"cache_creation_input_tokens\",\n \"cache_read_input_tokens\",\n ] as const) {\n if (typeof raw[key] === \"number\") next[key] = raw[key];\n }\n const thinking = raw.output_tokens_details?.thinking_tokens;\n if (typeof thinking === \"number\") next.thinking_tokens = thinking;\n return next;\n}\n\n/**\n * Anthropic usage onto `Usage`.\n *\n * Anthropic reports input in three disjoint parts: `input_tokens` (after the\n * last cache breakpoint), `cache_read_input_tokens` and\n * `cache_creation_input_tokens`. gemi's `inputTokens` is the whole prompt, as\n * OpenAI reports it, so it is their sum, and the two cache parts are its\n * breakdown (`cachedInputTokens`, `cacheWriteInputTokens`). Thinking tokens are part\n * of `output_tokens` and are its `reasoningTokens` breakdown. A field the\n * response did not carry stays absent rather than zero.\n */\nexport function toAnthropicUsage(raw: RawUsage | undefined): Usage {\n if (!raw) return emptyUsage();\n const read = raw.cache_read_input_tokens;\n const write = raw.cache_creation_input_tokens;\n const inputTokens = (raw.input_tokens ?? 0) + (read ?? 0) + (write ?? 0);\n const outputTokens = raw.output_tokens ?? 0;\n const usage: Usage = { inputTokens, outputTokens, totalTokens: inputTokens + outputTokens };\n if (typeof read === \"number\") usage.cachedInputTokens = read;\n if (typeof write === \"number\") usage.cacheWriteInputTokens = write;\n if (typeof raw.thinking_tokens === \"number\") usage.reasoningTokens = raw.thinking_tokens;\n return usage;\n}\n",
|
|
16
16
|
"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 supportsForcedToolChoice: true,\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 supportsForcedToolChoice: true,\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 supportsForcedToolChoice: true,\n };\n }\n\n return {\n reasoning: true,\n structuredOutput: true,\n fileInput: true,\n parallelToolCalls: true,\n toolSearch: true,\n supportsForcedToolChoice: 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 * What gemi's Responses request builder does on top of the model (#1345): it\n * sends `trailingContext` as a last developer message, after the cached\n * prefix, and holds a narrowed step to `allowedTools` with `tool_choice:\n * allowed_tools` while sending the full tool list. `allowed_tools` is taken\n * by the gpt-5 family, and by an id this file does not know (the same\n * capable default as everywhere here); older models keep a narrowed list.\n * Kept apart from `capabilitiesForModel`, which says what the model does.\n */\nexport function responsesRequestFeatures(model: string): Pick<ProviderCapabilities, \"trailingContext\" | \"allowedTools\"> {\n const family = parseFamily(normalizeModelId(model));\n return { trailingContext: true, allowedTools: !family || (family.kind === \"gpt\" && family.major >= 5) };\n}\n\n/**\n * What gemi's Messages request builder does on top of the model (#1345): it\n * sends `trailingContext` after the last message with the cache breakpoint\n * before it. The Messages API has no `allowed_tools`, so a narrowed step is\n * sent a narrowed list.\n */\nexport function claudeRequestFeatures(): Pick<ProviderCapabilities, \"trailingContext\" | \"allowedTools\"> {\n return { trailingContext: true };\n}\n\n/**\n * What a Claude model can do, read off its id, with the same bias as\n * `capabilitiesForModel`: an id this does not know gets every capability that\n * is safe to guess.\n *\n * - `reasoning`: adaptive thinking (`thinking: {type: \"adaptive\"}` with\n * `output_config.effort`), which the 4.6 models and everything after take.\n * The 4.5 generation and older only take a token budget and answer adaptive\n * thinking with a 400, so `reasoning` is dropped for them.\n * - `fileInput`: images (JPEG, PNG, GIF, WebP), PDFs and plain text, uploaded\n * through the Files API. Other types are not shown; see `fileBlocks`.\n * - `toolSearch`: false for now. Anthropic has a tool search tool, but\n * replaying its results in a history is not built yet, so deferred tools and\n * namespaces are sent flat and whole, which runs the agent the same.\n *\n * Forced tool choice is not a capability an agent can branch on; it decides\n * how the request is built. See `supportsForcedToolChoice`.\n */\nexport function capabilitiesForClaude(model: string): ProviderCapabilities {\n const id = normalizeModelId(model);\n // `claude-opus-4-1`, `claude-haiku-4-5`, `claude-sonnet-4-20250514` (minor\n // 0): the 4.x releases before 4.6.\n const four = /^claude-(?:opus|sonnet|haiku)-4(?:-(\\d{1,2}))?(?:-\\d{8})?$/.exec(id);\n const legacy = /^claude-(?:3|2|instant)/.test(id) || (!!four && Number(four[1] ?? 0) <= 5);\n return {\n reasoning: !legacy,\n structuredOutput: true,\n fileInput: true,\n parallelToolCalls: true,\n toolSearch: false,\n supportsForcedToolChoice: supportsForcedToolChoice(model),\n };\n}\n\n/**\n * Whether a Claude model takes `tool_choice` `any` and `tool`.\n *\n * Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.1 (and the Mythos and\n * 5.2 releases beside them) answer both with a 400, and every release since\n * Claude Opus 5 that did not keep them has dropped them. So this is a list of\n * the families known to take them, not of those known to refuse, and an id it\n * does not know is sent `auto`: a step that should have called a tool and\n * wrote text instead is a worse step, while a 400 is a failed one on every\n * forced step.\n */\nexport function supportsForcedToolChoice(model: string): boolean {\n const id = normalizeModelId(model);\n return (\n /^claude-(?:3|2|instant)/.test(id) ||\n /^claude-(?:opus|sonnet|haiku)-4(?:-|$)/.test(id) ||\n /^claude-(?:opus|sonnet|fable|mythos)-5(?:-\\d{8})?$/.test(id) ||\n /^claude-haiku-5-5(?:-\\d{8})?$/.test(id)\n );\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",
|