@buildanagent/sdk 0.1.0-alpha.8 → 0.1.0-alpha.9

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 (51) hide show
  1. package/README.md +55 -4
  2. package/dist/compose.d.ts +2 -1
  3. package/dist/compose.js +10 -4
  4. package/dist/compose.js.map +1 -1
  5. package/dist/errors.d.ts +2 -1
  6. package/dist/errors.js +2 -1
  7. package/dist/errors.js.map +1 -1
  8. package/dist/events.d.ts +18 -4
  9. package/dist/events.js +1 -0
  10. package/dist/events.js.map +1 -1
  11. package/dist/hook-checks.js +17 -0
  12. package/dist/hook-checks.js.map +1 -1
  13. package/dist/hook-runner.d.ts +10 -0
  14. package/dist/hook-runner.js +86 -9
  15. package/dist/hook-runner.js.map +1 -1
  16. package/dist/hooks.d.ts +9 -4
  17. package/dist/hooks.js.map +1 -1
  18. package/dist/index.d.ts +9 -3
  19. package/dist/index.js +7 -2
  20. package/dist/index.js.map +1 -1
  21. package/dist/loop.d.ts +5 -0
  22. package/dist/loop.js +26 -3
  23. package/dist/loop.js.map +1 -1
  24. package/dist/otel/observer.js +14 -0
  25. package/dist/otel/observer.js.map +1 -1
  26. package/dist/pauses.d.ts +32 -0
  27. package/dist/pauses.js +46 -0
  28. package/dist/pauses.js.map +1 -0
  29. package/dist/result.d.ts +27 -3
  30. package/dist/result.js.map +1 -1
  31. package/dist/run.d.ts +19 -3
  32. package/dist/run.js +17 -1
  33. package/dist/run.js.map +1 -1
  34. package/dist/tools/pipeline.d.ts +19 -3
  35. package/dist/tools/pipeline.js +24 -5
  36. package/dist/tools/pipeline.js.map +1 -1
  37. package/dist/vendor/agent-safety/bytes.d.ts +17 -0
  38. package/dist/vendor/agent-safety/bytes.js +59 -0
  39. package/dist/vendor/agent-safety/bytes.js.map +1 -0
  40. package/dist/vendor/agent-safety/errors.d.ts +8 -4
  41. package/dist/vendor/agent-safety/errors.js +2 -2
  42. package/dist/vendor/agent-safety/errors.js.map +1 -1
  43. package/dist/vendor/agent-safety/hash.js +3 -2
  44. package/dist/vendor/agent-safety/hash.js.map +1 -1
  45. package/dist/vendor/agent-safety/pending.d.ts +119 -0
  46. package/dist/vendor/agent-safety/pending.js +122 -0
  47. package/dist/vendor/agent-safety/pending.js.map +1 -0
  48. package/dist/vendor/agent-safety/signer.d.ts +42 -0
  49. package/dist/vendor/agent-safety/signer.js +128 -0
  50. package/dist/vendor/agent-safety/signer.js.map +1 -0
  51. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"hook-runner.js","sourceRoot":"","sources":["../src/hook-runner.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EACL,aAAa,EACb,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,GAElB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAkC,aAAa,EAAwB,MAAM,qBAAqB,CAAC;AAG1G,uHAAuH;AACvH,MAAM,OAAO,WAAY,SAAQ,QAAQ;IACrB,IAAI,GAAG,aAAa,CAAC;IAC9B,IAAI,CAAS;IAEtB,YAAY,IAAY,EAAE,KAAc;QACtC,KAAK,CAAC,aAAa,EAAE,OAAO,IAAI,iBAAiB,SAAS,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAChF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF;AAED,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAQD,+GAA+G;AAC/G,SAAS,WAAW,CAAC,IAAY,EAAE,MAAkB,EAAE,KAA0C;IAC/F,IA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AM,CACV,IAAY,EACZ,IAA0B,EAC1B,MAA8B;QAE9B,IAAI,CAAC;YACH,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,IAAI,EAAE,EAAE,CAAC;QAC/C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,0GAA0G;YAC1G,+FAA+F;YAC/F,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,qBAAqB;gBAAE,MAAM,KAAK,CAAC;YAC3E,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACxE,IAAI,IAAI,CAAC,UAAU;gBAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;YAClD,IAAI,MAAM,KAAK,SAAS;gBAAE,MAAM,IAAI,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAC7D,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QACpD,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Runs the interceptors for one run: builds each hook's frozen event, applies the failure policy, checks what the\n * hook returned and emits `hook_error` and `context_transformed`. The loop and the tool pipeline call it at each\n * moment and never look at the hooks themselves.\n *\n * Failure policy (D6): a hook that throws is reported as a `hook_error` event. Under `fail_closed`, the default, a\n * failed gate denies its call, a failed `afterToolCall` withholds the result, and any other failed hook throws a\n * `HookFailure`, which the loop turns into an `error` result. Under `continue` the failed hook is skipped.\n */\nimport type { AssistantMessage, Message, ModelContext, ModelRef, Usage } from \"@buildanagent/gateway\";\nimport { isSdkError, SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport { frozenCopy, thawedCopy } from \"./freeze.js\";\nimport {\n checkDecision,\n checkMessages,\n checkModelPatch,\n checkReplacement,\n checkResultPatch,\n checkStopDecision,\n type StopVerdict,\n} from \"./hook-checks.js\";\nimport type { CallOptions, GateDecision, HookEventBase, Interceptors, ModelCallPatch } from \"./hooks.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { type AnyTool, type GateOutcome, isContentList, type PipelineContext } from \"./tools/pipeline.js\";\nimport type { ToolCall, ToolResult } from \"./tools/types.js\";\n\n/** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */\nexport class HookFailure extends SdkError {\n override readonly name = \"HookFailure\";\n readonly hook: string;\n\n constructor(hook: string, cause: unknown) {\n super(\"hook_failed\", `the ${hook} hook failed: ${messageOf(cause)}`, { cause });\n this.hook = hook;\n }\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** How a guarded hook call ended: it returned, it failed and the run skips it, or it failed and a result stands in. */\ntype Guarded<T, R> =\n | { readonly status: \"ok\"; readonly value: T }\n | { readonly status: \"skipped\" }\n | { readonly status: \"closed\"; readonly value: R };\n\n/** The result of a call after `afterToolCall` returned `patch`, checked to still be one the model can read. */\nfunction mergeResult(tool: string, result: ToolResult, patch: Record<string, unknown> | undefined): ToolResult {\n if (patch === undefined) return result;\n const merged = { ...result, ...patch } as ToolResult;\n if (!isContentList(merged.content)) {\n throw new SdkError(\n \"invalid_hook_result\",\n `afterToolCall for \"${tool}\" returned content that is not a list of text and image blocks`,\n );\n }\n return merged;\n}\n\n/** What a run gives its hook runner. */\nexport interface HookRunnerSetup {\n readonly interceptors: Interceptors;\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n /** The index of the model call in progress. */\n stepIndex(): number;\n send(body: AgentEventBody): void;\n}\n\nfunction blocked(text: string, details: Record<string, unknown>): ToolResult {\n return { content: [{ type: \"text\", text }], isError: true, details };\n}\n\n/** The pipeline hooks that the interceptors fill, left out when no interceptor needs them. */\nexport type PipelineHooks = Pick<PipelineContext, \"gate\" | \"after\">;\n\nfunction gateOutcome(tool: string, decision: GateDecision): GateOutcome | undefined {\n if (decision.decision === \"allow\")\n return decision.input === undefined ? undefined : { input: thawedCopy(decision.input) };\n if (decision.decision === \"deny\") {\n return { blocked: blocked(`Tool call \"${tool}\" was denied: ${decision.reason}`, { decision: \"deny\" }) };\n }\n const why = decision.reason === undefined ? \"\" : ` (${decision.reason})`;\n const text = `Tool call \"${tool}\" needs approval${why}, and this run can't ask for it, so it was not run.`;\n return {\n blocked: blocked(text, { decision: \"ask\", ...(decision.reason === undefined ? {} : { reason: decision.reason }) }),\n };\n}\n\n/** Runs one run's interceptors. */\nexport class HookRunner {\n readonly #setup: HookRunnerSetup;\n readonly #hooks: Interceptors;\n readonly #continues: boolean;\n\n constructor(setup: HookRunnerSetup) {\n this.#setup = setup;\n this.#hooks = setup.interceptors;\n this.#continues = setup.interceptors.onFailure === \"continue\";\n }\n\n /** The gate and the after-hook, for the tool pipeline. */\n pipelineHooks(): PipelineHooks {\n return {\n ...(this.#hooks.beforeToolCall === undefined ? {} : { gate: (e) => this.#gate(e) }),\n ...(this.#hooks.afterToolCall === undefined ? {} : { after: (e) => this.#afterTool(e) }),\n };\n }\n\n /** The messages `transformContext` chose for this call, or undefined to send the transcript as it is. */\n async transformContext(input: {\n system: string;\n messages: readonly Message[];\n model: ModelRef;\n lastUsage: Usage | undefined;\n }): Promise<Message[] | undefined> {\n const hook = this.#hooks.transformContext;\n if (hook === undefined) return undefined;\n const { lastUsage, ...rest } = input;\n const event = this.#event({ ...rest, ...(lastUsage === undefined ? {} : { lastUsage }) });\n const guarded = await this.#guard(\"transformContext\", () => hook(event));\n if (guarded.status !== \"ok\") return undefined;\n const messages = checkMessages(\"transformContext\", guarded.value);\n this.#setup.send({ type: \"context_transformed\", before: input.messages.length, after: messages.length });\n return messages;\n }\n\n /** What `beforeModelCall` changed, if anything. */\n async beforeModelCall(input: { context: ModelContext; options: CallOptions }): Promise<ModelCallPatch | undefined> {\n const hook = this.#hooks.beforeModelCall;\n if (hook === undefined) return undefined;\n const event = this.#event(input);\n const guarded = await this.#guard(\"beforeModelCall\", () => hook(event));\n return guarded.status === \"ok\" ? checkModelPatch(guarded.value) : undefined;\n }\n\n /** The response the run goes on with: `afterModelCall`'s replacement, or `message` itself. */\n async afterModelCall(message: AssistantMessage): Promise<AssistantMessage> {\n const hook = this.#hooks.afterModelCall;\n if (hook === undefined) return message;\n const event = this.#event({ message });\n const guarded = await this.#guard(\"afterModelCall\", () => hook(event));\n return (guarded.status === \"ok\" ? checkReplacement(guarded.value) : undefined) ?? message;\n }\n\n /** What `shouldStop` decided. */\n async shouldStop(input: { messages: readonly Message[]; lastMessage: AssistantMessage }): Promise<StopVerdict> {\n const hook = this.#hooks.shouldStop;\n if (hook === undefined) return { kind: \"none\" };\n const event = this.#event(input);\n const guarded = await this.#guard(\"shouldStop\", () => hook(event));\n return guarded.status === \"ok\" ? checkStopDecision(guarded.value) : { kind: \"none\" };\n }\n\n async #gate(input: { call: ToolCall; tool: AnyTool; input: unknown }): Promise<GateOutcome | undefined> {\n const hook = this.#hooks.beforeToolCall;\n if (hook === undefined) return undefined;\n const { call, tool } = input;\n const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input }, call.callId);\n const failed = (error: unknown): GateOutcome => ({\n blocked: blocked(`Tool call \"${tool.name}\" was not run, because its permission check failed.`, {\n hook: \"beforeToolCall\",\n error: messageOf(error),\n }),\n });\n const guarded = await this.#guard(\"beforeToolCall\", () => hook(event), failed);\n if (guarded.status === \"skipped\") return undefined;\n return guarded.status === \"closed\" ? guarded.value : gateOutcome(tool.name, checkDecision(guarded.value));\n }\n\n async #afterTool(input: { call: ToolCall; tool: AnyTool; input: unknown; result: ToolResult }): Promise<ToolResult> {\n const hook = this.#hooks.afterToolCall;\n const { call, tool, result } = input;\n if (hook === undefined) return result;\n const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input, result }, call.callId);\n // The tool already ran, so the stand-in says so and keeps the write outcome: a model told only \"withheld\" would\n // retry a write that was applied.\n const withheld = (error: unknown): ToolResult => ({\n ...blocked(`Tool call \"${tool.name}\" ran, but its result was withheld, because its result check failed.`, {\n hook: \"afterToolCall\",\n error: messageOf(error),\n }),\n ...(result.outcome === undefined ? {} : { outcome: result.outcome }),\n });\n const guarded = await this.#guard(\"afterToolCall\", () => hook(event), withheld);\n if (guarded.status === \"skipped\") return result;\n return guarded.status === \"closed\"\n ? guarded.value\n : mergeResult(tool.name, result, checkResultPatch(guarded.value));\n }\n\n #event<P extends object>(payload: P, callId?: string): Readonly<HookEventBase & P> {\n const { runId, signal, clock } = this.#setup;\n return Object.freeze({\n runId,\n stepIndex: this.#setup.stepIndex(),\n ...(callId === undefined ? {} : { callId }),\n signal,\n timestamp: clock.now(),\n ...frozenCopy(payload),\n }) as Readonly<HookEventBase & P>;\n }\n\n /** Calls a hook under the failure policy. Without `closed`, a failure under `fail_closed` throws a `HookFailure`. */\n async #guard<T, R = never>(\n hook: string,\n call: () => T | Promise<T>,\n closed?: (error: unknown) => R,\n ): Promise<Guarded<Awaited<T>, R>> {\n try {\n return { status: \"ok\", value: await call() };\n } catch (error) {\n // A wrong return shape is a programmer error whatever the policy, even when a joined hook found it inside\n // `composeInterceptors()`: skipping or closing on it would let a typo in a gate pass silently.\n if (isSdkError(error) && error.code === \"invalid_hook_result\") throw error;\n this.#setup.send({ type: \"hook_error\", hook, error: messageOf(error) });\n if (this.#continues) return { status: \"skipped\" };\n if (closed === undefined) throw new HookFailure(hook, error);\n return { status: \"closed\", value: closed(error) };\n }\n }\n}\n"]}
