@buildanagent/harness 0.1.0-alpha.30 → 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 (58) hide show
  1. package/README.md +69 -3
  2. package/dist/credentials/addresses.d.ts +9 -0
  3. package/dist/credentials/addresses.js +52 -0
  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/extensions/load.js +5 -2
  8. package/dist/extensions/load.js.map +1 -1
  9. package/dist/extensions/lock.d.ts +16 -2
  10. package/dist/extensions/lock.js +155 -21
  11. package/dist/extensions/lock.js.map +1 -1
  12. package/dist/extensions/mcp-pins-node.d.ts +16 -0
  13. package/dist/extensions/mcp-pins-node.js +18 -0
  14. package/dist/extensions/mcp-pins-node.js.map +1 -0
  15. package/dist/extensions/node.d.ts +4 -2
  16. package/dist/extensions/node.js +4 -2
  17. package/dist/extensions/node.js.map +1 -1
  18. package/dist/harness.d.ts +7 -1
  19. package/dist/harness.js.map +1 -1
  20. package/dist/mcp/connection.d.ts +9 -3
  21. package/dist/mcp/connection.js +192 -25
  22. package/dist/mcp/connection.js.map +1 -1
  23. package/dist/mcp/errors.d.ts +5 -2
  24. package/dist/mcp/errors.js.map +1 -1
  25. package/dist/mcp/guarded-fetch.d.ts +33 -0
  26. package/dist/mcp/guarded-fetch.js +391 -0
  27. package/dist/mcp/guarded-fetch.js.map +1 -0
  28. package/dist/mcp/http-node.d.ts +15 -0
  29. package/dist/mcp/http-node.js +179 -0
  30. package/dist/mcp/http-node.js.map +1 -0
  31. package/dist/mcp/index.d.ts +6 -3
  32. package/dist/mcp/index.js +5 -2
  33. package/dist/mcp/index.js.map +1 -1
  34. package/dist/mcp/manager.d.ts +4 -3
  35. package/dist/mcp/manager.js +432 -47
  36. package/dist/mcp/manager.js.map +1 -1
  37. package/dist/mcp/pins.d.ts +9 -0
  38. package/dist/mcp/pins.js +54 -0
  39. package/dist/mcp/pins.js.map +1 -0
  40. package/dist/mcp/record.js +6 -0
  41. package/dist/mcp/record.js.map +1 -1
  42. package/dist/mcp/remote-config.d.ts +20 -0
  43. package/dist/mcp/remote-config.js +208 -0
  44. package/dist/mcp/remote-config.js.map +1 -0
  45. package/dist/mcp/remote.d.ts +20 -0
  46. package/dist/mcp/remote.js +146 -0
  47. package/dist/mcp/remote.js.map +1 -0
  48. package/dist/mcp/types.d.ts +198 -8
  49. package/dist/mcp/types.js.map +1 -1
  50. package/dist/server/protocol.schema.json +6 -3
  51. package/dist/session/runner.js +39 -6
  52. package/dist/session/runner.js.map +1 -1
  53. package/dist/tools/index.d.ts +1 -1
  54. package/dist/tools/index.js.map +1 -1
  55. package/dist/tools/types.d.ts +16 -0
  56. package/dist/tools/types.js.map +1 -1
  57. package/llms.txt +18 -2
  58. package/package.json +7 -6
