@buildanagent/sdk 0.1.0-alpha.12 → 0.1.0-alpha.14

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.
package/README.md CHANGED
@@ -42,7 +42,7 @@ A failed model call or a failing tool never makes a run throw. The run ends with
42
42
 
43
43
  - **`done`**: the model answered without calling a tool, or an output tool accepted its answer. A text answer cut off at `maxOutputTokens` also ends `done`, so check whether the last message's `stopReason` is `"length"` before you show it as complete.
44
44
  - **`max_steps`**: the run made `maxSteps` model calls, 20 by default, and the model still wanted to go on. The run also emits a `warning` event with `code: "max_steps"`, so a cap that cut a run short shows up in your logs.
45
- - **`error`**: a model call failed. `result.error` copies the failure's `kind`, `message` and HTTP `status`. Its `kind` is `overflow` for a request too large for the model's window, `quota` for an account out of credit, `retryable` for a temporary failure that outlasted the gateway's retries, `hook` for an interceptor that threw while the run fails closed, `unknown_price` for a budgeted run that can't price a call, and `fatal` otherwise.
45
+ - **`error`**: a model call failed. `result.error` copies the failure's `kind`, `message` and HTTP `status`. Its `kind` is `overflow` for a request too large for the model's window, `quota` for an account out of credit, `retryable` for a temporary failure that outlasted the gateway's retries and your `turnRetries`, `hook` for an interceptor that threw while the run fails closed, `unknown_price` for a budgeted run that can't price a call, and `fatal` otherwise.
46
46
  - **`aborted`**: you aborted the run.
47
47
  - **`stopped`**: a `shouldStop` hook ended the run, and `result.stoppedBy` is the reason it gave.
48
48
  - **`no_progress`**: the default progress policy found the model repeating a failing call, or a `shouldStop` hook ended the run with `{ stop: "no_progress", reason }`. `result.reason` says why.
@@ -54,6 +54,25 @@ A failed model call or a failing tool never makes a run throw. The run ends with
54
54
 
55
55
  Only the `done` result carries `output`. TypeScript rejects `result.output` until you have checked `result.stopReason === "done"`, so an unfinished run can't pass for a finished one. Every result carries `usage` and `cost`, summed over the run's model calls, and `steps`, the number of calls. `result.messages` holds the messages this run added. `result.context` holds the whole conversation, ready to continue.
56
56
 
57
+ ### Three layers retry a failed model call, and the SDK's is off by default
58
+
59
+ Three layers can retry a failed model call: the gateway, the loop and your own code. The gateway re-sends an HTTP request that failed before any output, twice by default. It never replays a call after output has started, because you have already seen that text. The loop's `turnRetries` covers that case: it calls the model again after a call that ended with a `retryable` error, such as a stream cut off after it began to answer. Without `turnRetries` the run ends `error` on the first failure, and `continueRun()` is how your code tries again.
60
+
61
+ ```ts
62
+ const result = await run({ model, system, input, turnRetries: 3 }).result;
63
+ ```
64
+
65
+ `turnRetries: 3` retries as Pi does. A turn retry follows these rules:
66
+
67
+ - **Only `retryable` failures retry.** `overflow`, `quota` and `fatal` end the run, and so does a `retryable` failure whose `error.retryAfterMs` is over the gateway's 60-second cap, which keeps its hint on the last message so you can wait and call again.
68
+ - **The wait matches the gateway's.** The first retry waits `turnRetryDelayMs` (2000 by default), each later retry of a streak waits twice as long, and a longer `retryAfterMs` hint wins, up to 60 seconds. Pass `sleep` to skip the wait in a test; a `sleep` that rejects ends the wait early and emits a `hook_error` event with `hook: "sleep"`. Aborting the run during the wait ends it `aborted`.
69
+ - **A retry costs a step.** Every attempt counts against `maxSteps`, so `maxSteps` still bounds the worst case. A run that `maxSteps` stops after at least one retry ends `max_steps`, with the last failed message in its transcript; a first failure on the last step ends `error`, as it would without `turnRetries`. The count of retries restarts after each call that succeeds.
70
+ - **A retry costs money.** The result's `usage` and `cost` include every failed attempt, and `budgetUsd` checks before each retry, counting what the failed attempts cost. A retry the budget can't cover is never announced: the run ends `budget` with the failed message in its transcript. When a failed attempt's cost is unknown, such as after a stream cut off before the provider reported usage, a budgeted run can't check its spend. It ends `error` with that failure's own error instead of retrying.
71
+ - **The transcript drops the failed message.** `result.context.messages` holds only the response the run went on with, and the failed call's tool calls never run. `afterModelCall` sees only that response, while `transformContext` and `beforeModelCall` run for every attempt. Their `lastUsage` stays the usage of the last response the run went on with.
72
+ - **The layers multiply.** A call can send up to `(retries + 1) * (turnRetries + 1)` requests, nine with the defaults and `turnRetries: 2`, so lower one of the two when a provider is failing hard.
73
+
74
+ A failed attempt ends with `model_call_end`, whose message carries its real usage. A `retry` event with `layer: "turn"` follows at once. After the wait, the failed attempt's `step_end` arrives, then the retry's `step_start` and `model_call_start`: every attempt is a step with its own `stepIndex`. A log writer should therefore drop a `model_call_end` that a turn `retry` follows, and keep every other one. A UI that rendered the failed call's text deltas must discard them when the `retry` event arrives, because the retry streams its own text.
75
+
57
76
  ### `runOrThrow()` turns an unfinished run into an exception
58
77
 
59
78
  If you would rather catch an exception than check the stop reason, `runOrThrow(run)` returns the `done` result and throws a `RunStoppedError` for any other. The error carries the `result` and the `context` to continue from. `RunStoppedError.isInstance(error)` recognises it, even across two copies of the package:
@@ -155,7 +174,7 @@ The events come in two layers. The delta layer streams each content block by its
155
174
  - **`steer_applied`** reports a queued steer or follow-up that entered the transcript, with its receipt.
156
175
  - **`approval_request`** reports a call that waits for a person, with its signed `request` and the `input` that request signs: a call a gate paused, or a tool's question. That call gets no `tool_call_end`. In a resumed run, **`resolution_rejected`** reports a request or resolution that failed its check, with the cause.
157
176
  - **`hook_error`** reports an interceptor or an observer that threw, with the hook's name and the message. It also reports a pause that could not be signed, with `hook: "signer"`.
