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.
@@ -0,0 +1,255 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _WebhookSecrets_backend;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.WebhookSecrets = exports.PLACEHOLDER_DESCRIPTION = exports.SECRET_DESCRIPTION = void 0;
16
+ exports.secretBackend = secretBackend;
17
+ /**
18
+ * `client.webhooks`: set, rotate, check and delete an agent webhook's signing secret (as Python's
19
+ * `sarvam_agents.compose.webhook_secrets`).
20
+ *
21
+ * The public surface is `WebhookSecrets`. Where the secret lives is behind `SecretBackend`, one small interface with
22
+ * one implementation today, `CustomApiBackend`: the secret is a bearer Custom API the SDK creates, owns and binds to
23
+ * the agent, always with `enabledForChats: false` (`CustomApiCreate` defaults it to true, which would let the agent's
24
+ * sandbox be handed the secret on requests to the webhook's host). When the server ships dedicated secret endpoints
25
+ * (SARC-2597: PUT/DELETE secret, rotate-secret, secretStatus), a second backend replaces this one in `secretBackend`
26
+ * and nothing else changes.
27
+ *
28
+ * No secret is logged, kept on an object or put in an error message.
29
+ */
30
+ const CustomAPIsApi_js_1 = require("../apis/CustomAPIsApi.js");
31
+ const runtime_js_1 = require("../runtime.js");
32
+ const errors_js_1 = require("./errors.js");
33
+ // Loaded on first use, so the root entry point (which exports `Client`) does not import `node:crypto` up front.
34
+ const loadWebhook = () => Promise.resolve().then(() => require("./webhook.js"));
35
+ const loadCrypto = () => Promise.resolve().then(() => require("../webhooks.js"));
36
+ /** Every Custom API the SDK creates for a webhook secret carries this description (and its name). */
37
+ exports.SECRET_DESCRIPTION = "Webhook signing secret managed by the Sarvam Agents SDK (client.webhooks). Do not edit.";
38
+ /** The description of the random secret `deploy` stores when none is set yet: `secretStatus` reads it as
39
+ * `"missing"`, and `setSecret`/`rotateSecret` overwrite it with `SECRET_DESCRIPTION`. */
40
+ exports.PLACEHOLDER_DESCRIPTION = "Webhook signing secret managed by the Sarvam Agents SDK (client.webhooks). Placeholder: call client.webhooks.set_secret";
41
+ const OWNED = [exports.SECRET_DESCRIPTION, exports.PLACEHOLDER_DESCRIPTION];
42
+ const PAGE = 100;
43
+ /** Throws `SecretFormatError` unless `secret` is `whsec_` plus base64 of 24 to 64 bytes (the verifier's own parser). */
44
+ async function checkSecret(secret) {
45
+ (await loadCrypto()).sign(secret, { msgId: "check", timestamp: 0, body: "" });
46
+ }
47
+ async function urlOf(hook) {
48
+ const url = typeof hook === "string" ? hook : hook === null || hook === void 0 ? void 0 : hook.url;
49
+ if (typeof url !== "string")
50
+ throw new errors_js_1.UserError("webhook: pass the webhook's URL (a string) or a webhook");
51
+ const problem = (await loadWebhook()).urlProblem(url);
52
+ if (problem !== null)
53
+ throw new errors_js_1.UserError("webhook: " + problem);
54
+ return url;
55
+ }
56
+ function agent(agentId) {
57
+ if (typeof agentId !== "string" || agentId.trim() === "")
58
+ throw new errors_js_1.UserError("agentId: pass the agent's id");
59
+ return agentId;
60
+ }
61
+ function status(err) {
62
+ return err instanceof runtime_js_1.ResponseError ? err.response.status : 0;
63
+ }
64
+ /** The server's reason, never its raw body: a 422 may echo the request, and the request carries the secret. */
65
+ async function apiMessage(err, secret) {
66
+ var _a, _b;
67
+ let message;
68
+ if (err instanceof runtime_js_1.ResponseError) {
69
+ try {
70
+ message = (_b = (_a = ((await err.response.clone().json()))) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.message;
71
+ }
72
+ catch (_c) {
73
+ message = undefined;
74
+ }
75
+ }
76
+ if (typeof message !== "string" || !message || (secret !== undefined && message.includes(secret))) {
77
+ return `HTTP ${status(err) || "error"}`;
78
+ }
79
+ return message;
80
+ }
81
+ /** Today's store: a bearer Custom API the SDK owns, bound to the agent, never enabled for chats. */
82
+ class CustomApiBackend {
83
+ constructor(api) {
84
+ this.api = api;
85
+ }
86
+ /** The caller's Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
87
+ async named(name) {
88
+ const found = [];
89
+ let offset = 0;
90
+ for (;;) {
91
+ const result = await this.api.listCustomApis({ q: name, limit: PAGE, offset });
92
+ for (const item of result.data)
93
+ if (item.name === name)
94
+ found.push(item);
95
+ offset += result.data.length;
96
+ if (result.data.length === 0 || !result.hasMore)
97
+ return found;
98
+ }
99
+ }
100
+ /** The Custom APIs named `name` that the SDK created; throws when only someone else's has the name. */
101
+ async owned(name) {
102
+ const named = await this.named(name);
103
+ const owned = named.filter((item) => { var _a; return OWNED.includes((_a = item.description) !== null && _a !== void 0 ? _a : ""); });
104
+ if (named.length > 0 && owned.length === 0) {
105
+ throw new errors_js_1.UserError(`a Custom API named '${name}' exists that the SDK did not create; it was left alone. ` +
106
+ "Rename or delete it, then try again");
107
+ }
108
+ return owned;
109
+ }
110
+ async bind(agentId, customApiId) {
111
+ const bound = (await this.api.listAgentCustomApis({ agentId })).data;
112
+ if (bound.some((item) => item.id === customApiId))
113
+ return;
114
+ try {
115
+ await this.api.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
116
+ }
117
+ catch (err) {
118
+ if (status(err) === 409)
119
+ return; // bound meanwhile
120
+ throw new errors_js_1.UserError(`could not bind the webhook secret to agent ${agentId}: ${await apiMessage(err)}`);
121
+ }
122
+ }
123
+ /** PATCH the secret in, always asking for `enabledForChats: false`. The server switches chats off by detaching a
124
+ * capability, and answers 404 when there is nothing to detach (the API is already off). Then the API is read
125
+ * back: only when it exists and is off is the PATCH sent again without the switch, so the secret still lands and
126
+ * chats stay off. */
127
+ async update(customApiId, host, description, secret) {
128
+ const patch = (off) => this.api.updateCustomApi({ customApiId, customApiUpdate: {
129
+ host, description, auth: { type: "bearer", token: secret }, ...off,
130
+ } });
131
+ try {
132
+ await patch({ enabledForChats: false });
133
+ }
134
+ catch (err) {
135
+ if (status(err) !== 404)
136
+ throw err;
137
+ if ((await this.api.getCustomApi({ customApiId })).enabledForChats !== false)
138
+ throw err; // gone (404) or on
139
+ await patch({});
140
+ }
141
+ }
142
+ async store(agentId, url, secret, owned, description = exports.SECRET_DESCRIPTION) {
143
+ const { secretCredentialName, webhookHost } = await loadWebhook();
144
+ const name = secretCredentialName(agentId, url);
145
+ const host = webhookHost(url);
146
+ let customApiId;
147
+ try {
148
+ if (owned.length > 0) {
149
+ customApiId = owned[0].id;
150
+ await this.update(customApiId, host, description, secret);
151
+ }
152
+ else {
153
+ customApiId = (await this.api.createCustomApi({ customApiCreate: {
154
+ name, description, host, enabledForChats: false, auth: { type: "bearer", token: secret },
155
+ } })).id;
156
+ }
157
+ }
158
+ catch (err) {
159
+ if (!(err instanceof runtime_js_1.ResponseError))
160
+ throw err;
161
+ throw new errors_js_1.UserError(`could not store the webhook secret for ${host}: ${await apiMessage(err, secret)}`);
162
+ }
163
+ await this.bind(agentId, customApiId);
164
+ return name;
165
+ }
166
+ async put(agentId, url, secret) {
167
+ await this.store(agentId, url, secret, await this.owned((await loadWebhook()).secretCredentialName(agentId, url)));
168
+ }
169
+ async status(agentId, url) {
170
+ const name = (await loadWebhook()).secretCredentialName(agentId, url);
171
+ // Not a placeholder, not someone else's.
172
+ const stored = (await this.named(name)).filter((item) => item.description === exports.SECRET_DESCRIPTION).map((i) => i.id);
173
+ if (stored.length === 0)
174
+ return "missing";
175
+ const bound = (await this.api.listAgentCustomApis({ agentId })).data;
176
+ return bound.some((item) => stored.includes(item.id)) ? "set" : "missing";
177
+ }
178
+ async delete(agentId, url) {
179
+ for (const item of await this.owned((await loadWebhook()).secretCredentialName(agentId, url))) {
180
+ try {
181
+ await this.api.unbindCustomApi({ agentId, customApiId: item.id });
182
+ }
183
+ catch (err) {
184
+ if (status(err) !== 404)
185
+ throw err;
186
+ }
187
+ try {
188
+ await this.api.deleteCustomApi({ customApiId: item.id });
189
+ }
190
+ catch (err) {
191
+ if (status(err) !== 404)
192
+ throw err;
193
+ }
194
+ }
195
+ }
196
+ async ensure(agentId, url) {
197
+ const name = (await loadWebhook()).secretCredentialName(agentId, url);
198
+ const owned = await this.owned(name);
199
+ if (owned.length > 0) {
200
+ await this.bind(agentId, owned[0].id);
201
+ return { name, status: owned[0].description === exports.SECRET_DESCRIPTION ? "set" : "missing" };
202
+ }
203
+ console.warn(`agent ${agentId}: webhook ${url} has no signing secret yet; stored a random one nobody holds, so ` +
204
+ "deliveries fail verification until you call client.webhooks.setSecret");
205
+ const stored = await this.store(agentId, url, (await loadCrypto()).generateSecret(), owned, exports.PLACEHOLDER_DESCRIPTION);
206
+ return { name: stored, status: "missing" };
207
+ }
208
+ }
209
+ /** The one place that picks where secrets live. */
210
+ function secretBackend(api) {
211
+ var _a;
212
+ return new CustomApiBackend((_a = api.customApis) !== null && _a !== void 0 ? _a : new CustomAPIsApi_js_1.CustomAPIsApi(api.config));
213
+ }
214
+ /**
215
+ * `client.webhooks`: the signing secret of each agent.json webhook.
216
+ *
217
+ * `webhook` is the webhook's URL (or a webhook object); the secret covers the URL's host. Secrets are `whsec_` plus
218
+ * base64 of 24 to 64 bytes.
219
+ */
220
+ class WebhookSecrets {
221
+ constructor(config) {
222
+ _WebhookSecrets_backend.set(this, void 0);
223
+ __classPrivateFieldSet(this, _WebhookSecrets_backend, secretBackend({ config }), "f");
224
+ }
225
+ /** Store `secret` (a new generated one when left out) as the webhook's signing secret and return it. A malformed
226
+ * secret throws `SecretFormatError` before anything is sent. */
227
+ async setSecret(agentId, webhook, secret) {
228
+ const id = agent(agentId);
229
+ const url = await urlOf(webhook);
230
+ const value = secret === undefined ? (await loadCrypto()).generateSecret() : secret;
231
+ if (secret !== undefined)
232
+ await checkSecret(secret);
233
+ await __classPrivateFieldGet(this, _WebhookSecrets_backend, "f").put(id, url, value);
234
+ return value;
235
+ }
236
+ /** Replace the webhook's signing secret with a new generated one and return it. Have your receiver accept the old
237
+ * and the new secret for a few minutes: a delivery still retrying is signed with the new one. */
238
+ async rotateSecret(agentId, webhook) {
239
+ return this.setSecret(agentId, webhook);
240
+ }
241
+ /** `"set"` when the agent has a signing secret stored by `setSecret` or `rotateSecret` for the webhook; `"missing"`
242
+ * otherwise, including while it holds the placeholder a deploy stored. */
243
+ async secretStatus(agentId, webhook) {
244
+ const id = agent(agentId);
245
+ return __classPrivateFieldGet(this, _WebhookSecrets_backend, "f").status(id, await urlOf(webhook));
246
+ }
247
+ /** Remove the webhook's signing secret. Only what the SDK stored is removed; a Custom API you made yourself is
248
+ * never touched. Deliveries to the webhook fail until a new secret is set or the webhook is removed. */
249
+ async deleteSecret(agentId, webhook) {
250
+ const id = agent(agentId);
251
+ await __classPrivateFieldGet(this, _WebhookSecrets_backend, "f").delete(id, await urlOf(webhook));
252
+ }
253
+ }
254
+ exports.WebhookSecrets = WebhookSecrets;
255
+ _WebhookSecrets_backend = new WeakMap();
@@ -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
+ }
@@ -0,0 +1,17 @@
1
+ import { WebhookSecrets } from "./compose/webhookSecrets.js";
2
+ /**
3
+ * Groups the hand-written helpers over one `Configuration`.
4
+ *
5
+ * ```ts
6
+ * const client = new Client(config);
7
+ * const secret = await client.webhooks.setSecret(agentId, "https://hooks.acme.com/panja");
8
+ * ```
9
+ */
10
+ export class Client {
11
+ constructor(config) {
12
+ this.config = config;
13
+ if (config === undefined || config === null)
14
+ throw new TypeError("new Client(config): pass a Configuration");
15
+ this.webhooks = new WebhookSecrets(config);
16
+ }
17
+ }
@@ -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;
@@ -53,10 +53,17 @@ async function update(transport, remote, agent, strict) {
53
53
  return settle(transport, remote, agent);
54
54
  }
