sarvam-agents-client 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -169,41 +169,54 @@ See [docs/compose.md](../docs/compose.md#typescript) for the full guide.
169
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
170
  outbound webhooks switched on; until then a deploy keeps the setting and logs the warning `webhooks_disabled`.
171
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):
172
+ **1. Name the endpoint on the agent** (`agent.json` `webhooks`) and deploy:
175
173
 
176
174
  ```ts
177
- import { CustomAPIsApi } from "sarvam-agents-client";
178
- import { generateSecret } from "sarvam-agents-client/webhooks";
175
+ import { Agent, deploy } from "sarvam-agents-client/compose";
179
176
 
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 } } });
177
+ const agent = new Agent({ name: "support-bot", instructions: "...", webhooks: [
178
+ { url: "https://hooks.acme.com/panja", events: ["turn.completed", "turn.failed", "turn.requires_action"] },
179
+ ] });
180
+ const deployment = await deploy(agent, { client: config });
184
181
  ```
185
182
 
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 } })`.
183
+ Leave `secretCredential` out: the deploy fills in the credential that `client.webhooks` manages for that agent and
184
+ host. The first deploy of a webhook with no secret yet stores a random placeholder secret, that nobody holds, so the
185
+ server accepts the webhook, and lists the webhook's URL in `deployment.webhooksMissingSecret`. While the placeholder
186
+ is there, `secretStatus` reads `"missing"`.
192
187
 
193
- **2. Name the endpoint on the agent** (`agent.json` `webhooks`, with `secretCredential` written as
194
- `secret_credential`):
188
+ Call `client.webhooks.setSecret` right after the first deploy, before pointing a provider at the agent. Until then
189
+ deliveries fail verification, and a receiver that answers 4xx makes Panja drop them.
190
+
191
+ **2. Set the signing secret** with `client.webhooks`:
195
192
 
196
193
  ```ts
