sarvam-agents-client 0.3.0 → 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 (125) hide show
  1. package/README.md +16 -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 +16 -3
  7. package/dist/compose/agent.js +76 -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 +5 -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 +20 -1
  23. package/dist/compose/settingsTransport.js +295 -3
  24. package/dist/compose/transport.d.ts +18 -1
  25. package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
  26. package/dist/esm/apis/FunctionToolsApi.js +61 -0
  27. package/dist/esm/apis/index.d.ts +1 -0
  28. package/dist/esm/apis/index.js +1 -0
  29. package/dist/esm/compose/agent.d.ts +16 -3
  30. package/dist/esm/compose/agent.js +76 -7
  31. package/dist/esm/compose/errors.d.ts +5 -1
  32. package/dist/esm/compose/errors.js +4 -1
  33. package/dist/esm/compose/events.d.ts +4 -0
  34. package/dist/esm/compose/events.js +33 -0
  35. package/dist/esm/compose/functionTool.d.ts +101 -0
  36. package/dist/esm/compose/functionTool.js +406 -0
  37. package/dist/esm/compose/index.d.ts +5 -2
  38. package/dist/esm/compose/index.js +1 -0
  39. package/dist/esm/compose/output.d.ts +11 -0
  40. package/dist/esm/compose/output.js +30 -9
  41. package/dist/esm/compose/run.d.ts +5 -1
  42. package/dist/esm/compose/run.js +118 -25
  43. package/dist/esm/compose/runState.d.ts +26 -1
  44. package/dist/esm/compose/runState.js +31 -1
  45. package/dist/esm/compose/settingsTransport.d.ts +20 -1
  46. package/dist/esm/compose/settingsTransport.js +298 -7
  47. package/dist/esm/compose/transport.d.ts +18 -1
  48. package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
  49. package/dist/esm/models/AgentConversationDetail.js +3 -0
  50. package/dist/esm/models/ClarifyBody.d.ts +6 -0
  51. package/dist/esm/models/ClarifyBody.js +2 -0
  52. package/dist/esm/models/ConversationDetail.d.ts +7 -0
  53. package/dist/esm/models/ConversationDetail.js +3 -0
  54. package/dist/esm/models/ErrorDetail.d.ts +1 -0
  55. package/dist/esm/models/ErrorDetail.js +2 -1
  56. package/dist/esm/models/FunctionResultBody.d.ts +44 -0
  57. package/dist/esm/models/FunctionResultBody.js +49 -0
  58. package/dist/esm/models/QueueMessageInput.d.ts +23 -0
  59. package/dist/esm/models/QueueMessageInput.js +14 -0
  60. package/dist/esm/models/RequiredAction.d.ts +77 -0
  61. package/dist/esm/models/RequiredAction.js +69 -0
  62. package/dist/esm/models/ResponseDetail.d.ts +8 -0
  63. package/dist/esm/models/ResponseDetail.js +2 -0
  64. package/dist/esm/models/ResponseInput.d.ts +23 -0
  65. package/dist/esm/models/ResponseInput.js +14 -0
  66. package/dist/esm/models/ToolResults200Response.d.ts +38 -0
  67. package/dist/esm/models/ToolResults200Response.js +47 -0
  68. package/dist/esm/models/ToolResultsBody.d.ts +39 -0
  69. package/dist/esm/models/ToolResultsBody.js +48 -0
  70. package/dist/esm/models/index.d.ts +4 -0
  71. package/dist/esm/models/index.js +4 -0
  72. package/dist/esm/streaming.d.ts +14 -2
  73. package/dist/esm/streaming.js +26 -4
  74. package/dist/models/AgentConversationDetail.d.ts +7 -0
  75. package/dist/models/AgentConversationDetail.js +3 -0
  76. package/dist/models/ClarifyBody.d.ts +6 -0
  77. package/dist/models/ClarifyBody.js +2 -0
  78. package/dist/models/ConversationDetail.d.ts +7 -0
  79. package/dist/models/ConversationDetail.js +3 -0
  80. package/dist/models/ErrorDetail.d.ts +1 -0
  81. package/dist/models/ErrorDetail.js +2 -1
  82. package/dist/models/FunctionResultBody.d.ts +44 -0
  83. package/dist/models/FunctionResultBody.js +56 -0
  84. package/dist/models/QueueMessageInput.d.ts +23 -0
  85. package/dist/models/QueueMessageInput.js +15 -1
  86. package/dist/models/RequiredAction.d.ts +77 -0
  87. package/dist/models/RequiredAction.js +77 -0
  88. package/dist/models/ResponseDetail.d.ts +8 -0
  89. package/dist/models/ResponseDetail.js +2 -0
  90. package/dist/models/ResponseInput.d.ts +23 -0
  91. package/dist/models/ResponseInput.js +15 -0
  92. package/dist/models/ToolResults200Response.d.ts +38 -0
  93. package/dist/models/ToolResults200Response.js +54 -0
  94. package/dist/models/ToolResultsBody.d.ts +39 -0
  95. package/dist/models/ToolResultsBody.js +55 -0
  96. package/dist/models/index.d.ts +4 -0
  97. package/dist/models/index.js +4 -0
  98. package/dist/streaming.d.ts +14 -2
  99. package/dist/streaming.js +27 -4
  100. package/package.json +1 -1
  101. package/src/apis/FunctionToolsApi.ts +102 -0
  102. package/src/apis/index.ts +1 -0
  103. package/src/compose/agent.ts +87 -9
  104. package/src/compose/errors.ts +7 -1
  105. package/src/compose/events.ts +30 -0
  106. package/src/compose/functionTool.ts +441 -0
  107. package/src/compose/index.ts +5 -2
  108. package/src/compose/output.ts +30 -9
  109. package/src/compose/run.ts +115 -18
  110. package/src/compose/runState.ts +44 -5
  111. package/src/compose/settingsTransport.ts +293 -7
  112. package/src/compose/transport.ts +24 -1
  113. package/src/models/AgentConversationDetail.ts +15 -0
  114. package/src/models/ClarifyBody.ts +8 -0
  115. package/src/models/ConversationDetail.ts +15 -0
  116. package/src/models/ErrorDetail.ts +2 -1
  117. package/src/models/FunctionResultBody.ts +83 -0
  118. package/src/models/QueueMessageInput.ts +28 -0
  119. package/src/models/RequiredAction.ts +128 -0
  120. package/src/models/ResponseDetail.ts +8 -0
  121. package/src/models/ResponseInput.ts +30 -0
  122. package/src/models/ToolResults200Response.ts +75 -0
  123. package/src/models/ToolResultsBody.ts +83 -0
  124. package/src/models/index.ts +4 -0
  125. package/src/streaming.ts +39 -3