55
55
  const updated = await transport.updateAgent(remote.agentId, agent);
56
- return deployment(remote.agentId, "updated", liveVersion(updated));
56
+ return deployment(remote.agentId, "updated", liveVersion(updated), missingSecrets(updated));
57
57
  }
58
- function deployment(agentId, action, version) {
59
- return version === undefined ? { agentId, action } : { agentId, action, version };
58
+ function deployment(agentId, action, version, webhooksMissingSecret = []) {
59
+ const out = version === undefined ? { agentId, action } : { agentId, action, version };
60
+ if (webhooksMissingSecret.length > 0)
61
+ out.webhooksMissingSecret = webhooksMissingSecret;
62
+ return out;
63
+ }
64
+ function missingSecrets(remote) {
65
+ const missing = remote === null || remote === void 0 ? void 0 : remote.webhooksMissingSecret;
66
+ return Array.isArray(missing) ? [...missing] : [];
60
67
  }
61
68
  // Optional chaining: a custom transport written for 0.3 may resolve anything from updateAgent/createAgent.
62
69
  function liveVersion(remote) {
@@ -89,13 +96,14 @@ async function deployWith(agent, transport, strict, adopt) {
89
96
  if (others.length) {
90
97
  throw new UserError(`cannot adopt ${adopt}: agent "${agent.name}" is already deployed as ${others.join(", ")}`);
91
98
  }
92
- return deployment(adopt, "updated", liveVersion(await transport.updateAgent(adopt, agent)));
99
+ const adopted = await transport.updateAgent(adopt, agent);
100
+ return deployment(adopt, "updated", liveVersion(adopted), missingSecrets(adopted));
93
101
  }
94
102
  if (found.length > 1)
95
103
  throw new DuplicateAgentsError(found.map((r) => r.agentId));
96
104
  if (found.length === 0) {
97
105
  const created = await transport.createAgent(agent);
98
- return deployment(created.agentId, "created", liveVersion(created));
106
+ return deployment(created.agentId, "created", liveVersion(created), missingSecrets(created));
99
107
  }
100
108
  return update(transport, found[0], agent, strict);
101
109
  }
@@ -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). */
@@ -9,6 +9,8 @@ import { answerClarify, postToolResults, reconnect, streamResponse } from "../st
9
9
  import { NotSupportedByServerError, RunError, UserError } from "./errors.js";