@@ -1 +1 @@
1
- {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../src/session/runner.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAA8D,MAAM,uBAAuB,CAAC;AACtH,OAAO,EAAE,cAAc,EAAkC,MAAM,wBAAwB,CAAC;AACxF,OAAO,EAEL,YAAY,EAEZ,mBAAmB,EACnB,WAAW,EACX,aAAa,EAOb,GAAG,EACH,WAAW,GAGZ,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAIL,iBAAiB,EACjB,kBAAkB,EAClB,aAAa,GACd,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAItD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE/D,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC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AAU,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IAC1D,0FAA0F;IAC1F,OAAO;QACL,GAAG,OAAO;QACV,KAAK,EAAE,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK;QAClC,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC;QAC3C,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC;KACxC,CAAC;AACJ,CAAC;AAED,6FAA6F;AAC7F,SAAS,YAAY,CAAC,MAAkB;IACtC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,MAA0C,CAAC;IAC9E,OAAO,IAAkB,CAAC;AAC5B,CAAC","sourcesContent":["/**\n * `runTurn()`: one SDK run, written into a session's log. The user entries are durable before the run starts, so a turn\n * that dies before its first model call leaves the question in the file. The run's own events then become entries\n * through one observer: a message's blocks and end when its call ends, a tool's result when the call ends, usage, and the\n * turn's end. Every write goes through one queue, so the permission pipeline's entries and the observer's never race for\n * the same parent.\n */\nimport { addCost, addUsage, type ContentBlock, type Message, type Model, type ModelRef } from \"@buildanagent/gateway\";\nimport { FORMAT_VERSION, type Origin, type SessionEntry } from \"@buildanagent/protocol\";\nimport {\n type AgentEvent,\n CAPABILITIES,\n type CallOptions,\n composeInterceptors,\n continueRun,\n DEFAULTS_HASH,\n type Interceptors,\n type Observer,\n type Recheck,\n type Resolution,\n type Run,\n type RunResult,\n run,\n SDK_VERSION,\n type ToolDefinition,\n type ToolResult,\n} from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport {\n type CompletionOutcome,\n type CompletionSettings,\n type CompletionStart,\n completionFailure,\n runCompletionCheck,\n snapshotStart,\n} from \"../completion/check.js\";\nimport type { ContextFill, TurnContext } from \"../context/types.js\";\nimport { HarnessError } from \"../errors.js\";\nimport { skillOfRead } from \"../extensions/skills.js\";\nimport type { Harness } from \"../harness.js\";\nimport type { PolicySession } from \"../permissions/types.js\";\nimport type { ToolWrapper } from \"../tools/types.js\";\nimport { contextOf } from \"./rebuild.js\";\nimport { settleOpenCalls, unansweredCalls } from \"./resume.js\";\nimport type { Session } from \"./session.js\";\nimport { findSticky, stickyDecision } from \"./sticky.js\";\nimport type { EntryInput } from \"./store.js\";\n\n/** One call to a `client_request` tool, as `TurnOptions.clientTool` receives it. */\nexport interface ClientToolCall {\n readonly callId: string;\n /** The tool's canonical name. */\n readonly tool: string;\n /** The input after the SDK validated it. */\n readonly input: unknown;\n /** Fires when the run is aborted, so the caller can withdraw the request it sent. */\n readonly signal: AbortSignal;\n}\n\n/** Runs a `client_request` tool's call by asking the client that holds the tool, and resolves with its result. */\nexport type ClientToolRunner = (call: ClientToolCall) => Promise<ToolResult>;\n\n/** The options of one turn. Anything left out takes the harness's setting. */\nexport interface TurnOptions<H = unknown> {\n readonly input: string | ContentBlock[];\n /** The `origin` of the input blocks: `operator` for text the host wrote, such as a scheduled prompt. Default `user`. */\n readonly inputOrigin?: \"user\" | \"operator\";\n readonly budgetUsd?: number;\n readonly signal?: AbortSignal;\n /** This turn's host context. A tool reads it as `ctx.app`; it reaches no schema, event or entry. */\n readonly hostContext?: H;\n readonly system?: string;\n /** The registered tools this turn may use, by name or alias. A name the registry lacks throws. Default every tool. */\n readonly tools?: readonly string[];\n readonly output?: ToolDefinition<unknown, unknown, unknown>;\n /** The model for this turn. A change from the session's last model is recorded as a `loadout` entry. */\n readonly model?: Model;\n readonly maxSteps?: number;\n /** How many times the loop re-issues a call that ended with a retryable error. Default none. */\n readonly turnRetries?: number;\n readonly modelOptions?: CallOptions;\n /** Called with the run as soon as it starts, so a caller can `steer()`, `followUp()` or abort it. */\n readonly onRun?: (run: Run<unknown>) => void;\n /** Called with how full the request view is after each model call's view is built, when the harness has a context policy. */\n readonly onContextFill?: (fill: ContextFill) => void;\n /** Called when the first run has ended because the request was too large and a retry may follow. */\n readonly onOverflowRetry?: () => void;\n /**\n * Checks the turn's completion. Before the model runs, the turn resolves the project's checks in this sandbox and\n * snapshots the workspace and the check config. A turn that ends `done` then runs those checks, diffs the workspace\n * and the config against the start, and writes a `completion_check` entry. The stop reason is unchanged: a failed\n * check, a flag or a check that could not run is recorded, never fatal. The result's `lastEntryId` is that entry.\n */\n readonly completion?: CompletionSettings;\n /** Called with the `completion_check` entry once it is written. */\n readonly onCompletionCheck?: (entry: SessionEntry) => void;\n /** Observers for this turn alone. Unlike `Run.on()`, they also see `run_start`. They run after the harness's own. */\n readonly observers?: readonly Observer[];\n /**\n * Runs the calls of every tool registered with the `client_request` pattern, in place of the tool's own `execute`.\n * The dispatcher sets it to send a `tool/call` request. Left out, the tool's own `execute` runs.\n */\n readonly clientTool?: ClientToolRunner;\n /**\n * The conversation so far. Left out, it is rebuilt from the session's log, so a turn in any process goes on from\n * what the log holds. Pass it only to run on a conversation the log doesn't hold.\n */\n readonly history?: readonly Message[];\n /** The clock of the entries and the run, for a test that needs the same bytes twice. Default the system clock. */\n readonly clock?: Clock;\n /** Makes the ids of the entries and of the run, for a test that needs the same bytes twice. Default `crypto.randomUUID()`. */\n readonly newId?: () => string;\n}\n\n/** What a turn returns: the SDK's result, and where the turn left the log. */\nexport type TurnResult = RunResult<unknown> & { sessionKey: string; lastEntryId: string };\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\ntype Body = DistributiveOmit<EntryInput, \"id\" | \"parentId\" | \"timestamp\" | \"origin\">;\n\n/** Writes entries one at a time, each after the one before, so every entry's parent is the entry before it. */\nclass EntryWriter {\n readonly #session: Session;\n readonly #newId: () => string;\n readonly #now: () => Date;\n readonly #onFailure: () => void;\n #chain: Promise<unknown> = Promise.resolve();\n #failure: unknown;\n #failed = false;\n\n constructor(session: Session, newId: () => string, now: () => Date, onFailure: () => void) {\n this.#session = session;\n this.#newId = newId;\n this.#now = now;\n this.#onFailure = onFailure;\n }\n\n /** The first write that failed, once one has. */\n failure(): { readonly error: unknown } | undefined {\n return this.#failed ? { error: this.#failure } : undefined;\n }\n\n write(origin: Origin, body: Body): Promise<SessionEntry> {\n const next = this.#chain.then(async () => {\n if (this.#failed) throw this.#failure;\n const entry = {\n ...body,\n id: this.#newId(),\n parentId: this.#session.head(),\n timestamp: this.#now().toISOString(),\n origin,\n };\n const [stored] = await this.#session.append([entry as EntryInput]);\n return stored as SessionEntry;\n });\n this.#chain = next.catch((error) => {\n if (!this.#failed) {\n this.#failed = true;\n this.#failure = error;\n // A log that can't be written can't be trusted to hold the turn, so the run stops.\n this.#onFailure();\n }\n });\n return next;\n }\n\n /** Waits for every write queued so far. */\n settled(): Promise<unknown> {\n return this.#chain;\n }\n}\n\nconst refKey = (ref: ModelRef): string => `${ref.api}\\u0000${ref.provider}\\u0000${ref.id}`;\n\n/**\n * The harness's wrapper, with a `client_request` tool's `execute` sent to `clientTool` first, so a write cap or shadow\n * mode still wraps the call the client runs.\n */\nfunction wrapperOf<H>(harness: Harness<H>, clientTool: ClientToolRunner | undefined): ToolWrapper<H> | undefined {\n if (clientTool === undefined) return harness.wrap;\n const inner: ToolWrapper<H> = harness.wrap ?? ((tool) => tool.definition);\n return (tool, hostContext) => {\n if (tool.pattern !== \"client_request\") return inner(tool, hostContext);\n const definition: ToolDefinition<unknown, unknown, unknown> = {\n ...tool.definition,\n execute: (input, ctx) => clientTool({ callId: ctx.callId, tool: tool.canonicalName, input, signal: ctx.signal }),\n };\n return inner({ ...tool, definition }, hostContext);\n };\n}\n\n/** The turn's tools: the registry's definitions for this host context, cut to the allowlist. */\nfunction toolsOf<H>(\n harness: Harness<H>,\n options: Pick<TurnOptions<H>, \"tools\" | \"hostContext\" | \"clientTool\">,\n): ToolDefinition<unknown, unknown, unknown>[] {\n const all = harness.registry.definitions(wrapperOf(harness, options.clientTool), options.hostContext as H);\n if (options.tools === undefined) return all;\n const allowed = new Set<string>();\n for (const name of options.tools) {\n const tool = harness.registry.get(name);\n if (tool === undefined)\n throw new HarnessError(\n \"invalid_turn_options\",\n `the tool allowlist names \"${name}\", which no tool is registered under`,\n );\n allowed.add(tool.canonicalName);\n }\n return all.filter((definition) => allowed.has(definition.name));\n}\n\n/**\n * Writes what a new session starts with: its header when the path is empty, and its `env_stamp` when the path has\n * none. `write` appends one entry after the ones before it.\n */\nexport async function recordSessionStart<H>(\n harness: Harness<H>,\n write: (origin: \"harness\", body: Body) => Promise<unknown>,\n model: Model,\n started: readonly SessionEntry[],\n): Promise<void> {\n if (started.length === 0) {\n await write(\"harness\", {\n type: \"session_header\",\n formatVersion: FORMAT_VERSION,\n harnessVersion: harness.harnessVersion,\n sdkVersion: SDK_VERSION,\n defaultsHash: DEFAULTS_HASH,\n capabilities: [...CAPABILITIES],\n ablationHash: harness.ablationHash,\n });\n }\n if (!started.some((entry) => entry.type === \"env_stamp\")) {\n await write(\"harness\", { type: \"env_stamp\", ...harness.env, model: model.ref });\n }\n}\n\n/** Writes what a new session starts with, and a `loadout` when the tools or the model differ from the last one recorded. */\nasync function recordLoadout<H>(\n harness: Harness<H>,\n writer: EntryWriter,\n model: Model,\n tools: readonly ToolDefinition<unknown, unknown, unknown>[],\n started: readonly SessionEntry[],\n): Promise<void> {\n await recordSessionStart(harness, (origin, body) => writer.write(origin, body), model, started);\n const names = tools.map((tool) => tool.name);\n const last = started.findLast((entry) => entry.type === \"loadout\");\n const same =\n last?.type === \"loadout\" &&\n last.model !== undefined &&\n refKey(last.model) === refKey(model.ref) &&\n [...last.tools].sort().join() === [...names].sort().join();\n if (!same) await writer.write(\"harness\", { type: \"loadout\", tools: names, model: model.ref });\n const written = new Set<string>();\n for (const record of harness.extensionRecords ?? []) {\n const key = `${record.name}\\0${record.contentHash}`;\n const known =\n written.has(key) ||\n started.some(\n (entry) =>\n entry.type === \"extension_loaded\" && entry.name === record.name && entry.contentHash === record.contentHash,\n );\n if (known) continue;\n written.add(key);\n await writer.write(\"harness\", { ...record, type: \"extension_loaded\" });\n }\n}\n\nasync function writeInput(\n writer: EntryWriter,\n options: { input: string | ContentBlock[]; inputOrigin?: \"user\" | \"operator\" },\n newId: () => string,\n) {\n const blocks: ContentBlock[] =\n typeof options.input === \"string\" ? [{ type: \"text\", text: options.input }] : options.input;\n const messageId = newId();\n for (const [index, block] of blocks.entries()) {\n await writer.write(options.inputOrigin ?? \"user\", {\n type: \"message_block\",\n messageId,\n role: \"user\",\n index,\n block,\n delivery: \"input\",\n });\n }\n}\n\ntype ModelMessage = Extract<AgentEvent, { type: \"model_call_end\" }>[\"message\"];\n\n/** Turns the run's events into entries. It keeps the last model message back until the next event shows it was kept. */\nclass EventRecorder {\n readonly #writer: EntryWriter;\n readonly #harness: Harness<unknown>;\n readonly #system: string;\n readonly #newId: () => string;\n readonly #tools = new Map<string, string>();\n readonly #inputs = new Map<string, unknown>();\n #pending: ModelMessage | undefined;\n\n readonly #mode: \"run\" | \"continue\";\n readonly #spillOf: TurnContext[\"spillOf\"] | undefined;\n\n constructor(\n writer: EntryWriter,\n harness: Harness<unknown>,\n system: string,\n newId: () => string,\n mode: \"run\" | \"continue\" = \"run\",\n spillOf?: TurnContext[\"spillOf\"],\n ) {\n this.#spillOf = spillOf;\n this.#mode = mode;\n this.#writer = writer;\n this.#harness = harness;\n this.#system = system;\n this.#newId = newId;\n }\n\n /** Queues a write and returns at once. A failure is recorded by the writer and rethrown by `runTurn()`. */\n #queue(origin: Origin, body: Body): void {\n this.#writer.write(origin, body).catch(() => undefined);\n }\n\n #usage(message: ModelMessage): void {\n this.#queue(\"harness\", {\n type: \"usage\",\n source: \"model_call\",\n usage: message.usage,\n ...(message.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: message.lastAttemptUsage }),\n cost: message.cost,\n });\n }\n\n /**\n * Queues the held-back message: its blocks, its end and its usage. The gate calls it before it writes, so a call's\n * decision never lands ahead of the message that made the call.\n */\n flush(): void {\n const message = this.#pending;\n if (message === undefined) return;\n this.#pending = undefined;\n const messageId = this.#newId();\n for (const [index, block] of message.content.entries()) {\n this.#queue(\"model\", { type: \"message_block\", messageId, role: \"assistant\", index, block });\n }\n this.#queue(\"model\", {\n type: \"message_end\",\n messageId,\n model: message.model,\n stopReason: message.stopReason,\n ...(message.error === undefined ? {} : { error: message.error }),\n });\n this.#usage(message);\n }\n\n /** Handles an event without waiting for the store, so the observer is never behind and the SDK never drops it. */\n handle(event: AgentEvent): void {\n if (event.type === \"retry\" && event.layer === \"turn\" && this.#pending !== undefined) {\n // The call's message is superseded and not in the transcript, but the provider billed it.\n const superseded = this.#pending;\n this.#pending = undefined;\n this.#usage(superseded);\n return;\n }\n this.flush();\n this.#record(event);\n }\n\n #record(event: AgentEvent): void {\n switch (event.type) {\n case \"run_start\":\n this.#queue(\"harness\", {\n type: \"turn_start\",\n runId: event.runId,\n mode: this.#mode,\n system: this.#system,\n });\n return;\n case \"approval_request\":\n // The request is in the log before any client hears of it: the harness's own observers wait for the writes.\n this.#queue(\"harness\", { type: \"approval_requested\", request: event.request, input: event.input });\n return;\n case \"model_call_end\":\n this.#pending = event.message;\n // A call the SDK refuses to start (unknown tool, bad input) gets no tool_call_start, so its name comes from here.\n for (const block of event.message.content) {\n if (block.type === \"tool_call\") this.#tools.set(block.callId, block.name);\n }\n return;\n case \"tool_call_start\":\n this.#tools.set(event.callId, event.tool);\n this.#inputs.set(event.callId, event.input);\n return;\n case \"tool_call_end\":\n this.#toolResult(event);\n return;\n case \"steer_applied\":\n for (const [index, block] of event.receipt.message.entries()) {\n this.#queue(\"user\", {\n type: \"message_block\",\n messageId: event.receipt.id,\n role: \"user\",\n index,\n block,\n delivery: event.receipt.kind,\n });\n }\n return;\n case \"run_end\":\n this.#queue(\"harness\", {\n type: \"turn_end\",\n runId: event.runId,\n stopReason: event.result.stopReason,\n steps: event.result.steps,\n });\n return;\n default:\n }\n }\n\n #toolResult(event: Extract<AgentEvent, { type: \"tool_call_end\" }>): void {\n const tool = this.#tools.get(event.callId) ?? \"\";\n const trust = this.#harness.registry.get(tool)?.outputTrust ?? \"untrusted\";\n const { result } = event;\n const spill = this.#spillOf?.(event.callId);\n this.#queue(\"tool\", {\n type: \"tool_result\",\n callId: event.callId,\n tool,\n content: [...result.content],\n isError: result.isError === true,\n ...(result.details === undefined ? {} : { details: result.details }),\n ...(spill === undefined ? {} : { spill }),\n trust,\n });\n this.#skillLoaded(tool, event);\n }\n\n /** A `read` that opened a listed skill's `SKILL.md` and succeeded put the skill's instructions in the context. */\n #skillLoaded(tool: string, event: Extract<AgentEvent, { type: \"tool_call_end\" }>): void {\n const skills = this.#harness.skills;\n if (skills === undefined || tool !== \"read\" || event.result.isError === true) return;\n const input = event.input ?? this.#inputs.get(event.callId);\n const skill = skillOfRead(skills, this.#harness.env.cwd, input);\n if (skill !== undefined) this.#queue(\"harness\", { type: \"skill_loaded\", name: skill.name, path: skill.path });\n }\n}\n\n/** What the layers that write inside a run are given: the turn's writer, and a way to wait for the run's entries. */\nfunction attachment(writer: EntryWriter, recorder: EventRecorder) {\n return {\n append: (origin: Origin, body: Body) => writer.write(origin, body),\n settle: async () => {\n recorder.flush();\n await writer.settled();\n },\n };\n}\n\n/** The turn's context layers, when the harness has a policy. */\nfunction contextFor<H>(\n harness: Harness<H>,\n session: Session,\n model: Model,\n options: { readonly onContextFill?: (fill: ContextFill) => void; readonly history?: readonly Message[] },\n retry = false,\n): TurnContext | undefined {\n return harness.context?.forTurn({\n session,\n model,\n ownHistory: options.history !== undefined,\n ...(retry ? { midTurn: false } : {}),\n ...(options.onContextFill === undefined ? {} : { onFill: options.onContextFill }),\n });\n}\n\n/** The interceptors of a turn: the harness's, the pipeline's gate, and a guard that refuses a model change inside a turn. */\nfunction interceptorsOf<H>(\n harness: Harness<H>,\n session: Session,\n writer: EntryWriter,\n recorder: EventRecorder,\n hostContext: H | undefined,\n turnModel: Model,\n turnContext: TurnContext | undefined,\n): Interceptors {\n const policySession: PolicySession = { append: (entry) => writer.write(\"harness\", entry) };\n const pipelineGate = harness.pipeline?.gate(async () => {\n // The model's message and the earlier results are queued first, so the gate's entries follow them in the log.\n recorder.flush();\n await writer.settled();\n return { session: policySession, hostContext, entries: await session.path() };\n });\n const gate =\n pipelineGate === undefined ? undefined : withStickyAllowances(pipelineGate, harness, session, writer, recorder);\n // The context policy runs first, so it reads and indexes the run's own transcript, and the harness's hooks see its view.\n const composed = composeInterceptors(turnContext?.interceptors ?? {}, harness.interceptors ?? {}, gate ?? {});\n const inner = composed.beforeModelCall;\n return {\n ...composed,\n async beforeModelCall(event) {\n const patch = await inner?.(event);\n if (\n patch !== undefined &&\n \"model\" in patch &&\n patch.model !== undefined &&\n refKey(patch.model.ref) !== refKey(turnModel.ref)\n ) {\n throw new HarnessError(\n \"invalid_turn_options\",\n \"a hook changed the model inside a turn; set TurnOptions.model for the next turn so it is recorded\",\n );\n }\n return patch;\n },\n };\n}\n\n/**\n * The pipeline's gate with the sticky allowances applied: a call the pipeline would ask about, and that a person's\n * earlier sticky `allow` covers, runs. A deny stays a deny, and the pipeline's own entry for the ask stays in the log\n * beside the entry that records the allowance.\n */\nfunction withStickyAllowances<H>(\n gate: NonNullable<ReturnType<NonNullable<Harness<H>[\"pipeline\"]>[\"gate\"]>>,\n harness: Harness<H>,\n session: Session,\n writer: EntryWriter,\n recorder: EventRecorder,\n): Pick<Interceptors, \"beforeToolCall\"> {\n return {\n async beforeToolCall(event) {\n // The pipeline's gate always has a `beforeToolCall`; a gate without one has nothing to ask.\n const decision = (await gate.beforeToolCall?.(event)) ?? { decision: \"allow\" as const };\n if (decision.decision !== \"ask\") return decision;\n recorder.flush();\n await writer.settled();\n const covered = await findSticky(\n await session.path(),\n { tool: event.tool, input: event.input, policyVersion: decision.policyVersion },\n harness.registry,\n );\n if (covered === undefined) return decision;\n const tool = harness.registry.get(event.tool)?.canonicalName ?? event.tool;\n await writer.write(\n \"harness\",\n await stickyDecision({ callId: event.callId, tool, input: event.input }, covered, decision.policyVersion),\n );\n return { decision: \"allow\", reason: \"a sticky allowance a person gave earlier covers this call\" };\n },\n };\n}\n\n/**\n * The harness's own observers, each held back on an approval request until the entries written so far are durable. An\n * observer that hears of a request can therefore always find its `approval_requested` entry in the log.\n */\nfunction afterWrites(observers: readonly Observer[] | undefined, writer: EntryWriter): Observer[] {\n return (observers ?? []).map(\n (observer): Observer =>\n async (event) => {\n // Only a request needs its entry first, and `settled()` never rejects: a failed write is the writer's to report.\n if (event.type === \"approval_request\") await writer.settled();\n await observer(event);\n },\n );\n}\n\n/** The run options a turn sets only when it has a value, so a missing one leaves the SDK's default. */\ntype RunSettings<H> = Pick<\n TurnOptions<H>,\n | \"clock\"\n | \"newId\"\n | \"hostContext\"\n | \"output\"\n | \"maxSteps\"\n | \"turnRetries\"\n | \"modelOptions\"\n | \"budgetUsd\"\n | \"onContextFill\"\n>;\n\nfunction optionalRunOptions<H>(options: RunSettings<H>, harness: Harness<H>, history: readonly Message[]) {\n return {\n ...(history.length === 0 ? {} : { history }),\n ...(options.clock === undefined ? {} : { clock: options.clock }),\n ...(options.newId === undefined ? {} : { idGenerator: options.newId }),\n ...(options.hostContext === undefined ? {} : { app: options.hostContext }),\n ...(options.output === undefined ? {} : { output: options.output }),\n ...(options.maxSteps === undefined ? {} : { maxSteps: options.maxSteps }),\n ...(options.turnRetries === undefined ? {} : { turnRetries: options.turnRetries }),\n ...(options.modelOptions === undefined ? {} : { modelOptions: options.modelOptions }),\n ...(options.budgetUsd === undefined ? {} : { budgetUsd: options.budgetUsd }),\n ...(harness.signer === undefined ? {} : { signer: harness.signer }),\n };\n}\n\n/** Waits for the run and for every queued write, and returns the result with where the log ends. */\nasync function settleTurn(handle: Run<unknown>, writer: EntryWriter, session: Session): Promise<TurnResult> {\n let result: RunResult<unknown> | undefined;\n let runError: unknown;\n try {\n result = (await handle.result) as RunResult<unknown>;\n } catch (error) {\n runError = error;\n }\n await writer.settled();\n // A store failure is the cause of an aborted run, so it comes before the run's own error.\n const failed = writer.failure();\n if (failed !== undefined) throw failed.error;\n if (result === undefined) throw runError;\n return { ...result, sessionKey: session.key.sessionId, lastEntryId: session.head() as string };\n}\n\n/** What every turn and every resume needs: a writer whose failure aborts the run, the run's signal and its id source. */\nfunction turnPlumbing(session: Session, options: { signal?: AbortSignal; clock?: Clock; newId?: () => string }) {\n const stop = new AbortController();\n const signal = options.signal === undefined ? stop.signal : AbortSignal.any([options.signal, stop.signal]);\n const newId = options.newId ?? (() => globalThis.crypto.randomUUID());\n const writer = new EntryWriter(\n session,\n newId,\n options.clock === undefined ? () => new Date() : () => new Date((options.clock as Clock).now()),\n () => stop.abort(),\n );\n return { signal, newId, writer };\n}\n\n/**\n * Runs one turn on a session and writes it to the log. The session must be open with a lock. The first turn of a new\n * session writes its header and `env_stamp`; a turn whose model or tools differ from the last recorded ones writes a\n * `loadout` first; the input blocks follow, and the run's events after them. The returned result is the SDK's, with the\n * session id and the id of the last entry the turn wrote. When the harness has a context policy and the run ends because\n * the provider said the request was too large, the policy compacts once and the turn goes on from the rebuilt context;\n * a second overflow ends the turn with that error.\n */\nexport async function runTurn<H = unknown>(\n session: Session,\n harness: Harness<H>,\n options: TurnOptions<H>,\n): Promise<TurnResult> {\n const settings = options.completion;\n // The start state is taken before the turn writes anything, and with the turn's own signal, so an abort stops it.\n // It is taken for every turn, because whether the turn ends `done` is known only after the model has run.\n const start =\n settings === undefined ? undefined : await snapshotStart(settings, options.signal ?? new AbortController().signal);\n const result = await retryAfterOverflow(session, harness, options, await runTurnOnce(session, harness, options));\n if (settings === undefined || result.stopReason !== \"done\") return result;\n return recordCompletion(session, settings, start, options, result);\n}\n\n/**\n * Runs the completion check after a `done` turn and writes its entry. The result's stop reason is left as it is, and a\n * check that throws (a sandbox error, a disposed sandbox) is recorded as a failed entry instead of losing the result.\n */\nasync function recordCompletion<H>(\n session: Session,\n settings: CompletionSettings,\n start: CompletionStart | undefined,\n options: TurnOptions<H>,\n result: TurnResult,\n): Promise<TurnResult> {\n const signal = options.signal ?? new AbortController().signal;\n let outcome: CompletionOutcome;\n try {\n outcome = await runCompletionCheck(settings, start, signal);\n } catch (error) {\n outcome = { checks: [], passed: false, flagged: [...(start?.failures ?? []), completionFailure(error)] };\n }\n const { writer } = turnPlumbing(session, options);\n let entry: SessionEntry;\n try {\n entry = await writer.write(\"harness\", { type: \"completion_check\", ...outcome });\n } catch {\n // A failed append (a lost lock, a store conflict) must not turn a `done` turn into a rejection: the turn's own\n // entries are written, and the result stands without the check's entry.\n return result;\n }\n options.onCompletionCheck?.(entry);\n return { ...result, lastEntryId: entry.id };\n}\n\nasync function runTurnOnce<H = unknown>(\n session: Session,\n harness: Harness<H>,\n options: TurnOptions<H>,\n): Promise<TurnResult> {\n const model = options.model ?? harness.model;\n const system = options.system ?? harness.system;\n const tools = toolsOf(harness, options);\n const { signal, newId, writer } = turnPlumbing(session, options);\n // What a crash left open is settled first, so the log reads as a whole and the context has no call without a result.\n let path = await session.path();\n const wrote = await settleOpenCalls(\n path,\n harness,\n (origin, body) => writer.write(origin, body as Body),\n !session.headMoved(),\n );\n if (wrote) path = await session.path();\n await recordLoadout(harness, writer, model, tools, path);\n const turnContext = contextFor(harness, session, model, options);\n const waiting = options.history === undefined ? unansweredCalls(path, true) : [];\n if (waiting.length > 0) {\n throw new HarnessError(\n \"invalid_turn_options\",\n `the session waits on tool calls with no result (${waiting.map((call) => call.callId).join(\", \")}); resolve them before another turn, or pass history`,\n );\n }\n // Between turns, before the input is written, the summary layer may replace an outgrown span with a summary. It\n // runs only once no call waits for a result, so a paused turn's own message is never in the span.\n if (\n options.history === undefined &&\n (await turnContext?.compact({ path, signal, append: (origin, body) => writer.write(origin, body) }))\n ) {\n path = await session.path();\n }\n const history = options.history ?? contextOf(path).messages;\n await writeInput(writer, options, newId);\n const recorder = new EventRecorder(writer, harness as Harness<unknown>, system, newId, \"run\", turnContext?.spillOf);\n turnContext?.attach(attachment(writer, recorder));\n const observer: Observer = (event) => recorder.handle(event);\n const handle = run({\n model,\n system,\n input: options.input,\n tools,\n signal,\n interceptors: interceptorsOf(harness, session, writer, recorder, options.hostContext, model, turnContext),\n observers: [observer, ...afterWrites(harness.observers, writer), ...afterWrites(options.observers, writer)],\n ...optionalRunOptions(options, harness, history),\n });\n options.onRun?.(handle);\n return settleTurn(handle, writer, session);\n}\n\n/**\n * Re-runs from an entry: HEAD moves to `entryId` with a `checkout` entry, and a new turn follows it as a new branch of\n * the same log. The entries of the branch it left stay as they were. The entry must not leave a tool call without its\n * result, because that call never ran on the new branch.\n */\nexport async function rerunFrom<H = unknown>(\n session: Session,\n harness: Harness<H>,\n entryId: string,\n options: TurnOptions<H>,\n): Promise<TurnResult> {\n const waiting = unansweredCalls(await session.path(entryId), true).map((call) => call.callId);\n if (waiting.length > 0) {\n throw new HarnessError(\n \"invalid_turn_options\",\n `entry ${entryId} follows tool calls with no result (${waiting.join(\", \")}), so a re-run from it would send calls that never ran`,\n );\n }\n await session.checkout(entryId);\n return runTurn(session, harness, options);\n}\n\n/** One `approval_resolved` entry as written: the answer, and what it covers beyond its own call. */\nexport interface ResolutionRecord {\n readonly resolution: Resolution;\n readonly sticky?: \"run\" | \"session\";\n readonly allowance?: { tool: string; inputHash?: string; commandPrefix?: string[]; policyVersion?: string };\n readonly groupId?: string;\n readonly quorum?: \"pending\";\n}\n\n/** What resuming a paused turn takes: the answers, and the same per-turn settings a turn has. */\nexport interface ResumeOptions<H = unknown> extends RunSettings<H> {\n /** The answers the SDK checks and applies: one per request whose answer is settled. */\n readonly resolutions: readonly Resolution[];\n /**\n * The `approval_resolved` entries to write before the run, with what each covers. Left out, each resolution is\n * written as it is. A request a quorum still waits on has a record here and no resolution.\n */\n readonly records?: readonly ResolutionRecord[];\n /**\n * The caller's app data. A request bound to app data when it paused runs only when the resume passes the same value,\n * so this is the caller's identity. The tools are the paused turn's, from the log. The model is the harness's, or\n * `model`, and one that differs from the paused turn's is recorded as a `loadout`. Pass the turn's `maxSteps`,\n * `output`, `turnRetries` and `modelOptions` again, because the log does not hold them.\n */\n readonly hostContext?: H;\n /** The model the resumed turn runs on, in place of the harness's. */\n readonly model?: Model;\n /** Aborts the resumed turn. */\n readonly signal?: AbortSignal;\n /** Called with the resumed run as soon as it starts, so a caller can `steer()`, `followUp()` or abort it. */\n readonly onRun?: (run: Run<unknown>) => void;\n /** Observers for this resume alone, as `TurnOptions.observers`. */\n readonly observers?: readonly Observer[];\n /** Runs the calls of `client_request` tools, as `TurnOptions.clientTool`. */\n readonly clientTool?: ClientToolRunner;\n}\n\n/** The resume's policy check: the pipeline decides the call again, so a deny written after the pause wins. */\nfunction recheckThrough<H>(\n session: Session,\n harness: Harness<H>,\n writer: EntryWriter,\n recorder: EventRecorder,\n hostContext: H | undefined,\n): Recheck {\n return async (pending, input) => {\n // The earlier results and decisions are queued first, so the pipeline reads a log that holds them.\n recorder.flush();\n await writer.settled();\n const decision = await harness.pipeline?.decide(\n { callId: pending.callId, tool: pending.tool, input, initiator: \"model\" },\n { session: { append: (entry) => writer.write(\"harness\", entry) }, hostContext, entries: await session.path() },\n );\n // A person approved the call, so a question the pipeline would ask again doesn't stop it; a deny does.\n return decision?.decision === \"deny\" ? { deny: decision.reason } : \"allow\";\n };\n}\n\n/**\n * Resumes a paused turn from the log alone. The context, with its waiting requests, is rebuilt before anything is\n * written; each resolution is then written as an `approval_resolved` entry, and `continueRun()` verifies the requests\n * against the harness's signer. Each approved call goes through the permission pipeline again first, and a deny now\n * turns the approval into a denial.\n */\nexport async function resumeTurn<H = unknown>(\n session: Session,\n harness: Harness<H>,\n options: ResumeOptions<H>,\n): Promise<TurnResult> {\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so no approval can be checked\");\n }\n const { signal, newId, writer } = turnPlumbing(session, options);\n const path = await session.path();\n const context = contextOf(path);\n const waiting = new Set((context.pending ?? []).map((request) => request.id));\n const answered = new Set<string>();\n for (const resolution of options.resolutions) {\n if (answered.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `request ${resolution.requestId} is answered twice in one resume`);\n }\n answered.add(resolution.requestId);\n if (!waiting.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `no request ${resolution.requestId} is waiting in this session`);\n }\n }\n // The paused turn's tools: the latest `loadout` names them, and one the registry has lost stops the resume.\n const names = path.findLast((entry) => entry.type === \"loadout\");\n const tools = toolsOf(harness, {\n ...(names?.type === \"loadout\" ? { tools: names.tools } : {}),\n ...(options.hostContext === undefined ? {} : { hostContext: options.hostContext }),\n ...(options.clientTool === undefined ? {} : { clientTool: options.clientTool }),\n });\n const records = options.records ?? options.resolutions.map((resolution) => ({ resolution }));\n for (const record of records) await writer.write(\"user\", { type: \"approval_resolved\", ...record });\n const model = options.model ?? harness.model;\n await recordLoadout(harness, writer, model, tools, path);\n const turnContext = contextFor(harness, session, model, options);\n const recorder = new EventRecorder(\n writer,\n harness as Harness<unknown>,\n context.system,\n newId,\n \"continue\",\n turnContext?.spillOf,\n );\n turnContext?.attach(attachment(writer, recorder));\n const handle = continueRun(context, {\n model,\n tools,\n resolutions: [...options.resolutions],\n recheck: recheckThrough(session, harness, writer, recorder, options.hostContext),\n signer: harness.signer,\n signal,\n interceptors: interceptorsOf(harness, session, writer, recorder, options.hostContext, model, turnContext),\n observers: [\n (event: AgentEvent) => recorder.handle(event),\n ...afterWrites(harness.observers, writer),\n ...afterWrites(options.observers, writer),\n ],\n ...optionalRunOptions(options, harness, []),\n });\n options.onRun?.(handle);\n return settleTurn(handle, writer, session);\n}\n\n/**\n * Layer 5: after a run that ended because the request was too large, asks the context policy to compact once and\n * goes on from the rebuilt context with `continueRun()`, which asks the model again because the gateway leaves the\n * failed response out of the request. Only one retry is made, so a second overflow is the turn's result.\n */\nasync function retryAfterOverflow<H>(\n session: Session,\n harness: Harness<H>,\n options: TurnOptions<H>,\n first: TurnResult,\n): Promise<TurnResult> {\n if (first.stopReason !== \"error\" || first.error.kind !== \"overflow\" || options.history !== undefined) return first;\n const model = options.model ?? harness.model;\n const turnContext = contextFor(harness, session, model, options, true);\n if (turnContext === undefined) return first;\n // The retry has what the first attempt left of `maxSteps`; with none left there is nothing to retry into.\n const stepsLeft = options.maxSteps === undefined ? undefined : options.maxSteps - first.steps;\n if (stepsLeft !== undefined && stepsLeft < 1) return first;\n const { signal, newId, writer } = turnPlumbing(session, options);\n // The first run has ended: a steer sent now waits for the retry's run.\n options.onOverflowRetry?.();\n let compacted: boolean;\n try {\n compacted = await turnContext.onOverflow({\n path: await session.path(),\n signal,\n append: (origin, body) => writer.write(origin, body),\n });\n } catch (error) {\n // An abort during the summary call ends the turn as aborted, not as the overflow it was trying to cure.\n if (signal.aborted) return { ...withoutError(first), stopReason: \"aborted\", lastEntryId: session.head() as string };\n throw error;\n }\n await writer.settled();\n // A summary call that was made and rejected wrote its usage entry, so the log ends later than the first result says.\n if (!compacted) return { ...first, lastEntryId: session.head() as string };\n const context = contextOf(await session.path());\n const recorder = new EventRecorder(\n writer,\n harness as Harness<unknown>,\n context.system,\n newId,\n \"continue\",\n turnContext.spillOf,\n );\n turnContext.attach(attachment(writer, recorder));\n const handle = continueRun(context, {\n model,\n tools: toolsOf(harness, options),\n resolutions: [],\n signal,\n interceptors: interceptorsOf(harness, session, writer, recorder, options.hostContext, model, turnContext),\n observers: [\n (event: AgentEvent) => recorder.handle(event),\n ...afterWrites(harness.observers, writer),\n ...afterWrites(options.observers, writer),\n ],\n ...optionalRunOptions(stepsLeft === undefined ? options : { ...options, maxSteps: stepsLeft }, harness, []),\n });\n options.onRun?.(handle);\n const retried = await settleTurn(handle, writer, session);\n // The turn's result counts both attempts: what the first one spent and the steps it took.\n return {\n ...retried,\n steps: first.steps + retried.steps,\n usage: addUsage(first.usage, retried.usage),\n cost: addCost(first.cost, retried.cost),\n };\n}\n\n/** A result without its `error`, for a turn that was cut short before the error mattered. */\nfunction withoutError(result: TurnResult): TurnResult {\n const { error: _error, ...rest } = result as TurnResult & { error?: unknown };\n return rest as TurnResult;\n}\n"]}
1
+ {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../src/session/runner.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,O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AAK,EAAE,OAAO,CAAC,KAAK,CAAC;QAC3C,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC;KACxC,CAAC;AACJ,CAAC;AAED,6FAA6F;AAC7F,SAAS,YAAY,CAAC,MAAkB;IACtC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,MAA0C,CAAC;IAC9E,OAAO,IAAkB,CAAC;AAC5B,CAAC","sourcesContent":["/**\n * `runTurn()`: one SDK run, written into a session's log. The user entries are durable before the run starts, so a turn\n * that dies before its first model call leaves the question in the file. The run's own events then become entries\n * through one observer: a message's blocks and end when its call ends, a tool's result when the call ends, usage, and the\n * turn's end. Every write goes through one queue, so the permission pipeline's entries and the observer's never race for\n * the same parent.\n */\nimport { addCost, addUsage, type ContentBlock, type Message, type Model, type ModelRef } from \"@buildanagent/gateway\";\nimport { FORMAT_VERSION, type Origin, type SessionEntry } from \"@buildanagent/protocol\";\nimport {\n type AgentEvent,\n CAPABILITIES,\n type CallOptions,\n composeInterceptors,\n continueRun,\n DEFAULTS_HASH,\n type Interceptors,\n type Observer,\n type Recheck,\n type Resolution,\n type Run,\n type RunResult,\n run,\n SDK_VERSION,\n type ToolDefinition,\n type ToolResult,\n} from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport {\n type CompletionOutcome,\n type CompletionSettings,\n type CompletionStart,\n completionFailure,\n runCompletionCheck,\n snapshotStart,\n} from \"../completion/check.js\";\nimport type { ContextFill, TurnContext } from \"../context/types.js\";\nimport { HarnessError } from \"../errors.js\";\nimport { skillOfRead } from \"../extensions/skills.js\";\nimport type { Harness } from \"../harness.js\";\nimport type { PolicySession } from \"../permissions/types.js\";\nimport type { ToolWrapper } from \"../tools/types.js\";\nimport { contextOf } from \"./rebuild.js\";\nimport { settleOpenCalls, unansweredCalls } from \"./resume.js\";\nimport type { Session } from \"./session.js\";\nimport { findSticky, stickyDecision } from \"./sticky.js\";\nimport type { EntryInput } from \"./store.js\";\n\n/** One call to a `client_request` tool, as `TurnOptions.clientTool` receives it. */\nexport interface ClientToolCall {\n readonly callId: string;\n /** The tool's canonical name. */\n readonly tool: string;\n /** The input after the SDK validated it. */\n readonly input: unknown;\n /** Fires when the run is aborted, so the caller can withdraw the request it sent. */\n readonly signal: AbortSignal;\n}\n\n/** Runs a `client_request` tool's call by asking the client that holds the tool, and resolves with its result. */\nexport type ClientToolRunner = (call: ClientToolCall) => Promise<ToolResult>;\n\n/** The options of one turn. Anything left out takes the harness's setting. */\nexport interface TurnOptions<H = unknown> {\n readonly input: string | ContentBlock[];\n /** The `origin` of the input blocks: `operator` for text the host wrote, such as a scheduled prompt. Default `user`. */\n readonly inputOrigin?: \"user\" | \"operator\";\n readonly budgetUsd?: number;\n readonly signal?: AbortSignal;\n /** This turn's host context. A tool reads it as `ctx.app`; it reaches no schema, event or entry. */\n readonly hostContext?: H;\n readonly system?: string;\n /** The registered tools this turn may use, by name or alias. A name the registry lacks throws. Default every tool. */\n readonly tools?: readonly string[];\n readonly output?: ToolDefinition<unknown, unknown, unknown>;\n /** The model for this turn. A change from the session's last model is recorded as a `loadout` entry. */\n readonly model?: Model;\n readonly maxSteps?: number;\n /** How many times the loop re-issues a call that ended with a retryable error. Default none. */\n readonly turnRetries?: number;\n readonly modelOptions?: CallOptions;\n /** Called with the run as soon as it starts, so a caller can `steer()`, `followUp()` or abort it. */\n readonly onRun?: (run: Run<unknown>) => void;\n /** Called with how full the request view is after each model call's view is built, when the harness has a context policy. */\n readonly onContextFill?: (fill: ContextFill) => void;\n /** Called when the first run has ended because the request was too large and a retry may follow. */\n readonly onOverflowRetry?: () => void;\n /**\n * Checks the turn's completion. Before the model runs, the turn resolves the project's checks in this sandbox and\n * snapshots the workspace and the check config. A turn that ends `done` then runs those checks, diffs the workspace\n * and the config against the start, and writes a `completion_check` entry. The stop reason is unchanged: a failed\n * check, a flag or a check that could not run is recorded, never fatal. The result's `lastEntryId` is that entry.\n */\n readonly completion?: CompletionSettings;\n /** Called with the `completion_check` entry once it is written. */\n readonly onCompletionCheck?: (entry: SessionEntry) => void;\n /** Observers for this turn alone. Unlike `Run.on()`, they also see `run_start`. They run after the harness's own. */\n readonly observers?: readonly Observer[];\n /**\n * Runs the calls of every tool registered with the `client_request` pattern, in place of the tool's own `execute`.\n * The dispatcher sets it to send a `tool/call` request. Left out, the tool's own `execute` runs.\n */\n readonly clientTool?: ClientToolRunner;\n /**\n * The conversation so far. Left out, it is rebuilt from the session's log, so a turn in any process goes on from\n * what the log holds. Pass it only to run on a conversation the log doesn't hold.\n */\n readonly history?: readonly Message[];\n /** The clock of the entries and the run, for a test that needs the same bytes twice. Default the system clock. */\n readonly clock?: Clock;\n /** Makes the ids of the entries and of the run, for a test that needs the same bytes twice. Default `crypto.randomUUID()`. */\n readonly newId?: () => string;\n}\n\n/** What a turn returns: the SDK's result, and where the turn left the log. */\nexport type TurnResult = RunResult<unknown> & { sessionKey: string; lastEntryId: string };\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\ntype Body = DistributiveOmit<EntryInput, \"id\" | \"parentId\" | \"timestamp\" | \"origin\">;\n\n/** Writes entries one at a time, each after the one before, so every entry's parent is the entry before it. */\nclass EntryWriter {\n readonly #session: Session;\n readonly #newId: () => string;\n readonly #now: () => Date;\n readonly #onFailure: () => void;\n #chain: Promise<unknown> = Promise.resolve();\n #failure: unknown;\n #failed = false;\n\n constructor(session: Session, newId: () => string, now: () => Date, onFailure: () => void) {\n this.#session = session;\n this.#newId = newId;\n this.#now = now;\n this.#onFailure = onFailure;\n }\n\n /** The first write that failed, once one has. */\n failure(): { readonly error: unknown } | undefined {\n return this.#failed ? { error: this.#failure } : undefined;\n }\n\n write(origin: Origin, body: Body): Promise<SessionEntry> {\n const next = this.#chain.then(async () => {\n if (this.#failed) throw this.#failure;\n const entry = {\n ...body,\n id: this.#newId(),\n parentId: this.#session.head(),\n timestamp: this.#now().toISOString(),\n origin,\n };\n const [stored] = await this.#session.append([entry as EntryInput]);\n return stored as SessionEntry;\n });\n this.#chain = next.catch((error) => {\n if (!this.#failed) {\n this.#failed = true;\n this.#failure = error;\n // A log that can't be written can't be trusted to hold the turn, so the run stops.\n this.#onFailure();\n }\n });\n return next;\n }\n\n /** Waits for every write queued so far. */\n settled(): Promise<unknown> {\n return this.#chain;\n }\n}\n\nconst refKey = (ref: ModelRef): string => `${ref.api}\\u0000${ref.provider}\\u0000${ref.id}`;\n\n/**\n * The harness's wrapper, with a `client_request` tool's `execute` sent to `clientTool` first, so a write cap or shadow\n * mode still wraps the call the client runs.\n */\nfunction wrapperOf<H>(harness: Harness<H>, clientTool: ClientToolRunner | undefined): ToolWrapper<H> | undefined {\n if (clientTool === undefined) return harness.wrap;\n const inner: ToolWrapper<H> = harness.wrap ?? ((tool) => tool.definition);\n return (tool, hostContext) => {\n if (tool.pattern !== \"client_request\") return inner(tool, hostContext);\n const definition: ToolDefinition<unknown, unknown, unknown> = {\n ...tool.definition,\n execute: (input, ctx) => clientTool({ callId: ctx.callId, tool: tool.canonicalName, input, signal: ctx.signal }),\n };\n return inner({ ...tool, definition }, hostContext);\n };\n}\n\n/** The turn's tools: the registry's definitions for this host context, cut to the allowlist. */\nfunction toolsOf<H>(\n harness: Harness<H>,\n options: Pick<TurnOptions<H>, \"tools\" | \"hostContext\" | \"clientTool\">,\n): ToolDefinition<unknown, unknown, unknown>[] {\n const all = harness.registry.definitions(wrapperOf(harness, options.clientTool), options.hostContext as H);\n if (options.tools === undefined) return all;\n const allowed = new Set<string>();\n for (const name of options.tools) {\n const tool = harness.registry.get(name);\n if (tool === undefined)\n throw new HarnessError(\n \"invalid_turn_options\",\n `the tool allowlist names \"${name}\", which no tool is registered under`,\n );\n allowed.add(tool.canonicalName);\n }\n return all.filter((definition) => allowed.has(definition.name));\n}\n\n/**\n * Writes what a new session starts with: its header when the path is empty, and its `env_stamp` when the path has\n * none. `write` appends one entry after the ones before it.\n */\nexport async function recordSessionStart<H>(\n harness: Harness<H>,\n write: (origin: \"harness\", body: Body) => Promise<unknown>,\n model: Model,\n started: readonly SessionEntry[],\n): Promise<void> {\n if (started.length === 0) {\n await write(\"harness\", {\n type: \"session_header\",\n formatVersion: FORMAT_VERSION,\n harnessVersion: harness.harnessVersion,\n sdkVersion: SDK_VERSION,\n defaultsHash: DEFAULTS_HASH,\n capabilities: [...CAPABILITIES],\n ablationHash: harness.ablationHash,\n });\n }\n if (!started.some((entry) => entry.type === \"env_stamp\")) {\n await write(\"harness\", { type: \"env_stamp\", ...harness.env, model: model.ref });\n }\n}\n\n/** Writes what a new session starts with, and a `loadout` when the tools or the model differ from the last one recorded. */\nasync function recordLoadout<H>(\n harness: Harness<H>,\n writer: EntryWriter,\n model: Model,\n tools: readonly ToolDefinition<unknown, unknown, unknown>[],\n started: readonly SessionEntry[],\n): Promise<void> {\n await recordSessionStart(harness, (origin, body) => writer.write(origin, body), model, started);\n const names = tools.map((tool) => tool.name);\n const last = started.findLast((entry) => entry.type === \"loadout\");\n const same =\n last?.type === \"loadout\" &&\n last.model !== undefined &&\n refKey(last.model) === refKey(model.ref) &&\n [...last.tools].sort().join() === [...names].sort().join();\n if (!same) await writer.write(\"harness\", { type: \"loadout\", tools: names, model: model.ref });\n const written = new Set<string>();\n for (const record of harness.extensionRecords ?? []) {\n const key = `${record.name}\\0${record.contentHash}`;\n const known =\n written.has(key) ||\n started.some(\n (entry) =>\n entry.type === \"extension_loaded\" && entry.name === record.name && entry.contentHash === record.contentHash,\n );\n if (known) continue;\n written.add(key);\n await writer.write(\"harness\", { ...record, type: \"extension_loaded\" });\n }\n}\n\nasync function writeInput(\n writer: EntryWriter,\n options: { input: string | ContentBlock[]; inputOrigin?: \"user\" | \"operator\" },\n newId: () => string,\n notices: readonly string[] = [],\n) {\n const blocks: ContentBlock[] =\n typeof options.input === \"string\" ? [{ type: \"text\", text: options.input }] : options.input;\n const messageId = newId();\n // A boundary's notice goes first, in the same user message, with the harness as its origin: the gateway's transcript\n // has no system role, so this is how an append-only log tells the model that tools changed (HD3).\n const all = [\n ...notices.map((text) => ({ origin: \"harness\" as const, block: { type: \"text\" as const, text } })),\n ...blocks.map((block) => ({ origin: options.inputOrigin ?? \"user\", block })),\n ];\n for (const [index, { origin, block }] of all.entries()) {\n await writer.write(origin, {\n type: \"message_block\",\n messageId,\n role: \"user\",\n index,\n block,\n delivery: \"input\",\n });\n }\n}\n\n/** The turn's input with the boundaries' notices in front, as the log holds it. */\nfunction withNotices(input: string | ContentBlock[], notices: readonly string[]): string | ContentBlock[] {\n if (notices.length === 0) return input;\n const blocks: ContentBlock[] = typeof input === \"string\" ? [{ type: \"text\", text: input }] : input;\n return [...notices.map((text): ContentBlock => ({ type: \"text\", text })), ...blocks];\n}\n\n/** Runs every turn boundary in order and gathers their notices, before the turn builds its tools. */\nasync function crossBoundaries<H>(harness: Harness<H>, signal: AbortSignal): Promise<string[]> {\n const notices: string[] = [];\n for (const boundary of harness.turnBoundaries ?? []) {\n for (const notice of await boundary.beginTurn(signal)) {\n if (typeof notice === \"string\" && notice !== \"\") notices.push(notice);\n }\n }\n return notices;\n}\n\ntype ModelMessage = Extract<AgentEvent, { type: \"model_call_end\" }>[\"message\"];\n\n/** Turns the run's events into entries. It keeps the last model message back until the next event shows it was kept. */\nclass EventRecorder {\n readonly #writer: EntryWriter;\n readonly #harness: Harness<unknown>;\n readonly #system: string;\n readonly #newId: () => string;\n readonly #tools = new Map<string, string>();\n readonly #inputs = new Map<string, unknown>();\n #pending: ModelMessage | undefined;\n\n readonly #mode: \"run\" | \"continue\";\n readonly #spillOf: TurnContext[\"spillOf\"] | undefined;\n\n constructor(\n writer: EntryWriter,\n harness: Harness<unknown>,\n system: string,\n newId: () => string,\n mode: \"run\" | \"continue\" = \"run\",\n spillOf?: TurnContext[\"spillOf\"],\n ) {\n this.#spillOf = spillOf;\n this.#mode = mode;\n this.#writer = writer;\n this.#harness = harness;\n this.#system = system;\n this.#newId = newId;\n }\n\n /** Queues a write and returns at once. A failure is recorded by the writer and rethrown by `runTurn()`. */\n #queue(origin: Origin, body: Body): void {\n this.#writer.write(origin, body).catch(() => undefined);\n }\n\n #usage(message: ModelMessage): void {\n this.#queue(\"harness\", {\n type: \"usage\",\n source: \"model_call\",\n usage: message.usage,\n ...(message.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: message.lastAttemptUsage }),\n cost: message.cost,\n });\n }\n\n /**\n * Queues the held-back message: its blocks, its end and its usage. The gate calls it before it writes, so a call's\n * decision never lands ahead of the message that made the call.\n */\n flush(): void {\n const message = this.#pending;\n if (message === undefined) return;\n this.#pending = undefined;\n const messageId = this.#newId();\n for (const [index, block] of message.content.entries()) {\n this.#queue(\"model\", { type: \"message_block\", messageId, role: \"assistant\", index, block });\n }\n this.#queue(\"model\", {\n type: \"message_end\",\n messageId,\n model: message.model,\n stopReason: message.stopReason,\n ...(message.error === undefined ? {} : { error: message.error }),\n });\n this.#usage(message);\n }\n\n /** Handles an event without waiting for the store, so the observer is never behind and the SDK never drops it. */\n handle(event: AgentEvent): void {\n if (event.type === \"retry\" && event.layer === \"turn\" && this.#pending !== undefined) {\n // The call's message is superseded and not in the transcript, but the provider billed it.\n const superseded = this.#pending;\n this.#pending = undefined;\n this.#usage(superseded);\n return;\n }\n this.flush();\n this.#record(event);\n }\n\n #record(event: AgentEvent): void {\n switch (event.type) {\n case \"run_start\":\n this.#queue(\"harness\", {\n type: \"turn_start\",\n runId: event.runId,\n mode: this.#mode,\n system: this.#system,\n });\n return;\n case \"approval_request\":\n // The request is in the log before any client hears of it: the harness's own observers wait for the writes.\n this.#queue(\"harness\", { type: \"approval_requested\", request: event.request, input: event.input });\n return;\n case \"model_call_end\":\n this.#pending = event.message;\n // A call the SDK refuses to start (unknown tool, bad input) gets no tool_call_start, so its name comes from here.\n for (const block of event.message.content) {\n if (block.type === \"tool_call\") this.#tools.set(block.callId, block.name);\n }\n return;\n case \"tool_call_start\":\n this.#tools.set(event.callId, event.tool);\n this.#inputs.set(event.callId, event.input);\n return;\n case \"tool_call_end\":\n this.#toolResult(event);\n return;\n case \"steer_applied\":\n for (const [index, block] of event.receipt.message.entries()) {\n this.#queue(\"user\", {\n type: \"message_block\",\n messageId: event.receipt.id,\n role: \"user\",\n index,\n block,\n delivery: event.receipt.kind,\n });\n }\n return;\n case \"run_end\":\n this.#queue(\"harness\", {\n type: \"turn_end\",\n runId: event.runId,\n stopReason: event.result.stopReason,\n steps: event.result.steps,\n });\n return;\n default:\n }\n }\n\n #toolResult(event: Extract<AgentEvent, { type: \"tool_call_end\" }>): void {\n const tool = this.#tools.get(event.callId) ?? \"\";\n const trust = this.#harness.registry.get(tool)?.outputTrust ?? \"untrusted\";\n const { result } = event;\n const spill = this.#spillOf?.(event.callId);\n this.#queue(\"tool\", {\n type: \"tool_result\",\n callId: event.callId,\n tool,\n content: [...result.content],\n isError: result.isError === true,\n ...(result.details === undefined ? {} : { details: result.details }),\n ...(spill === undefined ? {} : { spill }),\n trust,\n });\n this.#skillLoaded(tool, event);\n }\n\n /** A `read` that opened a listed skill's `SKILL.md` and succeeded put the skill's instructions in the context. */\n #skillLoaded(tool: string, event: Extract<AgentEvent, { type: \"tool_call_end\" }>): void {\n const skills = this.#harness.skills;\n if (skills === undefined || tool !== \"read\" || event.result.isError === true) return;\n const input = event.input ?? this.#inputs.get(event.callId);\n const skill = skillOfRead(skills, this.#harness.env.cwd, input);\n if (skill !== undefined) this.#queue(\"harness\", { type: \"skill_loaded\", name: skill.name, path: skill.path });\n }\n}\n\n/** What the layers that write inside a run are given: the turn's writer, and a way to wait for the run's entries. */\nfunction attachment(writer: EntryWriter, recorder: EventRecorder) {\n return {\n append: (origin: Origin, body: Body) => writer.write(origin, body),\n settle: async () => {\n recorder.flush();\n await writer.settled();\n },\n };\n}\n\n/** The turn's context layers, when the harness has a policy. */\nfunction contextFor<H>(\n harness: Harness<H>,\n session: Session,\n model: Model,\n options: { readonly onContextFill?: (fill: ContextFill) => void; readonly history?: readonly Message[] },\n retry = false,\n): TurnContext | undefined {\n return harness.context?.forTurn({\n session,\n model,\n ownHistory: options.history !== undefined,\n ...(retry ? { midTurn: false } : {}),\n ...(options.onContextFill === undefined ? {} : { onFill: options.onContextFill }),\n });\n}\n\n/** The interceptors of a turn: the harness's, the pipeline's gate, and a guard that refuses a model change inside a turn. */\nfunction interceptorsOf<H>(\n harness: Harness<H>,\n session: Session,\n writer: EntryWriter,\n recorder: EventRecorder,\n hostContext: H | undefined,\n turnModel: Model,\n turnContext: TurnContext | undefined,\n): Interceptors {\n const policySession: PolicySession = { append: (entry) => writer.write(\"harness\", entry) };\n const pipelineGate = harness.pipeline?.gate(async () => {\n // The model's message and the earlier results are queued first, so the gate's entries follow them in the log.\n recorder.flush();\n await writer.settled();\n return { session: policySession, hostContext, entries: await session.path() };\n });\n const gate =\n pipelineGate === undefined ? undefined : withStickyAllowances(pipelineGate, harness, session, writer, recorder);\n // The context policy runs first, so it reads and indexes the run's own transcript, and the harness's hooks see its view.\n const composed = composeInterceptors(turnContext?.interceptors ?? {}, harness.interceptors ?? {}, gate ?? {});\n const inner = composed.beforeModelCall;\n return {\n ...composed,\n async beforeModelCall(event) {\n const patch = await inner?.(event);\n if (\n patch !== undefined &&\n \"model\" in patch &&\n patch.model !== undefined &&\n refKey(patch.model.ref) !== refKey(turnModel.ref)\n ) {\n throw new HarnessError(\n \"invalid_turn_options\",\n \"a hook changed the model inside a turn; set TurnOptions.model for the next turn so it is recorded\",\n );\n }\n return patch;\n },\n };\n}\n\n/**\n * The pipeline's gate with the sticky allowances applied: a call the pipeline would ask about, and that a person's\n * earlier sticky `allow` covers, runs. A deny stays a deny, and the pipeline's own entry for the ask stays in the log\n * beside the entry that records the allowance.\n */\nfunction withStickyAllowances<H>(\n gate: NonNullable<ReturnType<NonNullable<Harness<H>[\"pipeline\"]>[\"gate\"]>>,\n harness: Harness<H>,\n session: Session,\n writer: EntryWriter,\n recorder: EventRecorder,\n): Pick<Interceptors, \"beforeToolCall\"> {\n return {\n async beforeToolCall(event) {\n // The pipeline's gate always has a `beforeToolCall`; a gate without one has nothing to ask.\n const decision = (await gate.beforeToolCall?.(event)) ?? { decision: \"allow\" as const };\n if (decision.decision !== \"ask\") return decision;\n recorder.flush();\n await writer.settled();\n const covered = await findSticky(\n await session.path(),\n { tool: event.tool, input: event.input, policyVersion: decision.policyVersion },\n harness.registry,\n );\n if (covered === undefined) return decision;\n const tool = harness.registry.get(event.tool)?.canonicalName ?? event.tool;\n await writer.write(\n \"harness\",\n await stickyDecision({ callId: event.callId, tool, input: event.input }, covered, decision.policyVersion),\n );\n return { decision: \"allow\", reason: \"a sticky allowance a person gave earlier covers this call\" };\n },\n };\n}\n\n/**\n * The harness's own observers, each held back on an approval request until the entries written so far are durable. An\n * observer that hears of a request can therefore always find its `approval_requested` entry in the log.\n */\nfunction afterWrites(observers: readonly Observer[] | undefined, writer: EntryWriter): Observer[] {\n return (observers ?? []).map(\n (observer): Observer =>\n async (event) => {\n // Only a request needs its entry first, and `settled()` never rejects: a failed write is the writer's to report.\n if (event.type === \"approval_request\") await writer.settled();\n await observer(event);\n },\n );\n}\n\n/** The run options a turn sets only when it has a value, so a missing one leaves the SDK's default. */\ntype RunSettings<H> = Pick<\n TurnOptions<H>,\n | \"clock\"\n | \"newId\"\n | \"hostContext\"\n | \"output\"\n | \"maxSteps\"\n | \"turnRetries\"\n | \"modelOptions\"\n | \"budgetUsd\"\n | \"onContextFill\"\n>;\n\nfunction optionalRunOptions<H>(options: RunSettings<H>, harness: Harness<H>, history: readonly Message[]) {\n return {\n ...(history.length === 0 ? {} : { history }),\n ...(options.clock === undefined ? {} : { clock: options.clock }),\n ...(options.newId === undefined ? {} : { idGenerator: options.newId }),\n ...(options.hostContext === undefined ? {} : { app: options.hostContext }),\n ...(options.output === undefined ? {} : { output: options.output }),\n ...(options.maxSteps === undefined ? {} : { maxSteps: options.maxSteps }),\n ...(options.turnRetries === undefined ? {} : { turnRetries: options.turnRetries }),\n ...(options.modelOptions === undefined ? {} : { modelOptions: options.modelOptions }),\n ...(options.budgetUsd === undefined ? {} : { budgetUsd: options.budgetUsd }),\n ...(harness.signer === undefined ? {} : { signer: harness.signer }),\n };\n}\n\n/** Waits for the run and for every queued write, and returns the result with where the log ends. */\nasync function settleTurn(handle: Run<unknown>, writer: EntryWriter, session: Session): Promise<TurnResult> {\n let result: RunResult<unknown> | undefined;\n let runError: unknown;\n try {\n result = (await handle.result) as RunResult<unknown>;\n } catch (error) {\n runError = error;\n }\n await writer.settled();\n // A store failure is the cause of an aborted run, so it comes before the run's own error.\n const failed = writer.failure();\n if (failed !== undefined) throw failed.error;\n if (result === undefined) throw runError;\n return { ...result, sessionKey: session.key.sessionId, lastEntryId: session.head() as string };\n}\n\n/** What every turn and every resume needs: a writer whose failure aborts the run, the run's signal and its id source. */\nfunction turnPlumbing(session: Session, options: { signal?: AbortSignal; clock?: Clock; newId?: () => string }) {\n const stop = new AbortController();\n const signal = options.signal === undefined ? stop.signal : AbortSignal.any([options.signal, stop.signal]);\n const newId = options.newId ?? (() => globalThis.crypto.randomUUID());\n const writer = new EntryWriter(\n session,\n newId,\n options.clock === undefined ? () => new Date() : () => new Date((options.clock as Clock).now()),\n () => stop.abort(),\n );\n return { signal, newId, writer };\n}\n\n/**\n * Runs one turn on a session and writes it to the log. The session must be open with a lock. The first turn of a new\n * session writes its header and `env_stamp`; a turn whose model or tools differ from the last recorded ones writes a\n * `loadout` first; the input blocks follow, and the run's events after them. The returned result is the SDK's, with the\n * session id and the id of the last entry the turn wrote. When the harness has a context policy and the run ends because\n * the provider said the request was too large, the policy compacts once and the turn goes on from the rebuilt context;\n * a second overflow ends the turn with that error.\n */\nexport async function runTurn<H = unknown>(\n session: Session,\n harness: Harness<H>,\n options: TurnOptions<H>,\n): Promise<TurnResult> {\n const settings = options.completion;\n // The start state is taken before the turn writes anything, and with the turn's own signal, so an abort stops it.\n // It is taken for every turn, because whether the turn ends `done` is known only after the model has run.\n const start =\n settings === undefined ? undefined : await snapshotStart(settings, options.signal ?? new AbortController().signal);\n const result = await retryAfterOverflow(session, harness, options, await runTurnOnce(session, harness, options));\n if (settings === undefined || result.stopReason !== \"done\") return result;\n return recordCompletion(session, settings, start, options, result);\n}\n\n/**\n * Runs the completion check after a `done` turn and writes its entry. The result's stop reason is left as it is, and a\n * check that throws (a sandbox error, a disposed sandbox) is recorded as a failed entry instead of losing the result.\n */\nasync function recordCompletion<H>(\n session: Session,\n settings: CompletionSettings,\n start: CompletionStart | undefined,\n options: TurnOptions<H>,\n result: TurnResult,\n): Promise<TurnResult> {\n const signal = options.signal ?? new AbortController().signal;\n let outcome: CompletionOutcome;\n try {\n outcome = await runCompletionCheck(settings, start, signal);\n } catch (error) {\n outcome = { checks: [], passed: false, flagged: [...(start?.failures ?? []), completionFailure(error)] };\n }\n const { writer } = turnPlumbing(session, options);\n let entry: SessionEntry;\n try {\n entry = await writer.write(\"harness\", { type: \"completion_check\", ...outcome });\n } catch {\n // A failed append (a lost lock, a store conflict) must not turn a `done` turn into a rejection: the turn's own\n // entries are written, and the result stands without the check's entry.\n return result;\n }\n options.onCompletionCheck?.(entry);\n return { ...result, lastEntryId: entry.id };\n}\n\nasync function runTurnOnce<H = unknown>(\n session: Session,\n harness: Harness<H>,\n options: TurnOptions<H>,\n): Promise<TurnResult> {\n const model = options.model ?? harness.model;\n const system = options.system ?? harness.system;\n const { signal, newId, writer } = turnPlumbing(session, options);\n // Tools change only here, between turns: a boundary registers what arrived since the last turn before the tools\n // are built, so nothing it does lands inside the run.\n const notices = await crossBoundaries(harness, signal);\n const tools = toolsOf(harness, options);\n // What a crash left open is settled first, so the log reads as a whole and the context has no call without a result.\n let path = await session.path();\n const wrote = await settleOpenCalls(\n path,\n harness,\n (origin, body) => writer.write(origin, body as Body),\n !session.headMoved(),\n );\n if (wrote) path = await session.path();\n await recordLoadout(harness, writer, model, tools, path);\n const turnContext = contextFor(harness, session, model, options);\n const waiting = options.history === undefined ? unansweredCalls(path, true) : [];\n if (waiting.length > 0) {\n throw new HarnessError(\n \"invalid_turn_options\",\n `the session waits on tool calls with no result (${waiting.map((call) => call.callId).join(\", \")}); resolve them before another turn, or pass history`,\n );\n }\n // Between turns, before the input is written, the summary layer may replace an outgrown span with a summary. It\n // runs only once no call waits for a result, so a paused turn's own message is never in the span.\n if (\n options.history === undefined &&\n (await turnContext?.compact({ path, signal, append: (origin, body) => writer.write(origin, body) }))\n ) {\n path = await session.path();\n }\n const history = options.history ?? contextOf(path).messages;\n await writeInput(writer, options, newId, notices);\n // A notice counts as told only once it is in the log; a turn that failed before here tells it again next time.\n await writer.settled();\n if (writer.failure() === undefined) for (const boundary of harness.turnBoundaries ?? []) boundary.commitNotices?.();\n const input = withNotices(options.input, notices);\n const recorder = new EventRecorder(writer, harness as Harness<unknown>, system, newId, \"run\", turnContext?.spillOf);\n turnContext?.attach(attachment(writer, recorder));\n const observer: Observer = (event) => recorder.handle(event);\n const handle = run({\n model,\n system,\n input,\n tools,\n signal,\n interceptors: interceptorsOf(harness, session, writer, recorder, options.hostContext, model, turnContext),\n observers: [observer, ...afterWrites(harness.observers, writer), ...afterWrites(options.observers, writer)],\n ...optionalRunOptions(options, harness, history),\n });\n options.onRun?.(handle);\n return settleTurn(handle, writer, session);\n}\n\n/**\n * Re-runs from an entry: HEAD moves to `entryId` with a `checkout` entry, and a new turn follows it as a new branch of\n * the same log. The entries of the branch it left stay as they were. The entry must not leave a tool call without its\n * result, because that call never ran on the new branch.\n */\nexport async function rerunFrom<H = unknown>(\n session: Session,\n harness: Harness<H>,\n entryId: string,\n options: TurnOptions<H>,\n): Promise<TurnResult> {\n const waiting = unansweredCalls(await session.path(entryId), true).map((call) => call.callId);\n if (waiting.length > 0) {\n throw new HarnessError(\n \"invalid_turn_options\",\n `entry ${entryId} follows tool calls with no result (${waiting.join(\", \")}), so a re-run from it would send calls that never ran`,\n );\n }\n await session.checkout(entryId);\n return runTurn(session, harness, options);\n}\n\n/** One `approval_resolved` entry as written: the answer, and what it covers beyond its own call. */\nexport interface ResolutionRecord {\n readonly resolution: Resolution;\n readonly sticky?: \"run\" | \"session\";\n readonly allowance?: { tool: string; inputHash?: string; commandPrefix?: string[]; policyVersion?: string };\n readonly groupId?: string;\n readonly quorum?: \"pending\";\n}\n\n/** What resuming a paused turn takes: the answers, and the same per-turn settings a turn has. */\nexport interface ResumeOptions<H = unknown> extends RunSettings<H> {\n /** The answers the SDK checks and applies: one per request whose answer is settled. */\n readonly resolutions: readonly Resolution[];\n /**\n * The `approval_resolved` entries to write before the run, with what each covers. Left out, each resolution is\n * written as it is. A request a quorum still waits on has a record here and no resolution.\n */\n readonly records?: readonly ResolutionRecord[];\n /**\n * The caller's app data. A request bound to app data when it paused runs only when the resume passes the same value,\n * so this is the caller's identity. The tools are the paused turn's, from the log. The model is the harness's, or\n * `model`, and one that differs from the paused turn's is recorded as a `loadout`. Pass the turn's `maxSteps`,\n * `output`, `turnRetries` and `modelOptions` again, because the log does not hold them.\n */\n readonly hostContext?: H;\n /** The model the resumed turn runs on, in place of the harness's. */\n readonly model?: Model;\n /** Aborts the resumed turn. */\n readonly signal?: AbortSignal;\n /** Called with the resumed run as soon as it starts, so a caller can `steer()`, `followUp()` or abort it. */\n readonly onRun?: (run: Run<unknown>) => void;\n /** Observers for this resume alone, as `TurnOptions.observers`. */\n readonly observers?: readonly Observer[];\n /** Runs the calls of `client_request` tools, as `TurnOptions.clientTool`. */\n readonly clientTool?: ClientToolRunner;\n}\n\n/** The resume's policy check: the pipeline decides the call again, so a deny written after the pause wins. */\nfunction recheckThrough<H>(\n session: Session,\n harness: Harness<H>,\n writer: EntryWriter,\n recorder: EventRecorder,\n hostContext: H | undefined,\n): Recheck {\n return async (pending, input) => {\n // The earlier results and decisions are queued first, so the pipeline reads a log that holds them.\n recorder.flush();\n await writer.settled();\n const decision = await harness.pipeline?.decide(\n { callId: pending.callId, tool: pending.tool, input, initiator: \"model\" },\n { session: { append: (entry) => writer.write(\"harness\", entry) }, hostContext, entries: await session.path() },\n );\n // A person approved the call, so a question the pipeline would ask again doesn't stop it; a deny does.\n return decision?.decision === \"deny\" ? { deny: decision.reason } : \"allow\";\n };\n}\n\n/**\n * Resumes a paused turn from the log alone. The context, with its waiting requests, is rebuilt before anything is\n * written; each resolution is then written as an `approval_resolved` entry, and `continueRun()` verifies the requests\n * against the harness's signer. Each approved call goes through the permission pipeline again first, and a deny now\n * turns the approval into a denial.\n */\nexport async function resumeTurn<H = unknown>(\n session: Session,\n harness: Harness<H>,\n options: ResumeOptions<H>,\n): Promise<TurnResult> {\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so no approval can be checked\");\n }\n const { signal, newId, writer } = turnPlumbing(session, options);\n const path = await session.path();\n const context = contextOf(path);\n const waiting = new Set((context.pending ?? []).map((request) => request.id));\n const answered = new Set<string>();\n for (const resolution of options.resolutions) {\n if (answered.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `request ${resolution.requestId} is answered twice in one resume`);\n }\n answered.add(resolution.requestId);\n if (!waiting.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `no request ${resolution.requestId} is waiting in this session`);\n }\n }\n // The paused turn's tools: the latest `loadout` names them, and one the registry has lost stops the resume.\n const names = path.findLast((entry) => entry.type === \"loadout\");\n const tools = toolsOf(harness, {\n ...(names?.type === \"loadout\" ? { tools: names.tools } : {}),\n ...(options.hostContext === undefined ? {} : { hostContext: options.hostContext }),\n ...(options.clientTool === undefined ? {} : { clientTool: options.clientTool }),\n });\n const records = options.records ?? options.resolutions.map((resolution) => ({ resolution }));\n for (const record of records) await writer.write(\"user\", { type: \"approval_resolved\", ...record });\n const model = options.model ?? harness.model;\n await recordLoadout(harness, writer, model, tools, path);\n const turnContext = contextFor(harness, session, model, options);\n const recorder = new EventRecorder(\n writer,\n harness as Harness<unknown>,\n context.system,\n newId,\n \"continue\",\n turnContext?.spillOf,\n );\n turnContext?.attach(attachment(writer, recorder));\n const handle = continueRun(context, {\n model,\n tools,\n resolutions: [...options.resolutions],\n recheck: recheckThrough(session, harness, writer, recorder, options.hostContext),\n signer: harness.signer,\n signal,\n interceptors: interceptorsOf(harness, session, writer, recorder, options.hostContext, model, turnContext),\n observers: [\n (event: AgentEvent) => recorder.handle(event),\n ...afterWrites(harness.observers, writer),\n ...afterWrites(options.observers, writer),\n ],\n ...optionalRunOptions(options, harness, []),\n });\n options.onRun?.(handle);\n return settleTurn(handle, writer, session);\n}\n\n/**\n * Layer 5: after a run that ended because the request was too large, asks the context policy to compact once and\n * goes on from the rebuilt context with `continueRun()`, which asks the model again because the gateway leaves the\n * failed response out of the request. Only one retry is made, so a second overflow is the turn's result.\n */\nasync function retryAfterOverflow<H>(\n session: Session,\n harness: Harness<H>,\n options: TurnOptions<H>,\n first: TurnResult,\n): Promise<TurnResult> {\n if (first.stopReason !== \"error\" || first.error.kind !== \"overflow\" || options.history !== undefined) return first;\n const model = options.model ?? harness.model;\n const turnContext = contextFor(harness, session, model, options, true);\n if (turnContext === undefined) return first;\n // The retry has what the first attempt left of `maxSteps`; with none left there is nothing to retry into.\n const stepsLeft = options.maxSteps === undefined ? undefined : options.maxSteps - first.steps;\n if (stepsLeft !== undefined && stepsLeft < 1) return first;\n const { signal, newId, writer } = turnPlumbing(session, options);\n // The first run has ended: a steer sent now waits for the retry's run.\n options.onOverflowRetry?.();\n let compacted: boolean;\n try {\n compacted = await turnContext.onOverflow({\n path: await session.path(),\n signal,\n append: (origin, body) => writer.write(origin, body),\n });\n } catch (error) {\n // An abort during the summary call ends the turn as aborted, not as the overflow it was trying to cure.\n if (signal.aborted) return { ...withoutError(first), stopReason: \"aborted\", lastEntryId: session.head() as string };\n throw error;\n }\n await writer.settled();\n // A summary call that was made and rejected wrote its usage entry, so the log ends later than the first result says.\n if (!compacted) return { ...first, lastEntryId: session.head() as string };\n const context = contextOf(await session.path());\n const recorder = new EventRecorder(\n writer,\n harness as Harness<unknown>,\n context.system,\n newId,\n \"continue\",\n turnContext.spillOf,\n );\n turnContext.attach(attachment(writer, recorder));\n const handle = continueRun(context, {\n model,\n tools: toolsOf(harness, options),\n resolutions: [],\n signal,\n interceptors: interceptorsOf(harness, session, writer, recorder, options.hostContext, model, turnContext),\n observers: [\n (event: AgentEvent) => recorder.handle(event),\n ...afterWrites(harness.observers, writer),\n ...afterWrites(options.observers, writer),\n ],\n ...optionalRunOptions(stepsLeft === undefined ? options : { ...options, maxSteps: stepsLeft }, harness, []),\n });\n options.onRun?.(handle);\n const retried = await settleTurn(handle, writer, session);\n // The turn's result counts both attempts: what the first one spent and the steps it took.\n return {\n ...retried,\n steps: first.steps + retried.steps,\n usage: addUsage(first.usage, retried.usage),\n cost: addCost(first.cost, retried.cost),\n };\n}\n\n/** A result without its `error`, for a turn that was cut short before the error mattered. */\nfunction withoutError(result: TurnResult): TurnResult {\n const { error: _error, ...rest } = result as TurnResult & { error?: unknown };\n return rest as TurnResult;\n}\n"]}
@@ -9,4 +9,4 @@ export type { FetchProxy } from "./builtins/fetch.js";
9
9
  export { DuplicateToolError } from "./errors.js";