package/README.md CHANGED
@@ -103,6 +103,20 @@ streams the rest of the reply:
103
103
  answerClarify(config, conversation.id, { requestId, answers: { ... } })
104
104
  ```
105
105
 
106
+ **Answer the agent's function calls.** An agent with function tools (`agent.json` `functions`) pauses on a
107
+ `data-function-call-request` event (`requestId`, `calls` with `toolCallId`, `name` and `arguments`, `expiresAt`). Run
108
+ the calls, then post every result in one request with `postToolResults`. It streams the rest of the turn:
109
+
110
+ ```ts
111
+ postToolResults(config, conversation.id,
112
+ { requestId, results: [{ toolCallId: "call_1", output: '{"status": "shipped"}' }] }, { idempotencyKey })
113
+ ```
114
+
115
+ Use the same `idempotencyKey` when you retry a post: a repeat the server already delivered resolves to an empty
116
+ stream with `duplicate` set (follow the turn with `reconnect`). Errors are the response's own status (409 with a
117
+ `reason` such as `in_progress` or `expired`, 503 to retry with the same key; see
118
+ [the function tools guide](../docs/compose.md#function-tools)). Compose's `tool()` does all of this for you.
119
+
106
120
  **Timeouts.** Every ordinary call is aborted after 120 seconds unless you pass your own `signal`. To change that
107
121
  limit for the whole SDK, set `defaults.requestTimeoutMs`. A stream is aborted if no data arrives for 60 seconds. A healthy stream never hits this, because the
108
122
  server sends a ping every 15 seconds. You can change the limit with `{ idleTimeoutMs }`. To cancel from your own code,
@@ -137,7 +151,8 @@ one with `ArtifactsApi.downloadUrl`.
137
151
  ## Compose
138
152
 
139
153
  Define an agent in code, deploy it by name and run it with `sarvam-agents-client/compose` (a separate import path; the
140
- package root is unchanged):
154
+ package root is unchanged). Function tools (`tool()`, run in your process), structured output and clarify questions
155
+ are handled for you:
141
156
 
142
157
  ```ts
