@buildanagent/sdk 0.1.0-alpha.8 → 0.1.0-alpha.9

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.
Files changed (51) hide show
  1. package/README.md +55 -4
  2. package/dist/compose.d.ts +2 -1
  3. package/dist/compose.js +10 -4
  4. package/dist/compose.js.map +1 -1
  5. package/dist/errors.d.ts +2 -1
  6. package/dist/errors.js +2 -1
  7. package/dist/errors.js.map +1 -1
  8. package/dist/events.d.ts +18 -4
  9. package/dist/events.js +1 -0
  10. package/dist/events.js.map +1 -1
  11. package/dist/hook-checks.js +17 -0
  12. package/dist/hook-checks.js.map +1 -1
  13. package/dist/hook-runner.d.ts +10 -0
  14. package/dist/hook-runner.js +86 -9
  15. package/dist/hook-runner.js.map +1 -1
  16. package/dist/hooks.d.ts +9 -4
  17. package/dist/hooks.js.map +1 -1
  18. package/dist/index.d.ts +9 -3
  19. package/dist/index.js +7 -2
  20. package/dist/index.js.map +1 -1
  21. package/dist/loop.d.ts +5 -0
  22. package/dist/loop.js +26 -3
  23. package/dist/loop.js.map +1 -1
  24. package/dist/otel/observer.js +14 -0
  25. package/dist/otel/observer.js.map +1 -1
  26. package/dist/pauses.d.ts +32 -0
  27. package/dist/pauses.js +46 -0
  28. package/dist/pauses.js.map +1 -0
  29. package/dist/result.d.ts +27 -3
  30. package/dist/result.js.map +1 -1
  31. package/dist/run.d.ts +19 -3
  32. package/dist/run.js +17 -1
  33. package/dist/run.js.map +1 -1
  34. package/dist/tools/pipeline.d.ts +19 -3
  35. package/dist/tools/pipeline.js +24 -5
  36. package/dist/tools/pipeline.js.map +1 -1
  37. package/dist/vendor/agent-safety/bytes.d.ts +17 -0
  38. package/dist/vendor/agent-safety/bytes.js +59 -0
  39. package/dist/vendor/agent-safety/bytes.js.map +1 -0
  40. package/dist/vendor/agent-safety/errors.d.ts +8 -4
  41. package/dist/vendor/agent-safety/errors.js +2 -2
  42. package/dist/vendor/agent-safety/errors.js.map +1 -1
  43. package/dist/vendor/agent-safety/hash.js +3 -2
  44. package/dist/vendor/agent-safety/hash.js.map +1 -1
  45. package/dist/vendor/agent-safety/pending.d.ts +119 -0
  46. package/dist/vendor/agent-safety/pending.js +122 -0
  47. package/dist/vendor/agent-safety/pending.js.map +1 -0
  48. package/dist/vendor/agent-safety/signer.d.ts +42 -0
  49. package/dist/vendor/agent-safety/signer.js +128 -0
  50. package/dist/vendor/agent-safety/signer.js.map +1 -0
  51. 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, hooks and the testing export. Approvals come next.
5
+ As of November 2026 the package holds the loop, tool definitions, hooks, signed pauses for approval and the testing export. Resuming a pause comes next.
6
6
 
7
7
  ## Install the alpha with `pnpm add @buildanagent/sdk@alpha`
8
8
 
@@ -47,8 +47,9 @@ A failed model call or a failing tool never makes a run throw. The run ends with
47
47
  - **`stopped`**: a tool from `clarificationTool()` asked the user a question, and `result.stoppedBy` is `"clarification"`; or a `shouldStop` hook ended the run, and `result.stoppedBy` is the reason it gave.
