@a-dray/aglib 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -150,7 +150,8 @@ export function createNativeHarness(options) {
150
150
  const cacheAfter = history.length - (history.at(-1)?.role === "system" ? 1 : 0);
151
151
  const generationId = crypto.randomUUID();
152
152
  const startedAt = new Date().toISOString();
153
- const generation = options.model.generate({
153
+ const turn = context.context?.turn;
154
+ const request = {
154
155
  messages: history,
155
156
  ...(context.tools ? { tools: context.tools.list() } : {}),
156
157
  ...(options.maxOutputTokens !== undefined ? { maxOutputTokens: options.maxOutputTokens } : {}),
@@ -158,7 +159,8 @@ export function createNativeHarness(options) {
158
159
  ...(options.effort ? { effort: options.effort } : {}),
159
160
  ...(cacheAfter > 0 ? { cacheAfter } : {}),
160
161
  signal: context.signal,
161
- });
162
+ };
163
+ const generation = options.model.generate(request);
162
164
  const launched = new Set();
163
165
  const steering = new Set();
164
166
  let inputForNext = false;
@@ -226,7 +228,7 @@ export function createNativeHarness(options) {
226
228
  launched.add(delta.call.callId);
227
229
  await context.commit([{
228
230
  type: "assistant", runId, content: "", calls: [delta.call],
229
- generation: { id: generationId, startedAt },
231
+ generation: { id: generationId, startedAt, ...(turn ? { turn } : {}) },
230
232
  }]);
231
233
  await startAsync(delta.call);
232
234
  }
@@ -237,7 +239,7 @@ export function createNativeHarness(options) {
237
239
  inputForNext = true;
238
240
  }
239
241
  for (const hook of context.hooks ?? [])
240
- await hook.afterModel?.(context, step.value);
242
+ await hook.afterModel?.(context, step.value, request);
241
243
  if (!step.value.ok) {
242
244
  await settlePending();
243
245
  if ((inputForNext || resultsForNextRequest) && step.value.error.retryable &&
@@ -256,7 +258,11 @@ export function createNativeHarness(options) {
256
258
  usage: response.usage,
257
259
  ...(response.providerState ? { providerState: response.providerState } : {}),
258
260
  generation: {
259
- id: generationId, ...(response.model ? { model: response.model } : {}), startedAt, endedAt,
261
+ id: generationId,
262
+ ...(response.model ? { model: response.model } : {}),
263
+ startedAt,
264
+ endedAt,
265
+ ...(turn ? { turn } : {}),
260
266
  },
261
267
  }]);
262
268
  if (response.finishReason === "length") {
@@ -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,EAAE,EAAE;KACf,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,SAAS,UAAU,CAAC,OAAuB;IACzC,MAAM,QAAQ,GAAG,IAAI,GAAG,CACtB,OAAO,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,eAAe,CAAC;SAChE,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,KAAK,SAAS,KAAK,CAAC,MAAM,EAAE,CAAC,CACzD,CAAC;IACF,OAAO,OAAO,CAAC,OAAO,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,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, 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 generation = options.model.generate({\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\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 },\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);\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, ...(response.model ? { model: response.model } : {}), startedAt, endedAt,\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,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,EAAE,EAAE;KACf,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,SAAS,UAAU,CAAC,OAAuB;IACzC,MAAM,QAAQ,GAAG,IAAI,GAAG,CACtB,OAAO,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,eAAe,CAAC;SAChE,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,KAAK,SA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,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,6 +1,6 @@
1
1
  import type { Content } from "../content.js";
2
2
  import type { Delivery, Entry, Stored, Usage } from "../session/entry.js";
3
- import type { Message, ModelResponse, ModelError } from "../model/model.js";
3
+ import type { Message, ModelRequest, ModelResponse, ModelError } from "../model/model.js";
4
4
  import type { Result } from "../result.js";
5
5
  import type { ToolExecutor } from "../tools/tool.js";
6
6
  import type { Failure } from "../result.js";
@@ -132,7 +132,12 @@ export interface LifecycleHook {
132
132
  name: string;
133
133
  beforeRun?(context: HarnessContext): void | Promise<void>;
134
134
  beforeModel?(context: HarnessContext): void | Failure | Promise<void | Failure>;
135
- afterModel?(context: HarnessContext, result: Result<ModelResponse, ModelError>): void | Promise<void>;
135
+ /**
136
+ * After one generation, with the request that was sent. The native harness
137
+ * always has that request; an external harness that owns its loop need not
138
+ * expose the boundary at all.
139
+ */
140
+ afterModel?(context: HarnessContext, result: Result<ModelResponse, ModelError>, request: ModelRequest): void | Promise<void>;
136
141
  /** Only a completed, non-cancelled run may continue, once per hook name and run id. */
137
142
  beforeStop?(context: HarnessContext, result: HarnessResult): void | {
138
143
  input: Content;
@@ -1 +1 @@
1
- {"version":3,"file":"harness.js","sourceRoot":"","sources":["../../src/harness/harness.ts"],"names":[],"mappings":"","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { Delivery, Entry, Stored, Usage } from \"../session/entry.js\";\nimport type { Message, ModelResponse, ModelError } from \"../model/model.js\";\nimport type { Result } from \"../result.js\";\nimport type { ToolExecutor } from \"../tools/tool.js\";\nimport type { Failure } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/**\n * Ephemeral output for a live viewer. Only committed entries are recovery state.\n *\n * An `entry` update carries the whole `Stored` shape — sequence and commit time\n * both. Anything building a live projection off this stream needs the timestamp\n * the log already has, and inventing one at receipt would put a second answer\n * to the same question into the world.\n */\nexport type Update =\n | { type: \"hook.error\"; hook: string; message: string }\n | { type: \"text.delta\"; text: string; phase?: \"commentary\" | \"final_answer\"; runId?: string; generationId?: string }\n | { type: \"reasoning.delta\"; text: string; runId?: string; generationId?: string }\n | { type: \"tool.progress\"; callId: string; data: JsonValue }\n /** Arguments arriving a fragment at a time, so a viewer can show a call forming. */\n | { type: \"tool-call.delta\"; callId: string; arguments: string; runId?: string; generationId?: string }\n | { type: \"entry\"; entry: Stored };\n\nexport interface HarnessContext {\n /** The same callbacks used by the run; a harness invokes model boundaries it owns. */\n hooks?: readonly LifecycleHook[];\n sessionId: string;\n runId: string;\n instructions: Content;\n /**\n * The log projected for this turn. A function, not a snapshot: it is rebuilt\n * from committed entries every time it is read, so a harness cannot hold a\n * transcript that drifts from the log.\n */\n history(): readonly Message[];\n /**\n * The committed log itself. A harness needs it to reason in sequence numbers\n * — where a compaction may cut, which call has no result yet — which the\n * projection deliberately does not carry.\n */\n entries(): readonly Stored[];\n /**\n * Application context placed around the cache boundary. `run` is stable for\n * the whole run and sits inside the cached prefix; `turn` is for this request\n * only and sits after it. Getting that split right is the loop's job because\n * only the loop knows where the prefix ends.\n */\n context?: { run?: string; turn?: string };\n tools?: ToolExecutor;\n /**\n * Commit to the log. Returns when durable — a harness never holds\n * uncommitted state.\n *\n * A refused write **rejects**, and a harness must not catch it: a lost\n * compare-and-swap means another writer is at this position, and the run is\n * over. Anything the agent was sending with that write goes with it.\n */\n commit(entries: readonly Entry[], deliveries?: readonly Delivery[]): Promise<void>;\n /**\n * Fold any waiting input into this activation, and say how much arrived.\n *\n * Called at a boundary the harness picks — ours takes it after each batch of\n * tool results, which is the last point at which nothing is half-done. This\n * is the whole of `priority: \"turn\"`: a message reaching a busy session\n * without the turn's work being thrown away to get its attention.\n *\n * A harness with no such point does not offer this, and a `\"turn\"` delivery\n * to it waits for the next activation instead. It is never promoted to\n * ending the one that is running — the sender asked for the place that costs\n * nothing, and the answer to \"I cannot\" is later, not more destructive.\n *\n * Absent when there is no store, because then nothing can be waiting.\n *\n * Two things it will not do. It folds nothing into an activation that has\n * been cancelled — a message taken off the queue by a run that is ending is a\n * message nobody answers and nothing can find again. And a store it cannot\n * read answers zero, the same as an empty queue: the failure is not hidden\n * for long, because the next commit meets it.\n */\n drain?(): Promise<number>;\n /** Wait until input may be available. A wake is a reason to drain, never the input itself. */\n waitForInput?(): Promise<void>;\n emit(update: Update): void;\n signal: AbortSignal;\n}\n\n/**\n * How one activation ended, and nothing about what it consumed.\n *\n * A harness used to report usage too, and that was a second answer to a\n * question the log already answers: every generation's counts are on the\n * `assistant` entry that carried it. `runAgent` sums those, so accounting is\n * the same fact for a harness that owns its own loop as for ours, and a\n * cancelled or failed activation still says what it spent.\n */\nexport type HarnessResult =\n | { status: \"completed\"; output: Content }\n | { status: \"cancelled\" }\n | { status: \"failed\"; error: Failure };\n\n/** One application extension, configured alongside other lifecycle work. */\nexport interface LifecycleHook {\n name: string;\n beforeRun?(context: HarnessContext): void | Promise<void>;\n beforeModel?(context: HarnessContext): void | Failure | Promise<void | Failure>;\n afterModel?(context: HarnessContext, result: Result<ModelResponse, ModelError>): void | Promise<void>;\n /** Only a completed, non-cancelled run may continue, once per hook name and run id. */\n beforeStop?(context: HarnessContext, result: HarnessResult):\n void | { input: Content } | { deliveries: readonly Delivery[] } |\n Promise<void | { input: Content } | { deliveries: readonly Delivery[] }>;\n /** After the terminal write; exceptions are observable but cannot change the outcome or skip other hooks. */\n afterRun?(context: HarnessContext, result: HarnessResult & { seq: number; usage: Usage }): void | Promise<void>;\n}\n\n/**\n * Executes one activation of an agent.\n *\n * One fact, not eight. Everything the old capability matrix carried was either\n * optional output, a different subsystem, or something no consumer asked about.\n *\n * `toolUse` went the same way, one release later. It claimed to say whose tools\n * ran — \"application\" through the executor, \"harness\" its own — and three\n * things were wrong with it. Nothing branched on it; no document owned the\n * claim; and the word did not survive contact with the adapters. A harness can\n * run a *vendor's* tools through our executor, validated and authorized, and a\n * harness can run tools *we wrote* inside its own process. Whose tools, whose\n * code and whose authority are three questions, and one enum answered none of\n * them reliably.\n *\n * The question it was reaching for — did anyone authorize this call — is a fact\n * about a call, not about a harness, and belongs on the tool entry if and when\n * something needs to read it. `recipes/vendored-agent` and\n * `docs/ARCHITECTURE.md` carry the per-adapter comparison in prose, which is\n * where a fact about adapters belongs and where it can be accurate.\n */\nexport interface Harness {\n readonly id: string;\n /** \"history\": committed entries are enough to restart. \"none\": an interrupted run is over. */\n readonly recovery: \"history\" | \"none\";\n run(context: HarnessContext): Promise<HarnessResult>;\n}\n"]}
1
+ {"version":3,"file":"harness.js","sourceRoot":"","sources":["../../src/harness/harness.ts"],"names":[],"mappings":"","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { Delivery, Entry, Stored, Usage } from \"../session/entry.js\";\nimport type { Message, ModelRequest, ModelResponse, ModelError } from \"../model/model.js\";\nimport type { Result } from \"../result.js\";\nimport type { ToolExecutor } from \"../tools/tool.js\";\nimport type { Failure } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/**\n * Ephemeral output for a live viewer. Only committed entries are recovery state.\n *\n * An `entry` update carries the whole `Stored` shape — sequence and commit time\n * both. Anything building a live projection off this stream needs the timestamp\n * the log already has, and inventing one at receipt would put a second answer\n * to the same question into the world.\n */\nexport type Update =\n | { type: \"hook.error\"; hook: string; message: string }\n | { type: \"text.delta\"; text: string; phase?: \"commentary\" | \"final_answer\"; runId?: string; generationId?: string }\n | { type: \"reasoning.delta\"; text: string; runId?: string; generationId?: string }\n | { type: \"tool.progress\"; callId: string; data: JsonValue }\n /** Arguments arriving a fragment at a time, so a viewer can show a call forming. */\n | { type: \"tool-call.delta\"; callId: string; arguments: string; runId?: string; generationId?: string }\n | { type: \"entry\"; entry: Stored };\n\nexport interface HarnessContext {\n /** The same callbacks used by the run; a harness invokes model boundaries it owns. */\n hooks?: readonly LifecycleHook[];\n sessionId: string;\n runId: string;\n instructions: Content;\n /**\n * The log projected for this turn. A function, not a snapshot: it is rebuilt\n * from committed entries every time it is read, so a harness cannot hold a\n * transcript that drifts from the log.\n */\n history(): readonly Message[];\n /**\n * The committed log itself. A harness needs it to reason in sequence numbers\n * — where a compaction may cut, which call has no result yet — which the\n * projection deliberately does not carry.\n */\n entries(): readonly Stored[];\n /**\n * Application context placed around the cache boundary. `run` is stable for\n * the whole run and sits inside the cached prefix; `turn` is for this request\n * only and sits after it. Getting that split right is the loop's job because\n * only the loop knows where the prefix ends.\n */\n context?: { run?: string; turn?: string };\n tools?: ToolExecutor;\n /**\n * Commit to the log. Returns when durable — a harness never holds\n * uncommitted state.\n *\n * A refused write **rejects**, and a harness must not catch it: a lost\n * compare-and-swap means another writer is at this position, and the run is\n * over. Anything the agent was sending with that write goes with it.\n */\n commit(entries: readonly Entry[], deliveries?: readonly Delivery[]): Promise<void>;\n /**\n * Fold any waiting input into this activation, and say how much arrived.\n *\n * Called at a boundary the harness picks — ours takes it after each batch of\n * tool results, which is the last point at which nothing is half-done. This\n * is the whole of `priority: \"turn\"`: a message reaching a busy session\n * without the turn's work being thrown away to get its attention.\n *\n * A harness with no such point does not offer this, and a `\"turn\"` delivery\n * to it waits for the next activation instead. It is never promoted to\n * ending the one that is running — the sender asked for the place that costs\n * nothing, and the answer to \"I cannot\" is later, not more destructive.\n *\n * Absent when there is no store, because then nothing can be waiting.\n *\n * Two things it will not do. It folds nothing into an activation that has\n * been cancelled — a message taken off the queue by a run that is ending is a\n * message nobody answers and nothing can find again. And a store it cannot\n * read answers zero, the same as an empty queue: the failure is not hidden\n * for long, because the next commit meets it.\n */\n drain?(): Promise<number>;\n /** Wait until input may be available. A wake is a reason to drain, never the input itself. */\n waitForInput?(): Promise<void>;\n emit(update: Update): void;\n signal: AbortSignal;\n}\n\n/**\n * How one activation ended, and nothing about what it consumed.\n *\n * A harness used to report usage too, and that was a second answer to a\n * question the log already answers: every generation's counts are on the\n * `assistant` entry that carried it. `runAgent` sums those, so accounting is\n * the same fact for a harness that owns its own loop as for ours, and a\n * cancelled or failed activation still says what it spent.\n */\nexport type HarnessResult =\n | { status: \"completed\"; output: Content }\n | { status: \"cancelled\" }\n | { status: \"failed\"; error: Failure };\n\n/** One application extension, configured alongside other lifecycle work. */\nexport interface LifecycleHook {\n name: string;\n beforeRun?(context: HarnessContext): void | Promise<void>;\n beforeModel?(context: HarnessContext): void | Failure | Promise<void | Failure>;\n /**\n * After one generation, with the request that was sent. The native harness\n * always has that request; an external harness that owns its loop need not\n * expose the boundary at all.\n */\n afterModel?(\n context: HarnessContext,\n result: Result<ModelResponse, ModelError>,\n request: ModelRequest,\n ): void | Promise<void>;\n /** Only a completed, non-cancelled run may continue, once per hook name and run id. */\n beforeStop?(context: HarnessContext, result: HarnessResult):\n void | { input: Content } | { deliveries: readonly Delivery[] } |\n Promise<void | { input: Content } | { deliveries: readonly Delivery[] }>;\n /** After the terminal write; exceptions are observable but cannot change the outcome or skip other hooks. */\n afterRun?(context: HarnessContext, result: HarnessResult & { seq: number; usage: Usage }): void | Promise<void>;\n}\n\n/**\n * Executes one activation of an agent.\n *\n * One fact, not eight. Everything the old capability matrix carried was either\n * optional output, a different subsystem, or something no consumer asked about.\n *\n * `toolUse` went the same way, one release later. It claimed to say whose tools\n * ran — \"application\" through the executor, \"harness\" its own — and three\n * things were wrong with it. Nothing branched on it; no document owned the\n * claim; and the word did not survive contact with the adapters. A harness can\n * run a *vendor's* tools through our executor, validated and authorized, and a\n * harness can run tools *we wrote* inside its own process. Whose tools, whose\n * code and whose authority are three questions, and one enum answered none of\n * them reliably.\n *\n * The question it was reaching for — did anyone authorize this call — is a fact\n * about a call, not about a harness, and belongs on the tool entry if and when\n * something needs to read it. `recipes/vendored-agent` and\n * `docs/ARCHITECTURE.md` carry the per-adapter comparison in prose, which is\n * where a fact about adapters belongs and where it can be accurate.\n */\nexport interface Harness {\n readonly id: string;\n /** \"history\": committed entries are enough to restart. \"none\": an interrupted run is over. */\n readonly recovery: \"history\" | \"none\";\n run(context: HarnessContext): Promise<HarnessResult>;\n}\n"]}
@@ -237,7 +237,7 @@ function encodeConversation(messages, cacheAt, provider) {
237
237
  if (spoken)
238
238
  content.push({ type: "text", text: spoken });
239
239
  for (const call of message.calls ?? []) {
240
- content.push({ type: "tool_use", id: call.callId, name: call.name, input: safeJson(call.arguments) });
240
+ content.push({ type: "tool_use", id: call.callId, name: call.name, input: JSON.parse(call.arguments) });
241
241
  }
242
242
  }
243
243
  out.push({ role: "assistant", content });
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/anthropic/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAUxD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAAyB;IAC5D,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAA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,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { isWaitStatus, retrying } from \"../../retry.js\";\n\nexport interface AnthropicOptions {\n apiKey: string;\n model: string;\n baseUrl?: string;\n version?: string;\n fetch?: typeof fetch;\n}\n\n/**\n * The Anthropic Messages wire.\n *\n * A genuinely different shape from OpenAI's — the leading system prompt hoisted\n * out of the message list, tool results carried as user content blocks, cache\n * breakpoints marked inline — which is the point of it being here: a port\n * proved against one wire format has not been proved.\n *\n * Three things this wire will refuse, and what we send instead:\n *\n * - **Thinking budgets.** `thinking: { type: \"enabled\", budget_tokens }` is\n * removed on the current models and returns 400. Depth is `output_config.effort`\n * over adaptive thinking, so `effort` maps there and nothing computes a budget.\n * - **Sampling controls.** `temperature`, `top_p` and `top_k` are removed on the\n * same models. `ModelRequest.temperature` is therefore dropped here rather\n * than forwarded into a request the provider rejects.\n * - **A system message in the middle of a turn.** Only the *leading* run of\n * system messages becomes the `system` field. One arriving after the\n * conversation has started is turn-scoped context, which the projection\n * deliberately places after the cache boundary, so it stays in `messages` as\n * a mid-conversation system message. Hoisting it would put the one thing that\n * changes every turn at the front of the prefix that must not change.\n * Supported on Opus 5, Opus 4.8 and Fable 5; a model without it fails the\n * request rather than silently having its cache invalidated every turn.\n */\nexport function createAnthropicModel(options: AnthropicOptions): Model {\n const call = retrying(options.fetch ?? fetch);\n const baseUrl = options.baseUrl ?? \"https://api.anthropic.com/v1\";\n const provider = `anthropic-messages:${baseUrl.replace(/\\/+$/, \"\")}:${options.model}`;\n\n return {\n id: `anthropic:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n // Only the leading run of system messages is the system prompt. Anything\n // after it belongs where the projection put it — see the header.\n let lead = 0;\n while (lead < request.messages.length && request.messages[lead]!.role === \"system\") lead += 1;\n const system = request.messages.slice(0, lead).map((message) => textOf(message.content));\n const conversation = request.messages.slice(lead);\n\n // Mark the reusable system prefix and the caller's conversation boundary;\n // volatile turn context follows that boundary and must stay outside it.\n const boundary = request.cacheAfter;\n const cacheSystem = boundary !== undefined && boundary >= lead && system.length > 0;\n const cacheAt = boundary !== undefined && boundary > lead ? boundary - lead - 1 : -1;\n\n const maxOutputTokens = request.maxOutputTokens ?? 32_000;\n\n let response: Response;\n try {\n response = await call(`${baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-api-key\": options.apiKey,\n \"anthropic-version\": options.version ?? \"2023-06-01\",\n },\n body: JSON.stringify({\n model: options.model,\n max_tokens: maxOutputTokens,\n ...(system.length ? { system: encodeSystem(system, cacheSystem) } : {}),\n messages: encodeConversation(conversation, cacheAt, provider),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.effort\n ? { thinking: { type: \"adaptive\" }, output_config: { effort: request.effort } }\n : {}),\n stream: true,\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n if (!response.ok) return err(await httpError(response));\n if (!response.body) return err({ code: \"provider\", message: \"No response body\", retryable: true });\n\n const text: string[] = [];\n const calls: ToolCall[] = [];\n let partial = \"\";\n let stop: string | undefined;\n let usage: Usage = {};\n let model: string | undefined;\n const providerBlocks = new Map<number, Record<string, JsonValue>>();\n const partialInputs = new Map<number, string>();\n\n // A stream that dies mid-body — cancelled, dropped, truncated — must come\n // back as a typed failure like any other. Without this the generator throws,\n // `run.result` rejects instead of resolving `cancelled`, no `run.finished`\n // is ever committed, and the activation stays open until its claim expires.\n try {\n for await (const event of sseData(response.body)) {\n let frame: AnthropicFrame;\n try { frame = JSON.parse(event) as AnthropicFrame; } catch { continue; }\n\n if (frame.type === \"message_start\" && frame.message) {\n model = frame.message.model;\n usage = { ...usage, ...decodeUsage(frame.message.usage) };\n }\n if (frame.type === \"content_block_start\" && frame.content_block) {\n const index = frame.index ?? providerBlocks.size;\n providerBlocks.set(index, clone(frame.content_block));\n if (frame.content_block.type === \"tool_use\") {\n calls.push({\n callId: String(frame.content_block.id ?? `call_${index}`),\n name: String(frame.content_block.name ?? \"\"),\n arguments: \"\",\n });\n partial = \"\";\n partialInputs.set(index, \"\");\n }\n }\n if (frame.type === \"content_block_delta\") {\n const delta = frame.delta!;\n const block = frame.index === undefined ? undefined : providerBlocks.get(frame.index);\n if (delta.type === \"text_delta\" && delta.text) { text.push(delta.text); yield { type: \"text.delta\", text: delta.text }; }\n if (delta.type === \"thinking_delta\" && delta.thinking) yield { type: \"reasoning.delta\", text: delta.thinking };\n if (block && delta.type === \"text_delta\" && delta.text !== undefined) {\n block[\"text\"] = `${typeof block[\"text\"] === \"string\" ? block[\"text\"] : \"\"}${delta.text}`;\n }\n if (block && delta.type === \"thinking_delta\" && delta.thinking !== undefined) {\n block[\"thinking\"] = `${typeof block[\"thinking\"] === \"string\" ? block[\"thinking\"] : \"\"}${delta.thinking}`;\n }\n if (block && delta.type === \"signature_delta\" && delta.signature !== undefined) {\n block[\"signature\"] = `${typeof block[\"signature\"] === \"string\" ? block[\"signature\"] : \"\"}${delta.signature}`;\n }\n if (delta.type === \"input_json_delta\" && delta.partial_json !== undefined) {\n partial += delta.partial_json;\n if (frame.index !== undefined) partialInputs.set(\n frame.index,\n `${partialInputs.get(frame.index) ?? \"\"}${delta.partial_json}`,\n );\n const current = calls.at(-1);\n if (current) yield { type: \"tool-call.delta\", callId: current.callId, arguments: delta.partial_json };\n }\n }\n if (frame.type === \"content_block_stop\" && calls.length) {\n const current = calls.at(-1)!;\n if (!current.arguments) current.arguments = partial || \"{}\";\n if (frame.index !== undefined && partialInputs.has(frame.index)) {\n const block = providerBlocks.get(frame.index);\n if (block) block[\"input\"] = safeJson(partialInputs.get(frame.index) || \"{}\");\n }\n }\n if (frame.type === \"message_delta\") {\n stop = frame.delta?.stop_reason ?? stop;\n usage = { ...usage, ...decodeUsage(frame.usage) };\n }\n if (frame.type === \"error\") {\n return err({ code: \"provider\", message: frame.error?.message ?? \"Provider error\", retryable: true });\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n const providerItems = [...providerBlocks.entries()]\n .sort(([left], [right]) => left - right)\n .map(([, block]) => block);\n return ok({\n message: { content: text.join(\"\"), ...(calls.length ? { calls } : {}) },\n finishReason: stop === \"max_tokens\" ? \"length\" : stop === \"refusal\" ? \"refusal\" : calls.length ? \"tool-calls\" : \"stop\",\n usage,\n ...(model ? { model } : {}),\n ...(providerItems.length ? { providerState: { provider, items: providerItems } } : {}),\n });\n },\n };\n}\n\n/**\n * Text blocks rather than one joined string, so the prefix can carry\n * breakpoints.\n *\n * Two are marked: the **first** block and the **last**. A breakpoint caches\n * everything before it, so the last one is what makes the whole prefix\n * reusable across a conversation's turns — and marking every block between\n * would buy nothing while spending a budget of four.\n *\n * The first earns its own for a different reason. The first block is an agent's\n * standing instructions, which are identical for every conversation it serves;\n * everything after it is composed per conversation and changes with it. With\n * one breakpoint at the end, a new conversation shares nothing: its prefix\n * differs from the last one somewhere in the middle, so the whole of it is\n * written again, instructions included. With one at the head, the instructions\n * are read from cache by every conversation and only what actually differs is\n * paid for — which is the common case for an agent serving many callers at\n * once, and free where there is only one.\n *\n * Skipped when there is a single block: the two marks would be the same one.\n */\nfunction encodeSystem(blocks: readonly string[], cache: boolean): unknown[] {\n const marked = new Set(blocks.length > 1 ? [0, blocks.length - 1] : [blocks.length - 1]);\n return blocks.map((text, index) => ({\n type: \"text\",\n text,\n ...(cache && marked.has(index) ? { cache_control: { type: \"ephemeral\" } } : {}),\n }));\n}\n\n/**\n * Tool results are user-role content blocks here, not a role of their own.\n *\n * `cacheAt` is an index into `messages`; the breakpoint lands on the last\n * content block that message produced. Tool results merge into a preceding user\n * block, so the mapping from message to block is not one to one and the mark is\n * placed as each message is encoded rather than computed afterwards.\n */\nfunction encodeConversation(messages: readonly Message[], cacheAt: number, provider: string): unknown[] {\n const out: { role: string; content: unknown[] }[] = [];\n let mark: unknown[] | undefined;\n\n messages.forEach((message, index) => {\n if (message.role === \"tool\") {\n const block = {\n type: \"tool_result\", tool_use_id: message.callId, content: typeof message.content === \"string\" ? message.content : encodeContent(message.content),\n ...(message.isError ? { is_error: true } : {}),\n };\n const last = out.at(-1);\n if (last?.role === \"user\") last.content.push(block);\n else out.push({ role: \"user\", content: [block] });\n } else if (message.role === \"assistant\") {\n const content: unknown[] = message.providerState?.provider === provider && message.providerState.items.length\n ? message.providerState.items.map(clone)\n : [];\n if (!content.length) {\n const spoken = textOf(message.content);\n if (spoken) content.push({ type: \"text\", text: spoken });\n for (const call of message.calls ?? []) {\n content.push({ type: \"tool_use\", id: call.callId, name: call.name, input: safeJson(call.arguments) });\n }\n }\n out.push({ role: \"assistant\", content });\n } else if (message.role === \"system\") {\n // Turn-scoped context, kept where the projection put it: an operator\n // instruction inside the conversation leaves the cached prefix intact,\n // where rewriting the front of it would invalidate every following turn.\n out.push({ role: \"system\", content: encodeContent(message.content) });\n } else {\n out.push({ role: \"user\", content: encodeContent(message.content) });\n }\n if (index === cacheAt) mark = out.at(-1)?.content;\n });\n\n const block = mark?.at(-1) as Record<string, unknown> | undefined;\n if (block) block[\"cache_control\"] = { type: \"ephemeral\" };\n return out;\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown[] {\n if (typeof content === \"string\") return [{ type: \"text\", text: content }];\n const parts: unknown[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") parts.push({ type: \"text\", text: part.text });\n if (part.type === \"image\") {\n parts.push(part.source.kind === \"url\"\n ? { type: \"image\", source: { type: \"url\", url: part.source.url } }\n : { type: \"image\", source: { type: \"base64\", media_type: part.mediaType, data: part.source.data } });\n }\n }\n return parts;\n}\n\nconst encodeTool = (tool: ToolSpec) => ({\n name: tool.name, description: tool.description, input_schema: tool.parameters,\n});\n\nconst safeJson = (raw: string): JsonValue => { try { return JSON.parse(raw) as JsonValue; } catch { return {}; } };\n\nconst clone = <T extends JsonValue>(value: T): T => JSON.parse(JSON.stringify(value)) as T;\n\nconst decodeUsage = (usage: AnthropicUsage | undefined): Usage => usage ? {\n ...(usage.input_tokens !== undefined ? { inputTokens: usage.input_tokens } : {}),\n ...(usage.output_tokens !== undefined ? { outputTokens: usage.output_tokens } : {}),\n ...(usage.cache_read_input_tokens !== undefined ? { cacheReadTokens: usage.cache_read_input_tokens } : {}),\n ...(usage.cache_creation_input_tokens !== undefined ? { cacheWriteTokens: usage.cache_creation_input_tokens } : {}),\n} : {};\n\n/**\n * A refusal, or a wait the retries did not outlast. The second keeps a\n * retryable code: the provider never said the request was wrong, and a caller\n * with the time to try again later is told so.\n */\nasync function httpError(response: Response): Promise<ModelError> {\n const wait = isWaitStatus(response.status);\n const body = await response.text().catch(() => \"\");\n const code: ModelError[\"code\"] =\n response.status === 401 || response.status === 403 ? \"auth\"\n : response.status === 400 && /prompt is too long|context/i.test(body) ? \"context-length\"\n : response.status === 429 ? \"rate-limit\"\n : wait ? \"provider\"\n : \"failed\";\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: wait,\n };\n}\n\nfunction transportError(error: unknown, signal?: AbortSignal): ModelError {\n if (signal?.aborted) return { code: \"cancelled\", message: \"Generation cancelled\", retryable: false };\n return { code: \"provider\", message: error instanceof Error ? error.message : String(error), retryable: true };\n}\n\nasync function* sseData(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line.startsWith(\"data:\")) yield line.slice(5).trim();\n newline = buffer.indexOf(\"\\n\");\n }\n }\n}\n\ninterface AnthropicUsage {\n input_tokens?: number; output_tokens?: number;\n cache_read_input_tokens?: number; cache_creation_input_tokens?: number;\n}\ninterface AnthropicFrame {\n type: string;\n index?: number;\n message?: { model?: string; usage?: AnthropicUsage };\n content_block?: Record<string, JsonValue> & { type: string };\n delta?: {\n type?: string; text?: string; thinking?: string; signature?: string;\n partial_json?: string; stop_reason?: string;\n };\n usage?: AnthropicUsage;\n error?: { message?: string };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/anthropic/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAUxD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAAyB;IAC5D,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC,CAAC;IAC9C,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,8BAA8B,CAAC;IAClE,MAAM,QAAQ,GAAG,sBAAsB,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;IAEtF,OAAO;QACL,EAAE,EAAE,aAAa,OAAO,CAAC,KAAK,EAAE;QAEhC,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAqB;YACnC,yEAAyE;YACzE,iEAAiE;YACjE,IAAI,IAAI,GAAG,CAAC,CAAC;YACb,OAAO,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC,MAAM,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAE,CAAC,IAAI,KAAK,QAAQ;gBAAE,IAAI,IAAI,CAAC,CAAC;YAC9F,MAAM,MAAM,GAAG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CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,IAA4C,EAAE,CAAC;QACvE,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnC,OAAO,OAAO,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC7C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;YACnC,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { isWaitStatus, retrying } from \"../../retry.js\";\n\nexport interface AnthropicOptions {\n apiKey: string;\n model: string;\n baseUrl?: string;\n version?: string;\n fetch?: typeof fetch;\n}\n\n/**\n * The Anthropic Messages wire.\n *\n * A genuinely different shape from OpenAI's — the leading system prompt hoisted\n * out of the message list, tool results carried as user content blocks, cache\n * breakpoints marked inline — which is the point of it being here: a port\n * proved against one wire format has not been proved.\n *\n * Three things this wire will refuse, and what we send instead:\n *\n * - **Thinking budgets.** `thinking: { type: \"enabled\", budget_tokens }` is\n * removed on the current models and returns 400. Depth is `output_config.effort`\n * over adaptive thinking, so `effort` maps there and nothing computes a budget.\n * - **Sampling controls.** `temperature`, `top_p` and `top_k` are removed on the\n * same models. `ModelRequest.temperature` is therefore dropped here rather\n * than forwarded into a request the provider rejects.\n * - **A system message in the middle of a turn.** Only the *leading* run of\n * system messages becomes the `system` field. One arriving after the\n * conversation has started is turn-scoped context, which the projection\n * deliberately places after the cache boundary, so it stays in `messages` as\n * a mid-conversation system message. Hoisting it would put the one thing that\n * changes every turn at the front of the prefix that must not change.\n * Supported on Opus 5, Opus 4.8 and Fable 5; a model without it fails the\n * request rather than silently having its cache invalidated every turn.\n */\nexport function createAnthropicModel(options: AnthropicOptions): Model {\n const call = retrying(options.fetch ?? fetch);\n const baseUrl = options.baseUrl ?? \"https://api.anthropic.com/v1\";\n const provider = `anthropic-messages:${baseUrl.replace(/\\/+$/, \"\")}:${options.model}`;\n\n return {\n id: `anthropic:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n // Only the leading run of system messages is the system prompt. Anything\n // after it belongs where the projection put it — see the header.\n let lead = 0;\n while (lead < request.messages.length && request.messages[lead]!.role === \"system\") lead += 1;\n const system = request.messages.slice(0, lead).map((message) => textOf(message.content));\n const conversation = request.messages.slice(lead);\n\n // Mark the reusable system prefix and the caller's conversation boundary;\n // volatile turn context follows that boundary and must stay outside it.\n const boundary = request.cacheAfter;\n const cacheSystem = boundary !== undefined && boundary >= lead && system.length > 0;\n const cacheAt = boundary !== undefined && boundary > lead ? boundary - lead - 1 : -1;\n\n const maxOutputTokens = request.maxOutputTokens ?? 32_000;\n\n let response: Response;\n try {\n response = await call(`${baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-api-key\": options.apiKey,\n \"anthropic-version\": options.version ?? \"2023-06-01\",\n },\n body: JSON.stringify({\n model: options.model,\n max_tokens: maxOutputTokens,\n ...(system.length ? { system: encodeSystem(system, cacheSystem) } : {}),\n messages: encodeConversation(conversation, cacheAt, provider),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.effort\n ? { thinking: { type: \"adaptive\" }, output_config: { effort: request.effort } }\n : {}),\n stream: true,\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n if (!response.ok) return err(await httpError(response));\n if (!response.body) return err({ code: \"provider\", message: \"No response body\", retryable: true });\n\n const text: string[] = [];\n const calls: ToolCall[] = [];\n let partial = \"\";\n let stop: string | undefined;\n let usage: Usage = {};\n let model: string | undefined;\n const providerBlocks = new Map<number, Record<string, JsonValue>>();\n const partialInputs = new Map<number, string>();\n\n // A stream that dies mid-body — cancelled, dropped, truncated — must come\n // back as a typed failure like any other. Without this the generator throws,\n // `run.result` rejects instead of resolving `cancelled`, no `run.finished`\n // is ever committed, and the activation stays open until its claim expires.\n try {\n for await (const event of sseData(response.body)) {\n let frame: AnthropicFrame;\n try { frame = JSON.parse(event) as AnthropicFrame; } catch { continue; }\n\n if (frame.type === \"message_start\" && frame.message) {\n model = frame.message.model;\n usage = { ...usage, ...decodeUsage(frame.message.usage) };\n }\n if (frame.type === \"content_block_start\" && frame.content_block) {\n const index = frame.index ?? providerBlocks.size;\n providerBlocks.set(index, clone(frame.content_block));\n if (frame.content_block.type === \"tool_use\") {\n calls.push({\n callId: String(frame.content_block.id ?? `call_${index}`),\n name: String(frame.content_block.name ?? \"\"),\n arguments: \"\",\n });\n partial = \"\";\n partialInputs.set(index, \"\");\n }\n }\n if (frame.type === \"content_block_delta\") {\n const delta = frame.delta!;\n const block = frame.index === undefined ? undefined : providerBlocks.get(frame.index);\n if (delta.type === \"text_delta\" && delta.text) { text.push(delta.text); yield { type: \"text.delta\", text: delta.text }; }\n if (delta.type === \"thinking_delta\" && delta.thinking) yield { type: \"reasoning.delta\", text: delta.thinking };\n if (block && delta.type === \"text_delta\" && delta.text !== undefined) {\n block[\"text\"] = `${typeof block[\"text\"] === \"string\" ? block[\"text\"] : \"\"}${delta.text}`;\n }\n if (block && delta.type === \"thinking_delta\" && delta.thinking !== undefined) {\n block[\"thinking\"] = `${typeof block[\"thinking\"] === \"string\" ? block[\"thinking\"] : \"\"}${delta.thinking}`;\n }\n if (block && delta.type === \"signature_delta\" && delta.signature !== undefined) {\n block[\"signature\"] = `${typeof block[\"signature\"] === \"string\" ? block[\"signature\"] : \"\"}${delta.signature}`;\n }\n if (delta.type === \"input_json_delta\" && delta.partial_json !== undefined) {\n partial += delta.partial_json;\n if (frame.index !== undefined) partialInputs.set(\n frame.index,\n `${partialInputs.get(frame.index) ?? \"\"}${delta.partial_json}`,\n );\n const current = calls.at(-1);\n if (current) yield { type: \"tool-call.delta\", callId: current.callId, arguments: delta.partial_json };\n }\n }\n if (frame.type === \"content_block_stop\" && calls.length) {\n const current = calls.at(-1)!;\n if (!current.arguments) current.arguments = partial || \"{}\";\n if (frame.index !== undefined && partialInputs.has(frame.index)) {\n const block = providerBlocks.get(frame.index);\n if (block) block[\"input\"] = safeJson(partialInputs.get(frame.index) || \"{}\");\n }\n }\n if (frame.type === \"message_delta\") {\n stop = frame.delta?.stop_reason ?? stop;\n usage = { ...usage, ...decodeUsage(frame.usage) };\n }\n if (frame.type === \"error\") {\n return err({ code: \"provider\", message: frame.error?.message ?? \"Provider error\", retryable: true });\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n const providerItems = [...providerBlocks.entries()]\n .sort(([left], [right]) => left - right)\n .map(([, block]) => block);\n return ok({\n message: { content: text.join(\"\"), ...(calls.length ? { calls } : {}) },\n finishReason: stop === \"max_tokens\" ? \"length\" : stop === \"refusal\" ? \"refusal\" : calls.length ? \"tool-calls\" : \"stop\",\n usage,\n ...(model ? { model } : {}),\n ...(providerItems.length ? { providerState: { provider, items: providerItems } } : {}),\n });\n },\n };\n}\n\n/**\n * Text blocks rather than one joined string, so the prefix can carry\n * breakpoints.\n *\n * Two are marked: the **first** block and the **last**. A breakpoint caches\n * everything before it, so the last one is what makes the whole prefix\n * reusable across a conversation's turns — and marking every block between\n * would buy nothing while spending a budget of four.\n *\n * The first earns its own for a different reason. The first block is an agent's\n * standing instructions, which are identical for every conversation it serves;\n * everything after it is composed per conversation and changes with it. With\n * one breakpoint at the end, a new conversation shares nothing: its prefix\n * differs from the last one somewhere in the middle, so the whole of it is\n * written again, instructions included. With one at the head, the instructions\n * are read from cache by every conversation and only what actually differs is\n * paid for — which is the common case for an agent serving many callers at\n * once, and free where there is only one.\n *\n * Skipped when there is a single block: the two marks would be the same one.\n */\nfunction encodeSystem(blocks: readonly string[], cache: boolean): unknown[] {\n const marked = new Set(blocks.length > 1 ? [0, blocks.length - 1] : [blocks.length - 1]);\n return blocks.map((text, index) => ({\n type: \"text\",\n text,\n ...(cache && marked.has(index) ? { cache_control: { type: \"ephemeral\" } } : {}),\n }));\n}\n\n/**\n * Tool results are user-role content blocks here, not a role of their own.\n *\n * `cacheAt` is an index into `messages`; the breakpoint lands on the last\n * content block that message produced. Tool results merge into a preceding user\n * block, so the mapping from message to block is not one to one and the mark is\n * placed as each message is encoded rather than computed afterwards.\n */\nfunction encodeConversation(messages: readonly Message[], cacheAt: number, provider: string): unknown[] {\n const out: { role: string; content: unknown[] }[] = [];\n let mark: unknown[] | undefined;\n\n messages.forEach((message, index) => {\n if (message.role === \"tool\") {\n const block = {\n type: \"tool_result\", tool_use_id: message.callId, content: typeof message.content === \"string\" ? message.content : encodeContent(message.content),\n ...(message.isError ? { is_error: true } : {}),\n };\n const last = out.at(-1);\n if (last?.role === \"user\") last.content.push(block);\n else out.push({ role: \"user\", content: [block] });\n } else if (message.role === \"assistant\") {\n const content: unknown[] = message.providerState?.provider === provider && message.providerState.items.length\n ? message.providerState.items.map(clone)\n : [];\n if (!content.length) {\n const spoken = textOf(message.content);\n if (spoken) content.push({ type: \"text\", text: spoken });\n for (const call of message.calls ?? []) {\n content.push({ type: \"tool_use\", id: call.callId, name: call.name, input: JSON.parse(call.arguments) as JsonValue });\n }\n }\n out.push({ role: \"assistant\", content });\n } else if (message.role === \"system\") {\n // Turn-scoped context, kept where the projection put it: an operator\n // instruction inside the conversation leaves the cached prefix intact,\n // where rewriting the front of it would invalidate every following turn.\n out.push({ role: \"system\", content: encodeContent(message.content) });\n } else {\n out.push({ role: \"user\", content: encodeContent(message.content) });\n }\n if (index === cacheAt) mark = out.at(-1)?.content;\n });\n\n const block = mark?.at(-1) as Record<string, unknown> | undefined;\n if (block) block[\"cache_control\"] = { type: \"ephemeral\" };\n return out;\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown[] {\n if (typeof content === \"string\") return [{ type: \"text\", text: content }];\n const parts: unknown[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") parts.push({ type: \"text\", text: part.text });\n if (part.type === \"image\") {\n parts.push(part.source.kind === \"url\"\n ? { type: \"image\", source: { type: \"url\", url: part.source.url } }\n : { type: \"image\", source: { type: \"base64\", media_type: part.mediaType, data: part.source.data } });\n }\n }\n return parts;\n}\n\nconst encodeTool = (tool: ToolSpec) => ({\n name: tool.name, description: tool.description, input_schema: tool.parameters,\n});\n\nconst safeJson = (raw: string): JsonValue => { try { return JSON.parse(raw) as JsonValue; } catch { return {}; } };\n\nconst clone = <T extends JsonValue>(value: T): T => JSON.parse(JSON.stringify(value)) as T;\n\nconst decodeUsage = (usage: AnthropicUsage | undefined): Usage => usage ? {\n ...(usage.input_tokens !== undefined ? { inputTokens: usage.input_tokens } : {}),\n ...(usage.output_tokens !== undefined ? { outputTokens: usage.output_tokens } : {}),\n ...(usage.cache_read_input_tokens !== undefined ? { cacheReadTokens: usage.cache_read_input_tokens } : {}),\n ...(usage.cache_creation_input_tokens !== undefined ? { cacheWriteTokens: usage.cache_creation_input_tokens } : {}),\n} : {};\n\n/**\n * A refusal, or a wait the retries did not outlast. The second keeps a\n * retryable code: the provider never said the request was wrong, and a caller\n * with the time to try again later is told so.\n */\nasync function httpError(response: Response): Promise<ModelError> {\n const wait = isWaitStatus(response.status);\n const body = await response.text().catch(() => \"\");\n const code: ModelError[\"code\"] =\n response.status === 401 || response.status === 403 ? \"auth\"\n : response.status === 400 && /prompt is too long|context/i.test(body) ? \"context-length\"\n : response.status === 429 ? \"rate-limit\"\n : wait ? \"provider\"\n : \"failed\";\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: wait,\n };\n}\n\nfunction transportError(error: unknown, signal?: AbortSignal): ModelError {\n if (signal?.aborted) return { code: \"cancelled\", message: \"Generation cancelled\", retryable: false };\n return { code: \"provider\", message: error instanceof Error ? error.message : String(error), retryable: true };\n}\n\nasync function* sseData(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line.startsWith(\"data:\")) yield line.slice(5).trim();\n newline = buffer.indexOf(\"\\n\");\n }\n }\n}\n\ninterface AnthropicUsage {\n input_tokens?: number; output_tokens?: number;\n cache_read_input_tokens?: number; cache_creation_input_tokens?: number;\n}\ninterface AnthropicFrame {\n type: string;\n index?: number;\n message?: { model?: string; usage?: AnthropicUsage };\n content_block?: Record<string, JsonValue> & { type: string };\n delta?: {\n type?: string; text?: string; thinking?: string; signature?: string;\n partial_json?: string; stop_reason?: string;\n };\n usage?: AnthropicUsage;\n error?: { message?: string };\n}\n"]}
@@ -124,12 +124,18 @@ export type Entry = {
124
124
  * span it took. `Stored.at` is when the entry was committed, which is a
125
125
  * different fact and not a substitute — anything projecting a generation
126
126
  * needs both ends of the call, and the commit is neither of them.
127
+ *
128
+ * `turn` is the `context.turn` that sat after the cache boundary on this
129
+ * request. The doctrine, run context and tools are on `run.context` once
130
+ * for the activation; the log is the transcript; this is the slice that
131
+ * changes every call. Absent when the application supplied none.
127
132
  */
128
133
  generation?: {
129
134
  id: string;
130
135
  model?: string;
131
136
  startedAt: string;
132
137
  endedAt?: string;
138
+ turn?: string;
133
139
  };
134
140
  } | {
135
141
  type: "model.finished";
@@ -152,6 +158,27 @@ export type Entry = {
152
158
  callId: string;
153
159
  result: ToolResult;
154
160
  }
161
+ /**
162
+ * The prefix this run offered the model: standing instructions, run-scoped
163
+ * context, and the tool catalogue. The application commits it; the loop does
164
+ * not. Not model-visible — the same facts already sit at the front of every
165
+ * request, and projecting them again would send them twice.
166
+ */
167
+ | {
168
+ type: "run.context";
169
+ runId: string;
170
+ /** The application's build that composed this prefix, when it says. */
171
+ build?: string;
172
+ instructions: Content;
173
+ run?: string;
174
+ tools?: readonly {
175
+ name: string;
176
+ description: string;
177
+ parameters: JsonValue;
178
+ async?: boolean;
179
+ concurrent?: boolean;
180
+ }[];
181
+ }
155
182
  /** Compaction output. `replaces` is the seq up to which entries are folded; nothing is deleted. */
156
183
  | {
157
184
  type: "summary";
@@ -1 +1 @@
1
- {"version":3,"file":"entry.js","sourceRoot":"","sources":["../../src/session/entry.ts"],"names":[],"mappings":"","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { Failure } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/** A model's request to invoke a tool. `arguments` is unparsed JSON as the provider sent it. */\nexport interface ToolCall {\n callId: string;\n name: string;\n arguments: string;\n /** The model may continue before this call reports its result. */\n async?: boolean;\n}\n\n/** Provider-owned continuation data, retained verbatim beside the output that produced it. */\nexport interface ProviderState {\n /** The provider wire allowed to replay these items. */\n provider: string;\n items: readonly JsonValue[];\n}\n\nexport interface ToolResult {\n content: Content;\n /** Structured channel for the application and the UI. Never reaches the model. */\n details?: JsonValue;\n isError?: boolean;\n /** Execution began but its effect is unknown; reconcile before issuing it again. */\n uncertain?: true;\n}\n\n/**\n * What a generation consumed.\n *\n * Absent stays absent — a count nobody reported is not a zero. This package\n * holds no rates and computes no money from tokens. Where an adapter does\n * arithmetic it is reconciling its wire's encoding to the meanings below:\n * normalization, which is an adapter's job, and never a new fact.\n *\n * That is why `costUsd` belongs here and a rate table does not. A cost the\n * provider *states* is an observation like the counts beside it, and dropping\n * it was the same mistake as dropping the model that served the request: an\n * application was left reconstructing, from a table it maintains by hand, a\n * number the wire had already given it. For a router that is not even possible\n * — it picks an upstream provider per request and adds its own margin, so no\n * static table can say what was charged.\n */\nexport interface Usage {\n /**\n * Input tokens that were neither read from nor written to a cache.\n *\n * **The three input counts are disjoint.** The prompt's total size is\n * `inputTokens + cacheReadTokens + cacheWriteTokens`; no field here is a\n * subset of another, so a caller sums and never subtracts.\n *\n * The wires disagree about this and one of them has to be converted. What\n * Anthropic calls `input_tokens` is already this — \"tokens which were not\n * read from or used to create a cache\". What OpenAI calls `prompt_tokens` is\n * the whole prompt, with `cached_tokens` counted inside it, so that adapter\n * subtracts once and callers stop having to know which wire answered.\n *\n * Disjoint is the choice that survives absence, which is the rule the rest of\n * this type runs on. Summing the fields you were given is right whichever\n * ones are missing; subtracting a field you were not given is not. Under the\n * other convention a heavily cached Anthropic turn priced its fresh tokens at\n * zero — quietly, because the subtraction was clamped at zero rather than\n * being allowed to go negative where somebody would have seen it.\n */\n inputTokens?: number;\n outputTokens?: number;\n /** Input tokens served from a cache. Disjoint from `inputTokens`. */\n cacheReadTokens?: number;\n /** Input tokens written to a cache. Disjoint from `inputTokens`. */\n cacheWriteTokens?: number;\n /**\n * What the provider said this generation cost, in US dollars. Reported,\n * never derived: no adapter computes this from a rate, and one whose wire\n * does not carry a cost leaves it absent rather than estimating.\n */\n costUsd?: number;\n}\n\n/**\n * Who sent an arrival: what sort of sender, and which one.\n *\n * aglib mints exactly one kind — `\"session\"`, a delivery from another session —\n * and interprets no other. Every other kind is the application's word for one of\n * its own senders: a person, a channel, a schedule, a webhook. The vocabulary\n * belongs to whoever can close it, and that is never this package.\n *\n * Two fields because absence was carrying four facts. This used to be the\n * sending session's id alone, so an operator, a channel and a timer all said the\n * same thing by saying nothing, and a recipient could not tell a person typing\n * from a routine firing. Packing both into one string instead — `\"routine:x\"` —\n * would put the vocabulary in a convention nothing closes, which is how such a\n * field ends up with values that exist only by grep and a different reading on\n * every surface that renders it.\n */\nexport interface From {\n kind: string;\n id: string;\n}\n\n/**\n * The canonical vocabulary. This is the session's state, not a record of it:\n * the loop reads its context by projecting these and appends back to them, so\n * there is no second transcript that could disagree.\n *\n * `tool.started` carries only the call id — the assistant entry above it\n * already holds the call, and duplicating name and arguments would be a second\n * field for a value another field determines.\n */\nexport type Entry =\n | { type: \"hook.input\"; runId: string; hook: string; input: Content }\n | { type: \"run.started\"; runId: string; input: Content; from?: From }\n | {\n type: \"assistant\"; runId: string; content: Content;\n calls?: readonly ToolCall[]; usage?: Usage; providerState?: ProviderState;\n /**\n * What produced this turn, when a model did: which model answered and the\n * span it took. `Stored.at` is when the entry was committed, which is a\n * different fact and not a substitute — anything projecting a generation\n * needs both ends of the call, and the commit is neither of them.\n */\n generation?: { id: string; model?: string; startedAt: string; endedAt?: string };\n }\n | { type: \"model.finished\"; runId: string; purpose: string; generation: { id: string; model?: string; startedAt: string; endedAt: string }; usage?: Usage }\n | { type: \"tool.started\"; runId: string; callId: string }\n | { type: \"tool.finished\"; runId: string; callId: string; result: ToolResult }\n /** Compaction output. `replaces` is the seq up to which entries are folded; nothing is deleted. */\n | { type: \"summary\"; runId: string; content: string; replaces: number }\n | { type: \"run.finished\"; runId: string; outcome: \"completed\" | \"failed\" | \"cancelled\"; error?: Failure };\n\nexport type EntryType = Entry[\"type\"];\n\n/** An entry once the log has given it a position. */\nexport type Stored<T extends Entry = Entry> = T & { seq: number; at: string };\n\n/**\n * Input delivered to a session, committed with the sender's own entries.\n * Spawning a child, replying to a parent and messaging a peer are all this.\n */\nexport interface Delivery {\n /** The session it is delivered to. */\n sessionId: string;\n input: Content;\n /**\n * Who sent it. Absent means the application did not say — not that nobody\n * did. Recorded on the receiving `run.started`, so an application can tell a\n * peer's message from its user's, and can see that it already answered one\n * that arrives twice. It becomes text the model reads only where the\n * recipient's agent asks, with `attribution`.\n */\n from?: From;\n /**\n * Where in the recipient's loop this lands. Defaults to \"next\".\n *\n * Three places, and each is an outcome a sender can reason about rather than\n * a level of urgency a harness interprets:\n *\n * \"interrupt\" — the running activation ends, so the next one begins with\n * this. Its uncommitted work is lost; everything it had\n * already committed stays.\n * \"turn\" — folded into the activation already running, before its next\n * model call. Nothing in flight is lost. Immediately, if\n * nothing is running.\n * \"next\" — at the start of the recipient's next activation.\n *\n * This used to be `now | next | later`, and `now` meant either of the first\n * two depending on the harness — fold if it had a safe point, end the\n * activation if it did not. One word for \"your message arrives and the work\n * continues\" and \"your message arrives and a turn's work is destroyed\". The\n * doctrine was that a priority names the requirement and not the mechanism,\n * but those are not two mechanisms for one requirement: they are two\n * different things happening to somebody's work, and a runtime answer saying\n * which one you got was invented to paper over it. `later` named a fourth\n * thing that nothing implemented.\n *\n * **A harness that cannot honour one falls back to a later place, never an\n * earlier one.** A loop with no safe point cannot do \"turn\", so it does\n * \"next\" — the message waits. It does not end the activation instead, which\n * is what falling back through an ordered scale used to do: ask for the\n * gentlest useful thing and get the most destructive one.\n */\n priority?: \"interrupt\" | \"turn\" | \"next\";\n /**\n * The sender's key for this delivery. Two deliveries with the same id are the\n * same delivery, so a retried send does not arrive twice.\n */\n id?: string;\n}\n"]}
1
+ {"version":3,"file":"entry.js","sourceRoot":"","sources":["../../src/session/entry.ts"],"names":[],"mappings":"","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { Failure } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/** A model's request to invoke a tool. `arguments` is unparsed JSON as the provider sent it. */\nexport interface ToolCall {\n callId: string;\n name: string;\n arguments: string;\n /** The model may continue before this call reports its result. */\n async?: boolean;\n}\n\n/** Provider-owned continuation data, retained verbatim beside the output that produced it. */\nexport interface ProviderState {\n /** The provider wire allowed to replay these items. */\n provider: string;\n items: readonly JsonValue[];\n}\n\nexport interface ToolResult {\n content: Content;\n /** Structured channel for the application and the UI. Never reaches the model. */\n details?: JsonValue;\n isError?: boolean;\n /** Execution began but its effect is unknown; reconcile before issuing it again. */\n uncertain?: true;\n}\n\n/**\n * What a generation consumed.\n *\n * Absent stays absent — a count nobody reported is not a zero. This package\n * holds no rates and computes no money from tokens. Where an adapter does\n * arithmetic it is reconciling its wire's encoding to the meanings below:\n * normalization, which is an adapter's job, and never a new fact.\n *\n * That is why `costUsd` belongs here and a rate table does not. A cost the\n * provider *states* is an observation like the counts beside it, and dropping\n * it was the same mistake as dropping the model that served the request: an\n * application was left reconstructing, from a table it maintains by hand, a\n * number the wire had already given it. For a router that is not even possible\n * — it picks an upstream provider per request and adds its own margin, so no\n * static table can say what was charged.\n */\nexport interface Usage {\n /**\n * Input tokens that were neither read from nor written to a cache.\n *\n * **The three input counts are disjoint.** The prompt's total size is\n * `inputTokens + cacheReadTokens + cacheWriteTokens`; no field here is a\n * subset of another, so a caller sums and never subtracts.\n *\n * The wires disagree about this and one of them has to be converted. What\n * Anthropic calls `input_tokens` is already this — \"tokens which were not\n * read from or used to create a cache\". What OpenAI calls `prompt_tokens` is\n * the whole prompt, with `cached_tokens` counted inside it, so that adapter\n * subtracts once and callers stop having to know which wire answered.\n *\n * Disjoint is the choice that survives absence, which is the rule the rest of\n * this type runs on. Summing the fields you were given is right whichever\n * ones are missing; subtracting a field you were not given is not. Under the\n * other convention a heavily cached Anthropic turn priced its fresh tokens at\n * zero — quietly, because the subtraction was clamped at zero rather than\n * being allowed to go negative where somebody would have seen it.\n */\n inputTokens?: number;\n outputTokens?: number;\n /** Input tokens served from a cache. Disjoint from `inputTokens`. */\n cacheReadTokens?: number;\n /** Input tokens written to a cache. Disjoint from `inputTokens`. */\n cacheWriteTokens?: number;\n /**\n * What the provider said this generation cost, in US dollars. Reported,\n * never derived: no adapter computes this from a rate, and one whose wire\n * does not carry a cost leaves it absent rather than estimating.\n */\n costUsd?: number;\n}\n\n/**\n * Who sent an arrival: what sort of sender, and which one.\n *\n * aglib mints exactly one kind — `\"session\"`, a delivery from another session —\n * and interprets no other. Every other kind is the application's word for one of\n * its own senders: a person, a channel, a schedule, a webhook. The vocabulary\n * belongs to whoever can close it, and that is never this package.\n *\n * Two fields because absence was carrying four facts. This used to be the\n * sending session's id alone, so an operator, a channel and a timer all said the\n * same thing by saying nothing, and a recipient could not tell a person typing\n * from a routine firing. Packing both into one string instead — `\"routine:x\"` —\n * would put the vocabulary in a convention nothing closes, which is how such a\n * field ends up with values that exist only by grep and a different reading on\n * every surface that renders it.\n */\nexport interface From {\n kind: string;\n id: string;\n}\n\n/**\n * The canonical vocabulary. This is the session's state, not a record of it:\n * the loop reads its context by projecting these and appends back to them, so\n * there is no second transcript that could disagree.\n *\n * `tool.started` carries only the call id — the assistant entry above it\n * already holds the call, and duplicating name and arguments would be a second\n * field for a value another field determines.\n */\nexport type Entry =\n | { type: \"hook.input\"; runId: string; hook: string; input: Content }\n | { type: \"run.started\"; runId: string; input: Content; from?: From }\n | {\n type: \"assistant\"; runId: string; content: Content;\n calls?: readonly ToolCall[]; usage?: Usage; providerState?: ProviderState;\n /**\n * What produced this turn, when a model did: which model answered and the\n * span it took. `Stored.at` is when the entry was committed, which is a\n * different fact and not a substitute — anything projecting a generation\n * needs both ends of the call, and the commit is neither of them.\n *\n * `turn` is the `context.turn` that sat after the cache boundary on this\n * request. The doctrine, run context and tools are on `run.context` once\n * for the activation; the log is the transcript; this is the slice that\n * changes every call. Absent when the application supplied none.\n */\n generation?: { id: string; model?: string; startedAt: string; endedAt?: string; turn?: string };\n }\n | { type: \"model.finished\"; runId: string; purpose: string; generation: { id: string; model?: string; startedAt: string; endedAt: string }; usage?: Usage }\n | { type: \"tool.started\"; runId: string; callId: string }\n | { type: \"tool.finished\"; runId: string; callId: string; result: ToolResult }\n /**\n * The prefix this run offered the model: standing instructions, run-scoped\n * context, and the tool catalogue. The application commits it; the loop does\n * not. Not model-visible — the same facts already sit at the front of every\n * request, and projecting them again would send them twice.\n */\n | {\n type: \"run.context\";\n runId: string;\n /** The application's build that composed this prefix, when it says. */\n build?: string;\n instructions: Content;\n run?: string;\n tools?: readonly {\n name: string;\n description: string;\n parameters: JsonValue;\n async?: boolean;\n concurrent?: boolean;\n }[];\n }\n /** Compaction output. `replaces` is the seq up to which entries are folded; nothing is deleted. */\n | { type: \"summary\"; runId: string; content: string; replaces: number }\n | { type: \"run.finished\"; runId: string; outcome: \"completed\" | \"failed\" | \"cancelled\"; error?: Failure };\n\nexport type EntryType = Entry[\"type\"];\n\n/** An entry once the log has given it a position. */\nexport type Stored<T extends Entry = Entry> = T & { seq: number; at: string };\n\n/**\n * Input delivered to a session, committed with the sender's own entries.\n * Spawning a child, replying to a parent and messaging a peer are all this.\n */\nexport interface Delivery {\n /** The session it is delivered to. */\n sessionId: string;\n input: Content;\n /**\n * Who sent it. Absent means the application did not say — not that nobody\n * did. Recorded on the receiving `run.started`, so an application can tell a\n * peer's message from its user's, and can see that it already answered one\n * that arrives twice. It becomes text the model reads only where the\n * recipient's agent asks, with `attribution`.\n */\n from?: From;\n /**\n * Where in the recipient's loop this lands. Defaults to \"next\".\n *\n * Three places, and each is an outcome a sender can reason about rather than\n * a level of urgency a harness interprets:\n *\n * \"interrupt\" — the running activation ends, so the next one begins with\n * this. Its uncommitted work is lost; everything it had\n * already committed stays.\n * \"turn\" — folded into the activation already running, before its next\n * model call. Nothing in flight is lost. Immediately, if\n * nothing is running.\n * \"next\" — at the start of the recipient's next activation.\n *\n * This used to be `now | next | later`, and `now` meant either of the first\n * two depending on the harness — fold if it had a safe point, end the\n * activation if it did not. One word for \"your message arrives and the work\n * continues\" and \"your message arrives and a turn's work is destroyed\". The\n * doctrine was that a priority names the requirement and not the mechanism,\n * but those are not two mechanisms for one requirement: they are two\n * different things happening to somebody's work, and a runtime answer saying\n * which one you got was invented to paper over it. `later` named a fourth\n * thing that nothing implemented.\n *\n * **A harness that cannot honour one falls back to a later place, never an\n * earlier one.** A loop with no safe point cannot do \"turn\", so it does\n * \"next\" — the message waits. It does not end the activation instead, which\n * is what falling back through an ordered scale used to do: ask for the\n * gentlest useful thing and get the most destructive one.\n */\n priority?: \"interrupt\" | \"turn\" | \"next\";\n /**\n * The sender's key for this delivery. Two deliveries with the same id are the\n * same delivery, so a retried send does not arrive twice.\n */\n id?: string;\n}\n"]}
@@ -1,6 +1,9 @@
1
1
  import type { Content } from "../content.js";
2
2
  import type { ProviderState, Stored, ToolCall } from "./entry.js";
3
- /** A message as a provider takes it: built per turn from the log, never held. */
3
+ /**
4
+ * A message as a provider takes it: built per turn from the log, never held.
5
+ * Every call's `arguments` parses here, whatever the log holds.
6
+ */
4
7
  export type Message = {
5
8
  role: "system";
6
9
  content: Content;
@@ -65,7 +65,7 @@ export function toMessages(input) {
65
65
  messages.push({
66
66
  role: "assistant",
67
67
  content: entry.content,
68
- ...(entry.calls?.length ? { calls: entry.calls } : {}),
68
+ ...(entry.calls?.length ? { calls: entry.calls.map(parseable) } : {}),
69
69
  ...(entry.providerState ? { providerState: entry.providerState } : {}),
70
70
  });
71
71
  for (const call of entry.calls ?? []) {
@@ -90,9 +90,10 @@ export function toMessages(input) {
90
90
  ...(entry.result.isError ? { isError: true } : {}),
91
91
  });
92
92
  break;
93
- // Not model-visible: tool.started is bookkeeping and run.finished is a
94
- // boundary.
93
+ // Not model-visible: tool.started and run.context are bookkeeping, and
94
+ // run.finished is a boundary.
95
95
  case "tool.started":
96
+ case "run.context":
96
97
  case "run.finished":
97
98
  break;
98
99
  }
@@ -103,4 +104,22 @@ export function toMessages(input) {
103
104
  messages.push({ role: "system", content: input.context.turn });
104
105
  return messages;
105
106
  }
107
+ /**
108
+ * A call whose arguments the model never finished as JSON. The log keeps the
109
+ * string as it was sent, and dispatch has already answered it with a failure;
110
+ * but a strict provider validates every call in the history it is handed, and
111
+ * one it cannot parse fails the whole request — every request, since the
112
+ * history is replayed whole — which is a session nobody can use again. The
113
+ * projection renders it as JSON that still holds what was said, so the model
114
+ * reads its own mistake beside the result that named it, on any wire.
115
+ */
116
+ function parseable(call) {
117
+ try {
118
+ JSON.parse(call.arguments);
119
+ return call;
120
+ }
121
+ catch {
122
+ return { ...call, arguments: JSON.stringify({ _unparsed: call.arguments }) };
123
+ }
124
+ }
106
125
  //# sourceMappingURL=messages.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/session/messages.ts"],"names":[],"mappings":"AAUA;;;;;;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;AAED;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,KAa1B;IACC,MAAM,QAAQ,GAAc,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,YAAY,EAAE,CAAC,CAAC;IAE9E,yEAAyE;IACzE,wEAAwE;IACxE,IAAI,KAAK,CAAC,OAAO,EAAE,GAAG;QAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,QA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MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI;wBAChD,OAAO,EAAE,2LAA2L;qBACrM,CAAC,CAAC;gBACL,CAAC;gBACD,MAAM;YACR,CAAC;YACD,KAAK,eAAe;gBAClB,QAAQ,CAAC,IAAI,CAAC;oBACZ,IAAI,EAAE,MAAM;oBACZ,MAAM,EAAE,KAAK,CAAC,MAAM;oBACpB,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,SAAS;wBAC7B,CAAC,CAAC,OAAO,KAAK,CAAC,MAAM,CAAC,OAAO,KAAK,QAAQ;4BACxC,CAAC,CAAC,kGAAkG,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE;4BAC1H,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,+FAA+F,EAAE,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC;wBACtJ,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO;oBACxB,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBACnD,CAAC,CAAC;gBACH,MAAM;YACR,uEAAuE;YACvE,YAAY;YACZ,KAAK,cAAc,CAAC;YACpB,KAAK,cAAc;gBACjB,MAAM;QACV,CAAC;IACH,CAAC;IAED,6EAA6E;IAC7E,oEAAoE;IACpE,IAAI,KAAK,CAAC,OAAO,EAAE,IAAI;QAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IACxF,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { From, ProviderState, Stored, ToolCall } from \"./entry.js\";\n\n/** A message as a provider takes it: built per turn from the log, never held. */\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 } : {}),\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 is bookkeeping and run.finished is a\n // boundary.\n case \"tool.started\":\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"]}
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;AAED;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,KAa1B;IACC,MAAM,QAAQ,GAAc,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,YAAY,EAAE,CAAC,CAAC;IAE9E,yEAAyE;IACzE,wEAAwE;IACxE,IAAI,KAAK,CAAC,OAAO,EAAE,GAAG;QAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IAEtF,8EAA8E;IAC9E,qEAAqE;IACrE,MAAM,GAAG,GAAG,aAAa,CAAC,KAAK,CA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,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-dray/aglib",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "type": "module",
5
5
  "description": "A small TypeScript toolkit for building your own agent harness.",
6
6
  "license": "MIT",