sarvam-agents-client 0.3.1 → 0.3.2

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.
@@ -9,6 +9,8 @@ import {
9
9
  import type { FunctionTool, FunctionToolOptions } from "./functionTool.js";
10
10
  import { checkOutputType, outputSchema } from "./output.js";
11
11
  import type { OutputType } from "./output.js";
12
+ import { checkWebhooks, copyWebhooks, webhooksJson } from "./webhook.js";
13
+ import type { Webhook } from "./webhook.js";
12
14
 
13
15
  const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
14
16
  const REASONING = ["off", "none", "low", "medium", "high", "xhigh", "max"];
@@ -48,6 +50,8 @@ export interface AgentOptions<TOutput extends OutputType | undefined = undefined
48
50
  metadata?: Record<string, string>;
49
51
  /** The shape of the final answer: `{ type: "json_schema", schema }` or a zod schema. `finalOutput` follows it. */
50
52
  outputType?: TOutput;
53
+ /** Endpoints that receive the turn's events (agent.json `webhooks`); at most 5. */
54
+ webhooks?: Webhook[];
51
55
  }
52
56
 
53
57
  function deepFreeze<T>(value: T): T {
@@ -134,6 +138,7 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
134
138
  readonly functionTimeoutSeconds?: number;
135
139
  readonly limits?: Limits;
136
140
  readonly metadata?: Record<string, string>;
141
+ readonly webhooks?: readonly Webhook[];
137
142
  /** Kept by reference and not frozen: a zod schema must stay usable. Non-enumerable, so deepFreeze skips it. */
138
143
  declare readonly outputType: TOutput;
139
144
 
@@ -170,8 +175,10 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
170
175
  this.functionTimeoutSeconds = opts.functionTimeoutSeconds;
171
176
  this.limits = clone(opts.limits);
172
177
  this.metadata = clone(opts.metadata);
178
+ this.webhooks = clone(opts.webhooks);
173
179
  Object.defineProperty(this, "outputType", { value: opts.outputType, enumerable: false, writable: false });
174
180
  this.check();
181
+ if (this.webhooks !== undefined) this.webhooks = copyWebhooks(this.webhooks);
175
182
  deepFreeze(this);
176
183
  }
177
184
 
@@ -243,6 +250,7 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
243
250
  if (names.indexOf("code_mode") !== -1 && names.indexOf("sandbox") === -1) {
244
251
  throw new UserError("tools: codeMode needs sandbox; add sandbox() to tools");
245
252
  }
253
+ if (this.webhooks !== undefined) checkWebhooks(this.webhooks);
246
254
  this.checkFunctions();
247
255
  }
248
256
 
@@ -327,6 +335,7 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
327
335
  if (functions.length > 0) out["functions"] = functions.map(functionToolSettings);
328
336
  }
329
337
  if (this.functionTimeoutSeconds !== undefined) out["function_timeout_seconds"] = this.functionTimeoutSeconds;
338
+ if (this.webhooks !== undefined && this.webhooks.length > 0) out["webhooks"] = webhooksJson(this.webhooks);
330
339
  if (this.outputType !== undefined) out["output_schema"] = outputSchema(this.outputType as OutputType);
331
340
  return out;
332
341
  }
@@ -4,6 +4,7 @@ export * from "./tools.js";
4
4
  export * from "./agent.js";
5
5
  export { tool } from "./functionTool.js";
6
6
  export type { FunctionCallDetails, FunctionTool, FunctionToolArgs, FunctionToolOptions } from "./functionTool.js";
7
+ export type { Webhook } from "./webhook.js";
7
8
  export type { Event, ClarifyQuestion, FunctionCallRequest, OutputCitation } from "./events.js";
8
9
  export { SettingsTransport } from "./settingsTransport.js";
9
10
  export type { PendingFunctionCalls, RemoteAgent, SettingsWarning, TurnStream, Transport } from "./transport.js";
@@ -2,6 +2,7 @@
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { AgentsApi } from "../apis/AgentsApi.js";
4
4
  import { ConversationsApi } from "../apis/ConversationsApi.js";
