sarvam-agents-client 0.3.1 → 0.4.0

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 (152) hide show
  1. package/README.md +82 -0
  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/compose/agent.d.ts +4 -0
  11. package/dist/compose/agent.js +8 -0
  12. package/dist/compose/deploy.d.ts +33 -7
  13. package/dist/compose/deploy.js +97 -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 +2 -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 +17 -0
  21. package/dist/compose/settingsTransport.js +176 -12
  22. package/dist/compose/transport.d.ts +11 -0
  23. package/dist/compose/transport.js +3 -0
  24. package/dist/compose/webhook.d.ts +19 -0
  25. package/dist/compose/webhook.js +184 -0
  26. package/dist/esm/apis/AgentConversationsApi.d.ts +2 -2
  27. package/dist/esm/apis/AgentConversationsApi.js +2 -2
  28. package/dist/esm/apis/AgentsApi.d.ts +195 -5
  29. package/dist/esm/apis/AgentsApi.js +478 -5
  30. package/dist/esm/apis/ArtifactsApi.d.ts +8 -4
  31. package/dist/esm/apis/ArtifactsApi.js +8 -4
  32. package/dist/esm/apis/ConversationsApi.d.ts +2 -0
  33. package/dist/esm/apis/ConversationsApi.js +6 -0
  34. package/dist/esm/compose/agent.d.ts +4 -0
  35. package/dist/esm/compose/agent.js +8 -0
  36. package/dist/esm/compose/deploy.d.ts +33 -7
  37. package/dist/esm/compose/deploy.js +97 -20
  38. package/dist/esm/compose/errors.d.ts +1 -1
  39. package/dist/esm/compose/errors.js +1 -1
  40. package/dist/esm/compose/index.d.ts +2 -1
  41. package/dist/esm/compose/index.js +1 -1
  42. package/dist/esm/compose/run.d.ts +5 -1
  43. package/dist/esm/compose/run.js +9 -9
  44. package/dist/esm/compose/settingsTransport.d.ts +17 -0
  45. package/dist/esm/compose/settingsTransport.js +176 -12
  46. package/dist/esm/compose/transport.d.ts +11 -0
  47. package/dist/esm/compose/transport.js +2 -1
  48. package/dist/esm/compose/webhook.d.ts +19 -0
  49. package/dist/esm/compose/webhook.js +177 -0
  50. package/dist/esm/models/AgentAttachmentDiff.d.ts +50 -0
  51. package/dist/esm/models/AgentAttachmentDiff.js +55 -0
  52. package/dist/esm/models/AgentContentsResource.d.ts +71 -0
  53. package/dist/esm/models/AgentContentsResource.js +70 -0
  54. package/dist/esm/models/AgentDeploy.d.ts +33 -0
  55. package/dist/esm/models/AgentDeploy.js +41 -0
  56. package/dist/esm/models/AgentDraftResource.d.ts +51 -0
  57. package/dist/esm/models/AgentDraftResource.js +52 -0
  58. package/dist/esm/models/AgentFileContent.d.ts +38 -0
  59. package/dist/esm/models/AgentFileContent.js +47 -0
  60. package/dist/esm/models/AgentHistoryResource.d.ts +71 -0
  61. package/dist/esm/models/AgentHistoryResource.js +66 -0
  62. package/dist/esm/models/AgentResource.d.ts +21 -0
  63. package/dist/esm/models/AgentResource.js +12 -0
  64. package/dist/esm/models/AgentSkillFilePin.d.ts +44 -0
  65. package/dist/esm/models/AgentSkillFilePin.js +51 -0
  66. package/dist/esm/models/AgentSubagentEntry.d.ts +38 -0
  67. package/dist/esm/models/AgentSubagentEntry.js +47 -0
  68. package/dist/esm/models/AgentVersionCreate.d.ts +32 -0
  69. package/dist/esm/models/AgentVersionCreate.js +41 -0
  70. package/dist/esm/models/AgentVersionDiffResource.d.ts +87 -0
  71. package/dist/esm/models/AgentVersionDiffResource.js +78 -0
  72. package/dist/esm/models/AgentVersionPick.d.ts +32 -0
  73. package/dist/esm/models/AgentVersionPick.js +43 -0
  74. package/dist/esm/models/AgentVersionResource.d.ts +56 -0
  75. package/dist/esm/models/AgentVersionResource.js +57 -0
  76. package/dist/esm/models/AppResource.d.ts +12 -0
  77. package/dist/esm/models/AppResource.js +4 -0
  78. package/dist/esm/models/ResponseInput.d.ts +6 -0
  79. package/dist/esm/models/ResponseInput.js +2 -0
  80. package/dist/esm/models/SkillUpdateResource.d.ts +38 -0
  81. package/dist/esm/models/SkillUpdateResource.js +47 -0
  82. package/dist/esm/models/index.d.ts +13 -0
  83. package/dist/esm/models/index.js +13 -0
  84. package/dist/esm/webhooks.d.ts +203 -0
  85. package/dist/esm/webhooks.js +215 -0
  86. package/dist/models/AgentAttachmentDiff.d.ts +50 -0
  87. package/dist/models/AgentAttachmentDiff.js +62 -0
  88. package/dist/models/AgentContentsResource.d.ts +71 -0
  89. package/dist/models/AgentContentsResource.js +77 -0
  90. package/dist/models/AgentDeploy.d.ts +33 -0
  91. package/dist/models/AgentDeploy.js +48 -0
  92. package/dist/models/AgentDraftResource.d.ts +51 -0
  93. package/dist/models/AgentDraftResource.js +59 -0
  94. package/dist/models/AgentFileContent.d.ts +38 -0
  95. package/dist/models/AgentFileContent.js +54 -0
  96. package/dist/models/AgentHistoryResource.d.ts +71 -0
  97. package/dist/models/AgentHistoryResource.js +74 -0
  98. package/dist/models/AgentResource.d.ts +21 -0
  99. package/dist/models/AgentResource.js +13 -1
  100. package/dist/models/AgentSkillFilePin.d.ts +44 -0
  101. package/dist/models/AgentSkillFilePin.js +58 -0
  102. package/dist/models/AgentSubagentEntry.d.ts +38 -0
  103. package/dist/models/AgentSubagentEntry.js +54 -0
  104. package/dist/models/AgentVersionCreate.d.ts +32 -0
  105. package/dist/models/AgentVersionCreate.js +48 -0
  106. package/dist/models/AgentVersionDiffResource.d.ts +87 -0
  107. package/dist/models/AgentVersionDiffResource.js +85 -0
  108. package/dist/models/AgentVersionPick.d.ts +32 -0
  109. package/dist/models/AgentVersionPick.js +50 -0
  110. package/dist/models/AgentVersionResource.d.ts +56 -0
  111. package/dist/models/AgentVersionResource.js +64 -0
  112. package/dist/models/AppResource.d.ts +12 -0
  113. package/dist/models/AppResource.js +4 -0
  114. package/dist/models/ResponseInput.d.ts +6 -0
  115. package/dist/models/ResponseInput.js +2 -0
  116. package/dist/models/SkillUpdateResource.d.ts +38 -0
  117. package/dist/models/SkillUpdateResource.js +54 -0
  118. package/dist/models/index.d.ts +13 -0
  119. package/dist/models/index.js +13 -0
  120. package/dist/webhooks.d.ts +203 -0
  121. package/dist/webhooks.js +224 -0
  122. package/package.json +9 -1
  123. package/src/apis/AgentConversationsApi.ts +2 -2
  124. package/src/apis/AgentsApi.ts +737 -6
  125. package/src/apis/ArtifactsApi.ts +8 -4
  126. package/src/apis/ConversationsApi.ts +10 -0
  127. package/src/compose/agent.ts +9 -0
  128. package/src/compose/deploy.ts +113 -20
  129. package/src/compose/errors.ts +1 -1
  130. package/src/compose/index.ts +2 -1
  131. package/src/compose/run.ts +6 -2
  132. package/src/compose/settingsTransport.ts +167 -10
  133. package/src/compose/transport.ts +12 -0
  134. package/src/compose/webhook.ts +181 -0
  135. package/src/models/AgentAttachmentDiff.ts +93 -0
  136. package/src/models/AgentContentsResource.ts +142 -0
  137. package/src/models/AgentDeploy.ts +66 -0
  138. package/src/models/AgentDraftResource.ts +99 -0
  139. package/src/models/AgentFileContent.ts +75 -0
  140. package/src/models/AgentHistoryResource.ts +121 -0
  141. package/src/models/AgentResource.ts +26 -0
  142. package/src/models/AgentSkillFilePin.ts +84 -0
  143. package/src/models/AgentSubagentEntry.ts +75 -0
  144. package/src/models/AgentVersionCreate.ts +65 -0
  145. package/src/models/AgentVersionDiffResource.ts +154 -0
  146. package/src/models/AgentVersionPick.ts +66 -0
  147. package/src/models/AgentVersionResource.ts +101 -0
  148. package/src/models/AppResource.ts +16 -0
  149. package/src/models/ResponseInput.ts +8 -0
  150. package/src/models/SkillUpdateResource.ts +75 -0
  151. package/src/models/index.ts +13 -0
  152. package/src/webhooks.ts +390 -0
