@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.
- package/README.md +88 -2
- package/dist/errors.d.ts +19 -0
- package/dist/errors.js +26 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +7 -3
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/tools/coerce.d.ts +15 -0
- package/dist/tools/coerce.js +93 -0
- package/dist/tools/coerce.js.map +1 -0
- package/dist/tools/define.d.ts +42 -0
- package/dist/tools/define.js +96 -0
- package/dist/tools/define.js.map +1 -0
- package/dist/tools/format-error.d.ts +13 -0
- package/dist/tools/format-error.js +65 -0
- package/dist/tools/format-error.js.map +1 -0
- package/dist/tools/outcome.d.ts +7 -0
- package/dist/tools/outcome.js +30 -0
- package/dist/tools/outcome.js.map +1 -0
- package/dist/tools/pipeline.d.ts +52 -0
- package/dist/tools/pipeline.js +184 -0
- package/dist/tools/pipeline.js.map +1 -0
- package/dist/tools/schema.d.ts +20 -0
- package/dist/tools/schema.js +100 -0
- package/dist/tools/schema.js.map +1 -0
- package/dist/tools/types.d.ts +144 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/vendor/agent-safety/errors.d.ts +14 -0
- package/dist/vendor/agent-safety/errors.js +21 -0
- package/dist/vendor/agent-safety/errors.js.map +1 -0
- package/dist/vendor/agent-safety/outcome.d.ts +88 -0
- package/dist/vendor/agent-safety/outcome.js +140 -0
- package/dist/vendor/agent-safety/outcome.js.map +1 -0
- package/dist/vendor/agent-safety/render.d.ts +40 -0
- package/dist/vendor/agent-safety/render.js +92 -0
- package/dist/vendor/agent-safety/render.js.map +1 -0
- package/package.json +11 -3
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
The SDK runs your agent's loop over [`@buildanagent/gateway`](../gateway/README.md): it calls the model, runs the tools the model asks for, and stops when the work is done. Its testing export lets you test that agent offline against a scripted model, with no API key.
|
|
4
4
|
|
|
5
|
-
As of November 2026 the package holds
|
|
5
|
+
As of November 2026 the package holds tool definitions and the testing export. You can define your tools and their rules now; the loop that calls the model and runs them comes next, with hooks, approvals and budgets.
|
|
6
6
|
|
|
7
7
|
## Install the alpha with `pnpm add @buildanagent/sdk@alpha`
|
|
8
8
|
|
|
@@ -12,7 +12,93 @@ Every release is an alpha until the first stable one, and npm serves the alphas
|
|
|
12
12
|
pnpm add @buildanagent/sdk@alpha @buildanagent/gateway@alpha
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
Both packages always share one version, and the SDK depends on that exact version of the gateway. Name the tag: a plain `pnpm add @buildanagent/sdk` installs `0.0.0-bootstrap.0`, a deprecated placeholder, because `latest` stays on it until the first stable release. The package needs Node 22 or later.
|
|
15
|
+
Both packages always share one version, and the SDK depends on that exact version of the gateway. Name the tag: a plain `pnpm add @buildanagent/sdk` installs `0.0.0-bootstrap.0`, a deprecated placeholder, because `latest` stays on it until the first stable release. The package needs Node 22.19 or later, the oldest Node its validator, pi-schema 1.5.2, supports.
|
|
16
|
+
|
|
17
|
+
Don't start Node with `--conditions=source` in a project that installs the SDK. Its validator, pi-schema 1.5.2, maps that condition to a source file its package doesn't ship, so the SDK's root entry fails to load under it ([validator check](docs/validator-check.md)).
|
|
18
|
+
|
|
19
|
+
## Define a tool with `defineTool()`
|
|
20
|
+
|
|
21
|
+
A tool is a name, a description the model reads, an input schema and an `execute` function. This tool looks up an order in your own store:
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
export function lookupOrderTool(findOrder: FindOrder) {
|
|
25
|
+
return defineTool({
|
|
26
|
+
name: "lookup_order",
|
|
27
|
+
description: "Look up an order by its number and return its status.",
|
|
28
|
+
inputSchema: z.object({ order: z.number().int().positive() }),
|
|
29
|
+
async execute({ order }) {
|
|
30
|
+
const found = await findOrder(order);
|
|
31
|
+
if (found === undefined) return { content: [{ type: "text", text: `No order ${order} exists.` }], isError: true };
|
|
32
|
+
return { content: [{ type: "text", text: `Order ${order} is ${found.status}.` }], structured: found };
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The input schema is either a Standard Schema or a raw JSON Schema object. A Standard Schema is a schema from a library that can also describe itself as JSON Schema: Zod 4.2 or later, ArkType, or Valibot through `toStandardJsonSchema()` from `@valibot/to-json-schema`. A raw schema follows draft 2020-12, or draft 7 when its `$schema` names draft 7. Raw schemas check `format` keywords such as `email` and `date`.
|
|
39
|
+
|
|
40
|
+
`execute` receives the validated input and returns a tool result with three channels:
|
|
41
|
+
|
|
42
|
+
- **`content`** is the text and images the model reads.
|
|
43
|
+
- **`details`** is for your logs and user interface; the model never sees it.
|
|
44
|
+
- **`structured`** is typed data for your code, such as the order above.
|
|
45
|
+
|
|
46
|
+
`defineTool()` checks the tool once, when you call it. A name outside the tool-name rule, 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`, throws an `SdkError`. So does a schema that does not compile.
|
|
47
|
+
|
|
48
|
+
## A failed call becomes an error the model can fix
|
|
49
|
+
|
|
50
|
+
Every tool call runs the same steps in order: find the tool by name, coerce the arguments, validate them, give `repair` one chance, then run `execute`. A failure the model caused, at any step, returns an error result to the model and throws nothing. When the model sends `"forty-two"` as the order number, it reads this:
|
|
51
|
+
|
|
52
|
+
```text
|
|
53
|
+
The arguments for tool "lookup_order" are invalid:
|
|
54
|
+
- /order: Invalid input: expected number, received string
|
|
55
|
+
Received arguments: {"order":"forty-two"}
|
|
56
|
+
Do not substitute a mock, a placeholder or invented data for this tool's result. Fix the call, try another approach, or tell the user what failed.
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Each failing field appears as its JSON Pointer path, so the model knows exactly what to fix. The last line is there because agents have been seen to answer a failed tool by inventing a result. Three options on the tool and one flag on your own result change what happens:
|
|
60
|
+
|
|
61
|
+
- **`repair`** receives invalid input and its issues, and returns fixed input to validate again, or `undefined` to report the failure.
|
|
62
|
+
- **`formatError`** builds the model's content for a failed call in place of the default text.
|
|
63
|
+
- **`redactErrors: true`** shows the model a fixed line when `execute` throws, and keeps the thrown message in the result's `details`. Use it when error messages may hold secrets, such as connection strings.
|
|
64
|
+
- **`isError: true`** on your own result marks a failure you report yourself, such as an order that doesn't exist.
|
|
65
|
+
|
|
66
|
+
The model also sees an error for a tool name that doesn't exist, with the list of real ones. A response that stopped at its output limit runs none of its tool calls, because their arguments may be cut short; the model is asked to send each call again. A response that ended in an error or was aborted runs none of its calls either, and once the run is cancelled no further call starts.
|
|
67
|
+
|
|
68
|
+
## Arguments are coerced by three rules
|
|
69
|
+
|
|
70
|
+
Models sometimes send a number as a string. Before validation, the SDK converts these values, and nothing else:
|
|
71
|
+
|
|
72
|
+
1. A string holding JSON becomes the object or array it encodes, where the schema expects an object or an array.
|
|
73
|
+
2. A string holding a decimal number becomes that number, where the schema expects a number, or an integer when the number is whole. A whole number beyond 2^53 stays a string, because JavaScript would round it to a different number.
|
|
74
|
+
3. The string `"true"` or `"false"` becomes a boolean, where the schema expects a boolean.
|
|
75
|
+
|
|
76
|
+
The rules reach nested values through `properties` and `items`, and only where the schema names a single type. A value that already has the expected type is never changed.
|
|
77
|
+
|
|
78
|
+
## Report what a write did with an outcome
|
|
79
|
+
|
|
80
|
+
A tool that changes the world, such as a refund, declares `effect: { kind: "write" }`. A tool without it counts as read-only, so it is safe to run again after a crash. The optional `businessKey` names the real-world operation, such as `refund:42`, so a retry is recognised as the same refund.
|
|
81
|
+
|
|
82
|
+
Such a tool returns an `outcome` beside its content. An outcome says which of five things happened: `applied`, `not_applied`, `compensated`, `partial` or `unknown`. It also says what the model should do next and whether a retry is safe. This refund tool reports a declined refund:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
return { ...base, kind: "not_applied", retry: "never", applied: [], reason: reply.code, next };
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The model reads the outcome first, as a sentence and as JSON, and then your content. For the declined refund the sentence begins "The refund_create call did not take effect, and nothing changed." Every kind except `applied` marks the result as an error. An outcome that breaks a rule, such as a retry its kind doesn't allow, throws an `SdkError`.
|
|
89
|
+
|
|
90
|
+
## End the run with `outputTool()`, or ask with `clarificationTool()`
|
|
91
|
+
|
|
92
|
+
`outputTool({ name, schema })` turns the run's final answer into a tool call. A call whose input passes the schema ends the run, and the validated answer is the result's `structured` value. A call that fails the schema returns the issues to the model, which can correct its answer and call again.
|
|
93
|
+
|
|
94
|
+
`clarificationTool()` gives the model a tool named `ask_user` that takes one `question`. Its result carries the question as a pause, so the run can wait for the user's answer. Pass `{ name }` to call it something else.
|
|
95
|
+
|
|
96
|
+
## `SdkError` marks a mistake in your code
|
|
97
|
+
|
|
98
|
+
The SDK throws only for programmer errors, never for a failure the model caused. `isSdkError(error)` recognises the error, and its `code` says why:
|
|
99
|
+
|
|
100
|
+
- **`invalid_tool_definition`**: a tool's name, description or schema is unusable, or two tools share a name.
|
|
101
|
+
- **`invalid_tool_result`**: `execute` returned something other than a tool result, or an invalid outcome. A text block needs a string `text`, and an image block a string `mediaType` and `data`.
|
|
16
102
|
|
|
17
103
|
## Test against a strict scripted model
|
|
18
104
|
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool
|
|
3
|
+
* that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never
|
|
4
|
+
* thrown: the tool pipeline returns it to the model as an error result.
|
|
5
|
+
*/
|
|
6
|
+
/** Why an `SdkError` was thrown. */
|
|
7
|
+
export type SdkErrorCode = "invalid_tool_definition" | "invalid_tool_result";
|
|
8
|
+
/**
|
|
9
|
+
* Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description or schema
|
|
10
|
+
* is unusable, or two tools share a name. `invalid_tool_result`: a tool's `execute` returned a malformed result or
|
|
11
|
+
* write outcome.
|
|
12
|
+
*/
|
|
13
|
+
export declare class SdkError extends Error {
|
|
14
|
+
readonly name = "SdkError";
|
|
15
|
+
readonly code: SdkErrorCode;
|
|
16
|
+
constructor(code: SdkErrorCode, message: string, options?: ErrorOptions);
|
|
17
|
+
}
|
|
18
|
+
/** True for an `SdkError`, including one from another copy of the package. */
|
|
19
|
+
export declare function isSdkError(error: unknown): error is SdkError;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool
|
|
3
|
+
* that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never
|
|
4
|
+
* thrown: the tool pipeline returns it to the model as an error result.
|
|
5
|
+
*/
|
|
6
|
+
// A registered symbol, so the guard still works when two copies of the package are bundled.
|
|
7
|
+
const SDK_ERROR = Symbol.for("buildanagent.sdk.SdkError");
|
|
8
|
+
/**
|
|
9
|
+
* Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description or schema
|
|
10
|
+
* is unusable, or two tools share a name. `invalid_tool_result`: a tool's `execute` returned a malformed result or
|
|
11
|
+
* write outcome.
|
|
12
|
+
*/
|
|
13
|
+
export class SdkError extends Error {
|
|
14
|
+
name = "SdkError";
|
|
15
|
+
code;
|
|
16
|
+
constructor(code, message, options) {
|
|
17
|
+
super(message, options);
|
|
18
|
+
this.code = code;
|
|
19
|
+
Object.defineProperty(this, SDK_ERROR, { value: true });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** True for an `SdkError`, including one from another copy of the package. */
|
|
23
|
+
export function isSdkError(error) {
|
|
24
|
+
return typeof error === "object" && error !== null && error[SDK_ERROR] === true;
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAKH,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D;;;;GAIG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACf,IAAI,GAAG,UAAU,CAAC;IAC3B,IAAI,CAAe;IAE5B,YAAY,IAAkB,EAAE,OAAe,EAAE,OAAsB;QACrE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1D,CAAC;CACF;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;AAC/G,CAAC","sourcesContent":["/**\n * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool\n * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never\n * thrown: the tool pipeline returns it to the model as an error result.\n */\n\n/** Why an `SdkError` was thrown. */\nexport type SdkErrorCode = \"invalid_tool_definition\" | \"invalid_tool_result\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SDK_ERROR = Symbol.for(\"buildanagent.sdk.SdkError\");\n\n/**\n * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description or schema\n * is unusable, or two tools share a name. `invalid_tool_result`: a tool's `execute` returned a malformed result or\n * write outcome.\n */\nexport class SdkError extends Error {\n override readonly name = \"SdkError\";\n readonly code: SdkErrorCode;\n\n constructor(code: SdkErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SDK_ERROR, { value: true });\n }\n}\n\n/** True for an `SdkError`, including one from another copy of the package. */\nexport function isSdkError(error: unknown): error is SdkError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SDK_ERROR] === true;\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`.
|
|
3
|
-
*
|
|
4
|
-
* The loop, tools, hooks, signed pauses and budgets are planned in the SDK plan §3.3.
|
|
2
|
+
* `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the tools: their definitions,
|
|
3
|
+
* schemas, results and write outcomes. The loop, hooks, signed pauses and budgets are planned in the SDK plan §3.3.
|
|
5
4
|
*/
|
|
5
|
+
export { isSdkError, SdkError, type SdkErrorCode } from "./errors.js";
|
|
6
|
+
export { type ClarificationToolOptions, clarificationTool, defineTool, type OutputToolOptions, outputTool, } from "./tools/define.js";
|
|
7
|
+
export type { JsonSchema, SchemaIssue, ToolContext, ToolDefinition, ToolEffect, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
|
|
8
|
+
export type { WriteOutcome } from "./vendor/agent-safety/outcome.js";
|
|
9
|
+
/** The package's name, `@buildanagent/sdk`. */
|
|
6
10
|
export declare const SDK_PACKAGE = "@buildanagent/sdk";
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`.
|
|
3
|
-
*
|
|
4
|
-
* The loop, tools, hooks, signed pauses and budgets are planned in the SDK plan §3.3.
|
|
2
|
+
* `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the tools: their definitions,
|
|
3
|
+
* schemas, results and write outcomes. The loop, hooks, signed pauses and budgets are planned in the SDK plan §3.3.
|
|
5
4
|
*/
|
|
5
|
+
export { isSdkError, SdkError } from "./errors.js";
|
|
6
|
+
export { clarificationTool, defineTool, outputTool, } from "./tools/define.js";
|
|
7
|
+
/** The package's name, `@buildanagent/sdk`. */
|
|
6
8
|
export const SDK_PACKAGE = "@buildanagent/sdk";
|
|
7
9
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AACtE,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,UAAU,GACX,MAAM,mBAAmB,CAAC;AAa3B,+CAA+C;AAC/C,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the tools: their definitions,\n * schemas, results and write outcomes. The loop, hooks, signed pauses and budgets are planned in the SDK plan §3.3.\n */\nexport { isSdkError, SdkError, type SdkErrorCode } from \"./errors.js\";\nexport {\n type ClarificationToolOptions,\n clarificationTool,\n defineTool,\n type OutputToolOptions,\n outputTool,\n} from \"./tools/define.js\";\nexport type {\n JsonSchema,\n SchemaIssue,\n ToolContext,\n ToolDefinition,\n ToolEffect,\n ToolFailure,\n ToolResult,\n ToolSchema,\n} from \"./tools/types.js\";\nexport type { WriteOutcome } from \"./vendor/agent-safety/outcome.js\";\n\n/** The package's name, `@buildanagent/sdk`. */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coercion: the few conversions the pipeline makes to a model's tool arguments before validation (D7 keeps coercion
|
|
3
|
+
* our own step, not the validator's). The rules stay minimal and the SDK README lists them:
|
|
4
|
+
*
|
|
5
|
+
* 1. A string that holds JSON becomes the object or array it encodes, where the schema's `type` is `object` or
|
|
6
|
+
* `array`.
|
|
7
|
+
* 2. A string that holds a decimal number becomes that number, where the `type` is `number`, or `integer` when the
|
|
8
|
+
* number is whole. A whole number outside the safe integer range (beyond 2^53) stays a string.
|
|
9
|
+
* 3. The string `"true"` or `"false"` becomes a boolean, where the `type` is `boolean`.
|
|
10
|
+
*
|
|
11
|
+
* The rules reach nested values through `properties` and `items` only, and only where `type` is a single string.
|
|
12
|
+
* They never change a value that already has the schema's type, and they never modify the input.
|
|
13
|
+
*/
|
|
14
|
+
/** Applies the coercion rules to `value` under `schema`, returning `value` itself when no rule applies. */
|
|
15
|
+
export declare function coerceValue(value: unknown, schema: unknown): unknown;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coercion: the few conversions the pipeline makes to a model's tool arguments before validation (D7 keeps coercion
|
|
3
|
+
* our own step, not the validator's). The rules stay minimal and the SDK README lists them:
|
|
4
|
+
*
|
|
5
|
+
* 1. A string that holds JSON becomes the object or array it encodes, where the schema's `type` is `object` or
|
|
6
|
+
* `array`.
|
|
7
|
+
* 2. A string that holds a decimal number becomes that number, where the `type` is `number`, or `integer` when the
|
|
8
|
+
* number is whole. A whole number outside the safe integer range (beyond 2^53) stays a string.
|
|
9
|
+
* 3. The string `"true"` or `"false"` becomes a boolean, where the `type` is `boolean`.
|
|
10
|
+
*
|
|
11
|
+
* The rules reach nested values through `properties` and `items` only, and only where `type` is a single string.
|
|
12
|
+
* They never change a value that already has the schema's type, and they never modify the input.
|
|
13
|
+
*/
|
|
14
|
+
const DECIMAL = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
|
|
15
|
+
function isRecord(value) {
|
|
16
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
function parseJson(text) {
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(text);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// Not JSON: the value stays a string, and validation reports it.
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function coerceObject(value, schema) {
|
|
28
|
+
const parsed = typeof value === "string" ? parseJson(value) : value;
|
|
29
|
+
const object = isRecord(parsed) ? parsed : undefined;
|
|
30
|
+
if (object === undefined)
|
|
31
|
+
return value;
|
|
32
|
+
const properties = isRecord(schema.properties) ? schema.properties : {};
|
|
33
|
+
let copy;
|
|
34
|
+
for (const [key, child] of Object.entries(properties)) {
|
|
35
|
+
if (!Object.hasOwn(object, key))
|
|
36
|
+
continue;
|
|
37
|
+
const coerced = coerceValue(object[key], child);
|
|
38
|
+
if (coerced === object[key])
|
|
39
|
+
continue;
|
|
40
|
+
copy ??= { ...object };
|
|
41
|
+
copy[key] = coerced;
|
|
42
|
+
}
|
|
43
|
+
return copy ?? object;
|
|
44
|
+
}
|
|
45
|
+
function coerceArray(value, schema) {
|
|
46
|
+
const parsed = typeof value === "string" ? parseJson(value) : value;
|
|
47
|
+
if (!Array.isArray(parsed))
|
|
48
|
+
return value;
|
|
49
|
+
if (!isRecord(schema.items))
|
|
50
|
+
return parsed;
|
|
51
|
+
const items = schema.items;
|
|
52
|
+
const coerced = parsed.map((item) => coerceValue(item, items));
|
|
53
|
+
return coerced.some((item, index) => item !== parsed[index]) ? coerced : parsed;
|
|
54
|
+
}
|
|
55
|
+
function coerceNumber(value, integer) {
|
|
56
|
+
if (typeof value !== "string" || !DECIMAL.test(value))
|
|
57
|
+
return value;
|
|
58
|
+
const number = Number(value);
|
|
59
|
+
if (!Number.isFinite(number) || (integer && !Number.isInteger(number)))
|
|
60
|
+
return value;
|
|
61
|
+
// A whole number past 2^53 would come out as a different number, such as another order's id, so it stays a string
|
|
62
|
+
// and validation reports it.
|
|
63
|
+
if (Number.isInteger(number) && !Number.isSafeInteger(number))
|
|
64
|
+
return value;
|
|
65
|
+
return number;
|
|
66
|
+
}
|
|
67
|
+
function coerceBoolean(value) {
|
|
68
|
+
if (value === "true")
|
|
69
|
+
return true;
|
|
70
|
+
if (value === "false")
|
|
71
|
+
return false;
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
/** Applies the coercion rules to `value` under `schema`, returning `value` itself when no rule applies. */
|
|
75
|
+
export function coerceValue(value, schema) {
|
|
76
|
+
if (!isRecord(schema) || typeof schema.type !== "string")
|
|
77
|
+
return value;
|
|
78
|
+
switch (schema.type) {
|
|
79
|
+
case "object":
|
|
80
|
+
return coerceObject(value, schema);
|
|
81
|
+
case "array":
|
|
82
|
+
return coerceArray(value, schema);
|
|
83
|
+
case "number":
|
|
84
|
+
return coerceNumber(value, false);
|
|
85
|
+
case "integer":
|
|
86
|
+
return coerceNumber(value, true);
|
|
87
|
+
case "boolean":
|
|
88
|
+
return coerceBoolean(value);
|
|
89
|
+
default:
|
|
90
|
+
return value;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=coerce.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coerce.js","sourceRoot":"","sources":["../../src/tools/coerce.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,MAAM,OAAO,GAAG,+CAA+C,CAAC;AAEhE,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,SAAS,CAAC,IAAY;IAC7B,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,iEAAiE;QACjE,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,SAAS,YAAY,CAAC,KAAc,EAAE,MAAc;IAClD,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC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AAM,CAAC,CAAC;QACrC,KAAK,OAAO;YACV,OAAO,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACpC,KAAK,QAAQ;YACX,OAAO,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QACpC,KAAK,SAAS;YACZ,OAAO,YAAY,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACnC,KAAK,SAAS;YACZ,OAAO,aAAa,CAAC,KAAK,CAAC,CAAC;QAC9B;YACE,OAAO,KAAK,CAAC;IACjB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Coercion: the few conversions the pipeline makes to a model's tool arguments before validation (D7 keeps coercion\n * our own step, not the validator's). The rules stay minimal and the SDK README lists them:\n *\n * 1. A string that holds JSON becomes the object or array it encodes, where the schema's `type` is `object` or\n * `array`.\n * 2. A string that holds a decimal number becomes that number, where the `type` is `number`, or `integer` when the\n * number is whole. A whole number outside the safe integer range (beyond 2^53) stays a string.\n * 3. The string `\"true\"` or `\"false\"` becomes a boolean, where the `type` is `boolean`.\n *\n * The rules reach nested values through `properties` and `items` only, and only where `type` is a single string.\n * They never change a value that already has the schema's type, and they never modify the input.\n */\n\ntype Schema = Readonly<Record<string, unknown>>;\n\nconst DECIMAL = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n // Not JSON: the value stays a string, and validation reports it.\n return undefined;\n }\n}\n\nfunction coerceObject(value: unknown, schema: Schema): unknown {\n const parsed = typeof value === \"string\" ? parseJson(value) : value;\n const object = isRecord(parsed) ? parsed : undefined;\n if (object === undefined) return value;\n const properties = isRecord(schema.properties) ? schema.properties : {};\n let copy: Record<string, unknown> | undefined;\n for (const [key, child] of Object.entries(properties)) {\n if (!Object.hasOwn(object, key)) continue;\n const coerced = coerceValue(object[key], child);\n if (coerced === object[key]) continue;\n copy ??= { ...object };\n copy[key] = coerced;\n }\n return copy ?? object;\n}\n\nfunction coerceArray(value: unknown, schema: Schema): unknown {\n const parsed = typeof value === \"string\" ? parseJson(value) : value;\n if (!Array.isArray(parsed)) return value;\n if (!isRecord(schema.items)) return parsed;\n const items = schema.items;\n const coerced = parsed.map((item: unknown) => coerceValue(item, items));\n return coerced.some((item, index) => item !== parsed[index]) ? coerced : parsed;\n}\n\nfunction coerceNumber(value: unknown, integer: boolean): unknown {\n if (typeof value !== \"string\" || !DECIMAL.test(value)) return value;\n const number = Number(value);\n if (!Number.isFinite(number) || (integer && !Number.isInteger(number))) return value;\n // A whole number past 2^53 would come out as a different number, such as another order's id, so it stays a string\n // and validation reports it.\n if (Number.isInteger(number) && !Number.isSafeInteger(number)) return value;\n return number;\n}\n\nfunction coerceBoolean(value: unknown): unknown {\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n return value;\n}\n\n/** Applies the coercion rules to `value` under `schema`, returning `value` itself when no rule applies. */\nexport function coerceValue(value: unknown, schema: unknown): unknown {\n if (!isRecord(schema) || typeof schema.type !== \"string\") return value;\n switch (schema.type) {\n case \"object\":\n return coerceObject(value, schema);\n case \"array\":\n return coerceArray(value, schema);\n case \"number\":\n return coerceNumber(value, false);\n case \"integer\":\n return coerceNumber(value, true);\n case \"boolean\":\n return coerceBoolean(value);\n default:\n return value;\n }\n}\n"]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
import { type PreparedSchema } from "./schema.js";
|
|
3
|
+
import type { ToolDefinition } from "./types.js";
|
|
4
|
+
/**
|
|
5
|
+
* Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code
|
|
6
|
+
* `invalid_tool_definition`, for a bad name, a missing description or `execute`, or an unusable schema.
|
|
7
|
+
*/
|
|
8
|
+
export declare function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>): PreparedSchema;
|
|
9
|
+
/**
|
|
10
|
+
* Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.
|
|
11
|
+
*
|
|
12
|
+
* Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
|
|
13
|
+
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, a raw JSON Schema does not
|
|
14
|
+
* compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe itself as JSON Schema.
|
|
15
|
+
*/
|
|
16
|
+
export declare function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S>;
|
|
17
|
+
/** The options of `outputTool()`. */
|
|
18
|
+
export interface OutputToolOptions<S> {
|
|
19
|
+
readonly name: string;
|
|
20
|
+
/** The schema of the final answer. A Standard Schema that can describe itself as JSON Schema, such as Zod 4.2's. */
|
|
21
|
+
readonly schema: StandardSchemaV1<unknown, S> & StandardJSONSchemaV1<unknown, S>;
|
|
22
|
+
/** Defaults to a line asking the model to call the tool once, with its final answer. */
|
|
23
|
+
readonly description?: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the
|
|
27
|
+
* validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model
|
|
28
|
+
* as an error result, so the model can correct the answer and call again.
|
|
29
|
+
*/
|
|
30
|
+
export declare function outputTool<S>(options: OutputToolOptions<S>): ToolDefinition<S, S>;
|
|
31
|
+
/** The options of `clarificationTool()`. */
|
|
32
|
+
export interface ClarificationToolOptions {
|
|
33
|
+
/** Defaults to `ask_user`. */
|
|
34
|
+
readonly name?: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind
|
|
38
|
+
* `clarification`, which the run turns into a request for the user's answer.
|
|
39
|
+
*/
|
|
40
|
+
export declare function clarificationTool(options?: ClarificationToolOptions): ToolDefinition<{
|
|
41
|
+
question: string;
|
|
42
|
+
}, never>;
|
|
@@ -0,0 +1,96 @@
|
|
|
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
|
+
// Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.
|
|
9
|
+
const prepared = new WeakMap();
|
|
10
|
+
function invalid(message, cause) {
|
|
11
|
+
return new SdkError("invalid_tool_definition", message, cause === undefined ? {} : { cause });
|
|
12
|
+
}
|
|
13
|
+
function checkName(name) {
|
|
14
|
+
if (typeof name !== "string")
|
|
15
|
+
throw invalid("a tool's name must be a string");
|
|
16
|
+
try {
|
|
17
|
+
assertCanonicalName(name);
|
|
18
|
+
}
|
|
19
|
+
catch (cause) {
|
|
20
|
+
throw invalid(cause instanceof Error ? cause.message : String(cause), cause);
|
|
21
|
+
}
|
|
22
|
+
return name;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code
|
|
26
|
+
* `invalid_tool_definition`, for a bad name, a missing description or `execute`, or an unusable schema.
|
|
27
|
+
*/
|
|
28
|
+
export function preparedSchemaOf(tool) {
|
|
29
|
+
const known = prepared.get(tool);
|
|
30
|
+
if (known !== undefined)
|
|
31
|
+
return known;
|
|
32
|
+
const name = checkName(tool.name);
|
|
33
|
+
if (typeof tool.description !== "string")
|
|
34
|
+
throw invalid(`tool "${name}": description must be a string`);
|
|
35
|
+
if (typeof tool.execute !== "function")
|
|
36
|
+
throw invalid(`tool "${name}": execute must be a function`);
|
|
37
|
+
const schema = prepareSchema(name, tool.inputSchema);
|
|
38
|
+
prepared.set(tool, schema);
|
|
39
|
+
return schema;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.
|
|
43
|
+
*
|
|
44
|
+
* Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
|
|
45
|
+
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, a raw JSON Schema does not
|
|
46
|
+
* compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe itself as JSON Schema.
|
|
47
|
+
*/
|
|
48
|
+
export function defineTool(definition) {
|
|
49
|
+
const tool = Object.freeze({ ...definition });
|
|
50
|
+
// Method parameters are bivariant, so a tool of any input type is a ToolDefinition<unknown, unknown>.
|
|
51
|
+
preparedSchemaOf(tool);
|
|
52
|
+
return tool;
|
|
53
|
+
}
|
|
54
|
+
const OUTPUT_DESCRIPTION = "Submit your final answer as this tool's input. Call it once, when the task is done.";
|
|
55
|
+
const OUTPUT_ACCEPTED = "The final answer was accepted.";
|
|
56
|
+
/**
|
|
57
|
+
* Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the
|
|
58
|
+
* validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model
|
|
59
|
+
* as an error result, so the model can correct the answer and call again.
|
|
60
|
+
*/
|
|
61
|
+
export function outputTool(options) {
|
|
62
|
+
return defineTool({
|
|
63
|
+
name: options.name,
|
|
64
|
+
description: options.description ?? OUTPUT_DESCRIPTION,
|
|
65
|
+
inputSchema: options.schema,
|
|
66
|
+
async execute(input) {
|
|
67
|
+
return { content: [{ type: "text", text: OUTPUT_ACCEPTED }], structured: input, terminate: true };
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
const CLARIFICATION_SCHEMA = Object.freeze({
|
|
72
|
+
type: "object",
|
|
73
|
+
properties: Object.freeze({
|
|
74
|
+
question: Object.freeze({ type: "string", minLength: 1, description: "The question to ask the user." }),
|
|
75
|
+
}),
|
|
76
|
+
required: Object.freeze(["question"]),
|
|
77
|
+
additionalProperties: false,
|
|
78
|
+
});
|
|
79
|
+
/**
|
|
80
|
+
* Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind
|
|
81
|
+
* `clarification`, which the run turns into a request for the user's answer.
|
|
82
|
+
*/
|
|
83
|
+
export function clarificationTool(options = {}) {
|
|
84
|
+
return defineTool({
|
|
85
|
+
name: options.name ?? "ask_user",
|
|
86
|
+
description: "Ask the user a question when you cannot continue without their answer.",
|
|
87
|
+
inputSchema: CLARIFICATION_SCHEMA,
|
|
88
|
+
async execute({ question }) {
|
|
89
|
+
return {
|
|
90
|
+
content: [{ type: "text", text: "The question was sent to the user." }],
|
|
91
|
+
pause: { kind: "clarification", question },
|
|
92
|
+
};
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
//# 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,EAAE,MAAM,uBAAuB,CAAC;AAE5D,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAuB,aAAa,EAAE,MAAM,aAAa,CAAC;AAGjE,+FAA+F;AAC/F,MAAM,QAAQ,GAAG,IAAI,OAAO,EAA0B,CAAC;AAEvD,SAAS,OAAO,CAAC,OAAe,EAAE,KAAe;IAC/C,OAAO,IAAI,QAAQ,CAAC,yBAAyB,EAAE,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;AAChG,CAAC;AAED,SAAS,SAAS,CAAC,IAAa;IAC9B,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,MAAM,OAAO,CAAC,gCAAgC,CAAC,CAAC;IAC9E,IAA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;AACL,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 } 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\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`, or an unusable 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 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, a raw JSON Schema does not\n * compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe 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`, which the run turns into a request for the user's answer.\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"]}
|
|
@@ -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,65 @@
|
|
|
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
|
+
response_error: (tool) => `Tool "${tool}" was not run, because the response ended with an error before it was complete. Re-issue the ` +
|
|
36
|
+
"call if it is still needed.",
|
|
37
|
+
response_aborted: (tool) => `Tool "${tool}" was not run, because the response was stopped before it was complete. Re-issue the call if it ` +
|
|
38
|
+
"is still needed.",
|
|
39
|
+
};
|
|
40
|
+
function issueLine(issue) {
|
|
41
|
+
return `- ${issue.path === "" ? "(the whole input)" : issue.path}: ${issue.message}`;
|
|
42
|
+
}
|
|
43
|
+
function describe(failure) {
|
|
44
|
+
switch (failure.kind) {
|
|
45
|
+
case "unknown_tool": {
|
|
46
|
+
const tools = failure.availableTools.length === 0 ? "none" : failure.availableTools.join(", ");
|
|
47
|
+
return `There is no tool named "${failure.tool}". The available tools are: ${tools}.`;
|
|
48
|
+
}
|
|
49
|
+
case "invalid_input":
|
|
50
|
+
return [`The arguments for tool "${failure.tool}" are invalid:`, ...failure.issues.map(issueLine)].join("\n");
|
|
51
|
+
case "execution_error":
|
|
52
|
+
return `Tool "${failure.tool}" failed: ${failure.message}`;
|
|
53
|
+
case "truncated":
|
|
54
|
+
return (`Tool "${failure.tool}" was not run, because the response was cut off at the output limit before the ` +
|
|
55
|
+
"call's arguments were complete. Re-issue the call with complete arguments, in a shorter response.");
|
|
56
|
+
case "not_run":
|
|
57
|
+
return NOT_RUN[failure.reason](failure.tool);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** The default content for a failed tool call: what failed, the received arguments, and the do-not-substitute line. */
|
|
61
|
+
export function formatToolError(failure) {
|
|
62
|
+
const text = [describe(failure), `Received arguments: ${showArguments(failure.input)}`, DO_NOT_SUBSTITUTE].join("\n");
|
|
63
|
+
return [{ type: "text", text }];
|
|
64
|
+
}
|
|
65
|
+
//# 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,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/C,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,IAAI,IAAY,CAAC;IACjB,IAAI,CAAC;QACH,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IACrD,CAAC;IAAC,MAAM,CAA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C,CAAC;YAC/F,OAAO,2BAA2B,OAAO,CAAC,IAAI,+BAA+B,KAAK,GAAG,CAAC;QACxF,CAAC;QACD,KAAK,eAAe;YAClB,OAAO,CAAC,2BAA2B,OAAO,CAAC,IAAI,gBAAgB,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAChH,KAAK,iBAAiB;YACpB,OAAO,SAAS,OAAO,CAAC,IAAI,aAAa,OAAO,CAAC,OAAO,EAAE,CAAC;QAC7D,KAAK,WAAW;YACd,OAAO,CACL,SAAS,OAAO,CAAC,IAAI,iFAAiF;gBACtG,mGAAmG,CACpG,CAAC;QACJ,KAAK,SAAS;YACZ,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACjD,CAAC;AACH,CAAC;AAED,uHAAuH;AACvH,MAAM,UAAU,eAAe,CAAC,OAAoB;IAClD,MAAM,IAAI,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,uBAAuB,aAAa,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,EAAE,iBAAiB,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACtH,OAAO,CAAC,EAAE,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 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"]}
|