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