@@ -6,11 +6,13 @@ exports.idempotencyKey = idempotencyKey;
6
6
  const node_crypto_1 = require("node:crypto");
7
7
  const AgentsApi_js_1 = require("../apis/AgentsApi.js");
8
8
  const ConversationsApi_js_1 = require("../apis/ConversationsApi.js");
9
+ const CustomAPIsApi_js_1 = require("../apis/CustomAPIsApi.js");
9
10
  const ResponsesApi_js_1 = require("../apis/ResponsesApi.js");
10
11
  const runtime_js_1 = require("../runtime.js");
11
12
  const streaming_js_1 = require("../streaming.js");
12
13
  const errors_js_1 = require("./errors.js");
13
14
  const events_js_1 = require("./events.js");
15
+ const transport_js_1 = require("./transport.js");
14
16
  const PAGE = 100;
15
17
  /** A post the server is still delivering (409 in_progress) is retried this many times, Retry-After apart. */
16
18
  const IN_PROGRESS_RETRIES = 5;
@@ -101,6 +103,24 @@ function firstDetail(error) {
101
103
  const first = Array.isArray(details) ? details[0] : undefined;
102
104
  return first !== null && typeof first === "object" && !Array.isArray(first) ? { ...first } : {};
103
105
  }
106
+ /** A deploy's 409 MISSING_DEPENDENCIES (the version uses a skill, app, knowledge base or sub-agent that was deleted
107
+ * since) as a UserError naming each one, else null. */
108
+ async function missingDependencies(err, agentId) {
109
+ if ((await reason(err, 409)) !== "MISSING_DEPENDENCIES")
110
+ return null;
111
+ const missing = firstDetail(await chatError(err))["missing"];
112
+ const items = Array.isArray(missing)
113
+ ? missing.filter((m) => m !== null && typeof m === "object")
114
+ : [];
115
+ const named = items.map((m) => `${m["kind"]} '${m["name"]}' (${m["id"]})`).join(", ");
116
+ return new errors_js_1.UserError(`agent ${agentId}: the new version can't go live because it uses something that was deleted` +
117
+ `${named ? ": " + named : ""}. Remove it from the agent, then deploy again`);
118
+ }
119
+ /** `AgentResource.versionState`; undefined from a server without versions (or an agent that is not managed). */
120
+ function versionStateOf(resource) {
121
+ var _a;
122
+ return (_a = resource.versionState) !== null && _a !== void 0 ? _a : undefined;
123
+ }
104
124
  function retryAfterMs(err) {
105
125
  var _a;
106
126
  const seconds = Number((_a = err.response.headers.get("retry-after")) !== null && _a !== void 0 ? _a : 2);
@@ -169,6 +189,14 @@ class Finished {
169
189
  }
170
190
  close() { }
171
191
  }