158
- - **`retry`** reports a failed request the gateway is retrying, and **`warning`** reports a reached cap or a model warning.
177
+ - **`retry`** reports a failed call that is being retried. Its `layer` is `gateway` for an HTTP request the model re-sends, or `turn` for a call the loop re-issues, as [the retry section](#three-layers-retry-a-failed-model-call-and-the-sdks-is-off-by-default) explains. **`warning`** reports a reached cap or a model warning.
159
178
  - **`error`** and **`abort`** report a failed call and an abort request.
160
179
  - **`agent_settled`** fires once nothing is running any more, retries and tools included. **`run_end`** follows it and carries the result.
161
180
 
@@ -508,6 +527,37 @@ Nothing in the testing export reads the system clock or `Math.random()`. `fixedC
508
527
 
509
528
  Start each test file with `import "@buildanagent/gateway/testing/setup"`, which keeps the test offline.
510
529
 
530
+ ## The support-triage capstone shows the whole SDK working in one agent
531
+
532
+ The capstone is the support-triage agent that each of the eight SDKs we verified implements, built on our SDK in [`examples/triage-agent.ts`](examples/triage-agent.ts). It gives the model a read-only `lookup_customer` tool, an `escalate` tool that waits for a person, and a `submit_triage` output tool. An audit observer records every call, the run stops after 8 steps, and a $0.25 budget stops it earlier. `startTriage()` runs the agent, and `resumeTriage()` resumes a paused run from its stored `context`, which can happen in another process that holds the same signing key.
533
+
534
+ The conformance suite in [`test/triage-suite.ts`](test/triage-suite.ts) takes a loop's `run` and `continueRun` and checks these behaviours on each backend. The backends are the scripted model and the Anthropic and Chat Completions mock transports:
535
+
536
+ - an approved escalation runs once in a second process and ends with a typed result;
537
+ - a rejected escalation never runs, and the model reads the denial;
538
+ - a result that fails its schema returns to the model as an error;
539
+ - a forged signature runs nothing and calls no model;
540
+ - a stored input that no longer matches its signature runs nothing;
541
+ - the step cap and the budget each end a runaway run;
542
+ - every request offers only `lookup_customer`, `escalate` and `submit_triage`.
543
+
544
+ The cases assert nothing about observers, so a loop without them can run the suite. `test/capstone.test.ts` checks the audit trail on the SDK's loop.
545
+
546
+ The tables in the [deep comparison](../../docs/comparison/deep-comparison.md#1-the-same-agent-takes-58-to-115-lines-on-every-sdk-and-differs-in-its-gate) count non-blank, non-comment lines, and include each reference file's scripted model and assertions. Our agent file holds neither, so the second row adds the suite and its backends, which cover more cases on three backends. The figures below are counted from the files as they are now, so two reference rows differ from the comparison's, which predates later edits to those files. A test recounts every row and the hook count, and fails when the table drifts. The Hooks column counts the extra pieces a capstone needs beyond its tools. Ours are the `beforeToolCall` gate and the audit observer, and LangChain's are two as well; a blank cell means the comparison records none.
547
+
548
+ | Capstone | Code lines | Hooks |
549
+ | --- | --- | --- |
550
+ | Our capstone, the agent alone | 80 | 2 |
551
+ | Our capstone with its cases and backends | 434 | 2 |
552
+ | Vercel AI SDK | 58 | |
553
+ | Claude Agent SDK | 62 | |
554
+ | LangChain.js | 67 | 2 |
555
+ | OpenAI Agents SDK | 76 | |
556
+ | Pi | 87 | |
557
+ | Copilot SDK | 105 | |
558
+ | Google ADK | 114 | |
559
+ | Cloudflare Agents | 122 | |
560
+
511
561
  ## Build the SDK with its dependencies
512
562
 
513
563
  The SDK compiles against the gateway's built `dist/*.d.ts`, so build both from the repo root with `pnpm --filter "@buildanagent/sdk..." build`, which builds the gateway first. `pnpm build` builds every package in the same order. On a clean checkout, `pnpm build` or `pnpm pack` run inside `packages/sdk` fails, because the gateway has no `dist/` yet. Tests and type-checks need no build.
package/dist/events.d.ts CHANGED
@@ -99,9 +99,18 @@ export type AgentEventBody = {
99
99
  readonly before: number;
100
100
  readonly after: number;
101
101
  }
102
- /** The model is retrying a failed request; `attempt` is 1 for the first retry. */
102
+ /**
103
+ * A failed model call is being retried; `attempt` is 1 for the first retry. `layer` says which retry it is.
104
+ * `gateway`: the model retries an HTTP request that failed before any output; its events follow `model_call_start`
105
+ * and nothing was streamed from the failed attempt. `turn`: the loop re-issues a call that ended with a `retryable`
106
+ * error, which `turnRetries` turns on. It comes right after that call's `model_call_end`, whose message is
107
+ * superseded: it is not in the transcript, and a UI that rendered the call's streamed deltas should discard them,
108
+ * because the retry streams its own. Once the wait ends, the failed call's `step_end` follows, then the retry's own
109
+ * `step_start` and `model_call_start` at the next `stepIndex`.
110
+ */
103
111
  | {
104
112
  readonly type: "retry";
113
+ readonly layer: "gateway" | "turn";
105
114
  readonly attempt: number;
106
115
  readonly delayMs: number;
107
116
  readonly error: string;
@@ -142,10 +151,11 @@ export type AgentEventBody = {
142
151
  readonly cause: ResolutionRejectionCause;
143
152
  }
144
153
  /**
145
- * An interceptor or an observer threw, or a pause could not be signed. `hook` names it (`beforeToolCall`,
146
- * `observer`, `signer` and so on) and `error` is the thrown message; for `signer` it is a fixed text with the
147
- * safety package's error code, never the signer's own message. The run goes on or fails by the interceptors'
148
- * `onFailure` setting; a failed observer never affects it, and a call whose pause could not be signed is blocked.
154
+ * An interceptor or an observer threw, a pause could not be signed, or a `sleep` passed to `run()` rejected. `hook`
155
+ * names it (`beforeToolCall`, `observer`, `signer`, `sleep` and so on) and `error` is the thrown message; for
156
+ * `signer` it is a fixed text with the safety package's error code, never the signer's own message. The run goes on
157
+ * or fails by the interceptors' `onFailure` setting; a failed observer never affects it, a call whose pause could
158
+ * not be signed is blocked, and a rejected `sleep` ends the wait before a turn retry early.
149
159
  */
150
160
  | {
151
161
  readonly type: "hook_error";
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAiIA,oEAAoE;AACpE,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC7C,WAAW;IACX,YAAY;IACZ,kBAAkB;IAClB,OAAO;IACP,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,iBAAiB;IACjB,iBAAiB;IACjB,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,gBAAgB;IAChB,SAAS;IACT,gBAAgB;IAChB,qBAAqB;IACrB,YAAY;IACZ,eAAe;IACf,iBAAiB;IACjB,kBAAkB;IAClB,qBAAqB;IACrB,kBAAkB;IAClB,eAAe;IACf,UAAU;IACV,OAAO;IACP,OAAO;IACP,eAAe;IACf,SAAS;CACuC,CAAC,CAAC","sourcesContent":["/**\n * The events a run streams: one closed union in two layers (agent-SDK guide §5). The delta layer streams each content\n * block by its index; the item layer's end events (`model_call_end`, `tool_call_end`, `run_end`) carry the\n * authoritative item, which a session log stores. `AGENT_EVENT_TYPES` lists the union at run time, so a test can\n * check that the loop emits no type the union does not declare.\n */\nimport type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from \"@buildanagent/gateway\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { DeliveryReceipt } from \"./steering.js\";\nimport type { ToolResult } from \"./tools/types.js\";\nimport type { RejectionCause, SignedPendingRequest } from \"./vendor/agent-safety/pending.js\";\n\n/** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */\nexport interface EventBase {\n readonly runId: string;\n readonly seq: number;\n readonly stepIndex: number;\n /** When the event was emitted, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** One model call's request as the loop sends it: the model, the context and the options. */\nexport interface ModelCallRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: DumpedOptions;\n}\n\n/**\n * Why a `warning` event fired. `max_steps`: the run reached `maxSteps` and stopped. `model_warning`: the model call\n * reported something that did not stop it, such as an option the provider would reject and the adapter dropped.\n */\nexport type WarningCode = \"max_steps\" | \"model_warning\";\n\n/**\n * Why `continueRun()` refused a resolution or a stored request: one of `verifyResolution()`'s causes, `replayed` when\n * two resolutions name one request, or `error` when the check itself threw, such as a signer whose `verify()` threw.\n * `unknown_request` also covers a resolution that names no request in the context.\n */\nexport type ResolutionRejectionCause = RejectionCause | \"replayed\" | \"error\";\n\n/** The body of each event, without the fields of `EventBase`. */\nexport type AgentEventBody =\n | {\n readonly type: \"run_start\";\n readonly sdkVersion: string;\n readonly specVersion: \"v1\";\n /** Reserved for a hash of the run's defaults; empty for now. */\n readonly defaultsHash: string;\n /** Reserved for the SDK's capability names; empty for now. */\n readonly capabilities: readonly string[];\n readonly model: ModelRef;\n }\n | { readonly type: \"run_end\"; readonly result: RunResult }\n /** Fires once nothing is running any more, retries and tools included; `run_end` follows it. */\n | { readonly type: \"agent_settled\" }\n | { readonly type: \"step_start\" }\n | { readonly type: \"step_end\"; readonly stopCheck: \"continue\" | \"stop\" }\n | { readonly type: \"model_call_start\"; readonly request: ModelCallRequest }\n | { readonly type: \"model_call_end\"; readonly message: AssistantMessage }\n | { readonly type: \"text_start\" | \"reasoning_start\" | \"tool_input_start\"; readonly index: number }\n | {\n readonly type: \"text_delta\" | \"reasoning_delta\" | \"tool_input_delta\";\n readonly index: number;\n readonly delta: string;\n }\n | {\n readonly type: \"text_end\" | \"reasoning_end\" | \"tool_input_end\";\n readonly index: number;\n readonly block: ContentBlock;\n }\n | { readonly type: \"tool_call_start\"; readonly callId: string; readonly tool: string; readonly input: unknown }\n | { readonly type: \"tool_call_update\"; readonly callId: string; readonly details: unknown }\n /**\n * `result` is what the model reads for the call, after `afterToolCall` has had its say. `input` is present only\n * when a `beforeToolCall` gate replaced the model's input, and holds the input the gate gave the call instead.\n */\n | {\n readonly type: \"tool_call_end\";\n readonly callId: string;\n readonly result: ToolResult;\n readonly input?: unknown;\n }\n /** `transformContext` returned the messages for one model call: `before` messages in, `after` messages out. */\n | { readonly type: \"context_transformed\"; readonly before: number; readonly after: number }\n /** The model is retrying a failed request; `attempt` is 1 for the first retry. */\n | { readonly type: \"retry\"; readonly attempt: number; readonly delayMs: number; readonly error: string }\n /**\n * A queued steer or follow-up entered the transcript as a user message, at the start of the step named by\n * `receipt.stepIndex`, before its model call. `receipt.kind` tells the two apart.\n */\n | { readonly type: \"steer_applied\"; readonly receipt: DeliveryReceipt }\n /**\n * The run signed a pending request for a call that waits for a person; `request.kind` tells the two kinds apart.\n * An `approval`: a gate returned `ask`. `input` is the input the request signs and the call would run with once\n * approved: the model's input after coercion, `repair` and any gate's replacement, so show the approver this, not\n * the model's raw arguments. It comes once every call of the step has been gated, after the call's\n * `tool_call_start` and before any call of the step runs; under `blockingApprovals()` it comes before the run waits\n * for the answer. A `clarification`: a tool asked the user `request.question`, and `input` is the input it ran\n * with; it comes once every call of the step has its result. A waiting call gets no `tool_call_end`, and the run\n * ends `awaiting_approval` or `clarification_requested` after the step.\n */\n | { readonly type: \"approval_request\"; readonly request: SignedPendingRequest; readonly input: unknown }\n /**\n * `continueRun()` refused a resolution, or a stored request it had to check: the call did not run, and unless the\n * resolution named no request in the context, the call asks again with a new request, which an `approval_request`\n * event follows. `requestId` is the id the resolution or the stored request gave, and `callId` the waiting call's,\n * when there is one. It holds no signature and no key.\n */\n | {\n readonly type: \"resolution_rejected\";\n readonly requestId: string;\n readonly callId?: string;\n readonly cause: ResolutionRejectionCause;\n }\n /**\n * An interceptor or an observer threw, or a pause could not be signed. `hook` names it (`beforeToolCall`,\n * `observer`, `signer` and so on) and `error` is the thrown message; for `signer` it is a fixed text with the\n * safety package's error code, never the signer's own message. The run goes on or fails by the interceptors'\n * `onFailure` setting; a failed observer never affects it, and a call whose pause could not be signed is blocked.\n */\n | { readonly type: \"hook_error\"; readonly hook: string; readonly error: string }\n | { readonly type: \"warning\"; readonly code: WarningCode; readonly detail: string }\n | { readonly type: \"error\"; readonly error: RunError }\n | { readonly type: \"abort\"; readonly reason?: string };\n\n/** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */\nexport type AgentEvent = EventBase & AgentEventBody;\n\n/** Every `AgentEvent` type. A run emits no type this list lacks. */\nexport const AGENT_EVENT_TYPES = Object.freeze([\n \"run_start\",\n \"step_start\",\n \"model_call_start\",\n \"retry\",\n \"text_start\",\n \"text_delta\",\n \"text_end\",\n \"reasoning_start\",\n \"reasoning_delta\",\n \"reasoning_end\",\n \"tool_input_start\",\n \"tool_input_delta\",\n \"tool_input_end\",\n \"warning\",\n \"model_call_end\",\n \"context_transformed\",\n \"hook_error\",\n \"steer_applied\",\n \"tool_call_start\",\n \"approval_request\",\n \"resolution_rejected\",\n \"tool_call_update\",\n \"tool_call_end\",\n \"step_end\",\n \"error\",\n \"abort\",\n \"agent_settled\",\n \"run_end\",\n] as const satisfies readonly AgentEvent[\"type\"][]);\n"]}
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAgJA,oEAAoE;AACpE,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC7C,WAAW;IACX,YAAY;IACZ,kBAAkB;IAClB,OAAO;IACP,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,iBAAiB;IACjB,iBAAiB;IACjB,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,gBAAgB;IAChB,SAAS;IACT,gBAAgB;IAChB,qBAAqB;IACrB,YAAY;IACZ,eAAe;IACf,iBAAiB;IACjB,kBAAkB;IAClB,qBAAqB;IACrB,kBAAkB;IAClB,eAAe;IACf,UAAU;IACV,OAAO;IACP,OAAO;IACP,eAAe;IACf,SAAS;CACuC,CAAC,CAAC","sourcesContent":["/**\n * The events a run streams: one closed union in two layers (agent-SDK guide §5). The delta layer streams each content\n * block by its index; the item layer's end events (`model_call_end`, `tool_call_end`, `run_end`) carry the\n * authoritative item, which a session log stores. `AGENT_EVENT_TYPES` lists the union at run time, so a test can\n * check that the loop emits no type the union does not declare.\n */\nimport type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from \"@buildanagent/gateway\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { DeliveryReceipt } from \"./steering.js\";\nimport type { ToolResult } from \"./tools/types.js\";\nimport type { RejectionCause, SignedPendingRequest } from \"./vendor/agent-safety/pending.js\";\n\n/** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */\nexport interface EventBase {\n readonly runId: string;\n readonly seq: number;\n readonly stepIndex: number;\n /** When the event was emitted, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** One model call's request as the loop sends it: the model, the context and the options. */\nexport interface ModelCallRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: DumpedOptions;\n}\n\n/**\n * Why a `warning` event fired. `max_steps`: the run reached `maxSteps` and stopped. `model_warning`: the model call\n * reported something that did not stop it, such as an option the provider would reject and the adapter dropped.\n */\nexport type WarningCode = \"max_steps\" | \"model_warning\";\n\n/**\n * Why `continueRun()` refused a resolution or a stored request: one of `verifyResolution()`'s causes, `replayed` when\n * two resolutions name one request, or `error` when the check itself threw, such as a signer whose `verify()` threw.\n * `unknown_request` also covers a resolution that names no request in the context.\n */\nexport type ResolutionRejectionCause = RejectionCause | \"replayed\" | \"error\";\n\n/** The body of each event, without the fields of `EventBase`. */\nexport type AgentEventBody =\n | {\n readonly type: \"run_start\";\n readonly sdkVersion: string;\n readonly specVersion: \"v1\";\n /** Reserved for a hash of the run's defaults; empty for now. */\n readonly defaultsHash: string;\n /** Reserved for the SDK's capability names; empty for now. */\n readonly capabilities: readonly string[];\n readonly model: ModelRef;\n }\n | { readonly type: \"run_end\"; readonly result: RunResult }\n /** Fires once nothing is running any more, retries and tools included; `run_end` follows it. */\n | { readonly type: \"agent_settled\" }\n | { readonly type: \"step_start\" }\n | { readonly type: \"step_end\"; readonly stopCheck: \"continue\" | \"stop\" }\n | { readonly type: \"model_call_start\"; readonly request: ModelCallRequest }\n | { readonly type: \"model_call_end\"; readonly message: AssistantMessage }\n | { readonly type: \"text_start\" | \"reasoning_start\" | \"tool_input_start\"; readonly index: number }\n | {\n readonly type: \"text_delta\" | \"reasoning_delta\" | \"tool_input_delta\";\n readonly index: number;\n readonly delta: string;\n }\n | {\n readonly type: \"text_end\" | \"reasoning_end\" | \"tool_input_end\";\n readonly index: number;\n readonly block: ContentBlock;\n }\n | { readonly type: \"tool_call_start\"; readonly callId: string; readonly tool: string; readonly input: unknown }\n | { readonly type: \"tool_call_update\"; readonly callId: string; readonly details: unknown }\n /**\n * `result` is what the model reads for the call, after `afterToolCall` has had its say. `input` is present only\n * when a `beforeToolCall` gate replaced the model's input, and holds the input the gate gave the call instead.\n */\n | {\n readonly type: \"tool_call_end\";\n readonly callId: string;\n readonly result: ToolResult;\n readonly input?: unknown;\n }\n /** `transformContext` returned the messages for one model call: `before` messages in, `after` messages out. */\n | { readonly type: \"context_transformed\"; readonly before: number; readonly after: number }\n /**\n * A failed model call is being retried; `attempt` is 1 for the first retry. `layer` says which retry it is.\n * `gateway`: the model retries an HTTP request that failed before any output; its events follow `model_call_start`\n * and nothing was streamed from the failed attempt. `turn`: the loop re-issues a call that ended with a `retryable`\n * error, which `turnRetries` turns on. It comes right after that call's `model_call_end`, whose message is\n * superseded: it is not in the transcript, and a UI that rendered the call's streamed deltas should discard them,\n * because the retry streams its own. Once the wait ends, the failed call's `step_end` follows, then the retry's own\n * `step_start` and `model_call_start` at the next `stepIndex`.\n */\n | {\n readonly type: \"retry\";\n readonly layer: \"gateway\" | \"turn\";\n readonly attempt: number;\n readonly delayMs: number;\n readonly error: string;\n }\n /**\n * A queued steer or follow-up entered the transcript as a user message, at the start of the step named by\n * `receipt.stepIndex`, before its model call. `receipt.kind` tells the two apart.\n */\n | { readonly type: \"steer_applied\"; readonly receipt: DeliveryReceipt }\n /**\n * The run signed a pending request for a call that waits for a person; `request.kind` tells the two kinds apart.\n * An `approval`: a gate returned `ask`. `input` is the input the request signs and the call would run with once\n * approved: the model's input after coercion, `repair` and any gate's replacement, so show the approver this, not\n * the model's raw arguments. It comes once every call of the step has been gated, after the call's\n * `tool_call_start` and before any call of the step runs; under `blockingApprovals()` it comes before the run waits\n * for the answer. A `clarification`: a tool asked the user `request.question`, and `input` is the input it ran\n * with; it comes once every call of the step has its result. A waiting call gets no `tool_call_end`, and the run\n * ends `awaiting_approval` or `clarification_requested` after the step.\n */\n | { readonly type: \"approval_request\"; readonly request: SignedPendingRequest; readonly input: unknown }\n /**\n * `continueRun()` refused a resolution, or a stored request it had to check: the call did not run, and unless the\n * resolution named no request in the context, the call asks again with a new request, which an `approval_request`\n * event follows. `requestId` is the id the resolution or the stored request gave, and `callId` the waiting call's,\n * when there is one. It holds no signature and no key.\n */\n | {\n readonly type: \"resolution_rejected\";\n readonly requestId: string;\n readonly callId?: string;\n readonly cause: ResolutionRejectionCause;\n }\n /**\n * An interceptor or an observer threw, a pause could not be signed, or a `sleep` passed to `run()` rejected. `hook`\n * names it (`beforeToolCall`, `observer`, `signer`, `sleep` and so on) and `error` is the thrown message; for\n * `signer` it is a fixed text with the safety package's error code, never the signer's own message. The run goes on\n * or fails by the interceptors' `onFailure` setting; a failed observer never affects it, a call whose pause could\n * not be signed is blocked, and a rejected `sleep` ends the wait before a turn retry early.\n */\n | { readonly type: \"hook_error\"; readonly hook: string; readonly error: string }\n | { readonly type: \"warning\"; readonly code: WarningCode; readonly detail: string }\n | { readonly type: \"error\"; readonly error: RunError }\n | { readonly type: \"abort\"; readonly reason?: string };\n\n/** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */\nexport type AgentEvent = EventBase & AgentEventBody;\n\n/** Every `AgentEvent` type. A run emits no type this list lacks. */\nexport const AGENT_EVENT_TYPES = Object.freeze([\n \"run_start\",\n \"step_start\",\n \"model_call_start\",\n \"retry\",\n \"text_start\",\n \"text_delta\",\n \"text_end\",\n \"reasoning_start\",\n \"reasoning_delta\",\n \"reasoning_end\",\n \"tool_input_start\",\n \"tool_input_delta\",\n \"tool_input_end\",\n \"warning\",\n \"model_call_end\",\n \"context_transformed\",\n \"hook_error\",\n \"steer_applied\",\n \"tool_call_start\",\n \"approval_request\",\n \"resolution_rejected\",\n \"tool_call_update\",\n \"tool_call_end\",\n \"step_end\",\n \"error\",\n \"abort\",\n \"agent_settled\",\n \"run_end\",\n] as const satisfies readonly AgentEvent[\"type\"][]);\n"]}
package/dist/hooks.d.ts CHANGED
@@ -35,7 +35,7 @@ export interface ContextEvent extends HookEventBase {
35
35
  readonly messages: readonly Message[];
36
36
  /** The model the run was started with. */
37
37
  readonly model: ModelRef;
38
- /** The previous model call's usage. Absent on the first call. */
38
+ /** The usage of the last response the run went on with, not a failed turn-retry attempt's. Absent on the first call. */
39
39
  readonly lastUsage?: Usage;
40
40
  }
