sarvam-agents-client 0.3.2 → 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.
Files changed (157) hide show
  1. package/README.md +36 -23
  2. package/dist/apis/AgentConversationsApi.d.ts +2 -2
  3. package/dist/apis/AgentConversationsApi.js +2 -2
  4. package/dist/apis/AgentsApi.d.ts +195 -5
  5. package/dist/apis/AgentsApi.js +478 -5
  6. package/dist/apis/ArtifactsApi.d.ts +8 -4
  7. package/dist/apis/ArtifactsApi.js +8 -4
  8. package/dist/apis/ConversationsApi.d.ts +2 -0
  9. package/dist/apis/ConversationsApi.js +6 -0
  10. package/dist/client.d.ts +16 -0
  11. package/dist/client.js +21 -0
  12. package/dist/compose/deploy.d.ts +37 -7
  13. package/dist/compose/deploy.js +105 -19
  14. package/dist/compose/errors.d.ts +1 -1
  15. package/dist/compose/errors.js +1 -1
  16. package/dist/compose/index.d.ts +1 -1
  17. package/dist/compose/index.js +2 -1
  18. package/dist/compose/run.d.ts +5 -1
  19. package/dist/compose/run.js +9 -9
  20. package/dist/compose/settingsTransport.d.ts +14 -0
  21. package/dist/compose/settingsTransport.js +151 -14
  22. package/dist/compose/transport.d.ts +14 -0
  23. package/dist/compose/transport.js +3 -0
  24. package/dist/compose/webhook.d.ts +18 -3
  25. package/dist/compose/webhook.js +59 -10
  26. package/dist/compose/webhookSecrets.d.ts +64 -0
  27. package/dist/compose/webhookSecrets.js +255 -0
  28. package/dist/esm/apis/AgentConversationsApi.d.ts +2 -2
  29. package/dist/esm/apis/AgentConversationsApi.js +2 -2
  30. package/dist/esm/apis/AgentsApi.d.ts +195 -5
  31. package/dist/esm/apis/AgentsApi.js +478 -5
  32. package/dist/esm/apis/ArtifactsApi.d.ts +8 -4
  33. package/dist/esm/apis/ArtifactsApi.js +8 -4
  34. package/dist/esm/apis/ConversationsApi.d.ts +2 -0
  35. package/dist/esm/apis/ConversationsApi.js +6 -0
  36. package/dist/esm/client.d.ts +16 -0
  37. package/dist/esm/client.js +17 -0
  38. package/dist/esm/compose/deploy.d.ts +37 -7
  39. package/dist/esm/compose/deploy.js +105 -20
  40. package/dist/esm/compose/errors.d.ts +1 -1
  41. package/dist/esm/compose/errors.js +1 -1
  42. package/dist/esm/compose/index.d.ts +1 -1
  43. package/dist/esm/compose/index.js +1 -1
  44. package/dist/esm/compose/run.d.ts +5 -1
  45. package/dist/esm/compose/run.js +9 -9
  46. package/dist/esm/compose/settingsTransport.d.ts +14 -0
  47. package/dist/esm/compose/settingsTransport.js +151 -14
  48. package/dist/esm/compose/transport.d.ts +14 -0
  49. package/dist/esm/compose/transport.js +2 -1
  50. package/dist/esm/compose/webhook.d.ts +18 -3
  51. package/dist/esm/compose/webhook.js +55 -9
  52. package/dist/esm/compose/webhookSecrets.d.ts +64 -0
  53. package/dist/esm/compose/webhookSecrets.js +250 -0
  54. package/dist/esm/index.d.ts +3 -0
  55. package/dist/esm/index.js +3 -0
  56. package/dist/esm/models/AgentAttachmentDiff.d.ts +50 -0
  57. package/dist/esm/models/AgentAttachmentDiff.js +55 -0
  58. package/dist/esm/models/AgentContentsResource.d.ts +71 -0
  59. package/dist/esm/models/AgentContentsResource.js +70 -0
  60. package/dist/esm/models/AgentDeploy.d.ts +33 -0
  61. package/dist/esm/models/AgentDeploy.js +41 -0
  62. package/dist/esm/models/AgentDraftResource.d.ts +51 -0
  63. package/dist/esm/models/AgentDraftResource.js +52 -0
  64. package/dist/esm/models/AgentFileContent.d.ts +38 -0
  65. package/dist/esm/models/AgentFileContent.js +47 -0
  66. package/dist/esm/models/AgentHistoryResource.d.ts +71 -0
  67. package/dist/esm/models/AgentHistoryResource.js +66 -0
  68. package/dist/esm/models/AgentResource.d.ts +21 -0
  69. package/dist/esm/models/AgentResource.js +12 -0
  70. package/dist/esm/models/AgentSkillFilePin.d.ts +44 -0
  71. package/dist/esm/models/AgentSkillFilePin.js +51 -0
  72. package/dist/esm/models/AgentSubagentEntry.d.ts +38 -0
  73. package/dist/esm/models/AgentSubagentEntry.js +47 -0
  74. package/dist/esm/models/AgentVersionCreate.d.ts +32 -0
  75. package/dist/esm/models/AgentVersionCreate.js +41 -0
  76. package/dist/esm/models/AgentVersionDiffResource.d.ts +87 -0
  77. package/dist/esm/models/AgentVersionDiffResource.js +78 -0
  78. package/dist/esm/models/AgentVersionPick.d.ts +32 -0
  79. package/dist/esm/models/AgentVersionPick.js +43 -0
  80. package/dist/esm/models/AgentVersionResource.d.ts +56 -0
  81. package/dist/esm/models/AgentVersionResource.js +57 -0
  82. package/dist/esm/models/AppResource.d.ts +12 -0
  83. package/dist/esm/models/AppResource.js +4 -0
  84. package/dist/esm/models/ResponseInput.d.ts +6 -0
  85. package/dist/esm/models/ResponseInput.js +2 -0
  86. package/dist/esm/models/SkillUpdateResource.d.ts +38 -0
  87. package/dist/esm/models/SkillUpdateResource.js +47 -0
  88. package/dist/esm/models/index.d.ts +13 -0
  89. package/dist/esm/models/index.js +13 -0
  90. package/dist/index.d.ts +3 -0
  91. package/dist/index.js +6 -0
  92. package/dist/models/AgentAttachmentDiff.d.ts +50 -0
  93. package/dist/models/AgentAttachmentDiff.js +62 -0
  94. package/dist/models/AgentContentsResource.d.ts +71 -0
  95. package/dist/models/AgentContentsResource.js +77 -0
  96. package/dist/models/AgentDeploy.d.ts +33 -0
  97. package/dist/models/AgentDeploy.js +48 -0
  98. package/dist/models/AgentDraftResource.d.ts +51 -0
  99. package/dist/models/AgentDraftResource.js +59 -0
  100. package/dist/models/AgentFileContent.d.ts +38 -0
  101. package/dist/models/AgentFileContent.js +54 -0
  102. package/dist/models/AgentHistoryResource.d.ts +71 -0
  103. package/dist/models/AgentHistoryResource.js +74 -0
  104. package/dist/models/AgentResource.d.ts +21 -0
  105. package/dist/models/AgentResource.js +13 -1
  106. package/dist/models/AgentSkillFilePin.d.ts +44 -0
  107. package/dist/models/AgentSkillFilePin.js +58 -0
  108. package/dist/models/AgentSubagentEntry.d.ts +38 -0
  109. package/dist/models/AgentSubagentEntry.js +54 -0
  110. package/dist/models/AgentVersionCreate.d.ts +32 -0
  111. package/dist/models/AgentVersionCreate.js +48 -0
  112. package/dist/models/AgentVersionDiffResource.d.ts +87 -0
  113. package/dist/models/AgentVersionDiffResource.js +85 -0
  114. package/dist/models/AgentVersionPick.d.ts +32 -0
  115. package/dist/models/AgentVersionPick.js +50 -0
  116. package/dist/models/AgentVersionResource.d.ts +56 -0
  117. package/dist/models/AgentVersionResource.js +64 -0
  118. package/dist/models/AppResource.d.ts +12 -0
  119. package/dist/models/AppResource.js +4 -0
  120. package/dist/models/ResponseInput.d.ts +6 -0
  121. package/dist/models/ResponseInput.js +2 -0
  122. package/dist/models/SkillUpdateResource.d.ts +38 -0
  123. package/dist/models/SkillUpdateResource.js +54 -0
  124. package/dist/models/index.d.ts +13 -0
  125. package/dist/models/index.js +13 -0
  126. package/package.json +1 -1
  127. package/src/apis/AgentConversationsApi.ts +2 -2
  128. package/src/apis/AgentsApi.ts +737 -6
  129. package/src/apis/ArtifactsApi.ts +8 -4
  130. package/src/apis/ConversationsApi.ts +10 -0
  131. package/src/client.ts +21 -0
  132. package/src/compose/deploy.ts +126 -20
  133. package/src/compose/errors.ts +1 -1
  134. package/src/compose/index.ts +1 -1
  135. package/src/compose/run.ts +6 -2
  136. package/src/compose/settingsTransport.ts +154 -16
  137. package/src/compose/transport.ts +15 -0
  138. package/src/compose/webhook.ts +64 -11
  139. package/src/compose/webhookSecrets.ts +257 -0
  140. package/src/index.ts +4 -0
  141. package/src/models/AgentAttachmentDiff.ts +93 -0
  142. package/src/models/AgentContentsResource.ts +142 -0
  143. package/src/models/AgentDeploy.ts +66 -0
  144. package/src/models/AgentDraftResource.ts +99 -0
  145. package/src/models/AgentFileContent.ts +75 -0
  146. package/src/models/AgentHistoryResource.ts +121 -0
  147. package/src/models/AgentResource.ts +26 -0
  148. package/src/models/AgentSkillFilePin.ts +84 -0
  149. package/src/models/AgentSubagentEntry.ts +75 -0
  150. package/src/models/AgentVersionCreate.ts +65 -0
  151. package/src/models/AgentVersionDiffResource.ts +154 -0
  152. package/src/models/AgentVersionPick.ts +66 -0
  153. package/src/models/AgentVersionResource.ts +101 -0
  154. package/src/models/AppResource.ts +16 -0
  155. package/src/models/ResponseInput.ts +8 -0
  156. package/src/models/SkillUpdateResource.ts +75 -0
  157. package/src/models/index.ts +13 -0
