loopzero-gateway 0.0.0-stage → 0.1.1

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.cjs ADDED
@@ -0,0 +1,2976 @@
1
+ 'use strict';
2
+
3
+ var loopzeroSdk = require('loopzero-sdk');
4
+ var readline = require('readline');
5
+ var crypto = require('crypto');
6
+ var fs = require('fs');
7
+ var path = require('path');
8
+ var promises = require('fs/promises');
9
+
10
+ // src/delivery/attachments.ts
11
+ function attachmentsOf(attachments) {
12
+ return attachments != null && attachments.length !== 0 ? { attachments } : {};
13
+ }
14
+ function refuseUnsupportedAttachments(adapter, outbound) {
15
+ const { attachments } = outbound;
16
+ if (adapter.supportsAttachments || attachments == null || attachments.length === 0) {
17
+ return void 0;
18
+ }
19
+ return {
20
+ ok: false,
21
+ error: {
22
+ code: "attachments_unsupported",
23
+ message: `${adapter.platform} adapter cannot send attachments`
24
+ }
25
+ };
26
+ }
27
+ var UNCOVERED_TABLE = `gateway-qq \`appSecret\` :: a QQ Bot AppSecret, an opaque 32-character string with no prefix or fixed shape. It travels only to the access-token endpoint and into the webhook signature derivation; the adapter never logs it.
28
+ gateway-x \`clientSecret\`, \`refreshToken\`, \`bearerToken\` :: an X OAuth 2.0 client secret, a rotating refresh token and an app bearer token, opaque strings with no fixed prefix. They travel only to the X API in Authorization headers and the token request body, which the adapter never logs.
29
+ gateway-buzz \`token\` :: a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs.
30
+ gateway-clickclack \`token\` :: a ClickClack bot token (\`ccb_\` prefix) or session token with no fixed shape for the latter. It travels only in Authorization headers, which the adapter never logs.
31
+ gateway-zalo \`accessToken\`, \`oaSecretKey\` :: a Zalo Official Account access token and OA secret key: opaque strings with no prefix or fixed shape to recognise. The token travels only in an \`access_token\` header and the key only into the signature check, and the adapter never logs either.
32
+ gateway-wechat \`appSecret\`, \`token\` :: a WeChat Official Account AppSecret (32 hex characters, indistinguishable from any other hex string) and the server-URL verification token (a string the operator chooses). The secret travels only to the access-token endpoint and the token only into the signature check; the adapter never logs either.
33
+ gateway-wecom \`corpSecret\`, \`token\`, \`encodingAesKey\` :: a WeCom application Secret (43 URL-safe base64 characters, indistinguishable from other opaque strings), the callback Token (a string the operator chooses) and the EncodingAESKey (43 base64 characters). The secret travels only to the access-token endpoint, the token into the signature check and the key into the decryption; the adapter never logs any of them.
34
+ gateway-yuanbao \`appSecret\`, \`callbackSecret\` :: a Yuanbao bot AppSecret and the callback signing secret, both opaque strings with no prefix or fixed shape. The app secret travels only to the access-token endpoint and the callback secret only into the signature check; the adapter never logs either.
35
+ gateway-zalo-personal \`credentials\` :: a Zalo web session: a cookie jar, an IMEI-like device id and a user agent. The cookie has no prefix or fixed shape to recognise. It travels only to the Zalo library, which the adapter never logs.
36
+ gateway-twitch \`accessToken\` :: 30 lowercase alphanumerics with no prefix, the shape of many ids and hashes in a log. It travels only in Authorization headers, which the adapter never logs.
37
+ gateway-tlon-urbit \`code\` :: a +code is four dash-joined phonemic syllable words, the same shape as an Urbit ship name such as ~sampel-palnet-sampel-palnet, which the logs exist to show. It travels only in the /~/login body, which the adapter never logs.
38
+ gateway-synology-chat \`botToken\` and \`incomingUrl\` :: a bot token is a random string the NAS generates with no prefix, and the Incoming URL carries its own token as a query parameter of an ordinary entry.cgi URL. Neither has a shape to claim without eating ordinary ids and URLs; the adapter never logs the URL, and refuses a callback token before reading it.
39
+ gateway-feishu-lark \`appSecret\` :: 32 alphanumerics with no prefix, the shape of many tokens and hashes; it travels only in the body of the tenant-token request, which the adapter never logs.
40
+ gateway-nostr \`secretKey\` (64-hex form) :: 64 hex characters is also every Nostr public key and event id, which the logs exist to show, and a sha256 digest. The nsec1 spelling of the same key is masked above.
41
+ gateway-sms \`authToken\` (Twilio), gateway-line \`channelSecret\` :: 32 lowercase hex characters, which is also an md5 digest, a dashless UUID and half a git tree hash. Masking it would eat the correlation id a developer reads the log to find.
42
+ gateway-mattermost \`accessToken\` :: 26 lowercase alphanumerics, which is exactly a lowercase ULID \u2014 the shape of most trace ids.
43
+ gateway-email \`password\`, gateway-sms \`apiSecret\` and \`signatureSecret\` (Vonage) :: no format of their own; a passphrase is indistinguishable from prose. The SDK's own \`key=value\` rule already masks these fully wherever they appear as \`field=value\`, and adding a pattern here made that WORSE by claiming the value first \u2014 it was masked as first6\u2026last4 instead of removed.
44
+ gateway-slack \`botToken\` :: already masked by one of the SDK's own twelve built-in patterns \u2014 \`xoxb-\` is Slack's and the SDK knows it. A pattern here would be a second one doing the first's work, and the field-level gate flagged its absence, which is the gate working.
45
+ gateway-whatsapp \`appSecret\` :: 32 lowercase hex, the same shape as the Twilio auth token above and as every md5 and dashless UUID. Masking it would eat the correlation ids in a log.
46
+ gateway-nextcloud-talk \`secret\` :: a Talk bot secret is a string of 40 to 128 characters the administrator chose for \`occ talk:bot:install\`, with no prefix or format to recognise. It never travels: both sides send only an HMAC made with it, and the adapter never logs it.
47
+ gateway-irc \`password\` and \`saslPassword\` :: a server password and a NickServ password are passphrases the operator chose, with no format to recognise. The SDK's \`key=value\` rule masks them as fields wherever they appear as \`password=...\`; the SASL payload on the wire is their base64, which the adapter never logs.
48
+ gateway-google-chat \`privateKey\` :: a PEM block spans lines, and in a log it usually arrives inside a JSON string with its line breaks escaped as \\n, which no single-line shape can claim whole. The SDK's \`key=value\` rule masks it as a field wherever it appears as \`private_key=...\` or \`privateKey=...\`.
49
+ gateway-line \`channelAccessToken\`, gateway-sms \`authToken\` (Plivo) :: long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message.`;
50
+ function parseUncovered(table) {
51
+ return table.split("\n").map((row) => {
52
+ const [field = "", why = ""] = row.split(" :: ");
53
+ return { field, why };
54
+ });
55
+ }
56
+ var CREDENTIAL_SHAPES = {
57
+ covered: [
58
+ {
59
+ field: "gateway-telegram `token`",
60
+ pattern: /(?<![A-Za-z0-9])\d{8,10}:[A-Za-z0-9_-]{35}(?![A-Za-z0-9_-])/g,
61
+ alsoMatches: "an 8-10 digit number joined by a colon to exactly 35 url-safe characters \u2014 a timestamped identifier of that exact width would be masked"
62
+ },
63
+ {
64
+ field: "gateway-discord `token`",
65
+ pattern: /(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{23,28}\.[A-Za-z0-9_-]{6,7}\.[A-Za-z0-9_-]{27,}(?![A-Za-z0-9_-])/g,
66
+ alsoMatches: "a three-part dotted identifier of those widths; a JWT's middle part is longer"
67
+ },
68
+ {
69
+ field: "gateway-slack `appToken`",
70
+ pattern: /(?<![A-Za-z0-9-])xapp-\d-[A-Z0-9]+-\d+-[a-f0-9]{32,}(?![a-f0-9])/g,
71
+ alsoMatches: "nothing plausible \u2014 the `xapp-` prefix and the shape are Slack's"
72
+ },
73
+ {
74
+ field: "gateway-matrix `accessToken`",
75
+ pattern: /(?<![A-Za-z0-9_])syt_[A-Za-z0-9_-]+_[A-Za-z0-9_-]+_[A-Za-z0-9]+(?![A-Za-z0-9_-])/g,
76
+ alsoMatches: "nothing plausible \u2014 `syt_` is Matrix's own prefix"
77
+ },
78
+ {
79
+ field: "gateway-whatsapp `accessToken`",
80
+ pattern: /(?<![A-Za-z0-9])EAA[A-Za-z0-9]{20,}(?![A-Za-z0-9])/g,
81
+ alsoMatches: "any identifier beginning EAA followed by 20 or more alphanumerics"
82
+ },
83
+ {
84
+ field: "gateway-teams `clientSecret`",
85
+ pattern: /(?<![A-Za-z0-9~])[A-Za-z0-9]{3}\d[A-Za-z0-9]?~[A-Za-z0-9._~-]{30,}(?![A-Za-z0-9._~-])/g,
86
+ alsoMatches: "an Entra-style secret is the only common value with a tilde in that position"
87
+ },
88
+ {
89
+ field: "gateway-nostr `secretKey` (nsec1 form)",
90
+ pattern: /(?<![a-z0-9])nsec1[02-9ac-hj-np-z]{58}(?![a-z0-9])/g,
91
+ alsoMatches: "nothing plausible \u2014 `nsec1` is NIP-19's prefix for a secret key"
92
+ }
93
+ ],
94
+ uncovered: parseUncovered(UNCOVERED_TABLE)
95
+ };
96
+ function maskShapes(text) {
97
+ let out = text;
98
+ for (const { pattern } of CREDENTIAL_SHAPES.covered) out = out.replace(pattern, "***");
99
+ return out;
100
+ }
101
+ function redactSecrets(value) {
102
+ return loopzeroSdk.Security.redact(maskShapes(typeof value === "string" ? value : String(value)));
103
+ }
104
+ function maskSecrets(text, secrets) {
105
+ const ordered = [...new Set(secrets)].filter((s) => s.length > 0).sort((a, b) => b.length - a.length);
106
+ let out = text;
107
+ for (const secret of ordered) out = out.split(secret).join("[redacted]");
108
+ return out;
109
+ }
110
+
111
+ // src/diagnostics.ts
112
+ function reportDiagnostic(tag, message, _options = {}) {
113
+ reportDiagnosticLine(`[${tag}] ${message}`);
114
+ }
115
+ function reportDiagnosticLine(line) {
116
+ process.stderr.write(`${redactSecrets(line)}
117
+ `);
118
+ }
119
+
120
+ // src/text/fence.ts
121
+ var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
122
+ var OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;
123
+ var CLOSING = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
124
+ function lineEndAt(text, from) {
125
+ let end = from;
126
+ while (end < text.length && text[end] !== "\n" && text[end] !== "\r") end += 1;
127
+ let next = end;
128
+ if (text[next] === "\r" && text[next + 1] === "\n") next += 2;
129
+ else if (next < text.length) next += 1;
130
+ return { end, next };
131
+ }
132
+ function findClose(text, from, run) {
133
+ for (let scan = from; scan < text.length; ) {
134
+ const line = lineEndAt(text, scan);
135
+ const found = CLOSING.exec(text.slice(scan, line.end))?.[1];
136
+ if (found !== void 0 && found[0] === run[0] && found.length >= run.length) return line;
137
+ scan = line.next;
138
+ }
139
+ return void 0;
140
+ }
141
+ function scanFences(text) {
142
+ if (!MAY_FENCE.test(text)) return [];
143
+ const regions = [];
144
+ let pos = 0;
145
+ while (pos < text.length) {
146
+ const start = pos;
147
+ const line = lineEndAt(text, start);
148
+ const open = OPENING.exec(text.slice(start, line.end));
149
+ const run = open?.[1];
150
+ if (run === void 0 || run.startsWith("`") && (open?.[2] ?? "").includes("`")) {
151
+ pos = line.next;
152
+ continue;
153
+ }
154
+ const close = findClose(text, line.next, run);
155
+ pos = close?.next ?? text.length;
156
+ const end = close?.end ?? text.length;
157
+ const closed = close !== void 0;
158
+ regions.push({
159
+ start,
160
+ openerEnd: line.end,
161
+ contentStart: line.next,
162
+ end,
163
+ opener: text.slice(start, line.end),
164
+ closer: run,
165
+ closed
166
+ });
167
+ }
168
+ return regions;
169
+ }
170
+ function fenceAt(regions, offset) {
171
+ return regions.find((r) => r.start < offset && offset < r.end);
172
+ }
173
+ function openerEol(text, region) {
174
+ if (text.startsWith("\r\n", region.openerEnd)) return "\r\n";
175
+ return text[region.openerEnd] === "\r" ? "\r" : "\n";
176
+ }
177
+
178
+ // src/text/dialect.ts
179
+ var DIALECTS = {
180
+ // WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
181
+ whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
182
+ // LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
183
+ line: {},
184
+ // SMS is plain text by definition of the medium.
185
+ sms: {}
186
+ };
187
+ var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
188
+ var GROUP_MARKERS = [
189
+ ["bold", "bold"],
190
+ ["strike", "strike"],
191
+ ["italicStar", "italic"],
192
+ ["italicUnderscore", "italic"],
193
+ ["code", "code"]
194
+ ];
195
+ function toDialect(text, platform) {
196
+ const dialect = DIALECTS[platform];
197
+ if (dialect === void 0) return text;
198
+ return rewriteMarkers(text, dialect);
199
+ }
200
+ function markerFor(matched, groups, dialect) {
201
+ if (groups === void 0) return matched;
202
+ for (const [group, marker] of GROUP_MARKERS) {
203
+ const content = groups[group];
204
+ if (content === void 0) continue;
205
+ const wrap = dialect[marker];
206
+ return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
207
+ }
208
+ return matched;
209
+ }
210
+ function rewriteMatch(matched, args, dialect) {
211
+ return markerFor(matched, args.at(-1), dialect);
212
+ }
213
+ function replaceMarkers(text, dialect) {
214
+ return text.replace(PATTERN, (matched, ...args) => rewriteMatch(matched, args, dialect));
215
+ }
216
+ var ROW_START = /[^\S\r\n]*\|/y;
217
+ var LINE_ENDING = /(\r\n|\r|\n)/;
218
+ var MARKER_CHARACTER = /[*_~\x60]/;
219
+ var PIPE = 124;
220
+ var BACKSLASH = 92;
221
+ var LF = 10;
222
+ var CR = 13;
223
+ function rowLocator(text) {
224
+ const rowStart = new RegExp(ROW_START);
225
+ let lineStart = 0;
226
+ let scanned = 0;
227
+ return (offset) => {
228
+ for (; scanned < offset; scanned += 1) {
229
+ const code = text.charCodeAt(scanned);
230
+ if (code === LF || code === CR) lineStart = scanned + 1;
231
+ }
232
+ rowStart.lastIndex = lineStart;
233
+ return rowStart.test(text);
234
+ };
235
+ }
236
+ function rewriteTableRow(row, dialect) {
237
+ let out = "";
238
+ let from = 0;
239
+ let backslashes = 0;
240
+ for (let i = 0; i < row.length; i += 1) {
241
+ const code = row.charCodeAt(i);
242
+ if (code === BACKSLASH) {
243
+ backslashes += 1;
244
+ continue;
245
+ }
246
+ if (code === PIPE && backslashes % 2 === 0) {
247
+ out += `${replaceMarkers(row.slice(from, i), dialect)}|`;
248
+ from = i + 1;
249
+ }
250
+ backslashes = 0;
251
+ }
252
+ return out + replaceMarkers(row.slice(from), dialect);
253
+ }
254
+ function rewriteLine(line, dialect, rowStart) {
255
+ rowStart.lastIndex = 0;
256
+ if (!rowStart.test(line)) return replaceMarkers(line, dialect);
257
+ return MARKER_CHARACTER.test(line) ? rewriteTableRow(line, dialect) : line;
258
+ }
259
+ function rewriteByLine(text, dialect) {
260
+ const rowStart = new RegExp(ROW_START);
261
+ return text.split(LINE_ENDING).map((piece) => rewriteLine(piece, dialect, rowStart)).join("");
262
+ }
263
+ function rewriteMarkers(text, dialect) {
264
+ const regions = scanFences(text);
265
+ if (regions.length === 0) return rewriteUnfenced(text, dialect);
266
+ let out = "";
267
+ let from = 0;
268
+ for (const region of regions) {
269
+ out += rewriteUnfenced(text.slice(from, region.start), dialect) + text.slice(region.start, region.end);
270
+ from = region.end;
271
+ }
272
+ return out + rewriteUnfenced(text.slice(from), dialect);
273
+ }
274
+ function rewriteUnfenced(text, dialect) {
275
+ const onTableRow = rowLocator(text);
276
+ let crossesRowPipe = false;
277
+ const rewritten = text.replace(PATTERN, (matched, ...args) => {
278
+ if (!crossesRowPipe && matched.includes("|")) {
279
+ crossesRowPipe = onTableRow(args.at(-3));
280
+ }
281
+ return rewriteMatch(matched, args, dialect);
282
+ });
283
+ return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
284
+ }
285
+
286
+ // src/text/channel-rendering.ts
287
+ var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
288
+ var STRIP = {};
289
+ var identity = (text) => text;
290
+ var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
291
+ var RENDERINGS = {
292
+ whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
293
+ slack: { format: "markdown", translate: translateWith(SLACK) },
294
+ discord: { format: "markdown", translate: identity },
295
+ mattermost: { format: "markdown", translate: identity },
296
+ teams: { format: "markdown", translate: identity },
297
+ signal: { format: "markdown", translate: identity },
298
+ line: { format: "plain", translate: translateWith(DIALECTS.line) },
299
+ sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
300
+ telegram: { format: "plain", translate: translateWith(STRIP) },
301
+ matrix: { format: "plain", translate: translateWith(STRIP) },
302
+ email: { format: "plain", translate: translateWith(STRIP) },
303
+ imessage: { format: "plain", translate: translateWith(STRIP) },
304
+ google_chat: { format: "plain", translate: translateWith(STRIP) },
305
+ irc: { format: "plain", translate: translateWith(STRIP) },
306
+ nextcloud_talk: { format: "markdown", translate: identity },
307
+ nostr: { format: "plain", translate: translateWith(STRIP) },
308
+ feishu_lark: { format: "plain", translate: translateWith(STRIP) },
309
+ synology_chat: { format: "plain", translate: translateWith(STRIP) },
310
+ tlon_urbit: { format: "plain", translate: translateWith(STRIP) },
311
+ twitch: { format: "plain", translate: translateWith(STRIP) },
312
+ buzz: { format: "plain", translate: translateWith(STRIP) },
313
+ clickclack: { format: "plain", translate: translateWith(STRIP) },
314
+ zalo_personal: { format: "plain", translate: translateWith(STRIP) },
315
+ zalo: { format: "plain", translate: translateWith(STRIP) },
316
+ wechat: { format: "plain", translate: translateWith(STRIP) },
317
+ wecom: { format: "plain", translate: translateWith(STRIP) },
318
+ yuanbao: { format: "plain", translate: translateWith(STRIP) },
319
+ qq: { format: "plain", translate: translateWith(STRIP) },
320
+ x: { format: "plain", translate: translateWith(STRIP) },
321
+ raft: { format: "plain", translate: translateWith(STRIP) }
322
+ };
323
+ function channelRendering(platform) {
324
+ const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
325
+ if (rendering === void 0) {
326
+ throw new RangeError(
327
+ `channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
328
+ );
329
+ }
330
+ return rendering;
331
+ }
332
+
333
+ // src/adapter/base.ts
334
+ var BasePlatformAdapter = class _BasePlatformAdapter {
335
+ /**
336
+ * Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.
337
+ *
338
+ * A handler is USER code and may throw. An adapter must contain that throw, name it as the
339
+ * handler's failure rather than the platform's, and keep delivering — one bad message ends
340
+ * neither the process nor the connection. Two adapters once discarded the rejection with `void`,
341
+ * which under Node's default ends the process; two more reported it as a platform-client error,
342
+ * sending whoever debugged their own handler to the wrong repository (#41).
343
+ *
344
+ * Ten copies of that knowledge is ten chances to get it wrong, so it lives here. The platform tag
345
+ * is taken from `this.platform`, which is the only part that differed between them.
346
+ */
347
+ async runHandler(handler, event) {
348
+ if (handler === void 0) return "no_handler";
349
+ try {
350
+ await handler(event);
351
+ } catch (err) {
352
+ const message = err instanceof Error ? err.message : String(err);
353
+ reportDiagnostic(this.platform, `handler threw: ${message}`, { });
354
+ return "handler_threw";
355
+ }
356
+ return "ok";
357
+ }
358
+ /** The handler {@link subscribe} holds; `undefined` while nobody is subscribed. */
359
+ subscribedHandler;
360
+ /** The body of {@link onInbound}: replace the handler, and unsubscribe only if it is still the one held. */
361
+ subscribe(handler) {
362
+ this.subscribedHandler = handler;
363
+ return () => {
364
+ if (this.subscribedHandler === handler) this.subscribedHandler = void 0;
365
+ };
366
+ }
367
+ /** The body of {@link deliver} for an adapter that subscribed through {@link subscribe}. */
368
+ deliverInbound(event) {
369
+ return this.runHandler(this.subscribedHandler, event);
370
+ }
371
+ /**
372
+ * Dispatch a webhook event once: `duplicate` when `seen` holds its id, `no_handler` when nobody
373
+ * subscribed (the id is then NOT remembered, so a redelivery is handled), otherwise remember the
374
+ * id and run the handler. A handler's throw is also logged under `label`.
375
+ */
376
+ async dispatchOnce(seen, event, label) {
377
+ if (seen.has(event.id)) return "duplicate";
378
+ if (this.subscribedHandler === void 0) return "no_handler";
379
+ seen.add(event.id);
380
+ const outcome = await this.runHandler(this.subscribedHandler, event);
381
+ if (outcome === "handler_threw") reportDiagnostic(label, "handler threw", { });
382
+ return outcome;
383
+ }
384
+ /** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */
385
+ outboundText(out) {
386
+ return out.format === "markdown" ? channelRendering(this.platform).translate(out.text) : out.text;
387
+ }
388
+ /**
389
+ * `attachments_unsupported` when `out` carries attachments and this adapter does not declare
390
+ * `supportsAttachments`, otherwise `undefined`. Call it first in `sendMessage`.
391
+ */
392
+ refuseAttachments(out) {
393
+ return refuseUnsupportedAttachments(this, out);
394
+ }
395
+ /**
396
+ * The local checks every text-only `sendMessage` makes before a request, in this order:
397
+ * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
398
+ * Returns the refusal, or `undefined` when the message may be sent.
399
+ */
400
+ refuseUnsendable(out, check2) {
401
+ const refuse = (code, message) => ({
402
+ ok: false,
403
+ error: { code, message }
404
+ });
405
+ if (out.text.length === 0) return refuse("empty_text", "outbound text is empty");
406
+ if (!check2.connected) {
407
+ return refuse("not_connected", `${check2.className}.connect() has not succeeded`);
408
+ }
409
+ if (check2.channel !== void 0 && !check2.channel.valid(out.channel.id)) {
410
+ return refuse("invalid_channel", check2.channel.message);
411
+ }
412
+ return void 0;
413
+ }
414
+ /**
415
+ * Whether {@link editMessage} can replace the text of a message this adapter sent.
416
+ *
417
+ * Read it before starting a preview: on `false`, send the final text instead. An adapter sets
418
+ * it at construction and MUST NOT change it with `connect()`. Annotated as `boolean` so that an
419
+ * edit-capable adapter can override it with `true`.
420
+ */
421
+ supportsEdit = false;
422
+ /**
423
+ * Whether {@link sendMessage} can send the images of `out.attachments` (B-674).
424
+ *
425
+ * Read it before attaching: on `false`, the adapter refuses a non-empty list with
426
+ * `attachments_unsupported`. Set at construction, never changed by `connect()`. Annotated as
427
+ * `boolean` so that an adapter that sends images can override it with `true`.
428
+ */
429
+ supportsAttachments = false;
430
+ /**
431
+ * The attachment kinds {@link sendMessage} can send. `undefined` means "not declared": the
432
+ * `capabilities` getter then reports `["image"]` when `supportsAttachments` is `true`, else `[]`.
433
+ */
434
+ attachmentKinds = void 0;
435
+ /**
436
+ * What this adapter can do, for an app that renders differently per channel.
437
+ *
438
+ * Derived from the members above and from which lifecycle methods the subclass overrides; an
439
+ * adapter overrides the getter only for what derivation cannot know. Read it at call time.
440
+ */
441
+ get capabilities() {
442
+ const proto = _BasePlatformAdapter.prototype;
443
+ return {
444
+ edit: this.supportsEdit,
445
+ attachments: this.attachmentKinds ?? (this.supportsAttachments ? ["image"] : []),
446
+ typing: this.startTyping !== proto.startTyping,
447
+ reactions: this.react !== proto.react,
448
+ threads: false
449
+ };
450
+ }
451
+ /**
452
+ * Replace the text of a message this adapter sent, keeping its id.
453
+ *
454
+ * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
455
+ * throws on platform errors. An edit-capable adapter applies, with no request, the same local
456
+ * checks its `sendMessage` applies (such as `empty_text`, and `not_connected` where the send
457
+ * checks the connection), plus `invalid_message_id`, and `edit_too_long` where the adapter
458
+ * splits text: an edit that would need more than one platform message is refused, never split.
459
+ *
460
+ * Default: refuses with `edit_unsupported`, makes no platform call, and checks nothing else
461
+ * first, so capability is answered before input.
462
+ */
463
+ async editMessage(_messageId, _out) {
464
+ return {
465
+ ok: false,
466
+ error: {
467
+ code: "edit_unsupported",
468
+ message: `${this.platform} adapter cannot edit a sent message`
469
+ }
470
+ };
471
+ }
472
+ /**
473
+ * React to an inbound message with an emoji (for example 👀 as an acknowledgement).
474
+ *
475
+ * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
476
+ * throws on platform errors. `channelId` is the channel the message is in and `messageId` the
477
+ * id the inbound event carried.
478
+ *
479
+ * Default: resolves `{ ok: false, error: { code: "react_unsupported" } }` and makes no
480
+ * platform call.
481
+ */
482
+ async react(_channelId, _messageId, _emoji) {
483
+ return {
484
+ ok: false,
485
+ error: {
486
+ code: "react_unsupported",
487
+ message: `${this.platform} adapter cannot react to a message`
488
+ }
489
+ };
490
+ }
491
+ /** Lifecycle: emit a typing indicator. Default: noop. */
492
+ async startTyping(_channelId) {
493
+ }
494
+ /** Lifecycle: stop the typing indicator. Default: noop. */
495
+ async stopTyping(_channelId) {
496
+ }
497
+ };
498
+ function parseMessage(line, onSkip) {
499
+ if (line.trim() === "") return void 0;
500
+ let value;
501
+ try {
502
+ value = JSON.parse(line);
503
+ } catch {
504
+ onSkip(line.slice(0, 120));
505
+ return void 0;
506
+ }
507
+ const isObject = typeof value === "object" && value !== null && !Array.isArray(value);
508
+ return isObject ? value : void 0;
509
+ }
510
+ function outcomeOf(message) {
511
+ const { error } = message;
512
+ if (error === void 0) return { kind: "result", result: message.result };
513
+ return {
514
+ kind: "error",
515
+ code: error.code ?? 0,
516
+ message: error.message ?? "unknown JSON-RPC error",
517
+ ...error.data === void 0 ? {} : { data: error.data }
518
+ };
519
+ }
520
+ var JsonRpcLineClient = class {
521
+ /**
522
+ * @param child - the running child; the client attaches to its pipes and events
523
+ * @param label - the stderr tag, e.g. `gateway-signal`
524
+ * @param onNotification - called for every message that carries a method and no id
525
+ * @param onClosed - called once, when the child exits or fails
526
+ */
527
+ constructor(child, label, onNotification, onClosed) {
528
+ this.child = child;
529
+ this.label = label;
530
+ this.onNotification = onNotification;
531
+ this.onClosed = onClosed;
532
+ const lines = readline.createInterface({ input: child.stdout, crlfDelay: Number.POSITIVE_INFINITY });
533
+ lines.on("line", (line) => this.handleLine(line));
534
+ child.stderr.resume();
535
+ child.stdin.on("error", (err) => this.close(`stdin: ${err.message}`));
536
+ child.on("error", (err) => this.close(err.message));
537
+ child.on("close", (code, signal) => this.close(`exited with ${signal ?? `code ${code}`}`));
538
+ }
539
+ child;
540
+ label;
541
+ onNotification;
542
+ onClosed;
543
+ counter = 0;
544
+ pending = /* @__PURE__ */ new Map();
545
+ alive = true;
546
+ /** Send `method` and wait for its answer, at most `timeoutMs`. */
547
+ request(method, params, timeoutMs) {
548
+ if (!this.alive || !this.child.stdin.writable) return Promise.resolve({ kind: "disconnected" });
549
+ this.counter += 1;
550
+ const id = this.counter;
551
+ const frame = `${JSON.stringify({ jsonrpc: "2.0", method, params, id })}
552
+ `;
553
+ return new Promise((resolve) => {
554
+ const timer = setTimeout(() => this.settle(id, { kind: "timeout" }), timeoutMs);
555
+ this.pending.set(id, { settle: resolve, timer });
556
+ this.child.stdin.write(frame, (err) => {
557
+ if (err) this.close(`stdin: ${err.message}`);
558
+ });
559
+ });
560
+ }
561
+ /** Settle every pending request as `disconnected` and stop accepting new ones. Idempotent. */
562
+ close(reason) {
563
+ if (!this.alive) return;
564
+ this.alive = false;
565
+ for (const id of Array.from(this.pending.keys())) this.settle(id, { kind: "disconnected" });
566
+ this.onClosed(reason);
567
+ }
568
+ settle(id, outcome) {
569
+ const entry = this.pending.get(id);
570
+ if (entry === void 0) return;
571
+ clearTimeout(entry.timer);
572
+ this.pending.delete(id);
573
+ entry.settle(outcome);
574
+ }
575
+ handleLine(line) {
576
+ if (!this.alive) return;
577
+ const message = parseMessage(line, (excerpt) => {
578
+ process.stderr.write(`[${this.label}] skipped a stdout line that is not JSON: ${excerpt}
579
+ `);
580
+ });
581
+ if (message === void 0) return;
582
+ const { id, method } = message;
583
+ if (typeof method === "string" && (id === void 0 || id === null)) {
584
+ this.onNotification({ method, params: message.params });
585
+ } else if (typeof id === "number") {
586
+ this.settle(id, outcomeOf(message));
587
+ }
588
+ }
589
+ };
590
+
591
+ // src/adapter/send-error.ts
592
+ function parseRetryAfter(value, now) {
593
+ if (value == null) return void 0;
594
+ const v = value.trim();
595
+ if (/^\d+$/.test(v)) return Number(v) * 1e3;
596
+ if (!/[A-Za-z]/.test(v)) return void 0;
597
+ const at = Date.parse(v);
598
+ if (Number.isNaN(at)) return void 0;
599
+ return Math.max(0, at - now);
600
+ }
601
+ var STATUS_CODES = {
602
+ 429: "rate_limit",
603
+ 401: "auth_failed",
604
+ 403: "permission_denied",
605
+ 408: "timeout"
606
+ };
607
+ function codeForStatus(status) {
608
+ return STATUS_CODES[status] ?? (status >= 500 ? "server_error" : "platform_error");
609
+ }
610
+ function sendErrorFromHttp(status, message, options) {
611
+ if (!Number.isInteger(status) || status < 100 || status > 599) {
612
+ throw new RangeError(`status must be an integer in 100..599, got ${String(status)}`);
613
+ }
614
+ const code = codeForStatus(status);
615
+ const retryAfterMs = status === 429 ? parseRetryAfter(options?.retryAfter, (options?.now ?? Date.now)()) : void 0;
616
+ return {
617
+ ok: false,
618
+ error: {
619
+ code,
620
+ message,
621
+ ...retryAfterMs !== void 0 ? { retryAfterMs } : {},
622
+ ...options?.platformCode !== void 0 ? { platformCode: options.platformCode } : {}
623
+ }
624
+ };
625
+ }
626
+
627
+ // src/auth/token-cache.ts
628
+ function createTokenCache(options) {
629
+ const marginMs = options.marginMs ?? 6e4;
630
+ const defaultTtlS = options.defaultTtlS ?? 7200;
631
+ const now = options.now ?? Date.now;
632
+ let cached;
633
+ let pending;
634
+ let generation = 0;
635
+ const refresh = (signal) => {
636
+ const started = generation;
637
+ const run = (async () => {
638
+ const fetched = await options.fetchToken(signal);
639
+ const ttl = fetched.expiresInS !== void 0 && fetched.expiresInS > 0 ? fetched.expiresInS : defaultTtlS;
640
+ if (started === generation) {
641
+ cached = { value: fetched.value, expiresAt: now() + ttl * 1e3 };
642
+ }
643
+ return fetched.value;
644
+ })();
645
+ const tracked = run.finally(() => {
646
+ if (pending === tracked) pending = void 0;
647
+ });
648
+ pending = tracked;
649
+ return tracked;
650
+ };
651
+ return {
652
+ get(opts) {
653
+ if (opts?.force !== true && cached !== void 0 && cached.expiresAt - marginMs > now()) {
654
+ return Promise.resolve(cached.value);
655
+ }
656
+ return pending ?? refresh(opts?.signal);
657
+ },
658
+ clear() {
659
+ generation += 1;
660
+ cached = void 0;
661
+ pending = void 0;
662
+ }
663
+ };
664
+ }
665
+
666
+ // src/text/seen-ids.ts
667
+ var DEFAULT_LIMIT = 1e3;
668
+ var SeenIds = class {
669
+ /** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
670
+ constructor(limit = DEFAULT_LIMIT) {
671
+ this.limit = limit;
672
+ }
673
+ limit;
674
+ ids = /* @__PURE__ */ new Set();
675
+ /**
676
+ * Record `id`.
677
+ *
678
+ * @returns `true` when the id was new, `false` when it was already held
679
+ */
680
+ add(id) {
681
+ if (this.ids.has(id)) return false;
682
+ this.ids.add(id);
683
+ if (this.ids.size > this.limit) {
684
+ const oldest = this.ids.values().next().value;
685
+ if (oldest !== void 0) this.ids.delete(oldest);
686
+ }
687
+ return true;
688
+ }
689
+ /** Whether `id` is held. */
690
+ has(id) {
691
+ return this.ids.has(id);
692
+ }
693
+ /** How many ids are held. */
694
+ get size() {
695
+ return this.ids.size;
696
+ }
697
+ };
698
+
699
+ // src/adapter/weixin-xml.ts
700
+ function parseFlatXml(xml) {
701
+ const out = {};
702
+ const tag = /<([A-Za-z][A-Za-z0-9]*)>(?:<!\[CDATA\[([\s\S]*?)\]\]>|([^<]*))<\/\1>/g;
703
+ for (const m of xml.matchAll(tag)) {
704
+ const name = m[1];
705
+ if (name !== void 0 && name !== "xml") out[name] = m[2] ?? decodeEntities(m[3] ?? "");
706
+ }
707
+ return out;
708
+ }
709
+ function decodeEntities(s) {
710
+ return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
711
+ }
712
+
713
+ // src/adapter/weixin-base.ts
714
+ var REQUEST_TIMEOUT_MS = 3e4;
715
+ var defaultFetch = async (url, init) => {
716
+ const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
717
+ return { status: res.status, text: () => res.text() };
718
+ };
719
+ function weixinMessageOf(err) {
720
+ return err instanceof Error ? err.message : String(err);
721
+ }
722
+ function weixinAck(reason) {
723
+ return { status: 200, body: "success", reason };
724
+ }
725
+ var WeixinAdapterBase = class extends BasePlatformAdapter {
726
+ cfg;
727
+ doFetch;
728
+ connected = false;
729
+ tokens;
730
+ seen = new SeenIds();
731
+ constructor(cfg) {
732
+ super();
733
+ this.cfg = cfg;
734
+ this.doFetch = cfg.fetch ?? defaultFetch;
735
+ this.tokens = createTokenCache({ fetchToken: () => this.requestToken() });
736
+ }
737
+ async connect() {
738
+ if (this.connected) return true;
739
+ try {
740
+ await this.token(true);
741
+ this.connected = true;
742
+ return true;
743
+ } catch (err) {
744
+ reportDiagnostic(this.cfg.label, `connect failed: ${weixinMessageOf(err)}`, {
745
+ });
746
+ return false;
747
+ }
748
+ }
749
+ async disconnect() {
750
+ this.connected = false;
751
+ this.tokens.clear();
752
+ }
753
+ /** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
754
+ async sendText(out) {
755
+ if (out.text.length === 0) {
756
+ return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
757
+ }
758
+ if (!this.connected) {
759
+ return {
760
+ ok: false,
761
+ error: {
762
+ code: "not_connected",
763
+ message: `${this.cfg.className}.connect() has not succeeded`
764
+ }
765
+ };
766
+ }
767
+ if (out.channel.id === "") {
768
+ return {
769
+ ok: false,
770
+ error: { code: "invalid_channel", message: `channel.id must be ${this.cfg.userNoun}` }
771
+ };
772
+ }
773
+ return this.sendParts(out);
774
+ }
775
+ async sendParts(out) {
776
+ const failed = `${this.platform}_send_failed`;
777
+ try {
778
+ for (const content of this.split(this.outboundText(out))) {
779
+ const token = await this.token(false);
780
+ const req = this.sendRequest(token, out.channel.id, content);
781
+ const body = await this.call("POST", req.path, req.payload);
782
+ if (body.errcode !== 0) {
783
+ return {
784
+ ok: false,
785
+ error: {
786
+ code: failed,
787
+ message: `${this.cfg.brand} error ${String(body.errcode)}: ${String(body.errmsg)}`
788
+ }
789
+ };
790
+ }
791
+ }
792
+ } catch (err) {
793
+ return { ok: false, error: { code: failed, message: weixinMessageOf(err) } };
794
+ }
795
+ return { ok: true, messageId: "" };
796
+ }
797
+ onInbound(handler) {
798
+ return this.subscribe(handler);
799
+ }
800
+ /** Deliver an event that arrived out of band, through `runHandler`. */
801
+ async deliver(event) {
802
+ return this.deliverInbound(event);
803
+ }
804
+ /** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */
805
+ async handleMessage(xml) {
806
+ const event = this.toEvent(parseFlatXml(xml));
807
+ if (event === "skip") return weixinAck("not a text message");
808
+ if (event === void 0) return { status: 400, body: "", reason: "incomplete" };
809
+ const outcome = await this.dispatchOnce(this.seen, event, this.cfg.label);
810
+ if (outcome === "no_handler") return { status: 503, body: "", reason: "no handler subscribed" };
811
+ return weixinAck(outcome);
812
+ }
813
+ token(force) {
814
+ return this.tokens.get({ force });
815
+ }
816
+ async requestToken() {
817
+ const body = await this.call("GET", this.tokenPath());
818
+ if (body.errcode !== void 0 && body.errcode !== 0) {
819
+ throw new Error(`token answered error ${String(body.errcode)}: ${String(body.errmsg)}`);
820
+ }
821
+ if (!body.access_token) throw new Error("token answer has no access_token");
822
+ return {
823
+ value: body.access_token,
824
+ ...body.expires_in === void 0 ? {} : { expiresInS: body.expires_in }
825
+ };
826
+ }
827
+ async call(method, path, payload) {
828
+ const res = await this.doFetch((this.cfg.apiBase ?? this.cfg.defaultBase) + path, {
829
+ method,
830
+ headers: { "Content-Type": "application/json" },
831
+ ...payload === void 0 ? {} : { body: JSON.stringify(payload) }
832
+ });
833
+ const text = await res.text();
834
+ try {
835
+ return JSON.parse(text);
836
+ } catch {
837
+ throw new Error(`${this.cfg.brand} answered HTTP ${res.status} with a non-JSON body`);
838
+ }
839
+ }
840
+ };
841
+ var DEFAULT_REFETCH_FLOOR_MS = 6e4;
842
+ var READ_TIMEOUT_MS = 1e4;
843
+ function jwksKeySet(options) {
844
+ const doFetch = options.fetch ?? ((url, init) => fetch(url, init));
845
+ const now = options.now ?? Date.now;
846
+ const floor = options.unknownKidRefetchFloorMs ?? DEFAULT_REFETCH_FLOOR_MS;
847
+ const swr = options.staleWhileRevalidate ?? true;
848
+ let held;
849
+ let lastReadStartedAt = Number.NEGATIVE_INFINITY;
850
+ let reading;
851
+ let lastFailure = "no read has completed";
852
+ async function fetchKeys() {
853
+ const response = await doFetch(options.url, { signal: AbortSignal.timeout(READ_TIMEOUT_MS) });
854
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
855
+ const keys = parseKeys(await response.json());
856
+ return { keys, freshUntil: now() + maxAgeMs(response.headers.get("cache-control")) };
857
+ }
858
+ function read() {
859
+ if (reading) return reading;
860
+ lastReadStartedAt = now();
861
+ const current = fetchKeys().then(
862
+ (next) => {
863
+ held = next;
864
+ reading = void 0;
865
+ return void 0;
866
+ },
867
+ (error) => {
868
+ lastFailure = error instanceof Error ? error.message : String(error);
869
+ reading = void 0;
870
+ return lastFailure;
871
+ }
872
+ );
873
+ reading = current;
874
+ return current;
875
+ }
876
+ const mayRead = () => !reading && now() - lastReadStartedAt >= floor;
877
+ function answer(kid) {
878
+ const key = held?.keys.get(kid);
879
+ if (key) return key;
880
+ return held ? "unlisted" : { unavailable: lastFailure };
881
+ }
882
+ async function refreshListed(kid) {
883
+ const refresh = reading ?? (mayRead() ? read() : void 0);
884
+ if (refresh && !swr) await refresh;
885
+ return answer(kid);
886
+ }
887
+ async function refreshUnknown(kid) {
888
+ const refresh = reading ?? (mayRead() ? read() : void 0);
889
+ const failure = refresh ? await refresh : void 0;
890
+ if (failure && !held?.keys.has(kid)) return { unavailable: failure };
891
+ return answer(kid);
892
+ }
893
+ return {
894
+ async lookup(kid) {
895
+ const listed = held?.keys.get(kid);
896
+ if (!held || !listed) return refreshUnknown(kid);
897
+ if (now() < held.freshUntil) return listed;
898
+ return refreshListed(kid);
899
+ }
900
+ };
901
+ }
902
+ function parseKey(jwk) {
903
+ if (typeof jwk !== "object" || jwk === null) return void 0;
904
+ const { kid, kty, use } = jwk;
905
+ if (typeof kid !== "string" || kty !== "RSA" || use !== void 0 && use !== "sig") {
906
+ return void 0;
907
+ }
908
+ try {
909
+ return [kid, crypto.createPublicKey({ key: jwk, format: "jwk" })];
910
+ } catch {
911
+ return void 0;
912
+ }
913
+ }
914
+ function parseKeys(body) {
915
+ const list = body?.keys;
916
+ if (!Array.isArray(list)) throw new Error("the key set has no `keys` array");
917
+ const entries = list.map(parseKey).filter((e) => e !== void 0);
918
+ return new Map(entries);
919
+ }
920
+ function maxAgeMs(cacheControl) {
921
+ const match = /(?:^|,)\s*max-age=(\d+)/i.exec(cacheControl ?? "");
922
+ return match?.[1] ? Number(match[1]) * 1e3 : 0;
923
+ }
924
+ var BASE64URL = /^[A-Za-z0-9_-]+$/;
925
+ function decodeJwt(token) {
926
+ const parts = token.split(".");
927
+ if (parts.length !== 3) return void 0;
928
+ const [h, p, s] = parts;
929
+ if (![h, p, s].every((part) => BASE64URL.test(part))) return void 0;
930
+ const header = jsonObject(h);
931
+ const payload = jsonObject(p);
932
+ if (!header || !payload) return void 0;
933
+ return { header, payload, signingInput: `${h}.${p}`, signature: Buffer.from(s, "base64url") };
934
+ }
935
+ function jsonObject(segment) {
936
+ try {
937
+ const value = JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
938
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
939
+ } catch {
940
+ return void 0;
941
+ }
942
+ }
943
+ async function verifyRs256Jwt(token, keys) {
944
+ const jwt = decodeJwt(token);
945
+ if (!jwt) return { ok: false, reason: "malformed" };
946
+ if (jwt.header.alg !== "RS256") return { ok: false, reason: "unsupported_alg" };
947
+ const kid = jwt.header.kid;
948
+ if (typeof kid !== "string" || kid === "") return { ok: false, reason: "malformed" };
949
+ const found = await keys.lookup(kid);
950
+ if (found === "unlisted") return { ok: false, reason: "unknown_kid" };
951
+ if ("unavailable" in found) return { ok: false, reason: "keys_unavailable" };
952
+ let valid = false;
953
+ try {
954
+ valid = crypto.verify("RSA-SHA256", Buffer.from(jwt.signingInput), found, jwt.signature);
955
+ } catch {
956
+ valid = false;
957
+ }
958
+ return valid ? { ok: true, header: jwt.header, payload: jwt.payload } : { ok: false, reason: "bad_signature" };
959
+ }
960
+
961
+ // src/errors/config-error.ts
962
+ var GatewayConfigurationError = class extends Error {
963
+ name = "GatewayConfigurationError";
964
+ code;
965
+ detail;
966
+ /**
967
+ * @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
968
+ * @param opts `code` (required), optional explicit `message`, optional `detail`.
969
+ */
970
+ constructor(prefix, opts) {
971
+ super(opts.message ?? `${prefix}: ${opts.code}`);
972
+ this.code = opts.code;
973
+ this.detail = opts.detail;
974
+ }
975
+ };
976
+
977
+ // src/channel/channel-config-readers.ts
978
+ function channelConfigReaders(prefix, createError = (options) => new GatewayConfigurationError(prefix, options)) {
979
+ const invalid2 = (key, expected) => createError({
980
+ code: "invalid_config",
981
+ message: `${prefix}: config.${key} must be ${expected}`,
982
+ detail: key
983
+ });
984
+ const isAbsent2 = (value) => value === void 0 || value === null || value === "";
985
+ const readString = (config, key) => {
986
+ const value = config[key];
987
+ if (isAbsent2(value)) return void 0;
988
+ if (typeof value !== "string") throw invalid2(key, "a string");
989
+ return value;
990
+ };
991
+ return {
992
+ invalid: invalid2,
993
+ isAbsent: isAbsent2,
994
+ readString,
995
+ requiredString(config, key) {
996
+ const value = config[key];
997
+ if (typeof value !== "string" || value === "") throw invalid2(key, "a non-empty string");
998
+ return value;
999
+ },
1000
+ readBoolean(config, key) {
1001
+ const value = config[key];
1002
+ if (isAbsent2(value)) return void 0;
1003
+ if (typeof value !== "boolean") throw invalid2(key, "a boolean");
1004
+ return value;
1005
+ },
1006
+ readNumber(config, key) {
1007
+ const value = config[key];
1008
+ if (isAbsent2(value)) return void 0;
1009
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1010
+ if (typeof value === "string" && /^\d+$/.test(value)) return Number(value);
1011
+ throw invalid2(key, "a number or a digit string");
1012
+ },
1013
+ readBooleanString(config, key) {
1014
+ const value = config[key];
1015
+ if (isAbsent2(value)) return void 0;
1016
+ if (typeof value === "boolean") return value;
1017
+ if (value === "true") return true;
1018
+ if (value === "false") return false;
1019
+ throw invalid2(key, 'a boolean or "true"/"false"');
1020
+ },
1021
+ readList(config, key) {
1022
+ const value = config[key];
1023
+ if (isAbsent2(value)) return void 0;
1024
+ if (typeof value === "string") {
1025
+ return value.split(",").map((item) => item.trim()).filter((item) => item !== "");
1026
+ }
1027
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
1028
+ throw invalid2(key, "an array of strings or a comma-separated string");
1029
+ }
1030
+ return value;
1031
+ },
1032
+ readFunction(config, key) {
1033
+ const value = config[key];
1034
+ if (isAbsent2(value)) return void 0;
1035
+ if (typeof value !== "function") throw invalid2(key, "a function");
1036
+ return value;
1037
+ }
1038
+ };
1039
+ }
1040
+
1041
+ // src/channel/channel-descriptor.ts
1042
+ function isAuthenticatedSender(descriptor) {
1043
+ return descriptor.senderIdentity === "authenticated";
1044
+ }
1045
+
1046
+ // src/channel/config-from-env.ts
1047
+ function envVarName(field, prefix = "") {
1048
+ return field.env === void 0 ? void 0 : prefix + field.env;
1049
+ }
1050
+ function readValue(env, name) {
1051
+ return env[name]?.trim() || void 0;
1052
+ }
1053
+ function configFromEnv(descriptor, env, options = "") {
1054
+ const opts = typeof options === "string" ? { prefix: options } : options;
1055
+ const config = {};
1056
+ const missing = [];
1057
+ const secrets = [];
1058
+ for (const field of descriptor.config) {
1059
+ const name = variableName(field, opts);
1060
+ if (name === void 0) continue;
1061
+ const value = readValue(env, name);
1062
+ if (value === void 0) {
1063
+ if (isRequired(field, opts)) missing.push(name);
1064
+ continue;
1065
+ }
1066
+ config[field.key] = value;
1067
+ recordSecret(field, value, secrets);
1068
+ }
1069
+ if (opts.enabledBy === void 0) return { config, missing, secrets };
1070
+ return { config, missing, secrets, enabled: isEnabled(env, opts.enabledBy) };
1071
+ }
1072
+ function variableName(field, opts) {
1073
+ const renamed = opts.rename !== void 0 && Object.hasOwn(opts.rename, field.key);
1074
+ return renamed ? opts.rename?.[field.key] : envVarName(field, opts.prefix);
1075
+ }
1076
+ function isRequired(field, opts) {
1077
+ return field.required || (opts.require?.includes(field.key) ?? false);
1078
+ }
1079
+ function isEnabled(env, name) {
1080
+ const flag = readValue(env, name)?.toLowerCase();
1081
+ return flag === "true" || flag === "1";
1082
+ }
1083
+ function recordSecret(field, value, secrets) {
1084
+ if (field.secret && !secrets.includes(value)) secrets.push(value);
1085
+ }
1086
+ function mismatch(parent, variant, name) {
1087
+ throw new GatewayConfigurationError("gateway", {
1088
+ code: "platform_mismatch",
1089
+ message: `channel ${parent.platform}: variant "${name}" reports platform ${variant.platform}`
1090
+ });
1091
+ }
1092
+ function unknownVariant(descriptor, name) {
1093
+ const valid = Object.keys(descriptor.variants ?? {});
1094
+ const given = name === void 0 ? "(none given)" : `"${name}"`;
1095
+ throw new GatewayConfigurationError("gateway", {
1096
+ code: "unknown_channel_variant",
1097
+ message: `channel ${descriptor.platform}: unknown variant ${given}; valid variants: ${valid.length > 0 ? valid.join(", ") : "(none)"}`
1098
+ });
1099
+ }
1100
+ function selectVariant(descriptor, name) {
1101
+ const variants = descriptor.variants ?? {};
1102
+ if (name === void 0 && Object.keys(variants).length === 0) return descriptor;
1103
+ const variant = name !== void 0 && Object.hasOwn(variants, name) ? variants[name] : void 0;
1104
+ if (variant === void 0) return unknownVariant(descriptor, name);
1105
+ if (variant.platform !== descriptor.platform) mismatch(descriptor, variant, name ?? "");
1106
+ return variant;
1107
+ }
1108
+
1109
+ // src/channel/create-channels.ts
1110
+ function isAbsent(value) {
1111
+ return value === void 0 || value === null || value === "";
1112
+ }
1113
+ function missingRequiredKeys(entry, values) {
1114
+ return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => {
1115
+ const name = envVarName(field, entry.envPrefix);
1116
+ return name === void 0 ? field.key : `${field.key} (env ${name})`;
1117
+ });
1118
+ }
1119
+ function refused(platform, code, reason) {
1120
+ return {
1121
+ refusal: {
1122
+ platform,
1123
+ error: new GatewayConfigurationError("gateway", {
1124
+ code,
1125
+ message: `channel ${platform}: ${reason}`
1126
+ })
1127
+ }
1128
+ };
1129
+ }
1130
+ function refuseBeforeCreate(entry, values, builtPlatforms) {
1131
+ const platform = entry.descriptor.platform;
1132
+ if (builtPlatforms.has(platform)) {
1133
+ return refused(platform, "duplicate_channel", "a channel for this platform was already built");
1134
+ }
1135
+ const missing = missingRequiredKeys(entry, values);
1136
+ if (missing.length > 0) {
1137
+ return refused(
1138
+ platform,
1139
+ "missing_required_config",
1140
+ `missing required config ${missing.join(", ")}`
1141
+ );
1142
+ }
1143
+ return void 0;
1144
+ }
1145
+ function createAdapter(entry, values) {
1146
+ const platform = entry.descriptor.platform;
1147
+ let adapter;
1148
+ try {
1149
+ adapter = entry.descriptor.create(values, entry.deps);
1150
+ } catch (err) {
1151
+ if (!(err instanceof GatewayConfigurationError)) throw err;
1152
+ return { refusal: { platform, error: err } };
1153
+ }
1154
+ if (adapter.platform !== platform) {
1155
+ return refused(
1156
+ platform,
1157
+ "platform_mismatch",
1158
+ `create returned an adapter reporting platform ${adapter.platform}`
1159
+ );
1160
+ }
1161
+ return { adapter };
1162
+ }
1163
+ function createChannels(entries) {
1164
+ const adapters = [];
1165
+ const channels = [];
1166
+ const rejected = [];
1167
+ const builtPlatforms = /* @__PURE__ */ new Set();
1168
+ for (const entry of entries) {
1169
+ const values = entry.config ?? {};
1170
+ const outcome = refuseBeforeCreate(entry, values, builtPlatforms) ?? createAdapter(entry, values);
1171
+ if (outcome.refusal !== void 0) {
1172
+ rejected.push(outcome.refusal);
1173
+ continue;
1174
+ }
1175
+ adapters.push(outcome.adapter);
1176
+ channels.push({ descriptor: entry.descriptor, adapter: outcome.adapter });
1177
+ builtPlatforms.add(entry.descriptor.platform);
1178
+ }
1179
+ return { adapters, channels, rejected };
1180
+ }
1181
+
1182
+ // src/delivery/router.ts
1183
+ var DeliveryRouter = class {
1184
+ adapters = /* @__PURE__ */ new Map();
1185
+ register(adapter) {
1186
+ this.adapters.set(adapter.platform, adapter);
1187
+ }
1188
+ async send(req) {
1189
+ const adapter = this.adapters.get(req.platform);
1190
+ if (adapter === void 0) {
1191
+ return {
1192
+ ok: false,
1193
+ error: { code: "no_adapter", message: `no adapter for platform "${req.platform}"` }
1194
+ };
1195
+ }
1196
+ const outbound = {
1197
+ channel: req.channel,
1198
+ text: req.text,
1199
+ ...req.format !== void 0 ? { format: req.format } : {},
1200
+ ...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {},
1201
+ ...attachmentsOf(req.attachments)
1202
+ };
1203
+ return refuseUnsupportedAttachments(adapter, outbound) ?? adapter.sendMessage(outbound);
1204
+ }
1205
+ };
1206
+
1207
+ // src/errors/lifecycle-error.ts
1208
+ var GatewayLifecycleError = class extends Error {
1209
+ name = "GatewayLifecycleError";
1210
+ /** Stable discriminator, so callers branch on `code` rather than on message text. */
1211
+ code;
1212
+ constructor(opts) {
1213
+ super(opts.message);
1214
+ this.code = opts.code;
1215
+ }
1216
+ };
1217
+ function senderKey(platform, senderId) {
1218
+ return `${platform}:${platform === "email" ? senderId.toLowerCase() : senderId}`;
1219
+ }
1220
+ var TTL_MS = 36e5;
1221
+ var FILE = "pairing.json";
1222
+ function unreadable() {
1223
+ return new GatewayConfigurationError("gateway", {
1224
+ code: "pairing_store_unreadable",
1225
+ message: "gateway: pairing_store_unreadable"
1226
+ });
1227
+ }
1228
+ function load(path) {
1229
+ let raw;
1230
+ try {
1231
+ raw = fs.readFileSync(path, "utf8");
1232
+ } catch (e) {
1233
+ if (e.code === "ENOENT") return /* @__PURE__ */ new Set();
1234
+ throw unreadable();
1235
+ }
1236
+ let parsed;
1237
+ try {
1238
+ parsed = JSON.parse(raw);
1239
+ } catch {
1240
+ throw unreadable();
1241
+ }
1242
+ const list = parsed?.paired;
1243
+ if (!Array.isArray(list) || !list.every((x) => typeof x === "string")) throw unreadable();
1244
+ return new Set(list);
1245
+ }
1246
+ function createFilePairingStore(options) {
1247
+ const clock = options.clock ?? Date.now;
1248
+ const random = options.random ?? crypto.randomInt;
1249
+ const path$1 = path.join(options.dir, FILE);
1250
+ const paired = load(path$1);
1251
+ const pending = /* @__PURE__ */ new Map();
1252
+ let chain = Promise.resolve();
1253
+ const prune = () => {
1254
+ const now = clock();
1255
+ for (const [code, p] of pending) if (p.expires <= now) pending.delete(code);
1256
+ };
1257
+ function persist(next) {
1258
+ fs.mkdirSync(options.dir, { recursive: true });
1259
+ const tmp = `${path$1}.${process.pid}.${crypto.randomUUID()}.tmp`;
1260
+ fs.writeFileSync(tmp, JSON.stringify({ paired: [...next].sort((a, b) => a.localeCompare(b)) }), {
1261
+ mode: 384,
1262
+ flag: "wx"
1263
+ });
1264
+ fs.renameSync(tmp, path$1);
1265
+ }
1266
+ return {
1267
+ issue(platform, senderId) {
1268
+ prune();
1269
+ for (const [code2, p] of pending) {
1270
+ if (senderKey(p.platform, p.senderId) === senderKey(platform, senderId)) return code2;
1271
+ }
1272
+ let code;
1273
+ do {
1274
+ code = String(random(1e5, 1e6));
1275
+ } while (pending.has(code));
1276
+ pending.set(code, { platform, senderId, expires: clock() + TTL_MS });
1277
+ return code;
1278
+ },
1279
+ approve(code) {
1280
+ const run = async () => {
1281
+ prune();
1282
+ const p = pending.get(code);
1283
+ if (!p) return { ok: false, reason: "unknown_or_expired" };
1284
+ const next = new Set(paired);
1285
+ next.add(senderKey(p.platform, p.senderId));
1286
+ try {
1287
+ persist(next);
1288
+ } catch {
1289
+ return { ok: false, reason: "write_failed" };
1290
+ }
1291
+ paired.add(senderKey(p.platform, p.senderId));
1292
+ pending.delete(code);
1293
+ return { ok: true, platform: p.platform, senderId: p.senderId };
1294
+ };
1295
+ const result = chain.then(run, run);
1296
+ chain = result.catch(() => void 0);
1297
+ return result;
1298
+ },
1299
+ isPaired(platform, senderId) {
1300
+ return paired.has(senderKey(platform, senderId));
1301
+ }
1302
+ };
1303
+ }
1304
+
1305
+ // src/hooks/access-policy.ts
1306
+ var SILENT = { block: true };
1307
+ var DEFAULT_REFUSAL = "Sorry, you are not authorized to use this assistant.";
1308
+ var DEFAULT_MESSAGES = {
1309
+ pairingCode: (code) => `Your pairing code is ${code}. Ask the owner to send /approve ${code}.`,
1310
+ invalidCode: "Unknown or expired code.",
1311
+ failedSave: "Saving the pairing failed. Check the storage and send the code again.",
1312
+ paired: "Paired.",
1313
+ pairingOff: "Pairing is not enabled."
1314
+ };
1315
+ function normalize(key) {
1316
+ const i = key.indexOf(":");
1317
+ return i < 0 ? key : senderKey(key.slice(0, i), key.slice(i + 1));
1318
+ }
1319
+ function stripUndefined(m) {
1320
+ return Object.fromEntries(
1321
+ Object.entries(m ?? {}).filter(([, v]) => v !== void 0)
1322
+ );
1323
+ }
1324
+ function check(keys, isAuth) {
1325
+ const out = /* @__PURE__ */ new Set();
1326
+ for (const key of keys) {
1327
+ const i = key.indexOf(":");
1328
+ const platform = i < 0 ? key : key.slice(0, i);
1329
+ if (!isAuth(platform)) {
1330
+ throw new GatewayConfigurationError("gateway", {
1331
+ code: "unauthenticated_owner",
1332
+ message: `gateway: unauthenticated_owner: platform ${platform} does not authenticate the sender`,
1333
+ detail: platform
1334
+ });
1335
+ }
1336
+ out.add(normalize(key));
1337
+ }
1338
+ return out;
1339
+ }
1340
+ function createAccessPolicyHook(options) {
1341
+ if (options.dm === "pairing" && !options.pairing) {
1342
+ throw new GatewayConfigurationError("gateway", {
1343
+ code: "pairing_store_required",
1344
+ message: "gateway: pairing_store_required"
1345
+ });
1346
+ }
1347
+ const owners = check(options.owners, options.isAuthenticated);
1348
+ const allowed = check(options.allowed ?? /* @__PURE__ */ new Set(), options.isAuthenticated);
1349
+ const clock = options.clock ?? Date.now;
1350
+ const interval = options.refusalIntervalMs ?? 36e5;
1351
+ const write = options.write ?? reportDiagnosticLine;
1352
+ const refusal = options.refusalText ?? DEFAULT_REFUSAL;
1353
+ const msg = { ...DEFAULT_MESSAGES, ...stripUndefined(options.messages) };
1354
+ const store = options.pairing;
1355
+ const refused2 = /* @__PURE__ */ new Map();
1356
+ const mayRefuse = (key) => {
1357
+ const now = clock();
1358
+ for (const [k, t] of refused2) if (now - t >= interval) refused2.delete(k);
1359
+ if (refused2.has(key)) return false;
1360
+ refused2.set(key, now);
1361
+ return true;
1362
+ };
1363
+ const pairingReply = (event) => {
1364
+ const code = store.issue(event.platform, event.sender.id);
1365
+ return {
1366
+ block: true,
1367
+ message: msg.pairingCode(code)
1368
+ };
1369
+ };
1370
+ const groupDecision = () => options.groups === "open" ? void 0 : SILENT;
1371
+ const stranger = (event, key) => {
1372
+ if (event.channel.type !== "dm") return groupDecision();
1373
+ if (options.dm === "open") return void 0;
1374
+ if (options.dm === "disabled" || !mayRefuse(key)) return SILENT;
1375
+ if (options.dm === "allowlist") return { block: true, message: refusal };
1376
+ return pairingReply(event);
1377
+ };
1378
+ const ownerMessage = async (text) => {
1379
+ const m = /^\/approve\s+(\d{6})\s*$/.exec(text.trim());
1380
+ if (!m?.[1]) return void 0;
1381
+ if (!store) return { block: true, message: msg.pairingOff };
1382
+ const r = await store.approve(m[1]);
1383
+ if (r.ok) return { block: true, message: msg.paired };
1384
+ return {
1385
+ block: true,
1386
+ message: r.reason === "write_failed" ? msg.failedSave : msg.invalidCode
1387
+ };
1388
+ };
1389
+ const isPaired = (event) => store?.isPaired(event.platform, event.sender.id) === true;
1390
+ const decide = async (event) => {
1391
+ if (options.passThrough?.(event)) return void 0;
1392
+ if (!options.isAuthenticated(event.platform)) return SILENT;
1393
+ const key = senderKey(event.platform, event.sender.id);
1394
+ if (owners.has(key)) return ownerMessage(event.text);
1395
+ if (allowed.has(key) || isPaired(event)) return void 0;
1396
+ return stranger(event, key);
1397
+ };
1398
+ return {
1399
+ name: "access-policy",
1400
+ async pre_inbound({ event }) {
1401
+ try {
1402
+ return await decide(event);
1403
+ } catch (e) {
1404
+ try {
1405
+ write(`access-policy: hook failed: ${redactSecrets(e)}`);
1406
+ } catch {
1407
+ }
1408
+ return SILENT;
1409
+ }
1410
+ }
1411
+ };
1412
+ }
1413
+
1414
+ // src/hooks/chat-command.ts
1415
+ var LEADING_MENTION = /^(?:<@[^>]+>|@\S+)\s+/;
1416
+ var DEFAULT_PREFIXES = ["/"];
1417
+ function matchPrefix(text, prefixes) {
1418
+ let best;
1419
+ for (const p of prefixes) {
1420
+ if (p.length > 0 && text.startsWith(p) && (best === void 0 || p.length > best.length)) {
1421
+ best = p;
1422
+ }
1423
+ }
1424
+ return best;
1425
+ }
1426
+ function parseChatCommand(text, options) {
1427
+ const body = text.trim().replace(LEADING_MENTION, "");
1428
+ const prefix = matchPrefix(body, options?.prefixes ?? DEFAULT_PREFIXES);
1429
+ if (prefix === void 0) return void 0;
1430
+ const rest = body.slice(prefix.length);
1431
+ const m = /^([^\s@]+)(?:@\S+)?(?:\s+([\s\S]*))?$/.exec(rest);
1432
+ if (!m?.[1]) return void 0;
1433
+ return { name: m[1].toLowerCase(), arg: (m[2] ?? "").trim() };
1434
+ }
1435
+ function usageOf(c) {
1436
+ return c.usage ?? `/${c.name}`;
1437
+ }
1438
+ function helpText(commands) {
1439
+ return commands.map((c) => `${usageOf(c)} - ${c.description}`).join("\n");
1440
+ }
1441
+ function assertUnique(names) {
1442
+ const seen = /* @__PURE__ */ new Set();
1443
+ for (const raw of names) {
1444
+ const name = raw.toLowerCase();
1445
+ if (seen.has(name)) {
1446
+ throw new GatewayConfigurationError("gateway", {
1447
+ code: "duplicate_command",
1448
+ message: `gateway: duplicate_command: ${raw}`,
1449
+ detail: raw
1450
+ });
1451
+ }
1452
+ seen.add(name);
1453
+ }
1454
+ }
1455
+ function badArity(c, arg) {
1456
+ const mode = c.arg ?? "optional";
1457
+ return mode === "none" && arg !== "" || mode === "required" && arg === "";
1458
+ }
1459
+ function commandHook(commands, options) {
1460
+ const helpName = options?.helpCommand === void 0 ? "help" : options.helpCommand;
1461
+ assertUnique([...commands.map((c) => c.name), ...helpName === false ? [] : [helpName]]);
1462
+ const byName = new Map(commands.map((c) => [c.name.toLowerCase(), c]));
1463
+ const help = helpText(commands);
1464
+ return {
1465
+ name: options?.name ?? "chat-commands",
1466
+ async pre_inbound({ event }) {
1467
+ const parsed = parseChatCommand(event.text);
1468
+ if (!parsed) return void 0;
1469
+ if (helpName !== false && parsed.name === helpName.toLowerCase()) {
1470
+ return { block: true, message: help };
1471
+ }
1472
+ const command = byName.get(parsed.name);
1473
+ if (!command) return void 0;
1474
+ if (badArity(command, parsed.arg)) return { block: true, message: usageOf(command) };
1475
+ return command.run(event, parsed.arg);
1476
+ }
1477
+ };
1478
+ }
1479
+
1480
+ // src/hooks/executor.ts
1481
+ var HOOK_PHASES = ["pre_inbound", "post_outbound", "on_error"];
1482
+ function malformedHook(index, why) {
1483
+ return new GatewayConfigurationError("gateway", {
1484
+ code: "malformed_hook",
1485
+ message: `gateway: hooks[${index}] ${why}`,
1486
+ detail: `hooks[${index}]`
1487
+ });
1488
+ }
1489
+ function assertHook(entry, index) {
1490
+ if (typeof entry !== "object" || entry === null) {
1491
+ throw malformedHook(index, `is ${entry === null ? "null" : typeof entry}, not a hook object`);
1492
+ }
1493
+ const hook = entry;
1494
+ if (typeof hook.name !== "string" || hook.name.length === 0) {
1495
+ throw malformedHook(
1496
+ index,
1497
+ "has no name \u2014 every hook is named so a log can say which one acted"
1498
+ );
1499
+ }
1500
+ const declared = HOOK_PHASES.filter((phase) => hook[phase] !== void 0);
1501
+ if (declared.length === 0) {
1502
+ throw malformedHook(
1503
+ index,
1504
+ `("${hook.name}") declares none of ${HOOK_PHASES.join(", ")} \u2014 it would never run`
1505
+ );
1506
+ }
1507
+ for (const phase of declared) {
1508
+ if (typeof hook[phase] !== "function") {
1509
+ throw malformedHook(index, `("${hook.name}") declares ${phase}, which is not callable`);
1510
+ }
1511
+ }
1512
+ }
1513
+ var HookExecutor = class {
1514
+ constructor(hooks) {
1515
+ this.hooks = hooks;
1516
+ hooks.forEach((hook, index) => {
1517
+ assertHook(hook, index);
1518
+ });
1519
+ }
1520
+ hooks;
1521
+ /**
1522
+ * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.
1523
+ * A hook throwing is treated as `{ block: true }` (logged via the runner).
1524
+ */
1525
+ async firePreInbound(ctx) {
1526
+ for (const h of this.hooks) {
1527
+ if (h.pre_inbound === void 0) continue;
1528
+ let decision;
1529
+ try {
1530
+ decision = await h.pre_inbound(ctx);
1531
+ } catch (err) {
1532
+ reportDiagnostic(
1533
+ "gateway",
1534
+ `pre_inbound hook "${h.name}" threw: ${err.message}`,
1535
+ { }
1536
+ );
1537
+ return {
1538
+ block: true,
1539
+ message: `Request blocked: hook "${h.name}" failed.`
1540
+ };
1541
+ }
1542
+ if (decision !== void 0 && decision.block === true) {
1543
+ return decision;
1544
+ }
1545
+ }
1546
+ return { block: false };
1547
+ }
1548
+ /** Fire all `post_outbound` hooks; errors logged via stderr. */
1549
+ async firePostOutbound(ctx) {
1550
+ for (const h of this.hooks) {
1551
+ if (h.post_outbound === void 0) continue;
1552
+ try {
1553
+ await h.post_outbound(ctx);
1554
+ } catch (err) {
1555
+ reportDiagnostic(
1556
+ "gateway",
1557
+ `post_outbound hook "${h.name}" threw: ${err.message}`,
1558
+ { }
1559
+ );
1560
+ }
1561
+ }
1562
+ }
1563
+ /** Fire all `on_error` hooks; errors logged via stderr. */
1564
+ async fireOnError(ctx) {
1565
+ for (const h of this.hooks) {
1566
+ if (h.on_error === void 0) continue;
1567
+ try {
1568
+ await h.on_error(ctx);
1569
+ } catch (err) {
1570
+ reportDiagnostic("gateway", `on_error hook "${h.name}" threw: ${err.message}`, {
1571
+ });
1572
+ }
1573
+ }
1574
+ }
1575
+ };
1576
+
1577
+ // src/hooks/group-activation.ts
1578
+ function groupActivationHook(options) {
1579
+ return {
1580
+ name: options.name ?? "group-activation",
1581
+ pre_inbound({ event }) {
1582
+ if (event.channel.type === "dm" || event.addressed !== false) return void 0;
1583
+ const mode = options.modeFor?.(event.channel.id) ?? options.mode;
1584
+ return mode === "mention" ? { block: true } : void 0;
1585
+ }
1586
+ };
1587
+ }
1588
+
1589
+ // src/runner/reconnect-backoff.ts
1590
+ function checkNonNegativeFinite(name, value) {
1591
+ if (!Number.isFinite(value) || value < 0) {
1592
+ throw new RangeError(`${name} must be a finite number >= 0, got ${value}`);
1593
+ }
1594
+ }
1595
+ var ReconnectBackoff = class {
1596
+ initialDelayMs;
1597
+ maxDelayMs;
1598
+ factor;
1599
+ maxAttempts;
1600
+ stableAfterMs;
1601
+ now;
1602
+ attempts = 0;
1603
+ openedAt;
1604
+ constructor(options = {}) {
1605
+ this.initialDelayMs = options.initialDelayMs ?? 1e3;
1606
+ this.maxDelayMs = options.maxDelayMs ?? 6e4;
1607
+ this.factor = options.factor ?? 2;
1608
+ this.maxAttempts = options.maxAttempts;
1609
+ this.stableAfterMs = options.stableAfterMs ?? 6e4;
1610
+ this.now = options.now ?? Date.now;
1611
+ checkNonNegativeFinite("initialDelayMs", this.initialDelayMs);
1612
+ checkNonNegativeFinite("maxDelayMs", this.maxDelayMs);
1613
+ if (!(this.factor >= 1) || !Number.isFinite(this.factor)) {
1614
+ throw new RangeError(`factor must be a finite number >= 1, got ${this.factor}`);
1615
+ }
1616
+ }
1617
+ /** Call when the connection opens. */
1618
+ opened() {
1619
+ this.openedAt = this.now();
1620
+ }
1621
+ /** Delay before the next attempt; `undefined` once `maxAttempts` is spent. Resets first if the last connection was stable. */
1622
+ nextDelayMs() {
1623
+ if (this.openedAt !== void 0) {
1624
+ if (this.now() - this.openedAt >= this.stableAfterMs) this.attempts = 0;
1625
+ this.openedAt = void 0;
1626
+ }
1627
+ if (this.maxAttempts !== void 0 && this.attempts >= this.maxAttempts) return void 0;
1628
+ const delay = Math.min(this.initialDelayMs * this.factor ** this.attempts, this.maxDelayMs);
1629
+ this.attempts += 1;
1630
+ return delay;
1631
+ }
1632
+ /** Back to the initial delay. */
1633
+ reset() {
1634
+ this.attempts = 0;
1635
+ this.openedAt = void 0;
1636
+ }
1637
+ };
1638
+
1639
+ // src/runner/gateway-runner.ts
1640
+ var DEFAULT_DRAIN_MS = 1e4;
1641
+ var TYPING_RENEW_MS = 4e3;
1642
+ function keepTyping(adapter, channelId) {
1643
+ const swallow = (p) => p.catch(() => void 0);
1644
+ const start = () => swallow(Promise.resolve().then(() => adapter.startTyping(channelId)));
1645
+ void start();
1646
+ const timer = setInterval(() => void start(), TYPING_RENEW_MS);
1647
+ timer.unref();
1648
+ return async () => {
1649
+ clearInterval(timer);
1650
+ await swallow(Promise.resolve().then(() => adapter.stopTyping(channelId)));
1651
+ };
1652
+ }
1653
+ var DEFAULT_COMMAND_PREFIXES = ["/"];
1654
+ function connectFailureReason(outcome, redact) {
1655
+ if (outcome.status === "fulfilled") return "connect returned false";
1656
+ const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
1657
+ return redact(message);
1658
+ }
1659
+ function isTerminalConnectError(err) {
1660
+ if (typeof err !== "object" || err === null) return false;
1661
+ const e = err;
1662
+ for (const key of ["status", "statusCode", "httpStatus"]) {
1663
+ if (e[key] === 401 || e[key] === 403) return true;
1664
+ }
1665
+ if (e.errcode === "M_UNKNOWN_TOKEN" || e.errcode === "M_FORBIDDEN") return true;
1666
+ const message = typeof e.message === "string" ? e.message : "";
1667
+ return /\b(?:http|status(?: code)?)\s*:?\s*(?:401|403)\b|unauthori[sz]ed|forbidden/i.test(
1668
+ message
1669
+ );
1670
+ }
1671
+ async function releaseAdapters(adapters, during, redact = redactSecrets) {
1672
+ await Promise.all(
1673
+ adapters.map(async (a) => {
1674
+ try {
1675
+ await a.disconnect();
1676
+ } catch (err) {
1677
+ const message = err instanceof Error ? err.message : String(err);
1678
+ reportDiagnostic(
1679
+ "gateway",
1680
+ `adapter "${a.platform}" disconnect failed while ${during}: ${redact(message)}`
1681
+ );
1682
+ }
1683
+ })
1684
+ );
1685
+ }
1686
+ var GatewayRunner = class {
1687
+ constructor(opts) {
1688
+ this.opts = opts;
1689
+ this.hookExecutor = new HookExecutor(opts.hooks ?? []);
1690
+ const secrets = opts.secrets ?? [];
1691
+ this.redact = (text) => redactSecrets(maskSecrets(text, secrets));
1692
+ }
1693
+ opts;
1694
+ hookExecutor;
1695
+ inflight = /* @__PURE__ */ new Set();
1696
+ unsubs = [];
1697
+ /** Slash command registry: name → handler (word-boundary match, EC-A). */
1698
+ commands = /* @__PURE__ */ new Map();
1699
+ startResult;
1700
+ /** The start that has not settled yet, shared by every overlapping `start()` call. */
1701
+ startInFlight;
1702
+ stopped = false;
1703
+ retryTimers = /* @__PURE__ */ new Set();
1704
+ connectedAdapters = /* @__PURE__ */ new Set();
1705
+ redact;
1706
+ /** The registered adapter for a platform, connected or not. */
1707
+ adapter(platform) {
1708
+ return this.opts.adapters.find((a) => a.platform === platform);
1709
+ }
1710
+ /** The adapters started now (a snapshot); updated by connects, retries and `stop()`. */
1711
+ connected() {
1712
+ return [...this.connectedAdapters];
1713
+ }
1714
+ emitState(platform, state, reason) {
1715
+ if ((this.opts.connectFailure ?? "rollback") !== "isolate") return;
1716
+ try {
1717
+ this.opts.onAdapterState?.(platform, state, reason);
1718
+ } catch {
1719
+ }
1720
+ }
1721
+ /**
1722
+ * Register a slash command. Match rule (EC-A): text === "/" + name
1723
+ * OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
1724
+ *
1725
+ * @public
1726
+ */
1727
+ command(name, handler) {
1728
+ this.commands.set(name, handler);
1729
+ }
1730
+ /**
1731
+ * Connect the adapters and wire inbound dispatch for the ones that connected.
1732
+ *
1733
+ * Resolves with what connected. A second call after the first resolved returns the same result
1734
+ * without connecting again.
1735
+ *
1736
+ * Overlapping calls share one start; a start overtaken by stop resolves with no adapter connected.
1737
+ * A call made before `stop()` while another is still connecting connects nothing and settles
1738
+ * with it; a call made after `stop()` throws `runner_stopped`. When `stop()` runs before the
1739
+ * connect settles, the adapters that connected are disconnected, no inbound dispatch is wired,
1740
+ * and the start resolves `{ connected: [], failed }`, keeping the `"isolate"` failures. Under
1741
+ * `"rollback"`, a connect that fails still rejects the start.
1742
+ *
1743
+ * Under `connectFailure: "rollback"`, every connect settles before the rollback, so a failing
1744
+ * start rejects only once its slowest connect settles, as a successful one resolves only then.
1745
+ *
1746
+ * An adapter whose `disconnect()` fails while a start rolls back, or while a start that `stop()`
1747
+ * overtook gives its adapters back, is named on stderr with the error redacted; how the start
1748
+ * settles does not change.
1749
+ *
1750
+ * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
1751
+ * stopped. A stopped runner is spent; construct a new one.
1752
+ * @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after
1753
+ * every connect settled and the adapters that did connect were disconnected.
1754
+ */
1755
+ async start() {
1756
+ if (this.stopped) {
1757
+ throw new GatewayLifecycleError({
1758
+ code: "runner_stopped",
1759
+ message: "GatewayRunner.start(): this runner has already been stopped and cannot be restarted. Construct a new GatewayRunner instead."
1760
+ });
1761
+ }
1762
+ if (this.startResult !== void 0) return this.startResult;
1763
+ if (this.startInFlight === void 0) {
1764
+ const pending = this.runStart();
1765
+ this.startInFlight = pending;
1766
+ pending.catch(() => {
1767
+ if (this.startInFlight === pending) this.startInFlight = void 0;
1768
+ });
1769
+ }
1770
+ return this.startInFlight;
1771
+ }
1772
+ async runStart() {
1773
+ const result = (this.opts.connectFailure ?? "rollback") === "isolate" ? await this.connectIsolated() : await this.connectAllOrRollback();
1774
+ if (this.stopped) {
1775
+ await releaseAdapters(
1776
+ result.connected,
1777
+ "releasing a start that stop() overtook",
1778
+ this.redact
1779
+ );
1780
+ this.connectedAdapters.clear();
1781
+ this.startResult = { connected: [], failed: result.failed };
1782
+ return this.startResult;
1783
+ }
1784
+ this.wireInbound(result.connected);
1785
+ for (const a of result.connected) this.connectedAdapters.add(a);
1786
+ this.startResult = {
1787
+ connected: result.connected.map((a) => a.platform),
1788
+ failed: result.failed
1789
+ };
1790
+ for (const adapter of result.retryable) {
1791
+ const policy = this.opts.reconnect;
1792
+ if (policy === void 0) break;
1793
+ this.scheduleReconnect(adapter, 1, new ReconnectBackoff(policy));
1794
+ }
1795
+ return this.startResult;
1796
+ }
1797
+ /** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
1798
+ scheduleReconnect(adapter, attempt, backoff) {
1799
+ const policy = this.opts.reconnect;
1800
+ if (policy === void 0 || this.stopped) return;
1801
+ const delay = backoff.nextDelayMs();
1802
+ if (delay === void 0) {
1803
+ reportDiagnostic(
1804
+ "gateway",
1805
+ `adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts`
1806
+ );
1807
+ return;
1808
+ }
1809
+ const timer = setTimeout(() => {
1810
+ this.retryTimers.delete(timer);
1811
+ void this.reconnectOnce(adapter, attempt, backoff);
1812
+ }, delay);
1813
+ timer.unref();
1814
+ this.retryTimers.add(timer);
1815
+ reportDiagnostic(
1816
+ "gateway",
1817
+ `adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms`
1818
+ );
1819
+ this.emitState(adapter.platform, "retrying", `reconnect attempt ${attempt} in ${delay}ms`);
1820
+ }
1821
+ async reconnectOnce(adapter, attempt, backoff) {
1822
+ if (this.stopped) return;
1823
+ try {
1824
+ if (await adapter.connect()) {
1825
+ if (this.stopped) {
1826
+ await releaseAdapters(
1827
+ [adapter],
1828
+ "releasing a reconnect that stop() overtook",
1829
+ this.redact
1830
+ );
1831
+ return;
1832
+ }
1833
+ this.wireInbound([adapter]);
1834
+ this.connectedAdapters.add(adapter);
1835
+ this.emitState(adapter.platform, "connected");
1836
+ const prev = this.startResult ?? { connected: [], failed: [] };
1837
+ this.startResult = {
1838
+ connected: [...prev.connected, adapter.platform],
1839
+ failed: prev.failed.filter((f) => f.platform !== adapter.platform)
1840
+ };
1841
+ reportDiagnostic(
1842
+ "gateway",
1843
+ `adapter "${adapter.platform}" connected on attempt ${attempt}`
1844
+ );
1845
+ return;
1846
+ }
1847
+ if (this.opts.reconnect?.retryFalse) {
1848
+ reportDiagnostic(
1849
+ "gateway",
1850
+ `adapter "${adapter.platform}" reconnect attempt ${attempt} answered false`
1851
+ );
1852
+ } else {
1853
+ reportDiagnostic(
1854
+ "gateway",
1855
+ `adapter "${adapter.platform}" refused to connect; not retrying`
1856
+ );
1857
+ return;
1858
+ }
1859
+ } catch (err) {
1860
+ const reason = connectFailureReason({ status: "rejected", reason: err }, this.redact);
1861
+ if (isTerminalConnectError(err)) {
1862
+ this.emitState(adapter.platform, "failed", reason);
1863
+ reportDiagnostic(
1864
+ "gateway",
1865
+ `adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying`
1866
+ );
1867
+ return;
1868
+ }
1869
+ reportDiagnostic(
1870
+ "gateway",
1871
+ `adapter "${adapter.platform}" reconnect attempt ${attempt} failed: ${reason}`
1872
+ );
1873
+ }
1874
+ this.scheduleReconnect(adapter, attempt + 1, backoff);
1875
+ }
1876
+ /**
1877
+ * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
1878
+ * the first failure. Every connect settles before the rollback: rolling back while one is still
1879
+ * pending left that adapter live once it connected.
1880
+ */
1881
+ async connectAllOrRollback() {
1882
+ const adapters = this.opts.adapters;
1883
+ const failures = [];
1884
+ const settled = await Promise.allSettled(
1885
+ adapters.map(async (a) => {
1886
+ let ok;
1887
+ try {
1888
+ ok = await a.connect();
1889
+ } catch (err) {
1890
+ failures.push(err);
1891
+ throw err;
1892
+ }
1893
+ if (!ok) {
1894
+ const refusal = new Error(`adapter "${a.platform}" connect returned false`);
1895
+ failures.push(refusal);
1896
+ throw refusal;
1897
+ }
1898
+ })
1899
+ );
1900
+ if (failures.length > 0) {
1901
+ const connected = adapters.filter((_, i) => settled[i]?.status === "fulfilled");
1902
+ await releaseAdapters(connected, "rolling back a failed start", this.redact);
1903
+ throw failures[0];
1904
+ }
1905
+ return { connected: [...adapters], failed: [], retryable: [] };
1906
+ }
1907
+ /**
1908
+ * Connect every adapter and keep the ones that connected. The `async` wrapper turns a
1909
+ * synchronous throw inside `connect()` into a rejection `allSettled` sees; a bare
1910
+ * `a => a.connect()` would let it escape `map` and reject `start()` itself.
1911
+ */
1912
+ async connectIsolated() {
1913
+ const adapters = this.opts.adapters;
1914
+ const results = await Promise.all(adapters.map((a) => this.connectOne(a)));
1915
+ const connected = [];
1916
+ const failed = [];
1917
+ const retryable = [];
1918
+ for (const r of results) {
1919
+ if (r.failure === void 0) connected.push(r.adapter);
1920
+ else failed.push(r.failure);
1921
+ if (r.retry) retryable.push(r.adapter);
1922
+ }
1923
+ return { connected, failed, retryable };
1924
+ }
1925
+ /** Connect one adapter, bounded by `connectTimeoutMs`, and report its state as it settles. */
1926
+ async connectOne(adapter) {
1927
+ const attempt = Promise.allSettled([(async () => adapter.connect())()]).then(
1928
+ ([r]) => r
1929
+ );
1930
+ const ms = this.opts.connectTimeoutMs;
1931
+ if (ms === void 0) return this.classify(adapter, await attempt);
1932
+ let timer;
1933
+ const first = await Promise.race([
1934
+ attempt,
1935
+ new Promise((resolve) => {
1936
+ timer = setTimeout(() => resolve("timeout"), ms);
1937
+ })
1938
+ ]);
1939
+ if (timer !== void 0) clearTimeout(timer);
1940
+ if (first !== "timeout") return this.classify(adapter, first);
1941
+ void attempt.then((late) => this.releaseLateConnect(adapter, late));
1942
+ const reason = `connect timed out after ${ms}ms`;
1943
+ this.emitState(adapter.platform, "timed_out", reason);
1944
+ return { adapter, failure: { platform: adapter.platform, reason }, retry: true };
1945
+ }
1946
+ /** A connect that finished after the runner gave up on it must not stay connected unseen. */
1947
+ releaseLateConnect(adapter, late) {
1948
+ if (late.status === "rejected") {
1949
+ this.emitState(adapter.platform, "failed", connectFailureReason(late, this.redact));
1950
+ return;
1951
+ }
1952
+ if (!late.value) return;
1953
+ if (this.connectedAdapters.has(adapter)) return;
1954
+ void releaseAdapters([adapter], "releasing a connect that timed out", this.redact);
1955
+ }
1956
+ classify(adapter, outcome) {
1957
+ if (outcome.status === "fulfilled" && outcome.value) {
1958
+ this.connectedAdapters.add(adapter);
1959
+ this.emitState(adapter.platform, "connected");
1960
+ return { adapter, failure: void 0, retry: false };
1961
+ }
1962
+ const reason = connectFailureReason(outcome, this.redact);
1963
+ this.emitState(adapter.platform, "failed", reason);
1964
+ const retry = outcome.status === "rejected" ? !isTerminalConnectError(outcome.reason) : outcome.value === false && this.opts.reconnect?.retryFalse === true;
1965
+ return { adapter, failure: { platform: adapter.platform, reason }, retry };
1966
+ }
1967
+ wireInbound(adapters) {
1968
+ for (const a of adapters) {
1969
+ const unsub = a.onInbound(async (event) => {
1970
+ const p = this.dispatch(event, a);
1971
+ this.inflight.add(p);
1972
+ p.finally(() => this.inflight.delete(p));
1973
+ });
1974
+ this.unsubs.push(unsub);
1975
+ }
1976
+ }
1977
+ /**
1978
+ * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
1979
+ * then disconnects adapters. Idempotent (EC-E). A disconnect that fails does not make `stop()`
1980
+ * reject and does not stop the other disconnects; it is written to stderr, redacted, naming the
1981
+ * platform.
1982
+ *
1983
+ * An adapter still connecting under an in-flight start is released when that start settles;
1984
+ * `stop()` does not wait for it.
1985
+ */
1986
+ async stop() {
1987
+ if (this.stopped) return;
1988
+ this.stopped = true;
1989
+ for (const unsub of this.unsubs) {
1990
+ try {
1991
+ unsub();
1992
+ } catch {
1993
+ }
1994
+ }
1995
+ this.unsubs.length = 0;
1996
+ for (const t of this.retryTimers) clearTimeout(t);
1997
+ this.retryTimers.clear();
1998
+ this.connectedAdapters.clear();
1999
+ const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
2000
+ if (this.inflight.size > 0) {
2001
+ let timer;
2002
+ try {
2003
+ await Promise.race([
2004
+ Promise.all([...this.inflight]).then(() => void 0),
2005
+ new Promise((r) => {
2006
+ timer = setTimeout(r, drainMs);
2007
+ })
2008
+ ]);
2009
+ } finally {
2010
+ if (timer !== void 0) clearTimeout(timer);
2011
+ }
2012
+ }
2013
+ await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner", this.redact);
2014
+ }
2015
+ /**
2016
+ * @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
2017
+ * settled dispatch that is never removed is a leak that grows for the life of the process, and it
2018
+ * is invisible from the outside — `stop()` drains correctly either way, because settled promises
2019
+ * resolve immediately whether or not anyone deleted them.
2020
+ */
2021
+ get _inflightSize() {
2022
+ return this.inflight.size;
2023
+ }
2024
+ /** @internal */
2025
+ async dispatch(event, adapter) {
2026
+ const ctx = this.buildContext(event, adapter);
2027
+ const decision = await this.hookExecutor.firePreInbound({ event });
2028
+ if (decision.block === true) {
2029
+ if (decision.message !== void 0 && decision.message.length > 0) {
2030
+ await ctx.reply(decision.message).catch(async (err) => {
2031
+ const error = err;
2032
+ await this.hookExecutor.fireOnError({ event, error });
2033
+ reportDiagnostic("gateway", `auto-reply error: ${this.redact(error.message)}`);
2034
+ });
2035
+ }
2036
+ return;
2037
+ }
2038
+ const slashHandler = this.matchSlashCommand(event);
2039
+ const handler = slashHandler ?? this.opts.handler;
2040
+ const work = (async () => {
2041
+ const stopTyping = keepTyping(adapter, event.channel.id);
2042
+ try {
2043
+ await handler(event, ctx);
2044
+ } catch (err) {
2045
+ await this.hookExecutor.fireOnError({ event, error: err });
2046
+ reportDiagnostic("gateway", `handler error: ${this.redact(err.message)}`);
2047
+ } finally {
2048
+ await stopTyping();
2049
+ }
2050
+ })();
2051
+ this.inflight.add(work);
2052
+ work.finally(() => this.inflight.delete(work));
2053
+ await work;
2054
+ }
2055
+ /**
2056
+ * EC-A: word-boundary slash command match. Prevents `/skill` from
2057
+ * shadowing `/skills`. Returns the handler if a command matches,
2058
+ * undefined otherwise.
2059
+ */
2060
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.
2061
+ matchSlashCommand(event) {
2062
+ const text = event.text;
2063
+ const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;
2064
+ let activePrefix;
2065
+ for (const p of prefixes) {
2066
+ if (text.startsWith(p)) {
2067
+ activePrefix = p;
2068
+ break;
2069
+ }
2070
+ }
2071
+ if (activePrefix === void 0) return void 0;
2072
+ for (const [name, handler] of this.commands) {
2073
+ const full = `${activePrefix}${name}`;
2074
+ if (text === full) return handler;
2075
+ if (text.startsWith(`${full} `)) return handler;
2076
+ if (text.startsWith(`${full}@`)) return handler;
2077
+ }
2078
+ return void 0;
2079
+ }
2080
+ /** EC-G: per-event ctx whose reply routes to the matching adapter. */
2081
+ buildContext(event, adapter) {
2082
+ return {
2083
+ event,
2084
+ reply: async (text, opts) => this.deliver(event, adapter, {
2085
+ channel: event.channel,
2086
+ text,
2087
+ ...opts?.format !== void 0 ? { format: opts.format } : {},
2088
+ ...attachmentsOf(opts?.attachments)
2089
+ })
2090
+ };
2091
+ }
2092
+ /**
2093
+ * Send one outbound on behalf of `event` and report it to `post_outbound`.
2094
+ *
2095
+ * Every reply leaves through here so the hook fires exactly once per attempt —
2096
+ * including the EC-D auto-reply, and including the attempt that finds no
2097
+ * adapter for the platform. An audit hook that counted only the deliveries
2098
+ * which reached a transport would omit precisely the ones that went nowhere.
2099
+ *
2100
+ * An outbound with attachments for an adapter that does not declare `supportsAttachments` is
2101
+ * refused here as `attachments_unsupported`, with no `sendMessage` call, so an adapter that
2102
+ * ignores the field cannot drop the image and report success (B-674).
2103
+ *
2104
+ * `post_outbound` observes; it does not intercept. The adapter's `SendResult`
2105
+ * is returned to the caller unchanged, and `HookExecutor` already contains a
2106
+ * throwing hook, so a broken observer cannot turn a delivered reply into a
2107
+ * failed one.
2108
+ *
2109
+ * @internal
2110
+ */
2111
+ async deliver(event, adapter, outbound) {
2112
+ const target = adapter?.platform === event.platform ? adapter : void 0;
2113
+ const result = target === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : refuseUnsupportedAttachments(target, outbound) ?? await target.sendMessage(outbound);
2114
+ await this.hookExecutor.firePostOutbound({ event, outbound, result });
2115
+ return result;
2116
+ }
2117
+ };
2118
+
2119
+ // src/runner/media-understanding.ts
2120
+ var DEFAULT_MAX_BYTES = 20 * 1024 * 1024;
2121
+ function sanitizeType(mediaType) {
2122
+ return mediaType.replace(/[^\w/.+-]/g, "");
2123
+ }
2124
+ function errorName(error) {
2125
+ return error instanceof Error ? error.name : "UnknownError";
2126
+ }
2127
+ function withMediaUnderstanding(handler, options) {
2128
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
2129
+ const write = options.write ?? reportDiagnosticLine;
2130
+ const understand = async (kind, media, fn) => {
2131
+ const type = sanitizeType(media.mediaType);
2132
+ if (fn === void 0) return `[Attachment of type ${type} not understood]`;
2133
+ const failed = `[Attachment of type ${type} could not be understood]`;
2134
+ if (media.size !== void 0 && media.size > maxBytes) {
2135
+ report(type, "TooLarge");
2136
+ return failed;
2137
+ }
2138
+ try {
2139
+ const data = await media.read();
2140
+ if (data.byteLength > maxBytes) {
2141
+ report(type, "TooLarge");
2142
+ return failed;
2143
+ }
2144
+ const text = await fn({ data, mediaType: media.mediaType });
2145
+ return `[${kind}: ${text}]`;
2146
+ } catch (error) {
2147
+ report(type, errorName(error));
2148
+ return failed;
2149
+ }
2150
+ };
2151
+ const report = (type, name) => {
2152
+ try {
2153
+ write(`[gateway] media understanding failed for ${type}: ${name}`);
2154
+ } catch {
2155
+ }
2156
+ };
2157
+ return async (event, ctx) => {
2158
+ const lines = [];
2159
+ if (event.audio !== void 0) {
2160
+ lines.push(
2161
+ await understand("Audio transcript", event.audio, options.transcribe?.bind(options))
2162
+ );
2163
+ }
2164
+ if (lines.length === 0) return handler(event, ctx);
2165
+ const text = [event.text, ...lines].filter((part) => part !== "").join("\n");
2166
+ const wrapped = { ...event, text };
2167
+ return handler(wrapped, ctx);
2168
+ };
2169
+ }
2170
+ var KEY_PATTERN = /^[A-Za-z0-9._:-]+$(?![\s\S])/;
2171
+ function fileFor(dir, key) {
2172
+ if (!KEY_PATTERN.test(key) || key === "." || key === "..") {
2173
+ throw new GatewayConfigurationError("gateway", {
2174
+ code: "invalid_credential_key",
2175
+ message: `gateway: invalid_credential_key (keys match [A-Za-z0-9._:-]+): ${JSON.stringify(key)}`
2176
+ });
2177
+ }
2178
+ return path.join(dir, key.replaceAll(":", "%3A"));
2179
+ }
2180
+ function createFileCredentialStore(dir) {
2181
+ return {
2182
+ async get(key) {
2183
+ const path = fileFor(dir, key);
2184
+ try {
2185
+ return await promises.readFile(path, "utf8");
2186
+ } catch (err) {
2187
+ if (err.code === "ENOENT") return void 0;
2188
+ throw new GatewayConfigurationError("gateway", {
2189
+ code: "credential_store_unreadable",
2190
+ message: `gateway: credential_store_unreadable: ${path}`,
2191
+ detail: err instanceof Error ? err.message : String(err)
2192
+ });
2193
+ }
2194
+ },
2195
+ async set(key, value) {
2196
+ const path = fileFor(dir, key);
2197
+ await promises.mkdir(dir, { recursive: true });
2198
+ const tmp = `${path}.${crypto.randomBytes(6).toString("hex")}.tmp`;
2199
+ try {
2200
+ await promises.writeFile(tmp, value, { mode: 384 });
2201
+ await promises.chmod(tmp, 384);
2202
+ await promises.rename(tmp, path);
2203
+ } catch (err) {
2204
+ await promises.unlink(tmp).catch(() => void 0);
2205
+ throw err;
2206
+ }
2207
+ }
2208
+ };
2209
+ }
2210
+
2211
+ // src/session/router.ts
2212
+ function defaultStrategy(event) {
2213
+ const { platform, channel, sender } = event;
2214
+ const sid = sanitize(sender.id);
2215
+ const cid = sanitize(channel.id);
2216
+ switch (channel.type) {
2217
+ case "dm":
2218
+ return `${platform}-dm-${sid}`;
2219
+ case "thread":
2220
+ if (channel.topicId === void 0) {
2221
+ return `${platform}-grp-${cid}-${sid}`;
2222
+ }
2223
+ return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;
2224
+ case "group":
2225
+ return `${platform}-grp-${cid}-${sid}`;
2226
+ }
2227
+ }
2228
+ function sanitize(s) {
2229
+ return s.replace(/_/g, "__").replace(/-/g, "_d");
2230
+ }
2231
+ var SessionRouter = class {
2232
+ constructor(strategy = defaultStrategy) {
2233
+ this.strategy = strategy;
2234
+ }
2235
+ strategy;
2236
+ resolveAgentId(event) {
2237
+ return this.strategy(event);
2238
+ }
2239
+ };
2240
+
2241
+ // src/session/bindings.ts
2242
+ function unknownAgent(agent) {
2243
+ return new GatewayConfigurationError("gateway", {
2244
+ code: "unknown_agent",
2245
+ message: `gateway: unknown_agent: ${agent}`,
2246
+ detail: agent
2247
+ });
2248
+ }
2249
+ function createAgentBindings(options) {
2250
+ const known = new Set(options.agents);
2251
+ if (!known.has(options.defaultAgent)) throw unknownAgent(options.defaultAgent);
2252
+ for (const rule of options.rules) {
2253
+ if (!known.has(rule.agent)) throw unknownAgent(rule.agent);
2254
+ if (rule.platform === void 0 && rule.account === void 0 && rule.peer === void 0) {
2255
+ throw new GatewayConfigurationError("gateway", {
2256
+ code: "empty_binding_rule",
2257
+ message: `gateway: empty_binding_rule: ${rule.agent}`,
2258
+ detail: rule.agent
2259
+ });
2260
+ }
2261
+ }
2262
+ const rules = [...options.rules];
2263
+ const { accountOf } = options;
2264
+ return {
2265
+ agentFor(event) {
2266
+ const ctx = {
2267
+ platform: event.platform,
2268
+ account: accountOf?.(event),
2269
+ peer: event.channel.type === "dm" ? event.sender.id : event.channel.id
2270
+ };
2271
+ let best = options.defaultAgent;
2272
+ let bestScore = 0;
2273
+ for (const rule of rules) {
2274
+ const score = scoreRule(rule, ctx);
2275
+ if (score > bestScore) {
2276
+ best = rule.agent;
2277
+ bestScore = score;
2278
+ }
2279
+ }
2280
+ return best;
2281
+ }
2282
+ };
2283
+ }
2284
+ function scoreRule(rule, ctx) {
2285
+ const fields = [
2286
+ [rule.platform, ctx.platform, 1],
2287
+ [rule.account, ctx.account, 2],
2288
+ [rule.peer, ctx.peer, 4]
2289
+ ];
2290
+ let score = 0;
2291
+ for (const [want, got, weight] of fields) {
2292
+ if (want === void 0) continue;
2293
+ if (want !== got) return 0;
2294
+ score += weight;
2295
+ }
2296
+ return score;
2297
+ }
2298
+ function bindingStrategy(bindings, inner) {
2299
+ return (event) => `${sanitize(bindings.agentFor(event))}-${inner(event)}`;
2300
+ }
2301
+
2302
+ // src/session/scoped-strategy.ts
2303
+ var join3 = (...segments) => segments.map(sanitize).join("-");
2304
+ function invalid(message, detail) {
2305
+ return new GatewayConfigurationError("gateway", {
2306
+ code: "invalid_session_scope",
2307
+ message: `gateway: invalid_session_scope: ${message}`,
2308
+ ...detail === void 0 ? {} : { detail }
2309
+ });
2310
+ }
2311
+ function scopedStrategy(options) {
2312
+ const { dmScope, peerLinks, accountLabel, groupScope = "channel", keys } = options;
2313
+ if (dmScope === "per-account-channel-peer" && (accountLabel === void 0 || accountLabel === "")) {
2314
+ throw invalid("per-account-channel-peer requires a non-empty accountLabel", "accountLabel");
2315
+ }
2316
+ if (peerLinks !== void 0) {
2317
+ for (const [from, peer] of peerLinks) {
2318
+ if (peer === "") throw invalid(`empty peer name for ${from}`, from);
2319
+ }
2320
+ }
2321
+ const dmKey = (platform, senderId) => {
2322
+ switch (dmScope) {
2323
+ case "main":
2324
+ return keys?.main ?? "_m-dm";
2325
+ case "per-peer": {
2326
+ const peer = peerLinks?.get(`${platform}:${senderId}`);
2327
+ if (peer === void 0) return join3(platform, "dm", senderId);
2328
+ return keys?.peer === void 0 ? `_p-dm-${sanitize(peer)}` : keys.peer(peer);
2329
+ }
2330
+ case "per-channel-peer":
2331
+ return join3(platform, "dm", senderId);
2332
+ case "per-account-channel-peer":
2333
+ return join3(platform, "dm", accountLabel ?? "", senderId);
2334
+ }
2335
+ };
2336
+ return (event) => {
2337
+ const { platform, channel, sender } = event;
2338
+ if (channel.type === "dm") return dmKey(platform, sender.id);
2339
+ if (channel.type === "thread" && channel.topicId !== void 0) {
2340
+ return join3(platform, "tpc", channel.id, channel.topicId);
2341
+ }
2342
+ return groupScope === "channel-sender" ? join3(platform, "grp", channel.id, sender.id) : join3(platform, "grp", channel.id);
2343
+ };
2344
+ }
2345
+
2346
+ // src/text/chunk.ts
2347
+ function searchBoundary(remaining, window, boundaries) {
2348
+ let cut = window;
2349
+ for (const b of boundaries) {
2350
+ cut = remaining.lastIndexOf(b, window);
2351
+ if (cut >= window * 0.5) return cut;
2352
+ }
2353
+ return cut;
2354
+ }
2355
+ function assertPositiveInt(label, value) {
2356
+ if (!Number.isInteger(value) || value <= 0) {
2357
+ throw new RangeError(`${label} must be a positive integer, received ${value}`);
2358
+ }
2359
+ }
2360
+ function guardSurrogate(text, cut) {
2361
+ if (cut >= text.length) return cut;
2362
+ const code = text.charCodeAt(cut);
2363
+ return code >= 56320 && code <= 57343 ? cut - 1 : cut;
2364
+ }
2365
+ function findCut(remaining, window, boundaries, lastResort, surrogateGuard) {
2366
+ let cut = searchBoundary(remaining, window, boundaries);
2367
+ if (cut < window * 0.5) {
2368
+ cut = lastResort === "last-boundary" && cut > 0 ? cut : window;
2369
+ }
2370
+ if (surrogateGuard) cut = guardSurrogate(remaining, cut);
2371
+ return cut <= 0 ? window : cut;
2372
+ }
2373
+ var isLineEnd = (ch) => ch === "\n" || ch === "\r";
2374
+ function startsTableRow(text, from) {
2375
+ let at = from;
2376
+ while (at < text.length && /^[^\S\r\n]$/.test(text[at] ?? "")) at += 1;
2377
+ return text[at] === "|";
2378
+ }
2379
+ function rowSafeCut(text, cut, window) {
2380
+ const start = tableRowStart(text, cut);
2381
+ if (start === void 0 || rowLength(text, start, cut, window) > window) return void 0;
2382
+ let end = start;
2383
+ while (end > 0 && isLineEnd(text[end - 1])) end -= 1;
2384
+ return end > 0 ? { end, start } : void 0;
2385
+ }
2386
+ function tableRowStart(text, cut) {
2387
+ if (cut >= text.length || isLineEnd(text[cut])) return void 0;
2388
+ let start = cut;
2389
+ while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;
2390
+ return start > 0 && startsTableRow(text, start) ? start : void 0;
2391
+ }
2392
+ function rowLength(text, start, cut, window) {
2393
+ let rowEnd = cut;
2394
+ while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;
2395
+ return rowEnd - start;
2396
+ }
2397
+ function rowStep(remaining, cut, window) {
2398
+ const moved = rowSafeCut(remaining, cut, window);
2399
+ if (moved === void 0) return void 0;
2400
+ return { chunk: remaining.slice(0, moved.end), remaining: remaining.slice(moved.start) };
2401
+ }
2402
+ function stepBeforeFence(remaining, region) {
2403
+ let end = region.start;
2404
+ while (end > 0 && isLineEnd(remaining[end - 1])) end -= 1;
2405
+ if (end === 0) return void 0;
2406
+ return { chunk: remaining.slice(0, end), remaining: remaining.slice(region.start) };
2407
+ }
2408
+ function stepThroughFence(remaining, region, window, surrogateGuard) {
2409
+ const eol = openerEol(remaining, region);
2410
+ const room = window - region.closer.length - eol.length;
2411
+ if (room <= region.contentStart) return void 0;
2412
+ let at = remaining.lastIndexOf("\n", room);
2413
+ let rest = at + 1;
2414
+ if (at < region.contentStart) {
2415
+ at = surrogateGuard ? guardSurrogate(remaining, room) : room;
2416
+ rest = at;
2417
+ } else if (remaining[at - 1] === "\r") {
2418
+ at -= 1;
2419
+ }
2420
+ return {
2421
+ chunk: `${remaining.slice(0, at)}${eol}${region.closer}`,
2422
+ remaining: `${region.opener}${eol}${remaining.slice(rest)}`
2423
+ };
2424
+ }
2425
+ function fenceStep(remaining, cut, window, surrogateGuard) {
2426
+ const region = fenceAt(scanFences(remaining), cut);
2427
+ if (region === void 0) return void 0;
2428
+ return cut <= region.openerEnd ? stepBeforeFence(remaining, region) : stepThroughFence(remaining, region, window, surrogateGuard);
2429
+ }
2430
+ function chunkText(text, options) {
2431
+ const {
2432
+ limit,
2433
+ safeLimit = limit,
2434
+ boundaries = ["\n\n", "\n", " "],
2435
+ lastResort = "window",
2436
+ surrogateGuard = false,
2437
+ stripLeading = /^\n+/,
2438
+ trimParts = false,
2439
+ keepTableRows = false
2440
+ } = options;
2441
+ assertPositiveInt("chunkText: limit", limit);
2442
+ assertPositiveInt("chunkText: safeLimit", safeLimit);
2443
+ if (safeLimit > limit) {
2444
+ throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);
2445
+ }
2446
+ const finalize = (parts2) => trimParts ? parts2.map((p) => p.trim()).filter((p) => p.length > 0) : parts2;
2447
+ if (text.length <= limit) {
2448
+ return finalize([text]);
2449
+ }
2450
+ const parts = [];
2451
+ const hasFence = scanFences(text).length > 0;
2452
+ let remaining = text;
2453
+ while (remaining.length > safeLimit) {
2454
+ const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);
2455
+ const step = (hasFence ? fenceStep(remaining, cut, safeLimit, surrogateGuard) : void 0) ?? (keepTableRows ? rowStep(remaining, cut, safeLimit) : void 0) ?? {
2456
+ chunk: remaining.slice(0, cut),
2457
+ remaining: remaining.slice(cut).replace(stripLeading, "")
2458
+ };
2459
+ parts.push(step.chunk);
2460
+ remaining = step.remaining;
2461
+ }
2462
+ if (remaining.length > 0) parts.push(remaining);
2463
+ return finalize(parts);
2464
+ }
2465
+ function chunkByGrapheme(text, options) {
2466
+ const { limit, partLimit = limit } = options;
2467
+ assertPositiveInt("chunkByGrapheme: limit", limit);
2468
+ assertPositiveInt("chunkByGrapheme: partLimit", partLimit);
2469
+ if (text.length === 0) return [""];
2470
+ if (text.length <= limit) return [text];
2471
+ const regions = scanFences(text);
2472
+ if (regions.length > 0) return chunkFencedByGrapheme(text, partLimit, regions);
2473
+ const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
2474
+ const parts = [];
2475
+ let buf = "";
2476
+ for (const { segment } of segmenter.segment(text)) {
2477
+ if (buf.length + segment.length > partLimit) {
2478
+ if (buf.length > 0) parts.push(buf);
2479
+ buf = "";
2480
+ }
2481
+ buf += segment;
2482
+ }
2483
+ if (buf.length > 0) parts.push(buf);
2484
+ return parts;
2485
+ }
2486
+ function graphemeBoundaries(text) {
2487
+ const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
2488
+ const starts = Array.from(segmenter.segment(text), (s) => s.index);
2489
+ starts.push(text.length);
2490
+ return (pos, max) => {
2491
+ const after = starts.filter((b) => b > pos);
2492
+ const within = after.filter((b) => b <= max);
2493
+ return within.at(-1) ?? after[0] ?? text.length;
2494
+ };
2495
+ }
2496
+ function chunkFencedByGrapheme(text, partLimit, regions) {
2497
+ const boundaryUpTo = graphemeBoundaries(text);
2498
+ const parts = [];
2499
+ let pos = 0;
2500
+ let prefix = "";
2501
+ while (prefix.length + (text.length - pos) > partLimit) {
2502
+ const room = partLimit - prefix.length;
2503
+ const plain2 = boundaryUpTo(pos, pos + room);
2504
+ const region = fenceAt(regions, plain2);
2505
+ const next = region === void 0 ? { cut: plain2, suffix: "", reopen: "" } : fenceGraphemeCut(text, region, pos, plain2, room, boundaryUpTo);
2506
+ parts.push(prefix + text.slice(pos, next.cut) + next.suffix);
2507
+ pos = next.cut;
2508
+ prefix = next.reopen;
2509
+ }
2510
+ parts.push(prefix + text.slice(pos));
2511
+ return parts;
2512
+ }
2513
+ function fenceGraphemeCut(text, region, pos, plain2, room, boundaryUpTo) {
2514
+ const none = { cut: plain2, suffix: "", reopen: "" };
2515
+ if (plain2 <= region.openerEnd) {
2516
+ return region.start > pos ? { ...none, cut: region.start } : none;
2517
+ }
2518
+ const eol = openerEol(text, region);
2519
+ const max = pos + room - region.closer.length - eol.length;
2520
+ const floor = Math.max(pos, region.contentStart);
2521
+ if (max <= floor) return none;
2522
+ let at = boundaryUpTo(pos, max);
2523
+ const nl = text.lastIndexOf("\n", at - 1);
2524
+ if (nl >= floor - 1 && nl + 1 > pos) at = nl + 1;
2525
+ if (at <= pos || at > max) return none;
2526
+ if (fenceAt([region], at) === void 0) return { ...none, cut: at };
2527
+ const closes = isLineEnd(text[at - 1]);
2528
+ return { cut: at, suffix: (closes ? "" : eol) + region.closer, reopen: region.opener + eol };
2529
+ }
2530
+
2531
+ // src/text/split-rows.ts
2532
+ var ROW_BLANK = /^[^\S\r\n]$/;
2533
+ function isLineEnd2(character) {
2534
+ return character === "\n" || character === "\r";
2535
+ }
2536
+ function startsTableRow2(text, from) {
2537
+ let at = from;
2538
+ while (at < text.length && ROW_BLANK.test(text[at] ?? "")) at += 1;
2539
+ return text[at] === "|";
2540
+ }
2541
+ function lineStartBefore(text, cut, partStart) {
2542
+ let at = cut;
2543
+ while (at > partStart && !isLineEnd2(text[at - 1])) at -= 1;
2544
+ return at;
2545
+ }
2546
+ function lineEndFrom(text, cut, bound) {
2547
+ let at = cut;
2548
+ while (at < text.length && at <= bound && !isLineEnd2(text[at])) at += 1;
2549
+ return at;
2550
+ }
2551
+ function advance(text, from, count, codepoint) {
2552
+ if (!codepoint) return Math.min(from + count, text.length);
2553
+ let at = from;
2554
+ for (let left = count; left > 0 && at < text.length; left -= 1) {
2555
+ at += (text.codePointAt(at) ?? 0) > 65535 ? 2 : 1;
2556
+ }
2557
+ return at;
2558
+ }
2559
+ function rowSafeCut2(text, partStart, cut, partLimit, codepoint) {
2560
+ const lineStart = lineStartBefore(text, cut, partStart);
2561
+ if (lineStart <= partStart || lineStart === cut) return cut;
2562
+ if (isLineEnd2(text[cut]) || !startsTableRow2(text, lineStart)) return cut;
2563
+ return rowFits(text, lineStart, cut, partLimit, codepoint) ? lineStart : cut;
2564
+ }
2565
+ function rowFits(text, lineStart, cut, partLimit, codepoint) {
2566
+ const window = lineStart + (codepoint ? 2 * partLimit : partLimit);
2567
+ const end = lineEndFrom(text, cut, window);
2568
+ if (end > window) return false;
2569
+ if (!codepoint) return true;
2570
+ let units = 0;
2571
+ for (let at = lineStart; at < end; units += 1) {
2572
+ if (units >= partLimit) return false;
2573
+ at += (text.codePointAt(at) ?? 0) > 65535 ? 2 : 1;
2574
+ }
2575
+ return true;
2576
+ }
2577
+ function graphemeCut(segments, start, limitCut) {
2578
+ const segment = segments.containing(limitCut);
2579
+ if (segment === void 0 || segment.index >= limitCut) return limitCut;
2580
+ return segment.index > start ? segment.index : segment.index + segment.segment.length;
2581
+ }
2582
+ function readUnit(partLimit, options) {
2583
+ const unit = options.unit ?? "utf16";
2584
+ if (unit !== "utf16" && unit !== "codepoint") {
2585
+ throw new RangeError(
2586
+ `splitKeepingRows: unit must be "utf16" or "codepoint", got ${String(unit)}`
2587
+ );
2588
+ }
2589
+ if (unit === "codepoint" && !(Number.isInteger(partLimit) && partLimit > 0)) {
2590
+ throw new RangeError(
2591
+ `splitKeepingRows: partLimit must be a positive integer, got ${partLimit}`
2592
+ );
2593
+ }
2594
+ return unit === "codepoint";
2595
+ }
2596
+ function splitKeepingRows(text, partLimit, options = {}) {
2597
+ const codepoint = readUnit(partLimit, options);
2598
+ const segments = new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(text);
2599
+ const parts = [];
2600
+ let start = 0;
2601
+ let limitCut = advance(text, start, partLimit, codepoint);
2602
+ while (limitCut < text.length) {
2603
+ const grapheme = graphemeCut(segments, start, limitCut);
2604
+ if (codepoint && grapheme > limitCut) {
2605
+ throw new RangeError(
2606
+ `splitKeepingRows: a grapheme at offset ${start} is longer than ${partLimit} code points`
2607
+ );
2608
+ }
2609
+ const cut = rowSafeCut2(text, start, grapheme, partLimit, codepoint);
2610
+ if (cut <= start) {
2611
+ throw new RangeError(`splitKeepingRows: no progress at offset ${start} of ${text.length}`);
2612
+ }
2613
+ parts.push(text.slice(start, cut));
2614
+ start = cut;
2615
+ limitCut = advance(text, start, partLimit, codepoint);
2616
+ }
2617
+ if (start < text.length) parts.push(text.slice(start));
2618
+ return parts;
2619
+ }
2620
+
2621
+ // src/webhook/deliver-status.ts
2622
+ function statusForDeliver(outcomes) {
2623
+ let status = 200;
2624
+ for (const outcome of outcomes) {
2625
+ if (outcome === "handler_threw") {
2626
+ status = 500;
2627
+ } else if (outcome === "no_handler") {
2628
+ if (status === 200) status = 503;
2629
+ } else if (outcome !== "ok") {
2630
+ throw new Error(`unknown deliver outcome: ${outcome}`);
2631
+ }
2632
+ }
2633
+ return status;
2634
+ }
2635
+
2636
+ // src/webhook/express-server.ts
2637
+ async function loadPeer(load2, onMissing) {
2638
+ try {
2639
+ const mod = await load2();
2640
+ return mod.default ?? mod;
2641
+ } catch {
2642
+ onMissing();
2643
+ }
2644
+ }
2645
+ function rawBodyCapture(tag, options = {}) {
2646
+ const maxBytes = options.maxBytes ?? DEFAULT_WEBHOOK_MAX_BYTES;
2647
+ if (!(maxBytes >= 0)) {
2648
+ throw new RangeError(
2649
+ `[${tag}] rawBodyCapture: maxBytes must be a number of zero or more (Infinity allowed), got ${maxBytes}`
2650
+ );
2651
+ }
2652
+ return (rawReq, rawRes, next) => {
2653
+ const req = rawReq;
2654
+ if (req.readableEnded === true || req.complete === true) {
2655
+ reportDiagnostic(
2656
+ tag,
2657
+ "raw body already consumed before signature capture \u2014 mount this router BEFORE any global body parser, or signature verification cannot see the bytes it must hash"
2658
+ );
2659
+ req.rawBody = "";
2660
+ next();
2661
+ return;
2662
+ }
2663
+ let buf = "";
2664
+ let bytes = 0;
2665
+ let refused2 = declaredLength(req) > maxBytes;
2666
+ let settled = false;
2667
+ req.setEncoding("utf8");
2668
+ req.on("data", (chunk) => {
2669
+ if (refused2 || settled) return;
2670
+ bytes += Buffer.byteLength(chunk);
2671
+ if (bytes > maxBytes) {
2672
+ refused2 = true;
2673
+ buf = "";
2674
+ return;
2675
+ }
2676
+ buf += chunk;
2677
+ });
2678
+ req.on("end", () => {
2679
+ if (settled) return;
2680
+ settled = true;
2681
+ if (refused2) {
2682
+ answerTooLarge(rawRes, tag, maxBytes);
2683
+ return;
2684
+ }
2685
+ req.rawBody = buf;
2686
+ next();
2687
+ });
2688
+ req.on("error", (err) => {
2689
+ if (settled) return;
2690
+ settled = true;
2691
+ if (refused2) return;
2692
+ next(err);
2693
+ });
2694
+ };
2695
+ }
2696
+ var DEFAULT_WEBHOOK_MAX_BYTES = 1024 * 1024;
2697
+ function declaredLength(req) {
2698
+ const value = req.headers?.["content-length"];
2699
+ const declared = Number(Array.isArray(value) ? value[0] : value);
2700
+ return Number.isFinite(declared) ? declared : 0;
2701
+ }
2702
+ function answerTooLarge(res, tag, maxBytes) {
2703
+ reportDiagnostic(tag, `refused a request (413): body larger than ${maxBytes} bytes`);
2704
+ res.status(413).json({ error: "request body too large" });
2705
+ }
2706
+ function listenerLifecycle(opts) {
2707
+ let started = false;
2708
+ let stopped = false;
2709
+ let listener;
2710
+ return {
2711
+ async start() {
2712
+ if (started || opts.injected) {
2713
+ started = true;
2714
+ return;
2715
+ }
2716
+ stopped = false;
2717
+ await new Promise((resolve, reject) => {
2718
+ const settle = (err) => {
2719
+ if (err === void 0) resolve();
2720
+ else reject(err);
2721
+ };
2722
+ const current = opts.app.listen(opts.port, settle);
2723
+ listener = current;
2724
+ current.once?.("error", settle);
2725
+ }).catch((err) => {
2726
+ listener = void 0;
2727
+ throw err;
2728
+ });
2729
+ started = true;
2730
+ },
2731
+ async stop() {
2732
+ if (stopped) return;
2733
+ stopped = true;
2734
+ started = false;
2735
+ const current = listener;
2736
+ listener = void 0;
2737
+ if (current === void 0) return;
2738
+ await new Promise((resolve) => {
2739
+ current.close(() => resolve());
2740
+ });
2741
+ }
2742
+ };
2743
+ }
2744
+
2745
+ // src/webhook/fetch-handler.ts
2746
+ var TOO_LARGE = /* @__PURE__ */ Symbol("too-large");
2747
+ function defaultPlatformFor(url) {
2748
+ const marker = "/webhooks/";
2749
+ const at = url.pathname.lastIndexOf(marker);
2750
+ if (at < 0) return void 0;
2751
+ const rest = url.pathname.slice(at + marker.length).replace(/\/+$/, "");
2752
+ const last = rest.split("/").pop();
2753
+ return last ? last : void 0;
2754
+ }
2755
+ function plain(status, extra) {
2756
+ return new Response(null, { status, headers: extra });
2757
+ }
2758
+ function tooLarge() {
2759
+ return plain(413, { connection: "close" });
2760
+ }
2761
+ async function readCapped(request, max) {
2762
+ const declared = request.headers.get("content-length");
2763
+ if (declared !== null && Number(declared) > max) return TOO_LARGE;
2764
+ if (request.body === null) return "";
2765
+ const reader = request.body.getReader();
2766
+ const chunks = [];
2767
+ let total = 0;
2768
+ for (; ; ) {
2769
+ const { done, value } = await reader.read();
2770
+ if (done) break;
2771
+ total += value.byteLength;
2772
+ if (total > max) {
2773
+ await reader.cancel().catch(() => void 0);
2774
+ return TOO_LARGE;
2775
+ }
2776
+ chunks.push(value);
2777
+ }
2778
+ const joined = new Uint8Array(total);
2779
+ let offset = 0;
2780
+ for (const chunk of chunks) {
2781
+ joined.set(chunk, offset);
2782
+ offset += chunk.byteLength;
2783
+ }
2784
+ return new TextDecoder().decode(joined);
2785
+ }
2786
+ function answerResponse(answer) {
2787
+ const headers = {};
2788
+ if (answer.contentType !== void 0) headers["content-type"] = answer.contentType;
2789
+ return new Response(answer.body ?? null, { status: answer.status, headers });
2790
+ }
2791
+ async function runDefault(webhook, adapter, request) {
2792
+ if (!await webhook.verify(adapter, request)) return plain(401);
2793
+ let payload;
2794
+ try {
2795
+ payload = JSON.parse(request.rawBody);
2796
+ } catch {
2797
+ return plain(400);
2798
+ }
2799
+ const result = await webhook.ingest(adapter, payload);
2800
+ if (result === "delivered") return plain(200);
2801
+ return plain(result === "no_handler" ? 503 : 400);
2802
+ }
2803
+ function headersOf(request) {
2804
+ const out = {};
2805
+ request.headers.forEach((value, key) => {
2806
+ out[key] = value;
2807
+ });
2808
+ return out;
2809
+ }
2810
+ async function readBody(request, max) {
2811
+ let body;
2812
+ try {
2813
+ body = await readCapped(request, max);
2814
+ } catch {
2815
+ return plain(400);
2816
+ }
2817
+ return body === TOO_LARGE ? tooLarge() : body;
2818
+ }
2819
+ function createWebhookHandler(options) {
2820
+ const max = options.maxBodyBytes ?? DEFAULT_WEBHOOK_MAX_BYTES;
2821
+ const platformFor = options.platformFor ?? defaultPlatformFor;
2822
+ const routes = /* @__PURE__ */ new Map();
2823
+ for (const channel of options.channels) {
2824
+ if (channel.descriptor.transport === "webhook")
2825
+ routes.set(channel.descriptor.platform, channel);
2826
+ }
2827
+ const route = (url) => {
2828
+ const platform = platformFor(url);
2829
+ return platform === void 0 ? void 0 : routes.get(platform);
2830
+ };
2831
+ return async (request) => {
2832
+ const channel = route(new URL(request.url));
2833
+ if (channel === void 0) return plain(404);
2834
+ const platform = channel.descriptor.platform;
2835
+ if (!options.isStarted(platform)) return plain(503);
2836
+ const webhook = channel.descriptor.webhook;
2837
+ const refused2 = refuseEarly(webhook, channel.adapter, request);
2838
+ if (refused2 !== void 0) return refused2;
2839
+ const rawBody = await readBody(request, max);
2840
+ if (typeof rawBody !== "string") return rawBody;
2841
+ try {
2842
+ return await dispatch(webhook, channel.adapter, {
2843
+ rawBody,
2844
+ headers: headersOf(request),
2845
+ method: request.method.toUpperCase(),
2846
+ url: request.url
2847
+ });
2848
+ } catch (error) {
2849
+ options.onError?.(platform, error);
2850
+ return plain(500);
2851
+ }
2852
+ };
2853
+ }
2854
+ function refuseEarly(webhook, adapter, request) {
2855
+ return refuseMethod(webhook, request) ?? precheckAnswer(webhook, adapter, request);
2856
+ }
2857
+ function precheckAnswer(webhook, adapter, request) {
2858
+ if (webhook.precheck === void 0) return void 0;
2859
+ const answer = webhook.precheck(adapter, {
2860
+ headers: headersOf(request),
2861
+ method: request.method.toUpperCase(),
2862
+ url: request.url
2863
+ });
2864
+ return answer === void 0 ? void 0 : answerResponse(answer);
2865
+ }
2866
+ function refuseMethod(webhook, request) {
2867
+ const methods = webhook.methods ?? ["POST"];
2868
+ const method = request.method.toUpperCase();
2869
+ if (methods.some((m) => m.toUpperCase() === method)) return void 0;
2870
+ return plain(405, { allow: methods.join(", ") });
2871
+ }
2872
+ async function dispatch(webhook, adapter, request) {
2873
+ if (webhook.handle !== void 0) return answerResponse(await webhook.handle(adapter, request));
2874
+ return runDefault(webhook, adapter, request);
2875
+ }
2876
+ function safeEqualString(expected, received) {
2877
+ if (typeof expected !== "string" || typeof received !== "string") return false;
2878
+ if (expected.length === 0 || received.length === 0) return false;
2879
+ const a = Buffer.from(expected, "utf8");
2880
+ const b = Buffer.from(received, "utf8");
2881
+ if (a.length !== b.length) return false;
2882
+ return crypto.timingSafeEqual(a, b);
2883
+ }
2884
+ function stripPrefix(signature, prefix) {
2885
+ if (typeof signature !== "string" || signature.length === 0) return null;
2886
+ if (!prefix) return signature;
2887
+ if (!signature.startsWith(prefix)) return null;
2888
+ const rest = signature.slice(prefix.length);
2889
+ return rest.length === 0 ? null : rest;
2890
+ }
2891
+ function normalize2(value, encoding, caseInsensitive) {
2892
+ return encoding === "hex" && caseInsensitive ? value.toLowerCase() : value;
2893
+ }
2894
+ function verifyHmac(opts) {
2895
+ const secrets = typeof opts.secrets === "string" ? [opts.secrets] : [...opts.secrets];
2896
+ if (secrets.length === 0 || secrets.some((s) => typeof s !== "string" || s.length === 0)) {
2897
+ throw new RangeError(
2898
+ "verifyHmac: `secrets` must be a non-empty string or a non-empty list of non-empty strings"
2899
+ );
2900
+ }
2901
+ const received = stripPrefix(opts.signature, opts.prefix);
2902
+ if (received === null) return false;
2903
+ const ci = opts.caseInsensitive === true;
2904
+ const got = normalize2(received, opts.encoding, ci);
2905
+ let ok = false;
2906
+ for (const secret of secrets) {
2907
+ const expected = crypto.createHmac(opts.algorithm, secret).update(opts.message).digest(opts.encoding);
2908
+ if (safeEqualString(normalize2(expected, opts.encoding, ci), got)) ok = true;
2909
+ }
2910
+ return ok;
2911
+ }
2912
+ function verifyDigest(opts) {
2913
+ const received = stripPrefix(opts.signature, opts.prefix);
2914
+ if (received === null) return false;
2915
+ const expected = crypto.createHash(opts.algorithm).update(opts.message).digest(opts.encoding);
2916
+ return safeEqualString(expected, received);
2917
+ }
2918
+
2919
+ exports.BasePlatformAdapter = BasePlatformAdapter;
2920
+ exports.CREDENTIAL_SHAPES = CREDENTIAL_SHAPES;
2921
+ exports.DEFAULT_WEBHOOK_MAX_BYTES = DEFAULT_WEBHOOK_MAX_BYTES;
2922
+ exports.DeliveryRouter = DeliveryRouter;
2923
+ exports.GatewayConfigurationError = GatewayConfigurationError;
2924
+ exports.GatewayLifecycleError = GatewayLifecycleError;
2925
+ exports.GatewayRunner = GatewayRunner;
2926
+ exports.HookExecutor = HookExecutor;
2927
+ exports.JsonRpcLineClient = JsonRpcLineClient;
2928
+ exports.ReconnectBackoff = ReconnectBackoff;
2929
+ exports.SeenIds = SeenIds;
2930
+ exports.SessionRouter = SessionRouter;
2931
+ exports.WeixinAdapterBase = WeixinAdapterBase;
2932
+ exports.bindingStrategy = bindingStrategy;
2933
+ exports.channelConfigReaders = channelConfigReaders;
2934
+ exports.channelRendering = channelRendering;
2935
+ exports.chunkByGrapheme = chunkByGrapheme;
2936
+ exports.chunkText = chunkText;
2937
+ exports.commandHook = commandHook;
2938
+ exports.configFromEnv = configFromEnv;
2939
+ exports.createAccessPolicyHook = createAccessPolicyHook;
2940
+ exports.createAgentBindings = createAgentBindings;
2941
+ exports.createChannels = createChannels;
2942
+ exports.createFileCredentialStore = createFileCredentialStore;
2943
+ exports.createFilePairingStore = createFilePairingStore;
2944
+ exports.createTokenCache = createTokenCache;
2945
+ exports.createWebhookHandler = createWebhookHandler;
2946
+ exports.decodeJwt = decodeJwt;
2947
+ exports.defaultStrategy = defaultStrategy;
2948
+ exports.groupActivationHook = groupActivationHook;
2949
+ exports.helpText = helpText;
2950
+ exports.isAuthenticatedSender = isAuthenticatedSender;
2951
+ exports.jwksKeySet = jwksKeySet;
2952
+ exports.listenerLifecycle = listenerLifecycle;
2953
+ exports.loadPeer = loadPeer;
2954
+ exports.maskSecrets = maskSecrets;
2955
+ exports.maskShapes = maskShapes;
2956
+ exports.parseChatCommand = parseChatCommand;
2957
+ exports.parseFlatXml = parseFlatXml;
2958
+ exports.rawBodyCapture = rawBodyCapture;
2959
+ exports.redactSecrets = redactSecrets;
2960
+ exports.refuseUnsupportedAttachments = refuseUnsupportedAttachments;
2961
+ exports.reportDiagnostic = reportDiagnostic;
2962
+ exports.safeEqualString = safeEqualString;
2963
+ exports.scanFences = scanFences;
2964
+ exports.scopedStrategy = scopedStrategy;
2965
+ exports.selectVariant = selectVariant;
2966
+ exports.sendErrorFromHttp = sendErrorFromHttp;
2967
+ exports.senderKey = senderKey;
2968
+ exports.splitKeepingRows = splitKeepingRows;
2969
+ exports.statusForDeliver = statusForDeliver;
2970
+ exports.toDialect = toDialect;
2971
+ exports.verifyDigest = verifyDigest;
2972
+ exports.verifyHmac = verifyHmac;
2973
+ exports.verifyRs256Jwt = verifyRs256Jwt;
2974
+ exports.withMediaUnderstanding = withMediaUnderstanding;
2975
+ //# sourceMappingURL=index.cjs.map
2976
+ //# sourceMappingURL=index.cjs.map