sarvam-agents-client 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +98 -1
  2. package/dist/apis/FunctionToolsApi.d.ts +33 -0
  3. package/dist/apis/FunctionToolsApi.js +65 -0
  4. package/dist/apis/index.d.ts +1 -0
  5. package/dist/apis/index.js +1 -0
  6. package/dist/compose/agent.d.ts +20 -3
  7. package/dist/compose/agent.js +84 -7
  8. package/dist/compose/errors.d.ts +5 -1
  9. package/dist/compose/errors.js +4 -1
  10. package/dist/compose/events.d.ts +4 -0
  11. package/dist/compose/events.js +34 -0
  12. package/dist/compose/functionTool.d.ts +101 -0
  13. package/dist/compose/functionTool.js +420 -0
  14. package/dist/compose/index.d.ts +6 -2
  15. package/dist/compose/index.js +3 -1
  16. package/dist/compose/output.d.ts +11 -0
  17. package/dist/compose/output.js +32 -7
  18. package/dist/compose/run.d.ts +5 -1
  19. package/dist/compose/run.js +118 -25
  20. package/dist/compose/runState.d.ts +26 -1
  21. package/dist/compose/runState.js +30 -0
  22. package/dist/compose/settingsTransport.d.ts +28 -1
  23. package/dist/compose/settingsTransport.js +389 -7
  24. package/dist/compose/transport.d.ts +18 -1
  25. package/dist/compose/webhook.d.ts +19 -0
  26. package/dist/compose/webhook.js +184 -0
  27. package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
  28. package/dist/esm/apis/FunctionToolsApi.js +61 -0
  29. package/dist/esm/apis/index.d.ts +1 -0
  30. package/dist/esm/apis/index.js +1 -0
  31. package/dist/esm/compose/agent.d.ts +20 -3
  32. package/dist/esm/compose/agent.js +84 -7
  33. package/dist/esm/compose/errors.d.ts +5 -1
  34. package/dist/esm/compose/errors.js +4 -1
  35. package/dist/esm/compose/events.d.ts +4 -0
  36. package/dist/esm/compose/events.js +33 -0
  37. package/dist/esm/compose/functionTool.d.ts +101 -0
  38. package/dist/esm/compose/functionTool.js +406 -0
  39. package/dist/esm/compose/index.d.ts +6 -2
  40. package/dist/esm/compose/index.js +1 -0
  41. package/dist/esm/compose/output.d.ts +11 -0
  42. package/dist/esm/compose/output.js +30 -9
  43. package/dist/esm/compose/run.d.ts +5 -1
  44. package/dist/esm/compose/run.js +118 -25
  45. package/dist/esm/compose/runState.d.ts +26 -1
  46. package/dist/esm/compose/runState.js +31 -1
  47. package/dist/esm/compose/settingsTransport.d.ts +28 -1
  48. package/dist/esm/compose/settingsTransport.js +392 -11
  49. package/dist/esm/compose/transport.d.ts +18 -1
  50. package/dist/esm/compose/webhook.d.ts +19 -0
  51. package/dist/esm/compose/webhook.js +177 -0
  52. package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
  53. package/dist/esm/models/AgentConversationDetail.js +3 -0
  54. package/dist/esm/models/ClarifyBody.d.ts +6 -0
  55. package/dist/esm/models/ClarifyBody.js +2 -0
  56. package/dist/esm/models/ConversationDetail.d.ts +7 -0
  57. package/dist/esm/models/ConversationDetail.js +3 -0
  58. package/dist/esm/models/ErrorDetail.d.ts +1 -0
  59. package/dist/esm/models/ErrorDetail.js +2 -1
  60. package/dist/esm/models/FunctionResultBody.d.ts +44 -0
  61. package/dist/esm/models/FunctionResultBody.js +49 -0
  62. package/dist/esm/models/QueueMessageInput.d.ts +23 -0
  63. package/dist/esm/models/QueueMessageInput.js +14 -0
  64. package/dist/esm/models/RequiredAction.d.ts +77 -0
  65. package/dist/esm/models/RequiredAction.js +69 -0
  66. package/dist/esm/models/ResponseDetail.d.ts +8 -0
  67. package/dist/esm/models/ResponseDetail.js +2 -0
  68. package/dist/esm/models/ResponseInput.d.ts +23 -0
  69. package/dist/esm/models/ResponseInput.js +14 -0
  70. package/dist/esm/models/ToolResults200Response.d.ts +38 -0
  71. package/dist/esm/models/ToolResults200Response.js +47 -0
  72. package/dist/esm/models/ToolResultsBody.d.ts +39 -0
  73. package/dist/esm/models/ToolResultsBody.js +48 -0
  74. package/dist/esm/models/index.d.ts +4 -0
  75. package/dist/esm/models/index.js +4 -0
  76. package/dist/esm/streaming.d.ts +14 -2
  77. package/dist/esm/streaming.js +26 -4
  78. package/dist/esm/webhooks.d.ts +203 -0
  79. package/dist/esm/webhooks.js +215 -0
  80. package/dist/models/AgentConversationDetail.d.ts +7 -0
  81. package/dist/models/AgentConversationDetail.js +3 -0
  82. package/dist/models/ClarifyBody.d.ts +6 -0
  83. package/dist/models/ClarifyBody.js +2 -0
  84. package/dist/models/ConversationDetail.d.ts +7 -0
  85. package/dist/models/ConversationDetail.js +3 -0
  86. package/dist/models/ErrorDetail.d.ts +1 -0
  87. package/dist/models/ErrorDetail.js +2 -1
  88. package/dist/models/FunctionResultBody.d.ts +44 -0
  89. package/dist/models/FunctionResultBody.js +56 -0
  90. package/dist/models/QueueMessageInput.d.ts +23 -0
  91. package/dist/models/QueueMessageInput.js +15 -1
  92. package/dist/models/RequiredAction.d.ts +77 -0
  93. package/dist/models/RequiredAction.js +77 -0
  94. package/dist/models/ResponseDetail.d.ts +8 -0
  95. package/dist/models/ResponseDetail.js +2 -0
  96. package/dist/models/ResponseInput.d.ts +23 -0
  97. package/dist/models/ResponseInput.js +15 -0
  98. package/dist/models/ToolResults200Response.d.ts +38 -0
  99. package/dist/models/ToolResults200Response.js +54 -0
  100. package/dist/models/ToolResultsBody.d.ts +39 -0
  101. package/dist/models/ToolResultsBody.js +55 -0
  102. package/dist/models/index.d.ts +4 -0
  103. package/dist/models/index.js +4 -0
  104. package/dist/streaming.d.ts +14 -2
  105. package/dist/streaming.js +27 -4
  106. package/dist/webhooks.d.ts +203 -0
  107. package/dist/webhooks.js +224 -0
  108. package/package.json +9 -1
  109. package/src/apis/FunctionToolsApi.ts +102 -0
  110. package/src/apis/index.ts +1 -0
  111. package/src/compose/agent.ts +96 -9
  112. package/src/compose/errors.ts +7 -1
  113. package/src/compose/events.ts +30 -0
  114. package/src/compose/functionTool.ts +441 -0
  115. package/src/compose/index.ts +6 -2
  116. package/src/compose/output.ts +30 -9
  117. package/src/compose/run.ts +115 -18
  118. package/src/compose/runState.ts +44 -5
  119. package/src/compose/settingsTransport.ts +379 -8
  120. package/src/compose/transport.ts +24 -1
  121. package/src/compose/webhook.ts +181 -0
  122. package/src/models/AgentConversationDetail.ts +15 -0
  123. package/src/models/ClarifyBody.ts +8 -0
  124. package/src/models/ConversationDetail.ts +15 -0
  125. package/src/models/ErrorDetail.ts +2 -1
  126. package/src/models/FunctionResultBody.ts +83 -0
  127. package/src/models/QueueMessageInput.ts +28 -0
  128. package/src/models/RequiredAction.ts +128 -0
  129. package/src/models/ResponseDetail.ts +8 -0
  130. package/src/models/ResponseInput.ts +30 -0
  131. package/src/models/ToolResults200Response.ts +75 -0
  132. package/src/models/ToolResultsBody.ts +83 -0
  133. package/src/models/index.ts +4 -0
  134. package/src/streaming.ts +39 -3
  135. package/src/webhooks.ts +390 -0
