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.
@@ -3,10 +3,13 @@
3
3
  *
4
4
  * The server (`claw_common/agent_settings/webhooks.py`) also checks that the host resolves to a public address and
5
5
  * that `secret_credential` names a vault credential bound to the agent whose allowed hosts cover the URL; those need
6
- * I/O and stay on the server, which refuses the save with a 422 that `deploy` throws as `UserError`. A new agent has
7
- * no credentials bound yet, so the deploy that creates it binds the caller's Custom API of each named credential first
8
- * (`SettingsTransport.createAgent`).
6
+ * I/O and stay on the server, which refuses the save with a 422 that `deploy` throws as `UserError`.
7
+ *
8
+ * `secretCredential` is optional and deprecated: left out, `deploy` writes the name `client.webhooks` uses for the
9
+ * agent and host (`secretCredentialName`). Given, the deploy that creates the agent binds the caller's Custom API of
10
+ * that name first (`SettingsTransport.createAgent`).
9
11
  */
12
+ import { createHash } from "node:crypto";
10
13
  import { UserError } from "./errors.js";
11
14
  import { WEBHOOK_EVENTS } from "../webhooks.js";
12
15
  import type { WebhookEventType } from "../webhooks.js";
@@ -17,8 +20,13 @@ export interface Webhook {
17
20
  url: string;
18
21
  /** 1 to 4 distinct events. `approval.requested` is reserved: accepted, not sent yet. */
19
22
  events: WebhookEventType[];
20
- /** The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). */
21
- secretCredential: string;
23
+ /**
24
+ * The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). Leave it out: `deploy`
25
+ * fills in the credential `client.webhooks` keeps, and `client.webhooks.setSecret(agentId, url)` sets the secret.
26
+ *
27
+ * @deprecated Use `client.webhooks.setSecret` instead of creating a Custom API and naming it here.
28
+ */
29
+ secretCredential?: string;
22
30
  }
23
31
 
24
32
  export const WEBHOOKS_MAX = 5;