10
10
  import { chunksFromUiMessage, fromUiChunk } from "./events.js";
11
11
  import { VERSION_NOTE } from "./transport.js";
12
+ import { secretCredentialName, urlProblem } from "./webhook.js";
13
+ import { secretBackend } from "./webhookSecrets.js";
12
14
  const PAGE = 100;
13
15
  /** A post the server is still delivering (409 in_progress) is retried this many times, Retry-After apart. */
14
16
  const IN_PROGRESS_RETRIES = 5;
@@ -193,6 +195,30 @@ function withoutWebhooks(settings) {
193
195
  const { sdk_hash: _hash, ...metadata } = settings["metadata"];
194
196
  return { ...out, metadata };
195
197
  }
198
+ function hooksOf(settings) {
199
+ const hooks = settings["webhooks"];
200
+ return Array.isArray(hooks) ? hooks.filter((h) => typeof h === "object" && h !== null && !Array.isArray(h)) : [];
201
+ }
202
+ function sdkNamed(agentId, hook) {
203
+ const url = hook["url"];
204
+ return typeof url === "string" && urlProblem(url) === null &&
205
+ hook["secret_credential"] === secretCredentialName(agentId, url);
206
+ }
207
+ /** `settings` as a definition writes them: a webhook whose `secret_credential` is the one `deploy` filled in loses it
208
+ * again, so the stored `sdk_hash` (computed without it) still matches. */
209
+ function asDefined(agentId, settings) {
210
+ if (!hooksOf(settings).some((h) => sdkNamed(agentId, h)))
211
+ return settings;
212
+ return {
213
+ ...settings,
214
+ webhooks: settings["webhooks"].map((h) => {
215
+ if (typeof h !== "object" || h === null || !sdkNamed(agentId, h))
216
+ return h;
217
+ const { secret_credential: _name, ...rest } = h;
218
+ return rest;
219
+ }),
220
+ };
221
+ }
196
222
  function isNotFound(err) {
197
223
  return err instanceof ResponseError && err.response.status === 404;
198
224
  }
