@buildanagent/sdk 0.1.0-alpha.1 → 0.1.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +163 -5
  2. package/dist/errors.d.ts +39 -0
  3. package/dist/errors.js +47 -0
  4. package/dist/errors.js.map +1 -0
  5. package/dist/events.d.ts +104 -0
  6. package/dist/events.js +27 -0
  7. package/dist/events.js.map +1 -0
  8. package/dist/index.d.ts +11 -3
  9. package/dist/index.js +8 -3
  10. package/dist/index.js.map +1 -1
  11. package/dist/loop.d.ts +38 -0
  12. package/dist/loop.js +232 -0
  13. package/dist/loop.js.map +1 -0
  14. package/dist/result.d.ts +77 -0
  15. package/dist/result.js +2 -0
  16. package/dist/result.js.map +1 -0
  17. package/dist/run.d.ts +78 -0
  18. package/dist/run.js +165 -0
  19. package/dist/run.js.map +1 -0
  20. package/dist/testing/scripted-model.d.ts +12 -2
  21. package/dist/testing/scripted-model.js +19 -2
  22. package/dist/testing/scripted-model.js.map +1 -1
  23. package/dist/tools/coerce.d.ts +15 -0
  24. package/dist/tools/coerce.js +93 -0
  25. package/dist/tools/coerce.js.map +1 -0
  26. package/dist/tools/define.d.ts +51 -0
  27. package/dist/tools/define.js +108 -0
  28. package/dist/tools/define.js.map +1 -0
  29. package/dist/tools/format-error.d.ts +13 -0
  30. package/dist/tools/format-error.js +65 -0
  31. package/dist/tools/format-error.js.map +1 -0
  32. package/dist/tools/outcome.d.ts +7 -0
  33. package/dist/tools/outcome.js +30 -0
  34. package/dist/tools/outcome.js.map +1 -0
  35. package/dist/tools/pipeline.d.ts +54 -0
  36. package/dist/tools/pipeline.js +185 -0
  37. package/dist/tools/pipeline.js.map +1 -0
  38. package/dist/tools/schema.d.ts +20 -0
  39. package/dist/tools/schema.js +100 -0
  40. package/dist/tools/schema.js.map +1 -0
  41. package/dist/tools/types.d.ts +152 -0
  42. package/dist/tools/types.js +2 -0
  43. package/dist/tools/types.js.map +1 -0
  44. package/dist/vendor/agent-safety/errors.d.ts +14 -0
  45. package/dist/vendor/agent-safety/errors.js +21 -0
  46. package/dist/vendor/agent-safety/errors.js.map +1 -0
  47. package/dist/vendor/agent-safety/outcome.d.ts +88 -0
  48. package/dist/vendor/agent-safety/outcome.js +140 -0
  49. package/dist/vendor/agent-safety/outcome.js.map +1 -0
  50. package/dist/vendor/agent-safety/render.d.ts +40 -0
  51. package/dist/vendor/agent-safety/render.js +92 -0
  52. package/dist/vendor/agent-safety/render.js.map +1 -0
  53. package/dist/version.d.ts +2 -0
  54. package/dist/version.js +8 -0
  55. package/dist/version.js.map +1 -0
  56. package/package.json +11 -3
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The SDK runs your agent's loop over [`@buildanagent/gateway`](../gateway/README.md): it calls the model, runs the tools the model asks for, and stops when the work is done. Its testing export lets you test that agent offline against a scripted model, with no API key.
4
4
 
5
- As of November 2026 the package holds only the testing export. The loop, tools, hooks, approvals and budgets are next.
5
+ As of November 2026 the package holds the loop, tool definitions and the testing export. Hooks, approvals and budgets come next.
6
6
 
7
7
  ## Install the alpha with `pnpm add @buildanagent/sdk@alpha`
8
8
 
@@ -12,14 +12,172 @@ Every release is an alpha until the first stable one, and npm serves the alphas
12
12
  pnpm add @buildanagent/sdk@alpha @buildanagent/gateway@alpha
