@a-dray/aglib 0.6.5 → 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"]}
@@ -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,KAAK,CAAC;IAClB,MAAM,GAAG,KAAK,CAAC;IAEf,YAAY,UA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AE,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;AAgDxB,MAAM,YAAY;IACP,WAAW,CAA4B;IACvC,MAAM,GAAG,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M,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,KAAK,EAAE,EAAE,GAAG,KAAK,CAAC,CAAC;AACzD,CAAC;A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C7E,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,MAAM,UAAU,aAAa,CAAC,OAA0B;IACtD,OAAO,OAAO,CAAC,M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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.5",
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",