1
+ {"version":3,"file":"hook-runner.js","sourceRoot":"","sources":["../src/hook-runner.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EACL,aAAa,EACb,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,GAElB,MAAM,kBA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AC;YACf,0GAA0G;YAC1G,+FAA+F;YAC/F,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,qBAAqB;gBAAE,MAAM,KAAK,CAAC;YAC3E,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACxE,IAAI,IAAI,CAAC,UAAU;gBAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;YAClD,IAAI,MAAM,KAAK,SAAS;gBAAE,MAAM,IAAI,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAC7D,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QACpD,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Runs the interceptors for one run: builds each hook's frozen event, applies the failure policy, checks what the\n * hook returned and emits `hook_error` and `context_transformed`. The loop and the tool pipeline call it at each\n * moment and never look at the hooks themselves.\n *\n * Failure policy (D6): a hook that throws is reported as a `hook_error` event. Under `fail_closed`, the default, a\n * failed gate denies its call, a failed `afterToolCall` withholds the result, and any other failed hook throws a\n * `HookFailure`, which the loop turns into an `error` result. Under `continue` the failed hook is skipped.\n *\n * A gate's `ask` pauses its call (D5): the runner signs a pending request through the one signing path, over the\n * input the call would run with, and hands the request and that input to the pipeline, which reports the pause once\n * every call of the step has been gated. A pause that can't be signed never pauses unsigned: the call is blocked\n * instead, whatever `onFailure` says.\n */\nimport type { AssistantMessage, Message, ModelContext, ModelRef, Usage } from \"@buildanagent/gateway\";\nimport { isSdkError, SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport { frozenCopy, thawedCopy } from \"./freeze.js\";\nimport {\n checkDecision,\n checkMessages,\n checkModelPatch,\n checkReplacement,\n checkResultPatch,\n checkStopDecision,\n type StopVerdict,\n} from \"./hook-checks.js\";\nimport type { CallOptions, GateDecision, HookEventBase, Interceptors, ModelCallPatch } from \"./hooks.js\";\nimport { signPause } from \"./pauses.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { preparedSchemaOf } from \"./tools/define.js\";\nimport { type AnyTool, type GateOutcome, isContentList, type PipelineContext } from \"./tools/pipeline.js\";\nimport type { ToolCall, ToolResult } from \"./tools/types.js\";\nimport { isSafetyError, type SafetyErrorCode } from \"./vendor/agent-safety/errors.js\";\nimport type { SignedPendingRequest } from \"./vendor/agent-safety/pending.js\";\nimport type { ApprovalSigner } from \"./vendor/agent-safety/signer.js\";\n\n/** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */\nexport class HookFailure extends SdkError {\n override readonly name = \"HookFailure\";\n readonly hook: string;\n\n constructor(hook: string, cause: unknown) {\n super(\"hook_failed\", `the ${hook} hook failed: ${messageOf(cause)}`, { cause });\n this.hook = hook;\n }\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** How a guarded hook call ended: it returned, it failed and the run skips it, or it failed and a result stands in. */\ntype Guarded<T, R> =\n | { readonly status: \"ok\"; readonly value: T }\n | { readonly status: \"skipped\" }\n | { readonly status: \"closed\"; readonly value: R };\n\n/** The result of a call after `afterToolCall` returned `patch`, checked to still be one the model can read. */\nfunction mergeResult(tool: string, result: ToolResult, patch: Record<string, unknown> | undefined): ToolResult {\n if (patch === undefined) return result;\n const merged = { ...result, ...patch } as ToolResult;\n if (!isContentList(merged.content)) {\n throw new SdkError(\n \"invalid_hook_result\",\n `afterToolCall for \"${tool}\" returned content that is not a list of text and image blocks`,\n );\n }\n return merged;\n}\n\n/** What a run gives its hook runner. */\nexport interface HookRunnerSetup {\n readonly interceptors: Interceptors;\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n /** The index of the model call in progress. */\n stepIndex(): number;\n send(body: AgentEventBody): void;\n /** Signs the pending request a gate's `ask` writes. */\n readonly signer: ApprovalSigner;\n /** Makes each pending request's id. */\n readonly nextId: () => string;\n}\n\n/** The decision of a gate that asks for a person. */\ntype AskDecision = Extract<GateDecision, { decision: \"ask\" }>;\n\nfunction blocked(text: string, details: Record<string, unknown>): ToolResult {\n return { content: [{ type: \"text\", text }], isError: true, details };\n}\n\n/** The pipeline hooks that the interceptors fill, left out when no interceptor needs them. */\nexport type PipelineHooks = Pick<PipelineContext, \"gate\" | \"after\">;\n\nfunction gateOutcome(tool: string, decision: Exclude<GateDecision, AskDecision>): GateOutcome | undefined {\n if (decision.decision === \"allow\")\n return decision.input === undefined ? undefined : { input: thawedCopy(decision.input) };\n return { blocked: blocked(`Tool call \"${tool}\" was denied: ${decision.reason}`, { decision: \"deny\" }) };\n}\n\nconst SAFETY_CODES: readonly string[] = [\n \"invalid_outcome\",\n \"invalid_input\",\n \"invalid_key_ring\",\n \"invalid_pending\",\n] satisfies readonly SafetyErrorCode[];\n\n/**\n * Why a pause could not be signed, as reports may show it: one of the safety package's error codes, or a fixed word.\n * A custom signer's own text is never passed on, because nothing stops it from quoting key material, and that holds\n * for a `code` too: any object can carry the safety error's marker, so only a known code is trusted.\n */\nfunction unsignedCause(error: unknown): string {\n return isSafetyError(error) && SAFETY_CODES.includes(error.code) ? error.code : \"signer_failed\";\n}\n\n/** Runs one run's interceptors. */\nexport class HookRunner {\n readonly #setup: HookRunnerSetup;\n readonly #hooks: Interceptors;\n readonly #continues: boolean;\n readonly #requestIds = new Set<string>();\n\n constructor(setup: HookRunnerSetup) {\n this.#setup = setup;\n this.#hooks = setup.interceptors;\n this.#continues = setup.interceptors.onFailure === \"continue\";\n }\n\n /** The gate and the after-hook, for the tool pipeline. */\n pipelineHooks(): PipelineHooks {\n return {\n ...(this.#hooks.beforeToolCall === undefined ? {} : { gate: (e) => this.#gate(e) }),\n ...(this.#hooks.afterToolCall === undefined ? {} : { after: (e) => this.#afterTool(e) }),\n };\n }\n\n /** The messages `transformContext` chose for this call, or undefined to send the transcript as it is. */\n async transformContext(input: {\n system: string;\n messages: readonly Message[];\n model: ModelRef;\n lastUsage: Usage | undefined;\n }): Promise<Message[] | undefined> {\n const hook = this.#hooks.transformContext;\n if (hook === undefined) return undefined;\n const { lastUsage, ...rest } = input;\n const event = this.#event({ ...rest, ...(lastUsage === undefined ? {} : { lastUsage }) });\n const guarded = await this.#guard(\"transformContext\", () => hook(event));\n if (guarded.status !== \"ok\") return undefined;\n const messages = checkMessages(\"transformContext\", guarded.value);\n this.#setup.send({ type: \"context_transformed\", before: input.messages.length, after: messages.length });\n return messages;\n }\n\n /** What `beforeModelCall` changed, if anything. */\n async beforeModelCall(input: { context: ModelContext; options: CallOptions }): Promise<ModelCallPatch | undefined> {\n const hook = this.#hooks.beforeModelCall;\n if (hook === undefined) return undefined;\n const event = this.#event(input);\n const guarded = await this.#guard(\"beforeModelCall\", () => hook(event));\n return guarded.status === \"ok\" ? checkModelPatch(guarded.value) : undefined;\n }\n\n /** The response the run goes on with: `afterModelCall`'s replacement, or `message` itself. */\n async afterModelCall(message: AssistantMessage): Promise<AssistantMessage> {\n const hook = this.#hooks.afterModelCall;\n if (hook === undefined) return message;\n const event = this.#event({ message });\n const guarded = await this.#guard(\"afterModelCall\", () => hook(event));\n return (guarded.status === \"ok\" ? checkReplacement(guarded.value) : undefined) ?? message;\n }\n\n /** What `shouldStop` decided. */\n async shouldStop(input: { messages: readonly Message[]; lastMessage: AssistantMessage }): Promise<StopVerdict> {\n const hook = this.#hooks.shouldStop;\n if (hook === undefined) return { kind: \"none\" };\n const event = this.#event(input);\n const guarded = await this.#guard(\"shouldStop\", () => hook(event));\n return guarded.status === \"ok\" ? checkStopDecision(guarded.value) : { kind: \"none\" };\n }\n\n async #gate(input: { call: ToolCall; tool: AnyTool; input: unknown }): Promise<GateOutcome | undefined> {\n const hook = this.#hooks.beforeToolCall;\n if (hook === undefined) return undefined;\n const { call, tool } = input;\n const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input }, call.callId);\n const failed = (error: unknown): GateOutcome => ({\n blocked: blocked(`Tool call \"${tool.name}\" was not run, because its permission check failed.`, {\n hook: \"beforeToolCall\",\n error: messageOf(error),\n }),\n });\n const guarded = await this.#guard(\"beforeToolCall\", () => hook(event), failed);\n if (guarded.status === \"skipped\") return undefined;\n if (guarded.status === \"closed\") return guarded.value;\n const decision = checkDecision(guarded.value);\n return decision.decision === \"ask\"\n ? this.#pause(call, tool, input.input, decision)\n : gateOutcome(tool.name, decision);\n }\n\n /**\n * Signs the pending request for a call a gate asked about and returns it with the input it signs. That input is the\n * one the call would run with: the checked input the gate saw, or the `ask`'s own replacement, which must pass the\n * tool's schema like an `allow`'s. If signing fails, the call is blocked: a pause that no signature covers is never\n * written.\n */\n async #pause(call: ToolCall, tool: AnyTool, seen: unknown, decision: AskDecision): Promise<GateOutcome> {\n const { signer, clock } = this.#setup;\n const { reason, policyVersion } = decision;\n const input = thawedCopy(decision.input === undefined ? seen : await this.#replacement(tool, decision.input));\n let request: SignedPendingRequest;\n try {\n request = await signPause(\n {\n kind: \"approval\",\n callId: call.callId,\n tool: tool.name,\n input,\n ...(policyVersion === undefined ? {} : { policyVersion }),\n // Display text only, so a blank reason is left out rather than failing the signature.\n ...(reason === undefined || reason === \"\" ? {} : { reason }),\n },\n signer,\n { generateId: () => this.#requestId(), now: () => new Date(clock.now()) },\n );\n } catch (error) {\n return this.#unsigned(tool.name, unsignedCause(error));\n }\n // A resolution names its request by id, so two pending requests of one run must never share one.\n if (this.#requestIds.has(request.id)) return this.#unsigned(tool.name, \"duplicate_request_id\");\n this.#requestIds.add(request.id);\n return { paused: request, input };\n }\n\n /**\n * The next request id from the run's `idGenerator`. A generator that repeats an id, such as one that always returns\n * a session id, was enough for a run id alone, so a repeat of the run id or of an earlier request's id falls back to\n * a random UUID instead of blocking the call.\n */\n #requestId(): string {\n const id = this.#setup.nextId();\n return id === this.#setup.runId || this.#requestIds.has(id) ? globalThis.crypto.randomUUID() : id;\n }\n\n /**\n * An `ask`'s replacement input, checked against the tool's schema, because a call must never run with input its own\n * tool would reject.\n */\n async #replacement(tool: AnyTool, input: unknown): Promise<unknown> {\n const checked = await preparedSchemaOf(tool).validate(input);\n if (checked.ok) return checked.value;\n const issues = checked.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join(\"; \");\n throw new SdkError(\n \"invalid_hook_result\",\n `beforeToolCall asked about tool \"${tool.name}\" with an input its schema rejects: ${issues}`,\n );\n }\n\n /** Blocks a call whose pause could not be signed, and reports why without the signer's own message. */\n #unsigned(tool: string, cause: string): GateOutcome {\n this.#setup.send({\n type: \"hook_error\",\n hook: \"signer\",\n error: `the approval request could not be signed (${cause})`,\n });\n const text = `Tool call \"${tool}\" needs approval, but its approval request could not be signed, so it was not run.`;\n return { blocked: blocked(text, { decision: \"ask\", error: cause }) };\n }\n\n async #afterTool(input: { call: ToolCall; tool: AnyTool; input: unknown; result: ToolResult }): Promise<ToolResult> {\n const hook = this.#hooks.afterToolCall;\n const { call, tool, result } = input;\n if (hook === undefined) return result;\n const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input, result }, call.callId);\n // The tool already ran, so the stand-in says so and keeps the write outcome: a model told only \"withheld\" would\n // retry a write that was applied.\n const withheld = (error: unknown): ToolResult => ({\n ...blocked(`Tool call \"${tool.name}\" ran, but its result was withheld, because its result check failed.`, {\n hook: \"afterToolCall\",\n error: messageOf(error),\n }),\n ...(result.outcome === undefined ? {} : { outcome: result.outcome }),\n });\n const guarded = await this.#guard(\"afterToolCall\", () => hook(event), withheld);\n if (guarded.status === \"skipped\") return result;\n return guarded.status === \"closed\"\n ? guarded.value\n : mergeResult(tool.name, result, checkResultPatch(guarded.value));\n }\n\n #event<P extends object>(payload: P, callId?: string): Readonly<HookEventBase & P> {\n const { runId, signal, clock } = this.#setup;\n return Object.freeze({\n runId,\n stepIndex: this.#setup.stepIndex(),\n ...(callId === undefined ? {} : { callId }),\n signal,\n timestamp: clock.now(),\n ...frozenCopy(payload),\n }) as Readonly<HookEventBase & P>;\n }\n\n /** Calls a hook under the failure policy. Without `closed`, a failure under `fail_closed` throws a `HookFailure`. */\n async #guard<T, R = never>(\n hook: string,\n call: () => T | Promise<T>,\n closed?: (error: unknown) => R,\n ): Promise<Guarded<Awaited<T>, R>> {\n try {\n return { status: \"ok\", value: await call() };\n } catch (error) {\n // A wrong return shape is a programmer error whatever the policy, even when a joined hook found it inside\n // `composeInterceptors()`: skipping or closing on it would let a typo in a gate pass silently.\n if (isSdkError(error) && error.code === \"invalid_hook_result\") throw error;\n this.#setup.send({ type: \"hook_error\", hook, error: messageOf(error) });\n if (this.#continues) return { status: \"skipped\" };\n if (closed === undefined) throw new HookFailure(hook, error);\n return { status: \"closed\", value: closed(error) };\n }\n }\n}\n"]}
package/dist/hooks.d.ts CHANGED
@@ -92,8 +92,12 @@ export interface ModelCallPatch {
92
92
  }
