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
@@ -51,7 +51,7 @@ function changedFields(remote, agent) {
51
51
  keys.push("instructions");
52
52
  return keys;
53
53
  }
54
- async function update(transport, remote, agent, strict) {
54
+ async function update(transport, remote, agent, strict, added) {
55
55
  const stored = storedHash(remote);
56
56
  if (stored !== undefined && (0, fingerprint_js_1.settingsFingerprint)(remote.instructions, remote.settings) !== stored) {
57
57
  const changed = changedFields(remote, agent);
@@ -60,8 +60,9 @@ async function update(transport, remote, agent, strict) {
60
60
  console.warn(`agent "${agent.name}" (${remote.agentId}) was edited outside the SDK; overwriting fields: ${changed.join(", ")}`);
61
61
  }
62
62
  else if (stored === agent.specHash()) {
63
- return settle(transport, remote, agent);
63
+ return settle(transport, remote, agent, added);
64
64
  }
65
+ added.urls = await addedUrls(transport, remote, agent);
65
66
  const updated = await transport.updateAgent(remote.agentId, agent);
66
67
  return deployment(remote.agentId, "updated", liveVersion(updated), missingSecrets(updated), updated === null || updated === void 0 ? void 0 : updated.triggerTokens);
67
68
  }
@@ -73,6 +74,40 @@ function deployment(agentId, action, version, webhooksMissingSecret = [], tokens
73
74
  out.triggerTokens = tokens;
74
75
  return out;
75
76
  }
77
+ /**
78
+ * The URLs of `agent`'s webhooks that this deploy adds: not in the agent.json last deployed (read before the write,
79
+ * with the transport's optional `deployedWebhookUrls`). Nothing deployed yet: every webhook. A read that fails
80
+ * (`null`), or a transport that cannot tell: none, so a secret is never created for a webhook deployed before.
81
+ */
82
+ async function addedUrls(transport, remote, agent) {
83
+ var _a;
84
+ const urls = ((_a = agent.webhooks) !== null && _a !== void 0 ? _a : []).map((h) => h.url);
85
+ if (urls.length === 0 || transport.deployedWebhookUrls === undefined)
86
+ return new Set();
87
+ const previous = await transport.deployedWebhookUrls(remote.agentId, remote.liveVersion, remote.versionState);
88
+ if (previous === null)
89
+ return new Set();
90
+ return new Set(urls.filter((u) => !previous.has(u)));
91
+ }
92
+ /**
93
+ * Create the signing secret of each webhook this deploy added (a URL not in the agent.json last deployed; on a first
94
+ * deploy, every webhook) when it has none. A webhook deployed before is never given a secret here, even when it has
95
+ * none (its owner may have deleted it on purpose): it is listed in `webhooksMissingSecret`, like a webhook whose create
96
+ * failed. Never rotates or overwrites a secret, and a failure never fails the deploy.
97
+ */
98
+ async function withWebhookSecrets(transport, agent, out, added) {
99
+ var _a;
100
+ if (!agent.webhooks || agent.webhooks.length === 0 || transport.createWebhookSecrets === undefined)
101
+ return out;
102
+ const { created, missing } = await transport.createWebhookSecrets(out.agentId, agent, added);
103
+ const allMissing = [...new Set([...((_a = out.webhooksMissingSecret) !== null && _a !== void 0 ? _a : []), ...missing])];
104
+ if (allMissing.length > 0)
105
+ out.webhooksMissingSecret = allMissing;
106
+ if (Object.keys(created).length > 0) {
107
+ Object.defineProperty(out, "webhookSecrets", { value: Object.freeze({ ...created }), enumerable: false });
108
+ }
109
+ return out;
110
+ }
76
111
  function missingSecrets(remote) {
77
112
  const missing = remote === null || remote === void 0 ? void 0 : remote.webhooksMissingSecret;
78
113
  return Array.isArray(missing) ? [...missing] : [];
@@ -102,16 +137,18 @@ function liveVersion(remote) {
102
137
  * goes live again with the next deploy of a changed definition. Only an agent with no live version that was never
103
138
  * paused (created, but its first deploy did not finish) is published here.
104
139
  */
105
- async function settle(transport, remote, agent) {
140
+ async function settle(transport, remote, agent, added) {
106
141
  const state = remote.versionState;
107
142
  if (state === undefined || state === "live" || state === "paused" || !transport.publish) {
108
143
  if (state === "live")
109
144
  await checkTriggers(transport, remote, agent);
110
145
  return deployment(remote.agentId, "unchanged", remote.liveVersion);
111
146
  }
147
+ added.urls = await addedUrls(transport, remote, agent);
112
148
  return published(remote.agentId, await transport.publish(remote.agentId, transport_js_1.VERSION_NOTE));
113
149
  }
114
- async function deployWith(agent, transport, strict, adopt) {
150
+ async function deployWith(agent, transport, strict, added, adopt) {
151
+ var _a;
115
152
  const found = await transport.findAgents(agent.name);
116
153
  if (adopt !== undefined) {
117
154
  const target = await transport.readAgent(adopt);
@@ -124,16 +161,18 @@ async function deployWith(agent, transport, strict, adopt) {
124
161
  if (others.length) {
125
162
  throw new errors_js_1.UserError(`cannot adopt ${adopt}: agent "${agent.name}" is already deployed as ${others.join(", ")}`);
126
163
  }
164
+ added.urls = await addedUrls(transport, target, agent);
127
165
  const adopted = await transport.updateAgent(adopt, agent);
128
166
  return deployment(adopt, "updated", liveVersion(adopted), missingSecrets(adopted), adopted === null || adopted === void 0 ? void 0 : adopted.triggerTokens);
129
167
  }
130
168
  if (found.length > 1)
131
169
  throw new errors_js_1.DuplicateAgentsError(found.map((r) => r.agentId));
132
170
  if (found.length === 0) {
171
+ added.urls = new Set(((_a = agent.webhooks) !== null && _a !== void 0 ? _a : []).map((h) => h.url)); // a new agent: every webhook is new
133
172
  const created = await transport.createAgent(agent);
134
173
  return deployment(created.agentId, "created", liveVersion(created), missingSecrets(created), created.triggerTokens);
135
174
  }
136
- return update(transport, found[0], agent, strict);
175
+ return update(transport, found[0], agent, strict, added);
137
176
  }
138
177
  /**
139
178
  * The id of the deployed agent named `agent.name`, for a run with `deploy: false`: reads only, writes nothing. The run
@@ -162,11 +201,21 @@ async function findDeployed(agent, transport) {
162
201
  * saves any edits the owner left in the draft, so check the draft first. `strict: true` throws `DriftError` instead of
163
202
  * overwriting fields edited outside the SDK. `adopt: agentId` takes over an agent made elsewhere. `version` is the live
164
203
  * version (the paused one while paused).
204
+ *
205
+ * The deploy then creates the signing secret of each webhook it added (a URL not in the agent.json last deployed;
206
+ * every webhook on a first deploy) and returns it once in `webhookSecrets` (by URL). An existing secret is never
207
+ * rotated or overwritten, and a missing one on a webhook deployed before is never recreated: it is listed in
208
+ * `webhooksMissingSecret`.
165
209
  */
166
210
  async function deploy(agent, opts = {}) {
167
211
  const transport = resolveTransport(opts.client, opts.transport);
168
212
  forget(agent.name); // this deploy may replace what cached runs of the name point at
169
- return serialized(agent.name, () => { var _a; return deployWith(agent, transport, (_a = opts.strict) !== null && _a !== void 0 ? _a : false, opts.adopt); });
213
+ return serialized(agent.name, async () => {
214
+ var _a;
215
+ const added = { urls: new Set() };
216
+ const out = await deployWith(agent, transport, (_a = opts.strict) !== null && _a !== void 0 ? _a : false, added, opts.adopt);
217
+ return withWebhookSecrets(transport, agent, out, added.urls);
218
+ });
170
219
  }
171
220
  /**
172
221
  * Delete the agent named `name` and all its versions; resolves true if one was deleted. It cannot be undone.
@@ -237,7 +286,11 @@ function agentIdFor(agent, transport, owner, deploy = true) {
237
286
  if (prev && prev.hash === hash)
238
287
  return prev.id;
239
288
  const id = deploy
240
- ? serialized(agent.name, () => deployWith(agent, transport, false)).then((d) => d.agentId)
289
+ ? serialized(agent.name, async () => {
290
+ // As deploy(): the webhooks a run's deploy adds get their secrets (client.webhooks.getSecret shows them).
291
+ const added = { urls: new Set() };
292
+ return withWebhookSecrets(transport, agent, await deployWith(agent, transport, false, added), added.urls);
293
+ }).then((d) => d.agentId)
241
294
  : serialized(agent.name, () => findDeployed(agent, transport));
242
295
  const entry = { hash, id };
243
296
  owners.set(owner, entry);
@@ -16,6 +16,10 @@ export declare class UserError extends AgentsError {
16
16
  message?: string;
17
17
  }>);
18
18
  }
19
+ /** `client.webhooks.createSecret`: the webhook already has a signing secret. Rotate it (`rotateSecret`), view it
20
+ * (`getSecret`), or delete it first. */
21
+ export declare class SecretExistsError extends UserError {
22
+ }
19
23
  /** Where a `ModelBehaviorError` came from: the server's check, or the `outputType`'s own `parse`. */
20
24
  export type ModelBehaviorErrorSource = "server" | "local_parse";
21
25
  /**
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  /** Error hierarchy for the compose layer. */
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.NotSupportedByServerError = exports.DuplicateAgentsError = exports.DriftError = exports.RunError = exports.NotSupportedError = exports.NotDeployedError = exports.MaxToolCallsExceededError = exports.MaxTokensExceededError = exports.MaxTurnsExceededError = exports.ModelBehaviorError = exports.UserError = exports.AgentsError = void 0;
4
+ exports.NotSupportedByServerError = exports.DuplicateAgentsError = exports.DriftError = exports.RunError = exports.NotSupportedError = exports.NotDeployedError = exports.MaxToolCallsExceededError = exports.MaxTokensExceededError = exports.MaxTurnsExceededError = exports.ModelBehaviorError = exports.SecretExistsError = exports.UserError = exports.AgentsError = void 0;
5
5
  class AgentsError extends Error {
6
6
  constructor(message) {
7
7
  super(message);
@@ -18,6 +18,11 @@ class UserError extends AgentsError {
18
18
  }
19
19
  }
20
20
  exports.UserError = UserError;
21
+ /** `client.webhooks.createSecret`: the webhook already has a signing secret. Rotate it (`rotateSecret`), view it
22
+ * (`getSecret`), or delete it first. */
23
+ class SecretExistsError extends UserError {
24
+ }
25
+ exports.SecretExistsError = SecretExistsError;
21
26
  /**
22
27
  * The agent's answer didn't match its `outputType`. `source` says where: `"server"` (no answer matched the schema
23
28
  * after the server's retry; `rawText` is the model's last attempt) or `"local_parse"` (the server accepted the answer
@@ -19,24 +19,29 @@ export declare class SettingsTransport implements Transport {
19
19
  private readonly agents;
20
20
  private readonly conversations;
21
21
  private readonly responses;
22
- private readonly customApis;
23
22
  private readonly triggers;
24
- private readonly secrets;
25
23
  constructor(config: Configuration);
26
24
  findAgents(sdkName: string): Promise<RemoteAgent[]>;
27
25
  readAgent(agentId: string): Promise<RemoteAgent>;
28
26
  createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
29
- /** `settings` with each webhook that names no `secret_credential` given the one `client.webhooks` keeps for the
30
- * agent and host (stored, with a random secret nobody holds, when there is none yet), and the URLs of those
31
- * webhooks still without a secret set by `client.webhooks`. */
32
- private withSecretCredentials;
33
- /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
34
- * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
35
- * checks credentials). */
36
- private webhookCredentials;
37
- /** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
38
- private customApiIds;
39
- private bind;
27
+ /**
28
+ * The webhook URLs of the agent.json last deployed, read before a deploy writes: the live (or paused) version's,
29
+ * `GET /v2/agents/{agentId}/versions/{version}` (its `agent.json` file). Without versions on the server, the
30
+ * agent's settings (`GET /v1/agents/{agentId}/settings`), which are what is deployed there. An empty set when
31
+ * nothing was ever deployed; null, with a warning, when it cannot be read.
32
+ */
33
+ deployedWebhookUrls(agentId: string, liveVersion?: number, versionState?: string): Promise<Set<string> | null>;
34
+ /**
35
+ * Create the signing secret of each webhook in `added` (the URLs this deploy added) whose `secretStatus` is
36
+ * `missing` (`POST .../webhooks/{webhookKey}/secret`); resolves to the new secrets by URL and the URLs of `agent`'s
37
+ * webhooks still without one. A webhook deployed before whose secret is missing is reported, never given one. An
38
+ * existing secret is never rotated or overwritten. Nothing here fails the deploy: a failure is logged (never with a
39
+ * secret) and the webhook reported missing.
40
+ */
41
+ createWebhookSecrets(agentId: string, agent: Agent<OutputType | undefined>, added?: ReadonlySet<string>): Promise<{
42
+ created: Record<string, string>;
43
+ missing: string[];
44
+ }>;
40
45
  updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
41
46
  /** Make what was just written what end users get. A server without versions (no `versionState`) gets the bodiless
42
47
  * deploy 0.3 sent; otherwise the draft is saved as a version and that version deployed. */
@@ -7,7 +7,6 @@ exports.idempotencyKey = idempotencyKey;
7
7
  const node_crypto_1 = require("node:crypto");
8
8
  const AgentsApi_js_1 = require("../apis/AgentsApi.js");
9
9
  const ConversationsApi_js_1 = require("../apis/ConversationsApi.js");
10
- const CustomAPIsApi_js_1 = require("../apis/CustomAPIsApi.js");
11
10
  const ResponsesApi_js_1 = require("../apis/ResponsesApi.js");
12
11
  const TriggersApi_js_1 = require("../apis/TriggersApi.js");
13
12
  const runtime_js_1 = require("../runtime.js");
@@ -206,38 +205,14 @@ class Finished {
206
205
  }
207
206
  close() { }
208
207
  }
209
- /** `settings` for a new agent's first write: no `webhooks` (the server checks them against the agent's bound
210
- * credentials, and a new agent has none yet) and no `sdk_hash` (it covers the webhooks, so an agent left in this
211
- * state would otherwise read as deployed and never get them). */
208
+ /** `settings` for a new agent's first write: no `webhooks` (written by the second write, whose envelope carries the
209
+ * save's webhook warnings) and no `sdk_hash` (it covers the webhooks, so an agent left in this state would otherwise
210
+ * read as deployed and never get them). */
212
211
  function withoutWebhooks(settings) {
213
212
  const { webhooks: _webhooks, ...out } = settings;
214
213
  const { sdk_hash: _hash, ...metadata } = settings["metadata"];
215
214
  return { ...out, metadata };
216
215
  }
217
- function hooksOf(settings) {
218
- const hooks = settings["webhooks"];
219
- return Array.isArray(hooks) ? hooks.filter((h) => typeof h === "object" && h !== null && !Array.isArray(h)) : [];
220
- }
221
- function sdkNamed(agentId, hook) {
222
- const url = hook["url"];
223
- return typeof url === "string" && (0, webhook_js_1.urlProblem)(url) === null &&
224
- hook["secret_credential"] === (0, webhook_js_1.secretCredentialName)(agentId, url);
225
- }
226
- /** `settings` as a definition writes them: a webhook whose `secret_credential` is the one `deploy` filled in loses it
227
- * again, so the stored `sdk_hash` (computed without it) still matches. */
228
- function asDefined(agentId, settings) {
229
- if (!hooksOf(settings).some((h) => sdkNamed(agentId, h)))
230
- return settings;
231
- return {
232
- ...settings,
233
- webhooks: settings["webhooks"].map((h) => {
234
- if (typeof h !== "object" || h === null || !sdkNamed(agentId, h))
235
- return h;
236
- const { secret_credential: _name, ...rest } = h;
237
- return rest;
238
- }),
239
- };
240
- }
241
216
  /** The deploy response's `triggerTokens` (the server shows each token once); never logged. An entry missing a field
242
217
  * is skipped with a warning that names the trigger, never the token. */
243
218
  function triggerTokens(resource) {
@@ -255,6 +230,13 @@ function triggerTokens(resource) {
255
230
  }
256
231
  return out;
257
232
  }
233
+ /** A v2 agent write's `webhookWarnings` (`host_unresolvable`). */
234
+ function logWebhookWarnings(agentId, resource) {
235
+ var _a;
236
+ const items = (_a = resource === null || resource === void 0 ? void 0 : resource.webhookWarnings) !== null && _a !== void 0 ? _a : [];
237
+ for (const w of items)
238
+ console.warn(`agent ${agentId}: webhook warning ${w === null || w === void 0 ? void 0 : w.code} at ${w === null || w === void 0 ? void 0 : w.path}: ${w === null || w === void 0 ? void 0 : w.message}`);
239
+ }
258
240
  function isNotFound(err) {
259
241
  return err instanceof runtime_js_1.ResponseError && err.response.status === 404;
260
242
  }
@@ -291,9 +273,7 @@ class SettingsTransport {
291
273
  this.agents = new AgentsApi_js_1.AgentsApi(config);
292
274
  this.conversations = new ConversationsApi_js_1.ConversationsApi(config);
293
275
  this.responses = new ResponsesApi_js_1.ResponsesApi(config);
294
- this.customApis = new CustomAPIsApi_js_1.CustomAPIsApi(config);
295
276
  this.triggers = new TriggersApi_js_1.TriggersApi(config);
296
- this.secrets = (0, webhookSecrets_js_1.secretBackend)({ customApis: this.customApis });
297
277
  }
298
278
  // -- agents ---------------------------------------------------------------------------------------------
299
279
  async findAgents(sdkName) {
@@ -322,13 +302,12 @@ class SettingsTransport {
322
302
  return this.remote(resource, await this.instructions(agentId));
323
303
  }
324
304
  async createAgent(agent) {
325
- var _a, _b, _c, _d;
326
- let settings = agent.toSettings();
327
- let missing = [];
305
+ var _a, _b, _c, _d, _e;
306
+ const settings = agent.toSettings();
328
307
  const webhooks = ((_a = settings["webhooks"]) !== null && _a !== void 0 ? _a : []);
329
- // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
330
- // without them, bind the Custom APIs they name, then write the settings in full.
331
- const { bind, unbound } = await this.webhookCredentials(webhooks);
308
+ // Webhooks are written in a second step, whose settings envelope carries the save's webhook warnings
309
+ // (webhooks_disabled, host_unresolvable). No save creates a webhook's signing secret: deploy() does that after the
310
+ // agent is live (createWebhookSecrets).
332
311
  let resource;
333
312
  try {
334
313
  resource = await this.agents.createAgent({
@@ -357,23 +336,14 @@ class SettingsTransport {
357
336
  throw err;
358
337
  }
359
338
  if (webhooks.length > 0) {
360
- for (const { path, name, customApiId } of bind)
361
- await this.bind(resource.id, path, name, customApiId);
362
- ({ settings, missing } = await this.withSecretCredentials(resource.id, settings));
363
339
  try {
364
340
  envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
365
341
  }
366
342
  catch (err) {
367
- const invalid = await invalidSettings(err);
368
- if (invalid === null)
369
- throw err;
370
- throw new errors_js_1.UserError([invalid.message, ...unbound].join("; "), invalid.issues);
343
+ throw (_c = (await invalidSettings(err))) !== null && _c !== void 0 ? _c : err;
371
344
  }
372
345
  }
373
346
  warnings = checkWarnings(envelope, settings);
374
- // Accepted unchecked (webhooks switched off): refused once they are on.
375
- for (const sentence of unbound)
376
- console.warn(`agent ${resource.id}: ${sentence}`);
377
347
  checkMetadata(envelope, agent);
378
348
  live = await this.goLive(resource.id, versionStateOf(resource), agent);
379
349
  }
@@ -391,90 +361,75 @@ class SettingsTransport {
391
361
  agentId: resource.id,
392
362
  name: agent.name,
393
363
  instructions: agent.instructions,
394
- settings: asDefined(resource.id, { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) }),
364
+ settings: (0, webhook_js_1.withoutLegacyCredentials)({ ...((_d = envelope.settings) !== null && _d !== void 0 ? _d : {}) }),
395
365
  warnings,
396
- ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
397
- triggerTokens: (_d = live.triggerTokens) !== null && _d !== void 0 ? _d : [],
366
+ triggerTokens: (_e = live.triggerTokens) !== null && _e !== void 0 ? _e : [],
398
367
  }, live.liveVersion, versionStateOf(resource));
399
368
  }
400
- /** `settings` with each webhook that names no `secret_credential` given the one `client.webhooks` keeps for the
401
- * agent and host (stored, with a random secret nobody holds, when there is none yet), and the URLs of those
402
- * webhooks still without a secret set by `client.webhooks`. */
403
- async withSecretCredentials(agentId, settings) {
404
- const hooks = hooksOf(settings);
405
- if (hooks.every((h) => "secret_credential" in h))
406
- return { settings, missing: [] };
407
- const filled = [];
408
- const missing = [];
409
- for (const h of settings["webhooks"]) {
410
- if (typeof h !== "object" || h === null || "secret_credential" in h) {
411
- filled.push(h);
412
- continue;
413
- }
414
- const url = h["url"];
415
- const { name, status } = await this.secrets.ensure(agentId, url);
416
- filled.push({ ...h, secret_credential: name });
417
- if (status === "missing")
418
- missing.push(url);
419
- }
420
- return { settings: { ...settings, webhooks: filled }, missing };
421
- }
422
- /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
423
- * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
424
- * checks credentials). */
425
- async webhookCredentials(webhooks) {
426
- const bind = [];
427
- const unbound = [];
428
- const seen = new Set();
429
- for (const [i, hook] of webhooks.entries()) {
430
- const name = hook.secret_credential;
431
- if (name === undefined || seen.has(name))
432
- continue; // left out: deploy fills in the one client.webhooks keeps
433
- seen.add(name);
434
- const path = `webhooks.${i}.secret_credential`;
435
- const ids = await this.customApiIds(name);
436
- if (ids.length === 1) {
437
- bind.push({ path, name, customApiId: ids[0] });
369
+ /**
370
+ * The webhook URLs of the agent.json last deployed, read before a deploy writes: the live (or paused) version's,
371
+ * `GET /v2/agents/{agentId}/versions/{version}` (its `agent.json` file). Without versions on the server, the
372
+ * agent's settings (`GET /v1/agents/{agentId}/settings`), which are what is deployed there. An empty set when
373
+ * nothing was ever deployed; null, with a warning, when it cannot be read.
374
+ */
375
+ async deployedWebhookUrls(agentId, liveVersion, versionState) {
376
+ var _a, _b, _c;
377
+ let settings;
378
+ try {
379
+ if (versionState === undefined) {
380
+ settings = (_a = (await this.agents.getAgentSettings({ agentId })).settings) !== null && _a !== void 0 ? _a : {};
438
381
  }
439
- else if (ids.length === 0) {
440
- unbound.push(`${path}: you have no Custom API named '${name}' to bind to the new agent; create it, then ` +
441
- "deploy again");
382
+ else if (liveVersion === undefined) {
383
+ return new Set();
442
384
  }
443
385
  else {
444
- unbound.push(`${path}: ${ids.length} of your Custom APIs are named '${name}', so none was bound to the new ` +
445
- "agent; rename or delete all but one, then deploy again");
386
+ const files = (_b = (await this.agents.getVersion({ agentId, version: liveVersion })).files) !== null && _b !== void 0 ? _b : [];
387
+ const data = (_c = files.find((f) => String(f.path).replace(/^\/+/, "") === "agent.json")) === null || _c === void 0 ? void 0 : _c.data;
388
+ settings = data ? JSON.parse(data) : {};
446
389
  }
447
390
  }
448
- return { bind, unbound };
449
- }
450
- /** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
451
- async customApiIds(name) {
452
- const ids = [];
453
- let offset = 0;
454
- for (;;) {
455
- const result = await this.customApis.listCustomApis({ q: name, limit: PAGE, offset });
456
- const items = result.data;
457
- for (const item of items)
458
- if (item.name === name)
459
- ids.push(item.id);
460
- offset += items.length;
461
- if (items.length === 0 || !result.hasMore)
462
- return ids;
391
+ catch (err) {
392
+ const why = err instanceof runtime_js_1.ResponseError ? `HTTP ${err.response.status}` : err instanceof SyntaxError ? "not JSON" : String(err);
393
+ console.warn(`agent ${agentId}: could not read the deployed agent.json (${why}), so this deploy creates no ` +
394
+ "webhook secret; create any you need with client.webhooks.createSecret");
395
+ return null;
396
+ }
397
+ const hooks = settings === null || settings === void 0 ? void 0 : settings.webhooks;
398
+ const out = new Set();
399
+ if (Array.isArray(hooks)) {
400
+ for (const h of hooks) {
401
+ const url = h === null || h === void 0 ? void 0 : h.url;
402
+ if (typeof url === "string")
403
+ out.add(url);
404
+ }
463
405
  }
406
+ return out;
464
407
  }
465
- async bind(agentId, path, name, customApiId) {
408
+ /**
409
+ * Create the signing secret of each webhook in `added` (the URLs this deploy added) whose `secretStatus` is
410
+ * `missing` (`POST .../webhooks/{webhookKey}/secret`); resolves to the new secrets by URL and the URLs of `agent`'s
411
+ * webhooks still without one. A webhook deployed before whose secret is missing is reported, never given one. An
412
+ * existing secret is never rotated or overwritten. Nothing here fails the deploy: a failure is logged (never with a
413
+ * secret) and the webhook reported missing.
414
+ */
415
+ async createWebhookSecrets(agentId, agent, added = new Set()) {
466
416
  var _a;
417
+ const urls = ((_a = agent.webhooks) !== null && _a !== void 0 ? _a : []).map((h) => h.url);
418
+ let result;
467
419
  try {
468
- await this.customApis.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
420
+ result = await (0, webhookSecrets_js_1.createMissingSecrets)(this.agents, agentId, urls, added);
469
421
  }
470
422
  catch (err) {
471
- const status = err instanceof runtime_js_1.ResponseError ? err.response.status : 0;
472
- if (!(err instanceof runtime_js_1.ResponseError) || status < 400 || status >= 500)
473
- throw err;
474
- const message = (_a = (await chatError(err))) === null || _a === void 0 ? void 0 : _a["message"];
475
- throw new errors_js_1.UserError(`${path}: could not bind the Custom API '${name}' to the new agent: ` +
476
- (typeof message === "string" && message ? message : `HTTP ${status}`));
423
+ const code = err instanceof runtime_js_1.ResponseError ? err.response.status : "error";
424
+ console.warn(`agent ${agentId}: could not read its webhooks to create their signing secrets (HTTP ${code}); ` +
425
+ "check client.webhooks.list(agentId) and createSecret for each");
426
+ return { created: {}, missing: [...urls] };
427
+ }
428
+ for (const url of result.missing) {
429
+ console.warn(`agent ${agentId}: webhook ${url} has no signing secret, so nothing is sent to it; create one ` +
430
+ "with client.webhooks.createSecret(agentId, url)");
477
431
  }
432
+ return result;
478
433
  }
479
434
  async updateAgent(agentId, agent) {
480
435
  var _a, _b, _c;
@@ -501,15 +456,6 @@ class SettingsTransport {
501
456
  if (instructionsChanged) {
502
457
  await this.agents.putInstructions({ agentId, instructionsBody: { data: agent.instructions } });
503
458
  }
504
- let missing;
505
- try {
506
- ({ settings, missing } = await this.withSecretCredentials(agentId, settings));
507
- }
508
- catch (err) {
509
- if (instructionsChanged)
510
- await this.restore(agentId, null, previousInstructions);
511
- throw err;
512
- }
513
459
  let envelope;
514
460
  try {
515
461
  envelope = await this.agents.putAgentSettings({ agentId, body: settings });
@@ -541,9 +487,8 @@ class SettingsTransport {
541
487
  agentId,
542
488
  name: agent.name,
543
489
  instructions: agent.instructions,
544
- settings: asDefined(agentId, { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) }),
490
+ settings: (0, webhook_js_1.withoutLegacyCredentials)({ ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) }),
545
491
  warnings,
546
- ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
547
492
  triggerTokens: (_c = live.triggerTokens) !== null && _c !== void 0 ? _c : [],
548
493
  }, live.liveVersion, versionStateOf(current));
549
494
  }
@@ -552,6 +497,7 @@ class SettingsTransport {
552
497
  async goLive(agentId, versionState, agent) {
553
498
  if (versionState === undefined) {
554
499
  const resource = await this.agents.deployAgent({ agentId }); // idempotent; moves an adopted draft to deployed
500
+ logWebhookWarnings(agentId, resource);
555
501
  return { triggerTokens: triggerTokens(resource) };
556
502
  }
557
503
  return this.publish(agentId, transport_js_1.VERSION_NOTE);
@@ -586,8 +532,9 @@ class SettingsTransport {
586
532
  const live = (_b = resource.liveVersion) !== null && _b !== void 0 ? _b : undefined;
587
533
  if (live !== undefined)
588
534
  deployed.add(`${agentId} v${live}`);
589
- return live === undefined ? { triggerTokens: triggerTokens(resource) }
590
- : { liveVersion: live, triggerTokens: triggerTokens(resource) };
535
+ logWebhookWarnings(agentId, resource);
536
+ const minted = { triggerTokens: triggerTokens(resource) };
537
+ return live === undefined ? minted : { liveVersion: live, ...minted };
591
538
  }
592
539
  /** Read the trigger rows of an unchanged live agent and warn, once per process, when they do not match
593
540
  * `agent.triggers`. Never deploys: an unchanged definition writes nothing, and the rows may differ because the
@@ -815,8 +762,9 @@ class SettingsTransport {
815
762
  if (instructions !== null) {
816
763
  await this.agents.putInstructions({ agentId, instructionsBody: { data: instructions } });
817
764
  }
818
- if (settings !== null)
765
+ if (settings !== null) {
819
766
  await this.agents.putAgentSettings({ agentId, body: settings });
767
+ }
820
768
  }
821
769
  catch (err) {
822
770
  console.warn(`could not restore agent ${agentId} after rejected settings: ${err}`);
@@ -829,7 +777,7 @@ class SettingsTransport {
829
777
  var _a;
830
778
  const remote = {
831
779
  agentId: resource.id, name: resource.name, instructions, warnings: [],
832
- settings: asDefined(resource.id, { ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }),
780
+ settings: (0, webhook_js_1.withoutLegacyCredentials)({ ...((_a = resource.settings) !== null && _a !== void 0 ? _a : {}) }),
833
781
  };
834
782
  // Left out, not set to undefined, when the server has no versions: the shape a 0.3 transport returned.
835
783
  if (resource.liveVersion !== undefined && resource.liveVersion !== null)
@@ -21,8 +21,8 @@ export interface RemoteAgent {
21
21
  /** `"live"`, `"paused"` or `"not_live"` (`AgentResource.versionState`); undefined when the server has no versions,
22
22
  * in which case deploy() never calls `publish`. */
23
23
  versionState?: string;
24
- /** URLs of the webhooks this write left without a secret set by `client.webhooks` (a placeholder secret nobody
25
- * holds stands in until `client.webhooks.setSecret`); left out when there are none. */
24
+ /** URLs of webhooks the write left without a signing secret; `deploy` adds them to
25
+ * `Deployment.webhooksMissingSecret`. The SDK's own transport leaves it out (see `createWebhookSecrets`). */
26
26
  webhooksMissingSecret?: string[];
27
27
  /** The bearer tokens the write's deploy minted (the server shows each once). */
28
28
  triggerTokens?: MintedTriggerToken[];
@@ -64,6 +64,16 @@ export interface Transport {
64
64
  * `agent.triggers` (a deploy whose trigger reconcile failed went live without them, or the owner changed them) it
65
65
  * warns, naming the fix. It never deploys: an unchanged definition writes nothing. */
66
66
  checkTriggers?(agentId: string, agent: Agent<OutputType | undefined>, liveVersion?: number): Promise<void>;
67
+ /** Optional: deploy() calls it before it writes, for the webhook URLs of the agent.json last deployed (an empty set
68
+ * when nothing was deployed; null when unknown, so nothing counts as added). */
69
+ deployedWebhookUrls?(agentId: string, liveVersion?: number, versionState?: string): Promise<Set<string> | null>;
70
+ /** Optional: deploy() calls it after a deploy of an agent with webhooks. It creates the signing secret of each
71
+ * webhook in `added` (the URLs the deploy added) that has none (never rotating or overwriting one) and resolves to
72
+ * the new secrets by URL and the URLs of the agent's webhooks still without one. */
73
+ createWebhookSecrets?(agentId: string, agent: Agent<OutputType | undefined>, added: ReadonlySet<string>): Promise<{
74
+ created: Record<string, string>;
75
+ missing: string[];
76
+ }>;
67
77
  startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
68
78
  answerClarify(conversationId: string, requestId: string, answers: Record<string, unknown>, signal?: AbortSignal): Promise<TurnStream>;
69
79
  resume(conversationId: string, responseId: string, lastEventId: string | null, signal?: AbortSignal): Promise<TurnStream>;
@@ -1,15 +1,16 @@
1
1
  import type { WebhookEventType } from "../webhooks.js";
2
- /** Where the agent reports a finished, failed or paused turn (agent.json `webhooks[]`). */
2
+ /** Where the agent reports a finished, failed or paused turn (agent.json `webhooks[]`). The deploy that adds it
3
+ * creates its signing secret and returns it once (`Deployment.webhookSecrets[url]`); nothing is delivered to a
4
+ * webhook without a secret. The secret belongs to the exact URL: a changed URL is a new webhook with a new secret. */
3
5
  export interface Webhook {
4
6
  /** An `https://` URL on port 443 with a DNS host; a query string is allowed. */
5
7
  url: string;
6
8
  /** 1 to 4 distinct events. `approval.requested` is reserved: accepted, not sent yet. */
7
9
  events: WebhookEventType[];
8
10
  /**
9
- * The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). Leave it out: `deploy`
10
- * fills in the credential `client.webhooks` keeps, and `client.webhooks.setSecret(agentId, url)` sets the secret.
11
+ * Ignored: never sent to the server, which keeps each webhook's signing secret itself.
11
12
  *
12
- * @deprecated Use `client.webhooks.setSecret` instead of creating a Custom API and naming it here.
13
+ * @deprecated Leave it out; `deploy` creates the webhook's secret.
13
14
  */
14
15
  secretCredential?: string;
15
16
  }
@@ -19,16 +20,12 @@ export declare const WEBHOOKS_MAX = 5;
19
20
  export declare function urlProblem(url: string): string | null;
20
21
  /** The server's pure `webhooks` rules (types first); throws `UserError` naming the agent.json path. */
21
22
  export declare function checkWebhooks(webhooks: unknown): void;
22
- /** Only the three fields (a copy). `secretCredential` is left out when absent, or when it is the name `deploy`
23
- * writes anyway (one spelling keeps one fingerprint). */
23
+ /** Only `url` and `events` (a copy): `secretCredential` is ignored, so it is dropped here. */
24
24
  export declare function copyWebhooks(webhooks: readonly Webhook[]): Webhook[];
25
25
  export declare function webhooksJson(webhooks: readonly Webhook[]): Record<string, unknown>[];
26
26
  /** The host of an allowed webhook URL, lowercased, without a trailing dot or a port. */
27
27
  export declare function webhookHost(url: string): string;
28
- /** Every Custom API the SDK creates for a webhook secret is named `webhook-secret:<agentId>:<host>`. */
29
- export declare const SECRET_NAME_PREFIX = "webhook-secret:";
30
- /** The credential name the SDK uses for `url`'s signing secret on agent `agentId` (what `deploy` writes as
31
- * `secret_credential` when a webhook leaves it out). A host too long to fit 256 characters is hashed. */
32
- export declare function secretCredentialName(agentId: string, url: string): string;
33
- /** Whether `name` is the SDK's credential name for `url`'s host, for any agent. */
34
- export declare function isSdkCredentialName(name: unknown, url: string): boolean;
28
+ /** Whether `name` is the `secret_credential` the 0.5.x SDK filled in for `url`'s host, for any agent. */
29
+ export declare function isLegacyCredentialName(name: unknown, url: string): boolean;
30
+ /** `settings` with the `secret_credential` the 0.5.x SDK filled in removed from each webhook. */
31
+ export declare function withoutLegacyCredentials(settings: Record<string, unknown>): Record<string, unknown>;