sarvam-agents-client 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,64 @@
1
+ /**
2
+ * `client.webhooks`: set, rotate, check and delete an agent webhook's signing secret (as Python's
3
+ * `sarvam_agents.compose.webhook_secrets`).
4
+ *
5
+ * The public surface is `WebhookSecrets`. Where the secret lives is behind `SecretBackend`, one small interface with
6
+ * one implementation today, `CustomApiBackend`: the secret is a bearer Custom API the SDK creates, owns and binds to
7
+ * the agent, always with `enabledForChats: false` (`CustomApiCreate` defaults it to true, which would let the agent's
8
+ * sandbox be handed the secret on requests to the webhook's host). When the server ships dedicated secret endpoints
9
+ * (SARC-2597: PUT/DELETE secret, rotate-secret, secretStatus), a second backend replaces this one in `secretBackend`
10
+ * and nothing else changes.
11
+ *
12
+ * No secret is logged, kept on an object or put in an error message.
13
+ */
14
+ import { CustomAPIsApi } from "../apis/CustomAPIsApi.js";
15
+ import type { Configuration } from "../runtime.js";
16
+ import type { Webhook } from "./webhook.js";
17
+ export type SecretStatus = "set" | "missing";
18
+ /** Every Custom API the SDK creates for a webhook secret carries this description (and its name). */
19
+ export declare const SECRET_DESCRIPTION = "Webhook signing secret managed by the Sarvam Agents SDK (client.webhooks). Do not edit.";
20
+ /** The description of the random secret `deploy` stores when none is set yet: `secretStatus` reads it as
21
+ * `"missing"`, and `setSecret`/`rotateSecret` overwrite it with `SECRET_DESCRIPTION`. */
22
+ export declare const PLACEHOLDER_DESCRIPTION = "Webhook signing secret managed by the Sarvam Agents SDK (client.webhooks). Placeholder: call client.webhooks.set_secret";
23
+ /** Where webhook secrets live. Swap the implementation in `secretBackend`, nowhere else. */
24
+ export interface SecretBackend {
25
+ /** Store `secret` for `url` on the agent, replacing any current one. */
26
+ put(agentId: string, url: string, secret: string): Promise<void>;
27
+ /** `"set"` only for a secret stored by `put`; a placeholder from `ensure` is `"missing"`. */
28
+ status(agentId: string, url: string): Promise<SecretStatus>;
29
+ /** Remove the secret; nothing to remove is not an error. */
30
+ delete(agentId: string, url: string): Promise<void>;
31
+ /** For `deploy`: make sure the agent has a secret for `url` (a random placeholder one if none) and return the
32
+ * credential name for agent.json `secret_credential` and `status` (`"missing"` while it is a placeholder). */
33
+ ensure(agentId: string, url: string): Promise<{
34
+ name: string;
35
+ status: SecretStatus;
36
+ }>;
37
+ }
38
+ /** The one place that picks where secrets live. */
39
+ export declare function secretBackend(api: {
40
+ config?: Configuration;
41
+ customApis?: CustomAPIsApi;
42
+ }): SecretBackend;
43
+ /**
44
+ * `client.webhooks`: the signing secret of each agent.json webhook.
45
+ *
46
+ * `webhook` is the webhook's URL (or a webhook object); the secret covers the URL's host. Secrets are `whsec_` plus
47
+ * base64 of 24 to 64 bytes.
48
+ */
49
+ export declare class WebhookSecrets {
50
+ #private;
51
+ constructor(config: Configuration);
52
+ /** Store `secret` (a new generated one when left out) as the webhook's signing secret and return it. A malformed
53
+ * secret throws `SecretFormatError` before anything is sent. */
54
+ setSecret(agentId: string, webhook: string | Webhook, secret?: string): Promise<string>;
55
+ /** Replace the webhook's signing secret with a new generated one and return it. Have your receiver accept the old
56
+ * and the new secret for a few minutes: a delivery still retrying is signed with the new one. */
57
+ rotateSecret(agentId: string, webhook: string | Webhook): Promise<string>;
58
+ /** `"set"` when the agent has a signing secret stored by `setSecret` or `rotateSecret` for the webhook; `"missing"`
59
+ * otherwise, including while it holds the placeholder a deploy stored. */
60
+ secretStatus(agentId: string, webhook: string | Webhook): Promise<SecretStatus>;
61
+ /** Remove the webhook's signing secret. Only what the SDK stored is removed; a Custom API you made yourself is
62
+ * never touched. Deliveries to the webhook fail until a new secret is set or the webhook is removed. */
63
+ deleteSecret(agentId: string, webhook: string | Webhook): Promise<void>;
64
+ }
@@ -0,0 +1,250 @@
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
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ 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
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _WebhookSecrets_backend;
13
+ /**
14
+ * `client.webhooks`: set, rotate, check and delete an agent webhook's signing secret (as Python's
15
+ * `sarvam_agents.compose.webhook_secrets`).
16
+ *
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.
23
+ *
24
+ * No secret is logged, kept on an object or put in an error message.
25
+ */
26
+ import { CustomAPIsApi } from "../apis/CustomAPIsApi.js";
27
+ import { ResponseError } from "../runtime.js";
28
+ import { UserError } from "./errors.js";
29
+ // Loaded on first use, so the root entry point (which exports `Client`) does not import `node:crypto` up front.
30
+ const loadWebhook = () => import("./webhook.js");
31
+ 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;
39
+ /** Throws `SecretFormatError` unless `secret` is `whsec_` plus base64 of 24 to 64 bytes (the verifier's own parser). */
40
+ async function checkSecret(secret) {
41
+ (await loadCrypto()).sign(secret, { msgId: "check", timestamp: 0, body: "" });
42
+ }
43
+ async function urlOf(hook) {
44
+ const url = typeof hook === "string" ? hook : hook === null || hook === void 0 ? void 0 : hook.url;
45
+ if (typeof url !== "string")
46
+ throw new UserError("webhook: pass the webhook's URL (a string) or a webhook");
47
+ const problem = (await loadWebhook()).urlProblem(url);
48
+ if (problem !== null)
49
+ throw new UserError("webhook: " + problem);
50
+ return url;
51
+ }
52
+ function agent(agentId) {
53
+ if (typeof agentId !== "string" || agentId.trim() === "")
54
+ throw new UserError("agentId: pass the agent's id");
55
+ return agentId;
56
+ }
57
+ function status(err) {
58
+ return err instanceof ResponseError ? err.response.status : 0;
59
+ }
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
+ }
71
+ }
72
+ if (typeof message !== "string" || !message || (secret !== undefined && message.includes(secret))) {
73
+ return `HTTP ${status(err) || "error"}`;
74
+ }
75
+ return message;
76
+ }
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;
110
+ try {
111
+ await this.api.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
112
+ }
113
+ 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
+ } });
127
+ try {
128
+ await patch({ enabledForChats: false });
129
+ }
130
+ 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;
143
+ 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
+ }
153
+ }
154
+ 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
+ }
190
+ }
191
+ }
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" };
198
+ }
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
+ }
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) {
224
+ const id = agent(agentId);
225
+ const url = await urlOf(webhook);
226
+ const value = secret === undefined ? (await loadCrypto()).generateSecret() : secret;
227
+ if (secret !== undefined)
228
+ 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);
236
+ }
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) {
240
+ const id = agent(agentId);
241
+ return __classPrivateFieldGet(this, _WebhookSecrets_backend, "f").status(id, await urlOf(webhook));
242
+ }
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));
248
+ }
249
+ }
250
+ _WebhookSecrets_backend = new WeakMap();
@@ -2,3 +2,6 @@ export * from './runtime.js';
2
2
  export * from './apis/index.js';