93
93
  /**
94
94
  * What `beforeToolCall` decides. `allow` runs the call, with `input` in place of the model's when given; the
95
- * replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask` asks a
96
- * person; until runs can pause, it blocks the call like `deny` with a message that says approval isn't available.
95
+ * replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask` pauses
96
+ * the call for a person: the run signs a pending request for it with the run's `signer`, and ends
97
+ * `awaiting_approval` once the step's other calls have their results. `reason` is shown to the approver and isn't
98
+ * signed; `policyVersion` is signed. An `ask` may carry an `input`, which must pass the tool's schema like an
99
+ * `allow`'s: the request is then signed over it, because it is the input the call would run with once approved.
100
+ * `composeInterceptors()` passes an earlier gate's replacement on this way when a later gate asks.
97
101
  */
98
102
  export type GateDecision = {
99
103
  readonly decision: "allow";
@@ -104,6 +108,7 @@ export type GateDecision = {
104
108
  readonly reason: string;
105
109
  } | {
106
110
  readonly decision: "ask";
111
+ readonly input?: unknown;
107
112
  readonly reason?: string;
108
113
  readonly policyVersion?: string;
109
114
  };
@@ -149,8 +154,8 @@ export interface Interceptors {
149
154
  /**
150
155
  * The gate: decides whether a tool call runs, once for each call that passed validation, one call at a time in
151
156
  * model order, and before any call of the step executes. With no `beforeToolCall`, no gate stands in the way and
152
- * every registered tool is allowed. A gate that returns `ask` pauses the run once pauses exist; until then `ask`
153
- * blocks the call. A gate that throws denies the call unless `onFailure` is `"continue"`. A gate must return a
157
+ * every registered tool is allowed. A gate that returns `ask` pauses the call, and the run ends `awaiting_approval`
158
+ * with a signed pending request for it. A gate that throws denies the call unless `onFailure` is `"continue"`. A gate must return a
154
159
  * decision: returning nothing throws an `SdkError` with code `invalid_hook_result`.
155
160
  */
156
161
  readonly beforeToolCall?: (e: ToolCallEvent) => MaybePromise<GateDecision>;
package/dist/hooks.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The hook types: six interceptors that can change a run, and the observer that only watches it. Each interceptor\n * takes one event object and returns a replacement, never mutating its input, because the event's data is frozen.\n */\nimport type {\n AssistantMessage,\n ContentBlock,\n Message,\n Model,\n ModelCallOptions,\n ModelContext,\n ModelRef,\n Usage,\n} from \"@buildanagent/gateway\";\nimport type { AgentEvent } from \"./events.js\";\nimport type { ToolResult } from \"./tools/types.js\";\n\n/** A value or a promise of one: a hook may be a plain function or an `async` one. */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * A value, or nothing: what a hook that may change something returns. `void` lets an `async` hook that has nothing\n * to change simply end, where `undefined` would force it to return explicitly.\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: a hook's return type, where void lets a function return nothing\nexport type OrNothing<T> = T | void;\n\n/** The options of one model call, without the abort signal, which the run supplies. */\nexport type CallOptions = Omit<ModelCallOptions, \"signal\">;\n\n/** The fields every hook event carries. */\nexport interface HookEventBase {\n /** The run's id. */\n readonly runId: string;\n /** The index of the model call the hook belongs to, counted from 0. */\n readonly stepIndex: number;\n /** The tool call's id, for the two tool hooks; absent for the others. */\n readonly callId?: string;\n /** The run's abort signal. Pass it on to any I/O the hook does. */\n readonly signal: AbortSignal;\n /** When the hook was called, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** What `transformContext` receives: the conversation as it stands before the model call. */\nexport interface ContextEvent extends HookEventBase {\n /** The system prompt. */\n readonly system: string;\n /** The whole conversation so far, never a view an earlier call's transform returned. */\n readonly messages: readonly Message[];\n /** The model the run was started with. */\n readonly model: ModelRef;\n /** The previous model call's usage. Absent on the first call. */\n readonly lastUsage?: Usage;\n}\n\n/** What `beforeModelCall` receives: the request about to be sent. */\nexport interface ModelCallEvent extends HookEventBase {\n /** The request: the system prompt, the messages `transformContext` returned and the tools this call sends. */\n readonly context: ModelContext;\n /** The options of this call, without the abort signal. */\n readonly options: CallOptions;\n}\n\n/** What `afterModelCall` receives: the model's finished response. */\nexport interface ModelResultEvent extends HookEventBase {\n /** The response, including a failed one, whose `stopReason` is `\"error\"`. */\n readonly message: AssistantMessage;\n}\n\n/** What `beforeToolCall` receives: a call whose input has passed the tool's schema. */\nexport interface ToolCallEvent extends HookEventBase {\n readonly callId: string;\n /** The tool's name. */\n readonly tool: string;\n /** The validated input. */\n readonly input: unknown;\n}\n\n/** What `afterToolCall` receives: the result of a call that executed, before the model reads it. */\nexport interface ToolResultEvent extends ToolCallEvent {\n readonly result: ToolResult;\n}\n\n/** What `shouldStop` receives, after a step's tool calls have their results. */\nexport interface StepEvent extends HookEventBase {\n /** The whole conversation so far, including this step's response and tool results. */\n readonly messages: readonly Message[];\n /** This step's model response. */\n readonly lastMessage: AssistantMessage;\n}\n\n/**\n * Changes to one model call's request. Every field is optional, and a change applies to that call only; the next\n * call starts again from the run's own settings.\n */\nexport interface ModelCallPatch {\n /** Replaces the system prompt for this call. */\n readonly system?: string;\n /** Replaces the messages sent for this call. The run's own transcript keeps its messages. */\n readonly messages?: readonly Message[];\n /**\n * The names of the tools to send, as the complete list: a tool left out is not sent, and a tool whose `exposure`\n * is `deferred` or `hidden` is sent when named. Tools always go out in definition order, whatever order this list\n * is in. A name that matches no tool throws an `SdkError` with code `invalid_hook_result`. A call to a tool that\n * was not sent gets the unknown-tool error.\n */\n readonly activeTools?: readonly string[];\n /** Makes this call with another model. */\n readonly model?: Model;\n /** Replaces the options of this call. */\n readonly options?: CallOptions;\n}\n\n/**\n * What `beforeToolCall` decides. `allow` runs the call, with `input` in place of the model's when given; the\n * replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask` asks a\n * person; until runs can pause, it blocks the call like `deny` with a message that says approval isn't available.\n */\nexport type GateDecision =\n | { readonly decision: \"allow\"; readonly input?: unknown; readonly reason?: string }\n | { readonly decision: \"deny\"; readonly reason: string }\n | { readonly decision: \"ask\"; readonly reason?: string; readonly policyVersion?: string };\n\n/**\n * Changes to a tool's result. Each field present replaces the result's own. A replaced `outcome` is not available\n * here: a write's outcome is rendered into `content` once, so replace `content` instead.\n */\nexport type ToolResultPatch = Partial<Omit<ToolResult, \"outcome\">>;\n\n/**\n * What `shouldStop` decides. `true` or `{ stop: \"hook\" }` ends the run `stopped`, with the reason as `stoppedBy`\n * (`\"hook\"` for `true`). `{ stop: \"no_progress\" }` ends it `no_progress`. `{ continue }` keeps a run going that the\n * model ended by answering in text, adding the content as a user message. When the model's step called tools, the run goes on anyway and the content is\n * not added, so a hook that must reach the model should return it after a text answer. `false` leaves the decision to the run.\n */\nexport type StopDecision =\n | boolean\n | { readonly continue: string | readonly ContentBlock[] }\n | { readonly stop: \"no_progress\" | \"hook\"; readonly reason: string };\n\n/**\n * The six interceptors, in the order a step calls them: `transformContext`, `beforeModelCall`, the model call,\n * `afterModelCall`, then for each tool call `beforeToolCall` and `afterToolCall`, and last `shouldStop`. A run takes\n * one object; `composeInterceptors()` joins several. Each hook may be `async`.\n */\nexport interface Interceptors {\n /**\n * Returns the messages to send for this model call, such as a masked or summarised view of a long conversation.\n * The view reaches that call's request only: the next call's event, `result.messages` and `result.context` hold\n * the full history. Each call emits a `context_transformed` event with the message counts.\n */\n readonly transformContext?: (e: ContextEvent) => MaybePromise<readonly Message[]>;\n /** Changes the request about to be sent. Return nothing to leave it as it is. */\n readonly beforeModelCall?: (e: ModelCallEvent) => MaybePromise<OrNothing<ModelCallPatch>>;\n /**\n * Replaces the model's response. The transcript and the `model_call_end` event hold the replacement, and its tool\n * calls are the ones that run. The call's usage and cost stay those of the model's own response. If it throws\n * while the run fails closed, both hold an empty stand-in with `stopReason: \"error\"` and that usage and cost.\n */\n readonly afterModelCall?: (e: ModelResultEvent) => MaybePromise<OrNothing<{ readonly message?: AssistantMessage }>>;\n /**\n * The gate: decides whether a tool call runs, once for each call that passed validation, one call at a time in\n * model order, and before any call of the step executes. With no `beforeToolCall`, no gate stands in the way and\n * every registered tool is allowed. A gate that returns `ask` pauses the run once pauses exist; until then `ask`\n * blocks the call. A gate that throws denies the call unless `onFailure` is `\"continue\"`. A gate must return a\n * decision: returning nothing throws an `SdkError` with code `invalid_hook_result`.\n */\n readonly beforeToolCall?: (e: ToolCallEvent) => MaybePromise<GateDecision>;\n /**\n * Replaces fields of a result before the model reads it, and before `tool_call_end` reports it. It runs for calls\n * that executed, including ones whose `execute` threw, and not for calls that never ran, such as an unknown tool,\n * invalid input or a denied call. Return nothing to keep the result.\n */\n readonly afterToolCall?: (e: ToolResultEvent) => MaybePromise<OrNothing<ToolResultPatch>>;\n /** Ends the run, or keeps it going, after a step. It is not asked once the run has a stop reason of its own. */\n readonly shouldStop?: (e: StepEvent) => MaybePromise<StopDecision>;\n /**\n * What a hook that throws does. `\"fail_closed\"` (the default) stops the unsafe thing: a failed `beforeToolCall`\n * denies the call, a failed `afterToolCall` withholds the result, and a failed model-moment hook or `shouldStop`\n * ends the run with `stopReason: \"error\"` and `error.kind: \"hook\"`. `\"continue\"` skips the failed hook and goes on\n * as if it had returned nothing. Either way the run emits a `hook_error` event.\n */\n readonly onFailure?: \"fail_closed\" | \"continue\";\n}\n\n/**\n * Watches a run: called with each event, in order, and never able to change the run. A promise it returns is waited\n * for before the next event is delivered to it. A throw or a rejection becomes a `hook_error` event.\n */\nexport type Observer = (event: AgentEvent) => MaybePromise<void>;\n"]}
1
+ {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The hook types: six interceptors that can change a run, and the observer that only watches it. Each interceptor\n * takes one event object and returns a replacement, never mutating its input, because the event's data is frozen.\n */\nimport type {\n AssistantMessage,\n ContentBlock,\n Message,\n Model,\n ModelCallOptions,\n ModelContext,\n ModelRef,\n Usage,\n} from \"@buildanagent/gateway\";\nimport type { AgentEvent } from \"./events.js\";\nimport type { ToolResult } from \"./tools/types.js\";\n\n/** A value or a promise of one: a hook may be a plain function or an `async` one. */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * A value, or nothing: what a hook that may change something returns. `void` lets an `async` hook that has nothing\n * to change simply end, where `undefined` would force it to return explicitly.\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: a hook's return type, where void lets a function return nothing\nexport type OrNothing<T> = T | void;\n\n/** The options of one model call, without the abort signal, which the run supplies. */\nexport type CallOptions = Omit<ModelCallOptions, \"signal\">;\n\n/** The fields every hook event carries. */\nexport interface HookEventBase {\n /** The run's id. */\n readonly runId: string;\n /** The index of the model call the hook belongs to, counted from 0. */\n readonly stepIndex: number;\n /** The tool call's id, for the two tool hooks; absent for the others. */\n readonly callId?: string;\n /** The run's abort signal. Pass it on to any I/O the hook does. */\n readonly signal: AbortSignal;\n /** When the hook was called, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** What `transformContext` receives: the conversation as it stands before the model call. */\nexport interface ContextEvent extends HookEventBase {\n /** The system prompt. */\n readonly system: string;\n /** The whole conversation so far, never a view an earlier call's transform returned. */\n readonly messages: readonly Message[];\n /** The model the run was started with. */\n readonly model: ModelRef;\n /** The previous model call's usage. Absent on the first call. */\n readonly lastUsage?: Usage;\n}\n\n/** What `beforeModelCall` receives: the request about to be sent. */\nexport interface ModelCallEvent extends HookEventBase {\n /** The request: the system prompt, the messages `transformContext` returned and the tools this call sends. */\n readonly context: ModelContext;\n /** The options of this call, without the abort signal. */\n readonly options: CallOptions;\n}\n\n/** What `afterModelCall` receives: the model's finished response. */\nexport interface ModelResultEvent extends HookEventBase {\n /** The response, including a failed one, whose `stopReason` is `\"error\"`. */\n readonly message: AssistantMessage;\n}\n\n/** What `beforeToolCall` receives: a call whose input has passed the tool's schema. */\nexport interface ToolCallEvent extends HookEventBase {\n readonly callId: string;\n /** The tool's name. */\n readonly tool: string;\n /** The validated input. */\n readonly input: unknown;\n}\n\n/** What `afterToolCall` receives: the result of a call that executed, before the model reads it. */\nexport interface ToolResultEvent extends ToolCallEvent {\n readonly result: ToolResult;\n}\n\n/** What `shouldStop` receives, after a step's tool calls have their results. */\nexport interface StepEvent extends HookEventBase {\n /** The whole conversation so far, including this step's response and tool results. */\n readonly messages: readonly Message[];\n /** This step's model response. */\n readonly lastMessage: AssistantMessage;\n}\n\n/**\n * Changes to one model call's request. Every field is optional, and a change applies to that call only; the next\n * call starts again from the run's own settings.\n */\nexport interface ModelCallPatch {\n /** Replaces the system prompt for this call. */\n readonly system?: string;\n /** Replaces the messages sent for this call. The run's own transcript keeps its messages. */\n readonly messages?: readonly Message[];\n /**\n * The names of the tools to send, as the complete list: a tool left out is not sent, and a tool whose `exposure`\n * is `deferred` or `hidden` is sent when named. Tools always go out in definition order, whatever order this list\n * is in. A name that matches no tool throws an `SdkError` with code `invalid_hook_result`. A call to a tool that\n * was not sent gets the unknown-tool error.\n */\n readonly activeTools?: readonly string[];\n /** Makes this call with another model. */\n readonly model?: Model;\n /** Replaces the options of this call. */\n readonly options?: CallOptions;\n}\n\n/**\n * What `beforeToolCall` decides. `allow` runs the call, with `input` in place of the model's when given; the\n * replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask` pauses\n * the call for a person: the run signs a pending request for it with the run's `signer`, and ends\n * `awaiting_approval` once the step's other calls have their results. `reason` is shown to the approver and isn't\n * signed; `policyVersion` is signed. An `ask` may carry an `input`, which must pass the tool's schema like an\n * `allow`'s: the request is then signed over it, because it is the input the call would run with once approved.\n * `composeInterceptors()` passes an earlier gate's replacement on this way when a later gate asks.\n */\nexport type GateDecision =\n | { readonly decision: \"allow\"; readonly input?: unknown; readonly reason?: string }\n | { readonly decision: \"deny\"; readonly reason: string }\n | { readonly decision: \"ask\"; readonly input?: unknown; readonly reason?: string; readonly policyVersion?: string };\n\n/**\n * Changes to a tool's result. Each field present replaces the result's own. A replaced `outcome` is not available\n * here: a write's outcome is rendered into `content` once, so replace `content` instead.\n */\nexport type ToolResultPatch = Partial<Omit<ToolResult, \"outcome\">>;\n\n/**\n * What `shouldStop` decides. `true` or `{ stop: \"hook\" }` ends the run `stopped`, with the reason as `stoppedBy`\n * (`\"hook\"` for `true`). `{ stop: \"no_progress\" }` ends it `no_progress`. `{ continue }` keeps a run going that the\n * model ended by answering in text, adding the content as a user message. When the model's step called tools, the run goes on anyway and the content is\n * not added, so a hook that must reach the model should return it after a text answer. `false` leaves the decision to the run.\n */\nexport type StopDecision =\n | boolean\n | { readonly continue: string | readonly ContentBlock[] }\n | { readonly stop: \"no_progress\" | \"hook\"; readonly reason: string };\n\n/**\n * The six interceptors, in the order a step calls them: `transformContext`, `beforeModelCall`, the model call,\n * `afterModelCall`, then for each tool call `beforeToolCall` and `afterToolCall`, and last `shouldStop`. A run takes\n * one object; `composeInterceptors()` joins several. Each hook may be `async`.\n */\nexport interface Interceptors {\n /**\n * Returns the messages to send for this model call, such as a masked or summarised view of a long conversation.\n * The view reaches that call's request only: the next call's event, `result.messages` and `result.context` hold\n * the full history. Each call emits a `context_transformed` event with the message counts.\n */\n readonly transformContext?: (e: ContextEvent) => MaybePromise<readonly Message[]>;\n /** Changes the request about to be sent. Return nothing to leave it as it is. */\n readonly beforeModelCall?: (e: ModelCallEvent) => MaybePromise<OrNothing<ModelCallPatch>>;\n /**\n * Replaces the model's response. The transcript and the `model_call_end` event hold the replacement, and its tool\n * calls are the ones that run. The call's usage and cost stay those of the model's own response. If it throws\n * while the run fails closed, both hold an empty stand-in with `stopReason: \"error\"` and that usage and cost.\n */\n readonly afterModelCall?: (e: ModelResultEvent) => MaybePromise<OrNothing<{ readonly message?: AssistantMessage }>>;\n /**\n * The gate: decides whether a tool call runs, once for each call that passed validation, one call at a time in\n * model order, and before any call of the step executes. With no `beforeToolCall`, no gate stands in the way and\n * every registered tool is allowed. A gate that returns `ask` pauses the call, and the run ends `awaiting_approval`\n * with a signed pending request for it. A gate that throws denies the call unless `onFailure` is `\"continue\"`. A gate must return a\n * decision: returning nothing throws an `SdkError` with code `invalid_hook_result`.\n */\n readonly beforeToolCall?: (e: ToolCallEvent) => MaybePromise<GateDecision>;\n /**\n * Replaces fields of a result before the model reads it, and before `tool_call_end` reports it. It runs for calls\n * that executed, including ones whose `execute` threw, and not for calls that never ran, such as an unknown tool,\n * invalid input or a denied call. Return nothing to keep the result.\n */\n readonly afterToolCall?: (e: ToolResultEvent) => MaybePromise<OrNothing<ToolResultPatch>>;\n /** Ends the run, or keeps it going, after a step. It is not asked once the run has a stop reason of its own. */\n readonly shouldStop?: (e: StepEvent) => MaybePromise<StopDecision>;\n /**\n * What a hook that throws does. `\"fail_closed\"` (the default) stops the unsafe thing: a failed `beforeToolCall`\n * denies the call, a failed `afterToolCall` withholds the result, and a failed model-moment hook or `shouldStop`\n * ends the run with `stopReason: \"error\"` and `error.kind: \"hook\"`. `\"continue\"` skips the failed hook and goes on\n * as if it had returned nothing. Either way the run emits a `hook_error` event.\n */\n readonly onFailure?: \"fail_closed\" | \"continue\";\n}\n\n/**\n * Watches a run: called with each event, in order, and never able to change the run. A promise it returns is waited\n * for before the next event is delivered to it. A throw or a rejection becomes a `hook_error` event.\n */\nexport type Observer = (event: AgentEvent) => MaybePromise<void>;\n"]}
package/dist/index.d.ts CHANGED
@@ -3,20 +3,26 @@
3
3
  * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
