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
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WEBHOOKS_MAX = void 0;
4
+ exports.urlProblem = urlProblem;
5
+ exports.checkWebhooks = checkWebhooks;
6
+ exports.copyWebhooks = copyWebhooks;
7
+ exports.webhooksJson = webhooksJson;
8
+ /**
9
+ * `webhooks` entries of `agent.json`, checked locally with the server's cheap rules (as the Python SDK does).
10
+ *
11
+ * The server (`claw_common/agent_settings/webhooks.py`) also checks that the host resolves to a public address and
12
+ * that `secret_credential` names a vault credential bound to the agent whose allowed hosts cover the URL; those need
13
+ * I/O and stay on the server, which refuses the save with a 422 that `deploy` throws as `UserError`. A new agent has
14
+ * no credentials bound yet, so the deploy that creates it binds the caller's Custom API of each named credential first
15
+ * (`SettingsTransport.createAgent`).
16
+ */
17
+ const errors_js_1 = require("./errors.js");
18
+ const webhooks_js_1 = require("../webhooks.js");
19
+ exports.WEBHOOKS_MAX = 5;
20
+ const WEBHOOK_URL_MAX = 2048;
21
+ const SECRET_CREDENTIAL_MAX = 256;
22
+ const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
23
+ // A last label that is a number (decimal, or 0x hex) makes resolvers read the whole host as an IPv4 address.
24
+ const NUMERIC_LABEL = /^(?:[0-9]+|0x[0-9a-f]*)$/;
25
+ const SCHEME = /^[A-Za-z][A-Za-z0-9+\-.]*$/;
26
+ /** Length in code points, as Python's `len`. */
27
+ function codePoints(text) {
28
+ return Array.from(text).length;
29
+ }
30
+ /** `[scheme, netloc, path, query]` as Python 3.12's `urlsplit` splits a URL without a fragment. */
31
+ function split(url) {
32
+ let rest = url;
33
+ let scheme = "";
34
+ const i = rest.indexOf(":");
35
+ if (i > 0 && SCHEME.test(rest.slice(0, i))) {
36
+ scheme = rest.slice(0, i).toLowerCase();
37
+ rest = rest.slice(i + 1);
38
+ }
39
+ let netloc = "";
40
+ if (rest.slice(0, 2) === "//") {
41
+ let end = rest.length;
42
+ for (const c of "/?#") {
43
+ const at = rest.indexOf(c, 2);
44
+ if (at >= 0)
45
+ end = Math.min(end, at);
46
+ }
47
+ netloc = rest.slice(2, end);
48
+ rest = rest.slice(end);
49
+ }
50
+ let query = "";
51
+ const q = rest.indexOf("?");
52
+ if (q >= 0) {
53
+ query = rest.slice(q + 1);
54
+ rest = rest.slice(0, q);
55
+ }
56
+ return [scheme, netloc, rest, query];
57
+ }
58
+ /** Python's `str.partition`. */
59
+ function partition(text, sep) {
60
+ const at = text.indexOf(sep);
61
+ return at < 0 ? [text, "", ""] : [text.slice(0, at), sep, text.slice(at + sep.length)];
62
+ }
63
+ /** `urlsplit`'s host (lowercased) and raw port (`null` when absent or empty). */
64
+ function hostPort(netloc) {
65
+ const hostinfo = netloc.slice(netloc.lastIndexOf("@") + 1);
66
+ const [, bracket, bracketed] = partition(hostinfo, "[");
67
+ let host;
68
+ let port;
69
+ if (bracket) {
70
+ const [inner, , after] = partition(bracketed, "]");
71
+ host = inner;
72
+ port = partition(after, ":")[2];
73
+ }
74
+ else {
75
+ [host, , port] = partition(hostinfo, ":");
76
+ }
77
+ return [host.toLowerCase(), port || null];
78
+ }
79
+ function stripTrailingDots(host) {
80
+ return host.replace(/\.+$/, "");
81
+ }
82
+ /** Why `url` is not an allowed webhook URL, or null. Every URL the server refuses is refused, with the server's
83
+ * sentence for every URL Python's `urlsplit` parses; for a netloc its NFKC check refuses, the sentence may differ. */
84
+ function urlProblem(url) {
85
+ if (codePoints(url) > WEBHOOK_URL_MAX)
86
+ return `url must be at most ${WEBHOOK_URL_MAX} characters.`;
87
+ for (let i = 0; i < url.length; i++) {
88
+ const code = url.charCodeAt(i);
89
+ if (code <= 0x20 || code === 0x7f)
90
+ return "url must not contain spaces or control characters.";
91
+ }
92
+ if (url.indexOf("#") !== -1)
93
+ return "url must not have a fragment.";
94
+ const [scheme, netloc, path] = split(url);
95
+ if (scheme !== "https")
96
+ return "url must start with https://.";
97
+ if (netloc.indexOf("@") !== -1)
98
+ return "url must not contain a user name or password.";
99
+ // urlsplit refuses unbalanced brackets outright
100
+ if ((netloc.indexOf("[") !== -1) !== (netloc.indexOf("]") !== -1)) {
101
+ return "url host must be a DNS name, not an IP address.";
102
+ }
103
+ const [rawHost, port] = hostPort(netloc);
104
+ if (port !== null) {
105
+ if (!/^[0-9]+$/.test(port) || Number(port) > 65535) {
106
+ return "url has an invalid port; leave the port out (443 is used).";
107
+ }
108
+ if (Number(port) !== 443)
109
+ return "url must use port 443; leave the port out.";
110
+ }
111
+ const host = stripTrailingDots(rawHost);
112
+ if (!host)
113
+ return "url must name a host, like https://hooks.example.com/panja.";
114
+ if (netloc.indexOf("[") !== -1)
115
+ return "url host must be a DNS name, not an IP address.";
116
+ const labels = host.split(".");
117
+ if (!labels.every((label) => LABEL.test(label)))
118
+ return "url host must be a DNS name, like hooks.example.com.";
119
+ if (NUMERIC_LABEL.test(labels[labels.length - 1]))
120
+ return "url host must be a DNS name, not an IP address.";
121
+ if (path.split("/").some((seg) => seg === "." || seg === ".."))
122
+ return "url path must not contain . or .. segments.";
123
+ return null;
124
+ }
125
+ /** Host (lowercased, no trailing dot, no port), path and query: two URLs with one key are one endpoint. */
126
+ function urlKey(url) {
127
+ const [, netloc, path, query] = split(url);
128
+ return `${stripTrailingDots(hostPort(netloc)[0])}${path}?${query}`;
129
+ }
130
+ /** The server's pure `webhooks` rules (types first); throws `UserError` naming the agent.json path. */
131
+ function checkWebhooks(webhooks) {
132
+ if (!Array.isArray(webhooks))
133
+ throw new errors_js_1.UserError("webhooks: must be a list of webhooks");
134
+ if (webhooks.length > exports.WEBHOOKS_MAX) {
135
+ throw new errors_js_1.UserError(`webhooks: webhooks may hold at most ${exports.WEBHOOKS_MAX} endpoints.`);
136
+ }
137
+ const seen = new Set();
138
+ webhooks.forEach((hook, i) => {
139
+ const where = `webhooks.${i}.`;
140
+ if (typeof hook !== "object" || hook === null || Array.isArray(hook)) {
141
+ throw new errors_js_1.UserError(`webhooks.${i}: must be an object with url, events and secretCredential`);
142
+ }
143
+ const { url, events, secretCredential } = hook;
144
+ if (typeof url !== "string")
145
+ throw new errors_js_1.UserError(where + "url: must be a string");
146
+ if (!Array.isArray(events) || !events.every((e) => typeof e === "string")) {
147
+ throw new errors_js_1.UserError(where + "events: must be a list of event names");
148
+ }
149
+ if (typeof secretCredential !== "string")
150
+ throw new errors_js_1.UserError(where + "secretCredential: must be a string");
151
+ // Python's Webhook is extra="forbid": a key dropped silently (a misplaced secret) would never verify.
152
+ const extra = Object.keys(hook).find((k) => k !== "url" && k !== "events" && k !== "secretCredential");
153
+ if (extra !== undefined)
154
+ throw new errors_js_1.UserError(where + extra + ": Extra inputs are not permitted");
155
+ const problem = urlProblem(url);
156
+ if (problem !== null)
157
+ throw new errors_js_1.UserError(where + "url: " + problem);
158
+ if (events.length < 1 || events.length > webhooks_js_1.WEBHOOK_EVENTS.length) {
159
+ throw new errors_js_1.UserError(where + `events: events must list 1 to ${webhooks_js_1.WEBHOOK_EVENTS.length} events.`);
160
+ }
161
+ if (events.some((e) => webhooks_js_1.WEBHOOK_EVENTS.indexOf(e) === -1)) {
162
+ throw new errors_js_1.UserError(where + `events: events must be from: ${webhooks_js_1.WEBHOOK_EVENTS.join(", ")}.`);
163
+ }
164
+ if (new Set(events).size !== events.length)
165
+ throw new errors_js_1.UserError(where + "events: events must not repeat an event.");
166
+ const n = codePoints(secretCredential);
167
+ if (n < 1 || n > SECRET_CREDENTIAL_MAX) {
168
+ throw new errors_js_1.UserError(where + "secret_credential: secret_credential must be the name of a vault credential " +
169
+ `(1 to ${SECRET_CREDENTIAL_MAX} characters).`);
170
+ }
171
+ const key = urlKey(url);
172
+ if (seen.has(key)) {
173
+ throw new errors_js_1.UserError(where + "url: webhooks must not list the same url twice; put all its events on one entry.");
174
+ }
175
+ seen.add(key);
176
+ });
177
+ }
178
+ /** Only the three fields, in agent.json's names (a copy). */
179
+ function copyWebhooks(webhooks) {
180
+ return webhooks.map((h) => ({ url: h.url, events: [...h.events], secretCredential: h.secretCredential }));
181
+ }
182
+ function webhooksJson(webhooks) {
183
+ return webhooks.map((h) => ({ url: h.url, events: [...h.events], secret_credential: h.secretCredential }));
184
+ }
@@ -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,61 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ /**
4
+ * Sarvam Agents API
5
+ * 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.
6
+ *
7
+ * The version of the OpenAPI document: 0.1.0
8
+ * Contact: support@sarvam.ai
9
+ *
10
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
11
+ * https://openapi-generator.tech
12
+ * Do not edit the class manually.
13
+ */
14
+ import * as runtime from '../runtime.js';
15
+ import { ToolResults200ResponseFromJSON, ToolResultsBodyToJSON, } from '../models/index.js';
16
+ /**
17
+ *
18
+ */
19
+ export class FunctionToolsApi extends runtime.BaseAPI {
20
+ /**
21
+ * Answer a paused turn\'s function calls and stream its continuation.
22
+ * Tool Results Route
23
+ */
24
+ async toolResultsRaw(requestParameters, initOverrides) {
25
+ if (requestParameters['conversationId'] == null) {
26
+ throw new runtime.RequiredError('conversationId', 'Required parameter "conversationId" was null or undefined when calling toolResults().');
27
+ }
28
+ if (requestParameters['toolResultsBody'] == null) {
29
+ throw new runtime.RequiredError('toolResultsBody', 'Required parameter "toolResultsBody" was null or undefined when calling toolResults().');
30
+ }
31
+ const queryParameters = {};
32
+ const headerParameters = {};
33
+ headerParameters['Content-Type'] = 'application/json';
34
+ if (requestParameters['idempotencyKey'] != null) {
35
+ headerParameters['Idempotency-Key'] = String(requestParameters['idempotencyKey']);
36
+ }
37
+ if (this.configuration && this.configuration.accessToken) {
38
+ const token = this.configuration.accessToken;
39
+ const tokenString = await token("bearerAuth", []);
40
+ if (tokenString) {
41
+ headerParameters["Authorization"] = `Bearer ${tokenString}`;
42
+ }
43
+ }
44
+ const response = await this.request({
45
+ path: `/v1/conversations/{conversationId}/tool-results`.replace(`{${"conversationId"}}`, runtime.encodePathParam('conversationId', requestParameters['conversationId'])),
46
+ method: 'POST',
47
+ headers: headerParameters,
48
+ query: queryParameters,
49
+ body: ToolResultsBodyToJSON(requestParameters['toolResultsBody']),
50
+ }, initOverrides);
51
+ return new runtime.JSONApiResponse(response, (jsonValue) => ToolResults200ResponseFromJSON(jsonValue));
52
+ }
53
+ /**
54
+ * Answer a paused turn\'s function calls and stream its continuation.
55
+ * Tool Results Route
56
+ */
57
+ async toolResults(requestParameters, initOverrides) {
58
+ const response = await this.toolResultsRaw(requestParameters, initOverrides);
59
+ return await response.value();
60
+ }
61
+ }
@@ -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';
@@ -9,6 +9,7 @@ export * from './CollectionsApi.js';
9
9
  export * from './ConversationsApi.js';
