@buildanagent/sdk 0.1.0-alpha.4 → 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 +115 -7
- package/dist/budget.d.ts +33 -0
- package/dist/budget.js +55 -0
- package/dist/budget.js.map +1 -0
- package/dist/compose.d.ts +22 -0
- package/dist/compose.js +137 -0
- package/dist/compose.js.map +1 -0
- package/dist/errors.d.ts +7 -2
- package/dist/errors.js +6 -1
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +22 -2
- package/dist/events.js +2 -0
- package/dist/events.js.map +1 -1
- package/dist/freeze.d.ts +11 -0
- package/dist/freeze.js +42 -0
- package/dist/freeze.js.map +1 -0
- package/dist/hook-checks.d.ts +31 -0
- package/dist/hook-checks.js +113 -0
- package/dist/hook-checks.js.map +1 -0
- package/dist/hook-runner.d.ts +60 -0
- package/dist/hook-runner.js +169 -0
- package/dist/hook-runner.js.map +1 -0
- package/dist/hooks.d.ts +177 -0
- package/dist/hooks.js +2 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +10 -4
- package/dist/index.js +9 -3
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +26 -8
- package/dist/loop.js +241 -35
- package/dist/loop.js.map +1 -1
- package/dist/observers.d.ts +31 -0
- package/dist/observers.js +98 -0
- package/dist/observers.js.map +1 -0
- package/dist/progress.d.ts +34 -0
- package/dist/progress.js +139 -0
- package/dist/progress.js.map +1 -0
- package/dist/result.d.ts +28 -5
- package/dist/result.js.map +1 -1
- package/dist/run.d.ts +69 -5
- package/dist/run.js +125 -7
- package/dist/run.js.map +1 -1
- package/dist/tools/define.d.ts +3 -3
- package/dist/tools/define.js +6 -3
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/pipeline.d.ts +29 -7
- package/dist/tools/pipeline.js +48 -14
- package/dist/tools/pipeline.js.map +1 -1
- package/dist/tools/types.d.ts +10 -2
- package/dist/tools/types.js.map +1 -1
- package/dist/vendor/agent-safety/hash.d.ts +16 -0
- package/dist/vendor/agent-safety/hash.js +109 -0
- package/dist/vendor/agent-safety/hash.js.map +1 -0
- package/package.json +2 -2
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 and the testing export.
|
|
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
|
|
|
@@ -34,7 +34,7 @@ for await (const event of started) {
|
|
|
34
34
|
const result = await started.result;
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
-
`model` comes from `createModel()` in the gateway, and a bare model id is a type error. A tool whose `exposure` is `"deferred"` or `"hidden"` is
|
|
37
|
+
`model` comes from `createModel()` in the gateway, and a bare model id is a type error. A tool whose `exposure` is `"deferred"` or `"hidden"` is sent to the model only when a `beforeModelCall` interceptor names it in `activeTools`, and a call to a tool the request didn't send gets the unknown-tool error.
|
|
38
38
|
|
|
39
39
|
### Every run ends with a stop reason
|
|
40
40
|
|
|
@@ -42,9 +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, 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
|
-
- **`stopped`**: a tool from `clarificationTool()` asked the user a question, and `result.stoppedBy` is `"clarification"
|
|
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`**: 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.
|
|
48
50
|
|
|
49
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.
|
|
50
52
|
|
|
@@ -68,6 +70,52 @@ const result = await runOrThrow(run({ model, system, input }));
|
|
|
68
70
|
|
|
69
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.
|
|
70
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
|
+
|
|
71
119
|
## A run streams one closed set of events
|
|
72
120
|
|
|
73
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.
|
|
@@ -77,13 +125,68 @@ The events come in two layers. The delta layer streams each content block by its
|
|
|
77
125
|
- **`run_start`** comes first, with the SDK's version, the spec version and the model.
|
|
78
126
|
- **`step_start`** and **`step_end`** wrap one model call and its tool calls; `step_end.stopCheck` says whether the run goes on.
|
|
79
127
|
- **`model_call_start`** carries the request, and **`model_call_end`** the final message.
|
|
80
|
-
- **`tool_call_start`**, **`tool_call_update`** and **`tool_call_end`** follow each tool call; `tool_call_end.result` is what the model reads.
|
|
128
|
+
- **`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.
|
|
129
|
+
- **`context_transformed`** reports the message counts before and after `transformContext` for one model call.
|
|
130
|
+
- **`hook_error`** reports an interceptor or an observer that threw, with the hook's name and the message.
|
|
81
131
|
- **`retry`** reports a failed request the gateway is retrying, and **`warning`** reports a reached cap or a model warning.
|
|
82
132
|
- **`error`** and **`abort`** report a failed call and an abort request.
|
|
83
133
|
- **`agent_settled`** fires once nothing is running any more, retries and tools included. **`run_end`** follows it and carries the result.
|
|
84
134
|
|
|
85
135
|
`AGENT_EVENT_TYPES` lists every type at run time, and a run emits no other. The union is closed, so a `switch` over `event.type` can be exhaustive.
|
|
86
136
|
|
|
137
|
+
## Hooks change a run at six moments, and observers only watch
|
|
138
|
+
|
|
139
|
+
A hook is a function that takes one event object. Interceptors can change, block or replace something; observers can only watch. Pass interceptors as one object in the `interceptors` option, and observers in `observers` or through `run.on()`.
|
|
140
|
+
|
|
141
|
+
### A step calls the interceptors in one fixed order
|
|
142
|
+
|
|
143
|
+
Each model call goes through the same moments, and each interceptor owns one of them:
|
|
144
|
+
|
|
145
|
+
1. **`transformContext`** returns the messages to send for this call. Use it to mask old tool output or summarise a long conversation. The view reaches that one request. The next call's event, `result.messages` and `result.context` all keep the full history, and each call emits a `context_transformed` event.
|
|
146
|
+
2. **`beforeModelCall`** returns a patch for the request: a `system` prompt, `messages`, `options`, another `model`, or `activeTools`. A patch lasts for that call only.
|
|
147
|
+
3. The model call runs.
|
|
148
|
+
4. **`afterModelCall`** returns `{ message }` to replace the response. The transcript, `model_call_end` and the tool calls that run all use the replacement, while usage and cost stay the model's own.
|
|
149
|
+
5. For each tool call, **`beforeToolCall`** decides whether it runs, and **`afterToolCall`** edits the result.
|
|
150
|
+
6. **`shouldStop`** decides whether the run ends.
|
|
151
|
+
|
|
152
|
+
Every event carries `runId`, `stepIndex`, `signal` and `timestamp`, and the two tool hooks add `callId`. Pass `signal` on to any I/O your hook does. The event's data is frozen, so a hook that tries to change it throws a `TypeError`. Return a replacement instead.
|
|
153
|
+
|
|
154
|
+
`activeTools` lists the tools to send, and only those. A tool whose `exposure` is `"deferred"` or `"hidden"` is sent when you name it, so a tool-search step can reveal a tool for the next request. Tools always go out in definition order, whatever order your list has, and a name that matches no tool throws `invalid_hook_result`. A call to a tool the request did not send gets the unknown-tool error.
|
|
155
|
+
|
|
156
|
+
### A gate decides each tool call
|
|
157
|
+
|
|
158
|
+
`beforeToolCall` returns `{ decision: "allow" }`, `{ decision: "deny", reason }` or `{ decision: "ask" }`. An `allow` may carry a new `input`, which must pass the tool's schema. A `deny` reaches the model as an error result that states the reason. Until runs can pause for approval, `ask` blocks the call the same way, with a message that says approval isn't available. The model never sees a silent block.
|
|
159
|
+
|
|
160
|
+
The run asks about one call at a time, in the order the model sent them, and no call of the step starts until every gate has answered. Without a `beforeToolCall`, every registered tool is allowed. A gate must return a decision: returning nothing throws `invalid_hook_result`, so a forgotten `return` can't pass for permission.
|
|
161
|
+
|
|
162
|
+
`afterToolCall` returns a patch of `content`, `details`, `structured`, `isError` or `terminate`. The patched result is what the model reads and what `tool_call_end` reports. It runs for calls that executed, a tool that threw included, and not for calls that never ran, such as an unknown tool, invalid input or a denied call. To change a write's `outcome`, replace `content` instead.
|
|
163
|
+
|
|
164
|
+
### `shouldStop` ends a run, or keeps it going
|
|
165
|
+
|
|
166
|
+
It returns `true` or `{ stop: "hook", reason }` to end the run `stopped`, with the reason as `stoppedBy` (`"hook"` for `true`). It returns `{ stop: "no_progress", reason }` to end it `no_progress`. It returns `{ continue: "text or blocks" }` to keep going a run whose model answered in text, with your content added as a user message. If the step called tools, the run goes on anyway and the content is not added. At the step cap the run ends `max_steps` instead. `false` leaves the decision to the run. A run that has already finished, failed, been aborted or asked a question keeps that outcome.
|
|
167
|
+
|
|
168
|
+
### A throwing interceptor fails closed
|
|
169
|
+
|
|
170
|
+
By default a hook that throws stops the unsafe thing, and the run emits a `hook_error` event:
|
|
171
|
+
|
|
172
|
+
- A failed `beforeToolCall` denies the call.
|
|
173
|
+
- A failed `afterToolCall` withholds the result, so a redaction that crashed can't leak the original. The stand-in tells the model the tool ran and keeps a write's outcome, so the model does not retry a write that was applied.
|
|
174
|
+
- A failed `transformContext`, `beforeModelCall`, `afterModelCall` or `shouldStop` ends the run with `stopReason: "error"` and `error.kind: "hook"`. If the run was aborted, it ends `aborted` instead. When `afterModelCall` fails, the transcript and `model_call_end` hold an empty stand-in with `stopReason: "error"` and the call's usage and cost, so the response is withheld but the billed call is still on record.
|
|
175
|
+
|
|
176
|
+
Set `onFailure: "continue"` to skip a failed hook and go on as if it had returned nothing. A hook that returns the wrong shape is a different case: it is a bug in your code, so the run's `result` rejects with `invalid_hook_result` whatever `onFailure` says.
|
|
177
|
+
|
|
178
|
+
### `composeInterceptors()` joins several objects
|
|
179
|
+
|
|
180
|
+
A run takes one `Interceptors` object, so `composeInterceptors(a, b)` joins a context policy, a permission check and an audit. For a moment that several define, the hooks run in the order given. `transformContext` passes the messages through each hook in turn. `beforeModelCall` merges the patches, a later field replacing an earlier one. `afterModelCall` and `afterToolCall` chain, each hook seeing the result so far. For gates the strictest answer wins: the first `deny` ends the check, an `ask` beats an `allow`, and an input one gate replaces is the input the next gate sees. For `shouldStop` the first stop wins, then the first continue. Each hook's return value is checked as if it ran alone, so a gate that returns nothing throws `invalid_hook_result` even when another gate allows the call. The joined `onFailure` is `"continue"` only when every object sets it to `"continue"`; an object that leaves it unset counts as `"fail_closed"`.
|
|
181
|
+
|
|
182
|
+
### Observers watch without changing anything
|
|
183
|
+
|
|
184
|
+
An observer is `(event) => void | Promise<void>`. Each one sees every event in order, and waits for its own promise before it gets the next. Observers don't wait for each other, so one slow observer delays only itself. The `observers` option sees events from `run_start`. `run.on(observer)` returns a function that removes it, and drops events still queued for it. Call it right after `run()` to see every event but `run_start`.
|
|
185
|
+
|
|
186
|
+
An observer that throws or rejects becomes a `hook_error` event with `hook: "observer"`, and never changes the run. The one exception is an observer that fails while handling `run_end`: nothing may follow that event, so the failure is dropped.
|
|
187
|
+
|
|
188
|
+
The run waits for observers to handle `agent_settled` and `run_end` before it settles, for at most `observerTimeoutMs` each time, a number from 1 to 2147483647 that defaults to 10000. An observer that hasn't caught up by then is removed and reported as a `hook_error`, so an observer whose promise never settles can't hold the run open. Each observer gets a frozen copy of the event, so it can't change the run's own data.
|
|
189
|
+
|
|
87
190
|
## Define a tool with `defineTool()`
|
|
88
191
|
|
|
89
192
|
A tool is a name, a description the model reads, an input schema and an `execute` function. This tool looks up an order in your own store:
|
|
@@ -175,10 +278,15 @@ Every tool gets a `ctx.signal` that fires when the run is aborted. It also fires
|
|
|
175
278
|
|
|
176
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:
|
|
177
280
|
|
|
178
|
-
- **`invalid_tool_definition`**: a tool's name, description, schema, exposure, `executionMode` or `
|
|
281
|
+
- **`invalid_tool_definition`**: a tool's name, description, schema, exposure, `executionMode`, `resourceKey` or `progressKey` is unusable, or two tools share a name.
|
|
179
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.
|
|
180
|
-
- **`invalid_run_options`**: `run()` or `continueRun()` got a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer,
|
|
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.
|
|
181
285
|
- **`invalid_model_stream`**: a model's stream ended without a final message, which only a broken adapter does.
|
|
286
|
+
Hooks add two `SdkError` codes:
|
|
287
|
+
|
|
288
|
+
- **`invalid_hook_result`**: an interceptor returned something its type forbids, such as a gate that returned no decision, an `activeTools` list that names no tool, or a replacement input that fails the tool's schema. The run's `result` rejects with this error.
|
|
289
|
+
- **`hook_failed`**: an interceptor threw while the run fails closed. The run catches it and reports a `hook` error result, so it never reaches your code.
|
|
182
290
|
- **`run_stopped`**: the error is a `RunStoppedError` from `runOrThrow()`.
|
|
183
291
|
- **`unexpected_model_call`**: the error is an `UnexpectedModelCallError` from `ScriptedModel`.
|
|
184
292
|
|
package/dist/budget.d.ts
ADDED
|
@@ -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"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Interceptors } from "./hooks.js";
|
|
2
|
+
/**
|
|
3
|
+
* Joins interceptor objects into one. For a moment that several objects define, the hooks run in the order given,
|
|
4
|
+
* and the result is:
|
|
5
|
+
*
|
|
6
|
+
* - `transformContext`: the messages pass through each hook in turn.
|
|
7
|
+
* - `beforeModelCall`: the patches are merged in order, a later field replacing an earlier one, and each hook sees
|
|
8
|
+
* the system prompt, messages and options the earlier ones set. A field left `undefined` keeps the earlier value.
|
|
9
|
+
* - `afterModelCall`: each hook sees the message the one before returned.
|
|
10
|
+
* - `beforeToolCall`: the strictest decision wins. The first `deny` ends the check, an `ask` beats `allow`, and an
|
|
11
|
+
* input one gate replaces is the input the next gate sees.
|
|
12
|
+
* - `afterToolCall`: the patches are applied in order, each hook seeing the result so far.
|
|
13
|
+
* - `shouldStop`: the first `stop` wins; failing that, the first `continue`.
|
|
14
|
+
*
|
|
15
|
+
* Each hook's return value is checked as if the hook ran alone, so a wrong shape, such as a gate that returns nothing,
|
|
16
|
+
* throws an `SdkError` with code `invalid_hook_result` whatever the other hooks return. A hook that throws fails the
|
|
17
|
+
* moment it belongs to, because the joined hook is one function. The joined `onFailure` is
|
|
18
|
+
* `"continue"` only when every object sets it to `"continue"`; an object that leaves it unset counts as
|
|
19
|
+
* `"fail_closed"`. One lenient object therefore never loosens the others, and a join of a gate with a lenient audit
|
|
20
|
+
* hook fails closed. Set `"continue"` on all of them, and the gate then fails open too.
|
|
21
|
+
*/
|
|
22
|
+
export declare function composeInterceptors(...sets: readonly Interceptors[]): Interceptors;
|
package/dist/compose.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { checkDecision, checkMessages, checkModelPatch, checkReplacement, checkResultPatch, checkStopDecision, } from "./hook-checks.js";
|
|
2
|
+
function hooksOf(sets, name) {
|
|
3
|
+
return sets.flatMap((set) => (set[name] === undefined ? [] : [set[name]]));
|
|
4
|
+
}
|
|
5
|
+
// Each joined hook checks what every one of its hooks returns, as the run checks a hook used alone, so a hook's wrong
|
|
6
|
+
// return shape is never hidden by the hooks around it. The checks throw `invalid_hook_result`, which the run rethrows
|
|
7
|
+
// whatever `onFailure` says.
|
|
8
|
+
/** The fields of `patch` that are set: a field set to `undefined` doesn't erase what an earlier hook set. */
|
|
9
|
+
function definedFields(patch) {
|
|
10
|
+
return Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined));
|
|
11
|
+
}
|
|
12
|
+
/** Passes the messages through each `transformContext` in turn: the second sees the first's view. */
|
|
13
|
+
const transform = (hooks) => async (e) => {
|
|
14
|
+
let messages = e.messages;
|
|
15
|
+
for (const hook of hooks)
|
|
16
|
+
messages = checkMessages("transformContext", await hook({ ...e, messages }));
|
|
17
|
+
return messages;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Merges the patches in order: a later field wins, and each hook sees the system prompt, messages and options set
|
|
21
|
+
* before it. `context.tools` stays the list the run would send, because only the run can lower a tool it activates.
|
|
22
|
+
*/
|
|
23
|
+
const before = (hooks) => async (e) => {
|
|
24
|
+
let event = e;
|
|
25
|
+
let merged;
|
|
26
|
+
for (const hook of hooks) {
|
|
27
|
+
const patch = checkModelPatch(await hook(event));
|
|
28
|
+
if (patch === undefined)
|
|
29
|
+
continue;
|
|
30
|
+
const fields = definedFields(patch);
|
|
31
|
+
merged = { ...merged, ...fields };
|
|
32
|
+
event = { ...event, context: contextAfter(event.context, fields), options: fields.options ?? event.options };
|
|
33
|
+
}
|
|
34
|
+
return merged;
|
|
35
|
+
};
|
|
36
|
+
function contextAfter(context, patch) {
|
|
37
|
+
return {
|
|
38
|
+
...context,
|
|
39
|
+
system: patch.system ?? context.system,
|
|
40
|
+
messages: patch.messages === undefined ? context.messages : [...patch.messages],
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** Chains the replacements: each hook sees the message the one before it returned. */
|
|
44
|
+
const after = (hooks) => async (e) => {
|
|
45
|
+
let message = e.message;
|
|
46
|
+
for (const hook of hooks)
|
|
47
|
+
message = checkReplacement(await hook({ ...e, message })) ?? message;
|
|
48
|
+
return { message };
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Asks each gate in turn and keeps the strictest answer: the first `deny` wins at once, an `ask` outranks an `allow`,
|
|
52
|
+
* and a replacement input from one gate is what the later gates see. A gate that throws makes the whole check fail.
|
|
53
|
+
*/
|
|
54
|
+
const gate = (hooks) => async (e) => {
|
|
55
|
+
let input = e.input;
|
|
56
|
+
let asked;
|
|
57
|
+
for (const hook of hooks) {
|
|
58
|
+
const decision = checkDecision(await hook({ ...e, input }));
|
|
59
|
+
if (decision.decision === "deny")
|
|
60
|
+
return decision;
|
|
61
|
+
if (decision.decision === "ask")
|
|
62
|
+
asked ??= decision;
|
|
63
|
+
else if (decision.input !== undefined)
|
|
64
|
+
input = decision.input;
|
|
65
|
+
}
|
|
66
|
+
return asked ?? { decision: "allow", ...(input === e.input ? {} : { input }) };
|
|
67
|
+
};
|
|
68
|
+
/** Applies the patches in order: each hook sees the result with the earlier patches applied. */
|
|
69
|
+
const afterTool = (hooks) => async (e) => {
|
|
70
|
+
let result = e.result;
|
|
71
|
+
let merged;
|
|
72
|
+
for (const hook of hooks) {
|
|
73
|
+
const patch = checkResultPatch(await hook({ ...e, result }));
|
|
74
|
+
if (patch === undefined)
|
|
75
|
+
continue;
|
|
76
|
+
const fields = definedFields(patch);
|
|
77
|
+
merged = { ...merged, ...fields };
|
|
78
|
+
result = { ...result, ...fields };
|
|
79
|
+
}
|
|
80
|
+
return merged;
|
|
81
|
+
};
|
|
82
|
+
/** The first `stop` wins at once; otherwise the first `continue` stands; otherwise the run decides. */
|
|
83
|
+
const stop = (hooks) => async (e) => {
|
|
84
|
+
let keepGoing = false;
|
|
85
|
+
for (const hook of hooks) {
|
|
86
|
+
const decision = await hook(e);
|
|
87
|
+
checkStopDecision(decision);
|
|
88
|
+
if (typeof decision === "object" && "continue" in decision) {
|
|
89
|
+
if (keepGoing === false)
|
|
90
|
+
keepGoing = decision;
|
|
91
|
+
}
|
|
92
|
+
else if (decision !== false)
|
|
93
|
+
return decision;
|
|
94
|
+
}
|
|
95
|
+
return keepGoing;
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* Joins interceptor objects into one. For a moment that several objects define, the hooks run in the order given,
|
|
99
|
+
* and the result is:
|
|
100
|
+
*
|
|
101
|
+
* - `transformContext`: the messages pass through each hook in turn.
|
|
102
|
+
* - `beforeModelCall`: the patches are merged in order, a later field replacing an earlier one, and each hook sees
|
|
103
|
+
* the system prompt, messages and options the earlier ones set. A field left `undefined` keeps the earlier value.
|
|
104
|
+
* - `afterModelCall`: each hook sees the message the one before returned.
|
|
105
|
+
* - `beforeToolCall`: the strictest decision wins. The first `deny` ends the check, an `ask` beats `allow`, and an
|
|
106
|
+
* input one gate replaces is the input the next gate sees.
|
|
107
|
+
* - `afterToolCall`: the patches are applied in order, each hook seeing the result so far.
|
|
108
|
+
* - `shouldStop`: the first `stop` wins; failing that, the first `continue`.
|
|
109
|
+
*
|
|
110
|
+
* Each hook's return value is checked as if the hook ran alone, so a wrong shape, such as a gate that returns nothing,
|
|
111
|
+
* throws an `SdkError` with code `invalid_hook_result` whatever the other hooks return. A hook that throws fails the
|
|
112
|
+
* moment it belongs to, because the joined hook is one function. The joined `onFailure` is
|
|
113
|
+
* `"continue"` only when every object sets it to `"continue"`; an object that leaves it unset counts as
|
|
114
|
+
* `"fail_closed"`. One lenient object therefore never loosens the others, and a join of a gate with a lenient audit
|
|
115
|
+
* hook fails closed. Set `"continue"` on all of them, and the gate then fails open too.
|
|
116
|
+
*/
|
|
117
|
+
export function composeInterceptors(...sets) {
|
|
118
|
+
const lenient = sets.every((set) => (set.onFailure ?? "fail_closed") === "continue");
|
|
119
|
+
const hooks = {
|
|
120
|
+
transformContext: hooksOf(sets, "transformContext"),
|
|
121
|
+
beforeModelCall: hooksOf(sets, "beforeModelCall"),
|
|
122
|
+
afterModelCall: hooksOf(sets, "afterModelCall"),
|
|
123
|
+
beforeToolCall: hooksOf(sets, "beforeToolCall"),
|
|
124
|
+
afterToolCall: hooksOf(sets, "afterToolCall"),
|
|
125
|
+
shouldStop: hooksOf(sets, "shouldStop"),
|
|
126
|
+
};
|
|
127
|
+
return {
|
|
128
|
+
...(hooks.transformContext.length === 0 ? {} : { transformContext: transform(hooks.transformContext) }),
|
|
129
|
+
...(hooks.beforeModelCall.length === 0 ? {} : { beforeModelCall: before(hooks.beforeModelCall) }),
|
|
130
|
+
...(hooks.afterModelCall.length === 0 ? {} : { afterModelCall: after(hooks.afterModelCall) }),
|
|
131
|
+
...(hooks.beforeToolCall.length === 0 ? {} : { beforeToolCall: gate(hooks.beforeToolCall) }),
|
|
132
|
+
...(hooks.afterToolCall.length === 0 ? {} : { afterToolCall: afterTool(hooks.afterToolCall) }),
|
|
133
|
+
...(hooks.shouldStop.length === 0 ? {} : { shouldStop: stop(hooks.shouldStop) }),
|
|
134
|
+
onFailure: lenient && sets.length > 0 ? "continue" : "fail_closed",
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=compose.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compose.js","sourceRoot":"","sources":["../src/compose.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,aAAa,EACb,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAa1B,SAAS,OAAO,CAAqD,IAA6B,EAAE,IAAO;IACzG,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAY,CAAC,CAAC,CAAC,CAAC;A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AAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,EAAE,CAAC;QAC7F,GAAG,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,EAAE,CAAC;QAC5F,GAAG,CAAC,KAAK,CAAC,aAAa,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,SAAS,CAAC,KAAK,CAAC,aAAa,CAAC,EAAE,CAAC;QAC9F,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC;QAChF,SAAS,EAAE,OAAO,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,aAAa;KACnE,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `composeInterceptors()`: joins several interceptor objects into one, so a context policy, a permission pipeline and\n * an audit can each be written and tested alone. A run takes one `Interceptors` object, and the joined one is it.\n */\nimport type { Message, ModelContext } from \"@buildanagent/gateway\";\nimport {\n checkDecision,\n checkMessages,\n checkModelPatch,\n checkReplacement,\n checkResultPatch,\n checkStopDecision,\n} from \"./hook-checks.js\";\nimport type {\n GateDecision,\n Interceptors,\n ModelCallEvent,\n ModelCallPatch,\n StepEvent,\n StopDecision,\n ToolResultPatch,\n} from \"./hooks.js\";\n\ntype Hook<K extends keyof Interceptors> = NonNullable<Interceptors[K]>;\n\nfunction hooksOf<K extends Exclude<keyof Interceptors, \"onFailure\">>(sets: readonly Interceptors[], name: K) {\n return sets.flatMap((set) => (set[name] === undefined ? [] : [set[name] as Hook<K>]));\n}\n\n// Each joined hook checks what every one of its hooks returns, as the run checks a hook used alone, so a hook's wrong\n// return shape is never hidden by the hooks around it. The checks throw `invalid_hook_result`, which the run rethrows\n// whatever `onFailure` says.\n\n/** The fields of `patch` that are set: a field set to `undefined` doesn't erase what an earlier hook set. */\nfunction definedFields<T extends object>(patch: T): Partial<T> {\n return Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined)) as Partial<T>;\n}\n\n/** Passes the messages through each `transformContext` in turn: the second sees the first's view. */\nconst transform =\n (hooks: readonly Hook<\"transformContext\">[]): Hook<\"transformContext\"> =>\n async (e) => {\n let messages: readonly Message[] = e.messages;\n for (const hook of hooks) messages = checkMessages(\"transformContext\", await hook({ ...e, messages }));\n return messages;\n };\n\n/**\n * Merges the patches in order: a later field wins, and each hook sees the system prompt, messages and options set\n * before it. `context.tools` stays the list the run would send, because only the run can lower a tool it activates.\n */\nconst before =\n (hooks: readonly Hook<\"beforeModelCall\">[]): Hook<\"beforeModelCall\"> =>\n async (e) => {\n let event: ModelCallEvent = e;\n let merged: ModelCallPatch | undefined;\n for (const hook of hooks) {\n const patch = checkModelPatch(await hook(event));\n if (patch === undefined) continue;\n const fields = definedFields(patch);\n merged = { ...merged, ...fields };\n event = { ...event, context: contextAfter(event.context, fields), options: fields.options ?? event.options };\n }\n return merged;\n };\n\nfunction contextAfter(context: ModelContext, patch: ModelCallPatch): ModelContext {\n return {\n ...context,\n system: patch.system ?? context.system,\n messages: patch.messages === undefined ? context.messages : [...patch.messages],\n };\n}\n\n/** Chains the replacements: each hook sees the message the one before it returned. */\nconst after =\n (hooks: readonly Hook<\"afterModelCall\">[]): Hook<\"afterModelCall\"> =>\n async (e) => {\n let message = e.message;\n for (const hook of hooks) message = checkReplacement(await hook({ ...e, message })) ?? message;\n return { message };\n };\n\n/**\n * Asks each gate in turn and keeps the strictest answer: the first `deny` wins at once, an `ask` outranks an `allow`,\n * and a replacement input from one gate is what the later gates see. A gate that throws makes the whole check fail.\n */\nconst gate =\n (hooks: readonly Hook<\"beforeToolCall\">[]): Hook<\"beforeToolCall\"> =>\n async (e) => {\n let input = e.input;\n let asked: GateDecision | undefined;\n for (const hook of hooks) {\n const decision = checkDecision(await hook({ ...e, input }));\n if (decision.decision === \"deny\") return decision;\n if (decision.decision === \"ask\") asked ??= decision;\n else if (decision.input !== undefined) input = decision.input;\n }\n return asked ?? { decision: \"allow\", ...(input === e.input ? {} : { input }) };\n };\n\n/** Applies the patches in order: each hook sees the result with the earlier patches applied. */\nconst afterTool =\n (hooks: readonly Hook<\"afterToolCall\">[]): Hook<\"afterToolCall\"> =>\n async (e) => {\n let result = e.result;\n let merged: ToolResultPatch | undefined;\n for (const hook of hooks) {\n const patch = checkResultPatch(await hook({ ...e, result }));\n if (patch === undefined) continue;\n const fields = definedFields(patch) as ToolResultPatch;\n merged = { ...merged, ...fields };\n result = { ...result, ...fields };\n }\n return merged;\n };\n\n/** The first `stop` wins at once; otherwise the first `continue` stands; otherwise the run decides. */\nconst stop =\n (hooks: readonly Hook<\"shouldStop\">[]): Hook<\"shouldStop\"> =>\n async (e: StepEvent) => {\n let keepGoing: StopDecision = false;\n for (const hook of hooks) {\n const decision = await hook(e);\n checkStopDecision(decision);\n if (typeof decision === \"object\" && \"continue\" in decision) {\n if (keepGoing === false) keepGoing = decision;\n } else if (decision !== false) return decision;\n }\n return keepGoing;\n };\n\n/**\n * Joins interceptor objects into one. For a moment that several objects define, the hooks run in the order given,\n * and the result is:\n *\n * - `transformContext`: the messages pass through each hook in turn.\n * - `beforeModelCall`: the patches are merged in order, a later field replacing an earlier one, and each hook sees\n * the system prompt, messages and options the earlier ones set. A field left `undefined` keeps the earlier value.\n * - `afterModelCall`: each hook sees the message the one before returned.\n * - `beforeToolCall`: the strictest decision wins. The first `deny` ends the check, an `ask` beats `allow`, and an\n * input one gate replaces is the input the next gate sees.\n * - `afterToolCall`: the patches are applied in order, each hook seeing the result so far.\n * - `shouldStop`: the first `stop` wins; failing that, the first `continue`.\n *\n * Each hook's return value is checked as if the hook ran alone, so a wrong shape, such as a gate that returns nothing,\n * throws an `SdkError` with code `invalid_hook_result` whatever the other hooks return. A hook that throws fails the\n * moment it belongs to, because the joined hook is one function. The joined `onFailure` is\n * `\"continue\"` only when every object sets it to `\"continue\"`; an object that leaves it unset counts as\n * `\"fail_closed\"`. One lenient object therefore never loosens the others, and a join of a gate with a lenient audit\n * hook fails closed. Set `\"continue\"` on all of them, and the gate then fails open too.\n */\nexport function composeInterceptors(...sets: readonly Interceptors[]): Interceptors {\n const lenient = sets.every((set) => (set.onFailure ?? \"fail_closed\") === \"continue\");\n const hooks = {\n transformContext: hooksOf(sets, \"transformContext\"),\n beforeModelCall: hooksOf(sets, \"beforeModelCall\"),\n afterModelCall: hooksOf(sets, \"afterModelCall\"),\n beforeToolCall: hooksOf(sets, \"beforeToolCall\"),\n afterToolCall: hooksOf(sets, \"afterToolCall\"),\n shouldStop: hooksOf(sets, \"shouldStop\"),\n };\n return {\n ...(hooks.transformContext.length === 0 ? {} : { transformContext: transform(hooks.transformContext) }),\n ...(hooks.beforeModelCall.length === 0 ? {} : { beforeModelCall: before(hooks.beforeModelCall) }),\n ...(hooks.afterModelCall.length === 0 ? {} : { afterModelCall: after(hooks.afterModelCall) }),\n ...(hooks.beforeToolCall.length === 0 ? {} : { beforeToolCall: gate(hooks.beforeToolCall) }),\n ...(hooks.afterToolCall.length === 0 ? {} : { afterToolCall: afterTool(hooks.afterToolCall) }),\n ...(hooks.shouldStop.length === 0 ? {} : { shouldStop: stop(hooks.shouldStop) }),\n onFailure: lenient && sets.length > 0 ? \"continue\" : \"fail_closed\",\n };\n}\n"]}
|
package/dist/errors.d.ts
CHANGED
|
@@ -7,13 +7,18 @@
|
|
|
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" | "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. `
|
|
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
|
|
18
|
+
* a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor
|
|
19
|
+
* threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,
|
|
20
|
+
* so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a
|
|
21
|
+
* `RunStoppedError`).
|
|
17
22
|
* `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
|
|
18
23
|
* `UnexpectedModelCallError`).
|
|
19
24
|
*/
|
package/dist/errors.js
CHANGED
|
@@ -5,7 +5,12 @@ 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. `
|
|
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
|
|
10
|
+
* a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor
|
|
11
|
+
* threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,
|
|
12
|
+
* so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a
|
|
13
|
+
* `RunStoppedError`).
|
|
9
14
|
* `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
|
|
10
15
|
* `UnexpectedModelCallError`).
|
|
11
16
|
*/
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"
|
|
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/events.d.ts
CHANGED
|
@@ -75,11 +75,21 @@ export type AgentEventBody = {
|
|
|
75
75
|
readonly callId: string;
|
|
76
76
|
readonly details: unknown;
|
|
77
77
|
}
|
|
78
|
-
/**
|
|
78
|
+
/**
|
|
79
|
+
* `result` is what the model reads for the call, after `afterToolCall` has had its say. `input` is present only
|
|
80
|
+
* when a `beforeToolCall` gate replaced the model's input, and holds the input the gate gave the call instead.
|
|
81
|
+
*/
|
|
79
82
|
| {
|
|
80
83
|
readonly type: "tool_call_end";
|
|
81
84
|
readonly callId: string;
|
|
82
85
|
readonly result: ToolResult;
|
|
86
|
+
readonly input?: unknown;
|
|
87
|
+
}
|
|
88
|
+
/** `transformContext` returned the messages for one model call: `before` messages in, `after` messages out. */
|
|
89
|
+
| {
|
|
90
|
+
readonly type: "context_transformed";
|
|
91
|
+
readonly before: number;
|
|
92
|
+
readonly after: number;
|
|
83
93
|
}
|
|
84
94
|
/** The model is retrying a failed request; `attempt` is 1 for the first retry. */
|
|
85
95
|
| {
|
|
@@ -87,6 +97,16 @@ export type AgentEventBody = {
|
|
|
87
97
|
readonly attempt: number;
|
|
88
98
|
readonly delayMs: number;
|
|
89
99
|
readonly error: string;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* An interceptor or an observer threw. `hook` names it (`beforeToolCall`, `observer` and so on) and `error` is the
|
|
103
|
+
* thrown message. The run goes on or fails by the interceptors' `onFailure` setting; a failed observer never
|
|
104
|
+
* affects it.
|
|
105
|
+
*/
|
|
106
|
+
| {
|
|
107
|
+
readonly type: "hook_error";
|
|
108
|
+
readonly hook: string;
|
|
109
|
+
readonly error: string;
|
|
90
110
|
} | {
|
|
91
111
|
readonly type: "warning";
|
|
92
112
|
readonly code: WarningCode;
|
|
@@ -101,4 +121,4 @@ export type AgentEventBody = {
|
|
|
101
121
|
/** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */
|
|
102
122
|
export type AgentEvent = EventBase & AgentEventBody;
|
|
103
123
|
/** Every `AgentEvent` type. A run emits no type this list lacks. */
|
|
104
|
-
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", "tool_call_start", "tool_call_update", "tool_call_end", "step_end", "error", "abort", "agent_settled", "run_end"];
|
|
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"];
|