@@ -2,8 +2,15 @@ import { NotSupportedError, UserError } from "./errors.js";
2
2
  import { settingsFingerprint } from "./fingerprint.js";
3
3
  import { BUILTIN_NAMES, checkWebSearchOptions } from "./builtins.js";
4
4
  import { BuiltinTool } from "./tools.js";
5
+ import {
6
+ DEFAULT_FUNCTION_TIMEOUT_SECONDS, FUNCTION_TIMEOUT_RANGE, FUNCTIONS_MAX, FUNCTIONS_TOTAL_MAX_BYTES, compactBytes,
7
+ functionToolSettings, isBuiltFunctionTool, isFunctionTool, tool,
8
+ } from "./functionTool.js";
9
+ import type { FunctionTool, FunctionToolOptions } from "./functionTool.js";
5
10
  import { checkOutputType, outputSchema } from "./output.js";
6
11
  import type { OutputType } from "./output.js";
12
+ import { checkWebhooks, copyWebhooks, webhooksJson } from "./webhook.js";
13
+ import type { Webhook } from "./webhook.js";
7
14
 
8
15
  const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
9
16
  const REASONING = ["off", "none", "low", "medium", "high", "xhigh", "max"];
@@ -23,6 +30,9 @@ export interface Limits {
23
30
  maxTokensPerTurn?: number;
24
31
  }
