@buildanagent/harness 0.1.0-alpha.29 → 0.1.0-alpha.31

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.
Files changed (84) hide show
  1. package/README.md +110 -3
  2. package/dist/credentials/addresses.d.ts +20 -0
  3. package/dist/credentials/addresses.js +93 -2
  4. package/dist/credentials/addresses.js.map +1 -1
  5. package/dist/credentials/egress-proxy.js +34 -4
  6. package/dist/credentials/egress-proxy.js.map +1 -1
  7. package/dist/errors.d.ts +6 -3
  8. package/dist/errors.js +5 -2
  9. package/dist/errors.js.map +1 -1
  10. package/dist/extensions/load.js +5 -2
  11. package/dist/extensions/load.js.map +1 -1
  12. package/dist/extensions/lock.d.ts +16 -2
  13. package/dist/extensions/lock.js +155 -21
  14. package/dist/extensions/lock.js.map +1 -1
  15. package/dist/extensions/mcp-pins-node.d.ts +16 -0
  16. package/dist/extensions/mcp-pins-node.js +18 -0
  17. package/dist/extensions/mcp-pins-node.js.map +1 -0
  18. package/dist/extensions/node.d.ts +4 -2
  19. package/dist/extensions/node.js +4 -2
  20. package/dist/extensions/node.js.map +1 -1
  21. package/dist/harness.d.ts +7 -1
  22. package/dist/harness.js.map +1 -1
  23. package/dist/mcp/connection.d.ts +9 -3
  24. package/dist/mcp/connection.js +192 -25
  25. package/dist/mcp/connection.js.map +1 -1
  26. package/dist/mcp/errors.d.ts +5 -2
  27. package/dist/mcp/errors.js.map +1 -1
  28. package/dist/mcp/guarded-fetch.d.ts +33 -0
  29. package/dist/mcp/guarded-fetch.js +391 -0
  30. package/dist/mcp/guarded-fetch.js.map +1 -0
  31. package/dist/mcp/http-node.d.ts +15 -0
  32. package/dist/mcp/http-node.js +179 -0
  33. package/dist/mcp/http-node.js.map +1 -0
  34. package/dist/mcp/index.d.ts +6 -3
  35. package/dist/mcp/index.js +5 -2
  36. package/dist/mcp/index.js.map +1 -1
  37. package/dist/mcp/manager.d.ts +4 -3
  38. package/dist/mcp/manager.js +432 -47
  39. package/dist/mcp/manager.js.map +1 -1
  40. package/dist/mcp/pins.d.ts +9 -0
  41. package/dist/mcp/pins.js +54 -0
  42. package/dist/mcp/pins.js.map +1 -0
  43. package/dist/mcp/record.js +6 -0
  44. package/dist/mcp/record.js.map +1 -1
  45. package/dist/mcp/remote-config.d.ts +20 -0
  46. package/dist/mcp/remote-config.js +208 -0
  47. package/dist/mcp/remote-config.js.map +1 -0
  48. package/dist/mcp/remote.d.ts +20 -0
  49. package/dist/mcp/remote.js +146 -0
  50. package/dist/mcp/remote.js.map +1 -0
  51. package/dist/mcp/types.d.ts +198 -8
  52. package/dist/mcp/types.js.map +1 -1
  53. package/dist/sandbox/escalation-table.d.ts +38 -0
  54. package/dist/sandbox/escalation-table.js +95 -0
  55. package/dist/sandbox/escalation-table.js.map +1 -0
  56. package/dist/sandbox/escalation.d.ts +191 -0
  57. package/dist/sandbox/escalation.js +370 -0
  58. package/dist/sandbox/escalation.js.map +1 -0
  59. package/dist/sandbox/index.d.ts +6 -3
  60. package/dist/sandbox/index.js +6 -3
  61. package/dist/sandbox/index.js.map +1 -1
  62. package/dist/sandbox/widen.d.ts +10 -0
  63. package/dist/sandbox/widen.js +150 -0
  64. package/dist/sandbox/widen.js.map +1 -0
  65. package/dist/server/protocol.schema.json +6 -3
  66. package/dist/session/approvals.d.ts +30 -1
  67. package/dist/session/approvals.js +12 -4
  68. package/dist/session/approvals.js.map +1 -1
  69. package/dist/session/code-call.d.ts +15 -1
  70. package/dist/session/code-call.js +2 -1
  71. package/dist/session/code-call.js.map +1 -1
  72. package/dist/session/escalation-log.d.ts +65 -0
  73. package/dist/session/escalation-log.js +84 -0
  74. package/dist/session/escalation-log.js.map +1 -0
  75. package/dist/session/rebuild.js +12 -3
  76. package/dist/session/rebuild.js.map +1 -1
  77. package/dist/session/runner.js +39 -6
  78. package/dist/session/runner.js.map +1 -1
  79. package/dist/tools/index.d.ts +1 -1
  80. package/dist/tools/index.js.map +1 -1
  81. package/dist/tools/types.d.ts +16 -0
  82. package/dist/tools/types.js.map +1 -1
  83. package/llms.txt +36 -2
  84. package/package.json +7 -6
