@a-dray/aglib 0.6.3 → 0.6.4

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.
@@ -303,12 +303,31 @@ async function httpError(response) {
303
303
  : response.status === 429 ? "rate-limit"
304
304
  : wait ? "provider"
305
305
  : "failed";
306
+ const said = errorBody(body);
307
+ const errorType = said?.["type"];
308
+ const details = said?.["details"];
309
+ const errorCode = details && typeof details === "object" ? details["error_code"] : undefined;
306
310
  return {
307
311
  code,
308
312
  message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : ""}`,
309
313
  retryable: wait,
314
+ status: response.status,
315
+ ...(typeof errorType === "string" ? { errorType } : {}),
316
+ ...(typeof errorCode === "string" ? { errorCode } : {}),
310
317
  };
311
318
  }
319
+ /** The `error` object of a refusal's JSON body, when it has one; read whole, not the cut the message keeps. */
320
+ function errorBody(body) {
321
+ let parsed;
322
+ try {
323
+ parsed = JSON.parse(body);
324
+ }
325
+ catch {
326
+ return undefined;
327
+ }
328
+ const error = parsed !== null && typeof parsed === "object" ? parsed.error : undefined;
329
+ return error !== null && typeof error === "object" && !Array.isArray(error) ? error : undefined;
330
+ }
312
331
  function transportError(error, signal) {
313
332
  if (signal?.aborted)
314
333
  return { code: "cancelled", message: "Generation cancelled", retryable: false };
@@ -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;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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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 // Mark the reusable system prefix and the caller's conversation boundary;\n // volatile turn context follows that boundary and must stay outside it.\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: JSON.parse(call.arguments) as JsonValue });\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
+ {"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,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,MAA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AI,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 // Mark the reusable system prefix and the caller's conversation boundary;\n // volatile turn context follows that boundary and must stay outside it.\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: JSON.parse(call.arguments) as JsonValue });\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 const said = errorBody(body);\n const errorType = said?.[\"type\"];\n const details = said?.[\"details\"];\n const errorCode = details && typeof details === \"object\" ? (details as Record<string, unknown>)[\"error_code\"] : undefined;\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: wait,\n status: response.status,\n ...(typeof errorType === \"string\" ? { errorType } : {}),\n ...(typeof errorCode === \"string\" ? { errorCode } : {}),\n };\n}\n\n/** The `error` object of a refusal's JSON body, when it has one; read whole, not the cut the message keeps. */\nfunction errorBody(body: string): Record<string, unknown> | undefined {\n let parsed: unknown;\n try { parsed = JSON.parse(body); } catch { return undefined; }\n const error = parsed !== null && typeof parsed === \"object\" ? (parsed as { error?: unknown }).error : undefined;\n return error !== null && typeof error === \"object\" && !Array.isArray(error) ? error as Record<string, unknown> : undefined;\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"]}
@@ -412,12 +412,30 @@ async function httpError(response, isWait) {
412
412
  : wait && (response.status === 429 || response.status === 402) ? "rate-limit"
413
413
  : wait ? "provider"
414
414
  : "failed";
415
+ const said = errorBody(body);
416
+ const errorType = said?.["type"];
417
+ const errorCode = said?.["code"];
415
418
  return {
416
419
  code,
417
420
  message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : ""}`,
418
421
  retryable: wait,
422
+ status: response.status,
423
+ ...(typeof errorType === "string" ? { errorType } : {}),
424
+ ...(typeof errorCode === "string" ? { errorCode } : {}),
419
425
  };
420
426
  }