197
- import { Agent } from "sarvam-agents-client/compose";
194
+ import { Client } from "sarvam-agents-client";
198
195
 
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
- ] });
196
+ const client = new Client(config); // config: the Configuration from the Quickstart
197
+ const url = "https://hooks.acme.com/panja";
198
+
199
+ const secret = await client.webhooks.setSecret(deployment.agentId, url); // generates a whsec_ secret and returns it
200
+ // or: await client.webhooks.setSecret(agentId, url, "whsec_...") to store one you made
201
+ await client.webhooks.secretStatus(agentId, url); // "set" or "missing" ("missing" while the deploy placeholder is there)
202
+ const newSecret = await client.webhooks.rotateSecret(agentId, url);
203
+ await client.webhooks.deleteSecret(agentId, url);
203
204
  ```
204
205
 
206
+ Keep the returned secret where your receiver runs: Panja never shows it again. A secret that is not `whsec_` plus
207
+ base64 of 24 to 64 bytes throws `SecretFormatError` before anything is sent. It works as in Python (see the
208
+ [Python README](../python/README.md#webhooks)): today the secret is a Custom API the SDK creates and binds, named
209
+ `webhook-secret:<agentId>:<host>`, with "enabled for chats" always **off**; `deleteSecret` only removes that one; a
210
+ later release moves secrets to a dedicated server store with no change to `client.webhooks`. Nothing logs a secret or
211
+ puts one in an error message.
212
+
213
+ `secretCredential: "acme_webhook"` still works, but is `@deprecated`: it names a Custom API you created and bound
214
+ yourself. To migrate, use `client.webhooks.setSecret` instead of creating a Custom API: call
215
+ `setSecret(agentId, url, currentSecret)`, drop `secretCredential` and deploy, then unbind and delete the old Custom
216
+ API (`unbindCustomApi`, `deleteCustomApi`).
217
+
205
218
  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
219
+ which name the `agent.json` path (`webhooks.0.url: ...`). Checks that need the server fail the deploy
207
220
  (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
221
  `NotSupportedByServerError` with `features` `["webhooks"]`.
209
222
 
@@ -0,0 +1,16 @@
1
+ import type { Configuration } from "./runtime.js";
2
+ import { WebhookSecrets } from "./compose/webhookSecrets.js";
3
+ /**
4
+ * Groups the hand-written helpers over one `Configuration`.
5
+ *
6
+ * ```ts
7
+ * const client = new Client(config);
8
+ * const secret = await client.webhooks.setSecret(agentId, "https://hooks.acme.com/panja");
9
+ * ```
10
+ */
11
+ export declare class Client {
12
+ readonly config: Configuration;
13
+ /** Set, rotate, check and delete an agent webhook's signing secret. */
14
+ readonly webhooks: WebhookSecrets;
15
+ constructor(config: Configuration);
16
+ }
package/dist/client.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Client = void 0;
4
+ const webhookSecrets_js_1 = require("./compose/webhookSecrets.js");
5
+ /**
6
+ * Groups the hand-written helpers over one `Configuration`.
7
+ *
8
+ * ```ts
9
+ * const client = new Client(config);
10
+ * const secret = await client.webhooks.setSecret(agentId, "https://hooks.acme.com/panja");
11
+ * ```
12
+ */
13
+ class Client {
14
+ constructor(config) {
15
+ this.config = config;
16
+ if (config === undefined || config === null)
17
+ throw new TypeError("new Client(config): pass a Configuration");
18
+ this.webhooks = new webhookSecrets_js_1.WebhookSecrets(config);
19
+ }
20
+ }
21
+ exports.Client = Client;
@@ -9,6 +9,10 @@ export interface Deployment {
9
9
  /** The live version, or while the agent is paused, the paused version (what `resumeAgent` brings back); undefined
10
10
  * from a server without versions, or when no version was ever live. */
11
11
  version?: number;
12
+ /** URLs of the webhooks that still have no signing secret: this deploy stored a placeholder secret nobody holds so
13
+ * the server accepts them. Call `client.webhooks.setSecret(agentId, url)` for each before pointing a provider at
14
+ * the agent; until then deliveries fail verification. Left out when there are none. */
15
+ webhooksMissingSecret?: string[];
12
16
  }
13
17
  /** Set (or clear, with null) the client used when deploy/remove/run get no client. */
14
18
  export declare function setDefaultClient(config: Configuration | null): void;
@@ -63,10 +63,17 @@ async function update(transport, remote, agent, strict) {
63
63
  return settle(transport, remote, agent);
64
64
  }
65
65
  const updated = await transport.updateAgent(remote.agentId, agent);
66
- return deployment(remote.agentId, "updated", liveVersion(updated));
66
+ return deployment(remote.agentId, "updated", liveVersion(updated), missingSecrets(updated));
67
67
  }
68
- function deployment(agentId, action, version) {
69
- return version === undefined ? { agentId, action } : { agentId, action, version };
68
+ function deployment(agentId, action, version, webhooksMissingSecret = []) {
69
+ const out = version === undefined ? { agentId, action } : { agentId, action, version };
70
+ if (webhooksMissingSecret.length > 0)
71
+ out.webhooksMissingSecret = webhooksMissingSecret;
72
+ return out;
73
+ }
74
+ function missingSecrets(remote) {
75
+ const missing = remote === null || remote === void 0 ? void 0 : remote.webhooksMissingSecret;
76
+ return Array.isArray(missing) ? [...missing] : [];
70
77
  }
71
78
  // Optional chaining: a custom transport written for 0.3 may resolve anything from updateAgent/createAgent.
72
79
  function liveVersion(remote) {
@@ -99,13 +106,14 @@ async function deployWith(agent, transport, strict, adopt) {
99
106
  if (others.length) {
100
107
  throw new errors_js_1.UserError(`cannot adopt ${adopt}: agent "${agent.name}" is already deployed as ${others.join(", ")}`);
101
108
  }
102
- return deployment(adopt, "updated", liveVersion(await transport.updateAgent(adopt, agent)));
109
+ const adopted = await transport.updateAgent(adopt, agent);
110
+ return deployment(adopt, "updated", liveVersion(adopted), missingSecrets(adopted));
103
111
  }
104
112
  if (found.length > 1)
105
113
  throw new errors_js_1.DuplicateAgentsError(found.map((r) => r.agentId));
106
114
  if (found.length === 0) {
107
115
  const created = await transport.createAgent(agent);
108
- return deployment(created.agentId, "created", liveVersion(created));
116
+ return deployment(created.agentId, "created", liveVersion(created), missingSecrets(created));
109
117
  }
110
118
  return update(transport, found[0], agent, strict);
111
119
  }
@@ -18,10 +18,15 @@ export declare class SettingsTransport implements Transport {
18
18
  private readonly conversations;
19
19
  private readonly responses;
20
20
  private readonly customApis;
21
+ private readonly secrets;
21
22
  constructor(config: Configuration);
22
23
  findAgents(sdkName: string): Promise<RemoteAgent[]>;
23
24
  readAgent(agentId: string): Promise<RemoteAgent>;
24
25
  createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
26
+ /** `settings` with each webhook that names no `secret_credential` given the one `client.webhooks` keeps for the
27
+ * agent and host (stored, with a random secret nobody holds, when there is none yet), and the URLs of those
28
+ * webhooks still without a secret set by `client.webhooks`. */
29
+ private withSecretCredentials;
25
30
  /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
26
31
  * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
27
32
  * checks credentials). */
@@ -13,6 +13,8 @@ const streaming_js_1 = require("../streaming.js");
13
13
  const errors_js_1 = require("./errors.js");
14
14
  const events_js_1 = require("./events.js");
15
15
  const transport_js_1 = require("./transport.js");
16
+ const webhook_js_1 = require("./webhook.js");
17
+ const webhookSecrets_js_1 = require("./webhookSecrets.js");
16
18
  const PAGE = 100;
17
19
  /** A post the server is still delivering (409 in_progress) is retried this many times, Retry-After apart. */
18
20
  const IN_PROGRESS_RETRIES = 5;
@@ -197,6 +199,30 @@ function withoutWebhooks(settings) {
197
199
  const { sdk_hash: _hash, ...metadata } = settings["metadata"];
198
200
  return { ...out, metadata };
199
201
  }
202
+ function hooksOf(settings) {
203
+ const hooks = settings["webhooks"];
204
+ return Array.isArray(hooks) ? hooks.filter((h) => typeof h === "object" && h !== null && !Array.isArray(h)) : [];
205
+ }
206
+ function sdkNamed(agentId, hook) {
207
+ const url = hook["url"];
208
+ return typeof url === "string" && (0, webhook_js_1.urlProblem)(url) === null &&
209
+ hook["secret_credential"] === (0, webhook_js_1.secretCredentialName)(agentId, url);
210
+ }
211
+ /** `settings` as a definition writes them: a webhook whose `secret_credential` is the one `deploy` filled in loses it
212
+ * again, so the stored `sdk_hash` (computed without it) still matches. */
213
+ function asDefined(agentId, settings) {
214
+ if (!hooksOf(settings).some((h) => sdkNamed(agentId, h)))
215
+ return settings;
216
+ return {
217
+ ...settings,
218
+ webhooks: settings["webhooks"].map((h) => {
219
+ if (typeof h !== "object" || h === null || !sdkNamed(agentId, h))
220
+ return h;
221
+ const { secret_credential: _name, ...rest } = h;
222
+ return rest;
223
+ }),
224
+ };
225
+ }
200
226
  function isNotFound(err) {
201
227
  return err instanceof runtime_js_1.ResponseError && err.response.status === 404;
202
228
  }
@@ -234,6 +260,7 @@ class SettingsTransport {
234
260
  this.conversations = new ConversationsApi_js_1.ConversationsApi(config);
235
261
  this.responses = new ResponsesApi_js_1.ResponsesApi(config);
236
262
  this.customApis = new CustomAPIsApi_js_1.CustomAPIsApi(config);
263
+ this.secrets = (0, webhookSecrets_js_1.secretBackend)({ customApis: this.customApis });
237
264
  }
238
265
  // -- agents ---------------------------------------------------------------------------------------------
239
266
  async findAgents(sdkName) {
@@ -263,7 +290,8 @@ class SettingsTransport {
263
290
  }
264
291
  async createAgent(agent) {
265
292
  var _a, _b, _c;
266
- const settings = agent.toSettings();
293
+ let settings = agent.toSettings();
294
+ let missing = [];
267
295
  const webhooks = ((_a = settings["webhooks"]) !== null && _a !== void 0 ? _a : []);
268
296
  // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
269
297
  // without them, bind the Custom APIs they name, then write the settings in full.
@@ -298,6 +326,7 @@ class SettingsTransport {
298
326
  if (webhooks.length > 0) {
299
327
  for (const { path, name, customApiId } of bind)
300
328
  await this.bind(resource.id, path, name, customApiId);
329
+ ({ settings, missing } = await this.withSecretCredentials(resource.id, settings));
301
330
  try {
302
331
  envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
303
332
  }
@@ -329,10 +358,33 @@ class SettingsTransport {
329
358
  agentId: resource.id,
330
359
  name: agent.name,
331
360
  instructions: agent.instructions,
332
- settings: { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) },
361
+ settings: asDefined(resource.id, { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) }),
333
362
  warnings,
363
+ ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
334
364
  }, live, versionStateOf(resource));
335
365
  }
366
+ /** `settings` with each webhook that names no `secret_credential` given the one `client.webhooks` keeps for the
367
+ * agent and host (stored, with a random secret nobody holds, when there is none yet), and the URLs of those
368
+ * webhooks still without a secret set by `client.webhooks`. */
369
+ async withSecretCredentials(agentId, settings) {
370
+ const hooks = hooksOf(settings);
371
+ if (hooks.every((h) => "secret_credential" in h))
372
+ return { settings, missing: [] };
373
+ const filled = [];
374
+ const missing = [];
375
+ for (const h of settings["webhooks"]) {
376
+ if (typeof h !== "object" || h === null || "secret_credential" in h) {
377
+ filled.push(h);
378
+ continue;
379
+ }
380
+ const url = h["url"];
381
+ const { name, status } = await this.secrets.ensure(agentId, url);
382
+ filled.push({ ...h, secret_credential: name });
383
+ if (status === "missing")
384
+ missing.push(url);
385
+ }
386
+ return { settings: { ...settings, webhooks: filled }, missing };
387
+ }
336
388
  /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
337
389
  * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
338
390
  * checks credentials). */
@@ -342,8 +394,8 @@ class SettingsTransport {
342
394
  const seen = new Set();
343
395
  for (const [i, hook] of webhooks.entries()) {
344
396
  const name = hook.secret_credential;
345
- if (seen.has(name))
346
- continue;
397
+ if (name === undefined || seen.has(name))
398
+ continue; // left out: deploy fills in the one client.webhooks keeps
347
399
  seen.add(name);
348
400
  const path = `webhooks.${i}.secret_credential`;
349
401
  const ids = await this.customApiIds(name);
@@ -392,7 +444,7 @@ class SettingsTransport {
392
444
  }
393
445
  async updateAgent(agentId, agent) {
394
446
  var _a, _b;
395
- const settings = agent.toSettings();
447
+ let settings = agent.toSettings();
396
448
  // findAgents searches by display name, so an adopted (or dashboard-renamed) agent must carry sdk_name.
397
449
  const current = await this.agents.getAgent({ agentId });
398
450
  if (current.name !== agent.name) {
@@ -415,6 +467,15 @@ class SettingsTransport {
415
467
  if (instructionsChanged) {
416
468
  await this.agents.putInstructions({ agentId, instructionsBody: { data: agent.instructions } });
417
469
  }
470
+ let missing;
471
+ try {
472
+ ({ settings, missing } = await this.withSecretCredentials(agentId, settings));
473
+ }
474
+ catch (err) {
475
+ if (instructionsChanged)
476
+ await this.restore(agentId, null, previousInstructions);
477
+ throw err;
478
+ }
418
479
  let envelope;
419
480
  try {
420
481
  envelope = await this.agents.putAgentSettings({ agentId, body: settings });
@@ -446,8 +507,9 @@ class SettingsTransport {
446
507
  agentId,
447
508
  name: agent.name,
448
509
  instructions: agent.instructions,
449
- settings: { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) },
510
+ settings: asDefined(agentId, { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) }),
450
511
  warnings,
512
+ ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
451
513
  }, live, versionStateOf(current));
452
514
  }
453
515
  /** Make what was just written what end users get. A server without versions (no `versionState`) gets the bodiless
@@ -664,7 +726,8 @@ class SettingsTransport {
664
726
  remote(resource, instructions) {
665
727
  var _a;
666
728
  const remote = {
667
- agentId: resource.id, name: resource.name, instructions, settings: { ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }, warnings: [],
729
+ agentId: resource.id, name: resource.name, instructions, warnings: [],
730
+ settings: asDefined(resource.id, { ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }),
668
731
  };
669
732
  // Left out, not set to undefined, when the server has no versions: the shape a 0.3 transport returned.
670
733
  if (resource.liveVersion !== undefined && resource.liveVersion !== null)
@@ -20,6 +20,9 @@ export interface RemoteAgent {
20
20
  /** `"live"`, `"paused"` or `"not_live"` (`AgentResource.versionState`); undefined when the server has no versions,
21
21
  * in which case deploy() never calls `publish`. */
22
22
  versionState?: string;
23
+ /** URLs of the webhooks this write left without a secret set by `client.webhooks` (a placeholder secret nobody
24
+ * holds stands in until `client.webhooks.setSecret`); left out when there are none. */
25
+ webhooksMissingSecret?: string[];
23
26
  }
24
27
  /** The note on every version deploy() saves, so the dashboard's version list shows which came from code. */
25
28
  export declare const VERSION_NOTE = "Deployed from the SDK";
@@ -5,8 +5,13 @@ export interface Webhook {
5
5
  url: string;
6
6
  /** 1 to 4 distinct events. `approval.requested` is reserved: accepted, not sent yet. */
7
7
  events: WebhookEventType[];
8
- /** The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). */
9
- secretCredential: string;
8
+ /**
9
+ * The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). Leave it out: `deploy`
10
+ * fills in the credential `client.webhooks` keeps, and `client.webhooks.setSecret(agentId, url)` sets the secret.
11
+ *
12
+ * @deprecated Use `client.webhooks.setSecret` instead of creating a Custom API and naming it here.
13
+ */
14
+ secretCredential?: string;
10
15
  }
11
16
  export declare const WEBHOOKS_MAX = 5;
12
17
  /** Why `url` is not an allowed webhook URL, or null. Every URL the server refuses is refused, with the server's
@@ -14,6 +19,16 @@ export declare const WEBHOOKS_MAX = 5;
14
19
  export declare function urlProblem(url: string): string | null;
15
20
  /** The server's pure `webhooks` rules (types first); throws `UserError` naming the agent.json path. */
16
21
  export declare function checkWebhooks(webhooks: unknown): void;
17
- /** Only the three fields, in agent.json's names (a copy). */
22
+ /** Only the three fields (a copy). `secretCredential` is left out when absent, or when it is the name `deploy`
23
+ * writes anyway (one spelling keeps one fingerprint). */
18
24
  export declare function copyWebhooks(webhooks: readonly Webhook[]): Webhook[];
19
25
  export declare function webhooksJson(webhooks: readonly Webhook[]): Record<string, unknown>[];
26
+ /** The host of an allowed webhook URL, lowercased, without a trailing dot or a port. */
27
+ export declare function webhookHost(url: string): string;
28
+ /** Every Custom API the SDK creates for a webhook secret is named `webhook-secret:<agentId>:<host>`. */
29
+ export declare const SECRET_NAME_PREFIX = "webhook-secret:";
30
+ /** The credential name the SDK uses for `url`'s signing secret on agent `agentId` (what `deploy` writes as
31
+ * `secret_credential` when a webhook leaves it out). A host too long to fit 256 characters is hashed. */
32
+ export declare function secretCredentialName(agentId: string, url: string): string;
33
+ /** Whether `name` is the SDK's credential name for `url`'s host, for any agent. */
34
+ export declare function isSdkCredentialName(name: unknown, url: string): boolean;
@@ -1,19 +1,25 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WEBHOOKS_MAX = void 0;
3
+ exports.SECRET_NAME_PREFIX = exports.WEBHOOKS_MAX = void 0;
4
4
  exports.urlProblem = urlProblem;
5
5
  exports.checkWebhooks = checkWebhooks;
6
6
  exports.copyWebhooks = copyWebhooks;
7
7
  exports.webhooksJson = webhooksJson;
8
+ exports.webhookHost = webhookHost;
9
+ exports.secretCredentialName = secretCredentialName;
10
+ exports.isSdkCredentialName = isSdkCredentialName;
8
11
  /**
9
12
  * `webhooks` entries of `agent.json`, checked locally with the server's cheap rules (as the Python SDK does).
10
13
  *
11
14
  * The server (`claw_common/agent_settings/webhooks.py`) also checks that the host resolves to a public address and
12
15
  * 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
+ * I/O and stay on the server, which refuses the save with a 422 that `deploy` throws as `UserError`.
17
+ *
18
+ * `secretCredential` is optional and deprecated: left out, `deploy` writes the name `client.webhooks` uses for the
19
+ * agent and host (`secretCredentialName`). Given, the deploy that creates the agent binds the caller's Custom API of
20
+ * that name first (`SettingsTransport.createAgent`).
16
21
  */
22
+ const node_crypto_1 = require("node:crypto");
17
23
  const errors_js_1 = require("./errors.js");
18
24
  const webhooks_js_1 = require("../webhooks.js");
19
25
  exports.WEBHOOKS_MAX = 5;
@@ -138,7 +144,7 @@ function checkWebhooks(webhooks) {
138
144
  webhooks.forEach((hook, i) => {
139
145
  const where = `webhooks.${i}.`;
140
146
  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`);