143
158
  import { Agent, run, deploy } from "sarvam-agents-client/compose";
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Sarvam Agents API
3
+ * Chat with a Sarvam agent, exchange files with it, and set it up (instructions, skills, knowledge bases, connectors, deploy) from your own code. Authenticate with a service token sent as a Bearer token, and send the header X-Panja-Origin: managed_agents on every request.
4
+ *
5
+ * The version of the OpenAPI document: 0.1.0
6
+ * Contact: support@sarvam.ai
7
+ *
8
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
9
+ * https://openapi-generator.tech
10
+ * Do not edit the class manually.
11
+ */
12
+ import * as runtime from '../runtime.js';
13
+ import type { ToolResults200Response, ToolResultsBody } from '../models/index.js';
14
+ export interface ToolResultsRequest {
15
+ conversationId: string;
16
+ toolResultsBody: ToolResultsBody;
17
+ idempotencyKey?: string | null;
18
+ }
19
+ /**
20
+ *
21
+ */
22
+ export declare class FunctionToolsApi extends runtime.BaseAPI {
23
+ /**
24
+ * Answer a paused turn\'s function calls and stream its continuation.
25
+ * Tool Results Route
26
+ */
27
+ toolResultsRaw(requestParameters: ToolResultsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<ToolResults200Response>>;
28
+ /**
29
+ * Answer a paused turn\'s function calls and stream its continuation.
30
+ * Tool Results Route
31
+ */
32
+ toolResults(requestParameters: ToolResultsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<ToolResults200Response>;
33
+ }
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ /* tslint:disable */
3
+ /* eslint-disable */
4
+ /**
5
+ * Sarvam Agents API
6
+ * Chat with a Sarvam agent, exchange files with it, and set it up (instructions, skills, knowledge bases, connectors, deploy) from your own code. Authenticate with a service token sent as a Bearer token, and send the header X-Panja-Origin: managed_agents on every request.
7
+ *
8
+ * The version of the OpenAPI document: 0.1.0
9
+ * Contact: support@sarvam.ai
10
+ *
11
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
12
+ * https://openapi-generator.tech
13
+ * Do not edit the class manually.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.FunctionToolsApi = void 0;
17
+ const runtime = require("../runtime.js");
18
+ const index_js_1 = require("../models/index.js");
19
+ /**
20
+ *
21
+ */
22
+ class FunctionToolsApi extends runtime.BaseAPI {
23
+ /**
24
+ * Answer a paused turn\'s function calls and stream its continuation.
25
+ * Tool Results Route
26
+ */
27
+ async toolResultsRaw(requestParameters, initOverrides) {
28
+ if (requestParameters['conversationId'] == null) {
29
+ throw new runtime.RequiredError('conversationId', 'Required parameter "conversationId" was null or undefined when calling toolResults().');
30
+ }
31
+ if (requestParameters['toolResultsBody'] == null) {
32
+ throw new runtime.RequiredError('toolResultsBody', 'Required parameter "toolResultsBody" was null or undefined when calling toolResults().');
33
+ }
34
+ const queryParameters = {};
35
+ const headerParameters = {};
36
+ headerParameters['Content-Type'] = 'application/json';
37
+ if (requestParameters['idempotencyKey'] != null) {
38
+ headerParameters['Idempotency-Key'] = String(requestParameters['idempotencyKey']);
39
+ }
40
+ if (this.configuration && this.configuration.accessToken) {
41
+ const token = this.configuration.accessToken;
42
+ const tokenString = await token("bearerAuth", []);
43
+ if (tokenString) {
44
+ headerParameters["Authorization"] = `Bearer ${tokenString}`;
45
+ }
46
+ }
47
+ const response = await this.request({
48
+ path: `/v1/conversations/{conversationId}/tool-results`.replace(`{${"conversationId"}}`, runtime.encodePathParam('conversationId', requestParameters['conversationId'])),
49
+ method: 'POST',
50
+ headers: headerParameters,
51
+ query: queryParameters,
52
+ body: (0, index_js_1.ToolResultsBodyToJSON)(requestParameters['toolResultsBody']),
53
+ }, initOverrides);
54
+ return new runtime.JSONApiResponse(response, (jsonValue) => (0, index_js_1.ToolResults200ResponseFromJSON)(jsonValue));
55
+ }
56
+ /**
57
+ * Answer a paused turn\'s function calls and stream its continuation.
58
+ * Tool Results Route
59
+ */
60
+ async toolResults(requestParameters, initOverrides) {
61
+ const response = await this.toolResultsRaw(requestParameters, initOverrides);
62
+ return await response.value();
63
+ }
64
+ }
65
+ exports.FunctionToolsApi = FunctionToolsApi;
@@ -7,6 +7,7 @@ export * from './CollectionsApi.js';
7
7
  export * from './ConversationsApi.js';
8
8
  export * from './CronsApi.js';
9
9
  export * from './CustomAPIsApi.js';
10
+ export * from './FunctionToolsApi.js';
10
11
  export * from './MessagesApi.js';
11
12
  export * from './ModelsApi.js';
12
13
  export * from './QueueApi.js';
@@ -25,6 +25,7 @@ __exportStar(require("./CollectionsApi.js"), exports);
25
25
  __exportStar(require("./ConversationsApi.js"), exports);
26
26
  __exportStar(require("./CronsApi.js"), exports);
27
27
  __exportStar(require("./CustomAPIsApi.js"), exports);
28
+ __exportStar(require("./FunctionToolsApi.js"), exports);
28
29
  __exportStar(require("./MessagesApi.js"), exports);
29
30
  __exportStar(require("./ModelsApi.js"), exports);
30
31
  __exportStar(require("./QueueApi.js"), exports);
@@ -1,4 +1,5 @@
1
1
  import { BuiltinTool } from "./tools.js";
2
+ import type { FunctionTool } from "./functionTool.js";
2
3
  import type { OutputType } from "./output.js";
3
4
  export interface ModelSettings {
4
5
  temperature?: number;
@@ -14,6 +15,8 @@ export interface Limits {
14
15
  maxToolCallsPerTurn?: number;
15
16
  maxTokensPerTurn?: number;
16
17
  }
18
+ /** An entry of `Agent` `tools`: a built-in (`sandbox()`, `webSearchTool()`, ...) or a function tool (`tool()`). */
19
+ export type AgentTool = BuiltinTool | FunctionTool;
17
20
  export interface AgentOptions<TOutput extends OutputType | undefined = undefined> {
18
21
  name: string;
19
22
  instructions?: string;
@@ -22,8 +25,11 @@ export interface AgentOptions<TOutput extends OutputType | undefined = undefined
22
25
  endpoint?: string;
23
26
  modelSettings?: ModelSettings;
24
27
  fallbackModels?: string[];
25
- /** Exact list of built-ins to keep on; omit to keep the server default (all on). */
26
- 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;
27
33
  limits?: Limits;
28
34
  metadata?: Record<string, string>;
29
35
  /** The shape of the final answer: `{ type: "json_schema", schema }` or a zod schema. `finalOutput` follows it. */
@@ -38,13 +44,20 @@ export declare class Agent<TOutput extends OutputType | undefined = undefined> {
38
44
  readonly endpoint?: string;
39
45
  readonly modelSettings?: ModelSettings;
40
46
  readonly fallbackModels?: string[];
41
- readonly tools?: readonly BuiltinTool[];
47
+ /** Built-ins and function tools, in the order given. */
48
+ readonly tools?: readonly AgentTool[];
49
+ readonly functionTimeoutSeconds?: number;
42
50
  readonly limits?: Limits;
43
51
  readonly metadata?: Record<string, string>;
44
52
  /** Kept by reference and not frozen: a zod schema must stay usable. Non-enumerable, so deepFreeze skips it. */
45
53
  readonly outputType: TOutput;
46
54
  constructor(rawOpts: AgentOptions<TOutput>);
47
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[];
48
61
  private baseSettings;
49
62
  specHash(): string;
50
63
  toSettings(): Record<string, unknown>;
@@ -4,6 +4,7 @@ exports.Agent = void 0;
4
4
  const errors_js_1 = require("./errors.js");
5
5
  const fingerprint_js_1 = require("./fingerprint.js");
6
6
  const builtins_js_1 = require("./builtins.js");
7
+ const functionTool_js_1 = require("./functionTool.js");
7
8
  const output_js_1 = require("./output.js");
8
9
  const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
9
10
  const REASONING = ["off", "none", "low", "medium", "high", "xhigh", "max"];
@@ -78,10 +79,18 @@ class Agent {
78
79
  constructor(rawOpts) {
79
80
  var _a, _b;
80
81
  const opts = normalize(rawOpts);
81
- for (const tool of (_a = opts.tools) !== null && _a !== void 0 ? _a : []) {
82
+ for (const tool of ((_a = opts.tools) !== null && _a !== void 0 ? _a : [])) {
82
83
  if (tool instanceof Agent) {
83
84
  throw new errors_js_1.NotSupportedError("sub-agents in tools are not supported yet (field: tools)");
84
85
  }
86
+ if (typeof tool === "function") {
87
+ throw new errors_js_1.UserError(`tools: ${tool.name || "a function"} is not a tool; wrap it with tool({ name, description, ` +
88
+ "parameters, execute })");
89
+ }
90
+ if (tool === null || typeof tool !== "object" || Array.isArray(tool)) {
91
+ throw new errors_js_1.UserError(`tools: ${JSON.stringify(tool)} is not a tool; list built-ins (sandbox(), webSearchTool(), ...) ` +
92
+ "and tool() function tools");
93
+ }
85
94
  }
86
95
  checkNumbers(opts);
87
96
  this.name = opts.name;
@@ -90,7 +99,17 @@ class Agent {
90
99
  this.endpoint = opts.endpoint;
91
100
  this.modelSettings = clone(opts.modelSettings);
92
101
  this.fallbackModels = clone(opts.fallbackModels);
93
- this.tools = clone(opts.tools);
102
+ // A function tool is kept by reference (it holds execute and maybe a zod schema); an object literal of that shape
103
+ // goes through tool().
104
+ this.tools = opts.tools === undefined ? undefined
105
+ : opts.tools.map((t) => {
106
+ if ((0, functionTool_js_1.isBuiltFunctionTool)(t))
107
+ return t;
108
+ if ((0, functionTool_js_1.isFunctionTool)(t))
109
+ return (0, functionTool_js_1.tool)(t);
110
+ return clone(t);
111
+ });
112
+ this.functionTimeoutSeconds = opts.functionTimeoutSeconds;
94
113
  this.limits = clone(opts.limits);
95
114
  this.metadata = clone(opts.metadata);
96
115
  Object.defineProperty(this, "outputType", { value: opts.outputType, enumerable: false, writable: false });
@@ -98,7 +117,6 @@ class Agent {
98
117
  deepFreeze(this);
99
118
  }
100
119
  check() {
101
- var _a, _b;
102
120
  if (typeof this.name !== "string" || !SLUG.test(this.name)) {
103
121
  throw new errors_js_1.UserError(`name: ${JSON.stringify(this.name)} must match ${SLUG.source}`);
104
122
  }
@@ -146,7 +164,7 @@ class Agent {
146
164
  throw new errors_js_1.UserError(`metadata: keys starting with 'sdk_' are reserved (${bad.join(", ")})`);
147
165
  }
148
166
  }
149
- const names = ((_a = this.tools) !== null && _a !== void 0 ? _a : []).map((t) => t.name);
167
+ const names = this.builtinTools.map((t) => t.name);
150
168
  for (const n of names) {
151
169
  if (builtins_js_1.BUILTIN_NAMES.indexOf(n) === -1) {
152
170
  throw new errors_js_1.UserError(`tools: unknown built-in tool ${JSON.stringify(n)} (known: ${builtins_js_1.BUILTIN_NAMES.join(", ")})`);
@@ -156,7 +174,7 @@ class Agent {
156
174
  if (dupes.length > 0) {
157
175
  throw new errors_js_1.UserError(`tools: duplicate built-in tool(s): ${dupes.join(", ")}`);
158
176
  }
159
- for (const t of (_b = this.tools) !== null && _b !== void 0 ? _b : []) {
177
+ for (const t of this.builtinTools) {
160
178
  if (t.options === undefined || Object.keys(t.options).length === 0)
161
179
  continue;
162
180
  if (t.name !== "web_search")
@@ -166,6 +184,49 @@ class Agent {
166
184
  if (names.indexOf("code_mode") !== -1 && names.indexOf("sandbox") === -1) {
167
185
  throw new errors_js_1.UserError("tools: codeMode needs sandbox; add sandbox() to tools");
168
186
  }
187
+ this.checkFunctions();
188
+ }
189
+ checkFunctions() {
190
+ const functions = this.functionTools;
191
+ if (functions.length > functionTool_js_1.FUNCTIONS_MAX) {
192
+ throw new errors_js_1.UserError(`tools: at most ${functionTool_js_1.FUNCTIONS_MAX} function tools (got ${functions.length})`);
193
+ }
194
+ const names = functions.map((t) => t.name);
195
+ const dupes = Array.from(new Set(names.filter((n, i) => names.indexOf(n) !== i))).sort();
196
+ if (dupes.length > 0)
197
+ throw new errors_js_1.UserError(`tools: duplicate function tool(s): ${dupes.join(", ")}`);
198
+ const total = functions.reduce((sum, t) => sum + (0, functionTool_js_1.compactBytes)((0, functionTool_js_1.functionToolSettings)(t)), 0);
199
+ if (total > functionTool_js_1.FUNCTIONS_TOTAL_MAX_BYTES) {
200
+ throw new errors_js_1.UserError(`tools: function tools are ${Math.ceil(total / 1024)} KB together (names, descriptions and ` +
201
+ "parameters); the server allows 64 KB, because every model call carries them");
202
+ }
203
+ const timeout = this.functionTimeoutSeconds;
204
+ if (timeout !== undefined) {
205
+ const [low, high] = functionTool_js_1.FUNCTION_TIMEOUT_RANGE;
206
+ if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < low || timeout > high) {
207
+ throw new errors_js_1.UserError(`functionTimeoutSeconds: must be a whole number of seconds from ${low} to ${high}`);
208
+ }
209
+ }
210
+ // A call still running when the server's deadline passes is answered too late (409 expired) and the run fails;
211
+ // one that times out here first goes to the model as a failed result in time.
212
+ const deadline = timeout !== null && timeout !== void 0 ? timeout : functionTool_js_1.DEFAULT_FUNCTION_TIMEOUT_SECONDS;
213
+ for (const t of functions) {
214
+ if (t.timeoutMs >= deadline * 1000) {
215
+ throw new errors_js_1.UserError(`${t.name}: timeoutMs=${t.timeoutMs} (${t.timeoutMs / 1000}s) must be shorter than the ` +
216
+ `agent's functionTimeoutSeconds (${deadline}s${timeout === undefined ? ", the server default" : ""}); ` +
217
+ "lower the tool's timeoutMs or raise functionTimeoutSeconds");
218
+ }
219
+ }
220
+ }
221
+ /** The built-in tools in `tools`, in order. */
222
+ get builtinTools() {
223
+ var _a;
224
+ return ((_a = this.tools) !== null && _a !== void 0 ? _a : []).filter((t) => !(0, functionTool_js_1.isFunctionTool)(t));
225
+ }
226
+ /** The function tools in `tools`, in order. */
227
+ get functionTools() {
228
+ var _a;
229
+ return ((_a = this.tools) !== null && _a !== void 0 ? _a : []).filter(functionTool_js_1.isFunctionTool);
169
230
  }
170
231
  baseSettings() {
171
232
  const out = { version: 1 };
@@ -200,15 +261,23 @@ class Agent {
200
261
  out["limits"] = limits;
201
262
  }
202
263
  if (this.tools !== undefined) {
203
- // Built-ins are on by default, so an exact list writes every unlisted one as off.
264
+ // Built-ins are on by default, so an exact list writes every unlisted one as off (function tools included:
265
+ // tools: [tool(...)] means that function and no built-in).
266
+ const builtins = this.builtinTools;
204
267
  const tools = {};
205
268
  for (const n of builtins_js_1.BUILTIN_NAMES) {
206
- const t = this.tools.find((x) => x.name === n);
269
+ const t = builtins.find((x) => x.name === n);
207
270
  tools[n] = t === undefined ? false
208
271
  : t.options !== undefined && Object.keys(t.options).length > 0 ? clone(t.options) : true;
209
272
  }
210
273
  out["builtin_tools"] = tools;
274
+ // Never an empty list: that would change every existing agent's fingerprint.
275
+ const functions = this.functionTools;
276
+ if (functions.length > 0)
277
+ out["functions"] = functions.map(functionTool_js_1.functionToolSettings);
211
278
  }
279
+ if (this.functionTimeoutSeconds !== undefined)
280
+ out["function_timeout_seconds"] = this.functionTimeoutSeconds;
212
281
  if (this.outputType !== undefined)
213
282
  out["output_schema"] = (0, output_js_1.outputSchema)(this.outputType);
214
283
  return out;
@@ -49,7 +49,11 @@ export declare class NotSupportedError extends AgentsError {
49
49
  }
50
50
  export declare class RunError extends AgentsError {
51
51
  readonly code: string;
52
- 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>);
53
57
  }
54
58
  export declare class DriftError extends AgentsError {
55
59
  readonly changed: string[];
@@ -56,9 +56,12 @@ class NotSupportedError extends AgentsError {
56
56
  }
57
57
  exports.NotSupportedError = NotSupportedError;
58
58
  class RunError extends AgentsError {
59
- constructor(code, message) {
59
+ constructor(code, message, status, details) {
60
60
  super(`${code}: ${message}`);
61
61
  this.code = code;
62
+ if (status !== undefined)
63
+ this.status = status;
64
+ this.details = { ...(details !== null && details !== void 0 ? details : {}) };
62
65
  }
63
66
  }
64
67
  exports.RunError = RunError;
@@ -105,3 +105,7 @@ export type Event = {
105
105
  * Never throws: malformed chunks degrade to `{ kind: "unknown", chunk }`.
106
106
  */
107
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);
@@ -128,3 +129,36 @@ function map(chunk) {
128
129
  return { kind: "unknown", chunk };
129
130
  }
130
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 {};