427
+ /** The `error` object of a refusal's JSON body, when it has one; read whole, not the cut the message keeps. */
428
+ function errorBody(body) {
429
+ let parsed;
430
+ try {
431
+ parsed = JSON.parse(body);
432
+ }
433
+ catch {
434
+ return undefined;
435
+ }
436
+ const error = parsed !== null && typeof parsed === "object" ? parsed.error : undefined;
437
+ return error !== null && typeof error === "object" && !Array.isArray(error) ? error : undefined;
438
+ }
421
439
  function transportError(error, signal) {
422
440
  if (signal?.aborted)
423
441
  return { code: "cancelled", message: "Generation cancelled", retryable: false };
@@ -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;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,OA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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 const lead = leadingSystem(request.messages);\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\n/** How far the leading run of system messages reaches: the standing instructions and the run's context. */\nfunction leadingSystem(messages: readonly Message[]): number {\n let lead = 0;\n while (lead < messages.length && messages[lead]!.role === \"system\") lead += 1;\n return lead;\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 const lead = leadingSystem(messages);\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 // A system message past the leading run is the turn's context, which the\n // projection places after the cache boundary so that the prefix before it\n // can be read back. This wire sends it as `user`, its text unchanged.\n // OpenRouter folds every `system` message into Gemini's one\n // `systemInstruction`, and Gemini's implicit cache treats that instruction\n // as immutable, so a request that ends in a `system` message reads nothing\n // from cache — 0 tokens of a 15,138-token prefix, whether repeated byte for\n // byte or with one line changed — where the same line as a trailing `user`\n // message reads 12,189. DeepSeek does the same, 0 against 15,104; GLM reads\n // 11,520 either way. In production that was Gemini 3.8 Flash falling from\n // a nine-tenths daily cache share to none, at full input price every turn.\n if (message.role === \"system\" && index >= lead) encoded[\"role\"] = \"user\";\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"]}
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,CAA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, 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 const lead = leadingSystem(request.messages);\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\n/** How far the leading run of system messages reaches: the standing instructions and the run's context. */\nfunction leadingSystem(messages: readonly Message[]): number {\n let lead = 0;\n while (lead < messages.length && messages[lead]!.role === \"system\") lead += 1;\n return lead;\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 const lead = leadingSystem(messages);\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 // A system message past the leading run is the turn's context, which the\n // projection places after the cache boundary so that the prefix before it\n // can be read back. This wire sends it as `user`, its text unchanged.\n // OpenRouter folds every `system` message into Gemini's one\n // `systemInstruction`, and Gemini's implicit cache treats that instruction\n // as immutable, so a request that ends in a `system` message reads nothing\n // from cache — 0 tokens of a 15,138-token prefix, whether repeated byte for\n // byte or with one line changed — where the same line as a trailing `user`\n // message reads 12,189. DeepSeek does the same, 0 against 15,104; GLM reads\n // 11,520 either way. In production that was Gemini 3.8 Flash falling from\n // a nine-tenths daily cache share to none, at full input price every turn.\n if (message.role === \"system\" && index >= lead) encoded[\"role\"] = \"user\";\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 const said = errorBody(body);\n const errorType = said?.[\"type\"];\n const errorCode = said?.[\"code\"];\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: wait,\n status: response.status,\n ...(typeof errorType === \"string\" ? { errorType } : {}),\n ...(typeof errorCode === \"string\" ? { errorCode } : {}),\n };\n}\n\n/** The `error` object of a refusal's JSON body, when it has one; read whole, not the cut the message keeps. */\nfunction errorBody(body: string): Record<string, unknown> | undefined {\n let parsed: unknown;\n try { parsed = JSON.parse(body); } catch { return undefined; }\n const error = parsed !== null && typeof parsed === \"object\" ? (parsed as { error?: unknown }).error : undefined;\n return error !== null && typeof error === \"object\" && !Array.isArray(error) ? error as Record<string, unknown> : undefined;\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"]}
@@ -70,14 +70,14 @@ class ResponsesHub {
70
70
  async #read() {
71
71
  try {
72
72
  for await (const envelope of this.#connection) {
73
- if (envelope.type === "message" && envelope.message) {
74
- const event = envelope.message;
73
+ const event = envelope.type === "message" ? record(envelope.message) : sentError(envelope);
74
+ if (event) {
75
75
  const lane = string(event["stream_id"]);
76
76
  if (lane) {
77
- this.#lanes.get(lane)?.queue.push(envelope);
77
+ this.#lanes.get(lane)?.queue.push({ type: "message", message: event });
78
78
  }
79
79
  else if (string(event["type"]) === "error") {
80
- this.#broadcast(envelope);
80
+ this.#broadcast({ type: "message", message: event });
81
81
  }
82
82
  else if (this.#lanes.size === 1) {
83
83
  this.#lanes.values().next().value?.queue.push(envelope);
@@ -138,6 +138,19 @@ class ResponsesHub {
138
138
  this.#onEnd();
139
139
  }
140
140
  }
141
+ /**
142
+ * The provider's `error` event, when that is what an error envelope carries.
143
+ * The SDK raises a server `error` event as an error envelope beside a socket's
144
+ * own failures, keeping the event on the error it raises; an event is one
145
+ * response's failure, or every response's when it names no lane, and the
146
+ * connection it arrived on is still open. Anything else is the socket failing.
147
+ */
148
+ function sentError(envelope) {
149
+ if (envelope.type !== "error")
150
+ return undefined;
151
+ const event = record(record(envelope.error)?.["error"]);
152
+ return event?.["type"] === "error" ? event : undefined;
153
+ }
141
154
  class EnvelopeQueue {
142
155
  #values = [];
143
156
  #waiters = [];
@@ -706,19 +719,27 @@ function addUsage(left, right) {
706
719
  }
707
720
  function responseFailure(response) {
708
721
  const error = record(response?.["error"]);
722
+ const errorCode = string(error?.["code"]);
709
723
  return {
710
724
  code: "provider",
711
725
  message: string(error?.["message"]) ?? "Responses generation failed",
712
726
  retryable: true,
727
+ ...(errorCode ? { errorCode } : {}),
713
728
  };
714
729
  }
730
+ /** An `error` event: a command's, with its detail under `error`, or a streaming one, with it on the event. */
715
731
  function eventError(event) {
716
- const error = record(event["error"]);
717
- const code = string(error?.["code"]);
732
+ const error = record(event["error"]) ?? event;
733
+ const errorCode = string(error["code"]);
734
+ const errorType = string(error["type"]);
735
+ const status = number(event["status"]);
718
736
  return {
719
- code: code === "rate_limit_exceeded" ? "rate-limit" : "failed",
720
- message: string(error?.["message"]) ?? "Responses command failed",
721
- retryable: code === "rate_limit_exceeded" || code === "server_error" || code === "response_not_found",
737
+ code: errorCode === "rate_limit_exceeded" ? "rate-limit" : "failed",
738
+ message: string(error["message"]) ?? "Responses command failed",
739
+ retryable: errorCode === "rate_limit_exceeded" || errorCode === "server_error" || errorCode === "response_not_found",
740
+ ...(status !== undefined ? { status } : {}),
741
+ ...(errorType && errorType !== "error" ? { errorType } : {}),
742
+ ...(errorCode ? { errorCode } : {}),
722
743
  };
723
744
  }
724
745
  function providerError(error) {
@@ -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,UA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S,GAAG,GAAe,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC;AAC/G,MAAM,WAAW,GAAG,CAAC,KAAc,EAA6C,EAAE,CAChF,KAAK,KAAK,YAAY,IAAI,KAAK,KAAK,cAAc,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,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 : {\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"]}
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,CAA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E,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 const event = envelope.type === \"message\" ? record(envelope.message) : sentError(envelope);\n if (event) {\n const lane = string(event[\"stream_id\"]);\n if (lane) {\n this.#lanes.get(lane)?.queue.push({ type: \"message\", message: event });\n } else if (string(event[\"type\"]) === \"error\") {\n this.#broadcast({ type: \"message\", message: event });\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\n/**\n * The provider's `error` event, when that is what an error envelope carries.\n * The SDK raises a server `error` event as an error envelope beside a socket's\n * own failures, keeping the event on the error it raises; an event is one\n * response's failure, or every response's when it names no lane, and the\n * connection it arrived on is still open. Anything else is the socket failing.\n */\nfunction sentError(envelope: StreamEnvelope): Record<string, unknown> | undefined {\n if (envelope.type !== \"error\") return undefined;\n const event = record(record(envelope.error)?.[\"error\"]);\n return event?.[\"type\"] === \"error\" ? event : undefined;\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 const errorCode = string(error?.[\"code\"]);\n return {\n code: \"provider\",\n message: string(error?.[\"message\"]) ?? \"Responses generation failed\",\n retryable: true,\n ...(errorCode ? { errorCode } : {}),\n };\n}\n\n/** An `error` event: a command's, with its detail under `error`, or a streaming one, with it on the event. */\nfunction eventError(event: Record<string, unknown>): ModelError {\n const error = record(event[\"error\"]) ?? event;\n const errorCode = string(error[\"code\"]);\n const errorType = string(error[\"type\"]);\n const status = number(event[\"status\"]);\n return {\n code: errorCode === \"rate_limit_exceeded\" ? \"rate-limit\" : \"failed\",\n message: string(error[\"message\"]) ?? \"Responses command failed\",\n retryable: errorCode === \"rate_limit_exceeded\" || errorCode === \"server_error\" || errorCode === \"response_not_found\",\n ...(status !== undefined ? { status } : {}),\n ...(errorType && errorType !== \"error\" ? { errorType } : {}),\n ...(errorCode ? { errorCode } : {}),\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"]}
@@ -69,8 +69,20 @@ export interface ModelResponse {
69
69
  model?: string;
70
70
  providerState?: ProviderState;
71
71
  }
72
+ /**
73
+ * `code` is aglib's reading of the failure. `status`, `errorType` and
74
+ * `errorCode` are the provider's own, as it sent them, for a caller whose
75
+ * decision turns on something `code` does not distinguish — a spent balance
76
+ * from a rate limit, say — so that caller reads fields rather than `message`.
77
+ */
72
78
  export interface ModelError extends Failure {
73
79
  code: "auth" | "rate-limit" | "context-length" | "cancelled" | "provider" | "failed";
80
+ /** The HTTP status of the refusal, or the one the provider's error event carried. */
81
+ status?: number;
82
+ /** The provider's error `type`, when its error body or event named one. */
83
+ errorType?: string;
84
+ /** The provider's error `code` (Anthropic's `details.error_code`), when it named one as a string. */
85
+ errorCode?: string;
74
86
  }
75
87
  /**
76
88
  * One method. Streaming is not a second contract: a caller that wants the whole
@@ -1 +1 @@
1
- {"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model/model.ts"],"names":[],"mappings":"AAuFA;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,UAA2B;IAE3B,IAAI,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IACnC,OAAO,CAAC,IAAI,CAAC,IAAI;QAAE,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IAClD,OAAO,IAAI,CAAC,KAAK,CAAC;AACpB,CAAC","sourcesContent":["import type { Content, ContentPart } from \"../content.js\";\nimport type { ProviderState, ToolCall, Usage } from \"../session/entry.js\";\nimport type { Message } from \"../session/messages.js\";\nimport type { ToolSpec } from \"../tools/tool.js\";\nimport type { Failure, Result } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/**\n * One provider call.\n *\n * There is no model *name* here, and that is the point: a model is a value.\n * `createAnthropicModel({ apiKey, model })` is the provider, the credential and\n * the model together, and choosing a different one is choosing a different\n * `Model` — which is already how the loop passes a cheaper one to compaction.\n *\n * A name would have to be resolved, and resolving is what goes wrong. The one\n * application that had a name field to use encoded provider and model into it\n * as `provider/model`, then had to split it back out — ambiguously, because a\n * provider's own ids contain slashes (`z-ai/glm-5.2`), so the split was\n * \"up to the first one\" with a comment apologising for it. One field, two facts.\n * Names leave this library as observations — `ModelResponse.model` says what\n * actually served — and never enter it as selections.\n */\nexport interface ModelRequest {\n messages: readonly Message[];\n tools?: readonly ToolSpec[];\n maxOutputTokens?: number;\n /**\n * Only for providers that still accept sampling controls. The current\n * Anthropic models reject it outright, so that adapter does not send it —\n * declaring the option here and dropping it there is the honest shape, since\n * the alternative is a request the provider 400s.\n */\n temperature?: number;\n /**\n * How much the model should think before answering, where it can. Named\n * levels rather than a token budget, because a budget is the one thing no\n * two providers agree on — and the providers that had one have since removed\n * it. Each adapter maps a level to its own control; one that has none\n * ignores it rather than failing.\n */\n effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n /** End the cacheable prefix after this many messages. A decision about one request only. */\n cacheAfter?: number;\n signal?: AbortSignal;\n}\n\nexport type ModelDelta =\n | { type: \"text.delta\"; text: string; phase?: \"commentary\" | \"final_answer\" }\n | { type: \"reasoning.delta\"; text: string }\n | { type: \"tool-call.delta\"; callId: string; arguments: string }\n /** A complete call may be executable before the response itself is done. */\n | { type: \"tool-call.done\"; call: ToolCall };\n\nexport interface ModelResponse {\n message: { content: Content; calls?: readonly ToolCall[] };\n finishReason: \"stop\" | \"tool-calls\" | \"length\" | \"refusal\";\n usage: Usage;\n model?: string;\n providerState?: ProviderState;\n}\n\nexport interface ModelError extends Failure {\n code: \"auth\" | \"rate-limit\" | \"context-length\" | \"cancelled\" | \"provider\" | \"failed\";\n}\n\n/**\n * One method. Streaming is not a second contract: a caller that wants the whole\n * response drains the generator and takes its return value, so no adapter has\n * to implement the same normalization twice.\n */\nexport type ModelSteerResult =\n | { status: \"accepted\"; id: string }\n | { status: \"rejected\"; error: ModelError };\n\nexport interface ModelGeneration extends AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n /** Queue new user messages on this active generation, when its provider can. */\n steer?(input: readonly Message[]): Promise<ModelSteerResult>;\n}\n\nexport interface Model {\n readonly id: string;\n /** This configured model accepts tools declared for asynchronous execution. */\n readonly asyncTools?: true;\n generate(request: ModelRequest): ModelGeneration;\n}\n\n/**\n * Drains a generation and returns only its outcome.\n *\n * Not on the `aglib/model` subpath. It was, for a recipe that turned a `Model`\n * into an Anthropic response; when that went, nothing outside the package\n * consumed it. `Model`'s own contract above says what a caller who wants the\n * whole response does, and this is the four lines of doing it.\n */\nexport async function collect(\n generation: ModelGeneration,\n): Promise<Result<ModelResponse, ModelError>> {\n let step = await generation.next();\n while (!step.done) step = await generation.next();\n return step.value;\n}\n\n/**\n * The vocabulary an adapter needs, re-exported from the port it implements.\n * An adapter imports these from here rather than reaching into the modules that\n * own them, so the port is the whole of its surface — every one of them appears\n * in a type above, which is what makes this the place to get them.\n */\nexport type { ContentPart, Message, ProviderState, ToolCall, ToolSpec, Usage };\n"]}
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model/model.ts"],"names":[],"mappings":"AAmGA;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,UAA2B;IAE3B,IAAI,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IACnC,OAAO,CAAC,IAAI,CAAC,IAAI;QAAE,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IAClD,OAAO,IAAI,CAAC,KAAK,CAAC;AACpB,CAAC","sourcesContent":["import type { Content, ContentPart } from \"../content.js\";\nimport type { ProviderState, ToolCall, Usage } from \"../session/entry.js\";\nimport type { Message } from \"../session/messages.js\";\nimport type { ToolSpec } from \"../tools/tool.js\";\nimport type { Failure, Result } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/**\n * One provider call.\n *\n * There is no model *name* here, and that is the point: a model is a value.\n * `createAnthropicModel({ apiKey, model })` is the provider, the credential and\n * the model together, and choosing a different one is choosing a different\n * `Model` — which is already how the loop passes a cheaper one to compaction.\n *\n * A name would have to be resolved, and resolving is what goes wrong. The one\n * application that had a name field to use encoded provider and model into it\n * as `provider/model`, then had to split it back out — ambiguously, because a\n * provider's own ids contain slashes (`z-ai/glm-5.2`), so the split was\n * \"up to the first one\" with a comment apologising for it. One field, two facts.\n * Names leave this library as observations — `ModelResponse.model` says what\n * actually served — and never enter it as selections.\n */\nexport interface ModelRequest {\n messages: readonly Message[];\n tools?: readonly ToolSpec[];\n maxOutputTokens?: number;\n /**\n * Only for providers that still accept sampling controls. The current\n * Anthropic models reject it outright, so that adapter does not send it —\n * declaring the option here and dropping it there is the honest shape, since\n * the alternative is a request the provider 400s.\n */\n temperature?: number;\n /**\n * How much the model should think before answering, where it can. Named\n * levels rather than a token budget, because a budget is the one thing no\n * two providers agree on — and the providers that had one have since removed\n * it. Each adapter maps a level to its own control; one that has none\n * ignores it rather than failing.\n */\n effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n /** End the cacheable prefix after this many messages. A decision about one request only. */\n cacheAfter?: number;\n signal?: AbortSignal;\n}\n\nexport type ModelDelta =\n | { type: \"text.delta\"; text: string; phase?: \"commentary\" | \"final_answer\" }\n | { type: \"reasoning.delta\"; text: string }\n | { type: \"tool-call.delta\"; callId: string; arguments: string }\n /** A complete call may be executable before the response itself is done. */\n | { type: \"tool-call.done\"; call: ToolCall };\n\nexport interface ModelResponse {\n message: { content: Content; calls?: readonly ToolCall[] };\n finishReason: \"stop\" | \"tool-calls\" | \"length\" | \"refusal\";\n usage: Usage;\n model?: string;\n providerState?: ProviderState;\n}\n\n/**\n * `code` is aglib's reading of the failure. `status`, `errorType` and\n * `errorCode` are the provider's own, as it sent them, for a caller whose\n * decision turns on something `code` does not distinguish — a spent balance\n * from a rate limit, say — so that caller reads fields rather than `message`.\n */\nexport interface ModelError extends Failure {\n code: \"auth\" | \"rate-limit\" | \"context-length\" | \"cancelled\" | \"provider\" | \"failed\";\n /** The HTTP status of the refusal, or the one the provider's error event carried. */\n status?: number;\n /** The provider's error `type`, when its error body or event named one. */\n errorType?: string;\n /** The provider's error `code` (Anthropic's `details.error_code`), when it named one as a string. */\n errorCode?: string;\n}\n\n/**\n * One method. Streaming is not a second contract: a caller that wants the whole\n * response drains the generator and takes its return value, so no adapter has\n * to implement the same normalization twice.\n */\nexport type ModelSteerResult =\n | { status: \"accepted\"; id: string }\n | { status: \"rejected\"; error: ModelError };\n\nexport interface ModelGeneration extends AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n /** Queue new user messages on this active generation, when its provider can. */\n steer?(input: readonly Message[]): Promise<ModelSteerResult>;\n}\n\nexport interface Model {\n readonly id: string;\n /** This configured model accepts tools declared for asynchronous execution. */\n readonly asyncTools?: true;\n generate(request: ModelRequest): ModelGeneration;\n}\n\n/**\n * Drains a generation and returns only its outcome.\n *\n * Not on the `aglib/model` subpath. It was, for a recipe that turned a `Model`\n * into an Anthropic response; when that went, nothing outside the package\n * consumed it. `Model`'s own contract above says what a caller who wants the\n * whole response does, and this is the four lines of doing it.\n */\nexport async function collect(\n generation: ModelGeneration,\n): Promise<Result<ModelResponse, ModelError>> {\n let step = await generation.next();\n while (!step.done) step = await generation.next();\n return step.value;\n}\n\n/**\n * The vocabulary an adapter needs, re-exported from the port it implements.\n * An adapter imports these from here rather than reaching into the modules that\n * own them, so the port is the whole of its surface — every one of them appears\n * in a type above, which is what makes this the place to get them.\n */\nexport type { ContentPart, Message, ProviderState, ToolCall, ToolSpec, Usage };\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-dray/aglib",
3
- "version": "0.6.3",
3
+ "version": "0.6.4",
4
4
  "type": "module",
5
5
  "description": "A small TypeScript toolkit for building your own agent harness.",
6
6
  "license": "MIT",