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

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.
@@ -26,7 +26,8 @@ function isModelContent(block) {
26
26
  return typeof text === "string";
27
27
  return type === "image" && typeof mediaType === "string" && typeof data === "string";
28
28
  }
29
- function isContentList(content) {
29
+ /** True for a list of text and image blocks, the only content a tool result may carry. */
30
+ export function isContentList(content) {
30
31
  return Array.isArray(content) && content.every(isModelContent);
31
32
  }
32
33
  // A formatter that throws, or returns something the model can't read, must not hide the failure from the model, so
@@ -157,6 +158,21 @@ function resourceKeyOf(tool, input) {
157
158
  }
158
159
  return key;
159
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)
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
+ }
160
176
  // Everything that happens before execution, for one call: name, cancellation, input checks, resource key, and the
161
177
  // gate. A call that fails any of them is `Done` with the result the model reads.
162
178
  async function prepareCall(call, early, byName, ctx) {
@@ -182,12 +198,12 @@ async function prepareCall(call, early, byName, ctx) {
182
198
  return { kind: "done", call, result: checked.result };
183
199
  if (ctx.signal.aborted)
184
200
  return { kind: "done", call, result: notRun(call, tool, "run_aborted") };
185
- const key = resourceKeyOf(tool, checked.input);
186
201
  // 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 };
202
+ const gated = await gateCall(call, tool, checked.input, ctx);
203
+ if ("blocked" in gated)
204
+ return { kind: "done", call, result: gated.blocked };
205
+ const replaced = "replaced" in gated;
206
+ return { kind: "ready", call, tool, input: gated.input, replaced, key: resourceKeyOf(tool, gated.input) };
191
207
  }
192
208
  // Only a first-party tool's hint counts: an MCP server's annotations are claims by someone we don't control. A tool
193
209
  // with an `effect` changes the world whatever its hint says, so it always queues as a writer.
@@ -211,7 +227,10 @@ async function runReady(item, ctx, batch) {
211
227
  return notRun(item.call, item.tool, ctx.signal.aborted ? "run_aborted" : "sibling_failed");
212
228
  }
213
229
  try {
214
- return await execute(item.tool, item.call, item.input, { ...ctx, signal: batch.signal });
230
+ const result = await execute(item.tool, item.call, item.input, { ...ctx, signal: batch.signal });
231
+ if (ctx.after === undefined)
232
+ return result;
233
+ return await ctx.after({ call: item.call, tool: item.tool, input: item.input, result });
215
234
  }
216
235
  catch (error) {
217
236
  batch.abort(error);
@@ -251,17 +270,23 @@ async function runCalls(calls, early, tools, ctx) {
251
270
  }
252
271
  }
253
272
  catch (error) {
254
- // None of these calls has executed, and none will.
273
+ // None of these calls has executed, and none will. The first error is the one thrown, so a receiver that throws
274
+ // here must not hide it or stop the other calls from getting their results.
255
275
  for (const item of prepared) {
256
276
  const result = item.kind === "done" ? item.result : notRun(item.call, item.tool, "sibling_failed");
257
- ctx.onResult?.({ call: item.call, result });
277
+ try {
278
+ ctx.onResult?.({ call: item.call, result });
279
+ }
280
+ catch {
281
+ // Not rethrown: the error being handled is thrown below.
282
+ }
258
283
  }
259
284
  throw error;
260
285
  }
261
286
  const sequential = calls.some((call) => byName.get(call.name)?.executionMode === "sequential");
262
287
  const { batch, release } = batchController(ctx.signal);
263
288
  try {
264
- return await deliver(prepared, start(prepared, sequential, ctx, batch), ctx);
289
+ return await deliver(prepared, start(prepared, sequential, ctx, batch), ctx, batch);
265
290
  }
266
291
  finally {
267
292
  release();
@@ -269,8 +294,9 @@ async function runCalls(calls, early, tools, ctx) {
269
294
  }
270
295
  // Passes each result on in model order, as soon as every result before it is in. A failed call has already cancelled
271
296
  // 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) {
297
+ // that happened is recorded, and then the first error is thrown. A receiver that throws is a failed call too: it
298
+ // cancels the siblings, and the results after it are still passed on.
299
+ async function deliver(prepared, running, ctx, batch) {
274
300
  const results = [];
275
301
  let failure;
276
302
  for (const [index, pending] of running.entries()) {
@@ -279,9 +305,17 @@ async function deliver(prepared, running, ctx) {
279
305
  failure ??= { error: settled.error };
280
306
  continue;
281
307
  }
282
- const entry = { call: prepared[index].call, result: settled.value };
308
+ const item = prepared[index];
309
+ const replaced = item.kind === "ready" && item.replaced ? { input: item.input } : {};
310
+ const entry = { call: item.call, result: settled.value, ...replaced };
283
311
  results.push(entry);
284
- ctx.onResult?.(entry);
312
+ try {
313
+ ctx.onResult?.(entry);
314
+ }
315
+ catch (error) {
316
+ failure ??= { error };
317
+ batch.abort(error);
318
+ }
285
319
  }
286
320
  if (failure !== undefined)
287
321
  throw failure.error;
@@ -1 +1 @@
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,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AAO,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,KAAK,EAAE,GAAG,GAAG,CAAC;IAC7D,MAAM,CAAC,KAAK,CAAC,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"]}
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;AA8DxD,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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,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,KAAK,EAAE,KAAK,EAAE,CAAC;YACtB,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC;IACH,CAAC;IACD,IAAI,OAAO,KAAK,SAAS;QAAE,MAAM,OAAO,CAAC,KAAK,CAAC;IAC/C,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,IAAc,EACd,KAAyB,EACzB,GAAoB;IAEpB,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,KAAK,EAAE,GAAG,GAAG,CAAC;IAC7D,MAAM,CAAC,KAAK,CAAC,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 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 { 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, `{ input }` to run it with\n * another input, which must pass the tool's schema, or `undefined` to let it run as it is. Without a gate every call\n * 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 * 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/** What a gate decides besides letting a call run unchanged. */\nexport type GateOutcome = { readonly blocked: ToolResult } | { readonly input: unknown };\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}\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\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// 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<{ readonly blocked: ToolResult } | { readonly input: unknown; readonly replaced?: true }> {\n const outcome = await ctx.gate?.({ call, tool, input });\n if (outcome === undefined) return { input };\n if (\"blocked\" 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 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 const replaced = \"replaced\" in gated;\n return { kind: \"ready\", call, tool, input: gated.input, replaced, key: resourceKeyOf(tool, gated.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>>[] {\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. 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 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 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>>[],\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 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 entry: ToolCallResult = { call: item.call, result: settled.value, ...replaced };\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, ...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"]}
@@ -134,8 +134,8 @@ export interface ToolDefinition<I = unknown, S = unknown> {
134
134
  readonly inputSchema: ToolSchema<I>;
135
135
  /**
136
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.
137
+ * `hidden` tool is left out of every request unless a `beforeModelCall` interceptor names it in `activeTools`, and
138
+ * a call the model makes to a tool that request didn't send gets the unknown-tool error result.
139
139
  */
140
140
  readonly exposure?: ToolExposure;
141
141
  /** Marks a tool that changes the world. A tool without it counts as read-only. */
@@ -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`), 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"]}
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 unless a `beforeModelCall` interceptor names it in `activeTools`, and\n * a call the model makes to a tool that request didn't send gets the unknown-tool error 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@buildanagent/sdk",
3
- "version": "0.1.0-alpha.4",
3
+ "version": "0.1.0-alpha.5",
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.4"
40
+ "@buildanagent/gateway": "0.1.0-alpha.5"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@cfworker/json-schema": "4.1.6",