sarvam-agents-client 0.5.2 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/README.md +52 -29
  2. package/dist/apis/AgentsApi.d.ts +96 -11
  3. package/dist/apis/AgentsApi.js +229 -9
  4. package/dist/apis/ConversationsApi.d.ts +5 -2
  5. package/dist/apis/ConversationsApi.js +7 -2
  6. package/dist/client.d.ts +3 -2
  7. package/dist/client.js +2 -1
  8. package/dist/compose/deploy.d.ts +14 -3
  9. package/dist/compose/deploy.js +60 -7
  10. package/dist/compose/errors.d.ts +4 -0
  11. package/dist/compose/errors.js +6 -1
  12. package/dist/compose/settingsTransport.d.ts +18 -13
  13. package/dist/compose/settingsTransport.js +78 -130
  14. package/dist/compose/transport.d.ts +12 -2
  15. package/dist/compose/webhook.d.ts +10 -13
  16. package/dist/compose/webhook.js +48 -45
  17. package/dist/compose/webhookSecrets.d.ts +79 -49
  18. package/dist/compose/webhookSecrets.js +244 -195
  19. package/dist/esm/apis/AgentsApi.d.ts +96 -11
  20. package/dist/esm/apis/AgentsApi.js +230 -10
  21. package/dist/esm/apis/ConversationsApi.d.ts +5 -2
  22. package/dist/esm/apis/ConversationsApi.js +7 -2
  23. package/dist/esm/client.d.ts +3 -2
  24. package/dist/esm/client.js +2 -1
  25. package/dist/esm/compose/deploy.d.ts +14 -3
  26. package/dist/esm/compose/deploy.js +60 -7
  27. package/dist/esm/compose/errors.d.ts +4 -0
  28. package/dist/esm/compose/errors.js +4 -0
  29. package/dist/esm/compose/settingsTransport.d.ts +18 -13
  30. package/dist/esm/compose/settingsTransport.js +80 -132
  31. package/dist/esm/compose/transport.d.ts +12 -2
  32. package/dist/esm/compose/webhook.d.ts +10 -13
  33. package/dist/esm/compose/webhook.js +45 -42
  34. package/dist/esm/compose/webhookSecrets.d.ts +79 -49
  35. package/dist/esm/compose/webhookSecrets.js +241 -193
  36. package/dist/esm/index.d.ts +2 -1
  37. package/dist/esm/index.js +2 -1
  38. package/dist/esm/models/AgentConversationDetail.d.ts +12 -0
  39. package/dist/esm/models/AgentConversationDetail.js +4 -0
  40. package/dist/esm/models/AgentConversationView.d.ts +12 -0
  41. package/dist/esm/models/AgentConversationView.js +4 -0
  42. package/dist/esm/models/AgentResource.d.ts +7 -0
  43. package/dist/esm/models/AgentResource.js +3 -0
  44. package/dist/esm/models/AgentVersionSavedResource.d.ts +65 -0
  45. package/dist/esm/models/AgentVersionSavedResource.js +60 -0
  46. package/dist/esm/models/AgentWebhookList.d.ts +33 -0
  47. package/dist/esm/models/AgentWebhookList.js +44 -0
  48. package/dist/esm/models/AgentWebhookView.d.ts +76 -0
  49. package/dist/esm/models/AgentWebhookView.js +70 -0
  50. package/dist/esm/models/ConversationDetail.d.ts +6 -0
  51. package/dist/esm/models/ConversationDetail.js +2 -0
  52. package/dist/esm/models/ConversationView.d.ts +6 -0
  53. package/dist/esm/models/ConversationView.js +2 -0
  54. package/dist/esm/models/ErrorDetailItem.d.ts +3 -0
  55. package/dist/esm/models/FileNodeView.d.ts +7 -0
  56. package/dist/esm/models/FileNodeView.js +3 -0
  57. package/dist/esm/models/QueueMessageInput.d.ts +6 -0
  58. package/dist/esm/models/QueueMessageInput.js +2 -0
  59. package/dist/esm/models/RotatedWebhookSecretView.d.ts +58 -0
  60. package/dist/esm/models/RotatedWebhookSecretView.js +61 -0
  61. package/dist/esm/models/SaveWarningView.d.ts +44 -0
  62. package/dist/esm/models/SaveWarningView.js +51 -0
  63. package/dist/esm/models/ShareSkippedResource.d.ts +41 -0
  64. package/dist/esm/models/ShareSkippedResource.js +47 -0
  65. package/dist/esm/models/WebhookSecretPutBody.d.ts +32 -0
  66. package/dist/esm/models/WebhookSecretPutBody.js +43 -0
  67. package/dist/esm/models/WebhookSecretStateView.d.ts +52 -0
  68. package/dist/esm/models/WebhookSecretStateView.js +56 -0
  69. package/dist/esm/models/WebhookSecretValueView.d.ts +32 -0
  70. package/dist/esm/models/WebhookSecretValueView.js +44 -0
  71. package/dist/esm/models/WebhookWarning.d.ts +44 -0
  72. package/dist/esm/models/WebhookWarning.js +51 -0
  73. package/dist/esm/models/index.d.ts +10 -0
  74. package/dist/esm/models/index.js +10 -0
  75. package/dist/index.d.ts +2 -1
  76. package/dist/index.js +4 -1
  77. package/dist/models/AgentConversationDetail.d.ts +12 -0
  78. package/dist/models/AgentConversationDetail.js +4 -0
  79. package/dist/models/AgentConversationView.d.ts +12 -0
  80. package/dist/models/AgentConversationView.js +4 -0
  81. package/dist/models/AgentResource.d.ts +7 -0
  82. package/dist/models/AgentResource.js +3 -0
  83. package/dist/models/AgentVersionSavedResource.d.ts +65 -0
  84. package/dist/models/AgentVersionSavedResource.js +67 -0
  85. package/dist/models/AgentWebhookList.d.ts +33 -0
  86. package/dist/models/AgentWebhookList.js +51 -0
  87. package/dist/models/AgentWebhookView.d.ts +76 -0
  88. package/dist/models/AgentWebhookView.js +78 -0
  89. package/dist/models/ConversationDetail.d.ts +6 -0
  90. package/dist/models/ConversationDetail.js +2 -0
  91. package/dist/models/ConversationView.d.ts +6 -0
  92. package/dist/models/ConversationView.js +2 -0
  93. package/dist/models/ErrorDetailItem.d.ts +3 -0
  94. package/dist/models/FileNodeView.d.ts +7 -0
  95. package/dist/models/FileNodeView.js +3 -0
  96. package/dist/models/QueueMessageInput.d.ts +6 -0
  97. package/dist/models/QueueMessageInput.js +2 -0
  98. package/dist/models/RotatedWebhookSecretView.d.ts +58 -0
  99. package/dist/models/RotatedWebhookSecretView.js +69 -0
  100. package/dist/models/SaveWarningView.d.ts +44 -0
  101. package/dist/models/SaveWarningView.js +58 -0
  102. package/dist/models/ShareSkippedResource.d.ts +41 -0
  103. package/dist/models/ShareSkippedResource.js +54 -0
  104. package/dist/models/WebhookSecretPutBody.d.ts +32 -0
  105. package/dist/models/WebhookSecretPutBody.js +50 -0
  106. package/dist/models/WebhookSecretStateView.d.ts +52 -0
  107. package/dist/models/WebhookSecretStateView.js +64 -0
  108. package/dist/models/WebhookSecretValueView.d.ts +32 -0
  109. package/dist/models/WebhookSecretValueView.js +51 -0
  110. package/dist/models/WebhookWarning.d.ts +44 -0
  111. package/dist/models/WebhookWarning.js +58 -0
  112. package/dist/models/index.d.ts +10 -0
  113. package/dist/models/index.js +10 -0
  114. package/package.json +1 -1
  115. package/src/apis/AgentsApi.ts +366 -11
  116. package/src/apis/ConversationsApi.ts +9 -2
  117. package/src/client.ts +3 -2
  118. package/src/compose/deploy.ts +71 -10
  119. package/src/compose/errors.ts +4 -0
  120. package/src/compose/settingsTransport.ts +78 -131
  121. package/src/compose/transport.ts +10 -2
  122. package/src/compose/webhook.ts +49 -45
  123. package/src/compose/webhookSecrets.ts +227 -179
  124. package/src/index.ts +2 -1
  125. package/src/models/AgentConversationDetail.ts +16 -0
  126. package/src/models/AgentConversationView.ts +16 -0
  127. package/src/models/AgentResource.ts +15 -0
  128. package/src/models/AgentVersionSavedResource.ts +119 -0
  129. package/src/models/AgentWebhookList.ts +74 -0
  130. package/src/models/AgentWebhookView.ts +129 -0
  131. package/src/models/ConversationDetail.ts +8 -0
  132. package/src/models/ConversationView.ts +8 -0
  133. package/src/models/ErrorDetailItem.ts +3 -0
  134. package/src/models/FileNodeView.ts +16 -0
  135. package/src/models/QueueMessageInput.ts +8 -0
  136. package/src/models/RotatedWebhookSecretView.ts +103 -0
  137. package/src/models/SaveWarningView.ts +84 -0
  138. package/src/models/ShareSkippedResource.ts +78 -0
  139. package/src/models/WebhookSecretPutBody.ts +66 -0
  140. package/src/models/WebhookSecretStateView.ts +94 -0
  141. package/src/models/WebhookSecretValueView.ts +66 -0
  142. package/src/models/WebhookWarning.ts +84 -0
  143. package/src/models/index.ts +10 -0
