@buildanagent/sdk 0.1.0-alpha.5 → 0.1.0-alpha.7

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
@@ -2,7 +2,7 @@
2
2
 
3
3
  The SDK runs your agent's loop over [`@buildanagent/gateway`](../gateway/README.md): it calls the model, runs the tools the model asks for, and stops when the work is done. Its testing export lets you test that agent offline against a scripted model, with no API key.
4
4
 
5
- As of November 2026 the package holds the loop, tool definitions, hooks and the testing export. Approvals and budgets come next.
5
+ As of November 2026 the package holds the loop, tool definitions, hooks and the testing export. Approvals come next.
6
6
 
7
7
  ## Install the alpha with `pnpm add @buildanagent/sdk@alpha`
8
8
 
@@ -42,10 +42,11 @@ 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, 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, `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 tool from `clarificationTool()` asked the user a question, and `result.stoppedBy` is `"clarification"`; or a `shouldStop` hook ended the run, and `result.stoppedBy` is the reason it gave.
48
- - **`no_progress`**: a `shouldStop` hook ended the run with `{ stop: "no_progress", reason }`, and `result.reason` repeats the reason.
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.
49
+ - **`budget`**: the next call could have taken the run past `budgetUsd`, so the run ended without making it. `result.spentUsd`, `result.projectedUsd` and `result.budgetUsd` give the numbers.
49
50
 
50
51
  `maxSteps` counts model calls, so an output call that fails its schema spends one of them. The tool calls of the last allowed response still run, so every call in the transcript has a result.
51
52
 
@@ -69,6 +70,75 @@ const result = await runOrThrow(run({ model, system, input }));
69
70
 
70
71
  An aborted run's transcript stays well formed: every tool call has a result, and the last message is an assistant message with `stopReason: "aborted"`. When tool results would end the transcript, because the abort came while tools ran or cut off a response that held tool calls, the loop appends an empty aborted message after them. Each gateway adapter drops it before the next request, so the transcript can be sent again as it is.
71
72
 
73
+ ## Three guards stop a runaway run
74
+
75
+ A run that loops or overspends costs real money, so the SDK ships three guards. Each is an option of `run()` and `continueRun()`, and the table gives its default (the budget has none).
76
+
77
+ | Guard | Default | Change it with |
78
+ | --- | --- | --- |
79
+ | USD budget | none | `budgetUsd: 5` |
80
+ | Progress policy | 3 identical failing calls, or 5 calls on one `progressKey` | `progress: { maxIdenticalFailures, maxSameKeyCalls }`, or `progress: false` |
81
+ | Depth cap | `maxDepth` 2 | `depth` and `maxDepth` |
82
+
83
+ These numbers are provisional. Recorded runs will retune them.
84
+
85
+ ### `budgetUsd` checks the cost before each call
86
+
87
+ Before every model call, the run projects the most that call can cost and compares the spend so far plus that projection with `budgetUsd`. If the call could pass the cap, the run ends with `stopReason: "budget"` and never sends it. The projection comes from the gateway's `projectCallCost()`: the previous call's reported input, plus a character-based estimate of the messages added since, at the model's input rate, plus the call's `maxOutputTokens` (or the model's own limit) at its output rate. The SDK re-exports the function, so code that calls `Model.complete()` outside the loop projects with the same formula.
88
+
89
+ Because the projection assumes the model may use its whole output allowance, the run stops early rather than late.
90
+
91
+ On the SDK's scripted 30-step run, with caps placed just above the spend after `k` calls, the pre-emptive check overshot the cap by $0 on every cap and sent 9.3 calls on average. A check that runs after each response overshot by $0.0105 on average, almost the whole call that crossed the cap. The cost of the early stop is cap left unspent: $0.054 on average in that run, set by how far `maxOutputTokens` sits above the output the model actually writes. Lower `maxOutputTokens` in `modelOptions` to tighten the projection.
92
+
93
+ The cap counts the calls the run itself makes. A `continueRun()` does not count the cost of the context it starts from.
94
+
95
+ A run with a budget needs a price for every call. If the model's price is unknown, the run ends `error` with `error.kind: "unknown_price"` before its first call, and so does a run whose earlier call came back with an unknown cost. Add the model to a catalog you pass to `createModel()`, or drop the budget.
96
+
97
+ ### The progress policy ends a run that repeats a failing call
98
+
99
+ The policy reads the run's transcript after each step, after your own `shouldStop` hook. It ends the run `no_progress` in two cases:
100
+
101
+ - **Identical failures.** The latest three tool calls name one tool, carry one input, and each returned an error. Inputs compare by `canonicalInputHash()`, so `{a, b}` and `{b, a}` are the same input. A successful call, or a call to another tool, breaks the streak.
102
+ - **One key.** A tool declares `progressKey(input)`, such as a file path plus a line, and five calls to it return that key with no success between them. A success with that key starts the count again, and calls with other keys do not affect it. The inputs may differ, which is how it catches a model that keeps rewording a failing edit. The function receives the input exactly as the model sent it, so it must cope with any shape; a key that throws or isn't a string leaves that call out of the count.
103
+
104
+ Your own `shouldStop` runs first and its stop wins, but neither its `{ continue }` nor a throw under `onFailure: "continue"` can keep a stuck run going. Pass `progress: { maxIdenticalFailures: 2 }` to tighten a threshold, or `progress: false` to turn the policy off. A `continueRun()` counts only the calls it makes, so you can continue a run that ended `no_progress` after you change what the model sees.
105
+
106
+ ### `depth` and `maxDepth` stop a tree of agents
107
+
108
+ Every tool receives `ctx.depth` (0 for a top-level run) and `ctx.maxDepth` (2 by default). A tool that starts its own agent passes the next level down with `nestedRunDepth(ctx)`:
109
+
110
+ ```ts
111
+ async execute(input, ctx) {
112
+ const child = run({ model, system, input: input.task, signal: ctx.signal, budgetUsd: 0.5, ...nestedRunDepth(ctx) });
113
+ return { content: [{ type: "text", text: (await child.result).stopReason }] };
114
+ }
115
+ ```
116
+
117
+ Pass `signal: ctx.signal` so the child stops when the parent's call is aborted. The parent's `budgetUsd` counts only the parent's own model calls, so give each child a budget of its own. A tool running at `depth === maxDepth` that starts a child run this way makes `run()` throw `max_depth_exceeded`. Since the throw happens inside `execute`, the model reads it as an error result and can answer without the sub-agent.
118
+
119
+ ## Steer a running agent with `run.steer()`, or queue a follow-up with `run.followUp()`
120
+
121
+ Both methods queue a user message and return a promise for a `DeliveryReceipt`. The loop applies queued messages only at a step boundary, so a model call or tool batch that is running is never cut. A steer is applied before the run's next model call: a steer sent while a batch of tool calls runs waits for the whole batch, and the model reads it after the tool results.
122
+
123
+ ```ts
124
+ const started = run({ model, system, input, tools });
125
+ const receipt = await started.steer("Use order 2 instead.");
126
+ console.log(receipt.stepIndex); // the step whose model call is the first to read the message
127
+ ```
128
+
129
+ A follow-up waits until the run would otherwise end. When the model answers without a tool call and a message is waiting, the run adds the waiting messages and makes one more model call, so a follow-up sent before the run ends extends it by one step. A waiting steer goes first, and follow-ups wait for the next time the run would end. The extra call counts against `maxSteps`: a run already at the cap ends as it would have.
130
+
131
+ A receipt resolves once its message is in the transcript. It holds an `id` that is unique within the run, the `kind` (`"steer"` or `"follow_up"`), the `message` as content blocks and the `stepIndex`, the step at whose start the run added the message. That step's model call is the first to read it, unless the run ends before the call, which a budget stop or a failed hook can cause. The run also emits one `steer_applied` event for each message, carrying the same receipt. A message is a string that isn't blank, or a non-empty list of text and image blocks whose text isn't blank. The run applies messages in the order they were sent.
132
+
133
+ The promise rejects with an `SdkError` whose code is `undelivered_message` when the run ends before it applies the message. That happens in four cases:
134
+
135
+ - You call after the run has its outcome.
136
+ - An abort, or any stop reason other than a text answer, ends the run.
137
+ - A `shouldStop` hook or the progress policy ends a run that answered in text.
138
+ - The run ends by calling its output tool.
139
+
140
+ The promise rejects with `invalid_run_options` for a blank message or a block that isn't text or an image. A promise you never await is safe to drop: a rejection nobody reads does not raise an unhandled rejection.
141
+
72
142
  ## A run streams one closed set of events
73
143
 
74
144
  Iterating a run yields its events. Each iteration starts from the run's first event, so you can start iterating at any time, even after the run has ended. Every event carries the run's `runId`, a `seq` that counts events from 0, a `stepIndex` that counts model calls from 0, and a `timestamp` from the run's clock.
@@ -80,6 +150,7 @@ The events come in two layers. The delta layer streams each content block by its
80
150
  - **`model_call_start`** carries the request, and **`model_call_end`** the final message.
81
151
  - **`tool_call_start`**, **`tool_call_update`** and **`tool_call_end`** follow each tool call; `tool_call_end.result` is what the model reads. When a `beforeToolCall` gate replaced the model's input, `tool_call_end.input` holds the input the call got instead.
82
152
  - **`context_transformed`** reports the message counts before and after `transformContext` for one model call.
153
+ - **`steer_applied`** reports a queued steer or follow-up that entered the transcript, with its receipt.
83
154
  - **`hook_error`** reports an interceptor or an observer that threw, with the hook's name and the message.
84
155
  - **`retry`** reports a failed request the gateway is retrying, and **`warning`** reports a reached cap or a model warning.
85
156
  - **`error`** and **`abort`** report a failed call and an abort request.
@@ -231,9 +302,11 @@ Every tool gets a `ctx.signal` that fires when the run is aborted. It also fires
231
302
 
232
303
  The SDK throws only for programmer errors, never for a failure the model caused. `isSdkError(error)` recognises the error, and its `code` says why:
233
304
 
234
- - **`invalid_tool_definition`**: a tool's name, description, schema, exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name.
305
+ - **`invalid_tool_definition`**: a tool's name, description, schema, exposure, `executionMode`, `resourceKey` or `progressKey` is unusable, or two tools share a name.
235
306
  - **`invalid_tool_result`**: `execute` returned something other than a tool result, or an invalid outcome. A text block needs a string `text`, and an image block a string `mediaType` and `data`. The run's `result` rejects with this error, and iterating the run throws it after the last event.
236
- - **`invalid_run_options`**: `run()` or `continueRun()` got a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, or an output tool whose `exposure` isn't `"direct"`.
307
+ - **`invalid_run_options`**: `run()` or `continueRun()` got a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool whose `exposure` isn't `"direct"`, a `budgetUsd` that isn't a non-negative number, a `progress` threshold that isn't a positive integer, or a `depth` or `maxDepth` that isn't a whole number.
308
+ - **`max_depth_exceeded`**: a tool started a run nested deeper than `maxDepth` allows.
309
+ - **`undelivered_message`**: `steer()` or `followUp()` rejects with it when the run ended before it could apply the message.
237
310
  - **`invalid_model_stream`**: a model's stream ended without a final message, which only a broken adapter does.
238
311
  Hooks add two `SdkError` codes:
239
312
 
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The USD budget (D9): the loop projects each call's cost before it sends the call, and ends the run `budget` when
3
+ * the spend so far plus that projection would pass the cap. The projection is the gateway's `projectCallCost()`, the
4
+ * same formula a caller uses outside the loop, so the loop's check and a caller's agree.
5
+ */
6
+ import { type Cost, type Model } from "@buildanagent/gateway";
7
+ import type { RunError } from "./result.js";
8
+ /** What a budget check decides before one call. */
9
+ export type BudgetVerdict = {
10
+ readonly kind: "allow";
11
+ } | {
12
+ readonly kind: "exceeded";
13
+ readonly reason: string;
14
+ readonly spentUsd: number;
15
+ readonly projectedUsd: number;
16
+ } | {
17
+ readonly kind: "unknown";
18
+ readonly error: RunError;
19
+ };
20
+ /** Checks the `budgetUsd` option: a finite number of dollars that isn't negative. */
21
+ export declare function checkBudgetOption(budgetUsd: unknown): number | undefined;
22
+ /**
23
+ * The refusal a budgeted run starts with when its model has no price, or `undefined` when the price is known. A
24
+ * budget can't be enforced against a price that is not there, and pricing the calls at zero would let the run spend
25
+ * without bound (D4).
26
+ */
27
+ export declare function unknownPriceError(model: Model): RunError | undefined;
28
+ /**
29
+ * Decides whether the next call may go out. `spent` is what the run's earlier calls cost, and `projected` is what
30
+ * `projectCallCost()` says the next call can cost at most. A cost that is unknown ends the run with `unknown_price`
31
+ * and never counts as zero.
32
+ */
33
+ export declare function checkBudget(budgetUsd: number, spent: Cost | undefined, projected: Cost): BudgetVerdict;
package/dist/budget.js ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The USD budget (D9): the loop projects each call's cost before it sends the call, and ends the run `budget` when
3
+ * the spend so far plus that projection would pass the cap. The projection is the gateway's `projectCallCost()`, the
4
+ * same formula a caller uses outside the loop, so the loop's check and a caller's agree.
5
+ */
6
+ import { emptyUsage } from "@buildanagent/gateway";
7
+ import { SdkError } from "./errors.js";
8
+ /** Checks the `budgetUsd` option: a finite number of dollars that isn't negative. */
9
+ export function checkBudgetOption(budgetUsd) {
10
+ if (budgetUsd === undefined)
11
+ return undefined;
12
+ if (typeof budgetUsd !== "number" || !Number.isFinite(budgetUsd) || budgetUsd < 0) {
13
+ throw new SdkError("invalid_run_options", `budgetUsd must be a finite number of dollars, 0 or more, got ${String(budgetUsd)}`);
14
+ }
15
+ return budgetUsd;
16
+ }
17
+ /**
18
+ * The refusal a budgeted run starts with when its model has no price, or `undefined` when the price is known. A
19
+ * budget can't be enforced against a price that is not there, and pricing the calls at zero would let the run spend
20
+ * without bound (D4).
21
+ */
22
+ export function unknownPriceError(model) {
23
+ const probe = model.price({ ...emptyUsage(), uncachedInput: 1 });
24
+ if (probe.total !== null)
25
+ return undefined;
26
+ const { provider, id } = model.ref;
27
+ return {
28
+ kind: "unknown_price",
29
+ message: `the price of ${provider}/${id} is unknown, so a run with a budgetUsd can't check its spend; add the model to a catalog or drop the budget`,
30
+ };
31
+ }
32
+ function unknownCost(what) {
33
+ return { kind: "unknown_price", message: `${what} unknown, so the budget can't be checked` };
34
+ }
35
+ /**
36
+ * Decides whether the next call may go out. `spent` is what the run's earlier calls cost, and `projected` is what
37
+ * `projectCallCost()` says the next call can cost at most. A cost that is unknown ends the run with `unknown_price`
38
+ * and never counts as zero.
39
+ */
40
+ export function checkBudget(budgetUsd, spent, projected) {
41
+ if (spent?.total === null)
42
+ return { kind: "unknown", error: unknownCost("an earlier call's cost is") };
43
+ if (projected.total === null)
44
+ return { kind: "unknown", error: unknownCost("the next call's projected cost is") };
45
+ const spentUsd = spent?.total ?? 0;
46
+ if (spentUsd + projected.total <= budgetUsd)
47
+ return { kind: "allow" };
48
+ const reason = `the run has spent ${dollars(spentUsd)} and the next call can cost up to ${dollars(projected.total)}, which passes the budget of ${dollars(budgetUsd)}`;
49
+ return { kind: "exceeded", reason, spentUsd, projectedUsd: projected.total };
50
+ }
51
+ /** A dollar amount for a message, to six significant digits, so a float sum doesn't print as $0.054000000000000006. */
52
+ function dollars(usd) {
53
+ return `$${Number(usd.toPrecision(6))}`;
54
+ }
55
+ //# sourceMappingURL=budget.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budget.js","sourceRoot":"","sources":["../src/budget.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAa,UAAU,EAAc,MAAM,uBAAuB,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AASvC,qFAAqF;AACrF,MAAM,UAAU,iBAAiB,CAAC,SAAkB;IAClD,IAAI,SAAS,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC9C,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,SAAS,GAAG,CAAC,EAAE,CAAC;QAClF,MAAM,IAAI,QAAQ,CAChB,qBAAqB,EACrB,gEAAgE,MAAM,CAAC,SAAS,CAAC,EAAE,CACpF,CAAC;IACJ,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAY;IAC5C,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,GAAG,UAAU,EAAE,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC,CAAC;IACjE,IAAI,KAAK,CAAC,KAAK,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IAC3C,MAAM,EAAE,QAAQ,EAAE,EAAE,EAAE,GAAG,KAAK,CAAC,GAAG,CAAC;IACnC,OAAO;QACL,IAAI,EAAE,eAAe;QACrB,OAAO,EAAE,gBAAgB,QAAQ,IAAI,EAAE,6GAA6G;KACrJ,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,IAAY;IAC/B,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,GAAG,IAAI,0CAA0C,EAAE,CAAC;AAC/F,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,SAAiB,EAAE,KAAuB,EAAE,SAAe;IACrF,IAAI,KAAK,EAAE,KAAK,KAAK,IAAI;QAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,WAAW,CAAC,2BAA2B,CAAC,EAAE,CAAC;IACvG,IAAI,SAAS,CAAC,KAAK,KAAK,IAAI;QAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,WAAW,CAAC,mCAAmC,CAAC,EAAE,CAAC;IAClH,MAAM,QAAQ,GAAG,KAAK,EAAE,KAAK,IAAI,CAAC,CAAC;IACnC,IAAI,QAAQ,GAAG,SAAS,CAAC,KAAK,IAAI,SAAS;QAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IACtE,MAAM,MAAM,GAAG,qBAAqB,OAAO,CAAC,QAAQ,CAAC,qCAAqC,OAAO,CAAC,SAAS,CAAC,KAAK,CAAC,gCAAgC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;IACvK,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,SAAS,CAAC,KAAK,EAAE,CAAC;AAC/E,CAAC;AAED,uHAAuH;AACvH,SAAS,OAAO,CAAC,GAAW;IAC1B,OAAO,IAAI,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["/**\n * The USD budget (D9): the loop projects each call's cost before it sends the call, and ends the run `budget` when\n * the spend so far plus that projection would pass the cap. The projection is the gateway's `projectCallCost()`, the\n * same formula a caller uses outside the loop, so the loop's check and a caller's agree.\n */\nimport { type Cost, emptyUsage, type Model } from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\nimport type { RunError } from \"./result.js\";\n\n/** What a budget check decides before one call. */\nexport type BudgetVerdict =\n | { readonly kind: \"allow\" }\n | { readonly kind: \"exceeded\"; readonly reason: string; readonly spentUsd: number; readonly projectedUsd: number }\n | { readonly kind: \"unknown\"; readonly error: RunError };\n\n/** Checks the `budgetUsd` option: a finite number of dollars that isn't negative. */\nexport function checkBudgetOption(budgetUsd: unknown): number | undefined {\n if (budgetUsd === undefined) return undefined;\n if (typeof budgetUsd !== \"number\" || !Number.isFinite(budgetUsd) || budgetUsd < 0) {\n throw new SdkError(\n \"invalid_run_options\",\n `budgetUsd must be a finite number of dollars, 0 or more, got ${String(budgetUsd)}`,\n );\n }\n return budgetUsd;\n}\n\n/**\n * The refusal a budgeted run starts with when its model has no price, or `undefined` when the price is known. A\n * budget can't be enforced against a price that is not there, and pricing the calls at zero would let the run spend\n * without bound (D4).\n */\nexport function unknownPriceError(model: Model): RunError | undefined {\n const probe = model.price({ ...emptyUsage(), uncachedInput: 1 });\n if (probe.total !== null) return undefined;\n const { provider, id } = model.ref;\n return {\n kind: \"unknown_price\",\n message: `the price of ${provider}/${id} is unknown, so a run with a budgetUsd can't check its spend; add the model to a catalog or drop the budget`,\n };\n}\n\nfunction unknownCost(what: string): RunError {\n return { kind: \"unknown_price\", message: `${what} unknown, so the budget can't be checked` };\n}\n\n/**\n * Decides whether the next call may go out. `spent` is what the run's earlier calls cost, and `projected` is what\n * `projectCallCost()` says the next call can cost at most. A cost that is unknown ends the run with `unknown_price`\n * and never counts as zero.\n */\nexport function checkBudget(budgetUsd: number, spent: Cost | undefined, projected: Cost): BudgetVerdict {\n if (spent?.total === null) return { kind: \"unknown\", error: unknownCost(\"an earlier call's cost is\") };\n if (projected.total === null) return { kind: \"unknown\", error: unknownCost(\"the next call's projected cost is\") };\n const spentUsd = spent?.total ?? 0;\n if (spentUsd + projected.total <= budgetUsd) return { kind: \"allow\" };\n const reason = `the run has spent ${dollars(spentUsd)} and the next call can cost up to ${dollars(projected.total)}, which passes the budget of ${dollars(budgetUsd)}`;\n return { kind: \"exceeded\", reason, spentUsd, projectedUsd: projected.total };\n}\n\n/** A dollar amount for a message, to six significant digits, so a float sum doesn't print as $0.054000000000000006. */\nfunction dollars(usd: number): string {\n return `$${Number(usd.toPrecision(6))}`;\n}\n"]}
package/dist/errors.d.ts CHANGED
@@ -7,17 +7,20 @@
7
7
  */
