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
@@ -11,6 +11,14 @@ export interface FunctionCallRequest {
11
11
  name: string;
12
12
  arguments: Record<string, unknown>;
13
13
  }
14
+ /** A source the structured output cited: the server's citation-manifest entry, passed through as sent. */
15
+ export interface OutputCitation {
16
+ cite_id: string;
17
+ type?: string;
18
+ url?: string;
19
+ title?: string;
20
+ [key: string]: unknown;
21
+ }
14
22
  export type Event = {
15
23
  kind: "text_start";
16
24
  id: string;
@@ -46,6 +54,32 @@ export type Event = {
46
54
  kind: "stopped";
47
55
  reason: string;
48
56
  }
57
+ /** The turn's structured output (`data-output`); `output` is null and `skipped` says why when the turn ended
58
+ * without one: `limit`, `budget`, `paused` or `suppressed` (a cron turn that ended `[SILENT]`), passed through as
59
+ * sent, so a newer server's value arrives unchanged. */
60
+ | {
61
+ kind: "output";
62
+ output: unknown;
63
+ skipped?: string;
64
+ /** How the server produced it (`tool_in_loop`, `tool_oversize`, `forced_tool`, `native`, `prompted`), passed
65
+ * through as sent. `tool_oversize`: the model's `final_answer` was too large for the tool loop and the server
66
+ * validated it afterwards. */
67
+ mode?: string;
68
+ /** The sources `output` cited, first citation first; absent when it cited none. `output` itself carries no
69
+ * `[cite:...]` markers. */
70
+ citations?: OutputCitation[];
71
+ /** Set when the turn's `final_answer` was refused for size and was not the answer: `oversize_answer_invalid`
72
+ * (it did not validate) or `oversize_answer_dropped` (too large to check), so `output` came from the model's
73
+ * later text. */
74
+ note?: string;
75
+ }
76
+ /** No answer matched the agent's output schema (`data-output-error`); `note` as on `output`. */
77
+ | {
78
+ kind: "output_error";
79
+ errors: string[];
80
+ rawText: string;
81
+ note?: string;
82
+ }
49
83
  /** An agent.json limit ended the turn (`data-turn-limit`); the wrap-up answer still follows. `capKind` is the
50
84
  * server's cap name: `max_turns`, `tool_calls` or `tokens`. `limit` is the agent.json `limits` key that set it
51
85
  * (`max_turns`, `max_tool_calls_per_turn` or `max_tokens_per_turn`) and `value` the configured number; both are
@@ -71,3 +105,7 @@ export type Event = {
71
105
  * Never throws: malformed chunks degrade to `{ kind: "unknown", chunk }`.
72
106
  */
73
107
  export declare function fromUiChunk(chunk: unknown): Event | null;
108
+ /** A stored UIMessage (`GET /v1/conversations/{id}` `messages`) as the stream chunks that would have produced it,
109
+ * ending with `finish`, so a finished turn can be read like a live one. Text parts become one text block each, tool
110
+ * parts a call and (when they have one) its output, `data-*` parts pass through; reasoning is dropped. */
111
+ export declare function chunksFromUiMessage(message: unknown): Record<string, unknown>[];
@@ -2,6 +2,7 @@
2
2
  /** Stream event model for `/v1/responses` UI-message-stream chunks. */
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.fromUiChunk = fromUiChunk;
5
+ exports.chunksFromUiMessage = chunksFromUiMessage;
5
6
  const IGNORED = ["start", "start-step", "finish-step", "tool-input-start", "tool-input-delta"];
6
7
  function isObject(v) {
7
8
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -27,7 +28,7 @@ function fromUiChunk(chunk) {
27
28
  }
28
29
  }
29
30
  function map(chunk) {
30
- var _a, _b;
31
+ var _a, _b, _c;
31
32
  const type = chunk["type"];
32
33
  const data = isObject(chunk["data"]) ? chunk["data"] : {};
33
34
  if (typeof type === "string" && IGNORED.indexOf(type) !== -1)
@@ -100,8 +101,64 @@ function map(chunk) {
100
101
  return { kind: "turn_failed", code: str(chunk["code"], "turn_failed"), message: text(chunk["errorText"]) };
101
102
  case "finish":
102
103
  return { kind: "turn_finished", reason: str(chunk["finishReason"], "stop") };
104
+ case "data-output": {
105
+ const ev = { kind: "output", output: (_c = data["output"]) !== null && _c !== void 0 ? _c : null };
106
+ if (typeof data["skipped"] === "string" && data["skipped"])
107
+ ev.skipped = data["skipped"];
108
+ if (typeof data["mode"] === "string" && data["mode"])
109
+ ev.mode = data["mode"];
110
+ const citations = Array.isArray(data["citations"]) ? data["citations"].filter(isObject) : [];
111
+ if (citations.length)
112
+ ev.citations = citations;
113
+ if (typeof data["note"] === "string" && data["note"])
114
+ ev.note = data["note"];
115
+ return ev;
116
+ }
117
+ case "data-output-error": {
118
+ const errors = data["errors"];
119
+ const ev = {
120
+ kind: "output_error",
121
+ errors: Array.isArray(errors) ? errors.map(String) : typeof errors === "string" ? [errors] : [],
122
+ rawText: text(data["rawText"]),
123
+ };
124
+ if (typeof data["note"] === "string" && data["note"])
125
+ ev.note = data["note"];
126
+ return ev;
127
+ }
103
128
  default:
104
- // data-output and data-output-error are unknown until structured output lands.
105
129
  return { kind: "unknown", chunk };
106
130
  }
107
131
  }
132
+ /** A stored UIMessage (`GET /v1/conversations/{id}` `messages`) as the stream chunks that would have produced it,
133
+ * ending with `finish`, so a finished turn can be read like a live one. Text parts become one text block each, tool
134
+ * parts a call and (when they have one) its output, `data-*` parts pass through; reasoning is dropped. */
135
+ function chunksFromUiMessage(message) {
136
+ const chunks = [];
137
+ const parts = isObject(message) && Array.isArray(message["parts"]) ? message["parts"] : [];
138
+ parts.forEach((part, n) => {
139
+ var _a, _b, _c, _d;
140
+ if (!isObject(part))
141
+ return;
142
+ const kind = typeof part["type"] === "string" ? part["type"] : "";
143
+ if (kind === "text") {
144
+ const id = `msg-text-${n}`;
145
+ chunks.push({ type: "text-start", id }, { type: "text-delta", id, delta: String((_a = part["text"]) !== null && _a !== void 0 ? _a : "") }, { type: "text-end", id });
146
+ }
147
+ else if (kind === "dynamic-tool" || kind.startsWith("tool-")) {
148
+ const name = (_b = part["toolName"]) !== null && _b !== void 0 ? _b : (kind.startsWith("tool-") ? kind.slice("tool-".length) : "");
149
+ const toolCallId = (_c = part["toolCallId"]) !== null && _c !== void 0 ? _c : "";
150
+ chunks.push({ type: "tool-input-available", toolCallId, toolName: name, input: part["input"] });
151
+ if (part["state"] === "output-available") {
152
+ chunks.push({ type: "tool-output-available", toolCallId, output: part["output"] });
153
+ }
154
+ else if (part["state"] === "output-error") {
155
+ chunks.push({ type: "tool-output-available", toolCallId, output: { error: (_d = part["errorText"]) !== null && _d !== void 0 ? _d : "" } });
156
+ }
157
+ }
158
+ else if (kind.startsWith("data-")) {
159
+ chunks.push({ type: kind, id: part["id"], data: part["data"] });
160
+ }
161
+ });
162
+ chunks.push({ type: "finish", finishReason: "stop" });
163
+ return chunks;
164
+ }
@@ -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,420 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CallsCancelled = exports.TRUNCATION_NOTE = exports.RESULTS_MAX_BYTES = exports.MAX_TIMEOUT_MS = exports.FUNCTIONS_TOTAL_MAX_BYTES = exports.DEFAULT_FUNCTION_TIMEOUT_SECONDS = exports.FUNCTION_TIMEOUT_RANGE = exports.FUNCTIONS_MAX = exports.RESERVED_FUNCTION_NAMES = exports.PARAMETERS_MAX_DEPTH = exports.PARAMETERS_MAX_BYTES = exports.DESCRIPTION_MAX_CHARS = exports.NAME_PATTERN = void 0;
4
+ exports.containerDepth = containerDepth;
5
+ exports.compactBytes = compactBytes;
6
+ exports.tool = tool;
7
+ exports.isFunctionTool = isFunctionTool;
8
+ exports.isBuiltFunctionTool = isBuiltFunctionTool;
9
+ exports.functionToolSettings = functionToolSettings;
10
+ exports.toolArguments = toolArguments;
11
+ exports.stringify = stringify;
12
+ exports.fit = fit;
13
+ exports.runCalls = runCalls;
14
+ /**
15
+ * Function tools: functions the agent calls and the runner runs in the caller's process (agent.json `functions`).
16
+ *
17
+ * `tool({ name, description, parameters, execute })` declares one. When the model calls it, the turn pauses on the
18
+ * server; `run()` calls `execute` here and posts the result back. `execute` is never sent anywhere.
19
+ *
20
+ * The checks mirror panja's `claw_common/agent_settings/functions.py` (and the Python SDK's `function_tool.py`), so a
21
+ * function the server would refuse fails when it is built, not at deploy.
22
+ */
23
+ const errors_js_1 = require("./errors.js");
24
+ const output_js_1 = require("./output.js");
25
+ exports.NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/;
26
+ exports.DESCRIPTION_MAX_CHARS = 1024;
27
+ /** The server's caps: one function's `parameters` (compact JSON), how many functions, and all of them together. */
28
+ exports.PARAMETERS_MAX_BYTES = 16 * 1024;
29
+ /** The deepest JSON nesting of `parameters`, counting every object and list (the root object is 1). */
30
+ exports.PARAMETERS_MAX_DEPTH = 16;
31
+ /** Names a function may not take: panja's `RESERVED_FUNCTION_NAMES` (platform tools, harness plumbing, built-in and
32
+ * sandbox tool names, retired v11 names, `clarify`), expanded. `shared/function_tool_vectors.json` pins it. */
33
+ exports.RESERVED_FUNCTION_NAMES = new Set([
34
+ "bash", "browse_addons", "clarify", "code_download_file", "code_execute", "code_install_packages",
35
+ "code_list_files", "code_upload_file", "cron", "delegate_task", "describe_tools", "fetch_repo", "final_answer",
36
+ "image_describe", "list_artifacts", "manage_skill_assign", "manage_skill_create", "manage_skill_delete",
37
+ "manage_skill_list", "manage_skill_show", "manage_skill_update", "manage_subagents", "patch", "present_output",
38
+ "read_file", "recommend_addons", "request_authorization", "run_program", "search_capabilities", "search_files",
39
+ "share_file", "skill_view", "slack_list_bot_conversations", "slack_post_as_bot", "snapshot_repo", "todo",
40
+ "tool_call", "tool_search", "translate_text", "upload", "verify_requirements", "view_image", "web_fetch",
41
+ "web_search", "workspace_emit", "workspace_output", "workspace_promote_archive", "workspace_repo", "write_file",
42
+ ]);
43
+ exports.FUNCTIONS_MAX = 32;
44
+ /** The server's range for `function_timeout_seconds` (save_check's maximum), and its value when agent.json leaves
45
+ * it out. */
46
+ exports.FUNCTION_TIMEOUT_RANGE = [10, 3000];
47
+ exports.DEFAULT_FUNCTION_TIMEOUT_SECONDS = 600;
48
+ exports.FUNCTIONS_TOTAL_MAX_BYTES = 64 * 1024;
49
+ exports.MAX_TIMEOUT_MS = 2 ** 31 - 1;
50
+ const DEFAULT_TIMEOUT_MS = 60000;
51
+ /** The server's default cap on one post's outputs together (`CLAW_FUNCTION_RESULT_MAX_BYTES`, UTF-8). It refuses
52
+ * (413) rather than truncates, so the runner truncates first. */
53
+ exports.RESULTS_MAX_BYTES = 65536;
54
+ exports.TRUNCATION_NOTE = "\n[truncated by sarvam-agents-client]";
55
+ const NAME_MAPS = ["properties", "$defs", "definitions", "dependentSchemas", "patternProperties"];
56
+ const DATA_KEYWORDS = ["enum", "const", "default", "examples", "required"];
57
+ /** Close every object schema that lists properties (`additionalProperties: false`), as Python's schemas are. */
58
+ function closeObjects(node) {
59
+ if (Array.isArray(node))
60
+ return node.map(closeObjects);
61
+ if (!isObject(node))
62
+ return node;
63
+ const out = {};
64
+ for (const [key, value] of Object.entries(node)) {
65
+ if (DATA_KEYWORDS.indexOf(key) !== -1)
66
+ out[key] = value;
67
+ else if (NAME_MAPS.indexOf(key) !== -1 && isObject(value)) {
68
+ out[key] = Object.fromEntries(Object.entries(value).map(([k, v]) => [k, closeObjects(v)]));
69
+ }
70
+ else
71
+ out[key] = closeObjects(value);
72
+ }
73
+ if (out["type"] === "object" && "properties" in out && !("additionalProperties" in out)) {
74
+ out["additionalProperties"] = false;
75
+ }
76
+ return out;
77
+ }
78
+ /** The functions and zod schemas behind each tool; kept off the frozen object so Agent's deepFreeze leaves them. */
79
+ const internals = new WeakMap();
80
+ function isObject(v) {
81
+ return typeof v === "object" && v !== null && !Array.isArray(v);
82
+ }
83
+ function chars(s) {
84
+ return Array.from(s).length;
85
+ }
86
+ /** How deep `value` nests objects and lists, as the server counts it: `value` is 1, scalars don't count. */
87
+ function containerDepth(value) {
88
+ let deepest = 0;
89
+ const stack = [[value, 1]];
90
+ while (stack.length) {
91
+ const [node, depth] = stack.pop();
92
+ if (node === null || typeof node !== "object")
93
+ continue;
94
+ deepest = Math.max(deepest, depth);
95
+ if (depth > exports.PARAMETERS_MAX_DEPTH)
96
+ break;
97
+ for (const child of Array.isArray(node) ? node : Object.values(node))
98
+ stack.push([child, depth + 1]);
99
+ }
100
+ return deepest;
101
+ }
102
+ function compactBytes(value) {
103
+ return new TextEncoder().encode(JSON.stringify(value)).length;
104
+ }
105
+ function deepFreeze(value) {
106
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
107
+ Object.freeze(value);
108
+ for (const key of Object.keys(value))
109
+ deepFreeze(value[key]);
110
+ }
111
+ return value;
112
+ }
113
+ /**
114
+ * A function the agent may call; it runs in this process when the model calls it.
115
+ *
116
+ * `parameters` is a zod object schema (the model's arguments are parsed with it before `execute` runs) or a JSON
117
+ * Schema object (written as given; required and unknown properties are checked). Throws `UserError` on what the
118
+ * server would refuse.
119
+ */
120
+ function tool(options) {
121
+ var _a;
122
+ if (!isObject(options)) {
123
+ throw new errors_js_1.UserError(`tools.function: build function tools with tool({ name, description, parameters, execute }) (got ${JSON.stringify(options)})`);
124
+ }
125
+ const name = options.name;
126
+ if (typeof name !== "string" || !exports.NAME_PATTERN.test(name)) {
127
+ throw new errors_js_1.UserError("tools.function: name must be letters, digits, _ or -, start with a letter or _, and be at most " +
128
+ `64 characters. Got ${JSON.stringify(name)}.`);
129
+ }
130
+ if (exports.RESERVED_FUNCTION_NAMES.has(name)) {
131
+ throw new errors_js_1.UserError(`tools.function: ${JSON.stringify(name)} is reserved: a built-in or platform tool has that name; ` +
132
+ "choose another.");
133
+ }
134
+ const fail = (field, sentence) => {
135
+ throw new errors_js_1.UserError(`tools.${name}.${field}: ${sentence}`);
136
+ };
137
+ const description = options.description;
138
+ if (typeof description !== "string" || chars(description) < 1 || chars(description) > exports.DESCRIPTION_MAX_CHARS) {
139
+ fail("description", `description must be 1 to ${exports.DESCRIPTION_MAX_CHARS} characters.`);
140
+ }
141
+ if (typeof options.execute !== "function")
142
+ fail("execute", "execute must be a function.");
143
+ const timeoutMs = (_a = options.timeoutMs) !== null && _a !== void 0 ? _a : DEFAULT_TIMEOUT_MS;
144
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > exports.MAX_TIMEOUT_MS) {
145
+ // Past 2^31-1 ms setTimeout fires at once; the server's function timeout is at most 3000 s anyway.
146
+ fail("timeoutMs", `timeoutMs must be a number of milliseconds > 0 and at most ${exports.MAX_TIMEOUT_MS}.`);
147
+ }
148
+ const raw = options.parameters;
149
+ let parameters = {};
150
+ let schema;
151
+ if ((0, output_js_1.isSchemaLike)(raw)) {
152
+ schema = raw;
153
+ // The arguments are the schema's input: a field with a default is optional for the model.
154
+ const json = schema.toJSONSchema({ io: "input" });
155
+ parameters = closeObjects((0, output_js_1.inlineSchema)(json, `tools.${name}.parameters`));
156
+ }
157
+ else if (isObject(raw)) {
158
+ try {
159
+ parameters = JSON.parse(JSON.stringify(raw));
160
+ }
161
+ catch (_b) {
162
+ fail("parameters", "parameters is not a valid JSON schema.");
163
+ }
164
+ }
165
+ else {
166
+ fail("parameters", 'parameters must be a zod object schema, or a JSON schema with "type": "object".');
167
+ }
168
+ // The server's checks, in its order.
169
+ if (parameters["type"] !== "object")
170
+ fail("parameters", 'parameters must be a JSON schema with "type": "object".');
171
+ if (containerDepth(parameters) > exports.PARAMETERS_MAX_DEPTH) {
172
+ fail("parameters", `parameters is nested more than ${exports.PARAMETERS_MAX_DEPTH} levels (objects and lists); flatten the ` +
173
+ "arguments.");
174
+ }
175
+ const size = compactBytes(parameters);
176
+ if (size > exports.PARAMETERS_MAX_BYTES) {
177
+ fail("parameters", `parameters are ${size} bytes as JSON Schema; the server allows at most 16 KB.`);
178
+ }
179
+ const problem = (0, output_js_1.schemaProblem)(parameters);
180
+ if (problem !== undefined)
181
+ fail("parameters", `parameters is not a valid JSON Schema: ${problem}`);
182
+ const out = { type: "function", name, description, parameters, timeoutMs };
183
+ internals.set(out, { execute: options.execute, schema });
184
+ return deepFreeze(out);
185
+ }
186
+ /** A tool built by `tool()` (or an object of that shape, which Agent re-checks through `tool()`). */
187
+ function isFunctionTool(value) {
188
+ return isObject(value) && value["type"] === "function";
189
+ }
190
+ /** Whether `value` came from `tool()` itself, with its `execute` attached. */
191
+ function isBuiltFunctionTool(value) {
192
+ return isFunctionTool(value) && internals.has(value);
193
+ }
194
+ /** One `functions` entry of agent.json. */
195
+ function functionToolSettings(t) {
196
+ return { name: t.name, description: t.description, parameters: JSON.parse(JSON.stringify(t.parameters)) };
197
+ }
198
+ /** Thrown by `runCalls` when its signal aborts. */
199
+ class CallsCancelled extends Error {
200
+ }
201
+ exports.CallsCancelled = CallsCancelled;
202
+ class TimedOut extends Error {
203
+ }
204
+ function describe(err) {
205
+ if (err instanceof Error)
206
+ return `${err.name}: ${err.message}`;
207
+ return String(err);
208
+ }
209
+ /** The model's arguments as `execute` takes them; throws UserError when they don't fit the schema. */
210
+ function toolArguments(t, args) {
211
+ var _a;
212
+ if (!isObject(args))
213
+ throw new errors_js_1.UserError(`invalid arguments for ${t.name}: arguments must be a JSON object`);
214
+ const schema = (_a = internals.get(t)) === null || _a === void 0 ? void 0 : _a.schema;
215
+ if (schema !== undefined) {
216
+ try {
217
+ return schema.parse(args);
218
+ }
219
+ catch (err) {
220
+ const issues = err.issues;
221
+ const text = Array.isArray(issues)
222
+ ? issues.slice(0, 5).map((i) => { var _a; return `${((_a = i.path) !== null && _a !== void 0 ? _a : []).join(".") || "$"}: ${i.message}`; }).join("; ")
223
+ : err.message;
224
+ throw new errors_js_1.UserError(`invalid arguments for ${t.name}: ${text}`);
225
+ }
226
+ }
227
+ const required = Array.isArray(t.parameters["required"]) ? t.parameters["required"] : [];
228
+ const missing = required.filter((k) => !Object.prototype.hasOwnProperty.call(args, k));
229
+ if (missing.length)
230
+ throw new errors_js_1.UserError(`invalid arguments for ${t.name}: missing ${missing.join(", ")}`);
231
+ const properties = isObject(t.parameters["properties"]) ? t.parameters["properties"] : {};
232
+ if (t.parameters["additionalProperties"] === false) {
233
+ const extra = Object.keys(args).filter((k) => !Object.prototype.hasOwnProperty.call(properties, k));
234
+ if (extra.length)
235
+ throw new errors_js_1.UserError(`invalid arguments for ${t.name}: unknown ${extra.join(", ")}`);
236
+ }
237
+ const issues = [];
238
+ checkValue(args, t.parameters, "", 1, issues);
239
+ if (issues.length)
240
+ throw new errors_js_1.UserError(`invalid arguments for ${t.name}: ${issues.slice(0, 5).join("; ")}`);
241
+ return args;
242
+ }
243
+ /** JSON Schema `type` names, as a value of each has them (an integer is also a number). */
244
+ function jsonTypes(value) {
245
+ if (value === null)
246
+ return ["null"];
247
+ if (Array.isArray(value))
248
+ return ["array"];
249
+ if (typeof value === "boolean")
250
+ return ["boolean"];
251
+ if (typeof value === "string")
252
+ return ["string"];
253
+ if (typeof value === "number")
254
+ return Number.isInteger(value) ? ["integer", "number"] : ["number"];
255
+ if (isObject(value))
256
+ return ["object"];
257
+ return [];
258
+ }
259
+ /** The model's arguments against a raw JSON Schema `parameters`, as Python's pydantic model checks them: `type`,
260
+ * `enum` and `const`, then `properties` (with `required` and `additionalProperties: false`) and `items` of nested
261
+ * objects and arrays, down to the schema's own depth (at most PARAMETERS_MAX_DEPTH). Collects "path: problem". */
262
+ function checkValue(value, schema, path, depth, issues) {
263
+ var _a;
264
+ if (!isObject(schema) || depth > exports.PARAMETERS_MAX_DEPTH || issues.length >= 5)
265
+ return;
266
+ const at = path || "$";
267
+ const type = schema["type"];
268
+ const allowed = typeof type === "string" ? [type] : Array.isArray(type) ? type.filter((x) => typeof x === "string") : [];
269
+ if (allowed.length && !jsonTypes(value).some((t) => allowed.includes(t))) {
270
+ issues.push(`${at}: expected ${allowed.join(" or ")}, got ${(_a = jsonTypes(value)[0]) !== null && _a !== void 0 ? _a : typeof value}`);
271
+ return;
272
+ }
273
+ if (Array.isArray(schema["enum"]) && !schema["enum"].some((e) => (0, output_js_1.sameKey)(e) === (0, output_js_1.sameKey)(value))) {
274
+ issues.push(`${at}: must be one of ${JSON.stringify(schema["enum"])}`);
275
+ return;
276
+ }
277
+ if ("const" in schema && (0, output_js_1.sameKey)(schema["const"]) !== (0, output_js_1.sameKey)(value)) {
278
+ issues.push(`${at}: must be ${JSON.stringify(schema["const"])}`);
279
+ return;
280
+ }
281
+ const join = (key) => (path ? `${path}.${key}` : String(key));
282
+ if (isObject(value) && depth > 1) {
283
+ const required = Array.isArray(schema["required"]) ? schema["required"].filter((k) => typeof k === "string") : [];
284
+ const missing = required.filter((k) => !Object.prototype.hasOwnProperty.call(value, k));
285
+ if (missing.length)
286
+ issues.push(`${at}: missing ${missing.join(", ")}`);
287
+ const props = isObject(schema["properties"]) ? schema["properties"] : {};
288
+ if (schema["additionalProperties"] === false) {
289
+ const extra = Object.keys(value).filter((k) => !Object.prototype.hasOwnProperty.call(props, k));
290
+ if (extra.length)
291
+ issues.push(`${at}: unknown ${extra.join(", ")}`);
292
+ }
293
+ }
294
+ if (isObject(value) && isObject(schema["properties"])) {
295
+ for (const [key, sub] of Object.entries(schema["properties"])) {
296
+ if (Object.prototype.hasOwnProperty.call(value, key))
297
+ checkValue(value[key], sub, join(key), depth + 1, issues);
298
+ }
299
+ }
300
+ if (Array.isArray(value) && isObject(schema["items"])) {
301
+ value.forEach((item, n) => checkValue(item, schema["items"], join(n), depth + 1, issues));
302
+ }
303
+ }
304
+ /** Strings as is; everything else as JSON (`String()` when JSON can't hold it). */
305
+ function stringify(value) {
306
+ if (typeof value === "string")
307
+ return value;
308
+ if (value === undefined || typeof value === "function" || typeof value === "symbol")
309
+ return String(value);
310
+ try {
311
+ const json = JSON.stringify(value);
312
+ return json === undefined ? String(value) : json;
313
+ }
314
+ catch (_a) {
315
+ return String(value);
316
+ }
317
+ }
318
+ /** Cut the largest outputs first, each ending with a note, so all of them fit `maxBytes` UTF-8 bytes. */
319
+ function fit(outputs, maxBytes = exports.RESULTS_MAX_BYTES) {
320
+ const encoder = new TextEncoder();
321
+ const bytes = outputs.map((o) => encoder.encode(o));
322
+ const sizes = bytes.map((b) => b.length);
323
+ if (sizes.reduce((a, b) => a + b, 0) <= maxBytes)
324
+ return outputs;
325
+ // The largest cap every output can keep: outputs at or under it stay whole, the rest are cut to it.
326
+ let low = 0;
327
+ let high = Math.max(...sizes);
328
+ while (low < high) {
329
+ const mid = Math.floor((low + high + 1) / 2);
330
+ if (sizes.reduce((a, s) => a + Math.min(s, mid), 0) <= maxBytes)
331
+ low = mid;
332
+ else
333
+ high = mid - 1;
334
+ }
335
+ const noteBytes = encoder.encode(exports.TRUNCATION_NOTE).length;
336
+ const decoder = new TextDecoder();
337
+ return outputs.map((o, i) => {
338
+ if (sizes[i] <= low)
339
+ return o;
340
+ let keep = Math.max(0, low - noteBytes);
341
+ while (keep > 0 && (bytes[i][keep] & 0xc0) === 0x80)
342
+ keep--; // never cut inside a character
343
+ return decoder.decode(bytes[i].subarray(0, keep)) + exports.TRUNCATION_NOTE;
344
+ });
345
+ }
346
+ async function runOne(t, call, known, signal, raiseErrors) {
347
+ if (t === undefined) {
348
+ return [`function ${JSON.stringify(call.name)} is not defined in this process (known: ${known.join(", ") || "none"}); ` +
349
+ "the app may be running older code than the agent", true];
350
+ }
351
+ let args;
352
+ try {
353
+ args = toolArguments(t, call.arguments);
354
+ }
355
+ catch (err) {
356
+ return [err.message, true];
357
+ }
358
+ const controller = new AbortController();
359
+ const onAbort = () => controller.abort(signal.reason);
360
+ signal.addEventListener("abort", onAbort, { once: true });
361
+ let timer;
362
+ const timeout = new Promise((_, reject) => {
363
+ timer = setTimeout(() => {
364
+ controller.abort(new TimedOut());
365
+ reject(new TimedOut());
366
+ }, t.timeoutMs);
367
+ });
368
+ try {
369
+ const { execute } = internals.get(t);
370
+ const value = await Promise.race([
371
+ Promise.resolve().then(() => execute(args, { callId: call.callId, signal: controller.signal })),
372
+ timeout,
373
+ ]);
374
+ return [stringify(value), false];
375
+ }
376
+ catch (err) {
377
+ if (err instanceof TimedOut)
378
+ return [`${t.name} timed out after ${t.timeoutMs / 1000} seconds`, true];
379
+ if (signal.aborted)
380
+ throw new CallsCancelled();
381
+ if (raiseErrors)
382
+ throw err;
383
+ return [describe(err), true];
384
+ }
385
+ finally {
386
+ clearTimeout(timer);
387
+ signal.removeEventListener("abort", onAbort);
388
+ }
389
+ }
390
+ /**
391
+ * Run every call at once and return one result per call, in call order. A call that throws, times out, names a
392
+ * function this process doesn't have, or has arguments that don't fit becomes a failed result the model can act on;
393
+ * with `raiseErrors` an error thrown by `execute` is thrown instead.
394
+ */
395
+ async function runCalls(tools, calls, { signal, raiseErrors = false }) {
396
+ const known = Array.from(tools.keys()).sort();
397
+ // With raiseErrors the first throw aborts every sibling call (their results would be dropped anyway).
398
+ const batch = new AbortController();
399
+ const onAbort = () => batch.abort(signal.reason);
400
+ if (signal.aborted)
401
+ batch.abort(signal.reason);
402
+ else
403
+ signal.addEventListener("abort", onAbort, { once: true });
404
+ let outputs;
405
+ try {
406
+ outputs = await Promise.all(calls.map((c) => runOne(tools.get(c.name), c, known, batch.signal, raiseErrors)
407
+ .catch((err) => {
408
+ if (raiseErrors && !(err instanceof CallsCancelled) && !batch.signal.aborted)
409
+ batch.abort(err);
410
+ throw err;
411
+ })));
412
+ }
413
+ finally {
414
+ signal.removeEventListener("abort", onAbort);
415
+ }
416
+ if (signal.aborted)
417
+ throw new CallsCancelled();
418
+ const texts = fit(outputs.map(([text]) => text));
419
+ return calls.map((c, i) => ({ callId: c.callId, output: texts[i], isError: outputs[i][1] }));
420
+ }