13
13
  ```
14
14
 
15
- Both packages always share one version, and the SDK depends on that exact version of the gateway. Name the tag: a plain `pnpm add @buildanagent/sdk` installs `0.0.0-bootstrap.0`, a deprecated placeholder, because `latest` stays on it until the first stable release. The package needs Node 22 or later.
15
+ Both packages always share one version, and the SDK depends on that exact version of the gateway. Name the tag: a plain `pnpm add @buildanagent/sdk` installs `0.0.0-bootstrap.0`, a deprecated placeholder, because `latest` stays on it until the first stable release. The package needs Node 22.19 or later, the oldest Node its validator, pi-schema 1.5.2, supports.
16
+
17
+ Don't start Node with `--conditions=source` in a project that installs the SDK. Its validator, pi-schema 1.5.2, maps that condition to a source file its package doesn't ship, so the SDK's root entry fails to load under it ([validator check](docs/validator-check.md)).
18
+
19
+ ## Run an agent with `run()`
20
+
21
+ `run()` starts the loop. It sends your system prompt and the user's message to the model, runs each tool the model calls, and sends the results back. It goes on until the model answers without calling a tool. This agent answers questions about orders with the `lookup_order` tool from the next section, and prints the answer as it streams:
22
+
23
+ ```ts
24
+ const started = run({
25
+ model,
26
+ system: SYSTEM_PROMPT,
27
+ input: question,
28
+ tools: [lookupOrderTool(findOrder)],
29
+ maxSteps: MAX_STEPS,
30
+ });
31
+ for await (const event of started) {
32
+ if (event.type === "text_delta") write(event.delta);
33
+ }
34
+ const result = await started.result;
35
+ ```
36
+
37
+ `model` comes from `createModel()` in the gateway, and a bare model id is a type error. The run makes its tool calls one at a time, in the order the model sent them. A tool whose `exposure` is `"deferred"` or `"hidden"` is never sent to the model, and a call to it gets the unknown-tool error.
38
+
39
+ ### Every run ends with a stop reason
40
+
41
+ A failed model call or a failing tool never makes a run throw. The run ends with a result whose `stopReason` says why:
42
+
43
+ - **`done`**: the model answered without calling a tool, or an output tool accepted its answer. A text answer cut off at `maxOutputTokens` also ends `done`, so check whether the last message's `stopReason` is `"length"` before you show it as complete.
44
+ - **`max_steps`**: the run made `maxSteps` model calls, 20 by default, and the model still wanted to go on. The run also emits a `warning` event with `code: "max_steps"`, so a cap that cut a run short shows up in your logs.
45
+ - **`error`**: a model call failed. `result.error` copies the failure's `kind`, `message` and HTTP `status`. Its `kind` is `overflow` for a request too large for the model's window, `quota` for an account out of credit, `retryable` for a temporary failure that outlasted the gateway's retries, and `fatal` otherwise.
46
+ - **`aborted`**: you aborted the run.
47
+ - **`stopped`**: a tool from `clarificationTool()` asked the user a question, and `result.stoppedBy` is `"clarification"`.
48
+
49
+ `maxSteps` counts model calls, so an output call that fails its schema spends one of them. The tool calls of the last allowed response still run, so every call in the transcript has a result.
50
+
51
+ Only the `done` result carries `output`. TypeScript rejects `result.output` until you have checked `result.stopReason === "done"`, so an unfinished run can't pass for a finished one. Every result carries `usage` and `cost`, summed over the run's model calls, and `steps`, the number of calls. `result.messages` holds the messages this run added. `result.context` holds the whole conversation, ready to continue.
52
+
53
+ ### `runOrThrow()` turns an unfinished run into an exception
54
+
55
+ If you would rather catch an exception than check the stop reason, `runOrThrow(run)` returns the `done` result and throws a `RunStoppedError` for any other. The error carries the `result` and the `context` to continue from. `RunStoppedError.isInstance(error)` recognises it, even across two copies of the package:
56
+
57
+ ```ts
58
+ const result = await runOrThrow(run({ model, system, input }));
59
+ ```
60
+
61
+ ### Continue a conversation with `continueRun()`
62
+
63
+ `continueRun(context, options)` goes on from a context: a previous result's `context`, or one you rebuilt from your own store. A context is plain JSON holding the system prompt and the messages. A run that stopped at `max_steps` continues with the model reading its last tool results. A `done` context ends with the model's answer, so add a user message to it before you continue, or pass the messages as `history` to `run()` with the new input.
64
+
65
+ ### Abort a run with `run.abort()` or a signal
66
+
67
+ `run.abort(reason)` stops a run, and so does the `signal` option. A model call in flight ends, and a running tool sees its `ctx.signal` fire. The run waits for that tool to return, so pass the signal on to your own I/O. Calls that haven't started get an error result instead of running.
68
+
69
+ An aborted run's transcript stays well formed: every tool call has a result, and the last message is an assistant message with `stopReason: "aborted"`. When tool results would end the transcript, because the abort came while tools ran or cut off a response that held tool calls, the loop appends an empty aborted message after them. Each gateway adapter drops it before the next request, so the transcript can be sent again as it is.
70
+
71
+ ## A run streams one closed set of events
72
+
73
+ 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.
74
+
75
+ The events come in two layers. The delta layer streams each content block by its index, for a user interface: `text_start`, `text_delta` and `text_end`, and the same three for `reasoning` and `tool_input`. The item layer carries the finished pieces for a log:
76
+
77
+ - **`run_start`** comes first, with the SDK's version, the spec version and the model.
78
+ - **`step_start`** and **`step_end`** wrap one model call and its tool calls; `step_end.stopCheck` says whether the run goes on.
79
+ - **`model_call_start`** carries the request, and **`model_call_end`** the final message.
80
+ - **`tool_call_start`**, **`tool_call_update`** and **`tool_call_end`** follow each tool call; `tool_call_end.result` is what the model reads.
81
+ - **`retry`** reports a failed request the gateway is retrying, and **`warning`** reports a reached cap or a model warning.
82
+ - **`error`** and **`abort`** report a failed call and an abort request.
83
+ - **`agent_settled`** fires once nothing is running any more, retries and tools included. **`run_end`** follows it and carries the result.
84
+
85
+ `AGENT_EVENT_TYPES` lists every type at run time, and a run emits no other. The union is closed, so a `switch` over `event.type` can be exhaustive.
86
+
87
+ ## Define a tool with `defineTool()`
88
+
89
+ A tool is a name, a description the model reads, an input schema and an `execute` function. This tool looks up an order in your own store:
90
+
91
+ ```ts
92
+ export function lookupOrderTool(findOrder: FindOrder) {
93
+ return defineTool({
94
+ name: "lookup_order",
95
+ description: "Look up an order by its number and return its status.",
96
+ inputSchema: z.object({ order: z.number().int().positive() }),
97
+ async execute({ order }) {
98
+ const found = await findOrder(order);
99
+ if (found === undefined) return { content: [{ type: "text", text: `No order ${order} exists.` }], isError: true };
100
+ return { content: [{ type: "text", text: `Order ${order} is ${found.status}.` }], structured: found };
101
+ },
102
+ });
103
+ }
104
+ ```
105
+
106
+ The input schema is either a Standard Schema or a raw JSON Schema object. A Standard Schema is a schema from a library that can also describe itself as JSON Schema: Zod 4.2 or later, ArkType, or Valibot through `toStandardJsonSchema()` from `@valibot/to-json-schema`. A raw schema follows draft 2020-12, or draft 7 when its `$schema` names draft 7. Raw schemas check `format` keywords such as `email` and `date`.
107
+
108
+ `execute` receives the validated input and returns a tool result with three channels:
109
+
110
+ - **`content`** is the text and images the model reads.
111
+ - **`details`** is for your logs and user interface; the model never sees it.
112
+ - **`structured`** is typed data for your code, such as the order above.
113
+
114
+ `defineTool()` checks the tool once, when you call it. A name outside the tool-name rule, 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`, throws an `SdkError`. So does a schema that does not compile.
115
+
116
+ ## A failed call becomes an error the model can fix
117
+
118
+ Every tool call runs the same steps in order: find the tool by name, coerce the arguments, validate them, give `repair` one chance, then run `execute`. A failure the model caused, at any step, returns an error result to the model and throws nothing. When the model sends `"forty-two"` as the order number, it reads this:
119
+
120
+ ```text
121
+ The arguments for tool "lookup_order" are invalid:
122
+ - /order: Invalid input: expected number, received string
123
+ Received arguments: {"order":"forty-two"}
124
+ Do not substitute a mock, a placeholder or invented data for this tool's result. Fix the call, try another approach, or tell the user what failed.
125
+ ```
126
+
127
+ Each failing field appears as its JSON Pointer path, so the model knows exactly what to fix. The last line is there because agents have been seen to answer a failed tool by inventing a result. Three options on the tool and one flag on your own result change what happens:
128
+
129
+ - **`repair`** receives invalid input and its issues, and returns fixed input to validate again, or `undefined` to report the failure.
130
+ - **`formatError`** builds the model's content for a failed call in place of the default text.
131
+ - **`redactErrors: true`** shows the model a fixed line when `execute` throws, and keeps the thrown message in the result's `details`. Use it when error messages may hold secrets, such as connection strings.
132
+ - **`isError: true`** on your own result marks a failure you report yourself, such as an order that doesn't exist.
133
+
134
+ The model also sees an error for a tool name that doesn't exist, with the list of real ones. A response that stopped at its output limit runs none of its tool calls, because their arguments may be cut short; the model is asked to send each call again. A response that ended in an error or was aborted runs none of its calls either, and once the run is cancelled no further call starts.
135
+
136
+ ## Arguments are coerced by three rules
137
+
138
+ Models sometimes send a number as a string. Before validation, the SDK converts these values, and nothing else:
139
+
140
+ 1. A string holding JSON becomes the object or array it encodes, where the schema expects an object or an array.
141
+ 2. A string holding a decimal number becomes that number, where the schema expects a number, or an integer when the number is whole. A whole number beyond 2^53 stays a string, because JavaScript would round it to a different number.
142
+ 3. The string `"true"` or `"false"` becomes a boolean, where the schema expects a boolean.
143
+
144
+ The rules reach nested values through `properties` and `items`, and only where the schema names a single type. A value that already has the expected type is never changed.
145
+
146
+ ## Report what a write did with an outcome
147
+
148
+ A tool that changes the world, such as a refund, declares `effect: { kind: "write" }`. A tool without it counts as read-only, so it is safe to run again after a crash. The optional `businessKey` names the real-world operation, such as `refund:42`, so a retry is recognised as the same refund.
149
+
150
+ Such a tool returns an `outcome` beside its content. An outcome says which of five things happened: `applied`, `not_applied`, `compensated`, `partial` or `unknown`. It also says what the model should do next and whether a retry is safe. This refund tool reports a declined refund:
151
+
152
+ ```ts
153
+ return { ...base, kind: "not_applied", retry: "never", applied: [], reason: reply.code, next };
154
+ ```
155
+
156
+ The model reads the outcome first, as a sentence and as JSON, and then your content. For the declined refund the sentence begins "The refund_create call did not take effect, and nothing changed." Every kind except `applied` marks the result as an error. An outcome that breaks a rule, such as a retry its kind doesn't allow, throws an `SdkError`.
157
+
158
+ ## End the run with `outputTool()`, or ask with `clarificationTool()`
159
+
160
+ `outputTool({ name, schema })` turns the run's final answer into a tool call. Pass it to `run()` as `output`. A call whose input passes the schema ends the run `done`, and the validated answer is `result.output`. A call that fails the schema returns the issues to the model, which can correct its answer and call again. If the model answers in text instead, or another tool returns `terminate: true`, the run still ends `done`, with `result.output` undefined. The output tool must keep the default `exposure`, because the model has to be sent it.
161
+
162
+ `clarificationTool()` gives the model a tool named `ask_user` that takes one `question`. Pass `{ name }` to call it something else. Once the model calls it, the run ends with `stopReason: "stopped"` and `stoppedBy: "clarification"`, and the question is the call's input in `result.messages`. To go on, add the user's answer to `result.context` as a user message and pass the context to `continueRun()`.
163
+
164
+ ## `SdkError` marks a mistake in your code
165
+
166
+ The SDK throws only for programmer errors, never for a failure the model caused. `isSdkError(error)` recognises the error, and its `code` says why:
167
+
168
+ - **`invalid_tool_definition`**: a tool's name, description, schema or exposure is unusable, or two tools share a name.
169
+ - **`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.
170
+ - **`invalid_run_options`**: `run()` or `continueRun()` got a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, or an output tool whose `exposure` isn't `"direct"`.
171
+ - **`invalid_model_stream`**: a model's stream ended without a final message, which only a broken adapter does.
172
+ - **`run_stopped`**: the error is a `RunStoppedError` from `runOrThrow()`.
173
+ - **`unexpected_model_call`**: the error is an `UnexpectedModelCallError` from `ScriptedModel`.
16
174
 
17
175
  ## Test against a strict scripted model
18
176
 
19
177
  `ScriptedModel` plays back the responses you script, one per model call. It fails loudly when your test's expectations drift:
20
178
 
21
- - **Too many calls throw.** A call past the last scripted step throws `UnexpectedModelCallError`.
22
- - **Unused steps fail.** `assertComplete()` throws if any step was never called; call it when the test ends.
179
+ - **Too many calls throw.** A call past the last scripted step throws `UnexpectedModelCallError`, an `SdkError` with code `unexpected_model_call`. Behind `createModel()`, the gateway turns that throw into a failed call, so a run ends `error` instead of throwing.
180
+ - **`assertComplete()` catches both drifts.** It throws if any step was never called, or if a call came after the last step. Call it when the test ends, so an over-run fails the test even when the run swallowed it.
23
181
  - **Requests are snapshots.** `calls` holds a frozen copy of each request, taken when the call was made, so later changes to your conversation never show up in it.
24
182
  - **Streams look real.** Text, reasoning and tool-call input arrive in small pieces (4 characters by default), and an abort is checked between pieces.
25
183
 
@@ -41,7 +199,7 @@ A step is either a fixed response or a function that builds one from the request
41
199
 
42
200
  ## Tests give the same result every run
43
201
 
44
- Nothing in the testing export reads the system clock or `Math.random()`. `fixedClock(start, stepMs)` returns a clock that advances by a fixed step, and `sequentialIds(prefix)` returns `prefix-1`, `prefix-2` and so on. For random numbers you can repeat, import `seededRandom(seed)` from `@buildanagent/gateway/testing`. The same script with the same clock and ids streams the same events every time.
202
+ Nothing in the testing export reads the system clock or `Math.random()`. `fixedClock(start, stepMs)` returns a clock that advances by a fixed step, and `sequentialIds(prefix)` returns `prefix-1`, `prefix-2` and so on. Pass them to `run()` as `clock` and `idGenerator`. For random numbers you can repeat, import `seededRandom(seed)` from `@buildanagent/gateway/testing`. The same script with the same clock and ids streams the same events every time, timestamps and run id included.
45
203
 
46
204
  Start each test file with `import "@buildanagent/gateway/testing/setup"`, which keeps the test offline.
47
205
 
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool
3
+ * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never
4
+ * thrown: the tool pipeline returns it to the model as an error result. Two subclasses keep their own names:
5
+ * `RunStoppedError`, which `runOrThrow()` throws for a run that did not finish, and the testing export's
6
+ * `UnexpectedModelCallError`.
7
+ */
8
+ import type { Context, UnfinishedResult } from "./result.js";
9
+ /** Why an `SdkError` was thrown. */
10
+ export type SdkErrorCode = "invalid_tool_definition" | "invalid_tool_result" | "invalid_run_options" | "invalid_model_stream" | "run_stopped" | "unexpected_model_call";
11
+ /**
12
+ * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema or
13
+ * exposure is unusable, or two tools share a name. `invalid_tool_result`: a tool's `execute` returned a malformed
14
+ * result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an option it can't use, such as a
15
+ * model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended without a final message.
16
+ * `run_stopped`: `runOrThrow()` was given a run that did not finish (a `RunStoppedError`). `unexpected_model_call`: a
17
+ * `ScriptedModel` was called more times than its script allows (an `UnexpectedModelCallError`).
18
+ */
19
+ export declare class SdkError extends Error {
20
+ readonly name: string;
21
+ readonly code: SdkErrorCode;
22
+ constructor(code: SdkErrorCode, message: string, options?: ErrorOptions);
23
+ }
24
+ /** True for an `SdkError`, including one from another copy of the package. */
25
+ export declare function isSdkError(error: unknown): error is SdkError;
26
+ /**
27
+ * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It
28
+ * carries the whole result, and the context to continue from. It is an `SdkError` with code `run_stopped`.
29
+ */
30
+ export declare class RunStoppedError extends SdkError {
31
+ readonly name = "RunStoppedError";
32
+ readonly stopReason: UnfinishedResult["stopReason"];
33
+ readonly result: UnfinishedResult;
34
+ /** The conversation so far, ready for `continueRun()`. */
35
+ readonly context: Context;
36
+ constructor(result: UnfinishedResult);
37
+ /** True for a `RunStoppedError`, including one from another copy of the package. Use it in place of `instanceof`. */
38
+ static isInstance(error: unknown): error is RunStoppedError;
39
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,47 @@
1
+ // A registered symbol, so the guard still works when two copies of the package are bundled.
2
+ const SDK_ERROR = Symbol.for("buildanagent.sdk.SdkError");
3
+ /**
4
+ * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema or
5
+ * exposure is unusable, or two tools share a name. `invalid_tool_result`: a tool's `execute` returned a malformed
6
+ * result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an option it can't use, such as a
7
+ * model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended without a final message.
8
+ * `run_stopped`: `runOrThrow()` was given a run that did not finish (a `RunStoppedError`). `unexpected_model_call`: a
9
+ * `ScriptedModel` was called more times than its script allows (an `UnexpectedModelCallError`).
10
+ */
11
+ export class SdkError extends Error {
12
+ name = "SdkError";
13
+ code;
14
+ constructor(code, message, options) {
15
+ super(message, options);
16
+ this.code = code;
17
+ Object.defineProperty(this, SDK_ERROR, { value: true });
18
+ }
19
+ }
20
+ /** True for an `SdkError`, including one from another copy of the package. */
21
+ export function isSdkError(error) {
22
+ return typeof error === "object" && error !== null && error[SDK_ERROR] === true;
23
+ }
24
+ const RUN_STOPPED_ERROR = Symbol.for("buildanagent.sdk.RunStoppedError");
25
+ /**
26
+ * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It
27
+ * carries the whole result, and the context to continue from. It is an `SdkError` with code `run_stopped`.
28
+ */
29
+ export class RunStoppedError extends SdkError {
30
+ name = "RunStoppedError";
31
+ stopReason;
32
+ result;
33
+ /** The conversation so far, ready for `continueRun()`. */
34
+ context;
35
+ constructor(result) {
36
+ super("run_stopped", `the run stopped with "${result.stopReason}" after ${result.steps} model calls`);
37
+ this.stopReason = result.stopReason;
38
+ this.result = result;
39
+ this.context = result.context;
40
+ Object.defineProperty(this, RUN_STOPPED_ERROR, { value: true });
41
+ }
42
+ /** True for a `RunStoppedError`, including one from another copy of the package. Use it in place of `instanceof`. */
43
+ static isInstance(error) {
44
+ return (typeof error === "object" && error !== null && error[RUN_STOPPED_ERROR] === true);
45
+ }
46
+ }
47
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAkBA,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D;;;;;;;GAOG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACf,IAAI,GAAW,UAAU,CAAC;IACnC,IAAI,CAAe;IAE5B,YAAY,IAAkB,EAAE,OAAe,EAAE,OAAsB;QACrE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1D,CAAC;CACF;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;AAC/G,CAAC;AAED,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;AAEzE;;;GAGG;AACH,MAAM,OAAO,eAAgB,SAAQ,QAAQ;IACzB,IAAI,GAAG,iBAAiB,CAAC;IAClC,UAAU,CAAiC;IAC3C,MAAM,CAAmB;IAClC,0DAA0D;IACjD,OAAO,CAAU;IAE1B,YAAY,MAAwB;QAClC,KAAK,CAAC,aAAa,EAAE,yBAAyB,MAAM,CAAC,UAAU,WAAW,MAAM,CAAC,KAAK,cAAc,CAAC,CAAC;QACtG,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;QACpC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;QAC9B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,iBAAiB,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAClE,CAAC;IAED,qHAAqH;IACrH,MAAM,CAAC,UAAU,CAAC,KAAc;QAC9B,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,iBAAiB,CAAC,KAAK,IAAI,CAC9G,CAAC;IACJ,CAAC;CACF","sourcesContent":["/**\n * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool\n * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never\n * thrown: the tool pipeline returns it to the model as an error result. Two subclasses keep their own names:\n * `RunStoppedError`, which `runOrThrow()` throws for a run that did not finish, and the testing export's\n * `UnexpectedModelCallError`.\n */\nimport type { Context, UnfinishedResult } from \"./result.js\";\n\n/** Why an `SdkError` was thrown. */\nexport type SdkErrorCode =\n | \"invalid_tool_definition\"\n | \"invalid_tool_result\"\n | \"invalid_run_options\"\n | \"invalid_model_stream\"\n | \"run_stopped\"\n | \"unexpected_model_call\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SDK_ERROR = Symbol.for(\"buildanagent.sdk.SdkError\");\n\n/**\n * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema or\n * exposure is unusable, or two tools share a name. `invalid_tool_result`: a tool's `execute` returned a malformed\n * result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an option it can't use, such as a\n * model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended without a final message.\n * `run_stopped`: `runOrThrow()` was given a run that did not finish (a `RunStoppedError`). `unexpected_model_call`: a\n * `ScriptedModel` was called more times than its script allows (an `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"]}
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The events a run streams: one closed union in two layers (agent-SDK guide §5). The delta layer streams each content
3
+ * block by its index; the item layer's end events (`model_call_end`, `tool_call_end`, `run_end`) carry the
4
+ * authoritative item, which a session log stores. `AGENT_EVENT_TYPES` lists the union at run time, so a test can
5
+ * check that the loop emits no type the union does not declare.
6
+ */
7
+ import type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from "@buildanagent/gateway";
8
+ import type { RunError, RunResult } from "./result.js";
9
+ import type { ToolResult } from "./tools/types.js";
10
+ /** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */
11
+ export interface EventBase {
12
+ readonly runId: string;
13
+ readonly seq: number;
14
+ readonly stepIndex: number;
15
+ /** When the event was emitted, from the run's clock, in ISO 8601. */
16
+ readonly timestamp: string;
17
+ }
18
+ /** One model call's request as the loop sends it: the model, the context and the options. */
19
+ export interface ModelCallRequest {
20
+ readonly model: ModelRef;
21
+ readonly context: ModelContext;
22
+ readonly options: DumpedOptions;
23
+ }
24
+ /**
25
+ * Why a `warning` event fired. `max_steps`: the run reached `maxSteps` and stopped. `model_warning`: the model call
26
+ * reported something that did not stop it, such as an option the provider would reject and the adapter dropped.
27
+ */
28
+ export type WarningCode = "max_steps" | "model_warning";
29
+ /** The body of each event, without the fields of `EventBase`. */
30
+ export type AgentEventBody = {
31
+ readonly type: "run_start";
32
+ readonly sdkVersion: string;
33
+ readonly specVersion: "v1";
34
+ /** Reserved for a hash of the run's defaults; empty for now. */
35
+ readonly defaultsHash: string;
36
+ /** Reserved for the SDK's capability names; empty for now. */
37
+ readonly capabilities: readonly string[];
38
+ readonly model: ModelRef;
39
+ } | {
40
+ readonly type: "run_end";
41
+ readonly result: RunResult;
42
+ }
43
+ /** Fires once nothing is running any more, retries and tools included; `run_end` follows it. */
44
+ | {
45
+ readonly type: "agent_settled";
46
+ } | {
47
+ readonly type: "step_start";
48
+ } | {
49
+ readonly type: "step_end";
50
+ readonly stopCheck: "continue" | "stop";
51
+ } | {
52
+ readonly type: "model_call_start";
53
+ readonly request: ModelCallRequest;
54
+ } | {
55
+ readonly type: "model_call_end";
56
+ readonly message: AssistantMessage;
57
+ } | {
58
+ readonly type: "text_start" | "reasoning_start" | "tool_input_start";
59
+ readonly index: number;
60
+ } | {
61
+ readonly type: "text_delta" | "reasoning_delta" | "tool_input_delta";
62
+ readonly index: number;
63
+ readonly delta: string;
64
+ } | {
65
+ readonly type: "text_end" | "reasoning_end" | "tool_input_end";
66
+ readonly index: number;
67
+ readonly block: ContentBlock;
68
+ } | {
69
+ readonly type: "tool_call_start";
70
+ readonly callId: string;
71
+ readonly tool: string;
72
+ readonly input: unknown;
73
+ } | {
74
+ readonly type: "tool_call_update";
75
+ readonly callId: string;
76
+ readonly details: unknown;
77
+ }
78
+ /** `result` is what the model reads for the call. */
79
+ | {
80
+ readonly type: "tool_call_end";
81
+ readonly callId: string;
82
+ readonly result: ToolResult;
83
+ }
84
+ /** The model is retrying a failed request; `attempt` is 1 for the first retry. */
85
+ | {
86
+ readonly type: "retry";
87
+ readonly attempt: number;
88
+ readonly delayMs: number;
89
+ readonly error: string;
90
+ } | {
91
+ readonly type: "warning";
92
+ readonly code: WarningCode;
93
+ readonly detail: string;
94
+ } | {
95
+ readonly type: "error";
96
+ readonly error: RunError;
97
+ } | {
98
+ readonly type: "abort";
99
+ readonly reason?: string;
100
+ };
101
+ /** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */
102
+ export type AgentEvent = EventBase & AgentEventBody;
103
+ /** Every `AgentEvent` type. A run emits no type this list lacks. */
104
+ export declare const AGENT_EVENT_TYPES: readonly ["run_start", "step_start", "model_call_start", "retry", "text_start", "text_delta", "text_end", "reasoning_start", "reasoning_delta", "reasoning_end", "tool_input_start", "tool_input_delta", "tool_input_end", "warning", "model_call_end", "tool_call_start", "tool_call_update", "tool_call_end", "step_end", "error", "abort", "agent_settled", "run_end"];
package/dist/events.js ADDED
@@ -0,0 +1,27 @@
1
+ /** Every `AgentEvent` type. A run emits no type this list lacks. */
2
+ export const AGENT_EVENT_TYPES = Object.freeze([
3
+ "run_start",
4
+ "step_start",
5
+ "model_call_start",
6
+ "retry",
7
+ "text_start",
8
+ "text_delta",
9
+ "text_end",
10
+ "reasoning_start",
11
+ "reasoning_delta",
12
+ "reasoning_end",
13
+ "tool_input_start",
14
+ "tool_input_delta",
15
+ "tool_input_end",
16
+ "warning",
17
+ "model_call_end",
18
+ "tool_call_start",
19
+ "tool_call_update",
20
+ "tool_call_end",
21
+ "step_end",
22
+ "error",
23
+ "abort",
24
+ "agent_settled",
25
+ "run_end",
26
+ ]);
27
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AA2EA,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,iBAAiB;IACjB,kBAAkB;IAClB,eAAe;IACf,UAAU;IACV,OAAO;IACP,OAAO;IACP,eAAe;IACf,SAAS;CACuC,CAAC,CAAC","sourcesContent":["/**\n * The events a run streams: one closed union in two layers (agent-SDK guide §5). The delta layer streams each content\n * block by its index; the item layer's end events (`model_call_end`, `tool_call_end`, `run_end`) carry the\n * authoritative item, which a session log stores. `AGENT_EVENT_TYPES` lists the union at run time, so a test can\n * check that the loop emits no type the union does not declare.\n */\nimport type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from \"@buildanagent/gateway\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { ToolResult } from \"./tools/types.js\";\n\n/** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */\nexport interface EventBase {\n readonly runId: string;\n readonly seq: number;\n readonly stepIndex: number;\n /** When the event was emitted, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** One model call's request as the loop sends it: the model, the context and the options. */\nexport interface ModelCallRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: DumpedOptions;\n}\n\n/**\n * Why a `warning` event fired. `max_steps`: the run reached `maxSteps` and stopped. `model_warning`: the model call\n * reported something that did not stop it, such as an option the provider would reject and the adapter dropped.\n */\nexport type WarningCode = \"max_steps\" | \"model_warning\";\n\n/** The body of each event, without the fields of `EventBase`. */\nexport type AgentEventBody =\n | {\n readonly type: \"run_start\";\n readonly sdkVersion: string;\n readonly specVersion: \"v1\";\n /** Reserved for a hash of the run's defaults; empty for now. */\n readonly defaultsHash: string;\n /** Reserved for the SDK's capability names; empty for now. */\n readonly capabilities: readonly string[];\n readonly model: ModelRef;\n }\n | { readonly type: \"run_end\"; readonly result: RunResult }\n /** Fires once nothing is running any more, retries and tools included; `run_end` follows it. */\n | { readonly type: \"agent_settled\" }\n | { readonly type: \"step_start\" }\n | { readonly type: \"step_end\"; readonly stopCheck: \"continue\" | \"stop\" }\n | { readonly type: \"model_call_start\"; readonly request: ModelCallRequest }\n | { readonly type: \"model_call_end\"; readonly message: AssistantMessage }\n | { readonly type: \"text_start\" | \"reasoning_start\" | \"tool_input_start\"; readonly index: number }\n | {\n readonly type: \"text_delta\" | \"reasoning_delta\" | \"tool_input_delta\";\n readonly index: number;\n readonly delta: string;\n }\n | {\n readonly type: \"text_end\" | \"reasoning_end\" | \"tool_input_end\";\n readonly index: number;\n readonly block: ContentBlock;\n }\n | { readonly type: \"tool_call_start\"; readonly callId: string; readonly tool: string; readonly input: unknown }\n | { readonly type: \"tool_call_update\"; readonly callId: string; readonly details: unknown }\n /** `result` is what the model reads for the call. */\n | { readonly type: \"tool_call_end\"; readonly callId: string; readonly result: ToolResult }\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 | { 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 \"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
@@ -1,6 +1,14 @@
1
1
  /**
2
- * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`.
3
- *
4
- * The loop, tools, hooks, signed pauses and budgets are planned in the SDK plan §3.3.
2
+ * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,
3
+ * `continueRun()`, `runOrThrow()`), its events and results, and the tools: their definitions, schemas, results and
4
+ * write outcomes. Hooks, signed pauses and budgets are planned in the SDK plan §3.3.
5
5
  */
