@a-dray/aglib 0.5.0 → 0.5.2

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.
@@ -1,5 +1,6 @@
1
1
  import { err, ok } from "../../../result.js";
2
2
  import { textOf } from "../../../content.js";
3
+ import { isWaitStatus, retrying } from "../../retry.js";
3
4
  /**
4
5
  * The Anthropic Messages wire.
5
6
  *
@@ -26,7 +27,7 @@ import { textOf } from "../../../content.js";
26
27
  * request rather than silently having its cache invalidated every turn.
27
28
  */
28
29
  export function createAnthropicModel(options) {
29
- const call = options.fetch ?? fetch;
30
+ const call = retrying(options.fetch ?? fetch);
30
31
  const baseUrl = options.baseUrl ?? "https://api.anthropic.com/v1";
31
32
  const provider = `anthropic-messages:${baseUrl.replace(/\/+$/, "")}:${options.model}`;
32
33
  return {
@@ -290,17 +291,23 @@ const decodeUsage = (usage) => usage ? {
290
291
  ...(usage.cache_read_input_tokens !== undefined ? { cacheReadTokens: usage.cache_read_input_tokens } : {}),
291
292
  ...(usage.cache_creation_input_tokens !== undefined ? { cacheWriteTokens: usage.cache_creation_input_tokens } : {}),
292
293
  } : {};
294
+ /**
295
+ * A refusal, or a wait the retries did not outlast. The second keeps a
296
+ * retryable code: the provider never said the request was wrong, and a caller
297
+ * with the time to try again later is told so.
298
+ */
293
299
  async function httpError(response) {
300
+ const wait = isWaitStatus(response.status);
294
301
  const body = await response.text().catch(() => "");
295
302
  const code = response.status === 401 || response.status === 403 ? "auth"
296
- : response.status === 429 ? "rate-limit"
297
- : response.status === 400 && /prompt is too long|context/i.test(body) ? "context-length"
298
- : response.status >= 500 ? "provider"
303
+ : response.status === 400 && /prompt is too long|context/i.test(body) ? "context-length"
304
+ : response.status === 429 ? "rate-limit"
305
+ : wait ? "provider"
299
306
  : "failed";
300
307
  return {
301
308
  code,
302
309
  message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : ""}`,
303
- retryable: code === "rate-limit" || code === "provider",
310
+ retryable: wait,
304
311
  };
305
312
  }
306
313
  function transportError(error, signal) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/anthropic/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAW7C;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAAyB;IAC5D,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC;IACpC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,8BAA8B,CAAC;IAClE,MAAM,QAAQ,GAAG,sBAAsB,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;IAEtF,OAAO;QACL,EAAE,EAAE,aAAa,OAAO,CAAC,KAAK,EAAE;QAEhC,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAqB;YACnC,yEAAyE;YACzE,iEAAiE;YACjE,IAAI,IAAI,GAAG,CAAC,CAAC;YACb,OAAO,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC,MAAM,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAE,CAAC,IAAI,KAAK,QAAQ;gBAAE,IAAI,IAAI,CAAC,CAAC;YAC9F,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC;YACzF,MAAM,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAElD,yEAAyE;YACzE,sEAAsE;YACtE,mEAAmE;YACnE,MAAM,QAAQ,GAAG,OAA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G,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC7C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;YACnC,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\n\nexport interface AnthropicOptions {\n apiKey: string;\n model: string;\n baseUrl?: string;\n version?: string;\n fetch?: typeof fetch;\n}\n\n/**\n * The Anthropic Messages wire.\n *\n * A genuinely different shape from OpenAI's — the leading system prompt hoisted\n * out of the message list, tool results carried as user content blocks, cache\n * breakpoints marked inline — which is the point of it being here: a port\n * proved against one wire format has not been proved.\n *\n * Three things this wire will refuse, and what we send instead:\n *\n * - **Thinking budgets.** `thinking: { type: \"enabled\", budget_tokens }` is\n * removed on the current models and returns 400. Depth is `output_config.effort`\n * over adaptive thinking, so `effort` maps there and nothing computes a budget.\n * - **Sampling controls.** `temperature`, `top_p` and `top_k` are removed on the\n * same models. `ModelRequest.temperature` is therefore dropped here rather\n * than forwarded into a request the provider rejects.\n * - **A system message in the middle of a turn.** Only the *leading* run of\n * system messages becomes the `system` field. One arriving after the\n * conversation has started is turn-scoped context, which the projection\n * deliberately places after the cache boundary, so it stays in `messages` as\n * a mid-conversation system message. Hoisting it would put the one thing that\n * changes every turn at the front of the prefix that must not change.\n * Supported on Opus 5, Opus 4.8 and Fable 5; a model without it fails the\n * request rather than silently having its cache invalidated every turn.\n */\nexport function createAnthropicModel(options: AnthropicOptions): Model {\n const call = options.fetch ?? fetch;\n const baseUrl = options.baseUrl ?? \"https://api.anthropic.com/v1\";\n const provider = `anthropic-messages:${baseUrl.replace(/\\/+$/, \"\")}:${options.model}`;\n\n return {\n id: `anthropic:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n // Only the leading run of system messages is the system prompt. Anything\n // after it belongs where the projection put it — see the header.\n let lead = 0;\n while (lead < request.messages.length && request.messages[lead]!.role === \"system\") lead += 1;\n const system = request.messages.slice(0, lead).map((message) => textOf(message.content));\n const conversation = request.messages.slice(lead);\n\n // The prefix ends where the caller says it does. In practice that is the\n // end of the system prompt, which is the one span fixed for the whole\n // run; a mark past it is honoured too rather than quietly ignored.\n const boundary = request.cacheAfter;\n const cacheSystem = boundary !== undefined && boundary >= lead && system.length > 0;\n const cacheAt = boundary !== undefined && boundary > lead ? boundary - lead - 1 : -1;\n\n const maxOutputTokens = request.maxOutputTokens ?? 32_000;\n\n let response: Response;\n try {\n response = await call(`${baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-api-key\": options.apiKey,\n \"anthropic-version\": options.version ?? \"2023-06-01\",\n },\n body: JSON.stringify({\n model: options.model,\n max_tokens: maxOutputTokens,\n ...(system.length ? { system: encodeSystem(system, cacheSystem) } : {}),\n messages: encodeConversation(conversation, cacheAt, provider),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.effort\n ? { thinking: { type: \"adaptive\" }, output_config: { effort: request.effort } }\n : {}),\n stream: true,\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n if (!response.ok) return err(await httpError(response));\n if (!response.body) return err({ code: \"provider\", message: \"No response body\", retryable: true });\n\n const text: string[] = [];\n const calls: ToolCall[] = [];\n let partial = \"\";\n let stop: string | undefined;\n let usage: Usage = {};\n let model: string | undefined;\n const providerBlocks = new Map<number, Record<string, JsonValue>>();\n const partialInputs = new Map<number, string>();\n\n // A stream that dies mid-body — cancelled, dropped, truncated — must come\n // back as a typed failure like any other. Without this the generator throws,\n // `run.result` rejects instead of resolving `cancelled`, no `run.finished`\n // is ever committed, and the activation stays open until its claim expires.\n try {\n for await (const event of sseData(response.body)) {\n let frame: AnthropicFrame;\n try { frame = JSON.parse(event) as AnthropicFrame; } catch { continue; }\n\n if (frame.type === \"message_start\" && frame.message) {\n model = frame.message.model;\n usage = { ...usage, ...decodeUsage(frame.message.usage) };\n }\n if (frame.type === \"content_block_start\" && frame.content_block) {\n const index = frame.index ?? providerBlocks.size;\n providerBlocks.set(index, clone(frame.content_block));\n if (frame.content_block.type === \"tool_use\") {\n calls.push({\n callId: String(frame.content_block.id ?? `call_${index}`),\n name: String(frame.content_block.name ?? \"\"),\n arguments: \"\",\n });\n partial = \"\";\n partialInputs.set(index, \"\");\n }\n }\n if (frame.type === \"content_block_delta\") {\n const delta = frame.delta!;\n const block = frame.index === undefined ? undefined : providerBlocks.get(frame.index);\n if (delta.type === \"text_delta\" && delta.text) { text.push(delta.text); yield { type: \"text.delta\", text: delta.text }; }\n if (delta.type === \"thinking_delta\" && delta.thinking) yield { type: \"reasoning.delta\", text: delta.thinking };\n if (block && delta.type === \"text_delta\" && delta.text !== undefined) {\n block[\"text\"] = `${typeof block[\"text\"] === \"string\" ? block[\"text\"] : \"\"}${delta.text}`;\n }\n if (block && delta.type === \"thinking_delta\" && delta.thinking !== undefined) {\n block[\"thinking\"] = `${typeof block[\"thinking\"] === \"string\" ? block[\"thinking\"] : \"\"}${delta.thinking}`;\n }\n if (block && delta.type === \"signature_delta\" && delta.signature !== undefined) {\n block[\"signature\"] = `${typeof block[\"signature\"] === \"string\" ? block[\"signature\"] : \"\"}${delta.signature}`;\n }\n if (delta.type === \"input_json_delta\" && delta.partial_json !== undefined) {\n partial += delta.partial_json;\n if (frame.index !== undefined) partialInputs.set(\n frame.index,\n `${partialInputs.get(frame.index) ?? \"\"}${delta.partial_json}`,\n );\n const current = calls.at(-1);\n if (current) yield { type: \"tool-call.delta\", callId: current.callId, arguments: delta.partial_json };\n }\n }\n if (frame.type === \"content_block_stop\" && calls.length) {\n const current = calls.at(-1)!;\n if (!current.arguments) current.arguments = partial || \"{}\";\n if (frame.index !== undefined && partialInputs.has(frame.index)) {\n const block = providerBlocks.get(frame.index);\n if (block) block[\"input\"] = safeJson(partialInputs.get(frame.index) || \"{}\");\n }\n }\n if (frame.type === \"message_delta\") {\n stop = frame.delta?.stop_reason ?? stop;\n usage = { ...usage, ...decodeUsage(frame.usage) };\n }\n if (frame.type === \"error\") {\n return err({ code: \"provider\", message: frame.error?.message ?? \"Provider error\", retryable: true });\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n const providerItems = [...providerBlocks.entries()]\n .sort(([left], [right]) => left - right)\n .map(([, block]) => block);\n return ok({\n message: { content: text.join(\"\"), ...(calls.length ? { calls } : {}) },\n finishReason: stop === \"max_tokens\" ? \"length\" : stop === \"refusal\" ? \"refusal\" : calls.length ? \"tool-calls\" : \"stop\",\n usage,\n ...(model ? { model } : {}),\n ...(providerItems.length ? { providerState: { provider, items: providerItems } } : {}),\n });\n },\n };\n}\n\n/**\n * Text blocks rather than one joined string, so the prefix can carry\n * breakpoints.\n *\n * Two are marked: the **first** block and the **last**. A breakpoint caches\n * everything before it, so the last one is what makes the whole prefix\n * reusable across a conversation's turns — and marking every block between\n * would buy nothing while spending a budget of four.\n *\n * The first earns its own for a different reason. The first block is an agent's\n * standing instructions, which are identical for every conversation it serves;\n * everything after it is composed per conversation and changes with it. With\n * one breakpoint at the end, a new conversation shares nothing: its prefix\n * differs from the last one somewhere in the middle, so the whole of it is\n * written again, instructions included. With one at the head, the instructions\n * are read from cache by every conversation and only what actually differs is\n * paid for — which is the common case for an agent serving many callers at\n * once, and free where there is only one.\n *\n * Skipped when there is a single block: the two marks would be the same one.\n */\nfunction encodeSystem(blocks: readonly string[], cache: boolean): unknown[] {\n const marked = new Set(blocks.length > 1 ? [0, blocks.length - 1] : [blocks.length - 1]);\n return blocks.map((text, index) => ({\n type: \"text\",\n text,\n ...(cache && marked.has(index) ? { cache_control: { type: \"ephemeral\" } } : {}),\n }));\n}\n\n/**\n * Tool results are user-role content blocks here, not a role of their own.\n *\n * `cacheAt` is an index into `messages`; the breakpoint lands on the last\n * content block that message produced. Tool results merge into a preceding user\n * block, so the mapping from message to block is not one to one and the mark is\n * placed as each message is encoded rather than computed afterwards.\n */\nfunction encodeConversation(messages: readonly Message[], cacheAt: number, provider: string): unknown[] {\n const out: { role: string; content: unknown[] }[] = [];\n let mark: unknown[] | undefined;\n\n messages.forEach((message, index) => {\n if (message.role === \"tool\") {\n const block = {\n type: \"tool_result\", tool_use_id: message.callId, content: typeof message.content === \"string\" ? message.content : encodeContent(message.content),\n ...(message.isError ? { is_error: true } : {}),\n };\n const last = out.at(-1);\n if (last?.role === \"user\") last.content.push(block);\n else out.push({ role: \"user\", content: [block] });\n } else if (message.role === \"assistant\") {\n const content: unknown[] = message.providerState?.provider === provider && message.providerState.items.length\n ? message.providerState.items.map(clone)\n : [];\n if (!content.length) {\n const spoken = textOf(message.content);\n if (spoken) content.push({ type: \"text\", text: spoken });\n for (const call of message.calls ?? []) {\n content.push({ type: \"tool_use\", id: call.callId, name: call.name, input: safeJson(call.arguments) });\n }\n }\n out.push({ role: \"assistant\", content });\n } else if (message.role === \"system\") {\n // Turn-scoped context, kept where the projection put it: an operator\n // instruction inside the conversation leaves the cached prefix intact,\n // where rewriting the front of it would invalidate every following turn.\n out.push({ role: \"system\", content: encodeContent(message.content) });\n } else {\n out.push({ role: \"user\", content: encodeContent(message.content) });\n }\n if (index === cacheAt) mark = out.at(-1)?.content;\n });\n\n const block = mark?.at(-1) as Record<string, unknown> | undefined;\n if (block) block[\"cache_control\"] = { type: \"ephemeral\" };\n return out;\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown[] {\n if (typeof content === \"string\") return [{ type: \"text\", text: content }];\n const parts: unknown[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") parts.push({ type: \"text\", text: part.text });\n if (part.type === \"image\") {\n parts.push(part.source.kind === \"url\"\n ? { type: \"image\", source: { type: \"url\", url: part.source.url } }\n : { type: \"image\", source: { type: \"base64\", media_type: part.mediaType, data: part.source.data } });\n }\n }\n return parts;\n}\n\nconst encodeTool = (tool: ToolSpec) => ({\n name: tool.name, description: tool.description, input_schema: tool.parameters,\n});\n\nconst safeJson = (raw: string): JsonValue => { try { return JSON.parse(raw) as JsonValue; } catch { return {}; } };\n\nconst clone = <T extends JsonValue>(value: T): T => JSON.parse(JSON.stringify(value)) as T;\n\nconst decodeUsage = (usage: AnthropicUsage | undefined): Usage => usage ? {\n ...(usage.input_tokens !== undefined ? { inputTokens: usage.input_tokens } : {}),\n ...(usage.output_tokens !== undefined ? { outputTokens: usage.output_tokens } : {}),\n ...(usage.cache_read_input_tokens !== undefined ? { cacheReadTokens: usage.cache_read_input_tokens } : {}),\n ...(usage.cache_creation_input_tokens !== undefined ? { cacheWriteTokens: usage.cache_creation_input_tokens } : {}),\n} : {};\n\nasync function httpError(response: Response): Promise<ModelError> {\n const body = await response.text().catch(() => \"\");\n const code: ModelError[\"code\"] =\n response.status === 401 || response.status === 403 ? \"auth\"\n : response.status === 429 ? \"rate-limit\"\n : response.status === 400 && /prompt is too long|context/i.test(body) ? \"context-length\"\n : response.status >= 500 ? \"provider\"\n : \"failed\";\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: code === \"rate-limit\" || code === \"provider\",\n };\n}\n\nfunction transportError(error: unknown, signal?: AbortSignal): ModelError {\n if (signal?.aborted) return { code: \"cancelled\", message: \"Generation cancelled\", retryable: false };\n return { code: \"provider\", message: error instanceof Error ? error.message : String(error), retryable: true };\n}\n\nasync function* sseData(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line.startsWith(\"data:\")) yield line.slice(5).trim();\n newline = buffer.indexOf(\"\\n\");\n }\n }\n}\n\ninterface AnthropicUsage {\n input_tokens?: number; output_tokens?: number;\n cache_read_input_tokens?: number; cache_creation_input_tokens?: number;\n}\ninterface AnthropicFrame {\n type: string;\n index?: number;\n message?: { model?: string; usage?: AnthropicUsage };\n content_block?: Record<string, JsonValue> & { type: string };\n delta?: {\n type?: string; text?: string; thinking?: string; signature?: string;\n partial_json?: string; stop_reason?: string;\n };\n usage?: AnthropicUsage;\n error?: { message?: string };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/anthropic/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAUxD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAAyB;IAC5D,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC,CAAC;IAC9C,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,8BAA8B,CAAC;IAClE,MAAM,QAAQ,GAAG,sBAAsB,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;IAEtF,OAAO;QACL,EAAE,EAAE,aAAa,OAAO,CAAC,KAAK,EAAE;QAEhC,KAAK,CAAC,CAAC,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,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAChH,CAAC;AAED,KAAK,SAAS,CAAC,CAAC,OAAO,CAAC,IAAgC;IACtD,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,IAA4C,EAAE,CAAC;QACvE,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnC,OAAO,OAAO,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC7C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;YACnC,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { isWaitStatus, retrying } from \"../../retry.js\";\n\nexport interface AnthropicOptions {\n apiKey: string;\n model: string;\n baseUrl?: string;\n version?: string;\n fetch?: typeof fetch;\n}\n\n/**\n * The Anthropic Messages wire.\n *\n * A genuinely different shape from OpenAI's — the leading system prompt hoisted\n * out of the message list, tool results carried as user content blocks, cache\n * breakpoints marked inline — which is the point of it being here: a port\n * proved against one wire format has not been proved.\n *\n * Three things this wire will refuse, and what we send instead:\n *\n * - **Thinking budgets.** `thinking: { type: \"enabled\", budget_tokens }` is\n * removed on the current models and returns 400. Depth is `output_config.effort`\n * over adaptive thinking, so `effort` maps there and nothing computes a budget.\n * - **Sampling controls.** `temperature`, `top_p` and `top_k` are removed on the\n * same models. `ModelRequest.temperature` is therefore dropped here rather\n * than forwarded into a request the provider rejects.\n * - **A system message in the middle of a turn.** Only the *leading* run of\n * system messages becomes the `system` field. One arriving after the\n * conversation has started is turn-scoped context, which the projection\n * deliberately places after the cache boundary, so it stays in `messages` as\n * a mid-conversation system message. Hoisting it would put the one thing that\n * changes every turn at the front of the prefix that must not change.\n * Supported on Opus 5, Opus 4.8 and Fable 5; a model without it fails the\n * request rather than silently having its cache invalidated every turn.\n */\nexport function createAnthropicModel(options: AnthropicOptions): Model {\n const call = retrying(options.fetch ?? fetch);\n const baseUrl = options.baseUrl ?? \"https://api.anthropic.com/v1\";\n const provider = `anthropic-messages:${baseUrl.replace(/\\/+$/, \"\")}:${options.model}`;\n\n return {\n id: `anthropic:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n // Only the leading run of system messages is the system prompt. Anything\n // after it belongs where the projection put it — see the header.\n let lead = 0;\n while (lead < request.messages.length && request.messages[lead]!.role === \"system\") lead += 1;\n const system = request.messages.slice(0, lead).map((message) => textOf(message.content));\n const conversation = request.messages.slice(lead);\n\n // The prefix ends where the caller says it does. In practice that is the\n // end of the system prompt, which is the one span fixed for the whole\n // run; a mark past it is honoured too rather than quietly ignored.\n const boundary = request.cacheAfter;\n const cacheSystem = boundary !== undefined && boundary >= lead && system.length > 0;\n const cacheAt = boundary !== undefined && boundary > lead ? boundary - lead - 1 : -1;\n\n const maxOutputTokens = request.maxOutputTokens ?? 32_000;\n\n let response: Response;\n try {\n response = await call(`${baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-api-key\": options.apiKey,\n \"anthropic-version\": options.version ?? \"2023-06-01\",\n },\n body: JSON.stringify({\n model: options.model,\n max_tokens: maxOutputTokens,\n ...(system.length ? { system: encodeSystem(system, cacheSystem) } : {}),\n messages: encodeConversation(conversation, cacheAt, provider),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.effort\n ? { thinking: { type: \"adaptive\" }, output_config: { effort: request.effort } }\n : {}),\n stream: true,\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n if (!response.ok) return err(await httpError(response));\n if (!response.body) return err({ code: \"provider\", message: \"No response body\", retryable: true });\n\n const text: string[] = [];\n const calls: ToolCall[] = [];\n let partial = \"\";\n let stop: string | undefined;\n let usage: Usage = {};\n let model: string | undefined;\n const providerBlocks = new Map<number, Record<string, JsonValue>>();\n const partialInputs = new Map<number, string>();\n\n // A stream that dies mid-body — cancelled, dropped, truncated — must come\n // back as a typed failure like any other. Without this the generator throws,\n // `run.result` rejects instead of resolving `cancelled`, no `run.finished`\n // is ever committed, and the activation stays open until its claim expires.\n try {\n for await (const event of sseData(response.body)) {\n let frame: AnthropicFrame;\n try { frame = JSON.parse(event) as AnthropicFrame; } catch { continue; }\n\n if (frame.type === \"message_start\" && frame.message) {\n model = frame.message.model;\n usage = { ...usage, ...decodeUsage(frame.message.usage) };\n }\n if (frame.type === \"content_block_start\" && frame.content_block) {\n const index = frame.index ?? providerBlocks.size;\n providerBlocks.set(index, clone(frame.content_block));\n if (frame.content_block.type === \"tool_use\") {\n calls.push({\n callId: String(frame.content_block.id ?? `call_${index}`),\n name: String(frame.content_block.name ?? \"\"),\n arguments: \"\",\n });\n partial = \"\";\n partialInputs.set(index, \"\");\n }\n }\n if (frame.type === \"content_block_delta\") {\n const delta = frame.delta!;\n const block = frame.index === undefined ? undefined : providerBlocks.get(frame.index);\n if (delta.type === \"text_delta\" && delta.text) { text.push(delta.text); yield { type: \"text.delta\", text: delta.text }; }\n if (delta.type === \"thinking_delta\" && delta.thinking) yield { type: \"reasoning.delta\", text: delta.thinking };\n if (block && delta.type === \"text_delta\" && delta.text !== undefined) {\n block[\"text\"] = `${typeof block[\"text\"] === \"string\" ? block[\"text\"] : \"\"}${delta.text}`;\n }\n if (block && delta.type === \"thinking_delta\" && delta.thinking !== undefined) {\n block[\"thinking\"] = `${typeof block[\"thinking\"] === \"string\" ? block[\"thinking\"] : \"\"}${delta.thinking}`;\n }\n if (block && delta.type === \"signature_delta\" && delta.signature !== undefined) {\n block[\"signature\"] = `${typeof block[\"signature\"] === \"string\" ? block[\"signature\"] : \"\"}${delta.signature}`;\n }\n if (delta.type === \"input_json_delta\" && delta.partial_json !== undefined) {\n partial += delta.partial_json;\n if (frame.index !== undefined) partialInputs.set(\n frame.index,\n `${partialInputs.get(frame.index) ?? \"\"}${delta.partial_json}`,\n );\n const current = calls.at(-1);\n if (current) yield { type: \"tool-call.delta\", callId: current.callId, arguments: delta.partial_json };\n }\n }\n if (frame.type === \"content_block_stop\" && calls.length) {\n const current = calls.at(-1)!;\n if (!current.arguments) current.arguments = partial || \"{}\";\n if (frame.index !== undefined && partialInputs.has(frame.index)) {\n const block = providerBlocks.get(frame.index);\n if (block) block[\"input\"] = safeJson(partialInputs.get(frame.index) || \"{}\");\n }\n }\n if (frame.type === \"message_delta\") {\n stop = frame.delta?.stop_reason ?? stop;\n usage = { ...usage, ...decodeUsage(frame.usage) };\n }\n if (frame.type === \"error\") {\n return err({ code: \"provider\", message: frame.error?.message ?? \"Provider error\", retryable: true });\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n const providerItems = [...providerBlocks.entries()]\n .sort(([left], [right]) => left - right)\n .map(([, block]) => block);\n return ok({\n message: { content: text.join(\"\"), ...(calls.length ? { calls } : {}) },\n finishReason: stop === \"max_tokens\" ? \"length\" : stop === \"refusal\" ? \"refusal\" : calls.length ? \"tool-calls\" : \"stop\",\n usage,\n ...(model ? { model } : {}),\n ...(providerItems.length ? { providerState: { provider, items: providerItems } } : {}),\n });\n },\n };\n}\n\n/**\n * Text blocks rather than one joined string, so the prefix can carry\n * breakpoints.\n *\n * Two are marked: the **first** block and the **last**. A breakpoint caches\n * everything before it, so the last one is what makes the whole prefix\n * reusable across a conversation's turns — and marking every block between\n * would buy nothing while spending a budget of four.\n *\n * The first earns its own for a different reason. The first block is an agent's\n * standing instructions, which are identical for every conversation it serves;\n * everything after it is composed per conversation and changes with it. With\n * one breakpoint at the end, a new conversation shares nothing: its prefix\n * differs from the last one somewhere in the middle, so the whole of it is\n * written again, instructions included. With one at the head, the instructions\n * are read from cache by every conversation and only what actually differs is\n * paid for — which is the common case for an agent serving many callers at\n * once, and free where there is only one.\n *\n * Skipped when there is a single block: the two marks would be the same one.\n */\nfunction encodeSystem(blocks: readonly string[], cache: boolean): unknown[] {\n const marked = new Set(blocks.length > 1 ? [0, blocks.length - 1] : [blocks.length - 1]);\n return blocks.map((text, index) => ({\n type: \"text\",\n text,\n ...(cache && marked.has(index) ? { cache_control: { type: \"ephemeral\" } } : {}),\n }));\n}\n\n/**\n * Tool results are user-role content blocks here, not a role of their own.\n *\n * `cacheAt` is an index into `messages`; the breakpoint lands on the last\n * content block that message produced. Tool results merge into a preceding user\n * block, so the mapping from message to block is not one to one and the mark is\n * placed as each message is encoded rather than computed afterwards.\n */\nfunction encodeConversation(messages: readonly Message[], cacheAt: number, provider: string): unknown[] {\n const out: { role: string; content: unknown[] }[] = [];\n let mark: unknown[] | undefined;\n\n messages.forEach((message, index) => {\n if (message.role === \"tool\") {\n const block = {\n type: \"tool_result\", tool_use_id: message.callId, content: typeof message.content === \"string\" ? message.content : encodeContent(message.content),\n ...(message.isError ? { is_error: true } : {}),\n };\n const last = out.at(-1);\n if (last?.role === \"user\") last.content.push(block);\n else out.push({ role: \"user\", content: [block] });\n } else if (message.role === \"assistant\") {\n const content: unknown[] = message.providerState?.provider === provider && message.providerState.items.length\n ? message.providerState.items.map(clone)\n : [];\n if (!content.length) {\n const spoken = textOf(message.content);\n if (spoken) content.push({ type: \"text\", text: spoken });\n for (const call of message.calls ?? []) {\n content.push({ type: \"tool_use\", id: call.callId, name: call.name, input: safeJson(call.arguments) });\n }\n }\n out.push({ role: \"assistant\", content });\n } else if (message.role === \"system\") {\n // Turn-scoped context, kept where the projection put it: an operator\n // instruction inside the conversation leaves the cached prefix intact,\n // where rewriting the front of it would invalidate every following turn.\n out.push({ role: \"system\", content: encodeContent(message.content) });\n } else {\n out.push({ role: \"user\", content: encodeContent(message.content) });\n }\n if (index === cacheAt) mark = out.at(-1)?.content;\n });\n\n const block = mark?.at(-1) as Record<string, unknown> | undefined;\n if (block) block[\"cache_control\"] = { type: \"ephemeral\" };\n return out;\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown[] {\n if (typeof content === \"string\") return [{ type: \"text\", text: content }];\n const parts: unknown[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") parts.push({ type: \"text\", text: part.text });\n if (part.type === \"image\") {\n parts.push(part.source.kind === \"url\"\n ? { type: \"image\", source: { type: \"url\", url: part.source.url } }\n : { type: \"image\", source: { type: \"base64\", media_type: part.mediaType, data: part.source.data } });\n }\n }\n return parts;\n}\n\nconst encodeTool = (tool: ToolSpec) => ({\n name: tool.name, description: tool.description, input_schema: tool.parameters,\n});\n\nconst safeJson = (raw: string): JsonValue => { try { return JSON.parse(raw) as JsonValue; } catch { return {}; } };\n\nconst clone = <T extends JsonValue>(value: T): T => JSON.parse(JSON.stringify(value)) as T;\n\nconst decodeUsage = (usage: AnthropicUsage | undefined): Usage => usage ? {\n ...(usage.input_tokens !== undefined ? { inputTokens: usage.input_tokens } : {}),\n ...(usage.output_tokens !== undefined ? { outputTokens: usage.output_tokens } : {}),\n ...(usage.cache_read_input_tokens !== undefined ? { cacheReadTokens: usage.cache_read_input_tokens } : {}),\n ...(usage.cache_creation_input_tokens !== undefined ? { cacheWriteTokens: usage.cache_creation_input_tokens } : {}),\n} : {};\n\n/**\n * A refusal, or a wait the retries did not outlast. The second keeps a\n * retryable code: the provider never said the request was wrong, and a caller\n * with the time to try again later is told so.\n */\nasync function httpError(response: Response): Promise<ModelError> {\n const wait = isWaitStatus(response.status);\n const body = await response.text().catch(() => \"\");\n const code: ModelError[\"code\"] =\n response.status === 401 || response.status === 403 ? \"auth\"\n : response.status === 400 && /prompt is too long|context/i.test(body) ? \"context-length\"\n : response.status === 429 ? \"rate-limit\"\n : wait ? \"provider\"\n : \"failed\";\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: wait,\n };\n}\n\nfunction transportError(error: unknown, signal?: AbortSignal): ModelError {\n if (signal?.aborted) return { code: \"cancelled\", message: \"Generation cancelled\", retryable: false };\n return { code: \"provider\", message: error instanceof Error ? error.message : String(error), retryable: true };\n}\n\nasync function* sseData(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line.startsWith(\"data:\")) yield line.slice(5).trim();\n newline = buffer.indexOf(\"\\n\");\n }\n }\n}\n\ninterface AnthropicUsage {\n input_tokens?: number; output_tokens?: number;\n cache_read_input_tokens?: number; cache_creation_input_tokens?: number;\n}\ninterface AnthropicFrame {\n type: string;\n index?: number;\n message?: { model?: string; usage?: AnthropicUsage };\n content_block?: Record<string, JsonValue> & { type: string };\n delta?: {\n type?: string; text?: string; thinking?: string; signature?: string;\n partial_json?: string; stop_reason?: string;\n };\n usage?: AnthropicUsage;\n error?: { message?: string };\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { Model } from "../../model.js";
2
+ import { type RetryOptions } from "../../retry.js";
2
3
  export interface OpenAiCompatibleOptions {
3
4
  apiKey: string;
4
5
  baseUrl: string;
@@ -11,6 +12,20 @@ export interface OpenAiCompatibleOptions {
11
12
  * request outright — so the dialect is declared rather than guessed.
12
13
  */
13
14
  effortParameter?: "reasoning_effort" | "reasoning" | "none";
15
+ /**
16
+ * How this endpoint spells a cache breakpoint, where it has one. Most models
17
+ * on this wire cache a repeated prefix by themselves and have no field for
18
+ * it — plain OpenAI rejects one it does not know — so the default sends none.
19
+ * OpenRouter takes Anthropic's `cache_control` on a text part and forwards
20
+ * it to the models that cache nothing without one.
21
+ */
22
+ cacheBreakpoint?: "cache_control" | "none";
23
+ /**
24
+ * A refusal this endpoint means as a wait, beyond the statuses every HTTP
25
+ * wire means so. Retried before the first delta like those, and reported as
26
+ * a rate limit when the retries run out.
27
+ */
28
+ isWait?: RetryOptions["isWait"];
14
29
  /** Injectable for tests; defaults to global fetch. */
15
30
  fetch?: typeof fetch;
16
31
  }
@@ -19,7 +34,23 @@ export interface OpenAiCompatibleOptions {
19
34
  * OpenRouter, Together, Groq, vLLM, Ollama. One adapter, one base URL.
20
35
  */
21
36
  export declare function createOpenAiCompatibleModel(options: OpenAiCompatibleOptions): Model;
22
- /** OpenRouter is this wire with a fixed base URL and attribution headers. */
37
+ /**
38
+ * OpenRouter is this wire with a fixed base URL, attribution headers, and two
39
+ * facts of its own.
40
+ *
41
+ * It caches Claude only when asked. Every other model it serves reads a
42
+ * repeated prefix from cache on its own; a Claude request without a
43
+ * `cache_control` mark is read in full every turn, at full price. The mark
44
+ * goes on the models that need it and on no other: whether the providers that
45
+ * cache by themselves ignore a mark is not something its documentation says,
46
+ * and a strict one could refuse the request.
47
+ *
48
+ * It answers 402 for two different things. One is an account with no credit,
49
+ * which is a refusal. The other is the account's credit being reserved by its
50
+ * own other requests still in flight, which clears when they finish — the
51
+ * commonest failure an agent serving several sessions at once will see, and a
52
+ * wait. The body's structured `error.metadata.reason` tells them apart.
53
+ */
23
54
  export declare function createOpenRouterModel(input: {
24
55
  apiKey: string;
25
56
  model: string;
@@ -1,12 +1,14 @@
1
1
  import { err, ok } from "../../../result.js";
2
2
  import { textOf } from "../../../content.js";
3
+ import { isWaitStatus, retrying } from "../../retry.js";
3
4
  /**
4
5
  * The OpenAI chat-completions wire, which almost every provider now speaks —
5
6
  * OpenRouter, Together, Groq, vLLM, Ollama. One adapter, one base URL.
6
7
  */
7
8
  export function createOpenAiCompatibleModel(options) {
8
- const call = options.fetch ?? fetch;
9
+ const call = retrying(options.fetch ?? fetch, { ...(options.isWait ? { isWait: options.isWait } : {}) });
9
10
  const provider = `openai-compatible:${options.baseUrl.replace(/\/+$/, "")}`;
11
+ const marking = options.cacheBreakpoint === "cache_control";
10
12
  return {
11
13
  id: `openai-compatible:${options.model}`,
12
14
  async *generate(request) {
@@ -21,7 +23,7 @@ export function createOpenAiCompatibleModel(options) {
21
23
  },
22
24
  body: JSON.stringify({
23
25
  model: options.model,
24
- messages: encodeConversation(request.messages, provider),
26
+ messages: encodeConversation(request.messages, provider, marking ? breakpoints(request) : new Set()),
25
27
  ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),
26
28
  ...(request.maxOutputTokens !== undefined ? { max_tokens: request.maxOutputTokens } : {}),
27
29
  ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),
@@ -36,7 +38,7 @@ export function createOpenAiCompatibleModel(options) {
36
38
  return err(transportError(error, request.signal));
37
39
  }
38
40
  if (!response.ok)
39
- return err(await httpError(response));
41
+ return err(await httpError(response, options.isWait));
40
42
  if (!response.body)
41
43
  return err({ code: "provider", message: "No response body", retryable: true });
42
44
  const text = [];
@@ -125,13 +127,31 @@ export function createOpenAiCompatibleModel(options) {
125
127
  },
126
128
  };
127
129
  }
128
- /** OpenRouter is this wire with a fixed base URL and attribution headers. */
130
+ /**
131
+ * OpenRouter is this wire with a fixed base URL, attribution headers, and two
132
+ * facts of its own.
133
+ *
134
+ * It caches Claude only when asked. Every other model it serves reads a
135
+ * repeated prefix from cache on its own; a Claude request without a
136
+ * `cache_control` mark is read in full every turn, at full price. The mark
137
+ * goes on the models that need it and on no other: whether the providers that
138
+ * cache by themselves ignore a mark is not something its documentation says,
139
+ * and a strict one could refuse the request.
140
+ *
141
+ * It answers 402 for two different things. One is an account with no credit,
142
+ * which is a refusal. The other is the account's credit being reserved by its
143
+ * own other requests still in flight, which clears when they finish — the
144
+ * commonest failure an agent serving several sessions at once will see, and a
145
+ * wait. The body's structured `error.metadata.reason` tells them apart.
146
+ */
129
147
  export function createOpenRouterModel(input) {
130
148
  return createOpenAiCompatibleModel({
131
149
  apiKey: input.apiKey,
132
150
  baseUrl: "https://openrouter.ai/api/v1",
133
151
  model: input.model,
134
152
  effortParameter: "reasoning",
153
+ cacheBreakpoint: /^~?anthropic\//.test(input.model) ? "cache_control" : "none",
154
+ isWait: inFlightBudgetExhausted,
135
155
  headers: {
136
156
  ...(input.appUrl ? { "http-referer": input.appUrl } : {}),
137
157
  ...(input.appName ? { "x-title": input.appName } : {}),
@@ -139,12 +159,43 @@ export function createOpenRouterModel(input) {
139
159
  ...(input.fetch ? { fetch: input.fetch } : {}),
140
160
  });
141
161
  }
162
+ async function inFlightBudgetExhausted(response) {
163
+ if (response.status !== 402)
164
+ return false;
165
+ const body = await response.clone().json().catch(() => undefined);
166
+ return body?.error?.metadata?.reason === "in_flight_budget_exhausted";
167
+ }
142
168
  function encodeEffort(effort, parameter) {
143
169
  if (!effort || parameter === "none")
144
170
  return {};
145
171
  return parameter === "reasoning" ? { reasoning: { effort } } : { reasoning_effort: effort };
146
172
  }
147
- function encodeConversation(messages, provider) {
173
+ /**
174
+ * Which messages carry a breakpoint: the same three places the Anthropic
175
+ * adapter marks, for the same reasons it gives.
176
+ *
177
+ * The prefix ends where the caller says. When that is at or past the leading
178
+ * run of system messages, the first and the last of them are marked — the last
179
+ * makes a conversation's own prefix reusable across its turns, the first makes
180
+ * the standing instructions every conversation shares reusable across
181
+ * conversations. A boundary past the system run marks the message it ends on
182
+ * as well. Three at most, inside a budget of four.
183
+ */
184
+ function breakpoints(request) {
185
+ const boundary = request.cacheAfter;
186
+ if (boundary === undefined)
187
+ return new Set();
188
+ let lead = 0;
189
+ while (lead < request.messages.length && request.messages[lead].role === "system")
190
+ lead += 1;
191
+ const marked = new Set();
192
+ if (lead > 0 && boundary >= lead)
193
+ marked.add(0).add(lead - 1);
194
+ if (boundary > lead && boundary <= request.messages.length)
195
+ marked.add(boundary - 1);
196
+ return marked;
197
+ }
198
+ function encodeConversation(messages, provider, marked) {
148
199
  const out = [];
149
200
  let images = [];
150
201
  const flush = () => {
@@ -152,21 +203,42 @@ function encodeConversation(messages, provider) {
152
203
  out.push({ role: "user", content: encodeContent(images) });
153
204
  images = [];
154
205
  };
155
- for (const message of messages) {
206
+ messages.forEach((message, index) => {
156
207
  // The wire accepts only text in tool replies. Keep every reply in a parallel
157
208
  // batch adjacent before supplying its images as associated user content.
158
209
  if (message.role !== "tool")
159
210
  flush();
160
- out.push(encodeMessage(message, provider));
211
+ const encoded = encodeMessage(message, provider);
212
+ if (marked.has(index))
213
+ mark(encoded);
214
+ out.push(encoded);
161
215
  if (message.role === "tool" && typeof message.content !== "string") {
162
216
  const media = message.content.filter((part) => part.type === "image");
163
217
  if (media.length)
164
218
  images.push({ type: "text", text: `Images from tool call ${message.callId}:` }, ...media);
165
219
  }
166
- }
220
+ });
167
221
  flush();
168
222
  return out;
169
223
  }
224
+ /**
225
+ * A breakpoint lands on a text part, so a bare string becomes one part to
226
+ * carry it. A message with no text — an assistant turn that only called tools,
227
+ * a user turn that is only an image — has nowhere to put one and gets none.
228
+ */
229
+ function mark(encoded) {
230
+ const content = encoded["content"];
231
+ if (typeof content === "string") {
232
+ if (content)
233
+ encoded["content"] = [{ type: "text", text: content, cache_control: { type: "ephemeral" } }];
234
+ return;
235
+ }
236
+ if (!Array.isArray(content))
237
+ return;
238
+ const last = content.findLast((part) => part["type"] === "text");
239
+ if (last)
240
+ last["cache_control"] = { type: "ephemeral" };
241
+ }
170
242
  function encodeMessage(message, provider) {
171
243
  if (message.role === "tool") {
172
244
  return { role: "tool", tool_call_id: message.callId, content: textOf(message.content) };
@@ -291,27 +363,40 @@ const decodeUsage = (usage) => ({
291
363
  // adds its own margin, so what it charged is a thing only it can say — and
292
364
  // the frame carrying it is the one this adapter already reads.
293
365
  ...(typeof usage.cost === "number" ? { costUsd: usage.cost } : {}),
294
- // `prompt_tokens` is the whole prompt and `cached_tokens` is counted inside
295
- // it — "cached tokens present in the prompt". `Usage` keeps the three input
296
- // counts disjoint, so the cached part comes out here rather than every
366
+ // `prompt_tokens` is the whole prompt, and both `cached_tokens` and
367
+ // `cache_write_tokens` are counted inside it. `Usage` keeps the three input
368
+ // counts disjoint, so the cached parts come out here rather than every
297
369
  // caller having to know which wire produced the number it is holding.
298
370
  ...(usage.prompt_tokens !== undefined
299
- ? { inputTokens: Math.max(usage.prompt_tokens - (usage.prompt_tokens_details?.cached_tokens ?? 0), 0) } : {}),
371
+ ? {
372
+ inputTokens: Math.max(usage.prompt_tokens
373
+ - (usage.prompt_tokens_details?.cached_tokens ?? 0)
374
+ - (usage.prompt_tokens_details?.cache_write_tokens ?? 0), 0),
375
+ }
376
+ : {}),
300
377
  ...(usage.completion_tokens !== undefined ? { outputTokens: usage.completion_tokens } : {}),
301
378
  ...(usage.prompt_tokens_details?.cached_tokens !== undefined
302
379
  ? { cacheReadTokens: usage.prompt_tokens_details.cached_tokens } : {}),
380
+ ...(usage.prompt_tokens_details?.cache_write_tokens !== undefined
381
+ ? { cacheWriteTokens: usage.prompt_tokens_details.cache_write_tokens } : {}),
303
382
  });
304
- async function httpError(response) {
383
+ /**
384
+ * A refusal, or a wait the retries did not outlast. The second keeps a
385
+ * retryable code: the provider never said the request was wrong, and a caller
386
+ * with the time to try again later is told so.
387
+ */
388
+ async function httpError(response, isWait) {
389
+ const wait = isWaitStatus(response.status) || (await isWait?.(response) ?? false);
305
390
  const body = await response.text().catch(() => "");
306
391
  const code = response.status === 401 || response.status === 403 ? "auth"
307
- : response.status === 429 ? "rate-limit"
308
- : response.status === 400 && /context|token/i.test(body) ? "context-length"
309
- : response.status >= 500 ? "provider"
392
+ : response.status === 400 && /context|token/i.test(body) ? "context-length"
393
+ : wait && (response.status === 429 || response.status === 402) ? "rate-limit"
394
+ : wait ? "provider"
310
395
  : "failed";
311
396
  return {
312
397
  code,
313
398
  message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : ""}`,
314
- retryable: code === "rate-limit" || code === "provider",
399
+ retryable: wait,
315
400
  };
316
401
  }
317
402
  function transportError(error, signal) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/openai-compatible/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAmB7C;;;GAGG;AACH,MAAM,UAAU,2BAA2B,CAAC,OAAgC;IAC1E,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC;IACpC,MAAM,QAAQ,GAAG,qBAAqB,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC;IAC5E,OAAO;QACL,EAAE,EAAE,qBAAqB,OAAO,CAAC,KAAK,EAAE;QAExC,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAqB;YACnC,IAAI,QAAkB,CAAC;YACvB,IAAI,CAAC;gBACH,QAAQ,GAAG,MAAM,IAAI,CAAC,GAAG,OAAO,CAAC,OAAO,mBAAmB,EAAE;oBAC3D,MAAM,EAAE,MAAM;oBACd,OAAO,EAAE;wBACP,cAAc,EAAE,kBAAkB;wBAClC,aAAa,EAAE,UAAU,OAAO,CAAC,MAAM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D,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,IAA4C,EAAE,CAAC;QACvE,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnC,OAAO,OAAO,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC7C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;YACnC,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\n\nexport interface OpenAiCompatibleOptions {\n apiKey: string;\n baseUrl: string;\n model: string;\n headers?: Readonly<Record<string, string>>;\n /**\n * How this endpoint spells reasoning effort. OpenAI takes `reasoning_effort`;\n * OpenRouter takes `reasoning: { effort }` and forwards it to whoever is\n * serving the model. Sending both is not compatibility — OpenAI rejects the\n * request outright — so the dialect is declared rather than guessed.\n */\n effortParameter?: \"reasoning_effort\" | \"reasoning\" | \"none\";\n /** Injectable for tests; defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * The OpenAI chat-completions wire, which almost every provider now speaks —\n * OpenRouter, Together, Groq, vLLM, Ollama. One adapter, one base URL.\n */\nexport function createOpenAiCompatibleModel(options: OpenAiCompatibleOptions): Model {\n const call = options.fetch ?? fetch;\n const provider = `openai-compatible:${options.baseUrl.replace(/\\/+$/, \"\")}`;\n return {\n id: `openai-compatible:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n let response: Response;\n try {\n response = await call(`${options.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${options.apiKey}`,\n ...options.headers,\n },\n body: JSON.stringify({\n model: options.model,\n messages: encodeConversation(request.messages, provider),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.maxOutputTokens !== undefined ? { max_tokens: request.maxOutputTokens } : {}),\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...encodeEffort(request.effort, options.effortParameter ?? \"reasoning_effort\"),\n stream: true,\n stream_options: { include_usage: true },\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n if (!response.ok) return err(await httpError(response));\n if (!response.body) return err({ code: \"provider\", message: \"No response body\", retryable: true });\n\n const text: string[] = [];\n const calls = new Map<number, { callId: string; name: string; arguments: string }>();\n let finish: ModelResponse[\"finishReason\"] = \"stop\";\n let usage: Usage = {};\n let model: string | undefined;\n const reasoningDetails: JsonValue[] = [];\n let sawReasoningDetails = false;\n const reasoning: string[] = [];\n const reasoningContent: string[] = [];\n\n // A stream that dies mid-body — cancelled, dropped, truncated — must come\n // back as a typed failure like any other. Without this the generator throws,\n // `run.result` rejects instead of resolving `cancelled`, no `run.finished`\n // is ever committed, and the activation stays open until its claim expires.\n try {\n for await (const event of sseLines(response.body)) {\n if (event === \"[DONE]\") break;\n let frame: ChatFrame;\n try { frame = JSON.parse(event) as ChatFrame; } catch { continue; }\n model ??= frame.model;\n if (frame.usage) usage = decodeUsage(frame.usage);\n\n const choice = frame.choices?.[0];\n if (!choice) continue;\n if (choice.finish_reason) finish = decodeFinish(choice.finish_reason);\n\n const content = choice.delta?.content;\n if (content) { text.push(content); yield { type: \"text.delta\", text: content }; }\n\n const reasoningDelta = choice.delta?.reasoning;\n const reasoningContentDelta = choice.delta?.reasoning_content;\n if (reasoningDelta !== undefined) reasoning.push(reasoningDelta);\n if (reasoningContentDelta !== undefined) reasoningContent.push(reasoningContentDelta);\n const visibleReasoning = reasoningDelta ?? reasoningContentDelta;\n if (visibleReasoning) yield { type: \"reasoning.delta\", text: visibleReasoning };\n if (choice.delta?.reasoning_details !== undefined) {\n sawReasoningDetails = true;\n appendReasoningDetails(reasoningDetails, choice.delta.reasoning_details);\n }\n\n for (const fragment of choice.delta?.tool_calls ?? []) {\n // Providers stream tool arguments in fragments, keyed by position;\n // only the first fragment carries the id and the name.\n const existing = calls.get(fragment.index) ?? {\n callId: fragment.id ?? `call_${fragment.index}`,\n name: fragment.function?.name ?? \"\",\n arguments: \"\",\n };\n if (fragment.id) existing.callId = fragment.id;\n if (fragment.function?.name) existing.name = fragment.function.name;\n if (fragment.function?.arguments) {\n existing.arguments += fragment.function.arguments;\n yield { type: \"tool-call.delta\", callId: existing.callId, arguments: fragment.function.arguments };\n }\n calls.set(fragment.index, existing);\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n const collected: ToolCall[] = [...calls.values()]\n .map((call) => ({ callId: call.callId, name: call.name, arguments: call.arguments || \"{}\" }));\n\n const state = reasoningState(reasoningDetails, sawReasoningDetails, reasoning, reasoningContent);\n return ok({\n message: { content: text.join(\"\"), ...(collected.length ? { calls: collected } : {}) },\n finishReason: collected.length && finish === \"stop\" ? \"tool-calls\" : finish,\n usage,\n ...(model ? { model } : {}),\n ...(state.length ? { providerState: { provider, items: state } } : {}),\n });\n },\n };\n}\n\n/** OpenRouter is this wire with a fixed base URL and attribution headers. */\nexport function createOpenRouterModel(input: {\n apiKey: string; model: string; appUrl?: string; appName?: string; fetch?: typeof fetch;\n}): Model {\n return createOpenAiCompatibleModel({\n apiKey: input.apiKey,\n baseUrl: \"https://openrouter.ai/api/v1\",\n model: input.model,\n effortParameter: \"reasoning\",\n headers: {\n ...(input.appUrl ? { \"http-referer\": input.appUrl } : {}),\n ...(input.appName ? { \"x-title\": input.appName } : {}),\n },\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n\nfunction encodeEffort(\n effort: ModelRequest[\"effort\"],\n parameter: \"reasoning_effort\" | \"reasoning\" | \"none\",\n): Record<string, unknown> {\n if (!effort || parameter === \"none\") return {};\n return parameter === \"reasoning\" ? { reasoning: { effort } } : { reasoning_effort: effort };\n}\n\nfunction encodeConversation(messages: readonly Message[], provider: string): Record<string, unknown>[] {\n const out: Record<string, unknown>[] = [];\n let images: ContentPart[] = [];\n const flush = () => {\n if (images.length) out.push({ role: \"user\", content: encodeContent(images) });\n images = [];\n };\n for (const message of messages) {\n // The wire accepts only text in tool replies. Keep every reply in a parallel\n // batch adjacent before supplying its images as associated user content.\n if (message.role !== \"tool\") flush();\n out.push(encodeMessage(message, provider));\n if (message.role === \"tool\" && typeof message.content !== \"string\") {\n const media = message.content.filter((part) => part.type === \"image\");\n if (media.length) images.push({ type: \"text\", text: `Images from tool call ${message.callId}:` }, ...media);\n }\n }\n flush();\n return out;\n}\n\nfunction encodeMessage(message: Message, provider: string): Record<string, unknown> {\n if (message.role === \"tool\") {\n return { role: \"tool\", tool_call_id: message.callId, content: textOf(message.content) };\n }\n if (message.role === \"assistant\") {\n return {\n role: \"assistant\",\n content: textOf(message.content) || null,\n ...decodeReasoningState(message, provider),\n ...(message.calls?.length\n ? {\n tool_calls: message.calls.map((call) => ({\n id: call.callId, type: \"function\",\n function: { name: call.name, arguments: call.arguments },\n })),\n }\n : {}),\n };\n }\n return { role: message.role, content: encodeContent(message.content) };\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown {\n if (typeof content === \"string\") return content;\n const parts: Record<string, unknown>[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") { parts.push({ type: \"text\", text: part.text }); continue; }\n if (part.type === \"image\") {\n const url = part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`;\n parts.push({ type: \"image_url\", image_url: { url } });\n }\n // Files and opaque blocks have no place on this wire. Dropping them beats\n // stringifying them into something the model would read as prose.\n }\n const only = parts.length === 1 ? parts[0] : undefined;\n return only?.type === \"text\" ? only.text : parts;\n}\n\nfunction reasoningState(\n details: readonly JsonValue[],\n sawDetails: boolean,\n reasoning: readonly string[],\n reasoningContent: readonly string[],\n): JsonValue[] {\n const state: Record<string, JsonValue> = {};\n if (sawDetails) state[\"reasoning_details\"] = details;\n if (!sawDetails && reasoning.length) state[\"reasoning\"] = reasoning.join(\"\");\n if (!sawDetails && reasoningContent.length) state[\"reasoning_content\"] = reasoningContent.join(\"\");\n return Object.keys(state).length ? [state] : [];\n}\n\nfunction decodeReasoningState(message: Extract<Message, { role: \"assistant\" }>, provider: string) {\n if (message.providerState?.provider !== provider) return {};\n const state: Record<string, JsonValue> = {};\n for (const item of message.providerState.items) {\n const value = record(item);\n const details = value?.[\"reasoning_details\"];\n if (Array.isArray(details)) state[\"reasoning_details\"] = details;\n for (const field of [\"reasoning\", \"reasoning_content\"] as const) {\n if (typeof value?.[field] === \"string\") state[field] = value[field];\n }\n }\n return state;\n}\n\n/** Rebuild the complete blocks OpenRouter's chat stream fragments by type. */\nfunction appendReasoningDetails(target: JsonValue[], incoming: readonly JsonValue[]): void {\n for (const raw of incoming) {\n const detail = record(raw);\n if (!detail) {\n target.push(clone(raw));\n continue;\n }\n const field = detail?.[\"type\"] === \"reasoning.text\" ? \"text\"\n : detail?.[\"type\"] === \"reasoning.summary\" ? \"summary\"\n : undefined;\n const previous = record(target.at(-1));\n if (!field || !previous || previous[\"type\"] !== detail[\"type\"] || !compatible(previous, detail, field)) {\n target.push(clone(raw));\n continue;\n }\n\n const merged: Record<string, JsonValue> = { ...previous };\n for (const [key, value] of Object.entries(detail)) {\n if (key === field) continue;\n if (value !== null || merged[key] === undefined) merged[key] = value;\n }\n merged[field] = `${typeof previous[field] === \"string\" ? previous[field] : \"\"}${\n typeof detail[field] === \"string\" ? detail[field] : \"\"\n }`;\n target[target.length - 1] = merged;\n }\n}\n\nfunction compatible(\n left: Readonly<Record<string, JsonValue>>,\n right: Readonly<Record<string, JsonValue>>,\n payload: string,\n): boolean {\n const keys = new Set([...Object.keys(left), ...Object.keys(right)]);\n for (const key of keys) {\n if (key === payload) continue;\n const a = left[key];\n const b = right[key];\n if (a === undefined || a === null || b === undefined || b === null) continue;\n if (JSON.stringify(a) !== JSON.stringify(b)) return false;\n }\n return true;\n}\n\nconst record = (value: JsonValue | undefined): Readonly<Record<string, JsonValue>> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Readonly<Record<string, JsonValue>>\n : undefined;\n\nconst clone = (value: JsonValue): JsonValue => JSON.parse(JSON.stringify(value)) as JsonValue;\n\nconst encodeTool = (tool: ToolSpec) => ({\n type: \"function\",\n function: { name: tool.name, description: tool.description, parameters: tool.parameters, strict: false },\n});\n\nconst decodeFinish = (reason: string): ModelResponse[\"finishReason\"] =>\n reason === \"tool_calls\" ? \"tool-calls\"\n : reason === \"length\" ? \"length\"\n : reason === \"content_filter\" ? \"refusal\"\n : \"stop\";\n\nconst decodeUsage = (usage: ChatUsage): Usage => ({\n // Carried, not computed. A router picks an upstream provider per request and\n // adds its own margin, so what it charged is a thing only it can say — and\n // the frame carrying it is the one this adapter already reads.\n ...(typeof usage.cost === \"number\" ? { costUsd: usage.cost } : {}),\n // `prompt_tokens` is the whole prompt and `cached_tokens` is counted inside\n // it — \"cached tokens present in the prompt\". `Usage` keeps the three input\n // counts disjoint, so the cached part comes out here rather than every\n // caller having to know which wire produced the number it is holding.\n ...(usage.prompt_tokens !== undefined\n ? { inputTokens: Math.max(usage.prompt_tokens - (usage.prompt_tokens_details?.cached_tokens ?? 0), 0) } : {}),\n ...(usage.completion_tokens !== undefined ? { outputTokens: usage.completion_tokens } : {}),\n ...(usage.prompt_tokens_details?.cached_tokens !== undefined\n ? { cacheReadTokens: usage.prompt_tokens_details.cached_tokens } : {}),\n});\n\nasync function httpError(response: Response): Promise<ModelError> {\n const body = await response.text().catch(() => \"\");\n const code: ModelError[\"code\"] =\n response.status === 401 || response.status === 403 ? \"auth\"\n : response.status === 429 ? \"rate-limit\"\n : response.status === 400 && /context|token/i.test(body) ? \"context-length\"\n : response.status >= 500 ? \"provider\"\n : \"failed\";\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: code === \"rate-limit\" || code === \"provider\",\n };\n}\n\nfunction transportError(error: unknown, signal?: AbortSignal): ModelError {\n if (signal?.aborted) return { code: \"cancelled\", message: \"Generation cancelled\", retryable: false };\n return { code: \"provider\", message: error instanceof Error ? error.message : String(error), retryable: true };\n}\n\n/** Server-sent events, reassembled across chunk boundaries. */\nasync function* sseLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line.startsWith(\"data:\")) yield line.slice(5).trim();\n newline = buffer.indexOf(\"\\n\");\n }\n }\n}\n\ninterface ChatUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n prompt_tokens_details?: { cached_tokens?: number };\n /**\n * What this generation was charged. OpenRouter sets it on every response and\n * calls it credits, whose base currency is US dollars; plain OpenAI and the\n * self-hosted endpoints on this wire do not send it at all, so it is absent\n * rather than zero there.\n */\n cost?: number;\n}\ninterface ChatFrame {\n model?: string;\n usage?: ChatUsage;\n choices?: readonly {\n finish_reason?: string | null;\n delta?: {\n content?: string;\n reasoning?: string;\n reasoning_content?: string;\n reasoning_details?: readonly JsonValue[];\n tool_calls?: readonly { index: number; id?: string; function?: { name?: string; arguments?: string } }[];\n };\n }[];\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/openai-compatible/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAqB,MAAM,gBAAgB,CAAC;AAgC3E;;;GAGG;AACH,MAAM,UAAU,2BAA2B,CAAC,OAAgC;IAC1E,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,IAAI,KAAK,EAAE,EAAE,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IACzG,MAAM,QAAQ,GAAG,qBAAqB,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC;IAC5E,MAAM,OAAO,GAAG,OAAO,CAAC,eAAe,KAAK,eAAe,CAAC;IAC5D,OAAO;QACL,EAAE,EAAE,qBAAqB,OAAO,CAAC,KAAK,EAAE;QAExC,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAqB;YACnC,IAAI,QAAkB,CAAC;YACvB,IAAI,CAAC;gBACH,QAAQ,GAAG,MAAM,IAAI,CAAC,GAAG,OAAO,CAAC,OAAO,mBAAmB,EAAE;oBAC3D,MAAM,EAAE,MAAM;oBACd,OAAO,EAAE;wBACP,cAAc,EAAE,kBAAkB;wBAClC,aAAa,EAAE,UAAU,OAAO,CAAC,MAAM,EAAE;wBACzC,GAAG,OAAO,CAAC,OAAO;qBACnB;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AC,QAAQ,CAAC,IAAgC;IACvD,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,IAA4C,EAAE,CAAC;QACvE,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnC,OAAO,OAAO,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC7C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;YACnC,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { isWaitStatus, retrying, type RetryOptions } from \"../../retry.js\";\n\nexport interface OpenAiCompatibleOptions {\n apiKey: string;\n baseUrl: string;\n model: string;\n headers?: Readonly<Record<string, string>>;\n /**\n * How this endpoint spells reasoning effort. OpenAI takes `reasoning_effort`;\n * OpenRouter takes `reasoning: { effort }` and forwards it to whoever is\n * serving the model. Sending both is not compatibility — OpenAI rejects the\n * request outright — so the dialect is declared rather than guessed.\n */\n effortParameter?: \"reasoning_effort\" | \"reasoning\" | \"none\";\n /**\n * How this endpoint spells a cache breakpoint, where it has one. Most models\n * on this wire cache a repeated prefix by themselves and have no field for\n * it — plain OpenAI rejects one it does not know — so the default sends none.\n * OpenRouter takes Anthropic's `cache_control` on a text part and forwards\n * it to the models that cache nothing without one.\n */\n cacheBreakpoint?: \"cache_control\" | \"none\";\n /**\n * A refusal this endpoint means as a wait, beyond the statuses every HTTP\n * wire means so. Retried before the first delta like those, and reported as\n * a rate limit when the retries run out.\n */\n isWait?: RetryOptions[\"isWait\"];\n /** Injectable for tests; defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * The OpenAI chat-completions wire, which almost every provider now speaks —\n * OpenRouter, Together, Groq, vLLM, Ollama. One adapter, one base URL.\n */\nexport function createOpenAiCompatibleModel(options: OpenAiCompatibleOptions): Model {\n const call = retrying(options.fetch ?? fetch, { ...(options.isWait ? { isWait: options.isWait } : {}) });\n const provider = `openai-compatible:${options.baseUrl.replace(/\\/+$/, \"\")}`;\n const marking = options.cacheBreakpoint === \"cache_control\";\n return {\n id: `openai-compatible:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n let response: Response;\n try {\n response = await call(`${options.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${options.apiKey}`,\n ...options.headers,\n },\n body: JSON.stringify({\n model: options.model,\n messages: encodeConversation(request.messages, provider, marking ? breakpoints(request) : new Set()),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.maxOutputTokens !== undefined ? { max_tokens: request.maxOutputTokens } : {}),\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...encodeEffort(request.effort, options.effortParameter ?? \"reasoning_effort\"),\n stream: true,\n stream_options: { include_usage: true },\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n if (!response.ok) return err(await httpError(response, options.isWait));\n if (!response.body) return err({ code: \"provider\", message: \"No response body\", retryable: true });\n\n const text: string[] = [];\n const calls = new Map<number, { callId: string; name: string; arguments: string }>();\n let finish: ModelResponse[\"finishReason\"] = \"stop\";\n let usage: Usage = {};\n let model: string | undefined;\n const reasoningDetails: JsonValue[] = [];\n let sawReasoningDetails = false;\n const reasoning: string[] = [];\n const reasoningContent: string[] = [];\n\n // A stream that dies mid-body — cancelled, dropped, truncated — must come\n // back as a typed failure like any other. Without this the generator throws,\n // `run.result` rejects instead of resolving `cancelled`, no `run.finished`\n // is ever committed, and the activation stays open until its claim expires.\n try {\n for await (const event of sseLines(response.body)) {\n if (event === \"[DONE]\") break;\n let frame: ChatFrame;\n try { frame = JSON.parse(event) as ChatFrame; } catch { continue; }\n model ??= frame.model;\n if (frame.usage) usage = decodeUsage(frame.usage);\n\n const choice = frame.choices?.[0];\n if (!choice) continue;\n if (choice.finish_reason) finish = decodeFinish(choice.finish_reason);\n\n const content = choice.delta?.content;\n if (content) { text.push(content); yield { type: \"text.delta\", text: content }; }\n\n const reasoningDelta = choice.delta?.reasoning;\n const reasoningContentDelta = choice.delta?.reasoning_content;\n if (reasoningDelta !== undefined) reasoning.push(reasoningDelta);\n if (reasoningContentDelta !== undefined) reasoningContent.push(reasoningContentDelta);\n const visibleReasoning = reasoningDelta ?? reasoningContentDelta;\n if (visibleReasoning) yield { type: \"reasoning.delta\", text: visibleReasoning };\n if (choice.delta?.reasoning_details !== undefined) {\n sawReasoningDetails = true;\n appendReasoningDetails(reasoningDetails, choice.delta.reasoning_details);\n }\n\n for (const fragment of choice.delta?.tool_calls ?? []) {\n // Providers stream tool arguments in fragments, keyed by position;\n // only the first fragment carries the id and the name.\n const existing = calls.get(fragment.index) ?? {\n callId: fragment.id ?? `call_${fragment.index}`,\n name: fragment.function?.name ?? \"\",\n arguments: \"\",\n };\n if (fragment.id) existing.callId = fragment.id;\n if (fragment.function?.name) existing.name = fragment.function.name;\n if (fragment.function?.arguments) {\n existing.arguments += fragment.function.arguments;\n yield { type: \"tool-call.delta\", callId: existing.callId, arguments: fragment.function.arguments };\n }\n calls.set(fragment.index, existing);\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n const collected: ToolCall[] = [...calls.values()]\n .map((call) => ({ callId: call.callId, name: call.name, arguments: call.arguments || \"{}\" }));\n\n const state = reasoningState(reasoningDetails, sawReasoningDetails, reasoning, reasoningContent);\n return ok({\n message: { content: text.join(\"\"), ...(collected.length ? { calls: collected } : {}) },\n finishReason: collected.length && finish === \"stop\" ? \"tool-calls\" : finish,\n usage,\n ...(model ? { model } : {}),\n ...(state.length ? { providerState: { provider, items: state } } : {}),\n });\n },\n };\n}\n\n/**\n * OpenRouter is this wire with a fixed base URL, attribution headers, and two\n * facts of its own.\n *\n * It caches Claude only when asked. Every other model it serves reads a\n * repeated prefix from cache on its own; a Claude request without a\n * `cache_control` mark is read in full every turn, at full price. The mark\n * goes on the models that need it and on no other: whether the providers that\n * cache by themselves ignore a mark is not something its documentation says,\n * and a strict one could refuse the request.\n *\n * It answers 402 for two different things. One is an account with no credit,\n * which is a refusal. The other is the account's credit being reserved by its\n * own other requests still in flight, which clears when they finish — the\n * commonest failure an agent serving several sessions at once will see, and a\n * wait. The body's structured `error.metadata.reason` tells them apart.\n */\nexport function createOpenRouterModel(input: {\n apiKey: string; model: string; appUrl?: string; appName?: string; fetch?: typeof fetch;\n}): Model {\n return createOpenAiCompatibleModel({\n apiKey: input.apiKey,\n baseUrl: \"https://openrouter.ai/api/v1\",\n model: input.model,\n effortParameter: \"reasoning\",\n cacheBreakpoint: /^~?anthropic\\//.test(input.model) ? \"cache_control\" : \"none\",\n isWait: inFlightBudgetExhausted,\n headers: {\n ...(input.appUrl ? { \"http-referer\": input.appUrl } : {}),\n ...(input.appName ? { \"x-title\": input.appName } : {}),\n },\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n\nasync function inFlightBudgetExhausted(response: Response): Promise<boolean> {\n if (response.status !== 402) return false;\n const body = await response.clone().json().catch(() => undefined) as\n { error?: { metadata?: { reason?: unknown } } } | undefined;\n return body?.error?.metadata?.reason === \"in_flight_budget_exhausted\";\n}\n\nfunction encodeEffort(\n effort: ModelRequest[\"effort\"],\n parameter: \"reasoning_effort\" | \"reasoning\" | \"none\",\n): Record<string, unknown> {\n if (!effort || parameter === \"none\") return {};\n return parameter === \"reasoning\" ? { reasoning: { effort } } : { reasoning_effort: effort };\n}\n\n/**\n * Which messages carry a breakpoint: the same three places the Anthropic\n * adapter marks, for the same reasons it gives.\n *\n * The prefix ends where the caller says. When that is at or past the leading\n * run of system messages, the first and the last of them are marked — the last\n * makes a conversation's own prefix reusable across its turns, the first makes\n * the standing instructions every conversation shares reusable across\n * conversations. A boundary past the system run marks the message it ends on\n * as well. Three at most, inside a budget of four.\n */\nfunction breakpoints(request: ModelRequest): ReadonlySet<number> {\n const boundary = request.cacheAfter;\n if (boundary === undefined) return new Set();\n let lead = 0;\n while (lead < request.messages.length && request.messages[lead]!.role === \"system\") lead += 1;\n const marked = new Set<number>();\n if (lead > 0 && boundary >= lead) marked.add(0).add(lead - 1);\n if (boundary > lead && boundary <= request.messages.length) marked.add(boundary - 1);\n return marked;\n}\n\nfunction encodeConversation(\n messages: readonly Message[], provider: string, marked: ReadonlySet<number>,\n): Record<string, unknown>[] {\n const out: Record<string, unknown>[] = [];\n let images: ContentPart[] = [];\n const flush = () => {\n if (images.length) out.push({ role: \"user\", content: encodeContent(images) });\n images = [];\n };\n messages.forEach((message, index) => {\n // The wire accepts only text in tool replies. Keep every reply in a parallel\n // batch adjacent before supplying its images as associated user content.\n if (message.role !== \"tool\") flush();\n const encoded = encodeMessage(message, provider);\n if (marked.has(index)) mark(encoded);\n out.push(encoded);\n if (message.role === \"tool\" && typeof message.content !== \"string\") {\n const media = message.content.filter((part) => part.type === \"image\");\n if (media.length) images.push({ type: \"text\", text: `Images from tool call ${message.callId}:` }, ...media);\n }\n });\n flush();\n return out;\n}\n\n/**\n * A breakpoint lands on a text part, so a bare string becomes one part to\n * carry it. A message with no text — an assistant turn that only called tools,\n * a user turn that is only an image — has nowhere to put one and gets none.\n */\nfunction mark(encoded: Record<string, unknown>): void {\n const content = encoded[\"content\"];\n if (typeof content === \"string\") {\n if (content) encoded[\"content\"] = [{ type: \"text\", text: content, cache_control: { type: \"ephemeral\" } }];\n return;\n }\n if (!Array.isArray(content)) return;\n const last = content.findLast((part: Record<string, unknown>) => part[\"type\"] === \"text\") as\n Record<string, unknown> | undefined;\n if (last) last[\"cache_control\"] = { type: \"ephemeral\" };\n}\n\nfunction encodeMessage(message: Message, provider: string): Record<string, unknown> {\n if (message.role === \"tool\") {\n return { role: \"tool\", tool_call_id: message.callId, content: textOf(message.content) };\n }\n if (message.role === \"assistant\") {\n return {\n role: \"assistant\",\n content: textOf(message.content) || null,\n ...decodeReasoningState(message, provider),\n ...(message.calls?.length\n ? {\n tool_calls: message.calls.map((call) => ({\n id: call.callId, type: \"function\",\n function: { name: call.name, arguments: call.arguments },\n })),\n }\n : {}),\n };\n }\n return { role: message.role, content: encodeContent(message.content) };\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown {\n if (typeof content === \"string\") return content;\n const parts: Record<string, unknown>[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") { parts.push({ type: \"text\", text: part.text }); continue; }\n if (part.type === \"image\") {\n const url = part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`;\n parts.push({ type: \"image_url\", image_url: { url } });\n }\n // Files and opaque blocks have no place on this wire. Dropping them beats\n // stringifying them into something the model would read as prose.\n }\n const only = parts.length === 1 ? parts[0] : undefined;\n return only?.type === \"text\" ? only.text : parts;\n}\n\nfunction reasoningState(\n details: readonly JsonValue[],\n sawDetails: boolean,\n reasoning: readonly string[],\n reasoningContent: readonly string[],\n): JsonValue[] {\n const state: Record<string, JsonValue> = {};\n if (sawDetails) state[\"reasoning_details\"] = details;\n if (!sawDetails && reasoning.length) state[\"reasoning\"] = reasoning.join(\"\");\n if (!sawDetails && reasoningContent.length) state[\"reasoning_content\"] = reasoningContent.join(\"\");\n return Object.keys(state).length ? [state] : [];\n}\n\nfunction decodeReasoningState(message: Extract<Message, { role: \"assistant\" }>, provider: string) {\n if (message.providerState?.provider !== provider) return {};\n const state: Record<string, JsonValue> = {};\n for (const item of message.providerState.items) {\n const value = record(item);\n const details = value?.[\"reasoning_details\"];\n if (Array.isArray(details)) state[\"reasoning_details\"] = details;\n for (const field of [\"reasoning\", \"reasoning_content\"] as const) {\n if (typeof value?.[field] === \"string\") state[field] = value[field];\n }\n }\n return state;\n}\n\n/** Rebuild the complete blocks OpenRouter's chat stream fragments by type. */\nfunction appendReasoningDetails(target: JsonValue[], incoming: readonly JsonValue[]): void {\n for (const raw of incoming) {\n const detail = record(raw);\n if (!detail) {\n target.push(clone(raw));\n continue;\n }\n const field = detail?.[\"type\"] === \"reasoning.text\" ? \"text\"\n : detail?.[\"type\"] === \"reasoning.summary\" ? \"summary\"\n : undefined;\n const previous = record(target.at(-1));\n if (!field || !previous || previous[\"type\"] !== detail[\"type\"] || !compatible(previous, detail, field)) {\n target.push(clone(raw));\n continue;\n }\n\n const merged: Record<string, JsonValue> = { ...previous };\n for (const [key, value] of Object.entries(detail)) {\n if (key === field) continue;\n if (value !== null || merged[key] === undefined) merged[key] = value;\n }\n merged[field] = `${typeof previous[field] === \"string\" ? previous[field] : \"\"}${\n typeof detail[field] === \"string\" ? detail[field] : \"\"\n }`;\n target[target.length - 1] = merged;\n }\n}\n\nfunction compatible(\n left: Readonly<Record<string, JsonValue>>,\n right: Readonly<Record<string, JsonValue>>,\n payload: string,\n): boolean {\n const keys = new Set([...Object.keys(left), ...Object.keys(right)]);\n for (const key of keys) {\n if (key === payload) continue;\n const a = left[key];\n const b = right[key];\n if (a === undefined || a === null || b === undefined || b === null) continue;\n if (JSON.stringify(a) !== JSON.stringify(b)) return false;\n }\n return true;\n}\n\nconst record = (value: JsonValue | undefined): Readonly<Record<string, JsonValue>> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Readonly<Record<string, JsonValue>>\n : undefined;\n\nconst clone = (value: JsonValue): JsonValue => JSON.parse(JSON.stringify(value)) as JsonValue;\n\nconst encodeTool = (tool: ToolSpec) => ({\n type: \"function\",\n function: { name: tool.name, description: tool.description, parameters: tool.parameters, strict: false },\n});\n\nconst decodeFinish = (reason: string): ModelResponse[\"finishReason\"] =>\n reason === \"tool_calls\" ? \"tool-calls\"\n : reason === \"length\" ? \"length\"\n : reason === \"content_filter\" ? \"refusal\"\n : \"stop\";\n\nconst decodeUsage = (usage: ChatUsage): Usage => ({\n // Carried, not computed. A router picks an upstream provider per request and\n // adds its own margin, so what it charged is a thing only it can say — and\n // the frame carrying it is the one this adapter already reads.\n ...(typeof usage.cost === \"number\" ? { costUsd: usage.cost } : {}),\n // `prompt_tokens` is the whole prompt, and both `cached_tokens` and\n // `cache_write_tokens` are counted inside it. `Usage` keeps the three input\n // counts disjoint, so the cached parts come out here rather than every\n // caller having to know which wire produced the number it is holding.\n ...(usage.prompt_tokens !== undefined\n ? {\n inputTokens: Math.max(\n usage.prompt_tokens\n - (usage.prompt_tokens_details?.cached_tokens ?? 0)\n - (usage.prompt_tokens_details?.cache_write_tokens ?? 0),\n 0,\n ),\n }\n : {}),\n ...(usage.completion_tokens !== undefined ? { outputTokens: usage.completion_tokens } : {}),\n ...(usage.prompt_tokens_details?.cached_tokens !== undefined\n ? { cacheReadTokens: usage.prompt_tokens_details.cached_tokens } : {}),\n ...(usage.prompt_tokens_details?.cache_write_tokens !== undefined\n ? { cacheWriteTokens: usage.prompt_tokens_details.cache_write_tokens } : {}),\n});\n\n/**\n * A refusal, or a wait the retries did not outlast. The second keeps a\n * retryable code: the provider never said the request was wrong, and a caller\n * with the time to try again later is told so.\n */\nasync function httpError(response: Response, isWait: RetryOptions[\"isWait\"]): Promise<ModelError> {\n const wait = isWaitStatus(response.status) || (await isWait?.(response) ?? false);\n const body = await response.text().catch(() => \"\");\n const code: ModelError[\"code\"] =\n response.status === 401 || response.status === 403 ? \"auth\"\n : response.status === 400 && /context|token/i.test(body) ? \"context-length\"\n : wait && (response.status === 429 || response.status === 402) ? \"rate-limit\"\n : wait ? \"provider\"\n : \"failed\";\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: wait,\n };\n}\n\nfunction transportError(error: unknown, signal?: AbortSignal): ModelError {\n if (signal?.aborted) return { code: \"cancelled\", message: \"Generation cancelled\", retryable: false };\n return { code: \"provider\", message: error instanceof Error ? error.message : String(error), retryable: true };\n}\n\n/** Server-sent events, reassembled across chunk boundaries. */\nasync function* sseLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line.startsWith(\"data:\")) yield line.slice(5).trim();\n newline = buffer.indexOf(\"\\n\");\n }\n }\n}\n\ninterface ChatUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n /**\n * `cache_write_tokens` is OpenRouter's, reported when the model it routed to\n * wrote the marked prefix; plain OpenAI sends only `cached_tokens`.\n */\n prompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };\n /**\n * What this generation was charged. OpenRouter sets it on every response and\n * calls it credits, whose base currency is US dollars; plain OpenAI and the\n * self-hosted endpoints on this wire do not send it at all, so it is absent\n * rather than zero there.\n */\n cost?: number;\n}\ninterface ChatFrame {\n model?: string;\n usage?: ChatUsage;\n choices?: readonly {\n finish_reason?: string | null;\n delta?: {\n content?: string;\n reasoning?: string;\n reasoning_content?: string;\n reasoning_details?: readonly JsonValue[];\n tool_calls?: readonly { index: number; id?: string; function?: { name?: string; arguments?: string } }[];\n };\n }[];\n}\n"]}
@@ -615,7 +615,11 @@ function encodeContent(content, output) {
615
615
  if (part.type === "file" && !output) {
616
616
  parts.push(part.source.kind === "url"
617
617
  ? { type: "input_file", file_url: part.source.url }
618
- : { type: "input_file", file_data: part.source.data, ...(part.name ? { filename: part.name } : {}) });
618
+ : {
619
+ type: "input_file",
620
+ file_data: `data:${part.mediaType};base64,${part.source.data}`,
621
+ ...(part.name ? { filename: part.name } : {}),
622
+ });
619
623
  continue;
620
624
  }
621
625
  if (part.type === "opaque" && part.provider === provider)
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/openai-responses/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAQ5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAE1D,MAAM,QAAQ,GAAG,kBAAkB,CAAC;AACpC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,YAAY,GAAG,EAAE,CAAC;AAgDxB,MAAM,YAAY;IACP,WAAW,CAA4B;IACvC,MAAM,GAAG,IAAI,GAAG,EAAmB,CAAC;IACpC,QAAQ,GAAa,EAAE,CAAC;IACxB,MAAM,CAAa;IAC5B,gBAAgB,GAAG,CAAC,CAAC;IACrB,UAAU,GAAG,CAAC,CAAC;IACf,SAAS,GAAG,KAAK,CAAC;IAClB,MAAM,GAAG,KAAK,CAAC;IAEf,YAAY,UAAqC,EAAE,KAAiB;QAClE,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;QAC9B,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,KAAK,IAAI,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IAED,IAAI;QACF,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,gBAAgB,IAAI,kBAAkB;YAAE,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CAAC,SAAS,CAAC;AACzE,MAAM,MAAM,GAAG,CAAC,KAAc,EAAuC,EAAE,CACrE,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAgC,CAAC,CAAC,CAAC,SAAS,CAAC;AACtH,MAAM,KAAK,GAAG,CAAC,KAAc,EAAsB,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AACxF,MAAM,MAAM,GAAG,CAAC,KAAc,EAAsB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACrG,MAAM,MAAM,GAAG,CAAC,KAAc,EAAsB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC","sourcesContent":["import OpenAI from \"openai\";\nimport { ResponsesWS } from \"openai/resources/responses/ws\";\nimport type { ResponsesClientEvent } from \"openai/resources/responses/responses\";\nimport type {\n Message, Model, ModelDelta, ModelError, ModelGeneration, ModelRequest,\n ModelResponse, ModelSteerResult, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport type { Content } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\n\nconst provider = \"openai-responses\";\nconst maxActiveResponses = 16;\nconst maxStreamIds = 32;\n\ninterface StreamEnvelope {\n type: string;\n message?: unknown;\n error?: unknown;\n code?: number;\n reason?: string;\n}\n\n/** The small part of ResponsesWS used here, injectable so the wire can be tested without a model call. */\nexport interface OpenAiResponsesConnection {\n send(event: unknown): void;\n close(): void;\n [Symbol.asyncIterator](): AsyncIterableIterator<StreamEnvelope>;\n}\n\nexport interface OpenAiResponsesOptions {\n apiKey: string;\n model: string;\n baseURL?: string;\n headers?: Readonly<Record<string, string>>;\n /** Declare function tools with OpenAI's asynchronous execution extension. */\n asyncTools?: boolean;\n /** Expose mid-generation steering. The provider remains the capability authority. */\n steering?: boolean;\n /** Injectable for tests; the default is the official SDK's ResponsesWS. */\n connect?: () => OpenAiResponsesConnection;\n}\n\nexport interface OpenAiResponsesModel extends Model {\n /** Close the reusable WebSocket and fail any generations still using it. */\n close(): void;\n}\n\ninterface ResponsesLane extends AsyncIterable<StreamEnvelope> {\n send(event: ResponsesClientEvent): void;\n /** Stop this consumer while leaving the shared transport available to other lanes. */\n cancel(): void;\n /** Release a terminal lane for reuse, or quarantine an unfinished lane. */\n release(terminal: boolean): void;\n}\n\ninterface HubLane {\n active: boolean;\n queue: EnvelopeQueue;\n}\n\nclass ResponsesHub {\n readonly #connection: OpenAiResponsesConnection;\n readonly #lanes = new Map<string, HubLane>();\n readonly #freeIds: string[] = [];\n readonly #onEnd: () => void;\n #activeResponses = 0;\n #issuedIds = 0;\n #retiring = false;\n #ended = false;\n\n constructor(connection: OpenAiResponsesConnection, onEnd: () => void) {\n this.#connection = connection;\n this.#onEnd = onEnd;\n void this.#read();\n }\n\n open(): ResponsesLane | undefined {\n if (this.#ended || this.#retiring || this.#activeResponses >= maxActiveResponses) return undefined;\n let id = this.#freeIds.pop();\n if (!id) {\n if (this.#issuedIds >= maxStreamIds) return undefined;\n id = `aglib-${crypto.randomUUID()}`;\n this.#issuedIds += 1;\n }\n const queue = new EnvelopeQueue();\n this.#lanes.set(id, { active: true, queue });\n this.#activeResponses += 1;\n let released = false;\n const release = (terminal: boolean) => {\n if (released) return;\n released = true;\n this.#release(id, terminal);\n };\n return {\n send: (event) => {\n if (event.type === \"response.create\") {\n this.#connection.send({ ...event, stream_id: id });\n } else {\n this.#connection.send(event);\n }\n },\n cancel: () => {\n queue.push({ type: \"close\", reason: \"generation cancelled\" });\n release(false);\n },\n release,\n [Symbol.asyncIterator]: () => queue[Symbol.asyncIterator](),\n };\n }\n\n retire(): void {\n if (this.#ended) return;\n this.#retiring = true;\n this.#closeWhenDrained();\n }\n\n close(): void {\n if (this.#ended) return;\n this.#finish({ type: \"close\", reason: \"Responses model closed\" });\n this.#connection.close();\n }\n\n async #read(): Promise<void> {\n try {\n for await (const envelope of this.#connection) {\n if (envelope.type === \"message\" && envelope.message) {\n const event = envelope.message as unknown as Record<string, unknown>;\n const lane = string(event[\"stream_id\"]);\n if (lane) {\n this.#lanes.get(lane)?.queue.push(envelope);\n } else if (string(event[\"type\"]) === \"error\") {\n this.#broadcast(envelope);\n } else if (this.#lanes.size === 1) {\n this.#lanes.values().next().value?.queue.push(envelope);\n } else {\n this.#finish({\n type: \"error\",\n error: new Error(\"Responses event omitted stream_id while multiple generations were active\"),\n });\n }\n continue;\n }\n if (envelope.type === \"error\" || envelope.type === \"close\") {\n this.#finish(envelope);\n return;\n }\n }\n this.#finish({ type: \"close\", reason: \"Responses WebSocket ended\" });\n } catch (error) {\n this.#finish({ type: \"error\", error });\n }\n }\n\n #broadcast(envelope: StreamEnvelope): void {\n for (const lane of this.#lanes.values()) lane.queue.push(envelope);\n }\n\n #release(id: string, terminal: boolean): void {\n const lane = this.#lanes.get(id);\n if (!lane) return;\n lane.active = false;\n this.#activeResponses -= 1;\n lane.queue.end();\n if (terminal) {\n this.#lanes.delete(id);\n this.#freeIds.push(id);\n } else {\n // An unfinished response can still emit events carrying this stream id.\n // Retire the connection rather than let those events enter another generation.\n this.#retiring = true;\n }\n this.#closeWhenDrained();\n }\n\n #closeWhenDrained(): void {\n if (this.#retiring && ![...this.#lanes.values()].some((lane) => lane.active)) this.close();\n }\n\n #finish(envelope: StreamEnvelope): void {\n if (this.#ended) return;\n this.#ended = true;\n this.#broadcast(envelope);\n for (const lane of this.#lanes.values()) lane.queue.end();\n this.#lanes.clear();\n this.#onEnd();\n }\n}\n\nclass EnvelopeQueue implements AsyncIterableIterator<StreamEnvelope> {\n readonly #values: StreamEnvelope[] = [];\n readonly #waiters: Array<(step: IteratorResult<StreamEnvelope>) => void> = [];\n #ended = false;\n\n push(value: StreamEnvelope): void {\n if (this.#ended) return;\n const waiter = this.#waiters.shift();\n if (waiter) waiter({ done: false, value });\n else this.#values.push(value);\n }\n\n end(): void {\n if (this.#ended) return;\n this.#ended = true;\n for (const waiter of this.#waiters.splice(0)) waiter({ done: true, value: undefined });\n }\n\n next(): Promise<IteratorResult<StreamEnvelope>> {\n const value = this.#values.shift();\n if (value) return Promise.resolve({ done: false, value });\n if (this.#ended) return Promise.resolve({ done: true, value: undefined });\n return new Promise((resolve) => this.#waiters.push(resolve));\n }\n\n [Symbol.asyncIterator](): AsyncIterableIterator<StreamEnvelope> { return this; }\n}\n\n/** OpenAI's Responses wire, including completed output items, async tools and optional steering. */\nexport function createOpenAiResponsesModel(options: OpenAiResponsesOptions): OpenAiResponsesModel {\n const client = new OpenAI({\n apiKey: options.apiKey,\n ...(options.baseURL ? { baseURL: options.baseURL } : {}),\n ...(options.headers ? { defaultHeaders: options.headers } : {}),\n });\n const connect = options.connect ?? (() => {\n const socket = new ResponsesWS(client);\n return {\n send(event: unknown) { socket.send(event as ResponsesClientEvent); },\n close() { socket.close(); },\n [Symbol.asyncIterator]() {\n return socket[Symbol.asyncIterator]() as AsyncIterableIterator<StreamEnvelope>;\n },\n };\n });\n const hubs = new Set<ResponsesHub>();\n let hub: ResponsesHub | undefined;\n\n const lane = () => {\n const existing = hub?.open();\n if (existing) return existing;\n hub?.retire();\n const next = new ResponsesHub(connect(), () => {\n hubs.delete(next);\n if (hub === next) hub = undefined;\n });\n hubs.add(next);\n hub = next;\n const opened = next.open();\n if (!opened) throw new Error(\"Responses WebSocket opened without an available lane\");\n return opened;\n };\n\n return {\n id: `${provider}:${options.model}`,\n ...(options.asyncTools ? { asyncTools: true as const } : {}),\n generate(request: ModelRequest): ModelGeneration {\n return generation(lane, options.model, request, options.steering === true);\n },\n close() {\n for (const openHub of [...hubs]) openHub.close();\n hub = undefined;\n },\n };\n}\n\nfunction generation(\n connect: () => ResponsesLane,\n configuredModel: string,\n request: ModelRequest,\n steering: boolean,\n): ModelGeneration {\n let connection: ResponsesLane | undefined;\n let activeResponseId: string | undefined;\n let ended = false;\n let wakeStarted!: () => void;\n const started = new Promise<void>((resolve) => { wakeStarted = resolve; });\n const steers: Steer[] = [];\n let steerTail = Promise.resolve();\n\n const iterator = (async function* (): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n if (request.signal?.aborted) {\n ended = true;\n wakeStarted();\n return err(cancelled());\n }\n\n try {\n connection = connect();\n } catch (error) {\n ended = true;\n wakeStarted();\n return err(providerError(error));\n }\n wakeStarted();\n\n const abort = () => connection?.cancel();\n request.signal?.addEventListener(\"abort\", abort, { once: true });\n\n const text: string[] = [];\n const calls = new Map<string, ToolCall>();\n const itemCalls = new Map<string, string>();\n const providerItems: JsonValue[] = [];\n const seenItems = new Set<string>();\n const itemPhases = new Map<string, \"commentary\" | \"final_answer\">();\n let usage: Usage = {};\n let servedModel: string | undefined;\n let completed: Record<string, unknown> | undefined;\n let refused = false;\n let terminal = false;\n\n try {\n connection.send(encodeRequest(configuredModel, request));\n\n for await (const envelope of connection) {\n if (envelope.type === \"error\") {\n rejectSteers(steers, providerError(envelope.error));\n return err(providerError(envelope.error));\n }\n if (envelope.type === \"close\") {\n const failure = request.signal?.aborted\n ? cancelled()\n : { code: \"provider\" as const, message: `Responses WebSocket closed${envelope.code ? ` (${envelope.code})` : \"\"}${envelope.reason ? `: ${envelope.reason}` : \"\"}`, retryable: true };\n rejectSteers(steers, failure);\n return err(failure);\n }\n if (envelope.type !== \"message\" || !envelope.message) continue;\n const event = envelope.message as unknown as Record<string, unknown>;\n const type = string(event[\"type\"]);\n\n if (type === \"error\") {\n const failure = eventError(event);\n rejectSteers(steers, failure);\n return err(failure);\n }\n\n if (type === \"response.created\") {\n const response = record(event[\"response\"]);\n const id = string(response?.[\"id\"]);\n if (id) {\n const wasActive = activeResponseId;\n activeResponseId = id;\n servedModel = string(response?.[\"model\"]) ?? servedModel;\n if (wasActive) applyNextSteer(steers, id);\n }\n continue;\n }\n\n if (type === \"response.steer.accepted\") {\n const detail = record(event[\"steer\"]);\n const waiting = steers.find((steer) => steer.sent && !steer.providerId && !steer.done);\n if (waiting) waiting.providerId = string(detail?.[\"id\"]);\n continue;\n }\n if (type === \"response.steer.failed\") {\n const detail = record(event[\"steer\"]);\n const id = string(detail?.[\"id\"]);\n const waiting = (id ? steers.find((steer) => steer.providerId === id) : undefined)\n ?? steers.find((steer) => steer.sent && !steer.done);\n waiting?.reject(eventError(event));\n continue;\n }\n if (type === \"response.steer.pending\") {\n const detail = record(event[\"steer\"]);\n const id = string(detail?.[\"id\"]);\n const waiting = steers.find((steer) => steer.providerId === id && !steer.done);\n waiting?.reject({\n code: \"failed\", retryable: true,\n message: \"Steering awaits client tool input; replay the durable input at the next model boundary\",\n });\n if (completed && noLiveSteers(steers)) {\n terminal = true;\n return finish(completed, text, calls, providerItems, usage, refused, servedModel);\n }\n continue;\n }\n\n if (type === \"response.output_text.delta\") {\n const delta = string(event[\"delta\"]);\n const phase = itemPhases.get(string(event[\"item_id\"]) ?? \"\");\n if (delta) {\n text.push(delta);\n yield { type: \"text.delta\", text: delta, ...(phase ? { phase } : {}) };\n }\n continue;\n }\n if (type === \"response.refusal.delta\" || type === \"response.refusal.done\") {\n refused = true;\n continue;\n }\n if (type === \"response.reasoning_summary_text.delta\") {\n const delta = string(event[\"delta\"]);\n if (delta) yield { type: \"reasoning.delta\", text: delta };\n continue;\n }\n if (type === \"response.output_item.added\") {\n const item = record(event[\"item\"]);\n const itemId = string(item?.[\"id\"]);\n const phase = outputPhase(item?.[\"phase\"]);\n if (itemId && phase) itemPhases.set(itemId, phase);\n if (item?.[\"type\"] === \"function_call\") {\n const callId = string(item[\"call_id\"]);\n if (itemId && callId) itemCalls.set(itemId, callId);\n }\n continue;\n }\n if (type === \"response.function_call_arguments.delta\") {\n const callId = itemCalls.get(string(event[\"item_id\"]) ?? \"\");\n const delta = string(event[\"delta\"]);\n if (callId && delta) yield { type: \"tool-call.delta\", callId, arguments: delta };\n continue;\n }\n if (type === \"response.output_item.done\") {\n const item = record(event[\"item\"]);\n if (item) appendItem(providerItems, seenItems, item);\n const call = decodeCall(item);\n if (call && !calls.has(call.callId)) {\n calls.set(call.callId, call);\n yield { type: \"tool-call.done\", call };\n }\n continue;\n }\n\n if (type === \"response.completed\") {\n const response = record(event[\"response\"]);\n if (!response) return err({ code: \"provider\", message: \"Responses completion omitted its response\", retryable: true });\n completed = response;\n servedModel = string(response[\"model\"]) ?? servedModel;\n refused ||= hasRefusal(response);\n usage = addUsage(usage, decodeUsage(record(response[\"usage\"])));\n for (const item of array(response[\"output\"])) {\n const value = record(item);\n if (!value) continue;\n appendItem(providerItems, seenItems, value);\n const call = decodeCall(value);\n if (call && !calls.has(call.callId)) {\n calls.set(call.callId, call);\n yield { type: \"tool-call.done\", call };\n }\n }\n\n const blocking = [...calls.values()].some((call) => call.async !== true);\n if (blocking) {\n rejectSteers(steers, {\n code: \"failed\", retryable: true,\n message: \"Steering did not reach a successor before client tool input became required\",\n });\n terminal = true;\n return finish(response, text, calls, providerItems, usage, refused, servedModel);\n }\n if (noLiveSteers(steers)) {\n terminal = true;\n return finish(response, text, calls, providerItems, usage, refused, servedModel);\n }\n continue;\n }\n\n if (type === \"response.incomplete\") {\n const response = record(event[\"response\"]);\n if (!response) return err({ code: \"provider\", message: \"Incomplete event omitted its response\", retryable: true });\n for (const item of array(response[\"output\"])) {\n const value = record(item);\n if (value) appendItem(providerItems, seenItems, value);\n }\n usage = addUsage(usage, decodeUsage(record(response[\"usage\"])));\n if (record(response[\"incomplete_details\"])?.[\"reason\"] === \"steered\") continue;\n rejectSteers(steers, { code: \"failed\", message: \"Response ended incomplete\", retryable: true });\n terminal = true;\n return finish(response, text, calls, providerItems, usage, refused || hasRefusal(response), servedModel);\n }\n\n if (type === \"response.failed\") {\n const failure = responseFailure(record(event[\"response\"]));\n rejectSteers(steers, failure);\n terminal = true;\n return err(failure);\n }\n }\n\n const failure = request.signal?.aborted ? cancelled() : {\n code: \"provider\" as const, message: \"Responses WebSocket ended before completion\", retryable: true,\n };\n rejectSteers(steers, failure);\n return err(failure);\n } catch (error) {\n const failure = request.signal?.aborted ? cancelled() : providerError(error);\n rejectSteers(steers, failure);\n return err(failure);\n } finally {\n ended = true;\n request.signal?.removeEventListener(\"abort\", abort);\n connection.release(terminal);\n rejectSteers(steers, {\n code: \"failed\", message: \"Generation ended before steering reached a successor\", retryable: true,\n });\n }\n })();\n\n const steer = async (input: readonly Message[]): Promise<ModelSteerResult> => {\n await started;\n if (ended || !connection || !activeResponseId) {\n return { status: \"rejected\", error: { code: \"failed\", message: \"No active response to steer\", retryable: true } };\n }\n const encoded = encodeSteer(input);\n if (!encoded.ok) return { status: \"rejected\", error: encoded.error };\n\n let release!: () => void;\n const before = steerTail;\n steerTail = new Promise<void>((resolve) => { release = resolve; });\n await before;\n if (ended || !connection || !activeResponseId) {\n release();\n return { status: \"rejected\", error: { code: \"failed\", message: \"No active response to steer\", retryable: true } };\n }\n\n const pending = createSteer(release);\n steers.push(pending);\n pending.sent = true;\n connection.send({\n type: \"response.steer\",\n previous_response_id: activeResponseId,\n input: encoded.value,\n } as ResponsesClientEvent);\n return pending.promise;\n };\n\n return steering ? Object.assign(iterator, { steer }) : iterator;\n}\n\ninterface Steer {\n sent: boolean;\n done: boolean;\n providerId?: string;\n promise: Promise<ModelSteerResult>;\n accept(responseId: string): void;\n reject(error: ModelError): void;\n}\n\nfunction createSteer(release: () => void): Steer {\n let resolve!: (result: ModelSteerResult) => void;\n const promise = new Promise<ModelSteerResult>((done) => { resolve = done; });\n const steer: Steer = {\n sent: false, done: false, promise,\n accept(responseId) {\n if (steer.done) return;\n steer.done = true;\n release();\n resolve({ status: \"accepted\", id: responseId });\n },\n reject(error) {\n if (steer.done) return;\n steer.done = true;\n release();\n resolve({ status: \"rejected\", error });\n },\n };\n return steer;\n}\n\nfunction applyNextSteer(steers: readonly Steer[], responseId: string): void {\n steers.find((steer) => steer.providerId && !steer.done)?.accept(responseId);\n}\n\nconst noLiveSteers = (steers: readonly Steer[]) => !steers.some((steer) => steer.sent && !steer.done);\n\nfunction rejectSteers(steers: readonly Steer[], error: ModelError): void {\n for (const steer of steers) steer.reject(error);\n}\n\nfunction encodeRequest(model: string, request: ModelRequest): ResponsesClientEvent {\n return {\n type: \"response.create\",\n model,\n store: false,\n include: [\"reasoning.encrypted_content\"],\n input: encodeMessages(request.messages),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.maxOutputTokens !== undefined ? { max_output_tokens: request.maxOutputTokens } : {}),\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...(request.effort ? { reasoning: { effort: request.effort, summary: \"auto\" } } : {}),\n } as ResponsesClientEvent;\n}\n\nfunction encodeMessages(messages: readonly Message[]): unknown[] {\n const input: unknown[] = [];\n const calls = new Set<string>();\n const providerCalls = new Set(messages.flatMap((message) =>\n message.role === \"assistant\" && message.providerState?.provider === provider\n ? message.providerState.items.flatMap((item) => {\n const value = record(item);\n const callId = value?.[\"type\"] === \"function_call\" ? string(value[\"call_id\"]) : undefined;\n return callId ? [callId] : [];\n })\n : []));\n const reachedProviderCall = new Set<string>();\n const deferredResults = new Map<string, unknown[]>();\n\n for (const message of messages) {\n if (message.role === \"assistant\" && message.providerState?.provider === provider) {\n const represented: string[] = [];\n for (const item of message.providerState.items) {\n const value = record(item);\n const callId = value?.[\"type\"] === \"function_call\" ? string(value[\"call_id\"]) : undefined;\n if (callId && calls.has(callId)) continue;\n if (callId) {\n calls.add(callId);\n reachedProviderCall.add(callId);\n represented.push(callId);\n }\n input.push(item);\n }\n // A fast async tool can finish before the response that launched it has\n // completed. The log keeps that chronology. The provider continuation\n // still requires its whole output before any result that answers it.\n for (const callId of represented) {\n input.push(...(deferredResults.get(callId) ?? []));\n deferredResults.delete(callId);\n }\n continue;\n }\n if (message.role === \"tool\") {\n const output = {\n type: \"function_call_output\", call_id: message.callId,\n output: encodeToolOutput(message.content),\n };\n if (providerCalls.has(message.callId) && !reachedProviderCall.has(message.callId)) {\n const waiting = deferredResults.get(message.callId) ?? [];\n waiting.push(output);\n deferredResults.set(message.callId, waiting);\n } else {\n input.push(output);\n }\n continue;\n }\n const role = message.role === \"system\" ? \"developer\" : message.role;\n if (message.content.length) {\n input.push({ type: \"message\", role, content: encodeContent(message.content, role === \"assistant\") });\n }\n if (message.role === \"assistant\") {\n for (const call of message.calls ?? []) {\n if (providerCalls.has(call.callId)) continue;\n if (calls.has(call.callId)) continue;\n calls.add(call.callId);\n input.push({\n type: \"function_call\", call_id: call.callId, name: call.name, arguments: call.arguments,\n ...(call.async ? { async: true } : {}),\n });\n }\n }\n }\n for (const outputs of deferredResults.values()) input.push(...outputs);\n return input;\n}\n\nfunction encodeSteer(messages: readonly Message[]): Result<unknown[], ModelError> {\n if (!messages.length || messages.some((message) => message.role !== \"user\")) {\n return err({ code: \"failed\", message: \"Responses steering accepts one or more user messages only\", retryable: false });\n }\n return ok(messages.map((message) => ({\n type: \"message\", role: \"user\", content: encodeContent(message.content, false),\n })));\n}\n\nfunction encodeContent(content: Content, output: boolean): unknown {\n if (typeof content === \"string\") return content;\n const parts: unknown[] = [];\n for (const part of content) {\n if (part.type === \"text\") {\n parts.push({ type: output ? \"output_text\" : \"input_text\", text: part.text });\n continue;\n }\n if (part.type === \"image\" && !output) {\n parts.push({\n type: \"input_image\",\n image_url: part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`,\n });\n continue;\n }\n if (part.type === \"file\" && !output) {\n parts.push(part.source.kind === \"url\"\n ? { type: \"input_file\", file_url: part.source.url }\n : { type: \"input_file\", file_data: part.source.data, ...(part.name ? { filename: part.name } : {}) });\n continue;\n }\n if (part.type === \"opaque\" && part.provider === provider) parts.push(part.data);\n }\n return parts;\n}\n\nfunction encodeToolOutput(content: Content): unknown {\n if (typeof content === \"string\") return content;\n return encodeContent(content, false);\n}\n\nconst encodeTool = (tool: ToolSpec) => ({\n type: \"function\" as const,\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n strict: false,\n ...(tool.async === true ? { async: true } : {}),\n});\n\nfunction decodeCall(item: Record<string, unknown> | undefined): ToolCall | undefined {\n if (!item || item[\"type\"] !== \"function_call\") return undefined;\n const callId = string(item[\"call_id\"]);\n const name = string(item[\"name\"]);\n if (!callId || !name) return undefined;\n return {\n callId,\n name,\n arguments: string(item[\"arguments\"]) || \"{}\",\n ...(item[\"async\"] === true ? { async: true } : {}),\n };\n}\n\nfunction finish(\n response: Record<string, unknown>,\n text: readonly string[],\n calls: ReadonlyMap<string, ToolCall>,\n providerItems: readonly JsonValue[],\n usage: Usage,\n refused: boolean,\n servedModel?: string,\n): Result<ModelResponse, ModelError> {\n const collected = [...calls.values()];\n const reason = string(record(response[\"incomplete_details\"])?.[\"reason\"]);\n const finishReason: ModelResponse[\"finishReason\"] =\n reason === \"max_output_tokens\" ? \"length\"\n : reason === \"content_filter\" || refused ? \"refusal\"\n : collected.some((call) => call.async !== true) ? \"tool-calls\"\n : \"stop\";\n return ok({\n message: { content: text.join(\"\"), ...(collected.length ? { calls: collected } : {}) },\n finishReason,\n usage,\n ...(servedModel ? { model: servedModel } : {}),\n ...(providerItems.length ? { providerState: { provider, items: providerItems } } : {}),\n });\n}\n\nfunction hasRefusal(response: Record<string, unknown>): boolean {\n return array(response[\"output\"]).some((item) =>\n array(record(item)?.[\"content\"]).some((part) => record(part)?.[\"type\"] === \"refusal\"));\n}\n\nfunction appendItem(target: JsonValue[], seen: Set<string>, item: Record<string, unknown>): void {\n const id = string(item[\"id\"]);\n if (id && seen.has(id)) return;\n if (id) seen.add(id);\n target.push(JSON.parse(JSON.stringify(item)) as JsonValue);\n}\n\nfunction decodeUsage(value: Record<string, unknown> | undefined): Usage {\n if (!value) return {};\n const details = record(value[\"input_tokens_details\"]);\n const input = number(value[\"input_tokens\"]);\n const cached = number(details?.[\"cached_tokens\"]);\n const written = number(details?.[\"cache_write_tokens\"]);\n return {\n ...(input !== undefined ? { inputTokens: Math.max(input - (cached ?? 0) - (written ?? 0), 0) } : {}),\n ...(cached !== undefined ? { cacheReadTokens: cached } : {}),\n ...(written !== undefined ? { cacheWriteTokens: written } : {}),\n ...(number(value[\"output_tokens\"]) !== undefined ? { outputTokens: number(value[\"output_tokens\"]) } : {}),\n };\n}\n\nfunction addUsage(left: Usage, right: Usage): Usage {\n const total: Usage = {};\n for (const key of [\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\", \"costUsd\"] as const) {\n const a = left[key];\n const b = right[key];\n if (a !== undefined || b !== undefined) total[key] = (a ?? 0) + (b ?? 0);\n }\n return total;\n}\n\nfunction responseFailure(response: Record<string, unknown> | undefined): ModelError {\n const error = record(response?.[\"error\"]);\n return {\n code: \"provider\",\n message: string(error?.[\"message\"]) ?? \"Responses generation failed\",\n retryable: true,\n };\n}\n\nfunction eventError(event: Record<string, unknown>): ModelError {\n const error = record(event[\"error\"]);\n const code = string(error?.[\"code\"]);\n return {\n code: code === \"rate_limit_exceeded\" ? \"rate-limit\" : \"failed\",\n message: string(error?.[\"message\"]) ?? \"Responses command failed\",\n retryable: code === \"rate_limit_exceeded\" || code === \"server_error\" || code === \"response_not_found\",\n };\n}\n\nfunction providerError(error: unknown): ModelError {\n const message = error instanceof Error ? error.message : String(error ?? \"Responses transport failed\");\n return { code: \"provider\", message, retryable: true };\n}\n\nconst cancelled = (): ModelError => ({ code: \"cancelled\", message: \"Generation cancelled\", retryable: false });\nconst outputPhase = (value: unknown): \"commentary\" | \"final_answer\" | undefined =>\n value === \"commentary\" || value === \"final_answer\" ? value : undefined;\nconst record = (value: unknown): Record<string, unknown> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;\nconst array = (value: unknown): readonly unknown[] => Array.isArray(value) ? value : [];\nconst string = (value: unknown): string | undefined => typeof value === \"string\" ? value : undefined;\nconst number = (value: unknown): number | undefined => typeof value === \"number\" ? value : undefined;\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/openai-responses/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAQ5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAE1D,MAAM,QAAQ,GAAG,kBAAkB,CAAC;AACpC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,YAAY,GAAG,EAAE,CAAC;AAgDxB,MAAM,YAAY;IACP,WAAW,CAA4B;IACvC,MAAM,GAAG,IAAI,GAAG,EAAmB,CAAC;IACpC,QAAQ,GAAa,EAAE,CAAC;IACxB,MAAM,CAAa;IAC5B,gBAAgB,GAAG,CAAC,CAAC;IACrB,UAAU,GAAG,CAAC,CAAC;IACf,SAAS,GAAG,KAAK,CAAC;IAClB,MAAM,GAAG,KAAK,CAAC;IAEf,YAAY,UAAqC,EAAE,KAAiB;QAClE,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;QAC9B,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,KAAK,IAAI,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IAED,IAAI;QACF,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,gBAAgB,IAAI,kBAAkB;YAAE,OAAO,SAAS,CAAC;QACnG,IAAI,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC;QAC7B,IAAI,CAAC,EAAE,EAAE,CAAC;YACR,IAAI,IAAI,CAAC,UAAU,IAAI,YAAY;gBAAE,OAAO,SAAS,CAAC;YACtD,EAAE,GAAG,SAAS,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC;YACpC,IAAI,CAAC,UAAU,IAAI,CAAC,CAAC;QACvB,CAAC;QAC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AAsB,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AACxF,MAAM,MAAM,GAAG,CAAC,KAAc,EAAsB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACrG,MAAM,MAAM,GAAG,CAAC,KAAc,EAAsB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC","sourcesContent":["import OpenAI from \"openai\";\nimport { ResponsesWS } from \"openai/resources/responses/ws\";\nimport type { ResponsesClientEvent } from \"openai/resources/responses/responses\";\nimport type {\n Message, Model, ModelDelta, ModelError, ModelGeneration, ModelRequest,\n ModelResponse, ModelSteerResult, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport type { Content } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\n\nconst provider = \"openai-responses\";\nconst maxActiveResponses = 16;\nconst maxStreamIds = 32;\n\ninterface StreamEnvelope {\n type: string;\n message?: unknown;\n error?: unknown;\n code?: number;\n reason?: string;\n}\n\n/** The small part of ResponsesWS used here, injectable so the wire can be tested without a model call. */\nexport interface OpenAiResponsesConnection {\n send(event: unknown): void;\n close(): void;\n [Symbol.asyncIterator](): AsyncIterableIterator<StreamEnvelope>;\n}\n\nexport interface OpenAiResponsesOptions {\n apiKey: string;\n model: string;\n baseURL?: string;\n headers?: Readonly<Record<string, string>>;\n /** Declare function tools with OpenAI's asynchronous execution extension. */\n asyncTools?: boolean;\n /** Expose mid-generation steering. The provider remains the capability authority. */\n steering?: boolean;\n /** Injectable for tests; the default is the official SDK's ResponsesWS. */\n connect?: () => OpenAiResponsesConnection;\n}\n\nexport interface OpenAiResponsesModel extends Model {\n /** Close the reusable WebSocket and fail any generations still using it. */\n close(): void;\n}\n\ninterface ResponsesLane extends AsyncIterable<StreamEnvelope> {\n send(event: ResponsesClientEvent): void;\n /** Stop this consumer while leaving the shared transport available to other lanes. */\n cancel(): void;\n /** Release a terminal lane for reuse, or quarantine an unfinished lane. */\n release(terminal: boolean): void;\n}\n\ninterface HubLane {\n active: boolean;\n queue: EnvelopeQueue;\n}\n\nclass ResponsesHub {\n readonly #connection: OpenAiResponsesConnection;\n readonly #lanes = new Map<string, HubLane>();\n readonly #freeIds: string[] = [];\n readonly #onEnd: () => void;\n #activeResponses = 0;\n #issuedIds = 0;\n #retiring = false;\n #ended = false;\n\n constructor(connection: OpenAiResponsesConnection, onEnd: () => void) {\n this.#connection = connection;\n this.#onEnd = onEnd;\n void this.#read();\n }\n\n open(): ResponsesLane | undefined {\n if (this.#ended || this.#retiring || this.#activeResponses >= maxActiveResponses) return undefined;\n let id = this.#freeIds.pop();\n if (!id) {\n if (this.#issuedIds >= maxStreamIds) return undefined;\n id = `aglib-${crypto.randomUUID()}`;\n this.#issuedIds += 1;\n }\n const queue = new EnvelopeQueue();\n this.#lanes.set(id, { active: true, queue });\n this.#activeResponses += 1;\n let released = false;\n const release = (terminal: boolean) => {\n if (released) return;\n released = true;\n this.#release(id, terminal);\n };\n return {\n send: (event) => {\n if (event.type === \"response.create\") {\n this.#connection.send({ ...event, stream_id: id });\n } else {\n this.#connection.send(event);\n }\n },\n cancel: () => {\n queue.push({ type: \"close\", reason: \"generation cancelled\" });\n release(false);\n },\n release,\n [Symbol.asyncIterator]: () => queue[Symbol.asyncIterator](),\n };\n }\n\n retire(): void {\n if (this.#ended) return;\n this.#retiring = true;\n this.#closeWhenDrained();\n }\n\n close(): void {\n if (this.#ended) return;\n this.#finish({ type: \"close\", reason: \"Responses model closed\" });\n this.#connection.close();\n }\n\n async #read(): Promise<void> {\n try {\n for await (const envelope of this.#connection) {\n if (envelope.type === \"message\" && envelope.message) {\n const event = envelope.message as unknown as Record<string, unknown>;\n const lane = string(event[\"stream_id\"]);\n if (lane) {\n this.#lanes.get(lane)?.queue.push(envelope);\n } else if (string(event[\"type\"]) === \"error\") {\n this.#broadcast(envelope);\n } else if (this.#lanes.size === 1) {\n this.#lanes.values().next().value?.queue.push(envelope);\n } else {\n this.#finish({\n type: \"error\",\n error: new Error(\"Responses event omitted stream_id while multiple generations were active\"),\n });\n }\n continue;\n }\n if (envelope.type === \"error\" || envelope.type === \"close\") {\n this.#finish(envelope);\n return;\n }\n }\n this.#finish({ type: \"close\", reason: \"Responses WebSocket ended\" });\n } catch (error) {\n this.#finish({ type: \"error\", error });\n }\n }\n\n #broadcast(envelope: StreamEnvelope): void {\n for (const lane of this.#lanes.values()) lane.queue.push(envelope);\n }\n\n #release(id: string, terminal: boolean): void {\n const lane = this.#lanes.get(id);\n if (!lane) return;\n lane.active = false;\n this.#activeResponses -= 1;\n lane.queue.end();\n if (terminal) {\n this.#lanes.delete(id);\n this.#freeIds.push(id);\n } else {\n // An unfinished response can still emit events carrying this stream id.\n // Retire the connection rather than let those events enter another generation.\n this.#retiring = true;\n }\n this.#closeWhenDrained();\n }\n\n #closeWhenDrained(): void {\n if (this.#retiring && ![...this.#lanes.values()].some((lane) => lane.active)) this.close();\n }\n\n #finish(envelope: StreamEnvelope): void {\n if (this.#ended) return;\n this.#ended = true;\n this.#broadcast(envelope);\n for (const lane of this.#lanes.values()) lane.queue.end();\n this.#lanes.clear();\n this.#onEnd();\n }\n}\n\nclass EnvelopeQueue implements AsyncIterableIterator<StreamEnvelope> {\n readonly #values: StreamEnvelope[] = [];\n readonly #waiters: Array<(step: IteratorResult<StreamEnvelope>) => void> = [];\n #ended = false;\n\n push(value: StreamEnvelope): void {\n if (this.#ended) return;\n const waiter = this.#waiters.shift();\n if (waiter) waiter({ done: false, value });\n else this.#values.push(value);\n }\n\n end(): void {\n if (this.#ended) return;\n this.#ended = true;\n for (const waiter of this.#waiters.splice(0)) waiter({ done: true, value: undefined });\n }\n\n next(): Promise<IteratorResult<StreamEnvelope>> {\n const value = this.#values.shift();\n if (value) return Promise.resolve({ done: false, value });\n if (this.#ended) return Promise.resolve({ done: true, value: undefined });\n return new Promise((resolve) => this.#waiters.push(resolve));\n }\n\n [Symbol.asyncIterator](): AsyncIterableIterator<StreamEnvelope> { return this; }\n}\n\n/** OpenAI's Responses wire, including completed output items, async tools and optional steering. */\nexport function createOpenAiResponsesModel(options: OpenAiResponsesOptions): OpenAiResponsesModel {\n const client = new OpenAI({\n apiKey: options.apiKey,\n ...(options.baseURL ? { baseURL: options.baseURL } : {}),\n ...(options.headers ? { defaultHeaders: options.headers } : {}),\n });\n const connect = options.connect ?? (() => {\n const socket = new ResponsesWS(client);\n return {\n send(event: unknown) { socket.send(event as ResponsesClientEvent); },\n close() { socket.close(); },\n [Symbol.asyncIterator]() {\n return socket[Symbol.asyncIterator]() as AsyncIterableIterator<StreamEnvelope>;\n },\n };\n });\n const hubs = new Set<ResponsesHub>();\n let hub: ResponsesHub | undefined;\n\n const lane = () => {\n const existing = hub?.open();\n if (existing) return existing;\n hub?.retire();\n const next = new ResponsesHub(connect(), () => {\n hubs.delete(next);\n if (hub === next) hub = undefined;\n });\n hubs.add(next);\n hub = next;\n const opened = next.open();\n if (!opened) throw new Error(\"Responses WebSocket opened without an available lane\");\n return opened;\n };\n\n return {\n id: `${provider}:${options.model}`,\n ...(options.asyncTools ? { asyncTools: true as const } : {}),\n generate(request: ModelRequest): ModelGeneration {\n return generation(lane, options.model, request, options.steering === true);\n },\n close() {\n for (const openHub of [...hubs]) openHub.close();\n hub = undefined;\n },\n };\n}\n\nfunction generation(\n connect: () => ResponsesLane,\n configuredModel: string,\n request: ModelRequest,\n steering: boolean,\n): ModelGeneration {\n let connection: ResponsesLane | undefined;\n let activeResponseId: string | undefined;\n let ended = false;\n let wakeStarted!: () => void;\n const started = new Promise<void>((resolve) => { wakeStarted = resolve; });\n const steers: Steer[] = [];\n let steerTail = Promise.resolve();\n\n const iterator = (async function* (): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n if (request.signal?.aborted) {\n ended = true;\n wakeStarted();\n return err(cancelled());\n }\n\n try {\n connection = connect();\n } catch (error) {\n ended = true;\n wakeStarted();\n return err(providerError(error));\n }\n wakeStarted();\n\n const abort = () => connection?.cancel();\n request.signal?.addEventListener(\"abort\", abort, { once: true });\n\n const text: string[] = [];\n const calls = new Map<string, ToolCall>();\n const itemCalls = new Map<string, string>();\n const providerItems: JsonValue[] = [];\n const seenItems = new Set<string>();\n const itemPhases = new Map<string, \"commentary\" | \"final_answer\">();\n let usage: Usage = {};\n let servedModel: string | undefined;\n let completed: Record<string, unknown> | undefined;\n let refused = false;\n let terminal = false;\n\n try {\n connection.send(encodeRequest(configuredModel, request));\n\n for await (const envelope of connection) {\n if (envelope.type === \"error\") {\n rejectSteers(steers, providerError(envelope.error));\n return err(providerError(envelope.error));\n }\n if (envelope.type === \"close\") {\n const failure = request.signal?.aborted\n ? cancelled()\n : { code: \"provider\" as const, message: `Responses WebSocket closed${envelope.code ? ` (${envelope.code})` : \"\"}${envelope.reason ? `: ${envelope.reason}` : \"\"}`, retryable: true };\n rejectSteers(steers, failure);\n return err(failure);\n }\n if (envelope.type !== \"message\" || !envelope.message) continue;\n const event = envelope.message as unknown as Record<string, unknown>;\n const type = string(event[\"type\"]);\n\n if (type === \"error\") {\n const failure = eventError(event);\n rejectSteers(steers, failure);\n return err(failure);\n }\n\n if (type === \"response.created\") {\n const response = record(event[\"response\"]);\n const id = string(response?.[\"id\"]);\n if (id) {\n const wasActive = activeResponseId;\n activeResponseId = id;\n servedModel = string(response?.[\"model\"]) ?? servedModel;\n if (wasActive) applyNextSteer(steers, id);\n }\n continue;\n }\n\n if (type === \"response.steer.accepted\") {\n const detail = record(event[\"steer\"]);\n const waiting = steers.find((steer) => steer.sent && !steer.providerId && !steer.done);\n if (waiting) waiting.providerId = string(detail?.[\"id\"]);\n continue;\n }\n if (type === \"response.steer.failed\") {\n const detail = record(event[\"steer\"]);\n const id = string(detail?.[\"id\"]);\n const waiting = (id ? steers.find((steer) => steer.providerId === id) : undefined)\n ?? steers.find((steer) => steer.sent && !steer.done);\n waiting?.reject(eventError(event));\n continue;\n }\n if (type === \"response.steer.pending\") {\n const detail = record(event[\"steer\"]);\n const id = string(detail?.[\"id\"]);\n const waiting = steers.find((steer) => steer.providerId === id && !steer.done);\n waiting?.reject({\n code: \"failed\", retryable: true,\n message: \"Steering awaits client tool input; replay the durable input at the next model boundary\",\n });\n if (completed && noLiveSteers(steers)) {\n terminal = true;\n return finish(completed, text, calls, providerItems, usage, refused, servedModel);\n }\n continue;\n }\n\n if (type === \"response.output_text.delta\") {\n const delta = string(event[\"delta\"]);\n const phase = itemPhases.get(string(event[\"item_id\"]) ?? \"\");\n if (delta) {\n text.push(delta);\n yield { type: \"text.delta\", text: delta, ...(phase ? { phase } : {}) };\n }\n continue;\n }\n if (type === \"response.refusal.delta\" || type === \"response.refusal.done\") {\n refused = true;\n continue;\n }\n if (type === \"response.reasoning_summary_text.delta\") {\n const delta = string(event[\"delta\"]);\n if (delta) yield { type: \"reasoning.delta\", text: delta };\n continue;\n }\n if (type === \"response.output_item.added\") {\n const item = record(event[\"item\"]);\n const itemId = string(item?.[\"id\"]);\n const phase = outputPhase(item?.[\"phase\"]);\n if (itemId && phase) itemPhases.set(itemId, phase);\n if (item?.[\"type\"] === \"function_call\") {\n const callId = string(item[\"call_id\"]);\n if (itemId && callId) itemCalls.set(itemId, callId);\n }\n continue;\n }\n if (type === \"response.function_call_arguments.delta\") {\n const callId = itemCalls.get(string(event[\"item_id\"]) ?? \"\");\n const delta = string(event[\"delta\"]);\n if (callId && delta) yield { type: \"tool-call.delta\", callId, arguments: delta };\n continue;\n }\n if (type === \"response.output_item.done\") {\n const item = record(event[\"item\"]);\n if (item) appendItem(providerItems, seenItems, item);\n const call = decodeCall(item);\n if (call && !calls.has(call.callId)) {\n calls.set(call.callId, call);\n yield { type: \"tool-call.done\", call };\n }\n continue;\n }\n\n if (type === \"response.completed\") {\n const response = record(event[\"response\"]);\n if (!response) return err({ code: \"provider\", message: \"Responses completion omitted its response\", retryable: true });\n completed = response;\n servedModel = string(response[\"model\"]) ?? servedModel;\n refused ||= hasRefusal(response);\n usage = addUsage(usage, decodeUsage(record(response[\"usage\"])));\n for (const item of array(response[\"output\"])) {\n const value = record(item);\n if (!value) continue;\n appendItem(providerItems, seenItems, value);\n const call = decodeCall(value);\n if (call && !calls.has(call.callId)) {\n calls.set(call.callId, call);\n yield { type: \"tool-call.done\", call };\n }\n }\n\n const blocking = [...calls.values()].some((call) => call.async !== true);\n if (blocking) {\n rejectSteers(steers, {\n code: \"failed\", retryable: true,\n message: \"Steering did not reach a successor before client tool input became required\",\n });\n terminal = true;\n return finish(response, text, calls, providerItems, usage, refused, servedModel);\n }\n if (noLiveSteers(steers)) {\n terminal = true;\n return finish(response, text, calls, providerItems, usage, refused, servedModel);\n }\n continue;\n }\n\n if (type === \"response.incomplete\") {\n const response = record(event[\"response\"]);\n if (!response) return err({ code: \"provider\", message: \"Incomplete event omitted its response\", retryable: true });\n for (const item of array(response[\"output\"])) {\n const value = record(item);\n if (value) appendItem(providerItems, seenItems, value);\n }\n usage = addUsage(usage, decodeUsage(record(response[\"usage\"])));\n if (record(response[\"incomplete_details\"])?.[\"reason\"] === \"steered\") continue;\n rejectSteers(steers, { code: \"failed\", message: \"Response ended incomplete\", retryable: true });\n terminal = true;\n return finish(response, text, calls, providerItems, usage, refused || hasRefusal(response), servedModel);\n }\n\n if (type === \"response.failed\") {\n const failure = responseFailure(record(event[\"response\"]));\n rejectSteers(steers, failure);\n terminal = true;\n return err(failure);\n }\n }\n\n const failure = request.signal?.aborted ? cancelled() : {\n code: \"provider\" as const, message: \"Responses WebSocket ended before completion\", retryable: true,\n };\n rejectSteers(steers, failure);\n return err(failure);\n } catch (error) {\n const failure = request.signal?.aborted ? cancelled() : providerError(error);\n rejectSteers(steers, failure);\n return err(failure);\n } finally {\n ended = true;\n request.signal?.removeEventListener(\"abort\", abort);\n connection.release(terminal);\n rejectSteers(steers, {\n code: \"failed\", message: \"Generation ended before steering reached a successor\", retryable: true,\n });\n }\n })();\n\n const steer = async (input: readonly Message[]): Promise<ModelSteerResult> => {\n await started;\n if (ended || !connection || !activeResponseId) {\n return { status: \"rejected\", error: { code: \"failed\", message: \"No active response to steer\", retryable: true } };\n }\n const encoded = encodeSteer(input);\n if (!encoded.ok) return { status: \"rejected\", error: encoded.error };\n\n let release!: () => void;\n const before = steerTail;\n steerTail = new Promise<void>((resolve) => { release = resolve; });\n await before;\n if (ended || !connection || !activeResponseId) {\n release();\n return { status: \"rejected\", error: { code: \"failed\", message: \"No active response to steer\", retryable: true } };\n }\n\n const pending = createSteer(release);\n steers.push(pending);\n pending.sent = true;\n connection.send({\n type: \"response.steer\",\n previous_response_id: activeResponseId,\n input: encoded.value,\n } as ResponsesClientEvent);\n return pending.promise;\n };\n\n return steering ? Object.assign(iterator, { steer }) : iterator;\n}\n\ninterface Steer {\n sent: boolean;\n done: boolean;\n providerId?: string;\n promise: Promise<ModelSteerResult>;\n accept(responseId: string): void;\n reject(error: ModelError): void;\n}\n\nfunction createSteer(release: () => void): Steer {\n let resolve!: (result: ModelSteerResult) => void;\n const promise = new Promise<ModelSteerResult>((done) => { resolve = done; });\n const steer: Steer = {\n sent: false, done: false, promise,\n accept(responseId) {\n if (steer.done) return;\n steer.done = true;\n release();\n resolve({ status: \"accepted\", id: responseId });\n },\n reject(error) {\n if (steer.done) return;\n steer.done = true;\n release();\n resolve({ status: \"rejected\", error });\n },\n };\n return steer;\n}\n\nfunction applyNextSteer(steers: readonly Steer[], responseId: string): void {\n steers.find((steer) => steer.providerId && !steer.done)?.accept(responseId);\n}\n\nconst noLiveSteers = (steers: readonly Steer[]) => !steers.some((steer) => steer.sent && !steer.done);\n\nfunction rejectSteers(steers: readonly Steer[], error: ModelError): void {\n for (const steer of steers) steer.reject(error);\n}\n\nfunction encodeRequest(model: string, request: ModelRequest): ResponsesClientEvent {\n return {\n type: \"response.create\",\n model,\n store: false,\n include: [\"reasoning.encrypted_content\"],\n input: encodeMessages(request.messages),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.maxOutputTokens !== undefined ? { max_output_tokens: request.maxOutputTokens } : {}),\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...(request.effort ? { reasoning: { effort: request.effort, summary: \"auto\" } } : {}),\n } as ResponsesClientEvent;\n}\n\nfunction encodeMessages(messages: readonly Message[]): unknown[] {\n const input: unknown[] = [];\n const calls = new Set<string>();\n const providerCalls = new Set(messages.flatMap((message) =>\n message.role === \"assistant\" && message.providerState?.provider === provider\n ? message.providerState.items.flatMap((item) => {\n const value = record(item);\n const callId = value?.[\"type\"] === \"function_call\" ? string(value[\"call_id\"]) : undefined;\n return callId ? [callId] : [];\n })\n : []));\n const reachedProviderCall = new Set<string>();\n const deferredResults = new Map<string, unknown[]>();\n\n for (const message of messages) {\n if (message.role === \"assistant\" && message.providerState?.provider === provider) {\n const represented: string[] = [];\n for (const item of message.providerState.items) {\n const value = record(item);\n const callId = value?.[\"type\"] === \"function_call\" ? string(value[\"call_id\"]) : undefined;\n if (callId && calls.has(callId)) continue;\n if (callId) {\n calls.add(callId);\n reachedProviderCall.add(callId);\n represented.push(callId);\n }\n input.push(item);\n }\n // A fast async tool can finish before the response that launched it has\n // completed. The log keeps that chronology. The provider continuation\n // still requires its whole output before any result that answers it.\n for (const callId of represented) {\n input.push(...(deferredResults.get(callId) ?? []));\n deferredResults.delete(callId);\n }\n continue;\n }\n if (message.role === \"tool\") {\n const output = {\n type: \"function_call_output\", call_id: message.callId,\n output: encodeToolOutput(message.content),\n };\n if (providerCalls.has(message.callId) && !reachedProviderCall.has(message.callId)) {\n const waiting = deferredResults.get(message.callId) ?? [];\n waiting.push(output);\n deferredResults.set(message.callId, waiting);\n } else {\n input.push(output);\n }\n continue;\n }\n const role = message.role === \"system\" ? \"developer\" : message.role;\n if (message.content.length) {\n input.push({ type: \"message\", role, content: encodeContent(message.content, role === \"assistant\") });\n }\n if (message.role === \"assistant\") {\n for (const call of message.calls ?? []) {\n if (providerCalls.has(call.callId)) continue;\n if (calls.has(call.callId)) continue;\n calls.add(call.callId);\n input.push({\n type: \"function_call\", call_id: call.callId, name: call.name, arguments: call.arguments,\n ...(call.async ? { async: true } : {}),\n });\n }\n }\n }\n for (const outputs of deferredResults.values()) input.push(...outputs);\n return input;\n}\n\nfunction encodeSteer(messages: readonly Message[]): Result<unknown[], ModelError> {\n if (!messages.length || messages.some((message) => message.role !== \"user\")) {\n return err({ code: \"failed\", message: \"Responses steering accepts one or more user messages only\", retryable: false });\n }\n return ok(messages.map((message) => ({\n type: \"message\", role: \"user\", content: encodeContent(message.content, false),\n })));\n}\n\nfunction encodeContent(content: Content, output: boolean): unknown {\n if (typeof content === \"string\") return content;\n const parts: unknown[] = [];\n for (const part of content) {\n if (part.type === \"text\") {\n parts.push({ type: output ? \"output_text\" : \"input_text\", text: part.text });\n continue;\n }\n if (part.type === \"image\" && !output) {\n parts.push({\n type: \"input_image\",\n image_url: part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`,\n });\n continue;\n }\n if (part.type === \"file\" && !output) {\n parts.push(part.source.kind === \"url\"\n ? { type: \"input_file\", file_url: part.source.url }\n : {\n type: \"input_file\",\n file_data: `data:${part.mediaType};base64,${part.source.data}`,\n ...(part.name ? { filename: part.name } : {}),\n });\n continue;\n }\n if (part.type === \"opaque\" && part.provider === provider) parts.push(part.data);\n }\n return parts;\n}\n\nfunction encodeToolOutput(content: Content): unknown {\n if (typeof content === \"string\") return content;\n return encodeContent(content, false);\n}\n\nconst encodeTool = (tool: ToolSpec) => ({\n type: \"function\" as const,\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n strict: false,\n ...(tool.async === true ? { async: true } : {}),\n});\n\nfunction decodeCall(item: Record<string, unknown> | undefined): ToolCall | undefined {\n if (!item || item[\"type\"] !== \"function_call\") return undefined;\n const callId = string(item[\"call_id\"]);\n const name = string(item[\"name\"]);\n if (!callId || !name) return undefined;\n return {\n callId,\n name,\n arguments: string(item[\"arguments\"]) || \"{}\",\n ...(item[\"async\"] === true ? { async: true } : {}),\n };\n}\n\nfunction finish(\n response: Record<string, unknown>,\n text: readonly string[],\n calls: ReadonlyMap<string, ToolCall>,\n providerItems: readonly JsonValue[],\n usage: Usage,\n refused: boolean,\n servedModel?: string,\n): Result<ModelResponse, ModelError> {\n const collected = [...calls.values()];\n const reason = string(record(response[\"incomplete_details\"])?.[\"reason\"]);\n const finishReason: ModelResponse[\"finishReason\"] =\n reason === \"max_output_tokens\" ? \"length\"\n : reason === \"content_filter\" || refused ? \"refusal\"\n : collected.some((call) => call.async !== true) ? \"tool-calls\"\n : \"stop\";\n return ok({\n message: { content: text.join(\"\"), ...(collected.length ? { calls: collected } : {}) },\n finishReason,\n usage,\n ...(servedModel ? { model: servedModel } : {}),\n ...(providerItems.length ? { providerState: { provider, items: providerItems } } : {}),\n });\n}\n\nfunction hasRefusal(response: Record<string, unknown>): boolean {\n return array(response[\"output\"]).some((item) =>\n array(record(item)?.[\"content\"]).some((part) => record(part)?.[\"type\"] === \"refusal\"));\n}\n\nfunction appendItem(target: JsonValue[], seen: Set<string>, item: Record<string, unknown>): void {\n const id = string(item[\"id\"]);\n if (id && seen.has(id)) return;\n if (id) seen.add(id);\n target.push(JSON.parse(JSON.stringify(item)) as JsonValue);\n}\n\nfunction decodeUsage(value: Record<string, unknown> | undefined): Usage {\n if (!value) return {};\n const details = record(value[\"input_tokens_details\"]);\n const input = number(value[\"input_tokens\"]);\n const cached = number(details?.[\"cached_tokens\"]);\n const written = number(details?.[\"cache_write_tokens\"]);\n return {\n ...(input !== undefined ? { inputTokens: Math.max(input - (cached ?? 0) - (written ?? 0), 0) } : {}),\n ...(cached !== undefined ? { cacheReadTokens: cached } : {}),\n ...(written !== undefined ? { cacheWriteTokens: written } : {}),\n ...(number(value[\"output_tokens\"]) !== undefined ? { outputTokens: number(value[\"output_tokens\"]) } : {}),\n };\n}\n\nfunction addUsage(left: Usage, right: Usage): Usage {\n const total: Usage = {};\n for (const key of [\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\", \"costUsd\"] as const) {\n const a = left[key];\n const b = right[key];\n if (a !== undefined || b !== undefined) total[key] = (a ?? 0) + (b ?? 0);\n }\n return total;\n}\n\nfunction responseFailure(response: Record<string, unknown> | undefined): ModelError {\n const error = record(response?.[\"error\"]);\n return {\n code: \"provider\",\n message: string(error?.[\"message\"]) ?? \"Responses generation failed\",\n retryable: true,\n };\n}\n\nfunction eventError(event: Record<string, unknown>): ModelError {\n const error = record(event[\"error\"]);\n const code = string(error?.[\"code\"]);\n return {\n code: code === \"rate_limit_exceeded\" ? \"rate-limit\" : \"failed\",\n message: string(error?.[\"message\"]) ?? \"Responses command failed\",\n retryable: code === \"rate_limit_exceeded\" || code === \"server_error\" || code === \"response_not_found\",\n };\n}\n\nfunction providerError(error: unknown): ModelError {\n const message = error instanceof Error ? error.message : String(error ?? \"Responses transport failed\");\n return { code: \"provider\", message, retryable: true };\n}\n\nconst cancelled = (): ModelError => ({ code: \"cancelled\", message: \"Generation cancelled\", retryable: false });\nconst outputPhase = (value: unknown): \"commentary\" | \"final_answer\" | undefined =>\n value === \"commentary\" || value === \"final_answer\" ? value : undefined;\nconst record = (value: unknown): Record<string, unknown> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;\nconst array = (value: unknown): readonly unknown[] => Array.isArray(value) ? value : [];\nconst string = (value: unknown): string | undefined => typeof value === \"string\" ? value : undefined;\nconst number = (value: unknown): number | undefined => typeof value === \"number\" ? value : undefined;\n"]}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Waiting out a provider that said "not yet".
3
+ *
4
+ * A request can fail before the provider has begun to answer it, and some of
5
+ * those failures are the provider asking for a moment rather than refusing the
6
+ * request: a rate limit, an overloaded upstream, a connection that never
7
+ * opened, a router whose credit is spoken for by our own other requests until
8
+ * they finish. Nothing about the request was wrong, so the right response is to
9
+ * wait and send it again. The loop continues past a retryable failure only when
10
+ * it already has new input to send, so without this a wait that would have
11
+ * cleared in seconds ends the activation instead.
12
+ *
13
+ * This sits at the `fetch` seam rather than around the generation because that
14
+ * is where "before the first delta" is exact: a status has been read and no
15
+ * body has. Once a body is open, partial output has already reached the
16
+ * caller, and whether to ask again is the loop's decision rather than the
17
+ * wire's. The bounds are stated in `INTERFACE.md`; this is where they are.
18
+ */
19
+ /** How many times one request is sent again after a wait. */
20
+ export declare const retries = 4;
21
+ /** What an adapter calls: `fetch`'s signature without the runtime extras Bun hangs on the global. */
22
+ export type Call = (...args: Parameters<typeof fetch>) => Promise<Response>;
23
+ export interface RetryOptions {
24
+ /**
25
+ * Whether a refused response is this endpoint's way of asking for a wait,
26
+ * beyond the statuses every HTTP wire means so. Asked only for a response
27
+ * `isWaitStatus` did not already decide; it may read a clone of the body.
28
+ */
29
+ isWait?: (response: Response) => Promise<boolean> | boolean;
30
+ /** Injectable for tests, which cannot wait out a backoff schedule for real. */
31
+ sleep?: (ms: number, signal: AbortSignal | undefined) => Promise<void>;
32
+ random?: () => number;
33
+ }
34
+ /**
35
+ * The statuses that mean "not yet" on any HTTP wire.
36
+ *
37
+ * 408 and 425 are the request arriving at the wrong moment, 409 is a lock the
38
+ * provider will release, 429 is a rate limit and 5xx is the provider's own
39
+ * trouble. Everything else is a statement about the request, and sending it
40
+ * again unchanged asks for the same answer.
41
+ */
42
+ export declare function isWaitStatus(status: number): boolean;
43
+ /**
44
+ * A `fetch` that waits and asks again when the answer is a wait.
45
+ *
46
+ * Returned to the adapter as the last response or the last transport error, so
47
+ * an exhausted retry is reported exactly as a single failure would have been —
48
+ * with a retryable code, because the provider never said the request was
49
+ * wrong. An abort of the request's signal ends a wait at once and is thrown as
50
+ * the abort it is.
51
+ */
52
+ export declare function retrying(call: Call, options?: RetryOptions): Call;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Waiting out a provider that said "not yet".
3
+ *
4
+ * A request can fail before the provider has begun to answer it, and some of
5
+ * those failures are the provider asking for a moment rather than refusing the
6
+ * request: a rate limit, an overloaded upstream, a connection that never
7
+ * opened, a router whose credit is spoken for by our own other requests until
8
+ * they finish. Nothing about the request was wrong, so the right response is to
9
+ * wait and send it again. The loop continues past a retryable failure only when
10
+ * it already has new input to send, so without this a wait that would have
11
+ * cleared in seconds ends the activation instead.
12
+ *
13
+ * This sits at the `fetch` seam rather than around the generation because that
14
+ * is where "before the first delta" is exact: a status has been read and no
15
+ * body has. Once a body is open, partial output has already reached the
16
+ * caller, and whether to ask again is the loop's decision rather than the
17
+ * wire's. The bounds are stated in `INTERFACE.md`; this is where they are.
18
+ */
19
+ /** How many times one request is sent again after a wait. */
20
+ export const retries = 4;
21
+ /** The ceiling of the first backoff; each retry's ceiling doubles the last, up to the cap. */
22
+ const backoffBaseMs = 1_000;
23
+ const backoffCapMs = 30_000;
24
+ /** The longest `Retry-After` honoured; a provider asking for more is waited for this long. */
25
+ const retryAfterCapMs = 120_000;
26
+ /** The most time one request spends waiting altogether; a wait that would pass it is not taken. */
27
+ const totalWaitCapMs = 180_000;
28
+ /**
29
+ * The statuses that mean "not yet" on any HTTP wire.
30
+ *
31
+ * 408 and 425 are the request arriving at the wrong moment, 409 is a lock the
32
+ * provider will release, 429 is a rate limit and 5xx is the provider's own
33
+ * trouble. Everything else is a statement about the request, and sending it
34
+ * again unchanged asks for the same answer.
35
+ */
36
+ export function isWaitStatus(status) {
37
+ return status === 408 || status === 409 || status === 425 || status === 429 || status >= 500;
38
+ }
39
+ /**
40
+ * A `fetch` that waits and asks again when the answer is a wait.
41
+ *
42
+ * Returned to the adapter as the last response or the last transport error, so
43
+ * an exhausted retry is reported exactly as a single failure would have been —
44
+ * with a retryable code, because the provider never said the request was
45
+ * wrong. An abort of the request's signal ends a wait at once and is thrown as
46
+ * the abort it is.
47
+ */
48
+ export function retrying(call, options = {}) {
49
+ const { isWait, sleep = pause, random = Math.random } = options;
50
+ return async (input, init) => {
51
+ const signal = init?.signal ?? undefined;
52
+ let waited = 0;
53
+ for (let attempt = 0;; attempt += 1) {
54
+ let response;
55
+ let delay;
56
+ try {
57
+ response = await call(input, init);
58
+ }
59
+ catch (error) {
60
+ if (signal?.aborted || attempt >= retries)
61
+ throw error;
62
+ delay = backoff(attempt, random);
63
+ if (waited + delay > totalWaitCapMs)
64
+ throw error;
65
+ waited += delay;
66
+ await sleep(delay, signal);
67
+ continue;
68
+ }
69
+ if (response.ok || attempt >= retries)
70
+ return response;
71
+ if (!isWaitStatus(response.status) && !(await isWait?.(response)))
72
+ return response;
73
+ delay = retryAfter(response.headers.get("retry-after")) ?? backoff(attempt, random);
74
+ if (waited + delay > totalWaitCapMs)
75
+ return response;
76
+ // The connection is not needed again, and holding a body nobody reads
77
+ // keeps it open for the whole wait.
78
+ await response.body?.cancel().catch(() => undefined);
79
+ waited += delay;
80
+ await sleep(delay, signal);
81
+ }
82
+ };
83
+ }
84
+ /** Full jitter over a doubling ceiling: the standard cure for retries that arrive together. */
85
+ const backoff = (attempt, random) => Math.round(random() * Math.min(backoffBaseMs * 2 ** attempt, backoffCapMs));
86
+ /** `Retry-After` as seconds or an HTTP date, clamped to what will be waited; absent when unparseable. */
87
+ function retryAfter(header) {
88
+ if (header === null)
89
+ return undefined;
90
+ const seconds = Number(header);
91
+ const ms = Number.isFinite(seconds) ? seconds * 1_000 : Date.parse(header) - Date.now();
92
+ if (!Number.isFinite(ms))
93
+ return undefined;
94
+ return Math.min(Math.max(ms, 0), retryAfterCapMs);
95
+ }
96
+ function pause(ms, signal) {
97
+ return new Promise((resolve, reject) => {
98
+ if (signal?.aborted) {
99
+ reject(aborted(signal));
100
+ return;
101
+ }
102
+ const onAbort = () => { clearTimeout(timer); reject(aborted(signal)); };
103
+ const timer = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms);
104
+ signal?.addEventListener("abort", onAbort, { once: true });
105
+ });
106
+ }
107
+ const aborted = (signal) => signal.reason ?? new DOMException("This operation was aborted", "AbortError");
108
+ //# sourceMappingURL=retry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/model/retry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,6DAA6D;AAC7D,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,CAAC;AACzB,8FAA8F;AAC9F,MAAM,aAAa,GAAG,KAAK,CAAC;AAC5B,MAAM,YAAY,GAAG,MAAM,CAAC;AAC5B,8FAA8F;AAC9F,MAAM,eAAe,GAAG,OAAO,CAAC;AAChC,mGAAmG;AACnG,MAAM,cAAc,GAAG,OAAO,CAAC;AAiB/B;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,OAAO,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,IAAI,GAAG,CAAC;AAC/F,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,QAAQ,CAAC,IAAU,EAAE,UAAwB,EAAE;IAC7D,MAAM,EAAE,MAAM,EAAE,KAAK,GAAG,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,OAAO,CAAC;IAChE,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;QAC3B,MAAM,MAAM,GAAG,IAAI,EAAE,MAAM,IAAI,SAAS,CAAC;QACzC,IAAI,MAAM,GAAG,CAAC,CAAC;QACf,KAAK,IAAI,OAAO,GAAG,CAAC,GAAI,OAAO,IAAI,CAAC,EAAE,CAAC;YACrC,IAAI,QAAkB,CAAC;YACvB,IAAI,KAAa,CAAC;YAClB,IAAI,CAAC;gBACH,QAAQ,GAAG,MAAM,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YACrC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,MAAM,EA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,CAC/C,MAAM,CAAC,MAAM,IAAI,IAAI,YAAY,CAAC,4BAA4B,EAAE,YAAY,CAAC,CAAC","sourcesContent":["/**\n * Waiting out a provider that said \"not yet\".\n *\n * A request can fail before the provider has begun to answer it, and some of\n * those failures are the provider asking for a moment rather than refusing the\n * request: a rate limit, an overloaded upstream, a connection that never\n * opened, a router whose credit is spoken for by our own other requests until\n * they finish. Nothing about the request was wrong, so the right response is to\n * wait and send it again. The loop continues past a retryable failure only when\n * it already has new input to send, so without this a wait that would have\n * cleared in seconds ends the activation instead.\n *\n * This sits at the `fetch` seam rather than around the generation because that\n * is where \"before the first delta\" is exact: a status has been read and no\n * body has. Once a body is open, partial output has already reached the\n * caller, and whether to ask again is the loop's decision rather than the\n * wire's. The bounds are stated in `INTERFACE.md`; this is where they are.\n */\n\n/** How many times one request is sent again after a wait. */\nexport const retries = 4;\n/** The ceiling of the first backoff; each retry's ceiling doubles the last, up to the cap. */\nconst backoffBaseMs = 1_000;\nconst backoffCapMs = 30_000;\n/** The longest `Retry-After` honoured; a provider asking for more is waited for this long. */\nconst retryAfterCapMs = 120_000;\n/** The most time one request spends waiting altogether; a wait that would pass it is not taken. */\nconst totalWaitCapMs = 180_000;\n\n/** What an adapter calls: `fetch`'s signature without the runtime extras Bun hangs on the global. */\nexport type Call = (...args: Parameters<typeof fetch>) => Promise<Response>;\n\nexport interface RetryOptions {\n /**\n * Whether a refused response is this endpoint's way of asking for a wait,\n * beyond the statuses every HTTP wire means so. Asked only for a response\n * `isWaitStatus` did not already decide; it may read a clone of the body.\n */\n isWait?: (response: Response) => Promise<boolean> | boolean;\n /** Injectable for tests, which cannot wait out a backoff schedule for real. */\n sleep?: (ms: number, signal: AbortSignal | undefined) => Promise<void>;\n random?: () => number;\n}\n\n/**\n * The statuses that mean \"not yet\" on any HTTP wire.\n *\n * 408 and 425 are the request arriving at the wrong moment, 409 is a lock the\n * provider will release, 429 is a rate limit and 5xx is the provider's own\n * trouble. Everything else is a statement about the request, and sending it\n * again unchanged asks for the same answer.\n */\nexport function isWaitStatus(status: number): boolean {\n return status === 408 || status === 409 || status === 425 || status === 429 || status >= 500;\n}\n\n/**\n * A `fetch` that waits and asks again when the answer is a wait.\n *\n * Returned to the adapter as the last response or the last transport error, so\n * an exhausted retry is reported exactly as a single failure would have been —\n * with a retryable code, because the provider never said the request was\n * wrong. An abort of the request's signal ends a wait at once and is thrown as\n * the abort it is.\n */\nexport function retrying(call: Call, options: RetryOptions = {}): Call {\n const { isWait, sleep = pause, random = Math.random } = options;\n return async (input, init) => {\n const signal = init?.signal ?? undefined;\n let waited = 0;\n for (let attempt = 0; ; attempt += 1) {\n let response: Response;\n let delay: number;\n try {\n response = await call(input, init);\n } catch (error) {\n if (signal?.aborted || attempt >= retries) throw error;\n delay = backoff(attempt, random);\n if (waited + delay > totalWaitCapMs) throw error;\n waited += delay;\n await sleep(delay, signal);\n continue;\n }\n if (response.ok || attempt >= retries) return response;\n if (!isWaitStatus(response.status) && !(await isWait?.(response))) return response;\n delay = retryAfter(response.headers.get(\"retry-after\")) ?? backoff(attempt, random);\n if (waited + delay > totalWaitCapMs) return response;\n // The connection is not needed again, and holding a body nobody reads\n // keeps it open for the whole wait.\n await response.body?.cancel().catch(() => undefined);\n waited += delay;\n await sleep(delay, signal);\n }\n };\n}\n\n/** Full jitter over a doubling ceiling: the standard cure for retries that arrive together. */\nconst backoff = (attempt: number, random: () => number): number =>\n Math.round(random() * Math.min(backoffBaseMs * 2 ** attempt, backoffCapMs));\n\n/** `Retry-After` as seconds or an HTTP date, clamped to what will be waited; absent when unparseable. */\nfunction retryAfter(header: string | null): number | undefined {\n if (header === null) return undefined;\n const seconds = Number(header);\n const ms = Number.isFinite(seconds) ? seconds * 1_000 : Date.parse(header) - Date.now();\n if (!Number.isFinite(ms)) return undefined;\n return Math.min(Math.max(ms, 0), retryAfterCapMs);\n}\n\nfunction pause(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) { reject(aborted(signal)); return; }\n const onAbort = () => { clearTimeout(timer); reject(aborted(signal!)); };\n const timer = setTimeout(() => { signal?.removeEventListener(\"abort\", onAbort); resolve(); }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nconst aborted = (signal: AbortSignal): unknown =>\n signal.reason ?? new DOMException(\"This operation was aborted\", \"AbortError\");\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-dray/aglib",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "type": "module",
5
5
  "description": "A small TypeScript toolkit for building your own agent harness.",
6
6
  "license": "MIT",