10
10
  export { createToolRegistry } from "./registry.js";
11
11
  export { type ToolSearchOptions, toolSearchInterceptors, toolSearchTool } from "./tool-search.js";
12
- export type { ApprovalReuse, HostPattern, OutputTrust, PreambleOptions, RegisteredTool, ToolExposure, ToolRegistration, ToolRegistry, ToolSource, ToolWrapper, } from "./types.js";
12
+ export type { ApprovalReuse, HostPattern, OutputTrust, PreambleOptions, RegisteredTool, ToolExposure, ToolRegistration, ToolRegistry, ToolSource, ToolWrapper, TurnBoundary, } from "./types.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/tools/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAA4B,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAEvF,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAA0B,sBAAsB,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/tools`: the tool registry, which names, defers and wraps the tools of every source, the\n * tool search that activates deferred ones, and the built-in tools, which reach files, commands and the web only\n * through a sandbox and an egress proxy.\n */\nexport { type BuiltinToolsOptions, builtinTools } from \"./builtins/builtins.js\";\nexport { BUILTIN_TOOL_DEFAULTS, BUILTIN_TOOLS_HASH } from \"./builtins/descriptions.js\";\nexport type { FetchProxy } from \"./builtins/fetch.js\";\nexport { DuplicateToolError } from \"./errors.js\";\nexport { createToolRegistry } from \"./registry.js\";\nexport { type ToolSearchOptions, toolSearchInterceptors, toolSearchTool } from \"./tool-search.js\";\nexport type {\n ApprovalReuse,\n HostPattern,\n OutputTrust,\n PreambleOptions,\n RegisteredTool,\n ToolExposure,\n ToolRegistration,\n ToolRegistry,\n ToolSource,\n ToolWrapper,\n} from \"./types.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/tools/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAA4B,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAEvF,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAA0B,sBAAsB,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/tools`: the tool registry, which names, defers and wraps the tools of every source, the\n * tool search that activates deferred ones, and the built-in tools, which reach files, commands and the web only\n * through a sandbox and an egress proxy.\n */\nexport { type BuiltinToolsOptions, builtinTools } from \"./builtins/builtins.js\";\nexport { BUILTIN_TOOL_DEFAULTS, BUILTIN_TOOLS_HASH } from \"./builtins/descriptions.js\";\nexport type { FetchProxy } from \"./builtins/fetch.js\";\nexport { DuplicateToolError } from \"./errors.js\";\nexport { createToolRegistry } from \"./registry.js\";\nexport { type ToolSearchOptions, toolSearchInterceptors, toolSearchTool } from \"./tool-search.js\";\nexport type {\n ApprovalReuse,\n HostPattern,\n OutputTrust,\n PreambleOptions,\n RegisteredTool,\n ToolExposure,\n ToolRegistration,\n ToolRegistry,\n ToolSource,\n ToolWrapper,\n TurnBoundary,\n} from \"./types.js\";\n"]}
@@ -104,3 +104,19 @@ export interface ToolRegistry {
104
104
  */
105
105
  preambleTokens(options?: PreambleOptions): number;
106
106
  }