41
41
  /** What `beforeModelCall` receives: the request about to be sent. */
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` 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, or, under `blockingApprovals()`, waits for the\n * handler's answer. `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"]}
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 usage of the last response the run went on with, not a failed turn-retry attempt's. 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, or, under `blockingApprovals()`, waits for the\n * handler's answer. `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/loop.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed tool result,
8
8
  * throws.
9
9
  */
10
- import { type Message, type Model } from "@buildanagent/gateway";
10
+ import { type Message, type Model, type Sleep } from "@buildanagent/gateway";
11
11
  import type { AgentEventBody } from "./events.js";
12
12
  import type { CallOptions, Interceptors } from "./hooks.js";
13
13
  import type { ProgressCheck } from "./progress.js";
@@ -33,6 +33,12 @@ export interface LoopSetup {
33
33
  readonly tools: readonly AnyTool[];
34
34
  readonly output: AnyTool | undefined;
35
35
  readonly maxSteps: number;
36
+ /** How many times the loop re-issues a model call that ended with a `retryable` error; 0 turns turn retries off. */
37
+ readonly turnRetries: number;
38
+ /** The wait before the first turn retry, in milliseconds; each later retry in a streak waits twice as long. */
39
+ readonly turnRetryDelayMs: number;
40
+ /** Waits between turn retries. */
41
+ readonly sleep: Sleep;
36
42
  /** The most the run's model calls may cost, in USD, or `undefined` for no cap (D9). */
37
43
  readonly budgetUsd?: number;
38
44
  /** How deeply this run is nested inside other agents' tool calls, and the deepest nesting allowed (D11). */
package/dist/loop.js CHANGED
@@ -7,7 +7,7 @@
7
7
  * Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed tool result,
8
8
  * throws.
9
9
  */
10
- import { addCost, addUsage, emptyUsage, projectCallCost, } from "@buildanagent/gateway";
10
+ import { addCost, addUsage, emptyUsage, MAX_RETRY_DELAY_MS, projectCallCost, retryDelay, retryHintMs, } from "@buildanagent/gateway";
11
11
  import { checkBudget, unknownPriceError } from "./budget.js";
12
12
  import { isSdkError, SdkError } from "./errors.js";
13
13
  import { HookFailure, HookRunner } from "./hook-runner.js";
@@ -38,6 +38,8 @@ class LoopState {
38
38
  output;
39
39
  /** Set when the run was kept going to deliver a follow-up, so the next step boundary applies the follow-ups too. */
40
40
  releaseFollowUps = false;
41
+ /** Set when a retryable failure could have been retried but `maxSteps` left no room, so the run ends `max_steps`. */
42
+ retryBlockedByMaxSteps = false;
41
43
  /** The signed requests of the calls that gates paused, in model order. */
42
44
  pending = [];
43
45
  /**
@@ -93,7 +95,13 @@ function forward(state, event) {
93
95
  case "start":
94
96
  return undefined;
95
97
  case "retry":
96
- state.send({ type: "retry", attempt: event.attempt, delayMs: event.delayMs, error: event.error });
98
+ state.send({
99
+ type: "retry",
100
+ layer: "gateway",
101
+ attempt: event.attempt,
102
+ delayMs: event.delayMs,
103
+ error: event.error,
104
+ });
97
105
  return undefined;
98
106
  case "warning":
99
107
  state.send({ type: "warning", code: "model_warning", detail: `${event.code}: ${event.message}` });
@@ -219,23 +227,20 @@ function budgetBlock(state, request) {
219
227
  };
220
228
  }
221
229
  }
230
+ /** Adds a finished model call's usage and cost to the run's totals, whether or not the loop goes on with its message. */
231
+ function account(state, message) {
232
+ state.steps += 1;
233
+ state.usage = addUsage(state.usage, message.usage);
234
+ state.lastUsage = message.usage;
235
+ state.cost = state.cost === undefined ? message.cost : addCost(state.cost, message.cost);
236
+ }
222
237
  /**
223
- * Makes one model call, streams its events and records the response. The call's usage and cost are the model's own
224
- * message's, so an `afterModelCall` replacement changes what the run goes on with, never what it is billed. When
225
- * `afterModelCall` fails and the run fails closed, a withheld stand-in is recorded before the run ends, so the
226
- * transcript and `model_call_end` still account for the billed call and none of its tool calls run.
238
+ * Runs `afterModelCall` on a response the run goes on with and records it. The call's usage and cost are the model's
239
+ * own message's, so a replacement changes what the run goes on with, never what it is billed. When `afterModelCall`
240
+ * fails and the run fails closed, a withheld stand-in is recorded before the run ends, so the transcript and
241
+ * `model_call_end` still account for the billed call and none of its tool calls run.
227
242
  */
228
- async function callModel(state) {
229
- const request = await buildRequest(state);
230
- const blocked = budgetBlock(state, request);
231
- if (blocked !== undefined)
232
- return { blocked };
233
- state.active = request.active;
234
- const original = await streamRequest(state, request);
235
- state.steps += 1;
236
- state.usage = addUsage(state.usage, original.usage);
237
- state.lastUsage = original.usage;
238
- state.cost = state.cost === undefined ? original.cost : addCost(state.cost, original.cost);
243
+ async function accept(state, original) {
239
244
  let message;
240
245
  try {
241
246
  message = await state.hooks.afterModelCall(original);
@@ -249,6 +254,82 @@ async function callModel(state) {
249
254
  record(state, message);
250
255
  return message;
251
256
  }
257
+ /**
258
+ * The wait before a turn retry of `failure`, or `undefined` when the call is not retried: turn retries are off or
259
+ * used up, the failure is not `retryable`, the provider asked for longer than the gateway's cap, or the run was
260
+ * aborted. A streak that would go on but for `maxSteps` sets `retryBlockedByMaxSteps`, so the run ends `max_steps`
261
+ * instead of `error`: every attempt counts as a step, which keeps `maxSteps` the bound on the worst case. A first
262
+ * failure on the last step has no streak to stop yet, so it ends the run `error` as it would without turn retries.
263
+ */
264
+ function turnRetryDelay(state, failure, streak) {
265
+ const { turnRetries, turnRetryDelayMs, maxSteps, signal } = state.setup;
266
+ if (streak > turnRetries || failure.stopReason !== "error" || failure.error?.kind !== "retryable")
267
+ return undefined;
268
+ const hintMs = retryHintMs(failure);
269
+ if (hintMs > MAX_RETRY_DELAY_MS || signal.aborted)
270
+ return undefined;
271
+ if (state.steps >= maxSteps) {
272
+ state.retryBlockedByMaxSteps = streak > 1;
273
+ return undefined;
274
+ }
275
+ return retryDelay(turnRetryDelayMs, streak, hintMs);
276
+ }
277
+ /** Waits before a turn retry. A caller's `sleep` that rejects ends the wait early instead of failing the run. */
278
+ async function retryWait(state, delayMs) {
279
+ try {
280
+ await state.setup.sleep(delayMs, state.setup.signal);
281
+ }
282
+ catch (error) {
283
+ state.send({ type: "hook_error", hook: "sleep", error: error instanceof Error ? error.message : String(error) });
284
+ }
285
+ }
286
+ /**
287
+ * Makes one model call, streams its events and records the response. A call that ends with a `retryable` error is
288
+ * made again while turn retries last: its `model_call_end` carries the failed message, which is not recorded in the
289
+ * transcript, and a `retry` event with `layer: "turn"` marks it superseded before the wait. Each attempt builds its
290
+ * own request, so the interceptors and the budget check see every one, and each counts as a step with its own
291
+ * `step_start` and `step_end`. The budget is checked before the `retry` event too, with the failed attempt's request,
292
+ * so a run that can't afford a retry, or whose spend became unknown, ends without announcing one: the failure stays
293
+ * in the transcript, and the run ends `budget`, or `error` with the failure's own error.
294
+ */
295
+ async function callModel(state) {
296
+ for (let streak = 1;; streak += 1) {
297
+ const request = await buildRequest(state);
298
+ const blocked = budgetBlock(state, request);
299
+ if (blocked !== undefined)
300
+ return { blocked };
301
+ state.active = request.active;
302
+ const original = await streamRequest(state, request);
303
+ const usageBefore = state.lastUsage;
304
+ account(state, original);
305
+ const delayMs = turnRetryDelay(state, original, streak);
306
+ if (delayMs === undefined)
307
+ return accept(state, original);
308
+ const unaffordable = budgetBlock(state, request);
309
+ if (unaffordable !== undefined) {
310
+ const message = await accept(state, original);
311
+ return unaffordable.stopReason === "budget" ? { blocked: unaffordable } : message;
312
+ }
313
+ state.send({ type: "model_call_end", message: original });
314
+ // The failed message never joins the transcript, so its usage must not stand for the context's size.
315
+ state.lastUsage = usageBefore;
316
+ state.send({
317
+ type: "retry",
318
+ layer: "turn",
319
+ attempt: streak,
320
+ delayMs,
321
+ error: original.error?.message ?? "retryable error",
322
+ });
323
+ await retryWait(state, delayMs);
324
+ if (state.setup.signal.aborted)
325
+ return { blocked: { stopReason: "aborted" } };
326
+ // Each model call is a step with its own index, so the retry's events don't share the failed call's.
327
+ state.send({ type: "step_end", stopCheck: "continue" });
328
+ state.stepIndex = state.steps;
329
+ state.send({ type: "step_start" });
330
+ applySteering(state);
331
+ }
332
+ }
252
333
  /** The tool message the model reads for one call. */
253
334
  function toolMessage(entry) {
254
335
  return {
@@ -356,8 +437,11 @@ function runErrorOf(message) {
356
437
  * finished: its message keeps `stopReason: "length"`.
357
438
  */
358
439
  function stopCheck(state, message, results) {
359
- if (message.stopReason === "error")
360
- return { stopReason: "error", error: runErrorOf(message) };
440
+ if (message.stopReason === "error") {
441
+ return state.retryBlockedByMaxSteps
442
+ ? { stopReason: "max_steps" }
443
+ : { stopReason: "error", error: runErrorOf(message) };
444
+ }
361
445
  if (message.stopReason === "aborted")
362
446
  return { stopReason: "aborted" };
363
447
  // A paused call is still waiting, so the run can't count as finished, and the pause is signed and stored with the
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,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAI3D,OAAO,EAAE,cAAc,EAAkC,MAAM,aAAa,CAAC;AAG7E,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAsC,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AAK5G;;;GAGG;AACH,MAAM,OAAO,GAAS,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AAoEvE,wCAA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C,CAAC;IAC3F,IAAI,OAAO,GAAwB,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;IAC/G,IAAI,CAAC;QACH,IAAI,OAAO,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS;YAAE,OAAO,GAAG,MAAM,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QAC3G,OAAO,OAAO,KAAK,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 { judgeOpenCalls, type ResumeSetup, type Verdict } from \"./resume.js\";\nimport type { SteeringQueue } from \"./steering.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { toWireTool } from \"./tools/define.js\";\nimport { type AnyTool, type PipelineContext, runToolCalls, type ToolCallResult } from \"./tools/pipeline.js\";\nimport type { ToolCall, ToolResult } from \"./tools/types.js\";\nimport type { SignedPendingRequest } from \"./vendor/agent-safety/pending.js\";\nimport type { ApprovalSigner } from \"./vendor/agent-safety/signer.js\";\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 /** The waiting calls of the context a `continueRun()` resumes, and their resolutions. */\n readonly resume?: ResumeSetup;\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\" | \"clarification_requested\";\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/** Records one call's result: the tool message the model reads, the output tool's answer and `tool_call_end`. */\nfunction recordResult(state: LoopState, entry: ToolCallResult): void {\n const { output } = state.setup;\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/** Holds a signed request for a person: in the run's pending list, by id in its inputs, and as `approval_request`. */\nfunction holdPause(state: LoopState, request: SignedPendingRequest, input: unknown): void {\n state.pending.push(request);\n state.pendingInputs[request.id] = input;\n state.send({ type: \"approval_request\", request, input });\n}\n\n/** True for a result that asks the user a question, which pauses its call instead of reaching the model. */\nfunction asksUser(result: ToolResult): boolean {\n return result.pause !== undefined && result.isError !== true;\n}\n\n/** The pipeline callbacks every tool batch of the run shares. `onResult` holds back a question for `askUser()`. */\nfunction pipelineOf(state: LoopState, asks: ToolCallResult[]): PipelineContext {\n const { runId, signal, clock, depth, maxDepth } = state.setup;\n return {\n runId,\n signal,\n clock,\n depth,\n maxDepth,\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 }) => holdPause(state, request, input),\n onResult: (entry) => {\n if (asksUser(entry.result)) asks.push(entry);\n else recordResult(state, entry);\n },\n };\n}\n\n/**\n * Signs a clarification request for each call whose tool asked the user a question, in model order. The call then\n * waits like a paused one, with no result; a question that can't be signed reaches the model as an error result.\n * Returns the batch's results with those error results in place.\n */\nasync function askUser(\n state: LoopState,\n results: readonly ToolCallResult[],\n asks: readonly ToolCallResult[],\n): Promise<ToolCallResult[]> {\n const replaced = new Map<ToolCallResult, ToolCallResult>();\n for (const entry of asks) {\n const question = entry.result.pause?.question;\n const outcome = await state.hooks.clarify(entry.call, entry.ranWith, question as string);\n if (\"paused\" in outcome) {\n holdPause(state, outcome.paused, outcome.input);\n } else if (\"blocked\" in outcome) {\n const blocked = { call: entry.call, result: outcome.blocked };\n recordResult(state, blocked);\n replaced.set(entry, blocked);\n }\n }\n return results.map((entry) => replaced.get(entry) ?? entry);\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 asks: ToolCallResult[] = [];\n const results = await runToolCalls(message, state.active, {\n ...pipelineOf(state, asks),\n ...state.hooks.pipelineHooks(),\n });\n return asks.length === 0 ? results : askUser(state, results, asks);\n}\n\n/**\n * The outcome of a run whose calls wait for a person. Its requests are put in the model's order of their calls, and\n * it ends `awaiting_approval` when any waits for an approval, or `clarification_requested` when all wait for answers.\n */\nfunction pausedOutcome(state: LoopState, message: AssistantMessage): Outcome {\n const order = callOrderOf(message);\n const pending = [...state.pending].sort((a, b) => order.indexOf(a.callId) - order.indexOf(b.callId));\n const approval = pending.some((request) => request.kind === \"approval\");\n return {\n stopReason: approval ? \"awaiting_approval\" : \"clarification_requested\",\n pending,\n pendingInputs: { ...state.pendingInputs },\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, including a question for the user, or a finished answer wins over an abort\n * that came too late to change it; otherwise an abort stops the run before the step cap does. A pause wins over a\n * finished answer too, because its call is still waiting. A text answer cut off at the output limit also counts as\n * 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) return pausedOutcome(state, message);\n const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);\n if (finished) return { stopReason: \"done\", output: state.output };\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\" || outcome.stopReason === \"clarification_requested\"\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/** The synthetic response that holds `calls`, so the pipeline runs them as one batch of the resumed message. */\nfunction batchOf(message: AssistantMessage, calls: readonly ToolCall[]): AssistantMessage {\n return { ...message, content: [...calls], stopReason: \"tool_calls\" };\n}\n\n/** The call ids of `message`'s tool calls, in model order. */\nfunction callOrderOf(message: AssistantMessage): string[] {\n return message.content.flatMap((block) => (block.type === \"tool_call\" ? [block.callId] : []));\n}\n\n/**\n * Puts the tool messages `list` gained from `from` on in the model's order of their calls, as a step records them.\n * A resume settles its calls by verdict, so without this a denial could come before an approval the model made first.\n */\nfunction inModelOrder(list: Message[], from: number, order: readonly string[]): void {\n const rank = (entry: Message) => (entry.role === \"tool\" ? order.indexOf(entry.callId) : order.length);\n const tail = list.splice(from).sort((a, b) => rank(a) - rank(b));\n list.push(...tail);\n}\n\n/**\n * Acts on the verdicts for a resumed context's waiting calls, before the run's first model call, which none of this\n * counts as, and records their results in the model's order. Returns the paused outcome when any call still waits,\n * and `done` when none does and an approved call's result ends the run, as `terminate` does in a step.\n */\nasync function resume(state: LoopState, setup: ResumeSetup): Promise<Outcome | undefined> {\n const { message } = setup;\n const from = { messages: state.messages.length, added: state.added.length };\n try {\n return await settle(state, setup);\n } finally {\n if (message !== undefined) {\n const order = callOrderOf(message);\n inModelOrder(state.messages, from.messages, order);\n inModelOrder(state.added, from.added, order);\n }\n }\n}\n\n/**\n * Verified answers and denials reach the model as results; verified approvals run, without the gate, with the input\n * their requests sign; requests that still wait stay pending; and calls whose checks failed ask again, through the\n * gate but never running.\n */\nasync function settle(state: LoopState, setup: ResumeSetup): Promise<Outcome | undefined> {\n const { signer } = state.setup;\n state.hooks.reserveRequestIds(setup.open.map((entry) => entry.request.id));\n const verdicts = await judgeOpenCalls(setup, { signer, send: (body) => state.send(body) });\n const of = <K extends Verdict[\"kind\"]>(kind: K) =>\n verdicts.filter((verdict): verdict is Extract<Verdict, { kind: K }> => verdict.kind === kind);\n for (const { call, result } of of(\"result\")) {\n state.send({ type: \"tool_call_start\", callId: call.callId, tool: call.name, input: call.input });\n recordResult(state, { call, result });\n }\n const asks: ToolCallResult[] = [];\n const { message } = setup;\n if (message === undefined) return undefined;\n const run = of(\"run\").map((verdict) => verdict.call);\n let ran: readonly ToolCallResult[] = [];\n if (run.length > 0) {\n const { after } = state.hooks.pipelineHooks();\n const ctx = { ...pipelineOf(state, asks), approved: true, ...(after === undefined ? {} : { after }) };\n // A verified request names its tool, and the run signed it only for a call to a tool its request had sent.\n const results = await runToolCalls(batchOf(message, run), state.setup.tools, ctx);\n ran = asks.length > 0 ? await askUser(state, results, asks) : results;\n }\n for (const { request, input } of of(\"wait\")) {\n state.pending.push(request);\n state.pendingInputs[request.id] = input;\n }\n const again = of(\"reissue\").map((verdict) => verdict.call);\n if (again.length > 0) {\n const ctx = { ...pipelineOf(state, asks), gate: state.hooks.reissueGate() };\n // Nothing verified these calls, so only the tools a request sends by default may ask again: a stored context\n // can't get a new signed request for a tool the model is never sent.\n await runToolCalls(batchOf(message, again), directTools(state.setup.tools), ctx);\n }\n if (state.pending.length > 0) return pausedOutcome(state, message);\n const ends = ran.some(({ result }) => result.terminate === true && !result.isError);\n return ends ? { stopReason: \"done\", output: state.output } : undefined;\n}\n\n/** `resume()`, with a hook that failed while the run fails closed ending the run as a step's failure would. */\nasync function resumeOrFail(state: LoopState, setup: ResumeSetup): Promise<Outcome | undefined> {\n try {\n return await resume(state, setup);\n } catch (error) {\n return failedOutcome(state, error);\n }\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 if (outcome === undefined && setup.resume !== undefined) outcome = await resumeOrFail(state, setup.resume);\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,EAEL,OAAO,EACP,QAAQ,EAGR,UAAU,EAEV,kBAAkB,EAIlB,eAAe,EACf,UAAU,EACV,WAAW,GAKZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAI3D,OAAO,EAAE,cAA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AAK,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 MAX_RETRY_DELAY_MS,\n type Message,\n type Model,\n type ModelContext,\n projectCallCost,\n retryDelay,\n retryHintMs,\n type Sleep,\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 { judgeOpenCalls, type ResumeSetup, type Verdict } from \"./resume.js\";\nimport type { SteeringQueue } from \"./steering.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { toWireTool } from \"./tools/define.js\";\nimport { type AnyTool, type PipelineContext, runToolCalls, type ToolCallResult } from \"./tools/pipeline.js\";\nimport type { ToolCall, ToolResult } from \"./tools/types.js\";\nimport type { SignedPendingRequest } from \"./vendor/agent-safety/pending.js\";\nimport type { ApprovalSigner } from \"./vendor/agent-safety/signer.js\";\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 /** How many times the loop re-issues a model call that ended with a `retryable` error; 0 turns turn retries off. */\n readonly turnRetries: number;\n /** The wait before the first turn retry, in milliseconds; each later retry in a streak waits twice as long. */\n readonly turnRetryDelayMs: number;\n /** Waits between turn retries. */\n readonly sleep: Sleep;\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 /** The waiting calls of the context a `continueRun()` resumes, and their resolutions. */\n readonly resume?: ResumeSetup;\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\" | \"clarification_requested\";\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 /** Set when a retryable failure could have been retried but `maxSteps` left no room, so the run ends `max_steps`. */\n retryBlockedByMaxSteps = 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({\n type: \"retry\",\n layer: \"gateway\",\n attempt: event.attempt,\n delayMs: event.delayMs,\n error: event.error,\n });\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/** Adds a finished model call's usage and cost to the run's totals, whether or not the loop goes on with its message. */\nfunction account(state: LoopState, message: AssistantMessage): void {\n state.steps += 1;\n state.usage = addUsage(state.usage, message.usage);\n state.lastUsage = message.usage;\n state.cost = state.cost === undefined ? message.cost : addCost(state.cost, message.cost);\n}\n\n/**\n * Runs `afterModelCall` on a response the run goes on with and records it. The call's usage and cost are the model's\n * own message's, so a replacement changes what the run goes on with, never what it is billed. When `afterModelCall`\n * fails and the run fails closed, a withheld stand-in is recorded before the run ends, so the transcript and\n * `model_call_end` still account for the billed call and none of its tool calls run.\n */\nasync function accept(state: LoopState, original: AssistantMessage): Promise<AssistantMessage> {\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/**\n * The wait before a turn retry of `failure`, or `undefined` when the call is not retried: turn retries are off or\n * used up, the failure is not `retryable`, the provider asked for longer than the gateway's cap, or the run was\n * aborted. A streak that would go on but for `maxSteps` sets `retryBlockedByMaxSteps`, so the run ends `max_steps`\n * instead of `error`: every attempt counts as a step, which keeps `maxSteps` the bound on the worst case. A first\n * failure on the last step has no streak to stop yet, so it ends the run `error` as it would without turn retries.\n */\nfunction turnRetryDelay(state: LoopState, failure: AssistantMessage, streak: number): number | undefined {\n const { turnRetries, turnRetryDelayMs, maxSteps, signal } = state.setup;\n if (streak > turnRetries || failure.stopReason !== \"error\" || failure.error?.kind !== \"retryable\") return undefined;\n const hintMs = retryHintMs(failure);\n if (hintMs > MAX_RETRY_DELAY_MS || signal.aborted) return undefined;\n if (state.steps >= maxSteps) {\n state.retryBlockedByMaxSteps = streak > 1;\n return undefined;\n }\n return retryDelay(turnRetryDelayMs, streak, hintMs);\n}\n\n/** Waits before a turn retry. A caller's `sleep` that rejects ends the wait early instead of failing the run. */\nasync function retryWait(state: LoopState, delayMs: number): Promise<void> {\n try {\n await state.setup.sleep(delayMs, state.setup.signal);\n } catch (error) {\n state.send({ type: \"hook_error\", hook: \"sleep\", error: error instanceof Error ? error.message : String(error) });\n }\n}\n\n/**\n * Makes one model call, streams its events and records the response. A call that ends with a `retryable` error is\n * made again while turn retries last: its `model_call_end` carries the failed message, which is not recorded in the\n * transcript, and a `retry` event with `layer: \"turn\"` marks it superseded before the wait. Each attempt builds its\n * own request, so the interceptors and the budget check see every one, and each counts as a step with its own\n * `step_start` and `step_end`. The budget is checked before the `retry` event too, with the failed attempt's request,\n * so a run that can't afford a retry, or whose spend became unknown, ends without announcing one: the failure stays\n * in the transcript, and the run ends `budget`, or `error` with the failure's own error.\n */\nasync function callModel(state: LoopState): Promise<AssistantMessage | { readonly blocked: Outcome }> {\n for (let streak = 1; ; streak += 1) {\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 const usageBefore = state.lastUsage;\n account(state, original);\n const delayMs = turnRetryDelay(state, original, streak);\n if (delayMs === undefined) return accept(state, original);\n const unaffordable = budgetBlock(state, request);\n if (unaffordable !== undefined) {\n const message = await accept(state, original);\n return unaffordable.stopReason === \"budget\" ? { blocked: unaffordable } : message;\n }\n state.send({ type: \"model_call_end\", message: original });\n // The failed message never joins the transcript, so its usage must not stand for the context's size.\n state.lastUsage = usageBefore;\n state.send({\n type: \"retry\",\n layer: \"turn\",\n attempt: streak,\n delayMs,\n error: original.error?.message ?? \"retryable error\",\n });\n await retryWait(state, delayMs);\n if (state.setup.signal.aborted) return { blocked: { stopReason: \"aborted\" } };\n // Each model call is a step with its own index, so the retry's events don't share the failed call's.\n state.send({ type: \"step_end\", stopCheck: \"continue\" });\n state.stepIndex = state.steps;\n state.send({ type: \"step_start\" });\n applySteering(state);\n }\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/** Records one call's result: the tool message the model reads, the output tool's answer and `tool_call_end`. */\nfunction recordResult(state: LoopState, entry: ToolCallResult): void {\n const { output } = state.setup;\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/** Holds a signed request for a person: in the run's pending list, by id in its inputs, and as `approval_request`. */\nfunction holdPause(state: LoopState, request: SignedPendingRequest, input: unknown): void {\n state.pending.push(request);\n state.pendingInputs[request.id] = input;\n state.send({ type: \"approval_request\", request, input });\n}\n\n/** True for a result that asks the user a question, which pauses its call instead of reaching the model. */\nfunction asksUser(result: ToolResult): boolean {\n return result.pause !== undefined && result.isError !== true;\n}\n\n/** The pipeline callbacks every tool batch of the run shares. `onResult` holds back a question for `askUser()`. */\nfunction pipelineOf(state: LoopState, asks: ToolCallResult[]): PipelineContext {\n const { runId, signal, clock, depth, maxDepth } = state.setup;\n return {\n runId,\n signal,\n clock,\n depth,\n maxDepth,\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 }) => holdPause(state, request, input),\n onResult: (entry) => {\n if (asksUser(entry.result)) asks.push(entry);\n else recordResult(state, entry);\n },\n };\n}\n\n/**\n * Signs a clarification request for each call whose tool asked the user a question, in model order. The call then\n * waits like a paused one, with no result; a question that can't be signed reaches the model as an error result.\n * Returns the batch's results with those error results in place.\n */\nasync function askUser(\n state: LoopState,\n results: readonly ToolCallResult[],\n asks: readonly ToolCallResult[],\n): Promise<ToolCallResult[]> {\n const replaced = new Map<ToolCallResult, ToolCallResult>();\n for (const entry of asks) {\n const question = entry.result.pause?.question;\n const outcome = await state.hooks.clarify(entry.call, entry.ranWith, question as string);\n if (\"paused\" in outcome) {\n holdPause(state, outcome.paused, outcome.input);\n } else if (\"blocked\" in outcome) {\n const blocked = { call: entry.call, result: outcome.blocked };\n recordResult(state, blocked);\n replaced.set(entry, blocked);\n }\n }\n return results.map((entry) => replaced.get(entry) ?? entry);\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 asks: ToolCallResult[] = [];\n const results = await runToolCalls(message, state.active, {\n ...pipelineOf(state, asks),\n ...state.hooks.pipelineHooks(),\n });\n return asks.length === 0 ? results : askUser(state, results, asks);\n}\n\n/**\n * The outcome of a run whose calls wait for a person. Its requests are put in the model's order of their calls, and\n * it ends `awaiting_approval` when any waits for an approval, or `clarification_requested` when all wait for answers.\n */\nfunction pausedOutcome(state: LoopState, message: AssistantMessage): Outcome {\n const order = callOrderOf(message);\n const pending = [...state.pending].sort((a, b) => order.indexOf(a.callId) - order.indexOf(b.callId));\n const approval = pending.some((request) => request.kind === \"approval\");\n return {\n stopReason: approval ? \"awaiting_approval\" : \"clarification_requested\",\n pending,\n pendingInputs: { ...state.pendingInputs },\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, including a question for the user, or a finished answer wins over an abort\n * that came too late to change it; otherwise an abort stops the run before the step cap does. A pause wins over a\n * finished answer too, because its call is still waiting. A text answer cut off at the output limit also counts as\n * 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\") {\n return state.retryBlockedByMaxSteps\n ? { stopReason: \"max_steps\" }\n : { stopReason: \"error\", error: runErrorOf(message) };\n }\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) return pausedOutcome(state, message);\n const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);\n if (finished) return { stopReason: \"done\", output: state.output };\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\" || outcome.stopReason === \"clarification_requested\"\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/** The synthetic response that holds `calls`, so the pipeline runs them as one batch of the resumed message. */\nfunction batchOf(message: AssistantMessage, calls: readonly ToolCall[]): AssistantMessage {\n return { ...message, content: [...calls], stopReason: \"tool_calls\" };\n}\n\n/** The call ids of `message`'s tool calls, in model order. */\nfunction callOrderOf(message: AssistantMessage): string[] {\n return message.content.flatMap((block) => (block.type === \"tool_call\" ? [block.callId] : []));\n}\n\n/**\n * Puts the tool messages `list` gained from `from` on in the model's order of their calls, as a step records them.\n * A resume settles its calls by verdict, so without this a denial could come before an approval the model made first.\n */\nfunction inModelOrder(list: Message[], from: number, order: readonly string[]): void {\n const rank = (entry: Message) => (entry.role === \"tool\" ? order.indexOf(entry.callId) : order.length);\n const tail = list.splice(from).sort((a, b) => rank(a) - rank(b));\n list.push(...tail);\n}\n\n/**\n * Acts on the verdicts for a resumed context's waiting calls, before the run's first model call, which none of this\n * counts as, and records their results in the model's order. Returns the paused outcome when any call still waits,\n * and `done` when none does and an approved call's result ends the run, as `terminate` does in a step.\n */\nasync function resume(state: LoopState, setup: ResumeSetup): Promise<Outcome | undefined> {\n const { message } = setup;\n const from = { messages: state.messages.length, added: state.added.length };\n try {\n return await settle(state, setup);\n } finally {\n if (message !== undefined) {\n const order = callOrderOf(message);\n inModelOrder(state.messages, from.messages, order);\n inModelOrder(state.added, from.added, order);\n }\n }\n}\n\n/**\n * Verified answers and denials reach the model as results; verified approvals run, without the gate, with the input\n * their requests sign; requests that still wait stay pending; and calls whose checks failed ask again, through the\n * gate but never running.\n */\nasync function settle(state: LoopState, setup: ResumeSetup): Promise<Outcome | undefined> {\n const { signer } = state.setup;\n state.hooks.reserveRequestIds(setup.open.map((entry) => entry.request.id));\n const verdicts = await judgeOpenCalls(setup, { signer, send: (body) => state.send(body) });\n const of = <K extends Verdict[\"kind\"]>(kind: K) =>\n verdicts.filter((verdict): verdict is Extract<Verdict, { kind: K }> => verdict.kind === kind);\n for (const { call, result } of of(\"result\")) {\n state.send({ type: \"tool_call_start\", callId: call.callId, tool: call.name, input: call.input });\n recordResult(state, { call, result });\n }\n const asks: ToolCallResult[] = [];\n const { message } = setup;\n if (message === undefined) return undefined;\n const run = of(\"run\").map((verdict) => verdict.call);\n let ran: readonly ToolCallResult[] = [];\n if (run.length > 0) {\n const { after } = state.hooks.pipelineHooks();\n const ctx = { ...pipelineOf(state, asks), approved: true, ...(after === undefined ? {} : { after }) };\n // A verified request names its tool, and the run signed it only for a call to a tool its request had sent.\n const results = await runToolCalls(batchOf(message, run), state.setup.tools, ctx);\n ran = asks.length > 0 ? await askUser(state, results, asks) : results;\n }\n for (const { request, input } of of(\"wait\")) {\n state.pending.push(request);\n state.pendingInputs[request.id] = input;\n }\n const again = of(\"reissue\").map((verdict) => verdict.call);\n if (again.length > 0) {\n const ctx = { ...pipelineOf(state, asks), gate: state.hooks.reissueGate() };\n // Nothing verified these calls, so only the tools a request sends by default may ask again: a stored context\n // can't get a new signed request for a tool the model is never sent.\n await runToolCalls(batchOf(message, again), directTools(state.setup.tools), ctx);\n }\n if (state.pending.length > 0) return pausedOutcome(state, message);\n const ends = ran.some(({ result }) => result.terminate === true && !result.isError);\n return ends ? { stopReason: \"done\", output: state.output } : undefined;\n}\n\n/** `resume()`, with a hook that failed while the run fails closed ending the run as a step's failure would. */\nasync function resumeOrFail(state: LoopState, setup: ResumeSetup): Promise<Outcome | undefined> {\n try {\n return await resume(state, setup);\n } catch (error) {\n return failedOutcome(state, error);\n }\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 if (outcome === undefined && setup.resume !== undefined) outcome = await resumeOrFail(state, setup.resume);\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"]}
package/dist/run.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the
4
4
  * non-streaming caller drive one loop.
