sarvam-agents-client 0.3.1 → 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.
package/README.md CHANGED
@@ -164,6 +164,88 @@ console.log((await run(agent, "How do I update my card?", { client: config })).f
164
164
 
165
165
  See [docs/compose.md](../docs/compose.md#typescript) for the full guide.
166
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
+
167
249
  ## Errors
168
250
 
169
251
  If an ID passed as a path parameter is empty, `.` or `..`, the SDK throws `InvalidPathParameterError` before
@@ -1,6 +1,7 @@
1
1
  import { BuiltinTool } from "./tools.js";
2
2
  import type { FunctionTool } from "./functionTool.js";
3
3
  import type { OutputType } from "./output.js";
4
+ import type { Webhook } from "./webhook.js";
4
5
  export interface ModelSettings {
5
6
  temperature?: number;
6
7
  topP?: number;
@@ -34,6 +35,8 @@ export interface AgentOptions<TOutput extends OutputType | undefined = undefined
34
35
  metadata?: Record<string, string>;
35
36
  /** The shape of the final answer: `{ type: "json_schema", schema }` or a zod schema. `finalOutput` follows it. */
36
37
  outputType?: TOutput;
38
+ /** Endpoints that receive the turn's events (agent.json `webhooks`); at most 5. */
39
+ webhooks?: Webhook[];
37
40
  }
38
41
  /** An agent with any output type: use it for helpers that accept every agent (plain `Agent` means a text agent). */
39
42
  export type AnyAgent = Agent<OutputType | undefined>;
@@ -49,6 +52,7 @@ export declare class Agent<TOutput extends OutputType | undefined = undefined> {
49
52
  readonly functionTimeoutSeconds?: number;
50
53
  readonly limits?: Limits;
51
54
  readonly metadata?: Record<string, string>;
55
+ readonly webhooks?: readonly Webhook[];
52
56
  /** Kept by reference and not frozen: a zod schema must stay usable. Non-enumerable, so deepFreeze skips it. */
53
57
  readonly outputType: TOutput;
54
58
  constructor(rawOpts: AgentOptions<TOutput>);
@@ -6,6 +6,7 @@ const fingerprint_js_1 = require("./fingerprint.js");
6
6
  const builtins_js_1 = require("./builtins.js");
7
7
  const functionTool_js_1 = require("./functionTool.js");
8
8
  const output_js_1 = require("./output.js");
9
+ const webhook_js_1 = require("./webhook.js");
9
10
  const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
10
11
  const REASONING = ["off", "none", "low", "medium", "high", "xhigh", "max"];
11
12
  const TOOL_CHOICES = ["auto", "none"];
@@ -112,8 +113,11 @@ class Agent {
112
113
  this.functionTimeoutSeconds = opts.functionTimeoutSeconds;
113
114
  this.limits = clone(opts.limits);
114
115
  this.metadata = clone(opts.metadata);
116
+ this.webhooks = clone(opts.webhooks);
115
117
  Object.defineProperty(this, "outputType", { value: opts.outputType, enumerable: false, writable: false });
116
118
  this.check();
119
+ if (this.webhooks !== undefined)
120
+ this.webhooks = (0, webhook_js_1.copyWebhooks)(this.webhooks);
117
121
  deepFreeze(this);
118
122
  }
119
123
  check() {
@@ -184,6 +188,8 @@ class Agent {
184
188
  if (names.indexOf("code_mode") !== -1 && names.indexOf("sandbox") === -1) {
185
189
  throw new errors_js_1.UserError("tools: codeMode needs sandbox; add sandbox() to tools");
186
190
  }
191
+ if (this.webhooks !== undefined)
192
+ (0, webhook_js_1.checkWebhooks)(this.webhooks);
187
193
  this.checkFunctions();
188
194
  }
189
195
  checkFunctions() {
@@ -278,6 +284,8 @@ class Agent {
278
284
  }
279
285
  if (this.functionTimeoutSeconds !== undefined)
280
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);
281
289
  if (this.outputType !== undefined)
282
290
  out["output_schema"] = (0, output_js_1.outputSchema)(this.outputType);
283
291
  return out;
@@ -4,6 +4,7 @@ export * from "./tools.js";
4
4
  export * from "./agent.js";
5
5
  export { tool } from "./functionTool.js";
6
6
  export type { FunctionCallDetails, FunctionTool, FunctionToolArgs, FunctionToolOptions } from "./functionTool.js";
7
+ export type { Webhook } from "./webhook.js";
7
8
  export type { Event, ClarifyQuestion, FunctionCallRequest, OutputCitation } from "./events.js";
8
9
  export { SettingsTransport } from "./settingsTransport.js";
9
10
  export type { PendingFunctionCalls, RemoteAgent, SettingsWarning, TurnStream, Transport } from "./transport.js";
@@ -17,10 +17,18 @@ export declare class SettingsTransport implements Transport {
17
17
  private readonly agents;
18
18
  private readonly conversations;
19
19
  private readonly responses;
20
+ private readonly customApis;
20
21
  constructor(config: Configuration);
21
22
  findAgents(sdkName: string): Promise<RemoteAgent[]>;
22
23
  readAgent(agentId: string): Promise<RemoteAgent>;
23
24
  createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
25
+ /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
26
+ * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
27
+ * checks credentials). */
28
+ private webhookCredentials;
29
+ /** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
30
+ private customApiIds;
31
+ private bind;
24
32
  updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
25
33
  deleteAgent(agentId: string): Promise<void>;
26
34
  startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
@@ -6,6 +6,7 @@ exports.idempotencyKey = idempotencyKey;
6
6
  const node_crypto_1 = require("node:crypto");
7
7
  const AgentsApi_js_1 = require("../apis/AgentsApi.js");
8
8
  const ConversationsApi_js_1 = require("../apis/ConversationsApi.js");
9
+ const CustomAPIsApi_js_1 = require("../apis/CustomAPIsApi.js");
9
10
  const ResponsesApi_js_1 = require("../apis/ResponsesApi.js");
10
11
  const runtime_js_1 = require("../runtime.js");
11
12
  const streaming_js_1 = require("../streaming.js");
@@ -169,6 +170,14 @@ class Finished {
169
170
  }
170
171
  close() { }
171
172
  }
173
+ /** `settings` for a new agent's first write: no `webhooks` (the server checks them against the agent's bound
174
+ * credentials, and a new agent has none yet) and no `sdk_hash` (it covers the webhooks, so an agent left in this
175
+ * state would otherwise read as deployed and never get them). */
176
+ function withoutWebhooks(settings) {
177
+ const { webhooks: _webhooks, ...out } = settings;
178
+ const { sdk_hash: _hash, ...metadata } = settings["metadata"];
179
+ return { ...out, metadata };
180
+ }
172
181
  function isNotFound(err) {
173
182
  return err instanceof runtime_js_1.ResponseError && err.response.status === 404;
174
183
  }
@@ -205,6 +214,7 @@ class SettingsTransport {
205
214
  this.agents = new AgentsApi_js_1.AgentsApi(config);
206
215
  this.conversations = new ConversationsApi_js_1.ConversationsApi(config);
207
216
  this.responses = new ResponsesApi_js_1.ResponsesApi(config);
217
+ this.customApis = new CustomAPIsApi_js_1.CustomAPIsApi(config);
208
218
  }
209
219
  // -- agents ---------------------------------------------------------------------------------------------
210
220
  async findAgents(sdkName) {
@@ -233,17 +243,24 @@ class SettingsTransport {
233
243
  return this.remote(resource, await this.instructions(agentId));
234
244
  }
235
245
  async createAgent(agent) {
236
- var _a, _b;
246
+ var _a, _b, _c;
237
247
  const settings = agent.toSettings();
248
+ const webhooks = ((_a = settings["webhooks"]) !== null && _a !== void 0 ? _a : []);
249
+ // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
250
+ // without them, bind the Custom APIs they name, then write the settings in full.
251
+ const { bind, unbound } = await this.webhookCredentials(webhooks);
238
252
  let resource;
239
253
  try {
240
254
  resource = await this.agents.createAgent({
241
- agentCreate: { name: agent.name, instructions: agent.instructions, settings },
255
+ agentCreate: {
256
+ name: agent.name, instructions: agent.instructions,
257
+ settings: webhooks.length > 0 ? withoutWebhooks(settings) : settings,
258
+ },
242
259
  });
243
260
  }
244
261
  catch (err) {
245
262
  // A 422 stored nothing, so there is no agent to delete.
246
- throw (_a = (await invalidSettings(err))) !== null && _a !== void 0 ? _a : err;
263
+ throw (_b = (await invalidSettings(err))) !== null && _b !== void 0 ? _b : err;
247
264
  }
248
265
  let envelope;
249
266
  let warnings;
@@ -258,7 +275,23 @@ class SettingsTransport {
258
275
  throw new errors_js_1.NotSupportedByServerError(["settings"]);
259
276
  throw err;
260
277
  }
278
+ if (webhooks.length > 0) {
279
+ for (const { path, name, customApiId } of bind)
280
+ await this.bind(resource.id, path, name, customApiId);
281
+ try {
282
+ envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
283
+ }
284
+ catch (err) {
285
+ const invalid = await invalidSettings(err);
286
+ if (invalid === null)
287
+ throw err;
288
+ throw new errors_js_1.UserError([invalid.message, ...unbound].join("; "), invalid.issues);
289
+ }
290
+ }
261
291
  warnings = checkWarnings(envelope, settings);
292
+ // Accepted unchecked (webhooks switched off): refused once they are on.
293
+ for (const sentence of unbound)
294
+ console.warn(`agent ${resource.id}: ${sentence}`);
262
295
  checkMetadata(envelope, agent);
263
296
  await this.agents.deployAgent({ agentId: resource.id });
264
297
  }
@@ -276,10 +309,67 @@ class SettingsTransport {
276
309
  agentId: resource.id,
277
310
  name: agent.name,
278
311
  instructions: agent.instructions,
279
- settings: { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) },
312
+ settings: { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) },
280
313
  warnings,
281
314
  };
282
315
  }
316
+ /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
317
+ * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
318
+ * checks credentials). */
319
+ async webhookCredentials(webhooks) {
320
+ const bind = [];
321
+ const unbound = [];
322
+ const seen = new Set();
323
+ for (const [i, hook] of webhooks.entries()) {
324
+ const name = hook.secret_credential;
325
+ if (seen.has(name))
326
+ continue;
327
+ seen.add(name);
328
+ const path = `webhooks.${i}.secret_credential`;
329
+ const ids = await this.customApiIds(name);
330
+ if (ids.length === 1) {
331
+ bind.push({ path, name, customApiId: ids[0] });
332
+ }
333
+ else if (ids.length === 0) {
334
+ unbound.push(`${path}: you have no Custom API named '${name}' to bind to the new agent; create it, then ` +
335
+ "deploy again");
336
+ }
337
+ else {
338
+ unbound.push(`${path}: ${ids.length} of your Custom APIs are named '${name}', so none was bound to the new ` +
339
+ "agent; rename or delete all but one, then deploy again");
340
+ }
341
+ }
342
+ return { bind, unbound };
343
+ }
344
+ /** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
345
+ async customApiIds(name) {
346
+ const ids = [];
347
+ let offset = 0;
348
+ for (;;) {
349
+ const result = await this.customApis.listCustomApis({ q: name, limit: PAGE, offset });
350
+ const items = result.data;
351
+ for (const item of items)
352
+ if (item.name === name)
353
+ ids.push(item.id);
354
+ offset += items.length;
355
+ if (items.length === 0 || !result.hasMore)
356
+ return ids;
357
+ }
358
+ }
359
+ async bind(agentId, path, name, customApiId) {
360
+ var _a;
361
+ try {
362
+ await this.customApis.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
363
+ }
364
+ catch (err) {
365
+ const status = err instanceof runtime_js_1.ResponseError ? err.response.status : 0;
366
+ if (!(err instanceof runtime_js_1.ResponseError) || status < 400 || status >= 500)
367
+ throw err;
368
+ const message = (_a = (await chatError(err))) === null || _a === void 0 ? void 0 : _a["message"];
369
+ throw new errors_js_1.UserError(`${path}: could not bind the Custom API '${name}' to the new agent: ` +
370
+ (typeof message === "string" && message ? message : `HTTP ${status}`));
371
+ }
372
+ }
283
373
  async updateAgent(agentId, agent) {
284
374
  var _a, _b;
285
375
  const settings = agent.toSettings();
@@ -0,0 +1,19 @@
1
+ import type { WebhookEventType } from "../webhooks.js";
2
+ /** Where the agent reports a finished, failed or paused turn (agent.json `webhooks[]`). */
3
+ export interface Webhook {
4
+ /** An `https://` URL on port 443 with a DNS host; a query string is allowed. */
5
+ url: string;
6
+ /** 1 to 4 distinct events. `approval.requested` is reserved: accepted, not sent yet. */
7
+ events: WebhookEventType[];
8
+ /** The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). */
9
+ secretCredential: string;
10
+ }
11
+ export declare const WEBHOOKS_MAX = 5;
12
+ /** Why `url` is not an allowed webhook URL, or null. Every URL the server refuses is refused, with the server's
13
+ * sentence for every URL Python's `urlsplit` parses; for a netloc its NFKC check refuses, the sentence may differ. */
14
+ export declare function urlProblem(url: string): string | null;
15
+ /** The server's pure `webhooks` rules (types first); throws `UserError` naming the agent.json path. */
16
+ export declare function checkWebhooks(webhooks: unknown): void;
17
+ /** Only the three fields, in agent.json's names (a copy). */
18
+ export declare function copyWebhooks(webhooks: readonly Webhook[]): Webhook[];
19
+ export declare function webhooksJson(webhooks: readonly Webhook[]): Record<string, unknown>[];
@@ -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
+ }
@@ -1,6 +1,7 @@
1
1
  import { BuiltinTool } from "./tools.js";
