@a-dray/aglib 0.7.0 → 0.7.1

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.
@@ -99,9 +99,12 @@ export function createOpenAiCompatibleModel(options) {
99
99
  callId: fragment.id ?? `call_${fragment.index}`,
100
100
  name: fragment.function?.name ?? "",
101
101
  arguments: "",
102
+ extensions: {},
102
103
  };
103
104
  if (fragment.id)
104
105
  existing.callId = fragment.id;
106
+ const { index: _index, id: _id, type: _type, function: _function, ...extensions } = fragment;
107
+ Object.assign(existing.extensions, extensions);
105
108
  if (fragment.function?.name)
106
109
  existing.name = fragment.function.name;
107
110
  if (fragment.function?.arguments) {
@@ -117,7 +120,10 @@ export function createOpenAiCompatibleModel(options) {
117
120
  }
118
121
  const collected = [...calls.values()]
119
122
  .map((call) => ({ callId: call.callId, name: call.name, arguments: call.arguments || "{}" }));
120
- const state = reasoningState(reasoningDetails, sawReasoningDetails, reasoning, reasoningContent);
123
+ const state = [
124
+ ...reasoningState(reasoningDetails, sawReasoningDetails, reasoning, reasoningContent),
125
+ ...toolCallState([...calls.values()]),
126
+ ];
121
127
  return ok({
122
128
  message: { content: text.join(""), ...(collected.length ? { calls: collected } : {}) },
123
129
  finishReason: collected.length && finish === "stop" ? "tool-calls" : finish,
@@ -265,6 +271,7 @@ function encodeMessage(message, provider) {
265
271
  return { role: "tool", tool_call_id: message.callId, content: textOf(message.content) };
266
272
  }
267
273
  if (message.role === "assistant") {
274
+ const extensions = decodeToolCallState(message, provider);
268
275
  return {
269
276
  role: "assistant",
270
277
  content: textOf(message.content) || null,
@@ -272,6 +279,7 @@ function encodeMessage(message, provider) {
272
279
  ...(message.calls?.length
273
280
  ? {
274
281
  tool_calls: message.calls.map((call) => ({
282
+ ...extensions.get(call.callId),
275
283
  id: call.callId, type: "function",
276
284
  function: { name: call.name, arguments: call.arguments },
277
285
  })),
@@ -330,6 +338,31 @@ function decodeReasoningState(message, provider) {
330
338
  }
331
339
  return state;
332
340
  }
341
+ /**
342
+ * Fields a provider adds to a tool call beyond the wire's own, kept by call id.
343
+ * Gemini signs each call this way, under `extra_content`, and refuses the next
344
+ * request if the signature does not come back on the call it was issued for.
345
+ */
346
+ function toolCallState(calls) {
347
+ const extended = calls.filter((call) => Object.keys(call.extensions).length);
348
+ return extended.length ? [{ tool_calls: extended.map((call) => ({ ...call.extensions, id: call.callId })) }] : [];
349
+ }
350
+ function decodeToolCallState(message, provider) {
351
+ const extensions = new Map();
352
+ if (message.providerState?.provider !== provider)
353
+ return extensions;
354
+ for (const item of message.providerState.items) {
355
+ const calls = record(item)?.["tool_calls"];
356
+ if (!Array.isArray(calls))
357
+ continue;
358
+ for (const call of calls) {
359
+ const fields = record(call);
360
+ if (typeof fields?.["id"] === "string")
361
+ extensions.set(fields["id"], fields);
362
+ }
363
+ }
364
+ return extensions;
365
+ }
333
366
  /** Rebuild the complete blocks OpenRouter's chat stream fragments by type. */
334
367
  function appendReasoningDetails(target, incoming) {
335
368
  for (const raw of incoming) {
@@ -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;AA2C3E;;;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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AE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAChH,CAAC;AAED,+DAA+D;AAC/D,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAgC;IACvD,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,IAA4C,EAAE,CAAC;QACvE,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnC,OAAO,OAAO,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC7C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;YACnC,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { isWaitStatus, retrying, type RetryOptions } from \"../../retry.js\";\n\nexport interface OpenAiCompatibleOptions {\n apiKey: string;\n baseUrl: string;\n model: string;\n headers?: Readonly<Record<string, string>>;\n /**\n * How this endpoint spells reasoning effort. OpenAI takes `reasoning_effort`;\n * OpenRouter takes `reasoning: { effort }` and forwards it to whoever is\n * serving the model. Sending both is not compatibility — OpenAI rejects the\n * request outright — so the dialect is declared rather than guessed.\n */\n effortParameter?: \"reasoning_effort\" | \"reasoning\" | \"none\";\n /**\n * How this endpoint spells a cache breakpoint, where it has one. Most models\n * on this wire cache a repeated prefix by themselves and have no field for\n * it — plain OpenAI rejects one it does not know — so the default sends none.\n * OpenRouter takes Anthropic's `cache_control` on a text part and forwards\n * it to the models that cache nothing without one.\n */\n cacheBreakpoint?: \"cache_control\" | \"none\";\n /**\n * The conversation this model is serving, sent as `prompt_cache_key` on every\n * request. A provider that caches a prefix per backend routes requests that\n * share a key to the backend holding it; without one a growing conversation\n * lands on a different backend each turn and reads almost none of it back.\n * Meta's Muse Spark behind OpenRouter is the case measured: 3% of a\n * conversation's prefix read from cache without it, 91% with it. Set only\n * where the endpoint takes the field — plain OpenAI chat completions does\n * not — so the default sends none.\n */\n promptCacheKey?: string;\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 ...(options.promptCacheKey ? { prompt_cache_key: options.promptCacheKey } : {}),\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; promptCacheKey?: 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 ...(input.promptCacheKey ? { promptCacheKey: input.promptCacheKey } : {}),\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\" || part.type === \"file\");\n if (media.length) images.push({ type: \"text\", text: `Attachments 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 if (part.type === \"file\") {\n const file_data = part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`;\n parts.push({ type: \"file\", file: { filename: part.name ?? \"attachment\", file_data } });\n }\n // 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"]}
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;AA2C3E;;;GAGG;AACH,MAAM,UAAU,2BAA2B,CAAC,OAAgC;IAC1E,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,IAAI,KAAK,EAAE,EAAE,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IACzG,MAAM,QAAQ,GAAG,qBAAqB,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC;IAC5E,MAAM,OAAO,GAAG,OAAO,CAAC,eAAe,KAAK,eAAe,CAAC;IAC5D,OAAO;QACL,EAAE,EAAE,qBAAqB,OAAO,CAAC,KAAK,EAAE;QAExC,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAqB;YACnC,IAAI,QAAkB,CAAC;YACvB,IAAI,CAAC;gBACH,QAAQ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AO,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IACrG,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAChH,CAAC;AAED,+DAA+D;AAC/D,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAgC;IACvD,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,IAA4C,EAAE,CAAC;QACvE,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnC,OAAO,OAAO,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC7C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;YACnC,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { isWaitStatus, retrying, type RetryOptions } from \"../../retry.js\";\n\nexport interface OpenAiCompatibleOptions {\n apiKey: string;\n baseUrl: string;\n model: string;\n headers?: Readonly<Record<string, string>>;\n /**\n * How this endpoint spells reasoning effort. OpenAI takes `reasoning_effort`;\n * OpenRouter takes `reasoning: { effort }` and forwards it to whoever is\n * serving the model. Sending both is not compatibility — OpenAI rejects the\n * request outright — so the dialect is declared rather than guessed.\n */\n effortParameter?: \"reasoning_effort\" | \"reasoning\" | \"none\";\n /**\n * How this endpoint spells a cache breakpoint, where it has one. Most models\n * on this wire cache a repeated prefix by themselves and have no field for\n * it — plain OpenAI rejects one it does not know — so the default sends none.\n * OpenRouter takes Anthropic's `cache_control` on a text part and forwards\n * it to the models that cache nothing without one.\n */\n cacheBreakpoint?: \"cache_control\" | \"none\";\n /**\n * The conversation this model is serving, sent as `prompt_cache_key` on every\n * request. A provider that caches a prefix per backend routes requests that\n * share a key to the backend holding it; without one a growing conversation\n * lands on a different backend each turn and reads almost none of it back.\n * Meta's Muse Spark behind OpenRouter is the case measured: 3% of a\n * conversation's prefix read from cache without it, 91% with it. Set only\n * where the endpoint takes the field — plain OpenAI chat completions does\n * not — so the default sends none.\n */\n promptCacheKey?: string;\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 ...(options.promptCacheKey ? { prompt_cache_key: options.promptCacheKey } : {}),\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; extensions: Record<string, JsonValue> }>();\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 extensions: {},\n };\n if (fragment.id) existing.callId = fragment.id;\n const { index: _index, id: _id, type: _type, function: _function, ...extensions } = fragment;\n Object.assign(existing.extensions, extensions);\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 = [\n ...reasoningState(reasoningDetails, sawReasoningDetails, reasoning, reasoningContent),\n ...toolCallState([...calls.values()]),\n ];\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; promptCacheKey?: 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 ...(input.promptCacheKey ? { promptCacheKey: input.promptCacheKey } : {}),\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\" || part.type === \"file\");\n if (media.length) images.push({ type: \"text\", text: `Attachments 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 const extensions = decodeToolCallState(message, provider);\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 ...extensions.get(call.callId),\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 if (part.type === \"file\") {\n const file_data = part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`;\n parts.push({ type: \"file\", file: { filename: part.name ?? \"attachment\", file_data } });\n }\n // 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/**\n * Fields a provider adds to a tool call beyond the wire's own, kept by call id.\n * Gemini signs each call this way, under `extra_content`, and refuses the next\n * request if the signature does not come back on the call it was issued for.\n */\nfunction toolCallState(\n calls: readonly { callId: string; extensions: Readonly<Record<string, JsonValue>> }[],\n): JsonValue[] {\n const extended = calls.filter((call) => Object.keys(call.extensions).length);\n return extended.length ? [{ tool_calls: extended.map((call) => ({ ...call.extensions, id: call.callId })) }] : [];\n}\n\nfunction decodeToolCallState(\n message: Extract<Message, { role: \"assistant\" }>, provider: string,\n): ReadonlyMap<string, Readonly<Record<string, JsonValue>>> {\n const extensions = new Map<string, Readonly<Record<string, JsonValue>>>();\n if (message.providerState?.provider !== provider) return extensions;\n for (const item of message.providerState.items) {\n const calls = record(item)?.[\"tool_calls\"];\n if (!Array.isArray(calls)) continue;\n for (const call of calls) {\n const fields = record(call);\n if (typeof fields?.[\"id\"] === \"string\") extensions.set(fields[\"id\"], fields);\n }\n }\n return extensions;\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 ({\n index: number; id?: string; type?: string; function?: { name?: string; arguments?: string };\n } & Record<string, JsonValue | undefined>)[];\n };\n }[];\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-dray/aglib",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "type": "module",
5
5
  "description": "A small TypeScript toolkit for building your own agent harness.",
6
6
  "license": "MIT",