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
@@ -14,6 +14,10 @@ import { NotSupportedByServerError, RunError, UserError } from "./errors.js";
14
14
  import { chunksFromUiMessage, fromUiChunk } from "./events.js";
15
15
  import type { Event } from "./events.js";
16
16
  import type { FunctionResult } from "./functionTool.js";
17
+ import { VERSION_NOTE } from "./transport.js";
18
+ import { secretCredentialName, urlProblem } from "./webhook.js";
19
+ import { secretBackend } from "./webhookSecrets.js";
20
+ import type { SecretBackend } from "./webhookSecrets.js";
17
21
  import type { PendingFunctionCalls, RemoteAgent, SettingsWarning, Transport, TurnStream } from "./transport.js";
18
22
 
19
23
  const PAGE = 100;
@@ -102,6 +106,24 @@ function firstDetail(error: Record<string, unknown> | null): Record<string, unkn
102
106
  return first !== null && typeof first === "object" && !Array.isArray(first) ? { ...first } : {};
103
107
  }
104
108
 
109
+ /** A deploy's 409 MISSING_DEPENDENCIES (the version uses a skill, app, knowledge base or sub-agent that was deleted
110
+ * since) as a UserError naming each one, else null. */
111
+ async function missingDependencies(err: unknown, agentId: string): Promise<UserError | null> {
112
+ if ((await reason(err, 409)) !== "MISSING_DEPENDENCIES") return null;
113
+ const missing = firstDetail(await chatError(err as ResponseError))["missing"];
114
+ const items = Array.isArray(missing)
115
+ ? (missing as unknown[]).filter((m): m is Record<string, unknown> => m !== null && typeof m === "object")
116
+ : [];
117
+ const named = items.map((m) => `${m["kind"]} '${m["name"]}' (${m["id"]})`).join(", ");
118
+ return new UserError(`agent ${agentId}: the new version can't go live because it uses something that was deleted` +
119
+ `${named ? ": " + named : ""}. Remove it from the agent, then deploy again`);
120
+ }
121
+
122
+ /** `AgentResource.versionState`; undefined from a server without versions (or an agent that is not managed). */
123
+ function versionStateOf(resource: { versionState?: string | null }): string | undefined {
124
+ return resource.versionState ?? undefined;
125
+ }
126
+
105
127
  function retryAfterMs(err: ResponseError): number {
106
128
  const seconds = Number(err.response.headers.get("retry-after") ?? 2);
107
129
  if (!Number.isFinite(seconds) || seconds < 0) return 2000;
@@ -182,6 +204,33 @@ function withoutWebhooks(settings: Record<string, any>): Record<string, any> {
182
204
  return { ...out, metadata };
183
205
  }
184
206
 
207
+ type Hook = Record<string, unknown>;
208
+
209
+ function hooksOf(settings: Record<string, any>): Hook[] {
210
+ const hooks = settings["webhooks"];
211
+ return Array.isArray(hooks) ? hooks.filter((h) => typeof h === "object" && h !== null && !Array.isArray(h)) : [];
212
+ }
213
+
214
+ function sdkNamed(agentId: string, hook: Hook): boolean {
215
+ const url = hook["url"];
216
+ return typeof url === "string" && urlProblem(url) === null &&
217
+ hook["secret_credential"] === secretCredentialName(agentId, url);
218
+ }
219
+
220
+ /** `settings` as a definition writes them: a webhook whose `secret_credential` is the one `deploy` filled in loses it
221
+ * again, so the stored `sdk_hash` (computed without it) still matches. */
222
+ function asDefined(agentId: string, settings: Record<string, any>): Record<string, any> {
223
+ if (!hooksOf(settings).some((h) => sdkNamed(agentId, h))) return settings;
224
+ return {
225
+ ...settings,
226
+ webhooks: (settings["webhooks"] as unknown[]).map((h) => {
227
+ if (typeof h !== "object" || h === null || !sdkNamed(agentId, h as Hook)) return h;
228
+ const { secret_credential: _name, ...rest } = h as Hook;
229
+ return rest;
230
+ }),
231
+ };
232
+ }
233
+
185
234
  function isNotFound(err: unknown): boolean {
186
235
  return err instanceof ResponseError && err.response.status === 404;
187
236
  }
@@ -221,12 +270,14 @@ export class SettingsTransport implements Transport {
221
270
  private readonly conversations: ConversationsApi;
222
271
  private readonly responses: ResponsesApi;
223
272
  private readonly customApis: CustomAPIsApi;
273
+ private readonly secrets: SecretBackend;
224
274
 
225
275
  constructor(private readonly config: Configuration) {
226
276
  this.agents = new AgentsApi(config);
227
277
  this.conversations = new ConversationsApi(config);
228
278
  this.responses = new ResponsesApi(config);
229
279
  this.customApis = new CustomAPIsApi(config);
280
+ this.secrets = secretBackend({ customApis: this.customApis });
230
281
  }
231
282
 
232
283
  // -- agents ---------------------------------------------------------------------------------------------
@@ -256,8 +307,9 @@ export class SettingsTransport implements Transport {
256
307
  }
257
308
 
258
309
  async createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent> {
259
- const settings = agent.toSettings();
260
- const webhooks = (settings["webhooks"] ?? []) as { secret_credential: string }[];
310
+ let settings = agent.toSettings();
311
+ let missing: string[] = [];
312
+ const webhooks = (settings["webhooks"] ?? []) as { secret_credential?: string }[];
261
313
  // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
262
314
  // without them, bind the Custom APIs they name, then write the settings in full.
263
315
  const { bind, unbound } = await this.webhookCredentials(webhooks);
@@ -275,6 +327,7 @@ export class SettingsTransport implements Transport {
275
327
  }
276
328
  let envelope: Envelope;
277
329
  let warnings: SettingsWarning[];
330
+ let live: number | undefined;
278
331
  // The create response never echoes settings, so support is read back from the settings route, which 404s
279
332
  // when the server has settings switched off (create then silently drops them).
280
333
  try {
@@ -286,6 +339,7 @@ export class SettingsTransport implements Transport {
286
339
  }
287
340
  if (webhooks.length > 0) {
288
341
  for (const { path, name, customApiId } of bind) await this.bind(resource.id, path, name, customApiId);
342
+ ({ settings, missing } = await this.withSecretCredentials(resource.id, settings));
289
343
  try {
290
344
  envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
291
345
  } catch (err) {
@@ -298,7 +352,7 @@ export class SettingsTransport implements Transport {
298
352
  // Accepted unchecked (webhooks switched off): refused once they are on.
299
353
  for (const sentence of unbound) console.warn(`agent ${resource.id}: ${sentence}`);
300
354
  checkMetadata(envelope, agent);
301
- await this.agents.deployAgent({ agentId: resource.id });
355
+ live = await this.goLive(resource.id, versionStateOf(resource), agent);
302
356
  } catch (err) {
303
357
  // Don't leave an orphan agent behind; a failing cleanup must not mask the original error.
304
358
  try {
@@ -308,19 +362,42 @@ export class SettingsTransport implements Transport {
308
362
  }
309
363
  throw err;
310
364
  }
311
- return {
365
+ return withVersion({
312
366
  agentId: resource.id,
313
367
  name: agent.name,
314
368
  instructions: agent.instructions,
315
- settings: { ...(envelope.settings ?? {}) },
369
+ settings: asDefined(resource.id, { ...(envelope.settings ?? {}) }),
316
370
  warnings,
317
- };
371
+ ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
372
+ }, live, versionStateOf(resource));
373
+ }
374
+
375
+ /** `settings` with each webhook that names no `secret_credential` given the one `client.webhooks` keeps for the
376
+ * agent and host (stored, with a random secret nobody holds, when there is none yet), and the URLs of those
377
+ * webhooks still without a secret set by `client.webhooks`. */
378
+ private async withSecretCredentials(agentId: string, settings: Record<string, any>):
379
+ Promise<{ settings: Record<string, any>; missing: string[] }> {
380
+ const hooks = hooksOf(settings);
381
+ if (hooks.every((h) => "secret_credential" in h)) return { settings, missing: [] };
382
+ const filled: unknown[] = [];
383
+ const missing: string[] = [];
384
+ for (const h of settings["webhooks"] as Hook[]) {
385
+ if (typeof h !== "object" || h === null || "secret_credential" in h) {
386
+ filled.push(h);
387
+ continue;
388
+ }
389
+ const url = h["url"] as string;
390
+ const { name, status } = await this.secrets.ensure(agentId, url);
391
+ filled.push({ ...h, secret_credential: name });
392
+ if (status === "missing") missing.push(url);
393
+ }
394
+ return { settings: { ...settings, webhooks: filled }, missing };
318
395
  }
319
396
 
320
397
  /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
321
398
  * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
322
399
  * checks credentials). */
323
- private async webhookCredentials(webhooks: { secret_credential: string }[]): Promise<{
400
+ private async webhookCredentials(webhooks: { secret_credential?: string }[]): Promise<{
324
401
  bind: { path: string; name: string; customApiId: string }[];
325
402
  unbound: string[];
326
403
  }> {
@@ -329,7 +406,7 @@ export class SettingsTransport implements Transport {
329
406
  const seen = new Set<string>();
330
407
  for (const [i, hook] of webhooks.entries()) {
331
408
  const name = hook.secret_credential;
332
- if (seen.has(name)) continue;
409
+ if (name === undefined || seen.has(name)) continue; // left out: deploy fills in the one client.webhooks keeps
333
410
  seen.add(name);
334
411
  const path = `webhooks.${i}.secret_credential`;
335
412
  const ids = await this.customApiIds(name);
@@ -372,9 +449,10 @@ export class SettingsTransport implements Transport {
372
449
  }
373
450
 
374
451
  async updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent> {
375
- const settings = agent.toSettings();
452
+ let settings = agent.toSettings();
376
453
  // findAgents searches by display name, so an adopted (or dashboard-renamed) agent must carry sdk_name.
377
- if ((await this.agents.getAgent({ agentId })).name !== agent.name) {
454
+ const current = await this.agents.getAgent({ agentId });
455
+ if (current.name !== agent.name) {
378
456
  await this.agents.updateAgent({ agentId, agentUpdate: { name: agent.name } });
379
457
  }
380
458
  // Rejections are only visible after the server stored the settings, so keep what was there to put it back.
@@ -392,6 +470,13 @@ export class SettingsTransport implements Transport {
392
470
  if (instructionsChanged) {
393
471
  await this.agents.putInstructions({ agentId, instructionsBody: { data: agent.instructions } });
394
472
  }
473
+ let missing: string[];
474
+ try {
475
+ ({ settings, missing } = await this.withSecretCredentials(agentId, settings));
476
+ } catch (err) {
477
+ if (instructionsChanged) await this.restore(agentId, null, previousInstructions);
478
+ throw err;
479
+ }
395
480
  let envelope: Envelope;
396
481
  try {
397
482
  envelope = await this.agents.putAgentSettings({ agentId, body: settings });
@@ -413,14 +498,49 @@ export class SettingsTransport implements Transport {
413
498
  throw err;
414
499
  }
415
500
  checkMetadata(envelope, agent);
416
- await this.agents.deployAgent({ agentId }); // idempotent; moves an adopted draft to deployed
417
- return {
501
+ const live = await this.goLive(agentId, versionStateOf(current), agent);
502
+ return withVersion({
418
503
  agentId,
419
504
  name: agent.name,
420
505
  instructions: agent.instructions,
421
- settings: { ...(envelope.settings ?? {}) },
506
+ settings: asDefined(agentId, { ...(envelope.settings ?? {}) }),
422
507
  warnings,
423
- };
508
+ ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
509
+ }, live, versionStateOf(current));
510
+ }
511
+
512
+ /** Make what was just written what end users get. A server without versions (no `versionState`) gets the bodiless
513
+ * deploy 0.3 sent; otherwise the draft is saved as a version and that version deployed. */
514
+ private async goLive(agentId: string, versionState: string | undefined, agent: Agent<OutputType | undefined>): Promise<number | undefined> {
515
+ if (versionState === undefined) {
516
+ await this.agents.deployAgent({ agentId }); // idempotent; moves an adopted draft to deployed
517
+ return undefined;
518
+ }
519
+ return this.publish(agentId, VERSION_NOTE);
520
+ }
521
+
522
+ /**
523
+ * Save the draft as the next version and make it live. 409 NO_CHANGES means the newest saved version already is the
524
+ * draft, so that version is deployed, by its number (never "the newest", which a save landing in between could
525
+ * change).
526
+ */
527
+ async publish(agentId: string, note: string): Promise<number | undefined> {
528
+ let version: number;
529
+ try {
530
+ version = (await this.agents.saveVersion({ agentId, agentVersionCreate: { note } })).version;
531
+ } catch (err) {
532
+ if ((await reason(err, 409)) !== "NO_CHANGES") throw err;
533
+ const newest = (await this.agents.getDraft({ agentId })).basedOnVersion;
534
+ if (newest === undefined || newest === null) throw err;
535
+ version = newest;
536
+ }
537
+ let resource;
538
+ try {
539
+ resource = await this.agents.deployAgent({ agentId, agentDeploy: { version } });
540
+ } catch (err) {
541
+ throw (await missingDependencies(err, agentId)) ?? err;
542
+ }
543
+ return resource.liveVersion ?? undefined;
424
544
  }
425
545
 
426
546
  async deleteAgent(agentId: string): Promise<void> {
@@ -621,11 +741,29 @@ export class SettingsTransport implements Transport {
621
741
  return (await this.agents.getInstructions({ agentId })).data;
622
742
  }
623
743
 
624
- private remote(resource: { id: string; name: string; settings?: { [key: string]: any } | null }, instructions: string): RemoteAgent {
625
- return { agentId: resource.id, name: resource.name, instructions, settings: { ...(resource.settings ?? {}) }, warnings: [] };
744
+ private remote(
745
+ resource: { id: string; name: string; settings?: { [key: string]: any } | null; versionState?: string | null; liveVersion?: number | null },
746
+ instructions: string,
747
+ ): RemoteAgent {
748
+ const remote: RemoteAgent = {
749
+ agentId: resource.id, name: resource.name, instructions, warnings: [],
750
+ settings: asDefined(resource.id, { ...(resource.settings ?? {}) }),
751
+ };
752
+ // Left out, not set to undefined, when the server has no versions: the shape a 0.3 transport returned.
753
+ if (resource.liveVersion !== undefined && resource.liveVersion !== null) remote.liveVersion = resource.liveVersion;
754
+ const state = versionStateOf(resource);
755
+ if (state !== undefined) remote.versionState = state;
756
+ return remote;
626
757
  }
627
758
  }
628
759
 
760
+ /** `remote` with the version fields set when known (left out otherwise, as a server without versions returns it). After a
761
+ * publish the agent is live whatever state it was read in. */
762
+ function withVersion(remote: RemoteAgent, live: number | undefined, state: string | undefined): RemoteAgent {
763
+ if (live !== undefined) return { ...remote, liveVersion: live, versionState: "live" };
764
+ return state === undefined ? remote : { ...remote, versionState: state };
765
+ }
766
+
629
767
  /** The server's 422 CHAT_VALIDATION / invalid_agent_settings rejection as a UserError, else null. */
630
768
  async function invalidSettings(err: unknown): Promise<UserError | null> {
631
769
  if (!(err instanceof ResponseError) || err.response.status !== 422) return null;
@@ -16,8 +16,20 @@ export interface RemoteAgent {
16
16
  instructions: string;
17
17
  settings: Record<string, unknown>;
18
18
  warnings: SettingsWarning[];
19
+ /** The version end users get (`AgentResource.liveVersion`); undefined when nothing is live or the server has no
20
+ * versions. */
21
+ liveVersion?: number;
22
+ /** `"live"`, `"paused"` or `"not_live"` (`AgentResource.versionState`); undefined when the server has no versions,
23
+ * in which case deploy() never calls `publish`. */
24
+ versionState?: string;
25
+ /** URLs of the webhooks this write left without a secret set by `client.webhooks` (a placeholder secret nobody
26
+ * holds stands in until `client.webhooks.setSecret`); left out when there are none. */
27
+ webhooksMissingSecret?: string[];
19
28
  }
20
29
 
30
+ /** The note on every version deploy() saves, so the dashboard's version list shows which came from code. */
31
+ export const VERSION_NOTE = "Deployed from the SDK";
32
+
21
33
  /** Async iterable of Events; the ids are filled in as the stream progresses. */
22
34
  export interface TurnStream extends AsyncIterable<Event> {
23
35
  readonly conversationId: string | null;
@@ -42,6 +54,9 @@ export interface Transport {
42
54
  createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
43
55
  updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
44
56
  deleteAgent(agentId: string): Promise<void>;
57
+ /** Save the draft as the next version and make that version live; resolves to the live version. Called only for
58
+ * an agent whose `versionState` is set. Optional so a transport written before versions still type-checks. */
59
+ publish?(agentId: string, note: string): Promise<number | undefined>;
45
60
  startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
46
61
  answerClarify(
47
62
  conversationId: string,
@@ -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
  import type { WebhookEventType } from "../webhooks.js";
@@ -17,8 +20,13 @@ export interface Webhook {
17
20
  url: string;
18
21
  /** 1 to 4 distinct events. `approval.requested` is reserved: accepted, not sent yet. */
19
22
  events: WebhookEventType[];
20
- /** The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). */
21
- secretCredential: string;
23
+ /**
24
+ * The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). Leave it out: `deploy`
25
+ * fills in the credential `client.webhooks` keeps, and `client.webhooks.setSecret(agentId, url)` sets the secret.
26
+ *
27
+ * @deprecated Use `client.webhooks.setSecret` instead of creating a Custom API and naming it here.
28
+ */
29
+ secretCredential?: string;
22
30
  }
23
31
 
24
32
  export const WEBHOOKS_MAX = 5;
@@ -138,14 +146,16 @@ export function checkWebhooks(webhooks: unknown): void {
138
146
  webhooks.forEach((hook: unknown, i: number) => {
139
147
  const where = `webhooks.${i}.`;
140
148
  if (typeof hook !== "object" || hook === null || Array.isArray(hook)) {
141
- throw new UserError(`webhooks.${i}: must be an object with url, events and secretCredential`);
149
+ throw new UserError(`webhooks.${i}: must be an object with url and events`);
142
150
  }
143
151
  const { url, events, secretCredential } = hook as Record<string, unknown>;
144
152
  if (typeof url !== "string") throw new UserError(where + "url: must be a string");
145
153
  if (!Array.isArray(events) || !events.every((e) => typeof e === "string")) {
146
154
  throw new UserError(where + "events: must be a list of event names");
147
155
  }
148
- if (typeof secretCredential !== "string") throw new UserError(where + "secretCredential: must be a string");
156
+ if (secretCredential !== undefined && typeof secretCredential !== "string") {
157
+ throw new UserError(where + "secretCredential: must be a string");
158
+ }
149
159
  // Python's Webhook is extra="forbid": a key dropped silently (a misplaced secret) would never verify.
150
160
  const extra = Object.keys(hook).find((k) => k !== "url" && k !== "events" && k !== "secretCredential");
151
161
  if (extra !== undefined) throw new UserError(where + extra + ": Extra inputs are not permitted");
@@ -158,7 +168,7 @@ export function checkWebhooks(webhooks: unknown): void {
158
168
  throw new UserError(where + `events: events must be from: ${WEBHOOK_EVENTS.join(", ")}.`);
159
169
  }
160
170
  if (new Set(events).size !== events.length) throw new UserError(where + "events: events must not repeat an event.");
161
- const n = codePoints(secretCredential);
171
+ const n = typeof secretCredential === "string" ? codePoints(secretCredential) : 1;
162
172
  if (n < 1 || n > SECRET_CREDENTIAL_MAX) {
163
173
  throw new UserError(where + "secret_credential: secret_credential must be the name of a vault credential " +
164
174
  `(1 to ${SECRET_CREDENTIAL_MAX} characters).`);
@@ -171,11 +181,54 @@ export function checkWebhooks(webhooks: unknown): void {
171
181
  });
172
182
  }
173
183
 
174
- /** Only the three fields, in agent.json's names (a copy). */
184
+ /** Only the three fields (a copy). `secretCredential` is left out when absent, or when it is the name `deploy`
185
+ * writes anyway (one spelling keeps one fingerprint). */
175
186
  export function copyWebhooks(webhooks: readonly Webhook[]): Webhook[] {
176
- return webhooks.map((h) => ({ url: h.url, events: [...h.events], secretCredential: h.secretCredential }));
187
+ return webhooks.map((h) => {
188
+ const copy: Webhook = { url: h.url, events: [...h.events] };
189
+ const name = h.secretCredential;
190
+ if (name !== undefined && !isSdkCredentialName(name, h.url)) copy.secretCredential = name;
191
+ return copy;
192
+ });
177
193
  }
178
194
 
179
195
  export function webhooksJson(webhooks: readonly Webhook[]): Record<string, unknown>[] {
180
- return webhooks.map((h) => ({ url: h.url, events: [...h.events], secret_credential: h.secretCredential }));
196
+ return webhooks.map((h) => {
197
+ const out: Record<string, unknown> = { url: h.url, events: [...h.events] };
198
+ if (h.secretCredential !== undefined) out["secret_credential"] = h.secretCredential;
199
+ return out;
200
+ });
201
+ }
202
+
203
+ /** The host of an allowed webhook URL, lowercased, without a trailing dot or a port. */
204
+ export function webhookHost(url: string): string {
205
+ return stripTrailingDots(hostPort(split(url)[1])[0]);
206
+ }
207
+
208
+ /** Every Custom API the SDK creates for a webhook secret is named `webhook-secret:<agentId>:<host>`. */
209
+ export const SECRET_NAME_PREFIX = "webhook-secret:";
210
+ const SECRET_NAME_MAX = 256;
211
+
212
+ function hashedHost(host: string): string {
213
+ return "sha256-" + createHash("sha256").update(host, "utf8").digest("hex").slice(0, 32);
214
+ }
215
+
216
+ /** The credential name the SDK uses for `url`'s signing secret on agent `agentId` (what `deploy` writes as
217
+ * `secret_credential` when a webhook leaves it out). A host too long to fit 256 characters is hashed. */
218
+ export function secretCredentialName(agentId: string, url: string): string {
219
+ const host = webhookHost(url);
220
+ const name = `${SECRET_NAME_PREFIX}${agentId}:${host}`;
221
+ return codePoints(name) <= SECRET_NAME_MAX ? name : `${SECRET_NAME_PREFIX}${agentId}:${hashedHost(host)}`;
222
+ }
223
+
224
+ /** Whether `name` is the SDK's credential name for `url`'s host, for any agent. */
225
+ export function isSdkCredentialName(name: unknown, url: string): boolean {
226
+ if (typeof name !== "string" || !name.startsWith(SECRET_NAME_PREFIX) || urlProblem(url) !== null) return false;
227
+ const rest = name.slice(SECRET_NAME_PREFIX.length);
228
+ const at = rest.lastIndexOf(":");
229
+ if (at <= 0) return false;
230
+ const agentId = rest.slice(0, at);
231
+ const tail = rest.slice(at + 1);
232
+ const host = webhookHost(url);
233
+ return !agentId.includes(":") && (tail === host || tail === hashedHost(host));
181
234
  }