192
+ /** `settings` for a new agent's first write: no `webhooks` (the server checks them against the agent's bound
193
+ * credentials, and a new agent has none yet) and no `sdk_hash` (it covers the webhooks, so an agent left in this
194
+ * state would otherwise read as deployed and never get them). */
195
+ function withoutWebhooks(settings) {
196
+ const { webhooks: _webhooks, ...out } = settings;
197
+ const { sdk_hash: _hash, ...metadata } = settings["metadata"];
198
+ return { ...out, metadata };
199
+ }
172
200
  function isNotFound(err) {
173
201
  return err instanceof runtime_js_1.ResponseError && err.response.status === 404;
174
202
  }
@@ -205,6 +233,7 @@ class SettingsTransport {
205
233
  this.agents = new AgentsApi_js_1.AgentsApi(config);
206
234
  this.conversations = new ConversationsApi_js_1.ConversationsApi(config);
207
235
  this.responses = new ResponsesApi_js_1.ResponsesApi(config);
236
+ this.customApis = new CustomAPIsApi_js_1.CustomAPIsApi(config);
208
237
  }
209
238
  // -- agents ---------------------------------------------------------------------------------------------
210
239
  async findAgents(sdkName) {
@@ -233,20 +262,28 @@ class SettingsTransport {
233
262
  return this.remote(resource, await this.instructions(agentId));
234
263
  }
235
264
  async createAgent(agent) {
236
- var _a, _b;
265
+ var _a, _b, _c;
237
266
  const settings = agent.toSettings();
267
+ const webhooks = ((_a = settings["webhooks"]) !== null && _a !== void 0 ? _a : []);
268
+ // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
269
+ // without them, bind the Custom APIs they name, then write the settings in full.
270
+ const { bind, unbound } = await this.webhookCredentials(webhooks);
238
271
  let resource;
239
272
  try {
240
273
  resource = await this.agents.createAgent({
241
- agentCreate: { name: agent.name, instructions: agent.instructions, settings },
274
+ agentCreate: {
275
+ name: agent.name, instructions: agent.instructions,
276
+ settings: webhooks.length > 0 ? withoutWebhooks(settings) : settings,
277
+ },
242
278
  });
243
279
  }
244
280
  catch (err) {
245
281
  // A 422 stored nothing, so there is no agent to delete.
246
- throw (_a = (await invalidSettings(err))) !== null && _a !== void 0 ? _a : err;
282
+ throw (_b = (await invalidSettings(err))) !== null && _b !== void 0 ? _b : err;
247
283
  }
248
284
  let envelope;
249
285
  let warnings;
286
+ let live;
250
287
  // The create response never echoes settings, so support is read back from the settings route, which 404s
251
288
  // when the server has settings switched off (create then silently drops them).
252
289
  try {
@@ -258,9 +295,25 @@ class SettingsTransport {
258
295
  throw new errors_js_1.NotSupportedByServerError(["settings"]);
259
296
  throw err;
260
297
  }
298
+ if (webhooks.length > 0) {
299
+ for (const { path, name, customApiId } of bind)
300
+ await this.bind(resource.id, path, name, customApiId);
301
+ try {
302
+ envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
303
+ }
304
+ catch (err) {
305
+ const invalid = await invalidSettings(err);
306
+ if (invalid === null)
307
+ throw err;
308
+ throw new errors_js_1.UserError([invalid.message, ...unbound].join("; "), invalid.issues);
309
+ }
310
+ }
261
311
  warnings = checkWarnings(envelope, settings);
312
+ // Accepted unchecked (webhooks switched off): refused once they are on.
313
+ for (const sentence of unbound)
314
+ console.warn(`agent ${resource.id}: ${sentence}`);
262
315
  checkMetadata(envelope, agent);
263
- await this.agents.deployAgent({ agentId: resource.id });
316
+ live = await this.goLive(resource.id, versionStateOf(resource), agent);
264
317
  }
265
318
  catch (err) {
266
319
  // Don't leave an orphan agent behind; a failing cleanup must not mask the original error.
@@ -272,19 +325,77 @@ class SettingsTransport {
272
325
  }
273
326
  throw err;
274
327
  }
275
- return {
328
+ return withVersion({
276
329
  agentId: resource.id,
277
330
  name: agent.name,
278
331
  instructions: agent.instructions,
279
- settings: { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) },
332
+ settings: { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) },
280
333
  warnings,
281
- };
334
+ }, live, versionStateOf(resource));
335
+ }
336
+ /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
337
+ * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
338
+ * checks credentials). */
339
+ async webhookCredentials(webhooks) {
340
+ const bind = [];
341
+ const unbound = [];
342
+ const seen = new Set();
343
+ for (const [i, hook] of webhooks.entries()) {
344
+ const name = hook.secret_credential;
345
+ if (seen.has(name))
346
+ continue;
347
+ seen.add(name);
348
+ const path = `webhooks.${i}.secret_credential`;
349
+ const ids = await this.customApiIds(name);
350
+ if (ids.length === 1) {
351
+ bind.push({ path, name, customApiId: ids[0] });
352
+ }
353
+ else if (ids.length === 0) {
354
+ unbound.push(`${path}: you have no Custom API named '${name}' to bind to the new agent; create it, then ` +
355
+ "deploy again");
356
+ }
357
+ else {
358
+ unbound.push(`${path}: ${ids.length} of your Custom APIs are named '${name}', so none was bound to the new ` +
359
+ "agent; rename or delete all but one, then deploy again");
360
+ }
361
+ }
362
+ return { bind, unbound };
363
+ }
364
+ /** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
365
+ async customApiIds(name) {
366
+ const ids = [];
367
+ let offset = 0;
368
+ for (;;) {
369
+ const result = await this.customApis.listCustomApis({ q: name, limit: PAGE, offset });
370
+ const items = result.data;
371
+ for (const item of items)
372
+ if (item.name === name)
373
+ ids.push(item.id);
374
+ offset += items.length;
375
+ if (items.length === 0 || !result.hasMore)
376
+ return ids;
377
+ }
378
+ }
379
+ async bind(agentId, path, name, customApiId) {
380
+ var _a;
381
+ try {
382
+ await this.customApis.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
383
+ }
384
+ catch (err) {
385
+ const status = err instanceof runtime_js_1.ResponseError ? err.response.status : 0;
386
+ if (!(err instanceof runtime_js_1.ResponseError) || status < 400 || status >= 500)
387
+ throw err;
388
+ const message = (_a = (await chatError(err))) === null || _a === void 0 ? void 0 : _a["message"];
389
+ throw new errors_js_1.UserError(`${path}: could not bind the Custom API '${name}' to the new agent: ` +
390
+ (typeof message === "string" && message ? message : `HTTP ${status}`));
391
+ }
282
392
  }
283
393
  async updateAgent(agentId, agent) {
284
394
  var _a, _b;
285
395
  const settings = agent.toSettings();
286
396
  // findAgents searches by display name, so an adopted (or dashboard-renamed) agent must carry sdk_name.
287
- if ((await this.agents.getAgent({ agentId })).name !== agent.name) {
397
+ const current = await this.agents.getAgent({ agentId });
398
+ if (current.name !== agent.name) {
288
399
  await this.agents.updateAgent({ agentId, agentUpdate: { name: agent.name } });
289
400
  }
290
401
  // Rejections are only visible after the server stored the settings, so keep what was there to put it back.
@@ -330,14 +441,51 @@ class SettingsTransport {
330
441
  throw err;
331
442
  }
332
443
  checkMetadata(envelope, agent);
333
- await this.agents.deployAgent({ agentId }); // idempotent; moves an adopted draft to deployed
334
- return {
444
+ const live = await this.goLive(agentId, versionStateOf(current), agent);
445
+ return withVersion({
335
446
  agentId,
336
447
  name: agent.name,
337
448
  instructions: agent.instructions,
338
449
  settings: { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) },
339
450
  warnings,
340
- };
451
+ }, live, versionStateOf(current));
452
+ }
453
+ /** Make what was just written what end users get. A server without versions (no `versionState`) gets the bodiless
454
+ * deploy 0.3 sent; otherwise the draft is saved as a version and that version deployed. */
455
+ async goLive(agentId, versionState, agent) {
456
+ if (versionState === undefined) {
457
+ await this.agents.deployAgent({ agentId }); // idempotent; moves an adopted draft to deployed
458
+ return undefined;
459
+ }
460
+ return this.publish(agentId, transport_js_1.VERSION_NOTE);
461
+ }
462
+ /**
463
+ * Save the draft as the next version and make it live. 409 NO_CHANGES means the newest saved version already is the
464
+ * draft, so that version is deployed, by its number (never "the newest", which a save landing in between could
465
+ * change).
466
+ */
467
+ async publish(agentId, note) {
468
+ var _a, _b;
469
+ let version;
470
+ try {
471
+ version = (await this.agents.saveVersion({ agentId, agentVersionCreate: { note } })).version;
472
+ }
473
+ catch (err) {
474
+ if ((await reason(err, 409)) !== "NO_CHANGES")
475
+ throw err;
476
+ const newest = (await this.agents.getDraft({ agentId })).basedOnVersion;
477
+ if (newest === undefined || newest === null)
478
+ throw err;
479
+ version = newest;
480
+ }
481
+ let resource;
482
+ try {
483
+ resource = await this.agents.deployAgent({ agentId, agentDeploy: { version } });
484
+ }
485
+ catch (err) {
486
+ throw (_a = (await missingDependencies(err, agentId))) !== null && _a !== void 0 ? _a : err;
487
+ }
488
+ return (_b = resource.liveVersion) !== null && _b !== void 0 ? _b : undefined;
341
489
  }