25
32
 
33
+ /** An entry of `Agent` `tools`: a built-in (`sandbox()`, `webSearchTool()`, ...) or a function tool (`tool()`). */
34
+ export type AgentTool = BuiltinTool | FunctionTool;
35
+
26
36
  export interface AgentOptions<TOutput extends OutputType | undefined = undefined> {
27
37
  name: string;
28
38
  instructions?: string;
@@ -31,12 +41,17 @@ export interface AgentOptions<TOutput extends OutputType | undefined = undefined
31
41
  endpoint?: string;
32
42
  modelSettings?: ModelSettings;
33
43
  fallbackModels?: string[];
34
- /** Exact list of built-ins to keep on; omit to keep the server default (all on). */
35
- tools?: BuiltinTool[];
44
+ /** Exact list of what the agent may use: built-ins (the unlisted ones are turned off) and function tools (agent.json
45
+ * `functions`). Omit to keep the server default (every built-in on, no functions). */
46
+ tools?: AgentTool[];
47
+ /** Seconds (10 to 3000, default 600) the server waits for this process to answer a function call (`function_timeout_seconds`). */
48
+ functionTimeoutSeconds?: number;
36
49
  limits?: Limits;
37
50
  metadata?: Record<string, string>;
38
51
  /** The shape of the final answer: `{ type: "json_schema", schema }` or a zod schema. `finalOutput` follows it. */
39
52
  outputType?: TOutput;
53
+ /** Endpoints that receive the turn's events (agent.json `webhooks`); at most 5. */
54
+ webhooks?: Webhook[];
40
55
  }
41
56
 