147
+ throw new errors_js_1.UserError(`webhooks.${i}: must be an object with url and events`);
142
148
  }
143
149
  const { url, events, secretCredential } = hook;
144
150
  if (typeof url !== "string")
@@ -146,8 +152,9 @@ function checkWebhooks(webhooks) {
146
152
  if (!Array.isArray(events) || !events.every((e) => typeof e === "string")) {
147
153
  throw new errors_js_1.UserError(where + "events: must be a list of event names");
148
154
  }
149
- if (typeof secretCredential !== "string")
155
+ if (secretCredential !== undefined && typeof secretCredential !== "string") {
150
156
  throw new errors_js_1.UserError(where + "secretCredential: must be a string");
157
+ }
151
158
  // Python's Webhook is extra="forbid": a key dropped silently (a misplaced secret) would never verify.
152
159
  const extra = Object.keys(hook).find((k) => k !== "url" && k !== "events" && k !== "secretCredential");
153
160
  if (extra !== undefined)
@@ -163,7 +170,7 @@ function checkWebhooks(webhooks) {
163
170
  }
164
171
  if (new Set(events).size !== events.length)
165
172
  throw new errors_js_1.UserError(where + "events: events must not repeat an event.");
166
- const n = codePoints(secretCredential);
173
+ const n = typeof secretCredential === "string" ? codePoints(secretCredential) : 1;
167
174
  if (n < 1 || n > SECRET_CREDENTIAL_MAX) {
168
175
  throw new errors_js_1.UserError(where + "secret_credential: secret_credential must be the name of a vault credential " +
169
176
  `(1 to ${SECRET_CREDENTIAL_MAX} characters).`);
@@ -175,10 +182,52 @@ function checkWebhooks(webhooks) {
175
182
  seen.add(key);
176
183
  });
177
184
  }
