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

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,52 @@ 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
+
72
119
  ## A run streams one closed set of events
73
120
 
74
121
  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.
@@ -231,9 +278,10 @@ Every tool gets a `ctx.signal` that fires when the run is aborted. It also fires
231
278
 
232
279
  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
280
 
234
- - **`invalid_tool_definition`**: a tool's name, description, schema, exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name.
281
+ - **`invalid_tool_definition`**: a tool's name, description, schema, exposure, `executionMode`, `resourceKey` or `progressKey` is unusable, or two tools share a name.
235
282
  - **`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"`.
283
+ - **`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.
284
+ - **`max_depth_exceeded`**: a tool started a run nested deeper than `maxDepth` allows.
237
285
  - **`invalid_model_stream`**: a model's stream ended without a final message, which only a broken adapter does.
238
286
  Hooks add two `SdkError` codes:
239
287
 
@@ -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,13 +7,14 @@
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" | "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
package/dist/errors.js CHANGED
@@ -5,7 +5,8 @@ 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
@@ -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":"AAqBA,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D;;;;;;;;;;;;;GAaG;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 | \"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 * `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/index.d.ts CHANGED
@@ -1,15 +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. Signed pauses are
6
+ * planned in the SDK plan §3.3.
6
7
  */
8
+ export { projectCallCost } from "@buildanagent/gateway";
7
9
  export { composeInterceptors } from "./compose.js";
