@buildanagent/sdk 0.1.0-alpha.0 → 0.1.0-alpha.10

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 (116) hide show
  1. package/README.md +425 -6
  2. package/dist/budget.d.ts +33 -0
  3. package/dist/budget.js +55 -0
  4. package/dist/budget.js.map +1 -0
  5. package/dist/compose.d.ts +26 -0
  6. package/dist/compose.js +157 -0
  7. package/dist/compose.js.map +1 -0
  8. package/dist/errors.d.ts +49 -0
  9. package/dist/errors.js +57 -0
  10. package/dist/errors.js.map +1 -0
  11. package/dist/events.d.ts +168 -0
  12. package/dist/events.js +32 -0
  13. package/dist/events.js.map +1 -0
  14. package/dist/freeze.d.ts +11 -0
  15. package/dist/freeze.js +42 -0
  16. package/dist/freeze.js.map +1 -0
  17. package/dist/hook-checks.d.ts +31 -0
  18. package/dist/hook-checks.js +130 -0
  19. package/dist/hook-checks.js.map +1 -0
  20. package/dist/hook-runner.d.ts +96 -0
  21. package/dist/hook-runner.js +372 -0
  22. package/dist/hook-runner.js.map +1 -0
  23. package/dist/hooks.d.ts +183 -0
  24. package/dist/hooks.js +2 -0
  25. package/dist/hooks.js.map +1 -0
  26. package/dist/index.d.ts +26 -3
  27. package/dist/index.js +21 -3
  28. package/dist/index.js.map +1 -1
  29. package/dist/loop.d.ts +67 -0
  30. package/dist/loop.js +644 -0
  31. package/dist/loop.js.map +1 -0
  32. package/dist/observers.d.ts +31 -0
  33. package/dist/observers.js +98 -0
  34. package/dist/observers.js.map +1 -0
  35. package/dist/otel/attributes.d.ts +43 -0
  36. package/dist/otel/attributes.js +50 -0
  37. package/dist/otel/attributes.js.map +1 -0
  38. package/dist/otel/content.d.ts +17 -0
  39. package/dist/otel/content.js +48 -0
  40. package/dist/otel/content.js.map +1 -0
  41. package/dist/otel/index.d.ts +6 -2
  42. package/dist/otel/index.js +6 -2
  43. package/dist/otel/index.js.map +1 -1
  44. package/dist/otel/observer.d.ts +82 -0
  45. package/dist/otel/observer.js +300 -0
  46. package/dist/otel/observer.js.map +1 -0
  47. package/dist/pauses.d.ts +61 -0
  48. package/dist/pauses.js +83 -0
  49. package/dist/pauses.js.map +1 -0
  50. package/dist/progress.d.ts +34 -0
  51. package/dist/progress.js +139 -0
  52. package/dist/progress.js.map +1 -0
  53. package/dist/result.d.ts +134 -0
  54. package/dist/result.js +2 -0
  55. package/dist/result.js.map +1 -0
  56. package/dist/resume.d.ts +76 -0
  57. package/dist/resume.js +237 -0
  58. package/dist/resume.js.map +1 -0
  59. package/dist/run.d.ts +214 -0
  60. package/dist/run.js +327 -0
  61. package/dist/run.js.map +1 -0
  62. package/dist/steering.d.ts +52 -0
  63. package/dist/steering.js +104 -0
  64. package/dist/steering.js.map +1 -0
  65. package/dist/testing/scripted-model.d.ts +17 -2
  66. package/dist/testing/scripted-model.js +22 -4
  67. package/dist/testing/scripted-model.js.map +1 -1
  68. package/dist/tools/coerce.d.ts +15 -0
  69. package/dist/tools/coerce.js +93 -0
  70. package/dist/tools/coerce.js.map +1 -0
  71. package/dist/tools/define.d.ts +54 -0
  72. package/dist/tools/define.js +121 -0
  73. package/dist/tools/define.js.map +1 -0
  74. package/dist/tools/format-error.d.ts +13 -0
  75. package/dist/tools/format-error.js +66 -0
  76. package/dist/tools/format-error.js.map +1 -0
  77. package/dist/tools/outcome.d.ts +7 -0
  78. package/dist/tools/outcome.js +30 -0
  79. package/dist/tools/outcome.js.map +1 -0
  80. package/dist/tools/pipeline.d.ts +111 -0
  81. package/dist/tools/pipeline.js +382 -0
  82. package/dist/tools/pipeline.js.map +1 -0
  83. package/dist/tools/scheduler.d.ts +33 -0
  84. package/dist/tools/scheduler.js +51 -0
  85. package/dist/tools/scheduler.js.map +1 -0
  86. package/dist/tools/schema.d.ts +20 -0
  87. package/dist/tools/schema.js +100 -0
  88. package/dist/tools/schema.js.map +1 -0
  89. package/dist/tools/types.d.ts +196 -0
  90. package/dist/tools/types.js +2 -0
  91. package/dist/tools/types.js.map +1 -0
  92. package/dist/vendor/agent-safety/bytes.d.ts +17 -0
  93. package/dist/vendor/agent-safety/bytes.js +59 -0
  94. package/dist/vendor/agent-safety/bytes.js.map +1 -0
  95. package/dist/vendor/agent-safety/errors.d.ts +22 -0
  96. package/dist/vendor/agent-safety/errors.js +22 -0
  97. package/dist/vendor/agent-safety/errors.js.map +1 -0
  98. package/dist/vendor/agent-safety/hash.d.ts +16 -0
  99. package/dist/vendor/agent-safety/hash.js +110 -0
  100. package/dist/vendor/agent-safety/hash.js.map +1 -0
  101. package/dist/vendor/agent-safety/outcome.d.ts +88 -0
  102. package/dist/vendor/agent-safety/outcome.js +140 -0
  103. package/dist/vendor/agent-safety/outcome.js.map +1 -0
  104. package/dist/vendor/agent-safety/pending.d.ts +119 -0
  105. package/dist/vendor/agent-safety/pending.js +122 -0
  106. package/dist/vendor/agent-safety/pending.js.map +1 -0
  107. package/dist/vendor/agent-safety/render.d.ts +40 -0
  108. package/dist/vendor/agent-safety/render.js +92 -0
  109. package/dist/vendor/agent-safety/render.js.map +1 -0
  110. package/dist/vendor/agent-safety/signer.d.ts +42 -0
  111. package/dist/vendor/agent-safety/signer.js +128 -0
  112. package/dist/vendor/agent-safety/signer.js.map +1 -0
  113. package/dist/version.d.ts +2 -0
  114. package/dist/version.js +8 -0
  115. package/dist/version.js.map +1 -0
  116. package/package.json +13 -3