42
57
  function deepFreeze<T>(value: T): T {
@@ -118,18 +133,29 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
118
133
  readonly endpoint?: string;
119
134
  readonly modelSettings?: ModelSettings;
120
135
  readonly fallbackModels?: string[];
121
- readonly tools?: readonly BuiltinTool[];
136
+ /** Built-ins and function tools, in the order given. */
137
+ readonly tools?: readonly AgentTool[];
138
+ readonly functionTimeoutSeconds?: number;
122
139
  readonly limits?: Limits;
123
140
  readonly metadata?: Record<string, string>;
141
+ readonly webhooks?: readonly Webhook[];
124
142
  /** Kept by reference and not frozen: a zod schema must stay usable. Non-enumerable, so deepFreeze skips it. */
125
143
  declare readonly outputType: TOutput;
126
144
 
127
145
  constructor(rawOpts: AgentOptions<TOutput>) {
128
146
  const opts = normalize(rawOpts);
129
- for (const tool of opts.tools ?? []) {
147
+ for (const tool of (opts.tools ?? []) as unknown[]) {
130
148
  if (tool instanceof Agent) {
131
149
  throw new NotSupportedError("sub-agents in tools are not supported yet (field: tools)");
132
150
  }
151
+ if (typeof tool === "function") {
152
+ throw new UserError(`tools: ${tool.name || "a function"} is not a tool; wrap it with tool({ name, description, ` +
153
+ "parameters, execute })");
154
+ }
155
+ if (tool === null || typeof tool !== "object" || Array.isArray(tool)) {
156
+ throw new UserError(`tools: ${JSON.stringify(tool)} is not a tool; list built-ins (sandbox(), webSearchTool(), ...) ` +
157
+ "and tool() function tools");
158
+ }
133
159
  }
134
160
  checkNumbers(opts);
135
161
  this.name = opts.name;
@@ -138,11 +164,21 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
138
164
  this.endpoint = opts.endpoint;
139
165
  this.modelSettings = clone(opts.modelSettings);
140
166
  this.fallbackModels = clone(opts.fallbackModels);
141
- this.tools = clone(opts.tools);
167
+ // A function tool is kept by reference (it holds execute and maybe a zod schema); an object literal of that shape
168
+ // goes through tool().
169
+ this.tools = opts.tools === undefined ? undefined
170
+ : opts.tools.map((t): AgentTool => {
171
+ if (isBuiltFunctionTool(t)) return t;
172
+ if (isFunctionTool(t)) return tool(t as unknown as FunctionToolOptions);
173
+ return clone(t);
174
+ });
175
+ this.functionTimeoutSeconds = opts.functionTimeoutSeconds;
142
176
  this.limits = clone(opts.limits);
143
177
  this.metadata = clone(opts.metadata);
178
+ this.webhooks = clone(opts.webhooks);
144
179
  Object.defineProperty(this, "outputType", { value: opts.outputType, enumerable: false, writable: false });
145
180
  this.check();
181
+ if (this.webhooks !== undefined) this.webhooks = copyWebhooks(this.webhooks);
146
182
  deepFreeze(this);
147
183
  }
148
184
 
@@ -196,7 +232,7 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
196
232
  throw new UserError(`metadata: keys starting with 'sdk_' are reserved (${bad.join(", ")})`);
197
233
  }
198
234
  }
