@buildanagent/sdk 0.1.0-alpha.4 → 0.1.0-alpha.5
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 +65 -5
- 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 +6 -2
- package/dist/errors.js +5 -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 +6 -3
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +18 -8
- package/dist/loop.js +190 -28
- 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/result.d.ts +11 -5
- package/dist/result.js.map +1 -1
- package/dist/run.d.ts +34 -4
- package/dist/run.js +84 -7
- package/dist/run.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 +2 -2
- package/dist/tools/types.js.map +1 -1
- 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 and budgets 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,10 @@ 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, 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`**: a `shouldStop` hook ended the run with `{ stop: "no_progress", reason }`, and `result.reason` repeats the reason.
|
|
48
49
|
|
|
49
50
|
`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
51
|
|
|
@@ -77,13 +78,68 @@ The events come in two layers. The delta layer streams each content block by its
|
|
|
77
78
|
- **`run_start`** comes first, with the SDK's version, the spec version and the model.
|
|
78
79
|
- **`step_start`** and **`step_end`** wrap one model call and its tool calls; `step_end.stopCheck` says whether the run goes on.
|
|
79
80
|
- **`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.
|
|
81
|
+
- **`tool_call_start`**, **`tool_call_update`** and **`tool_call_end`** follow each tool call; `tool_call_end.result` is what the model reads. When a `beforeToolCall` gate replaced the model's input, `tool_call_end.input` holds the input the call got instead.
|
|
82
|
+
- **`context_transformed`** reports the message counts before and after `transformContext` for one model call.
|
|
83
|
+
- **`hook_error`** reports an interceptor or an observer that threw, with the hook's name and the message.
|
|
81
84
|
- **`retry`** reports a failed request the gateway is retrying, and **`warning`** reports a reached cap or a model warning.
|
|
82
85
|
- **`error`** and **`abort`** report a failed call and an abort request.
|
|
83
86
|
- **`agent_settled`** fires once nothing is running any more, retries and tools included. **`run_end`** follows it and carries the result.
|
|
84
87
|
|
|
85
88
|
`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
89
|
|
|
90
|
+
## Hooks change a run at six moments, and observers only watch
|
|
91
|
+
|
|
92
|
+
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()`.
|
|
93
|
+
|
|
94
|
+
### A step calls the interceptors in one fixed order
|
|
95
|
+
|
|
96
|
+
Each model call goes through the same moments, and each interceptor owns one of them:
|
|
97
|
+
|
|
98
|
+
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.
|
|
99
|
+
2. **`beforeModelCall`** returns a patch for the request: a `system` prompt, `messages`, `options`, another `model`, or `activeTools`. A patch lasts for that call only.
|
|
100
|
+
3. The model call runs.
|
|
101
|
+
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.
|
|
102
|
+
5. For each tool call, **`beforeToolCall`** decides whether it runs, and **`afterToolCall`** edits the result.
|
|
103
|
+
6. **`shouldStop`** decides whether the run ends.
|
|
104
|
+
|
|
105
|
+
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.
|
|
106
|
+
|
|
107
|
+
`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.
|
|
108
|
+
|
|
109
|
+
### A gate decides each tool call
|
|
110
|
+
|
|
111
|
+
`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.
|
|
112
|
+
|
|
113
|
+
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.
|
|
114
|
+
|
|
115
|
+
`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.
|
|
116
|
+
|
|
117
|
+
### `shouldStop` ends a run, or keeps it going
|
|
118
|
+
|
|
119
|
+
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.
|
|
120
|
+
|
|
121
|
+
### A throwing interceptor fails closed
|
|
122
|
+
|
|
123
|
+
By default a hook that throws stops the unsafe thing, and the run emits a `hook_error` event:
|
|
124
|
+
|
|
125
|
+
- A failed `beforeToolCall` denies the call.
|
|
126
|
+
- 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.
|
|
127
|
+
- 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.
|
|
128
|
+
|
|
129
|
+
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.
|
|
130
|
+
|
|
131
|
+
### `composeInterceptors()` joins several objects
|
|
132
|
+
|
|
133
|
+
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"`.
|
|
134
|
+
|
|
135
|
+
### Observers watch without changing anything
|
|
136
|
+
|
|
137
|
+
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`.
|
|
138
|
+
|
|
139
|
+
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.
|
|
140
|
+
|
|
141
|
+
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.
|
|
142
|
+
|
|
87
143
|
## Define a tool with `defineTool()`
|
|
88
144
|
|
|
89
145
|
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:
|
|
@@ -179,6 +235,10 @@ The SDK throws only for programmer errors, never for a failure the model caused.
|
|
|
179
235
|
- **`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
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"`.
|
|
181
237
|
- **`invalid_model_stream`**: a model's stream ended without a final message, which only a broken adapter does.
|
|
238
|
+
Hooks add two `SdkError` codes:
|
|
239
|
+
|
|
240
|
+
- **`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.
|
|
241
|
+
- **`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
242
|
- **`run_stopped`**: the error is a `RunStoppedError` from `runOrThrow()`.
|
|
183
243
|
- **`unexpected_model_call`**: the error is an `UnexpectedModelCallError` from `ScriptedModel`.
|
|
184
244
|
|
|
@@ -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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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,17 @@
|
|
|
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" | "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. `invalid_hook_result`: an interceptor returned something its type does not allow, such as
|
|
17
|
+
* a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor
|
|
18
|
+
* threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,
|
|
19
|
+
* so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a
|
|
20
|
+
* `RunStoppedError`).
|
|
17
21
|
* `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
|
|
18
22
|
* `UnexpectedModelCallError`).
|
|
19
23
|
*/
|
package/dist/errors.js
CHANGED
|
@@ -5,7 +5,11 @@ 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. `invalid_hook_result`: an interceptor returned something its type does not allow, such as
|
|
9
|
+
* a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor
|
|
10
|
+
* threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,
|
|
11
|
+
* so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a
|
|
12
|
+
* `RunStoppedError`).
|
|
9
13
|
* `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
|
|
10
14
|
* `UnexpectedModelCallError`).
|
|
11
15
|
*/
|
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":"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"]}
|
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"];
|
package/dist/events.js
CHANGED
package/dist/events.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AA2FA,oEAAoE;AACpE,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC7C,WAAW;IACX,YAAY;IACZ,kBAAkB;IAClB,OAAO;IACP,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,iBAAiB;IACjB,iBAAiB;IACjB,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,gBAAgB;IAChB,SAAS;IACT,gBAAgB;IAChB,qBAAqB;IACrB,YAAY;IACZ,iBAAiB;IACjB,kBAAkB;IAClB,eAAe;IACf,UAAU;IACV,OAAO;IACP,OAAO;IACP,eAAe;IACf,SAAS;CACuC,CAAC,CAAC","sourcesContent":["/**\n * The events a run streams: one closed union in two layers (agent-SDK guide §5). The delta layer streams each content\n * block by its index; the item layer's end events (`model_call_end`, `tool_call_end`, `run_end`) carry the\n * authoritative item, which a session log stores. `AGENT_EVENT_TYPES` lists the union at run time, so a test can\n * check that the loop emits no type the union does not declare.\n */\nimport type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from \"@buildanagent/gateway\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { ToolResult } from \"./tools/types.js\";\n\n/** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */\nexport interface EventBase {\n readonly runId: string;\n readonly seq: number;\n readonly stepIndex: number;\n /** When the event was emitted, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** One model call's request as the loop sends it: the model, the context and the options. */\nexport interface ModelCallRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: DumpedOptions;\n}\n\n/**\n * Why a `warning` event fired. `max_steps`: the run reached `maxSteps` and stopped. `model_warning`: the model call\n * reported something that did not stop it, such as an option the provider would reject and the adapter dropped.\n */\nexport type WarningCode = \"max_steps\" | \"model_warning\";\n\n/** The body of each event, without the fields of `EventBase`. */\nexport type AgentEventBody =\n | {\n readonly type: \"run_start\";\n readonly sdkVersion: string;\n readonly specVersion: \"v1\";\n /** Reserved for a hash of the run's defaults; empty for now. */\n readonly defaultsHash: string;\n /** Reserved for the SDK's capability names; empty for now. */\n readonly capabilities: readonly string[];\n readonly model: ModelRef;\n }\n | { readonly type: \"run_end\"; readonly result: RunResult }\n /** Fires once nothing is running any more, retries and tools included; `run_end` follows it. */\n | { readonly type: \"agent_settled\" }\n | { readonly type: \"step_start\" }\n | { readonly type: \"step_end\"; readonly stopCheck: \"continue\" | \"stop\" }\n | { readonly type: \"model_call_start\"; readonly request: ModelCallRequest }\n | { readonly type: \"model_call_end\"; readonly message: AssistantMessage }\n | { readonly type: \"text_start\" | \"reasoning_start\" | \"tool_input_start\"; readonly index: number }\n | {\n readonly type: \"text_delta\" | \"reasoning_delta\" | \"tool_input_delta\";\n readonly index: number;\n readonly delta: string;\n }\n | {\n readonly type: \"text_end\" | \"reasoning_end\" | \"tool_input_end\";\n readonly index: number;\n readonly block: ContentBlock;\n }\n | { readonly type: \"tool_call_start\"; readonly callId: string; readonly tool: string; readonly input: unknown }\n | { readonly type: \"tool_call_update\"; readonly callId: string; readonly details: unknown }\n /**\n * `result` is what the model reads for the call, after `afterToolCall` has had its say. `input` is present only\n * when a `beforeToolCall` gate replaced the model's input, and holds the input the gate gave the call instead.\n */\n | {\n readonly type: \"tool_call_end\";\n readonly callId: string;\n readonly result: ToolResult;\n readonly input?: unknown;\n }\n /** `transformContext` returned the messages for one model call: `before` messages in, `after` messages out. */\n | { readonly type: \"context_transformed\"; readonly before: number; readonly after: number }\n /** The model is retrying a failed request; `attempt` is 1 for the first retry. */\n | { readonly type: \"retry\"; readonly attempt: number; readonly delayMs: number; readonly error: string }\n /**\n * An interceptor or an observer threw. `hook` names it (`beforeToolCall`, `observer` and so on) and `error` is the\n * thrown message. The run goes on or fails by the interceptors' `onFailure` setting; a failed observer never\n * affects it.\n */\n | { readonly type: \"hook_error\"; readonly hook: string; readonly error: string }\n | { readonly type: \"warning\"; readonly code: WarningCode; readonly detail: string }\n | { readonly type: \"error\"; readonly error: RunError }\n | { readonly type: \"abort\"; readonly reason?: string };\n\n/** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */\nexport type AgentEvent = EventBase & AgentEventBody;\n\n/** Every `AgentEvent` type. A run emits no type this list lacks. */\nexport const AGENT_EVENT_TYPES = Object.freeze([\n \"run_start\",\n \"step_start\",\n \"model_call_start\",\n \"retry\",\n \"text_start\",\n \"text_delta\",\n \"text_end\",\n \"reasoning_start\",\n \"reasoning_delta\",\n \"reasoning_end\",\n \"tool_input_start\",\n \"tool_input_delta\",\n \"tool_input_end\",\n \"warning\",\n \"model_call_end\",\n \"context_transformed\",\n \"hook_error\",\n \"tool_call_start\",\n \"tool_call_update\",\n \"tool_call_end\",\n \"step_end\",\n \"error\",\n \"abort\",\n \"agent_settled\",\n \"run_end\",\n] as const satisfies readonly AgentEvent[\"type\"][]);\n"]}
|
package/dist/freeze.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Frozen copies of the data a hook receives, so a hook that mutates its input throws instead of changing the run's
|
|
3
|
+
* own transcript (agent-SDK guide §6, rule 2: a hook returns a replacement).
|
|
4
|
+
*/
|
|
5
|
+
/** A deep, frozen copy of the plain objects and arrays in `value`; other values are shared. */
|
|
6
|
+
export declare function frozenCopy<T>(value: T): T;
|
|
7
|
+
/**
|
|
8
|
+
* A deep, writable copy of the plain objects and arrays in `value`. A hook's event holds frozen copies, so an input a
|
|
9
|
+
* gate hands back from the event must be thawed before a tool runs with it, or a tool that edits its input throws.
|
|
10
|
+
*/
|
|
11
|
+
export declare function thawedCopy<T>(value: T): T;
|
package/dist/freeze.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Frozen copies of the data a hook receives, so a hook that mutates its input throws instead of changing the run's
|
|
3
|
+
* own transcript (agent-SDK guide §6, rule 2: a hook returns a replacement).
|
|
4
|
+
*/
|
|
5
|
+
function isPlain(value) {
|
|
6
|
+
const prototype = Object.getPrototypeOf(value);
|
|
7
|
+
return prototype === Object.prototype || prototype === null;
|
|
8
|
+
}
|
|
9
|
+
function copyOf(value, seen, freeze = true) {
|
|
10
|
+
if (typeof value !== "object" || value === null)
|
|
11
|
+
return value;
|
|
12
|
+
const known = seen.get(value);
|
|
13
|
+
if (known !== undefined)
|
|
14
|
+
return known;
|
|
15
|
+
if (Array.isArray(value)) {
|
|
16
|
+
const copy = [];
|
|
17
|
+
seen.set(value, copy);
|
|
18
|
+
for (const item of value)
|
|
19
|
+
copy.push(copyOf(item, seen, freeze));
|
|
20
|
+
return freeze ? Object.freeze(copy) : copy;
|
|
21
|
+
}
|
|
22
|
+
// A class instance, such as an `Error` in a result's details, is kept as it is: copying would lose its behaviour.
|
|
23
|
+
if (!isPlain(value))
|
|
24
|
+
return value;
|
|
25
|
+
const copy = {};
|
|
26
|
+
seen.set(value, copy);
|
|
27
|
+
for (const [key, item] of Object.entries(value))
|
|
28
|
+
copy[key] = copyOf(item, seen, freeze);
|
|
29
|
+
return freeze ? Object.freeze(copy) : copy;
|
|
30
|
+
}
|
|
31
|
+
/** A deep, frozen copy of the plain objects and arrays in `value`; other values are shared. */
|
|
32
|
+
export function frozenCopy(value) {
|
|
33
|
+
return copyOf(value, new WeakMap());
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A deep, writable copy of the plain objects and arrays in `value`. A hook's event holds frozen copies, so an input a
|
|
37
|
+
* gate hands back from the event must be thawed before a tool runs with it, or a tool that edits its input throws.
|
|
38
|
+
*/
|
|
39
|
+
export function thawedCopy(value) {
|
|
40
|
+
return copyOf(value, new WeakMap(), false);
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=freeze.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"freeze.js","sourceRoot":"","sources":["../src/freeze.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,SAAS,OAAO,CAAC,KAAa;IAC5B,MAAM,SAAS,GAAG,MAAM,CAA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AC,CAAC,IAAI,CAAC;AAC7C,CAAC;AAED,+FAA+F;AAC/F,MAAM,UAAU,UAAU,CAAI,KAAQ;IACpC,OAAO,MAAM,CAAC,KAAK,EAAE,IAAI,OAAO,EAAE,CAAM,CAAC;AAC3C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAI,KAAQ;IACpC,OAAO,MAAM,CAAC,KAAK,EAAE,IAAI,OAAO,EAAE,EAAE,KAAK,CAAM,CAAC;AAClD,CAAC","sourcesContent":["/**\n * Frozen copies of the data a hook receives, so a hook that mutates its input throws instead of changing the run's\n * own transcript (agent-SDK guide §6, rule 2: a hook returns a replacement).\n */\n\nfunction isPlain(value: object): boolean {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction copyOf(value: unknown, seen: WeakMap<object, unknown>, freeze = true): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n const known = seen.get(value);\n if (known !== undefined) return known;\n if (Array.isArray(value)) {\n const copy: unknown[] = [];\n seen.set(value, copy);\n for (const item of value) copy.push(copyOf(item, seen, freeze));\n return freeze ? Object.freeze(copy) : copy;\n }\n // A class instance, such as an `Error` in a result's details, is kept as it is: copying would lose its behaviour.\n if (!isPlain(value)) return value;\n const copy: Record<string, unknown> = {};\n seen.set(value, copy);\n for (const [key, item] of Object.entries(value)) copy[key] = copyOf(item, seen, freeze);\n return freeze ? Object.freeze(copy) : copy;\n}\n\n/** A deep, frozen copy of the plain objects and arrays in `value`; other values are shared. */\nexport function frozenCopy<T>(value: T): T {\n return copyOf(value, new WeakMap()) as T;\n}\n\n/**\n * A deep, writable copy of the plain objects and arrays in `value`. A hook's event holds frozen copies, so an input a\n * gate hands back from the event must be thawed before a tool runs with it, or a tool that edits its input throws.\n */\nexport function thawedCopy<T>(value: T): T {\n return copyOf(value, new WeakMap(), false) as T;\n}\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checks on what an interceptor returned. A hook that returns the wrong shape is a programmer error, so each check
|
|
3
|
+
* throws an `SdkError` with code `invalid_hook_result` rather than failing closed: a typo in a gate must be loud.
|
|
4
|
+
*/
|
|
5
|
+
import type { AssistantMessage, ContentBlock, Message } from "@buildanagent/gateway";
|
|
6
|
+
import type { GateDecision, ModelCallPatch } from "./hooks.js";
|
|
7
|
+
/** Checks a list of messages and returns a copy of it. */
|
|
8
|
+
export declare function checkMessages(hook: string, value: unknown): Message[];
|
|
9
|
+
/** Checks `beforeModelCall`'s return value: nothing, or a patch of well-formed fields. */
|
|
10
|
+
export declare function checkModelPatch(value: unknown): ModelCallPatch | undefined;
|
|
11
|
+
/** Checks `afterModelCall`'s return value and returns the replacement message, if there is one. */
|
|
12
|
+
export declare function checkReplacement(value: unknown): AssistantMessage | undefined;
|
|
13
|
+
/** Checks `beforeToolCall`'s decision. */
|
|
14
|
+
export declare function checkDecision(value: unknown): GateDecision;
|
|
15
|
+
/** Checks `afterToolCall`'s patch. */
|
|
16
|
+
export declare function checkResultPatch(value: unknown): Record<string, unknown> | undefined;
|
|
17
|
+
/** What the run does after `shouldStop`. */
|
|
18
|
+
export type StopVerdict = {
|
|
19
|
+
readonly kind: "none";
|
|
20
|
+
} | {
|
|
21
|
+
readonly kind: "stop";
|
|
22
|
+
readonly stoppedBy: string;
|
|
23
|
+
} | {
|
|
24
|
+
readonly kind: "no_progress";
|
|
25
|
+
readonly reason: string;
|
|
26
|
+
} | {
|
|
27
|
+
readonly kind: "continue";
|
|
28
|
+
readonly content: ContentBlock[];
|
|
29
|
+
};
|
|
30
|
+
/** Checks `shouldStop`'s decision and turns it into a verdict. */
|
|
31
|
+
export declare function checkStopDecision(value: unknown): StopVerdict;
|