178
- /** Only the three fields, in agent.json's names (a copy). */
185
+ /** Only the three fields (a copy). `secretCredential` is left out when absent, or when it is the name `deploy`
186
+ * writes anyway (one spelling keeps one fingerprint). */
179
187
  function copyWebhooks(webhooks) {
180
- return webhooks.map((h) => ({ url: h.url, events: [...h.events], secretCredential: h.secretCredential }));
188
+ return webhooks.map((h) => {
189
+ const copy = { url: h.url, events: [...h.events] };
190
+ const name = h.secretCredential;
191
+ if (name !== undefined && !isSdkCredentialName(name, h.url))
192
+ copy.secretCredential = name;
193
+ return copy;
194
+ });
181
195
  }
182
196
  function webhooksJson(webhooks) {
183
- return webhooks.map((h) => ({ url: h.url, events: [...h.events], secret_credential: h.secretCredential }));
197
+ return webhooks.map((h) => {
198
+ const out = { url: h.url, events: [...h.events] };
199
+ if (h.secretCredential !== undefined)
200
+ out["secret_credential"] = h.secretCredential;
201
+ return out;
202
+ });
203
+ }
204
+ /** The host of an allowed webhook URL, lowercased, without a trailing dot or a port. */
205
+ function webhookHost(url) {
206
+ return stripTrailingDots(hostPort(split(url)[1])[0]);
207
+ }
208
+ /** Every Custom API the SDK creates for a webhook secret is named `webhook-secret:<agentId>:<host>`. */
209
+ exports.SECRET_NAME_PREFIX = "webhook-secret:";
210
+ const SECRET_NAME_MAX = 256;
211
+ function hashedHost(host) {
212
+ return "sha256-" + (0, node_crypto_1.createHash)("sha256").update(host, "utf8").digest("hex").slice(0, 32);
213
+ }
214
+ /** The credential name the SDK uses for `url`'s signing secret on agent `agentId` (what `deploy` writes as
215
+ * `secret_credential` when a webhook leaves it out). A host too long to fit 256 characters is hashed. */
216
+ function secretCredentialName(agentId, url) {
217
+ const host = webhookHost(url);
218
+ const name = `${exports.SECRET_NAME_PREFIX}${agentId}:${host}`;
219
+ return codePoints(name) <= SECRET_NAME_MAX ? name : `${exports.SECRET_NAME_PREFIX}${agentId}:${hashedHost(host)}`;
220
+ }
221
+ /** Whether `name` is the SDK's credential name for `url`'s host, for any agent. */
222
+ function isSdkCredentialName(name, url) {
223
+ if (typeof name !== "string" || !name.startsWith(exports.SECRET_NAME_PREFIX) || urlProblem(url) !== null)
224
+ return false;
225
+ const rest = name.slice(exports.SECRET_NAME_PREFIX.length);
226
+ const at = rest.lastIndexOf(":");
227
+ if (at <= 0)
228
+ return false;
229
+ const agentId = rest.slice(0, at);
230
+ const tail = rest.slice(at + 1);
231
+ const host = webhookHost(url);
232
+ return !agentId.includes(":") && (tail === host || tail === hashedHost(host));
184
233
  }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * `client.webhooks`: set, rotate, check and delete an agent webhook's signing secret (as Python's
