sarvam-agents-client 0.5.2 → 0.5.4

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 (174) hide show
  1. package/README.md +52 -29
  2. package/dist/apis/AgentsApi.d.ts +96 -11
  3. package/dist/apis/AgentsApi.js +229 -9
  4. package/dist/apis/ConversationsApi.d.ts +5 -2
  5. package/dist/apis/ConversationsApi.js +7 -2
  6. package/dist/client.d.ts +3 -2
  7. package/dist/client.js +2 -1
  8. package/dist/compat/core/agents.d.ts +6 -1
  9. package/dist/compat/core/agents.js +237 -27
  10. package/dist/compat/core/customApis.d.ts +76 -0
  11. package/dist/compat/core/customApis.js +424 -0
  12. package/dist/compat/core/data.js +1 -1
  13. package/dist/compat/openai/client.d.ts +3 -0
  14. package/dist/compat/openai/client.js +5 -1
  15. package/dist/compat/openai/index.d.ts +1 -0
  16. package/dist/compat/openai/index.js +0 -1
  17. package/dist/compat/openai/resources/agents.js +8 -1
  18. package/dist/compat/openai/resources/sarvam.d.ts +26 -0
  19. package/dist/compat/openai/resources/sarvam.js +56 -0
  20. package/dist/compose/deploy.d.ts +14 -3
  21. package/dist/compose/deploy.js +60 -7
  22. package/dist/compose/errors.d.ts +4 -0
  23. package/dist/compose/errors.js +6 -1
  24. package/dist/compose/settingsTransport.d.ts +18 -13
  25. package/dist/compose/settingsTransport.js +78 -130
  26. package/dist/compose/transport.d.ts +12 -2
  27. package/dist/compose/webhook.d.ts +10 -13
  28. package/dist/compose/webhook.js +48 -45
  29. package/dist/compose/webhookSecrets.d.ts +79 -49
  30. package/dist/compose/webhookSecrets.js +244 -195
  31. package/dist/esm/apis/AgentsApi.d.ts +96 -11
  32. package/dist/esm/apis/AgentsApi.js +230 -10
  33. package/dist/esm/apis/ConversationsApi.d.ts +5 -2
  34. package/dist/esm/apis/ConversationsApi.js +7 -2
  35. package/dist/esm/client.d.ts +3 -2
  36. package/dist/esm/client.js +2 -1
  37. package/dist/esm/compat/core/agents.d.ts +6 -1
  38. package/dist/esm/compat/core/agents.js +237 -27
  39. package/dist/esm/compat/core/customApis.d.ts +76 -0
  40. package/dist/esm/compat/core/customApis.js +419 -0
  41. package/dist/esm/compat/core/data.js +1 -1
  42. package/dist/esm/compat/openai/client.d.ts +3 -0
  43. package/dist/esm/compat/openai/client.js +5 -1
  44. package/dist/esm/compat/openai/index.d.ts +1 -0
  45. package/dist/esm/compat/openai/index.js +0 -1
  46. package/dist/esm/compat/openai/resources/agents.js +8 -1
  47. package/dist/esm/compat/openai/resources/sarvam.d.ts +26 -0
  48. package/dist/esm/compat/openai/resources/sarvam.js +51 -0
  49. package/dist/esm/compose/deploy.d.ts +14 -3
  50. package/dist/esm/compose/deploy.js +60 -7
  51. package/dist/esm/compose/errors.d.ts +4 -0
  52. package/dist/esm/compose/errors.js +4 -0
  53. package/dist/esm/compose/settingsTransport.d.ts +18 -13
  54. package/dist/esm/compose/settingsTransport.js +80 -132
  55. package/dist/esm/compose/transport.d.ts +12 -2
  56. package/dist/esm/compose/webhook.d.ts +10 -13
  57. package/dist/esm/compose/webhook.js +45 -42
  58. package/dist/esm/compose/webhookSecrets.d.ts +79 -49
  59. package/dist/esm/compose/webhookSecrets.js +241 -193
  60. package/dist/esm/index.d.ts +2 -1
  61. package/dist/esm/index.js +2 -1
  62. package/dist/esm/models/AgentConversationDetail.d.ts +12 -0
  63. package/dist/esm/models/AgentConversationDetail.js +4 -0
  64. package/dist/esm/models/AgentConversationView.d.ts +12 -0
  65. package/dist/esm/models/AgentConversationView.js +4 -0
  66. package/dist/esm/models/AgentResource.d.ts +7 -0
  67. package/dist/esm/models/AgentResource.js +3 -0
  68. package/dist/esm/models/AgentVersionSavedResource.d.ts +65 -0
  69. package/dist/esm/models/AgentVersionSavedResource.js +60 -0
  70. package/dist/esm/models/AgentWebhookList.d.ts +33 -0
  71. package/dist/esm/models/AgentWebhookList.js +44 -0
  72. package/dist/esm/models/AgentWebhookView.d.ts +76 -0
  73. package/dist/esm/models/AgentWebhookView.js +70 -0
  74. package/dist/esm/models/ConversationDetail.d.ts +6 -0
  75. package/dist/esm/models/ConversationDetail.js +2 -0
  76. package/dist/esm/models/ConversationView.d.ts +6 -0
  77. package/dist/esm/models/ConversationView.js +2 -0
  78. package/dist/esm/models/ErrorDetailItem.d.ts +3 -0
  79. package/dist/esm/models/FileNodeView.d.ts +7 -0
  80. package/dist/esm/models/FileNodeView.js +3 -0
  81. package/dist/esm/models/QueueMessageInput.d.ts +6 -0
  82. package/dist/esm/models/QueueMessageInput.js +2 -0
  83. package/dist/esm/models/RotatedWebhookSecretView.d.ts +58 -0
  84. package/dist/esm/models/RotatedWebhookSecretView.js +61 -0
  85. package/dist/esm/models/SaveWarningView.d.ts +44 -0
  86. package/dist/esm/models/SaveWarningView.js +51 -0
  87. package/dist/esm/models/ShareSkippedResource.d.ts +41 -0
  88. package/dist/esm/models/ShareSkippedResource.js +47 -0
  89. package/dist/esm/models/WebhookSecretPutBody.d.ts +32 -0
  90. package/dist/esm/models/WebhookSecretPutBody.js +43 -0
  91. package/dist/esm/models/WebhookSecretStateView.d.ts +52 -0
  92. package/dist/esm/models/WebhookSecretStateView.js +56 -0
  93. package/dist/esm/models/WebhookSecretValueView.d.ts +32 -0
  94. package/dist/esm/models/WebhookSecretValueView.js +44 -0
  95. package/dist/esm/models/WebhookWarning.d.ts +44 -0
  96. package/dist/esm/models/WebhookWarning.js +51 -0
  97. package/dist/esm/models/index.d.ts +10 -0
  98. package/dist/esm/models/index.js +10 -0
  99. package/dist/index.d.ts +2 -1
  100. package/dist/index.js +4 -1
  101. package/dist/models/AgentConversationDetail.d.ts +12 -0
  102. package/dist/models/AgentConversationDetail.js +4 -0
  103. package/dist/models/AgentConversationView.d.ts +12 -0
  104. package/dist/models/AgentConversationView.js +4 -0
  105. package/dist/models/AgentResource.d.ts +7 -0
  106. package/dist/models/AgentResource.js +3 -0
  107. package/dist/models/AgentVersionSavedResource.d.ts +65 -0
  108. package/dist/models/AgentVersionSavedResource.js +67 -0
  109. package/dist/models/AgentWebhookList.d.ts +33 -0
  110. package/dist/models/AgentWebhookList.js +51 -0
  111. package/dist/models/AgentWebhookView.d.ts +76 -0
  112. package/dist/models/AgentWebhookView.js +78 -0
  113. package/dist/models/ConversationDetail.d.ts +6 -0
  114. package/dist/models/ConversationDetail.js +2 -0
  115. package/dist/models/ConversationView.d.ts +6 -0
  116. package/dist/models/ConversationView.js +2 -0
  117. package/dist/models/ErrorDetailItem.d.ts +3 -0
  118. package/dist/models/FileNodeView.d.ts +7 -0
  119. package/dist/models/FileNodeView.js +3 -0
  120. package/dist/models/QueueMessageInput.d.ts +6 -0
  121. package/dist/models/QueueMessageInput.js +2 -0
  122. package/dist/models/RotatedWebhookSecretView.d.ts +58 -0
  123. package/dist/models/RotatedWebhookSecretView.js +69 -0
  124. package/dist/models/SaveWarningView.d.ts +44 -0
  125. package/dist/models/SaveWarningView.js +58 -0
  126. package/dist/models/ShareSkippedResource.d.ts +41 -0
  127. package/dist/models/ShareSkippedResource.js +54 -0
  128. package/dist/models/WebhookSecretPutBody.d.ts +32 -0
  129. package/dist/models/WebhookSecretPutBody.js +50 -0
  130. package/dist/models/WebhookSecretStateView.d.ts +52 -0
  131. package/dist/models/WebhookSecretStateView.js +64 -0
  132. package/dist/models/WebhookSecretValueView.d.ts +32 -0
  133. package/dist/models/WebhookSecretValueView.js +51 -0
  134. package/dist/models/WebhookWarning.d.ts +44 -0
  135. package/dist/models/WebhookWarning.js +58 -0
  136. package/dist/models/index.d.ts +10 -0
  137. package/dist/models/index.js +10 -0
  138. package/package.json +1 -1
  139. package/src/apis/AgentsApi.ts +366 -11
  140. package/src/apis/ConversationsApi.ts +9 -2
  141. package/src/client.ts +3 -2
  142. package/src/compat/core/agents.ts +265 -36
  143. package/src/compat/core/customApis.ts +506 -0
  144. package/src/compat/core/data.ts +1 -1
  145. package/src/compat/openai/client.ts +7 -1
  146. package/src/compat/openai/index.ts +9 -0
  147. package/src/compat/openai/resources/agents.ts +9 -1
  148. package/src/compat/openai/resources/sarvam.ts +94 -0
  149. package/src/compose/deploy.ts +71 -10
  150. package/src/compose/errors.ts +4 -0
  151. package/src/compose/settingsTransport.ts +78 -131
  152. package/src/compose/transport.ts +10 -2
  153. package/src/compose/webhook.ts +49 -45
  154. package/src/compose/webhookSecrets.ts +227 -179
  155. package/src/index.ts +2 -1
  156. package/src/models/AgentConversationDetail.ts +16 -0
  157. package/src/models/AgentConversationView.ts +16 -0
  158. package/src/models/AgentResource.ts +15 -0
  159. package/src/models/AgentVersionSavedResource.ts +119 -0
  160. package/src/models/AgentWebhookList.ts +74 -0
  161. package/src/models/AgentWebhookView.ts +129 -0
  162. package/src/models/ConversationDetail.ts +8 -0
  163. package/src/models/ConversationView.ts +8 -0
  164. package/src/models/ErrorDetailItem.ts +3 -0
  165. package/src/models/FileNodeView.ts +16 -0
  166. package/src/models/QueueMessageInput.ts +8 -0
  167. package/src/models/RotatedWebhookSecretView.ts +103 -0
  168. package/src/models/SaveWarningView.ts +84 -0
  169. package/src/models/ShareSkippedResource.ts +78 -0
  170. package/src/models/WebhookSecretPutBody.ts +66 -0
  171. package/src/models/WebhookSecretStateView.ts +94 -0
  172. package/src/models/WebhookSecretValueView.ts +66 -0
  173. package/src/models/WebhookWarning.ts +84 -0
  174. package/src/models/index.ts +10 -0
