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.
@@ -0,0 +1,390 @@
1
+ /**
2
+ * Receive the agent's outbound webhooks: verify the signature, then parse the event.
3
+ *
4
+ * Panja signs every delivery in the Standard Webhooks format. Verify against the raw body bytes before parsing:
5
+ *
6
+ * ```ts
7
+ * import { verify, parseEvent } from "sarvam-agents-client/webhooks";
8
+ * verify(rawBody, req.headers, "whsec_..."); // throws WebhookVerificationError
9
+ * const event = parseEvent(rawBody); // TurnCompletedEvent | TurnFailedEvent | ...
10
+ * ```
11
+ *
12
+ * `verify` behaves exactly like the server's reference verifier (`claw_common/webhooks/signing.py`) and the Python
13
+ * SDK's, and is tested against the server's vectors (`shared/webhooks/vectors.json`). Nothing here logs, and no error
14
+ * carries a secret or a signature: errors carry only a closed `reason` token. Uses `node:crypto` only.
15
+ */
16
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
17
+
18
+ /**
19
+ * Every event an `agent.json` webhook may subscribe to. `approval.requested` is reserved: the server accepts it
20
+ * (with the save warning `event_reserved`) but never sends it yet.
21
+ */
22
+ export const WEBHOOK_EVENTS = ["turn.completed", "turn.failed", "turn.requires_action", "approval.requested"] as const;
23
+ export type WebhookEventType = (typeof WEBHOOK_EVENTS)[number];
24
+
25
+ const SECRET_PREFIX = "whsec_";
26
+ const SECRET_MIN_BYTES = 24;
27
+ const SECRET_MAX_BYTES = 64;
28
+ const SIGNATURE_PREFIX = "v1,";
29
+ export const DEFAULT_TOLERANCE_S = 300;
30
+ /** `verify` examines at most this many space-separated signature entries; the rest are ignored. */
31
+ export const MAX_SIGNATURES_EXAMINED = 10;
32
+ /**
33
+ * A longer `webhook-timestamp` is refused as `bad_timestamp`, as on the server (where `int()` caps out at 4300
34
+ * digits); no real time needs more than 20.
35
+ */
36
+ export const MAX_TIMESTAMP_DIGITS = 20;
37
+
38
+ export type SecretFormatReason = "prefix" | "base64" | "length";
39
+ export type VerificationReason =
40
+ | "missing_header"
41
+ | "bad_timestamp"
42
+ | "timestamp_too_old"
43
+ | "timestamp_too_new"
44
+ | "no_matching_signature";
45
+
46
+ /** A secret is not `whsec_` + base64 of 24 to 64 bytes. The message is the reason alone, never the secret. */
47
+ export class SecretFormatError extends Error {
48
+ readonly reason: SecretFormatReason;
49
+ constructor(reason: SecretFormatReason) {
50
+ super(reason);
51
+ this.name = "SecretFormatError";
52
+ this.reason = reason;
53
+ Object.setPrototypeOf(this, new.target.prototype);
54
+ }
55
+ }
56
+
57
+ /** A delivery failed verification. The message is the reason alone. */
58
+ export class WebhookVerificationError extends Error {
59
+ readonly reason: VerificationReason;
60
+ constructor(reason: VerificationReason) {
61
+ super(reason);
62
+ this.name = "WebhookVerificationError";
63
+ this.reason = reason;
64
+ Object.setPrototypeOf(this, new.target.prototype);
65
+ }
66
+ }
67
+
68
+ /** What `verify` vouched for: the `webhook-id` (dedupe on it) and the `webhook-timestamp` in unix seconds. */
69
+ export interface VerifiedMessage {
70
+ msgId: string;
71
+ timestamp: number;
72
+ }
73
+
74
+ /** A fetch `Headers`, or a plain object such as Node's `req.headers`. Names are matched case-insensitively. */
75
+ export type HeadersLike =
76
+ | { forEach(callback: (value: string, key: string) => void): void; get(name: string): string | null }
77
+ | Record<string, string | string[] | undefined>;
78
+
79
+ export type Payload = string | Uint8Array;
80
+
81
+ export interface VerifyOptions {
82
+ /** Seconds the timestamp may differ from `now`; default 300. Must be finite and not negative. */
83
+ tolerance?: number;
84
+ /** The current time in unix seconds; default the clock. Must be finite. */
85
+ now?: number;
86
+ }
87
+
88
+ const B64 = /^[A-Za-z0-9+/]*={0,2}$/;
89
+
90
+ /**
91
+ * Python 3.12's `base64.b64decode(s, validate=True)`: the standard alphabet, padding only at the end and only where
92
+ * it completes the last group; leftover bits in the last character are ignored. Returns null when it would refuse.
93
+ */
94
+ function b64decodeStrict(text: string): Buffer | null {
95
+ if (!B64.test(text)) return null;
96
+ const data = text.replace(/=+$/, "");
97
+ const pads = text.length - data.length;
98
+ const rem = data.length % 4;
99
+ if (!((rem === 0 && pads === 0) || (rem === 2 && pads === 2) || (rem === 3 && pads === 1))) return null;
100
+ return Buffer.from(text, "base64");
101
+ }
102
+
103
+ function parseSecret(secret: string): Buffer {
104
+ if (typeof secret !== "string" || !secret.startsWith(SECRET_PREFIX)) throw new SecretFormatError("prefix");
105
+ const key = b64decodeStrict(secret.slice(SECRET_PREFIX.length));
106
+ if (key === null) throw new SecretFormatError("base64");
107
+ if (key.length < SECRET_MIN_BYTES || key.length > SECRET_MAX_BYTES) throw new SecretFormatError("length");
108
+ return key;
109
+ }
110
+
111
+ function bodyBytes(payload: Payload): Buffer {
112
+ if (typeof payload === "string") return Buffer.from(payload, "utf8");
113
+ return Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength);
114
+ }
115
+
116
+ function mac(key: Buffer, msgId: string, timestamp: string, body: Buffer): Buffer {
117
+ // The exact bytes received; the timestamp is the header string as received (never re-stringified).
118
+ return createHmac("sha256", key).update(Buffer.from(`${msgId}.${timestamp}.`, "utf8")).update(body).digest();
119
+ }
120
+
121
+ /** Lowercased name -> value; for a plain object the last spelling of a name wins, as in the Python verifier. */
122
+ function lowerHeaders(headers: HeadersLike): Map<string, unknown> {
123
+ const out = new Map<string, unknown>();
124
+ if (typeof (headers as { forEach?: unknown }).forEach === "function" &&
125
+ typeof (headers as { get?: unknown }).get === "function") {
126
+ (headers as { forEach(cb: (value: string, key: string) => void): void })
127
+ .forEach((value, key) => out.set(key.toLowerCase(), value));
128
+ return out;
129
+ }
130
+ for (const key of Object.keys(headers)) out.set(key.toLowerCase(), (headers as Record<string, unknown>)[key]);
131
+ return out;
132
+ }
133
+
134
+ function header(headers: Map<string, unknown>, name: string): string {
135
+ const value = headers.get(name);
136
+ return typeof value === "string" ? value : "";
137
+ }
138
+
139
+ // Python's str.split() with no argument: runs of str.isspace() characters (not JavaScript's \s, which adds U+FEFF
140
+ // and lacks U+001C..U+001F and U+0085).
141
+ const PY_WHITESPACE = /[\t\n\v\f\r\x1c-\x20\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/;
142
+
143
+ function splitWhitespace(text: string): string[] {
144
+ return text.split(PY_WHITESPACE).filter((part) => part.length > 0);
145
+ }
146
+
147
+ /** A fresh `whsec_` secret of `nbytes` (24 to 64) random bytes, to store as the webhook's vault credential. */
148
+ export function generateSecret(nbytes = 32): string {
149
+ if (!Number.isInteger(nbytes) || nbytes < SECRET_MIN_BYTES || nbytes > SECRET_MAX_BYTES) {
150
+ throw new SecretFormatError("length");
151
+ }
152
+ return SECRET_PREFIX + randomBytes(nbytes).toString("base64");
153
+ }
154
+
155
+ /** `"v1,<base64 HMAC-SHA256>"` over `{msgId}.{timestamp}.{body}`, as the server signs (for tests). */
156
+ export function sign(secret: string, msg: { msgId: string; timestamp: number; body: Payload }): string {
157
+ return SIGNATURE_PREFIX + mac(parseSecret(secret), msg.msgId, String(msg.timestamp), bodyBytes(msg.body))
158
+ .toString("base64");
159
+ }
160
+
161
+ /**
162
+ * Verify a delivery; throws `WebhookVerificationError` (or `SecretFormatError`) if it fails.
163
+ *
164
+ * `payload` is the raw request body (a `Buffer` from `express.raw()`, or the exact text), before any JSON parsing.
165
+ * `secret` is one `whsec_` secret, or several while you rotate. The `webhook-timestamp` must be 1 to 20 ASCII digits
166
+ * within `tolerance` seconds of `now`; it is checked before any HMAC work. Only the first 10 `webhook-signature`
167
+ * entries are examined and entries not starting `v1,` are skipped. Comparisons are constant time. A header given as
168
+ * an array counts as missing. Throws `TypeError` when `now` or `tolerance` is not a finite number, or `tolerance` is
169
+ * negative: `Number(process.env.UNSET)` is NaN, which would quietly turn off the timestamp check. An empty list of
170
+ * secrets throws `TypeError` too: a receiver missing its secret would otherwise refuse every delivery as forged.
171
+ */
172
+ export function verify(
173
+ payload: Payload,
174
+ headers: HeadersLike,
175
+ secret: string | readonly string[],
176
+ opts: VerifyOptions = {},
177
+ ): VerifiedMessage {
178
+ const now = opts.now ?? Math.floor(Date.now() / 1000);
179
+ const tolerance = opts.tolerance ?? DEFAULT_TOLERANCE_S;
180
+ if (!Number.isFinite(now) || !Number.isFinite(tolerance) || tolerance < 0) {
181
+ throw new TypeError("verify: now and tolerance must be finite numbers, and tolerance not negative");
182
+ }
183
+ const secrets = typeof secret === "string" ? [secret] : [...secret];
184
+ // A configuration error: as no_matching_signature it would refuse every genuine delivery.
185
+ if (secrets.length === 0) throw new TypeError("verify: no secrets; pass at least one whsec_ secret");
186
+ const body = bodyBytes(payload);
187
+ const lowered = lowerHeaders(headers);
188
+ const msgId = header(lowered, "webhook-id");
189
+ const rawTs = header(lowered, "webhook-timestamp");
190
+ const rawSigs = header(lowered, "webhook-signature");
191
+ if (!msgId || !rawTs || !rawSigs) throw new WebhookVerificationError("missing_header");
192
+ if (!/^[0-9]+$/.test(rawTs) || rawTs.length > MAX_TIMESTAMP_DIGITS) {
193
+ throw new WebhookVerificationError("bad_timestamp");
194
+ }
195
+ // Exact for every value near the clock; a larger one is far outside the tolerance either way.
196
+ const timestamp = Number(rawTs);
197
+ if (timestamp < now - tolerance) throw new WebhookVerificationError("timestamp_too_old");
198
+ if (timestamp > now + tolerance) throw new WebhookVerificationError("timestamp_too_new");
199
+
200
+ const received: Buffer[] = [];
201
+ for (const entry of splitWhitespace(rawSigs).slice(0, MAX_SIGNATURES_EXAMINED)) {
202
+ if (!entry.startsWith(SIGNATURE_PREFIX)) continue;
203
+ const decoded = b64decodeStrict(entry.slice(SIGNATURE_PREFIX.length));
204
+ if (decoded !== null) received.push(decoded);
205
+ }
206
+
207
+ let matched = false;
208
+ for (const s of secrets) {
209
+ const expected = mac(parseSecret(s), msgId, rawTs, body);
210
+ for (const candidate of received) {
211
+ // no early exit inside the loops: the work does not depend on which entry matches
212
+ if (candidate.length === expected.length && timingSafeEqual(candidate, expected)) matched = true;
213
+ }
214
+ }
215
+ if (!matched) throw new WebhookVerificationError("no_matching_signature");
216
+ return { msgId, timestamp };
217
+ }
218
+
219
+ // -- event payloads ------------------------------------------------------------------------------------------------
220
+ // The wire JSON as sent (camelCase); absent values are null, so the shape is stable. A newer server may add fields.
221
+
222
+ export interface TurnSource {
223
+ /** `message`, `cron` or `subagent_result`. */
224
+ kind: string;
225
+ /** `web`, `cli`, `slack`, `teams`, ... */
226
+ platform: string;
227
+ cronId: string | null;
228
+ scheduleRunId: string | null;
229
+ delegationIds: string[];
230
+ }
231
+
232
+ export interface TurnUsage {
233
+ inputTokens: number | null;
234
+ outputTokens: number | null;
235
+ reasoningTokens: number | null;
236
+ cacheReadTokens: number | null;
237
+ }
238
+
239
+ /** The `agent.json` limit that ended the turn. */
240
+ export interface TurnCap {
241
+ kind: string;
242
+ limit: string;
243
+ value: number | null;
244
+ }
245
+
246
+ export interface TurnData {
247
+ agent: { id: string };
248
+ /** `id` is the platform's conversation key; on web and API sessions, the id `GET /v1/conversations/{id}` takes. */
249
+ conversation: { id: string; sessionId: string };
250
+ /** `id` is the same on every event of a turn; `responseId` is currently always null. */
251
+ turn: { id: string; responseId: string | null };
252
+ source: TurnSource;
253
+ tenantId: string;
254
+ workspaceId: string;
255
+ userId: string;
256
+ /** Fields cut to fit the 64 KiB body cap (`text`, `rawText`, `output`, `actions.<i>.arguments`). */
257
+ truncated: string[];
258
+ }
259
+
260
+ export interface TurnCompletedData extends TurnData {
261
+ status: "completed";
262
+ text: string;
263
+ /** The validated structured output, or null. */
264
+ output: unknown;
265
+ /** `tool_in_loop`, `tool_oversize`, `forced_tool`, `native` or `prompted`; passed through as sent. */
266
+ outputMode: string | null;
267
+ /** `limit`, `budget`, `paused` or `suppressed`; passed through as sent. */
268
+ outputSkipped: string | null;
269
+ cap: TurnCap | null;
270
+ usage: TurnUsage;
271
+ }
272
+
273
+ export interface TurnFailedData extends TurnData {
274
+ status: "failed";
275
+ /** `code`: `user_stop`, `context_overflow`, `persist_failed`, `seat_budget_exhausted_error`, `schema_mismatch`,
276
+ * or `turn_failed`. */
277
+ error: { code: string; message: string };
278
+ /** Schema mismatch only: up to three `path: message` strings. */
279
+ errors: string[] | null;
280
+ /** Schema mismatch only: the model's raw text. */
281
+ rawText: string | null;
282
+ cap: TurnCap | null;
283
+ usage: TurnUsage;
284
+ }
285
+
286
+ export interface ClarifyQuestion {
287
+ id: string;
288
+ prompt: string;
289
+ inputType?: string;
290
+ choices?: string[] | null;
291
+ [key: string]: unknown;
292
+ }
293
+
294
+ export interface ClarifyAction {
295
+ type: "clarify";
296
+ requestId: string;
297
+ questions: ClarifyQuestion[];
298
+ createdAt: string | null;
299
+ expiresAt: string | null;
300
+ }
301
+
302
+ /**
303
+ * A function tool call waiting for its result: answer it with `postToolResults`
304
+ * (`POST /v1/conversations/{id}/tool-results` with `requestId` and this `toolCallId`), or continue the run with
305
+ * `run(agent, RunState.fromSession(...))`. A turn the SDK runner is driving answers its own function calls: don't
306
+ * answer those here too (the second answer gets 409 `already_answered`).
307
+ */
308
+ export interface FunctionCallAction {
309
+ type: "function_call";
310
+ requestId: string;
311
+ toolCallId: string;
312
+ name: string;
313
+ /** null when it was cut to fit the body cap (`truncated` lists `actions.<i>.arguments`). */
314
+ arguments: Record<string, unknown> | null;
315
+ createdAt: string | null;
316
+ expiresAt: string | null;
317
+ }
318
+
319
+ /**
320
+ * An action of a type this SDK release does not know, as sent. It is not part of `RequiredAction`, so narrowing on
321
+ * `type` keeps working; a newer server may still send one, so keep a default branch when you switch on `type`.
322
+ */
323
+ export interface UnknownAction {
324
+ type: string;
325
+ [key: string]: unknown;
326
+ }
327
+
328
+ /**
329
+ * Same shape as `requiredActions` on `GET /v1/conversations/{id}`. A newer server may send other action types
330
+ * (`UnknownAction`): `parseEvent` passes them through, so handle a `type` you don't know in a default branch.
331
+ */
332
+ export type RequiredAction = ClarifyAction | FunctionCallAction;
333
+
334
+ export interface TurnRequiresActionData extends TurnData {
335
+ status: "requires_action";
336
+ requestId: string;
337
+ /** `clarify` or `function_call`. */
338
+ kind: string;
339
+ expiresAt: string | null;
340
+ actions: RequiredAction[];
341
+ }
342
+
343
+ interface Envelope<T extends string, D> {
344
+ type: T;
345
+ id: string;
346
+ /** When the event was built: ISO 8601, UTC, milliseconds (`2026-11-11T10:15:42.123Z`). */
347
+ timestamp: string;
348
+ data: D;
349
+ }
350
+
351
+ export type TurnCompletedEvent = Envelope<"turn.completed", TurnCompletedData>;
352
+ export type TurnFailedEvent = Envelope<"turn.failed", TurnFailedData>;
353
+ export type TurnRequiresActionEvent = Envelope<"turn.requires_action", TurnRequiresActionData>;
354
+ export type WebhookEvent = TurnCompletedEvent | TurnFailedEvent | TurnRequiresActionEvent;
355
+
356
+ const STATUS = new Map<string, string>([
357
+ ["turn.completed", "completed"],
358
+ ["turn.failed", "failed"],
359
+ ["turn.requires_action", "requires_action"],
360
+ ]);
361
+
362
+ function isObject(value: unknown): value is Record<string, unknown> {
363
+ return typeof value === "object" && value !== null && !Array.isArray(value);
364
+ }
365
+
366
+ /**
367
+ * The typed event of a verified body (raw bytes, text or an already-parsed object).
368
+ *
369
+ * Returns `undefined` for an event type this SDK release doesn't know (reply 2xx and skip it). Throws `TypeError`
370
+ * when the body is not a webhook event or its `data.status` doesn't match its type. Only the envelope is checked;
371
+ * the fields are typed as the server documents them.
372
+ */
373
+ export function parseEvent(payload: Payload | Record<string, unknown>): WebhookEvent | undefined {
374
+ let raw: unknown = payload;
375
+ if (typeof payload === "string" || payload instanceof Uint8Array) {
376
+ try {
377
+ raw = JSON.parse(typeof payload === "string" ? payload : bodyBytes(payload).toString("utf8"));
378
+ } catch {
379
+ throw new TypeError("webhook body is not JSON");
380
+ }
381
+ }
382
+ if (!isObject(raw) || typeof raw.type !== "string") throw new TypeError("webhook body is not an event: no string 'type'");
383
+ const status = STATUS.get(raw.type);
384
+ if (status === undefined) return undefined;
385
+ if (typeof raw.id !== "string" || typeof raw.timestamp !== "string" || !isObject(raw.data) ||
386
+ raw.data.status !== status) {
387
+ throw new TypeError(`webhook body is not a ${raw.type} event`);
388
+ }
389
+ return raw as unknown as WebhookEvent;
390
+ }