3
+ * `sarvam_agents.compose.webhook_secrets`).
4
+ *
5
+ * The public surface is `WebhookSecrets`. Where the secret lives is behind `SecretBackend`, one small interface with
6
+ * one implementation today, `CustomApiBackend`: the secret is a bearer Custom API the SDK creates, owns and binds to
7
+ * the agent, always with `enabledForChats: false` (`CustomApiCreate` defaults it to true, which would let the agent's
8
+ * sandbox be handed the secret on requests to the webhook's host). When the server ships dedicated secret endpoints
9
+ * (SARC-2597: PUT/DELETE secret, rotate-secret, secretStatus), a second backend replaces this one in `secretBackend`
10
+ * and nothing else changes.
11
+ *
12
+ * No secret is logged, kept on an object or put in an error message.
13
+ */
14
+ import { CustomAPIsApi } from "../apis/CustomAPIsApi.js";
15
+ import type { Configuration } from "../runtime.js";
16
+ import type { Webhook } from "./webhook.js";
17
+ export type SecretStatus = "set" | "missing";
18
+ /** Every Custom API the SDK creates for a webhook secret carries this description (and its name). */
19
+ export declare const SECRET_DESCRIPTION = "Webhook signing secret managed by the Sarvam Agents SDK (client.webhooks). Do not edit.";
20
+ /** The description of the random secret `deploy` stores when none is set yet: `secretStatus` reads it as
21
+ * `"missing"`, and `setSecret`/`rotateSecret` overwrite it with `SECRET_DESCRIPTION`. */
22
+ export declare const PLACEHOLDER_DESCRIPTION = "Webhook signing secret managed by the Sarvam Agents SDK (client.webhooks). Placeholder: call client.webhooks.set_secret";
23
+ /** Where webhook secrets live. Swap the implementation in `secretBackend`, nowhere else. */
24
+ export interface SecretBackend {
25
+ /** Store `secret` for `url` on the agent, replacing any current one. */
26
+ put(agentId: string, url: string, secret: string): Promise<void>;
27
+ /** `"set"` only for a secret stored by `put`; a placeholder from `ensure` is `"missing"`. */
28
+ status(agentId: string, url: string): Promise<SecretStatus>;
29
+ /** Remove the secret; nothing to remove is not an error. */
30
+ delete(agentId: string, url: string): Promise<void>;
31
+ /** For `deploy`: make sure the agent has a secret for `url` (a random placeholder one if none) and return the
32
+ * credential name for agent.json `secret_credential` and `status` (`"missing"` while it is a placeholder). */
33
+ ensure(agentId: string, url: string): Promise<{
34
+ name: string;
35
+ status: SecretStatus;
36
+ }>;
37
+ }
38
+ /** The one place that picks where secrets live. */
39
+ export declare function secretBackend(api: {
40
+ config?: Configuration;
41
+ customApis?: CustomAPIsApi;
42
+ }): SecretBackend;
43
+ /**
44
+ * `client.webhooks`: the signing secret of each agent.json webhook.
45
+ *
46
+ * `webhook` is the webhook's URL (or a webhook object); the secret covers the URL's host. Secrets are `whsec_` plus
47
+ * base64 of 24 to 64 bytes.
48
+ */
49
+ export declare class WebhookSecrets {
50
+ #private;
51
+ constructor(config: Configuration);
52
+ /** Store `secret` (a new generated one when left out) as the webhook's signing secret and return it. A malformed
53
+ * secret throws `SecretFormatError` before anything is sent. */
54
+ setSecret(agentId: string, webhook: string | Webhook, secret?: string): Promise<string>;
55
+ /** Replace the webhook's signing secret with a new generated one and return it. Have your receiver accept the old
56
+ * and the new secret for a few minutes: a delivery still retrying is signed with the new one. */
57
+ rotateSecret(agentId: string, webhook: string | Webhook): Promise<string>;
58
+ /** `"set"` when the agent has a signing secret stored by `setSecret` or `rotateSecret` for the webhook; `"missing"`
59
+ * otherwise, including while it holds the placeholder a deploy stored. */
60
+ secretStatus(agentId: string, webhook: string | Webhook): Promise<SecretStatus>;
61
+ /** Remove the webhook's signing secret. Only what the SDK stored is removed; a Custom API you made yourself is
62
+ * never touched. Deliveries to the webhook fail until a new secret is set or the webhook is removed. */
63
+ deleteSecret(agentId: string, webhook: string | Webhook): Promise<void>;
64
+ }