sarvam-agents-client 0.5.2 → 0.5.3

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