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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +88 -2
  2. package/dist/errors.d.ts +19 -0
  3. package/dist/errors.js +26 -0
  4. package/dist/errors.js.map +1 -0
  5. package/dist/index.d.ts +7 -3
  6. package/dist/index.js +5 -3
  7. package/dist/index.js.map +1 -1
  8. package/dist/tools/coerce.d.ts +15 -0
  9. package/dist/tools/coerce.js +93 -0
  10. package/dist/tools/coerce.js.map +1 -0
  11. package/dist/tools/define.d.ts +42 -0
  12. package/dist/tools/define.js +96 -0
  13. package/dist/tools/define.js.map +1 -0
  14. package/dist/tools/format-error.d.ts +13 -0
  15. package/dist/tools/format-error.js +65 -0
  16. package/dist/tools/format-error.js.map +1 -0
  17. package/dist/tools/outcome.d.ts +7 -0
  18. package/dist/tools/outcome.js +30 -0
  19. package/dist/tools/outcome.js.map +1 -0
  20. package/dist/tools/pipeline.d.ts +52 -0
  21. package/dist/tools/pipeline.js +184 -0
  22. package/dist/tools/pipeline.js.map +1 -0
  23. package/dist/tools/schema.d.ts +20 -0
  24. package/dist/tools/schema.js +100 -0
  25. package/dist/tools/schema.js.map +1 -0
  26. package/dist/tools/types.d.ts +144 -0
  27. package/dist/tools/types.js +2 -0
  28. package/dist/tools/types.js.map +1 -0
  29. package/dist/vendor/agent-safety/errors.d.ts +14 -0
  30. package/dist/vendor/agent-safety/errors.js +21 -0
  31. package/dist/vendor/agent-safety/errors.js.map +1 -0
  32. package/dist/vendor/agent-safety/outcome.d.ts +88 -0
  33. package/dist/vendor/agent-safety/outcome.js +140 -0
  34. package/dist/vendor/agent-safety/outcome.js.map +1 -0
  35. package/dist/vendor/agent-safety/render.d.ts +40 -0
  36. package/dist/vendor/agent-safety/render.js +92 -0
  37. package/dist/vendor/agent-safety/render.js.map +1 -0
  38. package/package.json +11 -3
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The tool pipeline: the fixed steps every tool call runs (agent-SDK guide §4). Resolve the name, coerce, validate,
3
+ * an optional `repair`, the gate, `execute`, the write outcome, then `afterToolCall`. A failure the model caused
4
+ * becomes an error result and never throws; only a programmer error, such as a malformed tool result, throws an
5
+ * `SdkError`.
6
+ *
7
+ * The gate and `afterToolCall` steps hold their places in the order below, and the interceptors fill them in: until
8
+ * then every call is allowed and every result passes through unchanged. Calls run one at a time, in model order.
9
+ */
10
+ import type { AssistantMessage } from "@buildanagent/gateway";
11
+ import type { Clock } from "../testing/determinism.js";
12
+ import type { ToolCall, ToolDefinition, ToolResult } from "./types.js";
13
+ /** A tool of any input and structured type, as the pipeline holds it. */
14
+ export type AnyTool = ToolDefinition<unknown, unknown>;
15
+ /** What the pipeline needs from the run around it. */
16
+ export interface PipelineContext {
17
+ readonly runId: string;
18
+ readonly signal: AbortSignal;
19
+ readonly depth: number;
20
+ readonly maxDepth: number;
21
+ readonly clock: Clock;
22
+ /** Receives a tool's progress updates. */
23
+ onUpdate?(callId: string, details: unknown): void;
24
+ /**
25
+ * Receives each call's result as soon as `runToolCalls` has it, so the run can record a write before a later call
26
+ * in the same message throws.
27
+ */
28
+ onResult?(entry: ToolCallResult): void;
29
+ /**
30
+ * Called as soon as a tool's `execute` returns or throws, before the result is checked, so the run knows a write
31
+ * may have happened even when its result then throws an `SdkError`.
32
+ */
33
+ onExecuted?(call: ToolCall): void;
34
+ }
35
+ /** One tool call and the result the model will read for it. */
36
+ export interface ToolCallResult {
37
+ readonly call: ToolCall;
38
+ readonly result: ToolResult;
39
+ }
40
+ /**
41
+ * Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure
42
+ * the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws
43
+ * an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.
44
+ */
45
+ export declare function runToolCall(call: ToolCall, tools: readonly AnyTool[], ctx: PipelineContext): Promise<ToolResult>;
46
+ /**
47
+ * Runs every tool call of an assistant message, one at a time and in model order, and passes each result to
48
+ * `ctx.onResult` as it arrives. A message that stopped at the output limit (`stopReason: "length"`) runs nothing:
49
+ * each of its calls gets an error asking the model to re-issue it, because its arguments may be cut short. A message
50
+ * that ended in an error or was aborted also runs nothing, because its calls may be partial.
51
+ */
52
+ export declare function runToolCalls(message: AssistantMessage, tools: readonly AnyTool[], ctx: PipelineContext): Promise<ToolCallResult[]>;
@@ -0,0 +1,184 @@
1
+ import { SdkError } from "../errors.js";
2
+ import { coerceValue } from "./coerce.js";
3
+ import { preparedSchemaOf } from "./define.js";
4
+ import { formatToolError, REDACTED_MESSAGE } from "./format-error.js";
5
+ import { withOutcome } from "./outcome.js";
6
+ function toolsByName(tools) {
7
+ const byName = new Map();
8
+ for (const tool of tools) {
9
+ preparedSchemaOf(tool);
10
+ if (byName.has(tool.name)) {
11
+ throw new SdkError("invalid_tool_definition", `two tools are named "${tool.name}"; tool names must be unique`);
12
+ }
13
+ byName.set(tool.name, tool);
14
+ }
15
+ return byName;
16
+ }
17
+ function errorMessage(error) {
18
+ return error instanceof Error ? error.message : String(error);
19
+ }
20
+ function isModelContent(block) {
21
+ if (typeof block !== "object" || block === null)
22
+ return false;
23
+ const { type, text, mediaType, data } = block;
24
+ if (type === "text")
25
+ return typeof text === "string";
26
+ return type === "image" && typeof mediaType === "string" && typeof data === "string";
27
+ }
28
+ function isContentList(content) {
29
+ return Array.isArray(content) && content.every(isModelContent);
30
+ }
31
+ // A formatter that throws, or returns something the model can't read, must not hide the failure from the model, so
32
+ // the default text is used instead, and the formatter's error is kept in `details`.
33
+ function formatted(failure, tool) {
34
+ const fallback = formatToolError(failure);
35
+ if (tool?.formatError === undefined)
36
+ return { content: fallback };
37
+ let content;
38
+ try {
39
+ content = tool.formatError(failure);
40
+ }
41
+ catch (error) {
42
+ return { content: fallback, error: errorMessage(error) };
43
+ }
44
+ if (isContentList(content))
45
+ return { content };
46
+ return { content: fallback, error: "formatError did not return a list of text and image blocks" };
47
+ }
48
+ function failed(failure, tool, details = {}) {
49
+ const { content, error: formatterError } = formatted(failure, tool);
50
+ return {
51
+ content,
52
+ isError: true,
53
+ details: { failure, ...details, ...(formatterError === undefined ? {} : { formatterError }) },
54
+ };
55
+ }
56
+ // Coerce, validate, and on failure give `repair` one chance. The model sees the issues of its own arguments, and
57
+ // `details` keeps what repair returned.
58
+ async function checkInput(tool, call) {
59
+ const schema = preparedSchemaOf(tool);
60
+ const coerced = coerceValue(call.input, schema.jsonSchema);
61
+ const first = await schema.validate(coerced);
62
+ if (first.ok)
63
+ return { ok: true, input: first.value };
64
+ const failure = {
65
+ kind: "invalid_input",
66
+ tool: tool.name,
67
+ callId: call.callId,
68
+ input: call.input,
69
+ issues: first.issues,
70
+ };
71
+ if (tool.repair === undefined)
72
+ return { ok: false, result: failed(failure, tool) };
73
+ let repaired;
74
+ try {
75
+ repaired = await tool.repair({ input: coerced, issues: first.issues });
76
+ }
77
+ catch (error) {
78
+ return { ok: false, result: failed(failure, tool, { repairError: errorMessage(error) }) };
79
+ }
80
+ if (repaired === undefined)
81
+ return { ok: false, result: failed(failure, tool) };
82
+ const second = await schema.validate(coerceValue(repaired, schema.jsonSchema));
83
+ if (second.ok)
84
+ return { ok: true, input: second.value };
85
+ return { ok: false, result: failed(failure, tool, { repaired, repairedIssues: second.issues }) };
86
+ }
87
+ function checkResult(tool, result) {
88
+ const content = result?.content;
89
+ if (typeof result !== "object" || result === null || !isContentList(content)) {
90
+ throw new SdkError("invalid_tool_result", `tool "${tool}" must return an object whose content is a list of text and image blocks`);
91
+ }
92
+ return result;
93
+ }
94
+ async function execute(tool, call, input, ctx) {
95
+ const context = {
96
+ runId: ctx.runId,
97
+ callId: call.callId,
98
+ signal: ctx.signal,
99
+ depth: ctx.depth,
100
+ maxDepth: ctx.maxDepth,
101
+ clock: ctx.clock,
102
+ update: (details) => ctx.onUpdate?.(call.callId, details),
103
+ };
104
+ let result;
105
+ try {
106
+ result = await tool.execute(input, context);
107
+ }
108
+ catch (error) {
109
+ ctx.onExecuted?.(call);
110
+ const message = errorMessage(error);
111
+ const redacted = tool.redactErrors === true;
112
+ const failure = {
113
+ kind: "execution_error",
114
+ tool: tool.name,
115
+ callId: call.callId,
116
+ input: call.input,
117
+ message: redacted ? REDACTED_MESSAGE : message,
118
+ redacted,
119
+ };
120
+ return failed(failure, tool, { error: { name: error instanceof Error ? error.name : typeof error, message } });
121
+ }
122
+ ctx.onExecuted?.(call);
123
+ return withOutcome(tool.name, checkResult(tool.name, result));
124
+ }
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
+ function notRun(call, tool, reason) {
151
+ return failed({ kind: "not_run", reason, tool: call.name, callId: call.callId, input: call.input }, tool);
152
+ }
153
+ // Why none of a message's calls may run, or undefined when they all may.
154
+ function unrunnable(message, call, tools) {
155
+ const tool = tools.find((candidate) => candidate.name === call.name);
156
+ switch (message.stopReason) {
157
+ case "length":
158
+ return failed({ kind: "truncated", tool: call.name, callId: call.callId, input: call.input }, tool);
159
+ case "error":
160
+ return notRun(call, tool, "response_error");
161
+ case "aborted":
162
+ return notRun(call, tool, "response_aborted");
163
+ default:
164
+ return undefined;
165
+ }
166
+ }
167
+ /**
168
+ * Runs every tool call of an assistant message, one at a time and in model order, and passes each result to
169
+ * `ctx.onResult` as it arrives. A message that stopped at the output limit (`stopReason: "length"`) runs nothing:
170
+ * each of its calls gets an error asking the model to re-issue it, because its arguments may be cut short. A message
171
+ * that ended in an error or was aborted also runs nothing, because its calls may be partial.
172
+ */
173
+ export async function runToolCalls(message, tools, ctx) {
174
+ const calls = message.content.filter((block) => block.type === "tool_call");
175
+ toolsByName(tools);
176
+ const results = [];
177
+ for (const call of calls) {
178
+ const entry = { call, result: unrunnable(message, call, tools) ?? (await runToolCall(call, tools, ctx)) };
179
+ results.push(entry);
180
+ ctx.onResult?.(entry);
181
+ }
182
+ return results;
183
+ }
184
+ //# sourceMappingURL=pipeline.js.map
@@ -0,0 +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,EAA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AAK,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,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"]}
@@ -0,0 +1,20 @@
1
+ import type { JsonSchema, SchemaIssue, ToolSchema } from "./types.js";
2
+ /** The outcome of validating one input: the value `execute` receives, or the issues. */
3
+ export type Validation = {
4
+ readonly ok: true;
5
+ readonly value: unknown;
6
+ } | {
7
+ readonly ok: false;
8
+ readonly issues: readonly SchemaIssue[];
9
+ };
10
+ /** A tool's schema, ready for the pipeline. */
11
+ export interface PreparedSchema {
12
+ /** The JSON Schema the model is sent, and the one coercion reads. */
13
+ readonly jsonSchema: JsonSchema;
14
+ validate(value: unknown): Promise<Validation>;
15
+ }
16
+ /**
17
+ * Prepares a tool's input schema. Throws an `SdkError`, code `invalid_tool_definition`, when a raw schema does not
18
+ * compile or names a draft other than 2020-12 or 7, or when a Standard Schema cannot produce JSON Schema.
19
+ */
20
+ export declare function prepareSchema(tool: string, schema: ToolSchema<unknown>): PreparedSchema;
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Schema handling: turns a tool's `inputSchema` into the JSON Schema the model is sent and a validator the pipeline
3
+ * runs. A Standard Schema validates itself and describes itself as JSON Schema; a raw JSON Schema is compiled once
4
+ * with pi-schema, drafts 2020-12 and 7, with format checks on (D7).
5
+ */
6
+ import { compile } from "@earendil-works/pi-schema";
7
+ import { formats } from "@earendil-works/pi-schema/formats";
8
+ import { SdkError } from "../errors.js";
9
+ const DRAFT_7 = /^https?:\/\/json-schema\.org\/draft-07\/schema#?$/;
10
+ const DRAFT_2020_12 = /^https?:\/\/json-schema\.org\/draft\/2020-12\/schema#?$/;
11
+ function isStandardSchema(schema) {
12
+ return "~standard" in schema;
13
+ }
14
+ // An ArkType schema is a callable function that carries `~standard`, so a function counts when it has that property.
15
+ function isSchemaShaped(schema) {
16
+ if (typeof schema === "object")
17
+ return schema !== null;
18
+ return typeof schema === "function" && "~standard" in schema;
19
+ }
20
+ function invalid(tool, message, cause) {
21
+ return new SdkError("invalid_tool_definition", `tool "${tool}": ${message}`, cause === undefined ? {} : { cause });
22
+ }
23
+ function draftOf(tool, schema) {
24
+ const declared = schema.$schema;
25
+ if (declared === undefined || (typeof declared === "string" && DRAFT_2020_12.test(declared)))
26
+ return "2020-12";
27
+ if (typeof declared === "string" && DRAFT_7.test(declared))
28
+ return "7";
29
+ throw invalid(tool, `$schema ${JSON.stringify(declared)} is not draft 2020-12 or draft 7`);
30
+ }
31
+ function prepareJsonSchema(tool, schema) {
32
+ let validator;
33
+ try {
34
+ validator = compile(schema, { draft: draftOf(tool, schema), formats });
35
+ }
36
+ catch (cause) {
37
+ if (cause instanceof SdkError)
38
+ throw cause;
39
+ throw invalid(tool, "its input schema does not compile", cause);
40
+ }
41
+ return {
42
+ jsonSchema: schema,
43
+ async validate(value) {
44
+ if (validator.check(value))
45
+ return { ok: true, value };
46
+ const issues = validator.errors(value).map(({ path, keyword, message }) => ({ path, keyword, message }));
47
+ return { ok: false, issues };
48
+ },
49
+ };
50
+ }
51
+ // RFC 6901: "~" and "/" in a key are escaped as "~0" and "~1".
52
+ function pointer(path) {
53
+ return (path ?? [])
54
+ .map((segment) => {
55
+ const key = typeof segment === "object" ? segment.key : segment;
56
+ const text = typeof key === "symbol" ? (key.description ?? "") : String(key);
57
+ return `/${text.replaceAll("~", "~0").replaceAll("/", "~1")}`;
58
+ })
59
+ .join("");
60
+ }
61
+ function prepareStandardSchema(tool, schema) {
62
+ let jsonSchema;
63
+ try {
64
+ jsonSchema = schema["~standard"].jsonSchema.input({ target: "draft-2020-12" });
65
+ }
66
+ catch (cause) {
67
+ throw invalid(tool, "its Standard Schema cannot describe its input as draft 2020-12 JSON Schema", cause);
68
+ }
69
+ return {
70
+ jsonSchema,
71
+ async validate(value) {
72
+ let result;
73
+ try {
74
+ result = await schema["~standard"].validate(value);
75
+ }
76
+ catch (error) {
77
+ // A validator that throws is the schema library's failure, not the model's, but the model still needs an
78
+ // error result, so the throw becomes one issue at the root.
79
+ const message = error instanceof Error ? error.message : String(error);
80
+ return { ok: false, issues: [{ path: "", message: `the schema's validator threw: ${message}` }] };
81
+ }
82
+ if (result.issues === undefined)
83
+ return { ok: true, value: result.value };
84
+ return {
85
+ ok: false,
86
+ issues: result.issues.map((issue) => ({ path: pointer(issue.path), message: issue.message })),
87
+ };
88
+ },
89
+ };
90
+ }
91
+ /**
92
+ * Prepares a tool's input schema. Throws an `SdkError`, code `invalid_tool_definition`, when a raw schema does not
93
+ * compile or names a draft other than 2020-12 or 7, or when a Standard Schema cannot produce JSON Schema.
94
+ */
95
+ export function prepareSchema(tool, schema) {
96
+ if (!isSchemaShaped(schema))
97
+ throw invalid(tool, "inputSchema must be a JSON Schema object or a Standard Schema");
98
+ return isStandardSchema(schema) ? prepareStandardSchema(tool, schema) : prepareJsonSchema(tool, schema);
99
+ }
100
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/tools/sch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AAE,CAAC;YAC1E,OAAO;gBACL,EAAE,EAAE,KAAK;gBACT,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;aAC9F,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,MAA2B;IACrE,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC;QAAE,MAAM,OAAO,CAAC,IAAI,EAAE,+DAA+D,CAAC,CAAC;IAClH,OAAO,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,qBAAqB,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC1G,CAAC","sourcesContent":["/**\n * Schema handling: turns a tool's `inputSchema` into the JSON Schema the model is sent and a validator the pipeline\n * runs. A Standard Schema validates itself and describes itself as JSON Schema; a raw JSON Schema is compiled once\n * with pi-schema, drafts 2020-12 and 7, with format checks on (D7).\n */\nimport { compile, type Validator } from \"@earendil-works/pi-schema\";\nimport { formats } from \"@earendil-works/pi-schema/formats\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { SdkError } from \"../errors.js\";\nimport type { JsonSchema, SchemaIssue, ToolSchema } from \"./types.js\";\n\n/** The outcome of validating one input: the value `execute` receives, or the issues. */\nexport type Validation =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly issues: readonly SchemaIssue[] };\n\n/** A tool's schema, ready for the pipeline. */\nexport interface PreparedSchema {\n /** The JSON Schema the model is sent, and the one coercion reads. */\n readonly jsonSchema: JsonSchema;\n validate(value: unknown): Promise<Validation>;\n}\n\ntype StandardToolSchema = StandardSchemaV1<unknown, unknown> & StandardJSONSchemaV1<unknown, unknown>;\n\nconst DRAFT_7 = /^https?:\\/\\/json-schema\\.org\\/draft-07\\/schema#?$/;\nconst DRAFT_2020_12 = /^https?:\\/\\/json-schema\\.org\\/draft\\/2020-12\\/schema#?$/;\n\nfunction isStandardSchema(schema: ToolSchema<unknown>): schema is StandardToolSchema {\n return \"~standard\" in schema;\n}\n\n// An ArkType schema is a callable function that carries `~standard`, so a function counts when it has that property.\nfunction isSchemaShaped(schema: unknown): schema is ToolSchema<unknown> {\n if (typeof schema === \"object\") return schema !== null;\n return typeof schema === \"function\" && \"~standard\" in schema;\n}\n\nfunction invalid(tool: string, message: string, cause?: unknown): SdkError {\n return new SdkError(\"invalid_tool_definition\", `tool \"${tool}\": ${message}`, cause === undefined ? {} : { cause });\n}\n\nfunction draftOf(tool: string, schema: JsonSchema): \"7\" | \"2020-12\" {\n const declared = schema.$schema;\n if (declared === undefined || (typeof declared === \"string\" && DRAFT_2020_12.test(declared))) return \"2020-12\";\n if (typeof declared === \"string\" && DRAFT_7.test(declared)) return \"7\";\n throw invalid(tool, `$schema ${JSON.stringify(declared)} is not draft 2020-12 or draft 7`);\n}\n\nfunction prepareJsonSchema(tool: string, schema: JsonSchema): PreparedSchema {\n let validator: Validator<unknown>;\n try {\n validator = compile(schema, { draft: draftOf(tool, schema), formats });\n } catch (cause) {\n if (cause instanceof SdkError) throw cause;\n throw invalid(tool, \"its input schema does not compile\", cause);\n }\n return {\n jsonSchema: schema,\n async validate(value) {\n if (validator.check(value)) return { ok: true, value };\n const issues = validator.errors(value).map(({ path, keyword, message }) => ({ path, keyword, message }));\n return { ok: false, issues };\n },\n };\n}\n\n// RFC 6901: \"~\" and \"/\" in a key are escaped as \"~0\" and \"~1\".\nfunction pointer(path: StandardSchemaV1.Issue[\"path\"]): string {\n return (path ?? [])\n .map((segment) => {\n const key = typeof segment === \"object\" ? segment.key : segment;\n const text = typeof key === \"symbol\" ? (key.description ?? \"\") : String(key);\n return `/${text.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")}`;\n })\n .join(\"\");\n}\n\nfunction prepareStandardSchema(tool: string, schema: StandardToolSchema): PreparedSchema {\n let jsonSchema: JsonSchema;\n try {\n jsonSchema = schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" });\n } catch (cause) {\n throw invalid(tool, \"its Standard Schema cannot describe its input as draft 2020-12 JSON Schema\", cause);\n }\n return {\n jsonSchema,\n async validate(value) {\n let result: StandardSchemaV1.Result<unknown>;\n try {\n result = await schema[\"~standard\"].validate(value);\n } catch (error) {\n // A validator that throws is the schema library's failure, not the model's, but the model still needs an\n // error result, so the throw becomes one issue at the root.\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, issues: [{ path: \"\", message: `the schema's validator threw: ${message}` }] };\n }\n if (result.issues === undefined) return { ok: true, value: result.value };\n return {\n ok: false,\n issues: result.issues.map((issue) => ({ path: pointer(issue.path), message: issue.message })),\n };\n },\n };\n}\n\n/**\n * Prepares a tool's input schema. Throws an `SdkError`, code `invalid_tool_definition`, when a raw schema does not\n * compile or names a draft other than 2020-12 or 7, or when a Standard Schema cannot produce JSON Schema.\n */\nexport function prepareSchema(tool: string, schema: ToolSchema<unknown>): PreparedSchema {\n if (!isSchemaShaped(schema)) throw invalid(tool, \"inputSchema must be a JSON Schema object or a Standard Schema\");\n return isStandardSchema(schema) ? prepareStandardSchema(tool, schema) : prepareJsonSchema(tool, schema);\n}\n"]}
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The tool types: what a tool declares, what its `execute` receives and returns, and the failures the pipeline
3
+ * reports to the model (SDK plan §3.3; agent-SDK guide §4).
4
+ */
5
+ import type { ContentBlock, ModelContent } from "@buildanagent/gateway";
6
+ import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
7
+ import type { Clock } from "../testing/determinism.js";
8
+ import type { WriteOutcome } from "../vendor/agent-safety/outcome.js";
9
+ /** A JSON Schema object, draft 2020-12 or draft 7, such as `{ type: "object", properties: { … } }`. */
10
+ export type JsonSchema = Readonly<Record<string, unknown>>;
11
+ /**
12
+ * A tool's input schema: a Standard Schema that can also describe itself as JSON Schema (Zod 4.2 or later, ArkType,
13
+ * 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
14
+ * any other as draft 2020-12.
15
+ */
16
+ export type ToolSchema<I> = (StandardSchemaV1<unknown, I> & StandardJSONSchemaV1<unknown, I>) | JsonSchema;
17
+ /**
18
+ * One reason a tool input failed its schema. `path` is a JSON Pointer, such as `/items/0/sku`, or `""` for the whole
19
+ * input.
20
+ */
21
+ export interface SchemaIssue {
22
+ readonly path: string;
23
+ readonly message: string;
24
+ /** The JSON Schema keyword that failed, such as `required`, when the validator reports one. */
25
+ readonly keyword?: string;
26
+ }
27
+ /** The fields every tool failure carries. `input` is the arguments the model sent. */
28
+ interface FailureBase {
29
+ readonly tool: string;
30
+ readonly callId: string;
31
+ readonly input: unknown;
32
+ }
33
+ /**
34
+ * A failed tool call, as the error formatter receives it. `unknown_tool`: the model named a tool that doesn't exist.
35
+ * `invalid_input`: the arguments failed the schema, even after repair. `execution_error`: `execute` threw; with
36
+ * `redactErrors`, `message` is a fixed line and the thrown message is only in the result's `details`. `truncated`:
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
+ * response ended in an error (`response_error`) or was aborted (`response_aborted`), or the run was cancelled before
39
+ * the call started (`run_aborted`).
40
+ */
41
+ export type ToolFailure = (FailureBase & {
42
+ readonly kind: "unknown_tool";
43
+ readonly availableTools: readonly string[];
44
+ }) | (FailureBase & {
45
+ readonly kind: "invalid_input";
46
+ readonly issues: readonly SchemaIssue[];
47
+ }) | (FailureBase & {
48
+ readonly kind: "execution_error";
49
+ readonly message: string;
50
+ readonly redacted: boolean;
51
+ }) | (FailureBase & {
52
+ readonly kind: "truncated";
53
+ }) | (FailureBase & {
54
+ readonly kind: "not_run";
55
+ readonly reason: "response_error" | "response_aborted" | "run_aborted";
56
+ });
57
+ /**
58
+ * Declares that a tool changes the world, such as sending an email. A tool without `effect` counts as read-only, so
59
+ * a run that crashes mid-call may safely run it again. `businessKey` names the real-world operation, such as
60
+ * `refund:<order id>`, so the same write is recognised across retries and sessions.
61
+ */
62
+ export interface ToolEffect<I> {
63
+ readonly kind: "write";
64
+ businessKey?(input: I): string;
65
+ }
66
+ /** What a tool's `execute` receives besides its input. */
67
+ export interface ToolContext {
68
+ readonly runId: string;
69
+ readonly callId: string;
70
+ /** Fires when the run is aborted. */
71
+ readonly signal: AbortSignal;
72
+ /** How deeply this run is nested inside other agents' tool calls; 0 for a top-level run. */
73
+ readonly depth: number;
74
+ /** The deepest nesting allowed; a tool that starts another agent refuses at this depth. */
75
+ readonly maxDepth: number;
76
+ readonly clock: Clock;
77
+ /** Reports progress for a user interface, such as rows processed so far. The model never sees it. */
78
+ update(details: unknown): void;
79
+ }
80
+ /**
81
+ * What a tool returns. `content` is what the model reads, `details` is for logs and user interfaces, and
82
+ * `structured` is typed data for your code; only `content` reaches the model. `isError` marks a failure for the model.
83
+ * `terminate` asks the run to end after this step. `pause` asks the user a question. `outcome` reports what a write
84
+ * did: any kind except `applied` sets `isError`, and the model reads the outcome's sentence and fields before
85
+ * `content`.
86
+ */
87
+ export interface ToolResult<S = unknown> {
88
+ readonly content: readonly ModelContent[];
89
+ readonly details?: unknown;
90
+ readonly structured?: S;
91
+ readonly isError?: boolean;
92
+ readonly terminate?: boolean;
93
+ readonly pause?: {
94
+ readonly kind: "clarification";
95
+ readonly question: string;
96
+ };
97
+ readonly outcome?: WriteOutcome;
98
+ }
99
+ /**
100
+ * A tool the model can call. `I` is the input `execute` receives after validation, and `S` the type of `structured`.
101
+ *
102
+ * Every call runs the same steps: the name is resolved, the input is coerced and validated, `repair` gets one chance
103
+ * to fix invalid input, then `execute` runs. A failure the model caused, such as an unknown tool, invalid input or
104
+ * a throwing `execute`, returns an error result to the model. A result that isn't a list of text and image blocks,
105
+ * or that carries an invalid write outcome, throws an `SdkError` with code `invalid_tool_result`.
106
+ */
107
+ export interface ToolDefinition<I = unknown, S = unknown> {
108
+ /** 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`. */
109
+ readonly name: string;
110
+ readonly description: string;
111
+ /**
112
+ * `function` (the default) runs in your process. The other kinds are for tools that a provider defines or runs:
113
+ * `dynamic` tools have a schema known only at run time, such as one from an MCP server.
114
+ */
115
+ readonly kind?: "function" | "dynamic" | "provider-local" | "provider-executed";
116
+ readonly inputSchema: ToolSchema<I>;
117
+ /** Marks a tool that changes the world. A tool without it counts as read-only. */
118
+ readonly effect?: ToolEffect<I>;
119
+ /**
120
+ * Called once when the input fails its schema, with the coerced input and the issues. Return fixed input to
121
+ * validate again, or `undefined` to report the failure to the model.
122
+ */
123
+ repair?(e: {
124
+ readonly input: unknown;
125
+ readonly issues: readonly SchemaIssue[];
126
+ }): Promise<unknown>;
127
+ /**
128
+ * Builds the content the model reads for a failed call, in place of the default text, which lists the issues and
129
+ * the received arguments and tells the model not to substitute invented data. It runs synchronously; if it throws
130
+ * or returns anything but a list of text and image blocks, the model reads the default text instead.
131
+ */
132
+ formatError?(failure: ToolFailure): readonly ModelContent[];
133
+ /**
134
+ * When true, an error thrown by `execute` reaches the model as a fixed line, and its message goes only to the
135
+ * result's `details`. Default false.
136
+ */
137
+ readonly redactErrors?: boolean;
138
+ execute(input: I, ctx: ToolContext): Promise<ToolResult<S>>;
139
+ }
140
+ /** A tool call block from an assistant message. */
141
+ export type ToolCall = Extract<ContentBlock, {
142
+ type: "tool_call";
143
+ }>;
144
+ export {};
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +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 /** Fires when the run is aborted. */\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 /** Marks a tool that changes the world. A tool without it counts as read-only. */\n readonly effect?: ToolEffect<I>;\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"]}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason or
3
+ * an input that has no canonical JSON form.
4
+ */
5
+ /** Why a `SafetyError` was thrown. */
6
+ export type SafetyErrorCode = "invalid_outcome" | "invalid_input";
7
+ /** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */
8
+ export declare class SafetyError extends Error {
9
+ readonly name = "SafetyError";
10
+ readonly code: SafetyErrorCode;
11
+ constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions);
12
+ }
13
+ /** True for a `SafetyError`, including one from another copy of the package. */
14
+ export declare function isSafetyError(error: unknown): error is SafetyError;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason or
3
+ * an input that has no canonical JSON form.
4
+ */
5
+ // A registered symbol, so the guard still works when two copies of the package are bundled.
6
+ const SAFETY_ERROR = Symbol.for("buildanagent.agent-safety.SafetyError");
7
+ /** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */
8
+ export class SafetyError extends Error {
9
+ name = "SafetyError";
10
+ code;
11
+ constructor(code, message, options) {
12
+ super(message, options);
13
+ this.code = code;
14
+ Object.defineProperty(this, SAFETY_ERROR, { value: true });
15
+ }
16
+ }
17
+ /** True for a `SafetyError`, including one from another copy of the package. */
18
+ export function isSafetyError(error) {
19
+ return typeof error === "object" && error !== null && error[SAFETY_ERROR] === true;
20
+ }
21
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,4FAA4F;AAC5F,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;AAEzE,oHAAoH;AACpH,MAAM,OAAO,WAAY,SAAQ,KAAK;IAClB,IAAI,GAAG,aAAa,CAAC;IAC9B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAAsB;QACxE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAClH,CAAC","sourcesContent":["/**\n * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason or\n * an input that has no canonical JSON form.\n */\n\n/** Why a `SafetyError` was thrown. */\nexport type SafetyErrorCode = \"invalid_outcome\" | \"invalid_input\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SAFETY_ERROR = Symbol.for(\"buildanagent.agent-safety.SafetyError\");\n\n/** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */\nexport class SafetyError extends Error {\n override readonly name = \"SafetyError\";\n readonly code: SafetyErrorCode;\n\n constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SAFETY_ERROR, { value: true });\n }\n}\n\n/** True for a `SafetyError`, including one from another copy of the package. */\nexport function isSafetyError(error: unknown): error is SafetyError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SAFETY_ERROR] === true;\n}\n"]}