342
490
  async deleteAgent(agentId) {
343
491
  await this.agents.deleteAgent({ agentId });
@@ -515,10 +663,26 @@ class SettingsTransport {
515
663
  }
516
664
  remote(resource, instructions) {
517
665
  var _a;
518
- return { agentId: resource.id, name: resource.name, instructions, settings: { ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }, warnings: [] };
666
+ const remote = {
667
+ agentId: resource.id, name: resource.name, instructions, settings: { ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }, warnings: [],
668
+ };
669
+ // Left out, not set to undefined, when the server has no versions: the shape a 0.3 transport returned.
670
+ if (resource.liveVersion !== undefined && resource.liveVersion !== null)
671
+ remote.liveVersion = resource.liveVersion;
672
+ const state = versionStateOf(resource);
673
+ if (state !== undefined)
674
+ remote.versionState = state;
675
+ return remote;
519
676
  }
520
677
  }
521
678
  exports.SettingsTransport = SettingsTransport;
679
+ /** `remote` with the version fields set when known (left out otherwise, as a server without versions returns it). After a
680
+ * publish the agent is live whatever state it was read in. */
681
+ function withVersion(remote, live, state) {
682
+ if (live !== undefined)
683
+ return { ...remote, liveVersion: live, versionState: "live" };
684
+ return state === undefined ? remote : { ...remote, versionState: state };
685
+ }
522
686
  /** The server's 422 CHAT_VALIDATION / invalid_agent_settings rejection as a UserError, else null. */