@@ -2,7 +2,6 @@
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { AgentsApi } from "../apis/AgentsApi.js";
4
4
  import { ConversationsApi } from "../apis/ConversationsApi.js";
5
- import { CustomAPIsApi } from "../apis/CustomAPIsApi.js";
6
5
  import { ResponsesApi } from "../apis/ResponsesApi.js";
7
6
  import { TriggersApi } from "../apis/TriggersApi.js";
8
7
  import { FetchError, ResponseError } from "../runtime.js";
@@ -10,8 +9,8 @@ import { answerClarify, postToolResults, reconnect, streamResponse } from "../st
10
9
  import { NotSupportedByServerError, RunError, UserError } from "./errors.js";
11
10
  import { chunksFromUiMessage, fromUiChunk } from "./events.js";
12
11
  import { VERSION_NOTE } from "./transport.js";
13
- import { secretCredentialName, urlProblem } from "./webhook.js";
14
- import { secretBackend } from "./webhookSecrets.js";
12
+ import { withoutLegacyCredentials } from "./webhook.js";
13
+ import { createMissingSecrets } from "./webhookSecrets.js";
15
14
  import { triggerToken } from "./trigger.js";
16
15
  const PAGE = 100;
17
16
  /** A trigger row the server paused after failed turns has a `pausedReason` starting with this (PAUSED_AUTO_PREFIX). */