2
2
  import type { FunctionTool } from "./functionTool.js";
3
3
  import type { OutputType } from "./output.js";
4
+ import type { Webhook } from "./webhook.js";
4
5
  export interface ModelSettings {
5
6
  temperature?: number;
6
7
  topP?: number;
@@ -34,6 +35,8 @@ export interface AgentOptions<TOutput extends OutputType | undefined = undefined
34
35
  metadata?: Record<string, string>;
35
36
  /** The shape of the final answer: `{ type: "json_schema", schema }` or a zod schema. `finalOutput` follows it. */
36
37
  outputType?: TOutput;
38
+ /** Endpoints that receive the turn's events (agent.json `webhooks`); at most 5. */
39
+ webhooks?: Webhook[];
37
40
  }
38
41
  /** An agent with any output type: use it for helpers that accept every agent (plain `Agent` means a text agent). */
39
42
  export type AnyAgent = Agent<OutputType | undefined>;
@@ -49,6 +52,7 @@ export declare class Agent<TOutput extends OutputType | undefined = undefined> {
49
52
  readonly functionTimeoutSeconds?: number;
50
53
  readonly limits?: Limits;
51
54
  readonly metadata?: Record<string, string>;
55
+ readonly webhooks?: readonly Webhook[];
52
56
  /** Kept by reference and not frozen: a zod schema must stay usable. Non-enumerable, so deepFreeze skips it. */
53
57
  readonly outputType: TOutput;
54
58
  constructor(rawOpts: AgentOptions<TOutput>);
@@ -3,6 +3,7 @@ import { settingsFingerprint } from "./fingerprint.js";
3
3
  import { BUILTIN_NAMES, checkWebSearchOptions } from "./builtins.js";
4
4
  import { DEFAULT_FUNCTION_TIMEOUT_SECONDS, FUNCTION_TIMEOUT_RANGE, FUNCTIONS_MAX, FUNCTIONS_TOTAL_MAX_BYTES, compactBytes, functionToolSettings, isBuiltFunctionTool, isFunctionTool, tool, } from "./functionTool.js";
5
5
  import { checkOutputType, outputSchema } from "./output.js";
6
+ import { checkWebhooks, copyWebhooks, webhooksJson } from "./webhook.js";
6
7
  const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
7
8
  const REASONING = ["off", "none", "low", "medium", "high", "xhigh", "max"];
8
9
  const TOOL_CHOICES = ["auto", "none"];
@@ -109,8 +110,11 @@ export class Agent {
109
110
  this.functionTimeoutSeconds = opts.functionTimeoutSeconds;
110
111
  this.limits = clone(opts.limits);
111
112
  this.metadata = clone(opts.metadata);
113
+ this.webhooks = clone(opts.webhooks);
112
114
  Object.defineProperty(this, "outputType", { value: opts.outputType, enumerable: false, writable: false });
113
115
  this.check();
116
+ if (this.webhooks !== undefined)
117
+ this.webhooks = copyWebhooks(this.webhooks);
114
118
  deepFreeze(this);
115
119
  }
116
120
  check() {
@@ -181,6 +185,8 @@ export class Agent {
181
185
  if (names.indexOf("code_mode") !== -1 && names.indexOf("sandbox") === -1) {
182
186
  throw new UserError("tools: codeMode needs sandbox; add sandbox() to tools");
183
187
  }
188
+ if (this.webhooks !== undefined)
189
+ checkWebhooks(this.webhooks);
184
190
  this.checkFunctions();
185
191
  }
186
192
  checkFunctions() {
@@ -275,6 +281,8 @@ export class Agent {
275
281
  }
276
282
  if (this.functionTimeoutSeconds !== undefined)
277
283
  out["function_timeout_seconds"] = this.functionTimeoutSeconds;
284
+ if (this.webhooks !== undefined && this.webhooks.length > 0)
285
+ out["webhooks"] = webhooksJson(this.webhooks);
278
286
  if (this.outputType !== undefined)
279
287
  out["output_schema"] = outputSchema(this.outputType);
280
288
  return out;
@@ -4,6 +4,7 @@ export * from "./tools.js";
4
4
  export * from "./agent.js";
5
5
  export { tool } from "./functionTool.js";
6
6
  export type { FunctionCallDetails, FunctionTool, FunctionToolArgs, FunctionToolOptions } from "./functionTool.js";
7
+ export type { Webhook } from "./webhook.js";
7
8
  export type { Event, ClarifyQuestion, FunctionCallRequest, OutputCitation } from "./events.js";
8
9
  export { SettingsTransport } from "./settingsTransport.js";
9
10
  export type { PendingFunctionCalls, RemoteAgent, SettingsWarning, TurnStream, Transport } from "./transport.js";
@@ -17,10 +17,18 @@ export declare class SettingsTransport implements Transport {
17
17
  private readonly agents;
18
18
  private readonly conversations;
19
19
  private readonly responses;
20
+ private readonly customApis;
20
21
  constructor(config: Configuration);
21
22
  findAgents(sdkName: string): Promise<RemoteAgent[]>;
22
23
  readAgent(agentId: string): Promise<RemoteAgent>;
23
24
  createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
25
+ /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
26
+ * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
27
+ * checks credentials). */
28
+ private webhookCredentials;
29
+ /** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
30
+ private customApiIds;
31
+ private bind;
24
32
  updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
25
33
  deleteAgent(agentId: string): Promise<void>;
26
34
  startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;