@buildanagent/sdk 0.1.0-alpha.6 → 0.1.0-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -0
- package/dist/errors.d.ts +3 -1
- package/dist/errors.js +2 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +10 -1
- package/dist/events.js +1 -0
- package/dist/events.js.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +3 -0
- package/dist/loop.js +46 -3
- package/dist/loop.js.map +1 -1
- package/dist/run.d.ts +18 -0
- package/dist/run.js +10 -1
- package/dist/run.js.map +1 -1
- package/dist/steering.d.ts +52 -0
- package/dist/steering.js +104 -0
- package/dist/steering.js.map +1 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -116,6 +116,29 @@ async execute(input, ctx) {
|
|
|
116
116
|
|
|
117
117
|
Pass `signal: ctx.signal` so the child stops when the parent's call is aborted. The parent's `budgetUsd` counts only the parent's own model calls, so give each child a budget of its own. A tool running at `depth === maxDepth` that starts a child run this way makes `run()` throw `max_depth_exceeded`. Since the throw happens inside `execute`, the model reads it as an error result and can answer without the sub-agent.
|
|
118
118
|
|
|
119
|
+
## Steer a running agent with `run.steer()`, or queue a follow-up with `run.followUp()`
|
|
120
|
+
|
|
121
|
+
Both methods queue a user message and return a promise for a `DeliveryReceipt`. The loop applies queued messages only at a step boundary, so a model call or tool batch that is running is never cut. A steer is applied before the run's next model call: a steer sent while a batch of tool calls runs waits for the whole batch, and the model reads it after the tool results.
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
const started = run({ model, system, input, tools });
|
|
125
|
+
const receipt = await started.steer("Use order 2 instead.");
|
|
126
|
+
console.log(receipt.stepIndex); // the step whose model call is the first to read the message
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
A follow-up waits until the run would otherwise end. When the model answers without a tool call and a message is waiting, the run adds the waiting messages and makes one more model call, so a follow-up sent before the run ends extends it by one step. A waiting steer goes first, and follow-ups wait for the next time the run would end. The extra call counts against `maxSteps`: a run already at the cap ends as it would have.
|
|
130
|
+
|
|
131
|
+
A receipt resolves once its message is in the transcript. It holds an `id` that is unique within the run, the `kind` (`"steer"` or `"follow_up"`), the `message` as content blocks and the `stepIndex`, the step at whose start the run added the message. That step's model call is the first to read it, unless the run ends before the call, which a budget stop or a failed hook can cause. The run also emits one `steer_applied` event for each message, carrying the same receipt. A message is a string that isn't blank, or a non-empty list of text and image blocks whose text isn't blank. The run applies messages in the order they were sent.
|
|
132
|
+
|
|
133
|
+
The promise rejects with an `SdkError` whose code is `undelivered_message` when the run ends before it applies the message. That happens in four cases:
|
|
134
|
+
|
|
135
|
+
- You call after the run has its outcome.
|
|
136
|
+
- An abort, or any stop reason other than a text answer, ends the run.
|
|
137
|
+
- A `shouldStop` hook or the progress policy ends a run that answered in text.
|
|
138
|
+
- The run ends by calling its output tool.
|
|
139
|
+
|
|
140
|
+
The promise rejects with `invalid_run_options` for a blank message or a block that isn't text or an image. A promise you never await is safe to drop: a rejection nobody reads does not raise an unhandled rejection.
|
|
141
|
+
|
|
119
142
|
## A run streams one closed set of events
|
|
120
143
|
|
|
121
144
|
Iterating a run yields its events. Each iteration starts from the run's first event, so you can start iterating at any time, even after the run has ended. Every event carries the run's `runId`, a `seq` that counts events from 0, a `stepIndex` that counts model calls from 0, and a `timestamp` from the run's clock.
|
|
@@ -127,6 +150,7 @@ The events come in two layers. The delta layer streams each content block by its
|
|
|
127
150
|
- **`model_call_start`** carries the request, and **`model_call_end`** the final message.
|
|
128
151
|
- **`tool_call_start`**, **`tool_call_update`** and **`tool_call_end`** follow each tool call; `tool_call_end.result` is what the model reads. When a `beforeToolCall` gate replaced the model's input, `tool_call_end.input` holds the input the call got instead.
|
|
129
152
|
- **`context_transformed`** reports the message counts before and after `transformContext` for one model call.
|
|
153
|
+
- **`steer_applied`** reports a queued steer or follow-up that entered the transcript, with its receipt.
|
|
130
154
|
- **`hook_error`** reports an interceptor or an observer that threw, with the hook's name and the message.
|
|
131
155
|
- **`retry`** reports a failed request the gateway is retrying, and **`warning`** reports a reached cap or a model warning.
|
|
132
156
|
- **`error`** and **`abort`** report a failed call and an abort request.
|
|
@@ -282,6 +306,7 @@ The SDK throws only for programmer errors, never for a failure the model caused.
|
|
|
282
306
|
- **`invalid_tool_result`**: `execute` returned something other than a tool result, or an invalid outcome. A text block needs a string `text`, and an image block a string `mediaType` and `data`. The run's `result` rejects with this error, and iterating the run throws it after the last event.
|
|
283
307
|
- **`invalid_run_options`**: `run()` or `continueRun()` got a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool whose `exposure` isn't `"direct"`, a `budgetUsd` that isn't a non-negative number, a `progress` threshold that isn't a positive integer, or a `depth` or `maxDepth` that isn't a whole number.
|
|
284
308
|
- **`max_depth_exceeded`**: a tool started a run nested deeper than `maxDepth` allows.
|
|
309
|
+
- **`undelivered_message`**: `steer()` or `followUp()` rejects with it when the run ended before it could apply the message.
|
|
285
310
|
- **`invalid_model_stream`**: a model's stream ended without a final message, which only a broken adapter does.
|
|
286
311
|
Hooks add two `SdkError` codes:
|
|
287
312
|
|
package/dist/errors.d.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
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" | "max_depth_exceeded" | "invalid_hook_result" | "hook_failed" | "run_stopped" | "unexpected_model_call";
|
|
10
|
+
export type SdkErrorCode = "invalid_tool_definition" | "invalid_tool_result" | "invalid_run_options" | "invalid_model_stream" | "max_depth_exceeded" | "invalid_hook_result" | "hook_failed" | "run_stopped" | "undelivered_message" | "unexpected_model_call";
|
|
11
11
|
/**
|
|
12
12
|
* Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema,
|
|
13
13
|
* exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name. `invalid_tool_result`: a tool's
|
|
@@ -19,6 +19,8 @@ export type SdkErrorCode = "invalid_tool_definition" | "invalid_tool_result" | "
|
|
|
19
19
|
* threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,
|
|
20
20
|
* so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a
|
|
21
21
|
* `RunStoppedError`).
|
|
22
|
+
* `undelivered_message`: `steer()` or `followUp()` was called on a run that had ended, or the run ended before it
|
|
23
|
+
* could apply the message.
|
|
22
24
|
* `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
|
|
23
25
|
* `UnexpectedModelCallError`).
|
|
24
26
|
*/
|
package/dist/errors.js
CHANGED
|
@@ -11,6 +11,8 @@ const SDK_ERROR = Symbol.for("buildanagent.sdk.SdkError");
|
|
|
11
11
|
* threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,
|
|
12
12
|
* so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a
|
|
13
13
|
* `RunStoppedError`).
|
|
14
|
+
* `undelivered_message`: `steer()` or `followUp()` was called on a run that had ended, or the run ended before it
|
|
15
|
+
* could apply the message.
|
|
14
16
|
* `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
|
|
15
17
|
* `UnexpectedModelCallError`).
|
|
16
18
|
*/
|
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":"AAsBA,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,QA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C,iBAAiB,CAAC,KAAK,IAAI,CAC9G,CAAC;IACJ,CAAC;CACF","sourcesContent":["/**\n * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool\n * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never\n * thrown: the tool pipeline returns it to the model as an error result. Two subclasses keep their own names:\n * `RunStoppedError`, which `runOrThrow()` throws for a run that did not finish, and the testing export's\n * `UnexpectedModelCallError`.\n */\nimport type { Context, UnfinishedResult } from \"./result.js\";\n\n/** Why an `SdkError` was thrown. */\nexport type SdkErrorCode =\n | \"invalid_tool_definition\"\n | \"invalid_tool_result\"\n | \"invalid_run_options\"\n | \"invalid_model_stream\"\n | \"max_depth_exceeded\"\n | \"invalid_hook_result\"\n | \"hook_failed\"\n | \"run_stopped\"\n | \"undelivered_message\"\n | \"unexpected_model_call\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SDK_ERROR = Symbol.for(\"buildanagent.sdk.SdkError\");\n\n/**\n * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema,\n * exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name. `invalid_tool_result`: a tool's\n * `execute` returned a malformed result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an\n * option it can't use, such as a model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended\n * without a final message. `max_depth_exceeded`: a tool started a run nested deeper than `maxDepth` allows.\n * `invalid_hook_result`: an interceptor returned something its type does not allow, such as\n * a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor\n * threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,\n * so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a\n * `RunStoppedError`).\n * `undelivered_message`: `steer()` or `followUp()` was called on a run that had ended, or the run ended before it\n * could apply the message.\n * `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an\n * `UnexpectedModelCallError`).\n */\nexport class SdkError extends Error {\n override readonly name: string = \"SdkError\";\n readonly code: SdkErrorCode;\n\n constructor(code: SdkErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SDK_ERROR, { value: true });\n }\n}\n\n/** True for an `SdkError`, including one from another copy of the package. */\nexport function isSdkError(error: unknown): error is SdkError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SDK_ERROR] === true;\n}\n\nconst RUN_STOPPED_ERROR = Symbol.for(\"buildanagent.sdk.RunStoppedError\");\n\n/**\n * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It\n * carries the whole result, and the context to continue from. It is an `SdkError` with code `run_stopped`.\n */\nexport class RunStoppedError extends SdkError {\n override readonly name = \"RunStoppedError\";\n readonly stopReason: UnfinishedResult[\"stopReason\"];\n readonly result: UnfinishedResult;\n /** The conversation so far, ready for `continueRun()`. */\n readonly context: Context;\n\n constructor(result: UnfinishedResult) {\n super(\"run_stopped\", `the run stopped with \"${result.stopReason}\" after ${result.steps} model calls`);\n this.stopReason = result.stopReason;\n this.result = result;\n this.context = result.context;\n Object.defineProperty(this, RUN_STOPPED_ERROR, { value: true });\n }\n\n /** True for a `RunStoppedError`, including one from another copy of the package. Use it in place of `instanceof`. */\n static isInstance(error: unknown): error is RunStoppedError {\n return (\n typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[RUN_STOPPED_ERROR] === true\n );\n }\n}\n"]}
|
package/dist/events.d.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from "@buildanagent/gateway";
|
|
8
8
|
import type { RunError, RunResult } from "./result.js";
|
|
9
|
+
import type { DeliveryReceipt } from "./steering.js";
|
|
9
10
|
import type { ToolResult } from "./tools/types.js";
|
|
10
11
|
/** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */
|
|
11
12
|
export interface EventBase {
|
|
@@ -98,6 +99,14 @@ export type AgentEventBody = {
|
|
|
98
99
|
readonly delayMs: number;
|
|
99
100
|
readonly error: string;
|
|
100
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* A queued steer or follow-up entered the transcript as a user message, at the start of the step named by
|
|
104
|
+
* `receipt.stepIndex`, before its model call. `receipt.kind` tells the two apart.
|
|
105
|
+
*/
|
|
106
|
+
| {
|
|
107
|
+
readonly type: "steer_applied";
|
|
108
|
+
readonly receipt: DeliveryReceipt;
|
|
109
|
+
}
|
|
101
110
|
/**
|
|
102
111
|
* An interceptor or an observer threw. `hook` names it (`beforeToolCall`, `observer` and so on) and `error` is the
|
|
103
112
|
* thrown message. The run goes on or fails by the interceptors' `onFailure` setting; a failed observer never
|
|
@@ -121,4 +130,4 @@ export type AgentEventBody = {
|
|
|
121
130
|
/** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */
|
|
122
131
|
export type AgentEvent = EventBase & AgentEventBody;
|
|
123
132
|
/** Every `AgentEvent` type. A run emits no type this list lacks. */
|
|
124
|
-
export declare const AGENT_EVENT_TYPES: readonly ["run_start", "step_start", "model_call_start", "retry", "text_start", "text_delta", "text_end", "reasoning_start", "reasoning_delta", "reasoning_end", "tool_input_start", "tool_input_delta", "tool_input_end", "warning", "model_call_end", "context_transformed", "hook_error", "tool_call_start", "tool_call_update", "tool_call_end", "step_end", "error", "abort", "agent_settled", "run_end"];
|
|
133
|
+
export declare const AGENT_EVENT_TYPES: readonly ["run_start", "step_start", "model_call_start", "retry", "text_start", "text_delta", "text_end", "reasoning_start", "reasoning_delta", "reasoning_end", "tool_input_start", "tool_input_delta", "tool_input_end", "warning", "model_call_end", "context_transformed", "hook_error", "steer_applied", "tool_call_start", "tool_call_update", "tool_call_end", "step_end", "error", "abort", "agent_settled", "run_end"];
|
package/dist/events.js
CHANGED
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":"AAiGA,oEAAoE;AACpE,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC7C,WAAW;IACX,YAAY;IACZ,kBAAkB;IAClB,OAAO;IACP,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,iBAAiB;IACjB,iBAAiB;IACjB,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,gBAAgB;IAChB,SAAS;IACT,gBAAgB;IAChB,qBAAqB;IACrB,YAAY;IACZ,eAAe;IACf,iBAAiB;IACjB,kBAAkB;IAClB,eAAe;IACf,UAAU;IACV,OAAO;IACP,OAAO;IACP,eAAe;IACf,SAAS;CACuC,CAAC,CAAC","sourcesContent":["/**\n * The events a run streams: one closed union in two layers (agent-SDK guide §5). The delta layer streams each content\n * block by its index; the item layer's end events (`model_call_end`, `tool_call_end`, `run_end`) carry the\n * authoritative item, which a session log stores. `AGENT_EVENT_TYPES` lists the union at run time, so a test can\n * check that the loop emits no type the union does not declare.\n */\nimport type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from \"@buildanagent/gateway\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { DeliveryReceipt } from \"./steering.js\";\nimport type { ToolResult } from \"./tools/types.js\";\n\n/** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */\nexport interface EventBase {\n readonly runId: string;\n readonly seq: number;\n readonly stepIndex: number;\n /** When the event was emitted, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** One model call's request as the loop sends it: the model, the context and the options. */\nexport interface ModelCallRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: DumpedOptions;\n}\n\n/**\n * Why a `warning` event fired. `max_steps`: the run reached `maxSteps` and stopped. `model_warning`: the model call\n * reported something that did not stop it, such as an option the provider would reject and the adapter dropped.\n */\nexport type WarningCode = \"max_steps\" | \"model_warning\";\n\n/** The body of each event, without the fields of `EventBase`. */\nexport type AgentEventBody =\n | {\n readonly type: \"run_start\";\n readonly sdkVersion: string;\n readonly specVersion: \"v1\";\n /** Reserved for a hash of the run's defaults; empty for now. */\n readonly defaultsHash: string;\n /** Reserved for the SDK's capability names; empty for now. */\n readonly capabilities: readonly string[];\n readonly model: ModelRef;\n }\n | { readonly type: \"run_end\"; readonly result: RunResult }\n /** Fires once nothing is running any more, retries and tools included; `run_end` follows it. */\n | { readonly type: \"agent_settled\" }\n | { readonly type: \"step_start\" }\n | { readonly type: \"step_end\"; readonly stopCheck: \"continue\" | \"stop\" }\n | { readonly type: \"model_call_start\"; readonly request: ModelCallRequest }\n | { readonly type: \"model_call_end\"; readonly message: AssistantMessage }\n | { readonly type: \"text_start\" | \"reasoning_start\" | \"tool_input_start\"; readonly index: number }\n | {\n readonly type: \"text_delta\" | \"reasoning_delta\" | \"tool_input_delta\";\n readonly index: number;\n readonly delta: string;\n }\n | {\n readonly type: \"text_end\" | \"reasoning_end\" | \"tool_input_end\";\n readonly index: number;\n readonly block: ContentBlock;\n }\n | { readonly type: \"tool_call_start\"; readonly callId: string; readonly tool: string; readonly input: unknown }\n | { readonly type: \"tool_call_update\"; readonly callId: string; readonly details: unknown }\n /**\n * `result` is what the model reads for the call, after `afterToolCall` has had its say. `input` is present only\n * when a `beforeToolCall` gate replaced the model's input, and holds the input the gate gave the call instead.\n */\n | {\n readonly type: \"tool_call_end\";\n readonly callId: string;\n readonly result: ToolResult;\n readonly input?: unknown;\n }\n /** `transformContext` returned the messages for one model call: `before` messages in, `after` messages out. */\n | { readonly type: \"context_transformed\"; readonly before: number; readonly after: number }\n /** The model is retrying a failed request; `attempt` is 1 for the first retry. */\n | { readonly type: \"retry\"; readonly attempt: number; readonly delayMs: number; readonly error: string }\n /**\n * A queued steer or follow-up entered the transcript as a user message, at the start of the step named by\n * `receipt.stepIndex`, before its model call. `receipt.kind` tells the two apart.\n */\n | { readonly type: \"steer_applied\"; readonly receipt: DeliveryReceipt }\n /**\n * An interceptor or an observer threw. `hook` names it (`beforeToolCall`, `observer` and so on) and `error` is the\n * thrown message. The run goes on or fails by the interceptors' `onFailure` setting; a failed observer never\n * affects it.\n */\n | { readonly type: \"hook_error\"; readonly hook: string; readonly error: string }\n | { readonly type: \"warning\"; readonly code: WarningCode; readonly detail: string }\n | { readonly type: \"error\"; readonly error: RunError }\n | { readonly type: \"abort\"; readonly reason?: string };\n\n/** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */\nexport type AgentEvent = EventBase & AgentEventBody;\n\n/** Every `AgentEvent` type. A run emits no type this list lacks. */\nexport const AGENT_EVENT_TYPES = Object.freeze([\n \"run_start\",\n \"step_start\",\n \"model_call_start\",\n \"retry\",\n \"text_start\",\n \"text_delta\",\n \"text_end\",\n \"reasoning_start\",\n \"reasoning_delta\",\n \"reasoning_end\",\n \"tool_input_start\",\n \"tool_input_delta\",\n \"tool_input_end\",\n \"warning\",\n \"model_call_end\",\n \"context_transformed\",\n \"hook_error\",\n \"steer_applied\",\n \"tool_call_start\",\n \"tool_call_update\",\n \"tool_call_end\",\n \"step_end\",\n \"error\",\n \"abort\",\n \"agent_settled\",\n \"run_end\",\n] as const satisfies readonly AgentEvent[\"type\"][]);\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,
|
|
3
3
|
* `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
|
|
4
4
|
* outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
|
|
5
|
-
* holds the run's guards: a USD budget checked before each call, progress detection and a depth cap.
|
|
6
|
-
* planned in the SDK
|
|
5
|
+
* holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can
|
|
6
|
+
* steer a running agent or queue a follow-up, both applied at step boundaries. Signed pauses are planned in the SDK
|
|
7
|
+
* plan §3.3.
|
|
7
8
|
*/
|
|
8
9
|
export { projectCallCost } from "@buildanagent/gateway";
|
|
9
10
|
export { composeInterceptors } from "./compose.js";
|
|
@@ -13,6 +14,7 @@ export type { CallOptions, ContextEvent, GateDecision, HookEventBase, Intercepto
|
|
|
13
14
|
export { DEFAULT_PROGRESS, type ProgressPolicy } from "./progress.js";
|
|
14
15
|
export type { BudgetResult, Context, DoneResult, EndedResult, ErrorResult, NoProgressResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
|
|
15
16
|
export { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from "./run.js";
|
|
17
|
+
export type { DeliveryKind, DeliveryReceipt } from "./steering.js";
|
|
16
18
|
export { type ClarificationToolOptions, clarificationTool, defineTool, type OutputToolOptions, outputTool, } from "./tools/define.js";
|
|
17
19
|
export type { JsonSchema, SchemaIssue, ToolAnnotations, ToolContext, ToolDefinition, ToolEffect, ToolExecutionMode, ToolExposure, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
|
|
18
20
|
export type { WriteOutcome } from "./vendor/agent-safety/outcome.js";
|
package/dist/index.js
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,
|
|
3
3
|
* `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
|
|
4
4
|
* outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
|
|
5
|
-
* holds the run's guards: a USD budget checked before each call, progress detection and a depth cap.
|
|
6
|
-
* planned in the SDK
|
|
5
|
+
* holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can
|
|
6
|
+
* steer a running agent or queue a follow-up, both applied at step boundaries. Signed pauses are planned in the SDK
|
|
7
|
+
* plan §3.3.
|
|
7
8
|
*/
|
|
8
9
|
// Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.
|
|
9
10
|
export { projectCallCost } from "@buildanagent/gateway";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,sHAAsH;AACtH,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AACvF,OAAO,EACL,iBAAiB,GAMlB,MAAM,aAAa,CAAC;AAmBrB,OAAO,EAAE,gBAAgB,EAAuB,MAAM,eAAe,CAAC;AActE,OAAO,EAAE,WAAW,EAAE,cAAc,EAA4C,GAAG,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAElH,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,UAAU,GACX,MAAM,mBAAmB,CAAC;AAgB3B,+CAA+C;AAC/C,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,\n * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write\n * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also\n * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can\n * steer a running agent or queue a follow-up, both applied at step boundaries. Signed pauses are planned in the SDK\n * plan §3.3.\n */\n// Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.\nexport { projectCallCost } from \"@buildanagent/gateway\";\nexport { composeInterceptors } from \"./compose.js\";\nexport { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from \"./errors.js\";\nexport {\n AGENT_EVENT_TYPES,\n type AgentEvent,\n type AgentEventBody,\n type EventBase,\n type ModelCallRequest,\n type WarningCode,\n} from \"./events.js\";\nexport type {\n CallOptions,\n ContextEvent,\n GateDecision,\n HookEventBase,\n Interceptors,\n MaybePromise,\n ModelCallEvent,\n ModelCallPatch,\n ModelResultEvent,\n Observer,\n OrNothing,\n StepEvent,\n StopDecision,\n ToolCallEvent,\n ToolResultEvent,\n ToolResultPatch,\n} from \"./hooks.js\";\nexport { DEFAULT_PROGRESS, type ProgressPolicy } from \"./progress.js\";\nexport type {\n BudgetResult,\n Context,\n DoneResult,\n EndedResult,\n ErrorResult,\n NoProgressResult,\n ResultBase,\n RunError,\n RunResult,\n StoppedResult,\n UnfinishedResult,\n} from \"./result.js\";\nexport { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from \"./run.js\";\nexport type { DeliveryKind, DeliveryReceipt } from \"./steering.js\";\nexport {\n type ClarificationToolOptions,\n clarificationTool,\n defineTool,\n type OutputToolOptions,\n outputTool,\n} from \"./tools/define.js\";\nexport type {\n JsonSchema,\n SchemaIssue,\n ToolAnnotations,\n ToolContext,\n ToolDefinition,\n ToolEffect,\n ToolExecutionMode,\n ToolExposure,\n ToolFailure,\n ToolResult,\n ToolSchema,\n} from \"./tools/types.js\";\nexport type { WriteOutcome } from \"./vendor/agent-safety/outcome.js\";\n\n/** The package's name, `@buildanagent/sdk`. */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
|
package/dist/loop.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ import type { AgentEventBody } from "./events.js";
|
|
|
12
12
|
import type { CallOptions, Interceptors } from "./hooks.js";
|
|
13
13
|
import type { ProgressCheck } from "./progress.js";
|
|
14
14
|
import type { RunResult } from "./result.js";
|
|
15
|
+
import type { SteeringQueue } from "./steering.js";
|
|
15
16
|
import type { Clock } from "./testing/determinism.js";
|
|
16
17
|
import { type AnyTool } from "./tools/pipeline.js";
|
|
17
18
|
/** Everything one run needs, fixed when it starts. */
|
|
@@ -39,6 +40,8 @@ export interface LoopSetup {
|
|
|
39
40
|
readonly interceptors: Interceptors;
|
|
40
41
|
/** The default progress policy, run after the caller's `shouldStop`, or `undefined` when it is off (D11). */
|
|
41
42
|
readonly progress?: ProgressCheck;
|
|
43
|
+
/** The messages a caller queued with `steer()` and `followUp()`, applied only at step boundaries. */
|
|
44
|
+
readonly steering: SteeringQueue;
|
|
42
45
|
readonly signal: AbortSignal;
|
|
43
46
|
readonly clock: Clock;
|
|
44
47
|
}
|
package/dist/loop.js
CHANGED
|
@@ -37,6 +37,8 @@ class LoopState {
|
|
|
37
37
|
lastUsage;
|
|
38
38
|
cost;
|
|
39
39
|
output;
|
|
40
|
+
/** Set when the run was kept going to deliver a follow-up, so the next step boundary applies the follow-ups too. */
|
|
41
|
+
releaseFollowUps = false;
|
|
40
42
|
constructor(setup, emit, drain) {
|
|
41
43
|
this.setup = setup;
|
|
42
44
|
this.emit = emit;
|
|
@@ -325,6 +327,37 @@ function withVerdict(state, natural, verdict) {
|
|
|
325
327
|
return natural;
|
|
326
328
|
}
|
|
327
329
|
}
|
|
330
|
+
/**
|
|
331
|
+
* Applies the queued messages before a model call: every steer, and the follow-ups too once the run was kept going to
|
|
332
|
+
* deliver them. Each becomes a user message and a `steer_applied` event, in the order it was sent, and its receipt
|
|
333
|
+
* resolves with the index of the step about to run.
|
|
334
|
+
*/
|
|
335
|
+
function applySteering(state) {
|
|
336
|
+
const { steering } = state.setup;
|
|
337
|
+
const withFollowUps = state.releaseFollowUps;
|
|
338
|
+
state.releaseFollowUps = false;
|
|
339
|
+
for (const delivery of steering.take(withFollowUps)) {
|
|
340
|
+
// A copy, so a caller who changes a receipt's message cannot change the transcript.
|
|
341
|
+
state.append({ role: "user", content: delivery.message.map((block) => ({ ...block })) });
|
|
342
|
+
state.send({ type: "steer_applied", receipt: delivery.deliver(state.stepIndex) });
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Keeps a run that its model ended by answering going, when a message is waiting and the step cap leaves room for
|
|
347
|
+
* one more call: a steer comes first, and follow-ups wait for the next time the run would end. Any other outcome
|
|
348
|
+
* stands, as does a `stop` or `no_progress` verdict that `withVerdict` folded into `done`, and an abort that came
|
|
349
|
+
* after the answer, which `stopCheck` lets the answer win over. The messages still waiting are rejected when the run
|
|
350
|
+
* ends.
|
|
351
|
+
*/
|
|
352
|
+
function withQueued(state, outcome, verdict) {
|
|
353
|
+
const { steering, maxSteps, signal } = state.setup;
|
|
354
|
+
if (outcome?.stopReason !== "done" || !steering.hasPending() || state.steps >= maxSteps)
|
|
355
|
+
return outcome;
|
|
356
|
+
if (verdict.kind === "stop" || verdict.kind === "no_progress" || signal.aborted)
|
|
357
|
+
return outcome;
|
|
358
|
+
state.releaseFollowUps = !steering.hasSteers();
|
|
359
|
+
return undefined;
|
|
360
|
+
}
|
|
328
361
|
/** The stop check after one step, then the `shouldStop` hook where it may change it. */
|
|
329
362
|
async function decide(state, message, results) {
|
|
330
363
|
const natural = stopCheck(state, message, results);
|
|
@@ -332,7 +365,9 @@ async function decide(state, message, results) {
|
|
|
332
365
|
if (natural !== undefined && !endedByAnswer)
|
|
333
366
|
return natural;
|
|
334
367
|
const verdict = await state.hooks.shouldStop({ messages: state.messages, lastMessage: message });
|
|
335
|
-
|
|
368
|
+
const judged = await withProgress(state, verdict);
|
|
369
|
+
const outcome = withVerdict(state, natural, judged);
|
|
370
|
+
return endedByAnswer ? withQueued(state, outcome, judged) : outcome;
|
|
336
371
|
}
|
|
337
372
|
/**
|
|
338
373
|
* The caller's verdict, unless the progress policy finds the run stuck. A caller's own stop stands, and a caller's
|
|
@@ -357,6 +392,7 @@ async function runStep(state) {
|
|
|
357
392
|
state.send({ type: "step_start" });
|
|
358
393
|
let outcome;
|
|
359
394
|
try {
|
|
395
|
+
applySteering(state);
|
|
360
396
|
const called = await callModel(state);
|
|
361
397
|
if ("blocked" in called) {
|
|
362
398
|
outcome = called.blocked;
|
|
@@ -430,8 +466,15 @@ export async function runLoop(setup, emit, drain) {
|
|
|
430
466
|
// A budget needs a price to check against, so a model without one is refused before it is called (D4).
|
|
431
467
|
const refused = setup.budgetUsd === undefined ? undefined : unknownPriceError(setup.model);
|
|
432
468
|
let outcome = refused === undefined ? undefined : { stopReason: "error", error: refused };
|
|
433
|
-
|
|
434
|
-
outcome
|
|
469
|
+
try {
|
|
470
|
+
while (outcome === undefined) {
|
|
471
|
+
outcome = setup.signal.aborted ? { stopReason: "aborted" } : await runStep(state);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
finally {
|
|
475
|
+
// The run has its outcome, or threw for a programmer error, so a message still waiting can no longer reach a
|
|
476
|
+
// model call, and its receipt must not hang.
|
|
477
|
+
setup.steering.close();
|
|
435
478
|
}
|
|
436
479
|
return finish(state, outcome);
|
|
437
480
|
}
|
package/dist/loop.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop.js","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAEL,OAAO,EACP,QAAQ,EAGR,UAAU,EAKV,eAAe,GAIhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAK3D,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAgB,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AAGtF,kEAAkE;AAClE,MAAM,aAAa,GAAG,eAAe,CAAC;AAEtC;;;GAGG;AACH,MAAM,OAAO,GAAS,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AA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M,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,KAAgB,EAAE,IAAU,EAAE,KAAY;IACtE,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAChD,uGAAuG;IACvG,MAAM,OAAO,GAAG,KAAK,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,iBAAiB,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC3F,IAAI,OAAO,GAAwB,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;IAC/G,OAAO,OAAO,KAAK,SAAS,EAAE,CAAC;QAC7B,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IACpF,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAChC,CAAC","sourcesContent":["/**\n * The step loop: one model call, then the tool calls it asked for, then the stop check, until a stop reason holds\n * (agent-SDK guide §3). The non-streaming result is built from the same run, so there is one loop for both modes.\n *\n * Each step runs transform → before → stream → after → tools → stop. Those moments are where the interceptors\n * plug in (D6); a run without interceptors sends the transcript as it stands and keeps each response unchanged.\n * Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed tool result,\n * throws.\n */\nimport {\n type AssistantMessage,\n addCost,\n addUsage,\n type Cost,\n type DumpedOptions,\n emptyUsage,\n type GatewayEvent,\n type Message,\n type Model,\n type ModelContext,\n projectCallCost,\n type StreamOptions,\n type Usage,\n type WireTool,\n} from \"@buildanagent/gateway\";\nimport { checkBudget, unknownPriceError } from \"./budget.js\";\nimport { isSdkError, SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport type { StopVerdict } from \"./hook-checks.js\";\nimport { HookFailure, HookRunner } from \"./hook-runner.js\";\nimport type { CallOptions, Interceptors, ModelCallPatch } from \"./hooks.js\";\nimport type { ProgressCheck } from \"./progress.js\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { toWireTool } from \"./tools/define.js\";\nimport { type AnyTool, runToolCalls, type ToolCallResult } from \"./tools/pipeline.js\";\nimport type { ToolCall } from \"./tools/types.js\";\n\n/** The `stoppedBy` of a run that a clarification tool stopped. */\nconst CLARIFICATION = \"clarification\";\n\n/**\n * The cost of no model call: an exact zero. Its basis is `provider` because `addCost()` keeps the other cost's basis\n * when it adds a provider cost, so the zero never turns a billed sum into an estimate.\n */\nconst NO_COST: Cost = { total: 0, basis: \"provider\", currency: \"USD\" };\n\n/** Everything one run needs, fixed when it starts. */\nexport interface LoopSetup {\n readonly runId: string;\n readonly model: Model;\n readonly system: string;\n /** The conversation before this run's own messages. */\n readonly history: readonly Message[];\n /** The messages the run starts by adding, such as the user's input. */\n readonly input: readonly Message[];\n /**\n * Every tool the run knows, in definition order. A request sends the ones whose exposure is `direct`, or the ones\n * `activeTools` names, and only the tools a request sent can run.\n */\n readonly tools: readonly AnyTool[];\n readonly output: AnyTool | undefined;\n readonly maxSteps: number;\n /** The most the run's model calls may cost, in USD, or `undefined` for no cap (D9). */\n readonly budgetUsd?: number;\n /** How deeply this run is nested inside other agents' tool calls, and the deepest nesting allowed (D11). */\n readonly depth: number;\n readonly maxDepth: number;\n readonly modelOptions: CallOptions;\n readonly interceptors: Interceptors;\n /** The default progress policy, run after the caller's `shouldStop`, or `undefined` when it is off (D11). */\n readonly progress?: ProgressCheck;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n}\n\n/** Sends one event; the run adds the `EventBase` fields. */\nexport type Emit = (body: AgentEventBody, stepIndex: number) => void;\n\n/**\n * Resolves once every observer has handled the events sent so far. The loop calls it only once it has its outcome,\n * and the run treats the first call as the point after which an abort no longer counts.\n */\nexport type Drain = () => Promise<void>;\n\n/** How a run ended, before its usage, cost and messages are attached. */\ntype Outcome =\n | { readonly stopReason: \"done\"; readonly output: unknown }\n | { readonly stopReason: \"max_steps\" | \"aborted\" }\n | {\n readonly stopReason: \"budget\";\n readonly reason: string;\n readonly budgetUsd: number;\n readonly spentUsd: number;\n readonly projectedUsd: number;\n }\n | { readonly stopReason: \"error\"; readonly error: RunError }\n | { readonly stopReason: \"stopped\"; readonly stoppedBy: string }\n | { readonly stopReason: \"no_progress\"; readonly reason: string };\n\n/** What changes while a run goes on. */\nclass LoopState {\n readonly setup: LoopSetup;\n readonly emit: Emit;\n readonly messages: Message[];\n readonly added: Message[];\n readonly drain: Drain;\n readonly hooks: HookRunner;\n readonly #wire: ReadonlyMap<AnyTool, WireTool>;\n /** The tools the latest request sent; the tool calls of its response may run only these. */\n active: readonly AnyTool[] = [];\n steps = 0;\n stepIndex = 0;\n usage: Usage = emptyUsage();\n lastUsage: Usage | undefined;\n cost: Cost | undefined;\n output: unknown;\n\n constructor(setup: LoopSetup, emit: Emit, drain: Drain) {\n this.setup = setup;\n this.emit = emit;\n this.drain = drain;\n this.messages = [...setup.history, ...setup.input];\n this.added = [...setup.input];\n this.#wire = new Map(setup.tools.map((tool) => [tool, toWireTool(tool)]));\n this.hooks = new HookRunner({\n interceptors: setup.interceptors,\n runId: setup.runId,\n signal: setup.signal,\n clock: setup.clock,\n stepIndex: () => this.stepIndex,\n send: (body) => this.send(body),\n });\n }\n\n /** The wire form of each of `tools`, as a request sends them. */\n wireOf(tools: readonly AnyTool[]): WireTool[] {\n // Every tool of the run was lowered in the constructor, and a request names only the run's tools.\n return tools.map((tool) => this.#wire.get(tool) as WireTool);\n }\n\n send(body: AgentEventBody): void {\n this.emit(body, this.stepIndex);\n }\n\n append(message: Message): void {\n this.messages.push(message);\n this.added.push(message);\n }\n}\n\n/**\n * The stream options a request event records: everything but the payload hook, the abort signal and the caps, as the\n * gateway's own request dump leaves them out. An untyped caller may still pass a signal or caps in `modelOptions`.\n */\nfunction dumpedOptions(options: CallOptions): DumpedOptions {\n const { onPayload: _onPayload, signal: _signal, caps: _caps, ...rest } = options as StreamOptions;\n return rest;\n}\n\n/** Re-emits one model event as a run event, and returns the final message once the terminal event arrives. */\nfunction forward(state: LoopState, event: GatewayEvent): AssistantMessage | undefined {\n switch (event.type) {\n case \"done\":\n case \"error\":\n return event.message;\n case \"start\":\n return undefined;\n case \"retry\":\n state.send({ type: \"retry\", attempt: event.attempt, delayMs: event.delayMs, error: event.error });\n return undefined;\n case \"warning\":\n state.send({ type: \"warning\", code: \"model_warning\", detail: `${event.code}: ${event.message}` });\n return undefined;\n case \"text_start\":\n case \"reasoning_start\":\n case \"tool_input_start\":\n state.send({ type: event.type, index: event.index });\n return undefined;\n case \"text_delta\":\n case \"reasoning_delta\":\n case \"tool_input_delta\":\n state.send({ type: event.type, index: event.index, delta: event.delta });\n return undefined;\n default:\n state.send({ type: event.type, index: event.index, block: event.block });\n return undefined;\n }\n}\n\n/** One model call as it will be sent, after `transformContext` and `beforeModelCall`. */\ninterface Request {\n readonly model: Model;\n readonly context: ModelContext;\n readonly options: CallOptions;\n readonly active: readonly AnyTool[];\n}\n\n/** The tools a request sends unless `beforeModelCall` names others: the ones whose exposure is `direct`. */\nfunction directTools(tools: readonly AnyTool[]): AnyTool[] {\n return tools.filter((tool) => (tool.exposure ?? \"direct\") === \"direct\");\n}\n\n/** The tools `names` picks, in definition order whatever order `names` is in. */\nfunction toolsNamed(tools: readonly AnyTool[], names: readonly string[]): AnyTool[] {\n const unknown = names.filter((name) => !tools.some((tool) => tool.name === name));\n if (unknown.length > 0) {\n throw new SdkError(\"invalid_hook_result\", `activeTools names unknown tools: ${unknown.join(\", \")}`);\n }\n return tools.filter((tool) => names.includes(tool.name));\n}\n\nfunction patched(state: LoopState, request: Request, patch: ModelCallPatch): Request {\n const active = patch.activeTools === undefined ? request.active : toolsNamed(state.setup.tools, patch.activeTools);\n const { system, messages } = request.context;\n return {\n model: patch.model ?? request.model,\n options: patch.options ?? request.options,\n active,\n context: {\n system: patch.system ?? system,\n messages: patch.messages === undefined ? messages : [...patch.messages],\n tools: state.wireOf(active),\n },\n };\n}\n\n/**\n * Builds one call's request: the transcript, or the view `transformContext` returns for this call alone, then the\n * changes `beforeModelCall` asks for. The run's own transcript is never replaced by either.\n */\nasync function buildRequest(state: LoopState): Promise<Request> {\n const { model, system, modelOptions, tools } = state.setup;\n const view = await state.hooks.transformContext({\n system,\n messages: state.messages,\n model: model.ref,\n lastUsage: state.lastUsage,\n });\n const active = directTools(tools);\n const context = { system, messages: [...(view ?? state.messages)], tools: state.wireOf(active) };\n const request: Request = { model, context, options: modelOptions, active };\n const patch = await state.hooks.beforeModelCall({ context, options: modelOptions });\n return patch === undefined ? request : patched(state, request, patch);\n}\n\n/** Streams one request, re-emitting its events, and returns the model's final message. */\nasync function streamRequest(state: LoopState, request: Request): Promise<AssistantMessage> {\n const { model, context, options } = request;\n state.send({ type: \"model_call_start\", request: { model: model.ref, context, options: dumpedOptions(options) } });\n let message: AssistantMessage | undefined;\n for await (const event of model.stream(context, { ...options, signal: state.setup.signal })) {\n message = forward(state, event) ?? message;\n }\n if (message === undefined) {\n throw new SdkError(\"invalid_model_stream\", \"the model's stream ended without a done or error event\");\n }\n return message;\n}\n\n/** Adds a model call's response to the transcript and reports it. */\nfunction record(state: LoopState, message: AssistantMessage): void {\n state.append(message);\n state.send({ type: \"model_call_end\", message });\n}\n\n/**\n * What the transcript holds for a response whose `afterModelCall` failed while the run fails closed: no content, so a\n * check that crashed can't let the response through, but the call's usage and cost, which were billed. Its error stop\n * reason makes the replay pass skip it if the run is continued.\n */\nfunction withheld(original: AssistantMessage): AssistantMessage {\n const { model, usage, cost, lastAttemptUsage } = original;\n return {\n role: \"assistant\",\n content: [],\n model,\n stopReason: \"error\",\n error: { kind: \"fatal\", message: \"the response was withheld, because its afterModelCall check failed\" },\n usage,\n ...(lastAttemptUsage === undefined ? {} : { lastAttemptUsage }),\n cost,\n };\n}\n\n/**\n * The budget check before a call (D9): the outcome that ends the run when the spend so far plus the call's projected\n * cost would pass `budgetUsd`, or `undefined` when the call may go out. It checks the request as it will be sent,\n * after the interceptors have changed it, and projects with the model the request names.\n */\nfunction budgetBlock(state: LoopState, request: Request): Outcome | undefined {\n const { budgetUsd } = state.setup;\n if (budgetUsd === undefined) return undefined;\n const projected = projectCallCost(request.model, request.context, request.options);\n const verdict = checkBudget(budgetUsd, state.cost, projected);\n switch (verdict.kind) {\n case \"allow\":\n return undefined;\n case \"unknown\":\n return { stopReason: \"error\", error: verdict.error };\n case \"exceeded\":\n return {\n stopReason: \"budget\",\n reason: verdict.reason,\n budgetUsd,\n spentUsd: verdict.spentUsd,\n projectedUsd: verdict.projectedUsd,\n };\n }\n}\n\n/**\n * Makes one model call, streams its events and records the response. The call's usage and cost are the model's own\n * message's, so an `afterModelCall` replacement changes what the run goes on with, never what it is billed. When\n * `afterModelCall` fails and the run fails closed, a withheld stand-in is recorded before the run ends, so the\n * transcript and `model_call_end` still account for the billed call and none of its tool calls run.\n */\nasync function callModel(state: LoopState): Promise<AssistantMessage | { readonly blocked: Outcome }> {\n const request = await buildRequest(state);\n const blocked = budgetBlock(state, request);\n if (blocked !== undefined) return { blocked };\n state.active = request.active;\n const original = await streamRequest(state, request);\n state.steps += 1;\n state.usage = addUsage(state.usage, original.usage);\n state.lastUsage = original.usage;\n state.cost = state.cost === undefined ? original.cost : addCost(state.cost, original.cost);\n let message: AssistantMessage;\n try {\n message = await state.hooks.afterModelCall(original);\n } catch (error) {\n if (error instanceof HookFailure || (isSdkError(error) && error.code === \"invalid_hook_result\")) {\n record(state, withheld(original));\n }\n throw error;\n }\n record(state, message);\n return message;\n}\n\n/** The tool message the model reads for one call. */\nfunction toolMessage(entry: ToolCallResult): Message {\n return {\n role: \"tool\",\n callId: entry.call.callId,\n content: [...entry.result.content],\n isError: entry.result.isError === true,\n };\n}\n\n/** Runs the response's tool calls as the pipeline schedules them, recording each result in model order. */\nasync function runTools(state: LoopState, message: AssistantMessage): Promise<readonly ToolCallResult[]> {\n const { runId, signal, clock, output } = state.setup;\n return runToolCalls(message, state.active, {\n runId,\n signal,\n clock,\n depth: state.setup.depth,\n maxDepth: state.setup.maxDepth,\n ...state.hooks.pipelineHooks(),\n onStart: (call: ToolCall) =>\n state.send({ type: \"tool_call_start\", callId: call.callId, tool: call.name, input: call.input }),\n onUpdate: (callId, details) => state.send({ type: \"tool_call_update\", callId, details }),\n onResult: (entry) => {\n state.append(toolMessage(entry));\n if (output !== undefined && entry.call.name === output.name && entry.result.isError !== true) {\n state.output = entry.result.structured;\n }\n const ranWith = \"input\" in entry ? { input: entry.input } : {};\n state.send({ type: \"tool_call_end\", callId: entry.call.callId, result: entry.result, ...ranWith });\n },\n });\n}\n\n/** The failed call's error as the run reports it. A message without one counts as `fatal`. */\nfunction runErrorOf(message: AssistantMessage): RunError {\n const error = message.error;\n if (error === undefined) return { kind: \"fatal\", message: \"the model call failed without an error description\" };\n return { kind: error.kind, message: error.message, ...(error.status === undefined ? {} : { status: error.status }) };\n}\n\n/**\n * The stop check after one step. A finished answer, or a question for the user, wins over an abort that came too late\n * to change it; otherwise an abort stops the run before the step cap does. A text answer cut off at the output limit\n * also counts as finished: its message keeps `stopReason: \"length\"`.\n */\nfunction stopCheck(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Outcome | undefined {\n if (message.stopReason === \"error\") return { stopReason: \"error\", error: runErrorOf(message) };\n if (message.stopReason === \"aborted\") return { stopReason: \"aborted\" };\n const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);\n if (finished) return { stopReason: \"done\", output: state.output };\n // Until runs can pause for an answer, a clarification question stops the run, so the model never goes on as if the\n // user had been asked and answered.\n if (results.some(({ result }) => result.pause !== undefined && !result.isError)) {\n return { stopReason: \"stopped\", stoppedBy: CLARIFICATION };\n }\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n return undefined;\n}\n\n/**\n * What `shouldStop` changes about the stop check. A finished answer or an error stands whatever the hook says; the\n * hook can end a run that would go on, and can keep going a run the model ended by answering in text, until the\n * step cap.\n */\nfunction withVerdict(state: LoopState, natural: Outcome | undefined, verdict: StopVerdict): Outcome | undefined {\n if (natural !== undefined && verdict.kind !== \"continue\") return natural;\n switch (verdict.kind) {\n case \"stop\":\n return { stopReason: \"stopped\", stoppedBy: verdict.stoppedBy };\n case \"no_progress\":\n return { stopReason: \"no_progress\", reason: verdict.reason };\n case \"continue\":\n if (natural === undefined) return undefined;\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n state.append({ role: \"user\", content: verdict.content });\n return undefined;\n default:\n return natural;\n }\n}\n\n/** The stop check after one step, then the `shouldStop` hook where it may change it. */\nasync function decide(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Promise<Outcome | undefined> {\n const natural = stopCheck(state, message, results);\n const endedByAnswer = natural?.stopReason === \"done\" && results.length === 0;\n if (natural !== undefined && !endedByAnswer) return natural;\n const verdict = await state.hooks.shouldStop({ messages: state.messages, lastMessage: message });\n return withVerdict(state, natural, await withProgress(state, verdict));\n}\n\n/**\n * The caller's verdict, unless the progress policy finds the run stuck. A caller's own stop stands, and a caller's\n * `{ continue }` or failed hook can't keep a stuck run going.\n */\nasync function withProgress(state: LoopState, verdict: StopVerdict): Promise<StopVerdict> {\n if (verdict.kind === \"stop\" || verdict.kind === \"no_progress\" || state.setup.progress === undefined) return verdict;\n const reason = await state.setup.progress(state.messages);\n return reason === undefined ? verdict : { kind: \"no_progress\", reason };\n}\n\n/** The outcome of a hook that failed while the run fails closed. A failure caused by an abort ends the run aborted. */\nfunction failedOutcome(state: LoopState, error: unknown): Outcome {\n if (!(error instanceof HookFailure)) throw error;\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n return { stopReason: \"error\", error: { kind: \"hook\", message: error.message } };\n}\n\nasync function runStep(state: LoopState): Promise<Outcome | undefined> {\n state.stepIndex = state.steps;\n state.send({ type: \"step_start\" });\n let outcome: Outcome | undefined;\n try {\n const called = await callModel(state);\n if (\"blocked\" in called) {\n outcome = called.blocked;\n } else {\n const results = await runTools(state, called);\n outcome = await decide(state, called, results);\n }\n } catch (error) {\n outcome = failedOutcome(state, error);\n }\n state.send({ type: \"step_end\", stopCheck: outcome === undefined ? \"continue\" : \"stop\" });\n return outcome;\n}\n\n/**\n * An aborted run's transcript ends with an assistant message whose `stopReason` is `\"aborted\"`. When tool results end\n * the transcript, because the abort came while tools ran or cut off a response that held tool calls, the loop\n * appends an empty one after them; the replay pass drops it before any request.\n */\nfunction closeAborted(state: LoopState): void {\n const last = state.messages.at(-1);\n if (last?.role === \"assistant\" && last.stopReason === \"aborted\") return;\n state.append({\n role: \"assistant\",\n content: [],\n model: state.setup.model.ref,\n stopReason: \"aborted\",\n usage: emptyUsage(),\n cost: { ...NO_COST },\n });\n}\n\nfunction resultOf(state: LoopState, outcome: Outcome): RunResult {\n const base = {\n messages: state.added,\n context: { system: state.setup.system, messages: state.messages },\n usage: state.usage,\n cost: state.cost ?? { ...NO_COST },\n steps: state.steps,\n };\n return { ...base, ...outcome } as RunResult;\n}\n\n/**\n * Ends the run: the settle event comes once every observer has seen what came before it, and `run_end` after that.\n * An observer's failure while handling `agent_settled` is reported between the two; one while handling `run_end` is\n * dropped, so `run_end` stays the last event. The result is returned only once observers have seen it.\n */\nasync function finish(state: LoopState, outcome: Outcome): Promise<RunResult> {\n if (outcome.stopReason === \"aborted\") closeAborted(state);\n if (outcome.stopReason === \"max_steps\") {\n state.send({ type: \"warning\", code: \"max_steps\", detail: `the run reached maxSteps (${state.setup.maxSteps})` });\n }\n if (outcome.stopReason === \"error\") state.send({ type: \"error\", error: outcome.error });\n await state.drain();\n state.send({ type: \"agent_settled\" });\n await state.drain();\n const result = resultOf(state, outcome);\n state.send({ type: \"run_end\", result });\n await state.drain();\n return result;\n}\n\n/**\n * Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results\n * already received are in the transcript.\n */\nexport async function runLoop(setup: LoopSetup, emit: Emit, drain: Drain): Promise<RunResult> {\n const state = new LoopState(setup, emit, drain);\n // A budget needs a price to check against, so a model without one is refused before it is called (D4).\n const refused = setup.budgetUsd === undefined ? undefined : unknownPriceError(setup.model);\n let outcome: Outcome | undefined = refused === undefined ? undefined : { stopReason: \"error\", error: refused };\n while (outcome === undefined) {\n outcome = setup.signal.aborted ? { stopReason: \"aborted\" } : await runStep(state);\n }\n return finish(state, outcome);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"loop.js","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAEL,OAAO,EACP,QAAQ,EAGR,UAAU,EAKV,eAAe,GAIhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAM3D,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAgB,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AAGtF,kEAAkE;AAClE,MAAM,aAAa,GAAG,eAAe,CAAC;AAEtC;;;GAGG;AACH,MAAM,OAAO,GAAS,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AAyDvE,wCAAwC;AACxC,MAAM,SAAS;IACJ,KAAK,CAAY;IACjB,IAAI,CAAO;IACX,QAAQ,CAAY;IACpB,KAAK,CAAY;IACjB,KAAK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ACxC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;IACxC,MAAM,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,KAAgB,EAAE,IAAU,EAAE,KAAY;IACtE,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAChD,uGAAuG;IACvG,MAAM,OAAO,GAAG,KAAK,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,iBAAiB,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC3F,IAAI,OAAO,GAAwB,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;IAC/G,IAAI,CAAC;QACH,OAAO,OAAO,KAAK,SAAS,EAAE,CAAC;YAC7B,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;QACpF,CAAC;IACH,CAAC;YAAS,CAAC;QACT,6GAA6G;QAC7G,6CAA6C;QAC7C,KAAK,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAChC,CAAC","sourcesContent":["/**\n * The step loop: one model call, then the tool calls it asked for, then the stop check, until a stop reason holds\n * (agent-SDK guide §3). The non-streaming result is built from the same run, so there is one loop for both modes.\n *\n * Each step runs transform → before → stream → after → tools → stop. Those moments are where the interceptors\n * plug in (D6); a run without interceptors sends the transcript as it stands and keeps each response unchanged.\n * Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed tool result,\n * throws.\n */\nimport {\n type AssistantMessage,\n addCost,\n addUsage,\n type Cost,\n type DumpedOptions,\n emptyUsage,\n type GatewayEvent,\n type Message,\n type Model,\n type ModelContext,\n projectCallCost,\n type StreamOptions,\n type Usage,\n type WireTool,\n} from \"@buildanagent/gateway\";\nimport { checkBudget, unknownPriceError } from \"./budget.js\";\nimport { isSdkError, SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport type { StopVerdict } from \"./hook-checks.js\";\nimport { HookFailure, HookRunner } from \"./hook-runner.js\";\nimport type { CallOptions, Interceptors, ModelCallPatch } from \"./hooks.js\";\nimport type { ProgressCheck } from \"./progress.js\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { SteeringQueue } from \"./steering.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { toWireTool } from \"./tools/define.js\";\nimport { type AnyTool, runToolCalls, type ToolCallResult } from \"./tools/pipeline.js\";\nimport type { ToolCall } from \"./tools/types.js\";\n\n/** The `stoppedBy` of a run that a clarification tool stopped. */\nconst CLARIFICATION = \"clarification\";\n\n/**\n * The cost of no model call: an exact zero. Its basis is `provider` because `addCost()` keeps the other cost's basis\n * when it adds a provider cost, so the zero never turns a billed sum into an estimate.\n */\nconst NO_COST: Cost = { total: 0, basis: \"provider\", currency: \"USD\" };\n\n/** Everything one run needs, fixed when it starts. */\nexport interface LoopSetup {\n readonly runId: string;\n readonly model: Model;\n readonly system: string;\n /** The conversation before this run's own messages. */\n readonly history: readonly Message[];\n /** The messages the run starts by adding, such as the user's input. */\n readonly input: readonly Message[];\n /**\n * Every tool the run knows, in definition order. A request sends the ones whose exposure is `direct`, or the ones\n * `activeTools` names, and only the tools a request sent can run.\n */\n readonly tools: readonly AnyTool[];\n readonly output: AnyTool | undefined;\n readonly maxSteps: number;\n /** The most the run's model calls may cost, in USD, or `undefined` for no cap (D9). */\n readonly budgetUsd?: number;\n /** How deeply this run is nested inside other agents' tool calls, and the deepest nesting allowed (D11). */\n readonly depth: number;\n readonly maxDepth: number;\n readonly modelOptions: CallOptions;\n readonly interceptors: Interceptors;\n /** The default progress policy, run after the caller's `shouldStop`, or `undefined` when it is off (D11). */\n readonly progress?: ProgressCheck;\n /** The messages a caller queued with `steer()` and `followUp()`, applied only at step boundaries. */\n readonly steering: SteeringQueue;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n}\n\n/** Sends one event; the run adds the `EventBase` fields. */\nexport type Emit = (body: AgentEventBody, stepIndex: number) => void;\n\n/**\n * Resolves once every observer has handled the events sent so far. The loop calls it only once it has its outcome,\n * and the run treats the first call as the point after which an abort no longer counts.\n */\nexport type Drain = () => Promise<void>;\n\n/** How a run ended, before its usage, cost and messages are attached. */\ntype Outcome =\n | { readonly stopReason: \"done\"; readonly output: unknown }\n | { readonly stopReason: \"max_steps\" | \"aborted\" }\n | {\n readonly stopReason: \"budget\";\n readonly reason: string;\n readonly budgetUsd: number;\n readonly spentUsd: number;\n readonly projectedUsd: number;\n }\n | { readonly stopReason: \"error\"; readonly error: RunError }\n | { readonly stopReason: \"stopped\"; readonly stoppedBy: string }\n | { readonly stopReason: \"no_progress\"; readonly reason: string };\n\n/** What changes while a run goes on. */\nclass LoopState {\n readonly setup: LoopSetup;\n readonly emit: Emit;\n readonly messages: Message[];\n readonly added: Message[];\n readonly drain: Drain;\n readonly hooks: HookRunner;\n readonly #wire: ReadonlyMap<AnyTool, WireTool>;\n /** The tools the latest request sent; the tool calls of its response may run only these. */\n active: readonly AnyTool[] = [];\n steps = 0;\n stepIndex = 0;\n usage: Usage = emptyUsage();\n lastUsage: Usage | undefined;\n cost: Cost | undefined;\n output: unknown;\n /** Set when the run was kept going to deliver a follow-up, so the next step boundary applies the follow-ups too. */\n releaseFollowUps = false;\n\n constructor(setup: LoopSetup, emit: Emit, drain: Drain) {\n this.setup = setup;\n this.emit = emit;\n this.drain = drain;\n this.messages = [...setup.history, ...setup.input];\n this.added = [...setup.input];\n this.#wire = new Map(setup.tools.map((tool) => [tool, toWireTool(tool)]));\n this.hooks = new HookRunner({\n interceptors: setup.interceptors,\n runId: setup.runId,\n signal: setup.signal,\n clock: setup.clock,\n stepIndex: () => this.stepIndex,\n send: (body) => this.send(body),\n });\n }\n\n /** The wire form of each of `tools`, as a request sends them. */\n wireOf(tools: readonly AnyTool[]): WireTool[] {\n // Every tool of the run was lowered in the constructor, and a request names only the run's tools.\n return tools.map((tool) => this.#wire.get(tool) as WireTool);\n }\n\n send(body: AgentEventBody): void {\n this.emit(body, this.stepIndex);\n }\n\n append(message: Message): void {\n this.messages.push(message);\n this.added.push(message);\n }\n}\n\n/**\n * The stream options a request event records: everything but the payload hook, the abort signal and the caps, as the\n * gateway's own request dump leaves them out. An untyped caller may still pass a signal or caps in `modelOptions`.\n */\nfunction dumpedOptions(options: CallOptions): DumpedOptions {\n const { onPayload: _onPayload, signal: _signal, caps: _caps, ...rest } = options as StreamOptions;\n return rest;\n}\n\n/** Re-emits one model event as a run event, and returns the final message once the terminal event arrives. */\nfunction forward(state: LoopState, event: GatewayEvent): AssistantMessage | undefined {\n switch (event.type) {\n case \"done\":\n case \"error\":\n return event.message;\n case \"start\":\n return undefined;\n case \"retry\":\n state.send({ type: \"retry\", attempt: event.attempt, delayMs: event.delayMs, error: event.error });\n return undefined;\n case \"warning\":\n state.send({ type: \"warning\", code: \"model_warning\", detail: `${event.code}: ${event.message}` });\n return undefined;\n case \"text_start\":\n case \"reasoning_start\":\n case \"tool_input_start\":\n state.send({ type: event.type, index: event.index });\n return undefined;\n case \"text_delta\":\n case \"reasoning_delta\":\n case \"tool_input_delta\":\n state.send({ type: event.type, index: event.index, delta: event.delta });\n return undefined;\n default:\n state.send({ type: event.type, index: event.index, block: event.block });\n return undefined;\n }\n}\n\n/** One model call as it will be sent, after `transformContext` and `beforeModelCall`. */\ninterface Request {\n readonly model: Model;\n readonly context: ModelContext;\n readonly options: CallOptions;\n readonly active: readonly AnyTool[];\n}\n\n/** The tools a request sends unless `beforeModelCall` names others: the ones whose exposure is `direct`. */\nfunction directTools(tools: readonly AnyTool[]): AnyTool[] {\n return tools.filter((tool) => (tool.exposure ?? \"direct\") === \"direct\");\n}\n\n/** The tools `names` picks, in definition order whatever order `names` is in. */\nfunction toolsNamed(tools: readonly AnyTool[], names: readonly string[]): AnyTool[] {\n const unknown = names.filter((name) => !tools.some((tool) => tool.name === name));\n if (unknown.length > 0) {\n throw new SdkError(\"invalid_hook_result\", `activeTools names unknown tools: ${unknown.join(\", \")}`);\n }\n return tools.filter((tool) => names.includes(tool.name));\n}\n\nfunction patched(state: LoopState, request: Request, patch: ModelCallPatch): Request {\n const active = patch.activeTools === undefined ? request.active : toolsNamed(state.setup.tools, patch.activeTools);\n const { system, messages } = request.context;\n return {\n model: patch.model ?? request.model,\n options: patch.options ?? request.options,\n active,\n context: {\n system: patch.system ?? system,\n messages: patch.messages === undefined ? messages : [...patch.messages],\n tools: state.wireOf(active),\n },\n };\n}\n\n/**\n * Builds one call's request: the transcript, or the view `transformContext` returns for this call alone, then the\n * changes `beforeModelCall` asks for. The run's own transcript is never replaced by either.\n */\nasync function buildRequest(state: LoopState): Promise<Request> {\n const { model, system, modelOptions, tools } = state.setup;\n const view = await state.hooks.transformContext({\n system,\n messages: state.messages,\n model: model.ref,\n lastUsage: state.lastUsage,\n });\n const active = directTools(tools);\n const context = { system, messages: [...(view ?? state.messages)], tools: state.wireOf(active) };\n const request: Request = { model, context, options: modelOptions, active };\n const patch = await state.hooks.beforeModelCall({ context, options: modelOptions });\n return patch === undefined ? request : patched(state, request, patch);\n}\n\n/** Streams one request, re-emitting its events, and returns the model's final message. */\nasync function streamRequest(state: LoopState, request: Request): Promise<AssistantMessage> {\n const { model, context, options } = request;\n state.send({ type: \"model_call_start\", request: { model: model.ref, context, options: dumpedOptions(options) } });\n let message: AssistantMessage | undefined;\n for await (const event of model.stream(context, { ...options, signal: state.setup.signal })) {\n message = forward(state, event) ?? message;\n }\n if (message === undefined) {\n throw new SdkError(\"invalid_model_stream\", \"the model's stream ended without a done or error event\");\n }\n return message;\n}\n\n/** Adds a model call's response to the transcript and reports it. */\nfunction record(state: LoopState, message: AssistantMessage): void {\n state.append(message);\n state.send({ type: \"model_call_end\", message });\n}\n\n/**\n * What the transcript holds for a response whose `afterModelCall` failed while the run fails closed: no content, so a\n * check that crashed can't let the response through, but the call's usage and cost, which were billed. Its error stop\n * reason makes the replay pass skip it if the run is continued.\n */\nfunction withheld(original: AssistantMessage): AssistantMessage {\n const { model, usage, cost, lastAttemptUsage } = original;\n return {\n role: \"assistant\",\n content: [],\n model,\n stopReason: \"error\",\n error: { kind: \"fatal\", message: \"the response was withheld, because its afterModelCall check failed\" },\n usage,\n ...(lastAttemptUsage === undefined ? {} : { lastAttemptUsage }),\n cost,\n };\n}\n\n/**\n * The budget check before a call (D9): the outcome that ends the run when the spend so far plus the call's projected\n * cost would pass `budgetUsd`, or `undefined` when the call may go out. It checks the request as it will be sent,\n * after the interceptors have changed it, and projects with the model the request names.\n */\nfunction budgetBlock(state: LoopState, request: Request): Outcome | undefined {\n const { budgetUsd } = state.setup;\n if (budgetUsd === undefined) return undefined;\n const projected = projectCallCost(request.model, request.context, request.options);\n const verdict = checkBudget(budgetUsd, state.cost, projected);\n switch (verdict.kind) {\n case \"allow\":\n return undefined;\n case \"unknown\":\n return { stopReason: \"error\", error: verdict.error };\n case \"exceeded\":\n return {\n stopReason: \"budget\",\n reason: verdict.reason,\n budgetUsd,\n spentUsd: verdict.spentUsd,\n projectedUsd: verdict.projectedUsd,\n };\n }\n}\n\n/**\n * Makes one model call, streams its events and records the response. The call's usage and cost are the model's own\n * message's, so an `afterModelCall` replacement changes what the run goes on with, never what it is billed. When\n * `afterModelCall` fails and the run fails closed, a withheld stand-in is recorded before the run ends, so the\n * transcript and `model_call_end` still account for the billed call and none of its tool calls run.\n */\nasync function callModel(state: LoopState): Promise<AssistantMessage | { readonly blocked: Outcome }> {\n const request = await buildRequest(state);\n const blocked = budgetBlock(state, request);\n if (blocked !== undefined) return { blocked };\n state.active = request.active;\n const original = await streamRequest(state, request);\n state.steps += 1;\n state.usage = addUsage(state.usage, original.usage);\n state.lastUsage = original.usage;\n state.cost = state.cost === undefined ? original.cost : addCost(state.cost, original.cost);\n let message: AssistantMessage;\n try {\n message = await state.hooks.afterModelCall(original);\n } catch (error) {\n if (error instanceof HookFailure || (isSdkError(error) && error.code === \"invalid_hook_result\")) {\n record(state, withheld(original));\n }\n throw error;\n }\n record(state, message);\n return message;\n}\n\n/** The tool message the model reads for one call. */\nfunction toolMessage(entry: ToolCallResult): Message {\n return {\n role: \"tool\",\n callId: entry.call.callId,\n content: [...entry.result.content],\n isError: entry.result.isError === true,\n };\n}\n\n/** Runs the response's tool calls as the pipeline schedules them, recording each result in model order. */\nasync function runTools(state: LoopState, message: AssistantMessage): Promise<readonly ToolCallResult[]> {\n const { runId, signal, clock, output } = state.setup;\n return runToolCalls(message, state.active, {\n runId,\n signal,\n clock,\n depth: state.setup.depth,\n maxDepth: state.setup.maxDepth,\n ...state.hooks.pipelineHooks(),\n onStart: (call: ToolCall) =>\n state.send({ type: \"tool_call_start\", callId: call.callId, tool: call.name, input: call.input }),\n onUpdate: (callId, details) => state.send({ type: \"tool_call_update\", callId, details }),\n onResult: (entry) => {\n state.append(toolMessage(entry));\n if (output !== undefined && entry.call.name === output.name && entry.result.isError !== true) {\n state.output = entry.result.structured;\n }\n const ranWith = \"input\" in entry ? { input: entry.input } : {};\n state.send({ type: \"tool_call_end\", callId: entry.call.callId, result: entry.result, ...ranWith });\n },\n });\n}\n\n/** The failed call's error as the run reports it. A message without one counts as `fatal`. */\nfunction runErrorOf(message: AssistantMessage): RunError {\n const error = message.error;\n if (error === undefined) return { kind: \"fatal\", message: \"the model call failed without an error description\" };\n return { kind: error.kind, message: error.message, ...(error.status === undefined ? {} : { status: error.status }) };\n}\n\n/**\n * The stop check after one step. A finished answer, or a question for the user, wins over an abort that came too late\n * to change it; otherwise an abort stops the run before the step cap does. A text answer cut off at the output limit\n * also counts as finished: its message keeps `stopReason: \"length\"`.\n */\nfunction stopCheck(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Outcome | undefined {\n if (message.stopReason === \"error\") return { stopReason: \"error\", error: runErrorOf(message) };\n if (message.stopReason === \"aborted\") return { stopReason: \"aborted\" };\n const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);\n if (finished) return { stopReason: \"done\", output: state.output };\n // Until runs can pause for an answer, a clarification question stops the run, so the model never goes on as if the\n // user had been asked and answered.\n if (results.some(({ result }) => result.pause !== undefined && !result.isError)) {\n return { stopReason: \"stopped\", stoppedBy: CLARIFICATION };\n }\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n return undefined;\n}\n\n/**\n * What `shouldStop` changes about the stop check. A finished answer or an error stands whatever the hook says; the\n * hook can end a run that would go on, and can keep going a run the model ended by answering in text, until the\n * step cap.\n */\nfunction withVerdict(state: LoopState, natural: Outcome | undefined, verdict: StopVerdict): Outcome | undefined {\n if (natural !== undefined && verdict.kind !== \"continue\") return natural;\n switch (verdict.kind) {\n case \"stop\":\n return { stopReason: \"stopped\", stoppedBy: verdict.stoppedBy };\n case \"no_progress\":\n return { stopReason: \"no_progress\", reason: verdict.reason };\n case \"continue\":\n if (natural === undefined) return undefined;\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n state.append({ role: \"user\", content: verdict.content });\n return undefined;\n default:\n return natural;\n }\n}\n\n/**\n * Applies the queued messages before a model call: every steer, and the follow-ups too once the run was kept going to\n * deliver them. Each becomes a user message and a `steer_applied` event, in the order it was sent, and its receipt\n * resolves with the index of the step about to run.\n */\nfunction applySteering(state: LoopState): void {\n const { steering } = state.setup;\n const withFollowUps = state.releaseFollowUps;\n state.releaseFollowUps = false;\n for (const delivery of steering.take(withFollowUps)) {\n // A copy, so a caller who changes a receipt's message cannot change the transcript.\n state.append({ role: \"user\", content: delivery.message.map((block) => ({ ...block })) });\n state.send({ type: \"steer_applied\", receipt: delivery.deliver(state.stepIndex) });\n }\n}\n\n/**\n * Keeps a run that its model ended by answering going, when a message is waiting and the step cap leaves room for\n * one more call: a steer comes first, and follow-ups wait for the next time the run would end. Any other outcome\n * stands, as does a `stop` or `no_progress` verdict that `withVerdict` folded into `done`, and an abort that came\n * after the answer, which `stopCheck` lets the answer win over. The messages still waiting are rejected when the run\n * ends.\n */\nfunction withQueued(state: LoopState, outcome: Outcome | undefined, verdict: StopVerdict): Outcome | undefined {\n const { steering, maxSteps, signal } = state.setup;\n if (outcome?.stopReason !== \"done\" || !steering.hasPending() || state.steps >= maxSteps) return outcome;\n if (verdict.kind === \"stop\" || verdict.kind === \"no_progress\" || signal.aborted) return outcome;\n state.releaseFollowUps = !steering.hasSteers();\n return undefined;\n}\n\n/** The stop check after one step, then the `shouldStop` hook where it may change it. */\nasync function decide(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Promise<Outcome | undefined> {\n const natural = stopCheck(state, message, results);\n const endedByAnswer = natural?.stopReason === \"done\" && results.length === 0;\n if (natural !== undefined && !endedByAnswer) return natural;\n const verdict = await state.hooks.shouldStop({ messages: state.messages, lastMessage: message });\n const judged = await withProgress(state, verdict);\n const outcome = withVerdict(state, natural, judged);\n return endedByAnswer ? withQueued(state, outcome, judged) : outcome;\n}\n\n/**\n * The caller's verdict, unless the progress policy finds the run stuck. A caller's own stop stands, and a caller's\n * `{ continue }` or failed hook can't keep a stuck run going.\n */\nasync function withProgress(state: LoopState, verdict: StopVerdict): Promise<StopVerdict> {\n if (verdict.kind === \"stop\" || verdict.kind === \"no_progress\" || state.setup.progress === undefined) return verdict;\n const reason = await state.setup.progress(state.messages);\n return reason === undefined ? verdict : { kind: \"no_progress\", reason };\n}\n\n/** The outcome of a hook that failed while the run fails closed. A failure caused by an abort ends the run aborted. */\nfunction failedOutcome(state: LoopState, error: unknown): Outcome {\n if (!(error instanceof HookFailure)) throw error;\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n return { stopReason: \"error\", error: { kind: \"hook\", message: error.message } };\n}\n\nasync function runStep(state: LoopState): Promise<Outcome | undefined> {\n state.stepIndex = state.steps;\n state.send({ type: \"step_start\" });\n let outcome: Outcome | undefined;\n try {\n applySteering(state);\n const called = await callModel(state);\n if (\"blocked\" in called) {\n outcome = called.blocked;\n } else {\n const results = await runTools(state, called);\n outcome = await decide(state, called, results);\n }\n } catch (error) {\n outcome = failedOutcome(state, error);\n }\n state.send({ type: \"step_end\", stopCheck: outcome === undefined ? \"continue\" : \"stop\" });\n return outcome;\n}\n\n/**\n * An aborted run's transcript ends with an assistant message whose `stopReason` is `\"aborted\"`. When tool results end\n * the transcript, because the abort came while tools ran or cut off a response that held tool calls, the loop\n * appends an empty one after them; the replay pass drops it before any request.\n */\nfunction closeAborted(state: LoopState): void {\n const last = state.messages.at(-1);\n if (last?.role === \"assistant\" && last.stopReason === \"aborted\") return;\n state.append({\n role: \"assistant\",\n content: [],\n model: state.setup.model.ref,\n stopReason: \"aborted\",\n usage: emptyUsage(),\n cost: { ...NO_COST },\n });\n}\n\nfunction resultOf(state: LoopState, outcome: Outcome): RunResult {\n const base = {\n messages: state.added,\n context: { system: state.setup.system, messages: state.messages },\n usage: state.usage,\n cost: state.cost ?? { ...NO_COST },\n steps: state.steps,\n };\n return { ...base, ...outcome } as RunResult;\n}\n\n/**\n * Ends the run: the settle event comes once every observer has seen what came before it, and `run_end` after that.\n * An observer's failure while handling `agent_settled` is reported between the two; one while handling `run_end` is\n * dropped, so `run_end` stays the last event. The result is returned only once observers have seen it.\n */\nasync function finish(state: LoopState, outcome: Outcome): Promise<RunResult> {\n if (outcome.stopReason === \"aborted\") closeAborted(state);\n if (outcome.stopReason === \"max_steps\") {\n state.send({ type: \"warning\", code: \"max_steps\", detail: `the run reached maxSteps (${state.setup.maxSteps})` });\n }\n if (outcome.stopReason === \"error\") state.send({ type: \"error\", error: outcome.error });\n await state.drain();\n state.send({ type: \"agent_settled\" });\n await state.drain();\n const result = resultOf(state, outcome);\n state.send({ type: \"run_end\", result });\n await state.drain();\n return result;\n}\n\n/**\n * Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results\n * already received are in the transcript.\n */\nexport async function runLoop(setup: LoopSetup, emit: Emit, drain: Drain): Promise<RunResult> {\n const state = new LoopState(setup, emit, drain);\n // A budget needs a price to check against, so a model without one is refused before it is called (D4).\n const refused = setup.budgetUsd === undefined ? undefined : unknownPriceError(setup.model);\n let outcome: Outcome | undefined = refused === undefined ? undefined : { stopReason: \"error\", error: refused };\n try {\n while (outcome === undefined) {\n outcome = setup.signal.aborted ? { stopReason: \"aborted\" } : await runStep(state);\n }\n } finally {\n // The run has its outcome, or threw for a programmer error, so a message still waiting can no longer reach a\n // model call, and its receipt must not hang.\n setup.steering.close();\n }\n return finish(state, outcome);\n}\n"]}
|
package/dist/run.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ import type { AgentEvent } from "./events.js";
|
|
|
8
8
|
import type { CallOptions, Interceptors, Observer } from "./hooks.js";
|
|
9
9
|
import { type ProgressPolicy } from "./progress.js";
|
|
10
10
|
import type { Context, DoneResult, RunResult } from "./result.js";
|
|
11
|
+
import { type DeliveryReceipt } from "./steering.js";
|
|
11
12
|
import type { Clock } from "./testing/determinism.js";
|
|
12
13
|
import type { ToolContext, ToolDefinition } from "./tools/types.js";
|
|
13
14
|
/** The options `run()` and `continueRun()` share. */
|
|
@@ -112,6 +113,23 @@ export interface Run<S = unknown> extends AsyncIterable<AgentEvent> {
|
|
|
112
113
|
* in the `observers` option.
|
|
113
114
|
*/
|
|
114
115
|
on(observer: Observer): () => void;
|
|
116
|
+
/**
|
|
117
|
+
* Queues a user message that redirects the run. The run applies it at the next step boundary: after the model call
|
|
118
|
+
* or tool batch in flight, never inside it, and before the next model call. The promise resolves with a
|
|
119
|
+
* `DeliveryReceipt` once the message is in the transcript, and the run emits a `steer_applied` event for it. It
|
|
120
|
+
* rejects with an `SdkError` whose code is `undelivered_message` when the run ends first, and with
|
|
121
|
+
* `invalid_run_options` for a blank message or a block that isn't text or an image. Steers are applied in the
|
|
122
|
+
* order they were sent.
|
|
123
|
+
*/
|
|
124
|
+
steer(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;
|
|
125
|
+
/**
|
|
126
|
+
* Queues a user message that waits until the run would otherwise end. When the model has answered and no tool call
|
|
127
|
+
* is left, the run applies every waiting follow-up as user messages and makes one more model call, so a follow-up
|
|
128
|
+
* sent before the run ends extends it by one step. A steer that is waiting goes first. The run still ends, and the
|
|
129
|
+
* follow-up rejects with `undelivered_message`, when another stop reason ends it: a `shouldStop` hook or progress
|
|
130
|
+
* policy that stops it, its output tool, an abort or `maxSteps`. The receipt works as for `steer()`.
|
|
131
|
+
*/
|
|
132
|
+
followUp(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;
|
|
115
133
|
}
|
|
116
134
|
/**
|
|
117
135
|
* The `depth` and `maxDepth` options for a run that a tool starts: one level deeper than the tool's own run, under
|
package/dist/run.js
CHANGED
|
@@ -3,6 +3,7 @@ import { RunStoppedError, SdkError } from "./errors.js";
|
|
|
3
3
|
import { runLoop } from "./loop.js";
|
|
4
4
|
import { ObserverBus } from "./observers.js";
|
|
5
5
|
import { progressCheck, resolveProgress } from "./progress.js";
|
|
6
|
+
import { SteeringQueue } from "./steering.js";
|
|
6
7
|
import { preparedSchemaOf } from "./tools/define.js";
|
|
7
8
|
import { SDK_VERSION } from "./version.js";
|
|
8
9
|
/** The step cap's default, counted in model calls. */
|
|
@@ -66,11 +67,13 @@ class RunHandle {
|
|
|
66
67
|
#settled = false;
|
|
67
68
|
/** Set by `run_end`: nothing may follow it, so a late observer report is dropped. */
|
|
68
69
|
#closed = false;
|
|
70
|
+
#steering;
|
|
69
71
|
#failure;
|
|
70
72
|
#stepIndex = 0;
|
|
71
73
|
constructor(setup, signal, watch) {
|
|
72
74
|
this.id = setup.runId;
|
|
73
75
|
this.#clock = setup.clock;
|
|
76
|
+
this.#steering = new SteeringQueue(setup.runId);
|
|
74
77
|
this.#bus = new ObserverBus((hook, error) => {
|
|
75
78
|
if (!this.#closed)
|
|
76
79
|
this.#push({ type: "hook_error", hook, error: messageOf(error) }, this.#stepIndex);
|
|
@@ -95,7 +98,7 @@ class RunHandle {
|
|
|
95
98
|
this.#settled = true;
|
|
96
99
|
return this.#bus.flush();
|
|
97
100
|
};
|
|
98
|
-
const loop = Promise.resolve().then(() => runLoop({ ...setup, signal: this.#controller.signal }, emit, drain));
|
|
101
|
+
const loop = Promise.resolve().then(() => runLoop({ ...setup, signal: this.#controller.signal, steering: this.#steering }, emit, drain));
|
|
99
102
|
// The loop's result type is `RunResult<unknown>`; only the output tool, whose type is `S`, fills `output`.
|
|
100
103
|
this.result = loop;
|
|
101
104
|
// Handling the rejection here also keeps a caller who only iterates from an unhandled rejection: iteration
|
|
@@ -112,6 +115,12 @@ class RunHandle {
|
|
|
112
115
|
checkObserver(observer);
|
|
113
116
|
return this.#bus.add(observer);
|
|
114
117
|
}
|
|
118
|
+
steer(message) {
|
|
119
|
+
return this.#steering.add("steer", message);
|
|
120
|
+
}
|
|
121
|
+
followUp(message) {
|
|
122
|
+
return this.#steering.add("follow_up", message);
|
|
123
|
+
}
|
|
115
124
|
[Symbol.asyncIterator]() {
|
|
116
125
|
let cursor = 0;
|
|
117
126
|
return {
|
package/dist/run.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGxD,OAAO,EAAkB,OAAO,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAA2C,aAAa,EAAE,eAA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esContent":["/**\n * `run()`, `continueRun()` and `runOrThrow()`, and the `Run` object they share (SDK plan §3.3; D10). A run streams\n * its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the\n * non-streaming caller drive one loop.\n */\nimport type { ContentBlock, Message, Model } from \"@buildanagent/gateway\";\nimport { checkBudgetOption } from \"./budget.js\";\nimport { RunStoppedError, SdkError } from \"./errors.js\";\nimport type { AgentEvent, AgentEventBody } from \"./events.js\";\nimport type { CallOptions, Interceptors, Observer } from \"./hooks.js\";\nimport { type LoopSetup, runLoop } from \"./loop.js\";\nimport { ObserverBus } from \"./observers.js\";\nimport { type ProgressCheck, type ProgressPolicy, progressCheck, resolveProgress } from \"./progress.js\";\nimport type { Context, DoneResult, RunResult } from \"./result.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { preparedSchemaOf } from \"./tools/define.js\";\nimport type { AnyTool } from \"./tools/pipeline.js\";\nimport type { ToolContext, ToolDefinition } from \"./tools/types.js\";\nimport { SDK_VERSION } from \"./version.js\";\n\n/** The step cap's default, counted in model calls. */\nconst DEFAULT_MAX_STEPS = 20;\n\n/** The depth cap's default (D11): a top-level run, its subagents and their subagents may run, and no deeper. */\nconst DEFAULT_MAX_DEPTH = 2;\n\n/** How long the run waits, by default, for an observer to catch up before it drops it. */\nconst DEFAULT_OBSERVER_TIMEOUT_MS = 10_000;\n/** The longest delay `setTimeout` accepts; a larger one fires at once on Node and workerd alike. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\nconst systemClock: Clock = { now: () => new Date().toISOString() };\nconst randomIds = (): string => globalThis.crypto.randomUUID();\n\n/** The options `run()` and `continueRun()` share. */\nexport interface RunOptions<S = unknown> {\n /** The model, from `createModel()`. */\n readonly model: Model;\n /**\n * The tools the model may call. Tools whose `exposure` is `deferred` or `hidden` are not sent unless a\n * `beforeModelCall` interceptor names them in `activeTools`.\n */\n readonly tools?: readonly ToolDefinition<unknown, unknown>[];\n /**\n * A tool from `outputTool()` whose input is the final answer. It is sent with the other tools; once the model calls\n * it with input that passes its schema, the run ends `done`, and `result.output` holds the validated answer.\n */\n readonly output?: ToolDefinition<S, S>;\n /**\n * The most model calls the run may make. Default 20. A run that reaches it while the model still wants to go on\n * ends with `stopReason: \"max_steps\"` and emits a `warning` event with `code: \"max_steps\"`.\n */\n readonly maxSteps?: number;\n /**\n * The most the run's model calls may cost, in USD. Before each call the run projects its cost with\n * `projectCallCost()` and, if the spend so far plus that projection would pass the cap, ends with\n * `stopReason: \"budget\"` without making the call. The cap counts the calls this run makes, not the cost of the\n * history a `continueRun()` starts from. A budgeted run on a model whose price is unknown ends `error` with\n * `error.kind: \"unknown_price\"` before its first call, because it could not tell what it spent. Without it, a run\n * has no cap.\n */\n readonly budgetUsd?: number;\n /**\n * The default progress policy: the run ends `no_progress` after 3 identical failing tool calls in a row, or after 5\n * calls to a tool with one `progressKey` and no success between them. It runs after your own `shouldStop`, whose\n * `{ continue }` can't keep a stuck run going. Pass numbers to change either threshold, or `false` to turn the\n * policy off.\n */\n readonly progress?: ProgressPolicy | false;\n /**\n * How deeply this run is nested inside other agents' tool calls. Default 0. A tool that starts a run of its own\n * passes `depth: ctx.depth + 1` and `maxDepth: ctx.maxDepth`; `run()` throws an `SdkError` with code\n * `max_depth_exceeded` when `depth` is above `maxDepth`, which the tool's caller reads as an error result.\n */\n readonly depth?: number;\n /** The deepest nesting allowed, which tools read as `ctx.maxDepth`. Default 2. */\n readonly maxDepth?: number;\n /** Aborts the run, like `run.abort()`. */\n readonly signal?: AbortSignal;\n /** Options for every model call, such as `maxOutputTokens`. The run passes its own abort signal. */\n readonly modelOptions?: CallOptions;\n /**\n * The interceptors: hooks that can change the run at six moments. A run takes one object; join several with\n * `composeInterceptors()`. See `Interceptors` for the order and for what a failing hook does.\n */\n readonly interceptors?: Interceptors;\n /**\n * Observers, which receive every event from `run_start` on and can't change the run. Each observer sees the events in\n * order and waits for its own promises, but observers don't wait for each other. An observer that throws becomes a\n * `hook_error` event. The run waits for every observer to handle the last event before it settles, for at most\n * `observerTimeoutMs` each time it waits; an observer that hasn't caught up by then is removed and reported as a\n * `hook_error`.\n */\n readonly observers?: readonly Observer[];\n /**\n * The longest the run waits for its observers each time it waits for them: before `agent_settled`, before\n * `run_end` and before it settles. A number from 1 to 2147483647; the default is 10000. It bounds an observer whose promise never settles.\n */\n readonly observerTimeoutMs?: number;\n /** Stamps each event's `timestamp`, and is passed to tools. Defaults to the system clock. */\n readonly clock?: Clock;\n /** Makes the run's id. Defaults to `crypto.randomUUID()`. */\n readonly idGenerator?: () => string;\n}\n\n/** What `run()` takes besides the shared options. */\nexport interface RunInput {\n /** The system prompt. */\n readonly system: string;\n /** The user's message that starts the run. */\n readonly input: string | readonly ContentBlock[];\n /** Earlier messages to send before `input`, such as a previous conversation. */\n readonly history?: readonly Message[];\n}\n\n/**\n * A run in progress. Iterate it to stream its events: each iteration starts from the run's first event, so you can\n * start iterating at any time. Await `result` for the outcome; it rejects only for a programmer error, such as a\n * tool that returns a malformed result, and iteration then throws the same error after the last event.\n */\nexport interface Run<S = unknown> extends AsyncIterable<AgentEvent> {\n /** The run's id, which every event carries. */\n readonly id: string;\n /** The outcome, once the run has stopped. */\n readonly result: Promise<RunResult<S>>;\n /**\n * Stops the run. A model call in flight ends, a running tool sees its `signal` fire, and calls that haven't started\n * get an error result instead. The run then ends with `stopReason: \"aborted\"`. Does nothing once the run has its\n * outcome and is ending, which is before `agent_settled`.\n */\n abort(reason?: string): void;\n /**\n * Adds an observer that receives the events from now on, in order, and returns the function that removes it. An\n * event that was queued for it but not yet handled is dropped when you remove it. Add it right after `run()` to\n * see every event but `run_start`, which `run()` emits before it returns; to see that one too, pass the observer\n * in the `observers` option.\n */\n on(observer: Observer): () => void;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction checkObserver(observer: unknown): void {\n if (typeof observer !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `an observer must be a function, got ${typeof observer}`);\n }\n}\n\nconst HOOK_NAMES = [\n \"transformContext\",\n \"beforeModelCall\",\n \"afterModelCall\",\n \"beforeToolCall\",\n \"afterToolCall\",\n \"shouldStop\",\n] as const;\n\n/** Checks the interceptors option once, so a misspelt or mistyped hook fails at `run()` and not mid-run. */\nfunction checkInterceptors(interceptors: Interceptors): Interceptors {\n if (typeof interceptors !== \"object\" || interceptors === null) {\n throw new SdkError(\"invalid_run_options\", \"interceptors must be an object of hooks\");\n }\n for (const name of HOOK_NAMES) {\n const hook: unknown = interceptors[name];\n if (hook !== undefined && typeof hook !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.${name} must be a function, got ${typeof hook}`);\n }\n }\n const { onFailure } = interceptors;\n if (onFailure !== undefined && onFailure !== \"fail_closed\" && onFailure !== \"continue\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.onFailure must be \"fail_closed\" or \"continue\"`);\n }\n return interceptors;\n}\n\nfunction reasonOf(reason: unknown): string | undefined {\n if (typeof reason === \"string\") return reason;\n return reason instanceof Error ? reason.message : undefined;\n}\n\nclass RunHandle<S> implements Run<S> {\n readonly id: string;\n readonly result: Promise<RunResult<S>>;\n readonly #events: AgentEvent[] = [];\n readonly #controller = new AbortController();\n readonly #clock: Clock;\n readonly #bus: ObserverBus;\n #waiters: (() => void)[] = [];\n #ended = false;\n /** Set once the loop has its outcome and starts to end the run, so `abort()` no longer does anything. */\n #settled = false;\n /** Set by `run_end`: nothing may follow it, so a late observer report is dropped. */\n #closed = false;\n #failure: { readonly error: unknown } | undefined;\n #stepIndex = 0;\n\n constructor(setup: Omit<LoopSetup, \"signal\">, signal: AbortSignal | undefined, watch: ObserverSetup) {\n this.id = setup.runId;\n this.#clock = setup.clock;\n this.#bus = new ObserverBus((hook, error) => {\n if (!this.#closed) this.#push({ type: \"hook_error\", hook, error: messageOf(error) }, this.#stepIndex);\n }, watch.timeoutMs);\n const { observers } = watch;\n for (const observer of observers) this.#bus.add(observer);\n const emit = (body: AgentEventBody, stepIndex: number) => this.#push(body, stepIndex);\n const { model } = setup;\n const versions = { sdkVersion: SDK_VERSION, specVersion: \"v1\" as const, defaultsHash: \"\", capabilities: [] };\n emit({ type: \"run_start\", ...versions, model: model.ref }, 0);\n const forwardAbort = () => this.abort(reasonOf(signal?.reason));\n if (signal?.aborted) forwardAbort();\n else signal?.addEventListener(\"abort\", forwardAbort, { once: true });\n // The loop starts after this turn, so an observer added with `run.on()` straight after `run()` sees every event\n // after `run_start`, and a `run.abort()` straight after it stops the run before its first model call.\n // The loop drains the observers only once it has its outcome (`finish()`), so the first drain is also where an\n // abort stops mattering: it could no longer change the outcome, only add an `abort` event after it.\n const drain = () => {\n this.#settled = true;\n return this.#bus.flush();\n };\n const loop = Promise.resolve().then(() => runLoop({ ...setup, signal: this.#controller.signal }, emit, drain));\n // The loop's result type is `RunResult<unknown>`; only the output tool, whose type is `S`, fills `output`.\n this.result = loop as Promise<RunResult<S>>;\n // Handling the rejection here also keeps a caller who only iterates from an unhandled rejection: iteration\n // throws the same error.\n loop.then(\n () => this.#end(signal, forwardAbort, undefined),\n (error: unknown) => this.#end(signal, forwardAbort, { error }),\n );\n }\n\n abort(reason?: string): void {\n if (this.#settled || this.#ended || this.#controller.signal.aborted) return;\n this.#push(reason === undefined ? { type: \"abort\" } : { type: \"abort\", reason }, this.#stepIndex);\n this.#controller.abort(reason);\n }\n\n on(observer: Observer): () => void {\n checkObserver(observer);\n return this.#bus.add(observer);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {\n let cursor = 0;\n return {\n next: async () => {\n while (cursor >= this.#events.length && !this.#ended) {\n await new Promise<void>((resolve) => this.#waiters.push(resolve));\n }\n const event = this.#events[cursor];\n if (event !== undefined) {\n cursor += 1;\n return { value: event, done: false };\n }\n if (this.#failure !== undefined) throw this.#failure.error;\n return { value: undefined, done: true };\n },\n };\n }\n\n #push(body: AgentEventBody, stepIndex: number): void {\n this.#stepIndex = stepIndex;\n if (body.type === \"run_end\") this.#closed = true;\n const base = { runId: this.id, seq: this.#events.length, stepIndex, timestamp: this.#clock.now() };\n const event = { ...base, ...body } as AgentEvent;\n this.#events.push(event);\n this.#bus.deliver(event);\n this.#wake();\n }\n\n #end(signal: AbortSignal | undefined, forwardAbort: () => void, failure: { readonly error: unknown } | undefined) {\n signal?.removeEventListener(\"abort\", forwardAbort);\n this.#failure = failure;\n this.#ended = true;\n this.#wake();\n }\n\n #wake(): void {\n const waiters = this.#waiters;\n this.#waiters = [];\n for (const wake of waiters) wake();\n }\n}\n\nfunction isModel(model: unknown): model is Model {\n const candidate = model as Partial<Model> | null;\n return (\n typeof candidate === \"object\" &&\n candidate !== null &&\n typeof candidate.stream === \"function\" &&\n typeof candidate.price === \"function\" &&\n typeof candidate.ref === \"object\"\n );\n}\n\n/** Every tool the run may send, the output tool last unless `tools` already holds it, after checking each one. */\nfunction toolsOf(options: RunOptions<unknown>): AnyTool[] {\n const tools = [...(options.tools ?? [])] as AnyTool[];\n const output = options.output as AnyTool | undefined;\n if (output !== undefined && !tools.includes(output)) tools.push(output);\n const names = new Set<string>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (names.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n names.add(tool.name);\n }\n return tools;\n}\n\nfunction isCount(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n}\n\n/**\n * The `depth` and `maxDepth` options for a run that a tool starts: one level deeper than the tool's own run, under\n * the same cap. Spread it into the nested `run()`; the nested run throws `max_depth_exceeded` when the tool was\n * already at `maxDepth`.\n */\nexport function nestedRunDepth(ctx: Pick<ToolContext, \"depth\" | \"maxDepth\">): { depth: number; maxDepth: number } {\n return { depth: ctx.depth + 1, maxDepth: ctx.maxDepth };\n}\n\n/** Checks `depth` and `maxDepth`, and refuses a run nested deeper than the cap allows (D11). */\nfunction depthsOf(options: RunOptions<unknown>): { depth: number; maxDepth: number } {\n const { depth = 0, maxDepth = DEFAULT_MAX_DEPTH } = options;\n if (!isCount(depth) || !isCount(maxDepth)) {\n throw new SdkError(\n \"invalid_run_options\",\n `depth and maxDepth must be whole numbers, 0 or more, got ${String(depth)} and ${String(maxDepth)}`,\n );\n }\n if (depth > maxDepth) {\n throw new SdkError(\"max_depth_exceeded\", `a run at depth ${depth} is deeper than maxDepth ${maxDepth} allows`);\n }\n return { depth, maxDepth };\n}\n\n/**\n * The default progress policy for this run, or `undefined` when `progress: false` turns it off. `skip` is the number\n * of messages before the run's own.\n */\nfunction progressOf(options: RunOptions<unknown>, tools: readonly AnyTool[], skip: number): ProgressCheck | undefined {\n const policy = resolveProgress(options.progress);\n return policy === undefined ? undefined : progressCheck(tools, policy, skip);\n}\n\nfunction setupOf(options: RunOptions<unknown>, context: Context, input: readonly Message[]): Omit<LoopSetup, \"signal\"> {\n if (!isModel(options.model)) {\n throw new SdkError(\n \"invalid_run_options\",\n \"the model must come from createModel(), such as createModel({ adapter, id })\",\n );\n }\n const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;\n if (!Number.isInteger(maxSteps) || maxSteps < 1) {\n throw new SdkError(\"invalid_run_options\", `maxSteps must be a positive integer, got ${maxSteps}`);\n }\n const budgetUsd = checkBudgetOption(options.budgetUsd);\n const tools = toolsOf(options);\n const { depth, maxDepth } = depthsOf(options);\n const progress = progressOf(options, tools, context.messages.length + input.length);\n if (options.output !== undefined && (options.output.exposure ?? \"direct\") !== \"direct\") {\n throw new SdkError(\n \"invalid_run_options\",\n `the output tool \"${options.output.name}\" must be sent to the model, so its exposure must be \"direct\"`,\n );\n }\n return {\n runId: (options.idGenerator ?? randomIds)(),\n model: options.model,\n system: context.system,\n history: context.messages,\n input,\n tools,\n output: options.output as AnyTool | undefined,\n maxSteps,\n ...(budgetUsd === undefined ? {} : { budgetUsd }),\n depth,\n maxDepth,\n modelOptions: options.modelOptions ?? {},\n interceptors: checkInterceptors(options.interceptors ?? {}),\n ...(progress === undefined ? {} : { progress }),\n clock: options.clock ?? systemClock,\n };\n}\n\n/** The observers a run starts with, and how long it waits for them. */\ninterface ObserverSetup {\n readonly observers: readonly Observer[];\n readonly timeoutMs: number;\n}\n\nfunction observersOf(options: RunOptions<unknown>): ObserverSetup {\n const observers = options.observers ?? [];\n for (const observer of observers) checkObserver(observer);\n const timeoutMs = options.observerTimeoutMs ?? DEFAULT_OBSERVER_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_MS) {\n throw new SdkError(\n \"invalid_run_options\",\n `observerTimeoutMs must be a number from 1 to ${MAX_TIMER_MS}, got ${timeoutMs}`,\n );\n }\n return { observers, timeoutMs };\n}\n\n/**\n * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool\n * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an\n * unusable option: a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool\n * that isn't sent to the model, or two tools with one name.\n */\nexport function run<S = unknown>(options: RunOptions<S> & RunInput): Run<S> {\n const content = typeof options.input === \"string\" ? [{ type: \"text\" as const, text: options.input }] : options.input;\n const input: Message = { role: \"user\", content: [...content] };\n const setup = setupOf(options, { system: options.system, messages: options.history ?? [] }, [input]);\n return new RunHandle<S>(setup, options.signal, observersOf(options));\n}\n\n/**\n * Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like\n * `run()`, from the last message in the context, and `result.messages` holds only the messages it adds. The context\n * is sent as it stands, so add a user message to one that ends with the model's answer, such as a `done` result's.\n */\nexport function continueRun<S = unknown>(context: Context, options: RunOptions<S>): Run<S> {\n return new RunHandle<S>(setupOf(options, context, []), options.signal, observersOf(options));\n}\n\n/**\n * Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that\n * carries the result and the context to continue from.\n */\nexport async function runOrThrow<S>(started: Run<S>): Promise<DoneResult<S>> {\n const result = await started.result;\n if (result.stopReason === \"done\") return result;\n throw new RunStoppedError(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M,KAAK,GAAG,OAAO,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,OAAO,IAAI,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;IACrG,OAAO,IAAI,SAAS,CAAI,KAAK,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AACvE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAc,OAAgB,EAAE,OAAsB;IAC/E,OAAO,IAAI,SAAS,CAAI,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AAC/F,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAI,OAAe;IACjD,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC;IACpC,IAAI,MAAM,CAAC,UAAU,KAAK,MAAM;QAAE,OAAO,MAAM,CAAC;IAChD,MAAM,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * `run()`, `continueRun()` and `runOrThrow()`, and the `Run` object they share (SDK plan §3.3; D10). A run streams\n * its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the\n * non-streaming caller drive one loop.\n */\nimport type { ContentBlock, Message, Model } from \"@buildanagent/gateway\";\nimport { checkBudgetOption } from \"./budget.js\";\nimport { RunStoppedError, SdkError } from \"./errors.js\";\nimport type { AgentEvent, AgentEventBody } from \"./events.js\";\nimport type { CallOptions, Interceptors, Observer } from \"./hooks.js\";\nimport { type LoopSetup, runLoop } from \"./loop.js\";\nimport { ObserverBus } from \"./observers.js\";\nimport { type ProgressCheck, type ProgressPolicy, progressCheck, resolveProgress } from \"./progress.js\";\nimport type { Context, DoneResult, RunResult } from \"./result.js\";\nimport { type DeliveryReceipt, SteeringQueue } from \"./steering.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { preparedSchemaOf } from \"./tools/define.js\";\nimport type { AnyTool } from \"./tools/pipeline.js\";\nimport type { ToolContext, ToolDefinition } from \"./tools/types.js\";\nimport { SDK_VERSION } from \"./version.js\";\n\n/** The step cap's default, counted in model calls. */\nconst DEFAULT_MAX_STEPS = 20;\n\n/** The depth cap's default (D11): a top-level run, its subagents and their subagents may run, and no deeper. */\nconst DEFAULT_MAX_DEPTH = 2;\n\n/** How long the run waits, by default, for an observer to catch up before it drops it. */\nconst DEFAULT_OBSERVER_TIMEOUT_MS = 10_000;\n/** The longest delay `setTimeout` accepts; a larger one fires at once on Node and workerd alike. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\nconst systemClock: Clock = { now: () => new Date().toISOString() };\nconst randomIds = (): string => globalThis.crypto.randomUUID();\n\n/** The options `run()` and `continueRun()` share. */\nexport interface RunOptions<S = unknown> {\n /** The model, from `createModel()`. */\n readonly model: Model;\n /**\n * The tools the model may call. Tools whose `exposure` is `deferred` or `hidden` are not sent unless a\n * `beforeModelCall` interceptor names them in `activeTools`.\n */\n readonly tools?: readonly ToolDefinition<unknown, unknown>[];\n /**\n * A tool from `outputTool()` whose input is the final answer. It is sent with the other tools; once the model calls\n * it with input that passes its schema, the run ends `done`, and `result.output` holds the validated answer.\n */\n readonly output?: ToolDefinition<S, S>;\n /**\n * The most model calls the run may make. Default 20. A run that reaches it while the model still wants to go on\n * ends with `stopReason: \"max_steps\"` and emits a `warning` event with `code: \"max_steps\"`.\n */\n readonly maxSteps?: number;\n /**\n * The most the run's model calls may cost, in USD. Before each call the run projects its cost with\n * `projectCallCost()` and, if the spend so far plus that projection would pass the cap, ends with\n * `stopReason: \"budget\"` without making the call. The cap counts the calls this run makes, not the cost of the\n * history a `continueRun()` starts from. A budgeted run on a model whose price is unknown ends `error` with\n * `error.kind: \"unknown_price\"` before its first call, because it could not tell what it spent. Without it, a run\n * has no cap.\n */\n readonly budgetUsd?: number;\n /**\n * The default progress policy: the run ends `no_progress` after 3 identical failing tool calls in a row, or after 5\n * calls to a tool with one `progressKey` and no success between them. It runs after your own `shouldStop`, whose\n * `{ continue }` can't keep a stuck run going. Pass numbers to change either threshold, or `false` to turn the\n * policy off.\n */\n readonly progress?: ProgressPolicy | false;\n /**\n * How deeply this run is nested inside other agents' tool calls. Default 0. A tool that starts a run of its own\n * passes `depth: ctx.depth + 1` and `maxDepth: ctx.maxDepth`; `run()` throws an `SdkError` with code\n * `max_depth_exceeded` when `depth` is above `maxDepth`, which the tool's caller reads as an error result.\n */\n readonly depth?: number;\n /** The deepest nesting allowed, which tools read as `ctx.maxDepth`. Default 2. */\n readonly maxDepth?: number;\n /** Aborts the run, like `run.abort()`. */\n readonly signal?: AbortSignal;\n /** Options for every model call, such as `maxOutputTokens`. The run passes its own abort signal. */\n readonly modelOptions?: CallOptions;\n /**\n * The interceptors: hooks that can change the run at six moments. A run takes one object; join several with\n * `composeInterceptors()`. See `Interceptors` for the order and for what a failing hook does.\n */\n readonly interceptors?: Interceptors;\n /**\n * Observers, which receive every event from `run_start` on and can't change the run. Each observer sees the events in\n * order and waits for its own promises, but observers don't wait for each other. An observer that throws becomes a\n * `hook_error` event. The run waits for every observer to handle the last event before it settles, for at most\n * `observerTimeoutMs` each time it waits; an observer that hasn't caught up by then is removed and reported as a\n * `hook_error`.\n */\n readonly observers?: readonly Observer[];\n /**\n * The longest the run waits for its observers each time it waits for them: before `agent_settled`, before\n * `run_end` and before it settles. A number from 1 to 2147483647; the default is 10000. It bounds an observer whose promise never settles.\n */\n readonly observerTimeoutMs?: number;\n /** Stamps each event's `timestamp`, and is passed to tools. Defaults to the system clock. */\n readonly clock?: Clock;\n /** Makes the run's id. Defaults to `crypto.randomUUID()`. */\n readonly idGenerator?: () => string;\n}\n\n/** What `run()` takes besides the shared options. */\nexport interface RunInput {\n /** The system prompt. */\n readonly system: string;\n /** The user's message that starts the run. */\n readonly input: string | readonly ContentBlock[];\n /** Earlier messages to send before `input`, such as a previous conversation. */\n readonly history?: readonly Message[];\n}\n\n/**\n * A run in progress. Iterate it to stream its events: each iteration starts from the run's first event, so you can\n * start iterating at any time. Await `result` for the outcome; it rejects only for a programmer error, such as a\n * tool that returns a malformed result, and iteration then throws the same error after the last event.\n */\nexport interface Run<S = unknown> extends AsyncIterable<AgentEvent> {\n /** The run's id, which every event carries. */\n readonly id: string;\n /** The outcome, once the run has stopped. */\n readonly result: Promise<RunResult<S>>;\n /**\n * Stops the run. A model call in flight ends, a running tool sees its `signal` fire, and calls that haven't started\n * get an error result instead. The run then ends with `stopReason: \"aborted\"`. Does nothing once the run has its\n * outcome and is ending, which is before `agent_settled`.\n */\n abort(reason?: string): void;\n /**\n * Adds an observer that receives the events from now on, in order, and returns the function that removes it. An\n * event that was queued for it but not yet handled is dropped when you remove it. Add it right after `run()` to\n * see every event but `run_start`, which `run()` emits before it returns; to see that one too, pass the observer\n * in the `observers` option.\n */\n on(observer: Observer): () => void;\n /**\n * Queues a user message that redirects the run. The run applies it at the next step boundary: after the model call\n * or tool batch in flight, never inside it, and before the next model call. The promise resolves with a\n * `DeliveryReceipt` once the message is in the transcript, and the run emits a `steer_applied` event for it. It\n * rejects with an `SdkError` whose code is `undelivered_message` when the run ends first, and with\n * `invalid_run_options` for a blank message or a block that isn't text or an image. Steers are applied in the\n * order they were sent.\n */\n steer(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;\n /**\n * Queues a user message that waits until the run would otherwise end. When the model has answered and no tool call\n * is left, the run applies every waiting follow-up as user messages and makes one more model call, so a follow-up\n * sent before the run ends extends it by one step. A steer that is waiting goes first. The run still ends, and the\n * follow-up rejects with `undelivered_message`, when another stop reason ends it: a `shouldStop` hook or progress\n * policy that stops it, its output tool, an abort or `maxSteps`. The receipt works as for `steer()`.\n */\n followUp(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction checkObserver(observer: unknown): void {\n if (typeof observer !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `an observer must be a function, got ${typeof observer}`);\n }\n}\n\nconst HOOK_NAMES = [\n \"transformContext\",\n \"beforeModelCall\",\n \"afterModelCall\",\n \"beforeToolCall\",\n \"afterToolCall\",\n \"shouldStop\",\n] as const;\n\n/** Checks the interceptors option once, so a misspelt or mistyped hook fails at `run()` and not mid-run. */\nfunction checkInterceptors(interceptors: Interceptors): Interceptors {\n if (typeof interceptors !== \"object\" || interceptors === null) {\n throw new SdkError(\"invalid_run_options\", \"interceptors must be an object of hooks\");\n }\n for (const name of HOOK_NAMES) {\n const hook: unknown = interceptors[name];\n if (hook !== undefined && typeof hook !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.${name} must be a function, got ${typeof hook}`);\n }\n }\n const { onFailure } = interceptors;\n if (onFailure !== undefined && onFailure !== \"fail_closed\" && onFailure !== \"continue\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.onFailure must be \"fail_closed\" or \"continue\"`);\n }\n return interceptors;\n}\n\nfunction reasonOf(reason: unknown): string | undefined {\n if (typeof reason === \"string\") return reason;\n return reason instanceof Error ? reason.message : undefined;\n}\n\nclass RunHandle<S> implements Run<S> {\n readonly id: string;\n readonly result: Promise<RunResult<S>>;\n readonly #events: AgentEvent[] = [];\n readonly #controller = new AbortController();\n readonly #clock: Clock;\n readonly #bus: ObserverBus;\n #waiters: (() => void)[] = [];\n #ended = false;\n /** Set once the loop has its outcome and starts to end the run, so `abort()` no longer does anything. */\n #settled = false;\n /** Set by `run_end`: nothing may follow it, so a late observer report is dropped. */\n #closed = false;\n readonly #steering: SteeringQueue;\n #failure: { readonly error: unknown } | undefined;\n #stepIndex = 0;\n\n constructor(setup: Omit<LoopSetup, \"signal\" | \"steering\">, signal: AbortSignal | undefined, watch: ObserverSetup) {\n this.id = setup.runId;\n this.#clock = setup.clock;\n this.#steering = new SteeringQueue(setup.runId);\n this.#bus = new ObserverBus((hook, error) => {\n if (!this.#closed) this.#push({ type: \"hook_error\", hook, error: messageOf(error) }, this.#stepIndex);\n }, watch.timeoutMs);\n const { observers } = watch;\n for (const observer of observers) this.#bus.add(observer);\n const emit = (body: AgentEventBody, stepIndex: number) => this.#push(body, stepIndex);\n const { model } = setup;\n const versions = { sdkVersion: SDK_VERSION, specVersion: \"v1\" as const, defaultsHash: \"\", capabilities: [] };\n emit({ type: \"run_start\", ...versions, model: model.ref }, 0);\n const forwardAbort = () => this.abort(reasonOf(signal?.reason));\n if (signal?.aborted) forwardAbort();\n else signal?.addEventListener(\"abort\", forwardAbort, { once: true });\n // The loop starts after this turn, so an observer added with `run.on()` straight after `run()` sees every event\n // after `run_start`, and a `run.abort()` straight after it stops the run before its first model call.\n // The loop drains the observers only once it has its outcome (`finish()`), so the first drain is also where an\n // abort stops mattering: it could no longer change the outcome, only add an `abort` event after it.\n const drain = () => {\n this.#settled = true;\n return this.#bus.flush();\n };\n const loop = Promise.resolve().then(() =>\n runLoop({ ...setup, signal: this.#controller.signal, steering: this.#steering }, emit, drain),\n );\n // The loop's result type is `RunResult<unknown>`; only the output tool, whose type is `S`, fills `output`.\n this.result = loop as Promise<RunResult<S>>;\n // Handling the rejection here also keeps a caller who only iterates from an unhandled rejection: iteration\n // throws the same error.\n loop.then(\n () => this.#end(signal, forwardAbort, undefined),\n (error: unknown) => this.#end(signal, forwardAbort, { error }),\n );\n }\n\n abort(reason?: string): void {\n if (this.#settled || this.#ended || this.#controller.signal.aborted) return;\n this.#push(reason === undefined ? { type: \"abort\" } : { type: \"abort\", reason }, this.#stepIndex);\n this.#controller.abort(reason);\n }\n\n on(observer: Observer): () => void {\n checkObserver(observer);\n return this.#bus.add(observer);\n }\n\n steer(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n return this.#steering.add(\"steer\", message);\n }\n\n followUp(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n return this.#steering.add(\"follow_up\", message);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {\n let cursor = 0;\n return {\n next: async () => {\n while (cursor >= this.#events.length && !this.#ended) {\n await new Promise<void>((resolve) => this.#waiters.push(resolve));\n }\n const event = this.#events[cursor];\n if (event !== undefined) {\n cursor += 1;\n return { value: event, done: false };\n }\n if (this.#failure !== undefined) throw this.#failure.error;\n return { value: undefined, done: true };\n },\n };\n }\n\n #push(body: AgentEventBody, stepIndex: number): void {\n this.#stepIndex = stepIndex;\n if (body.type === \"run_end\") this.#closed = true;\n const base = { runId: this.id, seq: this.#events.length, stepIndex, timestamp: this.#clock.now() };\n const event = { ...base, ...body } as AgentEvent;\n this.#events.push(event);\n this.#bus.deliver(event);\n this.#wake();\n }\n\n #end(signal: AbortSignal | undefined, forwardAbort: () => void, failure: { readonly error: unknown } | undefined) {\n signal?.removeEventListener(\"abort\", forwardAbort);\n this.#failure = failure;\n this.#ended = true;\n this.#wake();\n }\n\n #wake(): void {\n const waiters = this.#waiters;\n this.#waiters = [];\n for (const wake of waiters) wake();\n }\n}\n\nfunction isModel(model: unknown): model is Model {\n const candidate = model as Partial<Model> | null;\n return (\n typeof candidate === \"object\" &&\n candidate !== null &&\n typeof candidate.stream === \"function\" &&\n typeof candidate.price === \"function\" &&\n typeof candidate.ref === \"object\"\n );\n}\n\n/** Every tool the run may send, the output tool last unless `tools` already holds it, after checking each one. */\nfunction toolsOf(options: RunOptions<unknown>): AnyTool[] {\n const tools = [...(options.tools ?? [])] as AnyTool[];\n const output = options.output as AnyTool | undefined;\n if (output !== undefined && !tools.includes(output)) tools.push(output);\n const names = new Set<string>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (names.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n names.add(tool.name);\n }\n return tools;\n}\n\nfunction isCount(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n}\n\n/**\n * The `depth` and `maxDepth` options for a run that a tool starts: one level deeper than the tool's own run, under\n * the same cap. Spread it into the nested `run()`; the nested run throws `max_depth_exceeded` when the tool was\n * already at `maxDepth`.\n */\nexport function nestedRunDepth(ctx: Pick<ToolContext, \"depth\" | \"maxDepth\">): { depth: number; maxDepth: number } {\n return { depth: ctx.depth + 1, maxDepth: ctx.maxDepth };\n}\n\n/** Checks `depth` and `maxDepth`, and refuses a run nested deeper than the cap allows (D11). */\nfunction depthsOf(options: RunOptions<unknown>): { depth: number; maxDepth: number } {\n const { depth = 0, maxDepth = DEFAULT_MAX_DEPTH } = options;\n if (!isCount(depth) || !isCount(maxDepth)) {\n throw new SdkError(\n \"invalid_run_options\",\n `depth and maxDepth must be whole numbers, 0 or more, got ${String(depth)} and ${String(maxDepth)}`,\n );\n }\n if (depth > maxDepth) {\n throw new SdkError(\"max_depth_exceeded\", `a run at depth ${depth} is deeper than maxDepth ${maxDepth} allows`);\n }\n return { depth, maxDepth };\n}\n\n/**\n * The default progress policy for this run, or `undefined` when `progress: false` turns it off. `skip` is the number\n * of messages before the run's own.\n */\nfunction progressOf(options: RunOptions<unknown>, tools: readonly AnyTool[], skip: number): ProgressCheck | undefined {\n const policy = resolveProgress(options.progress);\n return policy === undefined ? undefined : progressCheck(tools, policy, skip);\n}\n\nfunction setupOf(\n options: RunOptions<unknown>,\n context: Context,\n input: readonly Message[],\n): Omit<LoopSetup, \"signal\" | \"steering\"> {\n if (!isModel(options.model)) {\n throw new SdkError(\n \"invalid_run_options\",\n \"the model must come from createModel(), such as createModel({ adapter, id })\",\n );\n }\n const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;\n if (!Number.isInteger(maxSteps) || maxSteps < 1) {\n throw new SdkError(\"invalid_run_options\", `maxSteps must be a positive integer, got ${maxSteps}`);\n }\n const budgetUsd = checkBudgetOption(options.budgetUsd);\n const tools = toolsOf(options);\n const { depth, maxDepth } = depthsOf(options);\n const progress = progressOf(options, tools, context.messages.length + input.length);\n if (options.output !== undefined && (options.output.exposure ?? \"direct\") !== \"direct\") {\n throw new SdkError(\n \"invalid_run_options\",\n `the output tool \"${options.output.name}\" must be sent to the model, so its exposure must be \"direct\"`,\n );\n }\n return {\n runId: (options.idGenerator ?? randomIds)(),\n model: options.model,\n system: context.system,\n history: context.messages,\n input,\n tools,\n output: options.output as AnyTool | undefined,\n maxSteps,\n ...(budgetUsd === undefined ? {} : { budgetUsd }),\n depth,\n maxDepth,\n modelOptions: options.modelOptions ?? {},\n interceptors: checkInterceptors(options.interceptors ?? {}),\n ...(progress === undefined ? {} : { progress }),\n clock: options.clock ?? systemClock,\n };\n}\n\n/** The observers a run starts with, and how long it waits for them. */\ninterface ObserverSetup {\n readonly observers: readonly Observer[];\n readonly timeoutMs: number;\n}\n\nfunction observersOf(options: RunOptions<unknown>): ObserverSetup {\n const observers = options.observers ?? [];\n for (const observer of observers) checkObserver(observer);\n const timeoutMs = options.observerTimeoutMs ?? DEFAULT_OBSERVER_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_MS) {\n throw new SdkError(\n \"invalid_run_options\",\n `observerTimeoutMs must be a number from 1 to ${MAX_TIMER_MS}, got ${timeoutMs}`,\n );\n }\n return { observers, timeoutMs };\n}\n\n/**\n * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool\n * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an\n * unusable option: a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool\n * that isn't sent to the model, or two tools with one name.\n */\nexport function run<S = unknown>(options: RunOptions<S> & RunInput): Run<S> {\n const content = typeof options.input === \"string\" ? [{ type: \"text\" as const, text: options.input }] : options.input;\n const input: Message = { role: \"user\", content: [...content] };\n const setup = setupOf(options, { system: options.system, messages: options.history ?? [] }, [input]);\n return new RunHandle<S>(setup, options.signal, observersOf(options));\n}\n\n/**\n * Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like\n * `run()`, from the last message in the context, and `result.messages` holds only the messages it adds. The context\n * is sent as it stands, so add a user message to one that ends with the model's answer, such as a `done` result's.\n */\nexport function continueRun<S = unknown>(context: Context, options: RunOptions<S>): Run<S> {\n return new RunHandle<S>(setupOf(options, context, []), options.signal, observersOf(options));\n}\n\n/**\n * Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that\n * carries the result and the context to continue from.\n */\nexport async function runOrThrow<S>(started: Run<S>): Promise<DoneResult<S>> {\n const result = await started.result;\n if (result.stopReason === \"done\") return result;\n throw new RunStoppedError(result);\n}\n"]}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Steering and follow-up (SDK plan §3.3). A caller queues a user message while a run goes on; the loop applies it
|
|
3
|
+
* only at a step boundary, so a running model call or tool batch is never cut. A steer is applied before the run's
|
|
4
|
+
* next model call. A follow-up waits until the run would otherwise end. Each queued message returns a receipt once
|
|
5
|
+
* it has entered the transcript.
|
|
6
|
+
*/
|
|
7
|
+
import type { ContentBlock } from "@buildanagent/gateway";
|
|
8
|
+
/** Whether a message steers the run now or follows up once it would otherwise end. */
|
|
9
|
+
export type DeliveryKind = "steer" | "follow_up";
|
|
10
|
+
/**
|
|
11
|
+
* Proof that a queued message entered the transcript. `id` is unique within the run, `message` is the content the
|
|
12
|
+
* run added as a user message, and `stepIndex` is the step at whose start the run added it. That step's model call is
|
|
13
|
+
* the first to see the message, unless the run ends before the call, which a budget stop or a failed hook can cause.
|
|
14
|
+
*/
|
|
15
|
+
export interface DeliveryReceipt {
|
|
16
|
+
readonly id: string;
|
|
17
|
+
readonly kind: DeliveryKind;
|
|
18
|
+
readonly message: readonly ContentBlock[];
|
|
19
|
+
readonly stepIndex: number;
|
|
20
|
+
}
|
|
21
|
+
/** A message the loop took from the queue, with the function that settles its receipt. */
|
|
22
|
+
export interface Delivery {
|
|
23
|
+
readonly kind: DeliveryKind;
|
|
24
|
+
readonly message: readonly ContentBlock[];
|
|
25
|
+
/** Settles the receipt once the message is in the transcript. */
|
|
26
|
+
readonly deliver: (stepIndex: number) => DeliveryReceipt;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The queue between a caller and the loop. The caller adds with `steer()` and `followUp()`; the loop takes with
|
|
30
|
+
* `take()` at a step boundary, and closes the queue when the run has its outcome.
|
|
31
|
+
*/
|
|
32
|
+
export declare class SteeringQueue {
|
|
33
|
+
#private;
|
|
34
|
+
constructor(runId: string);
|
|
35
|
+
/**
|
|
36
|
+
* Queues a message. The promise rejects, never throws, for an unusable message or a run that has ended. A caller who
|
|
37
|
+
* ignores the promise must not crash the process when the run ends first, so a rejection is always marked handled;
|
|
38
|
+
* a caller who awaits it still sees it.
|
|
39
|
+
*/
|
|
40
|
+
add(kind: DeliveryKind, message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;
|
|
41
|
+
/** True while a steer is waiting. */
|
|
42
|
+
hasSteers(): boolean;
|
|
43
|
+
/** True while any message is waiting. */
|
|
44
|
+
hasPending(): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Removes and returns the waiting steers, and the waiting follow-ups too when `withFollowUps` is set, all in the
|
|
47
|
+
* order they were sent.
|
|
48
|
+
*/
|
|
49
|
+
take(withFollowUps: boolean): Delivery[];
|
|
50
|
+
/** Ends the queue: every message still waiting is rejected, and later calls are too. */
|
|
51
|
+
close(): void;
|
|
52
|
+
}
|
package/dist/steering.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { SdkError } from "./errors.js";
|
|
2
|
+
/** A copy of one block of a steering message that holds only the block's own fields. */
|
|
3
|
+
function checkBlock(block) {
|
|
4
|
+
const candidate = block;
|
|
5
|
+
if (candidate?.type === "text" && typeof candidate.text === "string") {
|
|
6
|
+
// Providers refuse an empty text block, so it is refused here rather than failing the next model call.
|
|
7
|
+
if (candidate.text.trim().length === 0) {
|
|
8
|
+
throw new SdkError("invalid_run_options", "a steering message's text block must not be empty");
|
|
9
|
+
}
|
|
10
|
+
return { type: "text", text: candidate.text };
|
|
11
|
+
}
|
|
12
|
+
if (candidate?.type === "image" && typeof candidate.mediaType === "string" && typeof candidate.data === "string") {
|
|
13
|
+
return { type: "image", mediaType: candidate.mediaType, data: candidate.data };
|
|
14
|
+
}
|
|
15
|
+
throw new SdkError("invalid_run_options", "a steering message holds only text and image blocks");
|
|
16
|
+
}
|
|
17
|
+
/** The content of a steering message: a string that isn't blank, or a non-empty list of text and image blocks. */
|
|
18
|
+
function contentOf(message) {
|
|
19
|
+
if (typeof message === "string") {
|
|
20
|
+
if (message.trim().length === 0)
|
|
21
|
+
throw new SdkError("invalid_run_options", "a steering message must not be empty");
|
|
22
|
+
return [{ type: "text", text: message }];
|
|
23
|
+
}
|
|
24
|
+
if (!Array.isArray(message) || message.length === 0) {
|
|
25
|
+
throw new SdkError("invalid_run_options", "a steering message must be a string or a non-empty list of blocks");
|
|
26
|
+
}
|
|
27
|
+
return message.map(checkBlock);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The queue between a caller and the loop. The caller adds with `steer()` and `followUp()`; the loop takes with
|
|
31
|
+
* `take()` at a step boundary, and closes the queue when the run has its outcome.
|
|
32
|
+
*/
|
|
33
|
+
export class SteeringQueue {
|
|
34
|
+
#runId;
|
|
35
|
+
#queue = [];
|
|
36
|
+
#count = 0;
|
|
37
|
+
#closed = false;
|
|
38
|
+
constructor(runId) {
|
|
39
|
+
this.#runId = runId;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Queues a message. The promise rejects, never throws, for an unusable message or a run that has ended. A caller who
|
|
43
|
+
* ignores the promise must not crash the process when the run ends first, so a rejection is always marked handled;
|
|
44
|
+
* a caller who awaits it still sees it.
|
|
45
|
+
*/
|
|
46
|
+
add(kind, message) {
|
|
47
|
+
const receipt = this.#enqueue(kind, message);
|
|
48
|
+
receipt.catch(() => undefined);
|
|
49
|
+
return receipt;
|
|
50
|
+
}
|
|
51
|
+
#enqueue(kind, message) {
|
|
52
|
+
let content;
|
|
53
|
+
try {
|
|
54
|
+
content = contentOf(message);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
return Promise.reject(error);
|
|
58
|
+
}
|
|
59
|
+
if (this.#closed)
|
|
60
|
+
return Promise.reject(undelivered(kind));
|
|
61
|
+
this.#count += 1;
|
|
62
|
+
const id = `${this.#runId}:message-${this.#count}`;
|
|
63
|
+
return new Promise((resolve, reject) => {
|
|
64
|
+
this.#queue.push({ id, kind, message: content, resolve, reject });
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/** True while a steer is waiting. */
|
|
68
|
+
hasSteers() {
|
|
69
|
+
return this.#queue.some((entry) => entry.kind === "steer");
|
|
70
|
+
}
|
|
71
|
+
/** True while any message is waiting. */
|
|
72
|
+
hasPending() {
|
|
73
|
+
return this.#queue.length > 0;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Removes and returns the waiting steers, and the waiting follow-ups too when `withFollowUps` is set, all in the
|
|
77
|
+
* order they were sent.
|
|
78
|
+
*/
|
|
79
|
+
take(withFollowUps) {
|
|
80
|
+
const taken = this.#queue.filter((entry) => withFollowUps || entry.kind === "steer");
|
|
81
|
+
this.#queue = this.#queue.filter((entry) => !taken.includes(entry));
|
|
82
|
+
return taken.map((entry) => ({
|
|
83
|
+
kind: entry.kind,
|
|
84
|
+
message: entry.message,
|
|
85
|
+
deliver: (stepIndex) => {
|
|
86
|
+
const receipt = { id: entry.id, kind: entry.kind, message: entry.message, stepIndex };
|
|
87
|
+
entry.resolve(receipt);
|
|
88
|
+
return receipt;
|
|
89
|
+
},
|
|
90
|
+
}));
|
|
91
|
+
}
|
|
92
|
+
/** Ends the queue: every message still waiting is rejected, and later calls are too. */
|
|
93
|
+
close() {
|
|
94
|
+
this.#closed = true;
|
|
95
|
+
const waiting = this.#queue;
|
|
96
|
+
this.#queue = [];
|
|
97
|
+
for (const entry of waiting)
|
|
98
|
+
entry.reject(undelivered(entry.kind));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function undelivered(kind) {
|
|
102
|
+
return new SdkError("undelivered_message", `the ${kind === "steer" ? "steer" : "follow-up"} was not applied: the run ended before its next step boundary`);
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=steering.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"steering.js","sourceRoot":"","sources":["../src/steering.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAiCvC,wFAAwF;AACxF,SAAS,UAAU,CAAC,KAAc;IAChC,MAAM,SAAS,GAAG,KAAuF,CAAC;IAC1G,IAAI,SAAS,EAAE,IAAI,KAAK,MAAM,IAAI,OAAO,SAAS,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QACrE,uGAAuG;QACvG,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACvC,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,mDAAmD,CAAC,CAAC;QACjG,CAAC;QACD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,CAAC;IAChD,CAAC;IACD,IAAI,SAAS,EAAE,IAAI,KAAK,OAAO,IAAI,OAAO,SAAS,CAAC,SAAS,KAAK,QAAQ,IAAI,OAAO,SAAS,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QACjH,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,CAAC,SAAS,EAAE,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,CAAC;IACjF,CAAC;IACD,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,qDAAqD,CAAC,CAAC;AACnG,CAAC;AAED,kHAAkH;AAClH,SAAS,SAAS,CAAC,OAAgB;IACjC,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,IAAI,OA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KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,SAAS,EAAE,CAAC;gBACvG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;gBACvB,OAAO,OAAO,CAAC;YACjB,CAAC;SACF,CAAC,CAAC,CAAC;IACN,CAAC;IAED,wFAAwF;IACxF,KAAK;QACH,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC;QAC5B,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;QACjB,KAAK,MAAM,KAAK,IAAI,OAAO;YAAE,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IACrE,CAAC;CACF;AAED,SAAS,WAAW,CAAC,IAAkB;IACrC,OAAO,IAAI,QAAQ,CACjB,qBAAqB,EACrB,OAAO,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,+DAA+D,CAC/G,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Steering and follow-up (SDK plan §3.3). A caller queues a user message while a run goes on; the loop applies it\n * only at a step boundary, so a running model call or tool batch is never cut. A steer is applied before the run's\n * next model call. A follow-up waits until the run would otherwise end. Each queued message returns a receipt once\n * it has entered the transcript.\n */\nimport type { ContentBlock } from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\n\n/** Whether a message steers the run now or follows up once it would otherwise end. */\nexport type DeliveryKind = \"steer\" | \"follow_up\";\n\n/**\n * Proof that a queued message entered the transcript. `id` is unique within the run, `message` is the content the\n * run added as a user message, and `stepIndex` is the step at whose start the run added it. That step's model call is\n * the first to see the message, unless the run ends before the call, which a budget stop or a failed hook can cause.\n */\nexport interface DeliveryReceipt {\n readonly id: string;\n readonly kind: DeliveryKind;\n readonly message: readonly ContentBlock[];\n readonly stepIndex: number;\n}\n\ninterface Queued {\n readonly id: string;\n readonly kind: DeliveryKind;\n readonly message: readonly ContentBlock[];\n readonly resolve: (receipt: DeliveryReceipt) => void;\n readonly reject: (error: unknown) => void;\n}\n\n/** A message the loop took from the queue, with the function that settles its receipt. */\nexport interface Delivery {\n readonly kind: DeliveryKind;\n readonly message: readonly ContentBlock[];\n /** Settles the receipt once the message is in the transcript. */\n readonly deliver: (stepIndex: number) => DeliveryReceipt;\n}\n\n/** A copy of one block of a steering message that holds only the block's own fields. */\nfunction checkBlock(block: unknown): ContentBlock {\n const candidate = block as { type?: unknown; text?: unknown; mediaType?: unknown; data?: unknown } | null;\n if (candidate?.type === \"text\" && typeof candidate.text === \"string\") {\n // Providers refuse an empty text block, so it is refused here rather than failing the next model call.\n if (candidate.text.trim().length === 0) {\n throw new SdkError(\"invalid_run_options\", \"a steering message's text block must not be empty\");\n }\n return { type: \"text\", text: candidate.text };\n }\n if (candidate?.type === \"image\" && typeof candidate.mediaType === \"string\" && typeof candidate.data === \"string\") {\n return { type: \"image\", mediaType: candidate.mediaType, data: candidate.data };\n }\n throw new SdkError(\"invalid_run_options\", \"a steering message holds only text and image blocks\");\n}\n\n/** The content of a steering message: a string that isn't blank, or a non-empty list of text and image blocks. */\nfunction contentOf(message: unknown): ContentBlock[] {\n if (typeof message === \"string\") {\n if (message.trim().length === 0) throw new SdkError(\"invalid_run_options\", \"a steering message must not be empty\");\n return [{ type: \"text\", text: message }];\n }\n if (!Array.isArray(message) || message.length === 0) {\n throw new SdkError(\"invalid_run_options\", \"a steering message must be a string or a non-empty list of blocks\");\n }\n return message.map(checkBlock);\n}\n\n/**\n * The queue between a caller and the loop. The caller adds with `steer()` and `followUp()`; the loop takes with\n * `take()` at a step boundary, and closes the queue when the run has its outcome.\n */\nexport class SteeringQueue {\n readonly #runId: string;\n #queue: Queued[] = [];\n #count = 0;\n #closed = false;\n\n constructor(runId: string) {\n this.#runId = runId;\n }\n\n /**\n * Queues a message. The promise rejects, never throws, for an unusable message or a run that has ended. A caller who\n * ignores the promise must not crash the process when the run ends first, so a rejection is always marked handled;\n * a caller who awaits it still sees it.\n */\n add(kind: DeliveryKind, message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n const receipt = this.#enqueue(kind, message);\n receipt.catch(() => undefined);\n return receipt;\n }\n\n #enqueue(kind: DeliveryKind, message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n let content: ContentBlock[];\n try {\n content = contentOf(message);\n } catch (error) {\n return Promise.reject(error);\n }\n if (this.#closed) return Promise.reject(undelivered(kind));\n this.#count += 1;\n const id = `${this.#runId}:message-${this.#count}`;\n return new Promise<DeliveryReceipt>((resolve, reject) => {\n this.#queue.push({ id, kind, message: content, resolve, reject });\n });\n }\n\n /** True while a steer is waiting. */\n hasSteers(): boolean {\n return this.#queue.some((entry) => entry.kind === \"steer\");\n }\n\n /** True while any message is waiting. */\n hasPending(): boolean {\n return this.#queue.length > 0;\n }\n\n /**\n * Removes and returns the waiting steers, and the waiting follow-ups too when `withFollowUps` is set, all in the\n * order they were sent.\n */\n take(withFollowUps: boolean): Delivery[] {\n const taken = this.#queue.filter((entry) => withFollowUps || entry.kind === \"steer\");\n this.#queue = this.#queue.filter((entry) => !taken.includes(entry));\n return taken.map((entry) => ({\n kind: entry.kind,\n message: entry.message,\n deliver: (stepIndex) => {\n const receipt: DeliveryReceipt = { id: entry.id, kind: entry.kind, message: entry.message, stepIndex };\n entry.resolve(receipt);\n return receipt;\n },\n }));\n }\n\n /** Ends the queue: every message still waiting is rejected, and later calls are too. */\n close(): void {\n this.#closed = true;\n const waiting = this.#queue;\n this.#queue = [];\n for (const entry of waiting) entry.reject(undelivered(entry.kind));\n }\n}\n\nfunction undelivered(kind: DeliveryKind): SdkError {\n return new SdkError(\n \"undelivered_message\",\n `the ${kind === \"steer\" ? \"steer\" : \"follow-up\"} was not applied: the run ended before its next step boundary`,\n );\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@buildanagent/sdk",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.7",
|
|
4
4
|
"description": "The buildanagent SDK: the agent loop, tools, hooks, signed pauses and budgets over the gateway.",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"repository": {
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@earendil-works/pi-schema": "1.5.2",
|
|
39
39
|
"@standard-schema/spec": "1.1.0",
|
|
40
|
-
"@buildanagent/gateway": "0.1.0-alpha.
|
|
40
|
+
"@buildanagent/gateway": "0.1.0-alpha.7"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@cfworker/json-schema": "4.1.6",
|