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
|
@@ -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 { answerClarify, postToolResults, reconnect, streamResponse } from "../streaming.js";
|
|
@@ -165,6 +166,14 @@ class Finished {
|
|
|
165
166
|
}
|
|
166
167
|
close() { }
|
|
167
168
|
}
|
|
169
|
+
/** `settings` for a new agent's first write: no `webhooks` (the server checks them against the agent's bound
|
|
170
|
+
* credentials, and a new agent has none yet) and no `sdk_hash` (it covers the webhooks, so an agent left in this
|
|
171
|
+
* state would otherwise read as deployed and never get them). */
|
|
172
|
+
function withoutWebhooks(settings) {
|
|
173
|
+
const { webhooks: _webhooks, ...out } = settings;
|
|
174
|
+
const { sdk_hash: _hash, ...metadata } = settings["metadata"];
|
|
175
|
+
return { ...out, metadata };
|
|
176
|
+
}
|
|
168
177
|
function isNotFound(err) {
|
|
169
178
|
return err instanceof ResponseError && err.response.status === 404;
|
|
170
179
|
}
|
|
@@ -201,6 +210,7 @@ export class SettingsTransport {
|
|
|
201
210
|
this.agents = new AgentsApi(config);
|
|
202
211
|
this.conversations = new ConversationsApi(config);
|
|
203
212
|
this.responses = new ResponsesApi(config);
|
|
213
|
+
this.customApis = new CustomAPIsApi(config);
|
|
204
214
|
}
|
|
205
215
|
// -- agents ---------------------------------------------------------------------------------------------
|
|
206
216
|
async findAgents(sdkName) {
|
|
@@ -229,17 +239,24 @@ export class SettingsTransport {
|
|
|
229
239
|
return this.remote(resource, await this.instructions(agentId));
|
|
230
240
|
}
|
|
231
241
|
async createAgent(agent) {
|
|
232
|
-
var _a, _b;
|
|
242
|
+
var _a, _b, _c;
|
|
233
243
|
const settings = agent.toSettings();
|
|
244
|
+
const webhooks = ((_a = settings["webhooks"]) !== null && _a !== void 0 ? _a : []);
|
|
245
|
+
// The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
|
|
246
|
+
// without them, bind the Custom APIs they name, then write the settings in full.
|
|
247
|
+
const { bind, unbound } = await this.webhookCredentials(webhooks);
|
|
234
248
|
let resource;
|
|
235
249
|
try {
|
|
236
250
|
resource = await this.agents.createAgent({
|
|
237
|
-
agentCreate: {
|
|
251
|
+
agentCreate: {
|
|
252
|
+
name: agent.name, instructions: agent.instructions,
|
|
253
|
+
settings: webhooks.length > 0 ? withoutWebhooks(settings) : settings,
|
|
254
|
+
},
|
|
238
255
|
});
|
|
239
256
|
}
|
|
240
257
|
catch (err) {
|
|
241
258
|
// A 422 stored nothing, so there is no agent to delete.
|
|
242
|
-
throw (
|
|
259
|
+
throw (_b = (await invalidSettings(err))) !== null && _b !== void 0 ? _b : err;
|
|
243
260
|
}
|
|
244
261
|
let envelope;
|
|
245
262
|
let warnings;
|
|
@@ -254,7 +271,23 @@ export class SettingsTransport {
|
|
|
254
271
|
throw new NotSupportedByServerError(["settings"]);
|
|
255
272
|
throw err;
|
|
256
273
|
}
|
|
274
|
+
if (webhooks.length > 0) {
|
|
275
|
+
for (const { path, name, customApiId } of bind)
|
|
276
|
+
await this.bind(resource.id, path, name, customApiId);
|
|
277
|
+
try {
|
|
278
|
+
envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
|
|
279
|
+
}
|
|
280
|
+
catch (err) {
|
|
281
|
+
const invalid = await invalidSettings(err);
|
|
282
|
+
if (invalid === null)
|
|
283
|
+
throw err;
|
|
284
|
+
throw new UserError([invalid.message, ...unbound].join("; "), invalid.issues);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
257
287
|
warnings = checkWarnings(envelope, settings);
|
|
288
|
+
// Accepted unchecked (webhooks switched off): refused once they are on.
|
|
289
|
+
for (const sentence of unbound)
|
|
290
|
+
console.warn(`agent ${resource.id}: ${sentence}`);
|
|
258
291
|
checkMetadata(envelope, agent);
|
|
259
292
|
await this.agents.deployAgent({ agentId: resource.id });
|
|
260
293
|
}
|
|
@@ -272,10 +305,67 @@ export class SettingsTransport {
|
|
|
272
305
|
agentId: resource.id,
|
|
273
306
|
name: agent.name,
|
|
274
307
|
instructions: agent.instructions,
|
|
275
|
-
settings: { ...((
|
|
308
|
+
settings: { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) },
|
|
276
309
|
warnings,
|
|
277
310
|
};
|
|
278
311
|
}
|
|
312
|
+
/** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
|
|
313
|
+
* one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
|
|
314
|
+
* checks credentials). */
|
|
315
|
+
async webhookCredentials(webhooks) {
|
|
316
|
+
const bind = [];
|
|
317
|
+
const unbound = [];
|
|
318
|
+
const seen = new Set();
|
|
319
|
+
for (const [i, hook] of webhooks.entries()) {
|
|
320
|
+
const name = hook.secret_credential;
|
|
321
|
+
if (seen.has(name))
|
|
322
|
+
continue;
|
|
323
|
+
seen.add(name);
|
|
324
|
+
const path = `webhooks.${i}.secret_credential`;
|
|
325
|
+
const ids = await this.customApiIds(name);
|
|
326
|
+
if (ids.length === 1) {
|
|
327
|
+
bind.push({ path, name, customApiId: ids[0] });
|
|
328
|
+
}
|
|
329
|
+
else if (ids.length === 0) {
|
|
330
|
+
unbound.push(`${path}: you have no Custom API named '${name}' to bind to the new agent; create it, then ` +
|
|
331
|
+
"deploy again");
|
|
332
|
+
}
|
|
333
|
+
else {
|
|
334
|
+
unbound.push(`${path}: ${ids.length} of your Custom APIs are named '${name}', so none was bound to the new ` +
|
|
335
|
+
"agent; rename or delete all but one, then deploy again");
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return { bind, unbound };
|
|
339
|
+
}
|
|
340
|
+
/** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
|
|
341
|
+
async customApiIds(name) {
|
|
342
|
+
const ids = [];
|
|
343
|
+
let offset = 0;
|
|
344
|
+
for (;;) {
|
|
345
|
+
const result = await this.customApis.listCustomApis({ q: name, limit: PAGE, offset });
|
|
346
|
+
const items = result.data;
|
|
347
|
+
for (const item of items)
|
|
348
|
+
if (item.name === name)
|
|
349
|
+
ids.push(item.id);
|
|
350
|
+
offset += items.length;
|
|
351
|
+
if (items.length === 0 || !result.hasMore)
|
|
352
|
+
return ids;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
async bind(agentId, path, name, customApiId) {
|
|
356
|
+
var _a;
|
|
357
|
+
try {
|
|
358
|
+
await this.customApis.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
|
|
359
|
+
}
|
|
360
|
+
catch (err) {
|
|
361
|
+
const status = err instanceof ResponseError ? err.response.status : 0;
|
|
362
|
+
if (!(err instanceof ResponseError) || status < 400 || status >= 500)
|
|
363
|
+
throw err;
|
|
364
|
+
const message = (_a = (await chatError(err))) === null || _a === void 0 ? void 0 : _a["message"];
|
|
365
|
+
throw new UserError(`${path}: could not bind the Custom API '${name}' to the new agent: ` +
|
|
366
|
+
(typeof message === "string" && message ? message : `HTTP ${status}`));
|
|
367
|
+
}
|
|
368
|
+
}
|
|
279
369
|
async updateAgent(agentId, agent) {
|
|
280
370
|
var _a, _b;
|
|
281
371
|
const settings = agent.toSettings();
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { WebhookEventType } from "../webhooks.js";
|
|
2
|
+
/** Where the agent reports a finished, failed or paused turn (agent.json `webhooks[]`). */
|
|
3
|
+
export interface Webhook {
|
|
4
|
+
/** An `https://` URL on port 443 with a DNS host; a query string is allowed. */
|
|
5
|
+
url: string;
|
|
6
|
+
/** 1 to 4 distinct events. `approval.requested` is reserved: accepted, not sent yet. */
|
|
7
|
+
events: WebhookEventType[];
|
|
8
|
+
/** The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). */
|
|
9
|
+
secretCredential: string;
|
|
10
|
+
}
|
|
11
|
+
export declare const WEBHOOKS_MAX = 5;
|
|
12
|
+
/** Why `url` is not an allowed webhook URL, or null. Every URL the server refuses is refused, with the server's
|
|
13
|
+
* sentence for every URL Python's `urlsplit` parses; for a netloc its NFKC check refuses, the sentence may differ. */
|
|
14
|
+
export declare function urlProblem(url: string): string | null;
|
|
15
|
+
/** The server's pure `webhooks` rules (types first); throws `UserError` naming the agent.json path. */
|
|
16
|
+
export declare function checkWebhooks(webhooks: unknown): void;
|
|
17
|
+
/** Only the three fields, in agent.json's names (a copy). */
|
|
18
|
+
export declare function copyWebhooks(webhooks: readonly Webhook[]): Webhook[];
|
|
19
|
+
export declare function webhooksJson(webhooks: readonly Webhook[]): Record<string, unknown>[];
|
|
@@ -0,0 +1,177 @@
|
|
|
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
|
+
export const WEBHOOKS_MAX = 5;
|
|
13
|
+
const WEBHOOK_URL_MAX = 2048;
|
|
14
|
+
const SECRET_CREDENTIAL_MAX = 256;
|
|
15
|
+
const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
16
|
+
// A last label that is a number (decimal, or 0x hex) makes resolvers read the whole host as an IPv4 address.
|
|
17
|
+
const NUMERIC_LABEL = /^(?:[0-9]+|0x[0-9a-f]*)$/;
|
|
18
|
+
const SCHEME = /^[A-Za-z][A-Za-z0-9+\-.]*$/;
|
|
19
|
+
/** Length in code points, as Python's `len`. */
|
|
20
|
+
function codePoints(text) {
|
|
21
|
+
return Array.from(text).length;
|
|
22
|
+
}
|
|
23
|
+
/** `[scheme, netloc, path, query]` as Python 3.12's `urlsplit` splits a URL without a fragment. */
|
|
24
|
+
function split(url) {
|
|
25
|
+
let rest = url;
|
|
26
|
+
let scheme = "";
|
|
27
|
+
const i = rest.indexOf(":");
|
|
28
|
+
if (i > 0 && SCHEME.test(rest.slice(0, i))) {
|
|
29
|
+
scheme = rest.slice(0, i).toLowerCase();
|
|
30
|
+
rest = rest.slice(i + 1);
|
|
31
|
+
}
|
|
32
|
+
let netloc = "";
|
|
33
|
+
if (rest.slice(0, 2) === "//") {
|
|
34
|
+
let end = rest.length;
|
|
35
|
+
for (const c of "/?#") {
|
|
36
|
+
const at = rest.indexOf(c, 2);
|
|
37
|
+
if (at >= 0)
|
|
38
|
+
end = Math.min(end, at);
|
|
39
|
+
}
|
|
40
|
+
netloc = rest.slice(2, end);
|
|
41
|
+
rest = rest.slice(end);
|
|
42
|
+
}
|
|
43
|
+
let query = "";
|
|
44
|
+
const q = rest.indexOf("?");
|
|
45
|
+
if (q >= 0) {
|
|
46
|
+
query = rest.slice(q + 1);
|
|
47
|
+
rest = rest.slice(0, q);
|
|
48
|
+
}
|
|
49
|
+
return [scheme, netloc, rest, query];
|
|
50
|
+
}
|
|
51
|
+
/** Python's `str.partition`. */
|
|
52
|
+
function partition(text, sep) {
|
|
53
|
+
const at = text.indexOf(sep);
|
|
54
|
+
return at < 0 ? [text, "", ""] : [text.slice(0, at), sep, text.slice(at + sep.length)];
|
|
55
|
+
}
|
|
56
|
+
/** `urlsplit`'s host (lowercased) and raw port (`null` when absent or empty). */
|
|
57
|
+
function hostPort(netloc) {
|
|
58
|
+
const hostinfo = netloc.slice(netloc.lastIndexOf("@") + 1);
|
|
59
|
+
const [, bracket, bracketed] = partition(hostinfo, "[");
|
|
60
|
+
let host;
|
|
61
|
+
let port;
|
|
62
|
+
if (bracket) {
|
|
63
|
+
const [inner, , after] = partition(bracketed, "]");
|
|
64
|
+
host = inner;
|
|
65
|
+
port = partition(after, ":")[2];
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
[host, , port] = partition(hostinfo, ":");
|
|
69
|
+
}
|
|
70
|
+
return [host.toLowerCase(), port || null];
|
|
71
|
+
}
|
|
72
|
+
function stripTrailingDots(host) {
|
|
73
|
+
return host.replace(/\.+$/, "");
|
|
74
|
+
}
|
|
75
|
+
/** Why `url` is not an allowed webhook URL, or null. Every URL the server refuses is refused, with the server's
|
|
76
|
+
* sentence for every URL Python's `urlsplit` parses; for a netloc its NFKC check refuses, the sentence may differ. */
|
|
77
|
+
export function urlProblem(url) {
|
|
78
|
+
if (codePoints(url) > WEBHOOK_URL_MAX)
|
|
79
|
+
return `url must be at most ${WEBHOOK_URL_MAX} characters.`;
|
|
80
|
+
for (let i = 0; i < url.length; i++) {
|
|
81
|
+
const code = url.charCodeAt(i);
|
|
82
|
+
if (code <= 0x20 || code === 0x7f)
|
|
83
|
+
return "url must not contain spaces or control characters.";
|
|
84
|
+
}
|
|
85
|
+
if (url.indexOf("#") !== -1)
|
|
86
|
+
return "url must not have a fragment.";
|
|
87
|
+
const [scheme, netloc, path] = split(url);
|
|
88
|
+
if (scheme !== "https")
|
|
89
|
+
return "url must start with https://.";
|
|
90
|
+
if (netloc.indexOf("@") !== -1)
|
|
91
|
+
return "url must not contain a user name or password.";
|
|
92
|
+
// urlsplit refuses unbalanced brackets outright
|
|
93
|
+
if ((netloc.indexOf("[") !== -1) !== (netloc.indexOf("]") !== -1)) {
|
|
94
|
+
return "url host must be a DNS name, not an IP address.";
|
|
95
|
+
}
|
|
96
|
+
const [rawHost, port] = hostPort(netloc);
|
|
97
|
+
if (port !== null) {
|
|
98
|
+
if (!/^[0-9]+$/.test(port) || Number(port) > 65535) {
|
|
99
|
+
return "url has an invalid port; leave the port out (443 is used).";
|
|
100
|
+
}
|
|
101
|
+
if (Number(port) !== 443)
|
|
102
|
+
return "url must use port 443; leave the port out.";
|
|
103
|
+
}
|
|
104
|
+
const host = stripTrailingDots(rawHost);
|
|
105
|
+
if (!host)
|
|
106
|
+
return "url must name a host, like https://hooks.example.com/panja.";
|
|
107
|
+
if (netloc.indexOf("[") !== -1)
|
|
108
|
+
return "url host must be a DNS name, not an IP address.";
|
|
109
|
+
const labels = host.split(".");
|
|
110
|
+
if (!labels.every((label) => LABEL.test(label)))
|
|
111
|
+
return "url host must be a DNS name, like hooks.example.com.";
|
|
112
|
+
if (NUMERIC_LABEL.test(labels[labels.length - 1]))
|
|
113
|
+
return "url host must be a DNS name, not an IP address.";
|
|
114
|
+
if (path.split("/").some((seg) => seg === "." || seg === ".."))
|
|
115
|
+
return "url path must not contain . or .. segments.";
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
/** Host (lowercased, no trailing dot, no port), path and query: two URLs with one key are one endpoint. */
|
|
119
|
+
function urlKey(url) {
|
|
120
|
+
const [, netloc, path, query] = split(url);
|
|
121
|
+
return `${stripTrailingDots(hostPort(netloc)[0])}${path}?${query}`;
|
|
122
|
+
}
|
|
123
|
+
/** The server's pure `webhooks` rules (types first); throws `UserError` naming the agent.json path. */
|
|
124
|
+
export function checkWebhooks(webhooks) {
|
|
125
|
+
if (!Array.isArray(webhooks))
|
|
126
|
+
throw new UserError("webhooks: must be a list of webhooks");
|
|
127
|
+
if (webhooks.length > WEBHOOKS_MAX) {
|
|
128
|
+
throw new UserError(`webhooks: webhooks may hold at most ${WEBHOOKS_MAX} endpoints.`);
|
|
129
|
+
}
|
|
130
|
+
const seen = new Set();
|
|
131
|
+
webhooks.forEach((hook, i) => {
|
|
132
|
+
const where = `webhooks.${i}.`;
|
|
133
|
+
if (typeof hook !== "object" || hook === null || Array.isArray(hook)) {
|
|
134
|
+
throw new UserError(`webhooks.${i}: must be an object with url, events and secretCredential`);
|
|
135
|
+
}
|
|
136
|
+
const { url, events, secretCredential } = hook;
|
|
137
|
+
if (typeof url !== "string")
|
|
138
|
+
throw new UserError(where + "url: must be a string");
|
|
139
|
+
if (!Array.isArray(events) || !events.every((e) => typeof e === "string")) {
|
|
140
|
+
throw new UserError(where + "events: must be a list of event names");
|
|
141
|
+
}
|
|
142
|
+
if (typeof secretCredential !== "string")
|
|
143
|
+
throw new UserError(where + "secretCredential: must be a string");
|
|
144
|
+
// Python's Webhook is extra="forbid": a key dropped silently (a misplaced secret) would never verify.
|
|
145
|
+
const extra = Object.keys(hook).find((k) => k !== "url" && k !== "events" && k !== "secretCredential");
|
|
146
|
+
if (extra !== undefined)
|
|
147
|
+
throw new UserError(where + extra + ": Extra inputs are not permitted");
|
|
148
|
+
const problem = urlProblem(url);
|
|
149
|
+
if (problem !== null)
|
|
150
|
+
throw new UserError(where + "url: " + problem);
|
|
151
|
+
if (events.length < 1 || events.length > WEBHOOK_EVENTS.length) {
|
|
152
|
+
throw new UserError(where + `events: events must list 1 to ${WEBHOOK_EVENTS.length} events.`);
|
|
153
|
+
}
|
|
154
|
+
if (events.some((e) => WEBHOOK_EVENTS.indexOf(e) === -1)) {
|
|
155
|
+
throw new UserError(where + `events: events must be from: ${WEBHOOK_EVENTS.join(", ")}.`);
|
|
156
|
+
}
|
|
157
|
+
if (new Set(events).size !== events.length)
|
|
158
|
+
throw new UserError(where + "events: events must not repeat an event.");
|
|
159
|
+
const n = codePoints(secretCredential);
|
|
160
|
+
if (n < 1 || n > SECRET_CREDENTIAL_MAX) {
|
|
161
|
+
throw new UserError(where + "secret_credential: secret_credential must be the name of a vault credential " +
|
|
162
|
+
`(1 to ${SECRET_CREDENTIAL_MAX} characters).`);
|
|
163
|
+
}
|
|
164
|
+
const key = urlKey(url);
|
|
165
|
+
if (seen.has(key)) {
|
|
166
|
+
throw new UserError(where + "url: webhooks must not list the same url twice; put all its events on one entry.");
|
|
167
|
+
}
|
|
168
|
+
seen.add(key);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
/** Only the three fields, in agent.json's names (a copy). */
|
|
172
|
+
export function copyWebhooks(webhooks) {
|
|
173
|
+
return webhooks.map((h) => ({ url: h.url, events: [...h.events], secretCredential: h.secretCredential }));
|
|
174
|
+
}
|
|
175
|
+
export function webhooksJson(webhooks) {
|
|
176
|
+
return webhooks.map((h) => ({ url: h.url, events: [...h.events], secret_credential: h.secretCredential }));
|
|
177
|
+
}
|
|
@@ -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 {};
|