@pidgeon-ai/sdk 1.68.0 → 2.0.0

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/dist/index.js CHANGED
@@ -1,2060 +1,295 @@
1
- // src/generated/core/bodySerializer.gen.ts
2
- var serializeFormDataPair = (data, key, value) => {
3
- if (typeof value === "string" || value instanceof Blob) {
4
- data.append(key, value);
5
- } else if (value instanceof Date) {
6
- data.append(key, value.toISOString());
7
- } else {
8
- data.append(key, JSON.stringify(value));
9
- }
10
- };
11
- var formDataBodySerializer = {
12
- bodySerializer: (body) => {
13
- const data = new FormData();
14
- Object.entries(body).forEach(([key, value]) => {
15
- if (value === void 0 || value === null) {
16
- return;
17
- }
18
- if (Array.isArray(value)) {
19
- value.forEach((v) => serializeFormDataPair(data, key, v));
20
- } else {
21
- serializeFormDataPair(data, key, value);
22
- }
23
- });
24
- return data;
25
- }
26
- };
27
- var jsonBodySerializer = {
28
- bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
29
- };
30
-
31
- // src/generated/core/serverSentEvents.gen.ts
32
- function createSseClient({
33
- onRequest,
34
- onSseError,
35
- onSseEvent,
36
- responseTransformer,
37
- responseValidator,
38
- sseDefaultRetryDelay,
39
- sseMaxRetryAttempts,
40
- sseMaxRetryDelay,
41
- sseSleepFn,
42
- url,
43
- ...options
44
- }) {
45
- let lastEventId;
46
- const sleep2 = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
47
- const createStream = async function* () {
48
- let retryDelay = sseDefaultRetryDelay ?? 3e3;
49
- let attempt = 0;
50
- const signal = options.signal ?? new AbortController().signal;
51
- while (true) {
52
- if (signal.aborted) break;
53
- attempt++;
54
- const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
55
- if (lastEventId !== void 0) {
56
- headers.set("Last-Event-ID", lastEventId);
57
- }
58
- try {
59
- const requestInit = {
60
- redirect: "follow",
61
- ...options,
62
- body: options.serializedBody,
63
- headers,
64
- signal
65
- };
66
- let request = new Request(url, requestInit);
67
- if (onRequest) {
68
- request = await onRequest(url, requestInit);
69
- }
70
- const _fetch = options.fetch ?? globalThis.fetch;
71
- const response = await _fetch(request);
72
- if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
73
- if (!response.body) throw new Error("No body in SSE response");
74
- const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
75
- let buffer = "";
76
- const abortHandler = () => {
77
- try {
78
- reader.cancel();
79
- } catch {
80
- }
81
- };
82
- signal.addEventListener("abort", abortHandler);
83
- try {
84
- while (true) {
85
- const { done, value } = await reader.read();
86
- if (done) break;
87
- buffer += value;
88
- buffer = buffer.replace(/\r\n?/g, "\n");
89
- const chunks = buffer.split("\n\n");
90
- buffer = chunks.pop() ?? "";
91
- for (const chunk of chunks) {
92
- const lines = chunk.split("\n");
93
- const dataLines = [];
94
- let eventName;
95
- for (const line of lines) {
96
- if (line.startsWith("data:")) {
97
- dataLines.push(line.replace(/^data:\s*/, ""));
98
- } else if (line.startsWith("event:")) {
99
- eventName = line.replace(/^event:\s*/, "");
100
- } else if (line.startsWith("id:")) {
101
- lastEventId = line.replace(/^id:\s*/, "");
102
- } else if (line.startsWith("retry:")) {
103
- const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
104
- if (!Number.isNaN(parsed)) {
105
- retryDelay = parsed;
106
- }
107
- }
108
- }
109
- let data;
110
- let parsedJson = false;
111
- if (dataLines.length) {
112
- const rawData = dataLines.join("\n");
113
- try {
114
- data = JSON.parse(rawData);
115
- parsedJson = true;
116
- } catch {
117
- data = rawData;
118
- }
119
- }
120
- if (parsedJson) {
121
- if (responseValidator) {
122
- await responseValidator(data);
123
- }
124
- if (responseTransformer) {
125
- data = await responseTransformer(data);
126
- }
127
- }
128
- onSseEvent?.({
129
- data,
130
- event: eventName,
131
- id: lastEventId,
132
- retry: retryDelay
133
- });
134
- if (dataLines.length) {
135
- yield data;
136
- }
137
- }
138
- }
139
- } finally {
140
- signal.removeEventListener("abort", abortHandler);
141
- reader.releaseLock();
142
- }
143
- break;
144
- } catch (error) {
145
- onSseError?.(error);
146
- if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
147
- break;
148
- }
149
- const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
150
- await sleep2(backoff);
151
- }
1
+ /**
2
+ * Pidgeon's TypeScript SDK (docs/plan.md §11).
3
+ *
4
+ * For an agent: `signedFetch`, or `agentFromEnv().fetch`, signs every request
5
+ * with the agent's key, so a website that checks can tell who stands behind it.
6
+ *
7
+ * For a website: `new Pidgeon({ apiKey }).verify(request)` asks Pidgeon who
8
+ * stands behind an agent's request and how they stand; `.report()` reports
9
+ * one that misbehaved.
10
+ *
11
+ * For an operator's tooling and coding agents: `.agents.setUp()` registers an
12
+ * agent, makes its key here and publishes the public half; `.inboxes`,
13
+ * `.messages` and `.drafts` are Email; `.sites` and `.mandates` are Auth.
14
+ *
15
+ * `generateAgentKey()` and `.publishKey()` make a
16
+ * key where the agent runs and publish its public half.
17
+ */
18
+ import { generateAgentKey, signAgentRequest, } from "./credential.js";
19
+ export * from "./credential.js";
20
+ export const DEFAULT_BASE_URL = 'https://pidgeon.ai';
21
+ export class PidgeonError extends Error {
22
+ status;
23
+ code;
24
+ constructor(status, code, message) {
25
+ super(message);
26
+ this.status = status;
27
+ this.code = code;
28
+ this.name = 'PidgeonError';
152
29
  }
153
- };
154
- const stream = createStream();
155
- return { stream };
156
30
  }
157
-
158
- // src/generated/core/pathSerializer.gen.ts
159
- var separatorArrayExplode = (style) => {
160
- switch (style) {
161
- case "label":
162
- return ".";
163
- case "matrix":
164
- return ";";
165
- case "simple":
166
- return ",";
167
- default:
168
- return "&";
169
- }
170
- };
171
- var separatorArrayNoExplode = (style) => {
172
- switch (style) {
173
- case "form":
174
- return ",";
175
- case "pipeDelimited":
176
- return "|";
177
- case "spaceDelimited":
178
- return "%20";
179
- default:
180
- return ",";
181
- }
182
- };
183
- var separatorObjectExplode = (style) => {
184
- switch (style) {
185
- case "label":
186
- return ".";
187
- case "matrix":
188
- return ";";
189
- case "simple":
190
- return ",";
191
- default:
192
- return "&";
193
- }
194
- };
195
- var serializeArrayParam = ({
196
- allowReserved,
197
- explode,
198
- name,
199
- style,
200
- value
201
- }) => {
202
- if (!explode) {
203
- const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
204
- switch (style) {
205
- case "label":
206
- return `.${joinedValues2}`;
207
- case "matrix":
208
- return `;${name}=${joinedValues2}`;
209
- case "simple":
210
- return joinedValues2;
211
- default:
212
- return `${name}=${joinedValues2}`;
213
- }
214
- }
215
- const separator = separatorArrayExplode(style);
216
- const joinedValues = value.map((v) => {
217
- if (style === "label" || style === "simple") {
218
- return allowReserved ? v : encodeURIComponent(v);
31
+ function headersOf(input) {
32
+ const raw = input.headers;
33
+ const out = {};
34
+ if (raw instanceof Headers) {
35
+ raw.forEach((value, name) => (out[name] = value));
36
+ return out;
219
37
  }
220
- return serializePrimitiveParam({
221
- allowReserved,
222
- name,
223
- value: v
224
- });
225
- }).join(separator);
226
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
227
- };
228
- var serializePrimitiveParam = ({
229
- allowReserved,
230
- name,
231
- value
232
- }) => {
233
- if (value === void 0 || value === null) {
234
- return "";
235
- }
236
- if (typeof value === "object") {
237
- throw new Error(
238
- "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
239
- );
240
- }
241
- return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
242
- };
243
- var serializeObjectParam = ({
244
- allowReserved,
245
- explode,
246
- name,
247
- style,
248
- value,
249
- valueOnly
250
- }) => {
251
- if (value instanceof Date) {
252
- return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
253
- }
254
- if (style !== "deepObject" && !explode) {
255
- let values = [];
256
- Object.entries(value).forEach(([key, v]) => {
257
- values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
258
- });
259
- const joinedValues2 = values.join(",");
260
- switch (style) {
261
- case "form":
262
- return `${name}=${joinedValues2}`;
263
- case "label":
264
- return `.${joinedValues2}`;
265
- case "matrix":
266
- return `;${name}=${joinedValues2}`;
267
- default:
268
- return joinedValues2;
38
+ for (const [name, value] of Object.entries(raw)) {
39
+ if (value !== undefined)
40
+ out[name.toLowerCase()] = Array.isArray(value) ? value.join(', ') : value;
269
41
  }
270
- }
271
- const separator = separatorObjectExplode(style);
272
- const joinedValues = Object.entries(value).map(
273
- ([key, v]) => serializePrimitiveParam({
274
- allowReserved,
275
- name: style === "deepObject" ? `${name}[${key}]` : key,
276
- value: v
277
- })
278
- ).join(separator);
279
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
280
- };
281
-
282
- // src/generated/core/utils.gen.ts
283
- var PATH_PARAM_RE = /\{[^{}]+\}/g;
284
- var defaultPathSerializer = ({ path, url: _url }) => {
285
- let url = _url;
286
- const matches = _url.match(PATH_PARAM_RE);
287
- if (matches) {
288
- for (const match of matches) {
289
- let explode = false;
290
- let name = match.substring(1, match.length - 1);
291
- let style = "simple";
292
- if (name.endsWith("*")) {
293
- explode = true;
294
- name = name.substring(0, name.length - 1);
295
- }
296
- if (name.startsWith(".")) {
297
- name = name.substring(1);
298
- style = "label";
299
- } else if (name.startsWith(";")) {
300
- name = name.substring(1);
301
- style = "matrix";
302
- }
303
- const value = path[name];
304
- if (value === void 0 || value === null) {
305
- continue;
306
- }
307
- if (Array.isArray(value)) {
308
- url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
309
- continue;
310
- }
311
- if (typeof value === "object") {
312
- url = url.replace(
313
- match,
314
- serializeObjectParam({
315
- explode,
316
- name,
317
- style,
318
- value,
319
- valueOnly: true
320
- })
321
- );
322
- continue;
323
- }
324
- if (style === "matrix") {
325
- url = url.replace(
326
- match,
327
- `;${serializePrimitiveParam({
328
- name,
329
- value
330
- })}`
331
- );
332
- continue;
333
- }
334
- const replaceValue = encodeURIComponent(
335
- style === "label" ? `.${value}` : value
336
- );
337
- url = url.replace(match, replaceValue);
338
- }
339
- }
340
- return url;
341
- };
342
- var getUrl = ({
343
- baseUrl,
344
- path,
345
- query,
346
- querySerializer,
347
- url: _url
348
- }) => {
349
- const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
350
- let url = (baseUrl ?? "") + pathUrl;
351
- if (path) {
352
- url = defaultPathSerializer({ path, url });
353
- }
354
- let search = query ? querySerializer(query) : "";
355
- if (search.startsWith("?")) {
356
- search = search.substring(1);
357
- }
358
- if (search) {
359
- url += `?${search}`;
360
- }
361
- return url;
362
- };
363
- function getValidRequestBody(options) {
364
- const hasBody = options.body !== void 0;
365
- const isSerializedBody = hasBody && options.bodySerializer;
366
- if (isSerializedBody) {
367
- if ("serializedBody" in options) {
368
- const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
369
- return hasSerializedBody ? options.serializedBody : null;
370
- }
371
- return options.body !== "" ? options.body : null;
372
- }
373
- if (hasBody) {
374
- return options.body;
375
- }
376
- return void 0;
42
+ return out;
377
43
  }
378
-
379
- // src/generated/core/auth.gen.ts
380
- var getAuthToken = async (auth, callback) => {
381
- const token = typeof callback === "function" ? await callback(auth) : callback;
382
- if (!token) {
383
- return;
384
- }
385
- if (auth.scheme === "bearer") {
386
- return `Bearer ${token}`;
387
- }
388
- if (auth.scheme === "basic") {
389
- return `Basic ${btoa(token)}`;
390
- }
391
- return token;
392
- };
393
-
394
- // src/generated/client/utils.gen.ts
395
- var createQuerySerializer = ({
396
- parameters = {},
397
- ...args
398
- } = {}) => {
399
- const querySerializer = (queryParams) => {
400
- const search = [];
401
- if (queryParams && typeof queryParams === "object") {
402
- for (const name in queryParams) {
403
- const value = queryParams[name];
404
- if (value === void 0 || value === null) {
405
- continue;
406
- }
407
- const options = parameters[name] || args;
408
- if (Array.isArray(value)) {
409
- const serializedArray = serializeArrayParam({
410
- allowReserved: options.allowReserved,
411
- explode: true,
412
- name,
413
- style: "form",
414
- value,
415
- ...options.array
416
- });
417
- if (serializedArray) search.push(serializedArray);
418
- } else if (typeof value === "object") {
419
- const serializedObject = serializeObjectParam({
420
- allowReserved: options.allowReserved,
421
- explode: true,
422
- name,
423
- style: "deepObject",
424
- value,
425
- ...options.object
426
- });
427
- if (serializedObject) search.push(serializedObject);
428
- } else {
429
- const serializedPrimitive = serializePrimitiveParam({
430
- allowReserved: options.allowReserved,
431
- name,
432
- value
433
- });
434
- if (serializedPrimitive) search.push(serializedPrimitive);
435
- }
436
- }
437
- }
438
- return search.join("&");
439
- };
440
- return querySerializer;
441
- };
442
- var getParseAs = (contentType) => {
443
- if (!contentType) {
444
- return "stream";
445
- }
446
- const cleanContent = contentType.split(";")[0]?.trim();
447
- if (!cleanContent) {
448
- return;
449
- }
450
- if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
451
- return "json";
452
- }
453
- if (cleanContent === "multipart/form-data") {
454
- return "formData";
455
- }
456
- if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
457
- return "blob";
458
- }
459
- if (cleanContent.startsWith("text/")) {
460
- return "text";
461
- }
462
- return;
463
- };
464
- var checkForExistence = (options, name) => {
465
- if (!name) {
466
- return false;
467
- }
468
- if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
469
- return true;
470
- }
471
- return false;
472
- };
473
- async function setAuthParams(options) {
474
- for (const auth of options.security ?? []) {
475
- if (checkForExistence(options, auth.name)) {
476
- continue;
477
- }
478
- const token = await getAuthToken(auth, options.auth);
479
- if (!token) {
480
- continue;
44
+ const messageBody = (input) => ({
45
+ to: input.to,
46
+ cc: input.cc,
47
+ bcc: input.bcc,
48
+ subject: input.subject,
49
+ text: input.text,
50
+ html: input.html,
51
+ reply_to: input.replyTo,
52
+ });
53
+ const segment = (id) => encodeURIComponent(id);
54
+ /**
55
+ * The client for Pidgeon's API: the website's, the operator's, and a coding
56
+ * agent's. Keep the API key on a server. `apiKey` is an API key (`pgn_…`) or
57
+ * an OAuth access token (`pgn_oat_…`); `getToken` is asked before each
58
+ * request instead, for a token that is refreshed.
59
+ */
60
+ export class Pidgeon {
61
+ token;
62
+ baseUrl;
63
+ fetchImpl;
64
+ constructor(options) {
65
+ const { apiKey, getToken } = options;
66
+ if (getToken)
67
+ this.token = getToken;
68
+ else if (apiKey)
69
+ this.token = async () => apiKey;
70
+ else
71
+ throw new Error('Pidgeon needs an API key (Settings → API keys).');
72
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, '');
73
+ this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
481
74
  }
482
- const name = auth.name ?? "Authorization";
483
- switch (auth.in) {
484
- case "query":
485
- if (!options.query) {
486
- options.query = {};
75
+ /** Any `/v1` call: the methods below are this with the path and body filled in. */
76
+ async request(method, path, options = {}) {
77
+ const url = new URL(`${this.baseUrl}${path}`);
78
+ for (const [name, value] of Object.entries(options.query ?? {})) {
79
+ if (value !== undefined)
80
+ url.searchParams.set(name, String(value));
487
81
  }
488
- options.query[name] = token;
489
- break;
490
- case "cookie":
491
- options.headers.append("Cookie", `${name}=${token}`);
492
- break;
493
- case "header":
494
- default:
495
- options.headers.set(name, token);
496
- break;
497
- }
498
- }
499
- }
500
- var buildUrl = (options) => getUrl({
501
- baseUrl: options.baseUrl,
502
- path: options.path,
503
- query: options.query,
504
- querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
505
- url: options.url
506
- });
507
- var mergeConfigs = (a, b) => {
508
- const config = { ...a, ...b };
509
- if (config.baseUrl?.endsWith("/")) {
510
- config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
511
- }
512
- config.headers = mergeHeaders(a.headers, b.headers);
513
- return config;
514
- };
515
- var headersEntries = (headers) => {
516
- const entries = [];
517
- headers.forEach((value, key) => {
518
- entries.push([key, value]);
519
- });
520
- return entries;
521
- };
522
- var mergeHeaders = (...headers) => {
523
- const mergedHeaders = new Headers();
524
- for (const header of headers) {
525
- if (!header) {
526
- continue;
527
- }
528
- const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
529
- for (const [key, value] of iterator) {
530
- if (value === null) {
531
- mergedHeaders.delete(key);
532
- } else if (Array.isArray(value)) {
533
- for (const v of value) {
534
- mergedHeaders.append(key, v);
82
+ const response = await this.fetchImpl(url, {
83
+ method,
84
+ headers: {
85
+ authorization: `Bearer ${await this.token()}`,
86
+ ...(options.body === undefined ? {} : { 'content-type': 'application/json' }),
87
+ ...options.headers,
88
+ },
89
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
90
+ });
91
+ if (response.status === 204)
92
+ return undefined;
93
+ const data = (await response.json().catch(() => null));
94
+ if (!response.ok) {
95
+ throw new PidgeonError(response.status, data?.error?.code ?? 'error', data?.error?.message ?? `Pidgeon answered ${response.status}.`);
535
96
  }
536
- } else if (value !== void 0) {
537
- mergedHeaders.set(
538
- key,
539
- typeof value === "object" ? JSON.stringify(value) : value
540
- );
541
- }
97
+ return data;
542
98
  }
543
- }
544
- return mergedHeaders;
545
- };
546
- var Interceptors = class {
547
- fns = [];
548
- clear() {
549
- this.fns = [];
550
- }
551
- eject(id) {
552
- const index = this.getInterceptorIndex(id);
553
- if (this.fns[index]) {
554
- this.fns[index] = null;
99
+ // ---------------------------------------------------------------- Bouncer
100
+ /** Who stands behind an agent's request, and how they stand. Forward it as you received it. */
101
+ verify(request) {
102
+ return this.request('POST', '/v1/verify', {
103
+ body: { request: { method: request.method, url: request.url, headers: headersOf(request) } },
104
+ });
555
105
  }
556
- }
557
- exists(id) {
558
- const index = this.getInterceptorIndex(id);
559
- return Boolean(this.fns[index]);
560
- }
561
- getInterceptorIndex(id) {
562
- if (typeof id === "number") {
563
- return this.fns[id] ? id : -1;
106
+ /** Report an agent from one of your verifications: what it did, in your words. */
107
+ report(input) {
108
+ return this.request('POST', '/v1/reports', {
109
+ body: {
110
+ verification_id: input.verificationId,
111
+ category: input.category,
112
+ evidence: input.evidence,
113
+ },
114
+ });
564
115
  }
565
- return this.fns.indexOf(id);
566
- }
567
- update(id, fn) {
568
- const index = this.getInterceptorIndex(id);
569
- if (this.fns[index]) {
570
- this.fns[index] = fn;
571
- return id;
116
+ // --------------------------------------------------------------- Passport
117
+ /**
118
+ * Publish an agent's public key. The request is signed with the key itself,
119
+ * which is how Pidgeon knows you hold it; the private half never leaves you.
120
+ */
121
+ async publishKey(input) {
122
+ const path = `/v1/agents/${segment(input.agentId)}/keys`;
123
+ const signature = await signAgentRequest(new Request(`${this.baseUrl}${path}`, { method: 'POST' }), { privateJwk: input.key.privateJwk, directory: input.directory });
124
+ return this.request('POST', path, {
125
+ body: { public_jwk: input.key.publicJwk },
126
+ headers: signature,
127
+ });
572
128
  }
573
- return false;
574
- }
575
- use(fn) {
576
- this.fns.push(fn);
577
- return this.fns.length - 1;
578
- }
579
- };
580
- var createInterceptors = () => ({
581
- error: new Interceptors(),
582
- request: new Interceptors(),
583
- response: new Interceptors()
584
- });
585
- var defaultQuerySerializer = createQuerySerializer({
586
- allowReserved: false,
587
- array: {
588
- explode: true,
589
- style: "form"
590
- },
591
- object: {
592
- explode: true,
593
- style: "deepObject"
594
- }
595
- });
596
- var defaultHeaders = {
597
- "Content-Type": "application/json"
598
- };
599
- var createConfig = (override = {}) => ({
600
- ...jsonBodySerializer,
601
- headers: defaultHeaders,
602
- parseAs: "auto",
603
- querySerializer: defaultQuerySerializer,
604
- ...override
605
- });
606
-
607
- // src/generated/client/client.gen.ts
608
- var createClient = (config = {}) => {
609
- let _config = mergeConfigs(createConfig(), config);
610
- const getConfig = () => ({ ..._config });
611
- const setConfig = (config2) => {
612
- _config = mergeConfigs(_config, config2);
613
- return getConfig();
614
- };
615
- const interceptors = createInterceptors();
616
- const beforeRequest = async (options) => {
617
- const opts = {
618
- ..._config,
619
- ...options,
620
- fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
621
- headers: mergeHeaders(_config.headers, options.headers),
622
- serializedBody: void 0
129
+ agents = {
130
+ list: (options = {}) => this.request('GET', '/v1/agents', { query: options }),
131
+ /** Register an agent. It has no key until you make one where it runs and publish it. */
132
+ create: (input) => this.request('POST', '/v1/agents', {
133
+ body: { name: input.name, purpose: input.purpose ?? '', pod_id: input.podId },
134
+ }),
135
+ /** The agent, its keys, its directory and its operator's reputation. */
136
+ get: (id) => this.request('GET', `/v1/agents/${segment(id)}`),
137
+ /**
138
+ * Register an agent, make its key here, and publish the public half
139
+ * signed with it. Keep `key.privateJwk` where the agent runs: it is the
140
+ * agent's identity, and Pidgeon never sees it.
141
+ */
142
+ setUp: async (input) => {
143
+ const agent = await this.agents.create(input);
144
+ const key = await generateAgentKey();
145
+ const { kid } = await this.publishKey({
146
+ agentId: agent.id,
147
+ key,
148
+ directory: agent.directory,
149
+ });
150
+ return { agent, key, kid };
151
+ },
152
+ };
153
+ // ------------------------------------------------------------------ Email
154
+ inboxes = {
155
+ list: (options = {}) => this.request('GET', '/v1/email/inboxes', { query: options }),
156
+ get: (id) => this.request('GET', `/v1/email/inboxes/${segment(id)}`),
157
+ /** `name` is the part before the @. Bind an agent's inbox to it with `agentId`. */
158
+ create: (input) => this.request('POST', '/v1/email/inboxes', {
159
+ body: {
160
+ name: input.name,
161
+ kind: input.kind ?? 'agent',
162
+ display_name: input.displayName,
163
+ agent_id: input.agentId,
164
+ pod_id: input.podId,
165
+ },
166
+ }),
167
+ /** Remove an inbox. Its address is retired, never given to anyone again. */
168
+ remove: (id) => this.request('DELETE', `/v1/email/inboxes/${segment(id)}`),
169
+ };
170
+ messages = {
171
+ /** Send from an inbox: `status` is `sent`, or `held` while a person approves it. */
172
+ send: (inboxId, input) => this.request('POST', `/v1/email/inboxes/${segment(inboxId)}/messages`, {
173
+ body: messageBody(input),
174
+ }),
175
+ };
176
+ drafts = {
177
+ create: (inboxId, input) => this.request('POST', `/v1/email/inboxes/${segment(inboxId)}/drafts`, {
178
+ body: messageBody(input),
179
+ }),
180
+ get: (id) => this.request('GET', `/v1/email/drafts/${segment(id)}`),
181
+ /** Replace a draft's addresses and body. */
182
+ update: (id, input) => this.request('PATCH', `/v1/email/drafts/${segment(id)}`, { body: messageBody(input) }),
183
+ remove: (id) => this.request('DELETE', `/v1/email/drafts/${segment(id)}`),
184
+ /** Send now, or at `sendAt` (up to 90 days ahead). */
185
+ send: (id, options = {}) => this.request('POST', `/v1/email/drafts/${segment(id)}/send`, {
186
+ body: {
187
+ send_at: options.sendAt instanceof Date ? options.sendAt.toISOString() : options.sendAt,
188
+ },
189
+ }),
190
+ /** Hold it for a person of the account to send or reject (`draft.approval_requested` carries the link). */
191
+ requestApproval: (id) => this.request('POST', `/v1/email/drafts/${segment(id)}/approval`, { body: {} }),
192
+ };
193
+ /** Send and receive rules, for one inbox or (`inboxId` left out) every inbox. Keys of the whole account only. */
194
+ rules = {
195
+ list: () => this.request('GET', '/v1/email/rules'),
196
+ create: (input) => this.request('POST', '/v1/email/rules', {
197
+ body: {
198
+ direction: input.direction,
199
+ action: input.action,
200
+ pattern: input.pattern,
201
+ inbox_id: input.inboxId ?? null,
202
+ },
203
+ }),
204
+ remove: (id) => this.request('DELETE', `/v1/email/rules/${segment(id)}`),
205
+ };
206
+ /** The do-not-send list: bounces and complaints put addresses on it; you can too. */
207
+ suppressions = {
208
+ list: () => this.request('GET', '/v1/email/suppressions'),
209
+ add: (address) => this.request('POST', '/v1/email/suppressions', { body: { address } }),
210
+ remove: (address) => this.request('DELETE', '/v1/email/suppressions', { query: { address } }),
211
+ };
212
+ // ------------------------------------------------------------------- Auth
213
+ /** Sites registered for Sign in with Pidgeon. */
214
+ sites = {
215
+ list: () => this.request('GET', '/v1/auth/clients'),
216
+ /** Answers `client_secret` once: keep it on the site's server. */
217
+ create: (input) => this.request('POST', '/v1/auth/clients', {
218
+ body: { name: input.name, redirect_uris: input.redirectUris, pod_id: input.podId },
219
+ }),
220
+ remove: (clientId) => this.request('DELETE', `/v1/auth/clients/${segment(clientId)}`),
221
+ };
222
+ /** A person's permission for one of your agents to act for them at one site. */
223
+ mandates = {
224
+ list: () => this.request('GET', '/v1/auth/mandates'),
225
+ /** Answers `consent_url`: send it to the person, who allows or declines. */
226
+ create: (input) => this.request('POST', '/v1/auth/mandates', {
227
+ body: {
228
+ agent_id: input.agentId,
229
+ client_id: input.clientId,
230
+ scope: input.scope,
231
+ description: input.description,
232
+ days: input.days,
233
+ },
234
+ }),
235
+ revoke: (id) => this.request('DELETE', `/v1/auth/mandates/${segment(id)}`),
236
+ };
237
+ // ---------------------------------------------------------------- Account
238
+ events = {
239
+ /** The account's event log, newest first. */
240
+ list: (options = {}) => this.request('GET', '/v1/events', { query: options }),
241
+ };
242
+ pods = {
243
+ list: () => this.request('GET', '/v1/pods'),
244
+ create: (name) => this.request('POST', '/v1/pods', { body: { name } }),
623
245
  };
624
- if (opts.security) {
625
- await setAuthParams(opts);
626
- }
627
- if (opts.requestValidator) {
628
- await opts.requestValidator(opts);
629
- }
630
- if (opts.body !== void 0 && opts.bodySerializer) {
631
- opts.serializedBody = opts.bodySerializer(opts.body);
632
- }
633
- if (opts.body === void 0 || opts.serializedBody === "") {
634
- opts.headers.delete("Content-Type");
635
- }
636
- const resolvedOpts = opts;
637
- const url = buildUrl(resolvedOpts);
638
- return { opts: resolvedOpts, url };
639
- };
640
- const request = async (options) => {
641
- const throwOnError = options.throwOnError ?? _config.throwOnError;
642
- const responseStyle = options.responseStyle ?? _config.responseStyle;
643
- let request2;
644
- let response;
645
- try {
646
- const { opts, url } = await beforeRequest(options);
647
- const requestInit = {
648
- redirect: "follow",
649
- ...opts,
650
- body: getValidRequestBody(opts)
651
- };
652
- request2 = new Request(url, requestInit);
653
- for (const fn of interceptors.request.fns) {
654
- if (fn) {
655
- request2 = await fn(request2, opts);
656
- }
657
- }
658
- const _fetch = opts.fetch;
659
- response = await _fetch(request2);
660
- for (const fn of interceptors.response.fns) {
661
- if (fn) {
662
- response = await fn(response, request2, opts);
663
- }
664
- }
665
- const result = {
666
- request: request2,
667
- response
668
- };
669
- if (response.ok) {
670
- const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
671
- if (response.status === 204 || response.headers.get("Content-Length") === "0") {
672
- let emptyData;
673
- switch (parseAs) {
674
- case "arrayBuffer":
675
- case "blob":
676
- case "text":
677
- emptyData = await response[parseAs]();
678
- break;
679
- case "formData":
680
- emptyData = new FormData();
681
- break;
682
- case "stream":
683
- emptyData = response.body;
684
- break;
685
- case "json":
686
- default:
687
- emptyData = {};
688
- break;
689
- }
690
- return opts.responseStyle === "data" ? emptyData : {
691
- data: emptyData,
692
- ...result
693
- };
694
- }
695
- let data;
696
- switch (parseAs) {
697
- case "arrayBuffer":
698
- case "blob":
699
- case "formData":
700
- case "text":
701
- data = await response[parseAs]();
702
- break;
703
- case "json": {
704
- const text = await response.text();
705
- data = text ? JSON.parse(text) : {};
706
- break;
707
- }
708
- case "stream":
709
- return opts.responseStyle === "data" ? response.body : {
710
- data: response.body,
711
- ...result
712
- };
713
- }
714
- if (parseAs === "json") {
715
- if (opts.responseValidator) {
716
- await opts.responseValidator(data);
717
- }
718
- if (opts.responseTransformer) {
719
- data = await opts.responseTransformer(data);
720
- }
721
- }
722
- return opts.responseStyle === "data" ? data : {
723
- data,
724
- ...result
725
- };
726
- }
727
- const textError = await response.text();
728
- let jsonError;
729
- try {
730
- jsonError = JSON.parse(textError);
731
- } catch {
732
- }
733
- throw jsonError ?? textError;
734
- } catch (error) {
735
- let finalError = error;
736
- for (const fn of interceptors.error.fns) {
737
- if (fn) {
738
- finalError = await fn(finalError, response, request2, options);
739
- }
740
- }
741
- finalError = finalError || {};
742
- if (throwOnError) {
743
- throw finalError;
744
- }
745
- return responseStyle === "data" ? void 0 : {
746
- error: finalError,
747
- request: request2,
748
- response
749
- };
750
- }
751
- };
752
- const makeMethodFn = (method) => (options) => request({ ...options, method });
753
- const makeSseFn = (method) => async (options) => {
754
- const { opts, url } = await beforeRequest(options);
755
- return createSseClient({
756
- ...opts,
757
- body: opts.body,
758
- method,
759
- onRequest: async (url2, init) => {
760
- let request2 = new Request(url2, init);
761
- for (const fn of interceptors.request.fns) {
762
- if (fn) {
763
- request2 = await fn(request2, opts);
764
- }
765
- }
766
- return request2;
767
- },
768
- serializedBody: getValidRequestBody(opts),
769
- url
770
- });
771
- };
772
- const _buildUrl = (options) => buildUrl({ ..._config, ...options });
773
- return {
774
- buildUrl: _buildUrl,
775
- connect: makeMethodFn("CONNECT"),
776
- delete: makeMethodFn("DELETE"),
777
- get: makeMethodFn("GET"),
778
- getConfig,
779
- head: makeMethodFn("HEAD"),
780
- interceptors,
781
- options: makeMethodFn("OPTIONS"),
782
- patch: makeMethodFn("PATCH"),
783
- post: makeMethodFn("POST"),
784
- put: makeMethodFn("PUT"),
785
- request,
786
- setConfig,
787
- sse: {
788
- connect: makeSseFn("CONNECT"),
789
- delete: makeSseFn("DELETE"),
790
- get: makeSseFn("GET"),
791
- head: makeSseFn("HEAD"),
792
- options: makeSseFn("OPTIONS"),
793
- patch: makeSseFn("PATCH"),
794
- post: makeSseFn("POST"),
795
- put: makeSseFn("PUT"),
796
- trace: makeSseFn("TRACE")
797
- },
798
- trace: makeMethodFn("TRACE")
799
- };
800
- };
801
-
802
- // src/runtime-config.ts
803
- var USER_AGENT = "@pidgeon-ai/sdk";
804
- var createClientConfig = (config) => ({
805
- ...config,
806
- ...typeof window === "undefined" ? { headers: { "User-Agent": USER_AGENT, ...plain(config?.headers) } } : {}
807
- });
808
- function plain(headers) {
809
- return headers && typeof headers === "object" && !(headers instanceof Headers) ? headers : {};
810
246
  }
811
-
812
- // src/generated/client.gen.ts
813
- var client = createClient(
814
- createClientConfig(createConfig({ baseUrl: "https://pidgeon.ai/api/v1" }))
815
- );
816
-
817
- // src/generated/sdk.gen.ts
818
- var agentSignUp = (options) => (options.client ?? client).post({
819
- url: "/agent/signup",
820
- ...options,
821
- headers: {
822
- "Content-Type": "application/json",
823
- ...options.headers
824
- }
825
- });
826
- var agentAttachHuman = (options) => (options.client ?? client).post({
827
- url: "/agent/human",
828
- ...options,
829
- headers: {
830
- "Content-Type": "application/json",
831
- ...options.headers
832
- }
833
- });
834
- var agentVerify = (options) => (options.client ?? client).post({
835
- url: "/agent/verify",
836
- ...options,
837
- headers: {
838
- "Content-Type": "application/json",
839
- ...options.headers
840
- }
841
- });
842
- var cardsGet = (options) => (options.client ?? client).get({
843
- url: "/cards/{id}",
844
- ...options
845
- });
846
- var verifySender = (options) => (options.client ?? client).post({
847
- url: "/verify",
848
- ...options,
849
- headers: {
850
- "Content-Type": "application/json",
851
- ...options.headers
852
- }
853
- });
854
- var logHead = (options) => (options?.client ?? client).get({
855
- url: "/log/head",
856
- ...options
857
- });
858
- var logCheckpoint = (options) => (options?.client ?? client).get({
859
- url: "/log/checkpoint",
860
- ...options
861
- });
862
- var logEntries = (options) => (options?.client ?? client).get({
863
- url: "/log/entries",
864
- ...options
865
- });
866
- var logProof = (options) => (options?.client ?? client).get({
867
- url: "/log/proof",
868
- ...options
869
- });
870
- var logConsistency = (options) => (options.client ?? client).get({
871
- url: "/log/consistency",
872
- ...options
873
- });
874
- var logMonitorsList = (options) => (options?.client ?? client).get({
875
- security: [{ scheme: "bearer", type: "http" }],
876
- url: "/log/monitors",
877
- ...options
878
- });
879
- var logMonitorsCreate = (options) => (options.client ?? client).post({
880
- security: [{ scheme: "bearer", type: "http" }],
881
- url: "/log/monitors",
882
- ...options,
883
- headers: {
884
- "Content-Type": "application/json",
885
- ...options.headers
886
- }
887
- });
888
- var logMonitorsDelete = (options) => (options.client ?? client).delete({
889
- security: [{ scheme: "bearer", type: "http" }],
890
- url: "/log/monitors/{id}",
891
- ...options
892
- });
893
- var grantsStatus = (options) => (options.client ?? client).get({
894
- url: "/grants/{id}/status",
895
- ...options
896
- });
897
- var agentConnect = (options) => (options.client ?? client).post({
898
- url: "/agent/connect",
899
- ...options,
900
- headers: {
901
- "Content-Type": "application/json",
902
- ...options.headers
903
- }
904
- });
905
- var agentSetup = (options) => (options?.client ?? client).get({
906
- security: [{ scheme: "bearer", type: "http" }],
907
- url: "/agent/setup",
908
- ...options
909
- });
910
- var identitiesList = (options) => (options?.client ?? client).get({
911
- security: [{ scheme: "bearer", type: "http" }],
912
- url: "/identities",
913
- ...options
914
- });
915
- var identitiesCreate = (options) => (options.client ?? client).post({
916
- security: [{ scheme: "bearer", type: "http" }],
917
- url: "/identities",
918
- ...options,
919
- headers: {
920
- "Content-Type": "application/json",
921
- ...options.headers
922
- }
923
- });
924
- var identitiesDelete = (options) => (options.client ?? client).delete({
925
- security: [{ scheme: "bearer", type: "http" }],
926
- url: "/identities/{id}",
927
- ...options
928
- });
929
- var identitiesGet = (options) => (options.client ?? client).get({
930
- security: [{ scheme: "bearer", type: "http" }],
931
- url: "/identities/{id}",
932
- ...options
933
- });
934
- var identitiesUpdate = (options) => (options.client ?? client).patch(
935
- {
936
- security: [{ scheme: "bearer", type: "http" }],
937
- url: "/identities/{id}",
938
- ...options,
939
- headers: {
940
- "Content-Type": "application/json",
941
- ...options.headers
942
- }
943
- }
944
- );
945
- var identitiesCard = (options) => (options.client ?? client).get({
946
- security: [{ scheme: "bearer", type: "http" }],
947
- url: "/identities/{id}/card",
948
- ...options
949
- });
950
- var identitiesAccessDelete = (options) => (options.client ?? client).delete({
951
- security: [{ scheme: "bearer", type: "http" }],
952
- url: "/identities/{id}/access",
953
- ...options
954
- });
955
- var identitiesAccessGet = (options) => (options.client ?? client).get({
956
- security: [{ scheme: "bearer", type: "http" }],
957
- url: "/identities/{id}/access",
958
- ...options
959
- });
960
- var identitiesAccessCreate = (options) => (options.client ?? client).post({
961
- security: [{ scheme: "bearer", type: "http" }],
962
- url: "/identities/{id}/access",
963
- ...options,
964
- headers: {
965
- "Content-Type": "application/json",
966
- ...options.headers
967
- }
968
- });
969
- var identitiesSendRulesDelete = (options) => (options.client ?? client).delete({
970
- security: [{ scheme: "bearer", type: "http" }],
971
- url: "/identities/{id}/send-rules",
972
- ...options
973
- });
974
- var identitiesSendRulesGet = (options) => (options.client ?? client).get({
975
- security: [{ scheme: "bearer", type: "http" }],
976
- url: "/identities/{id}/send-rules",
977
- ...options
978
- });
979
- var identitiesSendRulesCreate = (options) => (options.client ?? client).post({
980
- security: [{ scheme: "bearer", type: "http" }],
981
- url: "/identities/{id}/send-rules",
982
- ...options,
983
- headers: {
984
- "Content-Type": "application/json",
985
- ...options.headers
986
- }
987
- });
988
- var identitiesReceiveRulesDelete = (options) => (options.client ?? client).delete({
989
- security: [{ scheme: "bearer", type: "http" }],
990
- url: "/identities/{id}/receive-rules",
991
- ...options
992
- });
993
- var identitiesReceiveRulesGet = (options) => (options.client ?? client).get({
994
- security: [{ scheme: "bearer", type: "http" }],
995
- url: "/identities/{id}/receive-rules",
996
- ...options
997
- });
998
- var identitiesReceiveRulesCreate = (options) => (options.client ?? client).post({
999
- security: [{ scheme: "bearer", type: "http" }],
1000
- url: "/identities/{id}/receive-rules",
1001
- ...options,
1002
- headers: {
1003
- "Content-Type": "application/json",
1004
- ...options.headers
1005
- }
1006
- });
1007
- var identitiesSuspendTenant = (options) => (options.client ?? client).post({
1008
- security: [{ scheme: "bearer", type: "http" }],
1009
- url: "/tenants/{id}/suspend",
1010
- ...options
1011
- });
1012
- var podsList = (options) => (options?.client ?? client).get({
1013
- security: [{ scheme: "bearer", type: "http" }],
1014
- url: "/pods",
1015
- ...options
1016
- });
1017
- var podsCreate = (options) => (options.client ?? client).post({
1018
- security: [{ scheme: "bearer", type: "http" }],
1019
- url: "/pods",
1020
- ...options,
1021
- headers: {
1022
- "Content-Type": "application/json",
1023
- ...options.headers
1024
- }
1025
- });
1026
- var podsDelete = (options) => (options.client ?? client).delete({
1027
- security: [{ scheme: "bearer", type: "http" }],
1028
- url: "/pods/{id}",
1029
- ...options
1030
- });
1031
- var podsGet = (options) => (options.client ?? client).get({
1032
- security: [{ scheme: "bearer", type: "http" }],
1033
- url: "/pods/{id}",
1034
- ...options
1035
- });
1036
- var podsUpdate = (options) => (options.client ?? client).patch({
1037
- security: [{ scheme: "bearer", type: "http" }],
1038
- url: "/pods/{id}",
1039
- ...options,
1040
- headers: {
1041
- "Content-Type": "application/json",
1042
- ...options.headers
1043
- }
1044
- });
1045
- var labelsList = (options) => (options.client ?? client).get({
1046
- security: [{ scheme: "bearer", type: "http" }],
1047
- url: "/labels",
1048
- ...options
1049
- });
1050
- var labelsCreate = (options) => (options.client ?? client).post({
1051
- security: [{ scheme: "bearer", type: "http" }],
1052
- url: "/labels",
1053
- ...options,
1054
- headers: {
1055
- "Content-Type": "application/json",
1056
- ...options.headers
1057
- }
1058
- });
1059
- var labelsDelete = (options) => (options.client ?? client).delete({
1060
- security: [{ scheme: "bearer", type: "http" }],
1061
- url: "/labels/{id}",
1062
- ...options
1063
- });
1064
- var labelsUpdate = (options) => (options.client ?? client).patch({
1065
- security: [{ scheme: "bearer", type: "http" }],
1066
- url: "/labels/{id}",
1067
- ...options,
1068
- headers: {
1069
- "Content-Type": "application/json",
1070
- ...options.headers
1071
- }
1072
- });
1073
- var grantsTemplatesList = (options) => (options?.client ?? client).get({
1074
- security: [{ scheme: "bearer", type: "http" }],
1075
- url: "/grant-templates",
1076
- ...options
1077
- });
1078
- var grantsTemplatesCreate = (options) => (options.client ?? client).post({
1079
- security: [{ scheme: "bearer", type: "http" }],
1080
- url: "/grant-templates",
1081
- ...options,
1082
- headers: {
1083
- "Content-Type": "application/json",
1084
- ...options.headers
1085
- }
1086
- });
1087
- var grantsTemplatesDelete = (options) => (options.client ?? client).delete({
1088
- security: [{ scheme: "bearer", type: "http" }],
1089
- url: "/grant-templates/{id}",
1090
- ...options
1091
- });
1092
- var grantsList = (options) => (options.client ?? client).get({
1093
- security: [{ scheme: "bearer", type: "http" }],
1094
- url: "/grants",
1095
- ...options
1096
- });
1097
- var grantsCreate = (options) => (options.client ?? client).post({
1098
- security: [{ scheme: "bearer", type: "http" }],
1099
- url: "/grants",
1100
- ...options,
1101
- headers: {
1102
- "Content-Type": "application/json",
1103
- ...options.headers
1104
- }
1105
- });
1106
- var grantsRevoke = (options) => (options.client ?? client).delete({
1107
- security: [{ scheme: "bearer", type: "http" }],
1108
- url: "/grants/{id}",
1109
- ...options
1110
- });
1111
- var grantsGet = (options) => (options.client ?? client).get({
1112
- security: [{ scheme: "bearer", type: "http" }],
1113
- url: "/grants/{id}",
1114
- ...options
1115
- });
1116
- var contactsList = (options) => (options?.client ?? client).get({
1117
- security: [{ scheme: "bearer", type: "http" }],
1118
- url: "/contacts",
1119
- ...options
1120
- });
1121
- var contactsCreate = (options) => (options.client ?? client).post({
1122
- security: [{ scheme: "bearer", type: "http" }],
1123
- url: "/contacts",
1124
- ...options,
1125
- headers: {
1126
- "Content-Type": "application/json",
1127
- ...options.headers
1128
- }
1129
- });
1130
- var contactsDelete = (options) => (options.client ?? client).delete({
1131
- security: [{ scheme: "bearer", type: "http" }],
1132
- url: "/contacts/{id}",
1133
- ...options
1134
- });
1135
- var contactsGet = (options) => (options.client ?? client).get({
1136
- security: [{ scheme: "bearer", type: "http" }],
1137
- url: "/contacts/{id}",
1138
- ...options
1139
- });
1140
- var contactsUpdate = (options) => (options.client ?? client).patch({
1141
- security: [{ scheme: "bearer", type: "http" }],
1142
- url: "/contacts/{id}",
1143
- ...options,
1144
- headers: {
1145
- "Content-Type": "application/json",
1146
- ...options.headers
1147
- }
1148
- });
1149
- var contactsUnblock = (options) => (options.client ?? client).delete({
1150
- security: [{ scheme: "bearer", type: "http" }],
1151
- url: "/contacts/{id}/block",
1152
- ...options
1153
- });
1154
- var contactsBlock = (options) => (options.client ?? client).post({
1155
- security: [{ scheme: "bearer", type: "http" }],
1156
- url: "/contacts/{id}/block",
1157
- ...options
1158
- });
1159
- var threadsLabelsDelete = (options) => (options.client ?? client).delete({
1160
- security: [{ scheme: "bearer", type: "http" }],
1161
- url: "/threads/{id}/labels",
1162
- ...options
1163
- });
1164
- var threadsLabelsGet = (options) => (options.client ?? client).get({
1165
- security: [{ scheme: "bearer", type: "http" }],
1166
- url: "/threads/{id}/labels",
1167
- ...options
1168
- });
1169
- var threadsLabelsCreate = (options) => (options.client ?? client).post({
1170
- security: [{ scheme: "bearer", type: "http" }],
1171
- url: "/threads/{id}/labels",
1172
- ...options,
1173
- headers: {
1174
- "Content-Type": "application/json",
1175
- ...options.headers
1176
- }
1177
- });
1178
- var messagesListInThread = (options) => (options.client ?? client).get({
1179
- security: [{ scheme: "bearer", type: "http" }],
1180
- url: "/messages",
1181
- ...options
1182
- });
1183
- var messagesSend = (options) => (options.client ?? client).post({
1184
- security: [{ scheme: "bearer", type: "http" }],
1185
- url: "/messages",
1186
- ...options,
1187
- headers: {
1188
- "Content-Type": "application/json",
1189
- ...options.headers
1190
- }
1191
- });
1192
- var messagesCheck = (options) => (options.client ?? client).post({
1193
- security: [{ scheme: "bearer", type: "http" }],
1194
- url: "/messages/check",
1195
- ...options,
1196
- headers: {
1197
- "Content-Type": "application/json",
1198
- ...options.headers
1199
- }
1200
- });
1201
- var signInsApprove = (options) => (options.client ?? client).post({
1202
- security: [{ scheme: "bearer", type: "http" }],
1203
- url: "/sign-ins",
1204
- ...options,
1205
- headers: {
1206
- "Content-Type": "application/json",
1207
- ...options.headers
1208
- }
1209
- });
1210
- var messagesSearch = (options) => (options?.client ?? client).get({
1211
- security: [{ scheme: "bearer", type: "http" }],
1212
- url: "/messages/search",
1213
- ...options
1214
- });
1215
- var messagesAct = (options) => (options.client ?? client).post({
1216
- security: [{ scheme: "bearer", type: "http" }],
1217
- url: "/messages/actions",
1218
- ...options,
1219
- headers: {
1220
- "Content-Type": "application/json",
1221
- ...options.headers
1222
- }
1223
- });
1224
- var messagesUndo = (options) => (options.client ?? client).post({
1225
- security: [{ scheme: "bearer", type: "http" }],
1226
- url: "/messages/undo",
1227
- ...options,
1228
- headers: {
1229
- "Content-Type": "application/json",
1230
- ...options.headers
1231
- }
1232
- });
1233
- var messagesAwait = (options) => (options.client ?? client).get({
1234
- security: [{ scheme: "bearer", type: "http" }],
1235
- url: "/messages/await",
1236
- ...options
1237
- });
1238
- var messagesGet = (options) => (options.client ?? client).get({
1239
- security: [{ scheme: "bearer", type: "http" }],
1240
- url: "/messages/{id}",
1241
- ...options
1242
- });
1243
- var messagesUpdate = (options) => (options.client ?? client).patch({
1244
- security: [{ scheme: "bearer", type: "http" }],
1245
- url: "/messages/{id}",
1246
- ...options,
1247
- headers: {
1248
- "Content-Type": "application/json",
1249
- ...options.headers
1250
- }
1251
- });
1252
- var messagesReply = (options) => (options.client ?? client).post({
1253
- security: [{ scheme: "bearer", type: "http" }],
1254
- url: "/messages/{id}/reply",
1255
- ...options,
1256
- headers: {
1257
- "Content-Type": "application/json",
1258
- ...options.headers
1259
- }
1260
- });
1261
- var messagesReplyAll = (options) => (options.client ?? client).post({
1262
- security: [{ scheme: "bearer", type: "http" }],
1263
- url: "/messages/{id}/reply-all",
1264
- ...options,
1265
- headers: {
1266
- "Content-Type": "application/json",
1267
- ...options.headers
1268
- }
1269
- });
1270
- var messagesForward = (options) => (options.client ?? client).post({
1271
- security: [{ scheme: "bearer", type: "http" }],
1272
- url: "/messages/{id}/forward",
1273
- ...options,
1274
- headers: {
1275
- "Content-Type": "application/json",
1276
- ...options.headers
1277
- }
1278
- });
1279
- var messagesRaw = (options) => (options.client ?? client).get({
1280
- security: [{ scheme: "bearer", type: "http" }],
1281
- url: "/messages/{id}/raw",
1282
- ...options
1283
- });
1284
- var exportMail = (options) => (options?.client ?? client).get({
1285
- security: [{ scheme: "bearer", type: "http" }],
1286
- url: "/export",
1287
- ...options
1288
- });
1289
- var threadsList = (options) => (options?.client ?? client).get({
1290
- security: [{ scheme: "bearer", type: "http" }],
1291
- url: "/threads",
1292
- ...options
1293
- });
1294
- var threadsGet = (options) => (options.client ?? client).get({
1295
- security: [{ scheme: "bearer", type: "http" }],
1296
- url: "/threads/{id}",
1297
- ...options
1298
- });
1299
- var threadsUpdate = (options) => (options.client ?? client).patch({
1300
- security: [{ scheme: "bearer", type: "http" }],
1301
- url: "/threads/{id}",
1302
- ...options,
1303
- headers: {
1304
- "Content-Type": "application/json",
1305
- ...options.headers
1306
- }
1307
- });
1308
- var domainsList = (options) => (options?.client ?? client).get({
1309
- security: [{ scheme: "bearer", type: "http" }],
1310
- url: "/domains",
1311
- ...options
1312
- });
1313
- var domainsCreate = (options) => (options.client ?? client).post({
1314
- security: [{ scheme: "bearer", type: "http" }],
1315
- url: "/domains",
1316
- ...options,
1317
- headers: {
1318
- "Content-Type": "application/json",
1319
- ...options.headers
1320
- }
1321
- });
1322
- var domainsZoneFile = (options) => (options.client ?? client).get({
1323
- security: [{ scheme: "bearer", type: "http" }],
1324
- url: "/domains/{id}/zone-file",
1325
- ...options
1326
- });
1327
- var domainsGetSetupLink = (options) => (options.client ?? client).get({
1328
- security: [{ scheme: "bearer", type: "http" }],
1329
- url: "/domains/{id}/setup-link",
1330
- ...options
1331
- });
1332
- var domainsVerify = (options) => (options.client ?? client).post({
1333
- security: [{ scheme: "bearer", type: "http" }],
1334
- url: "/domains/{id}/verify",
1335
- ...options
1336
- });
1337
- var domainsDelete = (options) => (options.client ?? client).delete({
1338
- security: [{ scheme: "bearer", type: "http" }],
1339
- url: "/domains/{id}",
1340
- ...options
1341
- });
1342
- var domainsGet = (options) => (options.client ?? client).get({
1343
- security: [{ scheme: "bearer", type: "http" }],
1344
- url: "/domains/{id}",
1345
- ...options
1346
- });
1347
- var domainsUpdate = (options) => (options.client ?? client).patch({
1348
- security: [{ scheme: "bearer", type: "http" }],
1349
- url: "/domains/{id}",
1350
- ...options,
1351
- headers: {
1352
- "Content-Type": "application/json",
1353
- ...options.headers
1354
- }
1355
- });
1356
- var routingList = (options) => (options?.client ?? client).get({
1357
- security: [{ scheme: "bearer", type: "http" }],
1358
- url: "/routing-rules",
1359
- ...options
1360
- });
1361
- var routingCreate = (options) => (options.client ?? client).post({
1362
- security: [{ scheme: "bearer", type: "http" }],
1363
- url: "/routing-rules",
1364
- ...options,
1365
- headers: {
1366
- "Content-Type": "application/json",
1367
- ...options.headers
1368
- }
1369
- });
1370
- var routingDelete = (options) => (options.client ?? client).delete({
1371
- security: [{ scheme: "bearer", type: "http" }],
1372
- url: "/routing-rules/{id}",
1373
- ...options
1374
- });
1375
- var routingUpdate = (options) => (options.client ?? client).patch({
1376
- security: [{ scheme: "bearer", type: "http" }],
1377
- url: "/routing-rules/{id}",
1378
- ...options,
1379
- headers: {
1380
- "Content-Type": "application/json",
1381
- ...options.headers
1382
- }
1383
- });
1384
- var mailboxesList = (options) => (options.client ?? client).get({
1385
- security: [{ scheme: "bearer", type: "http" }],
1386
- url: "/mailboxes",
1387
- ...options
1388
- });
1389
- var mailboxesChanges = (options) => (options.client ?? client).get({
1390
- security: [{ scheme: "bearer", type: "http" }],
1391
- url: "/mailboxes/changes",
1392
- ...options
1393
- });
1394
- var mailboxesEmptyTrash = (options) => (options.client ?? client).delete({
1395
- security: [{ scheme: "bearer", type: "http" }],
1396
- url: "/mailboxes/{folder}",
1397
- ...options
1398
- });
1399
- var mailboxesListFolder = (options) => (options.client ?? client).get({
1400
- security: [{ scheme: "bearer", type: "http" }],
1401
- url: "/mailboxes/{folder}",
1402
- ...options
1403
- });
1404
- var keysList = (options) => (options?.client ?? client).get({
1405
- security: [{ scheme: "bearer", type: "http" }],
1406
- url: "/api-keys",
1407
- ...options
1408
- });
1409
- var keysCreate = (options) => (options.client ?? client).post({
1410
- security: [{ scheme: "bearer", type: "http" }],
1411
- url: "/api-keys",
1412
- ...options,
1413
- headers: {
1414
- "Content-Type": "application/json",
1415
- ...options.headers
1416
- }
1417
- });
1418
- var keysRevoke = (options) => (options.client ?? client).delete({
1419
- security: [{ scheme: "bearer", type: "http" }],
1420
- url: "/api-keys/{id}",
1421
- ...options
1422
- });
1423
- var keysGet = (options) => (options.client ?? client).get({
1424
- security: [{ scheme: "bearer", type: "http" }],
1425
- url: "/api-keys/{id}",
1426
- ...options
1427
- });
1428
- var keysUpdate = (options) => (options.client ?? client).patch({
1429
- security: [{ scheme: "bearer", type: "http" }],
1430
- url: "/api-keys/{id}",
1431
- ...options,
1432
- headers: {
1433
- "Content-Type": "application/json",
1434
- ...options.headers
1435
- }
1436
- });
1437
- var keysRotate = (options) => (options.client ?? client).post({
1438
- security: [{ scheme: "bearer", type: "http" }],
1439
- url: "/api-keys/{id}/rotate",
1440
- ...options,
1441
- headers: {
1442
- "Content-Type": "application/json",
1443
- ...options.headers
1444
- }
1445
- });
1446
- var testInbound = (options) => (options.client ?? client).post({
1447
- security: [{ scheme: "bearer", type: "http" }],
1448
- url: "/test/inbound",
1449
- ...options,
1450
- headers: {
1451
- "Content-Type": "application/json",
1452
- ...options.headers
1453
- }
1454
- });
1455
- var appPasswordsList = (options) => (options.client ?? client).get({
1456
- security: [{ scheme: "bearer", type: "http" }],
1457
- url: "/app-passwords",
1458
- ...options
1459
- });
1460
- var appPasswordsCreate = (options) => (options.client ?? client).post({
1461
- security: [{ scheme: "bearer", type: "http" }],
1462
- url: "/app-passwords",
1463
- ...options,
1464
- headers: {
1465
- "Content-Type": "application/json",
1466
- ...options.headers
1467
- }
1468
- });
1469
- var appPasswordsRevoke = (options) => (options.client ?? client).delete({
1470
- security: [{ scheme: "bearer", type: "http" }],
1471
- url: "/app-passwords/{id}",
1472
- ...options
1473
- });
1474
- var meGet = (options) => (options?.client ?? client).get({
1475
- security: [{ scheme: "bearer", type: "http" }],
1476
- url: "/me",
1477
- ...options
1478
- });
1479
- var workspaceGet = (options) => (options?.client ?? client).get({
1480
- security: [{ scheme: "bearer", type: "http" }],
1481
- url: "/workspace",
1482
- ...options
1483
- });
1484
- var workspaceMembers = (options) => (options?.client ?? client).get({
1485
- security: [{ scheme: "bearer", type: "http" }],
1486
- url: "/workspace/members",
1487
- ...options
1488
- });
1489
- var eventsList = (options) => (options?.client ?? client).get({
1490
- security: [{ scheme: "bearer", type: "http" }],
1491
- url: "/events",
1492
- ...options
1493
- });
1494
- var eventsSocket = (options) => (options?.client ?? client).get({
1495
- security: [{ scheme: "bearer", type: "http" }],
1496
- url: "/events/socket",
1497
- ...options
1498
- });
1499
- var eventsStream = (options) => (options?.client ?? client).sse.get({
1500
- security: [{ scheme: "bearer", type: "http" }],
1501
- url: "/events/stream",
1502
- ...options
1503
- });
1504
- var eventsGet = (options) => (options.client ?? client).get({
1505
- security: [{ scheme: "bearer", type: "http" }],
1506
- url: "/events/{id}",
1507
- ...options
1508
- });
1509
- var webhooksList = (options) => (options?.client ?? client).get({
1510
- security: [{ scheme: "bearer", type: "http" }],
1511
- url: "/webhooks",
1512
- ...options
1513
- });
1514
- var webhooksCreate = (options) => (options.client ?? client).post({
1515
- security: [{ scheme: "bearer", type: "http" }],
1516
- url: "/webhooks",
1517
- ...options,
1518
- headers: {
1519
- "Content-Type": "application/json",
1520
- ...options.headers
1521
- }
1522
- });
1523
- var webhooksDelete = (options) => (options.client ?? client).delete({
1524
- security: [{ scheme: "bearer", type: "http" }],
1525
- url: "/webhooks/{id}",
1526
- ...options
1527
- });
1528
- var webhooksGet = (options) => (options.client ?? client).get({
1529
- security: [{ scheme: "bearer", type: "http" }],
1530
- url: "/webhooks/{id}",
1531
- ...options
1532
- });
1533
- var webhooksUpdate = (options) => (options.client ?? client).patch({
1534
- security: [{ scheme: "bearer", type: "http" }],
1535
- url: "/webhooks/{id}",
1536
- ...options,
1537
- headers: {
1538
- "Content-Type": "application/json",
1539
- ...options.headers
1540
- }
1541
- });
1542
- var webhooksGetHeaders = (options) => (options.client ?? client).get({
1543
- security: [{ scheme: "bearer", type: "http" }],
1544
- url: "/webhooks/{id}/headers",
1545
- ...options
1546
- });
1547
- var webhooksUpdateHeaders = (options) => (options.client ?? client).put({
1548
- security: [{ scheme: "bearer", type: "http" }],
1549
- url: "/webhooks/{id}/headers",
1550
- ...options,
1551
- headers: {
1552
- "Content-Type": "application/json",
1553
- ...options.headers
1554
- }
1555
- });
1556
- var webhooksDeliveries = (options) => (options.client ?? client).get({
1557
- security: [{ scheme: "bearer", type: "http" }],
1558
- url: "/deliveries",
1559
- ...options
1560
- });
1561
- var webhooksReplay = (options) => (options.client ?? client).post({
1562
- security: [{ scheme: "bearer", type: "http" }],
1563
- url: "/deliveries/{id}/replay",
1564
- ...options
1565
- });
1566
- var messagesRespondToInvitation = (options) => (options.client ?? client).post({
1567
- security: [{ scheme: "bearer", type: "http" }],
1568
- url: "/messages/{id}/invitation/respond",
1569
- ...options,
1570
- headers: {
1571
- "Content-Type": "application/json",
1572
- ...options.headers
1573
- }
1574
- });
1575
- var calendarGet = (options) => (options.client ?? client).get({
1576
- security: [{ scheme: "bearer", type: "http" }],
1577
- url: "/identities/{id}/calendar",
1578
- ...options
1579
- });
1580
- var calendarUpdate = (options) => (options.client ?? client).patch({
1581
- security: [{ scheme: "bearer", type: "http" }],
1582
- url: "/identities/{id}/calendar",
1583
- ...options,
1584
- headers: {
1585
- "Content-Type": "application/json",
1586
- ...options.headers
1587
- }
1588
- });
1589
- var calendarListEvents = (options) => (options.client ?? client).get({
1590
- security: [{ scheme: "bearer", type: "http" }],
1591
- url: "/identities/{id}/calendar/events",
1592
- ...options
1593
- });
1594
- var calendarCreateEvent = (options) => (options.client ?? client).post({
1595
- security: [{ scheme: "bearer", type: "http" }],
1596
- url: "/identities/{id}/calendar/events",
1597
- ...options,
1598
- headers: {
1599
- "Content-Type": "application/json",
1600
- ...options.headers
1601
- }
1602
- });
1603
- var calendarRespondToEvent = (options) => (options.client ?? client).post({
1604
- security: [{ scheme: "bearer", type: "http" }],
1605
- url: "/identities/{id}/calendar/events/{eventId}/respond",
1606
- ...options,
1607
- headers: {
1608
- "Content-Type": "application/json",
1609
- ...options.headers
1610
- }
1611
- });
1612
- var calendarListEventInstances = (options) => (options.client ?? client).get({
1613
- security: [{ scheme: "bearer", type: "http" }],
1614
- url: "/identities/{id}/calendar/events/{eventId}/instances",
1615
- ...options
1616
- });
1617
- var calendarGetAgenda = (options) => (options.client ?? client).get(
1618
- {
1619
- security: [{ scheme: "bearer", type: "http" }],
1620
- url: "/identities/{id}/calendar/agenda",
1621
- ...options
1622
- }
1623
- );
1624
- var calendarFreeTime = (options) => (options.client ?? client).get({
1625
- security: [{ scheme: "bearer", type: "http" }],
1626
- url: "/calendar/free-time",
1627
- ...options
1628
- });
1629
- var calendarDeleteEvent = (options) => (options.client ?? client).delete({
1630
- security: [{ scheme: "bearer", type: "http" }],
1631
- url: "/identities/{id}/calendar/events/{eventId}",
1632
- ...options
1633
- });
1634
- var calendarGetEvent = (options) => (options.client ?? client).get({
1635
- security: [{ scheme: "bearer", type: "http" }],
1636
- url: "/identities/{id}/calendar/events/{eventId}",
1637
- ...options
1638
- });
1639
- var calendarUpdateEvent = (options) => (options.client ?? client).patch({
1640
- security: [{ scheme: "bearer", type: "http" }],
1641
- url: "/identities/{id}/calendar/events/{eventId}",
1642
- ...options,
1643
- headers: {
1644
- "Content-Type": "application/json",
1645
- ...options.headers
1646
- }
1647
- });
1648
- var draftsList = (options) => (options.client ?? client).get({
1649
- security: [{ scheme: "bearer", type: "http" }],
1650
- url: "/drafts",
1651
- ...options
1652
- });
1653
- var draftsCreate = (options) => (options.client ?? client).post({
1654
- security: [{ scheme: "bearer", type: "http" }],
1655
- url: "/drafts",
1656
- ...options,
1657
- headers: {
1658
- "Content-Type": "application/json",
1659
- ...options.headers
1660
- }
1661
- });
1662
- var draftsDelete = (options) => (options.client ?? client).delete({
1663
- security: [{ scheme: "bearer", type: "http" }],
1664
- url: "/drafts/{id}",
1665
- ...options
1666
- });
1667
- var draftsGet = (options) => (options.client ?? client).get({
1668
- security: [{ scheme: "bearer", type: "http" }],
1669
- url: "/drafts/{id}",
1670
- ...options
1671
- });
1672
- var draftsUpdate = (options) => (options.client ?? client).patch({
1673
- security: [{ scheme: "bearer", type: "http" }],
1674
- url: "/drafts/{id}",
1675
- ...options,
1676
- headers: {
1677
- "Content-Type": "application/json",
1678
- ...options.headers
1679
- }
1680
- });
1681
- var draftsSend = (options) => (options.client ?? client).post({
1682
- security: [{ scheme: "bearer", type: "http" }],
1683
- url: "/drafts/{id}/send",
1684
- ...options
1685
- });
1686
- var draftsApproval = (options) => (options.client ?? client).get({
1687
- security: [{ scheme: "bearer", type: "http" }],
1688
- url: "/drafts/{id}/approval",
1689
- ...options
1690
- });
1691
- var draftsCancelSchedule = (options) => (options.client ?? client).delete({
1692
- security: [{ scheme: "bearer", type: "http" }],
1693
- url: "/drafts/{id}/schedule",
1694
- ...options
1695
- });
1696
- var draftsSchedule = (options) => (options.client ?? client).post({
1697
- security: [{ scheme: "bearer", type: "http" }],
1698
- url: "/drafts/{id}/schedule",
1699
- ...options,
1700
- headers: {
1701
- "Content-Type": "application/json",
1702
- ...options.headers
1703
- }
1704
- });
1705
- var draftsRemoveAttachment = (options) => (options.client ?? client).delete({
1706
- security: [{ scheme: "bearer", type: "http" }],
1707
- url: "/drafts/{id}/attachments/{attachmentId}",
1708
- ...options
1709
- });
1710
- var metricsQuery = (options) => (options?.client ?? client).get({
1711
- security: [{ scheme: "bearer", type: "http" }],
1712
- url: "/metrics",
1713
- ...options
1714
- });
1715
- var attachmentsUpload = (options) => (options.client ?? client).post({
1716
- ...formDataBodySerializer,
1717
- security: [{ scheme: "bearer", type: "http" }],
1718
- url: "/attachments",
1719
- ...options,
1720
- headers: {
1721
- "Content-Type": null,
1722
- ...options.headers
1723
- }
1724
- });
1725
- var attachmentsCreateUpload = (options) => (options.client ?? client).post({
1726
- security: [{ scheme: "bearer", type: "http" }],
1727
- url: "/attachments/uploads",
1728
- ...options,
1729
- headers: {
1730
- "Content-Type": "application/json",
1731
- ...options.headers
1732
- }
1733
- });
1734
- var attachmentsCompleteUpload = (options) => (options.client ?? client).post({
1735
- security: [{ scheme: "bearer", type: "http" }],
1736
- url: "/attachments/{id}/complete",
1737
- ...options
1738
- });
1739
- var attachmentsDownloadUrl = (options) => (options.client ?? client).get({
1740
- security: [{ scheme: "bearer", type: "http" }],
1741
- url: "/attachments/{id}",
1742
- ...options
1743
- });
1744
- var attachmentsText = (options) => (options.client ?? client).get({
1745
- security: [{ scheme: "bearer", type: "http" }],
1746
- url: "/attachments/{id}/text",
1747
- ...options
1748
- });
1749
-
1750
- // src/webhooks.ts
1751
- var SIGNATURE_HEADER = "x-pidgeon-signature";
1752
- var TIMESTAMP_HEADER = "x-pidgeon-timestamp";
1753
- async function verifyWebhook(input) {
1754
- const get = (name) => {
1755
- if (input.headers instanceof Headers) return input.headers.get(name) ?? void 0;
1756
- const direct = input.headers[name];
1757
- if (direct !== void 0) return direct;
1758
- const wanted = name.toLowerCase();
1759
- for (const [key2, value] of Object.entries(input.headers)) {
1760
- if (key2.toLowerCase() === wanted) return value;
247
+ /** `fetch`, signed as your agent: every request carries its Web Bot Auth signature. */
248
+ export async function signedFetch(input, init, agent) {
249
+ const request = new Request(input, init);
250
+ const signature = await signAgentRequest(request, agent);
251
+ const headers = new Headers(request.headers);
252
+ for (const [name, value] of Object.entries(signature))
253
+ headers.set(name, value);
254
+ return fetch(new Request(request, { headers }));
255
+ }
256
+ /** Your agent, from `PIDGEON_AGENT_KEY` and `PIDGEON_DIRECTORY` (the dashboard gives both). */
257
+ export function agentFromEnv(env = process.env) {
258
+ const key = env.PIDGEON_AGENT_KEY;
259
+ const directory = env.PIDGEON_DIRECTORY;
260
+ if (!key || !directory) {
261
+ throw new Error('Set PIDGEON_AGENT_KEY and PIDGEON_DIRECTORY: your agent’s page on pidgeon.ai has both.');
1761
262
  }
1762
- return void 0;
1763
- };
1764
- const timestamp = get(TIMESTAMP_HEADER);
1765
- const signature = get(SIGNATURE_HEADER);
1766
- if (!timestamp || !signature) throw new Error("This request is not signed.");
1767
- const seconds = Number(timestamp);
1768
- if (!Number.isFinite(seconds)) throw new Error("The signature timestamp is not a number.");
1769
- const now = Math.floor((input.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
1770
- const tolerance = input.toleranceSeconds ?? 300;
1771
- if (Math.abs(now - seconds) > tolerance) {
1772
- throw new Error("This request is too old to trust. It may be a replay.");
1773
- }
1774
- const key = await crypto.subtle.importKey(
1775
- "raw",
1776
- new TextEncoder().encode(input.secret),
1777
- { name: "HMAC", hash: "SHA-256" },
1778
- false,
1779
- ["sign"]
1780
- );
1781
- const mac = await crypto.subtle.sign(
1782
- "HMAC",
1783
- key,
1784
- new TextEncoder().encode(`${seconds}.${input.rawBody}`)
1785
- );
1786
- const expected = `v1=${[...new Uint8Array(mac)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
1787
- if (!constantTimeEqual(expected, signature)) {
1788
- throw new Error("The signature does not match.");
1789
- }
1790
- return JSON.parse(input.rawBody);
263
+ const privateJwk = JSON.parse(key);
264
+ return { fetch: (input, init) => signedFetch(input, init, { privateJwk, directory }) };
1791
265
  }
1792
- function constantTimeEqual(a, b) {
1793
- if (a.length !== b.length) return false;
1794
- let difference = 0;
1795
- for (let index = 0; index < a.length; index += 1) {
1796
- difference |= a.charCodeAt(index) ^ b.charCodeAt(index);
1797
- }
1798
- return difference === 0;
266
+ export { generateAgentKey };
267
+ async function hmacHex(secret, message) {
268
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
269
+ const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message)));
270
+ return Array.from(mac, (byte) => byte.toString(16).padStart(2, '0')).join('');
1799
271
  }
1800
-
1801
- // src/stream.ts
1802
- async function* streamEvents(options) {
1803
- const base = (options.baseUrl ?? "https://pidgeon.ai/api/v1").replace(/\/$/, "");
1804
- let lastEventId;
1805
- let backoffMs = 1e3;
1806
- while (!options.signal?.aborted) {
1807
- const url = new URL(`${base}/events/stream`);
1808
- if (options.identityId) url.searchParams.set("identity_id", options.identityId);
1809
- if (options.type) url.searchParams.set("type", options.type);
1810
- if (options.after && !lastEventId) url.searchParams.set("after", options.after);
1811
- let response;
1812
- try {
1813
- response = await fetch(url, {
1814
- headers: {
1815
- authorization: `Bearer ${options.apiKey}`,
1816
- accept: "text/event-stream",
1817
- ...lastEventId ? { "last-event-id": lastEventId } : {}
1818
- },
1819
- signal: options.signal
1820
- });
1821
- } catch {
1822
- if (options.signal?.aborted) return;
1823
- await sleep(backoffMs, options.signal);
1824
- backoffMs = Math.min(backoffMs * 2, 3e4);
1825
- continue;
1826
- }
1827
- if (response.status === 401 || response.status === 403 || response.status === 404) {
1828
- throw new Error(
1829
- `Pidgeon refused the stream: ${response.status} ${await response.text().catch(() => "")}`.trim()
1830
- );
272
+ /**
273
+ * Check a webhook's `Pidgeon-Signature` header against your endpoint's secret
274
+ * and return the event, or throw. Pass the raw body as received, before any
275
+ * JSON parsing. Signatures older than `toleranceSeconds` are refused, so a
276
+ * captured delivery cannot be replayed later.
277
+ */
278
+ export async function verifyWebhook(secret, rawBody, signatureHeader, options = {}) {
279
+ const parts = Object.fromEntries((signatureHeader ?? '').split(',').map((part) => part.trim().split('=')));
280
+ const timestamp = Number(parts.t);
281
+ if (!Number.isInteger(timestamp) || typeof parts.v1 !== 'string') {
282
+ throw new PidgeonError(400, 'invalid_signature', 'The Pidgeon-Signature header is missing or malformed.');
1831
283
  }
1832
- if (!response.ok || !response.body) {
1833
- await sleep(backoffMs, options.signal);
1834
- backoffMs = Math.min(backoffMs * 2, 3e4);
1835
- continue;
284
+ const now = Math.floor((options.now ?? new Date()).getTime() / 1000);
285
+ if (Math.abs(now - timestamp) > (options.toleranceSeconds ?? 300)) {
286
+ throw new PidgeonError(400, 'stale_signature', 'The webhook was signed too long ago.');
1836
287
  }
1837
- backoffMs = 1e3;
1838
- try {
1839
- for await (const frame of frames(response.body, options.signal)) {
1840
- if (frame.id) lastEventId = frame.id;
1841
- if (!frame.data) continue;
1842
- if (frame.event === "error") continue;
1843
- let parsed;
1844
- try {
1845
- parsed = JSON.parse(frame.data);
1846
- } catch {
1847
- continue;
1848
- }
1849
- yield parsed;
1850
- }
1851
- } catch {
1852
- if (options.signal?.aborted) return;
1853
- await sleep(backoffMs, options.signal);
1854
- backoffMs = Math.min(backoffMs * 2, 3e4);
1855
- }
1856
- }
1857
- }
1858
- async function* frames(body, signal) {
1859
- const reader = body.getReader();
1860
- const decoder = new TextDecoder();
1861
- let buffer = "";
1862
- try {
1863
- while (!signal?.aborted) {
1864
- const { done, value } = await reader.read();
1865
- if (done) return;
1866
- buffer += decoder.decode(value, { stream: true });
1867
- let boundary = buffer.indexOf("\n\n");
1868
- while (boundary !== -1) {
1869
- const block = buffer.slice(0, boundary);
1870
- buffer = buffer.slice(boundary + 2);
1871
- boundary = buffer.indexOf("\n\n");
1872
- const frame = {};
1873
- const data = [];
1874
- for (const line of block.split("\n")) {
1875
- if (line.startsWith(":")) continue;
1876
- const colon = line.indexOf(":");
1877
- if (colon === -1) continue;
1878
- const field = line.slice(0, colon);
1879
- const value2 = line.slice(colon + 1).replace(/^ /, "");
1880
- if (field === "id") frame.id = value2;
1881
- else if (field === "event") frame.event = value2;
1882
- else if (field === "data") data.push(value2);
1883
- }
1884
- if (data.length > 0) frame.data = data.join("\n");
1885
- if (frame.id || frame.data) yield frame;
1886
- }
1887
- }
1888
- } finally {
1889
- await reader.cancel().catch(() => void 0);
1890
- }
1891
- }
1892
- function sleep(ms, signal) {
1893
- return new Promise((resolve) => {
1894
- const timer = setTimeout(resolve, ms);
1895
- signal?.addEventListener(
1896
- "abort",
1897
- () => {
1898
- clearTimeout(timer);
1899
- resolve();
1900
- },
1901
- { once: true }
1902
- );
1903
- });
288
+ const expected = await hmacHex(secret, `${timestamp}.${rawBody}`);
289
+ let same = expected.length === parts.v1.length;
290
+ for (let i = 0; i < expected.length; i++)
291
+ same = same && expected[i] === parts.v1[i];
292
+ if (!same)
293
+ throw new PidgeonError(400, 'invalid_signature', 'The webhook signature does not match.');
294
+ return JSON.parse(rawBody);
1904
295
  }
1905
- export {
1906
- SIGNATURE_HEADER,
1907
- TIMESTAMP_HEADER,
1908
- agentAttachHuman,
1909
- agentConnect,
1910
- agentSetup,
1911
- agentSignUp,
1912
- agentVerify,
1913
- appPasswordsCreate,
1914
- appPasswordsList,
1915
- appPasswordsRevoke,
1916
- attachmentsCompleteUpload,
1917
- attachmentsCreateUpload,
1918
- attachmentsDownloadUrl,
1919
- attachmentsText,
1920
- attachmentsUpload,
1921
- calendarCreateEvent,
1922
- calendarDeleteEvent,
1923
- calendarFreeTime,
1924
- calendarGet,
1925
- calendarGetAgenda,
1926
- calendarGetEvent,
1927
- calendarListEventInstances,
1928
- calendarListEvents,
1929
- calendarRespondToEvent,
1930
- calendarUpdate,
1931
- calendarUpdateEvent,
1932
- cardsGet,
1933
- client,
1934
- contactsBlock,
1935
- contactsCreate,
1936
- contactsDelete,
1937
- contactsGet,
1938
- contactsList,
1939
- contactsUnblock,
1940
- contactsUpdate,
1941
- createClient,
1942
- createConfig,
1943
- domainsCreate,
1944
- domainsDelete,
1945
- domainsGet,
1946
- domainsGetSetupLink,
1947
- domainsList,
1948
- domainsUpdate,
1949
- domainsVerify,
1950
- domainsZoneFile,
1951
- draftsApproval,
1952
- draftsCancelSchedule,
1953
- draftsCreate,
1954
- draftsDelete,
1955
- draftsGet,
1956
- draftsList,
1957
- draftsRemoveAttachment,
1958
- draftsSchedule,
1959
- draftsSend,
1960
- draftsUpdate,
1961
- eventsGet,
1962
- eventsList,
1963
- eventsSocket,
1964
- eventsStream,
1965
- exportMail,
1966
- grantsCreate,
1967
- grantsGet,
1968
- grantsList,
1969
- grantsRevoke,
1970
- grantsStatus,
1971
- grantsTemplatesCreate,
1972
- grantsTemplatesDelete,
1973
- grantsTemplatesList,
1974
- identitiesAccessCreate,
1975
- identitiesAccessDelete,
1976
- identitiesAccessGet,
1977
- identitiesCard,
1978
- identitiesCreate,
1979
- identitiesDelete,
1980
- identitiesGet,
1981
- identitiesList,
1982
- identitiesReceiveRulesCreate,
1983
- identitiesReceiveRulesDelete,
1984
- identitiesReceiveRulesGet,
1985
- identitiesSendRulesCreate,
1986
- identitiesSendRulesDelete,
1987
- identitiesSendRulesGet,
1988
- identitiesSuspendTenant,
1989
- identitiesUpdate,
1990
- keysCreate,
1991
- keysGet,
1992
- keysList,
1993
- keysRevoke,
1994
- keysRotate,
1995
- keysUpdate,
1996
- labelsCreate,
1997
- labelsDelete,
1998
- labelsList,
1999
- labelsUpdate,
2000
- logCheckpoint,
2001
- logConsistency,
2002
- logEntries,
2003
- logHead,
2004
- logMonitorsCreate,
2005
- logMonitorsDelete,
2006
- logMonitorsList,
2007
- logProof,
2008
- mailboxesChanges,
2009
- mailboxesEmptyTrash,
2010
- mailboxesList,
2011
- mailboxesListFolder,
2012
- meGet,
2013
- messagesAct,
2014
- messagesAwait,
2015
- messagesCheck,
2016
- messagesForward,
2017
- messagesGet,
2018
- messagesListInThread,
2019
- messagesRaw,
2020
- messagesReply,
2021
- messagesReplyAll,
2022
- messagesRespondToInvitation,
2023
- messagesSearch,
2024
- messagesSend,
2025
- messagesUndo,
2026
- messagesUpdate,
2027
- metricsQuery,
2028
- podsCreate,
2029
- podsDelete,
2030
- podsGet,
2031
- podsList,
2032
- podsUpdate,
2033
- routingCreate,
2034
- routingDelete,
2035
- routingList,
2036
- routingUpdate,
2037
- signInsApprove,
2038
- streamEvents,
2039
- testInbound,
2040
- threadsGet,
2041
- threadsLabelsCreate,
2042
- threadsLabelsDelete,
2043
- threadsLabelsGet,
2044
- threadsList,
2045
- threadsUpdate,
2046
- verifySender,
2047
- verifyWebhook,
2048
- webhooksCreate,
2049
- webhooksDelete,
2050
- webhooksDeliveries,
2051
- webhooksGet,
2052
- webhooksGetHeaders,
2053
- webhooksList,
2054
- webhooksReplay,
2055
- webhooksUpdate,
2056
- webhooksUpdateHeaders,
2057
- workspaceGet,
2058
- workspaceMembers
2059
- };
2060
- //# sourceMappingURL=index.js.map