5
5
  */
6
- import type { ContentBlock, Message, Model } from "@buildanagent/gateway";
6
+ import { type ContentBlock, type Message, type Model, type Sleep } from "@buildanagent/gateway";
7
7
  import type { AgentEvent } from "./events.js";
8
8
  import type { CallOptions, Interceptors, Observer } from "./hooks.js";
9
9
  import { type ProgressPolicy } from "./progress.js";
@@ -32,6 +32,29 @@ export interface RunOptions<S = unknown> {
32
32
  * ends with `stopReason: "max_steps"` and emits a `warning` event with `code: "max_steps"`.
33
33
  */
34
34
  readonly maxSteps?: number;
35
+ /**
36
+ * How many times the loop re-issues a model call that ended with a `retryable` error, such as a stream cut off
37
+ * after it had started to answer. Default 0: the run ends `error` on the first failure, and `continueRun()` is the
38
+ * way to try again. `turnRetries: 3` retries as Pi does. This is the third retry layer: the model's own retries
39
+ * (`createModel({ retries })`) re-send a request that failed before any output, so a call can make up to
40
+ * `(retries + 1) * (turnRetries + 1)` requests. The count restarts after each call that succeeds. Only
41
+ * `retryable` failures are retried: `overflow`, `quota` and `fatal` end the run, and so does a `retryable` failure
42
+ * whose `error.retryAfterMs` is over the gateway's 60-second cap. Every attempt counts against `maxSteps`, and a
43
+ * failed attempt's usage and cost go into the result; a run that `maxSteps` stops after a retry ends `max_steps`. With `budgetUsd` set, a retry the budget can't cover, or one after an attempt whose cost is
44
+ * unknown, is not made: the run ends `budget`, or `error` with the failure's own error.
45
+ * Each retry emits a `retry` event with `layer: "turn"`.
46
+ */
47
+ readonly turnRetries?: number;
48
+ /**
49
+ * The wait before the first turn retry, in milliseconds. Default 2000; each later retry of a streak waits twice as
50
+ * long, up to 60 seconds, or as long as the failure's `error.retryAfterMs` asks if that is longer.
51
+ */
52
+ readonly turnRetryDelayMs?: number;
53
+ /**
54
+ * Waits between turn retries. Defaults to a timer that ends early, without rejecting, when the run is aborted; a
55
+ * test passes a fake to skip the wait. A `sleep` that rejects ends the wait early and emits a `hook_error` event.
56
+ */
57
+ readonly sleep?: Sleep;
35
58
  /**
36
59
  * The most the run's model calls may cost, in USD. Before each call the run projects its cost with
37
60
  * `projectCallCost()` and, if the spend so far plus that projection would pass the cap, ends with
package/dist/run.js CHANGED
@@ -1,3 +1,9 @@
1
+ /**
2
+ * `run()`, `continueRun()` and `runOrThrow()`, and the `Run` object they share (SDK plan §3.3; D10). A run streams
3
+ * its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the
4
+ * non-streaming caller drive one loop.
5
+ */
6
+ import { abortableSleep, DEFAULT_INITIAL_RETRY_DELAY_MS, MAX_RETRY_DELAY_MS, } from "@buildanagent/gateway";
1
7
  import { checkBudgetOption } from "./budget.js";
2
8
  import { RunStoppedError, SdkError } from "./errors.js";
3
9
  import { runLoop } from "./loop.js";
@@ -220,6 +226,22 @@ function progressOf(options, tools, skip) {
220
226
  const policy = resolveProgress(options.progress);
221
227
  return policy === undefined ? undefined : progressCheck(tools, policy, skip);
222
228
  }
229
+ /** Checks the turn-retry options and fills in their defaults. */
230
+ function turnRetriesOf(options) {
231
+ const turnRetries = options.turnRetries ?? 0;
232
+ if (!Number.isInteger(turnRetries) || turnRetries < 0) {
233
+ throw new SdkError("invalid_run_options", `turnRetries must be a non-negative integer, got ${String(turnRetries)}`);
234
+ }
235
+ const turnRetryDelayMs = options.turnRetryDelayMs ?? DEFAULT_INITIAL_RETRY_DELAY_MS;
236
+ if (!Number.isFinite(turnRetryDelayMs) || turnRetryDelayMs < 0 || turnRetryDelayMs > MAX_RETRY_DELAY_MS) {
237
+ throw new SdkError("invalid_run_options", `turnRetryDelayMs must be a number from 0 to ${MAX_RETRY_DELAY_MS}, got ${String(turnRetryDelayMs)}`);
238
+ }
239
+ const sleep = options.sleep ?? abortableSleep;
240
+ if (typeof sleep !== "function") {
241
+ throw new SdkError("invalid_run_options", "sleep must be a function, such as async (ms, signal) => {}");
242
+ }
243
+ return { turnRetries, turnRetryDelayMs, sleep };
244
+ }
223
245
  function setupOf(options, context, input) {
224
246
  if (!isModel(options.model)) {
225
247
  throw new SdkError("invalid_run_options", "the model must come from createModel(), such as createModel({ adapter, id })");
@@ -232,6 +254,7 @@ function setupOf(options, context, input) {
232
254
  if (!isSigner(signer)) {
233
255
  throw new SdkError("invalid_run_options", "signer must be an ApprovalSigner, such as hmacSigner() or ephemeralSigner()");
234
256
  }
257
+ const retries = turnRetriesOf(options);
235
258
  const budgetUsd = checkBudgetOption(options.budgetUsd);
236
259
  const tools = toolsOf(options);
237
260
  const { depth, maxDepth } = depthsOf(options);
@@ -251,6 +274,7 @@ function setupOf(options, context, input) {
251
274
  tools,
252
275
  output: options.output,
253
276
  maxSteps,
277
+ ...retries,
254
278
  ...(budgetUsd === undefined ? {} : { budgetUsd }),
255
279
  depth,
256
280
  maxDepth,
package/dist/run.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGxD,OAAO,EAAkB,OAAO,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAA2C,aAAa,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAExG,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAwB,aAAa,EAAE,MAAM,eAAe,CAAC;AAEpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAIrD,OAAO,EAAuB,eAAe,EAAE,MAAM,iCAAiC,CAAC;AACvF,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAA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EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AACvE,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,WAAW,CAAc,OAAgB,EAAE,OAA2B;IACpF,MAAM,MAAM,GAAG,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC9E,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;IAC5C,OAAO,IAAI,SAAS,CAAI,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AACrH,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAI,OAAe;IACjD,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC;IACpC,IAAI,MAAM,CAAC,UAAU,KAAK,MAAM;QAAE,OAAO,MAAM,CAAC;IAChD,MAAM,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * `run()`, `continueRun()` and `runOrThrow()`, and the `Run` object they share (SDK plan §3.3; D10). A run streams\n * its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the\n * non-streaming caller drive one loop.\n */\nimport type { ContentBlock, Message, Model } from \"@buildanagent/gateway\";\nimport { checkBudgetOption } from \"./budget.js\";\nimport { RunStoppedError, SdkError } from \"./errors.js\";\nimport type { AgentEvent, AgentEventBody } from \"./events.js\";\nimport type { CallOptions, Interceptors, Observer } from \"./hooks.js\";\nimport { type LoopSetup, runLoop } from \"./loop.js\";\nimport { ObserverBus } from \"./observers.js\";\nimport { blockingHandlerOf, isSigner } from \"./pauses.js\";\nimport { type ProgressCheck, type ProgressPolicy, progressCheck, resolveProgress } from \"./progress.js\";\nimport type { Context, DoneResult, RunResult } from \"./result.js\";\nimport { resumeSetupOf } from \"./resume.js\";\nimport { type DeliveryReceipt, SteeringQueue } from \"./steering.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { preparedSchemaOf } from \"./tools/define.js\";\nimport type { AnyTool } from \"./tools/pipeline.js\";\nimport type { ToolContext, ToolDefinition } from \"./tools/types.js\";\nimport type { Recheck, Resolution } from \"./vendor/agent-safety/pending.js\";\nimport { type ApprovalSigner, ephemeralSigner } from \"./vendor/agent-safety/signer.js\";\nimport { SDK_VERSION } from \"./version.js\";\n\n/** The step cap's default, counted in model calls. */\nconst DEFAULT_MAX_STEPS = 20;\n\n/** The depth cap's default (D11): a top-level run, its subagents and their subagents may run, and no deeper. */\nconst DEFAULT_MAX_DEPTH = 2;\n\n/** How long the run waits, by default, for an observer to catch up before it drops it. */\nconst DEFAULT_OBSERVER_TIMEOUT_MS = 10_000;\n/** The longest delay `setTimeout` accepts; a larger one fires at once on Node and workerd alike. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\nconst systemClock: Clock = { now: () => new Date().toISOString() };\nconst randomIds = (): string => globalThis.crypto.randomUUID();\n\n/** The options `run()` and `continueRun()` share. */\nexport interface RunOptions<S = unknown> {\n /** The model, from `createModel()`. */\n readonly model: Model;\n /**\n * The tools the model may call. Tools whose `exposure` is `deferred` or `hidden` are not sent unless a\n * `beforeModelCall` interceptor names them in `activeTools`.\n */\n readonly tools?: readonly ToolDefinition<unknown, unknown>[];\n /**\n * A tool from `outputTool()` whose input is the final answer. It is sent with the other tools; once the model calls\n * it with input that passes its schema, the run ends `done`, and `result.output` holds the validated answer.\n */\n readonly output?: ToolDefinition<S, S>;\n /**\n * The most model calls the run may make. Default 20. A run that reaches it while the model still wants to go on\n * ends with `stopReason: \"max_steps\"` and emits a `warning` event with `code: \"max_steps\"`.\n */\n readonly maxSteps?: number;\n /**\n * The most the run's model calls may cost, in USD. Before each call the run projects its cost with\n * `projectCallCost()` and, if the spend so far plus that projection would pass the cap, ends with\n * `stopReason: \"budget\"` without making the call. The cap counts the calls this run makes, not the cost of the\n * history a `continueRun()` starts from. A budgeted run on a model whose price is unknown ends `error` with\n * `error.kind: \"unknown_price\"` before its first call, because it could not tell what it spent. Without it, a run\n * has no cap.\n */\n readonly budgetUsd?: number;\n /**\n * The default progress policy: the run ends `no_progress` after 3 identical failing tool calls in a row, or after 5\n * calls to a tool with one `progressKey` and no success between them. It runs after your own `shouldStop`, whose\n * `{ continue }` can't keep a stuck run going. Pass numbers to change either threshold, or `false` to turn the\n * policy off.\n */\n readonly progress?: ProgressPolicy | false;\n /**\n * How deeply this run is nested inside other agents' tool calls. Default 0. A tool that starts a run of its own\n * passes `depth: ctx.depth + 1` and `maxDepth: ctx.maxDepth`; `run()` throws an `SdkError` with code\n * `max_depth_exceeded` when `depth` is above `maxDepth`, which the tool's caller reads as an error result.\n */\n readonly depth?: number;\n /** The deepest nesting allowed, which tools read as `ctx.maxDepth`. Default 2. */\n readonly maxDepth?: number;\n /** Aborts the run, like `run.abort()`. */\n readonly signal?: AbortSignal;\n /** Options for every model call, such as `maxOutputTokens`. The run passes its own abort signal. */\n readonly modelOptions?: CallOptions;\n /**\n * The interceptors: hooks that can change the run at six moments. A run takes one object; join several with\n * `composeInterceptors()`. See `Interceptors` for the order and for what a failing hook does.\n */\n readonly interceptors?: Interceptors;\n /**\n * Observers, which receive every event from `run_start` on and can't change the run. Each observer sees the events in\n * order and waits for its own promises, but observers don't wait for each other. An observer that throws becomes a\n * `hook_error` event. The run waits for every observer to handle the last event before it settles, for at most\n * `observerTimeoutMs` each time it waits; an observer that hasn't caught up by then is removed and reported as a\n * `hook_error`.\n */\n readonly observers?: readonly Observer[];\n /**\n * The longest the run waits for its observers each time it waits for them: before `agent_settled`, before\n * `run_end` and before it settles. A number from 1 to 2147483647; the default is 10000. It bounds an observer whose promise never settles.\n */\n readonly observerTimeoutMs?: number;\n /** Stamps each event's `timestamp`, and is passed to tools. Defaults to the system clock. */\n readonly clock?: Clock;\n /**\n * Makes the run's id, then the id of each pending request the run signs. A request id that repeats the run's id or\n * an earlier request's id is replaced by `crypto.randomUUID()`, so a generator that always returns one id still\n * pauses every call; return a fresh id on every call to keep request ids deterministic. Defaults to\n * `crypto.randomUUID()`.\n */\n readonly idGenerator?: () => string;\n /**\n * Signs the pending request a run writes when a `beforeToolCall` gate returns `ask`. The default,\n * `ephemeralSigner()`, holds a random key that lives only in this process, so only this process can verify its\n * pauses: on a serverless host, or anywhere a pause may resume in another process, pass `hmacSigner()` over a key\n * ring you keep. A pause that can't be signed is never written unsigned; its call is blocked instead.\n */\n readonly signer?: ApprovalSigner;\n}\n\n/** What `continueRun()` takes besides the shared options: the answers to a paused context's requests. */\nexport interface ContinueOptions<S = unknown> extends RunOptions<S> {\n /**\n * A person's answer to each pending request of the context: `{ requestId, decision: \"allow\" | \"deny\" }` for an\n * approval, `{ requestId, answer }` for a question. Each is checked against its request and the input\n * `context.pendingInputs` holds for it, with the run's `signer`, before anything runs. A request no resolution\n * names still waits, and the run ends paused again without a model call.\n */\n readonly resolutions?: readonly Resolution[];\n /**\n * Runs current policy for each verified approval just before its call runs. It gets copies of the request and\n * input. Resolve to `\"allow\"` to run the call, or to `{ deny: reason }` to give the model an error result with that\n * reason instead. A `recheck` that throws or returns anything else denies the call. Without it, a verified approval\n * runs, so check policy before you resolve.\n */\n readonly recheck?: Recheck;\n}\n\n/** What `run()` takes besides the shared options. */\nexport interface RunInput {\n /** The system prompt. */\n readonly system: string;\n /** The user's message that starts the run. */\n readonly input: string | readonly ContentBlock[];\n /** Earlier messages to send before `input`, such as a previous conversation. */\n readonly history?: readonly Message[];\n}\n\n/**\n * A run in progress. Iterate it to stream its events: each iteration starts from the run's first event, so you can\n * start iterating at any time. Await `result` for the outcome; it rejects only for a programmer error, such as a\n * tool that returns a malformed result, and iteration then throws the same error after the last event.\n */\nexport interface Run<S = unknown> extends AsyncIterable<AgentEvent> {\n /** The run's id, which every event carries. */\n readonly id: string;\n /** The outcome, once the run has stopped. */\n readonly result: Promise<RunResult<S>>;\n /**\n * Stops the run. A model call in flight ends, a running tool sees its `signal` fire, and calls that haven't started\n * get an error result instead. The run then ends with `stopReason: \"aborted\"`, unless a gate already paused a call\n * in the step, which ends it `awaiting_approval`, because that call's signed request still waits. Does nothing once\n * the run has its outcome and is ending, which is before `agent_settled`.\n */\n abort(reason?: string): void;\n /**\n * Adds an observer that receives the events from now on, in order, and returns the function that removes it. An\n * event that was queued for it but not yet handled is dropped when you remove it. Add it right after `run()` to\n * see every event but `run_start`, which `run()` emits before it returns; to see that one too, pass the observer\n * in the `observers` option.\n */\n on(observer: Observer): () => void;\n /**\n * Queues a user message that redirects the run. The run applies it at the next step boundary: after the model call\n * or tool batch in flight, never inside it, and before the next model call. The promise resolves with a\n * `DeliveryReceipt` once the message is in the transcript, and the run emits a `steer_applied` event for it. It\n * rejects with an `SdkError` whose code is `undelivered_message` when the run ends first, and with\n * `invalid_run_options` for a blank message or a block that isn't text or an image. Steers are applied in the\n * order they were sent.\n */\n steer(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;\n /**\n * Queues a user message that waits until the run would otherwise end. When the model has answered and no tool call\n * is left, the run applies every waiting follow-up as user messages and makes one more model call, so a follow-up\n * sent before the run ends extends it by one step. A steer that is waiting goes first. The run still ends, and the\n * follow-up rejects with `undelivered_message`, when another stop reason ends it: a `shouldStop` hook or progress\n * policy that stops it, its output tool, an abort or `maxSteps`. The receipt works as for `steer()`.\n */\n followUp(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction checkObserver(observer: unknown): void {\n if (typeof observer !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `an observer must be a function, got ${typeof observer}`);\n }\n}\n\nconst HOOK_NAMES = [\n \"transformContext\",\n \"beforeModelCall\",\n \"afterModelCall\",\n \"beforeToolCall\",\n \"afterToolCall\",\n \"shouldStop\",\n] as const;\n\n/** Checks the interceptors option once, so a misspelt or mistyped hook fails at `run()` and not mid-run. */\nfunction checkInterceptors(interceptors: Interceptors): Interceptors {\n if (typeof interceptors !== \"object\" || interceptors === null) {\n throw new SdkError(\"invalid_run_options\", \"interceptors must be an object of hooks\");\n }\n for (const name of HOOK_NAMES) {\n const hook: unknown = interceptors[name];\n if (hook !== undefined && typeof hook !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.${name} must be a function, got ${typeof hook}`);\n }\n }\n blockingHandlerOf(interceptors);\n const { onFailure } = interceptors;\n if (onFailure !== undefined && onFailure !== \"fail_closed\" && onFailure !== \"continue\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.onFailure must be \"fail_closed\" or \"continue\"`);\n }\n return interceptors;\n}\n\nfunction reasonOf(reason: unknown): string | undefined {\n if (typeof reason === \"string\") return reason;\n return reason instanceof Error ? reason.message : undefined;\n}\n\nclass RunHandle<S> implements Run<S> {\n readonly id: string;\n readonly result: Promise<RunResult<S>>;\n readonly #events: AgentEvent[] = [];\n readonly #controller = new AbortController();\n readonly #clock: Clock;\n readonly #bus: ObserverBus;\n #waiters: (() => void)[] = [];\n #ended = false;\n /** Set once the loop has its outcome and starts to end the run, so `abort()` no longer does anything. */\n #settled = false;\n /** Set by `run_end`: nothing may follow it, so a late observer report is dropped. */\n #closed = false;\n readonly #steering: SteeringQueue;\n #failure: { readonly error: unknown } | undefined;\n #stepIndex = 0;\n\n constructor(setup: Omit<LoopSetup, \"signal\" | \"steering\">, signal: AbortSignal | undefined, watch: ObserverSetup) {\n this.id = setup.runId;\n this.#clock = setup.clock;\n this.#steering = new SteeringQueue(setup.runId);\n this.#bus = new ObserverBus((hook, error) => {\n if (!this.#closed) this.#push({ type: \"hook_error\", hook, error: messageOf(error) }, this.#stepIndex);\n }, watch.timeoutMs);\n const { observers } = watch;\n for (const observer of observers) this.#bus.add(observer);\n const emit = (body: AgentEventBody, stepIndex: number) => this.#push(body, stepIndex);\n const { model } = setup;\n const versions = { sdkVersion: SDK_VERSION, specVersion: \"v1\" as const, defaultsHash: \"\", capabilities: [] };\n emit({ type: \"run_start\", ...versions, model: model.ref }, 0);\n const forwardAbort = () => this.abort(reasonOf(signal?.reason));\n if (signal?.aborted) forwardAbort();\n else signal?.addEventListener(\"abort\", forwardAbort, { once: true });\n // The loop starts after this turn, so an observer added with `run.on()` straight after `run()` sees every event\n // after `run_start`, and a `run.abort()` straight after it stops the run before its first model call.\n // The loop drains the observers only once it has its outcome (`finish()`), so the first drain is also where an\n // abort stops mattering: it could no longer change the outcome, only add an `abort` event after it.\n const drain = () => {\n this.#settled = true;\n return this.#bus.flush();\n };\n const loop = Promise.resolve().then(() =>\n runLoop({ ...setup, signal: this.#controller.signal, steering: this.#steering }, emit, drain),\n );\n // The loop's result type is `RunResult<unknown>`; only the output tool, whose type is `S`, fills `output`.\n this.result = loop as Promise<RunResult<S>>;\n // Handling the rejection here also keeps a caller who only iterates from an unhandled rejection: iteration\n // throws the same error.\n loop.then(\n () => this.#end(signal, forwardAbort, undefined),\n (error: unknown) => this.#end(signal, forwardAbort, { error }),\n );\n }\n\n abort(reason?: string): void {\n if (this.#settled || this.#ended || this.#controller.signal.aborted) return;\n this.#push(reason === undefined ? { type: \"abort\" } : { type: \"abort\", reason }, this.#stepIndex);\n this.#controller.abort(reason);\n }\n\n on(observer: Observer): () => void {\n checkObserver(observer);\n return this.#bus.add(observer);\n }\n\n steer(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n return this.#steering.add(\"steer\", message);\n }\n\n followUp(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n return this.#steering.add(\"follow_up\", message);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {\n let cursor = 0;\n return {\n next: async () => {\n while (cursor >= this.#events.length && !this.#ended) {\n await new Promise<void>((resolve) => this.#waiters.push(resolve));\n }\n const event = this.#events[cursor];\n if (event !== undefined) {\n cursor += 1;\n return { value: event, done: false };\n }\n if (this.#failure !== undefined) throw this.#failure.error;\n return { value: undefined, done: true };\n },\n };\n }\n\n #push(body: AgentEventBody, stepIndex: number): void {\n this.#stepIndex = stepIndex;\n if (body.type === \"run_end\") this.#closed = true;\n const base = { runId: this.id, seq: this.#events.length, stepIndex, timestamp: this.#clock.now() };\n const event = { ...base, ...body } as AgentEvent;\n this.#events.push(event);\n this.#bus.deliver(event);\n this.#wake();\n }\n\n #end(signal: AbortSignal | undefined, forwardAbort: () => void, failure: { readonly error: unknown } | undefined) {\n signal?.removeEventListener(\"abort\", forwardAbort);\n this.#failure = failure;\n this.#ended = true;\n this.#wake();\n }\n\n #wake(): void {\n const waiters = this.#waiters;\n this.#waiters = [];\n for (const wake of waiters) wake();\n }\n}\n\nfunction isModel(model: unknown): model is Model {\n const candidate = model as Partial<Model> | null;\n return (\n typeof candidate === \"object\" &&\n candidate !== null &&\n typeof candidate.stream === \"function\" &&\n typeof candidate.price === \"function\" &&\n typeof candidate.ref === \"object\"\n );\n}\n\n/** Every tool the run may send, the output tool last unless `tools` already holds it, after checking each one. */\nfunction toolsOf(options: RunOptions<unknown>): AnyTool[] {\n const tools = [...(options.tools ?? [])] as AnyTool[];\n const output = options.output as AnyTool | undefined;\n if (output !== undefined && !tools.includes(output)) tools.push(output);\n const names = new Set<string>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (names.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n names.add(tool.name);\n }\n return tools;\n}\n\nfunction isCount(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n}\n\n/**\n * The `depth` and `maxDepth` options for a run that a tool starts: one level deeper than the tool's own run, under\n * the same cap. Spread it into the nested `run()`; the nested run throws `max_depth_exceeded` when the tool was\n * already at `maxDepth`.\n */\nexport function nestedRunDepth(ctx: Pick<ToolContext, \"depth\" | \"maxDepth\">): { depth: number; maxDepth: number } {\n return { depth: ctx.depth + 1, maxDepth: ctx.maxDepth };\n}\n\n/** Checks `depth` and `maxDepth`, and refuses a run nested deeper than the cap allows (D11). */\nfunction depthsOf(options: RunOptions<unknown>): { depth: number; maxDepth: number } {\n const { depth = 0, maxDepth = DEFAULT_MAX_DEPTH } = options;\n if (!isCount(depth) || !isCount(maxDepth)) {\n throw new SdkError(\n \"invalid_run_options\",\n `depth and maxDepth must be whole numbers, 0 or more, got ${String(depth)} and ${String(maxDepth)}`,\n );\n }\n if (depth > maxDepth) {\n throw new SdkError(\"max_depth_exceeded\", `a run at depth ${depth} is deeper than maxDepth ${maxDepth} allows`);\n }\n return { depth, maxDepth };\n}\n\n/**\n * The default progress policy for this run, or `undefined` when `progress: false` turns it off. `skip` is the number\n * of messages before the run's own.\n */\nfunction progressOf(options: RunOptions<unknown>, tools: readonly AnyTool[], skip: number): ProgressCheck | undefined {\n const policy = resolveProgress(options.progress);\n return policy === undefined ? undefined : progressCheck(tools, policy, skip);\n}\n\nfunction setupOf(\n options: RunOptions<unknown>,\n context: Context,\n input: readonly Message[],\n): Omit<LoopSetup, \"signal\" | \"steering\"> {\n if (!isModel(options.model)) {\n throw new SdkError(\n \"invalid_run_options\",\n \"the model must come from createModel(), such as createModel({ adapter, id })\",\n );\n }\n const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;\n if (!Number.isInteger(maxSteps) || maxSteps < 1) {\n throw new SdkError(\"invalid_run_options\", `maxSteps must be a positive integer, got ${maxSteps}`);\n }\n const signer = options.signer ?? ephemeralSigner();\n if (!isSigner(signer)) {\n throw new SdkError(\n \"invalid_run_options\",\n \"signer must be an ApprovalSigner, such as hmacSigner() or ephemeralSigner()\",\n );\n }\n const budgetUsd = checkBudgetOption(options.budgetUsd);\n const tools = toolsOf(options);\n const { depth, maxDepth } = depthsOf(options);\n const progress = progressOf(options, tools, context.messages.length + input.length);\n if (options.output !== undefined && (options.output.exposure ?? \"direct\") !== \"direct\") {\n throw new SdkError(\n \"invalid_run_options\",\n `the output tool \"${options.output.name}\" must be sent to the model, so its exposure must be \"direct\"`,\n );\n }\n const nextId = options.idGenerator ?? randomIds;\n return {\n runId: nextId(),\n nextId,\n signer,\n model: options.model,\n system: context.system,\n history: context.messages,\n input,\n tools,\n output: options.output as AnyTool | undefined,\n maxSteps,\n ...(budgetUsd === undefined ? {} : { budgetUsd }),\n depth,\n maxDepth,\n modelOptions: options.modelOptions ?? {},\n interceptors: checkInterceptors(options.interceptors ?? {}),\n ...(progress === undefined ? {} : { progress }),\n clock: options.clock ?? systemClock,\n };\n}\n\n/** The observers a run starts with, and how long it waits for them. */\ninterface ObserverSetup {\n readonly observers: readonly Observer[];\n readonly timeoutMs: number;\n}\n\nfunction observersOf(options: RunOptions<unknown>): ObserverSetup {\n const observers = options.observers ?? [];\n for (const observer of observers) checkObserver(observer);\n const timeoutMs = options.observerTimeoutMs ?? DEFAULT_OBSERVER_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_MS) {\n throw new SdkError(\n \"invalid_run_options\",\n `observerTimeoutMs must be a number from 1 to ${MAX_TIMER_MS}, got ${timeoutMs}`,\n );\n }\n return { observers, timeoutMs };\n}\n\n/**\n * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool\n * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an\n * unusable option: a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool\n * that isn't sent to the model, or two tools with one name.\n */\nexport function run<S = unknown>(options: RunOptions<S> & RunInput): Run<S> {\n const content = typeof options.input === \"string\" ? [{ type: \"text\" as const, text: options.input }] : options.input;\n const input: Message = { role: \"user\", content: [...content] };\n const setup = setupOf(options, { system: options.system, messages: options.history ?? [] }, [input]);\n return new RunHandle<S>(setup, options.signal, observersOf(options));\n}\n\n/**\n * Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like\n * `run()`, from the last message in the context, and `result.messages` holds only the messages it adds. The context\n * is sent as it stands, so add a user message to one that ends with the model's answer, such as a `done` result's.\n * A context whose last response ended in an error asks the model again.\n *\n * A paused context resumes with `resolutions`. Before the first model call, each waiting call's stored request is\n * verified with the run's `signer` against its call and its input in `context.pendingInputs`, then:\n *\n * - a verified `allow` runs the call once, with the input its request signs and without `beforeToolCall`, after\n * `recheck` allows it;\n * - a verified `deny` gives the model an error result with the reason, and a verified `answer` reaches the model as\n * the call's result;\n * - a request no resolution names still waits;\n * - a request or resolution that fails its check runs nothing, emits `resolution_rejected`, and the call asks again\n * with a new approval request: the gate is asked as for a new call, and the call pauses even when the gate allows\n * it. A call to a tool the model isn't sent by default gets the unknown-tool error result instead.\n *\n * Settling the requests is not a step. When a call still waits, the run ends paused again without a model call, and\n * when none does and an approved call's result sets `terminate`, the run ends `done` without one.\n * Each request answers once per context, but the SDK can't see other processes: mark a request used in your store\n * before you resume it, so a second resume of the same stored context is refused there.\n *\n * Throws an `SdkError` with code `invalid_run_options` for a context it can't read, for a context whose last\n * assistant message has a call with no result and no pending request, for a pending request whose call doesn't wait\n * in the context, and for malformed `resolutions` or `recheck`, besides the options `run()` refuses.\n */\nexport function continueRun<S = unknown>(context: Context, options: ContinueOptions<S>): Run<S> {\n const resume = resumeSetupOf(context, options?.resolutions, options?.recheck);\n const setup = setupOf(options, context, []);\n return new RunHandle<S>(resume === undefined ? setup : { ...setup, resume }, options.signal, observersOf(options));\n}\n\n/**\n * Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that\n * carries the result and the context to continue from.\n */\nexport async function runOrThrow<S>(started: Run<S>): Promise<DoneResult<S>> {\n const result = await started.result;\n if (result.stopReason === \"done\") return result;\n throw new RunStoppedError(result);\n}\n"]}
1
+ {"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,cAAc,EAEd,8BAA8B,EAC9B,kBAAkB,GAInB,MAAM,uBAAuB,CAAC;A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AE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,EAAE,CAAC;IAC/D,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,OAAO,IAAI,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;IACrG,OAAO,IAAI,SAAS,CAAI,KAAK,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AACvE,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,WAAW,CAAc,OAAgB,EAAE,OAA2B;IACpF,MAAM,MAAM,GAAG,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC9E,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;IAC5C,OAAO,IAAI,SAAS,CAAI,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AACrH,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAI,OAAe;IACjD,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC;IACpC,IAAI,MAAM,CAAC,UAAU,KAAK,MAAM;QAAE,OAAO,MAAM,CAAC;IAChD,MAAM,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * `run()`, `continueRun()` and `runOrThrow()`, and the `Run` object they share (SDK plan §3.3; D10). A run streams\n * its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the\n * non-streaming caller drive one loop.\n */\nimport {\n abortableSleep,\n type ContentBlock,\n DEFAULT_INITIAL_RETRY_DELAY_MS,\n MAX_RETRY_DELAY_MS,\n type Message,\n type Model,\n type Sleep,\n} from \"@buildanagent/gateway\";\nimport { checkBudgetOption } from \"./budget.js\";\nimport { RunStoppedError, SdkError } from \"./errors.js\";\nimport type { AgentEvent, AgentEventBody } from \"./events.js\";\nimport type { CallOptions, Interceptors, Observer } from \"./hooks.js\";\nimport { type LoopSetup, runLoop } from \"./loop.js\";\nimport { ObserverBus } from \"./observers.js\";\nimport { blockingHandlerOf, isSigner } from \"./pauses.js\";\nimport { type ProgressCheck, type ProgressPolicy, progressCheck, resolveProgress } from \"./progress.js\";\nimport type { Context, DoneResult, RunResult } from \"./result.js\";\nimport { resumeSetupOf } from \"./resume.js\";\nimport { type DeliveryReceipt, SteeringQueue } from \"./steering.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { preparedSchemaOf } from \"./tools/define.js\";\nimport type { AnyTool } from \"./tools/pipeline.js\";\nimport type { ToolContext, ToolDefinition } from \"./tools/types.js\";\nimport type { Recheck, Resolution } from \"./vendor/agent-safety/pending.js\";\nimport { type ApprovalSigner, ephemeralSigner } from \"./vendor/agent-safety/signer.js\";\nimport { SDK_VERSION } from \"./version.js\";\n\n/** The step cap's default, counted in model calls. */\nconst DEFAULT_MAX_STEPS = 20;\n\n/** The depth cap's default (D11): a top-level run, its subagents and their subagents may run, and no deeper. */\nconst DEFAULT_MAX_DEPTH = 2;\n\n/** How long the run waits, by default, for an observer to catch up before it drops it. */\nconst DEFAULT_OBSERVER_TIMEOUT_MS = 10_000;\n/** The longest delay `setTimeout` accepts; a larger one fires at once on Node and workerd alike. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\nconst systemClock: Clock = { now: () => new Date().toISOString() };\nconst randomIds = (): string => globalThis.crypto.randomUUID();\n\n/** The options `run()` and `continueRun()` share. */\nexport interface RunOptions<S = unknown> {\n /** The model, from `createModel()`. */\n readonly model: Model;\n /**\n * The tools the model may call. Tools whose `exposure` is `deferred` or `hidden` are not sent unless a\n * `beforeModelCall` interceptor names them in `activeTools`.\n */\n readonly tools?: readonly ToolDefinition<unknown, unknown>[];\n /**\n * A tool from `outputTool()` whose input is the final answer. It is sent with the other tools; once the model calls\n * it with input that passes its schema, the run ends `done`, and `result.output` holds the validated answer.\n */\n readonly output?: ToolDefinition<S, S>;\n /**\n * The most model calls the run may make. Default 20. A run that reaches it while the model still wants to go on\n * ends with `stopReason: \"max_steps\"` and emits a `warning` event with `code: \"max_steps\"`.\n */\n readonly maxSteps?: number;\n /**\n * How many times the loop re-issues a model call that ended with a `retryable` error, such as a stream cut off\n * after it had started to answer. Default 0: the run ends `error` on the first failure, and `continueRun()` is the\n * way to try again. `turnRetries: 3` retries as Pi does. This is the third retry layer: the model's own retries\n * (`createModel({ retries })`) re-send a request that failed before any output, so a call can make up to\n * `(retries + 1) * (turnRetries + 1)` requests. The count restarts after each call that succeeds. Only\n * `retryable` failures are retried: `overflow`, `quota` and `fatal` end the run, and so does a `retryable` failure\n * whose `error.retryAfterMs` is over the gateway's 60-second cap. Every attempt counts against `maxSteps`, and a\n * failed attempt's usage and cost go into the result; a run that `maxSteps` stops after a retry ends `max_steps`. With `budgetUsd` set, a retry the budget can't cover, or one after an attempt whose cost is\n * unknown, is not made: the run ends `budget`, or `error` with the failure's own error.\n * Each retry emits a `retry` event with `layer: \"turn\"`.\n */\n readonly turnRetries?: number;\n /**\n * The wait before the first turn retry, in milliseconds. Default 2000; each later retry of a streak waits twice as\n * long, up to 60 seconds, or as long as the failure's `error.retryAfterMs` asks if that is longer.\n */\n readonly turnRetryDelayMs?: number;\n /**\n * Waits between turn retries. Defaults to a timer that ends early, without rejecting, when the run is aborted; a\n * test passes a fake to skip the wait. A `sleep` that rejects ends the wait early and emits a `hook_error` event.\n */\n readonly sleep?: Sleep;\n /**\n * The most the run's model calls may cost, in USD. Before each call the run projects its cost with\n * `projectCallCost()` and, if the spend so far plus that projection would pass the cap, ends with\n * `stopReason: \"budget\"` without making the call. The cap counts the calls this run makes, not the cost of the\n * history a `continueRun()` starts from. A budgeted run on a model whose price is unknown ends `error` with\n * `error.kind: \"unknown_price\"` before its first call, because it could not tell what it spent. Without it, a run\n * has no cap.\n */\n readonly budgetUsd?: number;\n /**\n * The default progress policy: the run ends `no_progress` after 3 identical failing tool calls in a row, or after 5\n * calls to a tool with one `progressKey` and no success between them. It runs after your own `shouldStop`, whose\n * `{ continue }` can't keep a stuck run going. Pass numbers to change either threshold, or `false` to turn the\n * policy off.\n */\n readonly progress?: ProgressPolicy | false;\n /**\n * How deeply this run is nested inside other agents' tool calls. Default 0. A tool that starts a run of its own\n * passes `depth: ctx.depth + 1` and `maxDepth: ctx.maxDepth`; `run()` throws an `SdkError` with code\n * `max_depth_exceeded` when `depth` is above `maxDepth`, which the tool's caller reads as an error result.\n */\n readonly depth?: number;\n /** The deepest nesting allowed, which tools read as `ctx.maxDepth`. Default 2. */\n readonly maxDepth?: number;\n /** Aborts the run, like `run.abort()`. */\n readonly signal?: AbortSignal;\n /** Options for every model call, such as `maxOutputTokens`. The run passes its own abort signal. */\n readonly modelOptions?: CallOptions;\n /**\n * The interceptors: hooks that can change the run at six moments. A run takes one object; join several with\n * `composeInterceptors()`. See `Interceptors` for the order and for what a failing hook does.\n */\n readonly interceptors?: Interceptors;\n /**\n * Observers, which receive every event from `run_start` on and can't change the run. Each observer sees the events in\n * order and waits for its own promises, but observers don't wait for each other. An observer that throws becomes a\n * `hook_error` event. The run waits for every observer to handle the last event before it settles, for at most\n * `observerTimeoutMs` each time it waits; an observer that hasn't caught up by then is removed and reported as a\n * `hook_error`.\n */\n readonly observers?: readonly Observer[];\n /**\n * The longest the run waits for its observers each time it waits for them: before `agent_settled`, before\n * `run_end` and before it settles. A number from 1 to 2147483647; the default is 10000. It bounds an observer whose promise never settles.\n */\n readonly observerTimeoutMs?: number;\n /** Stamps each event's `timestamp`, and is passed to tools. Defaults to the system clock. */\n readonly clock?: Clock;\n /**\n * Makes the run's id, then the id of each pending request the run signs. A request id that repeats the run's id or\n * an earlier request's id is replaced by `crypto.randomUUID()`, so a generator that always returns one id still\n * pauses every call; return a fresh id on every call to keep request ids deterministic. Defaults to\n * `crypto.randomUUID()`.\n */\n readonly idGenerator?: () => string;\n /**\n * Signs the pending request a run writes when a `beforeToolCall` gate returns `ask`. The default,\n * `ephemeralSigner()`, holds a random key that lives only in this process, so only this process can verify its\n * pauses: on a serverless host, or anywhere a pause may resume in another process, pass `hmacSigner()` over a key\n * ring you keep. A pause that can't be signed is never written unsigned; its call is blocked instead.\n */\n readonly signer?: ApprovalSigner;\n}\n\n/** What `continueRun()` takes besides the shared options: the answers to a paused context's requests. */\nexport interface ContinueOptions<S = unknown> extends RunOptions<S> {\n /**\n * A person's answer to each pending request of the context: `{ requestId, decision: \"allow\" | \"deny\" }` for an\n * approval, `{ requestId, answer }` for a question. Each is checked against its request and the input\n * `context.pendingInputs` holds for it, with the run's `signer`, before anything runs. A request no resolution\n * names still waits, and the run ends paused again without a model call.\n */\n readonly resolutions?: readonly Resolution[];\n /**\n * Runs current policy for each verified approval just before its call runs. It gets copies of the request and\n * input. Resolve to `\"allow\"` to run the call, or to `{ deny: reason }` to give the model an error result with that\n * reason instead. A `recheck` that throws or returns anything else denies the call. Without it, a verified approval\n * runs, so check policy before you resolve.\n */\n readonly recheck?: Recheck;\n}\n\n/** What `run()` takes besides the shared options. */\nexport interface RunInput {\n /** The system prompt. */\n readonly system: string;\n /** The user's message that starts the run. */\n readonly input: string | readonly ContentBlock[];\n /** Earlier messages to send before `input`, such as a previous conversation. */\n readonly history?: readonly Message[];\n}\n\n/**\n * A run in progress. Iterate it to stream its events: each iteration starts from the run's first event, so you can\n * start iterating at any time. Await `result` for the outcome; it rejects only for a programmer error, such as a\n * tool that returns a malformed result, and iteration then throws the same error after the last event.\n */\nexport interface Run<S = unknown> extends AsyncIterable<AgentEvent> {\n /** The run's id, which every event carries. */\n readonly id: string;\n /** The outcome, once the run has stopped. */\n readonly result: Promise<RunResult<S>>;\n /**\n * Stops the run. A model call in flight ends, a running tool sees its `signal` fire, and calls that haven't started\n * get an error result instead. The run then ends with `stopReason: \"aborted\"`, unless a gate already paused a call\n * in the step, which ends it `awaiting_approval`, because that call's signed request still waits. Does nothing once\n * the run has its outcome and is ending, which is before `agent_settled`.\n */\n abort(reason?: string): void;\n /**\n * Adds an observer that receives the events from now on, in order, and returns the function that removes it. An\n * event that was queued for it but not yet handled is dropped when you remove it. Add it right after `run()` to\n * see every event but `run_start`, which `run()` emits before it returns; to see that one too, pass the observer\n * in the `observers` option.\n */\n on(observer: Observer): () => void;\n /**\n * Queues a user message that redirects the run. The run applies it at the next step boundary: after the model call\n * or tool batch in flight, never inside it, and before the next model call. The promise resolves with a\n * `DeliveryReceipt` once the message is in the transcript, and the run emits a `steer_applied` event for it. It\n * rejects with an `SdkError` whose code is `undelivered_message` when the run ends first, and with\n * `invalid_run_options` for a blank message or a block that isn't text or an image. Steers are applied in the\n * order they were sent.\n */\n steer(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;\n /**\n * Queues a user message that waits until the run would otherwise end. When the model has answered and no tool call\n * is left, the run applies every waiting follow-up as user messages and makes one more model call, so a follow-up\n * sent before the run ends extends it by one step. A steer that is waiting goes first. The run still ends, and the\n * follow-up rejects with `undelivered_message`, when another stop reason ends it: a `shouldStop` hook or progress\n * policy that stops it, its output tool, an abort or `maxSteps`. The receipt works as for `steer()`.\n */\n followUp(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction checkObserver(observer: unknown): void {\n if (typeof observer !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `an observer must be a function, got ${typeof observer}`);\n }\n}\n\nconst HOOK_NAMES = [\n \"transformContext\",\n \"beforeModelCall\",\n \"afterModelCall\",\n \"beforeToolCall\",\n \"afterToolCall\",\n \"shouldStop\",\n] as const;\n\n/** Checks the interceptors option once, so a misspelt or mistyped hook fails at `run()` and not mid-run. */\nfunction checkInterceptors(interceptors: Interceptors): Interceptors {\n if (typeof interceptors !== \"object\" || interceptors === null) {\n throw new SdkError(\"invalid_run_options\", \"interceptors must be an object of hooks\");\n }\n for (const name of HOOK_NAMES) {\n const hook: unknown = interceptors[name];\n if (hook !== undefined && typeof hook !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.${name} must be a function, got ${typeof hook}`);\n }\n }\n blockingHandlerOf(interceptors);\n const { onFailure } = interceptors;\n if (onFailure !== undefined && onFailure !== \"fail_closed\" && onFailure !== \"continue\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.onFailure must be \"fail_closed\" or \"continue\"`);\n }\n return interceptors;\n}\n\nfunction reasonOf(reason: unknown): string | undefined {\n if (typeof reason === \"string\") return reason;\n return reason instanceof Error ? reason.message : undefined;\n}\n\nclass RunHandle<S> implements Run<S> {\n readonly id: string;\n readonly result: Promise<RunResult<S>>;\n readonly #events: AgentEvent[] = [];\n readonly #controller = new AbortController();\n readonly #clock: Clock;\n readonly #bus: ObserverBus;\n #waiters: (() => void)[] = [];\n #ended = false;\n /** Set once the loop has its outcome and starts to end the run, so `abort()` no longer does anything. */\n #settled = false;\n /** Set by `run_end`: nothing may follow it, so a late observer report is dropped. */\n #closed = false;\n readonly #steering: SteeringQueue;\n #failure: { readonly error: unknown } | undefined;\n #stepIndex = 0;\n\n constructor(setup: Omit<LoopSetup, \"signal\" | \"steering\">, signal: AbortSignal | undefined, watch: ObserverSetup) {\n this.id = setup.runId;\n this.#clock = setup.clock;\n this.#steering = new SteeringQueue(setup.runId);\n this.#bus = new ObserverBus((hook, error) => {\n if (!this.#closed) this.#push({ type: \"hook_error\", hook, error: messageOf(error) }, this.#stepIndex);\n }, watch.timeoutMs);\n const { observers } = watch;\n for (const observer of observers) this.#bus.add(observer);\n const emit = (body: AgentEventBody, stepIndex: number) => this.#push(body, stepIndex);\n const { model } = setup;\n const versions = { sdkVersion: SDK_VERSION, specVersion: \"v1\" as const, defaultsHash: \"\", capabilities: [] };\n emit({ type: \"run_start\", ...versions, model: model.ref }, 0);\n const forwardAbort = () => this.abort(reasonOf(signal?.reason));\n if (signal?.aborted) forwardAbort();\n else signal?.addEventListener(\"abort\", forwardAbort, { once: true });\n // The loop starts after this turn, so an observer added with `run.on()` straight after `run()` sees every event\n // after `run_start`, and a `run.abort()` straight after it stops the run before its first model call.\n // The loop drains the observers only once it has its outcome (`finish()`), so the first drain is also where an\n // abort stops mattering: it could no longer change the outcome, only add an `abort` event after it.\n const drain = () => {\n this.#settled = true;\n return this.#bus.flush();\n };\n const loop = Promise.resolve().then(() =>\n runLoop({ ...setup, signal: this.#controller.signal, steering: this.#steering }, emit, drain),\n );\n // The loop's result type is `RunResult<unknown>`; only the output tool, whose type is `S`, fills `output`.\n this.result = loop as Promise<RunResult<S>>;\n // Handling the rejection here also keeps a caller who only iterates from an unhandled rejection: iteration\n // throws the same error.\n loop.then(\n () => this.#end(signal, forwardAbort, undefined),\n (error: unknown) => this.#end(signal, forwardAbort, { error }),\n );\n }\n\n abort(reason?: string): void {\n if (this.#settled || this.#ended || this.#controller.signal.aborted) return;\n this.#push(reason === undefined ? { type: \"abort\" } : { type: \"abort\", reason }, this.#stepIndex);\n this.#controller.abort(reason);\n }\n\n on(observer: Observer): () => void {\n checkObserver(observer);\n return this.#bus.add(observer);\n }\n\n steer(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n return this.#steering.add(\"steer\", message);\n }\n\n followUp(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n return this.#steering.add(\"follow_up\", message);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {\n let cursor = 0;\n return {\n next: async () => {\n while (cursor >= this.#events.length && !this.#ended) {\n await new Promise<void>((resolve) => this.#waiters.push(resolve));\n }\n const event = this.#events[cursor];\n if (event !== undefined) {\n cursor += 1;\n return { value: event, done: false };\n }\n if (this.#failure !== undefined) throw this.#failure.error;\n return { value: undefined, done: true };\n },\n };\n }\n\n #push(body: AgentEventBody, stepIndex: number): void {\n this.#stepIndex = stepIndex;\n if (body.type === \"run_end\") this.#closed = true;\n const base = { runId: this.id, seq: this.#events.length, stepIndex, timestamp: this.#clock.now() };\n const event = { ...base, ...body } as AgentEvent;\n this.#events.push(event);\n this.#bus.deliver(event);\n this.#wake();\n }\n\n #end(signal: AbortSignal | undefined, forwardAbort: () => void, failure: { readonly error: unknown } | undefined) {\n signal?.removeEventListener(\"abort\", forwardAbort);\n this.#failure = failure;\n this.#ended = true;\n this.#wake();\n }\n\n #wake(): void {\n const waiters = this.#waiters;\n this.#waiters = [];\n for (const wake of waiters) wake();\n }\n}\n\nfunction isModel(model: unknown): model is Model {\n const candidate = model as Partial<Model> | null;\n return (\n typeof candidate === \"object\" &&\n candidate !== null &&\n typeof candidate.stream === \"function\" &&\n typeof candidate.price === \"function\" &&\n typeof candidate.ref === \"object\"\n );\n}\n\n/** Every tool the run may send, the output tool last unless `tools` already holds it, after checking each one. */\nfunction toolsOf(options: RunOptions<unknown>): AnyTool[] {\n const tools = [...(options.tools ?? [])] as AnyTool[];\n const output = options.output as AnyTool | undefined;\n if (output !== undefined && !tools.includes(output)) tools.push(output);\n const names = new Set<string>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (names.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n names.add(tool.name);\n }\n return tools;\n}\n\nfunction isCount(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n}\n\n/**\n * The `depth` and `maxDepth` options for a run that a tool starts: one level deeper than the tool's own run, under\n * the same cap. Spread it into the nested `run()`; the nested run throws `max_depth_exceeded` when the tool was\n * already at `maxDepth`.\n */\nexport function nestedRunDepth(ctx: Pick<ToolContext, \"depth\" | \"maxDepth\">): { depth: number; maxDepth: number } {\n return { depth: ctx.depth + 1, maxDepth: ctx.maxDepth };\n}\n\n/** Checks `depth` and `maxDepth`, and refuses a run nested deeper than the cap allows (D11). */\nfunction depthsOf(options: RunOptions<unknown>): { depth: number; maxDepth: number } {\n const { depth = 0, maxDepth = DEFAULT_MAX_DEPTH } = options;\n if (!isCount(depth) || !isCount(maxDepth)) {\n throw new SdkError(\n \"invalid_run_options\",\n `depth and maxDepth must be whole numbers, 0 or more, got ${String(depth)} and ${String(maxDepth)}`,\n );\n }\n if (depth > maxDepth) {\n throw new SdkError(\"max_depth_exceeded\", `a run at depth ${depth} is deeper than maxDepth ${maxDepth} allows`);\n }\n return { depth, maxDepth };\n}\n\n/**\n * The default progress policy for this run, or `undefined` when `progress: false` turns it off. `skip` is the number\n * of messages before the run's own.\n */\nfunction progressOf(options: RunOptions<unknown>, tools: readonly AnyTool[], skip: number): ProgressCheck | undefined {\n const policy = resolveProgress(options.progress);\n return policy === undefined ? undefined : progressCheck(tools, policy, skip);\n}\n\n/** Checks the turn-retry options and fills in their defaults. */\nfunction turnRetriesOf(options: RunOptions<unknown>): Pick<LoopSetup, \"turnRetries\" | \"turnRetryDelayMs\" | \"sleep\"> {\n const turnRetries = options.turnRetries ?? 0;\n if (!Number.isInteger(turnRetries) || turnRetries < 0) {\n throw new SdkError(\"invalid_run_options\", `turnRetries must be a non-negative integer, got ${String(turnRetries)}`);\n }\n const turnRetryDelayMs = options.turnRetryDelayMs ?? DEFAULT_INITIAL_RETRY_DELAY_MS;\n if (!Number.isFinite(turnRetryDelayMs) || turnRetryDelayMs < 0 || turnRetryDelayMs > MAX_RETRY_DELAY_MS) {\n throw new SdkError(\n \"invalid_run_options\",\n `turnRetryDelayMs must be a number from 0 to ${MAX_RETRY_DELAY_MS}, got ${String(turnRetryDelayMs)}`,\n );\n }\n const sleep = options.sleep ?? abortableSleep;\n if (typeof sleep !== \"function\") {\n throw new SdkError(\"invalid_run_options\", \"sleep must be a function, such as async (ms, signal) => {}\");\n }\n return { turnRetries, turnRetryDelayMs, sleep };\n}\n\nfunction setupOf(\n options: RunOptions<unknown>,\n context: Context,\n input: readonly Message[],\n): Omit<LoopSetup, \"signal\" | \"steering\"> {\n if (!isModel(options.model)) {\n throw new SdkError(\n \"invalid_run_options\",\n \"the model must come from createModel(), such as createModel({ adapter, id })\",\n );\n }\n const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;\n if (!Number.isInteger(maxSteps) || maxSteps < 1) {\n throw new SdkError(\"invalid_run_options\", `maxSteps must be a positive integer, got ${maxSteps}`);\n }\n const signer = options.signer ?? ephemeralSigner();\n if (!isSigner(signer)) {\n throw new SdkError(\n \"invalid_run_options\",\n \"signer must be an ApprovalSigner, such as hmacSigner() or ephemeralSigner()\",\n );\n }\n const retries = turnRetriesOf(options);\n const budgetUsd = checkBudgetOption(options.budgetUsd);\n const tools = toolsOf(options);\n const { depth, maxDepth } = depthsOf(options);\n const progress = progressOf(options, tools, context.messages.length + input.length);\n if (options.output !== undefined && (options.output.exposure ?? \"direct\") !== \"direct\") {\n throw new SdkError(\n \"invalid_run_options\",\n `the output tool \"${options.output.name}\" must be sent to the model, so its exposure must be \"direct\"`,\n );\n }\n const nextId = options.idGenerator ?? randomIds;\n return {\n runId: nextId(),\n nextId,\n signer,\n model: options.model,\n system: context.system,\n history: context.messages,\n input,\n tools,\n output: options.output as AnyTool | undefined,\n maxSteps,\n ...retries,\n ...(budgetUsd === undefined ? {} : { budgetUsd }),\n depth,\n maxDepth,\n modelOptions: options.modelOptions ?? {},\n interceptors: checkInterceptors(options.interceptors ?? {}),\n ...(progress === undefined ? {} : { progress }),\n clock: options.clock ?? systemClock,\n };\n}\n\n/** The observers a run starts with, and how long it waits for them. */\ninterface ObserverSetup {\n readonly observers: readonly Observer[];\n readonly timeoutMs: number;\n}\n\nfunction observersOf(options: RunOptions<unknown>): ObserverSetup {\n const observers = options.observers ?? [];\n for (const observer of observers) checkObserver(observer);\n const timeoutMs = options.observerTimeoutMs ?? DEFAULT_OBSERVER_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_MS) {\n throw new SdkError(\n \"invalid_run_options\",\n `observerTimeoutMs must be a number from 1 to ${MAX_TIMER_MS}, got ${timeoutMs}`,\n );\n }\n return { observers, timeoutMs };\n}\n\n/**\n * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool\n * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an\n * unusable option: a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool\n * that isn't sent to the model, or two tools with one name.\n */\nexport function run<S = unknown>(options: RunOptions<S> & RunInput): Run<S> {\n const content = typeof options.input === \"string\" ? [{ type: \"text\" as const, text: options.input }] : options.input;\n const input: Message = { role: \"user\", content: [...content] };\n const setup = setupOf(options, { system: options.system, messages: options.history ?? [] }, [input]);\n return new RunHandle<S>(setup, options.signal, observersOf(options));\n}\n\n/**\n * Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like\n * `run()`, from the last message in the context, and `result.messages` holds only the messages it adds. The context\n * is sent as it stands, so add a user message to one that ends with the model's answer, such as a `done` result's.\n * A context whose last response ended in an error asks the model again.\n *\n * A paused context resumes with `resolutions`. Before the first model call, each waiting call's stored request is\n * verified with the run's `signer` against its call and its input in `context.pendingInputs`, then:\n *\n * - a verified `allow` runs the call once, with the input its request signs and without `beforeToolCall`, after\n * `recheck` allows it;\n * - a verified `deny` gives the model an error result with the reason, and a verified `answer` reaches the model as\n * the call's result;\n * - a request no resolution names still waits;\n * - a request or resolution that fails its check runs nothing, emits `resolution_rejected`, and the call asks again\n * with a new approval request: the gate is asked as for a new call, and the call pauses even when the gate allows\n * it. A call to a tool the model isn't sent by default gets the unknown-tool error result instead.\n *\n * Settling the requests is not a step. When a call still waits, the run ends paused again without a model call, and\n * when none does and an approved call's result sets `terminate`, the run ends `done` without one.\n * Each request answers once per context, but the SDK can't see other processes: mark a request used in your store\n * before you resume it, so a second resume of the same stored context is refused there.\n *\n * Throws an `SdkError` with code `invalid_run_options` for a context it can't read, for a context whose last\n * assistant message has a call with no result and no pending request, for a pending request whose call doesn't wait\n * in the context, and for malformed `resolutions` or `recheck`, besides the options `run()` refuses.\n */\nexport function continueRun<S = unknown>(context: Context, options: ContinueOptions<S>): Run<S> {\n const resume = resumeSetupOf(context, options?.resolutions, options?.recheck);\n const setup = setupOf(options, context, []);\n return new RunHandle<S>(resume === undefined ? setup : { ...setup, resume }, options.signal, observersOf(options));\n}\n\n/**\n * Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that\n * carries the result and the context to continue from.\n */\nexport async function runOrThrow<S>(started: Run<S>): Promise<DoneResult<S>> {\n const result = await started.result;\n if (result.stopReason === \"done\") return result;\n throw new RunStoppedError(result);\n}\n"]}
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an
3
3
  * input that has no canonical JSON form, a key ring that can't sign, or a model request that would use a credential
4
- * nobody configured.
4
+ * nobody configured. Its subclass `BudgetExceeded`, in the `./cost` subpath, is the refusal of a model call that would
5
+ * pass a USD cap.
5
6
  */
6
7
  /**
7
8
  * Why a `SafetyError` was thrown. `invalid_outcome`: a write outcome breaks a rule. `invalid_input`: a tool input has
@@ -10,12 +11,19 @@
10
11
  * model provider's key or base URL is empty, malformed or points at a gateway that may bill another credential.
11
12
  * `egress_refused`: a model request would leave for another host or carry another credential. `default_provider`: code
12
13
  * resolved a string model id, or another default provider is set, so a call could reach a gateway nobody configured.
13
- * `invalid_effect`: a guarded write's scope, business key or options break a rule.
14
+ * `invalid_effect`: a guarded write's scope, business key or options break a rule. `invalid_budget`: a cost guard's
15
+ * cap is not a finite number of dollars, 0 or more. `budget_exceeded`: a model call was refused before it was sent,
16
+ * because what the run or session has spent plus the call's projected cost would pass its USD cap. `unknown_price`: a
17
+ * model call was refused before it was sent, because the model has no catalog price or an earlier call reported no
18
+ * usage, so the cap can't be checked.
19
+ */
20
+ export type SafetyErrorCode = "invalid_outcome" | "invalid_input" | "invalid_key_ring" | "invalid_pending" | "invalid_byok_config" | "egress_refused" | "default_provider" | "invalid_effect" | "invalid_budget" | "budget_exceeded" | "unknown_price";
21
+ /**
22
+ * Thrown for a mistake in how the safety package is called, and, as its subclass `BudgetExceeded`, for a model call
23
+ * refused under a USD cap. A write that fails is an outcome, never this error.
14
24
  */
15
- export type SafetyErrorCode = "invalid_outcome" | "invalid_input" | "invalid_key_ring" | "invalid_pending" | "invalid_byok_config" | "egress_refused" | "default_provider" | "invalid_effect";
16
- /** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */
17
25
  export declare class SafetyError extends Error {
18
- readonly name = "SafetyError";
26
+ readonly name: string;
19
27
  readonly code: SafetyErrorCode;
20
28
  constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions);
21
29
  }
@@ -1,11 +1,15 @@
1
1
  /**
2
2
  * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an
3
3
  * input that has no canonical JSON form, a key ring that can't sign, or a model request that would use a credential
4
- * nobody configured.
4
+ * nobody configured. Its subclass `BudgetExceeded`, in the `./cost` subpath, is the refusal of a model call that would
5
+ * pass a USD cap.
5
6
  */
6
7
  // A registered symbol, so the guard still works when two copies of the package are bundled.
7
8
  const SAFETY_ERROR = Symbol.for("buildanagent.agent-safety.SafetyError");
8
- /** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */
9
+ /**
10
+ * Thrown for a mistake in how the safety package is called, and, as its subclass `BudgetExceeded`, for a model call
11
+ * refused under a USD cap. A write that fails is an outcome, never this error.
12
+ */
9
13
  export class SafetyError extends Error {
10
14
  name = "SafetyError";
11
15
  code;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAqBH,4FAA4F;AAC5F,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;AAEzE,oHAAoH;AACpH,MAAM,OAAO,WAAY,SAAQ,KAAK;IAClB,IAAI,GAAG,aAAa,CAAC;IAC9B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAAsB;QACxE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAClH,CAAC","sourcesContent":["/**\n * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an\n * input that has no canonical JSON form, a key ring that can't sign, or a model request that would use a credential\n * nobody configured.\n */\n\n/**\n * Why a `SafetyError` was thrown. `invalid_outcome`: a write outcome breaks a rule. `invalid_input`: a tool input has\n * no canonical JSON form, or a tool's context fails its `contextSchema`. `invalid_key_ring`: a signer's keys or key\n * ids can't be used. `invalid_pending`: the fields of a pending request can't be signed. `invalid_byok_config`: a\n * model provider's key or base URL is empty, malformed or points at a gateway that may bill another credential.\n * `egress_refused`: a model request would leave for another host or carry another credential. `default_provider`: code\n * resolved a string model id, or another default provider is set, so a call could reach a gateway nobody configured.\n * `invalid_effect`: a guarded write's scope, business key or options break a rule.\n */\nexport type SafetyErrorCode =\n | \"invalid_outcome\"\n | \"invalid_input\"\n | \"invalid_key_ring\"\n | \"invalid_pending\"\n | \"invalid_byok_config\"\n | \"egress_refused\"\n | \"default_provider\"\n | \"invalid_effect\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SAFETY_ERROR = Symbol.for(\"buildanagent.agent-safety.SafetyError\");\n\n/** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */\nexport class SafetyError extends Error {\n override readonly name = \"SafetyError\";\n readonly code: SafetyErrorCode;\n\n constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SAFETY_ERROR, { value: true });\n }\n}\n\n/** True for a `SafetyError`, including one from another copy of the package. */\nexport function isSafetyError(error: unknown): error is SafetyError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SAFETY_ERROR] === true;\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/errors.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA4BH,4FAA4F;AAC5F,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;AAEzE;;;GAGG;AACH,MAAM,OAAO,WAAY,SAAQ,KAAK;IAClB,IAAI,GAAW,aAAa,CAAC;IACtC,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAAsB;QACxE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAClH,CAAC","sourcesContent":["/**\n * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an\n * input that has no canonical JSON form, a key ring that can't sign, or a model request that would use a credential\n * nobody configured. Its subclass `BudgetExceeded`, in the `./cost` subpath, is the refusal of a model call that would\n * pass a USD cap.\n */\n\n/**\n * Why a `SafetyError` was thrown. `invalid_outcome`: a write outcome breaks a rule. `invalid_input`: a tool input has\n * no canonical JSON form, or a tool's context fails its `contextSchema`. `invalid_key_ring`: a signer's keys or key\n * ids can't be used. `invalid_pending`: the fields of a pending request can't be signed. `invalid_byok_config`: a\n * model provider's key or base URL is empty, malformed or points at a gateway that may bill another credential.\n * `egress_refused`: a model request would leave for another host or carry another credential. `default_provider`: code\n * resolved a string model id, or another default provider is set, so a call could reach a gateway nobody configured.\n * `invalid_effect`: a guarded write's scope, business key or options break a rule. `invalid_budget`: a cost guard's\n * cap is not a finite number of dollars, 0 or more. `budget_exceeded`: a model call was refused before it was sent,\n * because what the run or session has spent plus the call's projected cost would pass its USD cap. `unknown_price`: a\n * model call was refused before it was sent, because the model has no catalog price or an earlier call reported no\n * usage, so the cap can't be checked.\n */\nexport type SafetyErrorCode =\n | \"invalid_outcome\"\n | \"invalid_input\"\n | \"invalid_key_ring\"\n | \"invalid_pending\"\n | \"invalid_byok_config\"\n | \"egress_refused\"\n | \"default_provider\"\n | \"invalid_effect\"\n | \"invalid_budget\"\n | \"budget_exceeded\"\n | \"unknown_price\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SAFETY_ERROR = Symbol.for(\"buildanagent.agent-safety.SafetyError\");\n\n/**\n * Thrown for a mistake in how the safety package is called, and, as its subclass `BudgetExceeded`, for a model call\n * refused under a USD cap. A write that fails is an outcome, never this error.\n */\nexport class SafetyError extends Error {\n override readonly name: string = \"SafetyError\";\n readonly code: SafetyErrorCode;\n\n constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SAFETY_ERROR, { value: true });\n }\n}\n\n/** True for a `SafetyError`, including one from another copy of the package. */\nexport function isSafetyError(error: unknown): error is SafetyError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SAFETY_ERROR] === true;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@buildanagent/sdk",
3
- "version": "0.1.0-alpha.12",
3
+ "version": "0.1.0-alpha.14",
4
4
  "description": "The buildanagent SDK: the agent loop, tools, hooks, signed pauses and budgets over the gateway.",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "repository": {
@@ -37,7 +37,7 @@
37
37
  "dependencies": {
38
38
  "@earendil-works/pi-schema": "1.5.2",
39
39
  "@standard-schema/spec": "1.1.0",
40
- "@buildanagent/gateway": "0.1.0-alpha.12"
40
+ "@buildanagent/gateway": "0.1.0-alpha.14"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@cfworker/json-schema": "4.1.6",