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
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";
@@ -149,6 +164,88 @@ console.log((await run(agent, "How do I update my card?", { client: config })).f
149
164
 
150
165
  See [docs/compose.md](../docs/compose.md#typescript) for the full guide.
151
166
 
167
+ ## Webhooks
168
+
169
+ An agent can POST an event to your server when a turn completes, fails or waits for an answer. The server must have
170
+ outbound webhooks switched on; until then a deploy keeps the setting and logs the warning `webhooks_disabled`.
171
+
172
+ **1. Make a secret and store it as a credential.** The secret is `whsec_` plus base64 of 24 to 64 random bytes. Keep
173
+ a copy where your receiver runs; Panja never shows it again. Store it as a Custom API whose host is the webhook's
174
+ host, with "enabled for chats" off (otherwise the agent's sandbox could be handed it):
175
+
176
+ ```ts
177
+ import { CustomAPIsApi } from "sarvam-agents-client";
178
+ import { generateSecret } from "sarvam-agents-client/webhooks";
179
+
180
+ const secret = generateSecret();
181
+ const api = new CustomAPIsApi(config);
182
+ const created = await api.createCustomApi({ customApiCreate: { name: "acme_webhook", host: "hooks.acme.com",
183
+ enabledForChats: false, auth: { type: "bearer", token: secret } } });
184
+ ```
185
+
186
+ The server only accepts a webhook whose credential is bound to the agent. The deploy that creates the agent binds
187
+ it for you: it creates the agent without `webhooks`, binds your Custom API named by each `secretCredential`
188
+ (`bindCustomApi`), then saves the settings in full. If you have no Custom API of that name, or several, it binds
189
+ none and says so in the `UserError` (or, while the server doesn't check credentials, in a logged warning). For an
190
+ agent that already exists, bind the credential yourself before adding `webhooks`, with the `agentId` of the
191
+ deploy that created it: `await api.bindCustomApi({ agentId, bindCustomApiBody: { customApiId: created.id } })`.
192
+
193
+ **2. Name the endpoint on the agent** (`agent.json` `webhooks`, with `secretCredential` written as
194
+ `secret_credential`):
195
+
196
+ ```ts
197
+ import { Agent } from "sarvam-agents-client/compose";
198
+
199
+ const agent = new Agent({ name: "support-bot", instructions: "...", webhooks: [
200
+ { url: "https://hooks.acme.com/panja", events: ["turn.completed", "turn.failed", "turn.requires_action"],
201
+ secretCredential: "acme_webhook" },
202
+ ] });
203
+ ```
204
+
205
+ The rules are Python's (see the [Python README](../python/README.md#webhooks)), with the same `UserError` messages,
206
+ which name the `agent.json` path (`webhooks.0.secret_credential: ...`). Checks that need the server fail the deploy
207
+ (and delete an agent the deploy created) with `UserError`, whose `issues` hold the server's `{ code, path, message }` list; a server without webhooks throws
208
+ `NotSupportedByServerError` with `features` `["webhooks"]`.
209
+
210
+ **3. Verify and parse each delivery** from `sarvam-agents-client/webhooks` (a separate import path; `node:crypto`
211
+ only, so Node 18+ or a runtime with Node's `crypto` and `Buffer`, such as Workers with `nodejs_compat`; not a browser
212
+ or an edge runtime without them), on the raw body bytes (`express.raw()`, not `express.json()`):
213
+
214
+ ```ts
215
+ import { parseEvent, verify, WebhookVerificationError } from "sarvam-agents-client/webhooks";
216
+
217
+ let msgId: string;
218
+ try {
219
+ ({ msgId } = verify(req.body, req.headers, secret)); // or [oldSecret, newSecret] while rotating
220
+ } catch (e) {
221
+ if (e instanceof WebhookVerificationError) return res.status(400).send(e.reason);
222
+ throw e;
223
+ }
224
+ const event = parseEvent(req.body);
225
+ if (event?.type === "turn.completed") console.log(event.data.text, event.data.output);
226
+ ```
227
+
228
+ `verify(payload, headers, secret, { tolerance, now })` takes a `Buffer`/`Uint8Array` or string body, and Node's
229
+ `req.headers` or a fetch `Headers`. It behaves exactly like Python's `verify` and the server's reference verifier,
230
+ and both SDKs run the server's test vectors. It returns `{ msgId, timestamp }`; `e.reason` and `SecretFormatError`
231
+ are as in Python; an empty list of secrets throws `TypeError`. A header given as an array counts as missing.
232
+
233
+ `parseEvent` returns the JSON as sent, typed by its `type` (`TurnCompletedEvent`, `TurnFailedEvent`,
234
+ `TurnRequiresActionEvent`; narrow with `event.type`), or `undefined` for an event type this release doesn't know. It
235
+ checks the envelope and `data.status` and throws `TypeError` for a body that is not an event. A newer server may send
236
+ an action type this release doesn't know (typed `UnknownAction`, passed through as sent), so keep a default branch
237
+ when you switch on `action.type`. Answer a `clarify` action with `answerClarify` and a `function_call` action with
238
+ `postToolResults` (one result per `toolCallId`); a turn the SDK runner is driving answers its own function calls, so
239
+ leave those alone (a second answer gets 409 `already_answered`). The fields are listed
240
+ in the [Python README](../python/README.md#webhooks), in camelCase here (`data.turn.responseId`, `outputSkipped`,
241
+ `rawText`, `actions[i].toolCallId`).
242
+
243
+ Reply 2xx within 10 seconds and do the work afterwards. Only a 2xx stops the retries: a 408, 425, 429, 5xx, timeout
244
+ or network failure is retried (10 attempts over about 16 hours), while a 3xx or any other 4xx is given up at once.
245
+ So return a 5xx (or 429) for a failure you want retried, never a 4xx. Dedupe on `msgId`. Starting a delivery is best effort: if an event you expect doesn't come, read the turn from the conversation
246
+ API. A complete Express receiver is in
247
+ [docs/examples/webhooks/express_receiver.ts](../docs/examples/webhooks/express_receiver.ts).
248
+
152
249
  ## Errors
153
250
 
154
251
  If an ID passed as a path parameter is empty, `.` or `..`, the SDK throws `InvalidPathParameterError` before
@@ -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,5 +1,7 @@
1
1
  import { BuiltinTool } from "./tools.js";
2
+ import type { FunctionTool } from "./functionTool.js";
2
3
  import type { OutputType } from "./output.js";
4
+ import type { Webhook } from "./webhook.js";
3
5
  export interface ModelSettings {
4
6
  temperature?: number;
5
7
  topP?: number;
@@ -14,6 +16,8 @@ export interface Limits {
14
16
  maxToolCallsPerTurn?: number;
15
17
  maxTokensPerTurn?: number;
16
18
  }
19
+ /** An entry of `Agent` `tools`: a built-in (`sandbox()`, `webSearchTool()`, ...) or a function tool (`tool()`). */
20
+ export type AgentTool = BuiltinTool | FunctionTool;
17
21
  export interface AgentOptions<TOutput extends OutputType | undefined = undefined> {
18
22
  name: string;
19
23
  instructions?: string;
@@ -22,12 +26,17 @@ export interface AgentOptions<TOutput extends OutputType | undefined = undefined
22
26
  endpoint?: string;
23
27
  modelSettings?: ModelSettings;
24
28
  fallbackModels?: string[];
25
- /** Exact list of built-ins to keep on; omit to keep the server default (all on). */
26
- tools?: BuiltinTool[];
29
+ /** Exact list of what the agent may use: built-ins (the unlisted ones are turned off) and function tools (agent.json
30
+ * `functions`). Omit to keep the server default (every built-in on, no functions). */
31
+ tools?: AgentTool[];
32
+ /** Seconds (10 to 3000, default 600) the server waits for this process to answer a function call (`function_timeout_seconds`). */
33
+ functionTimeoutSeconds?: number;
27
34
  limits?: Limits;
28
35
  metadata?: Record<string, string>;
29
36
  /** The shape of the final answer: `{ type: "json_schema", schema }` or a zod schema. `finalOutput` follows it. */
30
37
  outputType?: TOutput;
38
+ /** Endpoints that receive the turn's events (agent.json `webhooks`); at most 5. */
39
+ webhooks?: Webhook[];
31
40
  }
32
41
  /** An agent with any output type: use it for helpers that accept every agent (plain `Agent` means a text agent). */
33
42
  export type AnyAgent = Agent<OutputType | undefined>;
@@ -38,13 +47,21 @@ export declare class Agent<TOutput extends OutputType | undefined = undefined> {
38
47
  readonly endpoint?: string;
39
48
  readonly modelSettings?: ModelSettings;
40
49
  readonly fallbackModels?: string[];
41
- readonly tools?: readonly BuiltinTool[];
50
+ /** Built-ins and function tools, in the order given. */
51
+ readonly tools?: readonly AgentTool[];
52
+ readonly functionTimeoutSeconds?: number;
42
53
  readonly limits?: Limits;
43
54
  readonly metadata?: Record<string, string>;
55
+ readonly webhooks?: readonly Webhook[];
44
56
  /** Kept by reference and not frozen: a zod schema must stay usable. Non-enumerable, so deepFreeze skips it. */
45
57
  readonly outputType: TOutput;
46
58
  constructor(rawOpts: AgentOptions<TOutput>);
47
59
  private check;
60
+ private checkFunctions;
61
+ /** The built-in tools in `tools`, in order. */
62
+ get builtinTools(): readonly BuiltinTool[];
63
+ /** The function tools in `tools`, in order. */
64
+ get functionTools(): readonly FunctionTool[];
48
65
  private baseSettings;
49
66
  specHash(): string;
50
67
  toSettings(): Record<string, unknown>;
@@ -4,7 +4,9 @@ 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");
9
+ const webhook_js_1 = require("./webhook.js");
8
10
  const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
9
11
  const REASONING = ["off", "none", "low", "medium", "high", "xhigh", "max"];
10
12
  const TOOL_CHOICES = ["auto", "none"];
@@ -78,10 +80,18 @@ class Agent {
78
80
  constructor(rawOpts) {
79
81
  var _a, _b;
80
82
  const opts = normalize(rawOpts);
81
- for (const tool of (_a = opts.tools) !== null && _a !== void 0 ? _a : []) {
83
+ for (const tool of ((_a = opts.tools) !== null && _a !== void 0 ? _a : [])) {
82
84
  if (tool instanceof Agent) {
83
85
  throw new errors_js_1.NotSupportedError("sub-agents in tools are not supported yet (field: tools)");
84
86
  }
87
+ if (typeof tool === "function") {
88
+ throw new errors_js_1.UserError(`tools: ${tool.name || "a function"} is not a tool; wrap it with tool({ name, description, ` +
89
+ "parameters, execute })");
90
+ }
91
+ if (tool === null || typeof tool !== "object" || Array.isArray(tool)) {
92
+ throw new errors_js_1.UserError(`tools: ${JSON.stringify(tool)} is not a tool; list built-ins (sandbox(), webSearchTool(), ...) ` +
93
+ "and tool() function tools");
94
+ }
85
95
  }
86
96
  checkNumbers(opts);
87
97
  this.name = opts.name;
@@ -90,15 +100,27 @@ class Agent {
90
100
  this.endpoint = opts.endpoint;
91
101
  this.modelSettings = clone(opts.modelSettings);
92
102
  this.fallbackModels = clone(opts.fallbackModels);
93
- this.tools = clone(opts.tools);
103
+ // A function tool is kept by reference (it holds execute and maybe a zod schema); an object literal of that shape
104
+ // goes through tool().
105
+ this.tools = opts.tools === undefined ? undefined
106
+ : opts.tools.map((t) => {
107
+ if ((0, functionTool_js_1.isBuiltFunctionTool)(t))
108
+ return t;
109
+ if ((0, functionTool_js_1.isFunctionTool)(t))
110
+ return (0, functionTool_js_1.tool)(t);
111
+ return clone(t);
112
+ });
113
+ this.functionTimeoutSeconds = opts.functionTimeoutSeconds;
94
114
  this.limits = clone(opts.limits);
95
115
  this.metadata = clone(opts.metadata);
116
+ this.webhooks = clone(opts.webhooks);
96
117
  Object.defineProperty(this, "outputType", { value: opts.outputType, enumerable: false, writable: false });
97
118
  this.check();
119
+ if (this.webhooks !== undefined)
120
+ this.webhooks = (0, webhook_js_1.copyWebhooks)(this.webhooks);
98
121
  deepFreeze(this);
99
122
  }
100
123
  check() {
101
- var _a, _b;
102
124
  if (typeof this.name !== "string" || !SLUG.test(this.name)) {
103
125
  throw new errors_js_1.UserError(`name: ${JSON.stringify(this.name)} must match ${SLUG.source}`);
104
126
  }
@@ -146,7 +168,7 @@ class Agent {
146
168
  throw new errors_js_1.UserError(`metadata: keys starting with 'sdk_' are reserved (${bad.join(", ")})`);
147
169
  }
148
170
  }
149
- const names = ((_a = this.tools) !== null && _a !== void 0 ? _a : []).map((t) => t.name);
171
+ const names = this.builtinTools.map((t) => t.name);
150
172
  for (const n of names) {
151
173
  if (builtins_js_1.BUILTIN_NAMES.indexOf(n) === -1) {
152
174
  throw new errors_js_1.UserError(`tools: unknown built-in tool ${JSON.stringify(n)} (known: ${builtins_js_1.BUILTIN_NAMES.join(", ")})`);
@@ -156,7 +178,7 @@ class Agent {
156
178
  if (dupes.length > 0) {
157
179
  throw new errors_js_1.UserError(`tools: duplicate built-in tool(s): ${dupes.join(", ")}`);
158
180
  }
159
- for (const t of (_b = this.tools) !== null && _b !== void 0 ? _b : []) {
181
+ for (const t of this.builtinTools) {
160
182
  if (t.options === undefined || Object.keys(t.options).length === 0)
161
183
  continue;
162
184
  if (t.name !== "web_search")
@@ -166,6 +188,51 @@ class Agent {
166
188
  if (names.indexOf("code_mode") !== -1 && names.indexOf("sandbox") === -1) {
167
189
  throw new errors_js_1.UserError("tools: codeMode needs sandbox; add sandbox() to tools");
168
190
  }
191
+ if (this.webhooks !== undefined)
192
+ (0, webhook_js_1.checkWebhooks)(this.webhooks);
193
+ this.checkFunctions();
194
+ }
195
+ checkFunctions() {
196
+ const functions = this.functionTools;
197
+ if (functions.length > functionTool_js_1.FUNCTIONS_MAX) {
198
+ throw new errors_js_1.UserError(`tools: at most ${functionTool_js_1.FUNCTIONS_MAX} function tools (got ${functions.length})`);
199
+ }
200
+ const names = functions.map((t) => t.name);
201
+ const dupes = Array.from(new Set(names.filter((n, i) => names.indexOf(n) !== i))).sort();
202
+ if (dupes.length > 0)
203
+ throw new errors_js_1.UserError(`tools: duplicate function tool(s): ${dupes.join(", ")}`);
204
+ const total = functions.reduce((sum, t) => sum + (0, functionTool_js_1.compactBytes)((0, functionTool_js_1.functionToolSettings)(t)), 0);
205
+ if (total > functionTool_js_1.FUNCTIONS_TOTAL_MAX_BYTES) {
206
+ throw new errors_js_1.UserError(`tools: function tools are ${Math.ceil(total / 1024)} KB together (names, descriptions and ` +
207
+ "parameters); the server allows 64 KB, because every model call carries them");
208
+ }
209
+ const timeout = this.functionTimeoutSeconds;
210
+ if (timeout !== undefined) {
211
+ const [low, high] = functionTool_js_1.FUNCTION_TIMEOUT_RANGE;
212
+ if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < low || timeout > high) {
213
+ throw new errors_js_1.UserError(`functionTimeoutSeconds: must be a whole number of seconds from ${low} to ${high}`);
214
+ }
215
+ }
216
+ // A call still running when the server's deadline passes is answered too late (409 expired) and the run fails;
217
+ // one that times out here first goes to the model as a failed result in time.
218
+ const deadline = timeout !== null && timeout !== void 0 ? timeout : functionTool_js_1.DEFAULT_FUNCTION_TIMEOUT_SECONDS;
219
+ for (const t of functions) {
220
+ if (t.timeoutMs >= deadline * 1000) {
221
+ throw new errors_js_1.UserError(`${t.name}: timeoutMs=${t.timeoutMs} (${t.timeoutMs / 1000}s) must be shorter than the ` +
222
+ `agent's functionTimeoutSeconds (${deadline}s${timeout === undefined ? ", the server default" : ""}); ` +
223
+ "lower the tool's timeoutMs or raise functionTimeoutSeconds");
224
+ }
225
+ }
226
+ }
227
+ /** The built-in tools in `tools`, in order. */
228
+ get builtinTools() {
229
+ var _a;
230
+ return ((_a = this.tools) !== null && _a !== void 0 ? _a : []).filter((t) => !(0, functionTool_js_1.isFunctionTool)(t));
231
+ }
232
+ /** The function tools in `tools`, in order. */
233
+ get functionTools() {
234
+ var _a;
235
+ return ((_a = this.tools) !== null && _a !== void 0 ? _a : []).filter(functionTool_js_1.isFunctionTool);
169
236
  }
170
237
  baseSettings() {
171
238
  const out = { version: 1 };
@@ -200,15 +267,25 @@ class Agent {
200
267
  out["limits"] = limits;
201
268
  }
202
269
  if (this.tools !== undefined) {
203
- // Built-ins are on by default, so an exact list writes every unlisted one as off.
270
+ // Built-ins are on by default, so an exact list writes every unlisted one as off (function tools included:
271
+ // tools: [tool(...)] means that function and no built-in).
272
+ const builtins = this.builtinTools;
204
273
  const tools = {};
205
274
  for (const n of builtins_js_1.BUILTIN_NAMES) {
206
- const t = this.tools.find((x) => x.name === n);
275
+ const t = builtins.find((x) => x.name === n);
207
276
  tools[n] = t === undefined ? false
208
277
  : t.options !== undefined && Object.keys(t.options).length > 0 ? clone(t.options) : true;
209
278
  }
210
279
  out["builtin_tools"] = tools;
280
+ // Never an empty list: that would change every existing agent's fingerprint.
281
+ const functions = this.functionTools;
282
+ if (functions.length > 0)
283
+ out["functions"] = functions.map(functionTool_js_1.functionToolSettings);
211
284
  }
285
+ if (this.functionTimeoutSeconds !== undefined)
286
+ out["function_timeout_seconds"] = this.functionTimeoutSeconds;
287
+ if (this.webhooks !== undefined && this.webhooks.length > 0)
288
+ out["webhooks"] = (0, webhook_js_1.webhooksJson)(this.webhooks);
212
289
  if (this.outputType !== undefined)
213
290
  out["output_schema"] = (0, output_js_1.outputSchema)(this.outputType);
214
291
  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 {};