107
+ /**
108
+ * A component that changes a session's tools only between turns, such as the MCP client. The runner calls
109
+ * `beginTurn()` once at the start of each turn, before it builds the turn's tools, so a change never lands inside a
110
+ * turn and the tools a request sends never change because of it.
111
+ */
112
+ export interface TurnBoundary {
113
+ /**
114
+ * Applies what changed since the last turn and returns the notices the turn writes in front of its input, as text
115
+ * blocks of origin `harness`. Each is text the component wrote itself and holds no outside party's prose, though it
116
+ * may name something an outside party named, such as an MCP tool's canonical name, which keeps only `A-Z`, `a-z`,
117
+ * `0-9`, `_` and `-` of the server's name for it. An empty list writes nothing.
118
+ */
119
+ beginTurn(signal: AbortSignal): Promise<readonly string[]>;
120
+ /** Called once the turn has written the notices, so a component can hold back what it told until then. */
121
+ commitNotices?(): void;
122
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/tools/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The registry's types: where a tool comes from, how the model reaches it, and what the harness records about it. The\n * registry holds one `RegisteredTool` per tool of every source, so permission rules, tool search and the session log\n * read one description of each.\n */\nimport type { ToolDefinition } from \"@buildanagent/sdk\";\n\n/** Where a tool comes from: the harness, an in-process extension, one MCP server (`mcp:<server>`) or the client. */\nexport type ToolSource = \"builtin\" | \"extension\" | `mcp:${string}` | \"client\";\n\n/** How a tool's code is reached: in this process, or by asking the client through a `tool/call` server request. */\nexport type HostPattern = \"in_process\" | \"client_request\";\n\n/** Whether a request sends the tool: `direct` always, `deferred` once tool search names it, `hidden` only when named. */\nexport type ToolExposure = \"direct\" | \"deferred\" | \"hidden\";\n\n/** Whether a tool's output may carry instructions an attacker wrote. */\nexport type OutputTrust = \"trusted\" | \"untrusted\";\n\n/** Which approvals may cover later calls: a sticky one, a grouped one, both, or none, so each call asks. */\nexport type ApprovalReuse = \"sticky\" | \"group\" | \"both\" | \"none\";\n\n/** A tool as the registry holds it, with its canonical name and every default resolved. */\nexport interface RegisteredTool {\n /** The name every request, permission rule and log entry uses. */\n readonly canonicalName: string;\n /** The name the tool was registered under, before any namespace or hash. */\n readonly name: string;\n /** A native or display name that a rule may match too. It never replaces the canonical name. */\n readonly alias?: string;\n readonly source: ToolSource;\n readonly pattern: HostPattern;\n readonly exposure: ToolExposure;\n /** `untrusted` for an MCP tool and a tool that calls a remote agent, `trusted` otherwise, unless the tool declares it. */\n readonly outputTrust: OutputTrust;\n /** Defaults to `both`. */\n readonly approvalReuse: ApprovalReuse;\n /** True for a tool that calls a remote agent, whose replies are untrusted input. */\n readonly remoteAgent: boolean;\n readonly definition: ToolDefinition<unknown, unknown, unknown>;\n}\n\n/** What `register()` takes: the tool, where it comes from, and any default it overrides. */\nexport interface ToolRegistration {\n /** The name the source knows the tool by. For an MCP tool it is the server's tool name, which the registry namespaces. */\n readonly name: string;\n readonly source: ToolSource;\n /** Defaults to `in_process`. */\n readonly pattern?: HostPattern;\n readonly alias?: string;\n /** Defaults to the source's exposure, which is `deferred` for MCP and `direct` for every other source. */\n readonly exposure?: ToolExposure;\n /** Defaults by source, as `RegisteredTool.outputTrust` says. */\n readonly outputTrust?: OutputTrust;\n /** Set it for a tool that calls a remote agent, so its output defaults to `untrusted`. */\n readonly remoteAgent?: boolean;\n readonly approvalReuse?: ApprovalReuse;\n /** Lets an extension, client or other non-MCP tool replace a built-in of the same name. It replaces nothing else. */\n readonly override?: boolean;\n readonly definition: ToolDefinition<unknown, unknown, unknown>;\n}\n\n/**\n * Wraps one registered tool's definition for a turn: a write cap, shadow mode or a sandbox binding, with the turn's\n * host context. The registry sets the result's name and exposure, so a wrapper can't rename a tool or expose it.\n */\nexport type ToolWrapper<H = unknown> = (\n tool: RegisteredTool,\n hostContext: H,\n) => ToolDefinition<unknown, unknown, unknown>;\n\n/** The options of `preambleTokens()`. */\nexport interface PreambleOptions {\n /** The system prompt, counted with the tool definitions. Left out, only the tools count. */\n readonly system?: string;\n}\n\n/** One registry for the tools of every source. */\nexport interface ToolRegistry {\n /**\n * Adds a tool and returns it as registered. Throws a `DuplicateToolError` when the canonical name or alias is\n * taken, and a `HarnessError`, code `invalid_tool_registration`, for a name, source or option that is unusable. An\n * MCP tool whose server or tool name needs cleaning, holds `__`, starts or ends with `_`, or runs past 64 characters gets a hash of its source\n * and name in its canonical name, so the name depends on the tool alone. Only a final name that is still taken throws.\n */\n register(tool: ToolRegistration): RegisteredTool;\n /**\n * Registers every tool in the list, or none of them: when one registration throws, the tools registered before it in\n * the list are removed again and the error is thrown. Returns the tools as registered, in the list's order.\n */\n registerAll(tools: readonly ToolRegistration[]): RegisteredTool[];\n /** The tool with this canonical name or alias, or `undefined`. */\n get(name: string): RegisteredTool | undefined;\n /** Every tool, in registration order. A replaced built-in keeps its place. */\n list(): readonly RegisteredTool[];\n /**\n * Sets the exposure of every tool of `source`, and of each one registered after. An explicit exposure on a tool is\n * replaced. A run keeps the exposure `definitions()` gave its tools, so take `definitions()` again for the next run.\n * A `RegisteredTool` that `register()` or `get()` returned earlier is a snapshot, so call `get()` again to read the\n * current exposure.\n */\n setExposure(source: ToolSource, exposure: ToolExposure): void;\n /**\n * The definitions for one turn, for `RunOptions.tools`, in registration order so the cached prefix never moves when\n * a tool activates. Each tool goes through `wrap`, which defaults to the tool's own definition.\n */\n definitions<H = undefined>(wrap?: ToolWrapper<H>, hostContext?: H): ToolDefinition<unknown, unknown, unknown>[];\n /**\n * The registry's own tools a request sends: every `direct` tool and every tool named in `activated`, in\n * registration order, and a name the registry doesn't hold is left out. It is not the complete list when the run also\n * has tools from outside the registry, so `toolSearchInterceptors()` builds its list from the request instead.\n */\n activeTools(activated: ReadonlySet<string>): string[];\n /**\n * An estimate of the tokens a request carries before any message: the system prompt and every `direct` tool. A\n * tool whose schema can't describe itself counts as an empty object schema.\n */\n preambleTokens(options?: PreambleOptions): number;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/tools/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The registry's types: where a tool comes from, how the model reaches it, and what the harness records about it. The\n * registry holds one `RegisteredTool` per tool of every source, so permission rules, tool search and the session log\n * read one description of each.\n */\nimport type { ToolDefinition } from \"@buildanagent/sdk\";\n\n/** Where a tool comes from: the harness, an in-process extension, one MCP server (`mcp:<server>`) or the client. */\nexport type ToolSource = \"builtin\" | \"extension\" | `mcp:${string}` | \"client\";\n\n/** How a tool's code is reached: in this process, or by asking the client through a `tool/call` server request. */\nexport type HostPattern = \"in_process\" | \"client_request\";\n\n/** Whether a request sends the tool: `direct` always, `deferred` once tool search names it, `hidden` only when named. */\nexport type ToolExposure = \"direct\" | \"deferred\" | \"hidden\";\n\n/** Whether a tool's output may carry instructions an attacker wrote. */\nexport type OutputTrust = \"trusted\" | \"untrusted\";\n\n/** Which approvals may cover later calls: a sticky one, a grouped one, both, or none, so each call asks. */\nexport type ApprovalReuse = \"sticky\" | \"group\" | \"both\" | \"none\";\n\n/** A tool as the registry holds it, with its canonical name and every default resolved. */\nexport interface RegisteredTool {\n /** The name every request, permission rule and log entry uses. */\n readonly canonicalName: string;\n /** The name the tool was registered under, before any namespace or hash. */\n readonly name: string;\n /** A native or display name that a rule may match too. It never replaces the canonical name. */\n readonly alias?: string;\n readonly source: ToolSource;\n readonly pattern: HostPattern;\n readonly exposure: ToolExposure;\n /** `untrusted` for an MCP tool and a tool that calls a remote agent, `trusted` otherwise, unless the tool declares it. */\n readonly outputTrust: OutputTrust;\n /** Defaults to `both`. */\n readonly approvalReuse: ApprovalReuse;\n /** True for a tool that calls a remote agent, whose replies are untrusted input. */\n readonly remoteAgent: boolean;\n readonly definition: ToolDefinition<unknown, unknown, unknown>;\n}\n\n/** What `register()` takes: the tool, where it comes from, and any default it overrides. */\nexport interface ToolRegistration {\n /** The name the source knows the tool by. For an MCP tool it is the server's tool name, which the registry namespaces. */\n readonly name: string;\n readonly source: ToolSource;\n /** Defaults to `in_process`. */\n readonly pattern?: HostPattern;\n readonly alias?: string;\n /** Defaults to the source's exposure, which is `deferred` for MCP and `direct` for every other source. */\n readonly exposure?: ToolExposure;\n /** Defaults by source, as `RegisteredTool.outputTrust` says. */\n readonly outputTrust?: OutputTrust;\n /** Set it for a tool that calls a remote agent, so its output defaults to `untrusted`. */\n readonly remoteAgent?: boolean;\n readonly approvalReuse?: ApprovalReuse;\n /** Lets an extension, client or other non-MCP tool replace a built-in of the same name. It replaces nothing else. */\n readonly override?: boolean;\n readonly definition: ToolDefinition<unknown, unknown, unknown>;\n}\n\n/**\n * Wraps one registered tool's definition for a turn: a write cap, shadow mode or a sandbox binding, with the turn's\n * host context. The registry sets the result's name and exposure, so a wrapper can't rename a tool or expose it.\n */\nexport type ToolWrapper<H = unknown> = (\n tool: RegisteredTool,\n hostContext: H,\n) => ToolDefinition<unknown, unknown, unknown>;\n\n/** The options of `preambleTokens()`. */\nexport interface PreambleOptions {\n /** The system prompt, counted with the tool definitions. Left out, only the tools count. */\n readonly system?: string;\n}\n\n/** One registry for the tools of every source. */\nexport interface ToolRegistry {\n /**\n * Adds a tool and returns it as registered. Throws a `DuplicateToolError` when the canonical name or alias is\n * taken, and a `HarnessError`, code `invalid_tool_registration`, for a name, source or option that is unusable. An\n * MCP tool whose server or tool name needs cleaning, holds `__`, starts or ends with `_`, or runs past 64 characters gets a hash of its source\n * and name in its canonical name, so the name depends on the tool alone. Only a final name that is still taken throws.\n */\n register(tool: ToolRegistration): RegisteredTool;\n /**\n * Registers every tool in the list, or none of them: when one registration throws, the tools registered before it in\n * the list are removed again and the error is thrown. Returns the tools as registered, in the list's order.\n */\n registerAll(tools: readonly ToolRegistration[]): RegisteredTool[];\n /** The tool with this canonical name or alias, or `undefined`. */\n get(name: string): RegisteredTool | undefined;\n /** Every tool, in registration order. A replaced built-in keeps its place. */\n list(): readonly RegisteredTool[];\n /**\n * Sets the exposure of every tool of `source`, and of each one registered after. An explicit exposure on a tool is\n * replaced. A run keeps the exposure `definitions()` gave its tools, so take `definitions()` again for the next run.\n * A `RegisteredTool` that `register()` or `get()` returned earlier is a snapshot, so call `get()` again to read the\n * current exposure.\n */\n setExposure(source: ToolSource, exposure: ToolExposure): void;\n /**\n * The definitions for one turn, for `RunOptions.tools`, in registration order so the cached prefix never moves when\n * a tool activates. Each tool goes through `wrap`, which defaults to the tool's own definition.\n */\n definitions<H = undefined>(wrap?: ToolWrapper<H>, hostContext?: H): ToolDefinition<unknown, unknown, unknown>[];\n /**\n * The registry's own tools a request sends: every `direct` tool and every tool named in `activated`, in\n * registration order, and a name the registry doesn't hold is left out. It is not the complete list when the run also\n * has tools from outside the registry, so `toolSearchInterceptors()` builds its list from the request instead.\n */\n activeTools(activated: ReadonlySet<string>): string[];\n /**\n * An estimate of the tokens a request carries before any message: the system prompt and every `direct` tool. A\n * tool whose schema can't describe itself counts as an empty object schema.\n */\n preambleTokens(options?: PreambleOptions): number;\n}\n\n/**\n * A component that changes a session's tools only between turns, such as the MCP client. The runner calls\n * `beginTurn()` once at the start of each turn, before it builds the turn's tools, so a change never lands inside a\n * turn and the tools a request sends never change because of it.\n */\nexport interface TurnBoundary {\n /**\n * Applies what changed since the last turn and returns the notices the turn writes in front of its input, as text\n * blocks of origin `harness`. Each is text the component wrote itself and holds no outside party's prose, though it\n * may name something an outside party named, such as an MCP tool's canonical name, which keeps only `A-Z`, `a-z`,\n * `0-9`, `_` and `-` of the server's name for it. An empty list writes nothing.\n */\n beginTurn(signal: AbortSignal): Promise<readonly string[]>;\n /** Called once the turn has written the notices, so a component can hold back what it told until then. */\n commitNotices?(): void;\n}\n"]}
package/llms.txt CHANGED
@@ -43,6 +43,9 @@ The sections of README.md and every public export, generated from this package's
43
43
  - [A turn that ends `done` runs the project's checks, and the diff flags are recorded, never fatal](README.md#a-turn-that-ends-done-runs-the-projects-checks-and-the-diff-flags-are-recorded-never-fatal)
44
44
  - [An extension adds hooks and tools in the harness's own process, and project trust only gates loading](README.md#an-extension-adds-hooks-and-tools-in-the-harnesss-own-process-and-project-trust-only-gates-loading)
45
45
  - [MCP servers connect side by side, each in its own era, and their tools wait behind tool search](README.md#mcp-servers-connect-side-by-side-each-in-its-own-era-and-their-tools-wait-behind-tool-search)
46
+ - [A remote server is reached over HTTPS to a public address, and every byte it sends is bounded](README.md#a-remote-server-is-reached-over-https-to-a-public-address-and-every-byte-it-sends-is-bounded)
47
+ - [Servers connect in the background, and the first turn waits only for `direct` servers](README.md#servers-connect-in-the-background-and-the-first-turn-waits-only-for-direct-servers)
48
+ - [A tool runs only while its definition matches its pin, and a change waits for the next turn](README.md#a-tool-runs-only-while-its-definition-matches-its-pin-and-a-change-waits-for-the-next-turn)
46
49
  - [A skill is a file the model reads, and only its name, description and path are in the prompt](README.md#a-skill-is-a-file-the-model-reads-and-only-its-name-description-and-path-are-in-the-prompt)
47
50
  - [`AGENTS.md`, `CLAUDE.md` and the plan files lead every request, labelled untrusted](README.md#agentsmd-claudemd-and-the-plan-files-lead-every-request-labelled-untrusted)
48
51
  - [A call that needs a person is a signed pause that any process with the key file can resume](README.md#a-call-that-needs-a-person-is-a-signed-pause-that-any-process-with-the-key-file-can-resume)
@@ -234,6 +237,7 @@ The sections of README.md and every public export, generated from this package's
234
237
  - `toolSearchTool()`: The `tool_search` tool: it searches the registry's `deferred` tools by the words of a query, records the best matches in `options.activated` and tells the model their names, plus the descriptions of trusted tools.
235
238
  - `type ToolSource`: Where a tool comes from: the harness, an in-process extension, one MCP server (`mcp:<server>`) or the client.
236
239
  - `type ToolWrapper`: Wraps one registered tool's definition for a turn: a write cap, shadow mode or a sandbox binding, with the turn's host context.
240
+ - `interface TurnBoundary`: A component that changes a session's tools only between turns, such as the MCP client.
237
241
 
238
242
  ## Exports from `@buildanagent/harness/mcp`
239
243
 
@@ -244,15 +248,24 @@ The sections of README.md and every public export, generated from this package's
244
248
  - `interface McpCallResult`: What one tool call returned.
245
249
  - `interface McpChannel`: A message channel to a server in this process, such as an `InMemoryTransport` from `@modelcontextprotocol/server`.
246
250
  - `interface McpConnection`: One connected server.
251
+ - `interface McpEgressFetch`: The part of an egress proxy a remote server's requests go through: `startEgressProxy()` returns one.
247
252
  - `type McpEra`: The protocol era a server speaks: the 2026-07-28 revision, or `legacy` for the 2025 revisions and their `initialize`.
248
253
  - `class McpError`: Thrown for a server that could not connect (`mcp_connect_failed`), a tool list the harness refuses (`mcp_tool_list_refused`) and a tool call that ended with no result (`mcp_call_failed`, with `failure` saying why).
254
+ - `interface McpHttpTransport`: A server reached over MCP's streamable HTTP transport: each message is a `POST`, and the answer is JSON or a server-sent event stream.
249
255
  - `interface McpInProcessTransport`: A server in this process, reached through a channel the host built.
250
256
  - `interface McpManager`: The MCP client as one removable component: it connects the servers and registers their tools.
251
257
  - `interface McpManagerOptions`: What `createMcpManager()` takes.
258
+ - `interface McpPendingTool`: A tool whose current definition has no matching pin, so it waits for a person's approval.
259
+ - `interface McpPinStore`: Where the approved definitions of each server's tools are kept: for each server, its tool names and the hash of each one's definition.
260
+ - `interface McpRemoteSettings`: The settings a remote server shares, over streamable HTTP or legacy SSE.
252
261
  - `interface McpServerConfig`: One MCP server the harness connects to.
253
262
  - `type McpServerStatus`: How one server's connection went.
263
+ - `interface McpSseTransport`: A server reached over the HTTP+SSE transport of the 2024-11-05 revision, which MCP has deprecated since 2025-03-26.
254
264
  - `interface McpStdioTransport`: A server the harness starts as a child process and speaks to over its standard input and output, one JSON message per line.
265
+ - `interface McpTimers`: The timers the MCP client waits with, so a test can run its waits on a clock of its own.
255
266
  - `interface McpTool`: A tool as a server lists it.
267
+ - `type McpToolState`: How a server's current definition of a tool compares with its pin.
268
+ - `memoryMcpPinStore()`: A pin store in memory, for a host that keeps approvals for the life of the process, and for tests.
256
269
 
257
270
  ## Exports from `@buildanagent/harness/permissions`
258
271
 
@@ -399,6 +412,7 @@ The sections of README.md and every public export, generated from this package's
399
412
  - `interface DiscoveredSkills`: The skills found, what to record about them, and why any were left out.
400
413
  - `discoverSkills()`: Finds the skills of the project `cwd` is in: each folder under `.agents/skills` holding a `SKILL.md`, in `cwd` and every folder above it up to the repository root (the first folder with a `.git`).
401
414
  - `interface DiscoverSkillsOptions`: The settings of `discoverSkills()`.
415
+ - `fileMcpPinStore()`: A pin store over the lock file at `lockFile`, such as `.agents/extensions.lock.json`.
402
416
  - `fileTrustStore()`: A trust store in the file at `file`, created on the first `trust()`.
403
417
  - `interface FoundContextFiles`: The context files found, and why any were skipped.
404
418
  - `hashExtensionDir()`: The hash of an extension folder: `sha256:` and the digest over each file's path and content digest, in sorted order.
@@ -407,9 +421,11 @@ The sections of README.md and every public export, generated from this package's
407
421
  - `pinProjectExtensions()`: Writes the lock file for every extension folder as it is now.
408
422
  - `planFileSource()`: A plan source that reads `.agents/plan.md` and `.agents/progress.json` under `root` each time it is called.
409
423
  - `interface ProjectExtensions`: The extensions a project supplied, what to record about them, and why any were skipped.
410
- - `readLock()`: The pins in a lock file, by extension folder name, or `undefined` when there is no lock file.
424
+ - `readLock()`: The pins in a lock file, by extension folder name, or `undefined` when there is no lock file or it pins no extension, because it holds MCP pins alone.
425
+ - `readMcpPins()`: The MCP pins of one server in a lock file, by tool name, or `undefined` when it holds none for the server.
411
426
  - `realPathTrustStore()`: A trust store in memory, for tests and for a host that decides trust itself, that resolves each folder to its real path when the store is built and when `trust()` adds it.
412
- - `writeLock()`: Writes the lock file for these pins, replacing the old one in one step.
427
+ - `writeLock()`: Writes the lock file for these extension pins, keeping its MCP pins, and replaces the old file in one step.
428
+ - `writeMcpPins()`: Replaces the MCP pins of one server in a lock file, keeping every other member.
413
429
 
414
430
  ## Exports from `@buildanagent/harness/memory`
415
431
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@buildanagent/harness",
3
- "version": "0.1.0-alpha.30",
3
+ "version": "0.1.0-alpha.31",
4
4
  "description": "The buildanagent harness: the session log, context policy, tools, permissions, sandbox and credentials around the SDK's loop.",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "repository": {
@@ -103,14 +103,15 @@
103
103
  "@anthropic-ai/sandbox-runtime": "0.0.83",
104
104
  "@earendil-works/pi-schema": "1.5.2",
105
105
  "@modelcontextprotocol/client": "2.4.0",
106
- "@buildanagent/agent-safety": "0.1.0-alpha.30",
107
- "@buildanagent/protocol": "0.1.0-alpha.30",
108
- "@buildanagent/sdk": "0.1.0-alpha.30",
109
- "@buildanagent/gateway": "0.1.0-alpha.30"
106
+ "@buildanagent/agent-safety": "0.1.0-alpha.31",
107
+ "@buildanagent/protocol": "0.1.0-alpha.31",
108
+ "@buildanagent/gateway": "0.1.0-alpha.31",
109
+ "@buildanagent/sdk": "0.1.0-alpha.31"
110
110
  },
111
111
  "devDependencies": {
112
112
  "@modelcontextprotocol/server": "2.4.0",
113
- "json-rpc-2.0": "1.8.1"
113
+ "json-rpc-2.0": "1.8.1",
114
+ "miniflare": "5.20261103.0-beta"
114
115
  },
115
116
  "scripts": {
116
117
  "build": "node ../../scripts/clean-dist.mjs && tsc -p tsconfig.build.json",