8
8
  import type { Context, UnfinishedResult } from "./result.js";
9
9
  /** Why an `SdkError` was thrown. */
10
- export type SdkErrorCode = "invalid_tool_definition" | "invalid_tool_result" | "invalid_run_options" | "invalid_model_stream" | "invalid_hook_result" | "hook_failed" | "run_stopped" | "unexpected_model_call";
10
+ export type SdkErrorCode = "invalid_tool_definition" | "invalid_tool_result" | "invalid_run_options" | "invalid_model_stream" | "max_depth_exceeded" | "invalid_hook_result" | "hook_failed" | "run_stopped" | "undelivered_message" | "unexpected_model_call";
11
11
  /**
12
12
  * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema,
13
13
  * exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name. `invalid_tool_result`: a tool's
14
14
  * `execute` returned a malformed result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an
15
15
  * option it can't use, such as a model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended
16
- * without a final message. `invalid_hook_result`: an interceptor returned something its type does not allow, such as
16
+ * without a final message. `max_depth_exceeded`: a tool started a run nested deeper than `maxDepth` allows.
17
+ * `invalid_hook_result`: an interceptor returned something its type does not allow, such as
17
18
  * a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor
18
19
  * threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,
19
20
  * so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a
20
21
  * `RunStoppedError`).
22
+ * `undelivered_message`: `steer()` or `followUp()` was called on a run that had ended, or the run ended before it
23
+ * could apply the message.
21
24
  * `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
22
25
  * `UnexpectedModelCallError`).
23
26
  */