@@ -138,14 +146,16 @@ export function checkWebhooks(webhooks: unknown): void {
138
146
  webhooks.forEach((hook: unknown, i: number) => {
139
147
  const where = `webhooks.${i}.`;
140
148
  if (typeof hook !== "object" || hook === null || Array.isArray(hook)) {
141
- throw new UserError(`webhooks.${i}: must be an object with url, events and secretCredential`);
149
+ throw new UserError(`webhooks.${i}: must be an object with url and events`);
142
150
  }
143
151
  const { url, events, secretCredential } = hook as Record<string, unknown>;
144
152
  if (typeof url !== "string") throw new UserError(where + "url: must be a string");
145
153
  if (!Array.isArray(events) || !events.every((e) => typeof e === "string")) {
146
154
  throw new UserError(where + "events: must be a list of event names");
147
155
  }
148
- if (typeof secretCredential !== "string") throw new UserError(where + "secretCredential: must be a string");
156
+ if (secretCredential !== undefined && typeof secretCredential !== "string") {
157
+ throw new UserError(where + "secretCredential: must be a string");
158
+ }
149
159
  // Python's Webhook is extra="forbid": a key dropped silently (a misplaced secret) would never verify.
150
160
  const extra = Object.keys(hook).find((k) => k !== "url" && k !== "events" && k !== "secretCredential");
151
161
  if (extra !== undefined) throw new UserError(where + extra + ": Extra inputs are not permitted");
@@ -158,7 +168,7 @@ export function checkWebhooks(webhooks: unknown): void {
158
168
  throw new UserError(where + `events: events must be from: ${WEBHOOK_EVENTS.join(", ")}.`);
159
169
  }
160
170
  if (new Set(events).size !== events.length) throw new UserError(where + "events: events must not repeat an event.");
161
- const n = codePoints(secretCredential);
171
+ const n = typeof secretCredential === "string" ? codePoints(secretCredential) : 1;
162
172
  if (n < 1 || n > SECRET_CREDENTIAL_MAX) {
163
173
  throw new UserError(where + "secret_credential: secret_credential must be the name of a vault credential " +
164
174
  `(1 to ${SECRET_CREDENTIAL_MAX} characters).`);
@@ -171,11 +181,54 @@ export function checkWebhooks(webhooks: unknown): void {
171
181
  });
172
182
  }
173
183
 
174
- /** Only the three fields, in agent.json's names (a copy). */
184
+ /** Only the three fields (a copy). `secretCredential` is left out when absent, or when it is the name `deploy`
185
+ * writes anyway (one spelling keeps one fingerprint). */
175
186
  export function copyWebhooks(webhooks: readonly Webhook[]): Webhook[] {
176
- return webhooks.map((h) => ({ url: h.url, events: [...h.events], secretCredential: h.secretCredential }));
187
+ return webhooks.map((h) => {
188
+ const copy: Webhook = { url: h.url, events: [...h.events] };
189
+ const name = h.secretCredential;
190
+ if (name !== undefined && !isSdkCredentialName(name, h.url)) copy.secretCredential = name;
191
+ return copy;
192
+ });
177
193
  }
178
194
 
179
195
  export function webhooksJson(webhooks: readonly Webhook[]): Record<string, unknown>[] {
180
- return webhooks.map((h) => ({ url: h.url, events: [...h.events], secret_credential: h.secretCredential }));
196
+ return webhooks.map((h) => {
197
+ const out: Record<string, unknown> = { url: h.url, events: [...h.events] };
198
+ if (h.secretCredential !== undefined) out["secret_credential"] = h.secretCredential;
199
+ return out;
200
+ });
201
+ }
202
+
203
+ /** The host of an allowed webhook URL, lowercased, without a trailing dot or a port. */
204
+ export function webhookHost(url: string): string {
205
+ return stripTrailingDots(hostPort(split(url)[1])[0]);
206
+ }
207
+
208
+ /** Every Custom API the SDK creates for a webhook secret is named `webhook-secret:<agentId>:<host>`. */
209
+ export const SECRET_NAME_PREFIX = "webhook-secret:";
210
+ const SECRET_NAME_MAX = 256;
211
+
212
+ function hashedHost(host: string): string {
213
+ return "sha256-" + createHash("sha256").update(host, "utf8").digest("hex").slice(0, 32);
214
+ }
215
+
216
+ /** The credential name the SDK uses for `url`'s signing secret on agent `agentId` (what `deploy` writes as
217
+ * `secret_credential` when a webhook leaves it out). A host too long to fit 256 characters is hashed. */
218
+ export function secretCredentialName(agentId: string, url: string): string {
219
+ const host = webhookHost(url);
220
+ const name = `${SECRET_NAME_PREFIX}${agentId}:${host}`;
221
+ return codePoints(name) <= SECRET_NAME_MAX ? name : `${SECRET_NAME_PREFIX}${agentId}:${hashedHost(host)}`;
222
+ }
223
+
224
+ /** Whether `name` is the SDK's credential name for `url`'s host, for any agent. */
225
+ export function isSdkCredentialName(name: unknown, url: string): boolean {
226
+ if (typeof name !== "string" || !name.startsWith(SECRET_NAME_PREFIX) || urlProblem(url) !== null) return false;
227
+ const rest = name.slice(SECRET_NAME_PREFIX.length);
228
+ const at = rest.lastIndexOf(":");
229
+ if (at <= 0) return false;
230
+ const agentId = rest.slice(0, at);
231
+ const tail = rest.slice(at + 1);
232
+ const host = webhookHost(url);
233
+ return !agentId.includes(":") && (tail === host || tail === hashedHost(host));
181
234
  }
@@ -0,0 +1,257 @@
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 { ResponseError } from "../runtime.js";
16
+ import type { Configuration } from "../runtime.js";
17
+ import { UserError } from "./errors.js";
18
+ import type { Webhook } from "./webhook.js";
19
+
20
+ // Loaded on first use, so the root entry point (which exports `Client`) does not import `node:crypto` up front.
21
+ const loadWebhook = () => import("./webhook.js");
22
+ const loadCrypto = () => import("../webhooks.js");
23
+
24
+ export type SecretStatus = "set" | "missing";
25
+
26
+ /** Every Custom API the SDK creates for a webhook secret carries this description (and its name). */
27
+ export const SECRET_DESCRIPTION =
28
+ "Webhook signing secret managed by the Sarvam Agents SDK (client.webhooks). Do not edit.";
29
+ /** The description of the random secret `deploy` stores when none is set yet: `secretStatus` reads it as
30
+ * `"missing"`, and `setSecret`/`rotateSecret` overwrite it with `SECRET_DESCRIPTION`. */
31
+ export const PLACEHOLDER_DESCRIPTION =
32
+ "Webhook signing secret managed by the Sarvam Agents SDK (client.webhooks). Placeholder: call client.webhooks.set_secret";
33
+ const OWNED = [SECRET_DESCRIPTION, PLACEHOLDER_DESCRIPTION];
34
+ const PAGE = 100;
35
+
36
+ /** Throws `SecretFormatError` unless `secret` is `whsec_` plus base64 of 24 to 64 bytes (the verifier's own parser). */
37
+ async function checkSecret(secret: string): Promise<void> {
38
+ (await loadCrypto()).sign(secret, { msgId: "check", timestamp: 0, body: "" });
39
+ }
40
+
41
+ async function urlOf(hook: string | Webhook): Promise<string> {
42
+ const url = typeof hook === "string" ? hook : hook?.url;
43
+ if (typeof url !== "string") throw new UserError("webhook: pass the webhook's URL (a string) or a webhook");
44
+ const problem = (await loadWebhook()).urlProblem(url);
45
+ if (problem !== null) throw new UserError("webhook: " + problem);
46
+ return url;
47
+ }
48
+
49
+ function agent(agentId: string): string {
50
+ if (typeof agentId !== "string" || agentId.trim() === "") throw new UserError("agentId: pass the agent's id");
51
+ return agentId;
52
+ }
53
+
54
+ function status(err: unknown): number {
55
+ return err instanceof ResponseError ? err.response.status : 0;
56
+ }
57
+
58
+ /** The server's reason, never its raw body: a 422 may echo the request, and the request carries the secret. */
59
+ async function apiMessage(err: unknown, secret?: string): Promise<string> {
60
+ let message: unknown;
61
+ if (err instanceof ResponseError) {
62
+ try {
63
+ message = ((await err.response.clone().json()) as { error?: { message?: unknown } })?.error?.message;
64
+ } catch {
65
+ message = undefined;
66
+ }
67
+ }
68
+ if (typeof message !== "string" || !message || (secret !== undefined && message.includes(secret))) {
69
+ return `HTTP ${status(err) || "error"}`;
70
+ }
71
+ return message;
72
+ }
73
+
74
+ /** Where webhook secrets live. Swap the implementation in `secretBackend`, nowhere else. */
75
+ export interface SecretBackend {
76
+ /** Store `secret` for `url` on the agent, replacing any current one. */
77
+ put(agentId: string, url: string, secret: string): Promise<void>;
78
+ /** `"set"` only for a secret stored by `put`; a placeholder from `ensure` is `"missing"`. */
79
+ status(agentId: string, url: string): Promise<SecretStatus>;
80
+ /** Remove the secret; nothing to remove is not an error. */
81
+ delete(agentId: string, url: string): Promise<void>;
82
+ /** For `deploy`: make sure the agent has a secret for `url` (a random placeholder one if none) and return the
83
+ * credential name for agent.json `secret_credential` and `status` (`"missing"` while it is a placeholder). */
84
+ ensure(agentId: string, url: string): Promise<{ name: string; status: SecretStatus }>;
85
+ }
86
+
87
+ interface Named { id: string; name: string; description?: string | null }
88
+
89
+ /** Today's store: a bearer Custom API the SDK owns, bound to the agent, never enabled for chats. */
90
+ class CustomApiBackend implements SecretBackend {
91
+ constructor(private readonly api: CustomAPIsApi) {}
92
+
93
+ /** The caller's Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
94
+ private async named(name: string): Promise<Named[]> {
95
+ const found: Named[] = [];
96
+ let offset = 0;
97
+ for (;;) {
98
+ const result = await this.api.listCustomApis({ q: name, limit: PAGE, offset });
99
+ for (const item of result.data) if (item.name === name) found.push(item);
100
+ offset += result.data.length;
101
+ if (result.data.length === 0 || !result.hasMore) return found;
102
+ }
103
+ }
104
+
105
+ /** The Custom APIs named `name` that the SDK created; throws when only someone else's has the name. */
106
+ private async owned(name: string): Promise<Named[]> {
107
+ const named = await this.named(name);
108
+ const owned = named.filter((item) => OWNED.includes(item.description ?? ""));
109
+ if (named.length > 0 && owned.length === 0) {
110
+ throw new UserError(`a Custom API named '${name}' exists that the SDK did not create; it was left alone. ` +
111
+ "Rename or delete it, then try again");
112
+ }
113
+ return owned;
114
+ }
115
+
116
+ private async bind(agentId: string, customApiId: string): Promise<void> {
117
+ const bound = (await this.api.listAgentCustomApis({ agentId })).data;
118
+ if (bound.some((item) => item.id === customApiId)) return;
119
+ try {
120
+ await this.api.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
121
+ } catch (err) {
122
+ if (status(err) === 409) return; // bound meanwhile
123
+ throw new UserError(`could not bind the webhook secret to agent ${agentId}: ${await apiMessage(err)}`);
124
+ }
125
+ }
126
+
127
+ /** PATCH the secret in, always asking for `enabledForChats: false`. The server switches chats off by detaching a
128
+ * capability, and answers 404 when there is nothing to detach (the API is already off). Then the API is read
129
+ * back: only when it exists and is off is the PATCH sent again without the switch, so the secret still lands and
130
+ * chats stay off. */
131
+ private async update(customApiId: string, host: string, description: string, secret: string): Promise<void> {
132
+ const patch = (off: { enabledForChats?: boolean }) => this.api.updateCustomApi({ customApiId, customApiUpdate: {
133
+ host, description, auth: { type: "bearer", token: secret }, ...off,
134
+ } });
135
+ try {
136
+ await patch({ enabledForChats: false });
137
+ } catch (err) {
138
+ if (status(err) !== 404) throw err;
139
+ if ((await this.api.getCustomApi({ customApiId })).enabledForChats !== false) throw err; // gone (404) or on
140
+ await patch({});
141
+ }
142
+ }
143
+
144
+ private async store(agentId: string, url: string, secret: string, owned: Named[],
145
+ description = SECRET_DESCRIPTION): Promise<string> {
146
+ const { secretCredentialName, webhookHost } = await loadWebhook();
147
+ const name = secretCredentialName(agentId, url);
148
+ const host = webhookHost(url);
149
+ let customApiId: string;
150
+ try {
151
+ if (owned.length > 0) {
152
+ customApiId = owned[0].id;
153
+ await this.update(customApiId, host, description, secret);
154
+ } else {
155
+ customApiId = (await this.api.createCustomApi({ customApiCreate: {
156
+ name, description, host, enabledForChats: false, auth: { type: "bearer", token: secret },
157
+ } })).id;
158
+ }
159
+ } catch (err) {
160
+ if (!(err instanceof ResponseError)) throw err;
161
+ throw new UserError(`could not store the webhook secret for ${host}: ${await apiMessage(err, secret)}`);
162
+ }
163
+ await this.bind(agentId, customApiId);
164
+ return name;
165
+ }
166
+
167
+ async put(agentId: string, url: string, secret: string): Promise<void> {
168
+ await this.store(agentId, url, secret, await this.owned((await loadWebhook()).secretCredentialName(agentId, url)));
169
+ }
170
+
171
+ async status(agentId: string, url: string): Promise<SecretStatus> {
172
+ const name = (await loadWebhook()).secretCredentialName(agentId, url);
173
+ // Not a placeholder, not someone else's.
174
+ const stored = (await this.named(name)).filter((item) => item.description === SECRET_DESCRIPTION).map((i) => i.id);
175
+ if (stored.length === 0) return "missing";
176
+ const bound = (await this.api.listAgentCustomApis({ agentId })).data;
177
+ return bound.some((item) => stored.includes(item.id)) ? "set" : "missing";
178
+ }
179
+
180
+ async delete(agentId: string, url: string): Promise<void> {
181
+ for (const item of await this.owned((await loadWebhook()).secretCredentialName(agentId, url))) {
182
+ try {
183
+ await this.api.unbindCustomApi({ agentId, customApiId: item.id });
184
+ } catch (err) {
185
+ if (status(err) !== 404) throw err;
186
+ }
187
+ try {
188
+ await this.api.deleteCustomApi({ customApiId: item.id });
189
+ } catch (err) {
190
+ if (status(err) !== 404) throw err;
191
+ }
192
+ }
193
+ }
194
+
195
+ async ensure(agentId: string, url: string): Promise<{ name: string; status: SecretStatus }> {
196
+ const name = (await loadWebhook()).secretCredentialName(agentId, url);
197
+ const owned = await this.owned(name);
198
+ if (owned.length > 0) {
199
+ await this.bind(agentId, owned[0].id);
200
+ return { name, status: owned[0].description === SECRET_DESCRIPTION ? "set" : "missing" };
201
+ }
202
+ console.warn(`agent ${agentId}: webhook ${url} has no signing secret yet; stored a random one nobody holds, so ` +
203
+ "deliveries fail verification until you call client.webhooks.setSecret");
204
+ const stored = await this.store(agentId, url, (await loadCrypto()).generateSecret(), owned, PLACEHOLDER_DESCRIPTION);
205
+ return { name: stored, status: "missing" };
206
+ }
207
+ }
208
+
209
+ /** The one place that picks where secrets live. */
210
+ export function secretBackend(api: { config?: Configuration; customApis?: CustomAPIsApi }): SecretBackend {
211
+ return new CustomApiBackend(api.customApis ?? new CustomAPIsApi(api.config));
212
+ }
213
+
214
+ /**
215
+ * `client.webhooks`: the signing secret of each agent.json webhook.
216
+ *
217
+ * `webhook` is the webhook's URL (or a webhook object); the secret covers the URL's host. Secrets are `whsec_` plus
218
+ * base64 of 24 to 64 bytes.
219
+ */
220
+ export class WebhookSecrets {
221
+ readonly #backend: SecretBackend;
222
+
223
+ constructor(config: Configuration) {
224
+ this.#backend = secretBackend({ config });
225
+ }
226
+
227
+ /** Store `secret` (a new generated one when left out) as the webhook's signing secret and return it. A malformed
228
+ * secret throws `SecretFormatError` before anything is sent. */
229
+ async setSecret(agentId: string, webhook: string | Webhook, secret?: string): Promise<string> {
230
+ const id = agent(agentId);
231
+ const url = await urlOf(webhook);
232
+ const value = secret === undefined ? (await loadCrypto()).generateSecret() : secret;
233
+ if (secret !== undefined) await checkSecret(secret);
234
+ await this.#backend.put(id, url, value);
235
+ return value;
236
+ }
237
+
238
+ /** Replace the webhook's signing secret with a new generated one and return it. Have your receiver accept the old
239
+ * and the new secret for a few minutes: a delivery still retrying is signed with the new one. */
240
+ async rotateSecret(agentId: string, webhook: string | Webhook): Promise<string> {
241
+ return this.setSecret(agentId, webhook);
242
+ }
243
+
244
+ /** `"set"` when the agent has a signing secret stored by `setSecret` or `rotateSecret` for the webhook; `"missing"`
245
+ * otherwise, including while it holds the placeholder a deploy stored. */
246
+ async secretStatus(agentId: string, webhook: string | Webhook): Promise<SecretStatus> {
247
+ const id = agent(agentId);
248
+ return this.#backend.status(id, await urlOf(webhook));
249
+ }
250
+
251
+ /** Remove the webhook's signing secret. Only what the SDK stored is removed; a Custom API you made yourself is
252
+ * never touched. Deliveries to the webhook fail until a new secret is set or the webhook is removed. */
253
+ async deleteSecret(agentId: string, webhook: string | Webhook): Promise<void> {
254
+ const id = agent(agentId);
255
+ await this.#backend.delete(id, await urlOf(webhook));
256
+ }
257
+ }
package/src/index.ts CHANGED
@@ -5,3 +5,7 @@ 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';
11
+ export type { SecretStatus } from './compose/webhookSecrets.js';