5
+ import { CustomAPIsApi } from "../apis/CustomAPIsApi.js";
5
6
  import { ResponsesApi } from "../apis/ResponsesApi.js";
6
7
  import { FetchError, ResponseError } from "../runtime.js";
7
8
  import type { Configuration } from "../runtime.js";
@@ -172,6 +173,15 @@ interface Envelope {
172
173
  warnings?: SettingsWarning[] | null;
173
174
  }
174
175
 
176
+ /** `settings` for a new agent's first write: no `webhooks` (the server checks them against the agent's bound
177
+ * credentials, and a new agent has none yet) and no `sdk_hash` (it covers the webhooks, so an agent left in this
178
+ * state would otherwise read as deployed and never get them). */
179
+ function withoutWebhooks(settings: Record<string, any>): Record<string, any> {
180
+ const { webhooks: _webhooks, ...out } = settings;
181
+ const { sdk_hash: _hash, ...metadata } = settings["metadata"];
182
+ return { ...out, metadata };
183
+ }
184
+
175
185
  function isNotFound(err: unknown): boolean {
176
186
  return err instanceof ResponseError && err.response.status === 404;
177
187
  }
@@ -210,11 +220,13 @@ export class SettingsTransport implements Transport {
210
220
  private readonly agents: AgentsApi;
211
221
  private readonly conversations: ConversationsApi;
212
222
  private readonly responses: ResponsesApi;
223
+ private readonly customApis: CustomAPIsApi;
213
224
 
214
225
  constructor(private readonly config: Configuration) {
215
226
  this.agents = new AgentsApi(config);
216
227
  this.conversations = new ConversationsApi(config);
217
228
  this.responses = new ResponsesApi(config);
229
+ this.customApis = new CustomAPIsApi(config);
218
230
  }
219
231
 
220
232
  // -- agents ---------------------------------------------------------------------------------------------
@@ -245,10 +257,17 @@ export class SettingsTransport implements Transport {
245
257
 
246
258
  async createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent> {
247
259
  const settings = agent.toSettings();
260
+ const webhooks = (settings["webhooks"] ?? []) as { secret_credential: string }[];
261
+ // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
262
+ // without them, bind the Custom APIs they name, then write the settings in full.
263
+ const { bind, unbound } = await this.webhookCredentials(webhooks);
248
264
  let resource;
249
265
  try {
250
266
  resource = await this.agents.createAgent({
251
- agentCreate: { name: agent.name, instructions: agent.instructions, settings },
267
+ agentCreate: {
268
+ name: agent.name, instructions: agent.instructions,
269
+ settings: webhooks.length > 0 ? withoutWebhooks(settings) : settings,
270
+ },
252
271
  });
253
272
  } catch (err) {
254
273
  // A 422 stored nothing, so there is no agent to delete.
@@ -265,7 +284,19 @@ export class SettingsTransport implements Transport {
265
284
  if (isNotFound(err)) throw new NotSupportedByServerError(["settings"]);
266
285
  throw err;
267
286
  }
287
+ if (webhooks.length > 0) {
288
+ for (const { path, name, customApiId } of bind) await this.bind(resource.id, path, name, customApiId);
289
+ try {
290
+ envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
291
+ } catch (err) {
292
+ const invalid = await invalidSettings(err);
293
+ if (invalid === null) throw err;
294
+ throw new UserError([invalid.message, ...unbound].join("; "), invalid.issues);
295
+ }
296
+ }
268
297
  warnings = checkWarnings(envelope, settings);
298
+ // Accepted unchecked (webhooks switched off): refused once they are on.
299
+ for (const sentence of unbound) console.warn(`agent ${resource.id}: ${sentence}`);
269
300
  checkMetadata(envelope, agent);
270
301
  await this.agents.deployAgent({ agentId: resource.id });
271
302
  } catch (err) {
@@ -286,6 +317,60 @@ export class SettingsTransport implements Transport {
286
317
  };
287
318
  }
288
319
 
320
+ /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
321
+ * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
322
+ * checks credentials). */
323
+ private async webhookCredentials(webhooks: { secret_credential: string }[]): Promise<{
324
+ bind: { path: string; name: string; customApiId: string }[];
325
+ unbound: string[];
326
+ }> {
327
+ const bind: { path: string; name: string; customApiId: string }[] = [];
328
+ const unbound: string[] = [];
329
+ const seen = new Set<string>();
330
+ for (const [i, hook] of webhooks.entries()) {
331
+ const name = hook.secret_credential;
332
+ if (seen.has(name)) continue;
333
+ seen.add(name);
334
+ const path = `webhooks.${i}.secret_credential`;
335
+ const ids = await this.customApiIds(name);
336
+ if (ids.length === 1) {
337
+ bind.push({ path, name, customApiId: ids[0] });
338
+ } else if (ids.length === 0) {
339
+ unbound.push(`${path}: you have no Custom API named '${name}' to bind to the new agent; create it, then ` +
340
+ "deploy again");
341
+ } else {
342
+ unbound.push(`${path}: ${ids.length} of your Custom APIs are named '${name}', so none was bound to the new ` +
343
+ "agent; rename or delete all but one, then deploy again");
344
+ }
345
+ }
346
+ return { bind, unbound };
347
+ }
348
+
349
+ /** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
350
+ private async customApiIds(name: string): Promise<string[]> {
351
+ const ids: string[] = [];
352
+ let offset = 0;
353
+ for (;;) {
354
+ const result = await this.customApis.listCustomApis({ q: name, limit: PAGE, offset });
355
+ const items = result.data;
356
+ for (const item of items) if (item.name === name) ids.push(item.id);
357
+ offset += items.length;
358
+ if (items.length === 0 || !result.hasMore) return ids;
359
+ }
360
+ }
361
+
362
+ private async bind(agentId: string, path: string, name: string, customApiId: string): Promise<void> {
363
+ try {
364
+ await this.customApis.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
365
+ } catch (err) {
366
+ const status = err instanceof ResponseError ? err.response.status : 0;
367
+ if (!(err instanceof ResponseError) || status < 400 || status >= 500) throw err;
368
+ const message = (await chatError(err))?.["message"];
369
+ throw new UserError(`${path}: could not bind the Custom API '${name}' to the new agent: ` +
370
+ (typeof message === "string" && message ? message : `HTTP ${status}`));
371
+ }
372
+ }
373
+
289
374
  async updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent> {
290
375
  const settings = agent.toSettings();
291
376
  // findAgents searches by display name, so an adopted (or dashboard-renamed) agent must carry sdk_name.
@@ -0,0 +1,181 @@
1
+ /**
2
+ * `webhooks` entries of `agent.json`, checked locally with the server's cheap rules (as the Python SDK does).
3
+ *
4
+ * The server (`claw_common/agent_settings/webhooks.py`) also checks that the host resolves to a public address and
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`).
9
+ */
10
+ import { UserError } from "./errors.js";
11
+ import { WEBHOOK_EVENTS } from "../webhooks.js";
12
+ import type { WebhookEventType } from "../webhooks.js";
13
+
14
+ /** Where the agent reports a finished, failed or paused turn (agent.json `webhooks[]`). */
15
+ export interface Webhook {
16
+ /** An `https://` URL on port 443 with a DNS host; a query string is allowed. */
17
+ url: string;
18
+ /** 1 to 4 distinct events. `approval.requested` is reserved: accepted, not sent yet. */
19
+ events: WebhookEventType[];
20
+ /** The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). */
21
+ secretCredential: string;
22
+ }
23
+
24
+ export const WEBHOOKS_MAX = 5;
25
+ const WEBHOOK_URL_MAX = 2048;
26
+ const SECRET_CREDENTIAL_MAX = 256;
27
+
28
+ const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
29
+ // A last label that is a number (decimal, or 0x hex) makes resolvers read the whole host as an IPv4 address.
30
+ const NUMERIC_LABEL = /^(?:[0-9]+|0x[0-9a-f]*)$/;
31
+ const SCHEME = /^[A-Za-z][A-Za-z0-9+\-.]*$/;
32
+
33
+ /** Length in code points, as Python's `len`. */
34
+ function codePoints(text: string): number {
35
+ return Array.from(text).length;
36
+ }
37
+
38
+ /** `[scheme, netloc, path, query]` as Python 3.12's `urlsplit` splits a URL without a fragment. */
39
+ function split(url: string): [string, string, string, string] {
40
+ let rest = url;
41
+ let scheme = "";
42
+ const i = rest.indexOf(":");
43
+ if (i > 0 && SCHEME.test(rest.slice(0, i))) {
44
+ scheme = rest.slice(0, i).toLowerCase();
45
+ rest = rest.slice(i + 1);
46
+ }
47
+ let netloc = "";
48
+ if (rest.slice(0, 2) === "//") {
49
+ let end = rest.length;
50
+ for (const c of "/?#") {
51
+ const at = rest.indexOf(c, 2);
52
+ if (at >= 0) end = Math.min(end, at);
53
+ }
54
+ netloc = rest.slice(2, end);
55
+ rest = rest.slice(end);
56
+ }
57
+ let query = "";
58
+ const q = rest.indexOf("?");
59
+ if (q >= 0) {
60
+ query = rest.slice(q + 1);
61
+ rest = rest.slice(0, q);
62
+ }
63
+ return [scheme, netloc, rest, query];
64
+ }
65
+
66
+ /** Python's `str.partition`. */
67
+ function partition(text: string, sep: string): [string, string, string] {
68
+ const at = text.indexOf(sep);
69
+ return at < 0 ? [text, "", ""] : [text.slice(0, at), sep, text.slice(at + sep.length)];
70
+ }
71
+
72
+ /** `urlsplit`'s host (lowercased) and raw port (`null` when absent or empty). */
73
+ function hostPort(netloc: string): [string, string | null] {
74
+ const hostinfo = netloc.slice(netloc.lastIndexOf("@") + 1);
75
+ const [, bracket, bracketed] = partition(hostinfo, "[");
76
+ let host: string;
77
+ let port: string;
78
+ if (bracket) {
79
+ const [inner, , after] = partition(bracketed, "]");
80
+ host = inner;
81
+ port = partition(after, ":")[2];
82
+ } else {
83
+ [host, , port] = partition(hostinfo, ":");
84
+ }
85
+ return [host.toLowerCase(), port || null];
86
+ }
87
+
88
+ function stripTrailingDots(host: string): string {
89
+ return host.replace(/\.+$/, "");
90
+ }
91
+
92
+ /** Why `url` is not an allowed webhook URL, or null. Every URL the server refuses is refused, with the server's
93
+ * sentence for every URL Python's `urlsplit` parses; for a netloc its NFKC check refuses, the sentence may differ. */
94
+ export function urlProblem(url: string): string | null {
95
+ if (codePoints(url) > WEBHOOK_URL_MAX) return `url must be at most ${WEBHOOK_URL_MAX} characters.`;
96
+ for (let i = 0; i < url.length; i++) {
97
+ const code = url.charCodeAt(i);
98
+ if (code <= 0x20 || code === 0x7f) return "url must not contain spaces or control characters.";
99
+ }
100
+ if (url.indexOf("#") !== -1) return "url must not have a fragment.";
101
+ const [scheme, netloc, path] = split(url);
102
+ if (scheme !== "https") return "url must start with https://.";
103
+ if (netloc.indexOf("@") !== -1) return "url must not contain a user name or password.";
104
+ // urlsplit refuses unbalanced brackets outright
105
+ if ((netloc.indexOf("[") !== -1) !== (netloc.indexOf("]") !== -1)) {
106
+ return "url host must be a DNS name, not an IP address.";
107
+ }
108
+ const [rawHost, port] = hostPort(netloc);
109
+ if (port !== null) {
110
+ if (!/^[0-9]+$/.test(port) || Number(port) > 65535) {
111
+ return "url has an invalid port; leave the port out (443 is used).";
112
+ }
113
+ if (Number(port) !== 443) return "url must use port 443; leave the port out.";
114
+ }
115
+ const host = stripTrailingDots(rawHost);
116
+ if (!host) return "url must name a host, like https://hooks.example.com/panja.";
117
+ if (netloc.indexOf("[") !== -1) return "url host must be a DNS name, not an IP address.";
118
+ const labels = host.split(".");
119
+ if (!labels.every((label) => LABEL.test(label))) return "url host must be a DNS name, like hooks.example.com.";
120
+ if (NUMERIC_LABEL.test(labels[labels.length - 1])) return "url host must be a DNS name, not an IP address.";
121
+ if (path.split("/").some((seg) => seg === "." || seg === "..")) return "url path must not contain . or .. segments.";
122
+ return null;
123
+ }
124
+
125
+ /** Host (lowercased, no trailing dot, no port), path and query: two URLs with one key are one endpoint. */
126
+ function urlKey(url: string): string {
127
+ const [, netloc, path, query] = split(url);
128
+ return `${stripTrailingDots(hostPort(netloc)[0])}${path}?${query}`;
129
+ }
130
+
131
+ /** The server's pure `webhooks` rules (types first); throws `UserError` naming the agent.json path. */
132
+ export function checkWebhooks(webhooks: unknown): void {
133
+ if (!Array.isArray(webhooks)) throw new UserError("webhooks: must be a list of webhooks");
134
+ if (webhooks.length > WEBHOOKS_MAX) {
135
+ throw new UserError(`webhooks: webhooks may hold at most ${WEBHOOKS_MAX} endpoints.`);
136
+ }
137
+ const seen = new Set<string>();
138
+ webhooks.forEach((hook: unknown, i: number) => {
139
+ const where = `webhooks.${i}.`;
140
+ if (typeof hook !== "object" || hook === null || Array.isArray(hook)) {
141
+ throw new UserError(`webhooks.${i}: must be an object with url, events and secretCredential`);
142
+ }
143
+ const { url, events, secretCredential } = hook as Record<string, unknown>;
144
+ if (typeof url !== "string") throw new UserError(where + "url: must be a string");
145
+ if (!Array.isArray(events) || !events.every((e) => typeof e === "string")) {
146
+ throw new UserError(where + "events: must be a list of event names");
147
+ }
148
+ if (typeof secretCredential !== "string") throw new UserError(where + "secretCredential: must be a string");
149
+ // Python's Webhook is extra="forbid": a key dropped silently (a misplaced secret) would never verify.
150
+ const extra = Object.keys(hook).find((k) => k !== "url" && k !== "events" && k !== "secretCredential");
151
+ if (extra !== undefined) throw new UserError(where + extra + ": Extra inputs are not permitted");
152
+ const problem = urlProblem(url);
153
+ if (problem !== null) throw new UserError(where + "url: " + problem);
154
+ if (events.length < 1 || events.length > WEBHOOK_EVENTS.length) {
155
+ throw new UserError(where + `events: events must list 1 to ${WEBHOOK_EVENTS.length} events.`);
156
+ }
157
+ if (events.some((e) => (WEBHOOK_EVENTS as readonly string[]).indexOf(e) === -1)) {
158
+ throw new UserError(where + `events: events must be from: ${WEBHOOK_EVENTS.join(", ")}.`);
159
+ }
160
+ if (new Set(events).size !== events.length) throw new UserError(where + "events: events must not repeat an event.");
161
+ const n = codePoints(secretCredential);
162
+ if (n < 1 || n > SECRET_CREDENTIAL_MAX) {
163
+ throw new UserError(where + "secret_credential: secret_credential must be the name of a vault credential " +
164
+ `(1 to ${SECRET_CREDENTIAL_MAX} characters).`);
165
+ }
166
+ const key = urlKey(url);
167
+ if (seen.has(key)) {
168
+ throw new UserError(where + "url: webhooks must not list the same url twice; put all its events on one entry.");
169
+ }
170
+ seen.add(key);
171
+ });
172
+ }
173
+
174
+ /** Only the three fields, in agent.json's names (a copy). */
175
+ export function copyWebhooks(webhooks: readonly Webhook[]): Webhook[] {
176
+ return webhooks.map((h) => ({ url: h.url, events: [...h.events], secretCredential: h.secretCredential }));
177
+ }
178
+
179
+ export function webhooksJson(webhooks: readonly Webhook[]): Record<string, unknown>[] {
180
+ return webhooks.map((h) => ({ url: h.url, events: [...h.events], secret_credential: h.secretCredential }));
181
+ }