@@ -201,38 +200,14 @@ class Finished {
201
200
  }
202
201
  close() { }
203
202
  }
204
- /** `settings` for a new agent's first write: no `webhooks` (the server checks them against the agent's bound
205
- * credentials, and a new agent has none yet) and no `sdk_hash` (it covers the webhooks, so an agent left in this
206
- * state would otherwise read as deployed and never get them). */
203
+ /** `settings` for a new agent's first write: no `webhooks` (written by the second write, whose envelope carries the
204
+ * save's webhook warnings) and no `sdk_hash` (it covers the webhooks, so an agent left in this state would otherwise
205
+ * read as deployed and never get them). */
207
206
  function withoutWebhooks(settings) {
208
207
  const { webhooks: _webhooks, ...out } = settings;
209
208
  const { sdk_hash: _hash, ...metadata } = settings["metadata"];
210
209
  return { ...out, metadata };
211
210
  }
212
- function hooksOf(settings) {
213
- const hooks = settings["webhooks"];
214
- return Array.isArray(hooks) ? hooks.filter((h) => typeof h === "object" && h !== null && !Array.isArray(h)) : [];
215
- }
216
- function sdkNamed(agentId, hook) {
217
- const url = hook["url"];
218
- return typeof url === "string" && urlProblem(url) === null &&
219
- hook["secret_credential"] === secretCredentialName(agentId, url);
220
- }
221
- /** `settings` as a definition writes them: a webhook whose `secret_credential` is the one `deploy` filled in loses it
222
- * again, so the stored `sdk_hash` (computed without it) still matches. */
223
- function asDefined(agentId, settings) {
224
- if (!hooksOf(settings).some((h) => sdkNamed(agentId, h)))
225
- return settings;
226
- return {
227
- ...settings,
228
- webhooks: settings["webhooks"].map((h) => {
229
- if (typeof h !== "object" || h === null || !sdkNamed(agentId, h))
230
- return h;
231
- const { secret_credential: _name, ...rest } = h;
232
- return rest;
233
- }),
234
- };
235
- }
236
211
  /** The deploy response's `triggerTokens` (the server shows each token once); never logged. An entry missing a field
237
212
  * is skipped with a warning that names the trigger, never the token. */
238
213
  function triggerTokens(resource) {
@@ -250,6 +225,13 @@ function triggerTokens(resource) {
250
225
  }
251
226
  return out;
252
227
  }
228
+ /** A v2 agent write's `webhookWarnings` (`host_unresolvable`). */
229
+ function logWebhookWarnings(agentId, resource) {
230
+ var _a;
231
+ const items = (_a = resource === null || resource === void 0 ? void 0 : resource.webhookWarnings) !== null && _a !== void 0 ? _a : [];
232
+ for (const w of items)
233
+ console.warn(`agent ${agentId}: webhook warning ${w === null || w === void 0 ? void 0 : w.code} at ${w === null || w === void 0 ? void 0 : w.path}: ${w === null || w === void 0 ? void 0 : w.message}`);
234
+ }
253
235
  function isNotFound(err) {
254
236
  return err instanceof ResponseError && err.response.status === 404;
255
237
  }
@@ -286,9 +268,7 @@ export class SettingsTransport {
286
268
  this.agents = new AgentsApi(config);
287
269
  this.conversations = new ConversationsApi(config);
288
270
  this.responses = new ResponsesApi(config);
289
- this.customApis = new CustomAPIsApi(config);
290
271
  this.triggers = new TriggersApi(config);
291
- this.secrets = secretBackend({ customApis: this.customApis });
292
272
  }
293
273
  // -- agents ---------------------------------------------------------------------------------------------
