sarvam-agents-client 0.3.0 → 0.3.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 +98 -1
- package/dist/apis/FunctionToolsApi.d.ts +33 -0
- package/dist/apis/FunctionToolsApi.js +65 -0
- package/dist/apis/index.d.ts +1 -0
- package/dist/apis/index.js +1 -0
- package/dist/compose/agent.d.ts +20 -3
- package/dist/compose/agent.js +84 -7
- package/dist/compose/errors.d.ts +5 -1
- package/dist/compose/errors.js +4 -1
- package/dist/compose/events.d.ts +4 -0
- package/dist/compose/events.js +34 -0
- package/dist/compose/functionTool.d.ts +101 -0
- package/dist/compose/functionTool.js +420 -0
- package/dist/compose/index.d.ts +6 -2
- package/dist/compose/index.js +3 -1
- package/dist/compose/output.d.ts +11 -0
- package/dist/compose/output.js +32 -7
- package/dist/compose/run.d.ts +5 -1
- package/dist/compose/run.js +118 -25
- package/dist/compose/runState.d.ts +26 -1
- package/dist/compose/runState.js +30 -0
- package/dist/compose/settingsTransport.d.ts +28 -1
- package/dist/compose/settingsTransport.js +389 -7
- package/dist/compose/transport.d.ts +18 -1
- package/dist/compose/webhook.d.ts +19 -0
- package/dist/compose/webhook.js +184 -0
- package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
- package/dist/esm/apis/FunctionToolsApi.js +61 -0
- package/dist/esm/apis/index.d.ts +1 -0
- package/dist/esm/apis/index.js +1 -0
- package/dist/esm/compose/agent.d.ts +20 -3
- package/dist/esm/compose/agent.js +84 -7
- package/dist/esm/compose/errors.d.ts +5 -1
- package/dist/esm/compose/errors.js +4 -1
- package/dist/esm/compose/events.d.ts +4 -0
- package/dist/esm/compose/events.js +33 -0
- package/dist/esm/compose/functionTool.d.ts +101 -0
- package/dist/esm/compose/functionTool.js +406 -0
- package/dist/esm/compose/index.d.ts +6 -2
- package/dist/esm/compose/index.js +1 -0
- package/dist/esm/compose/output.d.ts +11 -0
- package/dist/esm/compose/output.js +30 -9
- package/dist/esm/compose/run.d.ts +5 -1
- package/dist/esm/compose/run.js +118 -25
- package/dist/esm/compose/runState.d.ts +26 -1
- package/dist/esm/compose/runState.js +31 -1
- package/dist/esm/compose/settingsTransport.d.ts +28 -1
- package/dist/esm/compose/settingsTransport.js +392 -11
- package/dist/esm/compose/transport.d.ts +18 -1
- package/dist/esm/compose/webhook.d.ts +19 -0
- package/dist/esm/compose/webhook.js +177 -0
- package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
- package/dist/esm/models/AgentConversationDetail.js +3 -0
- package/dist/esm/models/ClarifyBody.d.ts +6 -0
- package/dist/esm/models/ClarifyBody.js +2 -0
- package/dist/esm/models/ConversationDetail.d.ts +7 -0
- package/dist/esm/models/ConversationDetail.js +3 -0
- package/dist/esm/models/ErrorDetail.d.ts +1 -0
- package/dist/esm/models/ErrorDetail.js +2 -1
- package/dist/esm/models/FunctionResultBody.d.ts +44 -0
- package/dist/esm/models/FunctionResultBody.js +49 -0
- package/dist/esm/models/QueueMessageInput.d.ts +23 -0
- package/dist/esm/models/QueueMessageInput.js +14 -0
- package/dist/esm/models/RequiredAction.d.ts +77 -0
- package/dist/esm/models/RequiredAction.js +69 -0
- package/dist/esm/models/ResponseDetail.d.ts +8 -0
- package/dist/esm/models/ResponseDetail.js +2 -0
- package/dist/esm/models/ResponseInput.d.ts +23 -0
- package/dist/esm/models/ResponseInput.js +14 -0
- package/dist/esm/models/ToolResults200Response.d.ts +38 -0
- package/dist/esm/models/ToolResults200Response.js +47 -0
- package/dist/esm/models/ToolResultsBody.d.ts +39 -0
- package/dist/esm/models/ToolResultsBody.js +48 -0
- package/dist/esm/models/index.d.ts +4 -0
- package/dist/esm/models/index.js +4 -0
- package/dist/esm/streaming.d.ts +14 -2
- package/dist/esm/streaming.js +26 -4
- package/dist/esm/webhooks.d.ts +203 -0
- package/dist/esm/webhooks.js +215 -0
- package/dist/models/AgentConversationDetail.d.ts +7 -0
- package/dist/models/AgentConversationDetail.js +3 -0
- package/dist/models/ClarifyBody.d.ts +6 -0
- package/dist/models/ClarifyBody.js +2 -0
- package/dist/models/ConversationDetail.d.ts +7 -0
- package/dist/models/ConversationDetail.js +3 -0
- package/dist/models/ErrorDetail.d.ts +1 -0
- package/dist/models/ErrorDetail.js +2 -1
- package/dist/models/FunctionResultBody.d.ts +44 -0
- package/dist/models/FunctionResultBody.js +56 -0
- package/dist/models/QueueMessageInput.d.ts +23 -0
- package/dist/models/QueueMessageInput.js +15 -1
- package/dist/models/RequiredAction.d.ts +77 -0
- package/dist/models/RequiredAction.js +77 -0
- package/dist/models/ResponseDetail.d.ts +8 -0
- package/dist/models/ResponseDetail.js +2 -0
- package/dist/models/ResponseInput.d.ts +23 -0
- package/dist/models/ResponseInput.js +15 -0
- package/dist/models/ToolResults200Response.d.ts +38 -0
- package/dist/models/ToolResults200Response.js +54 -0
- package/dist/models/ToolResultsBody.d.ts +39 -0
- package/dist/models/ToolResultsBody.js +55 -0
- package/dist/models/index.d.ts +4 -0
- package/dist/models/index.js +4 -0
- package/dist/streaming.d.ts +14 -2
- package/dist/streaming.js +27 -4
- package/dist/webhooks.d.ts +203 -0
- package/dist/webhooks.js +224 -0
- package/package.json +9 -1
- package/src/apis/FunctionToolsApi.ts +102 -0
- package/src/apis/index.ts +1 -0
- package/src/compose/agent.ts +96 -9
- package/src/compose/errors.ts +7 -1
- package/src/compose/events.ts +30 -0
- package/src/compose/functionTool.ts +441 -0
- package/src/compose/index.ts +6 -2
- package/src/compose/output.ts +30 -9
- package/src/compose/run.ts +115 -18
- package/src/compose/runState.ts +44 -5
- package/src/compose/settingsTransport.ts +379 -8
- package/src/compose/transport.ts +24 -1
- package/src/compose/webhook.ts +181 -0
- package/src/models/AgentConversationDetail.ts +15 -0
- package/src/models/ClarifyBody.ts +8 -0
- package/src/models/ConversationDetail.ts +15 -0
- package/src/models/ErrorDetail.ts +2 -1
- package/src/models/FunctionResultBody.ts +83 -0
- package/src/models/QueueMessageInput.ts +28 -0
- package/src/models/RequiredAction.ts +128 -0
- package/src/models/ResponseDetail.ts +8 -0
- package/src/models/ResponseInput.ts +30 -0
- package/src/models/ToolResults200Response.ts +75 -0
- package/src/models/ToolResultsBody.ts +83 -0
- package/src/models/index.ts +4 -0
- package/src/streaming.ts +39 -3
- package/src/webhooks.ts +390 -0
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { FunctionCallRequest } from "./events.js";
|
|
2
|
+
export declare const NAME_PATTERN: RegExp;
|
|
3
|
+
export declare const DESCRIPTION_MAX_CHARS = 1024;
|
|
4
|
+
/** The server's caps: one function's `parameters` (compact JSON), how many functions, and all of them together. */
|
|
5
|
+
export declare const PARAMETERS_MAX_BYTES: number;
|
|
6
|
+
/** The deepest JSON nesting of `parameters`, counting every object and list (the root object is 1). */
|
|
7
|
+
export declare const PARAMETERS_MAX_DEPTH = 16;
|
|
8
|
+
/** Names a function may not take: panja's `RESERVED_FUNCTION_NAMES` (platform tools, harness plumbing, built-in and
|
|
9
|
+
* sandbox tool names, retired v11 names, `clarify`), expanded. `shared/function_tool_vectors.json` pins it. */
|
|
10
|
+
export declare const RESERVED_FUNCTION_NAMES: ReadonlySet<string>;
|
|
11
|
+
export declare const FUNCTIONS_MAX = 32;
|
|
12
|
+
/** The server's range for `function_timeout_seconds` (save_check's maximum), and its value when agent.json leaves
|
|
13
|
+
* it out. */
|
|
14
|
+
export declare const FUNCTION_TIMEOUT_RANGE: readonly [number, number];
|
|
15
|
+
export declare const DEFAULT_FUNCTION_TIMEOUT_SECONDS = 600;
|
|
16
|
+
export declare const FUNCTIONS_TOTAL_MAX_BYTES: number;
|
|
17
|
+
export declare const MAX_TIMEOUT_MS: number;
|
|
18
|
+
/** The server's default cap on one post's outputs together (`CLAW_FUNCTION_RESULT_MAX_BYTES`, UTF-8). It refuses
|
|
19
|
+
* (413) rather than truncates, so the runner truncates first. */
|
|
20
|
+
export declare const RESULTS_MAX_BYTES = 65536;
|
|
21
|
+
export declare const TRUNCATION_NOTE = "\n[truncated by sarvam-agents-client]";
|
|
22
|
+
/** A zod (v4) schema, or anything with the same two methods. */
|
|
23
|
+
interface ParseableSchema {
|
|
24
|
+
parse(value: unknown): unknown;
|
|
25
|
+
toJSONSchema(params?: {
|
|
26
|
+
io?: "input" | "output";
|
|
27
|
+
}): Record<string, unknown>;
|
|
28
|
+
}
|
|
29
|
+
/** What `execute` gets besides the arguments. */
|
|
30
|
+
export interface FunctionCallDetails {
|
|
31
|
+
/** The model's tool-call id. */
|
|
32
|
+
callId: string;
|
|
33
|
+
/** Aborted when the call times out or the run is cancelled; pass it to `fetch` and the like. */
|
|
34
|
+
signal: AbortSignal;
|
|
35
|
+
}
|
|
36
|
+
/** The arguments `execute` receives: the zod schema's output type, or a plain object for a JSON Schema. */
|
|
37
|
+
export type FunctionToolArgs<P> = P extends ParseableSchema ? ReturnType<P["parse"]> : Record<string, unknown>;
|
|
38
|
+
export interface FunctionToolOptions<P extends ParseableSchema | Record<string, unknown> = Record<string, unknown>> {
|
|
39
|
+
/** Letters, digits, `_` or `-`, starting with a letter or `_`; at most 64 characters. */
|
|
40
|
+
name: string;
|
|
41
|
+
/** 1 to 1024 characters; what the model reads to decide when to call the function. */
|
|
42
|
+
description: string;
|
|
43
|
+
/** A zod object schema (arguments are parsed with it), or a JSON Schema object with `"type": "object"`. */
|
|
44
|
+
parameters: P;
|
|
45
|
+
/** Runs the call. Its return value goes to the model: strings as is, other values as JSON. */
|
|
46
|
+
execute: (args: FunctionToolArgs<P>, details: FunctionCallDetails) => unknown;
|
|
47
|
+
/** After this long the model gets a failed result instead (default 60 000 ms). */
|
|
48
|
+
timeoutMs?: number;
|
|
49
|
+
}
|
|
50
|
+
/** One function tool, as `tool()` returns it: checked and frozen. */
|
|
51
|
+
export interface FunctionTool {
|
|
52
|
+
/** The discriminator `Agent` uses. */
|
|
53
|
+
readonly type: "function";
|
|
54
|
+
readonly name: string;
|
|
55
|
+
readonly description: string;
|
|
56
|
+
/** The resolved JSON Schema (a zod schema's is inlined, `$schema` dropped). */
|
|
57
|
+
readonly parameters: Readonly<Record<string, unknown>>;
|
|
58
|
+
readonly timeoutMs: number;
|
|
59
|
+
}
|
|
60
|
+
/** How deep `value` nests objects and lists, as the server counts it: `value` is 1, scalars don't count. */
|
|
61
|
+
export declare function containerDepth(value: unknown): number;
|
|
62
|
+
export declare function compactBytes(value: unknown): number;
|
|
63
|
+
/**
|
|
64
|
+
* A function the agent may call; it runs in this process when the model calls it.
|
|
65
|
+
*
|
|
66
|
+
* `parameters` is a zod object schema (the model's arguments are parsed with it before `execute` runs) or a JSON
|
|
67
|
+
* Schema object (written as given; required and unknown properties are checked). Throws `UserError` on what the
|
|
68
|
+
* server would refuse.
|
|
69
|
+
*/
|
|
70
|
+
export declare function tool<P extends ParseableSchema | Record<string, unknown>>(options: FunctionToolOptions<P>): FunctionTool;
|
|
71
|
+
/** A tool built by `tool()` (or an object of that shape, which Agent re-checks through `tool()`). */
|
|
72
|
+
export declare function isFunctionTool(value: unknown): value is FunctionTool;
|
|
73
|
+
/** Whether `value` came from `tool()` itself, with its `execute` attached. */
|
|
74
|
+
export declare function isBuiltFunctionTool(value: unknown): value is FunctionTool;
|
|
75
|
+
/** One `functions` entry of agent.json. */
|
|
76
|
+
export declare function functionToolSettings(t: FunctionTool): Record<string, unknown>;
|
|
77
|
+
/** One call's result, as posted to the server. */
|
|
78
|
+
export interface FunctionResult {
|
|
79
|
+
callId: string;
|
|
80
|
+
output: string;
|
|
81
|
+
isError: boolean;
|
|
82
|
+
}
|
|
83
|
+
/** Thrown by `runCalls` when its signal aborts. */
|
|
84
|
+
export declare class CallsCancelled extends Error {
|
|
85
|
+
}
|
|
86
|
+
/** The model's arguments as `execute` takes them; throws UserError when they don't fit the schema. */
|
|
87
|
+
export declare function toolArguments(t: FunctionTool, args: unknown): unknown;
|
|
88
|
+
/** Strings as is; everything else as JSON (`String()` when JSON can't hold it). */
|
|
89
|
+
export declare function stringify(value: unknown): string;
|
|
90
|
+
/** Cut the largest outputs first, each ending with a note, so all of them fit `maxBytes` UTF-8 bytes. */
|
|
91
|
+
export declare function fit(outputs: string[], maxBytes?: number): string[];
|
|
92
|
+
/**
|
|
93
|
+
* Run every call at once and return one result per call, in call order. A call that throws, times out, names a
|
|
94
|
+
* function this process doesn't have, or has arguments that don't fit becomes a failed result the model can act on;
|
|
95
|
+
* with `raiseErrors` an error thrown by `execute` is thrown instead.
|
|
96
|
+
*/
|
|
97
|
+
export declare function runCalls(tools: ReadonlyMap<string, FunctionTool>, calls: readonly FunctionCallRequest[], { signal, raiseErrors }: {
|
|
98
|
+
signal: AbortSignal;
|
|
99
|
+
raiseErrors?: boolean;
|
|
100
|
+
}): Promise<FunctionResult[]>;
|
|
101
|
+
export {};
|
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Function tools: functions the agent calls and the runner runs in the caller's process (agent.json `functions`).
|
|
3
|
+
*
|
|
4
|
+
* `tool({ name, description, parameters, execute })` declares one. When the model calls it, the turn pauses on the
|
|
5
|
+
* server; `run()` calls `execute` here and posts the result back. `execute` is never sent anywhere.
|
|
6
|
+
*
|
|
7
|
+
* The checks mirror panja's `claw_common/agent_settings/functions.py` (and the Python SDK's `function_tool.py`), so a
|
|
8
|
+
* function the server would refuse fails when it is built, not at deploy.
|
|
9
|
+
*/
|
|
10
|
+
import { UserError } from "./errors.js";
|
|
11
|
+
import { inlineSchema, isSchemaLike, sameKey, schemaProblem } from "./output.js";
|
|
12
|
+
export const NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/;
|
|
13
|
+
export const DESCRIPTION_MAX_CHARS = 1024;
|
|
14
|
+
/** The server's caps: one function's `parameters` (compact JSON), how many functions, and all of them together. */
|
|
15
|
+
export const PARAMETERS_MAX_BYTES = 16 * 1024;
|
|
16
|
+
/** The deepest JSON nesting of `parameters`, counting every object and list (the root object is 1). */
|
|
17
|
+
export const PARAMETERS_MAX_DEPTH = 16;
|
|
18
|
+
/** Names a function may not take: panja's `RESERVED_FUNCTION_NAMES` (platform tools, harness plumbing, built-in and
|
|
19
|
+
* sandbox tool names, retired v11 names, `clarify`), expanded. `shared/function_tool_vectors.json` pins it. */
|
|
20
|
+
export const RESERVED_FUNCTION_NAMES = new Set([
|
|
21
|
+
"bash", "browse_addons", "clarify", "code_download_file", "code_execute", "code_install_packages",
|
|
22
|
+
"code_list_files", "code_upload_file", "cron", "delegate_task", "describe_tools", "fetch_repo", "final_answer",
|
|
23
|
+
"image_describe", "list_artifacts", "manage_skill_assign", "manage_skill_create", "manage_skill_delete",
|
|
24
|
+
"manage_skill_list", "manage_skill_show", "manage_skill_update", "manage_subagents", "patch", "present_output",
|
|
25
|
+
"read_file", "recommend_addons", "request_authorization", "run_program", "search_capabilities", "search_files",
|
|
26
|
+
"share_file", "skill_view", "slack_list_bot_conversations", "slack_post_as_bot", "snapshot_repo", "todo",
|
|
27
|
+
"tool_call", "tool_search", "translate_text", "upload", "verify_requirements", "view_image", "web_fetch",
|
|
28
|
+
"web_search", "workspace_emit", "workspace_output", "workspace_promote_archive", "workspace_repo", "write_file",
|
|
29
|
+
]);
|
|
30
|
+
export const FUNCTIONS_MAX = 32;
|
|
31
|
+
/** The server's range for `function_timeout_seconds` (save_check's maximum), and its value when agent.json leaves
|
|
32
|
+
* it out. */
|
|
33
|
+
export const FUNCTION_TIMEOUT_RANGE = [10, 3000];
|
|
34
|
+
export const DEFAULT_FUNCTION_TIMEOUT_SECONDS = 600;
|
|
35
|
+
export const FUNCTIONS_TOTAL_MAX_BYTES = 64 * 1024;
|
|
36
|
+
export /** setTimeout's largest delay. */ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
|
|
37
|
+
const DEFAULT_TIMEOUT_MS = 60000;
|
|
38
|
+
/** The server's default cap on one post's outputs together (`CLAW_FUNCTION_RESULT_MAX_BYTES`, UTF-8). It refuses
|
|
39
|
+
* (413) rather than truncates, so the runner truncates first. */
|
|
40
|
+
export const RESULTS_MAX_BYTES = 65536;
|
|
41
|
+
export const TRUNCATION_NOTE = "\n[truncated by sarvam-agents-client]";
|
|
42
|
+
const NAME_MAPS = ["properties", "$defs", "definitions", "dependentSchemas", "patternProperties"];
|
|
43
|
+
const DATA_KEYWORDS = ["enum", "const", "default", "examples", "required"];
|
|
44
|
+
/** Close every object schema that lists properties (`additionalProperties: false`), as Python's schemas are. */
|
|
45
|
+
function closeObjects(node) {
|
|
46
|
+
if (Array.isArray(node))
|
|
47
|
+
return node.map(closeObjects);
|
|
48
|
+
if (!isObject(node))
|
|
49
|
+
return node;
|
|
50
|
+
const out = {};
|
|
51
|
+
for (const [key, value] of Object.entries(node)) {
|
|
52
|
+
if (DATA_KEYWORDS.indexOf(key) !== -1)
|
|
53
|
+
out[key] = value;
|
|
54
|
+
else if (NAME_MAPS.indexOf(key) !== -1 && isObject(value)) {
|
|
55
|
+
out[key] = Object.fromEntries(Object.entries(value).map(([k, v]) => [k, closeObjects(v)]));
|
|
56
|
+
}
|
|
57
|
+
else
|
|
58
|
+
out[key] = closeObjects(value);
|
|
59
|
+
}
|
|
60
|
+
if (out["type"] === "object" && "properties" in out && !("additionalProperties" in out)) {
|
|
61
|
+
out["additionalProperties"] = false;
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
/** The functions and zod schemas behind each tool; kept off the frozen object so Agent's deepFreeze leaves them. */
|
|
66
|
+
const internals = new WeakMap();
|
|
67
|
+
function isObject(v) {
|
|
68
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
69
|
+
}
|
|
70
|
+
function chars(s) {
|
|
71
|
+
return Array.from(s).length;
|
|
72
|
+
}
|
|
73
|
+
/** How deep `value` nests objects and lists, as the server counts it: `value` is 1, scalars don't count. */
|
|
74
|
+
export function containerDepth(value) {
|
|
75
|
+
let deepest = 0;
|
|
76
|
+
const stack = [[value, 1]];
|
|
77
|
+
while (stack.length) {
|
|
78
|
+
const [node, depth] = stack.pop();
|
|
79
|
+
if (node === null || typeof node !== "object")
|
|
80
|
+
continue;
|
|
81
|
+
deepest = Math.max(deepest, depth);
|
|
82
|
+
if (depth > PARAMETERS_MAX_DEPTH)
|
|
83
|
+
break;
|
|
84
|
+
for (const child of Array.isArray(node) ? node : Object.values(node))
|
|
85
|
+
stack.push([child, depth + 1]);
|
|
86
|
+
}
|
|
87
|
+
return deepest;
|
|
88
|
+
}
|
|
89
|
+
export function compactBytes(value) {
|
|
90
|
+
return new TextEncoder().encode(JSON.stringify(value)).length;
|
|
91
|
+
}
|
|
92
|
+
function deepFreeze(value) {
|
|
93
|
+
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
94
|
+
Object.freeze(value);
|
|
95
|
+
for (const key of Object.keys(value))
|
|
96
|
+
deepFreeze(value[key]);
|
|
97
|
+
}
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* A function the agent may call; it runs in this process when the model calls it.
|
|
102
|
+
*
|
|
103
|
+
* `parameters` is a zod object schema (the model's arguments are parsed with it before `execute` runs) or a JSON
|
|
104
|
+
* Schema object (written as given; required and unknown properties are checked). Throws `UserError` on what the
|
|
105
|
+
* server would refuse.
|
|
106
|
+
*/
|
|
107
|
+
export function tool(options) {
|
|
108
|
+
var _a;
|
|
109
|
+
if (!isObject(options)) {
|
|
110
|
+
throw new UserError(`tools.function: build function tools with tool({ name, description, parameters, execute }) (got ${JSON.stringify(options)})`);
|
|
111
|
+
}
|
|
112
|
+
const name = options.name;
|
|
113
|
+
if (typeof name !== "string" || !NAME_PATTERN.test(name)) {
|
|
114
|
+
throw new UserError("tools.function: name must be letters, digits, _ or -, start with a letter or _, and be at most " +
|
|
115
|
+
`64 characters. Got ${JSON.stringify(name)}.`);
|
|
116
|
+
}
|
|
117
|
+
if (RESERVED_FUNCTION_NAMES.has(name)) {
|
|
118
|
+
throw new UserError(`tools.function: ${JSON.stringify(name)} is reserved: a built-in or platform tool has that name; ` +
|
|
119
|
+
"choose another.");
|
|
120
|
+
}
|
|
121
|
+
const fail = (field, sentence) => {
|
|
122
|
+
throw new UserError(`tools.${name}.${field}: ${sentence}`);
|
|
123
|
+
};
|
|
124
|
+
const description = options.description;
|
|
125
|
+
if (typeof description !== "string" || chars(description) < 1 || chars(description) > DESCRIPTION_MAX_CHARS) {
|
|
126
|
+
fail("description", `description must be 1 to ${DESCRIPTION_MAX_CHARS} characters.`);
|
|
127
|
+
}
|
|
128
|
+
if (typeof options.execute !== "function")
|
|
129
|
+
fail("execute", "execute must be a function.");
|
|
130
|
+
const timeoutMs = (_a = options.timeoutMs) !== null && _a !== void 0 ? _a : DEFAULT_TIMEOUT_MS;
|
|
131
|
+
if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMEOUT_MS) {
|
|
132
|
+
// Past 2^31-1 ms setTimeout fires at once; the server's function timeout is at most 3000 s anyway.
|
|
133
|
+
fail("timeoutMs", `timeoutMs must be a number of milliseconds > 0 and at most ${MAX_TIMEOUT_MS}.`);
|
|
134
|
+
}
|
|
135
|
+
const raw = options.parameters;
|
|
136
|
+
let parameters = {};
|
|
137
|
+
let schema;
|
|
138
|
+
if (isSchemaLike(raw)) {
|
|
139
|
+
schema = raw;
|
|
140
|
+
// The arguments are the schema's input: a field with a default is optional for the model.
|
|
141
|
+
const json = schema.toJSONSchema({ io: "input" });
|
|
142
|
+
parameters = closeObjects(inlineSchema(json, `tools.${name}.parameters`));
|
|
143
|
+
}
|
|
144
|
+
else if (isObject(raw)) {
|
|
145
|
+
try {
|
|
146
|
+
parameters = JSON.parse(JSON.stringify(raw));
|
|
147
|
+
}
|
|
148
|
+
catch (_b) {
|
|
149
|
+
fail("parameters", "parameters is not a valid JSON schema.");
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
fail("parameters", 'parameters must be a zod object schema, or a JSON schema with "type": "object".');
|
|
154
|
+
}
|
|
155
|
+
// The server's checks, in its order.
|
|
156
|
+
if (parameters["type"] !== "object")
|
|
157
|
+
fail("parameters", 'parameters must be a JSON schema with "type": "object".');
|
|
158
|
+
if (containerDepth(parameters) > PARAMETERS_MAX_DEPTH) {
|
|
159
|
+
fail("parameters", `parameters is nested more than ${PARAMETERS_MAX_DEPTH} levels (objects and lists); flatten the ` +
|
|
160
|
+
"arguments.");
|
|
161
|
+
}
|
|
162
|
+
const size = compactBytes(parameters);
|
|
163
|
+
if (size > PARAMETERS_MAX_BYTES) {
|
|
164
|
+
fail("parameters", `parameters are ${size} bytes as JSON Schema; the server allows at most 16 KB.`);
|
|
165
|
+
}
|
|
166
|
+
const problem = schemaProblem(parameters);
|
|
167
|
+
if (problem !== undefined)
|
|
168
|
+
fail("parameters", `parameters is not a valid JSON Schema: ${problem}`);
|
|
169
|
+
const out = { type: "function", name, description, parameters, timeoutMs };
|
|
170
|
+
internals.set(out, { execute: options.execute, schema });
|
|
171
|
+
return deepFreeze(out);
|
|
172
|
+
}
|
|
173
|
+
/** A tool built by `tool()` (or an object of that shape, which Agent re-checks through `tool()`). */
|
|
174
|
+
export function isFunctionTool(value) {
|
|
175
|
+
return isObject(value) && value["type"] === "function";
|
|
176
|
+
}
|
|
177
|
+
/** Whether `value` came from `tool()` itself, with its `execute` attached. */
|
|
178
|
+
export function isBuiltFunctionTool(value) {
|
|
179
|
+
return isFunctionTool(value) && internals.has(value);
|
|
180
|
+
}
|
|
181
|
+
/** One `functions` entry of agent.json. */
|
|
182
|
+
export function functionToolSettings(t) {
|
|
183
|
+
return { name: t.name, description: t.description, parameters: JSON.parse(JSON.stringify(t.parameters)) };
|
|
184
|
+
}
|
|
185
|
+
/** Thrown by `runCalls` when its signal aborts. */
|
|
186
|
+
export class CallsCancelled extends Error {
|
|
187
|
+
}
|
|
188
|
+
class TimedOut extends Error {
|
|
189
|
+
}
|
|
190
|
+
function describe(err) {
|
|
191
|
+
if (err instanceof Error)
|
|
192
|
+
return `${err.name}: ${err.message}`;
|
|
193
|
+
return String(err);
|
|
194
|
+
}
|
|
195
|
+
/** The model's arguments as `execute` takes them; throws UserError when they don't fit the schema. */
|
|
196
|
+
export function toolArguments(t, args) {
|
|
197
|
+
var _a;
|
|
198
|
+
if (!isObject(args))
|
|
199
|
+
throw new UserError(`invalid arguments for ${t.name}: arguments must be a JSON object`);
|
|
200
|
+
const schema = (_a = internals.get(t)) === null || _a === void 0 ? void 0 : _a.schema;
|
|
201
|
+
if (schema !== undefined) {
|
|
202
|
+
try {
|
|
203
|
+
return schema.parse(args);
|
|
204
|
+
}
|
|
205
|
+
catch (err) {
|
|
206
|
+
const issues = err.issues;
|
|
207
|
+
const text = Array.isArray(issues)
|
|
208
|
+
? issues.slice(0, 5).map((i) => { var _a; return `${((_a = i.path) !== null && _a !== void 0 ? _a : []).join(".") || "$"}: ${i.message}`; }).join("; ")
|
|
209
|
+
: err.message;
|
|
210
|
+
throw new UserError(`invalid arguments for ${t.name}: ${text}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const required = Array.isArray(t.parameters["required"]) ? t.parameters["required"] : [];
|
|
214
|
+
const missing = required.filter((k) => !Object.prototype.hasOwnProperty.call(args, k));
|
|
215
|
+
if (missing.length)
|
|
216
|
+
throw new UserError(`invalid arguments for ${t.name}: missing ${missing.join(", ")}`);
|
|
217
|
+
const properties = isObject(t.parameters["properties"]) ? t.parameters["properties"] : {};
|
|
218
|
+
if (t.parameters["additionalProperties"] === false) {
|
|
219
|
+
const extra = Object.keys(args).filter((k) => !Object.prototype.hasOwnProperty.call(properties, k));
|
|
220
|
+
if (extra.length)
|
|
221
|
+
throw new UserError(`invalid arguments for ${t.name}: unknown ${extra.join(", ")}`);
|
|
222
|
+
}
|
|
223
|
+
const issues = [];
|
|
224
|
+
checkValue(args, t.parameters, "", 1, issues);
|
|
225
|
+
if (issues.length)
|
|
226
|
+
throw new UserError(`invalid arguments for ${t.name}: ${issues.slice(0, 5).join("; ")}`);
|
|
227
|
+
return args;
|
|
228
|
+
}
|
|
229
|
+
/** JSON Schema `type` names, as a value of each has them (an integer is also a number). */
|
|
230
|
+
function jsonTypes(value) {
|
|
231
|
+
if (value === null)
|
|
232
|
+
return ["null"];
|
|
233
|
+
if (Array.isArray(value))
|
|
234
|
+
return ["array"];
|
|
235
|
+
if (typeof value === "boolean")
|
|
236
|
+
return ["boolean"];
|
|
237
|
+
if (typeof value === "string")
|
|
238
|
+
return ["string"];
|
|
239
|
+
if (typeof value === "number")
|
|
240
|
+
return Number.isInteger(value) ? ["integer", "number"] : ["number"];
|
|
241
|
+
if (isObject(value))
|
|
242
|
+
return ["object"];
|
|
243
|
+
return [];
|
|
244
|
+
}
|
|
245
|
+
/** The model's arguments against a raw JSON Schema `parameters`, as Python's pydantic model checks them: `type`,
|
|
246
|
+
* `enum` and `const`, then `properties` (with `required` and `additionalProperties: false`) and `items` of nested
|
|
247
|
+
* objects and arrays, down to the schema's own depth (at most PARAMETERS_MAX_DEPTH). Collects "path: problem". */
|
|
248
|
+
function checkValue(value, schema, path, depth, issues) {
|
|
249
|
+
var _a;
|
|
250
|
+
if (!isObject(schema) || depth > PARAMETERS_MAX_DEPTH || issues.length >= 5)
|
|
251
|
+
return;
|
|
252
|
+
const at = path || "$";
|
|
253
|
+
const type = schema["type"];
|
|
254
|
+
const allowed = typeof type === "string" ? [type] : Array.isArray(type) ? type.filter((x) => typeof x === "string") : [];
|
|
255
|
+
if (allowed.length && !jsonTypes(value).some((t) => allowed.includes(t))) {
|
|
256
|
+
issues.push(`${at}: expected ${allowed.join(" or ")}, got ${(_a = jsonTypes(value)[0]) !== null && _a !== void 0 ? _a : typeof value}`);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (Array.isArray(schema["enum"]) && !schema["enum"].some((e) => sameKey(e) === sameKey(value))) {
|
|
260
|
+
issues.push(`${at}: must be one of ${JSON.stringify(schema["enum"])}`);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if ("const" in schema && sameKey(schema["const"]) !== sameKey(value)) {
|
|
264
|
+
issues.push(`${at}: must be ${JSON.stringify(schema["const"])}`);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const join = (key) => (path ? `${path}.${key}` : String(key));
|
|
268
|
+
if (isObject(value) && depth > 1) {
|
|
269
|
+
const required = Array.isArray(schema["required"]) ? schema["required"].filter((k) => typeof k === "string") : [];
|
|
270
|
+
const missing = required.filter((k) => !Object.prototype.hasOwnProperty.call(value, k));
|
|
271
|
+
if (missing.length)
|
|
272
|
+
issues.push(`${at}: missing ${missing.join(", ")}`);
|
|
273
|
+
const props = isObject(schema["properties"]) ? schema["properties"] : {};
|
|
274
|
+
if (schema["additionalProperties"] === false) {
|
|
275
|
+
const extra = Object.keys(value).filter((k) => !Object.prototype.hasOwnProperty.call(props, k));
|
|
276
|
+
if (extra.length)
|
|
277
|
+
issues.push(`${at}: unknown ${extra.join(", ")}`);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (isObject(value) && isObject(schema["properties"])) {
|
|
281
|
+
for (const [key, sub] of Object.entries(schema["properties"])) {
|
|
282
|
+
if (Object.prototype.hasOwnProperty.call(value, key))
|
|
283
|
+
checkValue(value[key], sub, join(key), depth + 1, issues);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (Array.isArray(value) && isObject(schema["items"])) {
|
|
287
|
+
value.forEach((item, n) => checkValue(item, schema["items"], join(n), depth + 1, issues));
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/** Strings as is; everything else as JSON (`String()` when JSON can't hold it). */
|
|
291
|
+
export function stringify(value) {
|
|
292
|
+
if (typeof value === "string")
|
|
293
|
+
return value;
|
|
294
|
+
if (value === undefined || typeof value === "function" || typeof value === "symbol")
|
|
295
|
+
return String(value);
|
|
296
|
+
try {
|
|
297
|
+
const json = JSON.stringify(value);
|
|
298
|
+
return json === undefined ? String(value) : json;
|
|
299
|
+
}
|
|
300
|
+
catch (_a) {
|
|
301
|
+
return String(value);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/** Cut the largest outputs first, each ending with a note, so all of them fit `maxBytes` UTF-8 bytes. */
|
|
305
|
+
export function fit(outputs, maxBytes = RESULTS_MAX_BYTES) {
|
|
306
|
+
const encoder = new TextEncoder();
|
|
307
|
+
const bytes = outputs.map((o) => encoder.encode(o));
|
|
308
|
+
const sizes = bytes.map((b) => b.length);
|
|
309
|
+
if (sizes.reduce((a, b) => a + b, 0) <= maxBytes)
|
|
310
|
+
return outputs;
|
|
311
|
+
// The largest cap every output can keep: outputs at or under it stay whole, the rest are cut to it.
|
|
312
|
+
let low = 0;
|
|
313
|
+
let high = Math.max(...sizes);
|
|
314
|
+
while (low < high) {
|
|
315
|
+
const mid = Math.floor((low + high + 1) / 2);
|
|
316
|
+
if (sizes.reduce((a, s) => a + Math.min(s, mid), 0) <= maxBytes)
|
|
317
|
+
low = mid;
|
|
318
|
+
else
|
|
319
|
+
high = mid - 1;
|
|
320
|
+
}
|
|
321
|
+
const noteBytes = encoder.encode(TRUNCATION_NOTE).length;
|
|
322
|
+
const decoder = new TextDecoder();
|
|
323
|
+
return outputs.map((o, i) => {
|
|
324
|
+
if (sizes[i] <= low)
|
|
325
|
+
return o;
|
|
326
|
+
let keep = Math.max(0, low - noteBytes);
|
|
327
|
+
while (keep > 0 && (bytes[i][keep] & 0xc0) === 0x80)
|
|
328
|
+
keep--; // never cut inside a character
|
|
329
|
+
return decoder.decode(bytes[i].subarray(0, keep)) + TRUNCATION_NOTE;
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
async function runOne(t, call, known, signal, raiseErrors) {
|
|
333
|
+
if (t === undefined) {
|
|
334
|
+
return [`function ${JSON.stringify(call.name)} is not defined in this process (known: ${known.join(", ") || "none"}); ` +
|
|
335
|
+
"the app may be running older code than the agent", true];
|
|
336
|
+
}
|
|
337
|
+
let args;
|
|
338
|
+
try {
|
|
339
|
+
args = toolArguments(t, call.arguments);
|
|
340
|
+
}
|
|
341
|
+
catch (err) {
|
|
342
|
+
return [err.message, true];
|
|
343
|
+
}
|
|
344
|
+
const controller = new AbortController();
|
|
345
|
+
const onAbort = () => controller.abort(signal.reason);
|
|
346
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
347
|
+
let timer;
|
|
348
|
+
const timeout = new Promise((_, reject) => {
|
|
349
|
+
timer = setTimeout(() => {
|
|
350
|
+
controller.abort(new TimedOut());
|
|
351
|
+
reject(new TimedOut());
|
|
352
|
+
}, t.timeoutMs);
|
|
353
|
+
});
|
|
354
|
+
try {
|
|
355
|
+
const { execute } = internals.get(t);
|
|
356
|
+
const value = await Promise.race([
|
|
357
|
+
Promise.resolve().then(() => execute(args, { callId: call.callId, signal: controller.signal })),
|
|
358
|
+
timeout,
|
|
359
|
+
]);
|
|
360
|
+
return [stringify(value), false];
|
|
361
|
+
}
|
|
362
|
+
catch (err) {
|
|
363
|
+
if (err instanceof TimedOut)
|
|
364
|
+
return [`${t.name} timed out after ${t.timeoutMs / 1000} seconds`, true];
|
|
365
|
+
if (signal.aborted)
|
|
366
|
+
throw new CallsCancelled();
|
|
367
|
+
if (raiseErrors)
|
|
368
|
+
throw err;
|
|
369
|
+
return [describe(err), true];
|
|
370
|
+
}
|
|
371
|
+
finally {
|
|
372
|
+
clearTimeout(timer);
|
|
373
|
+
signal.removeEventListener("abort", onAbort);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Run every call at once and return one result per call, in call order. A call that throws, times out, names a
|
|
378
|
+
* function this process doesn't have, or has arguments that don't fit becomes a failed result the model can act on;
|
|
379
|
+
* with `raiseErrors` an error thrown by `execute` is thrown instead.
|
|
380
|
+
*/
|
|
381
|
+
export async function runCalls(tools, calls, { signal, raiseErrors = false }) {
|
|
382
|
+
const known = Array.from(tools.keys()).sort();
|
|
383
|
+
// With raiseErrors the first throw aborts every sibling call (their results would be dropped anyway).
|
|
384
|
+
const batch = new AbortController();
|
|
385
|
+
const onAbort = () => batch.abort(signal.reason);
|
|
386
|
+
if (signal.aborted)
|
|
387
|
+
batch.abort(signal.reason);
|
|
388
|
+
else
|
|
389
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
390
|
+
let outputs;
|
|
391
|
+
try {
|
|
392
|
+
outputs = await Promise.all(calls.map((c) => runOne(tools.get(c.name), c, known, batch.signal, raiseErrors)
|
|
393
|
+
.catch((err) => {
|
|
394
|
+
if (raiseErrors && !(err instanceof CallsCancelled) && !batch.signal.aborted)
|
|
395
|
+
batch.abort(err);
|
|
396
|
+
throw err;
|
|
397
|
+
})));
|
|
398
|
+
}
|
|
399
|
+
finally {
|
|
400
|
+
signal.removeEventListener("abort", onAbort);
|
|
401
|
+
}
|
|
402
|
+
if (signal.aborted)
|
|
403
|
+
throw new CallsCancelled();
|
|
404
|
+
const texts = fit(outputs.map(([text]) => text));
|
|
405
|
+
return calls.map((c, i) => ({ callId: c.callId, output: texts[i], isError: outputs[i][1] }));
|
|
406
|
+
}
|
|
@@ -2,13 +2,17 @@ export * from "./errors.js";
|
|
|
2
2
|
export * from "./fingerprint.js";
|
|
3
3
|
export * from "./tools.js";
|
|
4
4
|
export * from "./agent.js";
|
|
5
|
+
export { tool } from "./functionTool.js";
|
|
6
|
+
export type { FunctionCallDetails, FunctionTool, FunctionToolArgs, FunctionToolOptions } from "./functionTool.js";
|
|
7
|
+
export type { Webhook } from "./webhook.js";
|
|
5
8
|
export type { Event, ClarifyQuestion, FunctionCallRequest, OutputCitation } from "./events.js";
|
|
6
9
|
export { SettingsTransport } from "./settingsTransport.js";
|
|
7
|
-
export type { RemoteAgent, SettingsWarning, TurnStream, Transport } from "./transport.js";
|
|
10
|
+
export type { PendingFunctionCalls, RemoteAgent, SettingsWarning, TurnStream, Transport } from "./transport.js";
|
|
11
|
+
export type { FunctionResult } from "./functionTool.js";
|
|
8
12
|
export { deploy, undeploy, setDefaultClient } from "./deploy.js";
|
|
9
13
|
export type { Deployment } from "./deploy.js";
|
|
10
14
|
export { run, RunResult, StreamedRunResult } from "./run.js";
|
|
11
15
|
export type { RunOptions, RunStreamEvent, ClarifyHandler, StopReason } from "./run.js";
|
|
12
16
|
export type { JsonSchemaOutputType, OutputType, ResolvedOutput, SchemaLikeOutputType } from "./output.js";
|
|
13
17
|
export { RunState } from "./runState.js";
|
|
14
|
-
export type { Interruption } from "./runState.js";
|
|
18
|
+
export type { Interruption, PendingFunctionCall } from "./runState.js";
|
|
@@ -2,6 +2,7 @@ export * from "./errors.js";
|
|
|
2
2
|
export * from "./fingerprint.js";
|
|
3
3
|
export * from "./tools.js";
|
|
4
4
|
export * from "./agent.js";
|
|
5
|
+
export { tool } from "./functionTool.js";
|
|
5
6
|
export { SettingsTransport } from "./settingsTransport.js";
|
|
6
7
|
export { deploy, undeploy, setDefaultClient } from "./deploy.js";
|
|
7
8
|
export { run, RunResult, StreamedRunResult } from "./run.js";
|
|
@@ -15,9 +15,20 @@ export type OutputType = JsonSchemaOutputType | SchemaLikeOutputType<unknown>;
|
|
|
15
15
|
export type ResolvedOutput<T> = [T] extends [undefined] ? string : T extends {
|
|
16
16
|
parse(value: unknown): infer R;
|
|
17
17
|
} ? R : unknown;
|
|
18
|
+
export declare function isSchemaLike(v: unknown): v is SchemaLikeOutputType;
|
|
18
19
|
export declare function checkOutputType(v: unknown): void;
|
|
20
|
+
/** A JSON Schema (a copy) with every `$defs`/`definitions` entry inlined and `$schema` dropped (function tools'
|
|
21
|
+
* `parameters`). `label` names the field in the UserError a recursive or dangling reference raises. */
|
|
22
|
+
export declare function inlineSchema(schema: Record<string, unknown>, label: string): Record<string, unknown>;
|
|
19
23
|
/** Nesting depth of a JSON value, counted like the server: the root is 1. */
|
|
20
24
|
export declare function schemaDepth(node: unknown): number;
|
|
25
|
+
/** A value's identity for uniqueness, as the server compares: `1` equals `1.0`, `true` is not `1`. */
|
|
26
|
+
/** A canonical key for a JSON value: equal keys for equal values, key order ignored. */
|
|
27
|
+
export declare function sameKey(v: unknown): string;
|
|
28
|
+
/** Why `schema` fails its dialect's meta-schema (allowlisted keywords only), or undefined. */
|
|
29
|
+
/** Why `schema` is not a valid JSON Schema for its `$schema` dialect (2020-12 when absent or unknown, as the server's
|
|
30
|
+
* `validator_for` picks), or undefined. Checks the keywords the output-schema allowlist knows; others pass. */
|
|
31
|
+
export declare function schemaProblem(schema: Record<string, unknown>): string | undefined;
|
|
21
32
|
/** The output type's JSON Schema with definitions inlined, an OpenAPI `discriminator` and a no-op
|
|
22
33
|
* `propertyNames: {type: "string"}` dropped, and a root `$schema` naming 2020-12 (what zod writes, and the server's
|
|
23
34
|
* default) dropped; throws UserError on what the server refuses. Another `$schema` is kept, so the server reads the
|
|
@@ -42,7 +42,7 @@ const COUNTS = new Set(["minLength", "maxLength", "minItems", "maxItems", "minPr
|
|
|
42
42
|
function isObject(v) {
|
|
43
43
|
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
44
44
|
}
|
|
45
|
-
function isSchemaLike(v) {
|
|
45
|
+
export function isSchemaLike(v) {
|
|
46
46
|
return v !== null && typeof v === "object" &&
|
|
47
47
|
typeof v.parse === "function" &&
|
|
48
48
|
typeof v.toJSONSchema === "function";
|
|
@@ -56,9 +56,9 @@ export function checkOutputType(v) {
|
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
58
|
/** Replace each `$ref` to a definition with that definition, walking schema positions as the server does. */
|
|
59
|
-
function inline(node, defs, seen) {
|
|
59
|
+
function inline(node, defs, seen, label = "outputType") {
|
|
60
60
|
if (Array.isArray(node))
|
|
61
|
-
return node.map((v) => inline(v, defs, seen));
|
|
61
|
+
return node.map((v) => inline(v, defs, seen, label));
|
|
62
62
|
if (!isObject(node))
|
|
63
63
|
return node;
|
|
64
64
|
const ref = node["$ref"];
|
|
@@ -66,15 +66,15 @@ function inline(node, defs, seen) {
|
|
|
66
66
|
if (typeof ref === "string" && ref.startsWith(prefix)) {
|
|
67
67
|
const name = ref.slice(prefix.length);
|
|
68
68
|
if (seen.has(name))
|
|
69
|
-
throw new UserError(
|
|
69
|
+
throw new UserError(`${label}: ${name} is recursive; the server accepts no references`);
|
|
70
70
|
if (!(name in defs))
|
|
71
|
-
throw new UserError(
|
|
71
|
+
throw new UserError(`${label}: ${ref} doesn't resolve`);
|
|
72
72
|
const rest = {};
|
|
73
73
|
for (const [k, v] of Object.entries(node))
|
|
74
74
|
if (k !== "$ref")
|
|
75
75
|
rest[k] = v;
|
|
76
76
|
const target = JSON.parse(JSON.stringify(defs[name]));
|
|
77
|
-
return inline({ ...target, ...rest }, defs, new Set([...seen, name]));
|
|
77
|
+
return inline({ ...target, ...rest }, defs, new Set([...seen, name]), label);
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
80
|
const out = {};
|
|
@@ -90,14 +90,24 @@ function inline(node, defs, seen) {
|
|
|
90
90
|
else if (NAME_MAPS.has(key) && isObject(value)) {
|
|
91
91
|
const map = {};
|
|
92
92
|
for (const [name, child] of Object.entries(value))
|
|
93
|
-
map[name] = inline(child, defs, seen);
|
|
93
|
+
map[name] = inline(child, defs, seen, label);
|
|
94
94
|
out[key] = map;
|
|
95
95
|
}
|
|
96
96
|
else
|
|
97
|
-
out[key] = inline(value, defs, seen);
|
|
97
|
+
out[key] = inline(value, defs, seen, label);
|
|
98
98
|
}
|
|
99
99
|
return out;
|
|
100
100
|
}
|
|
101
|
+
/** A JSON Schema (a copy) with every `$defs`/`definitions` entry inlined and `$schema` dropped (function tools'
|
|
102
|
+
* `parameters`). `label` names the field in the UserError a recursive or dangling reference raises. */
|
|
103
|
+
export function inlineSchema(schema, label) {
|
|
104
|
+
const raw = JSON.parse(JSON.stringify(schema));
|
|
105
|
+
const defs = { ...(isObject(raw["$defs"]) ? raw["$defs"] : {}), ...(isObject(raw["definitions"]) ? raw["definitions"] : {}) };
|
|
106
|
+
delete raw["$defs"];
|
|
107
|
+
delete raw["definitions"];
|
|
108
|
+
delete raw["$schema"];
|
|
109
|
+
return inline(raw, defs, new Set(), label);
|
|
110
|
+
}
|
|
101
111
|
/** Nesting depth of a JSON value, counted like the server: the root is 1. */
|
|
102
112
|
export function schemaDepth(node) {
|
|
103
113
|
let deepest = 0;
|
|
@@ -237,7 +247,8 @@ function isNumber(v) {
|
|
|
237
247
|
return typeof v === "number";
|
|
238
248
|
}
|
|
239
249
|
/** A value's identity for uniqueness, as the server compares: `1` equals `1.0`, `true` is not `1`. */
|
|
240
|
-
|
|
250
|
+
/** A canonical key for a JSON value: equal keys for equal values, key order ignored. */
|
|
251
|
+
export function sameKey(v) {
|
|
241
252
|
if (Array.isArray(v))
|
|
242
253
|
return "[" + v.map(sameKey).join(",") + "]";
|
|
243
254
|
if (isObject(v))
|
|
@@ -248,6 +259,16 @@ function unique(values) {
|
|
|
248
259
|
return new Set(values.map(sameKey)).size === values.length;
|
|
249
260
|
}
|
|
250
261
|
/** Why `schema` fails its dialect's meta-schema (allowlisted keywords only), or undefined. */
|
|
262
|
+
/** Why `schema` is not a valid JSON Schema for its `$schema` dialect (2020-12 when absent or unknown, as the server's
|
|
263
|
+
* `validator_for` picks), or undefined. Checks the keywords the output-schema allowlist knows; others pass. */
|
|
264
|
+
export function schemaProblem(schema) {
|
|
265
|
+
var _a;
|
|
266
|
+
const uri = schema["$schema"];
|
|
267
|
+
if (uri !== undefined && typeof uri !== "string")
|
|
268
|
+
return "$schema must be a dialect URI string";
|
|
269
|
+
const draft = typeof uri === "string" ? (_a = DIALECTS[dialectKey(uri)]) !== null && _a !== void 0 ? _a : 2020 : 2020;
|
|
270
|
+
return metaProblem(schema, draft);
|
|
271
|
+
}
|
|
251
272
|
function metaProblem(schema, draft) {
|
|
252
273
|
const stack = [[schema, ""]];
|
|
253
274
|
while (stack.length) {
|