@buildanagent/sdk 0.1.0-alpha.2 → 0.1.0-alpha.4

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/dist/loop.js ADDED
@@ -0,0 +1,232 @@
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 { addCost, addUsage, emptyUsage, } from "@buildanagent/gateway";
11
+ import { SdkError } from "./errors.js";
12
+ import { toWireTool } from "./tools/define.js";
13
+ import { runToolCalls } from "./tools/pipeline.js";
14
+ /** The `stoppedBy` of a run that a clarification tool stopped. */
15
+ const CLARIFICATION = "clarification";
16
+ // The depth cap's defaults (D11). Nested runs pass their own depth once the depth cap is configurable.
17
+ const TOP_LEVEL_DEPTH = 0;
18
+ const DEFAULT_MAX_DEPTH = 2;
19
+ /**
20
+ * The cost of no model call: an exact zero. Its basis is `provider` because `addCost()` keeps the other cost's basis
21
+ * when it adds a provider cost, so the zero never turns a billed sum into an estimate.
22
+ */
23
+ const NO_COST = { total: 0, basis: "provider", currency: "USD" };
24
+ /** What changes while a run goes on. */
25
+ class LoopState {
26
+ setup;
27
+ emit;
28
+ messages;
29
+ added;
30
+ wireTools;
31
+ steps = 0;
32
+ stepIndex = 0;
33
+ usage = emptyUsage();
34
+ cost;
35
+ output;
36
+ constructor(setup, emit) {
37
+ this.setup = setup;
38
+ this.emit = emit;
39
+ this.messages = [...setup.history, ...setup.input];
40
+ this.added = [...setup.input];
41
+ this.wireTools = setup.tools.map(toWireTool);
42
+ }
43
+ send(body) {
44
+ this.emit(body, this.stepIndex);
45
+ }
46
+ append(message) {
47
+ this.messages.push(message);
48
+ this.added.push(message);
49
+ }
50
+ }
51
+ /**
52
+ * The stream options a request event records: everything but the payload hook, the abort signal and the caps, as the
53
+ * gateway's own request dump leaves them out. An untyped caller may still pass a signal or caps in `modelOptions`.
54
+ */
55
+ function dumpedOptions(options) {
56
+ const { onPayload: _onPayload, signal: _signal, caps: _caps, ...rest } = options;
57
+ return rest;
58
+ }
59
+ /** Re-emits one model event as a run event, and returns the final message once the terminal event arrives. */
60
+ function forward(state, event) {
61
+ switch (event.type) {
62
+ case "done":
63
+ case "error":
64
+ return event.message;
65
+ case "start":
66
+ return undefined;
67
+ case "retry":
68
+ state.send({ type: "retry", attempt: event.attempt, delayMs: event.delayMs, error: event.error });
69
+ return undefined;
70
+ case "warning":
71
+ state.send({ type: "warning", code: "model_warning", detail: `${event.code}: ${event.message}` });
72
+ return undefined;
73
+ case "text_start":
74
+ case "reasoning_start":
75
+ case "tool_input_start":
76
+ state.send({ type: event.type, index: event.index });
77
+ return undefined;
78
+ case "text_delta":
79
+ case "reasoning_delta":
80
+ case "tool_input_delta":
81
+ state.send({ type: event.type, index: event.index, delta: event.delta });
82
+ return undefined;
83
+ default:
84
+ state.send({ type: event.type, index: event.index, block: event.block });
85
+ return undefined;
86
+ }
87
+ }
88
+ /** Makes one model call, streams its events and records the response. */
89
+ async function callModel(state) {
90
+ const { model, system, modelOptions, signal } = state.setup;
91
+ const context = { system, messages: [...state.messages], tools: state.wireTools };
92
+ state.send({
93
+ type: "model_call_start",
94
+ request: { model: model.ref, context, options: dumpedOptions(modelOptions) },
95
+ });
96
+ let message;
97
+ for await (const event of model.stream(context, { ...modelOptions, signal })) {
98
+ message = forward(state, event) ?? message;
99
+ }
100
+ if (message === undefined) {
101
+ throw new SdkError("invalid_model_stream", "the model's stream ended without a done or error event");
102
+ }
103
+ state.steps += 1;
104
+ state.usage = addUsage(state.usage, message.usage);
105
+ state.cost = state.cost === undefined ? message.cost : addCost(state.cost, message.cost);
106
+ state.append(message);
107
+ state.send({ type: "model_call_end", message });
108
+ return message;
109
+ }
110
+ /** The tool message the model reads for one call. */
111
+ function toolMessage(entry) {
112
+ return {
113
+ role: "tool",
114
+ callId: entry.call.callId,
115
+ content: [...entry.result.content],
116
+ isError: entry.result.isError === true,
117
+ };
118
+ }
119
+ /** Runs the response's tool calls as the pipeline schedules them, recording each result in model order. */
120
+ async function runTools(state, message) {
121
+ const { runId, signal, clock, tools, output } = state.setup;
122
+ return runToolCalls(message, tools, {
123
+ runId,
124
+ signal,
125
+ clock,
126
+ depth: TOP_LEVEL_DEPTH,
127
+ maxDepth: DEFAULT_MAX_DEPTH,
128
+ onStart: (call) => state.send({ type: "tool_call_start", callId: call.callId, tool: call.name, input: call.input }),
129
+ onUpdate: (callId, details) => state.send({ type: "tool_call_update", callId, details }),
130
+ onResult: (entry) => {
131
+ state.append(toolMessage(entry));
132
+ if (output !== undefined && entry.call.name === output.name && entry.result.isError !== true) {
133
+ state.output = entry.result.structured;
134
+ }
135
+ state.send({ type: "tool_call_end", callId: entry.call.callId, result: entry.result });
136
+ },
137
+ });
138
+ }
139
+ /** The failed call's error as the run reports it. A message without one counts as `fatal`. */
140
+ function runErrorOf(message) {
141
+ const error = message.error;
142
+ if (error === undefined)
143
+ return { kind: "fatal", message: "the model call failed without an error description" };
144
+ return { kind: error.kind, message: error.message, ...(error.status === undefined ? {} : { status: error.status }) };
145
+ }
146
+ /**
147
+ * The stop check after one step. A finished answer, or a question for the user, wins over an abort that came too late
148
+ * to change it; otherwise an abort stops the run before the step cap does. A text answer cut off at the output limit
149
+ * also counts as finished: its message keeps `stopReason: "length"`.
150
+ */
151
+ function stopCheck(state, message, results) {
152
+ if (message.stopReason === "error")
153
+ return { stopReason: "error", error: runErrorOf(message) };
154
+ if (message.stopReason === "aborted")
155
+ return { stopReason: "aborted" };
156
+ const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);
157
+ if (finished)
158
+ return { stopReason: "done", output: state.output };
159
+ // Until runs can pause for an answer, a clarification question stops the run, so the model never goes on as if the
160
+ // user had been asked and answered.
161
+ if (results.some(({ result }) => result.pause !== undefined && !result.isError)) {
162
+ return { stopReason: "stopped", stoppedBy: CLARIFICATION };
163
+ }
164
+ if (state.setup.signal.aborted)
165
+ return { stopReason: "aborted" };
166
+ if (state.steps >= state.setup.maxSteps)
167
+ return { stopReason: "max_steps" };
168
+ return undefined;
169
+ }
170
+ async function runStep(state) {
171
+ state.stepIndex = state.steps;
172
+ state.send({ type: "step_start" });
173
+ const message = await callModel(state);
174
+ const results = await runTools(state, message);
175
+ const outcome = stopCheck(state, message, results);
176
+ state.send({ type: "step_end", stopCheck: outcome === undefined ? "continue" : "stop" });
177
+ return outcome;
178
+ }
179
+ /**
180
+ * An aborted run's transcript ends with an assistant message whose `stopReason` is `"aborted"`. When tool results end
181
+ * the transcript, because the abort came while tools ran or cut off a response that held tool calls, the loop
182
+ * appends an empty one after them; the replay pass drops it before any request.
183
+ */
184
+ function closeAborted(state) {
185
+ const last = state.messages.at(-1);
186
+ if (last?.role === "assistant" && last.stopReason === "aborted")
187
+ return;
188
+ state.append({
189
+ role: "assistant",
190
+ content: [],
191
+ model: state.setup.model.ref,
192
+ stopReason: "aborted",
193
+ usage: emptyUsage(),
194
+ cost: { ...NO_COST },
195
+ });
196
+ }
197
+ function resultOf(state, outcome) {
198
+ const base = {
199
+ messages: state.added,
200
+ context: { system: state.setup.system, messages: state.messages },
201
+ usage: state.usage,
202
+ cost: state.cost ?? { ...NO_COST },
203
+ steps: state.steps,
204
+ };
205
+ return { ...base, ...outcome };
206
+ }
207
+ function finish(state, outcome) {
208
+ if (outcome.stopReason === "aborted")
209
+ closeAborted(state);
210
+ if (outcome.stopReason === "max_steps") {
211
+ state.send({ type: "warning", code: "max_steps", detail: `the run reached maxSteps (${state.setup.maxSteps})` });
212
+ }
213
+ if (outcome.stopReason === "error")
214
+ state.send({ type: "error", error: outcome.error });
215
+ state.send({ type: "agent_settled" });
216
+ const result = resultOf(state, outcome);
217
+ state.send({ type: "run_end", result });
218
+ return result;
219
+ }
220
+ /**
221
+ * Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results
222
+ * already received are in the transcript.
223
+ */
224
+ export async function runLoop(setup, emit) {
225
+ const state = new LoopState(setup, emit);
226
+ let outcome;
227
+ while (outcome === undefined) {
228
+ outcome = setup.signal.aborted ? { stopReason: "aborted" } : await runStep(state);
229
+ }
230
+ return finish(state, outcome);
231
+ }
232
+ //# sourceMappingURL=loop.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loop.js","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAEL,OAAO,EACP,QAAQ,EAGR,UAAU,GASX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAIvC,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,uGAAuG;AACvG,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAE5B;;;GAGG;AACH,MAAM,OAAO,GAAS,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AA8BvE,wCAAwC;AACxC,MAAM,SAAS;IACJ,KAAK,CAAY;IACjB,IAAI,CAAO;IACX,QAAQ,CAAY;IACpB,KAAK,CAAY;IACjB,SAAS,CAAa;IAC/B,KAAK,GAAG,CAAC,CAAC;IACV,SAAS,GAAG,CAAC,CAAC;IACd,KAAK,GAAU,UAAU,EAAE,CAAC;IAC5B,IAAI,CAAmB;IACvB,MAAM,CAAU;IAEhB,YAAY,KAAgB,EAAE,IAAU;QACtC,IAAI,CAAC,KAAK,GAAG,KAAK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AK,EAAE,OAAO,CAAC,CAAC;IACxC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;IACxC,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,KAAgB,EAAE,IAAU;IACxD,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACzC,IAAI,OAA4B,CAAC;IACjC,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. The transform, before and after moments are\n * where the interceptors plug in (D6); until they exist the request is the transcript as it stands and the response\n * is kept unchanged. Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed\n * tool result, 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 ModelCallOptions,\n type ModelContext,\n type StreamOptions,\n type Usage,\n type WireTool,\n} from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.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// The depth cap's defaults (D11). Nested runs pass their own depth once the depth cap is configurable.\nconst TOP_LEVEL_DEPTH = 0;\nconst DEFAULT_MAX_DEPTH = 2;\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 /** The tools the model is sent, in definition order; only these can run. */\n readonly tools: readonly AnyTool[];\n readonly output: AnyTool | undefined;\n readonly maxSteps: number;\n readonly modelOptions: Omit<ModelCallOptions, \"signal\">;\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/** 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 | { readonly stopReason: \"error\"; readonly error: RunError }\n | { readonly stopReason: \"stopped\"; readonly stoppedBy: 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 wireTools: WireTool[];\n steps = 0;\n stepIndex = 0;\n usage: Usage = emptyUsage();\n cost: Cost | undefined;\n output: unknown;\n\n constructor(setup: LoopSetup, emit: Emit) {\n this.setup = setup;\n this.emit = emit;\n this.messages = [...setup.history, ...setup.input];\n this.added = [...setup.input];\n this.wireTools = setup.tools.map(toWireTool);\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: Omit<ModelCallOptions, \"signal\">): 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/** Makes one model call, streams its events and records the response. */\nasync function callModel(state: LoopState): Promise<AssistantMessage> {\n const { model, system, modelOptions, signal } = state.setup;\n const context: ModelContext = { system, messages: [...state.messages], tools: state.wireTools };\n state.send({\n type: \"model_call_start\",\n request: { model: model.ref, context, options: dumpedOptions(modelOptions) },\n });\n let message: AssistantMessage | undefined;\n for await (const event of model.stream(context, { ...modelOptions, 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 state.steps += 1;\n state.usage = addUsage(state.usage, message.usage);\n state.cost = state.cost === undefined ? message.cost : addCost(state.cost, message.cost);\n state.append(message);\n state.send({ type: \"model_call_end\", 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, tools, output } = state.setup;\n return runToolCalls(message, tools, {\n runId,\n signal,\n clock,\n depth: TOP_LEVEL_DEPTH,\n maxDepth: DEFAULT_MAX_DEPTH,\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 state.send({ type: \"tool_call_end\", callId: entry.call.callId, result: entry.result });\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\nasync function runStep(state: LoopState): Promise<Outcome | undefined> {\n state.stepIndex = state.steps;\n state.send({ type: \"step_start\" });\n const message = await callModel(state);\n const results = await runTools(state, message);\n const outcome = stopCheck(state, message, results);\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\nfunction finish(state: LoopState, outcome: Outcome): 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 state.send({ type: \"agent_settled\" });\n const result = resultOf(state, outcome);\n state.send({ type: \"run_end\", result });\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): Promise<RunResult> {\n const state = new LoopState(setup, emit);\n let outcome: Outcome | undefined;\n while (outcome === undefined) {\n outcome = setup.signal.aborted ? { stopReason: \"aborted\" } : await runStep(state);\n }\n return finish(state, outcome);\n}\n"]}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * What a run returns: a union discriminated by `stopReason`, in which only the `done` variant carries `output`, so
3
+ * code that reads the output without checking the stop reason fails to compile (D10). Every variant carries the
4
+ * usage, the cost and a context the run can continue from.
5
+ */
6
+ import type { AssistantMessage, Cost, Message, Usage } from "@buildanagent/gateway";
7
+ /**
8
+ * A run's conversation as plain JSON: the system prompt and every message so far. Store it anywhere and pass it to
9
+ * `continueRun()` to go on from where the run stopped.
10
+ */
11
+ export interface Context {
12
+ readonly system: string;
13
+ readonly messages: readonly Message[];
14
+ }
15
+ /** Why a model call failed, copied from the failed message's `error`. */
16
+ export interface RunError {
17
+ /**
18
+ * `overflow`: the request was larger than the model's context window. `quota`: the account is out of quota or
19
+ * credit. `retryable`: a temporary failure that outlasted the model's retries. `fatal`: any other failure, such as a
20
+ * rejected request.
21
+ */
22
+ readonly kind: NonNullable<AssistantMessage["error"]>["kind"];
23
+ readonly message: string;
24
+ /** The provider's HTTP status, when the failure came with one. */
25
+ readonly status?: number;
26
+ }
27
+ /** The fields every run result carries. */
28
+ export interface ResultBase {
29
+ /** The messages this run added: the input, if any, then every response and tool result, in order. */
30
+ readonly messages: readonly Message[];
31
+ /** The whole conversation, earlier history included, ready for `continueRun()`. */
32
+ readonly context: Context;
33
+ /** The tokens of every model call, summed. */
34
+ readonly usage: Usage;
35
+ /**
36
+ * The cost of every model call, summed. It is unknown if any call's cost is. A run that made no call costs an exact
37
+ * 0 with basis `provider`, so adding it to another cost keeps that cost's basis.
38
+ */
39
+ readonly cost: Cost;
40
+ /** How many model calls the run made. */
41
+ readonly steps: number;
42
+ }
43
+ /**
44
+ * A run that finished: the model answered without calling a tool, or an output tool accepted its answer. `output` is
45
+ * the accepted answer, and `undefined` when the run has no output tool, the model answered in text, or another tool
46
+ * ended the run with `terminate: true`. A text
47
+ * answer cut off at the output limit also ends `done`; its message's `stopReason` is then `"length"`.
48
+ */
49
+ export interface DoneResult<S> extends ResultBase {
50
+ readonly stopReason: "done";
51
+ readonly output: S | undefined;
52
+ }
53
+ /**
54
+ * A run that ended before it finished. `max_steps`: it made `maxSteps` model calls and the model still wanted to
55
+ * continue. `aborted`: it was aborted.
56
+ */
57
+ export interface EndedResult extends ResultBase {
58
+ readonly stopReason: "max_steps" | "aborted";
59
+ }
60
+ /** A run that ended because a model call failed. */
61
+ export interface ErrorResult extends ResultBase {
62
+ readonly stopReason: "error";
63
+ readonly error: RunError;
64
+ }
65
+ /**
66
+ * A run that stopped before it finished, for a reason `stoppedBy` names. `clarification`: a tool from
67
+ * `clarificationTool()` asked the user a question. To go on, add the answer to `context` as a user message and pass the
68
+ * context to `continueRun()`.
69
+ */
70
+ export interface StoppedResult extends ResultBase {
71
+ readonly stopReason: "stopped";
72
+ readonly stoppedBy: string;
73
+ }
74
+ /** What a run returns. Check `stopReason` before you read the fields of one variant. */
75
+ export type RunResult<S = unknown> = DoneResult<S> | EndedResult | ErrorResult | StoppedResult;
76
+ /** Every run result except `done`, which `runOrThrow()` turns into a `RunStoppedError`. */
77
+ export type UnfinishedResult = Exclude<RunResult, DoneResult<unknown>>;
package/dist/result.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=result.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result.js","sourceRoot":"","sources":["../src/result.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * What a run returns: a union discriminated by `stopReason`, in which only the `done` variant carries `output`, so\n * code that reads the output without checking the stop reason fails to compile (D10). Every variant carries the\n * usage, the cost and a context the run can continue from.\n */\nimport type { AssistantMessage, Cost, Message, Usage } from \"@buildanagent/gateway\";\n\n/**\n * A run's conversation as plain JSON: the system prompt and every message so far. Store it anywhere and pass it to\n * `continueRun()` to go on from where the run stopped.\n */\nexport interface Context {\n readonly system: string;\n readonly messages: readonly Message[];\n}\n\n/** Why a model call failed, copied from the failed message's `error`. */\nexport interface RunError {\n /**\n * `overflow`: the request was larger than the model's context window. `quota`: the account is out of quota or\n * credit. `retryable`: a temporary failure that outlasted the model's retries. `fatal`: any other failure, such as a\n * rejected request.\n */\n readonly kind: NonNullable<AssistantMessage[\"error\"]>[\"kind\"];\n readonly message: string;\n /** The provider's HTTP status, when the failure came with one. */\n readonly status?: number;\n}\n\n/** The fields every run result carries. */\nexport interface ResultBase {\n /** The messages this run added: the input, if any, then every response and tool result, in order. */\n readonly messages: readonly Message[];\n /** The whole conversation, earlier history included, ready for `continueRun()`. */\n readonly context: Context;\n /** The tokens of every model call, summed. */\n readonly usage: Usage;\n /**\n * The cost of every model call, summed. It is unknown if any call's cost is. A run that made no call costs an exact\n * 0 with basis `provider`, so adding it to another cost keeps that cost's basis.\n */\n readonly cost: Cost;\n /** How many model calls the run made. */\n readonly steps: number;\n}\n\n/**\n * A run that finished: the model answered without calling a tool, or an output tool accepted its answer. `output` is\n * the accepted answer, and `undefined` when the run has no output tool, the model answered in text, or another tool\n * ended the run with `terminate: true`. A text\n * answer cut off at the output limit also ends `done`; its message's `stopReason` is then `\"length\"`.\n */\nexport interface DoneResult<S> extends ResultBase {\n readonly stopReason: \"done\";\n readonly output: S | undefined;\n}\n\n/**\n * A run that ended before it finished. `max_steps`: it made `maxSteps` model calls and the model still wanted to\n * continue. `aborted`: it was aborted.\n */\nexport interface EndedResult extends ResultBase {\n readonly stopReason: \"max_steps\" | \"aborted\";\n}\n\n/** A run that ended because a model call failed. */\nexport interface ErrorResult extends ResultBase {\n readonly stopReason: \"error\";\n readonly error: RunError;\n}\n\n/**\n * A run that stopped before it finished, for a reason `stoppedBy` names. `clarification`: a tool from\n * `clarificationTool()` asked the user a question. To go on, add the answer to `context` as a user message and pass the\n * context to `continueRun()`.\n */\nexport interface StoppedResult extends ResultBase {\n readonly stopReason: \"stopped\";\n readonly stoppedBy: string;\n}\n\n/** What a run returns. Check `stopReason` before you read the fields of one variant. */\nexport type RunResult<S = unknown> = DoneResult<S> | EndedResult | ErrorResult | StoppedResult;\n\n/** Every run result except `done`, which `runOrThrow()` turns into a `RunStoppedError`. */\nexport type UnfinishedResult = Exclude<RunResult, DoneResult<unknown>>;\n"]}
package/dist/run.d.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * `run()`, `continueRun()` and `runOrThrow()`, and the `Run` object they share (SDK plan §3.3; D10). A run streams
3
+ * its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the
4
+ * non-streaming caller drive one loop.
5
+ */
6
+ import type { ContentBlock, Message, Model, ModelCallOptions } from "@buildanagent/gateway";
7
+ import type { AgentEvent } from "./events.js";
8
+ import type { Context, DoneResult, RunResult } from "./result.js";
9
+ import type { Clock } from "./testing/determinism.js";
10
+ import type { ToolDefinition } from "./tools/types.js";
11
+ /** The options `run()` and `continueRun()` share. */
12
+ export interface RunOptions<S = unknown> {
13
+ /** The model, from `createModel()`. */
14
+ readonly model: Model;
15
+ /** The tools the model may call. Tools whose `exposure` is `deferred` or `hidden` are not sent. */
16
+ readonly tools?: readonly ToolDefinition<unknown, unknown>[];
17
+ /**
18
+ * A tool from `outputTool()` whose input is the final answer. It is sent with the other tools; once the model calls
19
+ * it with input that passes its schema, the run ends `done`, and `result.output` holds the validated answer.
20
+ */
21
+ readonly output?: ToolDefinition<S, S>;
22
+ /**
23
+ * The most model calls the run may make. Default 20. A run that reaches it while the model still wants to go on
24
+ * ends with `stopReason: "max_steps"` and emits a `warning` event with `code: "max_steps"`.
25
+ */
26
+ readonly maxSteps?: number;
27
+ /** Aborts the run, like `run.abort()`. */
28
+ readonly signal?: AbortSignal;
29
+ /** Options for every model call, such as `maxOutputTokens`. The run passes its own abort signal. */
30
+ readonly modelOptions?: Omit<ModelCallOptions, "signal">;
31
+ /** Stamps each event's `timestamp`, and is passed to tools. Defaults to the system clock. */
32
+ readonly clock?: Clock;
33
+ /** Makes the run's id. Defaults to `crypto.randomUUID()`. */
34
+ readonly idGenerator?: () => string;
35
+ }
36
+ /** What `run()` takes besides the shared options. */
37
+ export interface RunInput {
38
+ /** The system prompt. */
39
+ readonly system: string;
40
+ /** The user's message that starts the run. */
41
+ readonly input: string | readonly ContentBlock[];
42
+ /** Earlier messages to send before `input`, such as a previous conversation. */
43
+ readonly history?: readonly Message[];
44
+ }
45
+ /**
46
+ * A run in progress. Iterate it to stream its events: each iteration starts from the run's first event, so you can
47
+ * start iterating at any time. Await `result` for the outcome; it rejects only for a programmer error, such as a
48
+ * tool that returns a malformed result, and iteration then throws the same error after the last event.
49
+ */
50
+ export interface Run<S = unknown> extends AsyncIterable<AgentEvent> {
51
+ /** The run's id, which every event carries. */
52
+ readonly id: string;
53
+ /** The outcome, once the run has stopped. */
54
+ readonly result: Promise<RunResult<S>>;
55
+ /**
56
+ * Stops the run. A model call in flight ends, a running tool sees its `signal` fire, and calls that haven't started
57
+ * get an error result instead. The run then ends with `stopReason: "aborted"`. Does nothing once the run has ended.
58
+ */
59
+ abort(reason?: string): void;
60
+ }
61
+ /**
62
+ * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool
63
+ * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an
64
+ * unusable option: a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool
65
+ * that isn't sent to the model, or two tools with one name.
66
+ */
67
+ export declare function run<S = unknown>(options: RunOptions<S> & RunInput): Run<S>;
68
+ /**
69
+ * Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like
70
+ * `run()`, from the last message in the context, and `result.messages` holds only the messages it adds. The context
71
+ * 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.
72
+ */
73
+ export declare function continueRun<S = unknown>(context: Context, options: RunOptions<S>): Run<S>;
74
+ /**
75
+ * Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that
76
+ * carries the result and the context to continue from.
77
+ */
78
+ export declare function runOrThrow<S>(started: Run<S>): Promise<DoneResult<S>>;
package/dist/run.js ADDED
@@ -0,0 +1,165 @@
1
+ import { RunStoppedError, SdkError } from "./errors.js";
2
+ import { runLoop } from "./loop.js";
3
+ import { preparedSchemaOf } from "./tools/define.js";
4
+ import { SDK_VERSION } from "./version.js";
5
+ /** The step cap's default, counted in model calls. */
6
+ const DEFAULT_MAX_STEPS = 20;
7
+ const systemClock = { now: () => new Date().toISOString() };
8
+ const randomIds = () => globalThis.crypto.randomUUID();
9
+ function reasonOf(reason) {
10
+ if (typeof reason === "string")
11
+ return reason;
12
+ return reason instanceof Error ? reason.message : undefined;
13
+ }
14
+ class RunHandle {
15
+ id;
16
+ result;
17
+ #events = [];
18
+ #controller = new AbortController();
19
+ #clock;
20
+ #waiters = [];
21
+ #ended = false;
22
+ #failure;
23
+ #stepIndex = 0;
24
+ constructor(setup, signal) {
25
+ this.id = setup.runId;
26
+ this.#clock = setup.clock;
27
+ const emit = (body, stepIndex) => this.#push(body, stepIndex);
28
+ const { model } = setup;
29
+ const versions = { sdkVersion: SDK_VERSION, specVersion: "v1", defaultsHash: "", capabilities: [] };
30
+ emit({ type: "run_start", ...versions, model: model.ref }, 0);
31
+ const forwardAbort = () => this.abort(reasonOf(signal?.reason));
32
+ if (signal?.aborted)
33
+ forwardAbort();
34
+ else
35
+ signal?.addEventListener("abort", forwardAbort, { once: true });
36
+ const loop = runLoop({ ...setup, signal: this.#controller.signal }, emit);
37
+ // The loop's result type is `RunResult<unknown>`; only the output tool, whose type is `S`, fills `output`.
38
+ this.result = loop;
39
+ // Handling the rejection here also keeps a caller who only iterates from an unhandled rejection: iteration
40
+ // throws the same error.
41
+ loop.then(() => this.#end(signal, forwardAbort, undefined), (error) => this.#end(signal, forwardAbort, { error }));
42
+ }
43
+ abort(reason) {
44
+ if (this.#ended || this.#controller.signal.aborted)
45
+ return;
46
+ this.#push(reason === undefined ? { type: "abort" } : { type: "abort", reason }, this.#stepIndex);
47
+ this.#controller.abort(reason);
48
+ }
49
+ [Symbol.asyncIterator]() {
50
+ let cursor = 0;
51
+ return {
52
+ next: async () => {
53
+ while (cursor >= this.#events.length && !this.#ended) {
54
+ await new Promise((resolve) => this.#waiters.push(resolve));
55
+ }
56
+ const event = this.#events[cursor];
57
+ if (event !== undefined) {
58
+ cursor += 1;
59
+ return { value: event, done: false };
60
+ }
61
+ if (this.#failure !== undefined)
62
+ throw this.#failure.error;
63
+ return { value: undefined, done: true };
64
+ },
65
+ };
66
+ }
67
+ #push(body, stepIndex) {
68
+ this.#stepIndex = stepIndex;
69
+ const base = { runId: this.id, seq: this.#events.length, stepIndex, timestamp: this.#clock.now() };
70
+ this.#events.push({ ...base, ...body });
71
+ this.#wake();
72
+ }
73
+ #end(signal, forwardAbort, failure) {
74
+ signal?.removeEventListener("abort", forwardAbort);
75
+ this.#failure = failure;
76
+ this.#ended = true;
77
+ this.#wake();
78
+ }
79
+ #wake() {
80
+ const waiters = this.#waiters;
81
+ this.#waiters = [];
82
+ for (const wake of waiters)
83
+ wake();
84
+ }
85
+ }
86
+ function isModel(model) {
87
+ const candidate = model;
88
+ return (typeof candidate === "object" &&
89
+ candidate !== null &&
90
+ typeof candidate.stream === "function" &&
91
+ typeof candidate.price === "function" &&
92
+ typeof candidate.ref === "object");
93
+ }
94
+ /** Every tool the run may send, the output tool last unless `tools` already holds it, after checking each one. */
95
+ function toolsOf(options) {
96
+ const tools = [...(options.tools ?? [])];
97
+ const output = options.output;
98
+ if (output !== undefined && !tools.includes(output))
99
+ tools.push(output);
100
+ const names = new Set();
101
+ for (const tool of tools) {
102
+ preparedSchemaOf(tool);
103
+ if (names.has(tool.name)) {
104
+ throw new SdkError("invalid_tool_definition", `two tools are named "${tool.name}"; tool names must be unique`);
105
+ }
106
+ names.add(tool.name);
107
+ }
108
+ return tools;
109
+ }
110
+ function setupOf(options, context, input) {
111
+ if (!isModel(options.model)) {
112
+ throw new SdkError("invalid_run_options", "the model must come from createModel(), such as createModel({ adapter, id })");
113
+ }
114
+ const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;
115
+ if (!Number.isInteger(maxSteps) || maxSteps < 1) {
116
+ throw new SdkError("invalid_run_options", `maxSteps must be a positive integer, got ${maxSteps}`);
117
+ }
118
+ const tools = toolsOf(options);
119
+ if (options.output !== undefined && (options.output.exposure ?? "direct") !== "direct") {
120
+ throw new SdkError("invalid_run_options", `the output tool "${options.output.name}" must be sent to the model, so its exposure must be "direct"`);
121
+ }
122
+ return {
123
+ runId: (options.idGenerator ?? randomIds)(),
124
+ model: options.model,
125
+ system: context.system,
126
+ history: context.messages,
127
+ input,
128
+ tools: tools.filter((tool) => (tool.exposure ?? "direct") === "direct"),
129
+ output: options.output,
130
+ maxSteps,
131
+ modelOptions: options.modelOptions ?? {},
132
+ clock: options.clock ?? systemClock,
133
+ };
134
+ }
135
+ /**
136
+ * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool
137
+ * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an
138
+ * unusable option: a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool
139
+ * that isn't sent to the model, or two tools with one name.
140
+ */
141
+ export function run(options) {
142
+ const content = typeof options.input === "string" ? [{ type: "text", text: options.input }] : options.input;
143
+ const input = { role: "user", content: [...content] };
144
+ const setup = setupOf(options, { system: options.system, messages: options.history ?? [] }, [input]);
145
+ return new RunHandle(setup, options.signal);
146
+ }
147
+ /**
148
+ * Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like
149
+ * `run()`, from the last message in the context, and `result.messages` holds only the messages it adds. The context
150
+ * 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.
151
+ */
152
+ export function continueRun(context, options) {
153
+ return new RunHandle(setupOf(options, context, []), options.signal);
154
+ }
155
+ /**
156
+ * Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that
157
+ * carries the result and the context to continue from.
158
+ */
159
+ export async function runOrThrow(started) {
160
+ const result = await started.result;
161
+ if (result.stopReason === "done")
162
+ return result;
163
+ throw new RunStoppedError(result);
164
+ }
165
+ //# sourceMappingURL=run.js.map