10
10
  export * from './CronsApi.js';
11
11
  export * from './CustomAPIsApi.js';
12
+ export * from './FunctionToolsApi.js';
12
13
  export * from './MessagesApi.js';
13
14
  export * from './ModelsApi.js';
14
15
  export * from './QueueApi.js';
@@ -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>;
@@ -1,7 +1,9 @@
1
1
  import { NotSupportedError, UserError } from "./errors.js";
2
2
  import { settingsFingerprint } from "./fingerprint.js";
3
3
  import { BUILTIN_NAMES, checkWebSearchOptions } from "./builtins.js";
4
+ import { DEFAULT_FUNCTION_TIMEOUT_SECONDS, FUNCTION_TIMEOUT_RANGE, FUNCTIONS_MAX, FUNCTIONS_TOTAL_MAX_BYTES, compactBytes, functionToolSettings, isBuiltFunctionTool, isFunctionTool, tool, } from "./functionTool.js";
4
5
  import { checkOutputType, outputSchema } from "./output.js";
6
+ import { checkWebhooks, copyWebhooks, webhooksJson } from "./webhook.js";
5
7
  const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
6
8
  const REASONING = ["off", "none", "low", "medium", "high", "xhigh", "max"];
7
9
  const TOOL_CHOICES = ["auto", "none"];