@@ -1 +1 @@
1
- {"version":3,"file":"code-call.js","sourceRoot":"","sources":["../../src/session/code-call.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAGpF,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EAIpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAI5C,OAAO,EAAuB,WAAW,EAAwB,MAAM,oBAAoB,CAAC;AAC5F,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAyB,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAExE,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AA0BzD,6GAA6G;AAC7G,MAAM,SAAS,GAAG,CAAC,CAAC;AAEpB,SAAS,IAAI,CAAC,OAAgB,EAAE,OAAkB;IAChD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;IACtE,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC;IACvE,OAAO;QACL,OAAO;QACP,KAAK;QACL,KAAK;QACL,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE,GAAG,KAAK,EAAE;YACpC,MAAM,KAAK,GAAG,EAAE,GAAG,IAAI,EAAE,EAAE,EAAE,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SAAS,CAAC,IAAI,2BAA2B,CAAC,CAAC;IACzG,CAAC;IACD,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC7C,IAAI,IAAI,EAAE,aAAa,KAAK,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO,KAAK,YAAY,EAAE,CAAC;QACvE,OAAO,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,aAAa,IAAI,CAAC,IAAI,oEAAoE,CAAC,CAAC;IACpH,CAAC;IACD,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;IACnF,uGAAuG;IACvG,IAAI,QAAQ,CAAC,QAAQ,KAAK,MAAM;QAAE,OAAO,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACzE,OAAO,OAAO,CAAC,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["/**\n * Code-initiated tool calls: a side effect the host's own code chose, run through the same permission pipeline, signed\n * pause and log as a call the model makes, with no model step. The `code_call` entry is written before anything else\n * of the call, and its id is the call id, so the effect key is fixed before the tool can run and a resume finds it.\n * A call starts once its log holds the entry that clears it to run; one that started with no result is never rerun.\n */\nimport { effectKey, renderOutcome, writeOutcome } from \"@buildanagent/agent-safety\";\nimport type { ContentBlock } from \"@buildanagent/gateway\";\nimport type { CodeCallEntry, Origin, SessionEntry } from \"@buildanagent/protocol\";\nimport {\n canonicalInputHash,\n createPendingRequest,\n type Resolution,\n type ToolContext,\n type ToolResult,\n verifyResolution,\n} from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport { HarnessError } from \"../errors.js\";\nimport type { CodeCall, CodeCallResult, Harness } from \"../harness.js\";\nimport type { Decision, PolicySession } from \"../permissions/types.js\";\nimport type { RegisteredTool } from \"../tools/types.js\";\nimport { type CodeCallRecord, codeCallsOf, type WaitingCodeCall } from \"./code-call-log.js\";\nimport { writeCodeCallResult } from \"./code-call-result.js\";\nimport { effectScope } from \"./effect-scope.js\";\nimport { interruptedResult } from \"./resume.js\";\nimport { type ResolutionRecord, recordSessionStart } from \"./runner.js\";\nimport type { Session } from \"./session.js\";\nimport { findSticky, stickyDecision } from \"./sticky.js\";\nimport type { EntryInput } from \"./store.js\";\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\ntype Body = DistributiveOmit<EntryInput, \"id\" | \"parentId\" | \"timestamp\" | \"origin\">;\n\n/** How a code call writes: one entry at a time after the one before, with its ids and clock. */\ninterface Io {\n readonly session: Session;\n write(origin: Origin, body: Body, id?: string): Promise<SessionEntry>;\n readonly newId: () => string;\n readonly clock: Clock;\n}\n\n/** The settings both a call and its resolution take: where its ids and time come from. */\ninterface IoOptions {\n readonly clock?: Clock;\n readonly newId?: () => string;\n}\n\n/** What running a code call needs besides the tool: its host context and its signal. */\ninterface RunOptions<H> extends IoOptions {\n readonly hostContext?: H;\n readonly signal?: AbortSignal;\n}\n\n// The SDK's default nesting cap, so a tool that starts an agent from a code call nests as it would in a run.\nconst MAX_DEPTH = 2;\n\nfunction ioOf(session: Session, options: IoOptions): Io {\n const newId = options.newId ?? (() => globalThis.crypto.randomUUID());\n const clock = options.clock ?? { now: () => new Date().toISOString() };\n return {\n session,\n newId,\n clock,\n async write(origin, body, id = newId()) {\n const entry = { ...body, id, parentId: session.head(), timestamp: clock.now(), origin } as EntryInput;\n const [stored] = await session.append([entry]);\n return stored as SessionEntry;\n },\n };\n}\n\nconst invalid = (message: string, cause?: unknown) =>\n new HarnessError(\"invalid_code_call\", message, cause === undefined ? {} : { cause });\n\nconst describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// One code call of a session runs at a time in a process: a second one would read the first one's open call as a crash.\n// Another process is kept out by the session's lock.\nconst queues = new WeakMap<Session, Promise<unknown>>();\n\n/** Runs `task` after every code call of `session` that this process started before it. */\nexport function inCodeCallQueue<T>(session: Session, task: () => Promise<T>): Promise<T> {\n const next = (queues.get(session) ?? Promise.resolve()).then(task, task);\n queues.set(\n session,\n next.catch(() => undefined),\n );\n return next;\n}\n\n/** The registered tool a code call names, refused when the registry lacks it or only a client can run it. */\nfunction toolFor<H>(harness: Harness<H>, name: string): RegisteredTool {\n const tool = harness.registry.get(name);\n if (tool === undefined) throw invalid(`no tool \"${name}\" is registered, so the code call can't run`);\n if (tool.pattern === \"client_request\") {\n throw invalid(`the tool \"${tool.canonicalName}\" runs on the client, which a code call has no way to reach`);\n }\n return tool;\n}\n\nasync function hashOf(value: unknown, what: string): Promise<string> {\n try {\n return await canonicalInputHash(value);\n } catch (error) {\n throw invalid(`the code call's ${what} has no canonical JSON form`, error);\n }\n}\n\n/**\n * The call's effect key: from the tool's business key when it declares one, and from the scope of `callId` otherwise.\n * A tool the registry no longer has gets the scope's key.\n */\nexport async function codeCallEffectKey<H>(\n session: Session,\n harness: Harness<H>,\n tool: RegisteredTool | undefined,\n call: { readonly callId: string; readonly input: unknown },\n): Promise<string> {\n const businessKey = tool?.definition.effect?.businessKey;\n try {\n return await effectKey(effectScope(session, harness, call.callId), businessKey?.(call.input));\n } catch (error) {\n throw invalid(`the effect key of the call to \"${tool?.canonicalName}\" could not be made`, error);\n }\n}\n\n/** Refuses a harness that can't decide or sign a code call, before anything is written. */\nfunction checkHarness<H>(harness: Harness<H>): void {\n if (harness.pipeline === undefined) {\n throw invalid(\"the harness has no permission pipeline, so no code call can be decided\");\n }\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so a code call could not ask anyone\");\n }\n}\n\n/**\n * Settles each code call a crash left open: writes the result it lacks. A call that started may have taken effect, so\n * it gets the result an interrupted model call gets. A call that never started never ran, so it gets an error that says\n * so: one that stopped before it could run or ask anyone, and one whose answer was written but which stopped, or was\n * refused, before it started. A call that asked and has no final answer still waits.\n */\nasync function settleCodeCalls<H>(path: readonly SessionEntry[], harness: Harness<H>, io: Io): Promise<void> {\n for (const { call, result, requested, answered, letRun } of codeCallsOf(path).values()) {\n if (result !== undefined || (requested !== undefined && !answered && !letRun)) continue;\n const body = letRun\n ? { origin: \"tool\" as const, ...interruptedResult(harness, call.tool) }\n : { origin: \"harness\" as const, ...notRun(answered ? NOT_RUN_ANSWERED : NOT_RUN_EARLY) };\n const { origin, ...fields } = body;\n await io.write(origin, { type: \"tool_result\", callId: call.callId, tool: call.tool, ...fields });\n }\n}\n\nconst NOT_RUN_EARLY = \"The code call stopped before it could run or ask anyone, so it never ran.\";\nconst NOT_RUN_ANSWERED = \"The code call stopped after its answer was written and before it could run, so it never ran.\";\n\nconst notRun = (text: string) => ({\n content: [{ type: \"text\" as const, text }],\n isError: true,\n trust: \"trusted\" as const,\n});\n\n/** Refuses a compensation that names no code call that ran, or that would share that call's effect key. */\nasync function checkCompensation<H>(\n session: Session,\n harness: Harness<H>,\n records: ReadonlyMap<string, CodeCallRecord>,\n compensated: string,\n ownKey: string,\n): Promise<void> {\n const target = records.get(compensated);\n // A denial is the harness's own result. A result from the tool, a crash's result, or a call let run that has no\n // result yet means the call ran or may have run.\n const ran = target?.result === undefined ? target?.letRun === true : target.result.origin === \"tool\";\n if (target === undefined || !ran) {\n throw invalid(`a compensation must name a code call that ran, and \"${compensated}\" names none`);\n }\n const theirs = await codeCallEffectKey(session, harness, harness.registry.get(target.call.tool), target.call);\n if (theirs === ownKey) {\n throw invalid(\"a compensation needs an effect key of its own, and this one has the key of the call it undoes\");\n }\n}\n\n/** Writes an error result for a call that does not run, and returns the denial. */\nasync function deny(io: Io, call: CodeCallEntry, reason: string): Promise<CodeCallResult> {\n const entry = await io.write(\"harness\", {\n type: \"tool_result\",\n callId: call.callId,\n tool: call.tool,\n ...notRun(reason),\n });\n return { status: \"denied\", callId: call.callId, reason, entryId: entry.id };\n}\n\n/** Decides the call with the pipeline, which writes its `permission_decision`, and keeps the policy version it used. */\nasync function decide<H>(\n harness: Harness<H>,\n session: Session,\n io: Io,\n call: CodeCallEntry,\n hostContext: H | undefined,\n): Promise<{ decision: Decision; policyVersion: string | undefined }> {\n let policyVersion: string | undefined;\n const policySession: PolicySession = {\n append(entry) {\n if (entry.type === \"permission_decision\") policyVersion = entry.policyVersion;\n return io.write(\"harness\", entry);\n },\n };\n // checkHarness() refused a harness without a pipeline before anything was written.\n const pipeline = harness.pipeline as NonNullable<Harness<H>[\"pipeline\"]>;\n const decision = await pipeline.decide(\n { callId: call.callId, tool: call.tool, input: call.input, initiator: \"code\" },\n { session: policySession, hostContext, entries: await session.path() },\n );\n return { decision, policyVersion: policyVersion === \"\" ? undefined : policyVersion };\n}\n\nconst isContentList = (content: unknown): content is ToolResult[\"content\"] =>\n Array.isArray(content) &&\n content.every(\n (block: Partial<ContentBlock> | null) =>\n (block?.type === \"text\" && typeof block.text === \"string\") ||\n (block?.type === \"image\" && typeof block.mediaType === \"string\" && typeof block.data === \"string\"),\n );\n\n/** A result with its write outcome's sentence in front of its content, as the model would read it. */\nfunction withOutcome(result: ToolResult<unknown>): ToolResult<unknown> {\n if (!isContentList(result?.content)) throw new TypeError(\"the tool returned content that is not text and images\");\n if (result.outcome === undefined) return result;\n const rendered = renderOutcome(result.outcome);\n return {\n ...result,\n content: [\n { type: \"text\", text: rendered.text },\n { type: \"text\", text: JSON.stringify({ outcome: rendered.payload }) },\n ...result.content,\n ],\n isError: result.isError === true || rendered.isError,\n };\n}\n\n/** The result of a tool that threw or returned something unusable: a write's outcome is unknown, since it may have run. */\nfunction thrownResult(tool: RegisteredTool, error: unknown): ToolResult<unknown> {\n const text = tool.definition.redactErrors === true ? \"The tool failed.\" : `The tool failed: ${describe(error)}`;\n if (tool.definition.effect?.kind !== \"write\") return { content: [{ type: \"text\", text }], isError: true };\n const rendered = renderOutcome(\n writeOutcome({\n kind: \"unknown\",\n operation: tool.canonicalName,\n retry: \"reconcile_first\",\n reason: \"WRITE_FAILED\",\n currentState: \"The tool failed before it returned, so the write may have taken effect.\",\n next: \"Check whether it took effect before you do anything else.\",\n }),\n );\n return {\n content: [\n { type: \"text\", text: rendered.text },\n { type: \"text\", text: JSON.stringify({ outcome: rendered.payload }) },\n { type: \"text\", text },\n ],\n isError: true,\n details: { outcome: rendered.payload },\n };\n}\n\n/**\n * Runs the tool through the harness's wrapper with the host context, and writes its result. The harness's interceptors\n * and observers belong to a turn's model step, so they don't run here; the pipeline already decided the call.\n */\nasync function runTool<H>(\n harness: Harness<H>,\n io: Io,\n tool: RegisteredTool,\n call: CodeCallEntry,\n options: RunOptions<H> & { readonly effectKey: string },\n): Promise<CodeCallResult> {\n const ctx: ToolContext<unknown> = {\n runId: call.callId,\n callId: call.callId,\n signal: options.signal ?? new AbortController().signal,\n depth: 0,\n maxDepth: MAX_DEPTH,\n clock: io.clock,\n app: options.hostContext,\n update: () => undefined,\n };\n let result: ToolResult<unknown>;\n // A wrapper that throws is recorded like a tool that throws, so the call that was let run still gets a result.\n try {\n const definition = harness.wrap === undefined ? tool.definition : harness.wrap(tool, options.hostContext as H);\n result = withOutcome(await definition.execute(call.input, ctx));\n } catch (error) {\n result = thrownResult(tool, error);\n }\n const writer = {\n session: io.session,\n now: io.clock.now,\n signal: ctx.signal,\n write: (body: Body) => io.write(\"tool\", body),\n };\n const entry = await writeCodeCallResult(harness, writer, tool, call, result);\n return { status: \"done\", callId: call.callId, result, entryId: entry.id, effectKey: options.effectKey };\n}\n\n/** Signs the request for a call the pipeline asks about, and writes it before anyone can hear of it. */\nasync function ask<H>(\n harness: Harness<H>,\n io: Io,\n call: CodeCallEntry,\n decision: { reason: string; policyVersion: string | undefined; hostContext: H | undefined; effectKey: string },\n): Promise<CodeCallResult> {\n const { reason, policyVersion, hostContext } = decision;\n const pending = await createPendingRequest(\n {\n kind: \"approval\",\n callId: call.callId,\n tool: call.tool,\n input: call.input,\n ...(policyVersion === undefined ? {} : { policyVersion }),\n ...(reason === \"\" ? {} : { reason }),\n ...(hostContext === undefined ? {} : { app: hostContext }),\n },\n // checkHarness() refused a harness without a signer before anything was written.\n harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n { generateId: io.newId, now: () => new Date(io.clock.now()) },\n );\n await io.write(\"harness\", { type: \"approval_requested\", request: pending, input: call.input });\n return { status: \"awaiting_approval\", callId: call.callId, pending, effectKey: decision.effectKey };\n}\n\n/** Checks everything a code call needs before its first entry, and returns its tool, input hash and effect key. */\nasync function prepare<H>(harness: Harness<H>, session: Session, call: CodeCall<H>, callId: string) {\n checkHarness(harness);\n const tool = toolFor(harness, call.tool);\n const inputHash = await hashOf(call.input, \"input\");\n if (call.hostContext !== undefined) await hashOf(call.hostContext, \"host context\");\n const key = await codeCallEffectKey(session, harness, tool, { callId, input: call.input });\n return { tool, inputHash, key };\n}\n\n/** `Harness.invokeTool()`: see its documentation. */\nexport async function invokeCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n call: CodeCall<H>,\n): Promise<CodeCallResult> {\n // Checked before the queue too, so an aborted call never waits behind another.\n call.signal?.throwIfAborted();\n return inCodeCallQueue(session, () => invokeQueued(harness, session, call));\n}\n\nasync function invokeQueued<H>(harness: Harness<H>, session: Session, call: CodeCall<H>): Promise<CodeCallResult> {\n const io = ioOf(session, call);\n const callId = io.newId();\n const { tool, inputHash, key } = await prepare(harness, session, call, callId);\n const path = await session.path();\n if (call.compensates !== undefined) {\n await checkCompensation(session, harness, codeCallsOf(path), call.compensates, key);\n }\n call.signal?.throwIfAborted();\n await recordSessionStart(harness, (origin, body) => io.write(origin, body), harness.model, path);\n await settleCodeCalls(await session.path(), harness, io);\n const entry: CodeCallEntry = {\n type: \"code_call\",\n callId,\n tool: tool.canonicalName,\n input: call.input,\n inputHash,\n ...(call.compensates === undefined ? {} : { compensates: call.compensates }),\n };\n await io.write(\"harness\", entry, callId);\n const { decision, policyVersion } = await decide(harness, session, io, entry, call.hostContext);\n if (decision.decision === \"deny\") return deny(io, entry, decision.reason);\n const run = { ...call, effectKey: key };\n if (decision.decision === \"allow\") return runTool(harness, io, tool, entry, run);\n const covered = await findSticky(await session.path(), { ...entry, policyVersion }, harness.registry);\n if (covered === undefined) {\n return ask(harness, io, entry, {\n reason: decision.reason,\n policyVersion,\n hostContext: call.hostContext,\n effectKey: key,\n });\n }\n await io.write(\"harness\", await stickyDecision(entry, covered, policyVersion));\n return runTool(harness, io, tool, entry, run);\n}\n\n/**\n * Checks a resolution against the waiting call's signed request before anything is written: the signature under a key\n * the signer holds, the host context the request binds, the call and tool, and the input, which must hash to the signed\n * hash in the `code_call` entry, in the `approval_requested` entry and in the request alike. Throws `approval_refused`\n * with the cause, which names no key, signature or input.\n */\nexport async function checkCodeCallRequest<H>(\n harness: Harness<H>,\n waiting: WaitingCodeCall,\n resolution: Resolution,\n hostContext: H | undefined,\n): Promise<void> {\n const { call, request, input } = waiting;\n const check = await verifyResolution(request, resolution, {\n signer: harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n call: { callId: call.callId, tool: call.tool, input: call.input },\n ...(hostContext === undefined ? {} : { app: hostContext }),\n });\n const cause = check.ok ? await inputCause(call, input) : check.cause;\n if (cause !== undefined) {\n throw new HarnessError(\n \"approval_refused\",\n `the request for code call ${call.callId} failed its check (${cause}), so nothing ran and nothing was written`,\n );\n }\n}\n\n/** `input_changed` unless the recorded input and the input shown to the approver both hash to the recorded hash. */\nasync function inputCause(call: CodeCallEntry, shown: unknown): Promise<\"input_changed\" | undefined> {\n const hash = async (value: unknown) => canonicalInputHash(value).catch(() => undefined);\n const [recorded, asked] = await Promise.all([hash(call.input), hash(shown)]);\n return recorded === call.inputHash && asked === call.inputHash ? undefined : \"input_changed\";\n}\n\n/** What the resolution of a code call is given: the answer the quorum settled on, if any, and the entries to write. */\nexport interface SettledCodeCall {\n readonly forRun: Resolution | undefined;\n readonly records: readonly ResolutionRecord[];\n readonly effectKey: string;\n}\n\n/**\n * Applies a code call's settled resolution: it writes the answers, then leaves the call waiting when the quorum still\n * waits, denies it for a person's or the policy's refusal, and otherwise decides it again with the pipeline, so a deny\n * written since the pause wins, and runs the tool itself, with no model step.\n */\nexport async function finishCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n waiting: WaitingCodeCall,\n settled: SettledCodeCall,\n options: RunOptions<H>,\n): Promise<CodeCallResult> {\n options.signal?.throwIfAborted();\n const io = ioOf(session, options);\n for (const record of settled.records) await io.write(\"user\", { type: \"approval_resolved\", ...record });\n const { call } = waiting;\n const { forRun, effectKey: key } = settled;\n if (forRun === undefined) {\n return { status: \"awaiting_approval\", callId: call.callId, pending: waiting.request, effectKey: key };\n }\n if (!(\"decision\" in forRun) || forRun.decision !== \"allow\") {\n return deny(io, call, (\"reason\" in forRun ? forRun.reason : undefined) ?? \"A person denied the call.\");\n }\n const tool = harness.registry.get(call.tool);\n if (tool?.canonicalName !== call.tool || tool.pattern !== \"in_process\") {\n return deny(io, call, `The tool \"${call.tool}\" is no longer registered for code calls, so the call did not run.`);\n }\n const { decision } = await decide(harness, session, io, call, options.hostContext);\n // A person approved the call, so a question the pipeline would ask again doesn't stop it; a deny does.\n if (decision.decision === \"deny\") return deny(io, call, decision.reason);\n return runTool(harness, io, tool, call, { ...options, effectKey: key });\n}\n"]}
1
+ {"version":3,"file":"code-call.js","sourceRoot":"","sources":["../../src/session/code-call.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAGpF,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EAIpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAI5C,OAAO,EAAuB,WAAW,EAAwB,MAAM,oBAAoB,CAAC;AAC5F,OAAO,EAAE,mBAAmB,EAAE,MAAM,u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E,OAAO,CAAC,WAAW,CAAC,CAAC;IACnF,uGAAuG;IACvG,IAAI,QAAQ,CAAC,QAAQ,KAAK,MAAM;QAAE,OAAO,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACzE,OAAO,OAAO,CAAC,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["/**\n * Code-initiated tool calls: a side effect the host's own code chose, run through the same permission pipeline, signed\n * pause and log as a call the model makes, with no model step. The `code_call` entry is written before anything else\n * of the call, and its id is the call id, so the effect key is fixed before the tool can run and a resume finds it.\n * A call starts once its log holds the entry that clears it to run; one that started with no result is never rerun.\n */\nimport { effectKey, renderOutcome, writeOutcome } from \"@buildanagent/agent-safety\";\nimport type { ContentBlock } from \"@buildanagent/gateway\";\nimport type { CodeCallEntry, Origin, SessionEntry } from \"@buildanagent/protocol\";\nimport {\n canonicalInputHash,\n createPendingRequest,\n type Resolution,\n type ToolContext,\n type ToolResult,\n verifyResolution,\n} from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport { HarnessError } from \"../errors.js\";\nimport type { CodeCall, CodeCallResult, Harness } from \"../harness.js\";\nimport type { Decision, PolicySession } from \"../permissions/types.js\";\nimport type { RegisteredTool } from \"../tools/types.js\";\nimport { type CodeCallRecord, codeCallsOf, type WaitingCodeCall } from \"./code-call-log.js\";\nimport { writeCodeCallResult } from \"./code-call-result.js\";\nimport { effectScope } from \"./effect-scope.js\";\nimport { interruptedResult } from \"./resume.js\";\nimport { type ResolutionRecord, recordSessionStart } from \"./runner.js\";\nimport type { Session } from \"./session.js\";\nimport { findSticky, stickyDecision } from \"./sticky.js\";\nimport type { EntryInput } from \"./store.js\";\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n/** An entry to write, without the fields the writer fills in. */\nexport type Body = DistributiveOmit<EntryInput, \"id\" | \"parentId\" | \"timestamp\" | \"origin\">;\n\n/** How a code call, or a sandbox escalation, writes: one entry at a time after the one before, with its ids and clock. */\nexport interface Io {\n readonly session: Session;\n write(origin: Origin, body: Body, id?: string): Promise<SessionEntry>;\n readonly newId: () => string;\n readonly clock: Clock;\n}\n\n/** The settings both a call and its resolution take: where its ids and time come from. */\nexport interface IoOptions {\n readonly clock?: Clock;\n readonly newId?: () => string;\n}\n\n/** What running a code call needs besides the tool: its host context and its signal. */\ninterface RunOptions<H> extends IoOptions {\n readonly hostContext?: H;\n readonly signal?: AbortSignal;\n}\n\n// The SDK's default nesting cap, so a tool that starts an agent from a code call nests as it would in a run.\nconst MAX_DEPTH = 2;\n\n/** A writer for `session` with the given ids and clock, defaulting to random ids and the system clock. */\nexport function ioOf(session: Session, options: IoOptions): Io {\n const newId = options.newId ?? (() => globalThis.crypto.randomUUID());\n const clock = options.clock ?? { now: () => new Date().toISOString() };\n return {\n session,\n newId,\n clock,\n async write(origin, body, id = newId()) {\n const entry = { ...body, id, parentId: session.head(), timestamp: clock.now(), origin } as EntryInput;\n const [stored] = await session.append([entry]);\n return stored as SessionEntry;\n },\n };\n}\n\nconst invalid = (message: string, cause?: unknown) =>\n new HarnessError(\"invalid_code_call\", message, cause === undefined ? {} : { cause });\n\nconst describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// One code call of a session runs at a time in a process: a second one would read the first one's open call as a crash.\n// Another process is kept out by the session's lock.\nconst queues = new WeakMap<Session, Promise<unknown>>();\n\n/** Runs `task` after every code call of `session` that this process started before it. */\nexport function inCodeCallQueue<T>(session: Session, task: () => Promise<T>): Promise<T> {\n const next = (queues.get(session) ?? Promise.resolve()).then(task, task);\n queues.set(\n session,\n next.catch(() => undefined),\n );\n return next;\n}\n\n/** The registered tool a code call names, refused when the registry lacks it or only a client can run it. */\nfunction toolFor<H>(harness: Harness<H>, name: string): RegisteredTool {\n const tool = harness.registry.get(name);\n if (tool === undefined) throw invalid(`no tool \"${name}\" is registered, so the code call can't run`);\n if (tool.pattern === \"client_request\") {\n throw invalid(`the tool \"${tool.canonicalName}\" runs on the client, which a code call has no way to reach`);\n }\n return tool;\n}\n\nasync function hashOf(value: unknown, what: string): Promise<string> {\n try {\n return await canonicalInputHash(value);\n } catch (error) {\n throw invalid(`the code call's ${what} has no canonical JSON form`, error);\n }\n}\n\n/**\n * The call's effect key: from the tool's business key when it declares one, and from the scope of `callId` otherwise.\n * A tool the registry no longer has gets the scope's key.\n */\nexport async function codeCallEffectKey<H>(\n session: Session,\n harness: Harness<H>,\n tool: RegisteredTool | undefined,\n call: { readonly callId: string; readonly input: unknown },\n): Promise<string> {\n const businessKey = tool?.definition.effect?.businessKey;\n try {\n return await effectKey(effectScope(session, harness, call.callId), businessKey?.(call.input));\n } catch (error) {\n throw invalid(`the effect key of the call to \"${tool?.canonicalName}\" could not be made`, error);\n }\n}\n\n/** Refuses a harness that can't decide or sign a code call, before anything is written. */\nfunction checkHarness<H>(harness: Harness<H>): void {\n if (harness.pipeline === undefined) {\n throw invalid(\"the harness has no permission pipeline, so no code call can be decided\");\n }\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so a code call could not ask anyone\");\n }\n}\n\n/**\n * Settles each code call a crash left open: writes the result it lacks. A call that started may have taken effect, so\n * it gets the result an interrupted model call gets. A call that never started never ran, so it gets an error that says\n * so: one that stopped before it could run or ask anyone, and one whose answer was written but which stopped, or was\n * refused, before it started. A call that asked and has no final answer still waits.\n */\nasync function settleCodeCalls<H>(path: readonly SessionEntry[], harness: Harness<H>, io: Io): Promise<void> {\n for (const { call, result, requested, answered, letRun } of codeCallsOf(path).values()) {\n if (result !== undefined || (requested !== undefined && !answered && !letRun)) continue;\n const body = letRun\n ? { origin: \"tool\" as const, ...interruptedResult(harness, call.tool) }\n : { origin: \"harness\" as const, ...notRun(answered ? NOT_RUN_ANSWERED : NOT_RUN_EARLY) };\n const { origin, ...fields } = body;\n await io.write(origin, { type: \"tool_result\", callId: call.callId, tool: call.tool, ...fields });\n }\n}\n\nconst NOT_RUN_EARLY = \"The code call stopped before it could run or ask anyone, so it never ran.\";\nconst NOT_RUN_ANSWERED = \"The code call stopped after its answer was written and before it could run, so it never ran.\";\n\nconst notRun = (text: string) => ({\n content: [{ type: \"text\" as const, text }],\n isError: true,\n trust: \"trusted\" as const,\n});\n\n/** Refuses a compensation that names no code call that ran, or that would share that call's effect key. */\nasync function checkCompensation<H>(\n session: Session,\n harness: Harness<H>,\n records: ReadonlyMap<string, CodeCallRecord>,\n compensated: string,\n ownKey: string,\n): Promise<void> {\n const target = records.get(compensated);\n // A denial is the harness's own result. A result from the tool, a crash's result, or a call let run that has no\n // result yet means the call ran or may have run.\n const ran = target?.result === undefined ? target?.letRun === true : target.result.origin === \"tool\";\n if (target === undefined || !ran) {\n throw invalid(`a compensation must name a code call that ran, and \"${compensated}\" names none`);\n }\n const theirs = await codeCallEffectKey(session, harness, harness.registry.get(target.call.tool), target.call);\n if (theirs === ownKey) {\n throw invalid(\"a compensation needs an effect key of its own, and this one has the key of the call it undoes\");\n }\n}\n\n/** Writes an error result for a call that does not run, and returns the denial. */\nasync function deny(io: Io, call: CodeCallEntry, reason: string): Promise<CodeCallResult> {\n const entry = await io.write(\"harness\", {\n type: \"tool_result\",\n callId: call.callId,\n tool: call.tool,\n ...notRun(reason),\n });\n return { status: \"denied\", callId: call.callId, reason, entryId: entry.id };\n}\n\n/** Decides the call with the pipeline, which writes its `permission_decision`, and keeps the policy version it used. */\nasync function decide<H>(\n harness: Harness<H>,\n session: Session,\n io: Io,\n call: CodeCallEntry,\n hostContext: H | undefined,\n): Promise<{ decision: Decision; policyVersion: string | undefined }> {\n let policyVersion: string | undefined;\n const policySession: PolicySession = {\n append(entry) {\n if (entry.type === \"permission_decision\") policyVersion = entry.policyVersion;\n return io.write(\"harness\", entry);\n },\n };\n // checkHarness() refused a harness without a pipeline before anything was written.\n const pipeline = harness.pipeline as NonNullable<Harness<H>[\"pipeline\"]>;\n const decision = await pipeline.decide(\n { callId: call.callId, tool: call.tool, input: call.input, initiator: \"code\" },\n { session: policySession, hostContext, entries: await session.path() },\n );\n return { decision, policyVersion: policyVersion === \"\" ? undefined : policyVersion };\n}\n\nconst isContentList = (content: unknown): content is ToolResult[\"content\"] =>\n Array.isArray(content) &&\n content.every(\n (block: Partial<ContentBlock> | null) =>\n (block?.type === \"text\" && typeof block.text === \"string\") ||\n (block?.type === \"image\" && typeof block.mediaType === \"string\" && typeof block.data === \"string\"),\n );\n\n/** A result with its write outcome's sentence in front of its content, as the model would read it. */\nfunction withOutcome(result: ToolResult<unknown>): ToolResult<unknown> {\n if (!isContentList(result?.content)) throw new TypeError(\"the tool returned content that is not text and images\");\n if (result.outcome === undefined) return result;\n const rendered = renderOutcome(result.outcome);\n return {\n ...result,\n content: [\n { type: \"text\", text: rendered.text },\n { type: \"text\", text: JSON.stringify({ outcome: rendered.payload }) },\n ...result.content,\n ],\n isError: result.isError === true || rendered.isError,\n };\n}\n\n/** The result of a tool that threw or returned something unusable: a write's outcome is unknown, since it may have run. */\nfunction thrownResult(tool: RegisteredTool, error: unknown): ToolResult<unknown> {\n const text = tool.definition.redactErrors === true ? \"The tool failed.\" : `The tool failed: ${describe(error)}`;\n if (tool.definition.effect?.kind !== \"write\") return { content: [{ type: \"text\", text }], isError: true };\n const rendered = renderOutcome(\n writeOutcome({\n kind: \"unknown\",\n operation: tool.canonicalName,\n retry: \"reconcile_first\",\n reason: \"WRITE_FAILED\",\n currentState: \"The tool failed before it returned, so the write may have taken effect.\",\n next: \"Check whether it took effect before you do anything else.\",\n }),\n );\n return {\n content: [\n { type: \"text\", text: rendered.text },\n { type: \"text\", text: JSON.stringify({ outcome: rendered.payload }) },\n { type: \"text\", text },\n ],\n isError: true,\n details: { outcome: rendered.payload },\n };\n}\n\n/**\n * Runs the tool through the harness's wrapper with the host context, and writes its result. The harness's interceptors\n * and observers belong to a turn's model step, so they don't run here; the pipeline already decided the call.\n */\nasync function runTool<H>(\n harness: Harness<H>,\n io: Io,\n tool: RegisteredTool,\n call: CodeCallEntry,\n options: RunOptions<H> & { readonly effectKey: string },\n): Promise<CodeCallResult> {\n const ctx: ToolContext<unknown> = {\n runId: call.callId,\n callId: call.callId,\n signal: options.signal ?? new AbortController().signal,\n depth: 0,\n maxDepth: MAX_DEPTH,\n clock: io.clock,\n app: options.hostContext,\n update: () => undefined,\n };\n let result: ToolResult<unknown>;\n // A wrapper that throws is recorded like a tool that throws, so the call that was let run still gets a result.\n try {\n const definition = harness.wrap === undefined ? tool.definition : harness.wrap(tool, options.hostContext as H);\n result = withOutcome(await definition.execute(call.input, ctx));\n } catch (error) {\n result = thrownResult(tool, error);\n }\n const writer = {\n session: io.session,\n now: io.clock.now,\n signal: ctx.signal,\n write: (body: Body) => io.write(\"tool\", body),\n };\n const entry = await writeCodeCallResult(harness, writer, tool, call, result);\n return { status: \"done\", callId: call.callId, result, entryId: entry.id, effectKey: options.effectKey };\n}\n\n/** Signs the request for a call the pipeline asks about, and writes it before anyone can hear of it. */\nasync function ask<H>(\n harness: Harness<H>,\n io: Io,\n call: CodeCallEntry,\n decision: { reason: string; policyVersion: string | undefined; hostContext: H | undefined; effectKey: string },\n): Promise<CodeCallResult> {\n const { reason, policyVersion, hostContext } = decision;\n const pending = await createPendingRequest(\n {\n kind: \"approval\",\n callId: call.callId,\n tool: call.tool,\n input: call.input,\n ...(policyVersion === undefined ? {} : { policyVersion }),\n ...(reason === \"\" ? {} : { reason }),\n ...(hostContext === undefined ? {} : { app: hostContext }),\n },\n // checkHarness() refused a harness without a signer before anything was written.\n harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n { generateId: io.newId, now: () => new Date(io.clock.now()) },\n );\n await io.write(\"harness\", { type: \"approval_requested\", request: pending, input: call.input });\n return { status: \"awaiting_approval\", callId: call.callId, pending, effectKey: decision.effectKey };\n}\n\n/** Checks everything a code call needs before its first entry, and returns its tool, input hash and effect key. */\nasync function prepare<H>(harness: Harness<H>, session: Session, call: CodeCall<H>, callId: string) {\n checkHarness(harness);\n const tool = toolFor(harness, call.tool);\n const inputHash = await hashOf(call.input, \"input\");\n if (call.hostContext !== undefined) await hashOf(call.hostContext, \"host context\");\n const key = await codeCallEffectKey(session, harness, tool, { callId, input: call.input });\n return { tool, inputHash, key };\n}\n\n/** `Harness.invokeTool()`: see its documentation. */\nexport async function invokeCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n call: CodeCall<H>,\n): Promise<CodeCallResult> {\n // Checked before the queue too, so an aborted call never waits behind another.\n call.signal?.throwIfAborted();\n return inCodeCallQueue(session, () => invokeQueued(harness, session, call));\n}\n\nasync function invokeQueued<H>(harness: Harness<H>, session: Session, call: CodeCall<H>): Promise<CodeCallResult> {\n const io = ioOf(session, call);\n const callId = io.newId();\n const { tool, inputHash, key } = await prepare(harness, session, call, callId);\n const path = await session.path();\n if (call.compensates !== undefined) {\n await checkCompensation(session, harness, codeCallsOf(path), call.compensates, key);\n }\n call.signal?.throwIfAborted();\n await recordSessionStart(harness, (origin, body) => io.write(origin, body), harness.model, path);\n await settleCodeCalls(await session.path(), harness, io);\n const entry: CodeCallEntry = {\n type: \"code_call\",\n callId,\n tool: tool.canonicalName,\n input: call.input,\n inputHash,\n ...(call.compensates === undefined ? {} : { compensates: call.compensates }),\n };\n await io.write(\"harness\", entry, callId);\n const { decision, policyVersion } = await decide(harness, session, io, entry, call.hostContext);\n if (decision.decision === \"deny\") return deny(io, entry, decision.reason);\n const run = { ...call, effectKey: key };\n if (decision.decision === \"allow\") return runTool(harness, io, tool, entry, run);\n const covered = await findSticky(await session.path(), { ...entry, policyVersion }, harness.registry);\n if (covered === undefined) {\n return ask(harness, io, entry, {\n reason: decision.reason,\n policyVersion,\n hostContext: call.hostContext,\n effectKey: key,\n });\n }\n await io.write(\"harness\", await stickyDecision(entry, covered, policyVersion));\n return runTool(harness, io, tool, entry, run);\n}\n\n/**\n * Checks a resolution against the waiting call's signed request before anything is written: the signature under a key\n * the signer holds, the host context the request binds, the call and tool, and the input, which must hash to the signed\n * hash in the `code_call` entry, in the `approval_requested` entry and in the request alike. Throws `approval_refused`\n * with the cause, which names no key, signature or input.\n */\nexport async function checkCodeCallRequest<H>(\n harness: Harness<H>,\n waiting: WaitingCodeCall,\n resolution: Resolution,\n hostContext: H | undefined,\n): Promise<void> {\n const { call, request, input } = waiting;\n const check = await verifyResolution(request, resolution, {\n signer: harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n call: { callId: call.callId, tool: call.tool, input: call.input },\n ...(hostContext === undefined ? {} : { app: hostContext }),\n });\n const cause = check.ok ? await inputCause(call, input) : check.cause;\n if (cause !== undefined) {\n throw new HarnessError(\n \"approval_refused\",\n `the request for code call ${call.callId} failed its check (${cause}), so nothing ran and nothing was written`,\n );\n }\n}\n\n/** `input_changed` unless the recorded input and the input shown to the approver both hash to the recorded hash. */\nasync function inputCause(call: CodeCallEntry, shown: unknown): Promise<\"input_changed\" | undefined> {\n const hash = async (value: unknown) => canonicalInputHash(value).catch(() => undefined);\n const [recorded, asked] = await Promise.all([hash(call.input), hash(shown)]);\n return recorded === call.inputHash && asked === call.inputHash ? undefined : \"input_changed\";\n}\n\n/** What the resolution of a code call is given: the answer the quorum settled on, if any, and the entries to write. */\nexport interface SettledCodeCall {\n readonly forRun: Resolution | undefined;\n readonly records: readonly ResolutionRecord[];\n readonly effectKey: string;\n}\n\n/**\n * Applies a code call's settled resolution: it writes the answers, then leaves the call waiting when the quorum still\n * waits, denies it for a person's or the policy's refusal, and otherwise decides it again with the pipeline, so a deny\n * written since the pause wins, and runs the tool itself, with no model step.\n */\nexport async function finishCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n waiting: WaitingCodeCall,\n settled: SettledCodeCall,\n options: RunOptions<H>,\n): Promise<CodeCallResult> {\n options.signal?.throwIfAborted();\n const io = ioOf(session, options);\n for (const record of settled.records) await io.write(\"user\", { type: \"approval_resolved\", ...record });\n const { call } = waiting;\n const { forRun, effectKey: key } = settled;\n if (forRun === undefined) {\n return { status: \"awaiting_approval\", callId: call.callId, pending: waiting.request, effectKey: key };\n }\n if (!(\"decision\" in forRun) || forRun.decision !== \"allow\") {\n return deny(io, call, (\"reason\" in forRun ? forRun.reason : undefined) ?? \"A person denied the call.\");\n }\n const tool = harness.registry.get(call.tool);\n if (tool?.canonicalName !== call.tool || tool.pattern !== \"in_process\") {\n return deny(io, call, `The tool \"${call.tool}\" is no longer registered for code calls, so the call did not run.`);\n }\n const { decision } = await decide(harness, session, io, call, options.hostContext);\n // A person approved the call, so a question the pipeline would ask again doesn't stop it; a deny does.\n if (decision.decision === \"deny\") return deny(io, call, decision.reason);\n return runTool(harness, io, tool, call, { ...options, effectKey: key });\n}\n"]}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * What the log says about each sandbox escalation: its latest signed request, whether its answer is final, whether its
3
+ * rerun started, and its result. An escalation is keyed by the call id of its request, whose tool is
4
+ * `ESCALATION_TOOL`. That name breaks the canonical tool-name rule, so no registered tool, and no call the model makes,
5
+ * can carry it. A rerun that started and has no result is never run again: the crash rule a code call follows.
6
+ */
7
+ import type { SessionEntry, ToolResultEntry } from "@buildanagent/protocol";
8
+ import type { SignedPendingRequest } from "@buildanagent/sdk";
9
+ import type { SandboxDenial, SandboxPolicy } from "../sandbox/types.js";
10
+ /** The tool name an escalation's signed request carries. It has a dot, so no registered tool can share it. */
11
+ export declare const ESCALATION_TOOL = "sandbox.escalation";
12
+ /**
13
+ * What an escalation's request signs, as the input of its `approval_requested` entry: the call the command ran for,
14
+ * the command, the workspace root, the policy it ran under and the denial. The rerun's policy is built from `policy`
15
+ * and `denial` alone, once the signature over this record verifies.
16
+ */
17
+ export interface EscalationRecord {
18
+ /** The tool the command ran for, which the permission pipeline decides again before the rerun. */
19
+ readonly tool: string;
20
+ /** That tool call's input, as the pipeline sees it. */
21
+ readonly input: unknown;
22
+ /** Who chose the call: the model, or the host's own code. */
23
+ readonly initiator: "model" | "code";
24
+ /** The tool call's own id, when the command ran for one. */
25
+ readonly toolCallId?: string;
26
+ /** The executable and its arguments. */
27
+ readonly command: readonly string[];
28
+ /** The working directory, relative to the workspace root. */
29
+ readonly cwd?: string;
30
+ /** The command's timeout, which the rerun keeps. */
31
+ readonly timeoutMs?: number;
32
+ /** The command's output cap, which the rerun keeps. */
33
+ readonly maxOutputBytes?: number;
34
+ /** The workspace root the sandbox was provisioned for. */
35
+ readonly root: string;
36
+ /** The policy the command ran under. */
37
+ readonly policy: SandboxPolicy;
38
+ /** What the backend refused. */
39
+ readonly denial: SandboxDenial;
40
+ }
41
+ /** True when `value` has the shape of an `EscalationRecord`. A record is checked after its signature verifies too. */
42
+ export declare function isEscalationRecord(value: unknown): value is EscalationRecord;
43
+ /** One escalation as the log records it. */
44
+ export interface EscalationLogRecord {
45
+ /** The escalation's id: its request's call id. */
46
+ readonly id: string;
47
+ /** The latest signed request and the record it signs, which a forged entry may not hold until it is checked. */
48
+ readonly requested: {
49
+ readonly request: SignedPendingRequest;
50
+ readonly input: unknown;
51
+ };
52
+ /** True once an answer is final: one no quorum still waits on, or the policy's refusal. */
53
+ readonly answered: boolean;
54
+ /**
55
+ * True once the rerun started: after a final allow, the permission pipeline wrote a decision that is not a deny.
56
+ * That entry is the last one before the rerun runs.
57
+ */
58
+ readonly started: boolean;
59
+ /** The escalation's `tool_result` entry, once it has one. */
60
+ readonly result?: SessionEntry & ToolResultEntry;
61
+ }
62
+ /** Every escalation on `path`, by id, in the order they asked. */
63
+ export declare function escalationsOf(path: readonly SessionEntry[]): Map<string, EscalationLogRecord>;
64
+ /** The escalations on `path` that wait for an answer: no final answer, no started rerun and no result. */
65
+ export declare function waitingEscalations(path: readonly SessionEntry[]): EscalationLogRecord[];
@@ -0,0 +1,84 @@
1
+ import { isDenial } from "../sandbox/widen.js";
2
+ /** The tool name an escalation's signed request carries. It has a dot, so no registered tool can share it. */
3
+ export const ESCALATION_TOOL = "sandbox.escalation";
4
+ const isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
5
+ function isPolicy(value) {
6
+ if (typeof value !== "object" || value === null)
7
+ return false;
8
+ const policy = value;
9
+ const network = policy.network;
10
+ return (isStrings(policy.readRoots) &&
11
+ isStrings(policy.writeRoots) &&
12
+ typeof network === "object" &&
13
+ network !== null &&
14
+ isStrings(network.allow) &&
15
+ isStrings(network.deny));
16
+ }
17
+ const optional = (value, type) => value === undefined || typeof value === type;
18
+ /** True when `value` has the shape of an `EscalationRecord`. A record is checked after its signature verifies too. */
19
+ export function isEscalationRecord(value) {
20
+ if (typeof value !== "object" || value === null)
21
+ return false;
22
+ const record = value;
23
+ return (typeof record.tool === "string" &&
24
+ (record.initiator === "model" || record.initiator === "code") &&
25
+ optional(record.toolCallId, "string") &&
26
+ isStrings(record.command) &&
27
+ record.command.length > 0 &&
28
+ optional(record.cwd, "string") &&
29
+ optional(record.timeoutMs, "number") &&
30
+ optional(record.maxOutputBytes, "number") &&
31
+ typeof record.root === "string" &&
32
+ isPolicy(record.policy) &&
33
+ isDenial(record.denial));
34
+ }
35
+ /** Folds a request: a later request for the same escalation replaces the earlier one and waits for its own answer. */
36
+ function foldRequest(drafts, byRequest, entry) {
37
+ if (entry.type !== "approval_requested")
38
+ return;
39
+ const id = entry.request.callId;
40
+ const requested = { request: entry.request, input: entry.input };
41
+ const draft = drafts.get(id);
42
+ if (draft === undefined)
43
+ drafts.set(id, { id, requested, answered: false, personAllowed: false, started: false });
44
+ else
45
+ Object.assign(draft, { requested, answered: false, personAllowed: false });
46
+ byRequest.set(entry.request.id, id);
47
+ }
48
+ /** Folds an entry that names the escalation's id: the pipeline's decision, which starts the rerun, or its result. */
49
+ function foldCall(draft, entry) {
50
+ if (entry.type === "permission_decision")
51
+ draft.started = entry.decision !== "deny" && draft.personAllowed;
52
+ else if (entry.type === "tool_result")
53
+ draft.result ??= entry;
54
+ }
55
+ function fold(drafts, byRequest, entry) {
56
+ if (entry.type === "approval_requested" && entry.request.tool === ESCALATION_TOOL) {
57
+ foldRequest(drafts, byRequest, entry);
58
+ }
59
+ else if (entry.type === "approval_resolved" && entry.quorum === undefined) {
60
+ const draft = drafts.get(byRequest.get(entry.resolution.requestId) ?? "");
61
+ if (draft === undefined)
62
+ return;
63
+ draft.answered = true;
64
+ draft.personAllowed = "decision" in entry.resolution && entry.resolution.decision === "allow";
65
+ }
66
+ else if ("callId" in entry) {
67
+ const draft = drafts.get(entry.callId);
68
+ if (draft !== undefined)
69
+ foldCall(draft, entry);
70
+ }
71
+ }
72
+ /** Every escalation on `path`, by id, in the order they asked. */
73
+ export function escalationsOf(path) {
74
+ const drafts = new Map();
75
+ const byRequest = new Map();
76
+ for (const entry of path)
77
+ fold(drafts, byRequest, entry);
78
+ return drafts;
79
+ }
80
+ /** The escalations on `path` that wait for an answer: no final answer, no started rerun and no result. */
81
+ export function waitingEscalations(path) {
82
+ return [...escalationsOf(path).values()].filter((record) => record.result === undefined && !record.answered && !record.started);
83
+ }
84
+ //# sourceMappingURL=escalation-log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"escalation-log.js","sourceRoot":"","sources":["../../src/session/escalation-log.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAE/C,8GAA8G;AAC9G,MAAM,CAAC,MAAM,eAAe,GAAG,oBAAoB,CAAC;AAgCpD,MAAM,SAAS,GAAG,CAAC,KAAc,EAAqB,EAAE,CACtD,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC;AAE1E,SAAS,QAAQ,CAAC,KAAc;IAC9B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,MAAM,GAAG,KAAgC,CAAC;IAChD,MAAM,OAAO,GAAG,MAAM,CAAC,OAA8C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O,CAC/E,CAAC;AACJ,CAAC","sourcesContent":["/**\n * What the log says about each sandbox escalation: its latest signed request, whether its answer is final, whether its\n * rerun started, and its result. An escalation is keyed by the call id of its request, whose tool is\n * `ESCALATION_TOOL`. That name breaks the canonical tool-name rule, so no registered tool, and no call the model makes,\n * can carry it. A rerun that started and has no result is never run again: the crash rule a code call follows.\n */\nimport type { SessionEntry, ToolResultEntry } from \"@buildanagent/protocol\";\nimport type { SignedPendingRequest } from \"@buildanagent/sdk\";\nimport type { SandboxDenial, SandboxPolicy } from \"../sandbox/types.js\";\nimport { isDenial } from \"../sandbox/widen.js\";\n\n/** The tool name an escalation's signed request carries. It has a dot, so no registered tool can share it. */\nexport const ESCALATION_TOOL = \"sandbox.escalation\";\n\n/**\n * What an escalation's request signs, as the input of its `approval_requested` entry: the call the command ran for,\n * the command, the workspace root, the policy it ran under and the denial. The rerun's policy is built from `policy`\n * and `denial` alone, once the signature over this record verifies.\n */\nexport interface EscalationRecord {\n /** The tool the command ran for, which the permission pipeline decides again before the rerun. */\n readonly tool: string;\n /** That tool call's input, as the pipeline sees it. */\n readonly input: unknown;\n /** Who chose the call: the model, or the host's own code. */\n readonly initiator: \"model\" | \"code\";\n /** The tool call's own id, when the command ran for one. */\n readonly toolCallId?: string;\n /** The executable and its arguments. */\n readonly command: readonly string[];\n /** The working directory, relative to the workspace root. */\n readonly cwd?: string;\n /** The command's timeout, which the rerun keeps. */\n readonly timeoutMs?: number;\n /** The command's output cap, which the rerun keeps. */\n readonly maxOutputBytes?: number;\n /** The workspace root the sandbox was provisioned for. */\n readonly root: string;\n /** The policy the command ran under. */\n readonly policy: SandboxPolicy;\n /** What the backend refused. */\n readonly denial: SandboxDenial;\n}\n\nconst isStrings = (value: unknown): value is string[] =>\n Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\nfunction isPolicy(value: unknown): value is SandboxPolicy {\n if (typeof value !== \"object\" || value === null) return false;\n const policy = value as Record<string, unknown>;\n const network = policy.network as Record<string, unknown> | undefined;\n return (\n isStrings(policy.readRoots) &&\n isStrings(policy.writeRoots) &&\n typeof network === \"object\" &&\n network !== null &&\n isStrings(network.allow) &&\n isStrings(network.deny)\n );\n}\n\nconst optional = (value: unknown, type: \"string\" | \"number\"): boolean => value === undefined || typeof value === type;\n\n/** True when `value` has the shape of an `EscalationRecord`. A record is checked after its signature verifies too. */\nexport function isEscalationRecord(value: unknown): value is EscalationRecord {\n if (typeof value !== \"object\" || value === null) return false;\n const record = value as Record<string, unknown>;\n return (\n typeof record.tool === \"string\" &&\n (record.initiator === \"model\" || record.initiator === \"code\") &&\n optional(record.toolCallId, \"string\") &&\n isStrings(record.command) &&\n record.command.length > 0 &&\n optional(record.cwd, \"string\") &&\n optional(record.timeoutMs, \"number\") &&\n optional(record.maxOutputBytes, \"number\") &&\n typeof record.root === \"string\" &&\n isPolicy(record.policy) &&\n isDenial(record.denial)\n );\n}\n\n/** One escalation as the log records it. */\nexport interface EscalationLogRecord {\n /** The escalation's id: its request's call id. */\n readonly id: string;\n /** The latest signed request and the record it signs, which a forged entry may not hold until it is checked. */\n readonly requested: { readonly request: SignedPendingRequest; readonly input: unknown };\n /** True once an answer is final: one no quorum still waits on, or the policy's refusal. */\n readonly answered: boolean;\n /**\n * True once the rerun started: after a final allow, the permission pipeline wrote a decision that is not a deny.\n * That entry is the last one before the rerun runs.\n */\n readonly started: boolean;\n /** The escalation's `tool_result` entry, once it has one. */\n readonly result?: SessionEntry & ToolResultEntry;\n}\n\ninterface Draft {\n id: string;\n requested: { request: SignedPendingRequest; input: unknown };\n answered: boolean;\n personAllowed: boolean;\n started: boolean;\n result?: SessionEntry & ToolResultEntry;\n}\n\n/** Folds a request: a later request for the same escalation replaces the earlier one and waits for its own answer. */\nfunction foldRequest(drafts: Map<string, Draft>, byRequest: Map<string, string>, entry: SessionEntry): void {\n if (entry.type !== \"approval_requested\") return;\n const id = entry.request.callId;\n const requested = { request: entry.request, input: entry.input };\n const draft = drafts.get(id);\n if (draft === undefined) drafts.set(id, { id, requested, answered: false, personAllowed: false, started: false });\n else Object.assign(draft, { requested, answered: false, personAllowed: false });\n byRequest.set(entry.request.id, id);\n}\n\n/** Folds an entry that names the escalation's id: the pipeline's decision, which starts the rerun, or its result. */\nfunction foldCall(draft: Draft, entry: SessionEntry): void {\n if (entry.type === \"permission_decision\") draft.started = entry.decision !== \"deny\" && draft.personAllowed;\n else if (entry.type === \"tool_result\") draft.result ??= entry;\n}\n\nfunction fold(drafts: Map<string, Draft>, byRequest: Map<string, string>, entry: SessionEntry): void {\n if (entry.type === \"approval_requested\" && entry.request.tool === ESCALATION_TOOL) {\n foldRequest(drafts, byRequest, entry);\n } else if (entry.type === \"approval_resolved\" && entry.quorum === undefined) {\n const draft = drafts.get(byRequest.get(entry.resolution.requestId) ?? \"\");\n if (draft === undefined) return;\n draft.answered = true;\n draft.personAllowed = \"decision\" in entry.resolution && entry.resolution.decision === \"allow\";\n } else if (\"callId\" in entry) {\n const draft = drafts.get(entry.callId);\n if (draft !== undefined) foldCall(draft, entry);\n }\n}\n\n/** Every escalation on `path`, by id, in the order they asked. */\nexport function escalationsOf(path: readonly SessionEntry[]): Map<string, EscalationLogRecord> {\n const drafts = new Map<string, Draft>();\n const byRequest = new Map<string, string>();\n for (const entry of path) fold(drafts, byRequest, entry);\n return drafts;\n}\n\n/** The escalations on `path` that wait for an answer: no final answer, no started rerun and no result. */\nexport function waitingEscalations(path: readonly SessionEntry[]): EscalationLogRecord[] {\n return [...escalationsOf(path).values()].filter(\n (record) => record.result === undefined && !record.answered && !record.started,\n );\n}\n"]}
@@ -6,6 +6,7 @@
6
6
  * call is the host's, not the model's, so its entries build no message either.