3
3
  export * from './models/index.js';
4
4
  export * from './streaming.js';
5
+ export { Client } from './client.js';
6
+ export { WebhookSecrets } from './compose/webhookSecrets.js';
7
+ export type { SecretStatus } from './compose/webhookSecrets.js';
package/dist/esm/index.js CHANGED
@@ -5,3 +5,6 @@ export * from './runtime.js';
5
5
  export * from './apis/index.js';
6
6
  export * from './models/index.js';
7
7
  export * from './streaming.js';
8
+ // Hand-written: the high-level client (client.webhooks).
9
+ export { Client } from './client.js';
10
+ export { WebhookSecrets } from './compose/webhookSecrets.js';
package/dist/index.d.ts CHANGED
@@ -2,3 +2,6 @@ export * from './runtime.js';
2
2
  export * from './apis/index.js';
3
3
  export * from './models/index.js';
4
4
  export * from './streaming.js';
5
+ export { Client } from './client.js';
6
+ export { WebhookSecrets } from './compose/webhookSecrets.js';
7
+ export type { SecretStatus } from './compose/webhookSecrets.js';
package/dist/index.js CHANGED
@@ -14,6 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.WebhookSecrets = exports.Client = void 0;
17
18
  /* tslint:disable */
18
19
  /* eslint-disable */
