sarvam-agents-client 0.2.3 → 0.3.1

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