@@ -1,56 +1,44 @@
1
1
  "use strict";
2
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
- if (kind === "m") throw new TypeError("Private method is not writable");
4
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
- };
8
2
  var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
3
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
4
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
5
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
6
  };
13
- var _WebhookSecrets_backend;
7
+ var _WebhookSecrets_instances, _WebhookSecrets_view;
14
8
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.WebhookSecrets = exports.PLACEHOLDER_DESCRIPTION = exports.SECRET_DESCRIPTION = void 0;
16
- exports.secretBackend = secretBackend;
9
+ exports.WebhookSecrets = exports.PREVIOUS_SECRET_SECONDS = void 0;
10
+ exports.errorCode = errorCode;
11
+ exports.createMissingSecrets = createMissingSecrets;
17
12
  /**
18
- * `client.webhooks`: set, rotate, check and delete an agent webhook's signing secret (as Python's
19
- * `sarvam_agents.compose.webhook_secrets`).
13
+ * `client.webhooks`: list an agent's webhooks, and create, view, rotate, set and delete each one's signing secret (as
14
+ * Python's `sarvam_agents.compose.webhook_secrets`).
20
15
  *
21
- * The public surface is `WebhookSecrets`. Where the secret lives is behind `SecretBackend`, one small interface with
22
- * one implementation today, `CustomApiBackend`: the secret is a bearer Custom API the SDK creates, owns and binds to
23
- * the agent, always with `enabledForChats: false` (`CustomApiCreate` defaults it to true, which would let the agent's
24
- * sandbox be handed the secret on requests to the webhook's host). When the server ships dedicated secret endpoints
25
- * (SARC-2597: PUT/DELETE secret, rotate-secret, secretStatus), a second backend replaces this one in `secretBackend`
26
- * and nothing else changes.
16
+ * Built on the owner-only routes of the server's webhook secret store (panja #1857, SARC-2597):
17
+ * `GET /v1/agents/{id}/webhooks` and `POST`/`GET`/`PUT`/`DELETE .../webhooks/{webhookKey}/secret` and
18
+ * `POST .../rotate-secret`. The `webhookKey` is always read from the list, by the webhook's exact URL; it is never
19
+ * computed here.
27
20
  *
28
21
  * No secret is logged, kept on an object or put in an error message.
29
22
  */