@@ -230,6 +256,7 @@ export class SettingsTransport {
230
256
  this.conversations = new ConversationsApi(config);
231
257
  this.responses = new ResponsesApi(config);
232
258
  this.customApis = new CustomAPIsApi(config);
259
+ this.secrets = secretBackend({ customApis: this.customApis });
233
260
  }
234
261
  // -- agents ---------------------------------------------------------------------------------------------
235
262
  async findAgents(sdkName) {
@@ -259,7 +286,8 @@ export class SettingsTransport {
259
286
  }
260
287
  async createAgent(agent) {
261
288
  var _a, _b, _c;
262
- const settings = agent.toSettings();
289
+ let settings = agent.toSettings();
290
+ let missing = [];
263
291
  const webhooks = ((_a = settings["webhooks"]) !== null && _a !== void 0 ? _a : []);
264
292
  // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
265
293
  // without them, bind the Custom APIs they name, then write the settings in full.
@@ -294,6 +322,7 @@ export class SettingsTransport {
294
322
  if (webhooks.length > 0) {
295
323
  for (const { path, name, customApiId } of bind)
296
324
  await this.bind(resource.id, path, name, customApiId);
325
+ ({ settings, missing } = await this.withSecretCredentials(resource.id, settings));
297
326
  try {
298
327
  envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
299
328
  }
@@ -325,10 +354,33 @@ export class SettingsTransport {
325
354
  agentId: resource.id,
326
355
  name: agent.name,
327
356
  instructions: agent.instructions,
328
- settings: { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) },
357
+ settings: asDefined(resource.id, { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) }),
329
358
  warnings,
359
+ ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
330
360
  }, live, versionStateOf(resource));
331
361
  }