package/dist/errors.js CHANGED
@@ -5,11 +5,14 @@ const SDK_ERROR = Symbol.for("buildanagent.sdk.SdkError");
5
5
  * exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name. `invalid_tool_result`: a tool's
6
6
  * `execute` returned a malformed result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an
7
7
  * option it can't use, such as a model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended
8
- * without a final message. `invalid_hook_result`: an interceptor returned something its type does not allow, such as
8
+ * without a final message. `max_depth_exceeded`: a tool started a run nested deeper than `maxDepth` allows.
9
+ * `invalid_hook_result`: an interceptor returned something its type does not allow, such as
9
10
  * a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor
10
11
  * threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,
11
12
  * so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a
12
13
  * `RunStoppedError`).
14
+ * `undelivered_message`: `steer()` or `followUp()` was called on a run that had ended, or the run ended before it
15
+ * could apply the message.
13
16
  * `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
14
17
  * `UnexpectedModelCallError`).
15
18
  */
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAoBA,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACf,IAAI,GAAW,UAAU,CAAC;IACnC,IAAI,CAAe;IAE5B,YAAY,IAAkB,EAAE,OAAe,EAAE,OAAsB;QACrE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1D,CAAC;CACF;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;AAC/G,CAAC;AAED,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;AAEzE;;;GAGG;AACH,MAAM,OAAO,eAAgB,SAAQ,QAAQ;IACzB,IAAI,GAAG,iBAAiB,CAAC;IAClC,UAAU,CAAiC;IAC3C,MAAM,CAAmB;IAClC,0DAA0D;IACjD,OAAO,CAAU;IAE1B,YAAY,MAAwB;QAClC,KAAK,CAAC,aAAa,EAAE,yBAAyB,MAAM,CAAC,UAAU,WAAW,MAAM,CAAC,KAAK,cAAc,CAAC,CAAC;QACtG,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;QACpC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;QAC9B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,iBAAiB,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAClE,CAAC;IAED,qHAAqH;IACrH,MAAM,CAAC,UAAU,CAAC,KAAc;QAC9B,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,iBAAiB,CAAC,KAAK,IAAI,CAC9G,CAAC;IACJ,CAAC;CACF","sourcesContent":["/**\n * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool\n * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never\n * thrown: the tool pipeline returns it to the model as an error result. Two subclasses keep their own names:\n * `RunStoppedError`, which `runOrThrow()` throws for a run that did not finish, and the testing export's\n * `UnexpectedModelCallError`.\n */\nimport type { Context, UnfinishedResult } from \"./result.js\";\n\n/** Why an `SdkError` was thrown. */\nexport type SdkErrorCode =\n | \"invalid_tool_definition\"\n | \"invalid_tool_result\"\n | \"invalid_run_options\"\n | \"invalid_model_stream\"\n | \"invalid_hook_result\"\n | \"hook_failed\"\n | \"run_stopped\"\n | \"unexpected_model_call\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SDK_ERROR = Symbol.for(\"buildanagent.sdk.SdkError\");\n\n/**\n * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema,\n * exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name. `invalid_tool_result`: a tool's\n * `execute` returned a malformed result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an\n * option it can't use, such as a model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended\n * without a final message. `invalid_hook_result`: an interceptor returned something its type does not allow, such as\n * a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor\n * threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,\n * so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a\n * `RunStoppedError`).\n * `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an\n * `UnexpectedModelCallError`).\n */\nexport class SdkError extends Error {\n override readonly name: string = \"SdkError\";\n readonly code: SdkErrorCode;\n\n constructor(code: SdkErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SDK_ERROR, { value: true });\n }\n}\n\n/** True for an `SdkError`, including one from another copy of the package. */\nexport function isSdkError(error: unknown): error is SdkError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SDK_ERROR] === true;\n}\n\nconst RUN_STOPPED_ERROR = Symbol.for(\"buildanagent.sdk.RunStoppedError\");\n\n/**\n * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It\n * carries the whole result, and the context to continue from. It is an `SdkError` with code `run_stopped`.\n */\nexport class RunStoppedError extends SdkError {\n override readonly name = \"RunStoppedError\";\n readonly stopReason: UnfinishedResult[\"stopReason\"];\n readonly result: UnfinishedResult;\n /** The conversation so far, ready for `continueRun()`. */\n readonly context: Context;\n\n constructor(result: UnfinishedResult) {\n super(\"run_stopped\", `the run stopped with \"${result.stopReason}\" after ${result.steps} model calls`);\n this.stopReason = result.stopReason;\n this.result = result;\n this.context = result.context;\n Object.defineProperty(this, RUN_STOPPED_ERROR, { value: true });\n }\n\n /** True for a `RunStoppedError`, including one from another copy of the package. Use it in place of `instanceof`. */\n static isInstance(error: unknown): error is RunStoppedError {\n return (\n typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[RUN_STOPPED_ERROR] === true\n );\n }\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAsBA,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACf,IAAI,GAAW,UAAU,CAAC;IACnC,IAAI,CAAe;IAE5B,YAAY,IAAkB,EAAE,OAAe,EAAE,OAAsB;QACrE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1D,CAAC;CACF;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;AAC/G,CAAC;AAED,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;AAEzE;;;GAGG;AACH,MAAM,OAAO,eAAgB,SAAQ,QAAQ;IACzB,IAAI,GAAG,iBAAiB,CAAC;IAClC,UAAU,CAAiC;IAC3C,MAAM,CAAmB;IAClC,0DAA0D;IACjD,OAAO,CAAU;IAE1B,YAAY,MAAwB;QAClC,KAAK,CAAC,aAAa,EAAE,yBAAyB,MAAM,CAAC,UAAU,WAAW,MAAM,CAAC,KAAK,cAAc,CAAC,CAAC;QACtG,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;QACpC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;QAC9B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,iBAAiB,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAClE,CAAC;IAED,qHAAqH;IACrH,MAAM,CAAC,UAAU,CAAC,KAAc;QAC9B,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,iBAAiB,CAAC,KAAK,IAAI,CAC9G,CAAC;IACJ,CAAC;CACF","sourcesContent":["/**\n * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool\n * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never\n * thrown: the tool pipeline returns it to the model as an error result. Two subclasses keep their own names:\n * `RunStoppedError`, which `runOrThrow()` throws for a run that did not finish, and the testing export's\n * `UnexpectedModelCallError`.\n */\nimport type { Context, UnfinishedResult } from \"./result.js\";\n\n/** Why an `SdkError` was thrown. */\nexport type SdkErrorCode =\n | \"invalid_tool_definition\"\n | \"invalid_tool_result\"\n | \"invalid_run_options\"\n | \"invalid_model_stream\"\n | \"max_depth_exceeded\"\n | \"invalid_hook_result\"\n | \"hook_failed\"\n | \"run_stopped\"\n | \"undelivered_message\"\n | \"unexpected_model_call\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SDK_ERROR = Symbol.for(\"buildanagent.sdk.SdkError\");\n\n/**\n * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema,\n * exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name. `invalid_tool_result`: a tool's\n * `execute` returned a malformed result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an\n * option it can't use, such as a model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended\n * without a final message. `max_depth_exceeded`: a tool started a run nested deeper than `maxDepth` allows.\n * `invalid_hook_result`: an interceptor returned something its type does not allow, such as\n * a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor\n * threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,\n * so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a\n * `RunStoppedError`).\n * `undelivered_message`: `steer()` or `followUp()` was called on a run that had ended, or the run ended before it\n * could apply the message.\n * `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an\n * `UnexpectedModelCallError`).\n */\nexport class SdkError extends Error {\n override readonly name: string = \"SdkError\";\n readonly code: SdkErrorCode;\n\n constructor(code: SdkErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SDK_ERROR, { value: true });\n }\n}\n\n/** True for an `SdkError`, including one from another copy of the package. */\nexport function isSdkError(error: unknown): error is SdkError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SDK_ERROR] === true;\n}\n\nconst RUN_STOPPED_ERROR = Symbol.for(\"buildanagent.sdk.RunStoppedError\");\n\n/**\n * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It\n * carries the whole result, and the context to continue from. It is an `SdkError` with code `run_stopped`.\n */\nexport class RunStoppedError extends SdkError {\n override readonly name = \"RunStoppedError\";\n readonly stopReason: UnfinishedResult[\"stopReason\"];\n readonly result: UnfinishedResult;\n /** The conversation so far, ready for `continueRun()`. */\n readonly context: Context;\n\n constructor(result: UnfinishedResult) {\n super(\"run_stopped\", `the run stopped with \"${result.stopReason}\" after ${result.steps} model calls`);\n this.stopReason = result.stopReason;\n this.result = result;\n this.context = result.context;\n Object.defineProperty(this, RUN_STOPPED_ERROR, { value: true });\n }\n\n /** True for a `RunStoppedError`, including one from another copy of the package. Use it in place of `instanceof`. */\n static isInstance(error: unknown): error is RunStoppedError {\n return (\n typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[RUN_STOPPED_ERROR] === true\n );\n }\n}\n"]}
package/dist/events.d.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from "@buildanagent/gateway";
8
8
  import type { RunError, RunResult } from "./result.js";