4
4
  * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
5
5
  * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can
6
- * steer a running agent or queue a follow-up, both applied at step boundaries. Signed pauses are planned in the SDK
7
- * plan §3.3.
6
+ * steer a running agent or queue a follow-up, both applied at step boundaries. A gate that asks for a person ends the
7
+ * run with a signed pending request; the signers, the input hash and the pending record are the safety package's,
8
+ * re-exported unchanged.
8
9
  */
9
10
  export { projectCallCost } from "@buildanagent/gateway";
10
11
  export { composeInterceptors } from "./compose.js";
11
12
  export { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from "./errors.js";
12
13
  export { AGENT_EVENT_TYPES, type AgentEvent, type AgentEventBody, type EventBase, type ModelCallRequest, type WarningCode, } from "./events.js";
13
14
  export type { CallOptions, ContextEvent, GateDecision, HookEventBase, Interceptors, MaybePromise, ModelCallEvent, ModelCallPatch, ModelResultEvent, Observer, OrNothing, StepEvent, StopDecision, ToolCallEvent, ToolResultEvent, ToolResultPatch, } from "./hooks.js";
15
+ export { createPendingRequest, type PendingRequestFields } from "./pauses.js";
14
16
  export { DEFAULT_PROGRESS, type ProgressPolicy } from "./progress.js";
15
- export type { BudgetResult, Context, DoneResult, EndedResult, ErrorResult, NoProgressResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
17
+ export type { AwaitingApprovalResult, BudgetResult, Context, DoneResult, EndedResult, ErrorResult, NoProgressResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
16
18
  export { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from "./run.js";
17
19
  export type { DeliveryKind, DeliveryReceipt } from "./steering.js";
18
20
  export { type ClarificationToolOptions, clarificationTool, defineTool, type OutputToolOptions, outputTool, } from "./tools/define.js";
19
21
  export type { JsonSchema, SchemaIssue, ToolAnnotations, ToolContext, ToolDefinition, ToolEffect, ToolExecutionMode, ToolExposure, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
22
+ export { isSafetyError, SafetyError, type SafetyErrorCode } from "./vendor/agent-safety/errors.js";
23
+ export { canonicalInputHash } from "./vendor/agent-safety/hash.js";
20
24
  export type { WriteOutcome } from "./vendor/agent-safety/outcome.js";
25
+ export type { Resolution, SignedPendingRequest, SignPendingOptions } from "./vendor/agent-safety/pending.js";
26
+ export { type ApprovalSigner, ephemeralSigner, type HmacSignerOptions, hmacSigner, } from "./vendor/agent-safety/signer.js";
21
27
  /** The package's name, `@buildanagent/sdk`. */
22
28
  export declare const SDK_PACKAGE = "@buildanagent/sdk";
package/dist/index.js CHANGED
@@ -3,17 +3,22 @@
3
3
  * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
4
4
  * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
5
5
  * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can
6
- * steer a running agent or queue a follow-up, both applied at step boundaries. Signed pauses are planned in the SDK
7
- * plan §3.3.
6
+ * steer a running agent or queue a follow-up, both applied at step boundaries. A gate that asks for a person ends the
7
+ * run with a signed pending request; the signers, the input hash and the pending record are the safety package's,
8
+ * re-exported unchanged.
8
9
  */
9
10
  // Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.
10
11
  export { projectCallCost } from "@buildanagent/gateway";
11
12
  export { composeInterceptors } from "./compose.js";
12
13
  export { isSdkError, RunStoppedError, SdkError } from "./errors.js";
13
14
  export { AGENT_EVENT_TYPES, } from "./events.js";
15
+ export { createPendingRequest } from "./pauses.js";
14
16
  export { DEFAULT_PROGRESS } from "./progress.js";
15
17
  export { continueRun, nestedRunDepth, run, runOrThrow } from "./run.js";
16
18
  export { clarificationTool, defineTool, outputTool, } from "./tools/define.js";
19
+ export { isSafetyError, SafetyError } from "./vendor/agent-safety/errors.js";
20
+ export { canonicalInputHash } from "./vendor/agent-safety/hash.js";
21
+ export { ephemeralSigner, hmacSigner, } from "./vendor/agent-safety/signer.js";
17
22
  /** The package's name, `@buildanagent/sdk`. */
18
23
  export const SDK_PACKAGE = "@buildanagent/sdk";
19
24
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,sHAAsH;AACtH,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AACvF,OAAO,EACL,iBAAiB,GAMlB,MAAM,aAAa,CAAC;AAmBrB,OAAO,EAAE,gBAAgB,EAAuB,MAAM,eAAe,CAAC;AActE,OAAO,EAAE,WAAW,EAAE,cAAc,EAA4C,GAAG,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAElH,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,UAAU,GACX,MAAM,mBAAmB,CAAC;AAgB3B,+CAA+C;AAC/C,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,\n * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write\n * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also\n * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can\n * steer a running agent or queue a follow-up, both applied at step boundaries. Signed pauses are planned in the SDK\n * plan §3.3.\n */\n// Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.\nexport { projectCallCost } from \"@buildanagent/gateway\";\nexport { composeInterceptors } from \"./compose.js\";\nexport { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from \"./errors.js\";\nexport {\n AGENT_EVENT_TYPES,\n type AgentEvent,\n type AgentEventBody,\n type EventBase,\n type ModelCallRequest,\n type WarningCode,\n} from \"./events.js\";\nexport type {\n CallOptions,\n ContextEvent,\n GateDecision,\n HookEventBase,\n Interceptors,\n MaybePromise,\n ModelCallEvent,\n ModelCallPatch,\n ModelResultEvent,\n Observer,\n OrNothing,\n StepEvent,\n StopDecision,\n ToolCallEvent,\n ToolResultEvent,\n ToolResultPatch,\n} from \"./hooks.js\";\nexport { DEFAULT_PROGRESS, type ProgressPolicy } from \"./progress.js\";\nexport type {\n BudgetResult,\n Context,\n DoneResult,\n EndedResult,\n ErrorResult,\n NoProgressResult,\n ResultBase,\n RunError,\n RunResult,\n StoppedResult,\n UnfinishedResult,\n} from \"./result.js\";\nexport { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from \"./run.js\";\nexport type { DeliveryKind, DeliveryReceipt } from \"./steering.js\";\nexport {\n type ClarificationToolOptions,\n clarificationTool,\n defineTool,\n type OutputToolOptions,\n outputTool,\n} from \"./tools/define.js\";\nexport type {\n JsonSchema,\n SchemaIssue,\n ToolAnnotations,\n ToolContext,\n ToolDefinition,\n ToolEffect,\n ToolExecutionMode,\n ToolExposure,\n ToolFailure,\n ToolResult,\n ToolSchema,\n} from \"./tools/types.js\";\nexport type { WriteOutcome } from \"./vendor/agent-safety/outcome.js\";\n\n/** The package's name, `@buildanagent/sdk`. */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,sHAAsH;AACtH,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AACvF,OAAO,EACL,iBAAiB,GAMlB,MAAM,aAAa,CAAC;AAmBrB,OAAO,EAAE,oBAAoB,EAA6B,MAAM,aAAa,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAuB,MAAM,eAAe,CAAC;AAetE,OAAO,EAAE,WAAW,EAAE,cAAc,EAA4C,GAAG,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAElH,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,UAAU,GACX,MAAM,mBAAmB,CAAC;AAc3B,OAAO,EAAE,aAAa,EAAE,WAAW,EAAwB,MAAM,iCAAiC,CAAC;AACnG,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAGnE,OAAO,EAEL,eAAe,EAEf,UAAU,GACX,MAAM,iCAAiC,CAAC;AAEzC,+CAA+C;AAC/C,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,\n * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write\n * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also\n * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can\n * steer a running agent or queue a follow-up, both applied at step boundaries. A gate that asks for a person ends the\n * run with a signed pending request; the signers, the input hash and the pending record are the safety package's,\n * re-exported unchanged.\n */\n// Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.\nexport { projectCallCost } from \"@buildanagent/gateway\";\nexport { composeInterceptors } from \"./compose.js\";\nexport { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from \"./errors.js\";\nexport {\n AGENT_EVENT_TYPES,\n type AgentEvent,\n type AgentEventBody,\n type EventBase,\n type ModelCallRequest,\n type WarningCode,\n} from \"./events.js\";\nexport type {\n CallOptions,\n ContextEvent,\n GateDecision,\n HookEventBase,\n Interceptors,\n MaybePromise,\n ModelCallEvent,\n ModelCallPatch,\n ModelResultEvent,\n Observer,\n OrNothing,\n StepEvent,\n StopDecision,\n ToolCallEvent,\n ToolResultEvent,\n ToolResultPatch,\n} from \"./hooks.js\";\nexport { createPendingRequest, type PendingRequestFields } from \"./pauses.js\";\nexport { DEFAULT_PROGRESS, type ProgressPolicy } from \"./progress.js\";\nexport type {\n AwaitingApprovalResult,\n BudgetResult,\n Context,\n DoneResult,\n EndedResult,\n ErrorResult,\n NoProgressResult,\n ResultBase,\n RunError,\n RunResult,\n StoppedResult,\n UnfinishedResult,\n} from \"./result.js\";\nexport { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from \"./run.js\";\nexport type { DeliveryKind, DeliveryReceipt } from \"./steering.js\";\nexport {\n type ClarificationToolOptions,\n clarificationTool,\n defineTool,\n type OutputToolOptions,\n outputTool,\n} from \"./tools/define.js\";\nexport type {\n JsonSchema,\n SchemaIssue,\n ToolAnnotations,\n ToolContext,\n ToolDefinition,\n ToolEffect,\n ToolExecutionMode,\n ToolExposure,\n ToolFailure,\n ToolResult,\n ToolSchema,\n} from \"./tools/types.js\";\nexport { isSafetyError, SafetyError, type SafetyErrorCode } from \"./vendor/agent-safety/errors.js\";\nexport { canonicalInputHash } from \"./vendor/agent-safety/hash.js\";\nexport type { WriteOutcome } from \"./vendor/agent-safety/outcome.js\";\nexport type { Resolution, SignedPendingRequest, SignPendingOptions } from \"./vendor/agent-safety/pending.js\";\nexport {\n type ApprovalSigner,\n ephemeralSigner,\n type HmacSignerOptions,\n hmacSigner,\n} from \"./vendor/agent-safety/signer.js\";\n\n/** The package's name, `@buildanagent/sdk`. */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
package/dist/loop.d.ts CHANGED
@@ -15,6 +15,7 @@ import type { RunResult } from "./result.js";
15
15
  import type { SteeringQueue } from "./steering.js";
16
16
  import type { Clock } from "./testing/determinism.js";
17
17
  import { type AnyTool } from "./tools/pipeline.js";
18
+ import type { ApprovalSigner } from "./vendor/agent-safety/signer.js";
18
19
  /** Everything one run needs, fixed when it starts. */
19
20
  export interface LoopSetup {
20
21
  readonly runId: string;
@@ -44,6 +45,10 @@ export interface LoopSetup {
44
45
  readonly steering: SteeringQueue;
45
46
  readonly signal: AbortSignal;
46
47
  readonly clock: Clock;
48
+ /** Signs the pending request of each call a gate asks about (D5). */
49
+ readonly signer: ApprovalSigner;
50
+ /** Makes each pending request's id. */
51
+ readonly nextId: () => string;
47
52
  }
48
53
  /** Sends one event; the run adds the `EventBase` fields. */
49
54
  export type Emit = (body: AgentEventBody, stepIndex: number) => void;
package/dist/loop.js CHANGED
@@ -39,6 +39,13 @@ class LoopState {
39
39
  output;
40
40
  /** Set when the run was kept going to deliver a follow-up, so the next step boundary applies the follow-ups too. */
41
41
  releaseFollowUps = false;
42
+ /** The signed requests of the calls that gates paused, in model order. */
43
+ pending = [];
44
+ /**
45
+ * The input each pending request signs, by request id. It has no prototype, because an id comes from the host's
46
+ * `idGenerator` and `"__proto__"` must be stored as a key like any other.
47
+ */
48
+ pendingInputs = Object.create(null);
42
49
  constructor(setup, emit, drain) {
43
50
  this.setup = setup;
44
51
  this.emit = emit;
@@ -53,6 +60,8 @@ class LoopState {
53
60
  clock: setup.clock,
54
61
  stepIndex: () => this.stepIndex,
55
62
  send: (body) => this.send(body),
63
+ signer: setup.signer,
64
+ nextId: setup.nextId,
56
65
  });
57
66
  }
58
67
  /** The wire form of each of `tools`, as a request sends them. */
@@ -262,6 +271,11 @@ async function runTools(state, message) {
262
271
  ...state.hooks.pipelineHooks(),
263
272
  onStart: (call) => state.send({ type: "tool_call_start", callId: call.callId, tool: call.name, input: call.input }),
264
273
  onUpdate: (callId, details) => state.send({ type: "tool_call_update", callId, details }),
274
+ onPause: ({ request, input }) => {
275
+ state.pending.push(request);
276
+ state.pendingInputs[request.id] = input;
277
+ state.send({ type: "approval_request", request, input });
278
+ },
265
279
  onResult: (entry) => {
266
280
  state.append(toolMessage(entry));
267
281
  if (output !== undefined && entry.call.name === output.name && entry.result.isError !== true) {
@@ -280,8 +294,9 @@ function runErrorOf(message) {
280
294
  return { kind: error.kind, message: error.message, ...(error.status === undefined ? {} : { status: error.status }) };
281
295
  }
282
296
  /**
283
- * The stop check after one step. A finished answer, or a question for the user, wins over an abort that came too late
284
- * to change it; otherwise an abort stops the run before the step cap does. A text answer cut off at the output limit
297
+ * The stop check after one step. A pause, a finished answer or a question for the user wins over an abort that came
298
+ * too late to change it; otherwise an abort stops the run before the step cap does. A pause wins over a finished
299
+ * answer too, because its call is still waiting. A text answer cut off at the output limit
285
300
  * also counts as finished: its message keeps `stopReason: "length"`.
286
301
  */
287
302
  function stopCheck(state, message, results) {
@@ -289,6 +304,11 @@ function stopCheck(state, message, results) {
289
304
  return { stopReason: "error", error: runErrorOf(message) };
290
305
  if (message.stopReason === "aborted")
291
306
  return { stopReason: "aborted" };
307
+ // A paused call is still waiting, so the run can't count as finished, and the pause is signed and stored with the
308
+ // context, so it outlasts an abort that came while the step's other calls ran.
309
+ if (state.pending.length > 0) {
310
+ return { stopReason: "awaiting_approval", pending: [...state.pending], pendingInputs: { ...state.pendingInputs } };
311
+ }
292
312
  const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);
293
313
  if (finished)
294
314
  return { stopReason: "done", output: state.output };
@@ -427,9 +447,12 @@ function closeAborted(state) {
427
447
  });
428
448
  }
429
449
  function resultOf(state, outcome) {
450
+ const pending = outcome.stopReason === "awaiting_approval"
451
+ ? { pending: [...outcome.pending], pendingInputs: { ...outcome.pendingInputs } }
452
+ : {};
430
453
  const base = {
431
454
  messages: state.added,
432
- context: { system: state.setup.system, messages: state.messages },
455
+ context: { system: state.setup.system, messages: state.messages, ...pending },
433
456
  usage: state.usage,
434
457
  cost: state.cost ?? { ...NO_COST },
435
458
  steps: state.steps,
package/dist/loop.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"loop.js","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAEL,OAAO,EACP,QAAQ,EAGR,UAAU,EAKV,eAAe,GAIhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE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K,SAAS,EAAE,CAAC;YAC7B,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;QACpF,CAAC;IACH,CAAC;YAAS,CAAC;QACT,6GAA6G;QAC7G,6CAA6C;QAC7C,KAAK,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAChC,CAAC","sourcesContent":["/**\n * The step loop: one model call, then the tool calls it asked for, then the stop check, until a stop reason holds\n * (agent-SDK guide §3). The non-streaming result is built from the same run, so there is one loop for both modes.\n *\n * Each step runs transform → before → stream → after → tools → stop. Those moments are where the interceptors\n * plug in (D6); a run without interceptors sends the transcript as it stands and keeps each response unchanged.\n * Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed tool result,\n * throws.\n */\nimport {\n type AssistantMessage,\n addCost,\n addUsage,\n type Cost,\n type DumpedOptions,\n emptyUsage,\n type GatewayEvent,\n type Message,\n type Model,\n type ModelContext,\n projectCallCost,\n type StreamOptions,\n type Usage,\n type WireTool,\n} from \"@buildanagent/gateway\";\nimport { checkBudget, unknownPriceError } from \"./budget.js\";\nimport { isSdkError, SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport type { StopVerdict } from \"./hook-checks.js\";\nimport { HookFailure, HookRunner } from \"./hook-runner.js\";\nimport type { CallOptions, Interceptors, ModelCallPatch } from \"./hooks.js\";\nimport type { ProgressCheck } from \"./progress.js\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { SteeringQueue } from \"./steering.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { toWireTool } from \"./tools/define.js\";\nimport { type AnyTool, runToolCalls, type ToolCallResult } from \"./tools/pipeline.js\";\nimport type { ToolCall } from \"./tools/types.js\";\n\n/** The `stoppedBy` of a run that a clarification tool stopped. */\nconst CLARIFICATION = \"clarification\";\n\n/**\n * The cost of no model call: an exact zero. Its basis is `provider` because `addCost()` keeps the other cost's basis\n * when it adds a provider cost, so the zero never turns a billed sum into an estimate.\n */\nconst NO_COST: Cost = { total: 0, basis: \"provider\", currency: \"USD\" };\n\n/** Everything one run needs, fixed when it starts. */\nexport interface LoopSetup {\n readonly runId: string;\n readonly model: Model;\n readonly system: string;\n /** The conversation before this run's own messages. */\n readonly history: readonly Message[];\n /** The messages the run starts by adding, such as the user's input. */\n readonly input: readonly Message[];\n /**\n * Every tool the run knows, in definition order. A request sends the ones whose exposure is `direct`, or the ones\n * `activeTools` names, and only the tools a request sent can run.\n */\n readonly tools: readonly AnyTool[];\n readonly output: AnyTool | undefined;\n readonly maxSteps: number;\n /** The most the run's model calls may cost, in USD, or `undefined` for no cap (D9). */\n readonly budgetUsd?: number;\n /** How deeply this run is nested inside other agents' tool calls, and the deepest nesting allowed (D11). */\n readonly depth: number;\n readonly maxDepth: number;\n readonly modelOptions: CallOptions;\n readonly interceptors: Interceptors;\n /** The default progress policy, run after the caller's `shouldStop`, or `undefined` when it is off (D11). */\n readonly progress?: ProgressCheck;\n /** The messages a caller queued with `steer()` and `followUp()`, applied only at step boundaries. */\n readonly steering: SteeringQueue;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n}\n\n/** Sends one event; the run adds the `EventBase` fields. */\nexport type Emit = (body: AgentEventBody, stepIndex: number) => void;\n\n/**\n * Resolves once every observer has handled the events sent so far. The loop calls it only once it has its outcome,\n * and the run treats the first call as the point after which an abort no longer counts.\n */\nexport type Drain = () => Promise<void>;\n\n/** How a run ended, before its usage, cost and messages are attached. */\ntype Outcome =\n | { readonly stopReason: \"done\"; readonly output: unknown }\n | { readonly stopReason: \"max_steps\" | \"aborted\" }\n | {\n readonly stopReason: \"budget\";\n readonly reason: string;\n readonly budgetUsd: number;\n readonly spentUsd: number;\n readonly projectedUsd: number;\n }\n | { readonly stopReason: \"error\"; readonly error: RunError }\n | { readonly stopReason: \"stopped\"; readonly stoppedBy: string }\n | { readonly stopReason: \"no_progress\"; readonly reason: string };\n\n/** What changes while a run goes on. */\nclass LoopState {\n readonly setup: LoopSetup;\n readonly emit: Emit;\n readonly messages: Message[];\n readonly added: Message[];\n readonly drain: Drain;\n readonly hooks: HookRunner;\n readonly #wire: ReadonlyMap<AnyTool, WireTool>;\n /** The tools the latest request sent; the tool calls of its response may run only these. */\n active: readonly AnyTool[] = [];\n steps = 0;\n stepIndex = 0;\n usage: Usage = emptyUsage();\n lastUsage: Usage | undefined;\n cost: Cost | undefined;\n output: unknown;\n /** Set when the run was kept going to deliver a follow-up, so the next step boundary applies the follow-ups too. */\n releaseFollowUps = false;\n\n constructor(setup: LoopSetup, emit: Emit, drain: Drain) {\n this.setup = setup;\n this.emit = emit;\n this.drain = drain;\n this.messages = [...setup.history, ...setup.input];\n this.added = [...setup.input];\n this.#wire = new Map(setup.tools.map((tool) => [tool, toWireTool(tool)]));\n this.hooks = new HookRunner({\n interceptors: setup.interceptors,\n runId: setup.runId,\n signal: setup.signal,\n clock: setup.clock,\n stepIndex: () => this.stepIndex,\n send: (body) => this.send(body),\n });\n }\n\n /** The wire form of each of `tools`, as a request sends them. */\n wireOf(tools: readonly AnyTool[]): WireTool[] {\n // Every tool of the run was lowered in the constructor, and a request names only the run's tools.\n return tools.map((tool) => this.#wire.get(tool) as WireTool);\n }\n\n send(body: AgentEventBody): void {\n this.emit(body, this.stepIndex);\n }\n\n append(message: Message): void {\n this.messages.push(message);\n this.added.push(message);\n }\n}\n\n/**\n * The stream options a request event records: everything but the payload hook, the abort signal and the caps, as the\n * gateway's own request dump leaves them out. An untyped caller may still pass a signal or caps in `modelOptions`.\n */\nfunction dumpedOptions(options: CallOptions): DumpedOptions {\n const { onPayload: _onPayload, signal: _signal, caps: _caps, ...rest } = options as StreamOptions;\n return rest;\n}\n\n/** Re-emits one model event as a run event, and returns the final message once the terminal event arrives. */\nfunction forward(state: LoopState, event: GatewayEvent): AssistantMessage | undefined {\n switch (event.type) {\n case \"done\":\n case \"error\":\n return event.message;\n case \"start\":\n return undefined;\n case \"retry\":\n state.send({ type: \"retry\", attempt: event.attempt, delayMs: event.delayMs, error: event.error });\n return undefined;\n case \"warning\":\n state.send({ type: \"warning\", code: \"model_warning\", detail: `${event.code}: ${event.message}` });\n return undefined;\n case \"text_start\":\n case \"reasoning_start\":\n case \"tool_input_start\":\n state.send({ type: event.type, index: event.index });\n return undefined;\n case \"text_delta\":\n case \"reasoning_delta\":\n case \"tool_input_delta\":\n state.send({ type: event.type, index: event.index, delta: event.delta });\n return undefined;\n default:\n state.send({ type: event.type, index: event.index, block: event.block });\n return undefined;\n }\n}\n\n/** One model call as it will be sent, after `transformContext` and `beforeModelCall`. */\ninterface Request {\n readonly model: Model;\n readonly context: ModelContext;\n readonly options: CallOptions;\n readonly active: readonly AnyTool[];\n}\n\n/** The tools a request sends unless `beforeModelCall` names others: the ones whose exposure is `direct`. */\nfunction directTools(tools: readonly AnyTool[]): AnyTool[] {\n return tools.filter((tool) => (tool.exposure ?? \"direct\") === \"direct\");\n}\n\n/** The tools `names` picks, in definition order whatever order `names` is in. */\nfunction toolsNamed(tools: readonly AnyTool[], names: readonly string[]): AnyTool[] {\n const unknown = names.filter((name) => !tools.some((tool) => tool.name === name));\n if (unknown.length > 0) {\n throw new SdkError(\"invalid_hook_result\", `activeTools names unknown tools: ${unknown.join(\", \")}`);\n }\n return tools.filter((tool) => names.includes(tool.name));\n}\n\nfunction patched(state: LoopState, request: Request, patch: ModelCallPatch): Request {\n const active = patch.activeTools === undefined ? request.active : toolsNamed(state.setup.tools, patch.activeTools);\n const { system, messages } = request.context;\n return {\n model: patch.model ?? request.model,\n options: patch.options ?? request.options,\n active,\n context: {\n system: patch.system ?? system,\n messages: patch.messages === undefined ? messages : [...patch.messages],\n tools: state.wireOf(active),\n },\n };\n}\n\n/**\n * Builds one call's request: the transcript, or the view `transformContext` returns for this call alone, then the\n * changes `beforeModelCall` asks for. The run's own transcript is never replaced by either.\n */\nasync function buildRequest(state: LoopState): Promise<Request> {\n const { model, system, modelOptions, tools } = state.setup;\n const view = await state.hooks.transformContext({\n system,\n messages: state.messages,\n model: model.ref,\n lastUsage: state.lastUsage,\n });\n const active = directTools(tools);\n const context = { system, messages: [...(view ?? state.messages)], tools: state.wireOf(active) };\n const request: Request = { model, context, options: modelOptions, active };\n const patch = await state.hooks.beforeModelCall({ context, options: modelOptions });\n return patch === undefined ? request : patched(state, request, patch);\n}\n\n/** Streams one request, re-emitting its events, and returns the model's final message. */\nasync function streamRequest(state: LoopState, request: Request): Promise<AssistantMessage> {\n const { model, context, options } = request;\n state.send({ type: \"model_call_start\", request: { model: model.ref, context, options: dumpedOptions(options) } });\n let message: AssistantMessage | undefined;\n for await (const event of model.stream(context, { ...options, signal: state.setup.signal })) {\n message = forward(state, event) ?? message;\n }\n if (message === undefined) {\n throw new SdkError(\"invalid_model_stream\", \"the model's stream ended without a done or error event\");\n }\n return message;\n}\n\n/** Adds a model call's response to the transcript and reports it. */\nfunction record(state: LoopState, message: AssistantMessage): void {\n state.append(message);\n state.send({ type: \"model_call_end\", message });\n}\n\n/**\n * What the transcript holds for a response whose `afterModelCall` failed while the run fails closed: no content, so a\n * check that crashed can't let the response through, but the call's usage and cost, which were billed. Its error stop\n * reason makes the replay pass skip it if the run is continued.\n */\nfunction withheld(original: AssistantMessage): AssistantMessage {\n const { model, usage, cost, lastAttemptUsage } = original;\n return {\n role: \"assistant\",\n content: [],\n model,\n stopReason: \"error\",\n error: { kind: \"fatal\", message: \"the response was withheld, because its afterModelCall check failed\" },\n usage,\n ...(lastAttemptUsage === undefined ? {} : { lastAttemptUsage }),\n cost,\n };\n}\n\n/**\n * The budget check before a call (D9): the outcome that ends the run when the spend so far plus the call's projected\n * cost would pass `budgetUsd`, or `undefined` when the call may go out. It checks the request as it will be sent,\n * after the interceptors have changed it, and projects with the model the request names.\n */\nfunction budgetBlock(state: LoopState, request: Request): Outcome | undefined {\n const { budgetUsd } = state.setup;\n if (budgetUsd === undefined) return undefined;\n const projected = projectCallCost(request.model, request.context, request.options);\n const verdict = checkBudget(budgetUsd, state.cost, projected);\n switch (verdict.kind) {\n case \"allow\":\n return undefined;\n case \"unknown\":\n return { stopReason: \"error\", error: verdict.error };\n case \"exceeded\":\n return {\n stopReason: \"budget\",\n reason: verdict.reason,\n budgetUsd,\n spentUsd: verdict.spentUsd,\n projectedUsd: verdict.projectedUsd,\n };\n }\n}\n\n/**\n * Makes one model call, streams its events and records the response. The call's usage and cost are the model's own\n * message's, so an `afterModelCall` replacement changes what the run goes on with, never what it is billed. When\n * `afterModelCall` fails and the run fails closed, a withheld stand-in is recorded before the run ends, so the\n * transcript and `model_call_end` still account for the billed call and none of its tool calls run.\n */\nasync function callModel(state: LoopState): Promise<AssistantMessage | { readonly blocked: Outcome }> {\n const request = await buildRequest(state);\n const blocked = budgetBlock(state, request);\n if (blocked !== undefined) return { blocked };\n state.active = request.active;\n const original = await streamRequest(state, request);\n state.steps += 1;\n state.usage = addUsage(state.usage, original.usage);\n state.lastUsage = original.usage;\n state.cost = state.cost === undefined ? original.cost : addCost(state.cost, original.cost);\n let message: AssistantMessage;\n try {\n message = await state.hooks.afterModelCall(original);\n } catch (error) {\n if (error instanceof HookFailure || (isSdkError(error) && error.code === \"invalid_hook_result\")) {\n record(state, withheld(original));\n }\n throw error;\n }\n record(state, message);\n return message;\n}\n\n/** The tool message the model reads for one call. */\nfunction toolMessage(entry: ToolCallResult): Message {\n return {\n role: \"tool\",\n callId: entry.call.callId,\n content: [...entry.result.content],\n isError: entry.result.isError === true,\n };\n}\n\n/** Runs the response's tool calls as the pipeline schedules them, recording each result in model order. */\nasync function runTools(state: LoopState, message: AssistantMessage): Promise<readonly ToolCallResult[]> {\n const { runId, signal, clock, output } = state.setup;\n return runToolCalls(message, state.active, {\n runId,\n signal,\n clock,\n depth: state.setup.depth,\n maxDepth: state.setup.maxDepth,\n ...state.hooks.pipelineHooks(),\n onStart: (call: ToolCall) =>\n state.send({ type: \"tool_call_start\", callId: call.callId, tool: call.name, input: call.input }),\n onUpdate: (callId, details) => state.send({ type: \"tool_call_update\", callId, details }),\n onResult: (entry) => {\n state.append(toolMessage(entry));\n if (output !== undefined && entry.call.name === output.name && entry.result.isError !== true) {\n state.output = entry.result.structured;\n }\n const ranWith = \"input\" in entry ? { input: entry.input } : {};\n state.send({ type: \"tool_call_end\", callId: entry.call.callId, result: entry.result, ...ranWith });\n },\n });\n}\n\n/** The failed call's error as the run reports it. A message without one counts as `fatal`. */\nfunction runErrorOf(message: AssistantMessage): RunError {\n const error = message.error;\n if (error === undefined) return { kind: \"fatal\", message: \"the model call failed without an error description\" };\n return { kind: error.kind, message: error.message, ...(error.status === undefined ? {} : { status: error.status }) };\n}\n\n/**\n * The stop check after one step. A finished answer, or a question for the user, wins over an abort that came too late\n * to change it; otherwise an abort stops the run before the step cap does. A text answer cut off at the output limit\n * also counts as finished: its message keeps `stopReason: \"length\"`.\n */\nfunction stopCheck(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Outcome | undefined {\n if (message.stopReason === \"error\") return { stopReason: \"error\", error: runErrorOf(message) };\n if (message.stopReason === \"aborted\") return { stopReason: \"aborted\" };\n const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);\n if (finished) return { stopReason: \"done\", output: state.output };\n // Until runs can pause for an answer, a clarification question stops the run, so the model never goes on as if the\n // user had been asked and answered.\n if (results.some(({ result }) => result.pause !== undefined && !result.isError)) {\n return { stopReason: \"stopped\", stoppedBy: CLARIFICATION };\n }\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n return undefined;\n}\n\n/**\n * What `shouldStop` changes about the stop check. A finished answer or an error stands whatever the hook says; the\n * hook can end a run that would go on, and can keep going a run the model ended by answering in text, until the\n * step cap.\n */\nfunction withVerdict(state: LoopState, natural: Outcome | undefined, verdict: StopVerdict): Outcome | undefined {\n if (natural !== undefined && verdict.kind !== \"continue\") return natural;\n switch (verdict.kind) {\n case \"stop\":\n return { stopReason: \"stopped\", stoppedBy: verdict.stoppedBy };\n case \"no_progress\":\n return { stopReason: \"no_progress\", reason: verdict.reason };\n case \"continue\":\n if (natural === undefined) return undefined;\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n state.append({ role: \"user\", content: verdict.content });\n return undefined;\n default:\n return natural;\n }\n}\n\n/**\n * Applies the queued messages before a model call: every steer, and the follow-ups too once the run was kept going to\n * deliver them. Each becomes a user message and a `steer_applied` event, in the order it was sent, and its receipt\n * resolves with the index of the step about to run.\n */\nfunction applySteering(state: LoopState): void {\n const { steering } = state.setup;\n const withFollowUps = state.releaseFollowUps;\n state.releaseFollowUps = false;\n for (const delivery of steering.take(withFollowUps)) {\n // A copy, so a caller who changes a receipt's message cannot change the transcript.\n state.append({ role: \"user\", content: delivery.message.map((block) => ({ ...block })) });\n state.send({ type: \"steer_applied\", receipt: delivery.deliver(state.stepIndex) });\n }\n}\n\n/**\n * Keeps a run that its model ended by answering going, when a message is waiting and the step cap leaves room for\n * one more call: a steer comes first, and follow-ups wait for the next time the run would end. Any other outcome\n * stands, as does a `stop` or `no_progress` verdict that `withVerdict` folded into `done`, and an abort that came\n * after the answer, which `stopCheck` lets the answer win over. The messages still waiting are rejected when the run\n * ends.\n */\nfunction withQueued(state: LoopState, outcome: Outcome | undefined, verdict: StopVerdict): Outcome | undefined {\n const { steering, maxSteps, signal } = state.setup;\n if (outcome?.stopReason !== \"done\" || !steering.hasPending() || state.steps >= maxSteps) return outcome;\n if (verdict.kind === \"stop\" || verdict.kind === \"no_progress\" || signal.aborted) return outcome;\n state.releaseFollowUps = !steering.hasSteers();\n return undefined;\n}\n\n/** The stop check after one step, then the `shouldStop` hook where it may change it. */\nasync function decide(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Promise<Outcome | undefined> {\n const natural = stopCheck(state, message, results);\n const endedByAnswer = natural?.stopReason === \"done\" && results.length === 0;\n if (natural !== undefined && !endedByAnswer) return natural;\n const verdict = await state.hooks.shouldStop({ messages: state.messages, lastMessage: message });\n const judged = await withProgress(state, verdict);\n const outcome = withVerdict(state, natural, judged);\n return endedByAnswer ? withQueued(state, outcome, judged) : outcome;\n}\n\n/**\n * The caller's verdict, unless the progress policy finds the run stuck. A caller's own stop stands, and a caller's\n * `{ continue }` or failed hook can't keep a stuck run going.\n */\nasync function withProgress(state: LoopState, verdict: StopVerdict): Promise<StopVerdict> {\n if (verdict.kind === \"stop\" || verdict.kind === \"no_progress\" || state.setup.progress === undefined) return verdict;\n const reason = await state.setup.progress(state.messages);\n return reason === undefined ? verdict : { kind: \"no_progress\", reason };\n}\n\n/** The outcome of a hook that failed while the run fails closed. A failure caused by an abort ends the run aborted. */\nfunction failedOutcome(state: LoopState, error: unknown): Outcome {\n if (!(error instanceof HookFailure)) throw error;\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n return { stopReason: \"error\", error: { kind: \"hook\", message: error.message } };\n}\n\nasync function runStep(state: LoopState): Promise<Outcome | undefined> {\n state.stepIndex = state.steps;\n state.send({ type: \"step_start\" });\n let outcome: Outcome | undefined;\n try {\n applySteering(state);\n const called = await callModel(state);\n if (\"blocked\" in called) {\n outcome = called.blocked;\n } else {\n const results = await runTools(state, called);\n outcome = await decide(state, called, results);\n }\n } catch (error) {\n outcome = failedOutcome(state, error);\n }\n state.send({ type: \"step_end\", stopCheck: outcome === undefined ? \"continue\" : \"stop\" });\n return outcome;\n}\n\n/**\n * An aborted run's transcript ends with an assistant message whose `stopReason` is `\"aborted\"`. When tool results end\n * the transcript, because the abort came while tools ran or cut off a response that held tool calls, the loop\n * appends an empty one after them; the replay pass drops it before any request.\n */\nfunction closeAborted(state: LoopState): void {\n const last = state.messages.at(-1);\n if (last?.role === \"assistant\" && last.stopReason === \"aborted\") return;\n state.append({\n role: \"assistant\",\n content: [],\n model: state.setup.model.ref,\n stopReason: \"aborted\",\n usage: emptyUsage(),\n cost: { ...NO_COST },\n });\n}\n\nfunction resultOf(state: LoopState, outcome: Outcome): RunResult {\n const base = {\n messages: state.added,\n context: { system: state.setup.system, messages: state.messages },\n usage: state.usage,\n cost: state.cost ?? { ...NO_COST },\n steps: state.steps,\n };\n return { ...base, ...outcome } as RunResult;\n}\n\n/**\n * Ends the run: the settle event comes once every observer has seen what came before it, and `run_end` after that.\n * An observer's failure while handling `agent_settled` is reported between the two; one while handling `run_end` is\n * dropped, so `run_end` stays the last event. The result is returned only once observers have seen it.\n */\nasync function finish(state: LoopState, outcome: Outcome): Promise<RunResult> {\n if (outcome.stopReason === \"aborted\") closeAborted(state);\n if (outcome.stopReason === \"max_steps\") {\n state.send({ type: \"warning\", code: \"max_steps\", detail: `the run reached maxSteps (${state.setup.maxSteps})` });\n }\n if (outcome.stopReason === \"error\") state.send({ type: \"error\", error: outcome.error });\n await state.drain();\n state.send({ type: \"agent_settled\" });\n await state.drain();\n const result = resultOf(state, outcome);\n state.send({ type: \"run_end\", result });\n await state.drain();\n return result;\n}\n\n/**\n * Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results\n * already received are in the transcript.\n */\nexport async function runLoop(setup: LoopSetup, emit: Emit, drain: Drain): Promise<RunResult> {\n const state = new LoopState(setup, emit, drain);\n // A budget needs a price to check against, so a model without one is refused before it is called (D4).\n const refused = setup.budgetUsd === undefined ? undefined : unknownPriceError(setup.model);\n let outcome: Outcome | undefined = refused === undefined ? undefined : { stopReason: \"error\", error: refused };\n try {\n while (outcome === undefined) {\n outcome = setup.signal.aborted ? { stopReason: \"aborted\" } : await runStep(state);\n }\n } finally {\n // The run has its outcome, or threw for a programmer error, so a message still waiting can no longer reach a\n // model call, and its receipt must not hang.\n setup.steering.close();\n }\n return finish(state, outcome);\n}\n"]}
1
+ {"version":3,"file":"loop.js","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAE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AAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;QACpF,CAAC;IACH,CAAC;YAAS,CAAC;QACT,6GAA6G;QAC7G,6CAA6C;QAC7C,KAAK,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAChC,CAAC","sourcesContent":["/**\n * The step loop: one model call, then the tool calls it asked for, then the stop check, until a stop reason holds\n * (agent-SDK guide §3). The non-streaming result is built from the same run, so there is one loop for both modes.\n *\n * Each step runs transform → before → stream → after → tools → stop. Those moments are where the interceptors\n * plug in (D6); a run without interceptors sends the transcript as it stands and keeps each response unchanged.\n * Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed tool result,\n * throws.\n */\nimport {\n type AssistantMessage,\n addCost,\n addUsage,\n type Cost,\n type DumpedOptions,\n emptyUsage,\n type GatewayEvent,\n type Message,\n type Model,\n type ModelContext,\n projectCallCost,\n type StreamOptions,\n type Usage,\n type WireTool,\n} from \"@buildanagent/gateway\";\nimport { checkBudget, unknownPriceError } from \"./budget.js\";\nimport { isSdkError, SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport type { StopVerdict } from \"./hook-checks.js\";\nimport { HookFailure, HookRunner } from \"./hook-runner.js\";\nimport type { CallOptions, Interceptors, ModelCallPatch } from \"./hooks.js\";\nimport type { ProgressCheck } from \"./progress.js\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { SteeringQueue } from \"./steering.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { toWireTool } from \"./tools/define.js\";\nimport { type AnyTool, runToolCalls, type ToolCallResult } from \"./tools/pipeline.js\";\nimport type { ToolCall } from \"./tools/types.js\";\nimport type { SignedPendingRequest } from \"./vendor/agent-safety/pending.js\";\nimport type { ApprovalSigner } from \"./vendor/agent-safety/signer.js\";\n\n/** The `stoppedBy` of a run that a clarification tool stopped. */\nconst CLARIFICATION = \"clarification\";\n\n/**\n * The cost of no model call: an exact zero. Its basis is `provider` because `addCost()` keeps the other cost's basis\n * when it adds a provider cost, so the zero never turns a billed sum into an estimate.\n */\nconst NO_COST: Cost = { total: 0, basis: \"provider\", currency: \"USD\" };\n\n/** Everything one run needs, fixed when it starts. */\nexport interface LoopSetup {\n readonly runId: string;\n readonly model: Model;\n readonly system: string;\n /** The conversation before this run's own messages. */\n readonly history: readonly Message[];\n /** The messages the run starts by adding, such as the user's input. */\n readonly input: readonly Message[];\n /**\n * Every tool the run knows, in definition order. A request sends the ones whose exposure is `direct`, or the ones\n * `activeTools` names, and only the tools a request sent can run.\n */\n readonly tools: readonly AnyTool[];\n readonly output: AnyTool | undefined;\n readonly maxSteps: number;\n /** The most the run's model calls may cost, in USD, or `undefined` for no cap (D9). */\n readonly budgetUsd?: number;\n /** How deeply this run is nested inside other agents' tool calls, and the deepest nesting allowed (D11). */\n readonly depth: number;\n readonly maxDepth: number;\n readonly modelOptions: CallOptions;\n readonly interceptors: Interceptors;\n /** The default progress policy, run after the caller's `shouldStop`, or `undefined` when it is off (D11). */\n readonly progress?: ProgressCheck;\n /** The messages a caller queued with `steer()` and `followUp()`, applied only at step boundaries. */\n readonly steering: SteeringQueue;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n /** Signs the pending request of each call a gate asks about (D5). */\n readonly signer: ApprovalSigner;\n /** Makes each pending request's id. */\n readonly nextId: () => string;\n}\n\n/** Sends one event; the run adds the `EventBase` fields. */\nexport type Emit = (body: AgentEventBody, stepIndex: number) => void;\n\n/**\n * Resolves once every observer has handled the events sent so far. The loop calls it only once it has its outcome,\n * and the run treats the first call as the point after which an abort no longer counts.\n */\nexport type Drain = () => Promise<void>;\n\n/** How a run ended, before its usage, cost and messages are attached. */\ntype Outcome =\n | { readonly stopReason: \"done\"; readonly output: unknown }\n | { readonly stopReason: \"max_steps\" | \"aborted\" }\n | {\n readonly stopReason: \"budget\";\n readonly reason: string;\n readonly budgetUsd: number;\n readonly spentUsd: number;\n readonly projectedUsd: number;\n }\n | { readonly stopReason: \"error\"; readonly error: RunError }\n | { readonly stopReason: \"stopped\"; readonly stoppedBy: string }\n | { readonly stopReason: \"no_progress\"; readonly reason: string }\n | {\n readonly stopReason: \"awaiting_approval\";\n readonly pending: readonly SignedPendingRequest[];\n readonly pendingInputs: Readonly<Record<string, unknown>>;\n };\n\n/** What changes while a run goes on. */\nclass LoopState {\n readonly setup: LoopSetup;\n readonly emit: Emit;\n readonly messages: Message[];\n readonly added: Message[];\n readonly drain: Drain;\n readonly hooks: HookRunner;\n readonly #wire: ReadonlyMap<AnyTool, WireTool>;\n /** The tools the latest request sent; the tool calls of its response may run only these. */\n active: readonly AnyTool[] = [];\n steps = 0;\n stepIndex = 0;\n usage: Usage = emptyUsage();\n lastUsage: Usage | undefined;\n cost: Cost | undefined;\n output: unknown;\n /** Set when the run was kept going to deliver a follow-up, so the next step boundary applies the follow-ups too. */\n releaseFollowUps = false;\n /** The signed requests of the calls that gates paused, in model order. */\n readonly pending: SignedPendingRequest[] = [];\n /**\n * The input each pending request signs, by request id. It has no prototype, because an id comes from the host's\n * `idGenerator` and `\"__proto__\"` must be stored as a key like any other.\n */\n readonly pendingInputs: Record<string, unknown> = Object.create(null);\n\n constructor(setup: LoopSetup, emit: Emit, drain: Drain) {\n this.setup = setup;\n this.emit = emit;\n this.drain = drain;\n this.messages = [...setup.history, ...setup.input];\n this.added = [...setup.input];\n this.#wire = new Map(setup.tools.map((tool) => [tool, toWireTool(tool)]));\n this.hooks = new HookRunner({\n interceptors: setup.interceptors,\n runId: setup.runId,\n signal: setup.signal,\n clock: setup.clock,\n stepIndex: () => this.stepIndex,\n send: (body) => this.send(body),\n signer: setup.signer,\n nextId: setup.nextId,\n });\n }\n\n /** The wire form of each of `tools`, as a request sends them. */\n wireOf(tools: readonly AnyTool[]): WireTool[] {\n // Every tool of the run was lowered in the constructor, and a request names only the run's tools.\n return tools.map((tool) => this.#wire.get(tool) as WireTool);\n }\n\n send(body: AgentEventBody): void {\n this.emit(body, this.stepIndex);\n }\n\n append(message: Message): void {\n this.messages.push(message);\n this.added.push(message);\n }\n}\n\n/**\n * The stream options a request event records: everything but the payload hook, the abort signal and the caps, as the\n * gateway's own request dump leaves them out. An untyped caller may still pass a signal or caps in `modelOptions`.\n */\nfunction dumpedOptions(options: CallOptions): DumpedOptions {\n const { onPayload: _onPayload, signal: _signal, caps: _caps, ...rest } = options as StreamOptions;\n return rest;\n}\n\n/** Re-emits one model event as a run event, and returns the final message once the terminal event arrives. */\nfunction forward(state: LoopState, event: GatewayEvent): AssistantMessage | undefined {\n switch (event.type) {\n case \"done\":\n case \"error\":\n return event.message;\n case \"start\":\n return undefined;\n case \"retry\":\n state.send({ type: \"retry\", attempt: event.attempt, delayMs: event.delayMs, error: event.error });\n return undefined;\n case \"warning\":\n state.send({ type: \"warning\", code: \"model_warning\", detail: `${event.code}: ${event.message}` });\n return undefined;\n case \"text_start\":\n case \"reasoning_start\":\n case \"tool_input_start\":\n state.send({ type: event.type, index: event.index });\n return undefined;\n case \"text_delta\":\n case \"reasoning_delta\":\n case \"tool_input_delta\":\n state.send({ type: event.type, index: event.index, delta: event.delta });\n return undefined;\n default:\n state.send({ type: event.type, index: event.index, block: event.block });\n return undefined;\n }\n}\n\n/** One model call as it will be sent, after `transformContext` and `beforeModelCall`. */\ninterface Request {\n readonly model: Model;\n readonly context: ModelContext;\n readonly options: CallOptions;\n readonly active: readonly AnyTool[];\n}\n\n/** The tools a request sends unless `beforeModelCall` names others: the ones whose exposure is `direct`. */\nfunction directTools(tools: readonly AnyTool[]): AnyTool[] {\n return tools.filter((tool) => (tool.exposure ?? \"direct\") === \"direct\");\n}\n\n/** The tools `names` picks, in definition order whatever order `names` is in. */\nfunction toolsNamed(tools: readonly AnyTool[], names: readonly string[]): AnyTool[] {\n const unknown = names.filter((name) => !tools.some((tool) => tool.name === name));\n if (unknown.length > 0) {\n throw new SdkError(\"invalid_hook_result\", `activeTools names unknown tools: ${unknown.join(\", \")}`);\n }\n return tools.filter((tool) => names.includes(tool.name));\n}\n\nfunction patched(state: LoopState, request: Request, patch: ModelCallPatch): Request {\n const active = patch.activeTools === undefined ? request.active : toolsNamed(state.setup.tools, patch.activeTools);\n const { system, messages } = request.context;\n return {\n model: patch.model ?? request.model,\n options: patch.options ?? request.options,\n active,\n context: {\n system: patch.system ?? system,\n messages: patch.messages === undefined ? messages : [...patch.messages],\n tools: state.wireOf(active),\n },\n };\n}\n\n/**\n * Builds one call's request: the transcript, or the view `transformContext` returns for this call alone, then the\n * changes `beforeModelCall` asks for. The run's own transcript is never replaced by either.\n */\nasync function buildRequest(state: LoopState): Promise<Request> {\n const { model, system, modelOptions, tools } = state.setup;\n const view = await state.hooks.transformContext({\n system,\n messages: state.messages,\n model: model.ref,\n lastUsage: state.lastUsage,\n });\n const active = directTools(tools);\n const context = { system, messages: [...(view ?? state.messages)], tools: state.wireOf(active) };\n const request: Request = { model, context, options: modelOptions, active };\n const patch = await state.hooks.beforeModelCall({ context, options: modelOptions });\n return patch === undefined ? request : patched(state, request, patch);\n}\n\n/** Streams one request, re-emitting its events, and returns the model's final message. */\nasync function streamRequest(state: LoopState, request: Request): Promise<AssistantMessage> {\n const { model, context, options } = request;\n state.send({ type: \"model_call_start\", request: { model: model.ref, context, options: dumpedOptions(options) } });\n let message: AssistantMessage | undefined;\n for await (const event of model.stream(context, { ...options, signal: state.setup.signal })) {\n message = forward(state, event) ?? message;\n }\n if (message === undefined) {\n throw new SdkError(\"invalid_model_stream\", \"the model's stream ended without a done or error event\");\n }\n return message;\n}\n\n/** Adds a model call's response to the transcript and reports it. */\nfunction record(state: LoopState, message: AssistantMessage): void {\n state.append(message);\n state.send({ type: \"model_call_end\", message });\n}\n\n/**\n * What the transcript holds for a response whose `afterModelCall` failed while the run fails closed: no content, so a\n * check that crashed can't let the response through, but the call's usage and cost, which were billed. Its error stop\n * reason makes the replay pass skip it if the run is continued.\n */\nfunction withheld(original: AssistantMessage): AssistantMessage {\n const { model, usage, cost, lastAttemptUsage } = original;\n return {\n role: \"assistant\",\n content: [],\n model,\n stopReason: \"error\",\n error: { kind: \"fatal\", message: \"the response was withheld, because its afterModelCall check failed\" },\n usage,\n ...(lastAttemptUsage === undefined ? {} : { lastAttemptUsage }),\n cost,\n };\n}\n\n/**\n * The budget check before a call (D9): the outcome that ends the run when the spend so far plus the call's projected\n * cost would pass `budgetUsd`, or `undefined` when the call may go out. It checks the request as it will be sent,\n * after the interceptors have changed it, and projects with the model the request names.\n */\nfunction budgetBlock(state: LoopState, request: Request): Outcome | undefined {\n const { budgetUsd } = state.setup;\n if (budgetUsd === undefined) return undefined;\n const projected = projectCallCost(request.model, request.context, request.options);\n const verdict = checkBudget(budgetUsd, state.cost, projected);\n switch (verdict.kind) {\n case \"allow\":\n return undefined;\n case \"unknown\":\n return { stopReason: \"error\", error: verdict.error };\n case \"exceeded\":\n return {\n stopReason: \"budget\",\n reason: verdict.reason,\n budgetUsd,\n spentUsd: verdict.spentUsd,\n projectedUsd: verdict.projectedUsd,\n };\n }\n}\n\n/**\n * Makes one model call, streams its events and records the response. The call's usage and cost are the model's own\n * message's, so an `afterModelCall` replacement changes what the run goes on with, never what it is billed. When\n * `afterModelCall` fails and the run fails closed, a withheld stand-in is recorded before the run ends, so the\n * transcript and `model_call_end` still account for the billed call and none of its tool calls run.\n */\nasync function callModel(state: LoopState): Promise<AssistantMessage | { readonly blocked: Outcome }> {\n const request = await buildRequest(state);\n const blocked = budgetBlock(state, request);\n if (blocked !== undefined) return { blocked };\n state.active = request.active;\n const original = await streamRequest(state, request);\n state.steps += 1;\n state.usage = addUsage(state.usage, original.usage);\n state.lastUsage = original.usage;\n state.cost = state.cost === undefined ? original.cost : addCost(state.cost, original.cost);\n let message: AssistantMessage;\n try {\n message = await state.hooks.afterModelCall(original);\n } catch (error) {\n if (error instanceof HookFailure || (isSdkError(error) && error.code === \"invalid_hook_result\")) {\n record(state, withheld(original));\n }\n throw error;\n }\n record(state, message);\n return message;\n}\n\n/** The tool message the model reads for one call. */\nfunction toolMessage(entry: ToolCallResult): Message {\n return {\n role: \"tool\",\n callId: entry.call.callId,\n content: [...entry.result.content],\n isError: entry.result.isError === true,\n };\n}\n\n/** Runs the response's tool calls as the pipeline schedules them, recording each result in model order. */\nasync function runTools(state: LoopState, message: AssistantMessage): Promise<readonly ToolCallResult[]> {\n const { runId, signal, clock, output } = state.setup;\n return runToolCalls(message, state.active, {\n runId,\n signal,\n clock,\n depth: state.setup.depth,\n maxDepth: state.setup.maxDepth,\n ...state.hooks.pipelineHooks(),\n onStart: (call: ToolCall) =>\n state.send({ type: \"tool_call_start\", callId: call.callId, tool: call.name, input: call.input }),\n onUpdate: (callId, details) => state.send({ type: \"tool_call_update\", callId, details }),\n onPause: ({ request, input }) => {\n state.pending.push(request);\n state.pendingInputs[request.id] = input;\n state.send({ type: \"approval_request\", request, input });\n },\n onResult: (entry) => {\n state.append(toolMessage(entry));\n if (output !== undefined && entry.call.name === output.name && entry.result.isError !== true) {\n state.output = entry.result.structured;\n }\n const ranWith = \"input\" in entry ? { input: entry.input } : {};\n state.send({ type: \"tool_call_end\", callId: entry.call.callId, result: entry.result, ...ranWith });\n },\n });\n}\n\n/** The failed call's error as the run reports it. A message without one counts as `fatal`. */\nfunction runErrorOf(message: AssistantMessage): RunError {\n const error = message.error;\n if (error === undefined) return { kind: \"fatal\", message: \"the model call failed without an error description\" };\n return { kind: error.kind, message: error.message, ...(error.status === undefined ? {} : { status: error.status }) };\n}\n\n/**\n * The stop check after one step. A pause, a finished answer or a question for the user wins over an abort that came\n * too late to change it; otherwise an abort stops the run before the step cap does. A pause wins over a finished\n * answer too, because its call is still waiting. A text answer cut off at the output limit\n * also counts as finished: its message keeps `stopReason: \"length\"`.\n */\nfunction stopCheck(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Outcome | undefined {\n if (message.stopReason === \"error\") return { stopReason: \"error\", error: runErrorOf(message) };\n if (message.stopReason === \"aborted\") return { stopReason: \"aborted\" };\n // A paused call is still waiting, so the run can't count as finished, and the pause is signed and stored with the\n // context, so it outlasts an abort that came while the step's other calls ran.\n if (state.pending.length > 0) {\n return { stopReason: \"awaiting_approval\", pending: [...state.pending], pendingInputs: { ...state.pendingInputs } };\n }\n const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);\n if (finished) return { stopReason: \"done\", output: state.output };\n // Until runs can pause for an answer, a clarification question stops the run, so the model never goes on as if the\n // user had been asked and answered.\n if (results.some(({ result }) => result.pause !== undefined && !result.isError)) {\n return { stopReason: \"stopped\", stoppedBy: CLARIFICATION };\n }\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n return undefined;\n}\n\n/**\n * What `shouldStop` changes about the stop check. A finished answer or an error stands whatever the hook says; the\n * hook can end a run that would go on, and can keep going a run the model ended by answering in text, until the\n * step cap.\n */\nfunction withVerdict(state: LoopState, natural: Outcome | undefined, verdict: StopVerdict): Outcome | undefined {\n if (natural !== undefined && verdict.kind !== \"continue\") return natural;\n switch (verdict.kind) {\n case \"stop\":\n return { stopReason: \"stopped\", stoppedBy: verdict.stoppedBy };\n case \"no_progress\":\n return { stopReason: \"no_progress\", reason: verdict.reason };\n case \"continue\":\n if (natural === undefined) return undefined;\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n state.append({ role: \"user\", content: verdict.content });\n return undefined;\n default:\n return natural;\n }\n}\n\n/**\n * Applies the queued messages before a model call: every steer, and the follow-ups too once the run was kept going to\n * deliver them. Each becomes a user message and a `steer_applied` event, in the order it was sent, and its receipt\n * resolves with the index of the step about to run.\n */\nfunction applySteering(state: LoopState): void {\n const { steering } = state.setup;\n const withFollowUps = state.releaseFollowUps;\n state.releaseFollowUps = false;\n for (const delivery of steering.take(withFollowUps)) {\n // A copy, so a caller who changes a receipt's message cannot change the transcript.\n state.append({ role: \"user\", content: delivery.message.map((block) => ({ ...block })) });\n state.send({ type: \"steer_applied\", receipt: delivery.deliver(state.stepIndex) });\n }\n}\n\n/**\n * Keeps a run that its model ended by answering going, when a message is waiting and the step cap leaves room for\n * one more call: a steer comes first, and follow-ups wait for the next time the run would end. Any other outcome\n * stands, as does a `stop` or `no_progress` verdict that `withVerdict` folded into `done`, and an abort that came\n * after the answer, which `stopCheck` lets the answer win over. The messages still waiting are rejected when the run\n * ends.\n */\nfunction withQueued(state: LoopState, outcome: Outcome | undefined, verdict: StopVerdict): Outcome | undefined {\n const { steering, maxSteps, signal } = state.setup;\n if (outcome?.stopReason !== \"done\" || !steering.hasPending() || state.steps >= maxSteps) return outcome;\n if (verdict.kind === \"stop\" || verdict.kind === \"no_progress\" || signal.aborted) return outcome;\n state.releaseFollowUps = !steering.hasSteers();\n return undefined;\n}\n\n/** The stop check after one step, then the `shouldStop` hook where it may change it. */\nasync function decide(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Promise<Outcome | undefined> {\n const natural = stopCheck(state, message, results);\n const endedByAnswer = natural?.stopReason === \"done\" && results.length === 0;\n if (natural !== undefined && !endedByAnswer) return natural;\n const verdict = await state.hooks.shouldStop({ messages: state.messages, lastMessage: message });\n const judged = await withProgress(state, verdict);\n const outcome = withVerdict(state, natural, judged);\n return endedByAnswer ? withQueued(state, outcome, judged) : outcome;\n}\n\n/**\n * The caller's verdict, unless the progress policy finds the run stuck. A caller's own stop stands, and a caller's\n * `{ continue }` or failed hook can't keep a stuck run going.\n */\nasync function withProgress(state: LoopState, verdict: StopVerdict): Promise<StopVerdict> {\n if (verdict.kind === \"stop\" || verdict.kind === \"no_progress\" || state.setup.progress === undefined) return verdict;\n const reason = await state.setup.progress(state.messages);\n return reason === undefined ? verdict : { kind: \"no_progress\", reason };\n}\n\n/** The outcome of a hook that failed while the run fails closed. A failure caused by an abort ends the run aborted. */\nfunction failedOutcome(state: LoopState, error: unknown): Outcome {\n if (!(error instanceof HookFailure)) throw error;\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n return { stopReason: \"error\", error: { kind: \"hook\", message: error.message } };\n}\n\nasync function runStep(state: LoopState): Promise<Outcome | undefined> {\n state.stepIndex = state.steps;\n state.send({ type: \"step_start\" });\n let outcome: Outcome | undefined;\n try {\n applySteering(state);\n const called = await callModel(state);\n if (\"blocked\" in called) {\n outcome = called.blocked;\n } else {\n const results = await runTools(state, called);\n outcome = await decide(state, called, results);\n }\n } catch (error) {\n outcome = failedOutcome(state, error);\n }\n state.send({ type: \"step_end\", stopCheck: outcome === undefined ? \"continue\" : \"stop\" });\n return outcome;\n}\n\n/**\n * An aborted run's transcript ends with an assistant message whose `stopReason` is `\"aborted\"`. When tool results end\n * the transcript, because the abort came while tools ran or cut off a response that held tool calls, the loop\n * appends an empty one after them; the replay pass drops it before any request.\n */\nfunction closeAborted(state: LoopState): void {\n const last = state.messages.at(-1);\n if (last?.role === \"assistant\" && last.stopReason === \"aborted\") return;\n state.append({\n role: \"assistant\",\n content: [],\n model: state.setup.model.ref,\n stopReason: \"aborted\",\n usage: emptyUsage(),\n cost: { ...NO_COST },\n });\n}\n\nfunction resultOf(state: LoopState, outcome: Outcome): RunResult {\n const pending =\n outcome.stopReason === \"awaiting_approval\"\n ? { pending: [...outcome.pending], pendingInputs: { ...outcome.pendingInputs } }\n : {};\n const base = {\n messages: state.added,\n context: { system: state.setup.system, messages: state.messages, ...pending },\n usage: state.usage,\n cost: state.cost ?? { ...NO_COST },\n steps: state.steps,\n };\n return { ...base, ...outcome } as RunResult;\n}\n\n/**\n * Ends the run: the settle event comes once every observer has seen what came before it, and `run_end` after that.\n * An observer's failure while handling `agent_settled` is reported between the two; one while handling `run_end` is\n * dropped, so `run_end` stays the last event. The result is returned only once observers have seen it.\n */\nasync function finish(state: LoopState, outcome: Outcome): Promise<RunResult> {\n if (outcome.stopReason === \"aborted\") closeAborted(state);\n if (outcome.stopReason === \"max_steps\") {\n state.send({ type: \"warning\", code: \"max_steps\", detail: `the run reached maxSteps (${state.setup.maxSteps})` });\n }\n if (outcome.stopReason === \"error\") state.send({ type: \"error\", error: outcome.error });\n await state.drain();\n state.send({ type: \"agent_settled\" });\n await state.drain();\n const result = resultOf(state, outcome);\n state.send({ type: \"run_end\", result });\n await state.drain();\n return result;\n}\n\n/**\n * Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results\n * already received are in the transcript.\n */\nexport async function runLoop(setup: LoopSetup, emit: Emit, drain: Drain): Promise<RunResult> {\n const state = new LoopState(setup, emit, drain);\n // A budget needs a price to check against, so a model without one is refused before it is called (D4).\n const refused = setup.budgetUsd === undefined ? undefined : unknownPriceError(setup.model);\n let outcome: Outcome | undefined = refused === undefined ? undefined : { stopReason: \"error\", error: refused };\n try {\n while (outcome === undefined) {\n outcome = setup.signal.aborted ? { stopReason: \"aborted\" } : await runStep(state);\n }\n } finally {\n // The run has its outcome, or threw for a programmer error, so a message still waiting can no longer reach a\n // model call, and its receipt must not hang.\n setup.steering.close();\n }\n return finish(state, outcome);\n}\n"]}