@buildanagent/sdk 0.1.0-alpha.1 → 0.1.0-alpha.11
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 +424 -5
- package/dist/budget.d.ts +33 -0
- package/dist/budget.js +55 -0
- package/dist/budget.js.map +1 -0
- package/dist/compose.d.ts +26 -0
- package/dist/compose.js +157 -0
- package/dist/compose.js.map +1 -0
- package/dist/errors.d.ts +49 -0
- package/dist/errors.js +57 -0
- package/dist/errors.js.map +1 -0
- package/dist/events.d.ts +168 -0
- package/dist/events.js +32 -0
- package/dist/events.js.map +1 -0
- package/dist/freeze.d.ts +11 -0
- package/dist/freeze.js +42 -0
- package/dist/freeze.js.map +1 -0
- package/dist/hook-checks.d.ts +31 -0
- package/dist/hook-checks.js +130 -0
- package/dist/hook-checks.js.map +1 -0
- package/dist/hook-runner.d.ts +96 -0
- package/dist/hook-runner.js +372 -0
- package/dist/hook-runner.js.map +1 -0
- package/dist/hooks.d.ts +183 -0
- package/dist/hooks.js +2 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +26 -3
- package/dist/index.js +21 -3
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +67 -0
- package/dist/loop.js +644 -0
- package/dist/loop.js.map +1 -0
- package/dist/observers.d.ts +31 -0
- package/dist/observers.js +98 -0
- package/dist/observers.js.map +1 -0
- package/dist/otel/attributes.d.ts +43 -0
- package/dist/otel/attributes.js +50 -0
- package/dist/otel/attributes.js.map +1 -0
- package/dist/otel/content.d.ts +17 -0
- package/dist/otel/content.js +48 -0
- package/dist/otel/content.js.map +1 -0
- package/dist/otel/index.d.ts +6 -2
- package/dist/otel/index.js +6 -2
- package/dist/otel/index.js.map +1 -1
- package/dist/otel/observer.d.ts +82 -0
- package/dist/otel/observer.js +300 -0
- package/dist/otel/observer.js.map +1 -0
- package/dist/pauses.d.ts +61 -0
- package/dist/pauses.js +83 -0
- package/dist/pauses.js.map +1 -0
- package/dist/progress.d.ts +34 -0
- package/dist/progress.js +139 -0
- package/dist/progress.js.map +1 -0
- package/dist/result.d.ts +134 -0
- package/dist/result.js +2 -0
- package/dist/result.js.map +1 -0
- package/dist/resume.d.ts +76 -0
- package/dist/resume.js +237 -0
- package/dist/resume.js.map +1 -0
- package/dist/run.d.ts +214 -0
- package/dist/run.js +327 -0
- package/dist/run.js.map +1 -0
- package/dist/steering.d.ts +52 -0
- package/dist/steering.js +104 -0
- package/dist/steering.js.map +1 -0
- package/dist/testing/scripted-model.d.ts +12 -2
- package/dist/testing/scripted-model.js +19 -2
- package/dist/testing/scripted-model.js.map +1 -1
- package/dist/tools/coerce.d.ts +15 -0
- package/dist/tools/coerce.js +93 -0
- package/dist/tools/coerce.js.map +1 -0
- package/dist/tools/define.d.ts +54 -0
- package/dist/tools/define.js +121 -0
- package/dist/tools/define.js.map +1 -0
- package/dist/tools/format-error.d.ts +13 -0
- package/dist/tools/format-error.js +66 -0
- package/dist/tools/format-error.js.map +1 -0
- package/dist/tools/outcome.d.ts +7 -0
- package/dist/tools/outcome.js +30 -0
- package/dist/tools/outcome.js.map +1 -0
- package/dist/tools/pipeline.d.ts +111 -0
- package/dist/tools/pipeline.js +382 -0
- package/dist/tools/pipeline.js.map +1 -0
- package/dist/tools/scheduler.d.ts +33 -0
- package/dist/tools/scheduler.js +51 -0
- package/dist/tools/scheduler.js.map +1 -0
- package/dist/tools/schema.d.ts +20 -0
- package/dist/tools/schema.js +100 -0
- package/dist/tools/schema.js.map +1 -0
- package/dist/tools/types.d.ts +196 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/vendor/agent-safety/bytes.d.ts +17 -0
- package/dist/vendor/agent-safety/bytes.js +59 -0
- package/dist/vendor/agent-safety/bytes.js.map +1 -0
- package/dist/vendor/agent-safety/errors.d.ts +23 -0
- package/dist/vendor/agent-safety/errors.js +22 -0
- package/dist/vendor/agent-safety/errors.js.map +1 -0
- package/dist/vendor/agent-safety/hash.d.ts +16 -0
- package/dist/vendor/agent-safety/hash.js +110 -0
- package/dist/vendor/agent-safety/hash.js.map +1 -0
- package/dist/vendor/agent-safety/outcome.d.ts +88 -0
- package/dist/vendor/agent-safety/outcome.js +140 -0
- package/dist/vendor/agent-safety/outcome.js.map +1 -0
- package/dist/vendor/agent-safety/pending.d.ts +119 -0
- package/dist/vendor/agent-safety/pending.js +122 -0
- package/dist/vendor/agent-safety/pending.js.map +1 -0
- package/dist/vendor/agent-safety/render.d.ts +40 -0
- package/dist/vendor/agent-safety/render.js +92 -0
- package/dist/vendor/agent-safety/render.js.map +1 -0
- package/dist/vendor/agent-safety/signer.d.ts +42 -0
- package/dist/vendor/agent-safety/signer.js +128 -0
- package/dist/vendor/agent-safety/signer.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +8 -0
- package/dist/version.js.map +1 -0
- package/package.json +13 -3
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { SdkError } from "../errors.js";
|
|
2
|
+
import { coerceValue } from "./coerce.js";
|
|
3
|
+
import { preparedSchemaOf } from "./define.js";
|
|
4
|
+
import { formatToolError, REDACTED_MESSAGE } from "./format-error.js";
|
|
5
|
+
import { withOutcome } from "./outcome.js";
|
|
6
|
+
import { schedule } from "./scheduler.js";
|
|
7
|
+
function toolsByName(tools) {
|
|
8
|
+
const byName = new Map();
|
|
9
|
+
for (const tool of tools) {
|
|
10
|
+
preparedSchemaOf(tool);
|
|
11
|
+
if (byName.has(tool.name)) {
|
|
12
|
+
throw new SdkError("invalid_tool_definition", `two tools are named "${tool.name}"; tool names must be unique`);
|
|
13
|
+
}
|
|
14
|
+
byName.set(tool.name, tool);
|
|
15
|
+
}
|
|
16
|
+
return byName;
|
|
17
|
+
}
|
|
18
|
+
function errorMessage(error) {
|
|
19
|
+
return error instanceof Error ? error.message : String(error);
|
|
20
|
+
}
|
|
21
|
+
function isModelContent(block) {
|
|
22
|
+
if (typeof block !== "object" || block === null)
|
|
23
|
+
return false;
|
|
24
|
+
const { type, text, mediaType, data } = block;
|
|
25
|
+
if (type === "text")
|
|
26
|
+
return typeof text === "string";
|
|
27
|
+
return type === "image" && typeof mediaType === "string" && typeof data === "string";
|
|
28
|
+
}
|
|
29
|
+
/** True for a list of text and image blocks, the only content a tool result may carry. */
|
|
30
|
+
export function isContentList(content) {
|
|
31
|
+
return Array.isArray(content) && content.every(isModelContent);
|
|
32
|
+
}
|
|
33
|
+
// A formatter that throws, or returns something the model can't read, must not hide the failure from the model, so
|
|
34
|
+
// the default text is used instead, and the formatter's error is kept in `details`.
|
|
35
|
+
function formatted(failure, tool) {
|
|
36
|
+
const fallback = formatToolError(failure);
|
|
37
|
+
if (tool?.formatError === undefined)
|
|
38
|
+
return { content: fallback };
|
|
39
|
+
let content;
|
|
40
|
+
try {
|
|
41
|
+
content = tool.formatError(failure);
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
return { content: fallback, error: errorMessage(error) };
|
|
45
|
+
}
|
|
46
|
+
if (isContentList(content))
|
|
47
|
+
return { content };
|
|
48
|
+
return { content: fallback, error: "formatError did not return a list of text and image blocks" };
|
|
49
|
+
}
|
|
50
|
+
function failed(failure, tool, details = {}) {
|
|
51
|
+
const { content, error: formatterError } = formatted(failure, tool);
|
|
52
|
+
return {
|
|
53
|
+
content,
|
|
54
|
+
isError: true,
|
|
55
|
+
details: { failure, ...details, ...(formatterError === undefined ? {} : { formatterError }) },
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
// Coerce, validate, and on failure give `repair` one chance. The model sees the issues of its own arguments, and
|
|
59
|
+
// `details` keeps what repair returned.
|
|
60
|
+
async function checkInput(tool, call) {
|
|
61
|
+
const schema = preparedSchemaOf(tool);
|
|
62
|
+
const coerced = coerceValue(call.input, schema.jsonSchema);
|
|
63
|
+
const first = await schema.validate(coerced);
|
|
64
|
+
if (first.ok)
|
|
65
|
+
return { ok: true, input: first.value };
|
|
66
|
+
const failure = {
|
|
67
|
+
kind: "invalid_input",
|
|
68
|
+
tool: tool.name,
|
|
69
|
+
callId: call.callId,
|
|
70
|
+
input: call.input,
|
|
71
|
+
issues: first.issues,
|
|
72
|
+
};
|
|
73
|
+
if (tool.repair === undefined)
|
|
74
|
+
return { ok: false, result: failed(failure, tool) };
|
|
75
|
+
let repaired;
|
|
76
|
+
try {
|
|
77
|
+
repaired = await tool.repair({ input: coerced, issues: first.issues });
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
return { ok: false, result: failed(failure, tool, { repairError: errorMessage(error) }) };
|
|
81
|
+
}
|
|
82
|
+
if (repaired === undefined)
|
|
83
|
+
return { ok: false, result: failed(failure, tool) };
|
|
84
|
+
const second = await schema.validate(coerceValue(repaired, schema.jsonSchema));
|
|
85
|
+
if (second.ok)
|
|
86
|
+
return { ok: true, input: second.value };
|
|
87
|
+
return { ok: false, result: failed(failure, tool, { repaired, repairedIssues: second.issues }) };
|
|
88
|
+
}
|
|
89
|
+
function checkResult(tool, result) {
|
|
90
|
+
const content = result?.content;
|
|
91
|
+
if (typeof result !== "object" || result === null || !isContentList(content)) {
|
|
92
|
+
throw new SdkError("invalid_tool_result", `tool "${tool}" must return an object whose content is a list of text and image blocks`);
|
|
93
|
+
}
|
|
94
|
+
return result;
|
|
95
|
+
}
|
|
96
|
+
async function execute(tool, call, input, ctx) {
|
|
97
|
+
const context = {
|
|
98
|
+
runId: ctx.runId,
|
|
99
|
+
callId: call.callId,
|
|
100
|
+
signal: ctx.signal,
|
|
101
|
+
depth: ctx.depth,
|
|
102
|
+
maxDepth: ctx.maxDepth,
|
|
103
|
+
clock: ctx.clock,
|
|
104
|
+
update: (details) => ctx.onUpdate?.(call.callId, details),
|
|
105
|
+
};
|
|
106
|
+
let result;
|
|
107
|
+
try {
|
|
108
|
+
result = await tool.execute(input, context);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
ctx.onExecuted?.(call);
|
|
112
|
+
const message = errorMessage(error);
|
|
113
|
+
const redacted = tool.redactErrors === true;
|
|
114
|
+
const failure = {
|
|
115
|
+
kind: "execution_error",
|
|
116
|
+
tool: tool.name,
|
|
117
|
+
callId: call.callId,
|
|
118
|
+
input: call.input,
|
|
119
|
+
message: redacted ? REDACTED_MESSAGE : message,
|
|
120
|
+
redacted,
|
|
121
|
+
};
|
|
122
|
+
return failed(failure, tool, { error: { name: error instanceof Error ? error.name : typeof error, message } });
|
|
123
|
+
}
|
|
124
|
+
ctx.onExecuted?.(call);
|
|
125
|
+
return withOutcome(tool.name, checkResult(tool.name, result));
|
|
126
|
+
}
|
|
127
|
+
function notRun(call, tool, reason) {
|
|
128
|
+
return failed({ kind: "not_run", reason, tool: call.name, callId: call.callId, input: call.input }, tool);
|
|
129
|
+
}
|
|
130
|
+
// Why none of a message's calls may run, or undefined when they all may.
|
|
131
|
+
function unrunnable(message, call, tools) {
|
|
132
|
+
const tool = tools.find((candidate) => candidate.name === call.name);
|
|
133
|
+
switch (message.stopReason) {
|
|
134
|
+
case "length":
|
|
135
|
+
return failed({ kind: "truncated", tool: call.name, callId: call.callId, input: call.input }, tool);
|
|
136
|
+
case "error":
|
|
137
|
+
return notRun(call, tool, "response_error");
|
|
138
|
+
case "aborted":
|
|
139
|
+
return notRun(call, tool, "response_aborted");
|
|
140
|
+
default:
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function resourceKeyOf(tool, input) {
|
|
145
|
+
if (tool.resourceKey === undefined)
|
|
146
|
+
return undefined;
|
|
147
|
+
let key;
|
|
148
|
+
try {
|
|
149
|
+
key = tool.resourceKey(input);
|
|
150
|
+
}
|
|
151
|
+
catch (cause) {
|
|
152
|
+
throw new SdkError("invalid_tool_definition", `tool "${tool.name}": resourceKey threw: ${errorMessage(cause)}`, {
|
|
153
|
+
cause,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
if (typeof key !== "string") {
|
|
157
|
+
throw new SdkError("invalid_tool_definition", `tool "${tool.name}": resourceKey must return a string`);
|
|
158
|
+
}
|
|
159
|
+
return key;
|
|
160
|
+
}
|
|
161
|
+
// Asks the gate about one call. A replacement input is checked against the tool's schema again, because the gate is
|
|
162
|
+
// user code and a call must never run with input its own tool would have rejected.
|
|
163
|
+
async function gateCall(call, tool, input, ctx) {
|
|
164
|
+
const outcome = await ctx.gate?.({ call, tool, input });
|
|
165
|
+
if (outcome === undefined)
|
|
166
|
+
return { input };
|
|
167
|
+
if ("blocked" in outcome || "paused" in outcome)
|
|
168
|
+
return outcome;
|
|
169
|
+
const checked = await preparedSchemaOf(tool).validate(outcome.input);
|
|
170
|
+
if (!checked.ok) {
|
|
171
|
+
const issues = checked.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join("; ");
|
|
172
|
+
throw new SdkError("invalid_hook_result", `beforeToolCall replaced the input of tool "${tool.name}" with input its schema rejects: ${issues}`);
|
|
173
|
+
}
|
|
174
|
+
return { input: checked.value, replaced: true };
|
|
175
|
+
}
|
|
176
|
+
// Everything that happens before execution, for one call: name, cancellation, input checks, resource key, and the
|
|
177
|
+
// gate. A call that fails any of them is `Done` with the result the model reads.
|
|
178
|
+
async function prepareCall(call, early, byName, ctx) {
|
|
179
|
+
if (early !== undefined)
|
|
180
|
+
return { kind: "done", call, result: early };
|
|
181
|
+
const tool = byName.get(call.name);
|
|
182
|
+
if (tool === undefined) {
|
|
183
|
+
const availableTools = [...byName.keys()];
|
|
184
|
+
const failure = {
|
|
185
|
+
kind: "unknown_tool",
|
|
186
|
+
tool: call.name,
|
|
187
|
+
callId: call.callId,
|
|
188
|
+
input: call.input,
|
|
189
|
+
availableTools,
|
|
190
|
+
};
|
|
191
|
+
return { kind: "done", call, result: failed(failure, undefined) };
|
|
192
|
+
}
|
|
193
|
+
// Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.
|
|
194
|
+
if (ctx.signal.aborted)
|
|
195
|
+
return { kind: "done", call, result: notRun(call, tool, "run_aborted") };
|
|
196
|
+
if (ctx.approved === true)
|
|
197
|
+
return prepareApproved(call, tool);
|
|
198
|
+
const checked = await checkInput(tool, call);
|
|
199
|
+
if (!checked.ok)
|
|
200
|
+
return { kind: "done", call, result: checked.result };
|
|
201
|
+
if (ctx.signal.aborted)
|
|
202
|
+
return { kind: "done", call, result: notRun(call, tool, "run_aborted") };
|
|
203
|
+
// Each call's gate settles before the next call's is asked, and every gate before any call executes.
|
|
204
|
+
const gated = await gateCall(call, tool, checked.input, ctx);
|
|
205
|
+
if ("blocked" in gated)
|
|
206
|
+
return { kind: "done", call, result: gated.blocked };
|
|
207
|
+
if ("paused" in gated)
|
|
208
|
+
return { kind: "paused", call, tool, request: gated.paused, input: gated.input };
|
|
209
|
+
const replaced = "replaced" in gated;
|
|
210
|
+
return { kind: "ready", call, tool, input: gated.input, replaced, key: resourceKeyOf(tool, gated.input) };
|
|
211
|
+
}
|
|
212
|
+
// A call whose input a verified approval signed runs with that input as it is. It is checked against the schema once
|
|
213
|
+
// more, because the tool may have changed since the pause, but the checked value never replaces it.
|
|
214
|
+
async function prepareApproved(call, tool) {
|
|
215
|
+
const checked = await preparedSchemaOf(tool).validate(call.input);
|
|
216
|
+
if (!checked.ok) {
|
|
217
|
+
const failure = {
|
|
218
|
+
kind: "invalid_input",
|
|
219
|
+
tool: tool.name,
|
|
220
|
+
callId: call.callId,
|
|
221
|
+
input: call.input,
|
|
222
|
+
issues: checked.issues,
|
|
223
|
+
};
|
|
224
|
+
return { kind: "done", call, result: failed(failure, tool) };
|
|
225
|
+
}
|
|
226
|
+
return { kind: "ready", call, tool, input: call.input, replaced: false, key: resourceKeyOf(tool, call.input) };
|
|
227
|
+
}
|
|
228
|
+
// Only a first-party tool's hint counts: an MCP server's annotations are claims by someone we don't control. A tool
|
|
229
|
+
// with an `effect` changes the world whatever its hint says, so it always queues as a writer.
|
|
230
|
+
function isTrustedReadOnly(tool) {
|
|
231
|
+
return tool.firstParty === true && tool.annotations?.readOnlyHint === true && tool.effect === undefined;
|
|
232
|
+
}
|
|
233
|
+
// Relays the run's cancellation to the signal the batch's tools receive, which a failing sibling can also fire.
|
|
234
|
+
function batchController(runSignal) {
|
|
235
|
+
const batch = new AbortController();
|
|
236
|
+
const relay = () => batch.abort(runSignal.reason);
|
|
237
|
+
if (runSignal.aborted)
|
|
238
|
+
relay();
|
|
239
|
+
else
|
|
240
|
+
runSignal.addEventListener("abort", relay, { once: true });
|
|
241
|
+
return { batch, release: () => runSignal.removeEventListener("abort", relay) };
|
|
242
|
+
}
|
|
243
|
+
// Runs one ready call under the batch's signal. A programmer error cancels the siblings before it propagates; a
|
|
244
|
+
// model-caused failure is an ordinary result and cancels nothing.
|
|
245
|
+
async function runReady(item, ctx, batch) {
|
|
246
|
+
if (batch.signal.aborted) {
|
|
247
|
+
return notRun(item.call, item.tool, ctx.signal.aborted ? "run_aborted" : "sibling_failed");
|
|
248
|
+
}
|
|
249
|
+
try {
|
|
250
|
+
const result = await execute(item.tool, item.call, item.input, { ...ctx, signal: batch.signal });
|
|
251
|
+
if (ctx.after === undefined)
|
|
252
|
+
return result;
|
|
253
|
+
return await ctx.after({ call: item.call, tool: item.tool, input: item.input, result });
|
|
254
|
+
}
|
|
255
|
+
catch (error) {
|
|
256
|
+
batch.abort(error);
|
|
257
|
+
throw error;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
// Starts every ready call by the scheduling rules and returns, in model order, the promise of each call's result.
|
|
261
|
+
function start(prepared, sequential, ctx, batch) {
|
|
262
|
+
const ready = prepared.filter((item) => item.kind === "ready");
|
|
263
|
+
const scheduled = schedule(ready.map((item) => ({
|
|
264
|
+
...(item.key === undefined ? {} : { key: item.key }),
|
|
265
|
+
readOnly: isTrustedReadOnly(item.tool),
|
|
266
|
+
run: () => runReady(item, ctx, batch),
|
|
267
|
+
})), sequential);
|
|
268
|
+
const byItem = new Map(ready.map((item, index) => [item, scheduled[index]]));
|
|
269
|
+
return prepared.map((item) => {
|
|
270
|
+
if (item.kind === "paused")
|
|
271
|
+
return undefined;
|
|
272
|
+
if (item.kind === "done")
|
|
273
|
+
return Promise.resolve({ ok: true, value: item.result });
|
|
274
|
+
return byItem.get(item);
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Runs the calls of one step. Each call is checked and gated one at a time, in model order, before any call executes.
|
|
279
|
+
* The calls that passed then start together, except that a call to a sequential tool makes the whole step run one
|
|
280
|
+
* call at a time, even when that call itself fails a check, and calls that share a `resourceKey` queue in model
|
|
281
|
+
* order. Results reach `ctx.onResult` in model order, each as soon as every result before it is in. A call the gate
|
|
282
|
+
* paused gets no result and is left out; each one reaches `ctx.onPause`, in model order, once every call is gated.
|
|
283
|
+
*
|
|
284
|
+
* A programmer error (an `SdkError`) in one call fires the signal the other calls hold, waits for them to stop, and
|
|
285
|
+
* is then thrown, after every other call's result has been passed on: a call after the failing one may have run and
|
|
286
|
+
* written. A programmer error while the calls are checked, such as a `resourceKey` that throws, is thrown after the
|
|
287
|
+
* calls already checked get their results, so every call that started has one, except the call that failed.
|
|
288
|
+
*/
|
|
289
|
+
async function runCalls(calls, early, tools, ctx) {
|
|
290
|
+
const byName = toolsByName(tools);
|
|
291
|
+
const prepared = [];
|
|
292
|
+
try {
|
|
293
|
+
for (const call of calls) {
|
|
294
|
+
ctx.onStart?.(call);
|
|
295
|
+
prepared.push(await prepareCall(call, early(call), byName, ctx));
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
// None of these calls has executed, and none will. The first error is the one thrown, so a receiver that throws
|
|
300
|
+
// here must not hide it or stop the other calls from getting their results.
|
|
301
|
+
// A paused call gets a not-run result here too: the run is failing, so its pause is never reported or returned.
|
|
302
|
+
for (const item of prepared) {
|
|
303
|
+
const result = item.kind === "done" ? item.result : notRun(item.call, item.tool, "sibling_failed");
|
|
304
|
+
try {
|
|
305
|
+
ctx.onResult?.({ call: item.call, result });
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
// Not rethrown: the error being handled is thrown below.
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
throw error;
|
|
312
|
+
}
|
|
313
|
+
// Reported only now, once every call has been gated, so a step that fails while its calls are checked never reports
|
|
314
|
+
// a pause and then gives the same call a result.
|
|
315
|
+
for (const item of prepared) {
|
|
316
|
+
if (item.kind === "paused")
|
|
317
|
+
ctx.onPause?.({ call: item.call, request: item.request, input: item.input });
|
|
318
|
+
}
|
|
319
|
+
const sequential = calls.some((call) => byName.get(call.name)?.executionMode === "sequential");
|
|
320
|
+
const { batch, release } = batchController(ctx.signal);
|
|
321
|
+
try {
|
|
322
|
+
return await deliver(prepared, start(prepared, sequential, ctx, batch), ctx, batch);
|
|
323
|
+
}
|
|
324
|
+
finally {
|
|
325
|
+
release();
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
// Passes each result on in model order, as soon as every result before it is in. A failed call has already cancelled
|
|
329
|
+
// the others; the loop still waits for each of them and passes its result on, so none is left running and a write
|
|
330
|
+
// that happened is recorded, and then the first error is thrown. A receiver that throws is a failed call too: it
|
|
331
|
+
// cancels the siblings, and the results after it are still passed on.
|
|
332
|
+
async function deliver(prepared, running, ctx, batch) {
|
|
333
|
+
const results = [];
|
|
334
|
+
let failure;
|
|
335
|
+
for (const [index, pending] of running.entries()) {
|
|
336
|
+
if (pending === undefined)
|
|
337
|
+
continue;
|
|
338
|
+
const settled = await pending;
|
|
339
|
+
if (!settled.ok) {
|
|
340
|
+
failure ??= { error: settled.error };
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
const item = prepared[index];
|
|
344
|
+
const replaced = item.kind === "ready" && item.replaced ? { input: item.input } : {};
|
|
345
|
+
const ran = item.kind === "ready" ? { ranWith: item.input } : {};
|
|
346
|
+
const entry = { call: item.call, result: settled.value, ...replaced, ...ran };
|
|
347
|
+
results.push(entry);
|
|
348
|
+
try {
|
|
349
|
+
ctx.onResult?.(entry);
|
|
350
|
+
}
|
|
351
|
+
catch (error) {
|
|
352
|
+
failure ??= { error };
|
|
353
|
+
batch.abort(error);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (failure !== undefined)
|
|
357
|
+
throw failure.error;
|
|
358
|
+
return results;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure
|
|
362
|
+
* the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws
|
|
363
|
+
* an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.
|
|
364
|
+
*/
|
|
365
|
+
export async function runToolCall(call, tools, ctx) {
|
|
366
|
+
const { onStart: _start, onResult: _result, onPause: _pause, ...quiet } = ctx;
|
|
367
|
+
const [entry] = await runCalls([call], () => undefined, tools, quiet);
|
|
368
|
+
if (entry === undefined)
|
|
369
|
+
throw new SdkError("invalid_hook_result", `runToolCall() can't pause the call "${call.name}"`);
|
|
370
|
+
return entry.result;
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Runs every tool call of an assistant message and passes each result to `ctx.onResult` in model order. A message
|
|
374
|
+
* that stopped at the output limit (`stopReason: "length"`) runs nothing: each of its calls gets an error asking the
|
|
375
|
+
* model to re-issue it, because its arguments may be cut short. A message that ended in an error or was aborted also
|
|
376
|
+
* runs nothing, because its calls may be partial. Otherwise the calls are scheduled as `runCalls` describes.
|
|
377
|
+
*/
|
|
378
|
+
export async function runToolCalls(message, tools, ctx) {
|
|
379
|
+
const calls = message.content.filter((block) => block.type === "tool_call");
|
|
380
|
+
return runCalls(calls, (call) => unrunnable(message, call, tools), tools, ctx);
|
|
381
|
+
}
|
|
382
|
+
//# sourceMappingURL=pipeline.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/tools/pipeline.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAGxC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC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AAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,EAAE,GAAG,GAAG,CAAC;IAC9E,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,QAAQ,CAAC,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC,SAAS,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IACtE,IAAI,KAAK,KAAK,SAAS;QACrB,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,uCAAuC,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC;IACjG,OAAO,KAAK,CAAC,MAAM,CAAC;AACtB,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,OAAyB,EACzB,KAAyB,EACzB,GAAoB;IAEpB,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAqB,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC;IAC/F,OAAO,QAAQ,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AACjF,CAAC","sourcesContent":["/**\n * The tool pipeline: the fixed steps every tool call runs (agent-SDK guide §4). Resolve the name, coerce, validate,\n * an optional `repair`, the gate, `execute`, the write outcome, then `afterToolCall`. A failure the model caused\n * becomes an error result and never throws; only a programmer error, such as a malformed tool result, throws an\n * `SdkError`.\n *\n * The gate runs after validation and `after` runs after `execute`. The run's interceptors fill them (`beforeToolCall`\n * and `afterToolCall`), and a pipeline without them allows every call and keeps every result. A step's calls are\n * checked and gated one at a time, in model order, and then scheduled together (see `runCalls`).\n */\nimport type { AssistantMessage, ModelContent } from \"@buildanagent/gateway\";\nimport { SdkError } from \"../errors.js\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport type { SignedPendingRequest } from \"../vendor/agent-safety/pending.js\";\nimport { coerceValue } from \"./coerce.js\";\nimport { preparedSchemaOf } from \"./define.js\";\nimport { formatToolError, REDACTED_MESSAGE } from \"./format-error.js\";\nimport { withOutcome } from \"./outcome.js\";\nimport { type Settled, schedule } from \"./scheduler.js\";\nimport type { ToolCall, ToolDefinition, ToolFailure, ToolResult } from \"./types.js\";\n\n/** A tool of any input and structured type, as the pipeline holds it. */\nexport type AnyTool = ToolDefinition<unknown, unknown>;\n\n/** What the pipeline needs from the run around it. */\nexport interface PipelineContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly depth: number;\n readonly maxDepth: number;\n readonly clock: Clock;\n /**\n * The gate: asked once for each call that passed validation, one call at a time in model order, and before any call\n * of the step executes. It returns `{ blocked }` to stop the call with that result, `{ paused, input }` to hold the\n * call for a person with no result at all, with the signed request and the input it signs, `{ input }` to run it\n * with another input, which must pass the tool's schema, or `undefined` to let it run as it is. Without a gate every\n * call is allowed.\n */\n gate?(e: {\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly input: unknown;\n }): Promise<GateOutcome | undefined>;\n /**\n * Called with the result of each call that executed, and returns the result to use in its place. It runs inside the\n * call's own task, so a sibling is never left running while it works, and a programmer error it throws cancels the\n * siblings like one from `execute`.\n */\n after?(e: {\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly input: unknown;\n readonly result: ToolResult;\n }): Promise<ToolResult>;\n /** Called for each call of a message before its result is worked out, whether or not the call will run. */\n onStart?(call: ToolCall): void;\n /** Receives a tool's progress updates. */\n onUpdate?(callId: string, details: unknown): void;\n /**\n * Receives each call's result as soon as `runToolCalls` has it, so the run can record a write before a later call\n * in the same message throws.\n */\n onResult?(entry: ToolCallResult): void;\n /**\n * Receives each call the gate paused, with its signed request and the input that request signs, in model order and\n * only once every call of the message has been gated.\n */\n onPause?(entry: PausedCall): void;\n /**\n * Called as soon as a tool's `execute` returns or throws, before the result is checked, so the run knows a write\n * may have happened even when its result then throws an `SdkError`.\n */\n onExecuted?(call: ToolCall): void;\n /**\n * True when every call already holds the input a verified approval signed: each runs with that input exactly, once\n * it still passes the tool's schema, and no gate is asked. Coercion and `repair` are skipped, because they ran\n * before the input was signed.\n */\n readonly approved?: boolean;\n}\n\n/** What a gate decides besides letting a call run unchanged. */\nexport type GateOutcome =\n | { readonly blocked: ToolResult }\n | { readonly paused: SignedPendingRequest; readonly input: unknown }\n | { readonly input: unknown };\n\n/** A tool call a gate paused: its signed request, and the input the request signs. */\nexport interface PausedCall {\n readonly call: ToolCall;\n readonly request: SignedPendingRequest;\n readonly input: unknown;\n}\n\n/** One tool call and the result the model will read for it. */\nexport interface ToolCallResult {\n readonly call: ToolCall;\n readonly result: ToolResult;\n /** The input the gate put in place of the model's, present only when the gate replaced it. */\n readonly input?: unknown;\n /** The input the call executed with, present only for a call that executed. */\n readonly ranWith?: unknown;\n}\n\nfunction toolsByName(tools: readonly AnyTool[]): ReadonlyMap<string, AnyTool> {\n const byName = new Map<string, AnyTool>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (byName.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n byName.set(tool.name, tool);\n }\n return byName;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isModelContent(block: unknown): block is ModelContent {\n if (typeof block !== \"object\" || block === null) return false;\n const { type, text, mediaType, data } = block as Record<string, unknown>;\n if (type === \"text\") return typeof text === \"string\";\n return type === \"image\" && typeof mediaType === \"string\" && typeof data === \"string\";\n}\n\n/** True for a list of text and image blocks, the only content a tool result may carry. */\nexport function isContentList(content: unknown): content is readonly ModelContent[] {\n return Array.isArray(content) && content.every(isModelContent);\n}\n\ntype Formatted = { readonly content: readonly ModelContent[]; readonly error?: string };\n\n// A formatter that throws, or returns something the model can't read, must not hide the failure from the model, so\n// the default text is used instead, and the formatter's error is kept in `details`.\nfunction formatted(failure: ToolFailure, tool: AnyTool | undefined): Formatted {\n const fallback = formatToolError(failure);\n if (tool?.formatError === undefined) return { content: fallback };\n let content: unknown;\n try {\n content = tool.formatError(failure);\n } catch (error) {\n return { content: fallback, error: errorMessage(error) };\n }\n if (isContentList(content)) return { content };\n return { content: fallback, error: \"formatError did not return a list of text and image blocks\" };\n}\n\nfunction failed(failure: ToolFailure, tool: AnyTool | undefined, details: Record<string, unknown> = {}): ToolResult {\n const { content, error: formatterError } = formatted(failure, tool);\n return {\n content,\n isError: true,\n details: { failure, ...details, ...(formatterError === undefined ? {} : { formatterError }) },\n };\n}\n\ntype Checked = { readonly ok: true; readonly input: unknown } | { readonly ok: false; readonly result: ToolResult };\n\n// Coerce, validate, and on failure give `repair` one chance. The model sees the issues of its own arguments, and\n// `details` keeps what repair returned.\nasync function checkInput(tool: AnyTool, call: ToolCall): Promise<Checked> {\n const schema = preparedSchemaOf(tool);\n const coerced = coerceValue(call.input, schema.jsonSchema);\n const first = await schema.validate(coerced);\n if (first.ok) return { ok: true, input: first.value };\n const failure: ToolFailure = {\n kind: \"invalid_input\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n issues: first.issues,\n };\n if (tool.repair === undefined) return { ok: false, result: failed(failure, tool) };\n let repaired: unknown;\n try {\n repaired = await tool.repair({ input: coerced, issues: first.issues });\n } catch (error) {\n return { ok: false, result: failed(failure, tool, { repairError: errorMessage(error) }) };\n }\n if (repaired === undefined) return { ok: false, result: failed(failure, tool) };\n const second = await schema.validate(coerceValue(repaired, schema.jsonSchema));\n if (second.ok) return { ok: true, input: second.value };\n return { ok: false, result: failed(failure, tool, { repaired, repairedIssues: second.issues }) };\n}\n\nfunction checkResult(tool: string, result: unknown): ToolResult {\n const content = (result as { content?: unknown } | null)?.content;\n if (typeof result !== \"object\" || result === null || !isContentList(content)) {\n throw new SdkError(\n \"invalid_tool_result\",\n `tool \"${tool}\" must return an object whose content is a list of text and image blocks`,\n );\n }\n return result as ToolResult;\n}\n\nasync function execute(tool: AnyTool, call: ToolCall, input: unknown, ctx: PipelineContext): Promise<ToolResult> {\n const context = {\n runId: ctx.runId,\n callId: call.callId,\n signal: ctx.signal,\n depth: ctx.depth,\n maxDepth: ctx.maxDepth,\n clock: ctx.clock,\n update: (details: unknown) => ctx.onUpdate?.(call.callId, details),\n };\n let result: unknown;\n try {\n result = await tool.execute(input, context);\n } catch (error) {\n ctx.onExecuted?.(call);\n const message = errorMessage(error);\n const redacted = tool.redactErrors === true;\n const failure: ToolFailure = {\n kind: \"execution_error\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n message: redacted ? REDACTED_MESSAGE : message,\n redacted,\n };\n return failed(failure, tool, { error: { name: error instanceof Error ? error.name : typeof error, message } });\n }\n ctx.onExecuted?.(call);\n return withOutcome(tool.name, checkResult(tool.name, result));\n}\n\ntype NotRunReason = Extract<ToolFailure, { kind: \"not_run\" }>[\"reason\"];\n\nfunction notRun(call: ToolCall, tool: AnyTool | undefined, reason: NotRunReason): ToolResult {\n return failed({ kind: \"not_run\", reason, tool: call.name, callId: call.callId, input: call.input }, tool);\n}\n\n// Why none of a message's calls may run, or undefined when they all may.\nfunction unrunnable(message: AssistantMessage, call: ToolCall, tools: readonly AnyTool[]): ToolResult | undefined {\n const tool = tools.find((candidate) => candidate.name === call.name);\n switch (message.stopReason) {\n case \"length\":\n return failed({ kind: \"truncated\", tool: call.name, callId: call.callId, input: call.input }, tool);\n case \"error\":\n return notRun(call, tool, \"response_error\");\n case \"aborted\":\n return notRun(call, tool, \"response_aborted\");\n default:\n return undefined;\n }\n}\n\n/** A call that passed every check before execution and now waits to be scheduled. */\ninterface Ready {\n readonly kind: \"ready\";\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly input: unknown;\n /** True when the gate replaced the model's input with `input`. */\n readonly replaced: boolean;\n readonly key: string | undefined;\n}\n\n/** A call whose result is already known: it failed a check, was gated or could not run. */\ninterface Done {\n readonly kind: \"done\";\n readonly call: ToolCall;\n readonly result: ToolResult;\n}\n\n/** A call held for a person: it never runs in this step and gets no result, so the transcript leaves it open. */\ninterface Paused {\n readonly kind: \"paused\";\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly request: SignedPendingRequest;\n /** The input the request signs, which the call would run with once approved. */\n readonly input: unknown;\n}\n\ntype Prepared = Ready | Done | Paused;\n\nfunction resourceKeyOf(tool: AnyTool, input: unknown): string | undefined {\n if (tool.resourceKey === undefined) return undefined;\n let key: unknown;\n try {\n key = tool.resourceKey(input);\n } catch (cause) {\n throw new SdkError(\"invalid_tool_definition\", `tool \"${tool.name}\": resourceKey threw: ${errorMessage(cause)}`, {\n cause,\n });\n }\n if (typeof key !== \"string\") {\n throw new SdkError(\"invalid_tool_definition\", `tool \"${tool.name}\": resourceKey must return a string`);\n }\n return key;\n}\n\n// Asks the gate about one call. A replacement input is checked against the tool's schema again, because the gate is\n// user code and a call must never run with input its own tool would have rejected.\nasync function gateCall(\n call: ToolCall,\n tool: AnyTool,\n input: unknown,\n ctx: PipelineContext,\n): Promise<\n | { readonly blocked: ToolResult }\n | { readonly paused: SignedPendingRequest; readonly input: unknown }\n | { readonly input: unknown; readonly replaced?: true }\n> {\n const outcome = await ctx.gate?.({ call, tool, input });\n if (outcome === undefined) return { input };\n if (\"blocked\" in outcome || \"paused\" in outcome) return outcome;\n const checked = await preparedSchemaOf(tool).validate(outcome.input);\n if (!checked.ok) {\n const issues = checked.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join(\"; \");\n throw new SdkError(\n \"invalid_hook_result\",\n `beforeToolCall replaced the input of tool \"${tool.name}\" with input its schema rejects: ${issues}`,\n );\n }\n return { input: checked.value, replaced: true };\n}\n\n// Everything that happens before execution, for one call: name, cancellation, input checks, resource key, and the\n// gate. A call that fails any of them is `Done` with the result the model reads.\nasync function prepareCall(\n call: ToolCall,\n early: ToolResult | undefined,\n byName: ReadonlyMap<string, AnyTool>,\n ctx: PipelineContext,\n): Promise<Prepared> {\n if (early !== undefined) return { kind: \"done\", call, result: early };\n const tool = byName.get(call.name);\n if (tool === undefined) {\n const availableTools = [...byName.keys()];\n const failure: ToolFailure = {\n kind: \"unknown_tool\",\n tool: call.name,\n callId: call.callId,\n input: call.input,\n availableTools,\n };\n return { kind: \"done\", call, result: failed(failure, undefined) };\n }\n // Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.\n if (ctx.signal.aborted) return { kind: \"done\", call, result: notRun(call, tool, \"run_aborted\") };\n if (ctx.approved === true) return prepareApproved(call, tool);\n const checked = await checkInput(tool, call);\n if (!checked.ok) return { kind: \"done\", call, result: checked.result };\n if (ctx.signal.aborted) return { kind: \"done\", call, result: notRun(call, tool, \"run_aborted\") };\n // Each call's gate settles before the next call's is asked, and every gate before any call executes.\n const gated = await gateCall(call, tool, checked.input, ctx);\n if (\"blocked\" in gated) return { kind: \"done\", call, result: gated.blocked };\n if (\"paused\" in gated) return { kind: \"paused\", call, tool, request: gated.paused, input: gated.input };\n const replaced = \"replaced\" in gated;\n return { kind: \"ready\", call, tool, input: gated.input, replaced, key: resourceKeyOf(tool, gated.input) };\n}\n\n// A call whose input a verified approval signed runs with that input as it is. It is checked against the schema once\n// more, because the tool may have changed since the pause, but the checked value never replaces it.\nasync function prepareApproved(call: ToolCall, tool: AnyTool): Promise<Prepared> {\n const checked = await preparedSchemaOf(tool).validate(call.input);\n if (!checked.ok) {\n const failure: ToolFailure = {\n kind: \"invalid_input\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n issues: checked.issues,\n };\n return { kind: \"done\", call, result: failed(failure, tool) };\n }\n return { kind: \"ready\", call, tool, input: call.input, replaced: false, key: resourceKeyOf(tool, call.input) };\n}\n\n// Only a first-party tool's hint counts: an MCP server's annotations are claims by someone we don't control. A tool\n// with an `effect` changes the world whatever its hint says, so it always queues as a writer.\nfunction isTrustedReadOnly(tool: AnyTool): boolean {\n return tool.firstParty === true && tool.annotations?.readOnlyHint === true && tool.effect === undefined;\n}\n\n// Relays the run's cancellation to the signal the batch's tools receive, which a failing sibling can also fire.\nfunction batchController(runSignal: AbortSignal): { batch: AbortController; release(): void } {\n const batch = new AbortController();\n const relay = () => batch.abort(runSignal.reason);\n if (runSignal.aborted) relay();\n else runSignal.addEventListener(\"abort\", relay, { once: true });\n return { batch, release: () => runSignal.removeEventListener(\"abort\", relay) };\n}\n\n// Runs one ready call under the batch's signal. A programmer error cancels the siblings before it propagates; a\n// model-caused failure is an ordinary result and cancels nothing.\nasync function runReady(item: Ready, ctx: PipelineContext, batch: AbortController): Promise<ToolResult> {\n if (batch.signal.aborted) {\n return notRun(item.call, item.tool, ctx.signal.aborted ? \"run_aborted\" : \"sibling_failed\");\n }\n try {\n const result = await execute(item.tool, item.call, item.input, { ...ctx, signal: batch.signal });\n if (ctx.after === undefined) return result;\n return await ctx.after({ call: item.call, tool: item.tool, input: item.input, result });\n } catch (error) {\n batch.abort(error);\n throw error;\n }\n}\n\n// Starts every ready call by the scheduling rules and returns, in model order, the promise of each call's result.\nfunction start(\n prepared: readonly Prepared[],\n sequential: boolean,\n ctx: PipelineContext,\n batch: AbortController,\n): (Promise<Settled<ToolResult>> | undefined)[] {\n const ready = prepared.filter((item): item is Ready => item.kind === \"ready\");\n const scheduled = schedule(\n ready.map((item) => ({\n ...(item.key === undefined ? {} : { key: item.key }),\n readOnly: isTrustedReadOnly(item.tool),\n run: () => runReady(item, ctx, batch),\n })),\n sequential,\n );\n const byItem = new Map<Prepared, Promise<Settled<ToolResult>> | undefined>(\n ready.map((item, index) => [item, scheduled[index]]),\n );\n return prepared.map((item) => {\n if (item.kind === \"paused\") return undefined;\n if (item.kind === \"done\") return Promise.resolve<Settled<ToolResult>>({ ok: true, value: item.result });\n return byItem.get(item);\n });\n}\n\n/**\n * Runs the calls of one step. Each call is checked and gated one at a time, in model order, before any call executes.\n * The calls that passed then start together, except that a call to a sequential tool makes the whole step run one\n * call at a time, even when that call itself fails a check, and calls that share a `resourceKey` queue in model\n * order. Results reach `ctx.onResult` in model order, each as soon as every result before it is in. A call the gate\n * paused gets no result and is left out; each one reaches `ctx.onPause`, in model order, once every call is gated.\n *\n * A programmer error (an `SdkError`) in one call fires the signal the other calls hold, waits for them to stop, and\n * is then thrown, after every other call's result has been passed on: a call after the failing one may have run and\n * written. A programmer error while the calls are checked, such as a `resourceKey` that throws, is thrown after the\n * calls already checked get their results, so every call that started has one, except the call that failed.\n */\nasync function runCalls(\n calls: readonly ToolCall[],\n early: (call: ToolCall) => ToolResult | undefined,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const byName = toolsByName(tools);\n const prepared: Prepared[] = [];\n try {\n for (const call of calls) {\n ctx.onStart?.(call);\n prepared.push(await prepareCall(call, early(call), byName, ctx));\n }\n } catch (error) {\n // None of these calls has executed, and none will. The first error is the one thrown, so a receiver that throws\n // here must not hide it or stop the other calls from getting their results.\n // A paused call gets a not-run result here too: the run is failing, so its pause is never reported or returned.\n for (const item of prepared) {\n const result = item.kind === \"done\" ? item.result : notRun(item.call, item.tool, \"sibling_failed\");\n try {\n ctx.onResult?.({ call: item.call, result });\n } catch {\n // Not rethrown: the error being handled is thrown below.\n }\n }\n throw error;\n }\n // Reported only now, once every call has been gated, so a step that fails while its calls are checked never reports\n // a pause and then gives the same call a result.\n for (const item of prepared) {\n if (item.kind === \"paused\") ctx.onPause?.({ call: item.call, request: item.request, input: item.input });\n }\n const sequential = calls.some((call) => byName.get(call.name)?.executionMode === \"sequential\");\n const { batch, release } = batchController(ctx.signal);\n try {\n return await deliver(prepared, start(prepared, sequential, ctx, batch), ctx, batch);\n } finally {\n release();\n }\n}\n\n// Passes each result on in model order, as soon as every result before it is in. A failed call has already cancelled\n// the others; the loop still waits for each of them and passes its result on, so none is left running and a write\n// that happened is recorded, and then the first error is thrown. A receiver that throws is a failed call too: it\n// cancels the siblings, and the results after it are still passed on.\nasync function deliver(\n prepared: readonly Prepared[],\n running: readonly (Promise<Settled<ToolResult>> | undefined)[],\n ctx: PipelineContext,\n batch: AbortController,\n): Promise<ToolCallResult[]> {\n const results: ToolCallResult[] = [];\n let failure: { readonly error: unknown } | undefined;\n for (const [index, pending] of running.entries()) {\n if (pending === undefined) continue;\n const settled = await pending;\n if (!settled.ok) {\n failure ??= { error: settled.error };\n continue;\n }\n const item = prepared[index] as Prepared;\n const replaced = item.kind === \"ready\" && item.replaced ? { input: item.input } : {};\n const ran = item.kind === \"ready\" ? { ranWith: item.input } : {};\n const entry: ToolCallResult = { call: item.call, result: settled.value, ...replaced, ...ran };\n results.push(entry);\n try {\n ctx.onResult?.(entry);\n } catch (error) {\n failure ??= { error };\n batch.abort(error);\n }\n }\n if (failure !== undefined) throw failure.error;\n return results;\n}\n\n/**\n * Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure\n * the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws\n * an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.\n */\nexport async function runToolCall(\n call: ToolCall,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolResult> {\n const { onStart: _start, onResult: _result, onPause: _pause, ...quiet } = ctx;\n const [entry] = await runCalls([call], () => undefined, tools, quiet);\n if (entry === undefined)\n throw new SdkError(\"invalid_hook_result\", `runToolCall() can't pause the call \"${call.name}\"`);\n return entry.result;\n}\n\n/**\n * Runs every tool call of an assistant message and passes each result to `ctx.onResult` in model order. A message\n * that stopped at the output limit (`stopReason: \"length\"`) runs nothing: each of its calls gets an error asking the\n * model to re-issue it, because its arguments may be cut short. A message that ended in an error or was aborted also\n * runs nothing, because its calls may be partial. Otherwise the calls are scheduled as `runCalls` describes.\n */\nexport async function runToolCalls(\n message: AssistantMessage,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const calls = message.content.filter((block): block is ToolCall => block.type === \"tool_call\");\n return runCalls(calls, (call) => unrunnable(message, call, tools), tools, ctx);\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The step scheduler: decides when each tool call of one step starts (agent-SDK guide §4). It knows nothing about
|
|
3
|
+
* tools, only about tasks that may share a resource, so the rules can be tested without a model.
|
|
4
|
+
*
|
|
5
|
+
* - By default every task starts at once, in model order.
|
|
6
|
+
* - In a sequential batch, each task starts only after the one before it has settled.
|
|
7
|
+
* - Tasks with the same `key` never overlap and start in model order. A read-only task shares its key with other
|
|
8
|
+
* read-only tasks (a readers-writer lock), and waits only for the writers before it.
|
|
9
|
+
*
|
|
10
|
+
* The queues are built while the tasks are handed in, in model order, so the order never depends on how fast a task
|
|
11
|
+
* runs. No timers are used: a task waits on the promises of the tasks ahead of it.
|
|
12
|
+
*/
|
|
13
|
+
/** One unit of work for the scheduler. */
|
|
14
|
+
export interface Task<T> {
|
|
15
|
+
/** Tasks with the same key never overlap. A task without one is not queued behind anything. */
|
|
16
|
+
readonly key?: string;
|
|
17
|
+
/** A read-only task may overlap other read-only tasks with its key; any other task waits for all before it. */
|
|
18
|
+
readonly readOnly: boolean;
|
|
19
|
+
run(): Promise<T>;
|
|
20
|
+
}
|
|
21
|
+
/** How a task ended: the scheduler catches each task's error so that no rejection goes unobserved. */
|
|
22
|
+
export type Settled<T> = {
|
|
23
|
+
readonly ok: true;
|
|
24
|
+
readonly value: T;
|
|
25
|
+
} | {
|
|
26
|
+
readonly ok: false;
|
|
27
|
+
readonly error: unknown;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Starts `tasks` by the rules above and returns one promise per task, in the same order. A task's own rejection
|
|
31
|
+
* becomes a `Settled` value, so the promises never reject. With `sequential`, keys are moot: one task runs at a time.
|
|
32
|
+
*/
|
|
33
|
+
export declare function schedule<T>(tasks: readonly Task<T>[], sequential: boolean): Promise<Settled<T>>[];
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The step scheduler: decides when each tool call of one step starts (agent-SDK guide §4). It knows nothing about
|
|
3
|
+
* tools, only about tasks that may share a resource, so the rules can be tested without a model.
|
|
4
|
+
*
|
|
5
|
+
* - By default every task starts at once, in model order.
|
|
6
|
+
* - In a sequential batch, each task starts only after the one before it has settled.
|
|
7
|
+
* - Tasks with the same `key` never overlap and start in model order. A read-only task shares its key with other
|
|
8
|
+
* read-only tasks (a readers-writer lock), and waits only for the writers before it.
|
|
9
|
+
*
|
|
10
|
+
* The queues are built while the tasks are handed in, in model order, so the order never depends on how fast a task
|
|
11
|
+
* runs. No timers are used: a task waits on the promises of the tasks ahead of it.
|
|
12
|
+
*/
|
|
13
|
+
async function settle(task) {
|
|
14
|
+
try {
|
|
15
|
+
return { ok: true, value: await task.run() };
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
return { ok: false, error };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function inLane(lanes, key, task) {
|
|
22
|
+
const lane = lanes.get(key) ?? { writer: Promise.resolve(), readers: [] };
|
|
23
|
+
lanes.set(key, lane);
|
|
24
|
+
const ahead = task.readOnly ? [lane.writer] : [lane.writer, ...lane.readers];
|
|
25
|
+
const settled = Promise.all(ahead).then(() => settle(task));
|
|
26
|
+
if (task.readOnly) {
|
|
27
|
+
lane.readers.push(settled);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
lane.writer = settled;
|
|
31
|
+
lane.readers = [];
|
|
32
|
+
}
|
|
33
|
+
return settled;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Starts `tasks` by the rules above and returns one promise per task, in the same order. A task's own rejection
|
|
37
|
+
* becomes a `Settled` value, so the promises never reject. With `sequential`, keys are moot: one task runs at a time.
|
|
38
|
+
*/
|
|
39
|
+
export function schedule(tasks, sequential) {
|
|
40
|
+
const lanes = new Map();
|
|
41
|
+
let previous = Promise.resolve();
|
|
42
|
+
return tasks.map((task) => {
|
|
43
|
+
if (sequential) {
|
|
44
|
+
const settled = previous.then(() => settle(task));
|
|
45
|
+
previous = settled;
|
|
46
|
+
return settled;
|
|
47
|
+
}
|
|
48
|
+
return task.key === undefined ? settle(task) : inLane(lanes, task.key, task);
|
|
49
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,EAAE,CAAC;IACpB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,QAAQ,CAAI,KAAyB,EAAE,UAAmB;IACxE,MAAM,KAAK,GAAG,IAAI,GAAG,EAAgB,CAAC;IACtC,IAAI,QAAQ,GAAqB,OAAO,CAAC,OAAO,EAAE,CAAC;IACnD,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QACxB,IAAI,UAAU,EAAE,CAAC;YACf,MAAM,OAAO,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;YAClD,QAAQ,GAAG,OAAO,CAAC;YACnB,OAAO,OAAO,CAAC;QACjB,CAAC;QACD,OAAO,IAAI,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC/E,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * The step scheduler: decides when each tool call of one step starts (agent-SDK guide §4). It knows nothing about\n * tools, only about tasks that may share a resource, so the rules can be tested without a model.\n *\n * - By default every task starts at once, in model order.\n * - In a sequential batch, each task starts only after the one before it has settled.\n * - Tasks with the same `key` never overlap and start in model order. A read-only task shares its key with other\n * read-only tasks (a readers-writer lock), and waits only for the writers before it.\n *\n * The queues are built while the tasks are handed in, in model order, so the order never depends on how fast a task\n * runs. No timers are used: a task waits on the promises of the tasks ahead of it.\n */\n\n/** One unit of work for the scheduler. */\nexport interface Task<T> {\n /** Tasks with the same key never overlap. A task without one is not queued behind anything. */\n readonly key?: string;\n /** A read-only task may overlap other read-only tasks with its key; any other task waits for all before it. */\n readonly readOnly: boolean;\n run(): Promise<T>;\n}\n\n/** How a task ended: the scheduler catches each task's error so that no rejection goes unobserved. */\nexport type Settled<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: unknown };\n\nasync function settle<T>(task: Task<T>): Promise<Settled<T>> {\n try {\n return { ok: true, value: await task.run() };\n } catch (error) {\n return { ok: false, error };\n }\n}\n\n// The tasks that currently hold or wait for one key: the last writer, and the readers queued since it.\ninterface Lane {\n writer: Promise<unknown>;\n readers: Promise<unknown>[];\n}\n\nfunction inLane<T>(lanes: Map<string, Lane>, key: string, task: Task<T>): Promise<Settled<T>> {\n const lane = lanes.get(key) ?? { writer: Promise.resolve(), readers: [] };\n lanes.set(key, lane);\n const ahead = task.readOnly ? [lane.writer] : [lane.writer, ...lane.readers];\n const settled = Promise.all(ahead).then(() => settle(task));\n if (task.readOnly) {\n lane.readers.push(settled);\n } else {\n lane.writer = settled;\n lane.readers = [];\n }\n return settled;\n}\n\n/**\n * Starts `tasks` by the rules above and returns one promise per task, in the same order. A task's own rejection\n * becomes a `Settled` value, so the promises never reject. With `sequential`, keys are moot: one task runs at a time.\n */\nexport function schedule<T>(tasks: readonly Task<T>[], sequential: boolean): Promise<Settled<T>>[] {\n const lanes = new Map<string, Lane>();\n let previous: Promise<unknown> = Promise.resolve();\n return tasks.map((task) => {\n if (sequential) {\n const settled = previous.then(() => settle(task));\n previous = settled;\n return settled;\n }\n return task.key === undefined ? settle(task) : inLane(lanes, task.key, task);\n });\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { JsonSchema, SchemaIssue, ToolSchema } from "./types.js";
|
|
2
|
+
/** The outcome of validating one input: the value `execute` receives, or the issues. */
|
|
3
|
+
export type Validation = {
|
|
4
|
+
readonly ok: true;
|
|
5
|
+
readonly value: unknown;
|
|
6
|
+
} | {
|
|
7
|
+
readonly ok: false;
|
|
8
|
+
readonly issues: readonly SchemaIssue[];
|
|
9
|
+
};
|
|
10
|
+
/** A tool's schema, ready for the pipeline. */
|
|
11
|
+
export interface PreparedSchema {
|
|
12
|
+
/** The JSON Schema the model is sent, and the one coercion reads. */
|
|
13
|
+
readonly jsonSchema: JsonSchema;
|
|
14
|
+
validate(value: unknown): Promise<Validation>;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Prepares a tool's input schema. Throws an `SdkError`, code `invalid_tool_definition`, when a raw schema does not
|
|
18
|
+
* compile or names a draft other than 2020-12 or 7, or when a Standard Schema cannot produce JSON Schema.
|
|
19
|
+
*/
|
|
20
|
+
export declare function prepareSchema(tool: string, schema: ToolSchema<unknown>): PreparedSchema;
|