9
+ import type { DeliveryReceipt } from "./steering.js";
9
10
  import type { ToolResult } from "./tools/types.js";
10
11
  /** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */
11
12
  export interface EventBase {
@@ -98,6 +99,14 @@ export type AgentEventBody = {
98
99
  readonly delayMs: number;
99
100
  readonly error: string;
100
101
  }
102
+ /**
103
+ * A queued steer or follow-up entered the transcript as a user message, at the start of the step named by
104
+ * `receipt.stepIndex`, before its model call. `receipt.kind` tells the two apart.
105
+ */
106
+ | {
107
+ readonly type: "steer_applied";
108
+ readonly receipt: DeliveryReceipt;
109
+ }
101
110
  /**
102
111
  * An interceptor or an observer threw. `hook` names it (`beforeToolCall`, `observer` and so on) and `error` is the
103
112
  * thrown message. The run goes on or fails by the interceptors' `onFailure` setting; a failed observer never
@@ -121,4 +130,4 @@ export type AgentEventBody = {
121
130
  /** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */
122
131
  export type AgentEvent = EventBase & AgentEventBody;
123
132
  /** Every `AgentEvent` type. A run emits no type this list lacks. */
124
- export declare const AGENT_EVENT_TYPES: readonly ["run_start", "step_start", "model_call_start", "retry", "text_start", "text_delta", "text_end", "reasoning_start", "reasoning_delta", "reasoning_end", "tool_input_start", "tool_input_delta", "tool_input_end", "warning", "model_call_end", "context_transformed", "hook_error", "tool_call_start", "tool_call_update", "tool_call_end", "step_end", "error", "abort", "agent_settled", "run_end"];
133
+ export declare const AGENT_EVENT_TYPES: readonly ["run_start", "step_start", "model_call_start", "retry", "text_start", "text_delta", "text_end", "reasoning_start", "reasoning_delta", "reasoning_end", "tool_input_start", "tool_input_delta", "tool_input_end", "warning", "model_call_end", "context_transformed", "hook_error", "steer_applied", "tool_call_start", "tool_call_update", "tool_call_end", "step_end", "error", "abort", "agent_settled", "run_end"];
package/dist/events.js CHANGED
@@ -17,6 +17,7 @@ export const AGENT_EVENT_TYPES = Object.freeze([
17
17
  "model_call_end",
18
18
  "context_transformed",
19
19
  "hook_error",
20
+ "steer_applied",
20
21
  "tool_call_start",
21
22
  "tool_call_update",
22
23
  "tool_call_end",
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AA2FA,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,iBAAiB;IACjB,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 { ToolResult } from \"./tools/types.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/** 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 * An interceptor or an observer threw. `hook` names it (`beforeToolCall`, `observer` and so on) and `error` is the\n * thrown message. The run goes on or fails by the interceptors' `onFailure` setting; a failed observer never\n * affects it.\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 \"tool_call_start\",\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":"AAiGA,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,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\";\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/** 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 * An interceptor or an observer threw. `hook` names it (`beforeToolCall`, `observer` and so on) and `error` is the\n * thrown message. The run goes on or fails by the interceptors' `onFailure` setting; a failed observer never\n * affects it.\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 \"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/index.d.ts CHANGED
@@ -1,15 +1,20 @@
1
1
  /**
2
2
  * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,
3
3
  * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
4
- * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. Signed pauses and
5
- * budgets are planned in the SDK plan §3.3.
4
+ * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
5
+ * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can
6
+ * steer a running agent or queue a follow-up, both applied at step boundaries. Signed pauses are planned in the SDK
7
+ * plan §3.3.
6
8
  */
9
+ export { projectCallCost } from "@buildanagent/gateway";
7
10
  export { composeInterceptors } from "./compose.js";
8
11
  export { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from "./errors.js";
9
12
  export { AGENT_EVENT_TYPES, type AgentEvent, type AgentEventBody, type EventBase, type ModelCallRequest, type WarningCode, } from "./events.js";
10
13
  export type { CallOptions, ContextEvent, GateDecision, HookEventBase, Interceptors, MaybePromise, ModelCallEvent, ModelCallPatch, ModelResultEvent, Observer, OrNothing, StepEvent, StopDecision, ToolCallEvent, ToolResultEvent, ToolResultPatch, } from "./hooks.js";
11
- export type { Context, DoneResult, EndedResult, ErrorResult, NoProgressResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
12
- export { continueRun, type Run, type RunInput, type RunOptions, run, runOrThrow } from "./run.js";
14
+ export { DEFAULT_PROGRESS, type ProgressPolicy } from "./progress.js";
15
+ export type { BudgetResult, Context, DoneResult, EndedResult, ErrorResult, NoProgressResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
16
+ export { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from "./run.js";
17
+ export type { DeliveryKind, DeliveryReceipt } from "./steering.js";
13
18
  export { type ClarificationToolOptions, clarificationTool, defineTool, type OutputToolOptions, outputTool, } from "./tools/define.js";
14
19
  export type { JsonSchema, SchemaIssue, ToolAnnotations, ToolContext, ToolDefinition, ToolEffect, ToolExecutionMode, ToolExposure, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
15
20
  export type { WriteOutcome } from "./vendor/agent-safety/outcome.js";
package/dist/index.js CHANGED
@@ -1,13 +1,18 @@
1
1
  /**
2
2
  * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,
3
3
  * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
4
- * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. Signed pauses and
5
- * budgets are planned in the SDK plan §3.3.
4
+ * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
5
+ * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can
6
+ * steer a running agent or queue a follow-up, both applied at step boundaries. Signed pauses are planned in the SDK
7
+ * plan §3.3.
6
8
  */
9
+ // Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.
10
+ export { projectCallCost } from "@buildanagent/gateway";
7
11
  export { composeInterceptors } from "./compose.js";
8
12
  export { isSdkError, RunStoppedError, SdkError } from "./errors.js";
9
13
  export { AGENT_EVENT_TYPES, } from "./events.js";
10
- export { continueRun, run, runOrThrow } from "./run.js";
14
+ export { DEFAULT_PROGRESS } from "./progress.js";
15
+ export { continueRun, nestedRunDepth, run, runOrThrow } from "./run.js";
11
16
  export { clarificationTool, defineTool, outputTool, } from "./tools/define.js";
12
17
  /** The package's name, `@buildanagent/sdk`. */
13
18
  export const SDK_PACKAGE = "@buildanagent/sdk";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AACvF,OAAO,EACL,iBAAiB,GAMlB,MAAM,aAAa,CAAC;AA+BrB,OAAO,EAAE,WAAW,EAA4C,GAAG,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAClG,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,UAAU,GACX,MAAM,mBAAmB,CAAC;AAgB3B,+CAA+C;AAC/C,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,\n * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write\n * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. Signed pauses and\n * budgets are planned in the SDK plan §3.3.\n */\nexport { composeInterceptors } from \"./compose.js\";\nexport { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from \"./errors.js\";\nexport {\n AGENT_EVENT_TYPES,\n type AgentEvent,\n type AgentEventBody,\n type EventBase,\n type ModelCallRequest,\n type WarningCode,\n} from \"./events.js\";\nexport type {\n CallOptions,\n ContextEvent,\n GateDecision,\n HookEventBase,\n Interceptors,\n MaybePromise,\n ModelCallEvent,\n ModelCallPatch,\n ModelResultEvent,\n Observer,\n OrNothing,\n StepEvent,\n StopDecision,\n ToolCallEvent,\n ToolResultEvent,\n ToolResultPatch,\n} from \"./hooks.js\";\nexport type {\n Context,\n DoneResult,\n EndedResult,\n ErrorResult,\n NoProgressResult,\n ResultBase,\n RunError,\n RunResult,\n StoppedResult,\n UnfinishedResult,\n} from \"./result.js\";\nexport { continueRun, type Run, type RunInput, type RunOptions, run, runOrThrow } from \"./run.js\";\nexport {\n type ClarificationToolOptions,\n clarificationTool,\n defineTool,\n type OutputToolOptions,\n outputTool,\n} from \"./tools/define.js\";\nexport type {\n JsonSchema,\n SchemaIssue,\n ToolAnnotations,\n ToolContext,\n ToolDefinition,\n ToolEffect,\n ToolExecutionMode,\n ToolExposure,\n ToolFailure,\n ToolResult,\n ToolSchema,\n} from \"./tools/types.js\";\nexport type { WriteOutcome } from \"./vendor/agent-safety/outcome.js\";\n\n/** The package's name, `@buildanagent/sdk`. */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,sHAAsH;AACtH,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AACvF,OAAO,EACL,iBAAiB,GAMlB,MAAM,aAAa,CAAC;AAmBrB,OAAO,EAAE,gBAAgB,EAAuB,MAAM,eAAe,CAAC;AActE,OAAO,EAAE,WAAW,EAAE,cAAc,EAA4C,GAAG,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAElH,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,UAAU,GACX,MAAM,mBAAmB,CAAC;AAgB3B,+CAA+C;AAC/C,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,\n * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write\n * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also\n * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can\n * steer a running agent or queue a follow-up, both applied at step boundaries. Signed pauses are planned in the SDK\n * plan §3.3.\n */\n// Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.\nexport { projectCallCost } from \"@buildanagent/gateway\";\nexport { composeInterceptors } from \"./compose.js\";\nexport { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from \"./errors.js\";\nexport {\n AGENT_EVENT_TYPES,\n type AgentEvent,\n type AgentEventBody,\n type EventBase,\n type ModelCallRequest,\n type WarningCode,\n} from \"./events.js\";\nexport type {\n CallOptions,\n ContextEvent,\n GateDecision,\n HookEventBase,\n Interceptors,\n MaybePromise,\n ModelCallEvent,\n ModelCallPatch,\n ModelResultEvent,\n Observer,\n OrNothing,\n StepEvent,\n StopDecision,\n ToolCallEvent,\n ToolResultEvent,\n ToolResultPatch,\n} from \"./hooks.js\";\nexport { DEFAULT_PROGRESS, type ProgressPolicy } from \"./progress.js\";\nexport type {\n BudgetResult,\n Context,\n DoneResult,\n EndedResult,\n ErrorResult,\n NoProgressResult,\n ResultBase,\n RunError,\n RunResult,\n StoppedResult,\n UnfinishedResult,\n} from \"./result.js\";\nexport { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from \"./run.js\";\nexport type { DeliveryKind, DeliveryReceipt } from \"./steering.js\";\nexport {\n type ClarificationToolOptions,\n clarificationTool,\n defineTool,\n type OutputToolOptions,\n outputTool,\n} from \"./tools/define.js\";\nexport type {\n JsonSchema,\n SchemaIssue,\n ToolAnnotations,\n ToolContext,\n ToolDefinition,\n ToolEffect,\n ToolExecutionMode,\n ToolExposure,\n ToolFailure,\n ToolResult,\n ToolSchema,\n} from \"./tools/types.js\";\nexport type { WriteOutcome } from \"./vendor/agent-safety/outcome.js\";\n\n/** The package's name, `@buildanagent/sdk`. */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
package/dist/loop.d.ts CHANGED
@@ -10,7 +10,9 @@
10
10
  import { type Message, type Model } from "@buildanagent/gateway";
11
11
  import type { AgentEventBody } from "./events.js";
12
12
  import type { CallOptions, Interceptors } from "./hooks.js";
13
+ import type { ProgressCheck } from "./progress.js";
13
14
  import type { RunResult } from "./result.js";
15
+ import type { SteeringQueue } from "./steering.js";
14
16
  import type { Clock } from "./testing/determinism.js";
15
17
  import { type AnyTool } from "./tools/pipeline.js";
16
18
  /** Everything one run needs, fixed when it starts. */
@@ -29,8 +31,17 @@ export interface LoopSetup {
29
31
  readonly tools: readonly AnyTool[];
30
32
  readonly output: AnyTool | undefined;
31
33
  readonly maxSteps: number;
34
+ /** The most the run's model calls may cost, in USD, or `undefined` for no cap (D9). */
35
+ readonly budgetUsd?: number;
36
+ /** How deeply this run is nested inside other agents' tool calls, and the deepest nesting allowed (D11). */
37
+ readonly depth: number;
38
+ readonly maxDepth: number;
32
39
  readonly modelOptions: CallOptions;
33
40
  readonly interceptors: Interceptors;
41
+ /** The default progress policy, run after the caller's `shouldStop`, or `undefined` when it is off (D11). */
42
+ readonly progress?: ProgressCheck;
43
+ /** The messages a caller queued with `steer()` and `followUp()`, applied only at step boundaries. */
44
+ readonly steering: SteeringQueue;
34
45
  readonly signal: AbortSignal;
35
46
  readonly clock: Clock;
36
47
  }