19
20
  // Hand-maintained entry point (listed in .openapi-generator-ignore): the generated exports plus the streaming helpers.
@@ -21,3 +22,8 @@ __exportStar(require("./runtime.js"), exports);
21
22
  __exportStar(require("./apis/index.js"), exports);
22
23
  __exportStar(require("./models/index.js"), exports);
23
24
  __exportStar(require("./streaming.js"), exports);
25
+ // Hand-written: the high-level client (client.webhooks).
26
+ var client_js_1 = require("./client.js");
27
+ Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return client_js_1.Client; } });
28
+ var webhookSecrets_js_1 = require("./compose/webhookSecrets.js");
29
+ Object.defineProperty(exports, "WebhookSecrets", { enumerable: true, get: function () { return webhookSecrets_js_1.WebhookSecrets; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sarvam-agents-client",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Client for the Sarvam Agents API: chat with an agent, exchange files with it, and set it up from your own code.",
5
5
  "author": "Sarvam AI <support@sarvam.ai>",
6
6
  "license": "MIT",
package/src/client.ts ADDED
@@ -0,0 +1,21 @@
1
+ // Hand-written, not generated: the high-level client.
2
+ import type { Configuration } from "./runtime.js";
3
+ import { WebhookSecrets } from "./compose/webhookSecrets.js";
4
+
5
+ /**
6
+ * Groups the hand-written helpers over one `Configuration`.
7
+ *
8
+ * ```ts
9
+ * const client = new Client(config);
10
+ * const secret = await client.webhooks.setSecret(agentId, "https://hooks.acme.com/panja");
11
+ * ```
12
+ */
13
+ export class Client {
14
+ /** Set, rotate, check and delete an agent webhook's signing secret. */
15
+ readonly webhooks: WebhookSecrets;
16
+
17
+ constructor(readonly config: Configuration) {
18
+ if (config === undefined || config === null) throw new TypeError("new Client(config): pass a Configuration");
19
+ this.webhooks = new WebhookSecrets(config);
20
+ }
21
+ }
@@ -14,6 +14,10 @@ export interface Deployment {
14
14
  /** The live version, or while the agent is paused, the paused version (what `resumeAgent` brings back); undefined
15
15
  * from a server without versions, or when no version was ever live. */
16
16
  version?: number;
17
+ /** URLs of the webhooks that still have no signing secret: this deploy stored a placeholder secret nobody holds so
18
+ * the server accepts them. Call `client.webhooks.setSecret(agentId, url)` for each before pointing a provider at
19
+ * the agent; until then deliveries fail verification. Left out when there are none. */
20
+ webhooksMissingSecret?: string[];
17
21
  }
18
22
 
19
23
  let defaultClient: Configuration | null = null;
@@ -70,11 +74,19 @@ async function update(transport: Transport, remote: RemoteAgent, agent: Agent<Ou
70
74
  return settle(transport, remote, agent);
71
75
  }
72
76
  const updated = await transport.updateAgent(remote.agentId, agent);
73
- return deployment(remote.agentId, "updated", liveVersion(updated));
77
+ return deployment(remote.agentId, "updated", liveVersion(updated), missingSecrets(updated));
74
78
  }
75
79
 
76
- function deployment(agentId: string, action: Deployment["action"], version: number | undefined): Deployment {
77
- return version === undefined ? { agentId, action } : { agentId, action, version };
80
+ function deployment(agentId: string, action: Deployment["action"], version: number | undefined,
81
+ webhooksMissingSecret: string[] = []): Deployment {
82
+ const out: Deployment = version === undefined ? { agentId, action } : { agentId, action, version };
83
+ if (webhooksMissingSecret.length > 0) out.webhooksMissingSecret = webhooksMissingSecret;
84
+ return out;
85
+ }
86
+
87
+ function missingSecrets(remote: RemoteAgent | undefined | null): string[] {
88
+ const missing = remote?.webhooksMissingSecret;
89
+ return Array.isArray(missing) ? [...missing] : [];
78
90
  }
79
91
 
80
92
  // Optional chaining: a custom transport written for 0.3 may resolve anything from updateAgent/createAgent.
@@ -109,12 +121,13 @@ async function deployWith(agent: Agent<OutputType | undefined>, transport: Trans
109
121
  if (others.length) {
110
122
  throw new UserError(`cannot adopt ${adopt}: agent "${agent.name}" is already deployed as ${others.join(", ")}`);
111
123
  }
112
- return deployment(adopt, "updated", liveVersion(await transport.updateAgent(adopt, agent)));
124
+ const adopted = await transport.updateAgent(adopt, agent);
125
+ return deployment(adopt, "updated", liveVersion(adopted), missingSecrets(adopted));
113
126
  }
114
127
  if (found.length > 1) throw new DuplicateAgentsError(found.map((r) => r.agentId));
115
128
  if (found.length === 0) {
116
129
  const created = await transport.createAgent(agent);
117
- return deployment(created.agentId, "created", liveVersion(created));
130
+ return deployment(created.agentId, "created", liveVersion(created), missingSecrets(created));
118
131
  }
119
132
  return update(transport, found[0], agent, strict);
120
133
  }
@@ -15,6 +15,9 @@ import { chunksFromUiMessage, fromUiChunk } from "./events.js";
15
15
  import type { Event } from "./events.js";
16
16
  import type { FunctionResult } from "./functionTool.js";
17
17
  import { VERSION_NOTE } from "./transport.js";
18
+ import { secretCredentialName, urlProblem } from "./webhook.js";
19
+ import { secretBackend } from "./webhookSecrets.js";
20
+ import type { SecretBackend } from "./webhookSecrets.js";
18
21
  import type { PendingFunctionCalls, RemoteAgent, SettingsWarning, Transport, TurnStream } from "./transport.js";
19
22
 
20
23
  const PAGE = 100;
@@ -201,6 +204,33 @@ function withoutWebhooks(settings: Record<string, any>): Record<string, any> {
201
204
  return { ...out, metadata };
202
205
  }
203
206
 
207
+ type Hook = Record<string, unknown>;
208
+
209
+ function hooksOf(settings: Record<string, any>): Hook[] {
210
+ const hooks = settings["webhooks"];
211
+ return Array.isArray(hooks) ? hooks.filter((h) => typeof h === "object" && h !== null && !Array.isArray(h)) : [];
212
+ }
213
+
214
+ function sdkNamed(agentId: string, hook: Hook): boolean {
215
+ const url = hook["url"];
216
+ return typeof url === "string" && urlProblem(url) === null &&
217
+ hook["secret_credential"] === secretCredentialName(agentId, url);
218
+ }
219
+
220
+ /** `settings` as a definition writes them: a webhook whose `secret_credential` is the one `deploy` filled in loses it
221
+ * again, so the stored `sdk_hash` (computed without it) still matches. */
222
+ function asDefined(agentId: string, settings: Record<string, any>): Record<string, any> {
223
+ if (!hooksOf(settings).some((h) => sdkNamed(agentId, h))) return settings;
224
+ return {
225
+ ...settings,
226
+ webhooks: (settings["webhooks"] as unknown[]).map((h) => {
227
+ if (typeof h !== "object" || h === null || !sdkNamed(agentId, h as Hook)) return h;
228
+ const { secret_credential: _name, ...rest } = h as Hook;
229
+ return rest;
230
+ }),
231
+ };
232
+ }
233
+
204
234
  function isNotFound(err: unknown): boolean {
205
235
  return err instanceof ResponseError && err.response.status === 404;
206
236
  }
@@ -240,12 +270,14 @@ export class SettingsTransport implements Transport {
240
270
  private readonly conversations: ConversationsApi;
241
271
  private readonly responses: ResponsesApi;
242
272
  private readonly customApis: CustomAPIsApi;
273
+ private readonly secrets: SecretBackend;
243
274
 
244
275
  constructor(private readonly config: Configuration) {
245
276
  this.agents = new AgentsApi(config);
246
277
  this.conversations = new ConversationsApi(config);
247
278
  this.responses = new ResponsesApi(config);
248
279
  this.customApis = new CustomAPIsApi(config);
280
+ this.secrets = secretBackend({ customApis: this.customApis });
249
281
  }
250
282
 
251
283
  // -- agents ---------------------------------------------------------------------------------------------
@@ -275,8 +307,9 @@ export class SettingsTransport implements Transport {
275
307
  }
276
308
 
277
309
  async createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent> {
278
- const settings = agent.toSettings();
279
- const webhooks = (settings["webhooks"] ?? []) as { secret_credential: string }[];
310
+ let settings = agent.toSettings();
311
+ let missing: string[] = [];
312
+ const webhooks = (settings["webhooks"] ?? []) as { secret_credential?: string }[];
280
313
  // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
281
314
  // without them, bind the Custom APIs they name, then write the settings in full.
282
315
  const { bind, unbound } = await this.webhookCredentials(webhooks);
@@ -306,6 +339,7 @@ export class SettingsTransport implements Transport {
306
339
  }
307
340
  if (webhooks.length > 0) {
308
341
  for (const { path, name, customApiId } of bind) await this.bind(resource.id, path, name, customApiId);
342
+ ({ settings, missing } = await this.withSecretCredentials(resource.id, settings));
309
343
  try {
310
344
  envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
311
345
  } catch (err) {
@@ -332,15 +366,38 @@ export class SettingsTransport implements Transport {
332
366
  agentId: resource.id,
333
367
  name: agent.name,
334
368
  instructions: agent.instructions,
335
- settings: { ...(envelope.settings ?? {}) },
369
+ settings: asDefined(resource.id, { ...(envelope.settings ?? {}) }),
336
370
  warnings,
371
+ ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
337
372
  }, live, versionStateOf(resource));
338
373
  }
339
374
 
375
+ /** `settings` with each webhook that names no `secret_credential` given the one `client.webhooks` keeps for the
376
+ * agent and host (stored, with a random secret nobody holds, when there is none yet), and the URLs of those
377
+ * webhooks still without a secret set by `client.webhooks`. */
378
+ private async withSecretCredentials(agentId: string, settings: Record<string, any>):
379
+ Promise<{ settings: Record<string, any>; missing: string[] }> {
380
+ const hooks = hooksOf(settings);
381
+ if (hooks.every((h) => "secret_credential" in h)) return { settings, missing: [] };
382
+ const filled: unknown[] = [];
383
+ const missing: string[] = [];
384
+ for (const h of settings["webhooks"] as Hook[]) {
385
+ if (typeof h !== "object" || h === null || "secret_credential" in h) {
386
+ filled.push(h);
387
+ continue;
388
+ }
389
+ const url = h["url"] as string;
390
+ const { name, status } = await this.secrets.ensure(agentId, url);
391
+ filled.push({ ...h, secret_credential: name });
392
+ if (status === "missing") missing.push(url);
393
+ }
394
+ return { settings: { ...settings, webhooks: filled }, missing };
395
+ }
396
+
340
397
  /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
341
398
  * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
342
399
  * checks credentials). */
343
- private async webhookCredentials(webhooks: { secret_credential: string }[]): Promise<{
400
+ private async webhookCredentials(webhooks: { secret_credential?: string }[]): Promise<{
344
401
  bind: { path: string; name: string; customApiId: string }[];
345
402
  unbound: string[];
346
403
  }> {
@@ -349,7 +406,7 @@ export class SettingsTransport implements Transport {
349
406
  const seen = new Set<string>();
350
407
  for (const [i, hook] of webhooks.entries()) {
351
408
  const name = hook.secret_credential;
352
- if (seen.has(name)) continue;
409
+ if (name === undefined || seen.has(name)) continue; // left out: deploy fills in the one client.webhooks keeps
353
410
  seen.add(name);
354
411
  const path = `webhooks.${i}.secret_credential`;
355
412
  const ids = await this.customApiIds(name);
@@ -392,7 +449,7 @@ export class SettingsTransport implements Transport {
392
449
  }
393
450
 
394
451
  async updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent> {
395
- const settings = agent.toSettings();
452
+ let settings = agent.toSettings();
396
453
  // findAgents searches by display name, so an adopted (or dashboard-renamed) agent must carry sdk_name.
397
454
  const current = await this.agents.getAgent({ agentId });
398
455
  if (current.name !== agent.name) {
@@ -413,6 +470,13 @@ export class SettingsTransport implements Transport {
413
470
  if (instructionsChanged) {
414
471
  await this.agents.putInstructions({ agentId, instructionsBody: { data: agent.instructions } });
415
472
  }
473
+ let missing: string[];
474
+ try {
475
+ ({ settings, missing } = await this.withSecretCredentials(agentId, settings));
476
+ } catch (err) {
477
+ if (instructionsChanged) await this.restore(agentId, null, previousInstructions);
478
+ throw err;
479
+ }
416
480
  let envelope: Envelope;
417
481
  try {
418
482
  envelope = await this.agents.putAgentSettings({ agentId, body: settings });
@@ -439,8 +503,9 @@ export class SettingsTransport implements Transport {
439
503
  agentId,
440
504
  name: agent.name,
441
505
  instructions: agent.instructions,
442
- settings: { ...(envelope.settings ?? {}) },
506
+ settings: asDefined(agentId, { ...(envelope.settings ?? {}) }),
443
507
  warnings,
508
+ ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
444
509
  }, live, versionStateOf(current));
445
510
  }
446
511
 
@@ -681,7 +746,8 @@ export class SettingsTransport implements Transport {
681
746
  instructions: string,
682
747
  ): RemoteAgent {
683
748
  const remote: RemoteAgent = {
684
- agentId: resource.id, name: resource.name, instructions, settings: { ...(resource.settings ?? {}) }, warnings: [],
749
+ agentId: resource.id, name: resource.name, instructions, warnings: [],
750
+ settings: asDefined(resource.id, { ...(resource.settings ?? {}) }),
685
751
  };
686
752
  // Left out, not set to undefined, when the server has no versions: the shape a 0.3 transport returned.
687
753
  if (resource.liveVersion !== undefined && resource.liveVersion !== null) remote.liveVersion = resource.liveVersion;
@@ -22,6 +22,9 @@ export interface RemoteAgent {
22
22
  /** `"live"`, `"paused"` or `"not_live"` (`AgentResource.versionState`); undefined when the server has no versions,
23
23
  * in which case deploy() never calls `publish`. */
24
24
  versionState?: string;
25
+ /** URLs of the webhooks this write left without a secret set by `client.webhooks` (a placeholder secret nobody
26
+ * holds stands in until `client.webhooks.setSecret`); left out when there are none. */
27
+ webhooksMissingSecret?: string[];
25
28
  }
26
29
 
27
30
  /** The note on every version deploy() saves, so the dashboard's version list shows which came from code. */