199
- const names = (this.tools ?? []).map((t) => t.name);
235
+ const names = this.builtinTools.map((t) => t.name);
200
236
  for (const n of names) {
201
237
  if ((BUILTIN_NAMES as readonly string[]).indexOf(n) === -1) {
202
238
  throw new UserError(`tools: unknown built-in tool ${JSON.stringify(n)} (known: ${BUILTIN_NAMES.join(", ")})`);
@@ -206,7 +242,7 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
206
242
  if (dupes.length > 0) {
207
243
  throw new UserError(`tools: duplicate built-in tool(s): ${dupes.join(", ")}`);
208
244
  }
209
- for (const t of this.tools ?? []) {
245
+ for (const t of this.builtinTools) {
210
246
  if (t.options === undefined || Object.keys(t.options).length === 0) continue;
211
247
  if (t.name !== "web_search") throw new UserError(`tools: ${t.name} takes no options`);
212
248
  checkWebSearchOptions(t.options);
@@ -214,6 +250,50 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
214
250
  if (names.indexOf("code_mode") !== -1 && names.indexOf("sandbox") === -1) {
215
251
  throw new UserError("tools: codeMode needs sandbox; add sandbox() to tools");
216
252
  }
253
+ if (this.webhooks !== undefined) checkWebhooks(this.webhooks);
254
+ this.checkFunctions();
255
+ }
256
+
257
+ private checkFunctions(): void {
258
+ const functions = this.functionTools;
259
+ if (functions.length > FUNCTIONS_MAX) {
260
+ throw new UserError(`tools: at most ${FUNCTIONS_MAX} function tools (got ${functions.length})`);
261
+ }
262
+ const names = functions.map((t) => t.name);
263
+ const dupes = Array.from(new Set(names.filter((n, i) => names.indexOf(n) !== i))).sort();
264
+ if (dupes.length > 0) throw new UserError(`tools: duplicate function tool(s): ${dupes.join(", ")}`);
265
+ const total = functions.reduce((sum, t) => sum + compactBytes(functionToolSettings(t)), 0);
266
+ if (total > FUNCTIONS_TOTAL_MAX_BYTES) {
267
+ throw new UserError(`tools: function tools are ${Math.ceil(total / 1024)} KB together (names, descriptions and ` +
268
+ "parameters); the server allows 64 KB, because every model call carries them");
269
+ }
270
+ const timeout = this.functionTimeoutSeconds;
271
+ if (timeout !== undefined) {
272
+ const [low, high] = FUNCTION_TIMEOUT_RANGE;
273
+ if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < low || timeout > high) {
274
+ throw new UserError(`functionTimeoutSeconds: must be a whole number of seconds from ${low} to ${high}`);
275
+ }
276
+ }
277
+ // A call still running when the server's deadline passes is answered too late (409 expired) and the run fails;
278
+ // one that times out here first goes to the model as a failed result in time.
279
+ const deadline = timeout ?? DEFAULT_FUNCTION_TIMEOUT_SECONDS;
280
+ for (const t of functions) {
281
+ if (t.timeoutMs >= deadline * 1000) {
282
+ throw new UserError(`${t.name}: timeoutMs=${t.timeoutMs} (${t.timeoutMs / 1000}s) must be shorter than the ` +
283
+ `agent's functionTimeoutSeconds (${deadline}s${timeout === undefined ? ", the server default" : ""}); ` +
284
+ "lower the tool's timeoutMs or raise functionTimeoutSeconds");
285
+ }
286
+ }
287
+ }
288
+
289
+ /** The built-in tools in `tools`, in order. */
290
+ get builtinTools(): readonly BuiltinTool[] {
291
+ return (this.tools ?? []).filter((t) => !isFunctionTool(t)) as BuiltinTool[];
292
+ }
293
+
294
+ /** The function tools in `tools`, in order. */
295
+ get functionTools(): readonly FunctionTool[] {
296
+ return (this.tools ?? []).filter(isFunctionTool);
217
297
  }
218
298
 
219
299
  private baseSettings(): Record<string, unknown> {
@@ -240,15 +320,22 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
240
320
  if (Object.keys(limits).length > 0) out["limits"] = limits;
241
321
  }
242
322
  if (this.tools !== undefined) {
243
- // Built-ins are on by default, so an exact list writes every unlisted one as off.
323
+ // Built-ins are on by default, so an exact list writes every unlisted one as off (function tools included:
324
+ // tools: [tool(...)] means that function and no built-in).
325
+ const builtins = this.builtinTools;
244
326
  const tools: Record<string, unknown> = {};
245
327
  for (const n of BUILTIN_NAMES) {
246
- const t = this.tools.find((x) => x.name === n);
328
+ const t = builtins.find((x) => x.name === n);
247
329
  tools[n] = t === undefined ? false
248
330
  : t.options !== undefined && Object.keys(t.options).length > 0 ? clone(t.options) : true;
249
331
  }
250
332
  out["builtin_tools"] = tools;
333
+ // Never an empty list: that would change every existing agent's fingerprint.
334
+ const functions = this.functionTools;
335
+ if (functions.length > 0) out["functions"] = functions.map(functionToolSettings);
251
336
  }
337
+ if (this.functionTimeoutSeconds !== undefined) out["function_timeout_seconds"] = this.functionTimeoutSeconds;
338
+ if (this.webhooks !== undefined && this.webhooks.length > 0) out["webhooks"] = webhooksJson(this.webhooks);
252
339
  if (this.outputType !== undefined) out["output_schema"] = outputSchema(this.outputType as OutputType);
253
340
  return out;
254
341
  }
@@ -62,9 +62,15 @@ export class NotSupportedError extends AgentsError {}
62
62
 
63
63
  export class RunError extends AgentsError {
64
64
  readonly code: string;
65
- constructor(code: string, message: string) {
65
+ /** The HTTP status when a request was refused (for example 409 on a function-results post). */
66
+ readonly status?: number;
67
+ /** The server's `error.details[0]` (for example `toolCallIds` or `maxBytes`); `{}` when none. */
68
+ readonly details: Record<string, unknown>;
69
+ constructor(code: string, message: string, status?: number, details?: Record<string, unknown>) {
66
70
  super(`${code}: ${message}`);
67
71
  this.code = code;
72
+ if (status !== undefined) this.status = status;
73
+ this.details = { ...(details ?? {}) };
68
74
  }
69
75
  }
70
76
 
@@ -180,3 +180,33 @@ function map(chunk: Record<string, unknown>): Event | null {
180
180
  return { kind: "unknown", chunk };
181
181
  }
182
182
  }
183
+
184
+ /** A stored UIMessage (`GET /v1/conversations/{id}` `messages`) as the stream chunks that would have produced it,
185
+ * ending with `finish`, so a finished turn can be read like a live one. Text parts become one text block each, tool
186
+ * parts a call and (when they have one) its output, `data-*` parts pass through; reasoning is dropped. */
187
+ export function chunksFromUiMessage(message: unknown): Record<string, unknown>[] {
188
+ const chunks: Record<string, unknown>[] = [];
189
+ const parts = isObject(message) && Array.isArray(message["parts"]) ? message["parts"] : [];
190
+ parts.forEach((part: unknown, n: number) => {
191
+ if (!isObject(part)) return;
192
+ const kind = typeof part["type"] === "string" ? part["type"] : "";
193
+ if (kind === "text") {
194
+ const id = `msg-text-${n}`;
195
+ chunks.push({ type: "text-start", id }, { type: "text-delta", id, delta: String(part["text"] ?? "") },
196
+ { type: "text-end", id });
197
+ } else if (kind === "dynamic-tool" || kind.startsWith("tool-")) {
198
+ const name = part["toolName"] ?? (kind.startsWith("tool-") ? kind.slice("tool-".length) : "");
199
+ const toolCallId = part["toolCallId"] ?? "";
200
+ chunks.push({ type: "tool-input-available", toolCallId, toolName: name, input: part["input"] });
201
+ if (part["state"] === "output-available") {
202
+ chunks.push({ type: "tool-output-available", toolCallId, output: part["output"] });
203
+ } else if (part["state"] === "output-error") {
204
+ chunks.push({ type: "tool-output-available", toolCallId, output: { error: part["errorText"] ?? "" } });
205
+ }
206
+ } else if (kind.startsWith("data-")) {
207
+ chunks.push({ type: kind, id: part["id"], data: part["data"] });
208
+ }
209
+ });
210
+ chunks.push({ type: "finish", finishReason: "stop" });
211
+ return chunks;
212
+ }