30
- const CustomAPIsApi_js_1 = require("../apis/CustomAPIsApi.js");
23
+ const AgentsApi_js_1 = require("../apis/AgentsApi.js");
31
24
  const runtime_js_1 = require("../runtime.js");
32
25
  const errors_js_1 = require("./errors.js");
33
26
  // Loaded on first use, so the root entry point (which exports `Client`) does not import `node:crypto` up front.
34
27
  const loadWebhook = () => Promise.resolve().then(() => require("./webhook.js"));
35
28
  const loadCrypto = () => Promise.resolve().then(() => require("../webhooks.js"));
36
- /** Every Custom API the SDK creates for a webhook secret carries this description (and its name). */
37
- exports.SECRET_DESCRIPTION = "Webhook signing secret managed by the Sarvam Agents SDK (client.webhooks). Do not edit.";
38
- /** The description of the random secret `deploy` stores when none is set yet: `secretStatus` reads it as
39
- * `"missing"`, and `setSecret`/`rotateSecret` overwrite it with `SECRET_DESCRIPTION`. */
40
- exports.PLACEHOLDER_DESCRIPTION = "Webhook signing secret managed by the Sarvam Agents SDK (client.webhooks). Placeholder: call client.webhooks.set_secret";
41
- const OWNED = [exports.SECRET_DESCRIPTION, exports.PLACEHOLDER_DESCRIPTION];
42
- const PAGE = 100;
29
+ /** How long a replaced secret keeps signing after `rotateSecret` or `setSecret` (fixed by the server). */
30
+ exports.PREVIOUS_SECRET_SECONDS = 86400;
43
31
  /** Throws `SecretFormatError` unless `secret` is `whsec_` plus base64 of 24 to 64 bytes (the verifier's own parser). */