48
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
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.
50
+ - **`awaiting_approval`**: a `beforeToolCall` gate returned `ask`, so the call waits for a person. `result.pending` holds one signed request for each waiting call, as [the pause section](#a-gate-that-asks-ends-the-run-with-a-signed-pending-request) explains.
50
51
 
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.
52
+ `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, except a call a gate paused, which waits for a person.
52
53
 
53
54
  Only the `done` result carries `output`. TypeScript rejects `result.output` until you have checked `result.stopReason === "done"`, so an unfinished run can't pass for a finished one. Every result carries `usage` and `cost`, summed over the run's model calls, and `steps`, the number of calls. `result.messages` holds the messages this run added. `result.context` holds the whole conversation, ready to continue.
54
55
 
@@ -151,7 +152,8 @@ The events come in two layers. The delta layer streams each content block by its
151
152
  - **`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.
152
153
  - **`context_transformed`** reports the message counts before and after `transformContext` for one model call.
153
154
  - **`steer_applied`** reports a queued steer or follow-up that entered the transcript, with its receipt.
154
- - **`hook_error`** reports an interceptor or an observer that threw, with the hook's name and the message.
155
+ - **`approval_request`** reports a call a gate paused, with its signed `request` and the `input` that request signs, once every call of the step has been gated. That call gets no `tool_call_end`.
156
+ - **`hook_error`** reports an interceptor or an observer that threw, with the hook's name and the message. It also reports a pause that could not be signed, with `hook: "signer"`.
155
157
  - **`retry`** reports a failed request the gateway is retrying, and **`warning`** reports a reached cap or a model warning.
156
158
  - **`error`** and **`abort`** report a failed call and an abort request.
157
159
  - **`agent_settled`** fires once nothing is running any more, retries and tools included. **`run_end`** follows it and carries the result.
@@ -179,7 +181,7 @@ Every event carries `runId`, `stepIndex`, `signal` and `timestamp`, and the two
179
181
 
180
182
  ### A gate decides each tool call
181
183
 
182
- `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.
184
+ `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, so the model never sees a silent block. An `ask` pauses the call: the run ends `awaiting_approval` with a signed pending request, as the next section explains.
183
185
 
184
186
  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.
185
187
 
@@ -211,6 +213,55 @@ An observer that throws or rejects becomes a `hook_error` event with `hook: "obs
211
213
 
212
214
  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.
213
215
 
216
+ ## A gate that asks ends the run with a signed pending request
217
+
218
+ When a `beforeToolCall` gate returns `{ decision: "ask", reason, policyVersion }`, the run doesn't run that call, and doesn't block on a callback either. It signs a pending request for the call, finishes the step's other calls, and ends with `stopReason: "awaiting_approval"`. Store the request with the context, show it to a person with the input it signs, and check the answer against the signature before the call runs:
219
+
220
+ ```ts
221
+ const result = await run({ model, system, input, tools, interceptors: { beforeToolCall: gate }, signer }).result;
222
+ if (result.stopReason === "awaiting_approval") {
223
+ await store.save(result.context); // result.context.pending holds the same requests as result.pending
224
+ }
225
+ ```
226
+
227
+ Each request is a `SignedPendingRequest`. Its signature covers six fields: the request's `id`, its `kind`, the `callId`, the `tool`, the `inputHash` and the `policyVersion`. The input hash is `canonicalInputHash()` of the input the call would run with once approved, so a stored pause whose call, tool or input changed no longer verifies. That input is the model's after coercion, `repair` and any gate's replacement, so it can differ from the call's arguments in the transcript; the request stores only its hash, and `result.context.pendingInputs` and the `approval_request` event hold the input itself, by request id. Show the approver that input, not the model's arguments.
228
+
229
+ A gate's `ask` may carry its own `input`, which must pass the tool's schema, and `composeInterceptors()` passes an earlier gate's replacement on that way when a later gate asks, so the pause signs the input the earlier gate chose.
230
+
231
+ `reason` and `createdAt` are shown to people and are not signed, so never let them decide anything. `keyId` names the key that signed.
232
+
233
+ A paused call has no result in the transcript, so the context ends with the model's call still open. The step's other calls run or are denied as usual, and every call a gate paused gets its own request, in model order. A pause wins over an output tool that answered in the same step, because its call is still waiting. The run emits `approval_request` with the request and its input once every call of the step has been gated and before any of them runs. The call gets no `tool_call_end`, and the OpenTelemetry observer ends its tool span without an error. The event is advisory. A later call in the step can still fail the run with a programmer error, which ends it `error` with no `pending`, so build an approval queue from `result.pending`, not from the events.
234
+
235
+ `continueRun()` can't resume a paused context yet. It throws `invalid_run_options` for a context whose `pending` isn't empty, so a waiting call is never dropped without an answer. Store `pending` and `pendingInputs` with the messages, because the check reads `pending`. A context saved without it gets through, and the gateway answers the open call with an error result. The call never runs, and no person is asked.
236
+
237
+ ### Pass `hmacSigner()` wherever a pause may resume in another process
238
+
239
+ The run signs with its `signer` option. The default, `ephemeralSigner()`, holds a random key that lives only in this process. On a serverless host an isolate or function can be recycled between the pause and the answer, and another process rejects the signature as one from an unknown key. The default signer is also shared by every run in the process, and the signed fields name no run or tenant, so a host that serves several tenants in one process stores each tenant's requests apart and passes a signer of its own. Pass `hmacSigner({ keys, current })` over a key ring you keep there:
240
+
241
+ ```ts
242
+ const signer = hmacSigner({ keys: { "2026-11": key2611, "2026-12": key2612 }, current: "2026-12" });
243
+ ```
244
+
245
+ `hmacSigner()` signs with the key `current` names and verifies with any key in `keys`, each 32 bytes or more. To rotate, add a new key and make it current, and keep the old key in the ring until no stored pause names it. A request whose `keyId` isn't in the ring fails verification. Keys stay inside non-extractable Web Crypto keys: no error, event, result or span holds a key's bytes.
246
+
247
+ A pause that can't be signed is never written unsigned. If the signer throws, the call is blocked with an error result, and a `hook_error` with `hook: "signer"` names the cause without the signer's own message. A request id from `idGenerator` that repeats the run's id or an earlier request's is replaced by a random UUID, so a generator that always returns one id still pauses every call.
248
+
249
+ ### Sign a pause outside a run with `createPendingRequest()`
250
+
251
+ Code that makes a tool call itself, rather than through the model, can build the same record:
252
+
253
+ ```ts
254
+ const request = await createPendingRequest({ kind: "approval", callId, tool: "refund", input, reason }, signer);
255
+ ```
256
+
257
+ `createPendingRequest()` signs through the same code path as the loop, so for the same fields, id and signer the two requests are identical byte for byte. Its optional third argument takes `generateId` and `now`, which default to `crypto.randomUUID()` and the current time. It rejects with `invalid_run_options` for a `kind` other than `"approval"` or a signer that isn't an `ApprovalSigner`.
258
+
259
+ ### The signers and the record belong to the safety package
260
+
261
+ `ApprovalSigner`, `ephemeralSigner()`, `hmacSigner()`, `canonicalInputHash()`, `SignedPendingRequest`, `Resolution` and `SignPendingOptions` are `@buildanagent/agent-safety`'s, re-exported unchanged. So are `SafetyError` and `isSafetyError()`, because `hmacSigner()` throws a `SafetyError` with code `invalid_key_ring` for an unusable ring, and `createPendingRequest()` rejects with one, code `invalid_pending` or `invalid_input`, for a blank field or an input with no canonical JSON form.
262
+
263
+ Until the safety package is published, the SDK carries byte-identical copies of its files, and a test fails if they drift. One consequence follows from the copies: in a process that loads both packages, each has its own ephemeral signer, so a pause signed by one's default doesn't verify with the other's.
264
+
214
265
  ## Export a run as OpenTelemetry spans with `otelObserver()`
215
266
 
216
267
  `otelObserver()` turns a run's events into spans that follow the OpenTelemetry GenAI conventions, and it sends them only to the tracer you pass. Import it from `@buildanagent/sdk/otel` and add it to `observers`. Pass it in `observers`, not to `run.on()` later: an observer added late misses `run_start` and records nothing for that run.
package/dist/compose.d.ts CHANGED
@@ -8,7 +8,8 @@ import type { Interceptors } from "./hooks.js";
8
8
  * the system prompt, messages and options the earlier ones set. A field left `undefined` keeps the earlier value.
9
9
  * - `afterModelCall`: each hook sees the message the one before returned.
10
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.
11
+ * input one gate replaces is the input the next gate sees. When a gate asks, the `ask` carries the last
12
+ * replacement, so the pending request is signed over the input the call would run with.
12
13
  * - `afterToolCall`: the patches are applied in order, each hook seeing the result so far.
13
14
  * - `shouldStop`: the first `stop` wins; failing that, the first `continue`.
14
15
  *
package/dist/compose.js CHANGED
@@ -49,7 +49,8 @@ const after = (hooks) => async (e) => {
49
49
  };
50
50
  /**
51
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.
52
+ * and a replacement input from one gate is what the later gates see. The answer carries the last replacement, an
53
+ * `ask`'s included, so a pause signs the input the call would run with. A gate that throws makes the whole check fail.
53
54
  */
54
55
  const gate = (hooks) => async (e) => {
55
56
  let input = e.input;
@@ -60,10 +61,14 @@ const gate = (hooks) => async (e) => {
60
61
  return decision;
61
62
  if (decision.decision === "ask")
62
63
  asked ??= decision;
63
- else if (decision.input !== undefined)
64
+ if (decision.input !== undefined)
64
65
  input = decision.input;
65
66
  }
66
- return asked ?? { decision: "allow", ...(input === e.input ? {} : { input }) };
67
+ const replaced = input === e.input ? {} : { input };
68
+ // An ask carries the input the later gates saw, so the pause is signed over the input the call would run with.
69
+ if (asked !== undefined)
70
+ return { ...asked, ...replaced };
71
+ return { decision: "allow", ...replaced };
67
72
  };
68
73
  /** Applies the patches in order: each hook sees the result with the earlier patches applied. */
69
74
  const afterTool = (hooks) => async (e) => {
@@ -103,7 +108,8 @@ const stop = (hooks) => async (e) => {
103
108
  * the system prompt, messages and options the earlier ones set. A field left `undefined` keeps the earlier value.
104
109
  * - `afterModelCall`: each hook sees the message the one before returned.
105
110
  * - `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.
111
+ * input one gate replaces is the input the next gate sees. When a gate asks, the `ask` carries the last
112
+ * replacement, so the pending request is signed over the input the call would run with.
107
113
  * - `afterToolCall`: the patches are applied in order, each hook seeing the result so far.
108
114
  * - `shouldStop`: the first `stop` wins; failing that, the first `continue`.
109
115
  *
@@ -1 +1 @@
1
- {"version":3,"file":"compose.js","sourceRoot":"","sources":["../src/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AAK,CAAC,gBAAgB,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,SAAS,CAAC,KAAK,CAAC,gBAAgB,CAAC,EAAE,CAAC;QACvG,GAAG,CAAC,KAAK,CAAC,eAAe,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,EAAE,CAAC;QACjG,GAAG,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,KAAK,CAAC,CAAC,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"]}
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;AACxF,CAAC;AAED,sHAAsH;AACtH,sHAAsH;AACtH,6BAA6B;AAE7B,6GAA6G;AAC7G,SAAS,aAAa,CAAmB,KAAQ;IAC/C,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAe,CAAC;AAC5G,CAAC;AAED,qGAAqG;AACrG,MAAM,SAAS,GACb,CAAC,KAA0C,EAA4B,EAAE,CACzE,KAAK,EAAE,CAAC,EAAE,EAAE;IACV,IAAI,QAAQ,GAAuB,CAAC,CAAC,QAAQ,CAAC;IAC9C,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,QAAQ,GAAG,aAAa,CAAC,kBAAkB,EAAE,MAAM,IAAI,CAAC,EAAE,GAAG,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;IACvG,OAAO,QAAQ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C,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. The answer carries the last replacement, an\n * `ask`'s included, so a pause signs the input the call would run with. 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 if (decision.input !== undefined) input = decision.input;\n }\n const replaced = input === e.input ? {} : { input };\n // An ask carries the input the later gates saw, so the pause is signed over the input the call would run with.\n if (asked !== undefined) return { ...asked, ...replaced };\n return { decision: \"allow\", ...replaced };\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. When a gate asks, the `ask` carries the last\n * replacement, so the pending request is signed over the input the call would run with.\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
@@ -33,7 +33,8 @@ export declare class SdkError extends Error {
33
33
  export declare function isSdkError(error: unknown): error is SdkError;
34
34
  /**
35
35
  * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It
36
- * carries the whole result, and the context to continue from. It is an `SdkError` with code `run_stopped`.
36
+ * carries the whole result, and the context to continue from; `continueRun()` refuses a paused run's context until it
37
+ * can resume pauses. It is an `SdkError` with code `run_stopped`.
37
38
  */
38
39
  export declare class RunStoppedError extends SdkError {
39
40
  readonly name = "RunStoppedError";
package/dist/errors.js CHANGED
@@ -32,7 +32,8 @@ export function isSdkError(error) {
32
32
  const RUN_STOPPED_ERROR = Symbol.for("buildanagent.sdk.RunStoppedError");
33
33
  /**
34
34
  * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It
35
- * carries the whole result, and the context to continue from. It is an `SdkError` with code `run_stopped`.
35
+ * carries the whole result, and the context to continue from; `continueRun()` refuses a paused run's context until it
36
+ * can resume pauses. It is an `SdkError` with code `run_stopped`.
36
37
  */
37
38
  export class RunStoppedError extends SdkError {
38
39
  name = "RunStoppedError";
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAsBA,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACf,IAAI,GAAW,UAAU,CAAC;IACnC,IAAI,CAAe;IAE5B,YAAY,IAAkB,EAAE,OAAe,EAAE,OAAsB;QACrE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1D,CAAC;CACF;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;AAC/G,CAAC;AAED,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;AAEzE;;;GAGG;AACH,MAAM,OAAO,eAAgB,SAAQ,QAAQ;IACzB,IAAI,GAAG,iBAAiB,CAAC;IAClC,UAAU,CAAiC;IAC3C,MAAM,CAAmB;IAClC,0DAA0D;IACjD,OAAO,CAAU;IAE1B,YAAY,MAAwB;QAClC,KAAK,CAAC,aAAa,EAAE,yBAAyB,MAAM,CAAC,UAAU,WAAW,MAAM,CAAC,KAAK,cAAc,CAAC,CAAC;QACtG,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;QACpC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;QAC9B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,iBAAiB,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAClE,CAAC;IAED,qHAAqH;IACrH,MAAM,CAAC,UAAU,CAAC,KAAc;QAC9B,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,iBAAiB,CAAC,KAAK,IAAI,CAC9G,CAAC;IACJ,CAAC;CACF","sourcesContent":["/**\n * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool\n * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never\n * thrown: the tool pipeline returns it to the model as an error result. Two subclasses keep their own names:\n * `RunStoppedError`, which `runOrThrow()` throws for a run that did not finish, and the testing export's\n * `UnexpectedModelCallError`.\n */\nimport type { Context, UnfinishedResult } from \"./result.js\";\n\n/** Why an `SdkError` was thrown. */\nexport type SdkErrorCode =\n | \"invalid_tool_definition\"\n | \"invalid_tool_result\"\n | \"invalid_run_options\"\n | \"invalid_model_stream\"\n | \"max_depth_exceeded\"\n | \"invalid_hook_result\"\n | \"hook_failed\"\n | \"run_stopped\"\n | \"undelivered_message\"\n | \"unexpected_model_call\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SDK_ERROR = Symbol.for(\"buildanagent.sdk.SdkError\");\n\n/**\n * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema,\n * exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name. `invalid_tool_result`: a tool's\n * `execute` returned a malformed result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an\n * option it can't use, such as a model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended\n * without a final message. `max_depth_exceeded`: a tool started a run nested deeper than `maxDepth` allows.\n * `invalid_hook_result`: an interceptor returned something its type does not allow, such as\n * a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor\n * threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,\n * so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a\n * `RunStoppedError`).\n * `undelivered_message`: `steer()` or `followUp()` was called on a run that had ended, or the run ended before it\n * could apply the message.\n * `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an\n * `UnexpectedModelCallError`).\n */\nexport class SdkError extends Error {\n override readonly name: string = \"SdkError\";\n readonly code: SdkErrorCode;\n\n constructor(code: SdkErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SDK_ERROR, { value: true });\n }\n}\n\n/** True for an `SdkError`, including one from another copy of the package. */\nexport function isSdkError(error: unknown): error is SdkError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SDK_ERROR] === true;\n}\n\nconst RUN_STOPPED_ERROR = Symbol.for(\"buildanagent.sdk.RunStoppedError\");\n\n/**\n * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It\n * carries the whole result, and the context to continue from. It is an `SdkError` with code `run_stopped`.\n */\nexport class RunStoppedError extends SdkError {\n override readonly name = \"RunStoppedError\";\n readonly stopReason: UnfinishedResult[\"stopReason\"];\n readonly result: UnfinishedResult;\n /** The conversation so far, ready for `continueRun()`. */\n readonly context: Context;\n\n constructor(result: UnfinishedResult) {\n super(\"run_stopped\", `the run stopped with \"${result.stopReason}\" after ${result.steps} model calls`);\n this.stopReason = result.stopReason;\n this.result = result;\n this.context = result.context;\n Object.defineProperty(this, RUN_STOPPED_ERROR, { value: true });\n }\n\n /** True for a `RunStoppedError`, including one from another copy of the package. Use it in place of `instanceof`. */\n static isInstance(error: unknown): error is RunStoppedError {\n return (\n typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[RUN_STOPPED_ERROR] === true\n );\n }\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAsBA,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACf,IAAI,GAAW,UAAU,CAAC;IACnC,IAAI,CAAe;IAE5B,YAAY,IAAkB,EAAE,OAAe,EAAE,OAAsB;QACrE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1D,CAAC;CACF;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;AAC/G,CAAC;AAED,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;AAEzE;;;;GAIG;AACH,MAAM,OAAO,eAAgB,SAAQ,QAAQ;IACzB,IAAI,GAAG,iBAAiB,CAAC;IAClC,UAAU,CAAiC;IAC3C,MAAM,CAAmB;IAClC,0DAA0D;IACjD,OAAO,CAAU;IAE1B,YAAY,MAAwB;QAClC,KAAK,CAAC,aAAa,EAAE,yBAAyB,MAAM,CAAC,UAAU,WAAW,MAAM,CAAC,KAAK,cAAc,CAAC,CAAC;QACtG,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;QACpC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;QAC9B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,iBAAiB,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAClE,CAAC;IAED,qHAAqH;IACrH,MAAM,CAAC,UAAU,CAAC,KAAc;QAC9B,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,iBAAiB,CAAC,KAAK,IAAI,CAC9G,CAAC;IACJ,CAAC;CACF","sourcesContent":["/**\n * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool\n * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never\n * thrown: the tool pipeline returns it to the model as an error result. Two subclasses keep their own names:\n * `RunStoppedError`, which `runOrThrow()` throws for a run that did not finish, and the testing export's\n * `UnexpectedModelCallError`.\n */\nimport type { Context, UnfinishedResult } from \"./result.js\";\n\n/** Why an `SdkError` was thrown. */\nexport type SdkErrorCode =\n | \"invalid_tool_definition\"\n | \"invalid_tool_result\"\n | \"invalid_run_options\"\n | \"invalid_model_stream\"\n | \"max_depth_exceeded\"\n | \"invalid_hook_result\"\n | \"hook_failed\"\n | \"run_stopped\"\n | \"undelivered_message\"\n | \"unexpected_model_call\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SDK_ERROR = Symbol.for(\"buildanagent.sdk.SdkError\");\n\n/**\n * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema,\n * exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name. `invalid_tool_result`: a tool's\n * `execute` returned a malformed result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an\n * option it can't use, such as a model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended\n * without a final message. `max_depth_exceeded`: a tool started a run nested deeper than `maxDepth` allows.\n * `invalid_hook_result`: an interceptor returned something its type does not allow, such as\n * a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor\n * threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,\n * so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a\n * `RunStoppedError`).\n * `undelivered_message`: `steer()` or `followUp()` was called on a run that had ended, or the run ended before it\n * could apply the message.\n * `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an\n * `UnexpectedModelCallError`).\n */\nexport class SdkError extends Error {\n override readonly name: string = \"SdkError\";\n readonly code: SdkErrorCode;\n\n constructor(code: SdkErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SDK_ERROR, { value: true });\n }\n}\n\n/** True for an `SdkError`, including one from another copy of the package. */\nexport function isSdkError(error: unknown): error is SdkError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SDK_ERROR] === true;\n}\n\nconst RUN_STOPPED_ERROR = Symbol.for(\"buildanagent.sdk.RunStoppedError\");\n\n/**\n * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It\n * carries the whole result, and the context to continue from; `continueRun()` refuses a paused run's context until it\n * can resume pauses. 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
@@ -8,6 +8,7 @@ import type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, Model
8
8
  import type { RunError, RunResult } from "./result.js";
9
9
  import type { DeliveryReceipt } from "./steering.js";
10
10
  import type { ToolResult } from "./tools/types.js";
11
+ import type { SignedPendingRequest } from "./vendor/agent-safety/pending.js";
11
12
  /** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */
12
13
  export interface EventBase {
13
14
  readonly runId: string;
@@ -108,9 +109,22 @@ export type AgentEventBody = {
108
109
  readonly receipt: DeliveryReceipt;
109
110
  }
110
111
  /**
111
- * An interceptor or an observer threw. `hook` names it (`beforeToolCall`, `observer` and so on) and `error` is the
112
- * thrown message. The run goes on or fails by the interceptors' `onFailure` setting; a failed observer never
113
- * affects it.
112
+ * A gate returned `ask` and the run signed a pending request for the call, which waits for a person. `input` is
113
+ * the input the request signs and the call would run with once approved: the model's input after coercion,
114
+ * `repair` and any gate's replacement, so show the approver this, not the model's raw arguments. It comes once every
115
+ * call of the step has been gated, after the call's `tool_call_start` and before any call of the step runs, and the
116
+ * call gets no `tool_call_end`: it doesn't run in this run. The run ends `awaiting_approval` after the step.
117
+ */
118
+ | {
119
+ readonly type: "approval_request";
120
+ readonly request: SignedPendingRequest;
121
+ readonly input: unknown;
122
+ }
123
+ /**
124
+ * An interceptor or an observer threw, or a pause could not be signed. `hook` names it (`beforeToolCall`,
125
+ * `observer`, `signer` and so on) and `error` is the thrown message; for `signer` it is a fixed text with the
126
+ * safety package's error code, never the signer's own message. The run goes on or fails by the interceptors'
127
+ * `onFailure` setting; a failed observer never affects it, and a call whose pause could not be signed is blocked.
114
128
  */
115
129
  | {
116
130
  readonly type: "hook_error";
@@ -130,4 +144,4 @@ export type AgentEventBody = {
130
144
  /** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */
131
145
  export type AgentEvent = EventBase & AgentEventBody;
132
146
  /** Every `AgentEvent` type. A run emits no type this list lacks. */
133
- export declare const AGENT_EVENT_TYPES: readonly ["run_start", "step_start", "model_call_start", "retry", "text_start", "text_delta", "text_end", "reasoning_start", "reasoning_delta", "reasoning_end", "tool_input_start", "tool_input_delta", "tool_input_end", "warning", "model_call_end", "context_transformed", "hook_error", "steer_applied", "tool_call_start", "tool_call_update", "tool_call_end", "step_end", "error", "abort", "agent_settled", "run_end"];
147
+ export declare const AGENT_EVENT_TYPES: readonly ["run_start", "step_start", "model_call_start", "retry", "text_start", "text_delta", "text_end", "reasoning_start", "reasoning_delta", "reasoning_end", "tool_input_start", "tool_input_delta", "tool_input_end", "warning", "model_call_end", "context_transformed", "hook_error", "steer_applied", "tool_call_start", "approval_request", "tool_call_update", "tool_call_end", "step_end", "error", "abort", "agent_settled", "run_end"];
package/dist/events.js CHANGED
@@ -19,6 +19,7 @@ export const AGENT_EVENT_TYPES = Object.freeze([
19
19
  "hook_error",
20
20
  "steer_applied",
21
21
  "tool_call_start",
22
+ "approval_request",
22
23
  "tool_call_update",
23
24
  "tool_call_end",
24
25
  "step_end",
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAiGA,oEAAoE;AACpE,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC7C,WAAW;IACX,YAAY;IACZ,kBAAkB;IAClB,OAAO;IACP,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,iBAAiB;IACjB,iBAAiB;IACjB,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,gBAAgB;IAChB,SAAS;IACT,gBAAgB;IAChB,qBAAqB;IACrB,YAAY;IACZ,eAAe;IACf,iBAAiB;IACjB,kBAAkB;IAClB,eAAe;IACf,UAAU;IACV,OAAO;IACP,OAAO;IACP,eAAe;IACf,SAAS;CACuC,CAAC,CAAC","sourcesContent":["/**\n * The events a run streams: one closed union in two layers (agent-SDK guide §5). The delta layer streams each content\n * block by its index; the item layer's end events (`model_call_end`, `tool_call_end`, `run_end`) carry the\n * authoritative item, which a session log stores. `AGENT_EVENT_TYPES` lists the union at run time, so a test can\n * check that the loop emits no type the union does not declare.\n */\nimport type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from \"@buildanagent/gateway\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { DeliveryReceipt } from \"./steering.js\";\nimport type { ToolResult } from \"./tools/types.js\";\n\n/** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */\nexport interface EventBase {\n readonly runId: string;\n readonly seq: number;\n readonly stepIndex: number;\n /** When the event was emitted, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** One model call's request as the loop sends it: the model, the context and the options. */\nexport interface ModelCallRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: DumpedOptions;\n}\n\n/**\n * Why a `warning` event fired. `max_steps`: the run reached `maxSteps` and stopped. `model_warning`: the model call\n * reported something that did not stop it, such as an option the provider would reject and the adapter dropped.\n */\nexport type WarningCode = \"max_steps\" | \"model_warning\";\n\n/** The body of each event, without the fields of `EventBase`. */\nexport type AgentEventBody =\n | {\n readonly type: \"run_start\";\n readonly sdkVersion: string;\n readonly specVersion: \"v1\";\n /** Reserved for a hash of the run's defaults; empty for now. */\n readonly defaultsHash: string;\n /** Reserved for the SDK's capability names; empty for now. */\n readonly capabilities: readonly string[];\n readonly model: ModelRef;\n }\n | { readonly type: \"run_end\"; readonly result: RunResult }\n /** Fires once nothing is running any more, retries and tools included; `run_end` follows it. */\n | { readonly type: \"agent_settled\" }\n | { readonly type: \"step_start\" }\n | { readonly type: \"step_end\"; readonly stopCheck: \"continue\" | \"stop\" }\n | { readonly type: \"model_call_start\"; readonly request: ModelCallRequest }\n | { readonly type: \"model_call_end\"; readonly message: AssistantMessage }\n | { readonly type: \"text_start\" | \"reasoning_start\" | \"tool_input_start\"; readonly index: number }\n | {\n readonly type: \"text_delta\" | \"reasoning_delta\" | \"tool_input_delta\";\n readonly index: number;\n readonly delta: string;\n }\n | {\n readonly type: \"text_end\" | \"reasoning_end\" | \"tool_input_end\";\n readonly index: number;\n readonly block: ContentBlock;\n }\n | { readonly type: \"tool_call_start\"; readonly callId: string; readonly tool: string; readonly input: unknown }\n | { readonly type: \"tool_call_update\"; readonly callId: string; readonly details: unknown }\n /**\n * `result` is what the model reads for the call, after `afterToolCall` has had its say. `input` is present only\n * when a `beforeToolCall` gate replaced the model's input, and holds the input the gate gave the call instead.\n */\n | {\n readonly type: \"tool_call_end\";\n readonly callId: string;\n readonly result: ToolResult;\n readonly input?: unknown;\n }\n /** `transformContext` returned the messages for one model call: `before` messages in, `after` messages out. */\n | { readonly type: \"context_transformed\"; readonly before: number; readonly after: number }\n /** The model is retrying a failed request; `attempt` is 1 for the first retry. */\n | { readonly type: \"retry\"; readonly attempt: number; readonly delayMs: number; readonly error: string }\n /**\n * A queued steer or follow-up entered the transcript as a user message, at the start of the step named by\n * `receipt.stepIndex`, before its model call. `receipt.kind` tells the two apart.\n */\n | { readonly type: \"steer_applied\"; readonly receipt: DeliveryReceipt }\n /**\n * An interceptor or an observer threw. `hook` names it (`beforeToolCall`, `observer` and so on) and `error` is the\n * thrown message. The run goes on or fails by the interceptors' `onFailure` setting; a failed observer never\n * affects it.\n */\n | { readonly type: \"hook_error\"; readonly hook: string; readonly error: string }\n | { readonly type: \"warning\"; readonly code: WarningCode; readonly detail: string }\n | { readonly type: \"error\"; readonly error: RunError }\n | { readonly type: \"abort\"; readonly reason?: string };\n\n/** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */\nexport type AgentEvent = EventBase & AgentEventBody;\n\n/** Every `AgentEvent` type. A run emits no type this list lacks. */\nexport const AGENT_EVENT_TYPES = Object.freeze([\n \"run_start\",\n \"step_start\",\n \"model_call_start\",\n \"retry\",\n \"text_start\",\n \"text_delta\",\n \"text_end\",\n \"reasoning_start\",\n \"reasoning_delta\",\n \"reasoning_end\",\n \"tool_input_start\",\n \"tool_input_delta\",\n \"tool_input_end\",\n \"warning\",\n \"model_call_end\",\n \"context_transformed\",\n \"hook_error\",\n \"steer_applied\",\n \"tool_call_start\",\n \"tool_call_update\",\n \"tool_call_end\",\n \"step_end\",\n \"error\",\n \"abort\",\n \"agent_settled\",\n \"run_end\",\n] as const satisfies readonly AgentEvent[\"type\"][]);\n"]}
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AA2GA,oEAAoE;AACpE,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC7C,WAAW;IACX,YAAY;IACZ,kBAAkB;IAClB,OAAO;IACP,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,iBAAiB;IACjB,iBAAiB;IACjB,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,gBAAgB;IAChB,SAAS;IACT,gBAAgB;IAChB,qBAAqB;IACrB,YAAY;IACZ,eAAe;IACf,iBAAiB;IACjB,kBAAkB;IAClB,kBAAkB;IAClB,eAAe;IACf,UAAU;IACV,OAAO;IACP,OAAO;IACP,eAAe;IACf,SAAS;CACuC,CAAC,CAAC","sourcesContent":["/**\n * The events a run streams: one closed union in two layers (agent-SDK guide §5). The delta layer streams each content\n * block by its index; the item layer's end events (`model_call_end`, `tool_call_end`, `run_end`) carry the\n * authoritative item, which a session log stores. `AGENT_EVENT_TYPES` lists the union at run time, so a test can\n * check that the loop emits no type the union does not declare.\n */\nimport type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from \"@buildanagent/gateway\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { DeliveryReceipt } from \"./steering.js\";\nimport type { ToolResult } from \"./tools/types.js\";\nimport type { SignedPendingRequest } from \"./vendor/agent-safety/pending.js\";\n\n/** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */\nexport interface EventBase {\n readonly runId: string;\n readonly seq: number;\n readonly stepIndex: number;\n /** When the event was emitted, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** One model call's request as the loop sends it: the model, the context and the options. */\nexport interface ModelCallRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: DumpedOptions;\n}\n\n/**\n * Why a `warning` event fired. `max_steps`: the run reached `maxSteps` and stopped. `model_warning`: the model call\n * reported something that did not stop it, such as an option the provider would reject and the adapter dropped.\n */\nexport type WarningCode = \"max_steps\" | \"model_warning\";\n\n/** The body of each event, without the fields of `EventBase`. */\nexport type AgentEventBody =\n | {\n readonly type: \"run_start\";\n readonly sdkVersion: string;\n readonly specVersion: \"v1\";\n /** Reserved for a hash of the run's defaults; empty for now. */\n readonly defaultsHash: string;\n /** Reserved for the SDK's capability names; empty for now. */\n readonly capabilities: readonly string[];\n readonly model: ModelRef;\n }\n | { readonly type: \"run_end\"; readonly result: RunResult }\n /** Fires once nothing is running any more, retries and tools included; `run_end` follows it. */\n | { readonly type: \"agent_settled\" }\n | { readonly type: \"step_start\" }\n | { readonly type: \"step_end\"; readonly stopCheck: \"continue\" | \"stop\" }\n | { readonly type: \"model_call_start\"; readonly request: ModelCallRequest }\n | { readonly type: \"model_call_end\"; readonly message: AssistantMessage }\n | { readonly type: \"text_start\" | \"reasoning_start\" | \"tool_input_start\"; readonly index: number }\n | {\n readonly type: \"text_delta\" | \"reasoning_delta\" | \"tool_input_delta\";\n readonly index: number;\n readonly delta: string;\n }\n | {\n readonly type: \"text_end\" | \"reasoning_end\" | \"tool_input_end\";\n readonly index: number;\n readonly block: ContentBlock;\n }\n | { readonly type: \"tool_call_start\"; readonly callId: string; readonly tool: string; readonly input: unknown }\n | { readonly type: \"tool_call_update\"; readonly callId: string; readonly details: unknown }\n /**\n * `result` is what the model reads for the call, after `afterToolCall` has had its say. `input` is present only\n * when a `beforeToolCall` gate replaced the model's input, and holds the input the gate gave the call instead.\n */\n | {\n readonly type: \"tool_call_end\";\n readonly callId: string;\n readonly result: ToolResult;\n readonly input?: unknown;\n }\n /** `transformContext` returned the messages for one model call: `before` messages in, `after` messages out. */\n | { readonly type: \"context_transformed\"; readonly before: number; readonly after: number }\n /** The model is retrying a failed request; `attempt` is 1 for the first retry. */\n | { readonly type: \"retry\"; readonly attempt: number; readonly delayMs: number; readonly error: string }\n /**\n * A queued steer or follow-up entered the transcript as a user message, at the start of the step named by\n * `receipt.stepIndex`, before its model call. `receipt.kind` tells the two apart.\n */\n | { readonly type: \"steer_applied\"; readonly receipt: DeliveryReceipt }\n /**\n * A gate returned `ask` and the run signed a pending request for the call, which waits for a person. `input` is\n * the input the request signs and the call would run with once approved: the model's input after coercion,\n * `repair` and any gate's replacement, so show the approver this, not the model's raw arguments. It comes once every\n * call of the step has been gated, after the call's `tool_call_start` and before any call of the step runs, and the\n * call gets no `tool_call_end`: it doesn't run in this run. The run ends `awaiting_approval` after the step.\n */\n | { readonly type: \"approval_request\"; readonly request: SignedPendingRequest; readonly input: unknown }\n /**\n * An interceptor or an observer threw, or a pause could not be signed. `hook` names it (`beforeToolCall`,\n * `observer`, `signer` and so on) and `error` is the thrown message; for `signer` it is a fixed text with the\n * safety package's error code, never the signer's own message. The run goes on or fails by the interceptors'\n * `onFailure` setting; a failed observer never affects it, and a call whose pause could not be signed is blocked.\n */\n | { readonly type: \"hook_error\"; readonly hook: string; readonly error: string }\n | { readonly type: \"warning\"; readonly code: WarningCode; readonly detail: string }\n | { readonly type: \"error\"; readonly error: RunError }\n | { readonly type: \"abort\"; readonly reason?: string };\n\n/** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */\nexport type AgentEvent = EventBase & AgentEventBody;\n\n/** Every `AgentEvent` type. A run emits no type this list lacks. */\nexport const AGENT_EVENT_TYPES = Object.freeze([\n \"run_start\",\n \"step_start\",\n \"model_call_start\",\n \"retry\",\n \"text_start\",\n \"text_delta\",\n \"text_end\",\n \"reasoning_start\",\n \"reasoning_delta\",\n \"reasoning_end\",\n \"tool_input_start\",\n \"tool_input_delta\",\n \"tool_input_end\",\n \"warning\",\n \"model_call_end\",\n \"context_transformed\",\n \"hook_error\",\n \"steer_applied\",\n \"tool_call_start\",\n \"approval_request\",\n \"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"]}
@@ -55,6 +55,21 @@ export function checkReplacement(value) {
55
55
  }
56
56
  return message;
57
57
  }
58
+ /**
59
+ * Checks the fields an `ask` adds, so a gate's own mistake is reported as one and not as a signer that failed.
60
+ * `policyVersion` is signed, so it must be a non-empty, well-formed string; `reason` is display text, which the pause
61
+ * leaves out when it is blank.
62
+ */
63
+ function checkAsk(value) {
64
+ const { reason, policyVersion } = value;
65
+ if (reason !== undefined && typeof reason !== "string") {
66
+ invalid("beforeToolCall", "returned ask with a reason that is not a string");
67
+ }
68
+ if (policyVersion !== undefined &&
69
+ (typeof policyVersion !== "string" || policyVersion === "" || !policyVersion.isWellFormed())) {
70
+ invalid("beforeToolCall", "returned ask with a policyVersion that is not a non-empty, well-formed string");
71
+ }
72
+ }
58
73
  /** Checks `beforeToolCall`'s decision. */
59
74
  export function checkDecision(value) {
60
75
  if (!isObject(value))
@@ -65,6 +80,8 @@ export function checkDecision(value) {
65
80
  }
66
81
  if (decision === "deny" && typeof reason !== "string")
67
82
  invalid("beforeToolCall", "returned deny without a reason");
83
+ if (decision === "ask")
84
+ checkAsk(value);
68
85
  return value;
69
86
  }
70
87
  /** Checks `afterToolCall`'s patch. */
@@ -1 +1 @@
1
- {"version":3,"file":"hook-checks.js","sourceRoot":"","sources":["../src/hook-checks.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,SAAS,OAAO,CAAC,IAAY,EAAE,OAAe;IAC5C,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,GAAG,IAAI,IAAI,OAAO,EAAE,CAAC,CAAC;AAClE,CAAC;AAED,SAAS,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D,CAAC","sourcesContent":["/**\n * Checks on what an interceptor returned. A hook that returns the wrong shape is a programmer error, so each check\n * throws an `SdkError` with code `invalid_hook_result` rather than failing closed: a typo in a gate must be loud.\n */\nimport type { AssistantMessage, ContentBlock, Message, Model } from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\nimport type { GateDecision, ModelCallPatch, StopDecision } from \"./hooks.js\";\nimport { isContentList } from \"./tools/pipeline.js\";\n\nfunction invalid(hook: string, problem: string): never {\n throw new SdkError(\"invalid_hook_result\", `${hook} ${problem}`);\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isMessage(value: unknown): value is Message {\n if (!isObject(value)) return false;\n if (value.role === \"tool\") return typeof value.callId === \"string\" && Array.isArray(value.content);\n return (value.role === \"user\" || value.role === \"assistant\") && Array.isArray(value.content);\n}\n\n/** Checks a list of messages and returns a copy of it. */\nexport function checkMessages(hook: string, value: unknown): Message[] {\n if (!Array.isArray(value) || !value.every(isMessage)) {\n invalid(hook, \"must return a list of messages, each with a role and content\");\n }\n return [...value];\n}\n\n/** Checks `beforeModelCall`'s return value: nothing, or a patch of well-formed fields. */\nexport function checkModelPatch(value: unknown): ModelCallPatch | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) invalid(\"beforeModelCall\", \"must return a patch object or nothing\");\n const { system, messages, activeTools, model, options } = value;\n if (system !== undefined && typeof system !== \"string\")\n invalid(\"beforeModelCall\", \"returned a system that is not a string\");\n if (messages !== undefined) checkMessages(\"beforeModelCall\", messages);\n if (activeTools !== undefined && !(Array.isArray(activeTools) && activeTools.every((n) => typeof n === \"string\"))) {\n invalid(\"beforeModelCall\", \"returned activeTools that is not a list of tool names\");\n }\n if (model !== undefined && typeof (model as Partial<Model> | null)?.stream !== \"function\") {\n invalid(\"beforeModelCall\", \"returned a model that is not from createModel()\");\n }\n if (options !== undefined && !isObject(options))\n invalid(\"beforeModelCall\", \"returned options that are not an object\");\n return value as ModelCallPatch;\n}\n\n/** Checks `afterModelCall`'s return value and returns the replacement message, if there is one. */\nexport function checkReplacement(value: unknown): AssistantMessage | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) invalid(\"afterModelCall\", \"must return { message } or nothing\");\n const { message } = value;\n if (message === undefined) return undefined;\n if (!isObject(message) || message.role !== \"assistant\" || !Array.isArray(message.content)) {\n invalid(\"afterModelCall\", \"returned a message that is not an assistant message\");\n }\n return message as unknown as AssistantMessage;\n}\n\n/** Checks `beforeToolCall`'s decision. */\nexport function checkDecision(value: unknown): GateDecision {\n if (!isObject(value)) invalid(\"beforeToolCall\", \"must return a decision: allow, deny or ask\");\n const { decision, reason } = value;\n if (decision !== \"allow\" && decision !== \"deny\" && decision !== \"ask\") {\n invalid(\"beforeToolCall\", `returned the decision ${JSON.stringify(decision)}; it must be allow, deny or ask`);\n }\n if (decision === \"deny\" && typeof reason !== \"string\") invalid(\"beforeToolCall\", \"returned deny without a reason\");\n return value as unknown as GateDecision;\n}\n\n/** Checks `afterToolCall`'s patch. */\nexport function checkResultPatch(value: unknown): Record<string, unknown> | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) invalid(\"afterToolCall\", \"must return a patch object or nothing\");\n if (\"outcome\" in value) invalid(\"afterToolCall\", \"returned an outcome; replace content instead\");\n for (const flag of [\"isError\", \"terminate\"] as const) {\n if (value[flag] !== undefined && typeof value[flag] !== \"boolean\") {\n invalid(\"afterToolCall\", `returned ${flag} that is not a boolean`);\n }\n }\n return value;\n}\n\n/** What the run does after `shouldStop`. */\nexport type StopVerdict =\n | { readonly kind: \"none\" }\n | { readonly kind: \"stop\"; readonly stoppedBy: string }\n | { readonly kind: \"no_progress\"; readonly reason: string }\n | { readonly kind: \"continue\"; readonly content: ContentBlock[] };\n\n// The continue content becomes a user message in the transcript, so a malformed block would fail a later request far\n// from the hook that returned it.\nfunction continueContent(value: string | readonly ContentBlock[]): ContentBlock[] {\n if (typeof value === \"string\") return [{ type: \"text\", text: value }];\n if (!isContentList(value)) {\n invalid(\"shouldStop\", \"returned a continue that is neither text nor a list of text and image blocks\");\n }\n return [...value];\n}\n\n/** Checks `shouldStop`'s decision and turns it into a verdict. */\nexport function checkStopDecision(value: unknown): StopVerdict {\n if (value === true) return { kind: \"stop\", stoppedBy: \"hook\" };\n if (value === false) return { kind: \"none\" };\n if (!isObject(value)) invalid(\"shouldStop\", \"must return a boolean, { continue } or { stop, reason }\");\n const decision = value as Exclude<StopDecision, boolean>;\n if (\"continue\" in decision) return { kind: \"continue\", content: continueContent(decision.continue) };\n if (typeof decision.reason !== \"string\" || (decision.stop !== \"hook\" && decision.stop !== \"no_progress\")) {\n invalid(\"shouldStop\", 'returned a stop that is not { stop: \"hook\" | \"no_progress\", reason }');\n }\n return decision.stop === \"hook\"\n ? { kind: \"stop\", stoppedBy: decision.reason }\n : { kind: \"no_progress\", reason: decision.reason };\n}\n"]}
1
+ {"version":3,"file":"hook-checks.js","sourceRoot":"","sources":["../src/hook-checks.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,SAAS,OAAO,CAAC,IAAY,EAAE,OAAe;IAC5C,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,GAAG,IAAI,IAAI,OAAO,EAAE,CAAC,CAAC;AAClE,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,SAAS,CAAC,KAAc;IAC/B,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACnC,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,OAAO,KAAK,CAAC,MAAM,KAAK,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AAC,IAAI,KAAK,MAAM;QAC7B,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC,MAAM,EAAE;QAC9C,CAAC,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;AACvD,CAAC","sourcesContent":["/**\n * Checks on what an interceptor returned. A hook that returns the wrong shape is a programmer error, so each check\n * throws an `SdkError` with code `invalid_hook_result` rather than failing closed: a typo in a gate must be loud.\n */\nimport type { AssistantMessage, ContentBlock, Message, Model } from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\nimport type { GateDecision, ModelCallPatch, StopDecision } from \"./hooks.js\";\nimport { isContentList } from \"./tools/pipeline.js\";\n\nfunction invalid(hook: string, problem: string): never {\n throw new SdkError(\"invalid_hook_result\", `${hook} ${problem}`);\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isMessage(value: unknown): value is Message {\n if (!isObject(value)) return false;\n if (value.role === \"tool\") return typeof value.callId === \"string\" && Array.isArray(value.content);\n return (value.role === \"user\" || value.role === \"assistant\") && Array.isArray(value.content);\n}\n\n/** Checks a list of messages and returns a copy of it. */\nexport function checkMessages(hook: string, value: unknown): Message[] {\n if (!Array.isArray(value) || !value.every(isMessage)) {\n invalid(hook, \"must return a list of messages, each with a role and content\");\n }\n return [...value];\n}\n\n/** Checks `beforeModelCall`'s return value: nothing, or a patch of well-formed fields. */\nexport function checkModelPatch(value: unknown): ModelCallPatch | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) invalid(\"beforeModelCall\", \"must return a patch object or nothing\");\n const { system, messages, activeTools, model, options } = value;\n if (system !== undefined && typeof system !== \"string\")\n invalid(\"beforeModelCall\", \"returned a system that is not a string\");\n if (messages !== undefined) checkMessages(\"beforeModelCall\", messages);\n if (activeTools !== undefined && !(Array.isArray(activeTools) && activeTools.every((n) => typeof n === \"string\"))) {\n invalid(\"beforeModelCall\", \"returned activeTools that is not a list of tool names\");\n }\n if (model !== undefined && typeof (model as Partial<Model> | null)?.stream !== \"function\") {\n invalid(\"beforeModelCall\", \"returned a model that is not from createModel()\");\n }\n if (options !== undefined && !isObject(options))\n invalid(\"beforeModelCall\", \"returned options that are not an object\");\n return value as ModelCallPatch;\n}\n\n/** Checks `afterModelCall`'s return value and returns the replacement message, if there is one. */\nexport function checkReplacement(value: unknown): AssistantMessage | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) invalid(\"afterModelCall\", \"must return { message } or nothing\");\n const { message } = value;\n if (message === undefined) return undefined;\n if (!isObject(message) || message.role !== \"assistant\" || !Array.isArray(message.content)) {\n invalid(\"afterModelCall\", \"returned a message that is not an assistant message\");\n }\n return message as unknown as AssistantMessage;\n}\n\n/**\n * Checks the fields an `ask` adds, so a gate's own mistake is reported as one and not as a signer that failed.\n * `policyVersion` is signed, so it must be a non-empty, well-formed string; `reason` is display text, which the pause\n * leaves out when it is blank.\n */\nfunction checkAsk(value: Record<string, unknown>): void {\n const { reason, policyVersion } = value;\n if (reason !== undefined && typeof reason !== \"string\") {\n invalid(\"beforeToolCall\", \"returned ask with a reason that is not a string\");\n }\n if (\n policyVersion !== undefined &&\n (typeof policyVersion !== \"string\" || policyVersion === \"\" || !policyVersion.isWellFormed())\n ) {\n invalid(\"beforeToolCall\", \"returned ask with a policyVersion that is not a non-empty, well-formed string\");\n }\n}\n\n/** Checks `beforeToolCall`'s decision. */\nexport function checkDecision(value: unknown): GateDecision {\n if (!isObject(value)) invalid(\"beforeToolCall\", \"must return a decision: allow, deny or ask\");\n const { decision, reason } = value;\n if (decision !== \"allow\" && decision !== \"deny\" && decision !== \"ask\") {\n invalid(\"beforeToolCall\", `returned the decision ${JSON.stringify(decision)}; it must be allow, deny or ask`);\n }\n if (decision === \"deny\" && typeof reason !== \"string\") invalid(\"beforeToolCall\", \"returned deny without a reason\");\n if (decision === \"ask\") checkAsk(value);\n return value as unknown as GateDecision;\n}\n\n/** Checks `afterToolCall`'s patch. */\nexport function checkResultPatch(value: unknown): Record<string, unknown> | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) invalid(\"afterToolCall\", \"must return a patch object or nothing\");\n if (\"outcome\" in value) invalid(\"afterToolCall\", \"returned an outcome; replace content instead\");\n for (const flag of [\"isError\", \"terminate\"] as const) {\n if (value[flag] !== undefined && typeof value[flag] !== \"boolean\") {\n invalid(\"afterToolCall\", `returned ${flag} that is not a boolean`);\n }\n }\n return value;\n}\n\n/** What the run does after `shouldStop`. */\nexport type StopVerdict =\n | { readonly kind: \"none\" }\n | { readonly kind: \"stop\"; readonly stoppedBy: string }\n | { readonly kind: \"no_progress\"; readonly reason: string }\n | { readonly kind: \"continue\"; readonly content: ContentBlock[] };\n\n// The continue content becomes a user message in the transcript, so a malformed block would fail a later request far\n// from the hook that returned it.\nfunction continueContent(value: string | readonly ContentBlock[]): ContentBlock[] {\n if (typeof value === \"string\") return [{ type: \"text\", text: value }];\n if (!isContentList(value)) {\n invalid(\"shouldStop\", \"returned a continue that is neither text nor a list of text and image blocks\");\n }\n return [...value];\n}\n\n/** Checks `shouldStop`'s decision and turns it into a verdict. */\nexport function checkStopDecision(value: unknown): StopVerdict {\n if (value === true) return { kind: \"stop\", stoppedBy: \"hook\" };\n if (value === false) return { kind: \"none\" };\n if (!isObject(value)) invalid(\"shouldStop\", \"must return a boolean, { continue } or { stop, reason }\");\n const decision = value as Exclude<StopDecision, boolean>;\n if (\"continue\" in decision) return { kind: \"continue\", content: continueContent(decision.continue) };\n if (typeof decision.reason !== \"string\" || (decision.stop !== \"hook\" && decision.stop !== \"no_progress\")) {\n invalid(\"shouldStop\", 'returned a stop that is not { stop: \"hook\" | \"no_progress\", reason }');\n }\n return decision.stop === \"hook\"\n ? { kind: \"stop\", stoppedBy: decision.reason }\n : { kind: \"no_progress\", reason: decision.reason };\n}\n"]}
@@ -6,6 +6,11 @@
6
6
  * Failure policy (D6): a hook that throws is reported as a `hook_error` event. Under `fail_closed`, the default, a
7
7
  * failed gate denies its call, a failed `afterToolCall` withholds the result, and any other failed hook throws a
8
8
  * `HookFailure`, which the loop turns into an `error` result. Under `continue` the failed hook is skipped.
9
+ *
10
+ * A gate's `ask` pauses its call (D5): the runner signs a pending request through the one signing path, over the
11
+ * input the call would run with, and hands the request and that input to the pipeline, which reports the pause once
12
+ * every call of the step has been gated. A pause that can't be signed never pauses unsigned: the call is blocked
13
+ * instead, whatever `onFailure` says.
9
14
  */
10
15
  import type { AssistantMessage, Message, ModelContext, ModelRef, Usage } from "@buildanagent/gateway";
11
16
  import { SdkError } from "./errors.js";
@@ -14,6 +19,7 @@ import { type StopVerdict } from "./hook-checks.js";
14
19
  import type { CallOptions, Interceptors, ModelCallPatch } from "./hooks.js";
15
20
  import type { Clock } from "./testing/determinism.js";
16
21
  import { type PipelineContext } from "./tools/pipeline.js";
22
+ import type { ApprovalSigner } from "./vendor/agent-safety/signer.js";
17
23
  /** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */
18
24
  export declare class HookFailure extends SdkError {
19
25
  readonly name = "HookFailure";
@@ -29,6 +35,10 @@ export interface HookRunnerSetup {
29
35
  /** The index of the model call in progress. */
30
36
  stepIndex(): number;
31
37
  send(body: AgentEventBody): void;
38
+ /** Signs the pending request a gate's `ask` writes. */
39
+ readonly signer: ApprovalSigner;
40
+ /** Makes each pending request's id. */
41
+ readonly nextId: () => string;
32
42
  }
33
43
  /** The pipeline hooks that the interceptors fill, left out when no interceptor needs them. */
34
44
  export type PipelineHooks = Pick<PipelineContext, "gate" | "after">;
@@ -1,7 +1,10 @@
1
1
  import { isSdkError, SdkError } from "./errors.js";
2
2
  import { frozenCopy, thawedCopy } from "./freeze.js";
3
3
  import { checkDecision, checkMessages, checkModelPatch, checkReplacement, checkResultPatch, checkStopDecision, } from "./hook-checks.js";
4
+ import { signPause } from "./pauses.js";
5
+ import { preparedSchemaOf } from "./tools/define.js";
4
6
  import { isContentList } from "./tools/pipeline.js";
7
+ import { isSafetyError } from "./vendor/agent-safety/errors.js";
5
8
  /** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */
6
9
  export class HookFailure extends SdkError {
7
10
  name = "HookFailure";
@@ -30,20 +33,28 @@ function blocked(text, details) {
30
33
  function gateOutcome(tool, decision) {
31
34
  if (decision.decision === "allow")
32
35
  return decision.input === undefined ? undefined : { input: thawedCopy(decision.input) };
33
- if (decision.decision === "deny") {
34
- return { blocked: blocked(`Tool call "${tool}" was denied: ${decision.reason}`, { decision: "deny" }) };
35
- }
36
- const why = decision.reason === undefined ? "" : ` (${decision.reason})`;
37
- const text = `Tool call "${tool}" needs approval${why}, and this run can't ask for it, so it was not run.`;
38
- return {
39
- blocked: blocked(text, { decision: "ask", ...(decision.reason === undefined ? {} : { reason: decision.reason }) }),
40
- };
36
+ return { blocked: blocked(`Tool call "${tool}" was denied: ${decision.reason}`, { decision: "deny" }) };
37
+ }
38
+ const SAFETY_CODES = [
39
+ "invalid_outcome",
40
+ "invalid_input",
41
+ "invalid_key_ring",
42
+ "invalid_pending",
43
+ ];
44
+ /**
45
+ * Why a pause could not be signed, as reports may show it: one of the safety package's error codes, or a fixed word.
46
+ * A custom signer's own text is never passed on, because nothing stops it from quoting key material, and that holds
47
+ * for a `code` too: any object can carry the safety error's marker, so only a known code is trusted.
48
+ */
49
+ function unsignedCause(error) {
50
+ return isSafetyError(error) && SAFETY_CODES.includes(error.code) ? error.code : "signer_failed";
41
51
  }
42
52
  /** Runs one run's interceptors. */
43
53
  export class HookRunner {
44
54
  #setup;
45
55
  #hooks;
46
56
  #continues;
57
+ #requestIds = new Set();
47
58
  constructor(setup) {
48
59
  this.#setup = setup;
49
60
  this.#hooks = setup.interceptors;
@@ -112,7 +123,73 @@ export class HookRunner {
112
123
  const guarded = await this.#guard("beforeToolCall", () => hook(event), failed);
113
124
  if (guarded.status === "skipped")
114
125
  return undefined;
115
- return guarded.status === "closed" ? guarded.value : gateOutcome(tool.name, checkDecision(guarded.value));
126
+ if (guarded.status === "closed")
127
+ return guarded.value;
128
+ const decision = checkDecision(guarded.value);
129
+ return decision.decision === "ask"
130
+ ? this.#pause(call, tool, input.input, decision)
131
+ : gateOutcome(tool.name, decision);
132
+ }
133
+ /**
134
+ * Signs the pending request for a call a gate asked about and returns it with the input it signs. That input is the
135
+ * one the call would run with: the checked input the gate saw, or the `ask`'s own replacement, which must pass the
136
+ * tool's schema like an `allow`'s. If signing fails, the call is blocked: a pause that no signature covers is never
137
+ * written.
138
+ */
139
+ async #pause(call, tool, seen, decision) {
140
+ const { signer, clock } = this.#setup;
141
+ const { reason, policyVersion } = decision;
142
+ const input = thawedCopy(decision.input === undefined ? seen : await this.#replacement(tool, decision.input));
143
+ let request;
144
+ try {
145
+ request = await signPause({
146
+ kind: "approval",
147
+ callId: call.callId,
148
+ tool: tool.name,
149
+ input,
150
+ ...(policyVersion === undefined ? {} : { policyVersion }),
151
+ // Display text only, so a blank reason is left out rather than failing the signature.
152
+ ...(reason === undefined || reason === "" ? {} : { reason }),
153
+ }, signer, { generateId: () => this.#requestId(), now: () => new Date(clock.now()) });
154
+ }
155
+ catch (error) {
156
+ return this.#unsigned(tool.name, unsignedCause(error));
157
+ }
158
+ // A resolution names its request by id, so two pending requests of one run must never share one.
159
+ if (this.#requestIds.has(request.id))
160
+ return this.#unsigned(tool.name, "duplicate_request_id");
161
+ this.#requestIds.add(request.id);
162
+ return { paused: request, input };
163
+ }
164
+ /**
165
+ * The next request id from the run's `idGenerator`. A generator that repeats an id, such as one that always returns
166
+ * a session id, was enough for a run id alone, so a repeat of the run id or of an earlier request's id falls back to
167
+ * a random UUID instead of blocking the call.
168
+ */
169
+ #requestId() {
170
+ const id = this.#setup.nextId();
171
+ return id === this.#setup.runId || this.#requestIds.has(id) ? globalThis.crypto.randomUUID() : id;
172
+ }
173
+ /**
174
+ * An `ask`'s replacement input, checked against the tool's schema, because a call must never run with input its own
175
+ * tool would reject.
176
+ */
177
+ async #replacement(tool, input) {
178
+ const checked = await preparedSchemaOf(tool).validate(input);
179
+ if (checked.ok)
180
+ return checked.value;
181
+ const issues = checked.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join("; ");
182
+ throw new SdkError("invalid_hook_result", `beforeToolCall asked about tool "${tool.name}" with an input its schema rejects: ${issues}`);
183
+ }
184
+ /** Blocks a call whose pause could not be signed, and reports why without the signer's own message. */
185
+ #unsigned(tool, cause) {
186
+ this.#setup.send({
187
+ type: "hook_error",
188
+ hook: "signer",
189
+ error: `the approval request could not be signed (${cause})`,
190
+ });
191
+ const text = `Tool call "${tool}" needs approval, but its approval request could not be signed, so it was not run.`;
192
+ return { blocked: blocked(text, { decision: "ask", error: cause }) };
116
193
  }
117
194
  async #afterTool(input) {
118
195
  const hook = this.#hooks.afterToolCall;