@a-dray/aglib 0.6.4 → 0.6.6

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.
@@ -101,7 +101,6 @@ export function createNativeHarness(options) {
101
101
  if (event.value.done)
102
102
  return;
103
103
  await finish(event.value.value);
104
- await context.drain?.();
105
104
  next = iterator.next();
106
105
  }
107
106
  };
@@ -309,6 +308,8 @@ export function createNativeHarness(options) {
309
308
  for (const call of calls)
310
309
  await finish(await executeOne(context, call));
311
310
  }
311
+ // Results commit individually, but incoming turn deliveries must wait
312
+ // until the foreground batch settles so they cannot split its replies.
312
313
  const arrived = await context.drain?.() ?? 0;
313
314
  if (synchronous.length || arrived || inputForNext || resultsForNextRequest || (calls.length && !context.tools))
314
315
  continue;
@@ -1 +1 @@
1
- {"version":3,"file":"loop.js","sourceRoot":"","sources":["../../../../src/harness/adapters/native/loop.ts"],"names":[],"mappings":"AAmBA,iFAAiF;AACjF,KAAK,UAAU,UAAU,CAAC,OAAuB,EAAE,IAAc;IAC/D,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACnB,OAAO;YACL,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,MAAM,EAAE,EAAE,OAAO,EAAE,kBAAkB,IAAI,CAAC,IAAI,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE;YAChF,UAAU,EAAE,EAAE;SACf,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,EAAE,MAAM,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;QAChG,OAAO,UAAU,CAAC;IACpB,CAAC;IACD,OAAO;QACL,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,MAAM,EAAE,EAAE,OAAO,EAAE,oBAAoB,EAAE,OAAO,EAAE,IAAI,EAAE;QACxD,UAAU,EAA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,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM;qBACjD,CAAC,CAAC,CAAC,CAAC;oBAEL,KAAK,MAAM,IAAI,IAAI,UAAU,EAAE,CAAC;wBAC9B,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;oBACtD,CAAC;oBAED,IAAI,WAAW,CAAC,MAAM;wBAAE,MAAM,YAAY,CAAC,WAAW,CAAC,CAAC;gBAC1D,CAAC;gBAED,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;oBACnC,KAAK,MAAM,IAAI,IAAI,KAAK;wBAAE,MAAM,MAAM,CAAC,MAAM,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;gBAC1E,CAAC;gBAED,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,CAAC;gBAC7C,IAAI,WAAW,CAAC,MAAM,IAAI,OAAO,IAAI,YAAY,IAAI,qBAAqB,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;oBAAE,SAAS;gBAEzH,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;oBACjB,MAAM,WAAW,EAAE,CAAC;oBACpB,SAAS;gBACX,CAAC;gBAED,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;YACnE,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { Harness, HarnessContext, HarnessResult } from \"../../harness.js\";\nimport type { Entry, ToolCall, ToolResult } from \"../../../session/entry.js\";\nimport type { Message, Model, ModelRequest, ModelSteerResult } from \"../../../model/model.js\";\nimport type { Delivery } from \"../../../store/store.js\";\n\nexport interface NativeHarnessOptions {\n model: Model;\n maxOutputTokens?: number;\n temperature?: number;\n /** How hard the model should think, where the provider supports it. */\n effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n}\n\ninterface Completion {\n callId: string;\n result: ToolResult;\n deliveries: readonly Delivery[];\n}\n\n/** Ask one tool call through the executor whose validation and policy own it. */\nasync function executeOne(context: HarnessContext, call: ToolCall): Promise<Completion> {\n if (!context.tools) {\n return {\n callId: call.callId,\n result: { content: `No tool named '${call.name}' is available.`, isError: true },\n deliveries: [],\n };\n }\n for await (const completion of context.tools.execute({ calls: [call], signal: context.signal })) {\n return completion;\n }\n return {\n callId: call.callId,\n result: { content: \"Tool use cancelled\", isError: true },\n deliveries: [],\n };\n}\n\n/** Calls left open by a process that died are never re-executed automatically. */\nfunction unresolved(context: HarnessContext): ToolCall[] {\n const answered = new Set(\n context.entries().filter((entry) => entry.type === \"tool.finished\")\n .map((entry) => `${entry.runId}\\u0000${entry.callId}`),\n );\n return context.entries().flatMap((entry) => entry.type === \"assistant\" && entry.runId === context.runId\n ? (entry.calls ?? []).filter((call) => !answered.has(`${entry.runId}\\u0000${call.callId}`))\n : []);\n}\n\n/**\n * Ask the model, run what it asks for, repeat.\n *\n * The loop holds no transcript. Every turn it re-reads `context.history()`,\n * which projects the committed log, and every result it produces goes back\n * through `context.commit` before the next turn is built. There is exactly one\n * representation of the conversation and it is the log.\n */\nexport function createNativeHarness(options: NativeHarnessOptions): Harness {\n return {\n id: \"native\",\n recovery: \"history\",\n\n async run(context: HarnessContext): Promise<HarnessResult> {\n const { runId } = context;\n const pending = new Map<string, Promise<Completion>>();\n const asyncTools = new Set(\n context.tools?.list().filter((tool) => tool.async === true).map((tool) => tool.name) ?? [],\n );\n const canRunAsync = (call: ToolCall) =>\n options.model.asyncTools === true && call.async === true && asyncTools.has(call.name);\n let resultsForNextRequest = false;\n\n // This function begins with unresolved calls only on recovery. Calls\n // started below stay in `pending` until they have reported back.\n const abandoned = unresolved(context);\n if (abandoned.length) {\n await context.commit(abandoned.map((call): Entry => ({\n type: \"tool.finished\", runId, callId: call.callId,\n result: {\n content: \"This call did not report back: the activation ended before its result was committed.\",\n isError: true,\n uncertain: true,\n },\n })));\n }\n\n const finish = async (completion: Completion) => {\n pending.delete(completion.callId);\n await context.commit([{\n type: \"tool.finished\", runId, callId: completion.callId, result: completion.result,\n }], completion.deliveries);\n resultsForNextRequest = true;\n };\n\n const firstPending = () => Promise.race(\n [...pending.entries()].map(async ([callId, completion]) => ({ callId, completion: await completion })),\n );\n\n const settlePending = async () => {\n while (pending.size) {\n const event = await firstPending();\n if (pending.has(event.callId)) await finish(event.completion);\n }\n };\n\n const startAsync = async (call: ToolCall) => {\n if (pending.has(call.callId)) return;\n if (!context.tools) {\n await finish(await executeOne(context, call));\n return;\n }\n await context.commit([{ type: \"tool.started\", runId, callId: call.callId }]);\n pending.set(call.callId, executeOne(context, call));\n };\n\n /** Commit foreground and background completions through the same writer. */\n const executeBatch = async (calls: readonly ToolCall[]) => {\n if (!context.tools) return;\n const iterator = context.tools.execute({ calls, signal: context.signal })[Symbol.asyncIterator]();\n let next = iterator.next();\n for (;;) {\n const event = await Promise.race([\n next.then((value) => ({ type: \"batch\" as const, value })),\n ...([...pending.entries()].map(async ([callId, completion]) => ({\n type: \"tool\" as const, value: { callId, completion: await completion },\n }))),\n ]);\n if (event.type === \"tool\") {\n if (pending.has(event.value.callId)) await finish(event.value.completion);\n continue;\n }\n if (event.value.done) return;\n await finish(event.value.value);\n await context.drain?.();\n next = iterator.next();\n }\n };\n\n // Input is raced only while it can still be folded in. After an abort,\n // `waitForInput` answers at once and `drain` folds nothing, and racing\n // them again is a microtask loop that never yields: every turn adds a\n // reaction to the pending delta, and a provider slow to honour the abort\n // sees the process eat memory until it is killed.\n const inputArm = () => context.waitForInput && !context.signal.aborted\n ? [context.waitForInput().then(() => ({ type: \"input\" as const }))]\n : [];\n\n /** Wait for one background result or newly delivered input. */\n const waitForWork = async (): Promise<void> => {\n for (;;) {\n const event = await Promise.race([\n firstPending().then((value) => ({ type: \"tool\" as const, value })),\n ...inputArm(),\n ]);\n if (event.type === \"tool\") {\n if (pending.has(event.value.callId)) await finish(event.value.completion);\n return;\n }\n if (await context.drain?.()) return;\n if (context.signal.aborted) return;\n }\n };\n\n for (;;) {\n if (context.signal.aborted) return { status: \"cancelled\" };\n\n for (const hook of context.hooks ?? []) {\n const failure = await hook.beforeModel?.(context);\n if (failure) return { status: \"failed\", error: failure };\n }\n if (context.signal.aborted) return { status: \"cancelled\" };\n const history = context.history();\n // Results committed after this snapshot need a later request even if\n // the active generation can continue independently of them.\n resultsForNextRequest = false;\n\n // The projection appends volatile turn context as its final system\n // message. Everything before it, including tool results, can be reused.\n const cacheAfter = history.length - (history.at(-1)?.role === \"system\" ? 1 : 0);\n const generationId = crypto.randomUUID();\n const startedAt = new Date().toISOString();\n const turn = context.context?.turn;\n const request: ModelRequest = {\n messages: history,\n ...(context.tools ? { tools: context.tools.list() } : {}),\n ...(options.maxOutputTokens !== undefined ? { maxOutputTokens: options.maxOutputTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n ...(options.effort ? { effort: options.effort } : {}),\n ...(cacheAfter > 0 ? { cacheAfter } : {}),\n signal: context.signal,\n };\n const generation = options.model.generate(request);\n\n const launched = new Set<string>();\n const steering = new Set<Promise<ModelSteerResult>>();\n let inputForNext = false;\n let next = generation.next();\n let step;\n\n for (;;) {\n const event = await Promise.race([\n next.then((value) => ({ type: \"model\" as const, value })),\n ...([...pending.entries()].map(async ([callId, completion]) => ({\n type: \"tool\" as const, value: { callId, completion: await completion },\n }))),\n ...inputArm(),\n ...([...steering].map(async (promise) => ({\n type: \"steer\" as const, promise, value: await promise,\n }))),\n ]);\n if (event.type === \"tool\") {\n if (pending.has(event.value.callId)) await finish(event.value.completion);\n continue;\n }\n if (event.type === \"steer\") {\n steering.delete(event.promise);\n if (event.value.status === \"rejected\") inputForNext = true;\n continue;\n }\n if (event.type === \"input\") {\n const arrived = await context.drain?.() ?? 0;\n if (!arrived) continue;\n const fresh = context.history().filter((message): message is Extract<Message, { role: \"user\" }> =>\n message.role === \"user\").slice(-arrived);\n if (!generation.steer || !fresh.length) {\n inputForNext = true;\n continue;\n }\n const attempt = generation.steer(fresh).catch((error): ModelSteerResult => ({\n status: \"rejected\",\n error: {\n code: \"failed\", retryable: true,\n message: error instanceof Error ? error.message : String(error),\n },\n }));\n steering.add(attempt);\n continue;\n }\n\n const current = event.value;\n if (current.done) { step = current; break; }\n const delta = current.value;\n if (delta.type === \"text.delta\") {\n context.emit({ ...delta, runId, generationId });\n }\n if (delta.type === \"reasoning.delta\") {\n context.emit({ type: \"reasoning.delta\", text: delta.text, runId, generationId });\n }\n if (delta.type === \"tool-call.delta\") {\n context.emit({\n type: \"tool-call.delta\", callId: delta.callId, arguments: delta.arguments, runId, generationId,\n });\n }\n if (delta.type === \"tool-call.done\" && canRunAsync(delta.call) && !launched.has(delta.call.callId)) {\n launched.add(delta.call.callId);\n await context.commit([{\n type: \"assistant\", runId, content: \"\", calls: [delta.call],\n generation: { id: generationId, startedAt, ...(turn ? { turn } : {}) },\n }]);\n await startAsync(delta.call);\n }\n next = generation.next();\n }\n\n for (const result of await Promise.all(steering)) {\n if (result.status === \"rejected\") inputForNext = true;\n }\n\n for (const hook of context.hooks ?? []) await hook.afterModel?.(context, step.value, request);\n if (!step.value.ok) {\n await settlePending();\n if ((inputForNext || resultsForNextRequest) && step.value.error.retryable &&\n step.value.error.code !== \"cancelled\" && !context.signal.aborted) continue;\n return step.value.error.code === \"cancelled\"\n ? { status: \"cancelled\" }\n : { status: \"failed\", error: step.value.error };\n }\n\n const endedAt = new Date().toISOString();\n const response = step.value.value;\n const calls = (response.message.calls ?? []).filter((call) => !launched.has(call.callId));\n\n await context.commit([{\n type: \"assistant\", runId, content: response.message.content,\n ...(calls.length ? { calls } : {}),\n usage: response.usage,\n ...(response.providerState ? { providerState: response.providerState } : {}),\n generation: {\n id: generationId,\n ...(response.model ? { model: response.model } : {}),\n startedAt,\n endedAt,\n ...(turn ? { turn } : {}),\n },\n }]);\n\n if (response.finishReason === \"length\") {\n // A truncated response can carry half-parsed arguments that happen to\n // be valid JSON. Calls already completed and launched by the provider\n // remain real; the incomplete remainder is refused.\n await context.commit(calls.map((call): Entry => ({\n type: \"tool.finished\", runId, callId: call.callId,\n result: {\n content: \"Not executed: the response was truncated. Reissue the call if it is still needed.\",\n isError: true,\n },\n })));\n await settlePending();\n if ((calls.length || resultsForNextRequest) && !context.signal.aborted) continue;\n return { status: \"failed\", error: {\n code: \"output-truncated\",\n message: \"The response stopped at the output limit before it was finished.\",\n retryable: false,\n } };\n }\n\n if (response.finishReason === \"refusal\" && !calls.length) {\n await settlePending();\n if ((inputForNext || resultsForNextRequest) && !context.signal.aborted) continue;\n return { status: \"failed\", error: {\n code: \"refused\", message: \"The provider declined to answer.\", retryable: false,\n } };\n }\n\n const asyncCalls = calls.filter(canRunAsync);\n const synchronous = calls.filter((call) => !canRunAsync(call));\n\n if (calls.length && context.tools) {\n await context.commit(calls.map((call): Entry => ({\n type: \"tool.started\", runId, callId: call.callId,\n })));\n\n for (const call of asyncCalls) {\n pending.set(call.callId, executeOne(context, call));\n }\n\n if (synchronous.length) await executeBatch(synchronous);\n }\n\n if (calls.length && !context.tools) {\n for (const call of calls) await finish(await executeOne(context, call));\n }\n\n const arrived = await context.drain?.() ?? 0;\n if (synchronous.length || arrived || inputForNext || resultsForNextRequest || (calls.length && !context.tools)) continue;\n\n if (pending.size) {\n await waitForWork();\n continue;\n }\n\n return { status: \"completed\", output: response.message.content };\n }\n },\n };\n}\n"]}
1
+ {"version":3,"file":"loop.js","sourceRoot":"","sources":["../../../../src/harness/adapters/native/loop.ts"],"names":[],"mappings":"AAmBA,iFAAiF;AACjF,KAAK,UAAU,UAAU,CAAC,OAAuB,EAAE,IAAc;IAC/D,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACnB,OAAO;YACL,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,MAAM,EAAE,EAAE,OAAO,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,IAAI,EAAE,CAAC;oBACjB,MAAM,WAAW,EAAE,CAAC;oBACpB,SAAS;gBACX,CAAC;gBAED,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;YACnE,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { Harness, HarnessContext, HarnessResult } from \"../../harness.js\";\nimport type { Entry, ToolCall, ToolResult } from \"../../../session/entry.js\";\nimport type { Message, Model, ModelRequest, ModelSteerResult } from \"../../../model/model.js\";\nimport type { Delivery } from \"../../../store/store.js\";\n\nexport interface NativeHarnessOptions {\n model: Model;\n maxOutputTokens?: number;\n temperature?: number;\n /** How hard the model should think, where the provider supports it. */\n effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n}\n\ninterface Completion {\n callId: string;\n result: ToolResult;\n deliveries: readonly Delivery[];\n}\n\n/** Ask one tool call through the executor whose validation and policy own it. */\nasync function executeOne(context: HarnessContext, call: ToolCall): Promise<Completion> {\n if (!context.tools) {\n return {\n callId: call.callId,\n result: { content: `No tool named '${call.name}' is available.`, isError: true },\n deliveries: [],\n };\n }\n for await (const completion of context.tools.execute({ calls: [call], signal: context.signal })) {\n return completion;\n }\n return {\n callId: call.callId,\n result: { content: \"Tool use cancelled\", isError: true },\n deliveries: [],\n };\n}\n\n/** Calls left open by a process that died are never re-executed automatically. */\nfunction unresolved(context: HarnessContext): ToolCall[] {\n const answered = new Set(\n context.entries().filter((entry) => entry.type === \"tool.finished\")\n .map((entry) => `${entry.runId}\\u0000${entry.callId}`),\n );\n return context.entries().flatMap((entry) => entry.type === \"assistant\" && entry.runId === context.runId\n ? (entry.calls ?? []).filter((call) => !answered.has(`${entry.runId}\\u0000${call.callId}`))\n : []);\n}\n\n/**\n * Ask the model, run what it asks for, repeat.\n *\n * The loop holds no transcript. Every turn it re-reads `context.history()`,\n * which projects the committed log, and every result it produces goes back\n * through `context.commit` before the next turn is built. There is exactly one\n * representation of the conversation and it is the log.\n */\nexport function createNativeHarness(options: NativeHarnessOptions): Harness {\n return {\n id: \"native\",\n recovery: \"history\",\n\n async run(context: HarnessContext): Promise<HarnessResult> {\n const { runId } = context;\n const pending = new Map<string, Promise<Completion>>();\n const asyncTools = new Set(\n context.tools?.list().filter((tool) => tool.async === true).map((tool) => tool.name) ?? [],\n );\n const canRunAsync = (call: ToolCall) =>\n options.model.asyncTools === true && call.async === true && asyncTools.has(call.name);\n let resultsForNextRequest = false;\n\n // This function begins with unresolved calls only on recovery. Calls\n // started below stay in `pending` until they have reported back.\n const abandoned = unresolved(context);\n if (abandoned.length) {\n await context.commit(abandoned.map((call): Entry => ({\n type: \"tool.finished\", runId, callId: call.callId,\n result: {\n content: \"This call did not report back: the activation ended before its result was committed.\",\n isError: true,\n uncertain: true,\n },\n })));\n }\n\n const finish = async (completion: Completion) => {\n pending.delete(completion.callId);\n await context.commit([{\n type: \"tool.finished\", runId, callId: completion.callId, result: completion.result,\n }], completion.deliveries);\n resultsForNextRequest = true;\n };\n\n const firstPending = () => Promise.race(\n [...pending.entries()].map(async ([callId, completion]) => ({ callId, completion: await completion })),\n );\n\n const settlePending = async () => {\n while (pending.size) {\n const event = await firstPending();\n if (pending.has(event.callId)) await finish(event.completion);\n }\n };\n\n const startAsync = async (call: ToolCall) => {\n if (pending.has(call.callId)) return;\n if (!context.tools) {\n await finish(await executeOne(context, call));\n return;\n }\n await context.commit([{ type: \"tool.started\", runId, callId: call.callId }]);\n pending.set(call.callId, executeOne(context, call));\n };\n\n /** Commit foreground and background completions through the same writer. */\n const executeBatch = async (calls: readonly ToolCall[]) => {\n if (!context.tools) return;\n const iterator = context.tools.execute({ calls, signal: context.signal })[Symbol.asyncIterator]();\n let next = iterator.next();\n for (;;) {\n const event = await Promise.race([\n next.then((value) => ({ type: \"batch\" as const, value })),\n ...([...pending.entries()].map(async ([callId, completion]) => ({\n type: \"tool\" as const, value: { callId, completion: await completion },\n }))),\n ]);\n if (event.type === \"tool\") {\n if (pending.has(event.value.callId)) await finish(event.value.completion);\n continue;\n }\n if (event.value.done) return;\n await finish(event.value.value);\n next = iterator.next();\n }\n };\n\n // Input is raced only while it can still be folded in. After an abort,\n // `waitForInput` answers at once and `drain` folds nothing, and racing\n // them again is a microtask loop that never yields: every turn adds a\n // reaction to the pending delta, and a provider slow to honour the abort\n // sees the process eat memory until it is killed.\n const inputArm = () => context.waitForInput && !context.signal.aborted\n ? [context.waitForInput().then(() => ({ type: \"input\" as const }))]\n : [];\n\n /** Wait for one background result or newly delivered input. */\n const waitForWork = async (): Promise<void> => {\n for (;;) {\n const event = await Promise.race([\n firstPending().then((value) => ({ type: \"tool\" as const, value })),\n ...inputArm(),\n ]);\n if (event.type === \"tool\") {\n if (pending.has(event.value.callId)) await finish(event.value.completion);\n return;\n }\n if (await context.drain?.()) return;\n if (context.signal.aborted) return;\n }\n };\n\n for (;;) {\n if (context.signal.aborted) return { status: \"cancelled\" };\n\n for (const hook of context.hooks ?? []) {\n const failure = await hook.beforeModel?.(context);\n if (failure) return { status: \"failed\", error: failure };\n }\n if (context.signal.aborted) return { status: \"cancelled\" };\n const history = context.history();\n // Results committed after this snapshot need a later request even if\n // the active generation can continue independently of them.\n resultsForNextRequest = false;\n\n // The projection appends volatile turn context as its final system\n // message. Everything before it, including tool results, can be reused.\n const cacheAfter = history.length - (history.at(-1)?.role === \"system\" ? 1 : 0);\n const generationId = crypto.randomUUID();\n const startedAt = new Date().toISOString();\n const turn = context.context?.turn;\n const request: ModelRequest = {\n messages: history,\n ...(context.tools ? { tools: context.tools.list() } : {}),\n ...(options.maxOutputTokens !== undefined ? { maxOutputTokens: options.maxOutputTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n ...(options.effort ? { effort: options.effort } : {}),\n ...(cacheAfter > 0 ? { cacheAfter } : {}),\n signal: context.signal,\n };\n const generation = options.model.generate(request);\n\n const launched = new Set<string>();\n const steering = new Set<Promise<ModelSteerResult>>();\n let inputForNext = false;\n let next = generation.next();\n let step;\n\n for (;;) {\n const event = await Promise.race([\n next.then((value) => ({ type: \"model\" as const, value })),\n ...([...pending.entries()].map(async ([callId, completion]) => ({\n type: \"tool\" as const, value: { callId, completion: await completion },\n }))),\n ...inputArm(),\n ...([...steering].map(async (promise) => ({\n type: \"steer\" as const, promise, value: await promise,\n }))),\n ]);\n if (event.type === \"tool\") {\n if (pending.has(event.value.callId)) await finish(event.value.completion);\n continue;\n }\n if (event.type === \"steer\") {\n steering.delete(event.promise);\n if (event.value.status === \"rejected\") inputForNext = true;\n continue;\n }\n if (event.type === \"input\") {\n const arrived = await context.drain?.() ?? 0;\n if (!arrived) continue;\n const fresh = context.history().filter((message): message is Extract<Message, { role: \"user\" }> =>\n message.role === \"user\").slice(-arrived);\n if (!generation.steer || !fresh.length) {\n inputForNext = true;\n continue;\n }\n const attempt = generation.steer(fresh).catch((error): ModelSteerResult => ({\n status: \"rejected\",\n error: {\n code: \"failed\", retryable: true,\n message: error instanceof Error ? error.message : String(error),\n },\n }));\n steering.add(attempt);\n continue;\n }\n\n const current = event.value;\n if (current.done) { step = current; break; }\n const delta = current.value;\n if (delta.type === \"text.delta\") {\n context.emit({ ...delta, runId, generationId });\n }\n if (delta.type === \"reasoning.delta\") {\n context.emit({ type: \"reasoning.delta\", text: delta.text, runId, generationId });\n }\n if (delta.type === \"tool-call.delta\") {\n context.emit({\n type: \"tool-call.delta\", callId: delta.callId, arguments: delta.arguments, runId, generationId,\n });\n }\n if (delta.type === \"tool-call.done\" && canRunAsync(delta.call) && !launched.has(delta.call.callId)) {\n launched.add(delta.call.callId);\n await context.commit([{\n type: \"assistant\", runId, content: \"\", calls: [delta.call],\n generation: { id: generationId, startedAt, ...(turn ? { turn } : {}) },\n }]);\n await startAsync(delta.call);\n }\n next = generation.next();\n }\n\n for (const result of await Promise.all(steering)) {\n if (result.status === \"rejected\") inputForNext = true;\n }\n\n for (const hook of context.hooks ?? []) await hook.afterModel?.(context, step.value, request);\n if (!step.value.ok) {\n await settlePending();\n if ((inputForNext || resultsForNextRequest) && step.value.error.retryable &&\n step.value.error.code !== \"cancelled\" && !context.signal.aborted) continue;\n return step.value.error.code === \"cancelled\"\n ? { status: \"cancelled\" }\n : { status: \"failed\", error: step.value.error };\n }\n\n const endedAt = new Date().toISOString();\n const response = step.value.value;\n const calls = (response.message.calls ?? []).filter((call) => !launched.has(call.callId));\n\n await context.commit([{\n type: \"assistant\", runId, content: response.message.content,\n ...(calls.length ? { calls } : {}),\n usage: response.usage,\n ...(response.providerState ? { providerState: response.providerState } : {}),\n generation: {\n id: generationId,\n ...(response.model ? { model: response.model } : {}),\n startedAt,\n endedAt,\n ...(turn ? { turn } : {}),\n },\n }]);\n\n if (response.finishReason === \"length\") {\n // A truncated response can carry half-parsed arguments that happen to\n // be valid JSON. Calls already completed and launched by the provider\n // remain real; the incomplete remainder is refused.\n await context.commit(calls.map((call): Entry => ({\n type: \"tool.finished\", runId, callId: call.callId,\n result: {\n content: \"Not executed: the response was truncated. Reissue the call if it is still needed.\",\n isError: true,\n },\n })));\n await settlePending();\n if ((calls.length || resultsForNextRequest) && !context.signal.aborted) continue;\n return { status: \"failed\", error: {\n code: \"output-truncated\",\n message: \"The response stopped at the output limit before it was finished.\",\n retryable: false,\n } };\n }\n\n if (response.finishReason === \"refusal\" && !calls.length) {\n await settlePending();\n if ((inputForNext || resultsForNextRequest) && !context.signal.aborted) continue;\n return { status: \"failed\", error: {\n code: \"refused\", message: \"The provider declined to answer.\", retryable: false,\n } };\n }\n\n const asyncCalls = calls.filter(canRunAsync);\n const synchronous = calls.filter((call) => !canRunAsync(call));\n\n if (calls.length && context.tools) {\n await context.commit(calls.map((call): Entry => ({\n type: \"tool.started\", runId, callId: call.callId,\n })));\n\n for (const call of asyncCalls) {\n pending.set(call.callId, executeOne(context, call));\n }\n\n if (synchronous.length) await executeBatch(synchronous);\n }\n\n if (calls.length && !context.tools) {\n for (const call of calls) await finish(await executeOne(context, call));\n }\n\n // Results commit individually, but incoming turn deliveries must wait\n // until the foreground batch settles so they cannot split its replies.\n const arrived = await context.drain?.() ?? 0;\n if (synchronous.length || arrived || inputForNext || resultsForNextRequest || (calls.length && !context.tools)) continue;\n\n if (pending.size) {\n await waitForWork();\n continue;\n }\n\n return { status: \"completed\", output: response.message.content };\n }\n },\n };\n}\n"]}
@@ -20,6 +20,17 @@ export interface OpenAiCompatibleOptions {
20
20
  * it to the models that cache nothing without one.
21
21
  */
22
22
  cacheBreakpoint?: "cache_control" | "none";
23
+ /**
24
+ * The conversation this model is serving, sent as `prompt_cache_key` on every
25
+ * request. A provider that caches a prefix per backend routes requests that
26
+ * share a key to the backend holding it; without one a growing conversation
27
+ * lands on a different backend each turn and reads almost none of it back.
28
+ * Meta's Muse Spark behind OpenRouter is the case measured: 3% of a
29
+ * conversation's prefix read from cache without it, 91% with it. Set only
30
+ * where the endpoint takes the field — plain OpenAI chat completions does
31
+ * not — so the default sends none.
32
+ */
33
+ promptCacheKey?: string;
23
34
  /**
24
35
  * A refusal this endpoint means as a wait, beyond the statuses every HTTP
25
36
  * wire means so. Retried before the first delta like those, and reported as
@@ -56,5 +67,6 @@ export declare function createOpenRouterModel(input: {
56
67
  model: string;
57
68
  appUrl?: string;
58
69
  appName?: string;
70
+ promptCacheKey?: string;
59
71
  fetch?: typeof fetch;
60
72
  }): Model;
@@ -28,6 +28,7 @@ export function createOpenAiCompatibleModel(options) {
28
28
  ...(request.maxOutputTokens !== undefined ? { max_tokens: request.maxOutputTokens } : {}),
29
29
  ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),
30
30
  ...encodeEffort(request.effort, options.effortParameter ?? "reasoning_effort"),
31
+ ...(options.promptCacheKey ? { prompt_cache_key: options.promptCacheKey } : {}),
31
32
  stream: true,
32
33
  stream_options: { include_usage: true },
33
34
  }),
@@ -152,6 +153,7 @@ export function createOpenRouterModel(input) {
152
153
  effortParameter: "reasoning",
153
154
  cacheBreakpoint: /^~?anthropic\//.test(input.model) ? "cache_control" : "none",
154
155
  isWait: inFlightBudgetExhausted,
156
+ ...(input.promptCacheKey ? { promptCacheKey: input.promptCacheKey } : {}),
155
157
  headers: {
156
158
  ...(input.appUrl ? { "http-referer": input.appUrl } : {}),
157
159
  ...(input.appName ? { "x-title": input.appName } : {}),
@@ -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,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IACzG,MAAM,QAAQ,GAAG,qBAAqB,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC;IAC5E,MAAM,OAAO,GAAG,OAAO,CAAC,eAAe,KAAK,eAAe,CAAC;IAC5D,OAAO;QACL,EAAE,EAAE,qBAAqB,OAAO,CAAC,KAAK,EAAE;QAExC,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAqB;YACnC,IAAI,QAAkB,CAAC;YACvB,IAAI,CAAC;gBACH,QAAQ,GAAG,MAAM,IAAI,CAAC,GAAG,OAAO,CAAC,OAAO,mBAAmB,EAAE;oBAC3D,MAAM,EAAE,MAAM;oBACd,OAAO,EAAE;wBACP,cAAc,EAAE,kBAAkB;wBAClC,aAAa,EAAE,UAAU,OAAO,CAAC,M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E,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 * 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"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/openai-compatible/index.ts"],"names":[],"mapp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,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 }>();\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\");\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"]}
@@ -62,10 +62,7 @@ class ResponsesHub {
62
62
  this.#closeWhenDrained();
63
63
  }
64
64
  close() {
65
- if (this.#ended)
66
- return;
67
65
  this.#finish({ type: "close", reason: "Responses model closed" });
68
- this.#connection.close();
69
66
  }
70
67
  async #read() {
71
68
  try {
@@ -136,6 +133,9 @@ class ResponsesHub {
136
133
  lane.queue.end();
137
134
  this.#lanes.clear();
138
135
  this.#onEnd();
136
+ // A hub that has stopped reading must not leave its socket open: nothing would hear what it
137
+ // says next, and the SDK raises an error nobody listens for as an unhandled rejection.
138
+ this.#connection.close();
139
139
  }
140
140
  }
141
141
  /**
@@ -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,K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AAM,SAAS,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 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"]}
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;A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AC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,IAAI,4BAA4B,CAAC,CAAC;IACvG,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AACxD,CAAC;AAED,MAAM,SAAS,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 this.#finish({ type: \"close\", reason: \"Responses model closed\" });\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 // A hub that has stopped reading must not leave its socket open: nothing would hear what it\n // says next, and the SDK raises an error nobody listens for as an unhandled rejection.\n this.#connection.close();\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"]}
@@ -43,8 +43,9 @@ export function toMessages(input) {
43
43
  // rejects an assistant turn holding a call with no result, so leaving the gap
44
44
  // would make the session permanently unusable. What is said is what is known
45
45
  // — the call did not report back — and never an invented result.
46
- const answered = new Set(input.entries.filter((entry) => entry.type === "tool.finished")
47
- .map((entry) => `${entry.runId}\u0000${entry.callId}`));
46
+ const answered = new Map(input.entries.filter((entry) => entry.type === "tool.finished")
47
+ .map((entry) => [`${entry.runId}\u0000${entry.callId}`, entry]));
48
+ const placed = new Set();
48
49
  const closed = new Set(input.entries.filter((entry) => entry.type === "run.finished").map((entry) => entry.runId));
49
50
  for (const entry of input.entries) {
50
51
  // The checkpoint describes the replaced prefix, not the moment it was
@@ -68,6 +69,18 @@ export function toMessages(input) {
68
69
  ...(entry.calls?.length ? { calls: entry.calls.map(parseable) } : {}),
69
70
  ...(entry.providerState ? { providerState: entry.providerState } : {}),
70
71
  });
72
+ // Older logs may have input between synchronous results. Group them
73
+ // beside their calls without rewriting the log or moving async results
74
+ // ahead of work that genuinely ran while those calls were pending.
75
+ const results = (entry.calls ?? []).filter((call) => !call.async)
76
+ .flatMap((call) => {
77
+ const result = answered.get(`${entry.runId}\u0000${call.callId}`);
78
+ return result && result.seq > cut ? [result] : [];
79
+ }).sort((a, b) => a.seq - b.seq);
80
+ for (const result of results) {
81
+ messages.push(toolMessage(result));
82
+ placed.add(result);
83
+ }
71
84
  for (const call of entry.calls ?? []) {
72
85
  if (answered.has(`${entry.runId}\u0000${call.callId}`) || !closed.has(entry.runId))
73
86
  continue;
@@ -79,16 +92,8 @@ export function toMessages(input) {
79
92
  break;
80
93
  }
81
94
  case "tool.finished":
82
- messages.push({
83
- role: "tool",
84
- callId: entry.callId,
85
- content: entry.result.uncertain
86
- ? typeof entry.result.content === "string"
87
- ? `Effect unknown. Reconcile the original action before retrying, including under a new call ID.\n${entry.result.content}`
88
- : [{ type: "text", text: "Effect unknown. Reconcile the original action before retrying, including under a new call ID." }, ...entry.result.content]
89
- : entry.result.content,
90
- ...(entry.result.isError ? { isError: true } : {}),
91
- });
95
+ if (!placed.has(entry))
96
+ messages.push(toolMessage(entry));
92
97
  break;
93
98
  // Not model-visible: tool.started and run.context are bookkeeping, and
94
99
  // run.finished is a boundary.
@@ -104,6 +109,18 @@ export function toMessages(input) {
104
109
  messages.push({ role: "system", content: input.context.turn });
105
110
  return messages;
106
111
  }
112
+ function toolMessage(entry) {
113
+ return {
114
+ role: "tool",
115
+ callId: entry.callId,
116
+ content: entry.result.uncertain
117
+ ? typeof entry.result.content === "string"
118
+ ? `Effect unknown. Reconcile the original action before retrying, including under a new call ID.\n${entry.result.content}`
119
+ : [{ type: "text", text: "Effect unknown. Reconcile the original action before retrying, including under a new call ID." }, ...entry.result.content]
120
+ : entry.result.content,
121
+ ...(entry.result.isError ? { isError: true } : {}),
122
+ };
123
+ }
107
124
  /**
108
125
  * A call whose arguments the model never finished as JSON. The log keeps the
109
126
  * string as it was sent, and dispatch has already answered it with a failure;
@@ -1 +1 @@
1
- {"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/session/messages.ts"],"names":[],"mappings":"AAaA;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAAC,OAA0B;IACtD,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AACxG,CAAC;AAED,8EAA8E;AAC9E,SAAS,QAAQ,CAAC,KAAc,EAAE,IAAsB;IACtD,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAC;IACxB,MAAM,KAAK,GAAG,SAAS,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,EAAE,GAAG,CAAC;IAC/C,OAAO,OAAO,KAAK,KAAK,QAAQ;QAC9B,CAAC,CAAC,GAAG,KAAK,KAAK,KAAK,EAAE;QACtB,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,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AAc;gBACjB,MAAM;QACV,CAAC;IACH,CAAC;IAED,6EAA6E;IAC7E,oEAAoE;IACpE,IAAI,KAAK,CAAC,OAAO,EAAE,IAAI;QAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IACxF,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,SAAS,CAAC,IAAc;IAC/B,IAAI,CAAC;QAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAAC,OAAO,IAAI,CAAC;IAAC,CAAC;IAChD,MAAM,CAAC;QAAC,OAAO,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,EAAE,CAAC;IAAC,CAAC;AACzF,CAAC","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { From, ProviderState, Stored, ToolCall } from \"./entry.js\";\n\n/**\n * A message as a provider takes it: built per turn from the log, never held.\n * Every call's `arguments` parses here, whatever the log holds.\n */\nexport type Message =\n | { role: \"system\"; content: Content }\n | { role: \"user\"; content: Content }\n | { role: \"assistant\"; content: Content; calls?: readonly ToolCall[]; providerState?: ProviderState }\n | { role: \"tool\"; callId: string; content: Content; isError?: boolean };\n\n/**\n * The position everything up to has been folded into a summary.\n *\n * One answer, because two callers need it: the projection skips what is folded,\n * and the loop refuses to cut at or behind it. They were the same reduce written\n * out twice.\n */\nexport function foldedThrough(entries: readonly Stored[]): number {\n return entries.reduce((at, entry) => entry.type === \"summary\" ? Math.max(at, entry.replaces) : at, 0);\n}\n\n/** Names the sender in the turn itself, since only text reaches the model. */\nfunction labelled(input: Content, from: From | undefined): Content {\n if (!from) return input;\n const label = `[from ${from.kind} ${from.id}]`;\n return typeof input === \"string\"\n ? `${label}\\n${input}`\n : [{ type: \"text\" as const, text: label }, ...input];\n}\n\n/**\n * The log projected into what a provider takes.\n *\n * Built fresh for every request and never held. That is the whole reason there\n * is no second transcript to drift from the log, and why nothing needs a test\n * proving two representations agree.\n */\nexport function toMessages(input: {\n instructions: Content;\n entries: readonly Stored[];\n context?: { run?: string; turn?: string };\n /**\n * Name each arrival's sender in the turn text, as `[from kind id]`.\n *\n * Off by default. `from` is provenance the log keeps whatever this says; an\n * application that renders its own attribution into the input it delivers\n * would otherwise hand the model two names for one sender, one of them a\n * session id that means nothing to it.\n */\n attribution?: boolean;\n}): readonly Message[] {\n const messages: Message[] = [{ role: \"system\", content: input.instructions }];\n\n // Run-scoped context sits immediately after the instructions, inside the\n // cacheable prefix, because it does not change for the life of the run.\n if (input.context?.run) messages.push({ role: \"system\", content: input.context.run });\n\n // A summary folds everything up to `replaces`. The source entries stay in the\n // log — compaction changes what the model sees, never what happened.\n const cut = foldedThrough(input.entries);\n const summary = input.entries.findLast((entry) => entry.type === \"summary\" && entry.replaces === cut);\n if (summary?.type === \"summary\") {\n messages.push({ role: \"user\", content: `<summary>\\n${summary.content}\\n</summary>` });\n }\n\n // A call whose result never committed. It happens when an activation ends\n // between asking and answering — cancelled, interrupted, or beaten to the\n // commit by another worker. The projection has to close it: a provider\n // rejects an assistant turn holding a call with no result, so leaving the gap\n // would make the session permanently unusable. What is said is what is known\n // — the call did not report back — and never an invented result.\n const answered = new Set(\n input.entries.filter((entry) => entry.type === \"tool.finished\")\n .map((entry) => `${entry.runId}\\u0000${entry.callId}`),\n );\n const closed = new Set(\n input.entries.filter((entry) => entry.type === \"run.finished\").map((entry) => entry.runId),\n );\n\n for (const entry of input.entries) {\n // The checkpoint describes the replaced prefix, not the moment it was\n // written. Newer instructions must follow it, including after another fold.\n if (entry.seq <= cut || entry.type === \"summary\") continue;\n switch (entry.type) {\n case \"hook.input\":\n messages.push({ role: \"user\", content: entry.input });\n break;\n case \"run.started\":\n messages.push({\n role: \"user\",\n content: input.attribution ? labelled(entry.input, entry.from) : entry.input,\n });\n break;\n case \"assistant\": {\n messages.push({\n role: \"assistant\",\n content: entry.content,\n ...(entry.calls?.length ? { calls: entry.calls.map(parseable) } : {}),\n ...(entry.providerState ? { providerState: entry.providerState } : {}),\n });\n for (const call of entry.calls ?? []) {\n if (answered.has(`${entry.runId}\\u0000${call.callId}`) || !closed.has(entry.runId)) continue;\n messages.push({\n role: \"tool\", callId: call.callId, isError: true,\n content: \"This call did not report back: the activation ended before its result was committed. Its effect is unknown. Reconcile the original action before retrying, including under a new call ID.\",\n });\n }\n break;\n }\n case \"tool.finished\":\n messages.push({\n role: \"tool\",\n callId: entry.callId,\n content: entry.result.uncertain\n ? typeof entry.result.content === \"string\"\n ? `Effect unknown. Reconcile the original action before retrying, including under a new call ID.\\n${entry.result.content}`\n : [{ type: \"text\", text: \"Effect unknown. Reconcile the original action before retrying, including under a new call ID.\" }, ...entry.result.content]\n : entry.result.content,\n ...(entry.result.isError ? { isError: true } : {}),\n });\n break;\n // Not model-visible: tool.started and run.context are bookkeeping, and\n // run.finished is a boundary.\n case \"tool.started\":\n case \"run.context\":\n case \"run.finished\":\n break;\n }\n }\n\n // Turn-scoped context sits last, after the cache boundary, because it is for\n // this request only and must not be written into the cached prefix.\n if (input.context?.turn) messages.push({ role: \"system\", content: input.context.turn });\n return messages;\n}\n\n/**\n * A call whose arguments the model never finished as JSON. The log keeps the\n * string as it was sent, and dispatch has already answered it with a failure;\n * but a strict provider validates every call in the history it is handed, and\n * one it cannot parse fails the whole request — every request, since the\n * history is replayed whole — which is a session nobody can use again. The\n * projection renders it as JSON that still holds what was said, so the model\n * reads its own mistake beside the result that named it, on any wire.\n */\nfunction parseable(call: ToolCall): ToolCall {\n try { JSON.parse(call.arguments); return call; }\n catch { return { ...call, arguments: JSON.stringify({ _unparsed: call.arguments }) }; }\n}\n"]}
1
+ {"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/session/messages.ts"],"names":[],"mappings":"AAaA;;;;;;GAMG;AACH,M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,CAAC;IACxF,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,SAAS,WAAW,CAAC,KAAiD;IACpE,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,SAAS;YAC7B,CAAC,CAAC,OAAO,KAAK,CAAC,MAAM,CAAC,OAAO,KAAK,QAAQ;gBACxC,CAAC,CAAC,kGAAkG,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE;gBAC1H,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,+FAA+F,EAAE,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC;YACtJ,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO;QACxB,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACnD,CAAC;AACJ,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,SAAS,CAAC,IAAc;IAC/B,IAAI,CAAC;QAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAAC,OAAO,IAAI,CAAC;IAAC,CAAC;IAChD,MAAM,CAAC;QAAC,OAAO,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,EAAE,CAAC;IAAC,CAAC;AACzF,CAAC","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { From, ProviderState, Stored, ToolCall } from \"./entry.js\";\n\n/**\n * A message as a provider takes it: built per turn from the log, never held.\n * Every call's `arguments` parses here, whatever the log holds.\n */\nexport type Message =\n | { role: \"system\"; content: Content }\n | { role: \"user\"; content: Content }\n | { role: \"assistant\"; content: Content; calls?: readonly ToolCall[]; providerState?: ProviderState }\n | { role: \"tool\"; callId: string; content: Content; isError?: boolean };\n\n/**\n * The position everything up to has been folded into a summary.\n *\n * One answer, because two callers need it: the projection skips what is folded,\n * and the loop refuses to cut at or behind it. They were the same reduce written\n * out twice.\n */\nexport function foldedThrough(entries: readonly Stored[]): number {\n return entries.reduce((at, entry) => entry.type === \"summary\" ? Math.max(at, entry.replaces) : at, 0);\n}\n\n/** Names the sender in the turn itself, since only text reaches the model. */\nfunction labelled(input: Content, from: From | undefined): Content {\n if (!from) return input;\n const label = `[from ${from.kind} ${from.id}]`;\n return typeof input === \"string\"\n ? `${label}\\n${input}`\n : [{ type: \"text\" as const, text: label }, ...input];\n}\n\n/**\n * The log projected into what a provider takes.\n *\n * Built fresh for every request and never held. That is the whole reason there\n * is no second transcript to drift from the log, and why nothing needs a test\n * proving two representations agree.\n */\nexport function toMessages(input: {\n instructions: Content;\n entries: readonly Stored[];\n context?: { run?: string; turn?: string };\n /**\n * Name each arrival's sender in the turn text, as `[from kind id]`.\n *\n * Off by default. `from` is provenance the log keeps whatever this says; an\n * application that renders its own attribution into the input it delivers\n * would otherwise hand the model two names for one sender, one of them a\n * session id that means nothing to it.\n */\n attribution?: boolean;\n}): readonly Message[] {\n const messages: Message[] = [{ role: \"system\", content: input.instructions }];\n\n // Run-scoped context sits immediately after the instructions, inside the\n // cacheable prefix, because it does not change for the life of the run.\n if (input.context?.run) messages.push({ role: \"system\", content: input.context.run });\n\n // A summary folds everything up to `replaces`. The source entries stay in the\n // log — compaction changes what the model sees, never what happened.\n const cut = foldedThrough(input.entries);\n const summary = input.entries.findLast((entry) => entry.type === \"summary\" && entry.replaces === cut);\n if (summary?.type === \"summary\") {\n messages.push({ role: \"user\", content: `<summary>\\n${summary.content}\\n</summary>` });\n }\n\n // A call whose result never committed. It happens when an activation ends\n // between asking and answering — cancelled, interrupted, or beaten to the\n // commit by another worker. The projection has to close it: a provider\n // rejects an assistant turn holding a call with no result, so leaving the gap\n // would make the session permanently unusable. What is said is what is known\n // — the call did not report back — and never an invented result.\n const answered = new Map(\n input.entries.filter((entry) => entry.type === \"tool.finished\")\n .map((entry) => [`${entry.runId}\\u0000${entry.callId}`, entry] as const),\n );\n const placed = new Set<Stored>();\n const closed = new Set(\n input.entries.filter((entry) => entry.type === \"run.finished\").map((entry) => entry.runId),\n );\n\n for (const entry of input.entries) {\n // The checkpoint describes the replaced prefix, not the moment it was\n // written. Newer instructions must follow it, including after another fold.\n if (entry.seq <= cut || entry.type === \"summary\") continue;\n switch (entry.type) {\n case \"hook.input\":\n messages.push({ role: \"user\", content: entry.input });\n break;\n case \"run.started\":\n messages.push({\n role: \"user\",\n content: input.attribution ? labelled(entry.input, entry.from) : entry.input,\n });\n break;\n case \"assistant\": {\n messages.push({\n role: \"assistant\",\n content: entry.content,\n ...(entry.calls?.length ? { calls: entry.calls.map(parseable) } : {}),\n ...(entry.providerState ? { providerState: entry.providerState } : {}),\n });\n // Older logs may have input between synchronous results. Group them\n // beside their calls without rewriting the log or moving async results\n // ahead of work that genuinely ran while those calls were pending.\n const results = (entry.calls ?? []).filter((call) => !call.async)\n .flatMap((call) => {\n const result = answered.get(`${entry.runId}\\u0000${call.callId}`);\n return result && result.seq > cut ? [result] : [];\n }).sort((a, b) => a.seq - b.seq);\n for (const result of results) {\n messages.push(toolMessage(result));\n placed.add(result);\n }\n for (const call of entry.calls ?? []) {\n if (answered.has(`${entry.runId}\\u0000${call.callId}`) || !closed.has(entry.runId)) continue;\n messages.push({\n role: \"tool\", callId: call.callId, isError: true,\n content: \"This call did not report back: the activation ended before its result was committed. Its effect is unknown. Reconcile the original action before retrying, including under a new call ID.\",\n });\n }\n break;\n }\n case \"tool.finished\":\n if (!placed.has(entry)) messages.push(toolMessage(entry));\n break;\n // Not model-visible: tool.started and run.context are bookkeeping, and\n // run.finished is a boundary.\n case \"tool.started\":\n case \"run.context\":\n case \"run.finished\":\n break;\n }\n }\n\n // Turn-scoped context sits last, after the cache boundary, because it is for\n // this request only and must not be written into the cached prefix.\n if (input.context?.turn) messages.push({ role: \"system\", content: input.context.turn });\n return messages;\n}\n\nfunction toolMessage(entry: Extract<Stored, { type: \"tool.finished\" }>): Message {\n return {\n role: \"tool\",\n callId: entry.callId,\n content: entry.result.uncertain\n ? typeof entry.result.content === \"string\"\n ? `Effect unknown. Reconcile the original action before retrying, including under a new call ID.\\n${entry.result.content}`\n : [{ type: \"text\", text: \"Effect unknown. Reconcile the original action before retrying, including under a new call ID.\" }, ...entry.result.content]\n : entry.result.content,\n ...(entry.result.isError ? { isError: true } : {}),\n };\n}\n\n/**\n * A call whose arguments the model never finished as JSON. The log keeps the\n * string as it was sent, and dispatch has already answered it with a failure;\n * but a strict provider validates every call in the history it is handed, and\n * one it cannot parse fails the whole request — every request, since the\n * history is replayed whole — which is a session nobody can use again. The\n * projection renders it as JSON that still holds what was said, so the model\n * reads its own mistake beside the result that named it, on any wire.\n */\nfunction parseable(call: ToolCall): ToolCall {\n try { JSON.parse(call.arguments); return call; }\n catch { return { ...call, arguments: JSON.stringify({ _unparsed: call.arguments }) }; }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-dray/aglib",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
4
4
  "type": "module",
5
5
  "description": "A small TypeScript toolkit for building your own agent harness.",
6
6
  "license": "MIT",