@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/README.md +90 -8
- package/dist/errors.d.ts +27 -6
- package/dist/errors.js +30 -8
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +104 -0
- package/dist/events.js +27 -0
- package/dist/events.js.map +1 -0
- package/dist/index.d.ts +8 -4
- package/dist/index.js +6 -3
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +38 -0
- package/dist/loop.js +232 -0
- package/dist/loop.js.map +1 -0
- package/dist/result.d.ts +77 -0
- package/dist/result.js +2 -0
- package/dist/result.js.map +1 -0
- package/dist/run.d.ts +78 -0
- package/dist/run.js +165 -0
- package/dist/run.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/define.d.ts +14 -4
- package/dist/tools/define.js +24 -4
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/format-error.js +1 -0
- package/dist/tools/format-error.js.map +1 -1
- package/dist/tools/pipeline.d.ts +18 -5
- package/dist/tools/pipeline.js +160 -34
- package/dist/tools/pipeline.js.map +1 -1
- 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/types.d.ts +47 -3
- package/dist/tools/types.js.map +1 -1
- package/dist/version.d.ts +2 -0
- package/dist/version.js +8 -0
- package/dist/version.js.map +1 -0
- package/package.json +2 -2
package/dist/tools/pipeline.js
CHANGED
|
@@ -3,6 +3,7 @@ import { coerceValue } from "./coerce.js";
|
|
|
3
3
|
import { preparedSchemaOf } from "./define.js";
|
|
4
4
|
import { formatToolError, REDACTED_MESSAGE } from "./format-error.js";
|
|
5
5
|
import { withOutcome } from "./outcome.js";
|
|
6
|
+
import { schedule } from "./scheduler.js";
|
|
6
7
|
function toolsByName(tools) {
|
|
7
8
|
const byName = new Map();
|
|
8
9
|
for (const tool of tools) {
|
|
@@ -122,31 +123,6 @@ async function execute(tool, call, input, ctx) {
|
|
|
122
123
|
ctx.onExecuted?.(call);
|
|
123
124
|
return withOutcome(tool.name, checkResult(tool.name, result));
|
|
124
125
|
}
|
|
125
|
-
/**
|
|
126
|
-
* Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure
|
|
127
|
-
* the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws
|
|
128
|
-
* an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.
|
|
129
|
-
*/
|
|
130
|
-
export async function runToolCall(call, tools, ctx) {
|
|
131
|
-
const byName = toolsByName(tools);
|
|
132
|
-
const tool = byName.get(call.name);
|
|
133
|
-
if (tool === undefined) {
|
|
134
|
-
const availableTools = [...byName.keys()];
|
|
135
|
-
return failed({ kind: "unknown_tool", tool: call.name, callId: call.callId, input: call.input, availableTools }, undefined);
|
|
136
|
-
}
|
|
137
|
-
// Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.
|
|
138
|
-
if (ctx.signal.aborted)
|
|
139
|
-
return notRun(call, tool, "run_aborted");
|
|
140
|
-
const checked = await checkInput(tool, call);
|
|
141
|
-
if (!checked.ok)
|
|
142
|
-
return checked.result;
|
|
143
|
-
if (ctx.signal.aborted)
|
|
144
|
-
return notRun(call, tool, "run_aborted");
|
|
145
|
-
// Gate: every call is allowed until the beforeToolCall interceptor exists.
|
|
146
|
-
const result = await execute(tool, call, checked.input, ctx);
|
|
147
|
-
// afterToolCall: the result passes through unchanged until that interceptor exists.
|
|
148
|
-
return result;
|
|
149
|
-
}
|
|
150
126
|
function notRun(call, tool, reason) {
|
|
151
127
|
return failed({ kind: "not_run", reason, tool: call.name, callId: call.callId, input: call.input }, tool);
|
|
152
128
|
}
|
|
@@ -164,21 +140,171 @@ function unrunnable(message, call, tools) {
|
|
|
164
140
|
return undefined;
|
|
165
141
|
}
|
|
166
142
|
}
|
|
143
|
+
function resourceKeyOf(tool, input) {
|
|
144
|
+
if (tool.resourceKey === undefined)
|
|
145
|
+
return undefined;
|
|
146
|
+
let key;
|
|
147
|
+
try {
|
|
148
|
+
key = tool.resourceKey(input);
|
|
149
|
+
}
|
|
150
|
+
catch (cause) {
|
|
151
|
+
throw new SdkError("invalid_tool_definition", `tool "${tool.name}": resourceKey threw: ${errorMessage(cause)}`, {
|
|
152
|
+
cause,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
if (typeof key !== "string") {
|
|
156
|
+
throw new SdkError("invalid_tool_definition", `tool "${tool.name}": resourceKey must return a string`);
|
|
157
|
+
}
|
|
158
|
+
return key;
|
|
159
|
+
}
|
|
160
|
+
// Everything that happens before execution, for one call: name, cancellation, input checks, resource key, and the
|
|
161
|
+
// gate. A call that fails any of them is `Done` with the result the model reads.
|
|
162
|
+
async function prepareCall(call, early, byName, ctx) {
|
|
163
|
+
if (early !== undefined)
|
|
164
|
+
return { kind: "done", call, result: early };
|
|
165
|
+
const tool = byName.get(call.name);
|
|
166
|
+
if (tool === undefined) {
|
|
167
|
+
const availableTools = [...byName.keys()];
|
|
168
|
+
const failure = {
|
|
169
|
+
kind: "unknown_tool",
|
|
170
|
+
tool: call.name,
|
|
171
|
+
callId: call.callId,
|
|
172
|
+
input: call.input,
|
|
173
|
+
availableTools,
|
|
174
|
+
};
|
|
175
|
+
return { kind: "done", call, result: failed(failure, undefined) };
|
|
176
|
+
}
|
|
177
|
+
// Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.
|
|
178
|
+
if (ctx.signal.aborted)
|
|
179
|
+
return { kind: "done", call, result: notRun(call, tool, "run_aborted") };
|
|
180
|
+
const checked = await checkInput(tool, call);
|
|
181
|
+
if (!checked.ok)
|
|
182
|
+
return { kind: "done", call, result: checked.result };
|
|
183
|
+
if (ctx.signal.aborted)
|
|
184
|
+
return { kind: "done", call, result: notRun(call, tool, "run_aborted") };
|
|
185
|
+
const key = resourceKeyOf(tool, checked.input);
|
|
186
|
+
// Each call's gate settles before the next call's is asked, and every gate before any call executes.
|
|
187
|
+
const blocked = await ctx.gate?.({ call, tool, input: checked.input });
|
|
188
|
+
if (blocked !== undefined)
|
|
189
|
+
return { kind: "done", call, result: blocked };
|
|
190
|
+
return { kind: "ready", call, tool, input: checked.input, key };
|
|
191
|
+
}
|
|
192
|
+
// Only a first-party tool's hint counts: an MCP server's annotations are claims by someone we don't control. A tool
|
|
193
|
+
// with an `effect` changes the world whatever its hint says, so it always queues as a writer.
|
|
194
|
+
function isTrustedReadOnly(tool) {
|
|
195
|
+
return tool.firstParty === true && tool.annotations?.readOnlyHint === true && tool.effect === undefined;
|
|
196
|
+
}
|
|
197
|
+
// Relays the run's cancellation to the signal the batch's tools receive, which a failing sibling can also fire.
|
|
198
|
+
function batchController(runSignal) {
|
|
199
|
+
const batch = new AbortController();
|
|
200
|
+
const relay = () => batch.abort(runSignal.reason);
|
|
201
|
+
if (runSignal.aborted)
|
|
202
|
+
relay();
|
|
203
|
+
else
|
|
204
|
+
runSignal.addEventListener("abort", relay, { once: true });
|
|
205
|
+
return { batch, release: () => runSignal.removeEventListener("abort", relay) };
|
|
206
|
+
}
|
|
207
|
+
// Runs one ready call under the batch's signal. A programmer error cancels the siblings before it propagates; a
|
|
208
|
+
// model-caused failure is an ordinary result and cancels nothing.
|
|
209
|
+
async function runReady(item, ctx, batch) {
|
|
210
|
+
if (batch.signal.aborted) {
|
|
211
|
+
return notRun(item.call, item.tool, ctx.signal.aborted ? "run_aborted" : "sibling_failed");
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
return await execute(item.tool, item.call, item.input, { ...ctx, signal: batch.signal });
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
batch.abort(error);
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
// Starts every ready call by the scheduling rules and returns, in model order, the promise of each call's result.
|
|
222
|
+
function start(prepared, sequential, ctx, batch) {
|
|
223
|
+
const ready = prepared.filter((item) => item.kind === "ready");
|
|
224
|
+
const scheduled = schedule(ready.map((item) => ({
|
|
225
|
+
...(item.key === undefined ? {} : { key: item.key }),
|
|
226
|
+
readOnly: isTrustedReadOnly(item.tool),
|
|
227
|
+
run: () => runReady(item, ctx, batch),
|
|
228
|
+
})), sequential);
|
|
229
|
+
const byItem = new Map(ready.map((item, index) => [item, scheduled[index]]));
|
|
230
|
+
return prepared.map((item) => (item.kind === "done" ? undefined : byItem.get(item)) ??
|
|
231
|
+
Promise.resolve({ ok: true, value: item.result }));
|
|
232
|
+
}
|
|
167
233
|
/**
|
|
168
|
-
* Runs
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
234
|
+
* Runs the calls of one step. Each call is checked and gated one at a time, in model order, before any call executes.
|
|
235
|
+
* The calls that passed then start together, except that a call to a sequential tool makes the whole step run one
|
|
236
|
+
* call at a time, even when that call itself fails a check, and calls that share a `resourceKey` queue in model
|
|
237
|
+
* order. Results reach `ctx.onResult` in model order, each as soon as every result before it is in.
|
|
238
|
+
*
|
|
239
|
+
* A programmer error (an `SdkError`) in one call fires the signal the other calls hold, waits for them to stop, and
|
|
240
|
+
* is then thrown, after every other call's result has been passed on: a call after the failing one may have run and
|
|
241
|
+
* written. A programmer error while the calls are checked, such as a `resourceKey` that throws, is thrown after the
|
|
242
|
+
* calls already checked get their results, so every call that started has one, except the call that failed.
|
|
172
243
|
*/
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
244
|
+
async function runCalls(calls, early, tools, ctx) {
|
|
245
|
+
const byName = toolsByName(tools);
|
|
246
|
+
const prepared = [];
|
|
247
|
+
try {
|
|
248
|
+
for (const call of calls) {
|
|
249
|
+
ctx.onStart?.(call);
|
|
250
|
+
prepared.push(await prepareCall(call, early(call), byName, ctx));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
// None of these calls has executed, and none will.
|
|
255
|
+
for (const item of prepared) {
|
|
256
|
+
const result = item.kind === "done" ? item.result : notRun(item.call, item.tool, "sibling_failed");
|
|
257
|
+
ctx.onResult?.({ call: item.call, result });
|
|
258
|
+
}
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
const sequential = calls.some((call) => byName.get(call.name)?.executionMode === "sequential");
|
|
262
|
+
const { batch, release } = batchController(ctx.signal);
|
|
263
|
+
try {
|
|
264
|
+
return await deliver(prepared, start(prepared, sequential, ctx, batch), ctx);
|
|
265
|
+
}
|
|
266
|
+
finally {
|
|
267
|
+
release();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
// Passes each result on in model order, as soon as every result before it is in. A failed call has already cancelled
|
|
271
|
+
// the others; the loop still waits for each of them and passes its result on, so none is left running and a write
|
|
272
|
+
// that happened is recorded, and then the first error is thrown.
|
|
273
|
+
async function deliver(prepared, running, ctx) {
|
|
176
274
|
const results = [];
|
|
177
|
-
|
|
178
|
-
|
|
275
|
+
let failure;
|
|
276
|
+
for (const [index, pending] of running.entries()) {
|
|
277
|
+
const settled = await pending;
|
|
278
|
+
if (!settled.ok) {
|
|
279
|
+
failure ??= { error: settled.error };
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
const entry = { call: prepared[index].call, result: settled.value };
|
|
179
283
|
results.push(entry);
|
|
180
284
|
ctx.onResult?.(entry);
|
|
181
285
|
}
|
|
286
|
+
if (failure !== undefined)
|
|
287
|
+
throw failure.error;
|
|
182
288
|
return results;
|
|
183
289
|
}
|
|
290
|
+
/**
|
|
291
|
+
* Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure
|
|
292
|
+
* the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws
|
|
293
|
+
* an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.
|
|
294
|
+
*/
|
|
295
|
+
export async function runToolCall(call, tools, ctx) {
|
|
296
|
+
const { onStart: _start, onResult: _result, ...quiet } = ctx;
|
|
297
|
+
const [entry] = await runCalls([call], () => undefined, tools, quiet);
|
|
298
|
+
return entry.result;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Runs every tool call of an assistant message and passes each result to `ctx.onResult` in model order. A message
|
|
302
|
+
* that stopped at the output limit (`stopReason: "length"`) runs nothing: each of its calls gets an error asking the
|
|
303
|
+
* model to re-issue it, because its arguments may be cut short. A message that ended in an error or was aborted also
|
|
304
|
+
* runs nothing, because its calls may be partial. Otherwise the calls are scheduled as `runCalls` describes.
|
|
305
|
+
*/
|
|
306
|
+
export async function runToolCalls(message, tools, ctx) {
|
|
307
|
+
const calls = message.content.filter((block) => block.type === "tool_call");
|
|
308
|
+
return runCalls(calls, (call) => unrunnable(message, call, tools), tools, ctx);
|
|
309
|
+
}
|
|
184
310
|
//# sourceMappingURL=pipeline.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/tools/pipeline.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAiC3C,SAAS,WAAW,CAAC,KAAyB;IAC5C,MAAM,MAAM,GAAG,IAAI,GAAG,EAAmB,CAAC;IAC1C,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,gBAAgB,CAAC,IAAI,CAAC,CAAC;QACvB,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,QAAQ,CAAC,yBAAyB,EAAE,wBAAwB,IAAI,CAAC,IAAI,8BAA8B,CAAC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,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,WAAW,CAAC,KAAK,CAAC,CAAC;IACnB,MAAM,OAAO,GAAqB,EAAE,CAAC;IACrC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,KAAK,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,MAAM,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;QAC1G,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACpB,GAAG,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,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 and `afterToolCall` steps hold their places in the order below, and the interceptors fill them in: until\n * then every call is allowed and every result passes through unchanged. Calls run one at a time, in model order.\n */\nimport type { AssistantMessage, ModelContent } from \"@buildanagent/gateway\";\nimport { SdkError } from \"../errors.js\";\nimport type { Clock } from \"../testing/determinism.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 { 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 /** 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 * 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\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}\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\nfunction 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\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 byName = toolsByName(tools);\n const tool = byName.get(call.name);\n if (tool === undefined) {\n const availableTools = [...byName.keys()];\n return failed(\n { kind: \"unknown_tool\", tool: call.name, callId: call.callId, input: call.input, availableTools },\n undefined,\n );\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 notRun(call, tool, \"run_aborted\");\n const checked = await checkInput(tool, call);\n if (!checked.ok) return checked.result;\n if (ctx.signal.aborted) return notRun(call, tool, \"run_aborted\");\n // Gate: every call is allowed until the beforeToolCall interceptor exists.\n const result = await execute(tool, call, checked.input, ctx);\n // afterToolCall: the result passes through unchanged until that interceptor exists.\n return 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/**\n * Runs every tool call of an assistant message, one at a time and in model order, and passes each result to\n * `ctx.onResult` as it arrives. A message that stopped at the output limit (`stopReason: \"length\"`) runs nothing:\n * each of its calls gets an error asking the model to re-issue it, because its arguments may be cut short. A message\n * that ended in an error or was aborted also runs nothing, because its calls may be partial.\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 toolsByName(tools);\n const results: ToolCallResult[] = [];\n for (const call of calls) {\n const entry = { call, result: unrunnable(message, call, tools) ?? (await runToolCall(call, tools, ctx)) };\n results.push(entry);\n ctx.onResult?.(entry);\n }\n return results;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/tools/pipeline.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAgB,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AA6CxD,SAAS,WAAW,CAAC,KAAyB;IAC5C,MAAM,MAAM,GAAG,IAAI,GAAG,EAAmB,CAAC;IAC1C,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,gBAAgB,CAAC,IAAI,CAAC,CAA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AAC,GAAG,MAAM,QAAQ,CAAC,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC,SAAS,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IACtE,OAAQ,KAAwB,CAAC,MAAM,CAAC;AAC1C,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 and `afterToolCall` steps hold their places in the order below, and the interceptors fill them in: until\n * then every call is allowed and every result passes through unchanged. A step's calls are checked and gated one at a\n * 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 { 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 a result to block the call, or `undefined` to let it run. 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<ToolResult | undefined>;\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 * 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\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}\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\nfunction 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 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\ntype Prepared = Ready | Done;\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// 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 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 const key = resourceKeyOf(tool, checked.input);\n // Each call's gate settles before the next call's is asked, and every gate before any call executes.\n const blocked = await ctx.gate?.({ call, tool, input: checked.input });\n if (blocked !== undefined) return { kind: \"done\", call, result: blocked };\n return { kind: \"ready\", call, tool, input: checked.input, key };\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 return await execute(item.tool, item.call, item.input, { ...ctx, signal: batch.signal });\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>>[] {\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(ready.map((item, index) => [item, scheduled[index]]));\n return prepared.map(\n (item) =>\n (item.kind === \"done\" ? undefined : byItem.get(item)) ??\n Promise.resolve<Settled<ToolResult>>({ ok: true, value: (item as Done).result }),\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.\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.\n for (const item of prepared) {\n const result = item.kind === \"done\" ? item.result : notRun(item.call, item.tool, \"sibling_failed\");\n ctx.onResult?.({ call: item.call, result });\n }\n throw error;\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);\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.\nasync function deliver(\n prepared: readonly Prepared[],\n running: readonly Promise<Settled<ToolResult>>[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const results: ToolCallResult[] = [];\n let failure: { readonly error: unknown } | undefined;\n for (const [index, pending] of running.entries()) {\n const settled = await pending;\n if (!settled.ok) {\n failure ??= { error: settled.error };\n continue;\n }\n const entry = { call: (prepared[index] as Prepared).call, result: settled.value };\n results.push(entry);\n ctx.onResult?.(entry);\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, ...quiet } = ctx;\n const [entry] = await runCalls([call], () => undefined, tools, quiet);\n return (entry as ToolCallResult).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
|
+
});
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=scheduler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduler.js","sourceRoot":"","sources":["../../src/tools/scheduler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAcH,KAAK,UAAU,MAAM,CAAI,IAAa;IACpC,IAAI,CAAC;QACH,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;IAC/C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACH,CAAC;AAQD,SAAS,MAAM,CAAI,KAAwB,EAAE,GAAW,EAAE,IAAa;IACrE,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CA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AAE,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"]}
|
package/dist/tools/types.d.ts
CHANGED
|
@@ -36,7 +36,7 @@ interface FailureBase {
|
|
|
36
36
|
* `redactErrors`, `message` is a fixed line and the thrown message is only in the result's `details`. `truncated`:
|
|
37
37
|
* the response was cut off at the output limit, so the call was not run. `not_run`: the call was not run because the
|
|
38
38
|
* response ended in an error (`response_error`) or was aborted (`response_aborted`), or the run was cancelled before
|
|
39
|
-
* the call started (`run_aborted`).
|
|
39
|
+
* the call started (`run_aborted`), or a sibling call in the same step threw a programmer error (`sibling_failed`).
|
|
40
40
|
*/
|
|
41
41
|
export type ToolFailure = (FailureBase & {
|
|
42
42
|
readonly kind: "unknown_tool";
|
|
@@ -52,7 +52,7 @@ export type ToolFailure = (FailureBase & {
|
|
|
52
52
|
readonly kind: "truncated";
|
|
53
53
|
}) | (FailureBase & {
|
|
54
54
|
readonly kind: "not_run";
|
|
55
|
-
readonly reason: "response_error" | "response_aborted" | "run_aborted";
|
|
55
|
+
readonly reason: "response_error" | "response_aborted" | "run_aborted" | "sibling_failed";
|
|
56
56
|
});
|
|
57
57
|
/**
|
|
58
58
|
* Declares that a tool changes the world, such as sending an email. A tool without `effect` counts as read-only, so
|
|
@@ -63,11 +63,29 @@ export interface ToolEffect<I> {
|
|
|
63
63
|
readonly kind: "write";
|
|
64
64
|
businessKey?(input: I): string;
|
|
65
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* What a tool says about itself, using the names of the Model Context Protocol's tool annotations. A hint comes from
|
|
68
|
+
* whoever wrote the tool, so the scheduler trusts it only for a tool marked `firstParty`.
|
|
69
|
+
*/
|
|
70
|
+
export interface ToolAnnotations {
|
|
71
|
+
/**
|
|
72
|
+
* The tool changes nothing. With `firstParty`, its calls that share a `resourceKey` run together, unless the tool
|
|
73
|
+
* also declares an `effect`, which wins.
|
|
74
|
+
*/
|
|
75
|
+
readonly readOnlyHint?: boolean;
|
|
76
|
+
}
|
|
77
|
+
/** How a tool's calls are scheduled within one step: `parallel` (the default) or `sequential`. */
|
|
78
|
+
export type ToolExecutionMode = "parallel" | "sequential";
|
|
79
|
+
/** Whether a tool is sent to the model: `direct`, `deferred` or `hidden`. */
|
|
80
|
+
export type ToolExposure = "direct" | "deferred" | "hidden";
|
|
66
81
|
/** What a tool's `execute` receives besides its input. */
|
|
67
82
|
export interface ToolContext {
|
|
68
83
|
readonly runId: string;
|
|
69
84
|
readonly callId: string;
|
|
70
|
-
/**
|
|
85
|
+
/**
|
|
86
|
+
* Fires when the run is aborted, and when a sibling call in the same step throws a programmer error, because the
|
|
87
|
+
* step is then abandoned. A sibling's error result, which the model reads and answers, never fires it.
|
|
88
|
+
*/
|
|
71
89
|
readonly signal: AbortSignal;
|
|
72
90
|
/** How deeply this run is nested inside other agents' tool calls; 0 for a top-level run. */
|
|
73
91
|
readonly depth: number;
|
|
@@ -114,8 +132,34 @@ export interface ToolDefinition<I = unknown, S = unknown> {
|
|
|
114
132
|
*/
|
|
115
133
|
readonly kind?: "function" | "dynamic" | "provider-local" | "provider-executed";
|
|
116
134
|
readonly inputSchema: ToolSchema<I>;
|
|
135
|
+
/**
|
|
136
|
+
* Whether the model is sent this tool. `direct` (the default) sends it with every model call. A `deferred` or
|
|
137
|
+
* `hidden` tool is left out of every request, and a call the model makes to it anyway gets the unknown-tool error
|
|
138
|
+
* result.
|
|
139
|
+
*/
|
|
140
|
+
readonly exposure?: ToolExposure;
|
|
117
141
|
/** Marks a tool that changes the world. A tool without it counts as read-only. */
|
|
118
142
|
readonly effect?: ToolEffect<I>;
|
|
143
|
+
/**
|
|
144
|
+
* How this tool's calls are scheduled. A step's calls start together by default. A tool that sets `sequential`
|
|
145
|
+
* makes every call of its step run one at a time, in the order the model sent them, because it may depend on the
|
|
146
|
+
* calls around it.
|
|
147
|
+
*/
|
|
148
|
+
readonly executionMode?: ToolExecutionMode;
|
|
149
|
+
/**
|
|
150
|
+
* Names the resource a call touches, such as a file path. Calls in one step that return the same key never run at
|
|
151
|
+
* the same time, in any tool, and run in model order; calls with different keys run together. It must be
|
|
152
|
+
* deterministic and return a string, and it receives the validated input.
|
|
153
|
+
*/
|
|
154
|
+
resourceKey?(input: I): string;
|
|
155
|
+
/** Hints about the tool, such as `readOnlyHint`. They affect scheduling only when `firstParty` is true. */
|
|
156
|
+
readonly annotations?: ToolAnnotations;
|
|
157
|
+
/**
|
|
158
|
+
* True for a tool you wrote, false (the default) for one that came from a server you don't control, such as an MCP
|
|
159
|
+
* tool. Only a first-party tool's `readOnlyHint` changes how its calls are scheduled: read-only calls that share a
|
|
160
|
+
* `resourceKey` run together, and wait only for the writers before them. A tool with an `effect` is never read-only.
|
|
161
|
+
*/
|
|
162
|
+
readonly firstParty?: boolean;
|
|
119
163
|
/**
|
|
120
164
|
* Called once when the input fails its schema, with the coerced input and the issues. Return fixed input to
|
|
121
165
|
* validate again, or `undefined` to report the failure to the model.
|
package/dist/tools/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/tools/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The tool types: what a tool declares, what its `execute` receives and returns, and the failures the pipeline\n * reports to the model (SDK plan §3.3; agent-SDK guide §4).\n */\nimport type { ContentBlock, ModelContent } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport type { WriteOutcome } from \"../vendor/agent-safety/outcome.js\";\n\n/** A JSON Schema object, draft 2020-12 or draft 7, such as `{ type: \"object\", properties: { … } }`. */\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\n/**\n * A tool's input schema: a Standard Schema that can also describe itself as JSON Schema (Zod 4.2 or later, ArkType,\n * or Valibot through `toStandardJsonSchema()` from `@valibot/to-json-schema`), or a raw JSON Schema object. A raw schema whose `$schema` names draft 7 is checked as draft 7, and\n * any other as draft 2020-12.\n */\nexport type ToolSchema<I> = (StandardSchemaV1<unknown, I> & StandardJSONSchemaV1<unknown, I>) | JsonSchema;\n\n/**\n * One reason a tool input failed its schema. `path` is a JSON Pointer, such as `/items/0/sku`, or `\"\"` for the whole\n * input.\n */\nexport interface SchemaIssue {\n readonly path: string;\n readonly message: string;\n /** The JSON Schema keyword that failed, such as `required`, when the validator reports one. */\n readonly keyword?: string;\n}\n\n/** The fields every tool failure carries. `input` is the arguments the model sent. */\ninterface FailureBase {\n readonly tool: string;\n readonly callId: string;\n readonly input: unknown;\n}\n\n/**\n * A failed tool call, as the error formatter receives it. `unknown_tool`: the model named a tool that doesn't exist.\n * `invalid_input`: the arguments failed the schema, even after repair. `execution_error`: `execute` threw; with\n * `redactErrors`, `message` is a fixed line and the thrown message is only in the result's `details`. `truncated`:\n * the response was cut off at the output limit, so the call was not run. `not_run`: the call was not run because the\n * response ended in an error (`response_error`) or was aborted (`response_aborted`), or the run was cancelled before\n * the call started (`run_aborted`).\n */\nexport type ToolFailure =\n | (FailureBase & { readonly kind: \"unknown_tool\"; readonly availableTools: readonly string[] })\n | (FailureBase & { readonly kind: \"invalid_input\"; readonly issues: readonly SchemaIssue[] })\n | (FailureBase & { readonly kind: \"execution_error\"; readonly message: string; readonly redacted: boolean })\n | (FailureBase & { readonly kind: \"truncated\" })\n | (FailureBase & {\n readonly kind: \"not_run\";\n readonly reason: \"response_error\" | \"response_aborted\" | \"run_aborted\";\n });\n\n/**\n * Declares that a tool changes the world, such as sending an email. A tool without `effect` counts as read-only, so\n * a run that crashes mid-call may safely run it again. `businessKey` names the real-world operation, such as\n * `refund:<order id>`, so the same write is recognised across retries and sessions.\n */\nexport interface ToolEffect<I> {\n readonly kind: \"write\";\n businessKey?(input: I): string;\n}\n\n/** What a tool's `execute` receives besides its input. */\nexport interface ToolContext {\n readonly runId: string;\n readonly callId: string;\n
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/tools/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The tool types: what a tool declares, what its `execute` receives and returns, and the failures the pipeline\n * reports to the model (SDK plan §3.3; agent-SDK guide §4).\n */\nimport type { ContentBlock, ModelContent } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport type { WriteOutcome } from \"../vendor/agent-safety/outcome.js\";\n\n/** A JSON Schema object, draft 2020-12 or draft 7, such as `{ type: \"object\", properties: { … } }`. */\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\n/**\n * A tool's input schema: a Standard Schema that can also describe itself as JSON Schema (Zod 4.2 or later, ArkType,\n * or Valibot through `toStandardJsonSchema()` from `@valibot/to-json-schema`), or a raw JSON Schema object. A raw schema whose `$schema` names draft 7 is checked as draft 7, and\n * any other as draft 2020-12.\n */\nexport type ToolSchema<I> = (StandardSchemaV1<unknown, I> & StandardJSONSchemaV1<unknown, I>) | JsonSchema;\n\n/**\n * One reason a tool input failed its schema. `path` is a JSON Pointer, such as `/items/0/sku`, or `\"\"` for the whole\n * input.\n */\nexport interface SchemaIssue {\n readonly path: string;\n readonly message: string;\n /** The JSON Schema keyword that failed, such as `required`, when the validator reports one. */\n readonly keyword?: string;\n}\n\n/** The fields every tool failure carries. `input` is the arguments the model sent. */\ninterface FailureBase {\n readonly tool: string;\n readonly callId: string;\n readonly input: unknown;\n}\n\n/**\n * A failed tool call, as the error formatter receives it. `unknown_tool`: the model named a tool that doesn't exist.\n * `invalid_input`: the arguments failed the schema, even after repair. `execution_error`: `execute` threw; with\n * `redactErrors`, `message` is a fixed line and the thrown message is only in the result's `details`. `truncated`:\n * the response was cut off at the output limit, so the call was not run. `not_run`: the call was not run because the\n * response ended in an error (`response_error`) or was aborted (`response_aborted`), or the run was cancelled before\n * the call started (`run_aborted`), or a sibling call in the same step threw a programmer error (`sibling_failed`).\n */\nexport type ToolFailure =\n | (FailureBase & { readonly kind: \"unknown_tool\"; readonly availableTools: readonly string[] })\n | (FailureBase & { readonly kind: \"invalid_input\"; readonly issues: readonly SchemaIssue[] })\n | (FailureBase & { readonly kind: \"execution_error\"; readonly message: string; readonly redacted: boolean })\n | (FailureBase & { readonly kind: \"truncated\" })\n | (FailureBase & {\n readonly kind: \"not_run\";\n readonly reason: \"response_error\" | \"response_aborted\" | \"run_aborted\" | \"sibling_failed\";\n });\n\n/**\n * Declares that a tool changes the world, such as sending an email. A tool without `effect` counts as read-only, so\n * a run that crashes mid-call may safely run it again. `businessKey` names the real-world operation, such as\n * `refund:<order id>`, so the same write is recognised across retries and sessions.\n */\nexport interface ToolEffect<I> {\n readonly kind: \"write\";\n businessKey?(input: I): string;\n}\n\n/**\n * What a tool says about itself, using the names of the Model Context Protocol's tool annotations. A hint comes from\n * whoever wrote the tool, so the scheduler trusts it only for a tool marked `firstParty`.\n */\nexport interface ToolAnnotations {\n /**\n * The tool changes nothing. With `firstParty`, its calls that share a `resourceKey` run together, unless the tool\n * also declares an `effect`, which wins.\n */\n readonly readOnlyHint?: boolean;\n}\n\n/** How a tool's calls are scheduled within one step: `parallel` (the default) or `sequential`. */\nexport type ToolExecutionMode = \"parallel\" | \"sequential\";\n\n/** Whether a tool is sent to the model: `direct`, `deferred` or `hidden`. */\nexport type ToolExposure = \"direct\" | \"deferred\" | \"hidden\";\n\n/** What a tool's `execute` receives besides its input. */\nexport interface ToolContext {\n readonly runId: string;\n readonly callId: string;\n /**\n * Fires when the run is aborted, and when a sibling call in the same step throws a programmer error, because the\n * step is then abandoned. A sibling's error result, which the model reads and answers, never fires it.\n */\n readonly signal: AbortSignal;\n /** How deeply this run is nested inside other agents' tool calls; 0 for a top-level run. */\n readonly depth: number;\n /** The deepest nesting allowed; a tool that starts another agent refuses at this depth. */\n readonly maxDepth: number;\n readonly clock: Clock;\n /** Reports progress for a user interface, such as rows processed so far. The model never sees it. */\n update(details: unknown): void;\n}\n\n/**\n * What a tool returns. `content` is what the model reads, `details` is for logs and user interfaces, and\n * `structured` is typed data for your code; only `content` reaches the model. `isError` marks a failure for the model.\n * `terminate` asks the run to end after this step. `pause` asks the user a question. `outcome` reports what a write\n * did: any kind except `applied` sets `isError`, and the model reads the outcome's sentence and fields before\n * `content`.\n */\nexport interface ToolResult<S = unknown> {\n readonly content: readonly ModelContent[];\n readonly details?: unknown;\n readonly structured?: S;\n readonly isError?: boolean;\n readonly terminate?: boolean;\n readonly pause?: { readonly kind: \"clarification\"; readonly question: string };\n readonly outcome?: WriteOutcome;\n}\n\n/**\n * A tool the model can call. `I` is the input `execute` receives after validation, and `S` the type of `structured`.\n *\n * Every call runs the same steps: the name is resolved, the input is coerced and validated, `repair` gets one chance\n * to fix invalid input, then `execute` runs. A failure the model caused, such as an unknown tool, invalid input or\n * a throwing `execute`, returns an error result to the model. A result that isn't a list of text and image blocks,\n * or that carries an invalid write outcome, throws an `SdkError` with code `invalid_tool_result`.\n */\nexport interface ToolDefinition<I = unknown, S = unknown> {\n /** 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`. */\n readonly name: string;\n readonly description: string;\n /**\n * `function` (the default) runs in your process. The other kinds are for tools that a provider defines or runs:\n * `dynamic` tools have a schema known only at run time, such as one from an MCP server.\n */\n readonly kind?: \"function\" | \"dynamic\" | \"provider-local\" | \"provider-executed\";\n readonly inputSchema: ToolSchema<I>;\n /**\n * Whether the model is sent this tool. `direct` (the default) sends it with every model call. A `deferred` or\n * `hidden` tool is left out of every request, and a call the model makes to it anyway gets the unknown-tool error\n * result.\n */\n readonly exposure?: ToolExposure;\n /** Marks a tool that changes the world. A tool without it counts as read-only. */\n readonly effect?: ToolEffect<I>;\n /**\n * How this tool's calls are scheduled. A step's calls start together by default. A tool that sets `sequential`\n * makes every call of its step run one at a time, in the order the model sent them, because it may depend on the\n * calls around it.\n */\n readonly executionMode?: ToolExecutionMode;\n /**\n * Names the resource a call touches, such as a file path. Calls in one step that return the same key never run at\n * the same time, in any tool, and run in model order; calls with different keys run together. It must be\n * deterministic and return a string, and it receives the validated input.\n */\n resourceKey?(input: I): string;\n /** Hints about the tool, such as `readOnlyHint`. They affect scheduling only when `firstParty` is true. */\n readonly annotations?: ToolAnnotations;\n /**\n * True for a tool you wrote, false (the default) for one that came from a server you don't control, such as an MCP\n * tool. Only a first-party tool's `readOnlyHint` changes how its calls are scheduled: read-only calls that share a\n * `resourceKey` run together, and wait only for the writers before them. A tool with an `effect` is never read-only.\n */\n readonly firstParty?: boolean;\n /**\n * Called once when the input fails its schema, with the coerced input and the issues. Return fixed input to\n * validate again, or `undefined` to report the failure to the model.\n */\n repair?(e: { readonly input: unknown; readonly issues: readonly SchemaIssue[] }): Promise<unknown>;\n /**\n * Builds the content the model reads for a failed call, in place of the default text, which lists the issues and\n * the received arguments and tells the model not to substitute invented data. It runs synchronously; if it throws\n * or returns anything but a list of text and image blocks, the model reads the default text instead.\n */\n formatError?(failure: ToolFailure): readonly ModelContent[];\n /**\n * When true, an error thrown by `execute` reaches the model as a fixed line, and its message goes only to the\n * result's `details`. Default false.\n */\n readonly redactErrors?: boolean;\n execute(input: I, ctx: ToolContext): Promise<ToolResult<S>>;\n}\n\n/** A tool call block from an assistant message. */\nexport type ToolCall = Extract<ContentBlock, { type: \"tool_call\" }>;\n"]}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SDK's own version, read from its package.json so it can't drift from the published version. `run_start`
|
|
3
|
+
* carries it, so a stored session records which SDK wrote it.
|
|
4
|
+
*/
|
|
5
|
+
import packageJson from "../package.json" with { type: "json" };
|
|
6
|
+
/** The version of `@buildanagent/sdk` in use, such as `0.1.0-alpha.1`. */
|
|
7
|
+
export const SDK_VERSION = packageJson.version;
|
|
8
|
+
//# sourceMappingURL=version.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,WAAW,MAAM,iBAAiB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAC;AAEhE,0EAA0E;AAC1E,MAAM,CAAC,MAAM,WAAW,GAAW,WAAW,CAAC,OAAO,CAAC","sourcesContent":["/**\n * The SDK's own version, read from its package.json so it can't drift from the published version. `run_start`\n * carries it, so a stored session records which SDK wrote it.\n */\nimport packageJson from \"../package.json\" with { type: \"json\" };\n\n/** The version of `@buildanagent/sdk` in use, such as `0.1.0-alpha.1`. */\nexport const SDK_VERSION: string = packageJson.version;\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@buildanagent/sdk",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.4",
|
|
4
4
|
"description": "The buildanagent SDK: the agent loop, tools, hooks, signed pauses and budgets over the gateway.",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"repository": {
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@earendil-works/pi-schema": "1.5.2",
|
|
39
39
|
"@standard-schema/spec": "1.1.0",
|
|
40
|
-
"@buildanagent/gateway": "0.1.0-alpha.
|
|
40
|
+
"@buildanagent/gateway": "0.1.0-alpha.4"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@cfworker/json-schema": "4.1.6",
|