523
687
  async function invalidSettings(err) {
524
688
  if (!(err instanceof runtime_js_1.ResponseError) || err.response.status !== 422)
@@ -14,7 +14,15 @@ 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;
17
23
  }
24
+ /** The note on every version deploy() saves, so the dashboard's version list shows which came from code. */
25
+ export declare const VERSION_NOTE = "Deployed from the SDK";
18
26
  /** Async iterable of Events; the ids are filled in as the stream progresses. */
19
27
  export interface TurnStream extends AsyncIterable<Event> {
20
28
  readonly conversationId: string | null;
@@ -37,6 +45,9 @@ export interface Transport {
37
45
  createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
38
46
  updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
39
47
  deleteAgent(agentId: string): Promise<void>;
48
+ /** Save the draft as the next version and make that version live; resolves to the live version. Called only for
49
+ * an agent whose `versionState` is set. Optional so a transport written before versions still type-checks. */
50
+ publish?(agentId: string, note: string): Promise<number | undefined>;
40
51
  startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
41
52
  answerClarify(conversationId: string, requestId: string, answers: Record<string, unknown>, signal?: AbortSignal): Promise<TurnStream>;
42
53
  resume(conversationId: string, responseId: string, lastEventId: string | null, signal?: AbortSignal): Promise<TurnStream>;
@@ -1,2 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VERSION_NOTE = void 0;
4
+ /** The note on every version deploy() saves, so the dashboard's version list shows which came from code. */
5
+ exports.VERSION_NOTE = "Deployed from the SDK";
@@ -0,0 +1,19 @@
1
+ import type { WebhookEventType } from "../webhooks.js";
2
+ /** Where the agent reports a finished, failed or paused turn (agent.json `webhooks[]`). */
3
+ export interface Webhook {
4
+ /** An `https://` URL on port 443 with a DNS host; a query string is allowed. */
5
+ url: string;
6
+ /** 1 to 4 distinct events. `approval.requested` is reserved: accepted, not sent yet. */
7
+ events: WebhookEventType[];
8
+ /** The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). */
9
+ secretCredential: string;
10
+ }
11
+ export declare const WEBHOOKS_MAX = 5;
12
+ /** Why `url` is not an allowed webhook URL, or null. Every URL the server refuses is refused, with the server's
13
+ * sentence for every URL Python's `urlsplit` parses; for a netloc its NFKC check refuses, the sentence may differ. */
14
+ export declare function urlProblem(url: string): string | null;
15
+ /** The server's pure `webhooks` rules (types first); throws `UserError` naming the agent.json path. */
16
+ export declare function checkWebhooks(webhooks: unknown): void;
17
+ /** Only the three fields, in agent.json's names (a copy). */
18
+ export declare function copyWebhooks(webhooks: readonly Webhook[]): Webhook[];
19
+ export declare function webhooksJson(webhooks: readonly Webhook[]): Record<string, unknown>[];
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WEBHOOKS_MAX = void 0;
4
+ exports.urlProblem = urlProblem;
5
+ exports.checkWebhooks = checkWebhooks;
6
+ exports.copyWebhooks = copyWebhooks;
7
+ exports.webhooksJson = webhooksJson;
8
+ /**
9
+ * `webhooks` entries of `agent.json`, checked locally with the server's cheap rules (as the Python SDK does).
10
+ *
11
+ * The server (`claw_common/agent_settings/webhooks.py`) also checks that the host resolves to a public address and
12
+ * that `secret_credential` names a vault credential bound to the agent whose allowed hosts cover the URL; those need
13
+ * I/O and stay on the server, which refuses the save with a 422 that `deploy` throws as `UserError`. A new agent has
14
+ * no credentials bound yet, so the deploy that creates it binds the caller's Custom API of each named credential first
15
+ * (`SettingsTransport.createAgent`).
16
+ */
17
+ const errors_js_1 = require("./errors.js");
18
+ const webhooks_js_1 = require("../webhooks.js");
19
+ exports.WEBHOOKS_MAX = 5;
20
+ const WEBHOOK_URL_MAX = 2048;
21
+ const SECRET_CREDENTIAL_MAX = 256;
22
+ const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
23
+ // A last label that is a number (decimal, or 0x hex) makes resolvers read the whole host as an IPv4 address.
24
+ const NUMERIC_LABEL = /^(?:[0-9]+|0x[0-9a-f]*)$/;
25
+ const SCHEME = /^[A-Za-z][A-Za-z0-9+\-.]*$/;
26
+ /** Length in code points, as Python's `len`. */
27
+ function codePoints(text) {
28
+ return Array.from(text).length;
29
+ }
30
+ /** `[scheme, netloc, path, query]` as Python 3.12's `urlsplit` splits a URL without a fragment. */
31
+ function split(url) {
32
+ let rest = url;
33
+ let scheme = "";
34
+ const i = rest.indexOf(":");
35
+ if (i > 0 && SCHEME.test(rest.slice(0, i))) {
36
+ scheme = rest.slice(0, i).toLowerCase();
37
+ rest = rest.slice(i + 1);
38
+ }
39
+ let netloc = "";
40
+ if (rest.slice(0, 2) === "//") {
41
+ let end = rest.length;
42
+ for (const c of "/?#") {
43
+ const at = rest.indexOf(c, 2);
44
+ if (at >= 0)
45
+ end = Math.min(end, at);
46
+ }
47
+ netloc = rest.slice(2, end);
48
+ rest = rest.slice(end);
49
+ }
50
+ let query = "";
51
+ const q = rest.indexOf("?");
52
+ if (q >= 0) {
53
+ query = rest.slice(q + 1);
54
+ rest = rest.slice(0, q);
55
+ }
56
+ return [scheme, netloc, rest, query];
57
+ }
58
+ /** Python's `str.partition`. */
59
+ function partition(text, sep) {
60
+ const at = text.indexOf(sep);
61
+ return at < 0 ? [text, "", ""] : [text.slice(0, at), sep, text.slice(at + sep.length)];
62
+ }
63
+ /** `urlsplit`'s host (lowercased) and raw port (`null` when absent or empty). */
64
+ function hostPort(netloc) {
65
+ const hostinfo = netloc.slice(netloc.lastIndexOf("@") + 1);
66
+ const [, bracket, bracketed] = partition(hostinfo, "[");
67
+ let host;
68
+ let port;
69
+ if (bracket) {
70
+ const [inner, , after] = partition(bracketed, "]");
71
+ host = inner;
72
+ port = partition(after, ":")[2];
73
+ }
74
+ else {
75
+ [host, , port] = partition(hostinfo, ":");
76
+ }
77
+ return [host.toLowerCase(), port || null];
78
+ }
79
+ function stripTrailingDots(host) {
80
+ return host.replace(/\.+$/, "");
81
+ }
82
+ /** Why `url` is not an allowed webhook URL, or null. Every URL the server refuses is refused, with the server's
83
+ * sentence for every URL Python's `urlsplit` parses; for a netloc its NFKC check refuses, the sentence may differ. */
84
+ function urlProblem(url) {
85
+ if (codePoints(url) > WEBHOOK_URL_MAX)
86
+ return `url must be at most ${WEBHOOK_URL_MAX} characters.`;
87
+ for (let i = 0; i < url.length; i++) {
88
+ const code = url.charCodeAt(i);
89
+ if (code <= 0x20 || code === 0x7f)
90
+ return "url must not contain spaces or control characters.";
91
+ }
92
+ if (url.indexOf("#") !== -1)
93
+ return "url must not have a fragment.";
94
+ const [scheme, netloc, path] = split(url);
95
+ if (scheme !== "https")
96
+ return "url must start with https://.";
97
+ if (netloc.indexOf("@") !== -1)
98
+ return "url must not contain a user name or password.";
99
+ // urlsplit refuses unbalanced brackets outright
100
+ if ((netloc.indexOf("[") !== -1) !== (netloc.indexOf("]") !== -1)) {
101
+ return "url host must be a DNS name, not an IP address.";
102
+ }
103
+ const [rawHost, port] = hostPort(netloc);
104
+ if (port !== null) {
105
+ if (!/^[0-9]+$/.test(port) || Number(port) > 65535) {
106
+ return "url has an invalid port; leave the port out (443 is used).";
107
+ }
108
+ if (Number(port) !== 443)
109
+ return "url must use port 443; leave the port out.";
110
+ }
111
+ const host = stripTrailingDots(rawHost);
112
+ if (!host)
113
+ return "url must name a host, like https://hooks.example.com/panja.";
114
+ if (netloc.indexOf("[") !== -1)
115
+ return "url host must be a DNS name, not an IP address.";
116
+ const labels = host.split(".");
117
+ if (!labels.every((label) => LABEL.test(label)))
118
+ return "url host must be a DNS name, like hooks.example.com.";
119
+ if (NUMERIC_LABEL.test(labels[labels.length - 1]))
120
+ return "url host must be a DNS name, not an IP address.";
121
+ if (path.split("/").some((seg) => seg === "." || seg === ".."))
122
+ return "url path must not contain . or .. segments.";
123
+ return null;
124
+ }
125
+ /** Host (lowercased, no trailing dot, no port), path and query: two URLs with one key are one endpoint. */
126
+ function urlKey(url) {
127
+ const [, netloc, path, query] = split(url);
128
+ return `${stripTrailingDots(hostPort(netloc)[0])}${path}?${query}`;
129
+ }
130
+ /** The server's pure `webhooks` rules (types first); throws `UserError` naming the agent.json path. */
131
+ function checkWebhooks(webhooks) {
132
+ if (!Array.isArray(webhooks))
133
+ throw new errors_js_1.UserError("webhooks: must be a list of webhooks");
134
+ if (webhooks.length > exports.WEBHOOKS_MAX) {
135
+ throw new errors_js_1.UserError(`webhooks: webhooks may hold at most ${exports.WEBHOOKS_MAX} endpoints.`);
136
+ }
137
+ const seen = new Set();
138
+ webhooks.forEach((hook, i) => {
139
+ const where = `webhooks.${i}.`;
140
+ if (typeof hook !== "object" || hook === null || Array.isArray(hook)) {
141
+ throw new errors_js_1.UserError(`webhooks.${i}: must be an object with url, events and secretCredential`);
142
+ }
143
+ const { url, events, secretCredential } = hook;
144
+ if (typeof url !== "string")
145
+ throw new errors_js_1.UserError(where + "url: must be a string");
146
+ if (!Array.isArray(events) || !events.every((e) => typeof e === "string")) {
147
+ throw new errors_js_1.UserError(where + "events: must be a list of event names");
148
+ }
149
+ if (typeof secretCredential !== "string")
150
+ throw new errors_js_1.UserError(where + "secretCredential: must be a string");
151
+ // Python's Webhook is extra="forbid": a key dropped silently (a misplaced secret) would never verify.
152
+ const extra = Object.keys(hook).find((k) => k !== "url" && k !== "events" && k !== "secretCredential");
153
+ if (extra !== undefined)
154
+ throw new errors_js_1.UserError(where + extra + ": Extra inputs are not permitted");
155
+ const problem = urlProblem(url);
156
+ if (problem !== null)
157
+ throw new errors_js_1.UserError(where + "url: " + problem);
158
+ if (events.length < 1 || events.length > webhooks_js_1.WEBHOOK_EVENTS.length) {
159
+ throw new errors_js_1.UserError(where + `events: events must list 1 to ${webhooks_js_1.WEBHOOK_EVENTS.length} events.`);
160
+ }
161
+ if (events.some((e) => webhooks_js_1.WEBHOOK_EVENTS.indexOf(e) === -1)) {
162
+ throw new errors_js_1.UserError(where + `events: events must be from: ${webhooks_js_1.WEBHOOK_EVENTS.join(", ")}.`);
163
+ }
164
+ if (new Set(events).size !== events.length)
165
+ throw new errors_js_1.UserError(where + "events: events must not repeat an event.");
166
+ const n = codePoints(secretCredential);
167
+ if (n < 1 || n > SECRET_CREDENTIAL_MAX) {
168
+ throw new errors_js_1.UserError(where + "secret_credential: secret_credential must be the name of a vault credential " +
169
+ `(1 to ${SECRET_CREDENTIAL_MAX} characters).`);
170
+ }
171
+ const key = urlKey(url);
172
+ if (seen.has(key)) {
173
+ throw new errors_js_1.UserError(where + "url: webhooks must not list the same url twice; put all its events on one entry.");
174
+ }
175
+ seen.add(key);
176
+ });
177
+ }
178
+ /** Only the three fields, in agent.json's names (a copy). */
179
+ function copyWebhooks(webhooks) {
180
+ return webhooks.map((h) => ({ url: h.url, events: [...h.events], secretCredential: h.secretCredential }));
181
+ }
182
+ function webhooksJson(webhooks) {
183
+ return webhooks.map((h) => ({ url: h.url, events: [...h.events], secret_credential: h.secretCredential }));
184
+ }
@@ -43,12 +43,12 @@ export interface ListAgentConversationsRequest {
43
43
  */
44
44
  export declare class AgentConversationsApi extends runtime.BaseAPI {
45
45
  /**
46
- * Presign one file of a session from the log, signed on each click. The file belongs to the session\'s user, not to the caller, so the in-app presign (scoped to the caller) would 404. Instead: 1. List the session\'s artifacts as its owner and require ``artifact_id`` among them. Without this check, an agent owner could presign any file of that user by guessing an id, not just this session\'s. 2. Presign through the owner-identity route the share links use. The gateway still checks the ids against the artifact\'s real owner.
46
+ * Presign one file of a session from the log, signed on each click. The file belongs to the session\'s user, not to the caller, so the in-app presign (scoped to the caller) would 404. Instead: 1. List the session\'s artifacts as its owner and require ``artifact_id`` among them. Without this check, an agent owner could presign any file of that user by guessing an id, not just this session\'s. 2. Presign with the owner\'s identity, as share links do. The artifact service still checks the ids against the artifact\'s real owner. The URL is a presigned S3 URL while the file is plaintext; clients that can follow file-gateway URLs use the v2 route.
47
47
  * Agent Conversation Artifact Download Url Route
48
48
  */
49
49
  agentConversationArtifactDownloadUrlRaw(requestParameters: AgentConversationArtifactDownloadUrlRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<DownloadUrlResponse>>;
50
50
  /**
51
- * Presign one file of a session from the log, signed on each click. The file belongs to the session\'s user, not to the caller, so the in-app presign (scoped to the caller) would 404. Instead: 1. List the session\'s artifacts as its owner and require ``artifact_id`` among them. Without this check, an agent owner could presign any file of that user by guessing an id, not just this session\'s. 2. Presign through the owner-identity route the share links use. The gateway still checks the ids against the artifact\'s real owner.
51
+ * Presign one file of a session from the log, signed on each click. The file belongs to the session\'s user, not to the caller, so the in-app presign (scoped to the caller) would 404. Instead: 1. List the session\'s artifacts as its owner and require ``artifact_id`` among them. Without this check, an agent owner could presign any file of that user by guessing an id, not just this session\'s. 2. Presign with the owner\'s identity, as share links do. The artifact service still checks the ids against the artifact\'s real owner. The URL is a presigned S3 URL while the file is plaintext; clients that can follow file-gateway URLs use the v2 route.
52
52
  * Agent Conversation Artifact Download Url Route
53
53
  */
54
54
  agentConversationArtifactDownloadUrl(requestParameters: AgentConversationArtifactDownloadUrlRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<DownloadUrlResponse>;
@@ -18,7 +18,7 @@ import { AgentConversationDetailFromJSON, DownloadUrlResponseFromJSON, MessagesR
18
18
  */
19
19
  export class AgentConversationsApi extends runtime.BaseAPI {
20
20
  /**
21
- * Presign one file of a session from the log, signed on each click. The file belongs to the session\'s user, not to the caller, so the in-app presign (scoped to the caller) would 404. Instead: 1. List the session\'s artifacts as its owner and require ``artifact_id`` among them. Without this check, an agent owner could presign any file of that user by guessing an id, not just this session\'s. 2. Presign through the owner-identity route the share links use. The gateway still checks the ids against the artifact\'s real owner.
21
+ * Presign one file of a session from the log, signed on each click. The file belongs to the session\'s user, not to the caller, so the in-app presign (scoped to the caller) would 404. Instead: 1. List the session\'s artifacts as its owner and require ``artifact_id`` among them. Without this check, an agent owner could presign any file of that user by guessing an id, not just this session\'s. 2. Presign with the owner\'s identity, as share links do. The artifact service still checks the ids against the artifact\'s real owner. The URL is a presigned S3 URL while the file is plaintext; clients that can follow file-gateway URLs use the v2 route.
22
22
  * Agent Conversation Artifact Download Url Route
23
23
  */
24
24
  async agentConversationArtifactDownloadUrlRaw(requestParameters, initOverrides) {
@@ -55,7 +55,7 @@ export class AgentConversationsApi extends runtime.BaseAPI {
55
55
  return new runtime.JSONApiResponse(response, (jsonValue) => DownloadUrlResponseFromJSON(jsonValue));
56
56
  }
57
57
  /**
58
- * Presign one file of a session from the log, signed on each click. The file belongs to the session\'s user, not to the caller, so the in-app presign (scoped to the caller) would 404. Instead: 1. List the session\'s artifacts as its owner and require ``artifact_id`` among them. Without this check, an agent owner could presign any file of that user by guessing an id, not just this session\'s. 2. Presign through the owner-identity route the share links use. The gateway still checks the ids against the artifact\'s real owner.
58
+ * Presign one file of a session from the log, signed on each click. The file belongs to the session\'s user, not to the caller, so the in-app presign (scoped to the caller) would 404. Instead: 1. List the session\'s artifacts as its owner and require ``artifact_id`` among them. Without this check, an agent owner could presign any file of that user by guessing an id, not just this session\'s. 2. Presign with the owner\'s identity, as share links do. The artifact service still checks the ids against the artifact\'s real owner. The URL is a presigned S3 URL while the file is plaintext; clients that can follow file-gateway URLs use the v2 route.
59
59
  * Agent Conversation Artifact Download Url Route
60
60
  */
61
61
  async agentConversationArtifactDownloadUrl(requestParameters, initOverrides) {