8
10
  export { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from "./errors.js";
9
11
  export { AGENT_EVENT_TYPES, type AgentEvent, type AgentEventBody, type EventBase, type ModelCallRequest, type WarningCode, } from "./events.js";
10
12
  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";
13
+ export { DEFAULT_PROGRESS, type ProgressPolicy } from "./progress.js";
14
+ export type { BudgetResult, Context, DoneResult, EndedResult, ErrorResult, NoProgressResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
15
+ export { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from "./run.js";
13
16
  export { type ClarificationToolOptions, clarificationTool, defineTool, type OutputToolOptions, outputTool, } from "./tools/define.js";
14
17
  export type { JsonSchema, SchemaIssue, ToolAnnotations, ToolContext, ToolDefinition, ToolEffect, ToolExecutionMode, ToolExposure, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
15
18
  export type { WriteOutcome } from "./vendor/agent-safety/outcome.js";
package/dist/index.js CHANGED
@@ -1,13 +1,17 @@
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. Signed pauses are
6
+ * planned in the SDK plan §3.3.
6
7
  */
8
+ // Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.
9
+ export { projectCallCost } from "@buildanagent/gateway";
7
10
  export { composeInterceptors } from "./compose.js";
8
11
  export { isSdkError, RunStoppedError, SdkError } from "./errors.js";
9
12
  export { AGENT_EVENT_TYPES, } from "./events.js";
10
- export { continueRun, run, runOrThrow } from "./run.js";
13
+ export { DEFAULT_PROGRESS } from "./progress.js";
14
+ export { continueRun, nestedRunDepth, run, runOrThrow } from "./run.js";
11
15
  export { clarificationTool, defineTool, outputTool, } from "./tools/define.js";
12
16
  /** The package's name, `@buildanagent/sdk`. */
13
17
  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;;;;;;GAMG;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;AAClH,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. Signed pauses are\n * planned in the SDK 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 {\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,6 +10,7 @@
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";
14
15
  import type { Clock } from "./testing/determinism.js";
15
16
  import { type AnyTool } from "./tools/pipeline.js";
@@ -29,8 +30,15 @@ export interface LoopSetup {
29
30
  readonly tools: readonly AnyTool[];
30
31
  readonly output: AnyTool | undefined;
31
32
  readonly maxSteps: number;
33
+ /** The most the run's model calls may cost, in USD, or `undefined` for no cap (D9). */
34
+ readonly budgetUsd?: number;
35
+ /** How deeply this run is nested inside other agents' tool calls, and the deepest nesting allowed (D11). */
36
+ readonly depth: number;
37
+ readonly maxDepth: number;
32
38
  readonly modelOptions: CallOptions;
33
39
  readonly interceptors: Interceptors;
40
+ /** The default progress policy, run after the caller's `shouldStop`, or `undefined` when it is off (D11). */
41
+ readonly progress?: ProgressCheck;
34
42
  readonly signal: AbortSignal;
35
43
  readonly clock: Clock;
36
44
  }
package/dist/loop.js CHANGED
@@ -7,16 +7,14 @@
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, } from "@buildanagent/gateway";
10
+ import { addCost, addUsage, emptyUsage, projectCallCost, } from "@buildanagent/gateway";
11
+ import { checkBudget, unknownPriceError } from "./budget.js";
11
12
  import { isSdkError, SdkError } from "./errors.js";
12
13
  import { HookFailure, HookRunner } from "./hook-runner.js";
13
14
  import { toWireTool } from "./tools/define.js";
14
15
  import { runToolCalls } from "./tools/pipeline.js";
15
16
  /** The `stoppedBy` of a run that a clarification tool stopped. */
16
17
  const CLARIFICATION = "clarification";
17
- // The depth cap's defaults (D11). Nested runs pass their own depth once the depth cap is configurable.
18
- const TOP_LEVEL_DEPTH = 0;
19
- const DEFAULT_MAX_DEPTH = 2;
20
18
  /**
21
19
  * The cost of no model call: an exact zero. Its basis is `provider` because `addCost()` keeps the other cost's basis
22
20
  * when it adds a provider cost, so the zero never turns a billed sum into an estimate.
@@ -185,6 +183,32 @@ function withheld(original) {
185
183
  cost,
186
184
  };
187
185
  }
186
+ /**
187
+ * The budget check before a call (D9): the outcome that ends the run when the spend so far plus the call's projected
188
+ * cost would pass `budgetUsd`, or `undefined` when the call may go out. It checks the request as it will be sent,
189
+ * after the interceptors have changed it, and projects with the model the request names.
190
+ */
191
+ function budgetBlock(state, request) {
192
+ const { budgetUsd } = state.setup;
193
+ if (budgetUsd === undefined)
194
+ return undefined;
195
+ const projected = projectCallCost(request.model, request.context, request.options);
196
+ const verdict = checkBudget(budgetUsd, state.cost, projected);
197
+ switch (verdict.kind) {
198
+ case "allow":
199
+ return undefined;
200
+ case "unknown":
201
+ return { stopReason: "error", error: verdict.error };
202
+ case "exceeded":
203
+ return {
204
+ stopReason: "budget",
205
+ reason: verdict.reason,
206
+ budgetUsd,
207
+ spentUsd: verdict.spentUsd,
208
+ projectedUsd: verdict.projectedUsd,
209
+ };
210
+ }
211
+ }
188
212
  /**
189
213
  * Makes one model call, streams its events and records the response. The call's usage and cost are the model's own
190
214
  * message's, so an `afterModelCall` replacement changes what the run goes on with, never what it is billed. When
@@ -193,6 +217,9 @@ function withheld(original) {
193
217
  */
194
218
  async function callModel(state) {
195
219
  const request = await buildRequest(state);
220
+ const blocked = budgetBlock(state, request);
221
+ if (blocked !== undefined)
222
+ return { blocked };
196
223
  state.active = request.active;
197
224
  const original = await streamRequest(state, request);
198
225
  state.steps += 1;
@@ -228,8 +255,8 @@ async function runTools(state, message) {
228
255
  runId,
229
256
  signal,
230
257
  clock,
231
- depth: TOP_LEVEL_DEPTH,
232
- maxDepth: DEFAULT_MAX_DEPTH,
258
+ depth: state.setup.depth,
259
+ maxDepth: state.setup.maxDepth,
233
260
  ...state.hooks.pipelineHooks(),
234
261
  onStart: (call) => state.send({ type: "tool_call_start", callId: call.callId, tool: call.name, input: call.input }),
235
262
  onUpdate: (callId, details) => state.send({ type: "tool_call_update", callId, details }),
@@ -305,7 +332,17 @@ async function decide(state, message, results) {
305
332
  if (natural !== undefined && !endedByAnswer)
306
333
  return natural;
307
334
  const verdict = await state.hooks.shouldStop({ messages: state.messages, lastMessage: message });
308
- return withVerdict(state, natural, verdict);
335
+ return withVerdict(state, natural, await withProgress(state, verdict));
336
+ }
337
+ /**
338
+ * The caller's verdict, unless the progress policy finds the run stuck. A caller's own stop stands, and a caller's
339
+ * `{ continue }` or failed hook can't keep a stuck run going.
340
+ */
341
+ async function withProgress(state, verdict) {
342
+ if (verdict.kind === "stop" || verdict.kind === "no_progress" || state.setup.progress === undefined)
343
+ return verdict;
344
+ const reason = await state.setup.progress(state.messages);
345
+ return reason === undefined ? verdict : { kind: "no_progress", reason };
309
346
  }
310
347
  /** The outcome of a hook that failed while the run fails closed. A failure caused by an abort ends the run aborted. */
311
348
  function failedOutcome(state, error) {
@@ -320,9 +357,14 @@ async function runStep(state) {
320
357
  state.send({ type: "step_start" });
321
358
  let outcome;
322
359
  try {
323
- const message = await callModel(state);
324
- const results = await runTools(state, message);
325
- outcome = await decide(state, message, results);
360
+ const called = await callModel(state);
361
+ if ("blocked" in called) {
362
+ outcome = called.blocked;
363
+ }
364
+ else {
365
+ const results = await runTools(state, called);
366
+ outcome = await decide(state, called, results);
367
+ }
326
368
  }
327
369
  catch (error) {
328
370
  outcome = failedOutcome(state, error);
@@ -385,7 +427,9 @@ async function finish(state, outcome) {
385
427
  */
386
428
  export async function runLoop(setup, emit, drain) {
387
429
  const state = new LoopState(setup, emit, drain);
388
- let outcome;
430
+ // A budget needs a price to check against, so a model without one is refused before it is called (D4).
431
+ const refused = setup.budgetUsd === undefined ? undefined : unknownPriceError(setup.model);
432
+ let outcome = refused === undefined ? undefined : { stopReason: "error", error: refused };
389
433
  while (outcome === undefined) {
390
434
  outcome = setup.signal.aborted ? { stopReason: "aborted" } : await runStep(state);
391
435
  }