6
+ export { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from "./errors.js";
7
+ export { AGENT_EVENT_TYPES, type AgentEvent, type AgentEventBody, type EventBase, type ModelCallRequest, type WarningCode, } from "./events.js";
8
+ export type { Context, DoneResult, EndedResult, ErrorResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
9
+ export { continueRun, type Run, type RunInput, type RunOptions, run, runOrThrow } from "./run.js";
10
+ export { type ClarificationToolOptions, clarificationTool, defineTool, type OutputToolOptions, outputTool, } from "./tools/define.js";
11
+ export type { JsonSchema, SchemaIssue, ToolContext, ToolDefinition, ToolEffect, ToolExposure, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
12
+ export type { WriteOutcome } from "./vendor/agent-safety/outcome.js";
13
+ /** The package's name, `@buildanagent/sdk`. */
6
14
  export declare const SDK_PACKAGE = "@buildanagent/sdk";
package/dist/index.js CHANGED
@@ -1,7 +1,12 @@
1
1
  /**
2
- * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`.
3
- *
4
- * The loop, tools, hooks, signed pauses and budgets are planned in the SDK plan §3.3.
2
+ * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,
3
+ * `continueRun()`, `runOrThrow()`), its events and results, and the tools: their definitions, schemas, results and
4
+ * write outcomes. Hooks, signed pauses and budgets are planned in the SDK plan §3.3.
5
5
  */
6
+ export { isSdkError, RunStoppedError, SdkError } from "./errors.js";
7
+ export { AGENT_EVENT_TYPES, } from "./events.js";
8
+ export { continueRun, run, runOrThrow } from "./run.js";
9
+ export { clarificationTool, defineTool, outputTool, } from "./tools/define.js";
10
+ /** The package's name, `@buildanagent/sdk`. */
6
11
  export const SDK_PACKAGE = "@buildanagent/sdk";
7
12
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`.\n *\n * The loop, tools, hooks, signed pauses and budgets are planned in the SDK plan §3.3.\n */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AACvF,OAAO,EACL,iBAAiB,GAMlB,MAAM,aAAa,CAAC;AAYrB,OAAO,EAAE,WAAW,EAA4C,GAAG,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAClG,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,UAAU,GACX,MAAM,mBAAmB,CAAC;AAc3B,+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, and the tools: their definitions, schemas, results and\n * write outcomes. Hooks, signed pauses and budgets are planned in the SDK plan §3.3.\n */\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 Context,\n DoneResult,\n EndedResult,\n ErrorResult,\n ResultBase,\n RunError,\n RunResult,\n StoppedResult,\n UnfinishedResult,\n} from \"./result.js\";\nexport { continueRun, type Run, type RunInput, type RunOptions, run, runOrThrow } from \"./run.js\";\nexport {\n type ClarificationToolOptions,\n clarificationTool,\n defineTool,\n type OutputToolOptions,\n outputTool,\n} from \"./tools/define.js\";\nexport type {\n JsonSchema,\n SchemaIssue,\n ToolContext,\n ToolDefinition,\n ToolEffect,\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 ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The step loop: one model call, then the tool calls it asked for, then the stop check, until a stop reason holds
3
+ * (agent-SDK guide §3). The non-streaming result is built from the same run, so there is one loop for both modes.
4
+ *
5
+ * Each step runs transform → before → stream → after → tools → stop. The transform, before and after moments are
6
+ * where the interceptors plug in (D6); until they exist the request is the transcript as it stands and the response
7
+ * is kept unchanged. Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed
8
+ * tool result, throws.
9
+ */
10
+ import { type Message, type Model, type ModelCallOptions } from "@buildanagent/gateway";
11
+ import type { AgentEventBody } from "./events.js";
12
+ import type { RunResult } from "./result.js";
13
+ import type { Clock } from "./testing/determinism.js";
14
+ import { type AnyTool } from "./tools/pipeline.js";
15
+ /** Everything one run needs, fixed when it starts. */
16
+ export interface LoopSetup {
17
+ readonly runId: string;
18
+ readonly model: Model;
19
+ readonly system: string;
20
+ /** The conversation before this run's own messages. */
21
+ readonly history: readonly Message[];
22
+ /** The messages the run starts by adding, such as the user's input. */
23
+ readonly input: readonly Message[];
24
+ /** The tools the model is sent, in definition order; only these can run. */
25
+ readonly tools: readonly AnyTool[];
26
+ readonly output: AnyTool | undefined;
27
+ readonly maxSteps: number;
28
+ readonly modelOptions: Omit<ModelCallOptions, "signal">;
29
+ readonly signal: AbortSignal;
30
+ readonly clock: Clock;
31
+ }
32
+ /** Sends one event; the run adds the `EventBase` fields. */
33
+ export type Emit = (body: AgentEventBody, stepIndex: number) => void;
34
+ /**
35
+ * Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results
36
+ * already received are in the transcript.
37
+ */
38
+ export declare function runLoop(setup: LoopSetup, emit: Emit): Promise<RunResult>;