294
274
  async findAgents(sdkName) {
@@ -317,13 +297,12 @@ export class SettingsTransport {
317
297
  return this.remote(resource, await this.instructions(agentId));
318
298
  }
319
299
  async createAgent(agent) {
320
- var _a, _b, _c, _d;
321
- let settings = agent.toSettings();
322
- let missing = [];
300
+ var _a, _b, _c, _d, _e;
301
+ const settings = agent.toSettings();
323
302
  const webhooks = ((_a = settings["webhooks"]) !== null && _a !== void 0 ? _a : []);
324
- // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
325
- // without them, bind the Custom APIs they name, then write the settings in full.
326
- const { bind, unbound } = await this.webhookCredentials(webhooks);
303
+ // Webhooks are written in a second step, whose settings envelope carries the save's webhook warnings
304
+ // (webhooks_disabled, host_unresolvable). No save creates a webhook's signing secret: deploy() does that after the
305
+ // agent is live (createWebhookSecrets).
327
306
  let resource;
328
307
  try {
329
308
  resource = await this.agents.createAgent({
@@ -352,23 +331,14 @@ export class SettingsTransport {
352
331
  throw err;
353
332
  }
354
333
  if (webhooks.length > 0) {
355
- for (const { path, name, customApiId } of bind)
356
- await this.bind(resource.id, path, name, customApiId);
357
- ({ settings, missing } = await this.withSecretCredentials(resource.id, settings));
358
334
  try {
359
335
  envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
360
336
  }
361
337
  catch (err) {
362
- const invalid = await invalidSettings(err);
363
- if (invalid === null)
364
- throw err;
365
- throw new UserError([invalid.message, ...unbound].join("; "), invalid.issues);
338
+ throw (_c = (await invalidSettings(err))) !== null && _c !== void 0 ? _c : err;
366
339
  }
367
340
  }
368
341
  warnings = checkWarnings(envelope, settings);
369
- // Accepted unchecked (webhooks switched off): refused once they are on.
370
- for (const sentence of unbound)
371
- console.warn(`agent ${resource.id}: ${sentence}`);
372
342
  checkMetadata(envelope, agent);
373
343
  live = await this.goLive(resource.id, versionStateOf(resource), agent);
374
344
  }
@@ -386,90 +356,75 @@ export class SettingsTransport {
386
356
  agentId: resource.id,
387
357
  name: agent.name,
388
358
  instructions: agent.instructions,
389
- settings: asDefined(resource.id, { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) }),
359
+ settings: withoutLegacyCredentials({ ...((_d = envelope.settings) !== null && _d !== void 0 ? _d : {}) }),
390
360
  warnings,
391
- ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
392
- triggerTokens: (_d = live.triggerTokens) !== null && _d !== void 0 ? _d : [],
361
+ triggerTokens: (_e = live.triggerTokens) !== null && _e !== void 0 ? _e : [],
393
362
  }, live.liveVersion, versionStateOf(resource));
394
363
  }
395
- /** `settings` with each webhook that names no `secret_credential` given the one `client.webhooks` keeps for the
396
- * agent and host (stored, with a random secret nobody holds, when there is none yet), and the URLs of those
397
- * webhooks still without a secret set by `client.webhooks`. */
398
- async withSecretCredentials(agentId, settings) {
399
- const hooks = hooksOf(settings);
400
- if (hooks.every((h) => "secret_credential" in h))
401
- return { settings, missing: [] };
402
- const filled = [];
403
- const missing = [];
404
- for (const h of settings["webhooks"]) {
405
- if (typeof h !== "object" || h === null || "secret_credential" in h) {
406
- filled.push(h);
407
- continue;
408
- }
409
- const url = h["url"];
410
- const { name, status } = await this.secrets.ensure(agentId, url);
411
- filled.push({ ...h, secret_credential: name });
412
- if (status === "missing")
413
- missing.push(url);
414
- }
415
- return { settings: { ...settings, webhooks: filled }, missing };
416
- }
417
- /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
418
- * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
419
- * checks credentials). */
420
- async webhookCredentials(webhooks) {
421
- const bind = [];
422
- const unbound = [];
423
- const seen = new Set();
424
- for (const [i, hook] of webhooks.entries()) {
425
- const name = hook.secret_credential;
426
- if (name === undefined || seen.has(name))
427
- continue; // left out: deploy fills in the one client.webhooks keeps
428
- seen.add(name);
429
- const path = `webhooks.${i}.secret_credential`;
430
- const ids = await this.customApiIds(name);
431
- if (ids.length === 1) {
432
- bind.push({ path, name, customApiId: ids[0] });
364
+ /**
365
+ * The webhook URLs of the agent.json last deployed, read before a deploy writes: the live (or paused) version's,
366
+ * `GET /v2/agents/{agentId}/versions/{version}` (its `agent.json` file). Without versions on the server, the
367
+ * agent's settings (`GET /v1/agents/{agentId}/settings`), which are what is deployed there. An empty set when
368
+ * nothing was ever deployed; null, with a warning, when it cannot be read.
369
+ */
370
+ async deployedWebhookUrls(agentId, liveVersion, versionState) {
371
+ var _a, _b, _c;
372
+ let settings;
373
+ try {
374
+ if (versionState === undefined) {
375
+ settings = (_a = (await this.agents.getAgentSettings({ agentId })).settings) !== null && _a !== void 0 ? _a : {};
433
376
  }
434
- else if (ids.length === 0) {
435
- unbound.push(`${path}: you have no Custom API named '${name}' to bind to the new agent; create it, then ` +
436
- "deploy again");
377
+ else if (liveVersion === undefined) {
378
+ return new Set();
437
379
  }
438
380
  else {
439
- unbound.push(`${path}: ${ids.length} of your Custom APIs are named '${name}', so none was bound to the new ` +
440
- "agent; rename or delete all but one, then deploy again");
381
+ const files = (_b = (await this.agents.getVersion({ agentId, version: liveVersion })).files) !== null && _b !== void 0 ? _b : [];
382
+ const data = (_c = files.find((f) => String(f.path).replace(/^\/+/, "") === "agent.json")) === null || _c === void 0 ? void 0 : _c.data;
383
+ settings = data ? JSON.parse(data) : {};
441
384
  }
442
385
  }
443
- return { bind, unbound };
444
- }
445
- /** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
446
- async customApiIds(name) {
447
- const ids = [];
448
- let offset = 0;
449
- for (;;) {
450
- const result = await this.customApis.listCustomApis({ q: name, limit: PAGE, offset });
451
- const items = result.data;
452
- for (const item of items)
453
- if (item.name === name)
454
- ids.push(item.id);
455
- offset += items.length;
456
- if (items.length === 0 || !result.hasMore)
457
- return ids;
386
+ catch (err) {
387
+ const why = err instanceof ResponseError ? `HTTP ${err.response.status}` : err instanceof SyntaxError ? "not JSON" : String(err);
388
+ console.warn(`agent ${agentId}: could not read the deployed agent.json (${why}), so this deploy creates no ` +
389
+ "webhook secret; create any you need with client.webhooks.createSecret");
390
+ return null;
391
+ }
392
+ const hooks = settings === null || settings === void 0 ? void 0 : settings.webhooks;
393
+ const out = new Set();
394
+ if (Array.isArray(hooks)) {
395
+ for (const h of hooks) {
396
+ const url = h === null || h === void 0 ? void 0 : h.url;
397
+ if (typeof url === "string")
398
+ out.add(url);
399
+ }
458
400
  }
401
+ return out;
459
402
  }
460
- async bind(agentId, path, name, customApiId) {
403
+ /**
404
+ * Create the signing secret of each webhook in `added` (the URLs this deploy added) whose `secretStatus` is
405
+ * `missing` (`POST .../webhooks/{webhookKey}/secret`); resolves to the new secrets by URL and the URLs of `agent`'s
406
+ * webhooks still without one. A webhook deployed before whose secret is missing is reported, never given one. An
407
+ * existing secret is never rotated or overwritten. Nothing here fails the deploy: a failure is logged (never with a
408
+ * secret) and the webhook reported missing.
409
+ */
410
+ async createWebhookSecrets(agentId, agent, added = new Set()) {
461
411
  var _a;
412
+ const urls = ((_a = agent.webhooks) !== null && _a !== void 0 ? _a : []).map((h) => h.url);
413
+ let result;
462
414
  try {
463
- await this.customApis.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
415
+ result = await createMissingSecrets(this.agents, agentId, urls, added);
464
416
  }
465
417
  catch (err) {
466
- const status = err instanceof ResponseError ? err.response.status : 0;
467
- if (!(err instanceof ResponseError) || status < 400 || status >= 500)
468
- throw err;
469
- const message = (_a = (await chatError(err))) === null || _a === void 0 ? void 0 : _a["message"];
470
- throw new UserError(`${path}: could not bind the Custom API '${name}' to the new agent: ` +
471
- (typeof message === "string" && message ? message : `HTTP ${status}`));
418
+ const code = err instanceof ResponseError ? err.response.status : "error";
419
+ console.warn(`agent ${agentId}: could not read its webhooks to create their signing secrets (HTTP ${code}); ` +
420
+ "check client.webhooks.list(agentId) and createSecret for each");
421
+ return { created: {}, missing: [...urls] };
422
+ }
423
+ for (const url of result.missing) {
424
+ console.warn(`agent ${agentId}: webhook ${url} has no signing secret, so nothing is sent to it; create one ` +
425
+ "with client.webhooks.createSecret(agentId, url)");
472
426
  }
427
+ return result;
473
428
  }
474
429
  async updateAgent(agentId, agent) {
475
430
  var _a, _b, _c;
@@ -496,15 +451,6 @@ export class SettingsTransport {
496
451
  if (instructionsChanged) {
497
452
  await this.agents.putInstructions({ agentId, instructionsBody: { data: agent.instructions } });
498
453
  }
499
- let missing;
500
- try {
501
- ({ settings, missing } = await this.withSecretCredentials(agentId, settings));
502
- }
503
- catch (err) {
504
- if (instructionsChanged)
505
- await this.restore(agentId, null, previousInstructions);
506
- throw err;
507
- }
508
454
  let envelope;
509
455
  try {
510
456
  envelope = await this.agents.putAgentSettings({ agentId, body: settings });
@@ -536,9 +482,8 @@ export class SettingsTransport {
536
482
  agentId,
537
483
  name: agent.name,
538
484
  instructions: agent.instructions,
539
- settings: asDefined(agentId, { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) }),
485
+ settings: withoutLegacyCredentials({ ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) }),
540
486
  warnings,
541
- ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
542
487
  triggerTokens: (_c = live.triggerTokens) !== null && _c !== void 0 ? _c : [],
543
488
  }, live.liveVersion, versionStateOf(current));
544
489
  }
@@ -547,6 +492,7 @@ export class SettingsTransport {
547
492
  async goLive(agentId, versionState, agent) {
548
493
  if (versionState === undefined) {
549
494
  const resource = await this.agents.deployAgent({ agentId }); // idempotent; moves an adopted draft to deployed
495
+ logWebhookWarnings(agentId, resource);
550
496
  return { triggerTokens: triggerTokens(resource) };
551
497
  }
552
498
  return this.publish(agentId, VERSION_NOTE);
@@ -581,8 +527,9 @@ export class SettingsTransport {
581
527
  const live = (_b = resource.liveVersion) !== null && _b !== void 0 ? _b : undefined;
582
528
  if (live !== undefined)
583
529
  deployed.add(`${agentId} v${live}`);
584
- return live === undefined ? { triggerTokens: triggerTokens(resource) }
585
- : { liveVersion: live, triggerTokens: triggerTokens(resource) };
530
+ logWebhookWarnings(agentId, resource);
531
+ const minted = { triggerTokens: triggerTokens(resource) };
532
+ return live === undefined ? minted : { liveVersion: live, ...minted };
586
533
  }
587
534
  /** Read the trigger rows of an unchanged live agent and warn, once per process, when they do not match
588
535
  * `agent.triggers`. Never deploys: an unchanged definition writes nothing, and the rows may differ because the
@@ -810,8 +757,9 @@ export class SettingsTransport {
810
757
  if (instructions !== null) {
811
758
  await this.agents.putInstructions({ agentId, instructionsBody: { data: instructions } });
812
759
  }
813
- if (settings !== null)
760
+ if (settings !== null) {
814
761
  await this.agents.putAgentSettings({ agentId, body: settings });
762
+ }
815
763
  }
816
764
  catch (err) {
817
765
  console.warn(`could not restore agent ${agentId} after rejected settings: ${err}`);
@@ -824,7 +772,7 @@ export class SettingsTransport {
824
772
  var _a;
825
773
  const remote = {
826
774
  agentId: resource.id, name: resource.name, instructions, warnings: [],
827
- settings: asDefined(resource.id, { ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }),
775
+ settings: withoutLegacyCredentials({ ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }),
828
776
  };
829
777
  // Left out, not set to undefined, when the server has no versions: the shape a 0.3 transport returned.
830
778
  if (resource.liveVersion !== undefined && resource.liveVersion !== null)
@@ -21,8 +21,8 @@ export interface RemoteAgent {
21
21
  /** `"live"`, `"paused"` or `"not_live"` (`AgentResource.versionState`); undefined when the server has no versions,
22
22
  * in which case deploy() never calls `publish`. */
23
23
  versionState?: string;
24
- /** URLs of the webhooks this write left without a secret set by `client.webhooks` (a placeholder secret nobody
25
- * holds stands in until `client.webhooks.setSecret`); left out when there are none. */
24
+ /** URLs of webhooks the write left without a signing secret; `deploy` adds them to
25
+ * `Deployment.webhooksMissingSecret`. The SDK's own transport leaves it out (see `createWebhookSecrets`). */
26
26
  webhooksMissingSecret?: string[];
27
27
  /** The bearer tokens the write's deploy minted (the server shows each once). */
28
28
  triggerTokens?: MintedTriggerToken[];
@@ -64,6 +64,16 @@ export interface Transport {
64
64
  * `agent.triggers` (a deploy whose trigger reconcile failed went live without them, or the owner changed them) it
65
65
  * warns, naming the fix. It never deploys: an unchanged definition writes nothing. */
66
66
  checkTriggers?(agentId: string, agent: Agent<OutputType | undefined>, liveVersion?: number): Promise<void>;
67
+ /** Optional: deploy() calls it before it writes, for the webhook URLs of the agent.json last deployed (an empty set
68
+ * when nothing was deployed; null when unknown, so nothing counts as added). */
69
+ deployedWebhookUrls?(agentId: string, liveVersion?: number, versionState?: string): Promise<Set<string> | null>;
70
+ /** Optional: deploy() calls it after a deploy of an agent with webhooks. It creates the signing secret of each
71
+ * webhook in `added` (the URLs the deploy added) that has none (never rotating or overwriting one) and resolves to
72
+ * the new secrets by URL and the URLs of the agent's webhooks still without one. */
73
+ createWebhookSecrets?(agentId: string, agent: Agent<OutputType | undefined>, added: ReadonlySet<string>): Promise<{
74
+ created: Record<string, string>;
75
+ missing: string[];
76
+ }>;
67
77
  startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
68
78
  answerClarify(conversationId: string, requestId: string, answers: Record<string, unknown>, signal?: AbortSignal): Promise<TurnStream>;
69
79
  resume(conversationId: string, responseId: string, lastEventId: string | null, signal?: AbortSignal): Promise<TurnStream>;
@@ -1,15 +1,16 @@
1
1
  import type { WebhookEventType } from "../webhooks.js";
2
- /** Where the agent reports a finished, failed or paused turn (agent.json `webhooks[]`). */
2
+ /** Where the agent reports a finished, failed or paused turn (agent.json `webhooks[]`). The deploy that adds it
3
+ * creates its signing secret and returns it once (`Deployment.webhookSecrets[url]`); nothing is delivered to a
4
+ * webhook without a secret. The secret belongs to the exact URL: a changed URL is a new webhook with a new secret. */
3
5
  export interface Webhook {
4
6
  /** An `https://` URL on port 443 with a DNS host; a query string is allowed. */
5
7
  url: string;
6
8
  /** 1 to 4 distinct events. `approval.requested` is reserved: accepted, not sent yet. */
7
9
  events: WebhookEventType[];
8
10
  /**
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
+ * Ignored: never sent to the server, which keeps each webhook's signing secret itself.
11
12
  *
12
- * @deprecated Use `client.webhooks.setSecret` instead of creating a Custom API and naming it here.
13
+ * @deprecated Leave it out; `deploy` creates the webhook's secret.
13
14
  */
14
15
  secretCredential?: string;
15
16
  }
@@ -19,16 +20,12 @@ export declare const WEBHOOKS_MAX = 5;
19
20
  export declare function urlProblem(url: string): string | null;
20
21
  /** The server's pure `webhooks` rules (types first); throws `UserError` naming the agent.json path. */
21
22
  export declare function checkWebhooks(webhooks: unknown): void;
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). */
23
+ /** Only `url` and `events` (a copy): `secretCredential` is ignored, so it is dropped here. */
24
24
  export declare function copyWebhooks(webhooks: readonly Webhook[]): Webhook[];
25
25
  export declare function webhooksJson(webhooks: readonly Webhook[]): Record<string, unknown>[];
26
26
  /** The host of an allowed webhook URL, lowercased, without a trailing dot or a port. */
27
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;
28
+ /** Whether `name` is the `secret_credential` the 0.5.x SDK filled in for `url`'s host, for any agent. */
29
+ export declare function isLegacyCredentialName(name: unknown, url: string): boolean;
30
+ /** `settings` with the `secret_credential` the 0.5.x SDK filled in removed from each webhook. */
31
+ export declare function withoutLegacyCredentials(settings: Record<string, unknown>): Record<string, unknown>;
@@ -1,20 +1,21 @@
1
1
  /**
2
2
  * `webhooks` entries of `agent.json`, checked locally with the server's cheap rules (as the Python SDK does).
3
3
  *
4
- * The server (`claw_common/agent_settings/webhooks.py`) also checks that the host resolves to a public address and
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`.
4
+ * The server (`claw_common/agent_settings/webhooks.py`) also checks that the host resolves to a public address; that
5
+ * needs I/O and stays on the server, which refuses the save with a 422 that `deploy` throws as `UserError`.
7
6
  *
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`).
7
+ * A webhook is identified by its URL. Its signing secret lives in the server's webhook secret store (panja #1857):
8
+ * `deploy` creates it for each webhook it adds and returns it once (`Deployment.webhookSecrets`);
9
+ * `client.webhooks` views, rotates, sets and deletes it.
10
+ *
11
+ * `secretCredential` is deprecated and ignored: the server no longer reads the vault for signing. It is still
12
+ * accepted and never sent, so `agent.json` stays clean.
11
13
  */
12
14
  import { createHash } from "node:crypto";
13
15
  import { UserError } from "./errors.js";
14
16
  import { WEBHOOK_EVENTS } from "../webhooks.js";
15
17
  export const WEBHOOKS_MAX = 5;
16
18
  const WEBHOOK_URL_MAX = 2048;
17
- const SECRET_CREDENTIAL_MAX = 256;
18
19
  const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
19
20
  // A last label that is a number (decimal, or 0x hex) makes resolvers read the whole host as an IPv4 address.
20
21
  const NUMERIC_LABEL = /^(?:[0-9]+|0x[0-9a-f]*)$/;
@@ -146,7 +147,8 @@ export function checkWebhooks(webhooks) {
146
147
  throw new UserError(where + "secretCredential: must be a string");
147
148
  }
148
149
  // Python's Webhook is extra="forbid": a key dropped silently (a misplaced secret) would never verify.
149
- const extra = Object.keys(hook).find((k) => k !== "url" && k !== "events" && k !== "secretCredential");
150
+ // A webhook is identified by its URL: a `name` is refused here, as the server does.
151
+ const extra = Object.keys(hook).find((k) => !["url", "events", "secretCredential"].includes(k));
150
152
  if (extra !== undefined)
151
153
  throw new UserError(where + extra + ": Extra inputs are not permitted");
152
154
  const problem = urlProblem(url);
@@ -160,11 +162,6 @@ export function checkWebhooks(webhooks) {
160
162
  }
161
163
  if (new Set(events).size !== events.length)
162
164
  throw new UserError(where + "events: events must not repeat an event.");
163
- const n = typeof secretCredential === "string" ? codePoints(secretCredential) : 1;
164
- if (n < 1 || n > SECRET_CREDENTIAL_MAX) {
165
- throw new UserError(where + "secret_credential: secret_credential must be the name of a vault credential " +
166
- `(1 to ${SECRET_CREDENTIAL_MAX} characters).`);
167
- }
168
165
  const key = urlKey(url);
169
166
  if (seen.has(key)) {
170
167
  throw new UserError(where + "url: webhooks must not list the same url twice; put all its events on one entry.");
@@ -172,47 +169,30 @@ export function checkWebhooks(webhooks) {
172
169
  seen.add(key);
173
170
  });
174
171
  }
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
+ /** Only `url` and `events` (a copy): `secretCredential` is ignored, so it is dropped here. */
177
173
  export function copyWebhooks(webhooks) {
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
+ return webhooks.map((h) => ({ url: h.url, events: [...h.events] }));
185
175
  }
186
176
  export function webhooksJson(webhooks) {
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
- });
177
+ return webhooks.map((h) => ({ url: h.url, events: [...h.events] }));
193
178
  }
194
179
  /** The host of an allowed webhook URL, lowercased, without a trailing dot or a port. */
195
180
  export function webhookHost(url) {
196
181
  return stripTrailingDots(hostPort(split(url)[1])[0]);
197
182
  }
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;
183
+ // -- 0.5.x compatibility ----------------------------------------------------------------------------------------
184
+ // The 0.5.x SDK filled in `secret_credential` as `webhook-secret:<agentId>:<host>` on every webhook it deployed. An
185
+ // agent it deployed still has that name in agent.json; the deploy reads such a webhook without it, so the stored
186
+ // `sdk_hash` (computed without it) still matches and the agent does not read as edited outside the SDK.
187
+ const LEGACY_PREFIX = "webhook-secret:";
201
188
  function hashedHost(host) {
202
189
  return "sha256-" + createHash("sha256").update(host, "utf8").digest("hex").slice(0, 32);
203
190
  }
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)
191
+ /** Whether `name` is the `secret_credential` the 0.5.x SDK filled in for `url`'s host, for any agent. */
192
+ export function isLegacyCredentialName(name, url) {
193
+ if (typeof name !== "string" || !name.startsWith(LEGACY_PREFIX) || urlProblem(url) !== null)
214
194
  return false;
215
- const rest = name.slice(SECRET_NAME_PREFIX.length);
195
+ const rest = name.slice(LEGACY_PREFIX.length);
216
196
  const at = rest.lastIndexOf(":");
217
197
  if (at <= 0)
218
198
  return false;
@@ -221,3 +201,26 @@ export function isSdkCredentialName(name, url) {
221
201
  const host = webhookHost(url);
222
202
  return !agentId.includes(":") && (tail === host || tail === hashedHost(host));
223
203
  }
204
+ /** `settings` with the `secret_credential` the 0.5.x SDK filled in removed from each webhook. */
205
+ export function withoutLegacyCredentials(settings) {
206
+ const hooks = settings["webhooks"];
207
+ if (!Array.isArray(hooks))
208
+ return settings;
209
+ const legacy = (h) => {
210
+ if (typeof h !== "object" || h === null)
211
+ return false;
212
+ const { url, secret_credential: name } = h;
213
+ return typeof url === "string" && isLegacyCredentialName(name, url);
214
+ };
215
+ if (!hooks.some(legacy))
216
+ return settings;
217
+ return {
218
+ ...settings,
219
+ webhooks: hooks.map((h) => {
220
+ if (!legacy(h))
221
+ return h;
222
+ const { secret_credential: _dropped, ...rest } = h;
223
+ return rest;
224
+ }),
225
+ };
226
+ }