7
7
  */
8
8
  import { HarnessError } from "../errors.js";
9
+ import { ESCALATION_TOOL } from "./escalation-log.js";
9
10
  const ordered = (blocks) => [...blocks].sort((a, b) => a.index - b.index).map((entry) => entry.block);
10
11
  /** Builds messages from entries one at a time, keeping a message open until the entry that ends it arrives. */
11
12
  class MessageBuilder {
@@ -186,10 +187,18 @@ export function contextWithStarts(path) {
186
187
  for (const entry of path)
187
188
  if (entry.type === "turn_start")
188
189
  system = entry.system;
189
- // A code call's result answers no call the model made, so the model never reads it.
190
- const codeCalls = new Set(path.flatMap((entry) => (entry.type === "code_call" ? [entry.callId] : [])));
190
+ // A code call's or a sandbox escalation's result answers no call the model made, so the model never reads it. Both
191
+ // are known by their call ids, never by the result's tool name: the model can call a tool named `sandbox.escalation`,
192
+ // and its error result must stay, or the rebuilt context would hold a tool call with no result.
193
+ const hostCalls = new Set(path.flatMap((entry) => {
194
+ if (entry.type === "code_call")
195
+ return [entry.callId];
196
+ if (entry.type === "approval_requested" && entry.request.tool === ESCALATION_TOOL)
197
+ return [entry.request.callId];
198
+ return [];
199
+ }));
191
200
  for (const entry of entries) {
192
- if (entry.type === "tool_result" && codeCalls.has(entry.callId))
201
+ if (entry.type === "tool_result" && hostCalls.has(entry.callId))
193
202
  continue;
194
203
  switch (entry.type) {
195
204
  case "message_block":
@@ -1 +1 @@
1
- {"version":3,"file":"rebuild.js","sourceRoot":"","sources":["../../src/session/rebuild.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAK5C,MAAM,OAAO,GAAG,CAAC,MAAwB,EAAkB,EAAE,CAC3D,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAE5E,+GAA+G;AAC/G,MAAM,cAAc;IACT,QAAQ,GAAc,EAAE,CAAC;IAClC,0EAA0E;IACjE,MAAM,GAAa,EAAE,CAAC;IAC/B,KAAK,CAAsB;IAClB,UAAU,CAAsB;IACzC,MAAM,CAA6D;IAEnE,YAAY,SAAS,GAAwB,IAAI,GAAG,EAA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AK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;SAC3F;QACD,MAAM;KACP,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,SAAS,CAAC,IAA6B;IACrD,OAAO,iBAAiB,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC;AACzC,CAAC","sourcesContent":["/**\n * Rebuilds the SDK's `Context` from a session's entries, so the log is the only state: any process can read the log\n * and go on with `continueRun()`. A message is the `message_block` entries that share a `messageId`, in `index` order;\n * an assistant message is closed by its `message_end` and takes its usage and cost from the `usage` entry right after\n * it. A `usage` entry anywhere else belongs to a call whose message was superseded, and builds no message. A code\n * call is the host's, not the model's, so its entries build no message either.\n */\n\nimport type { AssistantMessage, ContentBlock, Message } from \"@buildanagent/gateway\";\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Context, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\n\ntype Block = Extract<SessionEntry, { type: \"message_block\" }>;\ntype Pending = { role: \"user\" | \"assistant\"; id: string; blocks: Block[]; firstId: string };\n\nconst ordered = (blocks: readonly Block[]): ContentBlock[] =>\n [...blocks].sort((a, b) => a.index - b.index).map((entry) => entry.block);\n\n/** Builds messages from entries one at a time, keeping a message open until the entry that ends it arrives. */\nclass MessageBuilder {\n readonly messages: Message[] = [];\n /** The id of the first entry of each message, in step with `messages`. */\n readonly starts: string[] = [];\n #open: Pending | undefined;\n readonly #dropEmpty: ReadonlySet<string>;\n #ended: Extract<SessionEntry, { type: \"message_end\" }> | undefined;\n\n constructor(dropEmpty: ReadonlySet<string> = new Set()) {\n this.#dropEmpty = dropEmpty;\n }\n\n /** Closes the user message being built, if there is one. */\n #closeUser(): void {\n if (this.#open?.role !== \"user\") return;\n this.messages.push({ role: \"user\", content: ordered(this.#open.blocks) });\n this.starts.push(this.#open.firstId);\n this.#open = undefined;\n }\n\n block(entry: Block): void {\n this.#settleEnded(undefined);\n if (this.#open === undefined || this.#open.id !== entry.messageId || this.#open.role !== entry.role) {\n this.#closeUser();\n this.#open = { role: entry.role, id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#open.blocks.push(entry);\n }\n\n /** An assistant message with no usage entry after it still counts, with unknown cost. */\n #settleEnded(usage: Extract<SessionEntry, { type: \"usage\" }> | undefined): void {\n const end = this.#ended;\n const open = this.#open;\n if (end === undefined || open === undefined) return;\n this.#ended = undefined;\n this.#open = undefined;\n // A message whose signed reasoning was left out and that has nothing else would be an empty assistant turn.\n if (open.blocks.length === 0 && this.#dropEmpty.has(open.id)) return;\n const message: AssistantMessage = {\n role: \"assistant\",\n content: ordered(open.blocks),\n model: end.model,\n stopReason: end.stopReason,\n ...(end.error === undefined ? {} : { error: end.error }),\n usage: usage?.usage ?? EMPTY_USAGE,\n ...(usage?.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: usage.lastAttemptUsage }),\n cost: usage?.cost ?? EMPTY_COST,\n };\n this.messages.push(message);\n this.starts.push(open.firstId);\n }\n\n end(entry: Extract<SessionEntry, { type: \"message_end\" }>): void {\n this.#settleEnded(undefined);\n if (this.#open?.role !== \"assistant\" || this.#open.id !== entry.messageId) {\n // A message with no blocks has no open message to close.\n this.#closeUser();\n this.#open = { role: \"assistant\", id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#ended = entry;\n }\n\n usage(entry: Extract<SessionEntry, { type: \"usage\" }>): void {\n if (entry.source === \"model_call\" && this.#ended !== undefined) this.#settleEnded(entry);\n }\n\n toolResult(entry: Extract<SessionEntry, { type: \"tool_result\" }>): void {\n this.#settleEnded(undefined);\n this.#closeUser();\n this.messages.push({ role: \"tool\", callId: entry.callId, content: entry.content, isError: entry.isError });\n this.starts.push(entry.id);\n }\n\n finish(): Message[] {\n this.#settleEnded(undefined);\n this.#closeUser();\n return this.messages;\n }\n}\n\n// A message with no usage entry, which a crash between the two writes leaves, has no usage anyone knows.\nconst EMPTY_USAGE: AssistantMessage[\"usage\"] = {\n uncachedInput: 0,\n cacheRead: 0,\n cacheWrite: { \"5m\": 0, \"1h\": 0 },\n output: 0,\n reasoning: 0,\n raw: null,\n};\nconst EMPTY_COST: AssistantMessage[\"cost\"] = { total: null, basis: \"unknown\", currency: \"USD\" };\n\n/** A request that waits for a person, with the input its call would run with once approved. */\nexport interface PendingApproval {\n readonly request: SignedPendingRequest;\n readonly input: unknown;\n}\n\n/**\n * The requests on `path` that still wait: the latest request for each call of the last assistant message, while the call\n * has no result. A resolution does not end a wait, because the run that applies it may refuse it or never finish: only\n * the call's result does. A resume that started and died before the result is a crash, which `crashedResumes()` names,\n * and its requests do not wait.\n */\nexport function pendingApprovals(path: readonly SessionEntry[]): PendingApproval[] {\n const answered = new Set<string>();\n const latest = new Map<string, PendingApproval>();\n let lastMessage: string | undefined;\n let lastCalls = new Set<string>();\n for (const entry of path) {\n if (entry.type === \"tool_result\") answered.add(entry.callId);\n if (entry.type === \"approval_requested\")\n latest.set(entry.request.callId, { request: entry.request, input: entry.input });\n if (entry.type === \"message_block\" && entry.role === \"assistant\") {\n if (entry.messageId !== lastMessage) lastCalls = new Set();\n lastMessage = entry.messageId;\n if (entry.block.type === \"tool_call\") lastCalls.add(entry.block.callId);\n }\n }\n const crashed = crashedResumes(path);\n return [...latest.values()].filter(\n (entry) =>\n lastCalls.has(entry.request.callId) && !answered.has(entry.request.callId) && !crashed.has(entry.request.id),\n );\n}\n\n/**\n * The ids of the requests whose resume started and died: the log ends in a `continue` turn that has no end, after\n * allows were written for it. An approved call may have run, so it is settled as a crash and not asked again, even\n * when the run died before it reached that call.\n */\nexport function crashedResumes(path: readonly SessionEntry[]): Set<string> {\n const start = path.findLastIndex((entry) => entry.type === \"turn_start\");\n const turn = path[start];\n if (turn?.type !== \"turn_start\" || turn.mode !== \"continue\") return new Set();\n if (path.slice(start).some((entry) => entry.type === \"turn_end\")) return new Set();\n // Only the allows this run was given: a deny or an answer runs nothing, and an earlier run's answers are its own.\n const since = path.slice(0, start).findLastIndex((entry) => entry.type === \"turn_end\");\n return new Set(\n path.slice(since + 1, start).flatMap((entry) => {\n const answer = entry.type === \"approval_resolved\" && entry.quorum === undefined ? entry.resolution : undefined;\n return answer !== undefined && \"decision\" in answer && answer.decision === \"allow\" ? [answer.requestId] : [];\n }),\n );\n}\n\nconst isSignedReasoning = (entry: SessionEntry): boolean =>\n entry.type === \"message_block\" && entry.block.type === \"reasoning\" && entry.block.signature !== undefined;\n\n/** The user message that stands for the summarised span, so the model reads the summary where the span was. */\nexport function summaryMessage(summary: string): Message {\n return {\n role: \"user\",\n content: [\n { type: \"text\", text: `The earlier part of this conversation was summarized to save space:\\n\\n${summary}` },\n ],\n };\n}\n\n/**\n * The entries a context is built from, and whether a compaction applies. The latest `compaction` on the path replaces\n * everything before its `firstKeptEntryId`. The kept tail loses its signed reasoning, because a block that follows the\n * edited span would carry a signature the summary made stale; blocks written after the compaction are untouched.\n */\nexport function entriesAfterCompaction(path: readonly SessionEntry[]): {\n readonly entries: readonly SessionEntry[];\n readonly summary: string | undefined;\n /** The ids of messages that lost a signed reasoning block. */\n readonly stripped: ReadonlySet<string>;\n} {\n const at = path.findLastIndex((entry) => entry.type === \"compaction\");\n const compaction = path[at];\n if (compaction?.type !== \"compaction\") return { entries: path, summary: undefined, stripped: new Set() };\n const kept = path.findIndex((entry) => entry.id === compaction.firstKeptEntryId);\n if (kept < 0) {\n throw new HarnessError(\n \"entry_not_found\",\n `the compaction ${compaction.id} keeps from entry ${compaction.firstKeptEntryId}, which is not on this path`,\n );\n }\n // The messages that lose a block here are the only ones an empty result may drop.\n const stripped = new Set<string>();\n const entries = path.slice(kept).filter((entry, i) => {\n const drop = kept + i < at && isSignedReasoning(entry);\n if (drop && entry.type === \"message_block\") stripped.add(entry.messageId);\n return !drop;\n });\n return { entries: entries.filter((entry) => entry.type !== \"compaction\"), summary: compaction.summary, stripped };\n}\n\n/**\n * The context a path of entries stands for, with the id of the entry each message starts at (`null` for a summary).\n * `path` is a session's `path()`: the root to a HEAD, without `checkout` entries. The system prompt is the latest\n * `turn_start`'s, byte for byte, so a harness whose prompt changed later still rebuilds the conversation the model\n * saw. The latest compaction applies: its summary stands first, then the kept tail and what followed it.\n */\nexport function contextWithStarts(path: readonly SessionEntry[]): {\n readonly context: Context;\n readonly starts: readonly (string | null)[];\n} {\n const { entries, summary, stripped } = entriesAfterCompaction(path);\n const builder = new MessageBuilder(stripped);\n let system = \"\";\n for (const entry of path) if (entry.type === \"turn_start\") system = entry.system;\n // A code call's result answers no call the model made, so the model never reads it.\n const codeCalls = new Set(path.flatMap((entry) => (entry.type === \"code_call\" ? [entry.callId] : [])));\n for (const entry of entries) {\n if (entry.type === \"tool_result\" && codeCalls.has(entry.callId)) continue;\n switch (entry.type) {\n case \"message_block\":\n builder.block(entry);\n break;\n case \"message_end\":\n builder.end(entry);\n break;\n case \"usage\":\n builder.usage(entry);\n break;\n case \"tool_result\":\n builder.toolResult(entry);\n break;\n default:\n }\n }\n const built = builder.finish();\n const messages = summary === undefined ? built : [summaryMessage(summary), ...built];\n const starts = summary === undefined ? builder.starts : [null, ...builder.starts];\n const waiting = pendingApprovals(path);\n if (waiting.length === 0) return { context: { system, messages }, starts };\n return {\n context: {\n system,\n messages,\n pending: waiting.map((entry) => entry.request),\n pendingInputs: Object.fromEntries(waiting.map((entry) => [entry.request.id, entry.input])),\n },\n starts,\n };\n}\n\n/** The context a path of entries stands for. See `contextWithStarts()`. */\nexport function contextOf(path: readonly SessionEntry[]): Context {\n return contextWithStarts(path).context;\n}\n"]}
1
+ {"version":3,"file":"rebuild.js","sourceRoot":"","sources":["../../src/session/rebuild.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAKtD,MAAM,OAAO,GAAG,CAAC,MAAwB,EAAkB,EAAE,CAC3D,CA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AC,OAAO,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC;IACrF,MAAM,MAAM,GAAG,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAClF,MAAM,OAAO,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IACvC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,CAAC;IAC3E,OAAO;QACL,OAAO,EAAE;YACP,MAAM;YACN,QAAQ;YACR,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC;YAC9C,aAAa,EAAE,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;SAC3F;QACD,MAAM;KACP,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,SAAS,CAAC,IAA6B;IACrD,OAAO,iBAAiB,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC;AACzC,CAAC","sourcesContent":["/**\n * Rebuilds the SDK's `Context` from a session's entries, so the log is the only state: any process can read the log\n * and go on with `continueRun()`. A message is the `message_block` entries that share a `messageId`, in `index` order;\n * an assistant message is closed by its `message_end` and takes its usage and cost from the `usage` entry right after\n * it. A `usage` entry anywhere else belongs to a call whose message was superseded, and builds no message. A code\n * call is the host's, not the model's, so its entries build no message either.\n */\n\nimport type { AssistantMessage, ContentBlock, Message } from \"@buildanagent/gateway\";\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Context, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport { ESCALATION_TOOL } from \"./escalation-log.js\";\n\ntype Block = Extract<SessionEntry, { type: \"message_block\" }>;\ntype Pending = { role: \"user\" | \"assistant\"; id: string; blocks: Block[]; firstId: string };\n\nconst ordered = (blocks: readonly Block[]): ContentBlock[] =>\n [...blocks].sort((a, b) => a.index - b.index).map((entry) => entry.block);\n\n/** Builds messages from entries one at a time, keeping a message open until the entry that ends it arrives. */\nclass MessageBuilder {\n readonly messages: Message[] = [];\n /** The id of the first entry of each message, in step with `messages`. */\n readonly starts: string[] = [];\n #open: Pending | undefined;\n readonly #dropEmpty: ReadonlySet<string>;\n #ended: Extract<SessionEntry, { type: \"message_end\" }> | undefined;\n\n constructor(dropEmpty: ReadonlySet<string> = new Set()) {\n this.#dropEmpty = dropEmpty;\n }\n\n /** Closes the user message being built, if there is one. */\n #closeUser(): void {\n if (this.#open?.role !== \"user\") return;\n this.messages.push({ role: \"user\", content: ordered(this.#open.blocks) });\n this.starts.push(this.#open.firstId);\n this.#open = undefined;\n }\n\n block(entry: Block): void {\n this.#settleEnded(undefined);\n if (this.#open === undefined || this.#open.id !== entry.messageId || this.#open.role !== entry.role) {\n this.#closeUser();\n this.#open = { role: entry.role, id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#open.blocks.push(entry);\n }\n\n /** An assistant message with no usage entry after it still counts, with unknown cost. */\n #settleEnded(usage: Extract<SessionEntry, { type: \"usage\" }> | undefined): void {\n const end = this.#ended;\n const open = this.#open;\n if (end === undefined || open === undefined) return;\n this.#ended = undefined;\n this.#open = undefined;\n // A message whose signed reasoning was left out and that has nothing else would be an empty assistant turn.\n if (open.blocks.length === 0 && this.#dropEmpty.has(open.id)) return;\n const message: AssistantMessage = {\n role: \"assistant\",\n content: ordered(open.blocks),\n model: end.model,\n stopReason: end.stopReason,\n ...(end.error === undefined ? {} : { error: end.error }),\n usage: usage?.usage ?? EMPTY_USAGE,\n ...(usage?.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: usage.lastAttemptUsage }),\n cost: usage?.cost ?? EMPTY_COST,\n };\n this.messages.push(message);\n this.starts.push(open.firstId);\n }\n\n end(entry: Extract<SessionEntry, { type: \"message_end\" }>): void {\n this.#settleEnded(undefined);\n if (this.#open?.role !== \"assistant\" || this.#open.id !== entry.messageId) {\n // A message with no blocks has no open message to close.\n this.#closeUser();\n this.#open = { role: \"assistant\", id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#ended = entry;\n }\n\n usage(entry: Extract<SessionEntry, { type: \"usage\" }>): void {\n if (entry.source === \"model_call\" && this.#ended !== undefined) this.#settleEnded(entry);\n }\n\n toolResult(entry: Extract<SessionEntry, { type: \"tool_result\" }>): void {\n this.#settleEnded(undefined);\n this.#closeUser();\n this.messages.push({ role: \"tool\", callId: entry.callId, content: entry.content, isError: entry.isError });\n this.starts.push(entry.id);\n }\n\n finish(): Message[] {\n this.#settleEnded(undefined);\n this.#closeUser();\n return this.messages;\n }\n}\n\n// A message with no usage entry, which a crash between the two writes leaves, has no usage anyone knows.\nconst EMPTY_USAGE: AssistantMessage[\"usage\"] = {\n uncachedInput: 0,\n cacheRead: 0,\n cacheWrite: { \"5m\": 0, \"1h\": 0 },\n output: 0,\n reasoning: 0,\n raw: null,\n};\nconst EMPTY_COST: AssistantMessage[\"cost\"] = { total: null, basis: \"unknown\", currency: \"USD\" };\n\n/** A request that waits for a person, with the input its call would run with once approved. */\nexport interface PendingApproval {\n readonly request: SignedPendingRequest;\n readonly input: unknown;\n}\n\n/**\n * The requests on `path` that still wait: the latest request for each call of the last assistant message, while the call\n * has no result. A resolution does not end a wait, because the run that applies it may refuse it or never finish: only\n * the call's result does. A resume that started and died before the result is a crash, which `crashedResumes()` names,\n * and its requests do not wait.\n */\nexport function pendingApprovals(path: readonly SessionEntry[]): PendingApproval[] {\n const answered = new Set<string>();\n const latest = new Map<string, PendingApproval>();\n let lastMessage: string | undefined;\n let lastCalls = new Set<string>();\n for (const entry of path) {\n if (entry.type === \"tool_result\") answered.add(entry.callId);\n if (entry.type === \"approval_requested\")\n latest.set(entry.request.callId, { request: entry.request, input: entry.input });\n if (entry.type === \"message_block\" && entry.role === \"assistant\") {\n if (entry.messageId !== lastMessage) lastCalls = new Set();\n lastMessage = entry.messageId;\n if (entry.block.type === \"tool_call\") lastCalls.add(entry.block.callId);\n }\n }\n const crashed = crashedResumes(path);\n return [...latest.values()].filter(\n (entry) =>\n lastCalls.has(entry.request.callId) && !answered.has(entry.request.callId) && !crashed.has(entry.request.id),\n );\n}\n\n/**\n * The ids of the requests whose resume started and died: the log ends in a `continue` turn that has no end, after\n * allows were written for it. An approved call may have run, so it is settled as a crash and not asked again, even\n * when the run died before it reached that call.\n */\nexport function crashedResumes(path: readonly SessionEntry[]): Set<string> {\n const start = path.findLastIndex((entry) => entry.type === \"turn_start\");\n const turn = path[start];\n if (turn?.type !== \"turn_start\" || turn.mode !== \"continue\") return new Set();\n if (path.slice(start).some((entry) => entry.type === \"turn_end\")) return new Set();\n // Only the allows this run was given: a deny or an answer runs nothing, and an earlier run's answers are its own.\n const since = path.slice(0, start).findLastIndex((entry) => entry.type === \"turn_end\");\n return new Set(\n path.slice(since + 1, start).flatMap((entry) => {\n const answer = entry.type === \"approval_resolved\" && entry.quorum === undefined ? entry.resolution : undefined;\n return answer !== undefined && \"decision\" in answer && answer.decision === \"allow\" ? [answer.requestId] : [];\n }),\n );\n}\n\nconst isSignedReasoning = (entry: SessionEntry): boolean =>\n entry.type === \"message_block\" && entry.block.type === \"reasoning\" && entry.block.signature !== undefined;\n\n/** The user message that stands for the summarised span, so the model reads the summary where the span was. */\nexport function summaryMessage(summary: string): Message {\n return {\n role: \"user\",\n content: [\n { type: \"text\", text: `The earlier part of this conversation was summarized to save space:\\n\\n${summary}` },\n ],\n };\n}\n\n/**\n * The entries a context is built from, and whether a compaction applies. The latest `compaction` on the path replaces\n * everything before its `firstKeptEntryId`. The kept tail loses its signed reasoning, because a block that follows the\n * edited span would carry a signature the summary made stale; blocks written after the compaction are untouched.\n */\nexport function entriesAfterCompaction(path: readonly SessionEntry[]): {\n readonly entries: readonly SessionEntry[];\n readonly summary: string | undefined;\n /** The ids of messages that lost a signed reasoning block. */\n readonly stripped: ReadonlySet<string>;\n} {\n const at = path.findLastIndex((entry) => entry.type === \"compaction\");\n const compaction = path[at];\n if (compaction?.type !== \"compaction\") return { entries: path, summary: undefined, stripped: new Set() };\n const kept = path.findIndex((entry) => entry.id === compaction.firstKeptEntryId);\n if (kept < 0) {\n throw new HarnessError(\n \"entry_not_found\",\n `the compaction ${compaction.id} keeps from entry ${compaction.firstKeptEntryId}, which is not on this path`,\n );\n }\n // The messages that lose a block here are the only ones an empty result may drop.\n const stripped = new Set<string>();\n const entries = path.slice(kept).filter((entry, i) => {\n const drop = kept + i < at && isSignedReasoning(entry);\n if (drop && entry.type === \"message_block\") stripped.add(entry.messageId);\n return !drop;\n });\n return { entries: entries.filter((entry) => entry.type !== \"compaction\"), summary: compaction.summary, stripped };\n}\n\n/**\n * The context a path of entries stands for, with the id of the entry each message starts at (`null` for a summary).\n * `path` is a session's `path()`: the root to a HEAD, without `checkout` entries. The system prompt is the latest\n * `turn_start`'s, byte for byte, so a harness whose prompt changed later still rebuilds the conversation the model\n * saw. The latest compaction applies: its summary stands first, then the kept tail and what followed it.\n */\nexport function contextWithStarts(path: readonly SessionEntry[]): {\n readonly context: Context;\n readonly starts: readonly (string | null)[];\n} {\n const { entries, summary, stripped } = entriesAfterCompaction(path);\n const builder = new MessageBuilder(stripped);\n let system = \"\";\n for (const entry of path) if (entry.type === \"turn_start\") system = entry.system;\n // A code call's or a sandbox escalation's result answers no call the model made, so the model never reads it. Both\n // are known by their call ids, never by the result's tool name: the model can call a tool named `sandbox.escalation`,\n // and its error result must stay, or the rebuilt context would hold a tool call with no result.\n const hostCalls = new Set(\n path.flatMap((entry) => {\n if (entry.type === \"code_call\") return [entry.callId];\n if (entry.type === \"approval_requested\" && entry.request.tool === ESCALATION_TOOL) return [entry.request.callId];\n return [];\n }),\n );\n for (const entry of entries) {\n if (entry.type === \"tool_result\" && hostCalls.has(entry.callId)) continue;\n switch (entry.type) {\n case \"message_block\":\n builder.block(entry);\n break;\n case \"message_end\":\n builder.end(entry);\n break;\n case \"usage\":\n builder.usage(entry);\n break;\n case \"tool_result\":\n builder.toolResult(entry);\n break;\n default:\n }\n }\n const built = builder.finish();\n const messages = summary === undefined ? built : [summaryMessage(summary), ...built];\n const starts = summary === undefined ? builder.starts : [null, ...builder.starts];\n const waiting = pendingApprovals(path);\n if (waiting.length === 0) return { context: { system, messages }, starts };\n return {\n context: {\n system,\n messages,\n pending: waiting.map((entry) => entry.request),\n pendingInputs: Object.fromEntries(waiting.map((entry) => [entry.request.id, entry.input])),\n },\n starts,\n };\n}\n\n/** The context a path of entries stands for. See `contextWithStarts()`. */\nexport function contextOf(path: readonly SessionEntry[]): Context {\n return contextWithStarts(path).context;\n}\n"]}
@@ -137,11 +137,17 @@ async function recordLoadout(harness, writer, model, tools, started) {
137
137
  await writer.write("harness", { ...record, type: "extension_loaded" });
138
138
  }
139
139
  }
140
- async function writeInput(writer, options, newId) {
140
+ async function writeInput(writer, options, newId, notices = []) {
141
141
  const blocks = typeof options.input === "string" ? [{ type: "text", text: options.input }] : options.input;
142
142
  const messageId = newId();
143
- for (const [index, block] of blocks.entries()) {
144
- await writer.write(options.inputOrigin ?? "user", {
143
+ // A boundary's notice goes first, in the same user message, with the harness as its origin: the gateway's transcript
144
+ // has no system role, so this is how an append-only log tells the model that tools changed (HD3).
145
+ const all = [
146
+ ...notices.map((text) => ({ origin: "harness", block: { type: "text", text } })),
147
+ ...blocks.map((block) => ({ origin: options.inputOrigin ?? "user", block })),
148
+ ];
149
+ for (const [index, { origin, block }] of all.entries()) {
150
+ await writer.write(origin, {
145
151
  type: "message_block",
146
152
  messageId,
147
153
  role: "user",
@@ -151,6 +157,24 @@ async function writeInput(writer, options, newId) {
151
157
  });
152
158
  }
153
159
  }
160
+ /** The turn's input with the boundaries' notices in front, as the log holds it. */
161
+ function withNotices(input, notices) {
162
+ if (notices.length === 0)
163
+ return input;
164
+ const blocks = typeof input === "string" ? [{ type: "text", text: input }] : input;
165
+ return [...notices.map((text) => ({ type: "text", text })), ...blocks];
166
+ }
167
+ /** Runs every turn boundary in order and gathers their notices, before the turn builds its tools. */
168
+ async function crossBoundaries(harness, signal) {
169
+ const notices = [];
170
+ for (const boundary of harness.turnBoundaries ?? []) {
171
+ for (const notice of await boundary.beginTurn(signal)) {
172
+ if (typeof notice === "string" && notice !== "")
173
+ notices.push(notice);
174
+ }
175
+ }
176
+ return notices;
177
+ }
154
178
  /** Turns the run's events into entries. It keeps the last model message back until the next event shows it was kept. */
155
179
  class EventRecorder {
156
180
  #writer;
@@ -467,8 +491,11 @@ async function recordCompletion(session, settings, start, options, result) {
467
491
  async function runTurnOnce(session, harness, options) {
468
492
  const model = options.model ?? harness.model;
469
493
  const system = options.system ?? harness.system;
470
- const tools = toolsOf(harness, options);
471
494
  const { signal, newId, writer } = turnPlumbing(session, options);
495
+ // Tools change only here, between turns: a boundary registers what arrived since the last turn before the tools
496
+ // are built, so nothing it does lands inside the run.
497
+ const notices = await crossBoundaries(harness, signal);
498
+ const tools = toolsOf(harness, options);
472
499
  // What a crash left open is settled first, so the log reads as a whole and the context has no call without a result.
473
500
  let path = await session.path();
474
501
  const wrote = await settleOpenCalls(path, harness, (origin, body) => writer.write(origin, body), !session.headMoved());
@@ -487,14 +514,20 @@ async function runTurnOnce(session, harness, options) {
487
514
  path = await session.path();
488
515
  }
489
516
  const history = options.history ?? contextOf(path).messages;
490
- await writeInput(writer, options, newId);
517
+ await writeInput(writer, options, newId, notices);
518
+ // A notice counts as told only once it is in the log; a turn that failed before here tells it again next time.
519
+ await writer.settled();
520
+ if (writer.failure() === undefined)
521
+ for (const boundary of harness.turnBoundaries ?? [])
522
+ boundary.commitNotices?.();
523
+ const input = withNotices(options.input, notices);
491
524
  const recorder = new EventRecorder(writer, harness, system, newId, "run", turnContext?.spillOf);
492
525
  turnContext?.attach(attachment(writer, recorder));
493
526
  const observer = (event) => recorder.handle(event);
494
527
  const handle = run({
495
528
  model,
496
529
  system,
497
- input: options.input,
530
+ input,
498
531
  tools,
499
532
  signal,
500
533
  interceptors: interceptorsOf(harness, session, writer, recorder, options.hostContext, model, turnContext),