@buildanagent/sdk 0.1.0-alpha.0 → 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 +89 -3
- 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/testing/scripted-model.d.ts +5 -0
- package/dist/testing/scripted-model.js +3 -2
- package/dist/testing/scripted-model.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
|
@@ -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,MAA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AAC,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"]}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tool pipeline: the fixed steps every tool call runs (agent-SDK guide §4). Resolve the name, coerce, validate,
|
|
3
|
+
* an optional `repair`, the gate, `execute`, the write outcome, then `afterToolCall`. A failure the model caused
|
|
4
|
+
* becomes an error result and never throws; only a programmer error, such as a malformed tool result, throws an
|
|
5
|
+
* `SdkError`.
|
|
6
|
+
*
|
|
7
|
+
* The gate and `afterToolCall` steps hold their places in the order below, and the interceptors fill them in: until
|
|
8
|
+
* then every call is allowed and every result passes through unchanged. Calls run one at a time, in model order.
|
|
9
|
+
*/
|
|
10
|
+
import type { AssistantMessage } from "@buildanagent/gateway";
|
|
11
|
+
import type { Clock } from "../testing/determinism.js";
|
|
12
|
+
import type { ToolCall, ToolDefinition, ToolResult } from "./types.js";
|
|
13
|
+
/** A tool of any input and structured type, as the pipeline holds it. */
|
|
14
|
+
export type AnyTool = ToolDefinition<unknown, unknown>;
|
|
15
|
+
/** What the pipeline needs from the run around it. */
|
|
16
|
+
export interface PipelineContext {
|
|
17
|
+
readonly runId: string;
|
|
18
|
+
readonly signal: AbortSignal;
|
|
19
|
+
readonly depth: number;
|
|
20
|
+
readonly maxDepth: number;
|
|
21
|
+
readonly clock: Clock;
|
|
22
|
+
/** Receives a tool's progress updates. */
|
|
23
|
+
onUpdate?(callId: string, details: unknown): void;
|
|
24
|
+
/**
|
|
25
|
+
* Receives each call's result as soon as `runToolCalls` has it, so the run can record a write before a later call
|
|
26
|
+
* in the same message throws.
|
|
27
|
+
*/
|
|
28
|
+
onResult?(entry: ToolCallResult): void;
|
|
29
|
+
/**
|
|
30
|
+
* Called as soon as a tool's `execute` returns or throws, before the result is checked, so the run knows a write
|
|
31
|
+
* may have happened even when its result then throws an `SdkError`.
|
|
32
|
+
*/
|
|
33
|
+
onExecuted?(call: ToolCall): void;
|
|
34
|
+
}
|
|
35
|
+
/** One tool call and the result the model will read for it. */
|
|
36
|
+
export interface ToolCallResult {
|
|
37
|
+
readonly call: ToolCall;
|
|
38
|
+
readonly result: ToolResult;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure
|
|
42
|
+
* the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws
|
|
43
|
+
* an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.
|
|
44
|
+
*/
|
|
45
|
+
export declare function runToolCall(call: ToolCall, tools: readonly AnyTool[], ctx: PipelineContext): Promise<ToolResult>;
|
|
46
|
+
/**
|
|
47
|
+
* Runs every tool call of an assistant message, one at a time and in model order, and passes each result to
|
|
48
|
+
* `ctx.onResult` as it arrives. A message that stopped at the output limit (`stopReason: "length"`) runs nothing:
|
|
49
|
+
* each of its calls gets an error asking the model to re-issue it, because its arguments may be cut short. A message
|
|
50
|
+
* that ended in an error or was aborted also runs nothing, because its calls may be partial.
|
|
51
|
+
*/
|
|
52
|
+
export declare function runToolCalls(message: AssistantMessage, tools: readonly AnyTool[], ctx: PipelineContext): Promise<ToolCallResult[]>;
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { SdkError } from "../errors.js";
|
|
2
|
+
import { coerceValue } from "./coerce.js";
|
|
3
|
+
import { preparedSchemaOf } from "./define.js";
|
|
4
|
+
import { formatToolError, REDACTED_MESSAGE } from "./format-error.js";
|
|
5
|
+
import { withOutcome } from "./outcome.js";
|
|
6
|
+
function toolsByName(tools) {
|
|
7
|
+
const byName = new Map();
|
|
8
|
+
for (const tool of tools) {
|
|
9
|
+
preparedSchemaOf(tool);
|
|
10
|
+
if (byName.has(tool.name)) {
|
|
11
|
+
throw new SdkError("invalid_tool_definition", `two tools are named "${tool.name}"; tool names must be unique`);
|
|
12
|
+
}
|
|
13
|
+
byName.set(tool.name, tool);
|
|
14
|
+
}
|
|
15
|
+
return byName;
|
|
16
|
+
}
|
|
17
|
+
function errorMessage(error) {
|
|
18
|
+
return error instanceof Error ? error.message : String(error);
|
|
19
|
+
}
|
|
20
|
+
function isModelContent(block) {
|
|
21
|
+
if (typeof block !== "object" || block === null)
|
|
22
|
+
return false;
|
|
23
|
+
const { type, text, mediaType, data } = block;
|
|
24
|
+
if (type === "text")
|
|
25
|
+
return typeof text === "string";
|
|
26
|
+
return type === "image" && typeof mediaType === "string" && typeof data === "string";
|
|
27
|
+
}
|
|
28
|
+
function isContentList(content) {
|
|
29
|
+
return Array.isArray(content) && content.every(isModelContent);
|
|
30
|
+
}
|
|
31
|
+
// A formatter that throws, or returns something the model can't read, must not hide the failure from the model, so
|
|
32
|
+
// the default text is used instead, and the formatter's error is kept in `details`.
|
|
33
|
+
function formatted(failure, tool) {
|
|
34
|
+
const fallback = formatToolError(failure);
|
|
35
|
+
if (tool?.formatError === undefined)
|
|
36
|
+
return { content: fallback };
|
|
37
|
+
let content;
|
|
38
|
+
try {
|
|
39
|
+
content = tool.formatError(failure);
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
return { content: fallback, error: errorMessage(error) };
|
|
43
|
+
}
|
|
44
|
+
if (isContentList(content))
|
|
45
|
+
return { content };
|
|
46
|
+
return { content: fallback, error: "formatError did not return a list of text and image blocks" };
|
|
47
|
+
}
|
|
48
|
+
function failed(failure, tool, details = {}) {
|
|
49
|
+
const { content, error: formatterError } = formatted(failure, tool);
|
|
50
|
+
return {
|
|
51
|
+
content,
|
|
52
|
+
isError: true,
|
|
53
|
+
details: { failure, ...details, ...(formatterError === undefined ? {} : { formatterError }) },
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
// Coerce, validate, and on failure give `repair` one chance. The model sees the issues of its own arguments, and
|
|
57
|
+
// `details` keeps what repair returned.
|
|
58
|
+
async function checkInput(tool, call) {
|
|
59
|
+
const schema = preparedSchemaOf(tool);
|
|
60
|
+
const coerced = coerceValue(call.input, schema.jsonSchema);
|
|
61
|
+
const first = await schema.validate(coerced);
|
|
62
|
+
if (first.ok)
|
|
63
|
+
return { ok: true, input: first.value };
|
|
64
|
+
const failure = {
|
|
65
|
+
kind: "invalid_input",
|
|
66
|
+
tool: tool.name,
|
|
67
|
+
callId: call.callId,
|
|
68
|
+
input: call.input,
|
|
69
|
+
issues: first.issues,
|
|
70
|
+
};
|
|
71
|
+
if (tool.repair === undefined)
|
|
72
|
+
return { ok: false, result: failed(failure, tool) };
|
|
73
|
+
let repaired;
|
|
74
|
+
try {
|
|
75
|
+
repaired = await tool.repair({ input: coerced, issues: first.issues });
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
return { ok: false, result: failed(failure, tool, { repairError: errorMessage(error) }) };
|
|
79
|
+
}
|
|
80
|
+
if (repaired === undefined)
|
|
81
|
+
return { ok: false, result: failed(failure, tool) };
|
|
82
|
+
const second = await schema.validate(coerceValue(repaired, schema.jsonSchema));
|
|
83
|
+
if (second.ok)
|
|
84
|
+
return { ok: true, input: second.value };
|
|
85
|
+
return { ok: false, result: failed(failure, tool, { repaired, repairedIssues: second.issues }) };
|
|
86
|
+
}
|
|
87
|
+
function checkResult(tool, result) {
|
|
88
|
+
const content = result?.content;
|
|
89
|
+
if (typeof result !== "object" || result === null || !isContentList(content)) {
|
|
90
|
+
throw new SdkError("invalid_tool_result", `tool "${tool}" must return an object whose content is a list of text and image blocks`);
|
|
91
|
+
}
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
async function execute(tool, call, input, ctx) {
|
|
95
|
+
const context = {
|
|
96
|
+
runId: ctx.runId,
|
|
97
|
+
callId: call.callId,
|
|
98
|
+
signal: ctx.signal,
|
|
99
|
+
depth: ctx.depth,
|
|
100
|
+
maxDepth: ctx.maxDepth,
|
|
101
|
+
clock: ctx.clock,
|
|
102
|
+
update: (details) => ctx.onUpdate?.(call.callId, details),
|
|
103
|
+
};
|
|
104
|
+
let result;
|
|
105
|
+
try {
|
|
106
|
+
result = await tool.execute(input, context);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
ctx.onExecuted?.(call);
|
|
110
|
+
const message = errorMessage(error);
|
|
111
|
+
const redacted = tool.redactErrors === true;
|
|
112
|
+
const failure = {
|
|
113
|
+
kind: "execution_error",
|
|
114
|
+
tool: tool.name,
|
|
115
|
+
callId: call.callId,
|
|
116
|
+
input: call.input,
|
|
117
|
+
message: redacted ? REDACTED_MESSAGE : message,
|
|
118
|
+
redacted,
|
|
119
|
+
};
|
|
120
|
+
return failed(failure, tool, { error: { name: error instanceof Error ? error.name : typeof error, message } });
|
|
121
|
+
}
|
|
122
|
+
ctx.onExecuted?.(call);
|
|
123
|
+
return withOutcome(tool.name, checkResult(tool.name, result));
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure
|
|
127
|
+
* the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws
|
|
128
|
+
* an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.
|
|
129
|
+
*/
|
|
130
|
+
export async function runToolCall(call, tools, ctx) {
|
|
131
|
+
const byName = toolsByName(tools);
|
|
132
|
+
const tool = byName.get(call.name);
|
|
133
|
+
if (tool === undefined) {
|
|
134
|
+
const availableTools = [...byName.keys()];
|
|
135
|
+
return failed({ kind: "unknown_tool", tool: call.name, callId: call.callId, input: call.input, availableTools }, undefined);
|
|
136
|
+
}
|
|
137
|
+
// Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.
|
|
138
|
+
if (ctx.signal.aborted)
|
|
139
|
+
return notRun(call, tool, "run_aborted");
|
|
140
|
+
const checked = await checkInput(tool, call);
|
|
141
|
+
if (!checked.ok)
|
|
142
|
+
return checked.result;
|
|
143
|
+
if (ctx.signal.aborted)
|
|
144
|
+
return notRun(call, tool, "run_aborted");
|
|
145
|
+
// Gate: every call is allowed until the beforeToolCall interceptor exists.
|
|
146
|
+
const result = await execute(tool, call, checked.input, ctx);
|
|
147
|
+
// afterToolCall: the result passes through unchanged until that interceptor exists.
|
|
148
|
+
return result;
|
|
149
|
+
}
|
|
150
|
+
function notRun(call, tool, reason) {
|
|
151
|
+
return failed({ kind: "not_run", reason, tool: call.name, callId: call.callId, input: call.input }, tool);
|
|
152
|
+
}
|
|
153
|
+
// Why none of a message's calls may run, or undefined when they all may.
|
|
154
|
+
function unrunnable(message, call, tools) {
|
|
155
|
+
const tool = tools.find((candidate) => candidate.name === call.name);
|
|
156
|
+
switch (message.stopReason) {
|
|
157
|
+
case "length":
|
|
158
|
+
return failed({ kind: "truncated", tool: call.name, callId: call.callId, input: call.input }, tool);
|
|
159
|
+
case "error":
|
|
160
|
+
return notRun(call, tool, "response_error");
|
|
161
|
+
case "aborted":
|
|
162
|
+
return notRun(call, tool, "response_aborted");
|
|
163
|
+
default:
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Runs every tool call of an assistant message, one at a time and in model order, and passes each result to
|
|
169
|
+
* `ctx.onResult` as it arrives. A message that stopped at the output limit (`stopReason: "length"`) runs nothing:
|
|
170
|
+
* each of its calls gets an error asking the model to re-issue it, because its arguments may be cut short. A message
|
|
171
|
+
* that ended in an error or was aborted also runs nothing, because its calls may be partial.
|
|
172
|
+
*/
|
|
173
|
+
export async function runToolCalls(message, tools, ctx) {
|
|
174
|
+
const calls = message.content.filter((block) => block.type === "tool_call");
|
|
175
|
+
toolsByName(tools);
|
|
176
|
+
const results = [];
|
|
177
|
+
for (const call of calls) {
|
|
178
|
+
const entry = { call, result: unrunnable(message, call, tools) ?? (await runToolCall(call, tools, ctx)) };
|
|
179
|
+
results.push(entry);
|
|
180
|
+
ctx.onResult?.(entry);
|
|
181
|
+
}
|
|
182
|
+
return results;
|
|
183
|
+
}
|
|
184
|
+
//# sourceMappingURL=pipeline.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/tools/pipeline.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAiC3C,SAAS,WAAW,CAAC,KAAyB;IAC5C,MAAM,MAAM,GAAG,IAAI,GAAG,EAAmB,CAAC;IAC1C,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,gBAAgB,CAAC,IAAI,CAAC,CAAC;QACvB,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,QAAQ,CAAC,yBAAyB,EAAE,wBAAwB,IAAI,CAAC,IAAI,8BAA8B,CAAC,CAAC;QACjH,CAAC;QACD,MAAM,CAAC,GAAG,CAAC,IAAI,CAA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CAAC,MAAM,CAAC,CAAC,KAAK,EAAqB,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC;IAC/F,WAAW,CAAC,KAAK,CAAC,CAAC;IACnB,MAAM,OAAO,GAAqB,EAAE,CAAC;IACrC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,KAAK,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,MAAM,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;QAC1G,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACpB,GAAG,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["/**\n * The tool pipeline: the fixed steps every tool call runs (agent-SDK guide §4). Resolve the name, coerce, validate,\n * an optional `repair`, the gate, `execute`, the write outcome, then `afterToolCall`. A failure the model caused\n * becomes an error result and never throws; only a programmer error, such as a malformed tool result, throws an\n * `SdkError`.\n *\n * The gate and `afterToolCall` steps hold their places in the order below, and the interceptors fill them in: until\n * then every call is allowed and every result passes through unchanged. Calls run one at a time, in model order.\n */\nimport type { AssistantMessage, ModelContent } from \"@buildanagent/gateway\";\nimport { SdkError } from \"../errors.js\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport { coerceValue } from \"./coerce.js\";\nimport { preparedSchemaOf } from \"./define.js\";\nimport { formatToolError, REDACTED_MESSAGE } from \"./format-error.js\";\nimport { withOutcome } from \"./outcome.js\";\nimport type { ToolCall, ToolDefinition, ToolFailure, ToolResult } from \"./types.js\";\n\n/** A tool of any input and structured type, as the pipeline holds it. */\nexport type AnyTool = ToolDefinition<unknown, unknown>;\n\n/** What the pipeline needs from the run around it. */\nexport interface PipelineContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly depth: number;\n readonly maxDepth: number;\n readonly clock: Clock;\n /** Receives a tool's progress updates. */\n onUpdate?(callId: string, details: unknown): void;\n /**\n * Receives each call's result as soon as `runToolCalls` has it, so the run can record a write before a later call\n * in the same message throws.\n */\n onResult?(entry: ToolCallResult): void;\n /**\n * Called as soon as a tool's `execute` returns or throws, before the result is checked, so the run knows a write\n * may have happened even when its result then throws an `SdkError`.\n */\n onExecuted?(call: ToolCall): void;\n}\n\n/** One tool call and the result the model will read for it. */\nexport interface ToolCallResult {\n readonly call: ToolCall;\n readonly result: ToolResult;\n}\n\nfunction toolsByName(tools: readonly AnyTool[]): ReadonlyMap<string, AnyTool> {\n const byName = new Map<string, AnyTool>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (byName.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n byName.set(tool.name, tool);\n }\n return byName;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isModelContent(block: unknown): block is ModelContent {\n if (typeof block !== \"object\" || block === null) return false;\n const { type, text, mediaType, data } = block as Record<string, unknown>;\n if (type === \"text\") return typeof text === \"string\";\n return type === \"image\" && typeof mediaType === \"string\" && typeof data === \"string\";\n}\n\nfunction isContentList(content: unknown): content is readonly ModelContent[] {\n return Array.isArray(content) && content.every(isModelContent);\n}\n\ntype Formatted = { readonly content: readonly ModelContent[]; readonly error?: string };\n\n// A formatter that throws, or returns something the model can't read, must not hide the failure from the model, so\n// the default text is used instead, and the formatter's error is kept in `details`.\nfunction formatted(failure: ToolFailure, tool: AnyTool | undefined): Formatted {\n const fallback = formatToolError(failure);\n if (tool?.formatError === undefined) return { content: fallback };\n let content: unknown;\n try {\n content = tool.formatError(failure);\n } catch (error) {\n return { content: fallback, error: errorMessage(error) };\n }\n if (isContentList(content)) return { content };\n return { content: fallback, error: \"formatError did not return a list of text and image blocks\" };\n}\n\nfunction failed(failure: ToolFailure, tool: AnyTool | undefined, details: Record<string, unknown> = {}): ToolResult {\n const { content, error: formatterError } = formatted(failure, tool);\n return {\n content,\n isError: true,\n details: { failure, ...details, ...(formatterError === undefined ? {} : { formatterError }) },\n };\n}\n\ntype Checked = { readonly ok: true; readonly input: unknown } | { readonly ok: false; readonly result: ToolResult };\n\n// Coerce, validate, and on failure give `repair` one chance. The model sees the issues of its own arguments, and\n// `details` keeps what repair returned.\nasync function checkInput(tool: AnyTool, call: ToolCall): Promise<Checked> {\n const schema = preparedSchemaOf(tool);\n const coerced = coerceValue(call.input, schema.jsonSchema);\n const first = await schema.validate(coerced);\n if (first.ok) return { ok: true, input: first.value };\n const failure: ToolFailure = {\n kind: \"invalid_input\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n issues: first.issues,\n };\n if (tool.repair === undefined) return { ok: false, result: failed(failure, tool) };\n let repaired: unknown;\n try {\n repaired = await tool.repair({ input: coerced, issues: first.issues });\n } catch (error) {\n return { ok: false, result: failed(failure, tool, { repairError: errorMessage(error) }) };\n }\n if (repaired === undefined) return { ok: false, result: failed(failure, tool) };\n const second = await schema.validate(coerceValue(repaired, schema.jsonSchema));\n if (second.ok) return { ok: true, input: second.value };\n return { ok: false, result: failed(failure, tool, { repaired, repairedIssues: second.issues }) };\n}\n\nfunction checkResult(tool: string, result: unknown): ToolResult {\n const content = (result as { content?: unknown } | null)?.content;\n if (typeof result !== \"object\" || result === null || !isContentList(content)) {\n throw new SdkError(\n \"invalid_tool_result\",\n `tool \"${tool}\" must return an object whose content is a list of text and image blocks`,\n );\n }\n return result as ToolResult;\n}\n\nasync function execute(tool: AnyTool, call: ToolCall, input: unknown, ctx: PipelineContext): Promise<ToolResult> {\n const context = {\n runId: ctx.runId,\n callId: call.callId,\n signal: ctx.signal,\n depth: ctx.depth,\n maxDepth: ctx.maxDepth,\n clock: ctx.clock,\n update: (details: unknown) => ctx.onUpdate?.(call.callId, details),\n };\n let result: unknown;\n try {\n result = await tool.execute(input, context);\n } catch (error) {\n ctx.onExecuted?.(call);\n const message = errorMessage(error);\n const redacted = tool.redactErrors === true;\n const failure: ToolFailure = {\n kind: \"execution_error\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n message: redacted ? REDACTED_MESSAGE : message,\n redacted,\n };\n return failed(failure, tool, { error: { name: error instanceof Error ? error.name : typeof error, message } });\n }\n ctx.onExecuted?.(call);\n return withOutcome(tool.name, checkResult(tool.name, result));\n}\n\n/**\n * Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure\n * the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws\n * an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.\n */\nexport async function runToolCall(\n call: ToolCall,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolResult> {\n const byName = toolsByName(tools);\n const tool = byName.get(call.name);\n if (tool === undefined) {\n const availableTools = [...byName.keys()];\n return failed(\n { kind: \"unknown_tool\", tool: call.name, callId: call.callId, input: call.input, availableTools },\n undefined,\n );\n }\n // Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.\n if (ctx.signal.aborted) return notRun(call, tool, \"run_aborted\");\n const checked = await checkInput(tool, call);\n if (!checked.ok) return checked.result;\n if (ctx.signal.aborted) return notRun(call, tool, \"run_aborted\");\n // Gate: every call is allowed until the beforeToolCall interceptor exists.\n const result = await execute(tool, call, checked.input, ctx);\n // afterToolCall: the result passes through unchanged until that interceptor exists.\n return result;\n}\n\ntype NotRunReason = Extract<ToolFailure, { kind: \"not_run\" }>[\"reason\"];\n\nfunction notRun(call: ToolCall, tool: AnyTool | undefined, reason: NotRunReason): ToolResult {\n return failed({ kind: \"not_run\", reason, tool: call.name, callId: call.callId, input: call.input }, tool);\n}\n\n// Why none of a message's calls may run, or undefined when they all may.\nfunction unrunnable(message: AssistantMessage, call: ToolCall, tools: readonly AnyTool[]): ToolResult | undefined {\n const tool = tools.find((candidate) => candidate.name === call.name);\n switch (message.stopReason) {\n case \"length\":\n return failed({ kind: \"truncated\", tool: call.name, callId: call.callId, input: call.input }, tool);\n case \"error\":\n return notRun(call, tool, \"response_error\");\n case \"aborted\":\n return notRun(call, tool, \"response_aborted\");\n default:\n return undefined;\n }\n}\n\n/**\n * Runs every tool call of an assistant message, one at a time and in model order, and passes each result to\n * `ctx.onResult` as it arrives. A message that stopped at the output limit (`stopReason: \"length\"`) runs nothing:\n * each of its calls gets an error asking the model to re-issue it, because its arguments may be cut short. A message\n * that ended in an error or was aborted also runs nothing, because its calls may be partial.\n */\nexport async function runToolCalls(\n message: AssistantMessage,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const calls = message.content.filter((block): block is ToolCall => block.type === \"tool_call\");\n toolsByName(tools);\n const results: ToolCallResult[] = [];\n for (const call of calls) {\n const entry = { call, result: unrunnable(message, call, tools) ?? (await runToolCall(call, tools, ctx)) };\n results.push(entry);\n ctx.onResult?.(entry);\n }\n return results;\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { JsonSchema, SchemaIssue, ToolSchema } from "./types.js";
|
|
2
|
+
/** The outcome of validating one input: the value `execute` receives, or the issues. */
|
|
3
|
+
export type Validation = {
|
|
4
|
+
readonly ok: true;
|
|
5
|
+
readonly value: unknown;
|
|
6
|
+
} | {
|
|
7
|
+
readonly ok: false;
|
|
8
|
+
readonly issues: readonly SchemaIssue[];
|
|
9
|
+
};
|
|
10
|
+
/** A tool's schema, ready for the pipeline. */
|
|
11
|
+
export interface PreparedSchema {
|
|
12
|
+
/** The JSON Schema the model is sent, and the one coercion reads. */
|
|
13
|
+
readonly jsonSchema: JsonSchema;
|
|
14
|
+
validate(value: unknown): Promise<Validation>;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Prepares a tool's input schema. Throws an `SdkError`, code `invalid_tool_definition`, when a raw schema does not
|
|
18
|
+
* compile or names a draft other than 2020-12 or 7, or when a Standard Schema cannot produce JSON Schema.
|
|
19
|
+
*/
|
|
20
|
+
export declare function prepareSchema(tool: string, schema: ToolSchema<unknown>): PreparedSchema;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema handling: turns a tool's `inputSchema` into the JSON Schema the model is sent and a validator the pipeline
|
|
3
|
+
* runs. A Standard Schema validates itself and describes itself as JSON Schema; a raw JSON Schema is compiled once
|
|
4
|
+
* with pi-schema, drafts 2020-12 and 7, with format checks on (D7).
|
|
5
|
+
*/
|
|
6
|
+
import { compile } from "@earendil-works/pi-schema";
|
|
7
|
+
import { formats } from "@earendil-works/pi-schema/formats";
|
|
8
|
+
import { SdkError } from "../errors.js";
|
|
9
|
+
const DRAFT_7 = /^https?:\/\/json-schema\.org\/draft-07\/schema#?$/;
|
|
10
|
+
const DRAFT_2020_12 = /^https?:\/\/json-schema\.org\/draft\/2020-12\/schema#?$/;
|
|
11
|
+
function isStandardSchema(schema) {
|
|
12
|
+
return "~standard" in schema;
|
|
13
|
+
}
|
|
14
|
+
// An ArkType schema is a callable function that carries `~standard`, so a function counts when it has that property.
|
|
15
|
+
function isSchemaShaped(schema) {
|
|
16
|
+
if (typeof schema === "object")
|
|
17
|
+
return schema !== null;
|
|
18
|
+
return typeof schema === "function" && "~standard" in schema;
|
|
19
|
+
}
|
|
20
|
+
function invalid(tool, message, cause) {
|
|
21
|
+
return new SdkError("invalid_tool_definition", `tool "${tool}": ${message}`, cause === undefined ? {} : { cause });
|
|
22
|
+
}
|
|
23
|
+
function draftOf(tool, schema) {
|
|
24
|
+
const declared = schema.$schema;
|
|
25
|
+
if (declared === undefined || (typeof declared === "string" && DRAFT_2020_12.test(declared)))
|
|
26
|
+
return "2020-12";
|
|
27
|
+
if (typeof declared === "string" && DRAFT_7.test(declared))
|
|
28
|
+
return "7";
|
|
29
|
+
throw invalid(tool, `$schema ${JSON.stringify(declared)} is not draft 2020-12 or draft 7`);
|
|
30
|
+
}
|
|
31
|
+
function prepareJsonSchema(tool, schema) {
|
|
32
|
+
let validator;
|
|
33
|
+
try {
|
|
34
|
+
validator = compile(schema, { draft: draftOf(tool, schema), formats });
|
|
35
|
+
}
|
|
36
|
+
catch (cause) {
|
|
37
|
+
if (cause instanceof SdkError)
|
|
38
|
+
throw cause;
|
|
39
|
+
throw invalid(tool, "its input schema does not compile", cause);
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
jsonSchema: schema,
|
|
43
|
+
async validate(value) {
|
|
44
|
+
if (validator.check(value))
|
|
45
|
+
return { ok: true, value };
|
|
46
|
+
const issues = validator.errors(value).map(({ path, keyword, message }) => ({ path, keyword, message }));
|
|
47
|
+
return { ok: false, issues };
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
// RFC 6901: "~" and "/" in a key are escaped as "~0" and "~1".
|
|
52
|
+
function pointer(path) {
|
|
53
|
+
return (path ?? [])
|
|
54
|
+
.map((segment) => {
|
|
55
|
+
const key = typeof segment === "object" ? segment.key : segment;
|
|
56
|
+
const text = typeof key === "symbol" ? (key.description ?? "") : String(key);
|
|
57
|
+
return `/${text.replaceAll("~", "~0").replaceAll("/", "~1")}`;
|
|
58
|
+
})
|
|
59
|
+
.join("");
|
|
60
|
+
}
|
|
61
|
+
function prepareStandardSchema(tool, schema) {
|
|
62
|
+
let jsonSchema;
|
|
63
|
+
try {
|
|
64
|
+
jsonSchema = schema["~standard"].jsonSchema.input({ target: "draft-2020-12" });
|
|
65
|
+
}
|
|
66
|
+
catch (cause) {
|
|
67
|
+
throw invalid(tool, "its Standard Schema cannot describe its input as draft 2020-12 JSON Schema", cause);
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
jsonSchema,
|
|
71
|
+
async validate(value) {
|
|
72
|
+
let result;
|
|
73
|
+
try {
|
|
74
|
+
result = await schema["~standard"].validate(value);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
// A validator that throws is the schema library's failure, not the model's, but the model still needs an
|
|
78
|
+
// error result, so the throw becomes one issue at the root.
|
|
79
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
80
|
+
return { ok: false, issues: [{ path: "", message: `the schema's validator threw: ${message}` }] };
|
|
81
|
+
}
|
|
82
|
+
if (result.issues === undefined)
|
|
83
|
+
return { ok: true, value: result.value };
|
|
84
|
+
return {
|
|
85
|
+
ok: false,
|
|
86
|
+
issues: result.issues.map((issue) => ({ path: pointer(issue.path), message: issue.message })),
|
|
87
|
+
};
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Prepares a tool's input schema. Throws an `SdkError`, code `invalid_tool_definition`, when a raw schema does not
|
|
93
|
+
* compile or names a draft other than 2020-12 or 7, or when a Standard Schema cannot produce JSON Schema.
|
|
94
|
+
*/
|
|
95
|
+
export function prepareSchema(tool, schema) {
|
|
96
|
+
if (!isSchemaShaped(schema))
|
|
97
|
+
throw invalid(tool, "inputSchema must be a JSON Schema object or a Standard Schema");
|
|
98
|
+
return isStandardSchema(schema) ? prepareStandardSchema(tool, schema) : prepareJsonSchema(tool, schema);
|
|
99
|
+
}
|
|
100
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/tools/schema.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,OAAO,EAAkB,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAE5D,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAiBxC,MAAM,OAAO,GAAG,mDAAmD,CAAC;AACpE,MAAM,aAAa,GAAG,yDAAyD,CAAC;AAEhF,SAAS,gBAAgB,CAAC,MAA2B;IACnD,OAAO,WAAW,IAAI,MAAM,CAAC;AAC/B,CAAC;AAED,qHAAqH;AACrH,SAAS,cAAc,CAAC,MAAe;IACrC,IAAI,OAAO,MAAM,KAAK,QAAQ;Q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,+DAA+D,CAAC,CAAC;IAClH,OAAO,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,qBAAqB,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC1G,CAAC","sourcesContent":["/**\n * Schema handling: turns a tool's `inputSchema` into the JSON Schema the model is sent and a validator the pipeline\n * runs. A Standard Schema validates itself and describes itself as JSON Schema; a raw JSON Schema is compiled once\n * with pi-schema, drafts 2020-12 and 7, with format checks on (D7).\n */\nimport { compile, type Validator } from \"@earendil-works/pi-schema\";\nimport { formats } from \"@earendil-works/pi-schema/formats\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { SdkError } from \"../errors.js\";\nimport type { JsonSchema, SchemaIssue, ToolSchema } from \"./types.js\";\n\n/** The outcome of validating one input: the value `execute` receives, or the issues. */\nexport type Validation =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly issues: readonly SchemaIssue[] };\n\n/** A tool's schema, ready for the pipeline. */\nexport interface PreparedSchema {\n /** The JSON Schema the model is sent, and the one coercion reads. */\n readonly jsonSchema: JsonSchema;\n validate(value: unknown): Promise<Validation>;\n}\n\ntype StandardToolSchema = StandardSchemaV1<unknown, unknown> & StandardJSONSchemaV1<unknown, unknown>;\n\nconst DRAFT_7 = /^https?:\\/\\/json-schema\\.org\\/draft-07\\/schema#?$/;\nconst DRAFT_2020_12 = /^https?:\\/\\/json-schema\\.org\\/draft\\/2020-12\\/schema#?$/;\n\nfunction isStandardSchema(schema: ToolSchema<unknown>): schema is StandardToolSchema {\n return \"~standard\" in schema;\n}\n\n// An ArkType schema is a callable function that carries `~standard`, so a function counts when it has that property.\nfunction isSchemaShaped(schema: unknown): schema is ToolSchema<unknown> {\n if (typeof schema === \"object\") return schema !== null;\n return typeof schema === \"function\" && \"~standard\" in schema;\n}\n\nfunction invalid(tool: string, message: string, cause?: unknown): SdkError {\n return new SdkError(\"invalid_tool_definition\", `tool \"${tool}\": ${message}`, cause === undefined ? {} : { cause });\n}\n\nfunction draftOf(tool: string, schema: JsonSchema): \"7\" | \"2020-12\" {\n const declared = schema.$schema;\n if (declared === undefined || (typeof declared === \"string\" && DRAFT_2020_12.test(declared))) return \"2020-12\";\n if (typeof declared === \"string\" && DRAFT_7.test(declared)) return \"7\";\n throw invalid(tool, `$schema ${JSON.stringify(declared)} is not draft 2020-12 or draft 7`);\n}\n\nfunction prepareJsonSchema(tool: string, schema: JsonSchema): PreparedSchema {\n let validator: Validator<unknown>;\n try {\n validator = compile(schema, { draft: draftOf(tool, schema), formats });\n } catch (cause) {\n if (cause instanceof SdkError) throw cause;\n throw invalid(tool, \"its input schema does not compile\", cause);\n }\n return {\n jsonSchema: schema,\n async validate(value) {\n if (validator.check(value)) return { ok: true, value };\n const issues = validator.errors(value).map(({ path, keyword, message }) => ({ path, keyword, message }));\n return { ok: false, issues };\n },\n };\n}\n\n// RFC 6901: \"~\" and \"/\" in a key are escaped as \"~0\" and \"~1\".\nfunction pointer(path: StandardSchemaV1.Issue[\"path\"]): string {\n return (path ?? [])\n .map((segment) => {\n const key = typeof segment === \"object\" ? segment.key : segment;\n const text = typeof key === \"symbol\" ? (key.description ?? \"\") : String(key);\n return `/${text.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")}`;\n })\n .join(\"\");\n}\n\nfunction prepareStandardSchema(tool: string, schema: StandardToolSchema): PreparedSchema {\n let jsonSchema: JsonSchema;\n try {\n jsonSchema = schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" });\n } catch (cause) {\n throw invalid(tool, \"its Standard Schema cannot describe its input as draft 2020-12 JSON Schema\", cause);\n }\n return {\n jsonSchema,\n async validate(value) {\n let result: StandardSchemaV1.Result<unknown>;\n try {\n result = await schema[\"~standard\"].validate(value);\n } catch (error) {\n // A validator that throws is the schema library's failure, not the model's, but the model still needs an\n // error result, so the throw becomes one issue at the root.\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, issues: [{ path: \"\", message: `the schema's validator threw: ${message}` }] };\n }\n if (result.issues === undefined) return { ok: true, value: result.value };\n return {\n ok: false,\n issues: result.issues.map((issue) => ({ path: pointer(issue.path), message: issue.message })),\n };\n },\n };\n}\n\n/**\n * Prepares a tool's input schema. Throws an `SdkError`, code `invalid_tool_definition`, when a raw schema does not\n * compile or names a draft other than 2020-12 or 7, or when a Standard Schema cannot produce JSON Schema.\n */\nexport function prepareSchema(tool: string, schema: ToolSchema<unknown>): PreparedSchema {\n if (!isSchemaShaped(schema)) throw invalid(tool, \"inputSchema must be a JSON Schema object or a Standard Schema\");\n return isStandardSchema(schema) ? prepareStandardSchema(tool, schema) : prepareJsonSchema(tool, schema);\n}\n"]}
|