@@ -75,10 +77,18 @@ export class Agent {
75
77
  constructor(rawOpts) {
76
78
  var _a, _b;
77
79
  const opts = normalize(rawOpts);
78
- for (const tool of (_a = opts.tools) !== null && _a !== void 0 ? _a : []) {
80
+ for (const tool of ((_a = opts.tools) !== null && _a !== void 0 ? _a : [])) {
79
81
  if (tool instanceof Agent) {
80
82
  throw new NotSupportedError("sub-agents in tools are not supported yet (field: tools)");
81
83
  }
84
+ if (typeof tool === "function") {
85
+ throw new UserError(`tools: ${tool.name || "a function"} is not a tool; wrap it with tool({ name, description, ` +
86
+ "parameters, execute })");
87
+ }
88
+ if (tool === null || typeof tool !== "object" || Array.isArray(tool)) {
89
+ throw new UserError(`tools: ${JSON.stringify(tool)} is not a tool; list built-ins (sandbox(), webSearchTool(), ...) ` +
90
+ "and tool() function tools");
91
+ }
82
92
  }
83
93
  checkNumbers(opts);
84
94
  this.name = opts.name;
@@ -87,15 +97,27 @@ export class Agent {
87
97
  this.endpoint = opts.endpoint;
88
98
  this.modelSettings = clone(opts.modelSettings);
89
99
  this.fallbackModels = clone(opts.fallbackModels);
90
- this.tools = clone(opts.tools);
100
+ // A function tool is kept by reference (it holds execute and maybe a zod schema); an object literal of that shape
101
+ // goes through tool().
102
+ this.tools = opts.tools === undefined ? undefined
103
+ : opts.tools.map((t) => {
104
+ if (isBuiltFunctionTool(t))
105
+ return t;
106
+ if (isFunctionTool(t))
107
+ return tool(t);
108
+ return clone(t);
109
+ });
110
+ this.functionTimeoutSeconds = opts.functionTimeoutSeconds;
91
111
  this.limits = clone(opts.limits);
92
112
  this.metadata = clone(opts.metadata);
113
+ this.webhooks = clone(opts.webhooks);
93
114
  Object.defineProperty(this, "outputType", { value: opts.outputType, enumerable: false, writable: false });
94
115
  this.check();
116
+ if (this.webhooks !== undefined)
117
+ this.webhooks = copyWebhooks(this.webhooks);
95
118
  deepFreeze(this);
96
119
  }
97
120
  check() {
98
- var _a, _b;
99
121
  if (typeof this.name !== "string" || !SLUG.test(this.name)) {
100
122
  throw new UserError(`name: ${JSON.stringify(this.name)} must match ${SLUG.source}`);
101
123
  }
@@ -143,7 +165,7 @@ export class Agent {
143
165
  throw new UserError(`metadata: keys starting with 'sdk_' are reserved (${bad.join(", ")})`);
144
166
  }
145
167
  }
146
- const names = ((_a = this.tools) !== null && _a !== void 0 ? _a : []).map((t) => t.name);
168
+ const names = this.builtinTools.map((t) => t.name);
147
169
  for (const n of names) {
148
170
  if (BUILTIN_NAMES.indexOf(n) === -1) {
149
171
  throw new UserError(`tools: unknown built-in tool ${JSON.stringify(n)} (known: ${BUILTIN_NAMES.join(", ")})`);
@@ -153,7 +175,7 @@ export class Agent {
153
175
  if (dupes.length > 0) {
154
176
  throw new UserError(`tools: duplicate built-in tool(s): ${dupes.join(", ")}`);
155
177
  }
156
- for (const t of (_b = this.tools) !== null && _b !== void 0 ? _b : []) {
178
+ for (const t of this.builtinTools) {
157
179
  if (t.options === undefined || Object.keys(t.options).length === 0)
158
180
  continue;
159
181
  if (t.name !== "web_search")
@@ -163,6 +185,51 @@ export class Agent {
163
185
  if (names.indexOf("code_mode") !== -1 && names.indexOf("sandbox") === -1) {
164
186
  throw new UserError("tools: codeMode needs sandbox; add sandbox() to tools");
165
187
  }
188
+ if (this.webhooks !== undefined)
189
+ checkWebhooks(this.webhooks);
190
+ this.checkFunctions();
191
+ }
192
+ checkFunctions() {
193
+ const functions = this.functionTools;
194
+ if (functions.length > FUNCTIONS_MAX) {
195
+ throw new UserError(`tools: at most ${FUNCTIONS_MAX} function tools (got ${functions.length})`);
196
+ }
197
+ const names = functions.map((t) => t.name);
198
+ const dupes = Array.from(new Set(names.filter((n, i) => names.indexOf(n) !== i))).sort();
199
+ if (dupes.length > 0)
200
+ throw new UserError(`tools: duplicate function tool(s): ${dupes.join(", ")}`);
201
+ const total = functions.reduce((sum, t) => sum + compactBytes(functionToolSettings(t)), 0);
202
+ if (total > FUNCTIONS_TOTAL_MAX_BYTES) {
203
+ throw new UserError(`tools: function tools are ${Math.ceil(total / 1024)} KB together (names, descriptions and ` +
204
+ "parameters); the server allows 64 KB, because every model call carries them");
205
+ }
206
+ const timeout = this.functionTimeoutSeconds;
207
+ if (timeout !== undefined) {
208
+ const [low, high] = FUNCTION_TIMEOUT_RANGE;
209
+ if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < low || timeout > high) {
210
+ throw new UserError(`functionTimeoutSeconds: must be a whole number of seconds from ${low} to ${high}`);
211
+ }
212
+ }
213
+ // A call still running when the server's deadline passes is answered too late (409 expired) and the run fails;
214
+ // one that times out here first goes to the model as a failed result in time.
215
+ const deadline = timeout !== null && timeout !== void 0 ? timeout : DEFAULT_FUNCTION_TIMEOUT_SECONDS;
216
+ for (const t of functions) {
217
+ if (t.timeoutMs >= deadline * 1000) {
218
+ throw new UserError(`${t.name}: timeoutMs=${t.timeoutMs} (${t.timeoutMs / 1000}s) must be shorter than the ` +
219
+ `agent's functionTimeoutSeconds (${deadline}s${timeout === undefined ? ", the server default" : ""}); ` +
220
+ "lower the tool's timeoutMs or raise functionTimeoutSeconds");
221
+ }
222
+ }
223
+ }
224
+ /** The built-in tools in `tools`, in order. */
225
+ get builtinTools() {
226
+ var _a;
227
+ return ((_a = this.tools) !== null && _a !== void 0 ? _a : []).filter((t) => !isFunctionTool(t));
228
+ }
229
+ /** The function tools in `tools`, in order. */
230
+ get functionTools() {
231
+ var _a;
232
+ return ((_a = this.tools) !== null && _a !== void 0 ? _a : []).filter(isFunctionTool);
166
233
  }
167
234
  baseSettings() {
168
235
  const out = { version: 1 };
@@ -197,15 +264,25 @@ export class Agent {
197
264
  out["limits"] = limits;
198
265
  }
199
266
  if (this.tools !== undefined) {
200
- // Built-ins are on by default, so an exact list writes every unlisted one as off.
267
+ // Built-ins are on by default, so an exact list writes every unlisted one as off (function tools included:
268
+ // tools: [tool(...)] means that function and no built-in).
269
+ const builtins = this.builtinTools;
201
270
  const tools = {};
202
271
  for (const n of BUILTIN_NAMES) {
203
- const t = this.tools.find((x) => x.name === n);
272
+ const t = builtins.find((x) => x.name === n);
204
273
  tools[n] = t === undefined ? false
205
274
  : t.options !== undefined && Object.keys(t.options).length > 0 ? clone(t.options) : true;
206
275
  }
207
276
  out["builtin_tools"] = tools;
277
+ // Never an empty list: that would change every existing agent's fingerprint.
278
+ const functions = this.functionTools;
279
+ if (functions.length > 0)
280
+ out["functions"] = functions.map(functionToolSettings);
208
281
  }
282
+ if (this.functionTimeoutSeconds !== undefined)
283
+ out["function_timeout_seconds"] = this.functionTimeoutSeconds;
284
+ if (this.webhooks !== undefined && this.webhooks.length > 0)
285
+ out["webhooks"] = webhooksJson(this.webhooks);
209
286
  if (this.outputType !== undefined)
210
287
  out["output_schema"] = outputSchema(this.outputType);
211
288
  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[];
@@ -45,9 +45,12 @@ export class NotDeployedError extends AgentsError {
45
45
  export class NotSupportedError extends AgentsError {
46
46
  }
47
47
  export class RunError extends AgentsError {
48
- constructor(code, message) {
48
+ constructor(code, message, status, details) {
49
49
  super(`${code}: ${message}`);
50
50
  this.code = code;
51
+ if (status !== undefined)
52
+ this.status = status;
53
+ this.details = { ...(details !== null && details !== void 0 ? details : {}) };
51
54
  }
52
55
  }
53
56
  export class DriftError extends AgentsError {
@@ -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>[];
@@ -125,3 +125,36 @@ function map(chunk) {
125
125
  return { kind: "unknown", chunk };
126
126
  }
127
127
  }
128
+ /** A stored UIMessage (`GET /v1/conversations/{id}` `messages`) as the stream chunks that would have produced it,
129
+ * ending with `finish`, so a finished turn can be read like a live one. Text parts become one text block each, tool
130
+ * parts a call and (when they have one) its output, `data-*` parts pass through; reasoning is dropped. */
131
+ export function chunksFromUiMessage(message) {
132
+ const chunks = [];
133
+ const parts = isObject(message) && Array.isArray(message["parts"]) ? message["parts"] : [];
134
+ parts.forEach((part, n) => {
135
+ var _a, _b, _c, _d;
136
+ if (!isObject(part))
137
+ return;
138
+ const kind = typeof part["type"] === "string" ? part["type"] : "";
139
+ if (kind === "text") {
140
+ const id = `msg-text-${n}`;
141
+ chunks.push({ type: "text-start", id }, { type: "text-delta", id, delta: String((_a = part["text"]) !== null && _a !== void 0 ? _a : "") }, { type: "text-end", id });
142
+ }
143
+ else if (kind === "dynamic-tool" || kind.startsWith("tool-")) {
144
+ const name = (_b = part["toolName"]) !== null && _b !== void 0 ? _b : (kind.startsWith("tool-") ? kind.slice("tool-".length) : "");
145
+ const toolCallId = (_c = part["toolCallId"]) !== null && _c !== void 0 ? _c : "";
146
+ chunks.push({ type: "tool-input-available", toolCallId, toolName: name, input: part["input"] });
147
+ if (part["state"] === "output-available") {
148
+ chunks.push({ type: "tool-output-available", toolCallId, output: part["output"] });
149
+ }
150
+ else if (part["state"] === "output-error") {
151
+ chunks.push({ type: "tool-output-available", toolCallId, output: { error: (_d = part["errorText"]) !== null && _d !== void 0 ? _d : "" } });
152
+ }
153
+ }
154
+ else if (kind.startsWith("data-")) {
155
+ chunks.push({ type: kind, id: part["id"], data: part["data"] });
156
+ }
157
+ });
158
+ chunks.push({ type: "finish", finishReason: "stop" });
159
+ return chunks;
160
+ }