@@ -0,0 +1,54 @@
1
+ /**
2
+ * `defineTool()`, `outputTool()` and `clarificationTool()`: each checks a definition once and prepares its schema,
3
+ * so a broken tool throws when it is defined rather than when the model first calls it.
4
+ */
5
+ import { type WireTool } from "@buildanagent/gateway";
6
+ import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
7
+ import { type PreparedSchema } from "./schema.js";
8
+ import type { ToolDefinition } from "./types.js";
9
+ /**
10
+ * Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code
11
+ * `invalid_tool_definition`, for a bad name, a missing description or `execute`, an unknown exposure, or an unusable
12
+ * schema.
13
+ */
14
+ export declare function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>): PreparedSchema;
15
+ /**
16
+ * Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.
17
+ *
18
+ * Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
19
+ * from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three
20
+ * values, `executionMode` is neither `parallel` nor `sequential`, `resourceKey` or `progressKey` is not a function,
21
+ * a raw JSON Schema does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe
22
+ * itself as JSON Schema.
23
+ */
24
+ export declare function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S>;
25
+ /** The options of `outputTool()`. */
26
+ export interface OutputToolOptions<S> {
27
+ readonly name: string;
28
+ /** The schema of the final answer. A Standard Schema that can describe itself as JSON Schema, such as Zod 4.2's. */
29
+ readonly schema: StandardSchemaV1<unknown, S> & StandardJSONSchemaV1<unknown, S>;
30
+ /** Defaults to a line asking the model to call the tool once, with its final answer. */
31
+ readonly description?: string;
32
+ }
33
+ /**
34
+ * Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the
35
+ * validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model
36
+ * as an error result, so the model can correct the answer and call again.
37
+ */
38
+ export declare function outputTool<S>(options: OutputToolOptions<S>): ToolDefinition<S, S>;
39
+ /** The options of `clarificationTool()`. */
40
+ export interface ClarificationToolOptions {
41
+ /** Defaults to `ask_user`. */
42
+ readonly name?: string;
43
+ }
44
+ /**
45
+ * Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind
46
+ * `clarification`: the run signs a clarification request for the call, which gets no result, and ends
47
+ * `clarification_requested`. Pass the user's answer to `continueRun()` as `{ requestId, answer }`, and the model reads
48
+ * the answer as the call's result.
49
+ */
50
+ export declare function clarificationTool(options?: ClarificationToolOptions): ToolDefinition<{
51
+ question: string;
52
+ }, never>;
53
+ /** The tool as one model call sends it: its name, description and input JSON Schema. */
54
+ export declare function toWireTool(tool: ToolDefinition<unknown, unknown>): WireTool;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * `defineTool()`, `outputTool()` and `clarificationTool()`: each checks a definition once and prepares its schema,
3
+ * so a broken tool throws when it is defined rather than when the model first calls it.
4
+ */
5
+ import { assertCanonicalName } from "@buildanagent/gateway";
6
+ import { SdkError } from "../errors.js";
7
+ import { prepareSchema } from "./schema.js";
8
+ const EXPOSURES = ["direct", "deferred", "hidden"];
9
+ const EXECUTION_MODES = ["parallel", "sequential"];
10
+ // Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.
11
+ const prepared = new WeakMap();
12
+ function invalid(message, cause) {
13
+ return new SdkError("invalid_tool_definition", message, cause === undefined ? {} : { cause });
14
+ }
15
+ function checkName(name) {
16
+ if (typeof name !== "string")
17
+ throw invalid("a tool's name must be a string");
18
+ try {
19
+ assertCanonicalName(name);
20
+ }
21
+ catch (cause) {
22
+ throw invalid(cause instanceof Error ? cause.message : String(cause), cause);
23
+ }
24
+ return name;
25
+ }
26
+ /**
27
+ * Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code
28
+ * `invalid_tool_definition`, for a bad name, a missing description or `execute`, an unknown exposure, or an unusable
29
+ * schema.
30
+ */
31
+ export function preparedSchemaOf(tool) {
32
+ const known = prepared.get(tool);
33
+ if (known !== undefined)
34
+ return known;
35
+ const name = checkName(tool.name);
36
+ if (typeof tool.description !== "string")
37
+ throw invalid(`tool "${name}": description must be a string`);
38
+ if (typeof tool.execute !== "function")
39
+ throw invalid(`tool "${name}": execute must be a function`);
40
+ if (tool.exposure !== undefined && !EXPOSURES.includes(tool.exposure)) {
41
+ throw invalid(`tool "${name}": exposure must be "direct", "deferred" or "hidden"`);
42
+ }
43
+ if (tool.executionMode !== undefined && !EXECUTION_MODES.includes(tool.executionMode)) {
44
+ throw invalid(`tool "${name}": executionMode must be "parallel" or "sequential"`);
45
+ }
46
+ if (tool.resourceKey !== undefined && typeof tool.resourceKey !== "function") {
47
+ throw invalid(`tool "${name}": resourceKey must be a function`);
48
+ }
49
+ if (tool.progressKey !== undefined && typeof tool.progressKey !== "function") {
50
+ throw invalid(`tool "${name}": progressKey must be a function`);
51
+ }
52
+ const schema = prepareSchema(name, tool.inputSchema);
53
+ prepared.set(tool, schema);
54
+ return schema;
55
+ }
56
+ /**
57
+ * Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.
58
+ *
59
+ * Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
60
+ * from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three
61
+ * values, `executionMode` is neither `parallel` nor `sequential`, `resourceKey` or `progressKey` is not a function,
62
+ * a raw JSON Schema does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe
63
+ * itself as JSON Schema.
64
+ */
65
+ export function defineTool(definition) {
66
+ const tool = Object.freeze({ ...definition });
67
+ // Method parameters are bivariant, so a tool of any input type is a ToolDefinition<unknown, unknown>.
68
+ preparedSchemaOf(tool);
69
+ return tool;
70
+ }
71
+ const OUTPUT_DESCRIPTION = "Submit your final answer as this tool's input. Call it once, when the task is done.";
72
+ const OUTPUT_ACCEPTED = "The final answer was accepted.";
73
+ /**
74
+ * Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the
75
+ * validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model
76
+ * as an error result, so the model can correct the answer and call again.
77
+ */
78
+ export function outputTool(options) {
79
+ return defineTool({
80
+ name: options.name,
81
+ description: options.description ?? OUTPUT_DESCRIPTION,
82
+ inputSchema: options.schema,
83
+ async execute(input) {
84
+ return { content: [{ type: "text", text: OUTPUT_ACCEPTED }], structured: input, terminate: true };
85
+ },
86
+ });
87
+ }
88
+ const CLARIFICATION_SCHEMA = Object.freeze({
89
+ type: "object",
90
+ properties: Object.freeze({
91
+ question: Object.freeze({ type: "string", minLength: 1, description: "The question to ask the user." }),
92
+ }),
93
+ required: Object.freeze(["question"]),
94
+ additionalProperties: false,
95
+ });
96
+ /**
97
+ * Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind
98
+ * `clarification`: the run signs a clarification request for the call, which gets no result, and ends
99
+ * `clarification_requested`. Pass the user's answer to `continueRun()` as `{ requestId, answer }`, and the model reads
100
+ * the answer as the call's result.
101
+ */
102
+ export function clarificationTool(options = {}) {
103
+ return defineTool({
104
+ name: options.name ?? "ask_user",
105
+ description: "Ask the user a question when you cannot continue without their answer.",
106
+ inputSchema: CLARIFICATION_SCHEMA,
107
+ async execute({ question }) {
108
+ return {
109
+ content: [{ type: "text", text: "The question was sent to the user." }],
110
+ pause: { kind: "clarification", question },
111
+ };
112
+ },
113
+ });
114
+ }
115
+ /** The tool as one model call sends it: its name, description and input JSON Schema. */
116
+ export function toWireTool(tool) {
117
+ const { jsonSchema } = preparedSchemaOf(tool);
118
+ // Adapters only read the schema; the cast drops the `readonly` that keeps our own code from changing it.
119
+ return { name: tool.name, description: tool.description, inputSchema: jsonSchema };
120
+ }
121
+ //# sourceMappingURL=define.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,mBAAmB,EAAiB,MAAM,uBAAuB,CAAC;AAE3E,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAuB,aAAa,EAAE,MAAM,aAAa,CAAC;AAGjE,MAAM,SAAS,GAAsB,CAAC,QAAQ,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC;AACtE,MAAM,eAAe,GAAsB,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;AAEtE,+FAA+F;AAC/F,MAAM,QAAQ,GAAG,IAAI,OAAO,EAA0B,CAAC;AAEvD,SAAS,OAAO,CAAC,OAAe,EAAE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,WAAW,EAAE,UAAqC,EAAE,CAAC;AAChH,CAAC","sourcesContent":["/**\n * `defineTool()`, `outputTool()` and `clarificationTool()`: each checks a definition once and prepares its schema,\n * so a broken tool throws when it is defined rather than when the model first calls it.\n */\nimport { assertCanonicalName, type WireTool } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { SdkError } from \"../errors.js\";\nimport { type PreparedSchema, prepareSchema } from \"./schema.js\";\nimport type { ToolDefinition, ToolResult } from \"./types.js\";\n\nconst EXPOSURES: readonly string[] = [\"direct\", \"deferred\", \"hidden\"];\nconst EXECUTION_MODES: readonly string[] = [\"parallel\", \"sequential\"];\n\n// Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.\nconst prepared = new WeakMap<object, PreparedSchema>();\n\nfunction invalid(message: string, cause?: unknown): SdkError {\n return new SdkError(\"invalid_tool_definition\", message, cause === undefined ? {} : { cause });\n}\n\nfunction checkName(name: unknown): string {\n if (typeof name !== \"string\") throw invalid(\"a tool's name must be a string\");\n try {\n assertCanonicalName(name);\n } catch (cause) {\n throw invalid(cause instanceof Error ? cause.message : String(cause), cause);\n }\n return name;\n}\n\n/**\n * Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code\n * `invalid_tool_definition`, for a bad name, a missing description or `execute`, an unknown exposure, or an unusable\n * schema.\n */\nexport function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>): PreparedSchema {\n const known = prepared.get(tool);\n if (known !== undefined) return known;\n const name = checkName(tool.name);\n if (typeof tool.description !== \"string\") throw invalid(`tool \"${name}\": description must be a string`);\n if (typeof tool.execute !== \"function\") throw invalid(`tool \"${name}\": execute must be a function`);\n if (tool.exposure !== undefined && !EXPOSURES.includes(tool.exposure)) {\n throw invalid(`tool \"${name}\": exposure must be \"direct\", \"deferred\" or \"hidden\"`);\n }\n if (tool.executionMode !== undefined && !EXECUTION_MODES.includes(tool.executionMode)) {\n throw invalid(`tool \"${name}\": executionMode must be \"parallel\" or \"sequential\"`);\n }\n if (tool.resourceKey !== undefined && typeof tool.resourceKey !== \"function\") {\n throw invalid(`tool \"${name}\": resourceKey must be a function`);\n }\n if (tool.progressKey !== undefined && typeof tool.progressKey !== \"function\") {\n throw invalid(`tool \"${name}\": progressKey must be a function`);\n }\n const schema = prepareSchema(name, tool.inputSchema);\n prepared.set(tool, schema);\n return schema;\n}\n\n/**\n * Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.\n *\n * Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters\n * from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three\n * values, `executionMode` is neither `parallel` nor `sequential`, `resourceKey` or `progressKey` is not a function,\n * a raw JSON Schema does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe\n * itself as JSON Schema.\n */\nexport function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S> {\n const tool = Object.freeze({ ...definition });\n // Method parameters are bivariant, so a tool of any input type is a ToolDefinition<unknown, unknown>.\n preparedSchemaOf(tool as ToolDefinition<unknown, unknown>);\n return tool;\n}\n\n/** The options of `outputTool()`. */\nexport interface OutputToolOptions<S> {\n readonly name: string;\n /** The schema of the final answer. A Standard Schema that can describe itself as JSON Schema, such as Zod 4.2's. */\n readonly schema: StandardSchemaV1<unknown, S> & StandardJSONSchemaV1<unknown, S>;\n /** Defaults to a line asking the model to call the tool once, with its final answer. */\n readonly description?: string;\n}\n\nconst OUTPUT_DESCRIPTION = \"Submit your final answer as this tool's input. Call it once, when the task is done.\";\nconst OUTPUT_ACCEPTED = \"The final answer was accepted.\";\n\n/**\n * Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the\n * validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model\n * as an error result, so the model can correct the answer and call again.\n */\nexport function outputTool<S>(options: OutputToolOptions<S>): ToolDefinition<S, S> {\n return defineTool<S, S>({\n name: options.name,\n description: options.description ?? OUTPUT_DESCRIPTION,\n inputSchema: options.schema,\n async execute(input): Promise<ToolResult<S>> {\n return { content: [{ type: \"text\", text: OUTPUT_ACCEPTED }], structured: input, terminate: true };\n },\n });\n}\n\n/** The options of `clarificationTool()`. */\nexport interface ClarificationToolOptions {\n /** Defaults to `ask_user`. */\n readonly name?: string;\n}\n\nconst CLARIFICATION_SCHEMA = Object.freeze({\n type: \"object\",\n properties: Object.freeze({\n question: Object.freeze({ type: \"string\", minLength: 1, description: \"The question to ask the user.\" }),\n }),\n required: Object.freeze([\"question\"]),\n additionalProperties: false,\n});\n\n/**\n * Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind\n * `clarification`: the run signs a clarification request for the call, which gets no result, and ends\n * `clarification_requested`. Pass the user's answer to `continueRun()` as `{ requestId, answer }`, and the model reads\n * the answer as the call's result.\n */\nexport function clarificationTool(options: ClarificationToolOptions = {}): ToolDefinition<{ question: string }, never> {\n return defineTool<{ question: string }, never>({\n name: options.name ?? \"ask_user\",\n description: \"Ask the user a question when you cannot continue without their answer.\",\n inputSchema: CLARIFICATION_SCHEMA,\n async execute({ question }) {\n return {\n content: [{ type: \"text\", text: \"The question was sent to the user.\" }],\n pause: { kind: \"clarification\", question },\n };\n },\n });\n}\n\n/** The tool as one model call sends it: its name, description and input JSON Schema. */\nexport function toWireTool(tool: ToolDefinition<unknown, unknown>): WireTool {\n const { jsonSchema } = preparedSchemaOf(tool);\n // Adapters only read the schema; the cast drops the `readonly` that keeps our own code from changing it.\n return { name: tool.name, description: tool.description, inputSchema: jsonSchema as Record<string, unknown> };\n}\n"]}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The default error text the model reads for a failed tool call. Every message says what failed, shows the
3
+ * arguments the model sent, and tells the model not to answer the failure with invented data, because agents have
4
+ * been seen to "make a mock implementation" when a tool fails (agent-SDK guide §4).
5
+ */
6
+ import type { ModelContent } from "@buildanagent/gateway";
7
+ import type { ToolFailure } from "./types.js";
8
+ /** The line every default error message ends with. */
9
+ export declare const DO_NOT_SUBSTITUTE: string;
10
+ /** The fixed line a redacted error shows the model in place of the thrown message. */
11
+ export declare const REDACTED_MESSAGE = "its error message is hidden.";
12
+ /** The default content for a failed tool call: what failed, the received arguments, and the do-not-substitute line. */
13
+ export declare function formatToolError(failure: ToolFailure): ModelContent[];
@@ -0,0 +1,66 @@
1
+ /** The line every default error message ends with. */
2
+ export const DO_NOT_SUBSTITUTE = "Do not substitute a mock, a placeholder or invented data for this tool's result. Fix the call, try another " +
3
+ "approach, or tell the user what failed.";
4
+ /** The fixed line a redacted error shows the model in place of the thrown message. */
5
+ export const REDACTED_MESSAGE = "its error message is hidden.";
6
+ // Received arguments are shown up to this many characters, so one huge argument can't flood the context.
7
+ const MAX_ARGUMENTS_LENGTH = 2000;
8
+ // `String()` can itself throw, on an object with no prototype, so the last resort is the object tag.
9
+ function plainString(input) {
10
+ try {
11
+ return String(input);
12
+ }
13
+ catch {
14
+ return Object.prototype.toString.call(input);
15
+ }
16
+ }
17
+ function showArguments(input) {
18
+ let text;
19
+ try {
20
+ text = JSON.stringify(input) ?? plainString(input);
21
+ }
22
+ catch {
23
+ // Input from a test double or a tool bridge may hold a cycle or a bigint, which JSON can't encode.
24
+ text = plainString(input);
25
+ }
26
+ if (text.length <= MAX_ARGUMENTS_LENGTH)
27
+ return text;
28
+ // Cut before a surrogate pair rather than through it, so the text stays valid UTF-16.
29
+ const high = text.charCodeAt(MAX_ARGUMENTS_LENGTH - 1);
30
+ const end = high >= 0xd800 && high <= 0xdbff ? MAX_ARGUMENTS_LENGTH - 1 : MAX_ARGUMENTS_LENGTH;
31
+ return `${text.slice(0, end)}… (${text.length - end} more characters)`;
32
+ }
33
+ const NOT_RUN = {
34
+ run_aborted: (tool) => `Tool "${tool}" was not run, because the run was cancelled.`,
35
+ sibling_failed: (tool) => `Tool "${tool}" was not run, because another call in the same step failed with an error in the tool itself.`,
36
+ response_error: (tool) => `Tool "${tool}" was not run, because the response ended with an error before it was complete. Re-issue the ` +
37
+ "call if it is still needed.",
38
+ response_aborted: (tool) => `Tool "${tool}" was not run, because the response was stopped before it was complete. Re-issue the call if it ` +
39
+ "is still needed.",
40
+ };
41
+ function issueLine(issue) {
42
+ return `- ${issue.path === "" ? "(the whole input)" : issue.path}: ${issue.message}`;
43
+ }
44
+ function describe(failure) {
45
+ switch (failure.kind) {
46
+ case "unknown_tool": {
47
+ const tools = failure.availableTools.length === 0 ? "none" : failure.availableTools.join(", ");
48
+ return `There is no tool named "${failure.tool}". The available tools are: ${tools}.`;
49
+ }
50
+ case "invalid_input":
51
+ return [`The arguments for tool "${failure.tool}" are invalid:`, ...failure.issues.map(issueLine)].join("\n");
52
+ case "execution_error":
53
+ return `Tool "${failure.tool}" failed: ${failure.message}`;
54
+ case "truncated":
55
+ return (`Tool "${failure.tool}" was not run, because the response was cut off at the output limit before the ` +
56
+ "call's arguments were complete. Re-issue the call with complete arguments, in a shorter response.");
57
+ case "not_run":
58
+ return NOT_RUN[failure.reason](failure.tool);
59
+ }
60
+ }
61
+ /** The default content for a failed tool call: what failed, the received arguments, and the do-not-substitute line. */
62
+ export function formatToolError(failure) {
63
+ const text = [describe(failure), `Received arguments: ${showArguments(failure.input)}`, DO_NOT_SUBSTITUTE].join("\n");
64
+ return [{ type: "text", text }];
65
+ }
66
+ //# sourceMappingURL=format-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format-error.js","sourceRoot":"","sources":["../../src/tools/format-error.ts"],"names":[],"mappings":"AAQA,sDAAsD;AACtD,MAAM,CAAC,MAAM,iBAAiB,GAC5B,6GAA6G;IAC7G,yCAAyC,CAAC;AAE5C,sFAAsF;AACtF,MAAM,CAAC,MAAM,gBAAgB,GAAG,8BAA8B,CAAC;AAE/D,yGAAyG;AACzG,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAElC,qGAAqG;AACrG,SAAS,WAAW,CAAC,KAAc;IACjC,IAAI,CAAC;QACH,OAAO,MAA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IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;AAClC,CAAC","sourcesContent":["/**\n * The default error text the model reads for a failed tool call. Every message says what failed, shows the\n * arguments the model sent, and tells the model not to answer the failure with invented data, because agents have\n * been seen to \"make a mock implementation\" when a tool fails (agent-SDK guide §4).\n */\nimport type { ModelContent } from \"@buildanagent/gateway\";\nimport type { SchemaIssue, ToolFailure } from \"./types.js\";\n\n/** The line every default error message ends with. */\nexport const DO_NOT_SUBSTITUTE =\n \"Do not substitute a mock, a placeholder or invented data for this tool's result. Fix the call, try another \" +\n \"approach, or tell the user what failed.\";\n\n/** The fixed line a redacted error shows the model in place of the thrown message. */\nexport const REDACTED_MESSAGE = \"its error message is hidden.\";\n\n// Received arguments are shown up to this many characters, so one huge argument can't flood the context.\nconst MAX_ARGUMENTS_LENGTH = 2000;\n\n// `String()` can itself throw, on an object with no prototype, so the last resort is the object tag.\nfunction plainString(input: unknown): string {\n try {\n return String(input);\n } catch {\n return Object.prototype.toString.call(input);\n }\n}\n\nfunction showArguments(input: unknown): string {\n let text: string;\n try {\n text = JSON.stringify(input) ?? plainString(input);\n } catch {\n // Input from a test double or a tool bridge may hold a cycle or a bigint, which JSON can't encode.\n text = plainString(input);\n }\n if (text.length <= MAX_ARGUMENTS_LENGTH) return text;\n // Cut before a surrogate pair rather than through it, so the text stays valid UTF-16.\n const high = text.charCodeAt(MAX_ARGUMENTS_LENGTH - 1);\n const end = high >= 0xd800 && high <= 0xdbff ? MAX_ARGUMENTS_LENGTH - 1 : MAX_ARGUMENTS_LENGTH;\n return `${text.slice(0, end)}… (${text.length - end} more characters)`;\n}\n\nconst NOT_RUN = {\n run_aborted: (tool: string) => `Tool \"${tool}\" was not run, because the run was cancelled.`,\n sibling_failed: (tool: string) =>\n `Tool \"${tool}\" was not run, because another call in the same step failed with an error in the tool itself.`,\n response_error: (tool: string) =>\n `Tool \"${tool}\" was not run, because the response ended with an error before it was complete. Re-issue the ` +\n \"call if it is still needed.\",\n response_aborted: (tool: string) =>\n `Tool \"${tool}\" was not run, because the response was stopped before it was complete. Re-issue the call if it ` +\n \"is still needed.\",\n} as const;\n\nfunction issueLine(issue: SchemaIssue): string {\n return `- ${issue.path === \"\" ? \"(the whole input)\" : issue.path}: ${issue.message}`;\n}\n\nfunction describe(failure: ToolFailure): string {\n switch (failure.kind) {\n case \"unknown_tool\": {\n const tools = failure.availableTools.length === 0 ? \"none\" : failure.availableTools.join(\", \");\n return `There is no tool named \"${failure.tool}\". The available tools are: ${tools}.`;\n }\n case \"invalid_input\":\n return [`The arguments for tool \"${failure.tool}\" are invalid:`, ...failure.issues.map(issueLine)].join(\"\\n\");\n case \"execution_error\":\n return `Tool \"${failure.tool}\" failed: ${failure.message}`;\n case \"truncated\":\n return (\n `Tool \"${failure.tool}\" was not run, because the response was cut off at the output limit before the ` +\n \"call's arguments were complete. Re-issue the call with complete arguments, in a shorter response.\"\n );\n case \"not_run\":\n return NOT_RUN[failure.reason](failure.tool);\n }\n}\n\n/** The default content for a failed tool call: what failed, the received arguments, and the do-not-substitute line. */\nexport function formatToolError(failure: ToolFailure): ModelContent[] {\n const text = [describe(failure), `Received arguments: ${showArguments(failure.input)}`, DO_NOT_SUBSTITUTE].join(\"\\n\");\n return [{ type: \"text\", text }];\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import type { ToolResult } from "./types.js";
2
+ /**
3
+ * Puts a result's write outcome in front of the content the model reads, and sets `isError` for every kind except
4
+ * `applied`. A result without an outcome comes back unchanged. Throws an `SdkError`, code `invalid_tool_result`,
5
+ * when the outcome breaks a rule.
6
+ */
7
+ export declare function withOutcome<S>(tool: string, result: ToolResult<S>): ToolResult<S>;
@@ -0,0 +1,30 @@
1
+ import { SdkError } from "../errors.js";
2
+ import { isSafetyError } from "../vendor/agent-safety/errors.js";
3
+ import { renderOutcome } from "../vendor/agent-safety/render.js";
4
+ function render(tool, outcome) {
5
+ try {
6
+ // The outcome is checked again here, so one built by hand or revived from JSON follows the same rules.
7
+ return renderOutcome(outcome);
8
+ }
9
+ catch (cause) {
10
+ const reason = isSafetyError(cause) ? cause.message : String(cause);
11
+ throw new SdkError("invalid_tool_result", `tool "${tool}" returned an invalid write outcome: ${reason}`, { cause });
12
+ }
13
+ }
14
+ /**
15
+ * Puts a result's write outcome in front of the content the model reads, and sets `isError` for every kind except
16
+ * `applied`. A result without an outcome comes back unchanged. Throws an `SdkError`, code `invalid_tool_result`,
17
+ * when the outcome breaks a rule.
18
+ */
19
+ export function withOutcome(tool, result) {
20
+ if (result.outcome === undefined)
21
+ return result;
22
+ const rendered = render(tool, result.outcome);
23
+ const content = [
24
+ { type: "text", text: rendered.text },
25
+ { type: "text", text: JSON.stringify({ outcome: rendered.payload }) },
26
+ ...result.content,
27
+ ];
28
+ return { ...result, content, isError: result.isError === true || rendered.isError };
29
+ }
30
+ //# sourceMappingURL=outcome.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outcome.js","sourceRoot":"","sources":["../../src/tools/outcome.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAC;AAEjE,OAAO,EAAwB,aAAa,EAAE,MAAM,kCAAkC,CAAC;AAGvF,SAAS,MAAM,CAAC,IAAY,EAAE,OAAqB;IACjD,IAAI,CAAC;QACH,uGAAuG;QACvG,OAAO,aAAa,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,MAAM,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACpE,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,SAAS,IAAI,wCAAwC,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;IACtH,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAI,IAAY,EAAE,MAAqB;IAChE,IAAI,MAAM,CAAC,OAAO,KAAK,SAAS;QAAE,OAAO,MAAM,CAAC;IAChD,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IAC9C,MAAM,OAAO,GAAmB;QAC9B,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE;QACrC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,EAAE;QACrE,GAAG,MAAM,CAAC,OAAO;KAClB,CAAC;IACF,OAAO,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,KAAK,IAAI,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;AACtF,CAAC","sourcesContent":["/**\n * Write outcomes in tool results. The outcome's sentence and fields go first in the content the model reads, and\n * any kind except `applied` sets `isError`. The outcome travels in the result body as well as in the error flag,\n * because some adapters drop the flag (close-sdk-gaps SG3).\n */\nimport type { ModelContent } from \"@buildanagent/gateway\";\nimport { SdkError } from \"../errors.js\";\nimport { isSafetyError } from \"../vendor/agent-safety/errors.js\";\nimport type { WriteOutcome } from \"../vendor/agent-safety/outcome.js\";\nimport { type RenderedOutcome, renderOutcome } from \"../vendor/agent-safety/render.js\";\nimport type { ToolResult } from \"./types.js\";\n\nfunction render(tool: string, outcome: WriteOutcome): RenderedOutcome {\n try {\n // The outcome is checked again here, so one built by hand or revived from JSON follows the same rules.\n return renderOutcome(outcome);\n } catch (cause) {\n const reason = isSafetyError(cause) ? cause.message : String(cause);\n throw new SdkError(\"invalid_tool_result\", `tool \"${tool}\" returned an invalid write outcome: ${reason}`, { cause });\n }\n}\n\n/**\n * Puts a result's write outcome in front of the content the model reads, and sets `isError` for every kind except\n * `applied`. A result without an outcome comes back unchanged. Throws an `SdkError`, code `invalid_tool_result`,\n * when the outcome breaks a rule.\n */\nexport function withOutcome<S>(tool: string, result: ToolResult<S>): ToolResult<S> {\n if (result.outcome === undefined) return result;\n const rendered = render(tool, result.outcome);\n const content: ModelContent[] = [\n { type: \"text\", text: rendered.text },\n { type: \"text\", text: JSON.stringify({ outcome: rendered.payload }) },\n ...result.content,\n ];\n return { ...result, content, isError: result.isError === true || rendered.isError };\n}\n"]}
@@ -0,0 +1,111 @@
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 runs after validation and `after` runs after `execute`. The run's interceptors fill them (`beforeToolCall`
8
+ * and `afterToolCall`), and a pipeline without them allows every call and keeps every result. A step's calls are
9
+ * checked and gated one at a time, in model order, and then scheduled together (see `runCalls`).
10
+ */
11
+ import type { AssistantMessage, ModelContent } from "@buildanagent/gateway";
12
+ import type { Clock } from "../testing/determinism.js";
13
+ import type { SignedPendingRequest } from "../vendor/agent-safety/pending.js";
14
+ import type { ToolCall, ToolDefinition, ToolResult } from "./types.js";
15
+ /** A tool of any input and structured type, as the pipeline holds it. */
16
+ export type AnyTool = ToolDefinition<unknown, unknown>;
17
+ /** What the pipeline needs from the run around it. */
18
+ export interface PipelineContext {
19
+ readonly runId: string;
20
+ readonly signal: AbortSignal;
21
+ readonly depth: number;
22
+ readonly maxDepth: number;
23
+ readonly clock: Clock;
24
+ /**
25
+ * The gate: asked once for each call that passed validation, one call at a time in model order, and before any call
26
+ * of the step executes. It returns `{ blocked }` to stop the call with that result, `{ paused, input }` to hold the
27
+ * call for a person with no result at all, with the signed request and the input it signs, `{ input }` to run it
28
+ * with another input, which must pass the tool's schema, or `undefined` to let it run as it is. Without a gate every
29
+ * call is allowed.
30
+ */
31
+ gate?(e: {
32
+ readonly call: ToolCall;
33
+ readonly tool: AnyTool;
34
+ readonly input: unknown;
35
+ }): Promise<GateOutcome | undefined>;
36
+ /**
37
+ * Called with the result of each call that executed, and returns the result to use in its place. It runs inside the
38
+ * call's own task, so a sibling is never left running while it works, and a programmer error it throws cancels the
39
+ * siblings like one from `execute`.
40
+ */
41
+ after?(e: {
42
+ readonly call: ToolCall;
43
+ readonly tool: AnyTool;
44
+ readonly input: unknown;
45
+ readonly result: ToolResult;
46
+ }): Promise<ToolResult>;
47
+ /** Called for each call of a message before its result is worked out, whether or not the call will run. */
48
+ onStart?(call: ToolCall): void;
49
+ /** Receives a tool's progress updates. */
50
+ onUpdate?(callId: string, details: unknown): void;
51
+ /**
52
+ * Receives each call's result as soon as `runToolCalls` has it, so the run can record a write before a later call
53
+ * in the same message throws.
54
+ */
55
+ onResult?(entry: ToolCallResult): void;
56
+ /**
57
+ * Receives each call the gate paused, with its signed request and the input that request signs, in model order and
58
+ * only once every call of the message has been gated.
59
+ */
60
+ onPause?(entry: PausedCall): void;
61
+ /**
62
+ * Called as soon as a tool's `execute` returns or throws, before the result is checked, so the run knows a write
63
+ * may have happened even when its result then throws an `SdkError`.
64
+ */
65
+ onExecuted?(call: ToolCall): void;
66
+ /**
67
+ * True when every call already holds the input a verified approval signed: each runs with that input exactly, once
68
+ * it still passes the tool's schema, and no gate is asked. Coercion and `repair` are skipped, because they ran
69
+ * before the input was signed.
70
+ */
71
+ readonly approved?: boolean;
72
+ }
73
+ /** What a gate decides besides letting a call run unchanged. */
74
+ export type GateOutcome = {
75
+ readonly blocked: ToolResult;
76
+ } | {
77
+ readonly paused: SignedPendingRequest;
78
+ readonly input: unknown;
79
+ } | {
80
+ readonly input: unknown;
81
+ };
82
+ /** A tool call a gate paused: its signed request, and the input the request signs. */
83
+ export interface PausedCall {
84
+ readonly call: ToolCall;
85
+ readonly request: SignedPendingRequest;
86
+ readonly input: unknown;
87
+ }
88
+ /** One tool call and the result the model will read for it. */
89
+ export interface ToolCallResult {
90
+ readonly call: ToolCall;
91
+ readonly result: ToolResult;
92
+ /** The input the gate put in place of the model's, present only when the gate replaced it. */
93
+ readonly input?: unknown;
94
+ /** The input the call executed with, present only for a call that executed. */
95
+ readonly ranWith?: unknown;
96
+ }
97
+ /** True for a list of text and image blocks, the only content a tool result may carry. */
98
+ export declare function isContentList(content: unknown): content is readonly ModelContent[];
99
+ /**
100
+ * Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure
101
+ * the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws
102
+ * an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.
103
+ */
104
+ export declare function runToolCall(call: ToolCall, tools: readonly AnyTool[], ctx: PipelineContext): Promise<ToolResult>;
105
+ /**
106
+ * Runs every tool call of an assistant message and passes each result to `ctx.onResult` in model order. A message
107
+ * that stopped at the output limit (`stopReason: "length"`) runs nothing: each of its calls gets an error asking the
108
+ * model to re-issue it, because its arguments may be cut short. A message that ended in an error or was aborted also
109
+ * runs nothing, because its calls may be partial. Otherwise the calls are scheduled as `runCalls` describes.
110
+ */
111
+ export declare function runToolCalls(message: AssistantMessage, tools: readonly AnyTool[], ctx: PipelineContext): Promise<ToolCallResult[]>;