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
@@ -1,4 +1,6 @@
1
1
  import { BuiltinTool } from "./tools.js";
2
+ import type { FunctionTool } from "./functionTool.js";
3
+ import type { OutputType } from "./output.js";
2
4
  export interface ModelSettings {
3
5
  temperature?: number;
4
6
  topP?: number;
@@ -13,7 +15,9 @@ export interface Limits {
13
15
  maxToolCallsPerTurn?: number;
14
16
  maxTokensPerTurn?: number;
15
17
  }
16
- export interface AgentOptions {
18
+ /** An entry of `Agent` `tools`: a built-in (`sandbox()`, `webSearchTool()`, ...) or a function tool (`tool()`). */
19
+ export type AgentTool = BuiltinTool | FunctionTool;
20
+ export interface AgentOptions<TOutput extends OutputType | undefined = undefined> {
17
21
  name: string;
18
22
  instructions?: string;
19
23
  model?: string;
@@ -21,23 +25,39 @@ export interface AgentOptions {
21
25
  endpoint?: string;
22
26
  modelSettings?: ModelSettings;
23
27
  fallbackModels?: string[];
24
- /** Exact list of built-ins to keep on; omit to keep the server default (all on). */
25
- tools?: BuiltinTool[];
28
+ /** Exact list of what the agent may use: built-ins (the unlisted ones are turned off) and function tools (agent.json
29
+ * `functions`). Omit to keep the server default (every built-in on, no functions). */
30
+ tools?: AgentTool[];
31
+ /** Seconds (10 to 3000, default 600) the server waits for this process to answer a function call (`function_timeout_seconds`). */
32
+ functionTimeoutSeconds?: number;
26
33
  limits?: Limits;
27
34
  metadata?: Record<string, string>;
35
+ /** The shape of the final answer: `{ type: "json_schema", schema }` or a zod schema. `finalOutput` follows it. */
36
+ outputType?: TOutput;
28
37
  }
29
- export declare class Agent {
38
+ /** An agent with any output type: use it for helpers that accept every agent (plain `Agent` means a text agent). */
39
+ export type AnyAgent = Agent<OutputType | undefined>;
40
+ export declare class Agent<TOutput extends OutputType | undefined = undefined> {
30
41
  readonly name: string;
31
42
  readonly instructions: string;
32
43
  readonly model?: string;
33
44
  readonly endpoint?: string;
34
45
  readonly modelSettings?: ModelSettings;
35
46
  readonly fallbackModels?: string[];
36
- readonly tools?: readonly BuiltinTool[];
47
+ /** Built-ins and function tools, in the order given. */
48
+ readonly tools?: readonly AgentTool[];
49
+ readonly functionTimeoutSeconds?: number;
37
50
  readonly limits?: Limits;
38
51
  readonly metadata?: Record<string, string>;
39
- constructor(rawOpts: AgentOptions);
52
+ /** Kept by reference and not frozen: a zod schema must stay usable. Non-enumerable, so deepFreeze skips it. */
53
+ readonly outputType: TOutput;
54
+ constructor(rawOpts: AgentOptions<TOutput>);
40
55
  private check;
56
+ private checkFunctions;
57
+ /** The built-in tools in `tools`, in order. */
58
+ get builtinTools(): readonly BuiltinTool[];
59
+ /** The function tools in `tools`, in order. */
60
+ get functionTools(): readonly FunctionTool[];
41
61
  private baseSettings;
42
62
  specHash(): string;
43
63
  toSettings(): Record<string, unknown>;
@@ -1,6 +1,8 @@
1
1
  import { NotSupportedError, UserError } from "./errors.js";
2
2
  import { settingsFingerprint } from "./fingerprint.js";
3
3
  import { BUILTIN_NAMES, checkWebSearchOptions } from "./builtins.js";
4
+ import { DEFAULT_FUNCTION_TIMEOUT_SECONDS, FUNCTION_TIMEOUT_RANGE, FUNCTIONS_MAX, FUNCTIONS_TOTAL_MAX_BYTES, compactBytes, functionToolSettings, isBuiltFunctionTool, isFunctionTool, tool, } from "./functionTool.js";
5
+ import { checkOutputType, outputSchema } from "./output.js";
4
6
  const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
5
7
  const REASONING = ["off", "none", "low", "medium", "high", "xhigh", "max"];
6
8
  const TOOL_CHOICES = ["auto", "none"];
@@ -74,10 +76,18 @@ export class Agent {
74
76
  constructor(rawOpts) {
75
77
  var _a, _b;
76
78
  const opts = normalize(rawOpts);
77
- for (const tool of (_a = opts.tools) !== null && _a !== void 0 ? _a : []) {
79
+ for (const tool of ((_a = opts.tools) !== null && _a !== void 0 ? _a : [])) {
78
80
  if (tool instanceof Agent) {
79
81
  throw new NotSupportedError("sub-agents in tools are not supported yet (field: tools)");
80
82
  }
83
+ if (typeof tool === "function") {
84
+ throw new UserError(`tools: ${tool.name || "a function"} is not a tool; wrap it with tool({ name, description, ` +
85
+ "parameters, execute })");
86
+ }
87
+ if (tool === null || typeof tool !== "object" || Array.isArray(tool)) {
88
+ throw new UserError(`tools: ${JSON.stringify(tool)} is not a tool; list built-ins (sandbox(), webSearchTool(), ...) ` +
89
+ "and tool() function tools");
90
+ }
81
91
  }
82
92
  checkNumbers(opts);
83
93
  this.name = opts.name;
@@ -86,17 +96,31 @@ export class Agent {
86
96
  this.endpoint = opts.endpoint;
87
97
  this.modelSettings = clone(opts.modelSettings);
88
98
  this.fallbackModels = clone(opts.fallbackModels);
89
- this.tools = clone(opts.tools);
99
+ // A function tool is kept by reference (it holds execute and maybe a zod schema); an object literal of that shape
100
+ // goes through tool().
101
+ this.tools = opts.tools === undefined ? undefined
102
+ : opts.tools.map((t) => {
103
+ if (isBuiltFunctionTool(t))
104
+ return t;
105
+ if (isFunctionTool(t))
106
+ return tool(t);
107
+ return clone(t);
108
+ });
109
+ this.functionTimeoutSeconds = opts.functionTimeoutSeconds;
90
110
  this.limits = clone(opts.limits);
91
111
  this.metadata = clone(opts.metadata);
112
+ Object.defineProperty(this, "outputType", { value: opts.outputType, enumerable: false, writable: false });
92
113
  this.check();
93
114
  deepFreeze(this);
94
115
  }
95
116
  check() {
96
- var _a, _b;
97
117
  if (typeof this.name !== "string" || !SLUG.test(this.name)) {
98
118
  throw new UserError(`name: ${JSON.stringify(this.name)} must match ${SLUG.source}`);
99
119
  }
120
+ if (this.outputType !== undefined) {
121
+ checkOutputType(this.outputType);
122
+ outputSchema(this.outputType); // refuse what the server would, before anything is sent
123
+ }
100
124
  for (const [key, value] of [["model", this.model], ["endpoint", this.endpoint]]) {
101
125
  if (value !== undefined && (typeof value !== "string" || value === "")) {
102
126
  throw new UserError(`${key}: must be a non-empty string`);
@@ -137,7 +161,7 @@ export class Agent {
137
161
  throw new UserError(`metadata: keys starting with 'sdk_' are reserved (${bad.join(", ")})`);
138
162
  }
139
163
  }
140
- const names = ((_a = this.tools) !== null && _a !== void 0 ? _a : []).map((t) => t.name);
164
+ const names = this.builtinTools.map((t) => t.name);
141
165
  for (const n of names) {
142
166
  if (BUILTIN_NAMES.indexOf(n) === -1) {
143
167
  throw new UserError(`tools: unknown built-in tool ${JSON.stringify(n)} (known: ${BUILTIN_NAMES.join(", ")})`);
@@ -147,7 +171,7 @@ export class Agent {
147
171
  if (dupes.length > 0) {
148
172
  throw new UserError(`tools: duplicate built-in tool(s): ${dupes.join(", ")}`);
149
173
  }
150
- for (const t of (_b = this.tools) !== null && _b !== void 0 ? _b : []) {
174
+ for (const t of this.builtinTools) {
151
175
  if (t.options === undefined || Object.keys(t.options).length === 0)
152
176
  continue;
153
177
  if (t.name !== "web_search")
@@ -157,6 +181,49 @@ export class Agent {
157
181
  if (names.indexOf("code_mode") !== -1 && names.indexOf("sandbox") === -1) {
158
182
  throw new UserError("tools: codeMode needs sandbox; add sandbox() to tools");
159
183
  }
184
+ this.checkFunctions();
185
+ }
186
+ checkFunctions() {
187
+ const functions = this.functionTools;
188
+ if (functions.length > FUNCTIONS_MAX) {
189
+ throw new UserError(`tools: at most ${FUNCTIONS_MAX} function tools (got ${functions.length})`);
190
+ }
191
+ const names = functions.map((t) => t.name);
192
+ const dupes = Array.from(new Set(names.filter((n, i) => names.indexOf(n) !== i))).sort();
193
+ if (dupes.length > 0)
194
+ throw new UserError(`tools: duplicate function tool(s): ${dupes.join(", ")}`);
195
+ const total = functions.reduce((sum, t) => sum + compactBytes(functionToolSettings(t)), 0);
196
+ if (total > FUNCTIONS_TOTAL_MAX_BYTES) {
197
+ throw new UserError(`tools: function tools are ${Math.ceil(total / 1024)} KB together (names, descriptions and ` +
198
+ "parameters); the server allows 64 KB, because every model call carries them");
199
+ }
200
+ const timeout = this.functionTimeoutSeconds;
201
+ if (timeout !== undefined) {
202
+ const [low, high] = FUNCTION_TIMEOUT_RANGE;
203
+ if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < low || timeout > high) {
204
+ throw new UserError(`functionTimeoutSeconds: must be a whole number of seconds from ${low} to ${high}`);
205
+ }
206
+ }
207
+ // A call still running when the server's deadline passes is answered too late (409 expired) and the run fails;
208
+ // one that times out here first goes to the model as a failed result in time.
209
+ const deadline = timeout !== null && timeout !== void 0 ? timeout : DEFAULT_FUNCTION_TIMEOUT_SECONDS;
210
+ for (const t of functions) {
211
+ if (t.timeoutMs >= deadline * 1000) {
212
+ throw new UserError(`${t.name}: timeoutMs=${t.timeoutMs} (${t.timeoutMs / 1000}s) must be shorter than the ` +
213
+ `agent's functionTimeoutSeconds (${deadline}s${timeout === undefined ? ", the server default" : ""}); ` +
214
+ "lower the tool's timeoutMs or raise functionTimeoutSeconds");
215
+ }
216
+ }
217
+ }
218
+ /** The built-in tools in `tools`, in order. */
219
+ get builtinTools() {
220
+ var _a;
221
+ return ((_a = this.tools) !== null && _a !== void 0 ? _a : []).filter((t) => !isFunctionTool(t));
222
+ }
223
+ /** The function tools in `tools`, in order. */
224
+ get functionTools() {
225
+ var _a;
226
+ return ((_a = this.tools) !== null && _a !== void 0 ? _a : []).filter(isFunctionTool);
160
227
  }
161
228
  baseSettings() {
162
229
  const out = { version: 1 };
@@ -191,15 +258,25 @@ export class Agent {
191
258
  out["limits"] = limits;
192
259
  }
193
260
  if (this.tools !== undefined) {
194
- // Built-ins are on by default, so an exact list writes every unlisted one as off.
261
+ // Built-ins are on by default, so an exact list writes every unlisted one as off (function tools included:
262
+ // tools: [tool(...)] means that function and no built-in).
263
+ const builtins = this.builtinTools;
195
264
  const tools = {};
196
265
  for (const n of BUILTIN_NAMES) {
197
- const t = this.tools.find((x) => x.name === n);
266
+ const t = builtins.find((x) => x.name === n);
198
267
  tools[n] = t === undefined ? false
199
268
  : t.options !== undefined && Object.keys(t.options).length > 0 ? clone(t.options) : true;
200
269
  }
201
270
  out["builtin_tools"] = tools;
271
+ // Never an empty list: that would change every existing agent's fingerprint.
272
+ const functions = this.functionTools;
273
+ if (functions.length > 0)
274
+ out["functions"] = functions.map(functionToolSettings);
202
275
  }
276
+ if (this.functionTimeoutSeconds !== undefined)
277
+ out["function_timeout_seconds"] = this.functionTimeoutSeconds;
278
+ if (this.outputType !== undefined)
279
+ out["output_schema"] = outputSchema(this.outputType);
203
280
  return out;
204
281
  }
205
282
  specHash() {
@@ -1,6 +1,7 @@
1
1
  /** deploy()/undeploy(): upsert a hosted agent by name, with fingerprint-based drift detection, and the deploy cache. */
2
2
  import type { Configuration } from "../runtime.js";
3
3
  import type { Agent } from "./agent.js";
4
+ import type { OutputType } from "./output.js";
4
5
  import type { Transport } from "./transport.js";
5
6
  export interface Deployment {
6
7
  agentId: string;
@@ -10,7 +11,7 @@ export interface Deployment {
10
11
  export declare function setDefaultClient(config: Configuration | null): void;
11
12
  export declare function getDefaultClient(): Configuration | null;
12
13
  export declare function resolveTransport(client?: Configuration, transport?: Transport): Transport;
13
- export declare function deploy(agent: Agent, opts?: {
14
+ export declare function deploy(agent: Agent<OutputType | undefined>, opts?: {
14
15
  client?: Configuration;
15
16
  transport?: Transport;
16
17
  strict?: boolean;
@@ -27,4 +28,4 @@ export declare function forget(name: string): void;
27
28
  * Keyed by name, as the server is: a variant with the same name redeploys, chained after any in-flight deploy so
28
29
  * deploys of one name never overlap.
29
30
  */
30
- export declare function agentIdFor(agent: Agent, transport: Transport, owner: object): Promise<string>;
31
+ export declare function agentIdFor(agent: Agent<OutputType | undefined>, transport: Transport, owner: object): Promise<string>;
@@ -16,7 +16,24 @@ export declare class UserError extends AgentsError {
16
16
  message?: string;
17
17
  }>);
18
18
  }
19
+ /** Where a `ModelBehaviorError` came from: the server's check, or the `outputType`'s own `parse`. */
20
+ export type ModelBehaviorErrorSource = "server" | "local_parse";
21
+ /**
22
+ * The agent's answer didn't match its `outputType`. `source` says where: `"server"` (no answer matched the schema
23
+ * after the server's retry; `rawText` is the model's last attempt) or `"local_parse"` (the server accepted the answer
24
+ * but the `outputType`'s `parse` refused it, for example a zod refinement; `rawText` is the server's JSON,
25
+ * re-serialised).
26
+ */
19
27
  export declare class ModelBehaviorError extends AgentsError {
28
+ readonly rawText: string;
29
+ readonly errors: string[];
30
+ /** The server's `outputNote`: the turn's size-refused `final_answer` was not the answer. */
31
+ readonly note: string | undefined;
32
+ readonly source: ModelBehaviorErrorSource;
33
+ /** The run's conversation, set when a run rejects with this, so the caller can continue it (`conversationId`) or
34
+ * fetch its `ResponseDetail`. */
35
+ conversationId: string | undefined;
36
+ constructor(rawText?: string, errors?: string[], note?: string, source?: ModelBehaviorErrorSource);
20
37
  }
21
38
  export declare class MaxTurnsExceededError extends AgentsError {
22
39
  }
@@ -32,7 +49,11 @@ export declare class NotSupportedError extends AgentsError {
32
49
  }
33
50
  export declare class RunError extends AgentsError {
34
51
  readonly code: string;
35
- constructor(code: string, message: string);
52
+ /** The HTTP status when a request was refused (for example 409 on a function-results post). */
53
+ readonly status?: number;
54
+ /** The server's `error.details[0]` (for example `toolCallIds` or `maxBytes`); `{}` when none. */
55
+ readonly details: Record<string, unknown>;
56
+ constructor(code: string, message: string, status?: number, details?: Record<string, unknown>);
36
57
  }
37
58
  export declare class DriftError extends AgentsError {
38
59
  readonly changed: string[];
@@ -13,7 +13,24 @@ export class UserError extends AgentsError {
13
13
  this.issues = issues;
14
14
  }
15
15
  }
16
+ /**
17
+ * The agent's answer didn't match its `outputType`. `source` says where: `"server"` (no answer matched the schema
18
+ * after the server's retry; `rawText` is the model's last attempt) or `"local_parse"` (the server accepted the answer
19
+ * but the `outputType`'s `parse` refused it, for example a zod refinement; `rawText` is the server's JSON,
20
+ * re-serialised).
21
+ */
16
22
  export class ModelBehaviorError extends AgentsError {
23
+ constructor(rawText = "", errors = [], note, source = "server") {
24
+ const prefix = source === "server" ? "model output rejected" : "model output rejected by outputType";
25
+ super(errors.length ? `${prefix}: ` + errors.join("; ") : rawText);
26
+ /** The run's conversation, set when a run rejects with this, so the caller can continue it (`conversationId`) or
27
+ * fetch its `ResponseDetail`. */
28
+ this.conversationId = undefined;
29
+ this.rawText = rawText;
30
+ this.errors = errors.slice();
31
+ this.note = note;
32
+ this.source = source;
33
+ }
17
34
  }
18
35
  export class MaxTurnsExceededError extends AgentsError {
19
36
  }
@@ -28,9 +45,12 @@ export class NotDeployedError extends AgentsError {
28
45
  export class NotSupportedError extends AgentsError {
29
46
  }
30
47
  export class RunError extends AgentsError {
31
- constructor(code, message) {
48
+ constructor(code, message, status, details) {
32
49
  super(`${code}: ${message}`);
33
50
  this.code = code;
51
+ if (status !== undefined)
52
+ this.status = status;
53
+ this.details = { ...(details !== null && details !== void 0 ? details : {}) };
34
54
  }
35
55
  }
36
56
  export class DriftError extends AgentsError {
@@ -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>[];
@@ -24,7 +24,7 @@ export function fromUiChunk(chunk) {
24
24
  }
25
25
  }
26
26
  function map(chunk) {
27
- var _a, _b;
27
+ var _a, _b, _c;
28
28
  const type = chunk["type"];
29
29
  const data = isObject(chunk["data"]) ? chunk["data"] : {};
30
30
  if (typeof type === "string" && IGNORED.indexOf(type) !== -1)
@@ -97,8 +97,64 @@ function map(chunk) {
97
97
  return { kind: "turn_failed", code: str(chunk["code"], "turn_failed"), message: text(chunk["errorText"]) };
98
98
  case "finish":
99
99
  return { kind: "turn_finished", reason: str(chunk["finishReason"], "stop") };
100
+ case "data-output": {
101
+ const ev = { kind: "output", output: (_c = data["output"]) !== null && _c !== void 0 ? _c : null };
102
+ if (typeof data["skipped"] === "string" && data["skipped"])
103
+ ev.skipped = data["skipped"];
104
+ if (typeof data["mode"] === "string" && data["mode"])
105
+ ev.mode = data["mode"];
106
+ const citations = Array.isArray(data["citations"]) ? data["citations"].filter(isObject) : [];
107
+ if (citations.length)
108
+ ev.citations = citations;
109
+ if (typeof data["note"] === "string" && data["note"])
110
+ ev.note = data["note"];
111
+ return ev;
112
+ }
113
+ case "data-output-error": {
114
+ const errors = data["errors"];
115
+ const ev = {
116
+ kind: "output_error",
117
+ errors: Array.isArray(errors) ? errors.map(String) : typeof errors === "string" ? [errors] : [],
118
+ rawText: text(data["rawText"]),
119
+ };
120
+ if (typeof data["note"] === "string" && data["note"])
121
+ ev.note = data["note"];
122
+ return ev;
123
+ }
100
124
  default:
101
- // data-output and data-output-error are unknown until structured output lands.
102
125
  return { kind: "unknown", chunk };
103
126
  }
104
127
  }
128
+ /** A stored UIMessage (`GET /v1/conversations/{id}` `messages`) as the stream chunks that would have produced it,
129
+ * ending with `finish`, so a finished turn can be read like a live one. Text parts become one text block each, tool
130
+ * parts a call and (when they have one) its output, `data-*` parts pass through; reasoning is dropped. */
131
+ export function chunksFromUiMessage(message) {
132
+ const chunks = [];
133
+ const parts = isObject(message) && Array.isArray(message["parts"]) ? message["parts"] : [];
134
+ parts.forEach((part, n) => {
135
+ var _a, _b, _c, _d;
136
+ if (!isObject(part))
137
+ return;
138
+ const kind = typeof part["type"] === "string" ? part["type"] : "";
139
+ if (kind === "text") {
140
+ const id = `msg-text-${n}`;
141
+ chunks.push({ type: "text-start", id }, { type: "text-delta", id, delta: String((_a = part["text"]) !== null && _a !== void 0 ? _a : "") }, { type: "text-end", id });
142
+ }
143
+ else if (kind === "dynamic-tool" || kind.startsWith("tool-")) {
144
+ const name = (_b = part["toolName"]) !== null && _b !== void 0 ? _b : (kind.startsWith("tool-") ? kind.slice("tool-".length) : "");
145
+ const toolCallId = (_c = part["toolCallId"]) !== null && _c !== void 0 ? _c : "";
146
+ chunks.push({ type: "tool-input-available", toolCallId, toolName: name, input: part["input"] });
147
+ if (part["state"] === "output-available") {
148
+ chunks.push({ type: "tool-output-available", toolCallId, output: part["output"] });
149
+ }
150
+ else if (part["state"] === "output-error") {
151
+ chunks.push({ type: "tool-output-available", toolCallId, output: { error: (_d = part["errorText"]) !== null && _d !== void 0 ? _d : "" } });
152
+ }
153
+ }
154
+ else if (kind.startsWith("data-")) {
155
+ chunks.push({ type: kind, id: part["id"], data: part["data"] });
156
+ }
157
+ });
158
+ chunks.push({ type: "finish", finishReason: "stop" });
159
+ return chunks;
160
+ }
@@ -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 {};