@@ -8,6 +8,9 @@ import { FetchError, ResponseError } from "../runtime.js";
8
8
  import { answerClarify, postToolResults, reconnect, streamResponse } from "../streaming.js";
9
9
  import { NotSupportedByServerError, RunError, UserError } from "./errors.js";
10
10
  import { chunksFromUiMessage, fromUiChunk } from "./events.js";
11
+ import { VERSION_NOTE } from "./transport.js";
12
+ import { secretCredentialName, urlProblem } from "./webhook.js";
13
+ import { secretBackend } from "./webhookSecrets.js";
11
14
  const PAGE = 100;
12
15
  /** A post the server is still delivering (409 in_progress) is retried this many times, Retry-After apart. */
13
16
  const IN_PROGRESS_RETRIES = 5;
@@ -98,6 +101,24 @@ function firstDetail(error) {
98
101
  const first = Array.isArray(details) ? details[0] : undefined;
99
102
  return first !== null && typeof first === "object" && !Array.isArray(first) ? { ...first } : {};
100
103
  }
104
+ /** A deploy's 409 MISSING_DEPENDENCIES (the version uses a skill, app, knowledge base or sub-agent that was deleted
105
+ * since) as a UserError naming each one, else null. */
106
+ async function missingDependencies(err, agentId) {
107
+ if ((await reason(err, 409)) !== "MISSING_DEPENDENCIES")
108
+ return null;
109
+ const missing = firstDetail(await chatError(err))["missing"];
110
+ const items = Array.isArray(missing)
111
+ ? missing.filter((m) => m !== null && typeof m === "object")
112
+ : [];
113
+ const named = items.map((m) => `${m["kind"]} '${m["name"]}' (${m["id"]})`).join(", ");
114
+ return new UserError(`agent ${agentId}: the new version can't go live because it uses something that was deleted` +
115
+ `${named ? ": " + named : ""}. Remove it from the agent, then deploy again`);
116
+ }
117
+ /** `AgentResource.versionState`; undefined from a server without versions (or an agent that is not managed). */
118
+ function versionStateOf(resource) {
119
+ var _a;
120
+ return (_a = resource.versionState) !== null && _a !== void 0 ? _a : undefined;
121
+ }
101
122
  function retryAfterMs(err) {
102
123
  var _a;
103
124
  const seconds = Number((_a = err.response.headers.get("retry-after")) !== null && _a !== void 0 ? _a : 2);
@@ -174,6 +195,30 @@ function withoutWebhooks(settings) {
174
195
  const { sdk_hash: _hash, ...metadata } = settings["metadata"];
175
196
  return { ...out, metadata };
176
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
+ }
177
222
  function isNotFound(err) {
178
223
  return err instanceof ResponseError && err.response.status === 404;
179
224
  }
@@ -211,6 +256,7 @@ export class SettingsTransport {
211
256
  this.conversations = new ConversationsApi(config);
212
257
  this.responses = new ResponsesApi(config);
213
258
  this.customApis = new CustomAPIsApi(config);
259
+ this.secrets = secretBackend({ customApis: this.customApis });
214
260
  }
215
261
  // -- agents ---------------------------------------------------------------------------------------------
216
262
  async findAgents(sdkName) {
@@ -240,7 +286,8 @@ export class SettingsTransport {
240
286
  }
241
287
  async createAgent(agent) {
242
288
  var _a, _b, _c;
243
- const settings = agent.toSettings();
289
+ let settings = agent.toSettings();
290
+ let missing = [];
244
291
  const webhooks = ((_a = settings["webhooks"]) !== null && _a !== void 0 ? _a : []);
245
292
  // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
246
293
  // without them, bind the Custom APIs they name, then write the settings in full.
@@ -260,6 +307,7 @@ export class SettingsTransport {
260
307
  }
261
308
  let envelope;
262
309
  let warnings;
310
+ let live;
263
311
  // The create response never echoes settings, so support is read back from the settings route, which 404s
264
312
  // when the server has settings switched off (create then silently drops them).
265
313
  try {
@@ -274,6 +322,7 @@ export class SettingsTransport {
274
322
  if (webhooks.length > 0) {
275
323
  for (const { path, name, customApiId } of bind)
276
324
  await this.bind(resource.id, path, name, customApiId);
325
+ ({ settings, missing } = await this.withSecretCredentials(resource.id, settings));
277
326
  try {
278
327
  envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
279
328
  }
@@ -289,7 +338,7 @@ export class SettingsTransport {
289
338
  for (const sentence of unbound)
290
339
  console.warn(`agent ${resource.id}: ${sentence}`);
291
340
  checkMetadata(envelope, agent);
292
- await this.agents.deployAgent({ agentId: resource.id });
341
+ live = await this.goLive(resource.id, versionStateOf(resource), agent);
293
342
  }
294
343
  catch (err) {
295
344
  // Don't leave an orphan agent behind; a failing cleanup must not mask the original error.
@@ -301,13 +350,36 @@ export class SettingsTransport {
301
350
  }
302
351
  throw err;
303
352
  }
304
- return {
353
+ return withVersion({
305
354
  agentId: resource.id,
306
355
  name: agent.name,
307
356
  instructions: agent.instructions,
308
- settings: { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) },
357
+ settings: asDefined(resource.id, { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) }),
309
358
  warnings,
310
- };
359
+ ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
360
+ }, live, versionStateOf(resource));
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 };
311
383
  }
312
384
  /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
313
385
  * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
@@ -318,8 +390,8 @@ export class SettingsTransport {
318
390
  const seen = new Set();
319
391
  for (const [i, hook] of webhooks.entries()) {
320
392
  const name = hook.secret_credential;
321
- if (seen.has(name))
322
- continue;
393
+ if (name === undefined || seen.has(name))
394
+ continue; // left out: deploy fills in the one client.webhooks keeps
323
395
  seen.add(name);
324
396
  const path = `webhooks.${i}.secret_credential`;
325
397
  const ids = await this.customApiIds(name);
@@ -368,9 +440,10 @@ export class SettingsTransport {
368
440
  }
369
441
  async updateAgent(agentId, agent) {
370
442
  var _a, _b;
371
- const settings = agent.toSettings();
443
+ let settings = agent.toSettings();
372
444
  // findAgents searches by display name, so an adopted (or dashboard-renamed) agent must carry sdk_name.
373
- if ((await this.agents.getAgent({ agentId })).name !== agent.name) {
445
+ const current = await this.agents.getAgent({ agentId });
446
+ if (current.name !== agent.name) {
374
447
  await this.agents.updateAgent({ agentId, agentUpdate: { name: agent.name } });
375
448
  }
376
449
  // Rejections are only visible after the server stored the settings, so keep what was there to put it back.
@@ -390,6 +463,15 @@ export class SettingsTransport {
390
463
  if (instructionsChanged) {
391
464
  await this.agents.putInstructions({ agentId, instructionsBody: { data: agent.instructions } });
392
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
+ }
393
475
  let envelope;
394
476
  try {
395
477
  envelope = await this.agents.putAgentSettings({ agentId, body: settings });
@@ -416,14 +498,52 @@ export class SettingsTransport {
416
498
  throw err;
417
499
  }
418
500
  checkMetadata(envelope, agent);
419
- await this.agents.deployAgent({ agentId }); // idempotent; moves an adopted draft to deployed
420
- return {
501
+ const live = await this.goLive(agentId, versionStateOf(current), agent);
502
+ return withVersion({
421
503
  agentId,
422
504
  name: agent.name,
423
505
  instructions: agent.instructions,
424
- settings: { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) },
506
+ settings: asDefined(agentId, { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) }),
425
507
  warnings,
426
- };
508
+ ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
509
+ }, live, versionStateOf(current));
510
+ }
511
+ /** Make what was just written what end users get. A server without versions (no `versionState`) gets the bodiless
512
+ * deploy 0.3 sent; otherwise the draft is saved as a version and that version deployed. */
513
+ async goLive(agentId, versionState, agent) {
514
+ if (versionState === undefined) {
515
+ await this.agents.deployAgent({ agentId }); // idempotent; moves an adopted draft to deployed
516
+ return undefined;
517
+ }
518
+ return this.publish(agentId, VERSION_NOTE);
519
+ }
520
+ /**
521
+ * Save the draft as the next version and make it live. 409 NO_CHANGES means the newest saved version already is the
522
+ * draft, so that version is deployed, by its number (never "the newest", which a save landing in between could
523
+ * change).
524
+ */
525
+ async publish(agentId, note) {
526
+ var _a, _b;
527
+ let version;
528
+ try {
529
+ version = (await this.agents.saveVersion({ agentId, agentVersionCreate: { note } })).version;
530
+ }
531
+ catch (err) {
532
+ if ((await reason(err, 409)) !== "NO_CHANGES")
533
+ throw err;
534
+ const newest = (await this.agents.getDraft({ agentId })).basedOnVersion;
535
+ if (newest === undefined || newest === null)
536
+ throw err;
537
+ version = newest;
538
+ }
539
+ let resource;
540
+ try {
541
+ resource = await this.agents.deployAgent({ agentId, agentDeploy: { version } });
542
+ }
543
+ catch (err) {
544
+ throw (_a = (await missingDependencies(err, agentId))) !== null && _a !== void 0 ? _a : err;
545
+ }
546
+ return (_b = resource.liveVersion) !== null && _b !== void 0 ? _b : undefined;
427
547
  }
428
548
  async deleteAgent(agentId) {
429
549
  await this.agents.deleteAgent({ agentId });
@@ -601,9 +721,26 @@ export class SettingsTransport {
601
721
  }
602
722
  remote(resource, instructions) {
603
723
  var _a;
604
- return { agentId: resource.id, name: resource.name, instructions, settings: { ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }, warnings: [] };
724
+ const remote = {
725
+ agentId: resource.id, name: resource.name, instructions, warnings: [],
726
+ settings: asDefined(resource.id, { ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }),
727
+ };
728
+ // Left out, not set to undefined, when the server has no versions: the shape a 0.3 transport returned.
729
+ if (resource.liveVersion !== undefined && resource.liveVersion !== null)
730
+ remote.liveVersion = resource.liveVersion;
731
+ const state = versionStateOf(resource);
732
+ if (state !== undefined)
733
+ remote.versionState = state;
734
+ return remote;
605
735
  }
606
736
  }
737
+ /** `remote` with the version fields set when known (left out otherwise, as a server without versions returns it). After a
738
+ * publish the agent is live whatever state it was read in. */
739
+ function withVersion(remote, live, state) {
740
+ if (live !== undefined)
741
+ return { ...remote, liveVersion: live, versionState: "live" };
742
+ return state === undefined ? remote : { ...remote, versionState: state };
743
+ }
607
744
  /** The server's 422 CHAT_VALIDATION / invalid_agent_settings rejection as a UserError, else null. */
608
745
  async function invalidSettings(err) {
609
746
  if (!(err instanceof ResponseError) || err.response.status !== 422)
@@ -14,7 +14,18 @@ export interface RemoteAgent {
14
14
  instructions: string;
15
15
  settings: Record<string, unknown>;
16
16
  warnings: SettingsWarning[];
17
+ /** The version end users get (`AgentResource.liveVersion`); undefined when nothing is live or the server has no
18
+ * versions. */
19
+ liveVersion?: number;
20
+ /** `"live"`, `"paused"` or `"not_live"` (`AgentResource.versionState`); undefined when the server has no versions,
21
+ * in which case deploy() never calls `publish`. */
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[];
17
26
  }
27
+ /** The note on every version deploy() saves, so the dashboard's version list shows which came from code. */
28
+ export declare const VERSION_NOTE = "Deployed from the SDK";
18
29
  /** Async iterable of Events; the ids are filled in as the stream progresses. */
19
30
  export interface TurnStream extends AsyncIterable<Event> {
20
31
  readonly conversationId: string | null;
@@ -37,6 +48,9 @@ export interface Transport {
37
48
  createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
38
49
  updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
39
50
  deleteAgent(agentId: string): Promise<void>;
51
+ /** Save the draft as the next version and make that version live; resolves to the live version. Called only for
52
+ * an agent whose `versionState` is set. Optional so a transport written before versions still type-checks. */
53
+ publish?(agentId: string, note: string): Promise<number | undefined>;
40
54
  startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
41
55
  answerClarify(conversationId: string, requestId: string, answers: Record<string, unknown>, signal?: AbortSignal): Promise<TurnStream>;
42
56
  resume(conversationId: string, responseId: string, lastEventId: string | null, signal?: AbortSignal): Promise<TurnStream>;
@@ -1 +1,2 @@
1
- export {};
1
+ /** The note on every version deploy() saves, so the dashboard's version list shows which came from code. */
2
+ export 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
  }
@@ -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
+ }