362
+ /** `settings` with each webhook that names no `secret_credential` given the one `client.webhooks` keeps for the
363
+ * agent and host (stored, with a random secret nobody holds, when there is none yet), and the URLs of those
364
+ * webhooks still without a secret set by `client.webhooks`. */
365
+ async withSecretCredentials(agentId, settings) {
366
+ const hooks = hooksOf(settings);
367
+ if (hooks.every((h) => "secret_credential" in h))
368
+ return { settings, missing: [] };
369
+ const filled = [];
370
+ const missing = [];
371
+ for (const h of settings["webhooks"]) {
372
+ if (typeof h !== "object" || h === null || "secret_credential" in h) {
373
+ filled.push(h);
374
+ continue;
375
+ }
376
+ const url = h["url"];
377
+ const { name, status } = await this.secrets.ensure(agentId, url);
378
+ filled.push({ ...h, secret_credential: name });
379
+ if (status === "missing")
380
+ missing.push(url);
381
+ }
382
+ return { settings: { ...settings, webhooks: filled }, missing };
383
+ }
332
384
  /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
333
385
  * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
334
386
  * checks credentials). */
@@ -338,8 +390,8 @@ export class SettingsTransport {
338
390
  const seen = new Set();
339
391
  for (const [i, hook] of webhooks.entries()) {
340
392
  const name = hook.secret_credential;
341
- if (seen.has(name))
342
- continue;
393
+ if (name === undefined || seen.has(name))
394
+ continue; // left out: deploy fills in the one client.webhooks keeps
343
395
  seen.add(name);
344
396
  const path = `webhooks.${i}.secret_credential`;
345
397
  const ids = await this.customApiIds(name);
@@ -388,7 +440,7 @@ export class SettingsTransport {
388
440
  }
389
441
  async updateAgent(agentId, agent) {
390
442
  var _a, _b;
391
- const settings = agent.toSettings();
443
+ let settings = agent.toSettings();
392
444
  // findAgents searches by display name, so an adopted (or dashboard-renamed) agent must carry sdk_name.
393
445
  const current = await this.agents.getAgent({ agentId });
394
446
  if (current.name !== agent.name) {
@@ -411,6 +463,15 @@ export class SettingsTransport {
411
463
  if (instructionsChanged) {
412
464
  await this.agents.putInstructions({ agentId, instructionsBody: { data: agent.instructions } });
413
465
  }
466
+ let missing;
467
+ try {
468
+ ({ settings, missing } = await this.withSecretCredentials(agentId, settings));
469
+ }
470
+ catch (err) {
471
+ if (instructionsChanged)
472
+ await this.restore(agentId, null, previousInstructions);
473
+ throw err;
474
+ }
414
475
  let envelope;
415
476
  try {
416
477
  envelope = await this.agents.putAgentSettings({ agentId, body: settings });
@@ -442,8 +503,9 @@ export class SettingsTransport {
442
503
  agentId,
443
504
  name: agent.name,
444
505
  instructions: agent.instructions,
445
- settings: { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) },
506
+ settings: asDefined(agentId, { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) }),
446
507
  warnings,
508
+ ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
447
509
  }, live, versionStateOf(current));
448
510
  }
449
511
  /** Make what was just written what end users get. A server without versions (no `versionState`) gets the bodiless
@@ -660,7 +722,8 @@ export class SettingsTransport {
660
722
  remote(resource, instructions) {
661
723
  var _a;
662
724
  const remote = {
663
- agentId: resource.id, name: resource.name, instructions, settings: { ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }, warnings: [],
725
+ agentId: resource.id, name: resource.name, instructions, warnings: [],
726
+ settings: asDefined(resource.id, { ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }),
664
727
  };
665
728
  // Left out, not set to undefined, when the server has no versions: the shape a 0.3 transport returned.
666
729
  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;
@@ -3,10 +3,13 @@
3
3
  *
4
4
  * The server (`claw_common/agent_settings/webhooks.py`) also checks that the host resolves to a public address and
5
5
  * that `secret_credential` names a vault credential bound to the agent whose allowed hosts cover the URL; those need
6
- * I/O and stay on the server, which refuses the save with a 422 that `deploy` throws as `UserError`. A new agent has
7
- * no credentials bound yet, so the deploy that creates it binds the caller's Custom API of each named credential first
8
- * (`SettingsTransport.createAgent`).
6
+ * I/O and stay on the server, which refuses the save with a 422 that `deploy` throws as `UserError`.
7
+ *
8
+ * `secretCredential` is optional and deprecated: left out, `deploy` writes the name `client.webhooks` uses for the
9
+ * agent and host (`secretCredentialName`). Given, the deploy that creates the agent binds the caller's Custom API of
10
+ * that name first (`SettingsTransport.createAgent`).
9
11
  */
12
+ import { createHash } from "node:crypto";
10
13
  import { UserError } from "./errors.js";
11
14
  import { WEBHOOK_EVENTS } from "../webhooks.js";
12
15
  export const WEBHOOKS_MAX = 5;
@@ -131,7 +134,7 @@ export function checkWebhooks(webhooks) {
131
134
  webhooks.forEach((hook, i) => {
132
135
  const where = `webhooks.${i}.`;
133
136
  if (typeof hook !== "object" || hook === null || Array.isArray(hook)) {
134
- throw new UserError(`webhooks.${i}: must be an object with url, events and secretCredential`);
137
+ throw new UserError(`webhooks.${i}: must be an object with url and events`);
135
138
  }
136
139
  const { url, events, secretCredential } = hook;
137
140
  if (typeof url !== "string")
@@ -139,8 +142,9 @@ export function checkWebhooks(webhooks) {
139
142
  if (!Array.isArray(events) || !events.every((e) => typeof e === "string")) {
140
143
  throw new UserError(where + "events: must be a list of event names");
141
144
  }
142
- if (typeof secretCredential !== "string")
145
+ if (secretCredential !== undefined && typeof secretCredential !== "string") {
143
146
  throw new UserError(where + "secretCredential: must be a string");
147
+ }
144
148
  // Python's Webhook is extra="forbid": a key dropped silently (a misplaced secret) would never verify.
145
149
  const extra = Object.keys(hook).find((k) => k !== "url" && k !== "events" && k !== "secretCredential");
146
150
  if (extra !== undefined)
@@ -156,7 +160,7 @@ export function checkWebhooks(webhooks) {
156
160
  }
157
161
  if (new Set(events).size !== events.length)
158
162
  throw new UserError(where + "events: events must not repeat an event.");
159
- const n = codePoints(secretCredential);
163
+ const n = typeof secretCredential === "string" ? codePoints(secretCredential) : 1;
160
164
  if (n < 1 || n > SECRET_CREDENTIAL_MAX) {
161
165
  throw new UserError(where + "secret_credential: secret_credential must be the name of a vault credential " +
162
166
  `(1 to ${SECRET_CREDENTIAL_MAX} characters).`);
@@ -168,10 +172,52 @@ export function checkWebhooks(webhooks) {
168
172
  seen.add(key);
169
173
  });
170
174
  }
171
- /** Only the three fields, in agent.json's names (a copy). */
175
+ /** Only the three fields (a copy). `secretCredential` is left out when absent, or when it is the name `deploy`
176
+ * writes anyway (one spelling keeps one fingerprint). */
172
177
  export function copyWebhooks(webhooks) {
173
- return webhooks.map((h) => ({ url: h.url, events: [...h.events], secretCredential: h.secretCredential }));
178
+ return webhooks.map((h) => {
179
+ const copy = { url: h.url, events: [...h.events] };
180
+ const name = h.secretCredential;
181
+ if (name !== undefined && !isSdkCredentialName(name, h.url))
182
+ copy.secretCredential = name;
183
+ return copy;
184
+ });
174
185
  }
175
186
  export function webhooksJson(webhooks) {
176
- return webhooks.map((h) => ({ url: h.url, events: [...h.events], secret_credential: h.secretCredential }));
187
+ return webhooks.map((h) => {
188
+ const out = { url: h.url, events: [...h.events] };
189
+ if (h.secretCredential !== undefined)
190
+ out["secret_credential"] = h.secretCredential;
191
+ return out;
192
+ });
193
+ }
194
+ /** The host of an allowed webhook URL, lowercased, without a trailing dot or a port. */
195
+ export function webhookHost(url) {
196
+ return stripTrailingDots(hostPort(split(url)[1])[0]);
197
+ }
198
+ /** Every Custom API the SDK creates for a webhook secret is named `webhook-secret:<agentId>:<host>`. */
199
+ export const SECRET_NAME_PREFIX = "webhook-secret:";
200
+ const SECRET_NAME_MAX = 256;
201
+ function hashedHost(host) {
202
+ return "sha256-" + createHash("sha256").update(host, "utf8").digest("hex").slice(0, 32);
203
+ }
204
+ /** The credential name the SDK uses for `url`'s signing secret on agent `agentId` (what `deploy` writes as
205
+ * `secret_credential` when a webhook leaves it out). A host too long to fit 256 characters is hashed. */
206
+ export function secretCredentialName(agentId, url) {
207
+ const host = webhookHost(url);
208
+ const name = `${SECRET_NAME_PREFIX}${agentId}:${host}`;
209
+ return codePoints(name) <= SECRET_NAME_MAX ? name : `${SECRET_NAME_PREFIX}${agentId}:${hashedHost(host)}`;
210
+ }
211
+ /** Whether `name` is the SDK's credential name for `url`'s host, for any agent. */
212
+ export function isSdkCredentialName(name, url) {
213
+ if (typeof name !== "string" || !name.startsWith(SECRET_NAME_PREFIX) || urlProblem(url) !== null)
214
+ return false;
215
+ const rest = name.slice(SECRET_NAME_PREFIX.length);
216
+ const at = rest.lastIndexOf(":");
217
+ if (at <= 0)
218
+ return false;
219
+ const agentId = rest.slice(0, at);
220
+ const tail = rest.slice(at + 1);
221
+ const host = webhookHost(url);
222
+ return !agentId.includes(":") && (tail === host || tail === hashedHost(host));
177
223
  }