44
32
  async function checkSecret(secret) {
45
33
  (await loadCrypto()).sign(secret, { msgId: "check", timestamp: 0, body: "" });
46
34
  }
47
- async function urlOf(hook) {
48
- const url = typeof hook === "string" ? hook : hook === null || hook === void 0 ? void 0 : hook.url;
35
+ async function urlOf(webhook) {
36
+ const url = typeof webhook === "string" ? webhook : webhook === null || webhook === void 0 ? void 0 : webhook.url;
49
37
  if (typeof url !== "string")
50
- throw new errors_js_1.UserError("webhook: pass the webhook's URL (a string) or a webhook");
38
+ throw new errors_js_1.UserError("url: pass the webhook's URL (a string) or a webhook");
51
39
  const problem = (await loadWebhook()).urlProblem(url);
52
40
  if (problem !== null)
53
- throw new errors_js_1.UserError("webhook: " + problem);
41
+ throw new errors_js_1.UserError("url: " + problem);
54
42
  return url;
55
43
  }
56
44
  function agent(agentId) {
@@ -61,195 +49,256 @@ function agent(agentId) {
61
49
  function status(err) {
62
50
  return err instanceof runtime_js_1.ResponseError ? err.response.status : 0;
63
51
  }
64
- /** The server's reason, never its raw body: a 422 may echo the request, and the request carries the secret. */
65
- async function apiMessage(err, secret) {
66
- var _a, _b;
67
- let message;
68
- if (err instanceof runtime_js_1.ResponseError) {
69
- try {
70
- message = (_b = (_a = ((await err.response.clone().json()))) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.message;
71
- }
72
- catch (_c) {
73
- message = undefined;
74
- }
52
+ /** The chat_service `error` object of a refusal, or null (the framework's own answer, e.g. no such route). */
53
+ async function chatError(err) {
54
+ var _a;
55
+ if (!(err instanceof runtime_js_1.ResponseError))
56
+ return null;
57
+ try {
58
+ const error = (_a = ((await err.response.clone().json()))) === null || _a === void 0 ? void 0 : _a.error;
59
+ return typeof error === "object" && error !== null ? error : null;
75
60
  }
61
+ catch (_b) {
62
+ return null;
63
+ }
64
+ }
65
+ /** The server's reason, never its raw body: a 422 may echo the request, and the request may carry the secret. */
66
+ async function apiMessage(err, secret) {
67
+ var _a;
68
+ const message = (_a = (await chatError(err))) === null || _a === void 0 ? void 0 : _a.message;
76
69
  if (typeof message !== "string" || !message || (secret !== undefined && message.includes(secret))) {
77
70
  return `HTTP ${status(err) || "error"}`;
78
71
  }
79
72
  return message;
80
73
  }
81
- /** Today's store: a bearer Custom API the SDK owns, bound to the agent, never enabled for chats. */
82
- class CustomApiBackend {
83
- constructor(api) {
84
- this.api = api;
85
- }
86
- /** The caller's Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
87
- async named(name) {
88
- const found = [];
89
- let offset = 0;
90
- for (;;) {
91
- const result = await this.api.listCustomApis({ q: name, limit: PAGE, offset });
92
- for (const item of result.data)
93
- if (item.name === name)
94
- found.push(item);
95
- offset += result.data.length;
96
- if (result.data.length === 0 || !result.hasMore)
97
- return found;
98
- }
99
- }
100
- /** The Custom APIs named `name` that the SDK created; throws when only someone else's has the name. */
101
- async owned(name) {
102
- const named = await this.named(name);
103
- const owned = named.filter((item) => { var _a; return OWNED.includes((_a = item.description) !== null && _a !== void 0 ? _a : ""); });
104
- if (named.length > 0 && owned.length === 0) {
105
- throw new errors_js_1.UserError(`a Custom API named '${name}' exists that the SDK did not create; it was left alone. ` +
106
- "Rename or delete it, then try again");
107
- }
108
- return owned;
109
- }
110
- async bind(agentId, customApiId) {
111
- const bound = (await this.api.listAgentCustomApis({ agentId })).data;
112
- if (bound.some((item) => item.id === customApiId))
113
- return;
74
+ /** The fine-grained reason of a chat_service error (`details[0].code` or `.reason`), else undefined. */
75
+ async function errorCode(err) {
76
+ var _a;
77
+ const details = (_a = (await chatError(err))) === null || _a === void 0 ? void 0 : _a.details;
78
+ if (Array.isArray(details) && typeof details[0] === "object" && details[0] !== null) {
79
+ const { reason, code } = details[0];
80
+ const value = code !== null && code !== void 0 ? code : reason;
81
+ return typeof value === "string" ? value : undefined;
82
+ }
83
+ return undefined;
84
+ }
85
+ /** What to do about each refusal the secret routes answer with (`error.details[0].code`). */
86
+ const REFUSALS = {
87
+ webhook_not_found: "the agent has no such webhook (any more); deploy the agent with it first",
88
+ secret_missing: "it has no signing secret; create one with createSecret",
89
+ invalid_secret: "the server refused the secret (a whsec_ secret: base64 of 24 to 64 bytes)",
90
+ secret_unreadable: "its secret can no longer be decrypted on the server; rotate it (rotateSecret) or set a new " +
91
+ "one (setSecret)",
92
+ secret_store_unavailable: "the server cannot store webhook secrets right now; try again later",
93
+ };
94
+ async function refusal(err, what, secret) {
95
+ if (!(err instanceof runtime_js_1.ResponseError))
96
+ return err;
97
+ const code = await errorCode(err);
98
+ if (status(err) === 409 && code === "secret_exists") {
99
+ return new errors_js_1.SecretExistsError(`${what}: it already has a signing secret; replace it with rotateSecret, view it ` +
100
+ "with getSecret, or delete it first");
101
+ }
102
+ if (code !== undefined && code in REFUSALS)
103
+ return new errors_js_1.UserError(`${what}: ${REFUSALS[code]}`);
104
+ if (status(err) === 404) {
105
+ return new errors_js_1.UserError(`${what}: not found (or not yours; only the agent's owner manages its webhook secrets)`);
106
+ }
107
+ if (status(err) === 403)
108
+ return new errors_js_1.UserError(`${what}: only the agent's owner manages its webhook secrets`);
109
+ return new errors_js_1.UserError(`${what}: ${await apiMessage(err, secret)}`);
110
+ }
111
+ /**
112
+ * `client.webhooks`: an agent's agent.json webhooks and each one's signing secret.
113
+ *
114
+ * `url` is the webhook's URL exactly as in agent.json (or a webhook object). Its `webhookKey` is read from `list` by
115
+ * exact URL match, so the agent must have the webhook (`deploy` it first). Secrets are `whsec_` plus base64 of 24 to
116
+ * 64 bytes. Only the agent's owner can call these.
117
+ *
118
+ * `deploy` already creates the secret of each webhook it adds and returns it once (`Deployment.webhookSecrets`).
119
+ * Nothing is delivered to a webhook without a secret.
120
+ */
121
+ class WebhookSecrets {
122
+ constructor(config) {
123
+ _WebhookSecrets_instances.add(this);
124
+ this.api = new AgentsApi_js_1.AgentsApi(config);
125
+ }
126
+ /**
127
+ * The agent's webhooks, each with `webhookKey`, `url`, `events`, `inAgentJson`, `secretStatus` (`"set"` or
128
+ * `"missing"`), `secretUpdatedAt` and, during the 24 hours after a rotation, `previousExpiresAt`.
129
+ *
130
+ * After them come orphans: a secret whose webhook was removed from agent.json is kept (the same URL added back signs
131
+ * with it again) and listed with `inAgentJson: false` and `url: null` (the server keeps only the key). Remove one
132
+ * with `deleteSecret(agentId, { webhookKey })`.
133
+ */
134
+ async list(agentId) {
135
+ var _a;
136
+ const id = agent(agentId);
114
137
  try {
115
- await this.api.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
138
+ return (_a = (await this.api.listAgentWebhooks({ agentId: id })).items) !== null && _a !== void 0 ? _a : [];
116
139
  }
117
140
  catch (err) {
118
- if (status(err) === 409)
119
- return; // bound meanwhile
120
- throw new errors_js_1.UserError(`could not bind the webhook secret to agent ${agentId}: ${await apiMessage(err)}`);
121
- }
122
- }
123
- /** PATCH the secret in, always asking for `enabledForChats: false`. The server switches chats off by detaching a
124
- * capability, and answers 404 when there is nothing to detach (the API is already off). Then the API is read
125
- * back: only when it exists and is off is the PATCH sent again without the switch, so the secret still lands and
126
- * chats stay off. */
127
- async update(customApiId, host, description, secret) {
128
- const patch = (off) => this.api.updateCustomApi({ customApiId, customApiUpdate: {
129
- host, description, auth: { type: "bearer", token: secret }, ...off,
130
- } });
141
+ throw await refusal(err, `agent ${id}`);
142
+ }
143
+ }
144
+ /** `"set"` or `"missing"` (nothing is sent to a webhook without a secret). */
145
+ async secretStatus(agentId, url) {
146
+ const id = agent(agentId);
147
+ return (await __classPrivateFieldGet(this, _WebhookSecrets_instances, "m", _WebhookSecrets_view).call(this, id, await urlOf(url))).secretStatus;
148
+ }
149
+ /** The webhook's current signing secret, to view again at any time (never the previous one during a rotation).
150
+ * Throws `UserError` when it has none. If it leaked, rotate it. */
151
+ async getSecret(agentId, url) {
152
+ const id = agent(agentId);
153
+ const u = await urlOf(url);
154
+ const { webhookKey } = await __classPrivateFieldGet(this, _WebhookSecrets_instances, "m", _WebhookSecrets_view).call(this, id, u);
131
155
  try {
132
- await patch({ enabledForChats: false });
156
+ return (await this.api.viewAgentWebhookSecret({ agentId: id, webhookKey })).secret;
133
157
  }
134
158
  catch (err) {
135
- if (status(err) !== 404)
136
- throw err;
137
- if ((await this.api.getCustomApi({ customApiId })).enabledForChats !== false)
138
- throw err; // gone (404) or on
139
- await patch({});
140
- }
141
- }
142
- async store(agentId, url, secret, owned, description = exports.SECRET_DESCRIPTION) {
143
- const { secretCredentialName, webhookHost } = await loadWebhook();
144
- const name = secretCredentialName(agentId, url);
145
- const host = webhookHost(url);
146
- let customApiId;
159
+ throw await refusal(err, `webhook ${u} of agent ${id}`);
160
+ }
161
+ }
162
+ /** Create the webhook's first signing secret (or a new one after a delete) and return it. Give it to your receiver.
163
+ * Throws `SecretExistsError` when the webhook already has one: rotate it instead. */
164
+ async createSecret(agentId, url) {
165
+ const id = agent(agentId);
166
+ const u = await urlOf(url);
167
+ const { webhookKey } = await __classPrivateFieldGet(this, _WebhookSecrets_instances, "m", _WebhookSecrets_view).call(this, id, u);
147
168
  try {
148
- if (owned.length > 0) {
149
- customApiId = owned[0].id;
150
- await this.update(customApiId, host, description, secret);
151
- }
152
- else {
153
- customApiId = (await this.api.createCustomApi({ customApiCreate: {
154
- name, description, host, enabledForChats: false, auth: { type: "bearer", token: secret },
155
- } })).id;
156
- }
169
+ return (await this.api.createAgentWebhookSecret({ agentId: id, webhookKey })).secret;
157
170
  }
158
171
  catch (err) {
159
- if (!(err instanceof runtime_js_1.ResponseError))
160
- throw err;
161
- throw new errors_js_1.UserError(`could not store the webhook secret for ${host}: ${await apiMessage(err, secret)}`);
162
- }
163
- await this.bind(agentId, customApiId);
164
- return name;
165
- }
166
- async put(agentId, url, secret) {
167
- await this.store(agentId, url, secret, await this.owned((await loadWebhook()).secretCredentialName(agentId, url)));
168
- }
169
- async status(agentId, url) {
170
- const name = (await loadWebhook()).secretCredentialName(agentId, url);
171
- // Not a placeholder, not someone else's.
172
- const stored = (await this.named(name)).filter((item) => item.description === exports.SECRET_DESCRIPTION).map((i) => i.id);
173
- if (stored.length === 0)
174
- return "missing";
175
- const bound = (await this.api.listAgentCustomApis({ agentId })).data;
176
- return bound.some((item) => stored.includes(item.id)) ? "set" : "missing";
177
- }
178
- async delete(agentId, url) {
179
- for (const item of await this.owned((await loadWebhook()).secretCredentialName(agentId, url))) {
180
- try {
181
- await this.api.unbindCustomApi({ agentId, customApiId: item.id });
182
- }
183
- catch (err) {
184
- if (status(err) !== 404)
185
- throw err;
186
- }
187
- try {
188
- await this.api.deleteCustomApi({ customApiId: item.id });
189
- }
190
- catch (err) {
191
- if (status(err) !== 404)
192
- throw err;
193
- }
172
+ throw await refusal(err, `webhook ${u} of agent ${id}`);
194
173
  }
195
174
  }
196
- async ensure(agentId, url) {
197
- const name = (await loadWebhook()).secretCredentialName(agentId, url);
198
- const owned = await this.owned(name);
199
- if (owned.length > 0) {
200
- await this.bind(agentId, owned[0].id);
201
- return { name, status: owned[0].description === exports.SECRET_DESCRIPTION ? "set" : "missing" };
175
+ /**
176
+ * Replace the webhook's signing secret with a new one the server generates, and return it.
177
+ *
178
+ * The old secret keeps signing for 24 hours (fixed), so every delivery meanwhile carries both signatures: switch
179
+ * your receiver to the new secret within that time. There is one previous slot: rotating again within the 24 hours
180
+ * drops the first old secret at once. After a leak, cut over at once instead: `deleteSecret`, then `createSecret`.
181
+ * Throws `UserError` when the webhook has no secret: create one first.
182
+ */
183
+ async rotateSecret(agentId, url) {
184
+ const id = agent(agentId);
185
+ const u = await urlOf(url);
186
+ const { webhookKey } = await __classPrivateFieldGet(this, _WebhookSecrets_instances, "m", _WebhookSecrets_view).call(this, id, u);
187
+ try {
188
+ return (await this.api.rotateAgentWebhookSecret({ agentId: id, webhookKey })).secret;
189
+ }
190
+ catch (err) {
191
+ throw await refusal(err, `webhook ${u} of agent ${id}`);
202
192
  }
203
- console.warn(`agent ${agentId}: webhook ${url} has no signing secret yet; stored a random one nobody holds, so ` +
204
- "deliveries fail verification until you call client.webhooks.setSecret");
205
- const stored = await this.store(agentId, url, (await loadCrypto()).generateSecret(), owned, exports.PLACEHOLDER_DESCRIPTION);
206
- return { name: stored, status: "missing" };
207
- }
208
- }
209
- /** The one place that picks where secrets live. */
210
- function secretBackend(api) {
211
- var _a;
212
- return new CustomApiBackend((_a = api.customApis) !== null && _a !== void 0 ? _a : new CustomAPIsApi_js_1.CustomAPIsApi(api.config));
213
- }
214
- /**
215
- * `client.webhooks`: the signing secret of each agent.json webhook.
216
- *
217
- * `webhook` is the webhook's URL (or a webhook object); the secret covers the URL's host. Secrets are `whsec_` plus
218
- * base64 of 24 to 64 bytes.
219
- */
220
- class WebhookSecrets {
221
- constructor(config) {
222
- _WebhookSecrets_backend.set(this, void 0);
223
- __classPrivateFieldSet(this, _WebhookSecrets_backend, secretBackend({ config }), "f");
224
193
  }
225
- /** Store `secret` (a new generated one when left out) as the webhook's signing secret and return it. A malformed
226
- * secret throws `SecretFormatError` before anything is sent. */
227
- async setSecret(agentId, webhook, secret) {
194
+ async setSecret(agentId, url, secret) {
228
195
  const id = agent(agentId);
229
- const url = await urlOf(webhook);
230
- const value = secret === undefined ? (await loadCrypto()).generateSecret() : secret;
231
- if (secret !== undefined)
196
+ const u = await urlOf(url);
197
+ const generated = secret === undefined;
198
+ let value;
199
+ if (generated) {
200
+ console.warn("client.webhooks.setSecret(agentId, url) without a secret is deprecated: call createSecret (no " +
201
+ "secret yet) or rotateSecret (replace it) instead");
202
+ value = (await loadCrypto()).generateSecret();
203
+ }
204
+ else {
205
+ if (typeof secret !== "string")
206
+ throw new errors_js_1.UserError("secret: pass the whsec_ secret as a string");
232
207
  await checkSecret(secret);
233
- await __classPrivateFieldGet(this, _WebhookSecrets_backend, "f").put(id, url, value);
234
- return value;
235
- }
236
- /** Replace the webhook's signing secret with a new generated one and return it. Have your receiver accept the old
237
- * and the new secret for a few minutes: a delivery still retrying is signed with the new one. */
238
- async rotateSecret(agentId, webhook) {
239
- return this.setSecret(agentId, webhook);
240
- }
241
- /** `"set"` when the agent has a signing secret stored by `setSecret` or `rotateSecret` for the webhook; `"missing"`
242
- * otherwise, including while it holds the placeholder a deploy stored. */
243
- async secretStatus(agentId, webhook) {
244
- const id = agent(agentId);
245
- return __classPrivateFieldGet(this, _WebhookSecrets_backend, "f").status(id, await urlOf(webhook));
208
+ value = secret;
209
+ }
210
+ const { webhookKey } = await __classPrivateFieldGet(this, _WebhookSecrets_instances, "m", _WebhookSecrets_view).call(this, id, u);
211
+ try {
212
+ await this.api.putAgentWebhookSecret({ agentId: id, webhookKey, webhookSecretPutBody: { secret: value } });
213
+ }
214
+ catch (err) {
215
+ throw await refusal(err, `webhook ${u} of agent ${id}`, value);
216
+ }
217
+ if (generated)
218
+ return value;
246
219
  }
247
- /** Remove the webhook's signing secret. Only what the SDK stored is removed; a Custom API you made yourself is
248
- * never touched. Deliveries to the webhook fail until a new secret is set or the webhook is removed. */
249
- async deleteSecret(agentId, webhook) {
220
+ /**
221
+ * Remove the webhook's signing secret (the current one and any previous one). Nothing is sent to the webhook until
222
+ * it gets a new one (`createSecret` or `setSecret`), even if it is removed from agent.json and added back. Nothing
223
+ * to remove is not an error.
224
+ *
225
+ * Pass the webhook's `url`, or `{ webhookKey }` (from `list`) for an orphan: a secret whose webhook was removed from
226
+ * agent.json has no URL.
227
+ */
228
+ async deleteSecret(agentId, url) {
250
229
  const id = agent(agentId);
251
- await __classPrivateFieldGet(this, _WebhookSecrets_backend, "f").delete(id, await urlOf(webhook));
230
+ let webhookKey;
231
+ let what;
232
+ const byKey = typeof url === "object" && url !== null && "webhookKey" in url;
233
+ if (byKey) {
234
+ const key = url.webhookKey;
235
+ if (typeof key !== "string" || key === "" || "url" in url) {
236
+ throw new errors_js_1.UserError("deleteSecret: pass the webhook's url, or { webhookKey } from client.webhooks.list for " +
237
+ "an orphan (not both)");
238
+ }
239
+ webhookKey = key;
240
+ what = `webhook ${key} of agent ${id}`;
241
+ }
242
+ else {
243
+ const u = await urlOf(url);
244
+ const found = (await this.list(id)).find((v) => v.url === u);
245
+ if (found === undefined) {
246
+ throw new errors_js_1.UserError(`webhook ${u} is not on agent ${id}. A webhook removed from agent.json is listed without ` +
247
+ "its url: find it in client.webhooks.list(agentId) (inAgentJson false) and pass { webhookKey }");
248
+ }
249
+ webhookKey = found.webhookKey;
250
+ what = `webhook ${u} of agent ${id}`;
251
+ }
252
+ try {
253
+ await this.api.deleteAgentWebhookSecret({ agentId: id, webhookKey });
254
+ }
255
+ catch (err) {
256
+ throw await refusal(err, what);
257
+ }
252
258
  }
253
259
  }
254
260
  exports.WebhookSecrets = WebhookSecrets;
255
- _WebhookSecrets_backend = new WeakMap();
261
+ _WebhookSecrets_instances = new WeakSet(), _WebhookSecrets_view = async function _WebhookSecrets_view(agentId, url) {
262
+ const found = (await this.list(agentId)).find((v) => v.inAgentJson && v.url === url);
263
+ if (found === undefined) {
264
+ throw new errors_js_1.UserError(`webhook ${url} is not on agent ${agentId}: deploy the agent with it first, or check the ` +
265
+ "URL (it must match agent.json exactly)");
266
+ }
267
+ return found;
268
+ };
269
+ /**
270
+ * For `deploy`: create the secret of each of `urls` that is in `added` (the webhooks the deploy added) and whose
271
+ * `secretStatus` is `missing`. Returns the new secrets by URL and the URLs still without a secret: a failed create, a
272
+ * webhook not listed, and a webhook deployed before whose secret is missing (never recreated here). Never rotates or
273
+ * overwrites a secret. A failed create is reported as missing, never thrown; a failed list throws.
274
+ */
275
+ async function createMissingSecrets(api, agentId, urls, added) {
276
+ var _a;
277
+ const created = {};
278
+ const missing = [];
279
+ if (urls.length === 0)
280
+ return { created, missing };
281
+ const views = (_a = (await api.listAgentWebhooks({ agentId })).items) !== null && _a !== void 0 ? _a : [];
282
+ for (const url of urls) {
283
+ const view = views.find((v) => v.inAgentJson && v.url === url);
284
+ if (view === undefined) {
285
+ missing.push(url);
286
+ continue;
287
+ }
288
+ if (view.secretStatus !== "missing")
289
+ continue;
290
+ if (!added.has(url)) {
291
+ missing.push(url); // deployed before: its owner may have deleted the secret on purpose
292
+ continue;
293
+ }
294
+ try {
295
+ created[url] = (await api.createAgentWebhookSecret({ agentId, webhookKey: view.webhookKey })).secret;
296
+ }
297
+ catch (err) {
298
+ if (status(err) === 409 && (await errorCode(err)) === "secret_exists")
299
+ continue; // created meanwhile: not ours
300
+ missing.push(url);
301
+ }
302
+ }
303
+ return { created, missing };
304
+ }