loopzero-gateway 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2852 @@
1
+ import { Writable, Readable } from 'node:stream';
2
+ import { KeyObject } from 'node:crypto';
3
+
4
+ /**
5
+ * A bounded set of ids, oldest evicted first, so a long-running process remembers what it delivered
6
+ * without growing for ever (NFR-003).
7
+ */
8
+ /**
9
+ * The ids an adapter has already delivered, at most `limit` of them.
10
+ */
11
+ declare class SeenIds {
12
+ private readonly limit;
13
+ private readonly ids;
14
+ /** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
15
+ constructor(limit?: number);
16
+ /**
17
+ * Record `id`.
18
+ *
19
+ * @returns `true` when the id was new, `false` when it was already held
20
+ */
21
+ add(id: string): boolean;
22
+ /** Whether `id` is held. */
23
+ has(id: string): boolean;
24
+ /** How many ids are held. */
25
+ get size(): number;
26
+ }
27
+
28
+ /**
29
+ * The event variants of the platforms added in S-003: batch 1 (B-354 to B-358) and batch 2 (B-359
30
+ * to B-363).
31
+ *
32
+ * They live beside `message-event.ts` rather than in it to keep that file, which holds the registry
33
+ * and its guard, within the 500-line budget. `message-event.ts` files each of them under its key
34
+ * in `PlatformEventRegistry`; the package barrel exports them.
35
+ */
36
+
37
+ /** Signal-specific event variant (B-354), received from `signal-cli jsonRpc`. */
38
+ interface SignalMessageEvent extends BaseMessageEvent {
39
+ readonly platform: "signal";
40
+ readonly signal: {
41
+ /** Envelope timestamp (ms since epoch); Signal's own message id. */
42
+ readonly timestamp: number;
43
+ /** Sender's phone number, when signal-cli knows it. */
44
+ readonly sourceNumber?: string;
45
+ /** Sender's account UUID, when signal-cli knows it. */
46
+ readonly sourceUuid?: string;
47
+ /** Group id, present only for a group message. */
48
+ readonly groupId?: string;
49
+ /** Raw signal-cli envelope — escape hatch. */
50
+ readonly raw: unknown;
51
+ };
52
+ }
53
+ /** iMessage-specific event variant (B-355), received from `imsg rpc` on a signed-in Mac. */
54
+ interface IMessageMessageEvent extends BaseMessageEvent {
55
+ readonly platform: "imessage";
56
+ readonly imessage: {
57
+ /** `imsg`'s numeric chat id; the send target for a reply. */
58
+ readonly chatId: number;
59
+ /** Messages' own message GUID. */
60
+ readonly guid: string;
61
+ /** `imsg`'s `is_group` for the chat; agrees with `channel.type === "group"`. */
62
+ readonly isGroup: boolean;
63
+ /** Participant handles (phone numbers or emails) as `imsg` reports them for the chat. */
64
+ readonly participants: readonly string[];
65
+ /** Raw `imsg` notification payload — escape hatch. */
66
+ readonly raw: unknown;
67
+ };
68
+ }
69
+ /** Google Chat-specific event variant (B-356), posted to the Chat app's HTTPS endpoint. */
70
+ interface GoogleChatMessageEvent extends BaseMessageEvent {
71
+ readonly platform: "google_chat";
72
+ readonly google_chat: {
73
+ /** The message's resource name, `spaces/<space>/messages/<message>`. */
74
+ readonly messageName: string;
75
+ /** The space's resource name, `spaces/<space>`; the send target for a reply. */
76
+ readonly spaceName: string;
77
+ /** The space's `spaceType` (`SPACE`, `GROUP_CHAT` or `DIRECT_MESSAGE`), when Chat sent one. */
78
+ readonly spaceType?: string;
79
+ /** The thread's resource name, when the message is in a thread. */
80
+ readonly threadName?: string;
81
+ /** Raw Chat event — escape hatch. */
82
+ readonly raw: unknown;
83
+ };
84
+ }
85
+ /** IRC-specific event variant (B-357), read from a PRIVMSG on the adapter's own connection. */
86
+ interface IrcMessageEvent extends BaseMessageEvent {
87
+ readonly platform: "irc";
88
+ readonly irc: {
89
+ /** Where the PRIVMSG was addressed: a channel, `#name`, or the adapter's own nick for a DM. */
90
+ readonly target: string;
91
+ /** The sender's nick, from the line's prefix. */
92
+ readonly nick: string;
93
+ /** True for a CTCP ACTION (`/me`); `text` then holds the action without its CTCP framing. */
94
+ readonly action: boolean;
95
+ /** The line's IRCv3 message tags, unescaped; empty when the server sent none. */
96
+ readonly tags: Readonly<Record<string, string>>;
97
+ /** The raw line as the server sent it, without CRLF — escape hatch. */
98
+ readonly raw: string;
99
+ };
100
+ }
101
+ /**
102
+ * Nextcloud Talk event variant (B-358), read from a bot webhook `Create` activity that carried a
103
+ * signature the adapter verified.
104
+ */
105
+ interface NextcloudTalkMessageEvent extends BaseMessageEvent {
106
+ readonly platform: "nextcloud_talk";
107
+ readonly nextcloud_talk: {
108
+ /** The conversation's token, the `target.id` of the activity; a reply goes to it. */
109
+ readonly roomToken: string;
110
+ /** Talk's id for the message, the activity's `object.id`. */
111
+ readonly messageId: string;
112
+ /** Who wrote it, as Talk names actors: `users/<id>`, `guests/<id>`, `bots/<id>`… */
113
+ readonly actorId: string;
114
+ /** The id of the message this one answers, when it is a reply. */
115
+ readonly replyToId?: string;
116
+ /** The parsed webhook body — escape hatch. */
117
+ readonly raw: unknown;
118
+ };
119
+ }
120
+ /** Nostr event variant (B-359): a NIP-17 direct message (kind 14) or a NIP-04 one (kind 4). */
121
+ interface NostrMessageEvent extends BaseMessageEvent {
122
+ readonly platform: "nostr";
123
+ readonly nostr: {
124
+ /** The sender's public key, 64 lowercase hex characters; the send target for a reply. */
125
+ readonly pubkey: string;
126
+ /** 14 for a NIP-17 rumor unwrapped from a gift wrap, 4 for a NIP-04 encrypted message. */
127
+ readonly kind: 4 | 14;
128
+ /** The message's `created_at` in Unix seconds, as its sender stated it. */
129
+ readonly createdAt: number;
130
+ /** The decrypted rumor or kind 4 event — escape hatch. */
131
+ readonly raw: unknown;
132
+ };
133
+ }
134
+ /** Feishu/Lark event variant (B-360), an `im.message.receive_v1` event from the long connection. */
135
+ interface FeishuLarkMessageEvent extends BaseMessageEvent {
136
+ readonly platform: "feishu_lark";
137
+ readonly feishu_lark: {
138
+ /** The chat's `chat_id`; the send target for a reply. */
139
+ readonly chatId: string;
140
+ /** The message's `message_id`. */
141
+ readonly messageId: string;
142
+ /** The sender's `open_id`. */
143
+ readonly openId: string;
144
+ /** The event's `event_id`, which a redelivery repeats. */
145
+ readonly eventId: string;
146
+ /** Raw event — escape hatch. */
147
+ readonly raw: unknown;
148
+ };
149
+ }
150
+ /** Synology Chat event variant (B-361), an outgoing bot callback from the NAS. */
151
+ interface SynologyChatMessageEvent extends BaseMessageEvent {
152
+ readonly platform: "synology_chat";
153
+ readonly synology_chat: {
154
+ /** The sender's numeric user id; a reply goes to `user_ids: [userId]`. */
155
+ readonly userId: number;
156
+ /** The sender's user name. */
157
+ readonly username: string;
158
+ /** The callback's `post_id`. */
159
+ readonly postId: string;
160
+ /** The callback's `timestamp`. */
161
+ readonly timestamp: number;
162
+ /** The parsed callback body — escape hatch. */
163
+ readonly raw: unknown;
164
+ };
165
+ }
166
+ /** Tlon event variant (B-362), a DM read from the ship's `chat` app at `/v3`. */
167
+ interface TlonUrbitMessageEvent extends BaseMessageEvent {
168
+ readonly platform: "tlon_urbit";
169
+ readonly tlon_urbit: {
170
+ /** The sender's ship, `~name`; the send target for a reply. */
171
+ readonly ship: string;
172
+ /** The message id, `<ship>/<@ud>`. */
173
+ readonly messageId: string;
174
+ /** The essay's `sent` time in Unix milliseconds. */
175
+ readonly sent: number;
176
+ /** The `/v3` event — escape hatch. */
177
+ readonly raw: unknown;
178
+ };
179
+ }
180
+ /** Buzz event variant (B-367), a `message.created` realtime event. */
181
+ interface BuzzMessageEvent extends BaseMessageEvent {
182
+ readonly platform: "buzz";
183
+ readonly buzz: {
184
+ /** The message's id. */
185
+ readonly messageId: string;
186
+ /** The channel the message was posted in; for a DM, the DM channel id. */
187
+ readonly channelId: string;
188
+ /** The workspace the event belongs to, when the event names one. */
189
+ readonly workspaceId: string;
190
+ /** The parent message id when the message is a thread reply, else `""`. */
191
+ readonly threadId: string;
192
+ /** The realtime cursor of the event, `""` when absent. */
193
+ readonly cursor: string;
194
+ /** The event object — escape hatch. */
195
+ readonly raw: unknown;
196
+ };
197
+ }
198
+ /** ClickClack event variant (B-366), a `message.created` realtime event. */
199
+ interface ClickClackMessageEvent extends BaseMessageEvent {
200
+ readonly platform: "clickclack";
201
+ readonly clickclack: {
202
+ /** The message's id. */
203
+ readonly messageId: string;
204
+ /** The channel the message was posted in; for a DM, the DM channel id. */
205
+ readonly channelId: string;
206
+ /** The workspace the event belongs to, when the event names one. */
207
+ readonly workspaceId: string;
208
+ /** The parent message id when the message is a thread reply, else `""`. */
209
+ readonly threadId: string;
210
+ /** The realtime cursor of the event, `""` when absent. */
211
+ readonly cursor: string;
212
+ /** The event object — escape hatch. */
213
+ readonly raw: unknown;
214
+ };
215
+ }
216
+ /** Zalo Personal event variant (B-365), a message read from a personal Zalo account's listener. */
217
+ interface ZaloPersonalMessageEvent extends BaseMessageEvent {
218
+ readonly platform: "zalo_personal";
219
+ readonly zalo_personal: {
220
+ /** The message's `msgId`. */
221
+ readonly messageId: string;
222
+ /** The conversation's id: the peer's uid for a direct chat, the group id for a group. */
223
+ readonly threadId: string;
224
+ /** `"user"` for a direct chat, `"group"` for a group. */
225
+ readonly threadType: "user" | "group";
226
+ /** The sender's uid. */
227
+ readonly senderUid: string;
228
+ /** The listener's message object — escape hatch. */
229
+ readonly raw: unknown;
230
+ };
231
+ }
232
+ /** Zalo Official Account event variant (B-364), a `user_send_text` webhook event. */
233
+ interface ZaloMessageEvent extends BaseMessageEvent {
234
+ readonly platform: "zalo";
235
+ readonly zalo: {
236
+ /** The message's `msg_id`. */
237
+ readonly messageId: string;
238
+ /** The sender's user id for this OA; the send target for a reply. */
239
+ readonly userId: string;
240
+ /** The Official Account's id (the event's `recipient.id`). */
241
+ readonly oaId: string;
242
+ /** The webhook event — escape hatch. */
243
+ readonly raw: unknown;
244
+ };
245
+ }
246
+ /** WeChat Official Account event variant, a text message pushed to the server URL. */
247
+ interface WeChatMessageEvent extends BaseMessageEvent {
248
+ readonly platform: "wechat";
249
+ readonly wechat: {
250
+ /** The message's `MsgId`. */
251
+ readonly messageId: string;
252
+ /** The sender's OpenID for this account; the send target for a reply. */
253
+ readonly openId: string;
254
+ /** The Official Account's original id (the message's `ToUserName`). */
255
+ readonly accountId: string;
256
+ /** The parsed XML fields — escape hatch. */
257
+ readonly raw: unknown;
258
+ };
259
+ }
260
+ /** Raft event variant, one wake delivered by the Raft CLI wake bridge. */
261
+ interface RaftMessageEvent extends BaseMessageEvent {
262
+ readonly platform: "raft";
263
+ readonly raft: {
264
+ /** The wake's id. */
265
+ readonly messageId: string;
266
+ /** Who woke the agent in Raft. */
267
+ readonly senderId: string;
268
+ /** The parsed wake line — escape hatch. */
269
+ readonly raw: unknown;
270
+ };
271
+ }
272
+ /** WeCom (企业微信) self-built application event variant, a text message pushed to the callback URL. */
273
+ interface WeComMessageEvent extends BaseMessageEvent {
274
+ readonly platform: "wecom";
275
+ readonly wecom: {
276
+ /** The message's `MsgId`. */
277
+ readonly messageId: string;
278
+ /** The sender's WeCom user id; the send target for a reply. */
279
+ readonly userId: string;
280
+ /** The corp id (the message's `ToUserName`). */
281
+ readonly corpId: string;
282
+ /** The parsed XML fields — escape hatch. */
283
+ readonly raw: unknown;
284
+ };
285
+ }
286
+ /** QQ Bot event variant, a C2C (direct) text message pushed to the signed webhook. */
287
+ interface QQMessageEvent extends BaseMessageEvent {
288
+ readonly platform: "qq";
289
+ readonly qq: {
290
+ /** The message's id; a reply is sent as a passive reply to it. */
291
+ readonly messageId: string;
292
+ /** The sender's `user_openid`; the send target for a reply. */
293
+ readonly userOpenId: string;
294
+ /** The webhook payload — escape hatch. */
295
+ readonly raw: unknown;
296
+ };
297
+ }
298
+ /** Yuanbao (元宝) bot event variant, a text message pushed to the signed callback URL. */
299
+ interface YuanbaoMessageEvent extends BaseMessageEvent {
300
+ readonly platform: "yuanbao";
301
+ readonly yuanbao: {
302
+ /** The message's id. */
303
+ readonly messageId: string;
304
+ /** The sender's Yuanbao user id; the send target for a reply. */
305
+ readonly userId: string;
306
+ /** The callback body — escape hatch. */
307
+ readonly raw: unknown;
308
+ };
309
+ }
310
+ /** Twitch event variant (B-363), a `channel.chat.message` EventSub notification. */
311
+ interface TwitchMessageEvent extends BaseMessageEvent {
312
+ readonly platform: "twitch";
313
+ readonly twitch: {
314
+ /** The channel's broadcaster user id; the send target for a reply. */
315
+ readonly broadcasterUserId: string;
316
+ /** The chatter's user id. */
317
+ readonly chatterUserId: string;
318
+ /** The chatter's login name. */
319
+ readonly chatterLogin: string;
320
+ /** The chat message's `message_id`. */
321
+ readonly messageId: string;
322
+ /** The notification's `event` object — escape hatch. */
323
+ readonly raw: unknown;
324
+ };
325
+ }
326
+ /** One tweet of a mention's thread, oldest first in {@link XMessageEvent.x}`.thread`. */
327
+ interface XThreadTweet {
328
+ readonly tweetId: string;
329
+ readonly authorId: string;
330
+ /** The author's handle, `""` when the API did not return it. */
331
+ readonly username: string;
332
+ readonly text: string;
333
+ }
334
+ /** X (Twitter) event variant, a tweet that mentions the bot account. */
335
+ interface XMessageEvent extends BaseMessageEvent {
336
+ readonly platform: "x";
337
+ readonly x: {
338
+ /** The mention tweet's id; a reply is posted under it. */
339
+ readonly tweetId: string;
340
+ /** The thread's conversation id; also the channel id. */
341
+ readonly conversationId: string;
342
+ /** The author's user id. */
343
+ readonly authorId: string;
344
+ /** The tweets the mention replies to, oldest first; empty when it starts a thread. */
345
+ readonly thread: readonly XThreadTweet[];
346
+ /** The tweet the mention quotes, when it quotes one. */
347
+ readonly quoted?: XThreadTweet;
348
+ /** `true` when the author is not allowlisted and was let in by guest mode. */
349
+ readonly guest: boolean;
350
+ /** The tweet object — escape hatch. */
351
+ readonly raw: unknown;
352
+ };
353
+ }
354
+
355
+ /**
356
+ * `MessageEvent` — canonical inbound shape every adapter emits (T1.1, ADR D173).
357
+ *
358
+ * Discriminated union keyed by `platform`. Platform-specific extensions live
359
+ * in optional sibling fields (`telegram?`, `discord?`) typed by the adapter
360
+ * package. The default narrow pattern is:
361
+ *
362
+ * ```typescript
363
+ * switch (event.platform) {
364
+ * case "telegram": return event.telegram.threadId; // narrowed
365
+ * case "discord": return event.discord.guildId; // narrowed
366
+ * }
367
+ * ```
368
+ *
369
+ * This union is **open to extension and closed to corruption**. It is derived from
370
+ * {@link PlatformEventRegistry}, an interface a package outside this repository extends through
371
+ * declaration merging — so a gateway can be authored, published and consumed without editing this
372
+ * file, while narrowing still holds over platforms declared here and elsewhere alike. Entries that
373
+ * are not well-formed event shapes agreeing with their own key are excluded rather than admitted.
374
+ *
375
+ * It was closed until 2026-08-23. `docs/adr/0001-message-event-closed-union.md` records why, and
376
+ * `docs/adr/0002-platform-event-registry.md` records what changed and what the guard costs.
377
+ *
378
+ * @public
379
+ */
380
+
381
+ /**
382
+ * The audio of a voice note an inbound message carries (B-715): read on demand, so an app whose
383
+ * `pre_inbound` hook refuses a sender never downloads the sender's media.
384
+ *
385
+ * Nothing is fetched until `read()` is called. The first call fetches; later calls return the
386
+ * same bytes. `read()` rejects when the platform cannot deliver them (the error message is safe
387
+ * to log: it never carries a credential).
388
+ */
389
+ interface InboundAudio {
390
+ /** The audio bytes, fetched on the first call and cached. */
391
+ read(): Promise<Uint8Array>;
392
+ /** The length in bytes the platform reported before any download; absent when it reported none. */
393
+ readonly size?: number;
394
+ /** The media type of the bytes, such as `audio/ogg`. */
395
+ readonly mediaType: string;
396
+ /** The length in whole seconds the platform reported; 0 when it reported none. */
397
+ readonly durationSeconds: number;
398
+ }
399
+ /** Fields common to every platform's inbound event. */
400
+ interface BaseMessageEvent {
401
+ /** Stable id used as a session-key segment and for dedup. */
402
+ readonly id: string;
403
+ /**
404
+ * Discriminator.
405
+ *
406
+ * Typed `string` here and narrowed to a literal by every variant. It cannot be `PlatformName`:
407
+ * that type is derived from the guarded union below, and the union is built out of shapes that
408
+ * extend this interface — naming it here would make the two reference each other (`TS2456`).
409
+ * Widening it is also what lets `PlatformName` be derived from the FILTERED union rather than
410
+ * from `keyof`, so a name and an event can never disagree about which platforms exist.
411
+ */
412
+ readonly platform: string;
413
+ /** Sender identity (opaque, platform-namespaced). */
414
+ readonly sender: {
415
+ readonly id: string;
416
+ readonly username?: string;
417
+ readonly displayName?: string;
418
+ };
419
+ /** Channel / chat scope (opaque, platform-namespaced). */
420
+ readonly channel: {
421
+ readonly id: string;
422
+ readonly type: "dm" | "group" | "thread";
423
+ readonly topicId?: string;
424
+ };
425
+ /** Plain-text content (caption for media-only messages; empty string when absent). */
426
+ readonly text: string;
427
+ /** Receipt timestamp (ms since epoch). */
428
+ readonly receivedAt: number;
429
+ /** Optional reply-target message id. */
430
+ readonly replyTo?: string;
431
+ /**
432
+ * Whether the bot was addressed: mentioned, replied to, or named by a command.
433
+ *
434
+ * Set by an adapter that can tell, independently of its `requireMention` option. `undefined`
435
+ * means the adapter could not tell (no bot identity, or a payload that carries only text);
436
+ * it is not the same as `false`.
437
+ */
438
+ readonly addressed?: boolean;
439
+ /**
440
+ * The voice note's audio, when the adapter read one (B-715). Absent for a message with no voice,
441
+ * and for a voice the adapter could not read.
442
+ */
443
+ readonly audio?: InboundAudio;
444
+ }
445
+ /** Telegram-specific event variant. */
446
+ interface TelegramMessageEvent extends BaseMessageEvent {
447
+ readonly platform: "telegram";
448
+ readonly telegram: {
449
+ readonly chatId: number;
450
+ readonly messageId: number;
451
+ readonly threadId?: number;
452
+ /** Raw grammy `Context` — narrowed by the adapter package. */
453
+ readonly raw: unknown;
454
+ };
455
+ }
456
+ /** Discord-specific event variant. */
457
+ interface DiscordMessageEvent extends BaseMessageEvent {
458
+ readonly platform: "discord";
459
+ readonly discord: {
460
+ readonly guildId: string | null;
461
+ readonly channelId: string;
462
+ readonly messageId: string;
463
+ /** Raw discord.js `Message` — narrowed by the adapter package. */
464
+ readonly raw: unknown;
465
+ };
466
+ }
467
+ /** Slack-specific event variant (ADR D274). */
468
+ interface SlackMessageEvent extends BaseMessageEvent {
469
+ readonly platform: "slack";
470
+ readonly slack: {
471
+ /** Slack workspace id (a.k.a. team_id). May be `undefined` for some legacy events. */
472
+ readonly teamId: string | undefined;
473
+ /** Slack channel id (Cxxxxxxxx | Gxxxxxxxx | Dxxxxxxxx). */
474
+ readonly channelId: string;
475
+ /** Slack user id (Uxxxxxxxx) or `"anonymous"` if absent. */
476
+ readonly userId: string;
477
+ /** Message timestamp = canonical Slack message id. */
478
+ readonly ts: string;
479
+ /** Set only when the message belongs to a thread. */
480
+ readonly threadTs?: string;
481
+ /** Slack message subtype (e.g. `"thread_broadcast"`). */
482
+ readonly subtype?: string;
483
+ /** Raw Bolt event body — narrowed by the adapter package. */
484
+ readonly raw: unknown;
485
+ };
486
+ }
487
+ /** WhatsApp-specific event variant (ADR D308). */
488
+ interface WhatsAppMessageEvent extends BaseMessageEvent {
489
+ readonly platform: "whatsapp";
490
+ readonly whatsapp: {
491
+ /** WhatsApp message id — `wamid.xxx` for cloud, `msg.id._serialized` for web. */
492
+ readonly wamid: string;
493
+ /** Meta-issued phone-number-id (cloud only; undefined for web bridge). */
494
+ readonly phoneNumberId?: string;
495
+ /** Contact's profile name when Meta provides it. */
496
+ readonly contactName?: string;
497
+ /**
498
+ * The address this arrived on, verbatim — what a reply must be sent to.
499
+ *
500
+ * `channel.id` is normalised to digits, which is what an allowlist compares and what a session
501
+ * key is built from. The normalisation strips the DOMAIN, and the domain is what says which
502
+ * kind of identifier it is: `@s.whatsapp.net` a phone, `@g.us` a group, `@lid` an account's
503
+ * linked identity. A note-to-self arrives addressed by LID, so answering `channel.id` rebuilds
504
+ * `…@s.whatsapp.net` — an address that does not exist, and a send that reports ok and lands
505
+ * nowhere (#84).
506
+ *
507
+ * `sendMessage` accepts this verbatim: a `to` containing `@` is already an address and is
508
+ * passed through untouched.
509
+ *
510
+ * Present on the baileys backend. The cloud backend addresses recipients by phone and has no
511
+ * JID to report.
512
+ */
513
+ readonly channelJid?: string;
514
+ /**
515
+ * Which backend produced this event.
516
+ *
517
+ * `baileys` joined `cloud` and `web` in 0.2: it speaks the WhatsApp Web multi-device
518
+ * protocol over a WebSocket, where `web` drives a headless browser. Consumers that
519
+ * switch exhaustively on this must handle the third case.
520
+ */
521
+ readonly backend: "cloud" | "web" | "baileys";
522
+ /** Raw envelope — backend-specific, narrowed by the adapter package. */
523
+ readonly raw: unknown;
524
+ };
525
+ }
526
+ /** Microsoft Teams-specific event variant (ADR D325). */
527
+ interface TeamsMessageEvent extends BaseMessageEvent {
528
+ readonly platform: "teams";
529
+ readonly teams: {
530
+ /** Teams activity id (`MessageActivity.id`). */
531
+ readonly activityId: string;
532
+ /** Teams conversation id. */
533
+ readonly conversationId: string;
534
+ /** Teams conversation classification — open string per SDK type. */
535
+ readonly conversationType: "personal" | "groupChat" | "channel" | (string & {});
536
+ /** Tenant id of the sender (Azure AD). */
537
+ readonly tenantId?: string;
538
+ /** Channel id (only when conversationType === "channel"). */
539
+ readonly channelId?: string;
540
+ /** Team id (only when conversationType === "channel"). */
541
+ readonly teamId?: string;
542
+ /** Raw Teams `MessageActivity` — narrowed by the adapter package. */
543
+ readonly raw: unknown;
544
+ };
545
+ }
546
+ /** Email-specific event variant (ADR D339). */
547
+ interface EmailMessageEvent extends BaseMessageEvent {
548
+ readonly platform: "email";
549
+ readonly email: {
550
+ /** Message-ID without `<>` braces. Use as `channel.topicId` for threading. */
551
+ readonly messageId: string;
552
+ /** Previous Message-ID this message replies to (without `<>`). */
553
+ readonly inReplyTo?: string;
554
+ /** Full References chain (oldest → newest, no braces). */
555
+ readonly references?: readonly string[];
556
+ /** Decoded Subject (fallback `"(no subject)"`). */
557
+ readonly subject: string;
558
+ /** Sender address (lowercased, normalized). */
559
+ readonly fromAddress: string;
560
+ /** Sender display name when present. */
561
+ readonly fromName?: string;
562
+ /** All To/Cc recipients lowercased; bot's own address EXCLUDED. */
563
+ readonly recipients: readonly string[];
564
+ /** Count of attachments (v0.1 drops payloads — see D335). */
565
+ readonly attachmentCount: number;
566
+ /** Raw `mailparser.ParsedMail` — escape hatch. */
567
+ readonly raw: unknown;
568
+ };
569
+ }
570
+ /** SMS-specific event variant (ADR D389). */
571
+ interface SMSMessageEvent extends BaseMessageEvent {
572
+ readonly platform: "sms";
573
+ readonly sms: {
574
+ /** Which backend processed this inbound. */
575
+ readonly backend: "twilio" | "plivo" | "vonage";
576
+ /** Provider message id (Twilio MessageSid, Plivo MessageUuid, Vonage messageId). */
577
+ readonly messageId: string;
578
+ /** Sender phone in E.164 format (D391). */
579
+ readonly from: string;
580
+ /** Recipient phone in E.164 format (D391). */
581
+ readonly to: string;
582
+ /** Raw webhook payload — backend-specific, narrowed by the adapter package. */
583
+ readonly raw: unknown;
584
+ };
585
+ }
586
+ /** Mattermost-specific event variant (ADR D397). */
587
+ interface MattermostMessageEvent extends BaseMessageEvent {
588
+ readonly platform: "mattermost";
589
+ readonly mattermost: {
590
+ /** Mattermost post id. */
591
+ readonly postId: string;
592
+ /** Channel id (Mattermost internal id). */
593
+ readonly channelId: string;
594
+ /** Team id the channel belongs to. */
595
+ readonly teamId: string;
596
+ /** When set, the message is a thread reply rooted at this post id (D399). */
597
+ readonly rootId?: string;
598
+ /** Original Mattermost channel type (`D`/`G`/`O`/`P`) before normalization (D402). */
599
+ readonly channelType: "D" | "G" | "O" | "P" | (string & {});
600
+ /** Raw `@mattermost/client` Post — escape hatch. */
601
+ readonly raw: unknown;
602
+ };
603
+ }
604
+ /** LINE-specific event variant (ADR D405). */
605
+ interface LineMessageEvent extends BaseMessageEvent {
606
+ readonly platform: "line";
607
+ readonly line: {
608
+ /** LINE source classification (D410). */
609
+ readonly sourceType: "user" | "group" | "room";
610
+ /** LINE source id (userId / groupId / roomId). */
611
+ readonly sourceId: string;
612
+ /** LINE message id. */
613
+ readonly messageId: string;
614
+ /** UserIds mentioned in the message (D409 — never inline). */
615
+ readonly mentionees: ReadonlyArray<string>;
616
+ /** Reply token (one-shot, 60s TTL). Adapter manages cache — caller should not use directly. */
617
+ readonly replyToken?: string;
618
+ /** Raw LINE webhook event — escape hatch. */
619
+ readonly raw: unknown;
620
+ };
621
+ }
622
+ /** Matrix-specific event variant (ADR D413). */
623
+ interface MatrixMessageEvent extends BaseMessageEvent {
624
+ readonly platform: "matrix";
625
+ readonly matrix: {
626
+ /** Matrix room id (`!xxx:server`). */
627
+ readonly roomId: string;
628
+ /** Matrix event id (`$xxx:server`). */
629
+ readonly eventId: string;
630
+ /** Number of joined members in the room — used for DM detection (D416). */
631
+ readonly memberCount: number;
632
+ /** Raw `matrix-js-sdk` `MatrixEvent` — escape hatch (D421). */
633
+ readonly raw: unknown;
634
+ };
635
+ }
636
+ /**
637
+ * The open registry every platform's inbound event is filed under.
638
+ *
639
+ * **This is an `interface` on purpose, and it must stay one.** An interface can be extended from
640
+ * another package through declaration merging; a type alias cannot. That single property is what
641
+ * lets a gateway be authored, published and consumed without editing this file — the capability
642
+ * B-008 measured as impossible (`TS2416`, compiled against the published declaration) and ADR-0002
643
+ * decided to unlock. Collapsing it back into a type alias would silently remove that capability
644
+ * while every test in this package still passed.
645
+ *
646
+ * A third-party gateway registers itself from its own package:
647
+ *
648
+ * ```typescript
649
+ * declare module "loopzero-gateway" {
650
+ * interface PlatformEventRegistry {
651
+ * acmechat: AcmeChatMessageEvent;
652
+ * }
653
+ * }
654
+ * ```
655
+ *
656
+ * @public
657
+ */
658
+ interface PlatformEventRegistry {
659
+ telegram: TelegramMessageEvent;
660
+ discord: DiscordMessageEvent;
661
+ slack: SlackMessageEvent;
662
+ whatsapp: WhatsAppMessageEvent;
663
+ teams: TeamsMessageEvent;
664
+ email: EmailMessageEvent;
665
+ sms: SMSMessageEvent;
666
+ mattermost: MattermostMessageEvent;
667
+ line: LineMessageEvent;
668
+ matrix: MatrixMessageEvent;
669
+ signal: SignalMessageEvent;
670
+ imessage: IMessageMessageEvent;
671
+ google_chat: GoogleChatMessageEvent;
672
+ irc: IrcMessageEvent;
673
+ nextcloud_talk: NextcloudTalkMessageEvent;
674
+ nostr: NostrMessageEvent;
675
+ feishu_lark: FeishuLarkMessageEvent;
676
+ synology_chat: SynologyChatMessageEvent;
677
+ tlon_urbit: TlonUrbitMessageEvent;
678
+ twitch: TwitchMessageEvent;
679
+ zalo_personal: ZaloPersonalMessageEvent;
680
+ zalo: ZaloMessageEvent;
681
+ wechat: WeChatMessageEvent;
682
+ wecom: WeComMessageEvent;
683
+ yuanbao: YuanbaoMessageEvent;
684
+ x: XMessageEvent;
685
+ qq: QQMessageEvent;
686
+ raft: RaftMessageEvent;
687
+ clickclack: ClickClackMessageEvent;
688
+ buzz: BuzzMessageEvent;
689
+ }
690
+ /**
691
+ * `true` only for `any` — the one type that would otherwise swallow the union.
692
+ *
693
+ * `any extends X` distributes to both branches of a conditional, so an ordinary
694
+ * `T extends BaseMessageEvent ? T : never` does NOT keep `any` out. This does: nothing but `any`
695
+ * makes `1 & T` accept `0`.
696
+ */
697
+ type IsAny<T> = 0 extends 1 & T ? true : false;
698
+ /**
699
+ * A registry key must be a literal, never the broad `string` an index signature produces.
700
+ *
701
+ * Measured in review: `interface PlatformEventRegistry { [key: string]: BaseMessageEvent }` is a
702
+ * LEGAL augmentation — every existing variant is assignable to the base — and without this it
703
+ * widens the whole platform name to `string`, so every typo becomes valid and every consumer's
704
+ * `switch` stops narrowing. That is the same collapse an `any` VALUE causes, arriving through the
705
+ * key side, and it is why both sides are gated.
706
+ */
707
+ type LiteralKey<K> = string extends K ? never : K;
708
+ /**
709
+ * The registry's LITERAL keys — index signatures dropped before `keyof` ever sees them.
710
+ *
711
+ * Filtering the value was not enough, measured twice. `keyof` over a registry carrying
712
+ * `{ [key: string]: BaseMessageEvent }` is `string | number`, and indexing a mapped type by that
713
+ * yields `never` for BOTH the union and the platform name: a hostile augmentation did not merely
714
+ * fail to join, it annihilated the union and broke every first-party narrowing site with
715
+ * `TS2339: Property 'telegram' does not exist on type 'never'`.
716
+ *
717
+ * It also fixes a second measured defect for free. Mapping over `keyof` directly is HOMOMORPHIC, so
718
+ * an OPTIONAL entry (`acmechat?: Event`, a shape an author writes by accident) kept its modifier and
719
+ * injected `undefined` into the union — `TS18048: 'e' is possibly 'undefined'` on a plain `switch`.
720
+ * Mapping over a computed key set is not homomorphic and drops the modifier. A `-?` was written
721
+ * here first as an explicit belt; the gate showed it could not be made to matter while this type is
722
+ * in place, so it was removed rather than kept as decoration nothing can fail without.
723
+ */
724
+ type LiteralKeysOf<R> = keyof {
725
+ [K in keyof R as string extends K ? never : number extends K ? never : symbol extends K ? never : K]: 0;
726
+ };
727
+ /**
728
+ * A registry entry joins {@link MessageEvent} only if it is a real event shape
729
+ * (`docs/adr/0002-platform-event-registry.md`).
730
+ *
731
+ * Measured, not anticipated: without this guard a single entry typed `any` collapses the whole
732
+ * union, and `tsc --strict` then accepts `event.completelyMadeUpField.nested.nonsense` on EVERY
733
+ * consumer — ours included — with no error in any package and nothing red in any suite. The closed
734
+ * union could not fail that way, so the guard is what keeps the new capability from costing a
735
+ * safety property the old design had.
736
+ *
737
+ * A malformed entry is EXCLUDED rather than admitted. It is NOT free for anybody else, and an
738
+ * earlier version of this docblock said it was — measured false twice over. Filtering the VALUE
739
+ * alone left two shapes that break every consumer rather than only their author:
740
+ * `{ [key: string]: … }` made `keyof` yield `string | number`, so the union and the platform name
741
+ * both collapsed to `never`; and `acmechat?: …` kept its optional modifier through a homomorphic
742
+ * mapping and injected `undefined` into the union. Both are handled above — the first by
743
+ * {@link LiteralKeysOf}, the second by the `-?` on the mapping. What remains true, and is the
744
+ * honest version of the original claim:
745
+ * a `Record<PlatformName, T>` written against the first-party platforms still fails to compile, because the rejected
746
+ * key is gone from `PlatformName` while the consumer's literal map is not. What the exclusion buys
747
+ * is that the failure is a missing-key error at the consumer's own map rather than a silent loss
748
+ * of narrowing everywhere.
749
+ *
750
+ * Exported for the contract test in `tests/types/registry-guard.test.ts`, which asserts against
751
+ * this type rather than a copy of it — a copy would stay green with the guard deleted. It is
752
+ * deliberately NOT re-exported from the package barrel; it is an implementation detail of the
753
+ * derivation, not part of the published surface.
754
+ */
755
+ type Registered<K, T> = IsAny<T> extends true ? never : [T] extends [BaseMessageEvent] ? [T] extends [{
756
+ readonly platform: LiteralKey<K>;
757
+ }] ? [LiteralKey<K>] extends [never] ? never : T : never : never;
758
+ /**
759
+ * The canonical inbound event: every guarded entry in {@link PlatformEventRegistry}.
760
+ *
761
+ * Derived rather than written, so third-party platforms are included automatically and exhaustive
762
+ * narrowing still holds over all of them.
763
+ *
764
+ * @public
765
+ */
766
+ type MessageEvent = {
767
+ [K in LiteralKeysOf<PlatformEventRegistry>]: Registered<K, PlatformEventRegistry[K]>;
768
+ }[LiteralKeysOf<PlatformEventRegistry>];
769
+ /**
770
+ * Every platform that actually has a well-formed event in {@link PlatformEventRegistry}.
771
+ *
772
+ * Derived from the GUARDED union rather than from `keyof`, so `PlatformName` and
773
+ * `MessageEvent["platform"]` are the same set by construction. Deriving from `keyof` let a rejected
774
+ * entry keep contributing its key, which produced names no event could ever carry — an adapter
775
+ * could register for a platform that cannot exist.
776
+ *
777
+ * Still a union of string literals, so `switch (event.platform)` narrows and a misspelled name is
778
+ * a compile error.
779
+ */
780
+ type PlatformName = MessageEvent["platform"];
781
+
782
+ /**
783
+ * `BasePlatformAdapter` — contract every transport adapter implements
784
+ * (T1.2, ADR D172).
785
+ *
786
+ * Adapters share ~30% of lifecycle code (typing indicators, event
787
+ * normalization patterns). An abstract class with concrete defaults
788
+ * + abstract hooks is the right shape — interface-only would force
789
+ * every adapter to copy the defaults.
790
+ *
791
+ * Consumers use it via `instanceof` and the public subclass exports
792
+ * (`TelegramAdapter`, `DiscordAdapter`, ...).
793
+ */
794
+
795
+ /**
796
+ * An image an outbound message carries: its bytes and their media type (B-674).
797
+ *
798
+ * The bytes travel by reference: the runner does not copy them on the way to the adapter. The
799
+ * caller must not change `data` or the list until the send's promise settles: an adapter that
800
+ * sends several attachments reads each one only when its turn comes.
801
+ */
802
+ interface OutboundImageAttachment {
803
+ readonly kind: "image";
804
+ /** The media type of `data`, such as `image/png`. */
805
+ readonly mediaType: string;
806
+ readonly data: Uint8Array;
807
+ /** A file name the platform may show; optional. */
808
+ readonly filename?: string;
809
+ }
810
+ /** An audio clip an outbound message carries, such as a spoken reply (B-715). Same rules as an image. */
811
+ interface OutboundAudioAttachment {
812
+ readonly kind: "audio";
813
+ /** The media type of `data`, such as `audio/ogg`. */
814
+ readonly mediaType: string;
815
+ readonly data: Uint8Array;
816
+ /** A file name the platform may show; optional. */
817
+ readonly filename?: string;
818
+ }
819
+ /** An attachment an outbound message carries, told apart by `kind`. */
820
+ type OutboundAttachment = OutboundImageAttachment | OutboundAudioAttachment;
821
+ /** Outbound message shape — what `sendMessage` accepts. */
822
+ interface OutboundMessage {
823
+ readonly channel: {
824
+ readonly id: string;
825
+ readonly type: "dm" | "group" | "thread";
826
+ readonly topicId?: string;
827
+ };
828
+ readonly text: string;
829
+ /** Markdown / HTML rendering hint. Default "plain". */
830
+ readonly format?: "plain" | "markdown" | "html";
831
+ /** Optional reply target. */
832
+ readonly replyTo?: string;
833
+ /**
834
+ * Images to send with the text. An adapter whose {@link BasePlatformAdapter.supportsAttachments}
835
+ * is `false` refuses a non-empty list with `attachments_unsupported`; it never drops it.
836
+ */
837
+ readonly attachments?: ReadonlyArray<OutboundAttachment>;
838
+ }
839
+ /**
840
+ * Shared failure codes for {@link SendResult}.
841
+ *
842
+ * - `empty_text`, `not_connected`, `invalid_channel`, `attachments_unsupported`: core refused the send.
843
+ * - `rate_limit`: the platform throttled the send; see `retryAfterMs`.
844
+ * - `permission_denied`: the credential is valid but may not post here (HTTP 403).
845
+ * - `auth_failed`: the credential was rejected (HTTP 401).
846
+ * - `timeout`: the platform or the request timed out (HTTP 408).
847
+ * - `server_error`: the platform failed (HTTP 5xx).
848
+ * - `network_error`: the request never got an answer.
849
+ * - `platform_error`: any other platform refusal.
850
+ */
851
+ type SendErrorCode = "empty_text" | "not_connected" | "invalid_channel" | "attachments_unsupported" | "rate_limit" | "permission_denied" | "auth_failed" | "timeout" | "server_error" | "network_error" | "platform_error";
852
+ /** The error of a failed {@link SendResult}. */
853
+ interface SendError {
854
+ /** A known code, or a platform-specific one an adapter has not mapped yet. */
855
+ readonly code: SendErrorCode | (string & {});
856
+ readonly message: string;
857
+ /** Set when the platform said how long to wait. */
858
+ readonly retryAfterMs?: number;
859
+ /** The platform's own code, kept for logs. */
860
+ readonly platformCode?: string;
861
+ }
862
+ /**
863
+ * Send result — adapters return this instead of throwing on platform errors.
864
+ * `error.code` is a {@link SendErrorCode} or a platform-specific string.
865
+ */
866
+ interface SendResult {
867
+ readonly ok: boolean;
868
+ readonly messageId?: string;
869
+ readonly error?: SendError;
870
+ }
871
+ /** The facts about an adapter that an app picks its rendering from. */
872
+ interface AdapterCapabilities {
873
+ readonly edit: boolean;
874
+ /** The attachment kinds the adapter sends; `[]` when none. */
875
+ readonly attachments: ReadonlyArray<OutboundAttachment["kind"]>;
876
+ readonly typing: boolean;
877
+ readonly reactions: boolean;
878
+ readonly threads: boolean;
879
+ /** Longest text one message holds; `undefined` when the adapter does not know. */
880
+ readonly maxMessageChars?: number;
881
+ }
882
+ /**
883
+ * Abstract base for all platform adapters.
884
+ *
885
+ * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.
886
+ * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden; `editMessage` refuses
887
+ * with `edit_unsupported` unless overridden.
888
+ *
889
+ * **Contract:**
890
+ * - `connect()` is idempotent. Calling twice returns true the second time.
891
+ * - `disconnect()` is idempotent.
892
+ * - `sendMessage` returns a `SendResult`; it MUST NOT throw on platform errors
893
+ * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.
894
+ * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling
895
+ * `onInbound` twice replaces the previous handler — does NOT stack.
896
+ * - `sendMessage` with empty text and no attachments returns `{ ok: false, code: "empty_text" }`.
897
+ * An adapter that refuses attachments answers `attachments_unsupported` first, and one that
898
+ * sends them (Telegram) accepts empty text with an image.
899
+ * - `supportsEdit` says whether the adapter has an edit call. It is `false` unless the adapter
900
+ * overrides it, and it MUST NOT change with `connect()`. `true` does not promise that every
901
+ * edit is accepted: an adapter whose injected client lacks the edit call (Matrix) still answers
902
+ * `edit_unsupported`, which a caller handles like any other refusal.
903
+ * - `editMessage` returns a `SendResult` and never throws on platform errors. The default refuses
904
+ * with `edit_unsupported` and makes no platform call.
905
+ * - `supportsAttachments` says whether `sendMessage` can send `out.attachments`. It is `false`
906
+ * unless the adapter overrides it, and it MUST NOT change with `connect()`. An adapter that
907
+ * does not support them refuses a non-empty list with `attachments_unsupported` and makes no
908
+ * platform call; an edit carrying an attachment is refused the same way.
909
+ * - Edits are not ordered by the adapter. Two edits of one message id in flight at once reach the
910
+ * platform in either order, so a caller awaits each edit before the next, or keeps one in flight
911
+ * and coalesces to the latest text.
912
+ *
913
+ * @public
914
+ */
915
+ declare abstract class BasePlatformAdapter {
916
+ abstract readonly platform: PlatformName;
917
+ /** Open the connection. Returns `true` on success; never throws. */
918
+ abstract connect(): Promise<boolean>;
919
+ /** Close the connection. Idempotent; safe to call when never connected. */
920
+ abstract disconnect(): Promise<void>;
921
+ /** Send a message. Returns a `SendResult`; never throws on platform errors. */
922
+ abstract sendMessage(out: OutboundMessage): Promise<SendResult>;
923
+ /**
924
+ * Subscribe to inbound events. Returns an unsubscribe function.
925
+ * EC-H: second call REPLACES the previous handler (does not stack).
926
+ *
927
+ * The handler is user code and may throw. An adapter MUST contain that throw, report it as the
928
+ * HANDLER's failure — not the platform's — and keep delivering: one bad message never ends the
929
+ * process nor the connection. Two adapters used to discard the rejection with `void`, which under
930
+ * Node's default ends the process, and two more reported it as a platform-client error, sending
931
+ * whoever debugged their own handler to the wrong repository. Eight had converged on the right
932
+ * behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds every
933
+ * adapter to it.
934
+ */
935
+ abstract onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
936
+ /**
937
+ * Deliver an inbound event that arrived OUT OF BAND, and report what the handler did with it.
938
+ *
939
+ * Six adapters self-deliver once connected — long polling, a gateway socket, Socket Mode, a sync
940
+ * loop, IMAP. The webhook platforms cannot: the payload arrives on an HTTP route the application
941
+ * owns, and until this existed there was no supported call that joined the two. `onInbound` had no
942
+ * public counterpart, so `GatewayRunner` was reachable for eight platforms and not for LINE or
943
+ * WhatsApp Cloud, which every app then wired by hand beside the runner instead of through it
944
+ * (#83).
945
+ *
946
+ * The return value distinguishes the three outcomes a caller can act on, because they are not the
947
+ * same problem: nobody subscribed, the handler ran, or the handler threw. Answering a webhook 200
948
+ * for the first is wrong — the provider would stop retrying a message nothing received.
949
+ *
950
+ * Implementations should be one line over {@link runHandler}, which owns the containment.
951
+ */
952
+ abstract deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
953
+ /**
954
+ * Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.
955
+ *
956
+ * A handler is USER code and may throw. An adapter must contain that throw, name it as the
957
+ * handler's failure rather than the platform's, and keep delivering — one bad message ends
958
+ * neither the process nor the connection. Two adapters once discarded the rejection with `void`,
959
+ * which under Node's default ends the process; two more reported it as a platform-client error,
960
+ * sending whoever debugged their own handler to the wrong repository (#41).
961
+ *
962
+ * Ten copies of that knowledge is ten chances to get it wrong, so it lives here. The platform tag
963
+ * is taken from `this.platform`, which is the only part that differed between them.
964
+ */
965
+ protected runHandler(handler: ((event: MessageEvent) => Promise<void>) | undefined, event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
966
+ /** The handler {@link subscribe} holds; `undefined` while nobody is subscribed. */
967
+ protected subscribedHandler: ((event: MessageEvent) => Promise<void>) | undefined;
968
+ /** The body of {@link onInbound}: replace the handler, and unsubscribe only if it is still the one held. */
969
+ protected subscribe(handler: (event: MessageEvent) => Promise<void>): () => void;
970
+ /** The body of {@link deliver} for an adapter that subscribed through {@link subscribe}. */
971
+ protected deliverInbound(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
972
+ /**
973
+ * Dispatch a webhook event once: `duplicate` when `seen` holds its id, `no_handler` when nobody
974
+ * subscribed (the id is then NOT remembered, so a redelivery is handled), otherwise remember the
975
+ * id and run the handler. A handler's throw is also logged under `label`.
976
+ */
977
+ protected dispatchOnce(seen: SeenIds, event: MessageEvent, label: string): Promise<"ok" | "no_handler" | "handler_threw" | "duplicate">;
978
+ /** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */
979
+ protected outboundText(out: OutboundMessage): string;
980
+ /**
981
+ * `attachments_unsupported` when `out` carries attachments and this adapter does not declare
982
+ * `supportsAttachments`, otherwise `undefined`. Call it first in `sendMessage`.
983
+ */
984
+ protected refuseAttachments(out: OutboundMessage): SendResult | undefined;
985
+ /**
986
+ * The local checks every text-only `sendMessage` makes before a request, in this order:
987
+ * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
988
+ * Returns the refusal, or `undefined` when the message may be sent.
989
+ */
990
+ protected refuseUnsendable(out: OutboundMessage, check: {
991
+ readonly className: string;
992
+ readonly connected: boolean;
993
+ readonly channel?: {
994
+ readonly valid: (id: string) => boolean;
995
+ readonly message: string;
996
+ };
997
+ }): SendResult | undefined;
998
+ /**
999
+ * Whether {@link editMessage} can replace the text of a message this adapter sent.
1000
+ *
1001
+ * Read it before starting a preview: on `false`, send the final text instead. An adapter sets
1002
+ * it at construction and MUST NOT change it with `connect()`. Annotated as `boolean` so that an
1003
+ * edit-capable adapter can override it with `true`.
1004
+ */
1005
+ readonly supportsEdit: boolean;
1006
+ /**
1007
+ * Whether {@link sendMessage} can send the images of `out.attachments` (B-674).
1008
+ *
1009
+ * Read it before attaching: on `false`, the adapter refuses a non-empty list with
1010
+ * `attachments_unsupported`. Set at construction, never changed by `connect()`. Annotated as
1011
+ * `boolean` so that an adapter that sends images can override it with `true`.
1012
+ */
1013
+ readonly supportsAttachments: boolean;
1014
+ /**
1015
+ * The attachment kinds {@link sendMessage} can send. `undefined` means "not declared": the
1016
+ * `capabilities` getter then reports `["image"]` when `supportsAttachments` is `true`, else `[]`.
1017
+ */
1018
+ protected readonly attachmentKinds: ReadonlyArray<OutboundAttachment["kind"]> | undefined;
1019
+ /**
1020
+ * What this adapter can do, for an app that renders differently per channel.
1021
+ *
1022
+ * Derived from the members above and from which lifecycle methods the subclass overrides; an
1023
+ * adapter overrides the getter only for what derivation cannot know. Read it at call time.
1024
+ */
1025
+ get capabilities(): AdapterCapabilities;
1026
+ /**
1027
+ * Replace the text of a message this adapter sent, keeping its id.
1028
+ *
1029
+ * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
1030
+ * throws on platform errors. An edit-capable adapter applies, with no request, the same local
1031
+ * checks its `sendMessage` applies (such as `empty_text`, and `not_connected` where the send
1032
+ * checks the connection), plus `invalid_message_id`, and `edit_too_long` where the adapter
1033
+ * splits text: an edit that would need more than one platform message is refused, never split.
1034
+ *
1035
+ * Default: refuses with `edit_unsupported`, makes no platform call, and checks nothing else
1036
+ * first, so capability is answered before input.
1037
+ */
1038
+ editMessage(_messageId: string, _out: OutboundMessage): Promise<SendResult>;
1039
+ /**
1040
+ * React to an inbound message with an emoji (for example 👀 as an acknowledgement).
1041
+ *
1042
+ * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
1043
+ * throws on platform errors. `channelId` is the channel the message is in and `messageId` the
1044
+ * id the inbound event carried.
1045
+ *
1046
+ * Default: resolves `{ ok: false, error: { code: "react_unsupported" } }` and makes no
1047
+ * platform call.
1048
+ */
1049
+ react(_channelId: string, _messageId: string, _emoji: string): Promise<SendResult>;
1050
+ /** Lifecycle: emit a typing indicator. Default: noop. */
1051
+ startTyping(_channelId: string): Promise<void>;
1052
+ /** Lifecycle: stop the typing indicator. Default: noop. */
1053
+ stopTyping(_channelId: string): Promise<void>;
1054
+ }
1055
+
1056
+ /**
1057
+ * A JSON-RPC 2.0 client over a child's stdio, one message per line.
1058
+ *
1059
+ * signal-cli's `jsonRpc` mode reads requests on stdin and writes responses and notifications on
1060
+ * stdout. Two failure paths here would otherwise end the host process, and both were measured:
1061
+ * an `EPIPE` on a stdin the child already closed, raised as an `error` event nobody listens to,
1062
+ * and a `JSON.parse` throw on a stray log line inside a stream listener. The first is listened
1063
+ * to and the second is caught and reported, so a dying or noisy child costs its own requests and
1064
+ * nothing else.
1065
+ *
1066
+ * @public
1067
+ */
1068
+
1069
+ /** The child process shape the client drives: its three pipes, `kill`, and `close`/`error` events. */
1070
+ interface JsonRpcChild {
1071
+ readonly stdin: Writable;
1072
+ readonly stdout: Readable;
1073
+ readonly stderr: Readable;
1074
+ kill(signal?: NodeJS.Signals | number): boolean;
1075
+ on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
1076
+ on(event: "error", listener: (err: Error) => void): this;
1077
+ }
1078
+ /** How one request ended. Never a rejection: every outcome is a value the caller maps. */
1079
+ type RpcOutcome = {
1080
+ readonly kind: "result";
1081
+ readonly result: unknown;
1082
+ } | {
1083
+ readonly kind: "error";
1084
+ readonly code: number;
1085
+ readonly message: string;
1086
+ readonly data?: unknown;
1087
+ } | {
1088
+ readonly kind: "timeout";
1089
+ } | {
1090
+ readonly kind: "disconnected";
1091
+ };
1092
+ /** A server-to-client message with no id. */
1093
+ interface RpcNotification {
1094
+ readonly method: string;
1095
+ readonly params: unknown;
1096
+ }
1097
+ /** Line-framed JSON-RPC over one child. Dead once the child exits or `close()` is called. */
1098
+ declare class JsonRpcLineClient {
1099
+ private readonly child;
1100
+ private readonly label;
1101
+ private readonly onNotification;
1102
+ private readonly onClosed;
1103
+ private counter;
1104
+ private readonly pending;
1105
+ private alive;
1106
+ /**
1107
+ * @param child - the running child; the client attaches to its pipes and events
1108
+ * @param label - the stderr tag, e.g. `gateway-signal`
1109
+ * @param onNotification - called for every message that carries a method and no id
1110
+ * @param onClosed - called once, when the child exits or fails
1111
+ */
1112
+ constructor(child: JsonRpcChild, label: string, onNotification: (notification: RpcNotification) => void, onClosed: (reason: string) => void);
1113
+ /** Send `method` and wait for its answer, at most `timeoutMs`. */
1114
+ request(method: string, params: unknown, timeoutMs: number): Promise<RpcOutcome>;
1115
+ /** Settle every pending request as `disconnected` and stop accepting new ones. Idempotent. */
1116
+ close(reason: string): void;
1117
+ private settle;
1118
+ private handleLine;
1119
+ }
1120
+
1121
+ /**
1122
+ * Map an HTTP status to a failed SendResult: 429 -> rate_limit (retryAfterMs from a Retry-After
1123
+ * value in seconds or an HTTP date), 401 -> auth_failed, 403 -> permission_denied,
1124
+ * 408 -> timeout, 5xx -> server_error, other -> platform_error.
1125
+ */
1126
+ declare function sendErrorFromHttp(status: number, message: string, options?: {
1127
+ retryAfter?: string | null;
1128
+ platformCode?: string;
1129
+ now?: () => number;
1130
+ }): SendResult;
1131
+
1132
+ /**
1133
+ * `WeixinAdapterBase` — the connect / token / send / dispatch flow that the WeChat and WeCom
1134
+ * adapters share. A subclass supplies the platform's endpoints, its signature check and its event
1135
+ * shape; this class owns everything else.
1136
+ *
1137
+ * @public
1138
+ */
1139
+
1140
+ /** A `fetch`-shaped function; the adapter's only network seam. @public */
1141
+ type WeixinFetch = (url: string, init: {
1142
+ method: string;
1143
+ headers: Record<string, string>;
1144
+ body?: string;
1145
+ }) => Promise<{
1146
+ status: number;
1147
+ text(): Promise<string>;
1148
+ }>;
1149
+ /**
1150
+ * What a webhook route answers. `body` is the text to write back; anything but 200 makes the
1151
+ * platform retry.
1152
+ *
1153
+ * @public
1154
+ */
1155
+ type WeixinWebhookAnswer = {
1156
+ readonly status: 200 | 400 | 401 | 503;
1157
+ readonly body: string;
1158
+ readonly reason: string;
1159
+ };
1160
+ /** What a subclass tells the base about its platform. @public */
1161
+ interface WeixinAdapterConfig {
1162
+ /** Log prefix, e.g. `gateway-wechat`. */
1163
+ readonly label: string;
1164
+ /** Class name used in the `not_connected` message, e.g. `WeChatAdapter`. */
1165
+ readonly className: string;
1166
+ /** Brand used in messages, e.g. `WeChat`. */
1167
+ readonly brand: string;
1168
+ /** What `channel.id` must be, e.g. `a WeChat OpenID`. */
1169
+ readonly userNoun: string;
1170
+ /** API base used when `apiBase` is not set. */
1171
+ readonly defaultBase: string;
1172
+ readonly apiBase?: string;
1173
+ readonly fetch?: WeixinFetch;
1174
+ }
1175
+ /** One send call: a path (with its access token) and a JSON payload. @public */
1176
+ interface WeixinSendRequest {
1177
+ readonly path: string;
1178
+ readonly payload: unknown;
1179
+ }
1180
+ /**
1181
+ * Shared base of the WeChat and WeCom adapters.
1182
+ *
1183
+ * @public
1184
+ */
1185
+ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
1186
+ private readonly cfg;
1187
+ private readonly doFetch;
1188
+ private connected;
1189
+ private readonly tokens;
1190
+ private readonly seen;
1191
+ constructor(cfg: WeixinAdapterConfig);
1192
+ /** Path and query of the access-token request. */
1193
+ protected abstract tokenPath(): string;
1194
+ /** The send call for one part of a reply. */
1195
+ protected abstract sendRequest(token: string, userId: string, content: string): WeixinSendRequest;
1196
+ /** Cut a reply into parts the platform accepts. */
1197
+ protected abstract split(text: string): string[];
1198
+ /** The event for a text message, `"skip"` for another type, `undefined` for a text with gaps. */
1199
+ protected abstract toEvent(fields: Record<string, string>): MessageEvent | "skip" | undefined;
1200
+ connect(): Promise<boolean>;
1201
+ disconnect(): Promise<void>;
1202
+ /** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
1203
+ protected sendText(out: OutboundMessage): Promise<SendResult>;
1204
+ private sendParts;
1205
+ onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
1206
+ /** Deliver an event that arrived out of band, through `runHandler`. */
1207
+ deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
1208
+ /** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */
1209
+ protected handleMessage(xml: string): Promise<WeixinWebhookAnswer>;
1210
+ private token;
1211
+ private requestToken;
1212
+ private call;
1213
+ }
1214
+
1215
+ /**
1216
+ * Read the flat XML the Tencent webhook platforms (WeChat, WeCom) push:
1217
+ * `<xml><Tag><![CDATA[v]]></Tag>…</xml>`. The messages these adapters take have no nesting, so a
1218
+ * tag scan is enough and no XML library is needed.
1219
+ *
1220
+ * @public
1221
+ */
1222
+ declare function parseFlatXml(xml: string): Record<string, string>;
1223
+
1224
+ /**
1225
+ * A JWKS key-set cache and RS256 JWT signature verification, for platforms that sign their
1226
+ * requests with a JWT. Signature only: issuer, audience and expiry stay with the caller.
1227
+ */
1228
+
1229
+ /** A key for a `kid`, `"unlisted"` when the key set does not list it, or why no key set is readable. */
1230
+ type JwksLookup = KeyObject | "unlisted" | {
1231
+ readonly unavailable: string;
1232
+ };
1233
+ /** Where a JWKS is read from, and how its cache behaves. */
1234
+ interface JwksKeySetOptions {
1235
+ readonly url: string;
1236
+ readonly fetch?: (url: string, init?: {
1237
+ signal?: AbortSignal;
1238
+ }) => Promise<Response>;
1239
+ readonly now?: () => number;
1240
+ /** Minimum time between refetches triggered by an unknown kid. Default 60_000. */
1241
+ readonly unknownKidRefetchFloorMs?: number;
1242
+ /** Serve a stale key set while one refresh runs. Default true. */
1243
+ readonly staleWhileRevalidate?: boolean;
1244
+ }
1245
+ /** A cache of the keys a JWKS publishes, looked up by `kid`. */
1246
+ interface JwksKeySet {
1247
+ lookup(kid: string): Promise<JwksLookup>;
1248
+ }
1249
+ /**
1250
+ * A JWKS key set cached for the `max-age` its response declares. Concurrent lookups share one
1251
+ * read; a read starts at most once per `unknownKidRefetchFloorMs`. A failed read keeps the last
1252
+ * good copy.
1253
+ */
1254
+ declare function jwksKeySet(options: JwksKeySetOptions): JwksKeySet;
1255
+ /** A compact JWT split into its parts; nothing in it is verified yet. */
1256
+ interface DecodedJwt {
1257
+ readonly header: Readonly<Record<string, unknown>>;
1258
+ readonly payload: Readonly<Record<string, unknown>>;
1259
+ readonly signingInput: string;
1260
+ readonly signature: Buffer;
1261
+ }
1262
+ /** Split a compact JWT into its parts without checking anything; `undefined` when malformed. */
1263
+ declare function decodeJwt(token: string): DecodedJwt | undefined;
1264
+ /** The outcome of checking a token's signature: its claims, or why it was refused. */
1265
+ type VerifyJwtResult = {
1266
+ readonly ok: true;
1267
+ readonly header: DecodedJwt["header"];
1268
+ readonly payload: DecodedJwt["payload"];
1269
+ } | {
1270
+ readonly ok: false;
1271
+ readonly reason: "malformed" | "unsupported_alg" | "unknown_kid" | "keys_unavailable" | "bad_signature";
1272
+ };
1273
+ /** Signature only. Issuer, audience and expiry stay with the caller. */
1274
+ declare function verifyRs256Jwt(token: string, keys: JwksKeySet): Promise<VerifyJwtResult>;
1275
+
1276
+ /**
1277
+ * `createTokenCache` — holds one expiring access token and shares a single refresh between every
1278
+ * concurrent caller.
1279
+ *
1280
+ * @public
1281
+ */
1282
+ /** A token as the platform reported it. @public */
1283
+ interface FetchedToken {
1284
+ readonly value: string;
1285
+ /** Lifetime in seconds as the platform reported it; `defaultTtlS` when absent or not positive. */
1286
+ readonly expiresInS?: number;
1287
+ }
1288
+ /** Options of {@link createTokenCache}. @public */
1289
+ interface TokenCacheOptions {
1290
+ /** Fetch a fresh token. Receives the signal of the caller that started the fetch. */
1291
+ readonly fetchToken: (signal?: AbortSignal) => Promise<FetchedToken>;
1292
+ /** Refresh this long before expiry. Default 60_000. */
1293
+ readonly marginMs?: number;
1294
+ /** Default 7200. */
1295
+ readonly defaultTtlS?: number;
1296
+ readonly now?: () => number;
1297
+ }
1298
+ /** A cached expiring token. @public */
1299
+ interface TokenCache {
1300
+ /**
1301
+ * The cached token, or one fetch shared by every concurrent caller. `force` skips the cache
1302
+ * (but still joins a fetch already in flight). The signal of the caller that starts a fetch
1303
+ * governs it; later callers' signals do not cancel their wait.
1304
+ */
1305
+ get(options?: {
1306
+ force?: boolean;
1307
+ signal?: AbortSignal;
1308
+ }): Promise<string>;
1309
+ /** Forget the cached token (after a 401, for example). */
1310
+ clear(): void;
1311
+ }
1312
+ /** Build a {@link TokenCache}. A failed fetch rejects every waiting caller and is not cached. @public */
1313
+ declare function createTokenCache(options: TokenCacheOptions): TokenCache;
1314
+
1315
+ /**
1316
+ * `GatewayConfigurationError` — shared base for per-adapter configuration
1317
+ * errors (roadmap M0/M2).
1318
+ *
1319
+ * Every platform adapter previously defined an identical
1320
+ * `ConfigurationError extends Error` (same `code`/`detail` fields, same
1321
+ * options interface, same `` `${pkg}: ${code}` `` default message) — only the
1322
+ * package prefix differed. This base single-sources that contract. Adapters
1323
+ * extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
1324
+ * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
1325
+ *
1326
+ * @public
1327
+ */
1328
+ /** Public input shape for the {@link GatewayConfigurationError} constructor. */
1329
+ interface GatewayConfigurationErrorOptions {
1330
+ readonly code: string;
1331
+ readonly message?: string;
1332
+ readonly detail?: string;
1333
+ }
1334
+ /**
1335
+ * Base configuration error. Not thrown directly by adapters — they subclass it
1336
+ * with a fixed package prefix.
1337
+ */
1338
+ declare class GatewayConfigurationError extends Error {
1339
+ readonly name: string;
1340
+ readonly code: string;
1341
+ readonly detail: string | undefined;
1342
+ /**
1343
+ * @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
1344
+ * @param opts `code` (required), optional explicit `message`, optional `detail`.
1345
+ */
1346
+ constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
1347
+ }
1348
+
1349
+ /**
1350
+ * `channelConfigReaders` — the config readers every channel's `create` needs, written once.
1351
+ *
1352
+ * Each channel package used to carry its own copy of `invalid`, `readString`, `requiredString`
1353
+ * and friends; only the error prefix differed. The readers throw a configuration error coded
1354
+ * `invalid_config` with the message `${prefix}: config.${key} must be ${expected}`.
1355
+ *
1356
+ * @public
1357
+ */
1358
+
1359
+ /** A channel's config object, as `create` receives it. */
1360
+ type ChannelConfigInput = Readonly<Record<string, unknown>>;
1361
+ /** The readers bound to one package prefix. */
1362
+ interface ChannelConfigReaders {
1363
+ /** Builds (does not throw) the `invalid_config` error for `key`. */
1364
+ invalid(key: string, expected: string): GatewayConfigurationError;
1365
+ /** `undefined`, `null` and `""` are absent. */
1366
+ isAbsent(value: unknown): boolean;
1367
+ /** An optional string; absent gives `undefined`, a non-string throws. */
1368
+ readString(config: ChannelConfigInput, key: string): string | undefined;
1369
+ /** A required string; absent, empty or a non-string throws. */
1370
+ requiredString(config: ChannelConfigInput, key: string): string;
1371
+ /** An optional boolean; absent gives `undefined`, a non-boolean throws. */
1372
+ readBoolean(config: ChannelConfigInput, key: string): boolean | undefined;
1373
+ /** An optional number: a finite number or a digit string; anything else throws. */
1374
+ readNumber(config: ChannelConfigInput, key: string): number | undefined;
1375
+ /** An optional boolean as a boolean or the string `"true"`/`"false"`; anything else throws. */
1376
+ readBooleanString(config: ChannelConfigInput, key: string): boolean | undefined;
1377
+ /** An optional list of strings: an array or a comma-separated string (items trimmed). */
1378
+ readList(config: ChannelConfigInput, key: string): string[] | undefined;
1379
+ /**
1380
+ * An optional function; absent gives `undefined`, a non-function throws. Only callability is
1381
+ * checked: the caller names the signature `T` and is responsible for it.
1382
+ */
1383
+ readFunction<T extends (...args: never[]) => unknown>(config: ChannelConfigInput, key: string): T | undefined;
1384
+ }
1385
+ /**
1386
+ * Returns the config readers for a package.
1387
+ *
1388
+ * @param prefix Package prefix in every message, e.g. `"gateway-line"`.
1389
+ * @param createError Builds the error to throw; defaults to `GatewayConfigurationError`. Pass a
1390
+ * package's own subclass to keep its `instanceof` contract.
1391
+ */
1392
+ declare function channelConfigReaders(prefix: string, createError?: (options: {
1393
+ readonly code: string;
1394
+ readonly message: string;
1395
+ readonly detail: string;
1396
+ }) => GatewayConfigurationError): ChannelConfigReaders;
1397
+
1398
+ /**
1399
+ * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).
1400
+ *
1401
+ * A platform package exports one static descriptor: the config fields its channel needs, how to
1402
+ * build its adapter from them, and, for a channel that receives webhooks, how to verify and ingest
1403
+ * a request. An app then wires every channel with the same loop (`createChannels`) instead of one
1404
+ * branch per platform. The core only reads these shapes; it never names a platform.
1405
+ *
1406
+ * @public
1407
+ */
1408
+
1409
+ /** One configuration field a channel reads. */
1410
+ interface ChannelConfigField {
1411
+ /** The key `create` reads from its config object. */
1412
+ readonly key: string;
1413
+ /** A required field that is absent, `null` or `""` rejects the channel before `create` runs. */
1414
+ readonly required: boolean;
1415
+ /** The value is a credential: never log it, and keep it out of anything shown to a user. */
1416
+ readonly secret: boolean;
1417
+ /** What the field is, for a human configuring the channel. */
1418
+ readonly description: string;
1419
+ /** Variable name without the app prefix, e.g. `"TELEGRAM_TOKEN"`. Read by `configFromEnv`. */
1420
+ readonly env?: string;
1421
+ }
1422
+ /** A webhook request as the app's HTTP layer received it, before anything parsed the body. */
1423
+ interface WebhookRequest {
1424
+ /** The exact request bytes as text; signatures are computed over them. */
1425
+ readonly rawBody: string;
1426
+ /** Request headers. Descriptors look a header up without regard to case. */
1427
+ readonly headers: Readonly<Record<string, string | undefined>>;
1428
+ /** The HTTP method. Always set by `createWebhookHandler`; optional so existing callers compile. */
1429
+ readonly method?: string;
1430
+ /** The full request URL, query included. Always set by `createWebhookHandler`. */
1431
+ readonly url?: string;
1432
+ }
1433
+ /** The answer a channel's `handle` gives for one webhook request. */
1434
+ interface WebhookAnswer {
1435
+ /** The HTTP status. */
1436
+ readonly status: number;
1437
+ /** The response body, when the platform expects one. */
1438
+ readonly body?: string;
1439
+ /** The response `content-type`. */
1440
+ readonly contentType?: string;
1441
+ }
1442
+ /**
1443
+ * What `ingest` did with a verified payload: `"delivered"` dispatched it, `"malformed"` refused it
1444
+ * without dispatching, and `"no_handler"` dispatched nothing because the payload holds a message
1445
+ * for the handler and none is subscribed (before the runner starts, after it stops, or for an
1446
+ * adapter whose connect failed under `connectFailure: "isolate"`). Answer only `"delivered"` with
1447
+ * a success status, so a platform that redelivers can send the rest again.
1448
+ */
1449
+ type IngestResult = "delivered" | "malformed" | "no_handler";
1450
+ /**
1451
+ * The webhook half of a channel: verify a request, then hand its payload to the adapter.
1452
+ *
1453
+ * `verify` and `ingest` are declared as methods on purpose. Method parameters are bivariant, which
1454
+ * is what lets a descriptor typed for its own adapter class sit in a list of
1455
+ * `ChannelDescriptor<BasePlatformAdapter>`; written as function-typed properties, that assignment
1456
+ * would fail under `strictFunctionTypes`.
1457
+ */
1458
+ interface ChannelWebhook<TAdapter extends BasePlatformAdapter> {
1459
+ /** `true` when the request carries a valid signature for this adapter's credentials. */
1460
+ verify(adapter: TAdapter, request: WebhookRequest): boolean | Promise<boolean>;
1461
+ /** Dispatch a parsed, verified payload, or report it malformed without dispatching. */
1462
+ ingest(adapter: TAdapter, payload: unknown): Promise<IngestResult>;
1463
+ /** Methods the route takes. Default `["POST"]`. */
1464
+ readonly methods?: readonly string[];
1465
+ /**
1466
+ * Called with the method, URL and headers before the body is read. An answer refuses the request
1467
+ * there (an unreadable or oversized body never gets a 400 or 413); `undefined` lets it go on.
1468
+ */
1469
+ precheck?(adapter: TAdapter, request: Omit<WebhookRequest, "rawBody">): WebhookAnswer | undefined;
1470
+ /** Full control of one request. When absent, the handler runs verify, JSON.parse and ingest. */
1471
+ handle?(adapter: TAdapter, request: WebhookRequest): Promise<WebhookAnswer>;
1472
+ }
1473
+ /**
1474
+ * Whether a channel's `sender.id` is proven by the platform. An email From header or an SMS caller
1475
+ * id is written by the sender (CWE-290), so such a channel declares why it cannot be trusted.
1476
+ *
1477
+ * @public
1478
+ */
1479
+ type SenderIdentity = "authenticated"
1480
+ /** Why the sender id can be forged, for error messages. */
1481
+ | {
1482
+ readonly unauthenticated: string;
1483
+ };
1484
+ /**
1485
+ * Runtime dependencies an app hands to a descriptor's `create`: objects that are not configuration
1486
+ * (a credential store, a QR sink). Each descriptor documents the keys it reads and ignores the rest.
1487
+ */
1488
+ type ChannelDeps = Readonly<Record<string, unknown>>;
1489
+ interface ChannelDescriptorBase<TAdapter extends BasePlatformAdapter> {
1490
+ /** The platform the built adapter reports as its `platform`. */
1491
+ readonly platform: PlatformName;
1492
+ /** Every field `create` reads. */
1493
+ readonly config: ReadonlyArray<ChannelConfigField>;
1494
+ /**
1495
+ * Build the adapter. Throws a `GatewayConfigurationError` (or a subclass) for a value it refuses,
1496
+ * which `createChannels` reports as a rejected channel; it performs no network call.
1497
+ */
1498
+ create(config: Readonly<Record<string, unknown>>, deps?: ChannelDeps): TAdapter;
1499
+ /**
1500
+ * Whether `sender.id` is authenticated. Absent means unknown and is treated as not
1501
+ * authenticated (fail closed); it is optional only so descriptors in other packages keep compiling.
1502
+ */
1503
+ readonly senderIdentity?: SenderIdentity;
1504
+ /**
1505
+ * Alternative config shapes for the same platform (for example WhatsApp cloud versus baileys),
1506
+ * chosen by name with `selectVariant`. Each variant reports the parent's `platform`.
1507
+ */
1508
+ readonly variants?: Readonly<Record<string, ChannelDescriptor>>;
1509
+ }
1510
+ /**
1511
+ * A channel described as data. A `socket` channel opens its own connection to the platform; a
1512
+ * `webhook` channel receives requests the app routes to `webhook.verify` and `webhook.ingest`.
1513
+ *
1514
+ * @public
1515
+ */
1516
+ type ChannelDescriptor<TAdapter extends BasePlatformAdapter = BasePlatformAdapter> = (ChannelDescriptorBase<TAdapter> & {
1517
+ readonly transport: "socket";
1518
+ readonly webhook?: never;
1519
+ }) | (ChannelDescriptorBase<TAdapter> & {
1520
+ readonly transport: "webhook";
1521
+ readonly webhook: ChannelWebhook<TAdapter>;
1522
+ });
1523
+ /**
1524
+ * True only when the descriptor declares `senderIdentity: "authenticated"`. An absent or
1525
+ * unauthenticated declaration is false.
1526
+ *
1527
+ * @public
1528
+ */
1529
+ declare function isAuthenticatedSender(descriptor: ChannelDescriptor): boolean;
1530
+
1531
+ /**
1532
+ * `configFromEnv` and `selectVariant`: bind a channel descriptor's config fields to environment
1533
+ * variables, and pick one of a platform's config shapes.
1534
+ *
1535
+ * @public
1536
+ */
1537
+
1538
+ /** What `configFromEnv` read from the environment. Holds secret values: never log it whole. */
1539
+ interface EnvConfig {
1540
+ /** Trimmed, non-empty values by config key. */
1541
+ readonly config: Readonly<Record<string, string>>;
1542
+ /** Full variable names of required fields that are unset, empty or whitespace. */
1543
+ readonly missing: readonly string[];
1544
+ /** Values of present fields marked secret, for a log mask. Never logged. */
1545
+ readonly secrets: readonly string[];
1546
+ /** Present only when `enabledBy` was given: whether that variable is `"true"` (any case) or `"1"`. */
1547
+ readonly enabled?: boolean;
1548
+ }
1549
+ /** Options for `configFromEnv`; a plain string is shorthand for `{ prefix }`. */
1550
+ interface EnvOptions {
1551
+ /** Prepended to each field's `env`. Default `""`. */
1552
+ readonly prefix?: string;
1553
+ /** Full variable name by config key, replacing `prefix + field.env` for that field. */
1554
+ readonly rename?: Readonly<Record<string, string>>;
1555
+ /** Config keys that are required in addition to the fields marked required. */
1556
+ readonly require?: readonly string[];
1557
+ /** Full name of a flag variable; `enabled` is true when it is `"true"` (any case) or `"1"`. */
1558
+ readonly enabledBy?: string;
1559
+ }
1560
+ type Env = Readonly<Record<string, string | undefined>>;
1561
+ /**
1562
+ * Read a descriptor's fields from `env`, using `prefix + field.env` (or the `rename` entry for the key) as the variable name. Fields
1563
+ * without `env` are skipped.
1564
+ */
1565
+ declare function configFromEnv(descriptor: ChannelDescriptor, env: Env, options?: string | EnvOptions): EnvConfig;
1566
+ /**
1567
+ * The descriptor to use for `name`: the descriptor itself when `name` is undefined and it has no
1568
+ * variants, otherwise the named variant. Throws `unknown_channel_variant` for a name that is not a
1569
+ * variant (or a missing name when variants exist) and `platform_mismatch` for a variant whose
1570
+ * platform differs from its parent's.
1571
+ */
1572
+ declare function selectVariant(descriptor: ChannelDescriptor, name: string | undefined): ChannelDescriptor;
1573
+
1574
+ /**
1575
+ * `createChannels` — build every configured channel from its descriptor (FR-002 of B-018).
1576
+ *
1577
+ * One loop replaces the per-platform constructor calls an app used to write. A channel whose
1578
+ * configuration is refused lands in `rejected` and the others are still built, so one bad entry
1579
+ * never stops the healthy ones. Nothing here connects or performs I/O (NFR-001): connecting is the
1580
+ * runner's job, after the app has seen what was rejected.
1581
+ *
1582
+ * @public
1583
+ */
1584
+
1585
+ /** One channel to build: its descriptor and the configuration the app supplies for it. */
1586
+ interface ChannelEntry {
1587
+ readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;
1588
+ /** Values keyed by the descriptor's field keys. Absent means every required field is missing. */
1589
+ readonly config?: Readonly<Record<string, unknown>>;
1590
+ /** Runtime dependencies passed to the descriptor's `create` as its second argument. */
1591
+ readonly deps?: ChannelDeps;
1592
+ /**
1593
+ * The prefix passed to `configFromEnv` for this entry, so a missing field's rejection names its
1594
+ * full environment variable. Defaults to `""`.
1595
+ */
1596
+ readonly envPrefix?: string;
1597
+ }
1598
+ /** A channel that was not built, and the configuration error that says why. */
1599
+ interface ChannelRejection {
1600
+ readonly platform: PlatformName;
1601
+ readonly error: GatewayConfigurationError;
1602
+ }
1603
+ /** A built adapter paired with the descriptor that built it, so a consumer need not re-pair them. */
1604
+ interface BuiltChannel {
1605
+ readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;
1606
+ readonly adapter: BasePlatformAdapter;
1607
+ }
1608
+ /** What `createChannels` built and what it refused. */
1609
+ interface CreateChannelsResult {
1610
+ readonly adapters: BasePlatformAdapter[];
1611
+ /** The same adapters, in the same order, each paired with its descriptor. */
1612
+ readonly channels: BuiltChannel[];
1613
+ readonly rejected: ChannelRejection[];
1614
+ }
1615
+ /**
1616
+ * Build an adapter for each entry whose required fields are present.
1617
+ *
1618
+ * An entry missing a required field (absent, `null` or `""`; `0` and `false` count as present) is
1619
+ * rejected with a `GatewayConfigurationError` coded `missing_required_config` that names every
1620
+ * missing key, and its `create` is never called. A `GatewayConfigurationError` thrown by `create`
1621
+ * is reported the same way. Any other throw is a defect, not a configuration fault, and propagates.
1622
+ *
1623
+ * Only one adapter per platform is built, because the runner routes replies and `stop()` by
1624
+ * platform. The first entry built for a platform wins; a later entry for that platform is rejected
1625
+ * with a `GatewayConfigurationError` coded `duplicate_channel`, before its required fields are
1626
+ * checked, and its `create` is never called. An entry rejected for its configuration built
1627
+ * nothing, so it does not claim its platform.
1628
+ *
1629
+ * The runner keys adapters by the adapter's own `platform`, so an adapter must report the platform
1630
+ * its descriptor declares. One that reports another is discarded unconnected and its entry is
1631
+ * rejected with a `GatewayConfigurationError` coded `platform_mismatch`; it claims no platform.
1632
+ *
1633
+ * @public
1634
+ */
1635
+ declare function createChannels(entries: ReadonlyArray<ChannelEntry>): CreateChannelsResult;
1636
+
1637
+ /**
1638
+ * How the core's two outbound builders treat `attachments` (B-674): `GatewayRunner`'s `ctx.reply`
1639
+ * and `DeliveryRouter.send` both carry a non-empty list and both refuse it for an adapter that
1640
+ * does not declare `supportsAttachments`.
1641
+ *
1642
+ * The refusal here is defence in depth: every adapter in this repository refuses on its own, but an
1643
+ * adapter written elsewhere inherits `supportsAttachments = false` and may ignore the field, sending
1644
+ * the text alone and reporting success. Refusing before the adapter is called keeps the image from
1645
+ * being dropped in silence whichever adapter receives it.
1646
+ */
1647
+
1648
+ /**
1649
+ * `attachments_unsupported` when `outbound` carries attachments and `adapter` does not declare
1650
+ * `supportsAttachments`, otherwise `undefined`. Makes no platform call.
1651
+ *
1652
+ * `GatewayRunner` and `DeliveryRouter` call it before they reach an adapter; an adapter calls it
1653
+ * (or {@link BasePlatformAdapter.refuseAttachments}) to refuse on a direct `sendMessage`. Absent,
1654
+ * `null` and empty `attachments` pass; any other value without a zero length, such as `{}` from a
1655
+ * JavaScript caller, is refused.
1656
+ */
1657
+ declare function refuseUnsupportedAttachments(adapter: BasePlatformAdapter, outbound: OutboundMessage): SendResult | undefined;
1658
+
1659
+ /**
1660
+ * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).
1661
+ *
1662
+ * The router holds a map of `platform → adapter` and forwards
1663
+ * `DeliveryRequest` to the right adapter's `sendMessage`. Composes
1664
+ * with `Cron` from `loopzero-sdk` for scheduled delivery — the
1665
+ * router is the "WHERE to send", Cron is the "WHEN to fire".
1666
+ *
1667
+ * @public
1668
+ */
1669
+
1670
+ /** Target for an outbound delivery. */
1671
+ interface DeliveryTarget {
1672
+ readonly platform: PlatformName;
1673
+ readonly channel: {
1674
+ readonly id: string;
1675
+ readonly type: "dm" | "group" | "thread";
1676
+ readonly topicId?: string;
1677
+ };
1678
+ }
1679
+ /** Full outbound request: target + content. */
1680
+ interface DeliveryRequest extends DeliveryTarget {
1681
+ readonly text: string;
1682
+ readonly format?: "plain" | "markdown" | "html";
1683
+ readonly replyTo?: string;
1684
+ /** Images to send with the text; an empty list is left out (B-674). */
1685
+ readonly attachments?: ReadonlyArray<OutboundAttachment>;
1686
+ }
1687
+ /**
1688
+ * Routes outbound requests to the correct adapter.
1689
+ *
1690
+ * **Contract:**
1691
+ * - `register` is last-writer-wins by platform.
1692
+ * - `send` with unknown platform returns `{ ok: false, code: "no_adapter" }`.
1693
+ * - `send` never throws on platform errors (delegates to adapter's SendResult).
1694
+ * - `send` with attachments refuses with `attachments_unsupported`, calling no `sendMessage`, when
1695
+ * the adapter does not declare `supportsAttachments`.
1696
+ *
1697
+ * @public
1698
+ */
1699
+ declare class DeliveryRouter {
1700
+ private readonly adapters;
1701
+ register(adapter: BasePlatformAdapter): void;
1702
+ send(req: DeliveryRequest): Promise<SendResult>;
1703
+ }
1704
+
1705
+ /** Options for {@link reportDiagnostic}. */
1706
+ interface ReportDiagnosticOptions {
1707
+ /** A failure (as opposed to an informational line). Default false. */
1708
+ readonly failure?: boolean;
1709
+ }
1710
+ /**
1711
+ * Redact, prefix with `[tag] `, and write one line.
1712
+ *
1713
+ * Every diagnostic line from the gateway goes through here, so redaction (and
1714
+ * later, routing) happens in one place. `options.failure` does not change the
1715
+ * output today; it marks the line for routing once the SDK exports its emitters.
1716
+ */
1717
+ declare function reportDiagnostic(tag: string, message: string, _options?: ReportDiagnosticOptions): void;
1718
+
1719
+ /**
1720
+ * `GatewayLifecycleError` — a lifecycle method was called from a state that
1721
+ * cannot honour it.
1722
+ *
1723
+ * Distinct from {@link GatewayConfigurationError}, which reports a bad or
1724
+ * missing setting at construction time. This one reports a legal call made at
1725
+ * an illegal moment: the configuration is fine, the ordering is not.
1726
+ *
1727
+ * It exists because the alternative is worse than an error. `GatewayRunner`
1728
+ * used to accept `start()` after `stop()` and quietly produce a runner that
1729
+ * reconnected its adapters and then refused to disconnect them — a leak that
1730
+ * reported success. Failing loudly at the call that cannot be honoured is the
1731
+ * only outcome a caller can act on.
1732
+ *
1733
+ * @public
1734
+ */
1735
+ /** Public input shape for the {@link GatewayLifecycleError} constructor. */
1736
+ interface GatewayLifecycleErrorOptions {
1737
+ /** Stable, machine-readable discriminator (e.g. `"runner_stopped"`). */
1738
+ readonly code: string;
1739
+ /** Human-readable explanation, including what the caller should do instead. */
1740
+ readonly message: string;
1741
+ }
1742
+ /**
1743
+ * Thrown when a lifecycle transition is not available from the current state.
1744
+ *
1745
+ * @public
1746
+ */
1747
+ declare class GatewayLifecycleError extends Error {
1748
+ readonly name: string;
1749
+ /** Stable discriminator, so callers branch on `code` rather than on message text. */
1750
+ readonly code: string;
1751
+ constructor(opts: GatewayLifecycleErrorOptions);
1752
+ }
1753
+
1754
+ /**
1755
+ * File-backed pairing store: senders approved by an owner are kept in `pairing.json`.
1756
+ * Pending codes live in memory for one hour.
1757
+ *
1758
+ * @public
1759
+ */
1760
+ /** Pairing store used by the access policy hook. */
1761
+ interface PairingStore {
1762
+ /** A 6-digit code for the sender; the same code while one is pending. */
1763
+ issue(platform: string, senderId: string): string;
1764
+ approve(code: string): Promise<{
1765
+ ok: true;
1766
+ platform: string;
1767
+ senderId: string;
1768
+ } | {
1769
+ ok: false;
1770
+ reason: "unknown_or_expired" | "write_failed";
1771
+ }>;
1772
+ isPaired(platform: string, senderId: string): boolean;
1773
+ }
1774
+ /** `<platform>:<senderId>`; email ids compare case-insensitively. */
1775
+ declare function senderKey(platform: string, senderId: string): string;
1776
+ /** Creates a store persisted in `<dir>/pairing.json` (mode 0600). */
1777
+ declare function createFilePairingStore(options: {
1778
+ dir: string;
1779
+ clock?: () => number;
1780
+ random?: (min: number, max: number) => number;
1781
+ }): PairingStore;
1782
+
1783
+ /**
1784
+ * Gateway hooks — own contract, not a `Plugin.kind` extension
1785
+ * (T4.1, ADRs D176, D177).
1786
+ *
1787
+ * Three fire points:
1788
+ * - `pre_inbound` — runs sequentially; first `{ block: true }` short-circuits.
1789
+ * - `post_outbound` — fire-and-forget; errors logged.
1790
+ * - `on_error` — fire-and-forget; called when the handler throws.
1791
+ *
1792
+ * Signature mirrors the SDK's `pre_tool_call` veto (D101) so consumers
1793
+ * have a single mental model for "block or continue" hooks.
1794
+ *
1795
+ * @public
1796
+ */
1797
+
1798
+ /** Closed enum of hook fire points. */
1799
+ type HookName = "pre_inbound" | "post_outbound" | "on_error";
1800
+ /**
1801
+ * Decision returned by a `pre_inbound` hook.
1802
+ *
1803
+ * - `block: true` short-circuits the chain — handler does NOT run.
1804
+ * - `message` set → runner calls `ctx.reply(message)` BEFORE short-circuit (EC-D).
1805
+ * - `block: false` or `undefined` → continue.
1806
+ */
1807
+ interface HookDecision {
1808
+ readonly block?: boolean;
1809
+ readonly message?: string;
1810
+ }
1811
+ /** Context passed to `pre_inbound` hooks. */
1812
+ interface PreInboundContext {
1813
+ readonly event: MessageEvent;
1814
+ }
1815
+ /** Context passed to `post_outbound` hooks. */
1816
+ interface PostOutboundContext {
1817
+ readonly event: MessageEvent;
1818
+ readonly outbound: OutboundMessage;
1819
+ readonly result: SendResult;
1820
+ }
1821
+ /** Context passed to `on_error` hooks. */
1822
+ interface OnErrorContext {
1823
+ readonly event: MessageEvent;
1824
+ readonly error: Error;
1825
+ }
1826
+ /** A gateway hook: any of the three fire-point methods are optional. */
1827
+ interface GatewayHook {
1828
+ readonly name: string;
1829
+ pre_inbound?(ctx: PreInboundContext): Promise<HookDecision | void> | HookDecision | void;
1830
+ post_outbound?(ctx: PostOutboundContext): Promise<void> | void;
1831
+ on_error?(ctx: OnErrorContext): Promise<void> | void;
1832
+ }
1833
+
1834
+ /**
1835
+ * Access policy hook: who may talk to the agent, with sender pairing.
1836
+ *
1837
+ * @public
1838
+ */
1839
+
1840
+ type DmPolicy = "pairing" | "allowlist" | "open" | "disabled";
1841
+ /** Every reply text the access policy sends. Omitted entries keep their default. */
1842
+ interface AccessPolicyMessages {
1843
+ /** Reply to a stranger in `pairing` mode; receives the issued code. */
1844
+ readonly pairingCode?: (code: string) => string;
1845
+ /** Owner sent `/approve` with an unknown or expired code. */
1846
+ readonly invalidCode?: string;
1847
+ /** Owner sent `/approve` and the pairing could not be saved. */
1848
+ readonly failedSave?: string;
1849
+ /** Owner's `/approve` succeeded. */
1850
+ readonly paired?: string;
1851
+ /** Owner sent `/approve` while pairing is off. */
1852
+ readonly pairingOff?: string;
1853
+ }
1854
+ /** Options for {@link createAccessPolicyHook}. */
1855
+ interface AccessPolicyOptions {
1856
+ /** `<platform>:<senderId>` keys. */
1857
+ readonly owners: ReadonlySet<string>;
1858
+ readonly allowed?: ReadonlySet<string>;
1859
+ readonly dm: DmPolicy;
1860
+ /** Group messages from non-members: "silent" (default) or "open". */
1861
+ readonly groups?: "silent" | "open";
1862
+ /** Which platforms authenticate the sender. */
1863
+ readonly isAuthenticated: (platform: PlatformName) => boolean;
1864
+ /** Required when dm is "pairing". */
1865
+ readonly pairing?: PairingStore;
1866
+ readonly refusalText?: string;
1867
+ /** Reply texts; each entry defaults to the built-in wording. */
1868
+ readonly messages?: AccessPolicyMessages;
1869
+ readonly refusalIntervalMs?: number;
1870
+ /** Let a message through untouched. */
1871
+ readonly passThrough?: (event: MessageEvent) => boolean;
1872
+ readonly clock?: () => number;
1873
+ readonly write?: (line: string) => void;
1874
+ }
1875
+ /** Builds the `pre_inbound` access policy hook. */
1876
+ declare function createAccessPolicyHook(options: AccessPolicyOptions): GatewayHook;
1877
+
1878
+ /**
1879
+ * Chat command parsing and a single `pre_inbound` hook for many commands.
1880
+ *
1881
+ * Recognises a command behind one leading mention (`<@U123> /help`,
1882
+ * `@bot /help`) and with Telegram's `@botname` suffix (`/help@my_bot`).
1883
+ * The name is matched exactly: `/new chat` is `/new` with arg `chat`,
1884
+ * `/newer` is never `/new`.
1885
+ *
1886
+ * @public
1887
+ */
1888
+
1889
+ /** A parsed chat command. */
1890
+ interface ParsedChatCommand {
1891
+ /** Command name, without the prefix and without `@bot`. */
1892
+ readonly name: string;
1893
+ /** Trimmed rest of the text, `""` when none. */
1894
+ readonly arg: string;
1895
+ }
1896
+ /**
1897
+ * Strips one leading `<@U...>` or `@name` mention and a `@bot` suffix.
1898
+ * Returns `undefined` for text that is not a command.
1899
+ */
1900
+ declare function parseChatCommand(text: string, options?: {
1901
+ prefixes?: ReadonlyArray<string>;
1902
+ }): ParsedChatCommand | undefined;
1903
+ /** One command handled by {@link commandHook}. */
1904
+ interface ChatCommand {
1905
+ readonly name: string;
1906
+ readonly description: string;
1907
+ /** Default `"optional"`. */
1908
+ readonly arg?: "none" | "optional" | "required";
1909
+ /** Usage line shown in help. Default `"/<name>"`. */
1910
+ readonly usage?: string;
1911
+ run(event: MessageEvent, arg: string): HookDecision | undefined | Promise<HookDecision | undefined>;
1912
+ }
1913
+ /** Help text listing every command's usage and description, in declaration order. */
1914
+ declare function helpText(commands: ReadonlyArray<ChatCommand>): string;
1915
+ /**
1916
+ * One `pre_inbound` hook for many commands. Also answers `/help`
1917
+ * (rename with `helpCommand`, disable with `false`).
1918
+ */
1919
+ declare function commandHook(commands: ReadonlyArray<ChatCommand>, options?: {
1920
+ name?: string;
1921
+ helpCommand?: string | false;
1922
+ }): GatewayHook;
1923
+
1924
+ /**
1925
+ * `HookExecutor` — runs registered gateway hooks at their fire points.
1926
+ *
1927
+ * Split out of `hooks/types.ts` (which now holds the contract only) so the
1928
+ * filename predicts its contents: interfaces live in `types.ts`, the run
1929
+ * engine lives here. Behavior is identical to the previous colocated class.
1930
+ *
1931
+ * @public
1932
+ */
1933
+
1934
+ declare class HookExecutor {
1935
+ private readonly hooks;
1936
+ constructor(hooks: ReadonlyArray<GatewayHook>);
1937
+ /**
1938
+ * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.
1939
+ * A hook throwing is treated as `{ block: true }` (logged via the runner).
1940
+ */
1941
+ firePreInbound(ctx: PreInboundContext): Promise<HookDecision>;
1942
+ /** Fire all `post_outbound` hooks; errors logged via stderr. */
1943
+ firePostOutbound(ctx: PostOutboundContext): Promise<void>;
1944
+ /** Fire all `on_error` hooks; errors logged via stderr. */
1945
+ fireOnError(ctx: OnErrorContext): Promise<void>;
1946
+ }
1947
+
1948
+ /**
1949
+ * `groupActivationHook` — blocks group messages that did not address the bot, per chat.
1950
+ *
1951
+ * @public
1952
+ */
1953
+
1954
+ /** `"mention"` answers only messages that address the bot; `"always"` answers every message. */
1955
+ type GroupActivationMode = "mention" | "always";
1956
+ /** Options for {@link groupActivationHook}. */
1957
+ interface GroupActivationOptions {
1958
+ /** Mode for chats `modeFor` has no answer for. */
1959
+ readonly mode: GroupActivationMode;
1960
+ /** Read on every message, so an app can change a chat's mode at run time. */
1961
+ modeFor?(channelId: string): GroupActivationMode | undefined;
1962
+ /** Hook name. Default `"group-activation"`. */
1963
+ readonly name?: string;
1964
+ }
1965
+ /**
1966
+ * A `pre_inbound` hook that blocks a group or thread message when the mode is `"mention"` and the
1967
+ * adapter reported `addressed: false`. Direct messages and events with `addressed` unset pass.
1968
+ */
1969
+ declare function groupActivationHook(options: GroupActivationOptions): GatewayHook;
1970
+
1971
+ /**
1972
+ * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).
1973
+ *
1974
+ * Owns the adapter map, dispatches inbound events through the hook chain,
1975
+ * builds a per-event `GatewayContext` whose `reply` auto-routes to the
1976
+ * adapter matching `event.platform` (EC-G).
1977
+ *
1978
+ * **Lifecycle:**
1979
+ * - `start()` connects all adapters in parallel and resolves a `StartResult`.
1980
+ * By default (`connectFailure: "rollback"`) partial failure rolls back:
1981
+ * connected adapters get `disconnect()`, then the error rethrows. Under
1982
+ * `connectFailure: "isolate"` the adapters that connected keep running and
1983
+ * the rest are reported in `StartResult.failed`.
1984
+ * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)
1985
+ * BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner
1986
+ * cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.
1987
+ *
1988
+ * **Hook chain on inbound:**
1989
+ * 1. `firePreInbound({ event })`
1990
+ * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.
1991
+ * 3. If `block: true` only: short-circuit silently.
1992
+ * 4. Otherwise: call user handler.
1993
+ * 5. On handler throw: fire `on_error`, log via `redactSecrets` (EC-F).
1994
+ *
1995
+ * Every reply — the handler's `ctx.reply` and the EC-D auto-reply alike — fires
1996
+ * `post_outbound` with the event, the outbound and the adapter's result, once
1997
+ * per attempt. The hook observes the delivery; it cannot change what the caller
1998
+ * of `reply` receives.
1999
+ *
2000
+ * @public
2001
+ */
2002
+
2003
+ /** Per-event context passed to the user handler. */
2004
+ interface GatewayContext {
2005
+ /** Send a reply to the originating channel (auto-routed by `event.platform`). */
2006
+ reply(text: string, opts?: {
2007
+ format?: "plain" | "markdown" | "html";
2008
+ /** Images to send with the text; an empty list is left out (B-674). */
2009
+ attachments?: ReadonlyArray<OutboundAttachment>;
2010
+ }): Promise<SendResult>;
2011
+ /** The triggering event. */
2012
+ readonly event: MessageEvent;
2013
+ }
2014
+ /** User-supplied handler. */
2015
+ type GatewayHandler = (event: MessageEvent, ctx: GatewayContext) => Promise<void>;
2016
+ /** Runner configuration. */
2017
+ interface GatewayRunnerOptions {
2018
+ readonly adapters: ReadonlyArray<BasePlatformAdapter>;
2019
+ readonly handler: GatewayHandler;
2020
+ readonly hooks?: ReadonlyArray<GatewayHook>;
2021
+ /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */
2022
+ readonly drainTimeoutMs?: number;
2023
+ /**
2024
+ * Prefixes that `runner.command(name, h)` matches on. Default `["/"]`
2025
+ * (Telegram-style). Pass `["!"]` for Discord, `["/", "!"]` to accept
2026
+ * both. Word-boundary match (EC-A) applies to every prefix.
2027
+ *
2028
+ * @public
2029
+ */
2030
+ readonly commandPrefixes?: ReadonlyArray<string>;
2031
+ /**
2032
+ * What `start()` does when an adapter fails to connect. `"rollback"` (the default) disconnects
2033
+ * the adapters that did connect and rethrows: all or nothing. `"isolate"` keeps the adapters that
2034
+ * connected, wires inbound only for them, and reports the others in the resolved
2035
+ * `StartResult.failed`, so one channel that cannot connect does not stop the healthy ones.
2036
+ *
2037
+ * @public
2038
+ */
2039
+ readonly connectFailure?: ConnectFailure;
2040
+ /**
2041
+ * Retry, in the background, an adapter whose `connect()` threw a transient error under
2042
+ * `connectFailure: "isolate"` (network refused, DNS, 5xx), with exponential backoff and a log
2043
+ * line per attempt. An adapter that connects on a retry is wired for inbound and joins
2044
+ * `connected`. A `connect()` that resolves `false`, or throws a credential error (HTTP 401/403,
2045
+ * `M_UNKNOWN_TOKEN`, `M_FORBIDDEN`, "unauthorized"), is terminal: it is reported once and not
2046
+ * retried. Off unless set; ignored under `"rollback"`.
2047
+ *
2048
+ * @public
2049
+ */
2050
+ readonly reconnect?: ReconnectPolicy;
2051
+ /**
2052
+ * Under `connectFailure: "isolate"`, give up on one adapter's `connect()` after this many ms. The
2053
+ * adapter is reported `timed_out`, counted in `StartResult.failed`, and never wired for inbound:
2054
+ * if its `connect()` resolves `true` later, the runner disconnects it. With `reconnect` set it is
2055
+ * retried like a transient failure. Ignored under `"rollback"`, as `reconnect` is.
2056
+ *
2057
+ * @public
2058
+ */
2059
+ readonly connectTimeoutMs?: number;
2060
+ /**
2061
+ * Called as each adapter changes state, while `start()` may still be pending. `reason` is
2062
+ * redacted. A callback that throws is ignored. Ignored under `"rollback"`.
2063
+ *
2064
+ * @public
2065
+ */
2066
+ readonly onAdapterState?: (platform: PlatformName, state: AdapterState, reason?: string) => void;
2067
+ /**
2068
+ * Exact credential values masked (longest first) in every reason and log line before
2069
+ * `redactSecrets` runs.
2070
+ *
2071
+ * @public
2072
+ */
2073
+ readonly secrets?: ReadonlyArray<string>;
2074
+ }
2075
+ /**
2076
+ * Where one adapter stands under `connectFailure: "isolate"`, as reported to
2077
+ * `GatewayRunnerOptions.onAdapterState`.
2078
+ *
2079
+ * @public
2080
+ */
2081
+ type AdapterState = "connected" | "failed" | "retrying" | "timed_out";
2082
+ /**
2083
+ * Backoff for `GatewayRunnerOptions.reconnect`. The delay before attempt n is
2084
+ * `min(initialDelayMs * factor^(n-1), maxDelayMs)`.
2085
+ *
2086
+ * @public
2087
+ */
2088
+ interface ReconnectPolicy {
2089
+ /** Delay before the first retry. Default 1000ms. */
2090
+ readonly initialDelayMs?: number;
2091
+ /** Cap on the delay between attempts. Default 60_000ms. */
2092
+ readonly maxDelayMs?: number;
2093
+ /** Multiplier per attempt. Default 2. */
2094
+ readonly factor?: number;
2095
+ /** Give up after this many retries. Default: keep trying until `stop()`. */
2096
+ readonly maxAttempts?: number;
2097
+ /**
2098
+ * Treat a `connect()` that resolves `false` like one that throws a transient error: retry it on
2099
+ * the same backoff. Default `false`, where `false` is final.
2100
+ */
2101
+ readonly retryFalse?: boolean;
2102
+ }
2103
+ /**
2104
+ * How `GatewayRunner.start()` treats an adapter that fails to connect: `"rollback"` (all or
2105
+ * nothing, the default) or `"isolate"` (keep the ones that connected).
2106
+ *
2107
+ * @public
2108
+ */
2109
+ type ConnectFailure = "rollback" | "isolate";
2110
+ /**
2111
+ * What `GatewayRunner.start()` connected. Under `"rollback"` `failed` is always empty, because a
2112
+ * failure rejects instead; under `"isolate"` it names each adapter that did not connect and why,
2113
+ * with any credential in the reason redacted.
2114
+ *
2115
+ * @public
2116
+ */
2117
+ interface StartResult {
2118
+ readonly connected: ReadonlyArray<PlatformName>;
2119
+ readonly failed: ReadonlyArray<{
2120
+ readonly platform: PlatformName;
2121
+ readonly reason: string;
2122
+ }>;
2123
+ }
2124
+ /**
2125
+ * Holds the registered adapters and dispatches inbound events through
2126
+ * the hook chain to the user handler. Use the sugar `runner.command(...)`
2127
+ * for slash command dispatch with word-boundary matching (EC-A).
2128
+ *
2129
+ * @public
2130
+ */
2131
+ declare class GatewayRunner {
2132
+ private readonly opts;
2133
+ private readonly hookExecutor;
2134
+ private readonly inflight;
2135
+ private readonly unsubs;
2136
+ /** Slash command registry: name → handler (word-boundary match, EC-A). */
2137
+ private readonly commands;
2138
+ private startResult;
2139
+ /** The start that has not settled yet, shared by every overlapping `start()` call. */
2140
+ private startInFlight;
2141
+ private stopped;
2142
+ private readonly retryTimers;
2143
+ private readonly connectedAdapters;
2144
+ private readonly redact;
2145
+ constructor(opts: GatewayRunnerOptions);
2146
+ /** The registered adapter for a platform, connected or not. */
2147
+ adapter(platform: PlatformName): BasePlatformAdapter | undefined;
2148
+ /** The adapters started now (a snapshot); updated by connects, retries and `stop()`. */
2149
+ connected(): BasePlatformAdapter[];
2150
+ private emitState;
2151
+ /**
2152
+ * Register a slash command. Match rule (EC-A): text === "/" + name
2153
+ * OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
2154
+ *
2155
+ * @public
2156
+ */
2157
+ command(name: string, handler: GatewayHandler): void;
2158
+ /**
2159
+ * Connect the adapters and wire inbound dispatch for the ones that connected.
2160
+ *
2161
+ * Resolves with what connected. A second call after the first resolved returns the same result
2162
+ * without connecting again.
2163
+ *
2164
+ * Overlapping calls share one start; a start overtaken by stop resolves with no adapter connected.
2165
+ * A call made before `stop()` while another is still connecting connects nothing and settles
2166
+ * with it; a call made after `stop()` throws `runner_stopped`. When `stop()` runs before the
2167
+ * connect settles, the adapters that connected are disconnected, no inbound dispatch is wired,
2168
+ * and the start resolves `{ connected: [], failed }`, keeping the `"isolate"` failures. Under
2169
+ * `"rollback"`, a connect that fails still rejects the start.
2170
+ *
2171
+ * Under `connectFailure: "rollback"`, every connect settles before the rollback, so a failing
2172
+ * start rejects only once its slowest connect settles, as a successful one resolves only then.
2173
+ *
2174
+ * An adapter whose `disconnect()` fails while a start rolls back, or while a start that `stop()`
2175
+ * overtook gives its adapters back, is named on stderr with the error redacted; how the start
2176
+ * settles does not change.
2177
+ *
2178
+ * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
2179
+ * stopped. A stopped runner is spent; construct a new one.
2180
+ * @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after
2181
+ * every connect settled and the adapters that did connect were disconnected.
2182
+ */
2183
+ start(): Promise<StartResult>;
2184
+ private runStart;
2185
+ /** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
2186
+ private scheduleReconnect;
2187
+ private reconnectOnce;
2188
+ /**
2189
+ * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
2190
+ * the first failure. Every connect settles before the rollback: rolling back while one is still
2191
+ * pending left that adapter live once it connected.
2192
+ */
2193
+ private connectAllOrRollback;
2194
+ /**
2195
+ * Connect every adapter and keep the ones that connected. The `async` wrapper turns a
2196
+ * synchronous throw inside `connect()` into a rejection `allSettled` sees; a bare
2197
+ * `a => a.connect()` would let it escape `map` and reject `start()` itself.
2198
+ */
2199
+ private connectIsolated;
2200
+ /** Connect one adapter, bounded by `connectTimeoutMs`, and report its state as it settles. */
2201
+ private connectOne;
2202
+ /** A connect that finished after the runner gave up on it must not stay connected unseen. */
2203
+ private releaseLateConnect;
2204
+ private classify;
2205
+ private wireInbound;
2206
+ /**
2207
+ * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
2208
+ * then disconnects adapters. Idempotent (EC-E). A disconnect that fails does not make `stop()`
2209
+ * reject and does not stop the other disconnects; it is written to stderr, redacted, naming the
2210
+ * platform.
2211
+ *
2212
+ * An adapter still connecting under an in-flight start is released when that start settles;
2213
+ * `stop()` does not wait for it.
2214
+ */
2215
+ stop(): Promise<void>;
2216
+ /**
2217
+ * EC-A: word-boundary slash command match. Prevents `/skill` from
2218
+ * shadowing `/skills`. Returns the handler if a command matches,
2219
+ * undefined otherwise.
2220
+ */
2221
+ private matchSlashCommand;
2222
+ /** EC-G: per-event ctx whose reply routes to the matching adapter. */
2223
+ private buildContext;
2224
+ }
2225
+
2226
+ /** Options for `withMediaUnderstanding`: the functions that understand media, a size cap and a failure sink. */
2227
+ interface MediaUnderstandingOptions {
2228
+ /** e.g. plugin-voice's transcribe, bound to its config. */
2229
+ transcribe?(audio: {
2230
+ data: Uint8Array;
2231
+ mediaType: string;
2232
+ }): Promise<string>;
2233
+ /** Called for each image an event carries, once inbound images exist. */
2234
+ describeImage?(image: {
2235
+ data: Uint8Array;
2236
+ mediaType: string;
2237
+ }): Promise<string>;
2238
+ /** Largest payload sent to a function. Default 20 MiB; larger is reported as not understood. */
2239
+ readonly maxBytes?: number;
2240
+ /** Where a failure is reported, with the media type and the error name only. */
2241
+ readonly write?: (line: string) => void;
2242
+ }
2243
+ /** Wraps a handler: the event it receives has the transcript or description appended to text. */
2244
+ declare function withMediaUnderstanding(handler: GatewayHandler, options: MediaUnderstandingOptions): GatewayHandler;
2245
+
2246
+ /**
2247
+ * Options for {@link ReconnectBackoff}. Delay fields default as documented on `ReconnectPolicy`.
2248
+ *
2249
+ * @public
2250
+ */
2251
+ interface ReconnectBackoffOptions extends ReconnectPolicy {
2252
+ /** A connection open at least this long resets the delay. Default 60_000. */
2253
+ readonly stableAfterMs?: number;
2254
+ /** Clock in ms; defaults to `Date.now`. */
2255
+ readonly now?: () => number;
2256
+ }
2257
+ /**
2258
+ * Reconnect delay for an adapter that holds a long-lived connection: `min(initialDelayMs *
2259
+ * factor^(n-1), maxDelayMs)` for attempt n, reset after a connection that stayed open for
2260
+ * `stableAfterMs`.
2261
+ *
2262
+ * @public
2263
+ */
2264
+ declare class ReconnectBackoff {
2265
+ private readonly initialDelayMs;
2266
+ private readonly maxDelayMs;
2267
+ private readonly factor;
2268
+ private readonly maxAttempts;
2269
+ private readonly stableAfterMs;
2270
+ private readonly now;
2271
+ private attempts;
2272
+ private openedAt;
2273
+ constructor(options?: ReconnectBackoffOptions);
2274
+ /** Call when the connection opens. */
2275
+ opened(): void;
2276
+ /** Delay before the next attempt; `undefined` once `maxAttempts` is spent. Resets first if the last connection was stable. */
2277
+ nextDelayMs(): number | undefined;
2278
+ /** Back to the initial delay. */
2279
+ reset(): void;
2280
+ }
2281
+
2282
+ /** A credential shape this module masks, and the cost of matching it. */
2283
+ interface CoveredShape {
2284
+ /** The platform and field, for the reader of the table. */
2285
+ readonly field: string;
2286
+ /** Anchored to the shape. */
2287
+ readonly pattern: RegExp;
2288
+ /** What else this matches. Every entry has one — a shape narrow enough to have none is rare. */
2289
+ readonly alsoMatches: string;
2290
+ }
2291
+ /** A credential this repository declares and this module does not mask. */
2292
+ interface UncoveredShape {
2293
+ /** The platform and field. */
2294
+ readonly field: string;
2295
+ /** Why a pattern for it would cost more than it buys. */
2296
+ readonly why: string;
2297
+ }
2298
+ /**
2299
+ * What is masked and what is not.
2300
+ *
2301
+ * The uncovered list is the point of publishing this as data rather than burying it in a regex
2302
+ * table: a reader can see which of their credentials this protects, and a maintainer adding an
2303
+ * adapter can see the standard the new shape has to meet.
2304
+ */
2305
+ declare const CREDENTIAL_SHAPES: {
2306
+ readonly covered: readonly CoveredShape[];
2307
+ readonly uncovered: readonly UncoveredShape[];
2308
+ };
2309
+ /**
2310
+ * Replace every covered shape with `***`.
2311
+ *
2312
+ * Full replacement rather than the SDK's `first6…last4`: a partial mask of a credential is still a
2313
+ * disclosure, and the six leading characters of a token identify the account it belongs to.
2314
+ *
2315
+ * @param text
2316
+ * @returns the text with covered shapes removed
2317
+ */
2318
+ declare function maskShapes(text: string): string;
2319
+ /**
2320
+ * Mask this domain's shapes, then apply the SDK's redactor.
2321
+ *
2322
+ * The one function the log sites call. Order matters: ours runs first so a covered shape is gone
2323
+ * before the SDK's `key=value` rule can shorten it instead, and the SDK still contributes its own
2324
+ * twelve patterns for everything we do not know about.
2325
+ *
2326
+ * @param value the value to redact — a message, an error, anything stringifiable
2327
+ * @returns the redacted string
2328
+ */
2329
+ declare function redactSecrets(value: unknown): string;
2330
+ /**
2331
+ * Replace each exact value in `secrets` with `[redacted]`, longest value first so a value that
2332
+ * contains another is masked whole. Empty values are ignored. It does not run `redactSecrets`:
2333
+ * call that afterwards, because it shortens some shapes to a head and tail and the masked fragments
2334
+ * would otherwise survive.
2335
+ *
2336
+ * @param text the text to mask
2337
+ * @param secrets the exact credential values configured for this process
2338
+ * @returns the text with every occurrence of every value replaced
2339
+ */
2340
+ declare function maskSecrets(text: string, secrets: ReadonlyArray<string>): string;
2341
+
2342
+ /**
2343
+ * A small key/value store for credentials an adapter must keep across restarts, such as a rotated
2344
+ * OAuth refresh token.
2345
+ *
2346
+ * @public
2347
+ */
2348
+ /** Reads and writes one string credential per key. @public */
2349
+ interface CredentialStore {
2350
+ /** The stored value, or `undefined` when the key was never set. */
2351
+ get(key: string): Promise<string | undefined>;
2352
+ /** Store `value` under `key`, replacing any earlier value. */
2353
+ set(key: string, value: string): Promise<void>;
2354
+ }
2355
+ /** One file per key under `dir`, mode 0600, written to a temp file and renamed. @public */
2356
+ declare function createFileCredentialStore(dir: string): CredentialStore;
2357
+
2358
+ /**
2359
+ * `SessionRouter` — pure routing logic: `MessageEvent → agentId`
2360
+ * (T2.1, ADR D174).
2361
+ *
2362
+ * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).
2363
+ * The router's job is to produce a stable, deterministic key — the SDK then
2364
+ * hydrates the actual session.
2365
+ *
2366
+ * Default strategy format: `<platform>-<channelType>-<...key parts>`.
2367
+ *
2368
+ * **EC-B:** thread events without a `topicId` (adapter bug or non-thread
2369
+ * forum message) fall back to the group key — prevents `...-undefined`
2370
+ * split-brain sessions.
2371
+ *
2372
+ * @public
2373
+ */
2374
+
2375
+ /** Strategy function: pure mapping from event to agentId string. */
2376
+ type AgentIdStrategy = (event: MessageEvent) => string;
2377
+ /**
2378
+ * Default strategy. Escapes ids (`_` to `__`, `-` to `_d`) so the format
2379
+ * remains splittable on `-` and distinct ids never share a key.
2380
+ */
2381
+ declare function defaultStrategy(event: MessageEvent): string;
2382
+ /**
2383
+ * Routes inbound events to agent ids. Defaults to `defaultStrategy`;
2384
+ * callers override per-bot to preserve legacy keys (telegram-pro keeps
2385
+ * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).
2386
+ *
2387
+ * @public
2388
+ */
2389
+ declare class SessionRouter {
2390
+ private readonly strategy;
2391
+ constructor(strategy?: AgentIdStrategy);
2392
+ resolveAgentId(event: MessageEvent): string;
2393
+ }
2394
+
2395
+ /**
2396
+ * Rule-based agent bindings: pick the agent that answers a message by
2397
+ * platform, account and peer.
2398
+ *
2399
+ * @public
2400
+ */
2401
+
2402
+ interface AgentBindingRule {
2403
+ readonly agent: string;
2404
+ readonly platform?: PlatformName;
2405
+ /** Matched against accountOf(event). */
2406
+ readonly account?: string;
2407
+ /** Matched against event.sender.id for a DM and event.channel.id otherwise. */
2408
+ readonly peer?: string;
2409
+ }
2410
+ /** Options for {@link createAgentBindings}. */
2411
+ interface AgentBindingsOptions {
2412
+ readonly defaultAgent: string;
2413
+ readonly rules: ReadonlyArray<AgentBindingRule>;
2414
+ /** Agents that exist; every rule and the default must name one. */
2415
+ readonly agents: ReadonlyArray<string>;
2416
+ /** Which bot account received the event, when the app runs several. Default: undefined. */
2417
+ readonly accountOf?: (event: MessageEvent) => string | undefined;
2418
+ }
2419
+ /** Chooses the agent that answers an event. */
2420
+ interface AgentBindings {
2421
+ agentFor(event: MessageEvent): string;
2422
+ }
2423
+ /**
2424
+ * Builds bindings from rules. The most specific matching rule wins (peer 4, account 2,
2425
+ * platform 1), ties go to the earlier rule, no match gives `defaultAgent`.
2426
+ * Throws `GatewayConfigurationError` for `unknown_agent` or `empty_binding_rule`.
2427
+ */
2428
+ declare function createAgentBindings(options: AgentBindingsOptions): AgentBindings;
2429
+ /** Prefixes another strategy's key with the bound agent, so two agents never share a session. */
2430
+ declare function bindingStrategy(bindings: AgentBindings, inner: AgentIdStrategy): AgentIdStrategy;
2431
+
2432
+ /**
2433
+ * `scopedStrategy` — session keys with DM scopes, peer links and account labels.
2434
+ *
2435
+ * `dm` is always the second key segment, so no label or peer name can make a
2436
+ * DM key equal a group (`grp`) or thread (`tpc`) key. Every segment is encoded
2437
+ * with `encodeURIComponent` and joined with `:`, which it never emits, so the
2438
+ * key mapping is injective. Linked peers and `main` use a leading `@` segment,
2439
+ * which no encoded platform can start with (`@` encodes to `%40`).
2440
+ *
2441
+ * @public
2442
+ */
2443
+
2444
+ /** How DMs are keyed: one conversation, per peer, per channel and peer, or per account too. */
2445
+ type DmScope = "main" | "per-peer" | "per-channel-peer" | "per-account-channel-peer";
2446
+ /** Options for {@link scopedStrategy}. */
2447
+ interface ScopedStrategyOptions {
2448
+ readonly dmScope: DmScope;
2449
+ /** `<platform>:<senderId>` to a peer name. Used by `per-peer`. */
2450
+ readonly peerLinks?: ReadonlyMap<string, string>;
2451
+ /** Required when `dmScope` is `per-account-channel-peer`. */
2452
+ readonly accountLabel?: string;
2453
+ /** Group key: one per channel (default) or one per channel and sender. */
2454
+ readonly groupScope?: "channel" | "channel-sender";
2455
+ /**
2456
+ * Overrides the `main` and linked-peer DM keys so an app can keep the keys
2457
+ * its stored sessions already use. `peer` receives the raw (unescaped) peer
2458
+ * name. The caller owns uniqueness: a custom key can collide with other keys.
2459
+ */
2460
+ readonly keys?: {
2461
+ readonly main?: string;
2462
+ readonly peer?: (name: string) => string;
2463
+ };
2464
+ }
2465
+ /**
2466
+ * Builds a strategy for the chosen DM scope. Keys:
2467
+ * `main` → `_m-dm`; `per-peer` linked → `_p-dm-<peer>`, unlinked → the
2468
+ * per-channel-peer key; `per-channel-peer` → `<platform>-dm-<sender>`;
2469
+ * `per-account-channel-peer` → `<platform>-dm-<account>-<sender>`.
2470
+ * Groups are `<platform>-grp-<channel>[-<sender>]`, topic threads
2471
+ * `<platform>-tpc-<channel>-<topic>`. Every segment is escaped with `sanitize`.
2472
+ * `keys` replaces the `main` and linked-peer formats. A throwing `keys.peer` throws per event.
2473
+ * Throws `GatewayConfigurationError` (`invalid_session_scope`) on bad options, never per event.
2474
+ */
2475
+ declare function scopedStrategy(options: ScopedStrategyOptions): AgentIdStrategy;
2476
+
2477
+ /**
2478
+ * What `ChatPresenter` needs to know about one platform: how to rewrite the text, and which
2479
+ * `format` to declare on the message (B-019 FR-001, FR-002).
2480
+ *
2481
+ * `toDialect` alone is not enough, and composing it with the presenter's defaults proved it:
2482
+ * `ChatPresenter` declares `markdown` unless told otherwise, and `toDialect` passes a platform it
2483
+ * was not taught through unchanged. So matrix and email put `**bold**` on the wire as characters
2484
+ * (matrix drops `markdown` with a warning, email escapes it into `<pre>`), and telegram and slack
2485
+ * were handed a bold spelled for a dialect whose bold is a single asterisk. The text rewrite and
2486
+ * the format flag have to be chosen together, per platform, by the package that knows what each
2487
+ * adapter does with `format` — this one.
2488
+ *
2489
+ * Pure data and pure functions: no I/O, and the same input always gives the same output.
2490
+ * `loopzero-gateway` still does not depend on `loopzero-presenter`; `ChannelRendering` matches
2491
+ * the presenter's `translate` and `format` options structurally.
2492
+ */
2493
+
2494
+ /**
2495
+ * The pair a consumer spreads into `ChatPresenter`'s options for one platform.
2496
+ *
2497
+ * @public
2498
+ */
2499
+ interface ChannelRendering {
2500
+ /** The rendering hint the adapter receives as `OutboundMessage.format`. */
2501
+ readonly format: "plain" | "markdown";
2502
+ /** Rewrites the assembled answer for the platform. Pure and deterministic. */
2503
+ readonly translate: (text: string) => string;
2504
+ }
2505
+ /**
2506
+ * The rendering `ChatPresenter` needs for `platform`.
2507
+ *
2508
+ * Only the four inline markers `toDialect` knows are rewritten: bold, italic, strikethrough and
2509
+ * inline code. Headings, links, lists and block quotes pass through on every platform, and fenced
2510
+ * code is not handled yet (the inline-code rule rewrites a fence's backticks).
2511
+ *
2512
+ * @param platform - the destination, typically `event.platform` of the inbound message
2513
+ * @returns the `{ translate, format }` pair for that platform
2514
+ * @throws RangeError when `platform` is not one of the platforms this package knows. Answering with
2515
+ * nothing would let the presenter fall back to identity and `markdown`, which is the defect this
2516
+ * function exists to remove.
2517
+ * @public
2518
+ */
2519
+ declare function channelRendering(platform: PlatformName): ChannelRendering;
2520
+
2521
+ /**
2522
+ * `chunkText` — transport-agnostic, boundary-preferring text chunker.
2523
+ *
2524
+ * Single-sources the message-splitting knowledge that was copy-pasted across
2525
+ * the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two
2526
+ * boundary-search families that existed in the adapters:
2527
+ *
2528
+ * - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),
2529
+ * boundary preference `"\n\n" → "\n" → " "`, UTF-16 surrogate-pair guard,
2530
+ * leading-whitespace strip on continuation, optional part-trim.
2531
+ * - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),
2532
+ * boundary preference `"\n\n" → "\n"` (no space), no surrogate guard,
2533
+ * leading-newline strip on continuation.
2534
+ *
2535
+ * The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different
2536
+ * algorithm and is intentionally NOT folded in here — those adapters keep their
2537
+ * grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.
2538
+ *
2539
+ * @public
2540
+ */
2541
+ /** Options for {@link chunkText}. */
2542
+ interface ChunkTextOptions {
2543
+ /**
2544
+ * Hard cap. If the whole input is `<= limit`, it is returned as a single
2545
+ * chunk (subject to `trimParts`). Continuation chunks are cut within the
2546
+ * `safeLimit` window.
2547
+ */
2548
+ readonly limit: number;
2549
+ /**
2550
+ * Soft window each cut searches within. Defaults to `limit`. The Telegram
2551
+ * family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).
2552
+ */
2553
+ readonly safeLimit?: number;
2554
+ /**
2555
+ * Boundary strings tried, in order, from most to least preferred. A boundary
2556
+ * is accepted once its position is `>= window * 0.5`; otherwise the next one
2557
+ * is tried. Default: `["\n\n", "\n", " "]`.
2558
+ */
2559
+ readonly boundaries?: readonly string[];
2560
+ /**
2561
+ * When no boundary reaches the half-window threshold:
2562
+ * - `"last-boundary"` — use the last computed boundary if it is `> 0`,
2563
+ * else fall back to the window edge (Slack family).
2564
+ * - `"window"` — fall back straight to the window edge (Telegram family).
2565
+ * Default: `"window"`.
2566
+ */
2567
+ readonly lastResort?: "last-boundary" | "window";
2568
+ /**
2569
+ * Guard against slicing through a UTF-16 low surrogate (splitting an emoji).
2570
+ * Default: `false`.
2571
+ */
2572
+ readonly surrogateGuard?: boolean;
2573
+ /**
2574
+ * Pattern stripped from the START of each continuation chunk. Default `/^\n+/`
2575
+ * (Telegram family). Slack family uses `/^\s+/`.
2576
+ */
2577
+ readonly stripLeading?: RegExp;
2578
+ /**
2579
+ * When true, each resulting part is `.trim()`-ed and empty parts are dropped
2580
+ * (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.
2581
+ */
2582
+ readonly trimParts?: boolean;
2583
+ /**
2584
+ * When true, a cut that would fall inside a Markdown table row (a line whose first non-blank
2585
+ * character is `|`) moves back to the start of that row, provided the row fits in the window and
2586
+ * does not open the chunk; the row then opens the next chunk whole and byte-identical (B-556).
2587
+ * A row longer than the window is cut by length as before. Text with no table row splits exactly
2588
+ * as without the option. Default: `false`.
2589
+ */
2590
+ readonly keepTableRows?: boolean;
2591
+ }
2592
+ /**
2593
+ * Split `text` into chunks no longer than the configured window, preferring
2594
+ * natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.
2595
+ */
2596
+ declare function chunkText(text: string, options: ChunkTextOptions): string[];
2597
+ /** Options for {@link chunkByGrapheme}. */
2598
+ interface ChunkByGraphemeOptions {
2599
+ /** If `text.length <= limit`, it is returned as a single chunk. */
2600
+ readonly limit: number;
2601
+ /**
2602
+ * Max length per emitted part during the grapheme walk. Defaults to `limit`.
2603
+ * Callers that reserve room for a per-part prefix (e.g. SMS `"(i/N) "`) pass a
2604
+ * `partLimit` below `limit`.
2605
+ */
2606
+ readonly partLimit?: number;
2607
+ }
2608
+ /**
2609
+ * Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,
2610
+ * regional-indicator pair, or combining sequence. Distinct algorithm from
2611
+ * {@link chunkText} — used by adapters that must respect grapheme boundaries
2612
+ * (LINE, SMS) rather than search for whitespace boundaries.
2613
+ *
2614
+ * @public
2615
+ */
2616
+ declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
2617
+
2618
+ /**
2619
+ * Rewrite `text` for `platform`.
2620
+ *
2621
+ * @param text - the assembled answer, in markdown as the model produced it
2622
+ * @param platform - the destination; one this function has not been taught passes through
2623
+ * @returns the text in the platform's dialect, or unchanged when none is known
2624
+ * @public
2625
+ */
2626
+ declare function toDialect(text: string, platform: string): string;
2627
+
2628
+ /**
2629
+ * Fenced code block scanner (B-518).
2630
+ *
2631
+ * Reads the fences of CommonMark § 4.5: a line of at most three blanks, then three or more
2632
+ * backticks or tildes (an info string after a backtick run holds no backtick), closed by a line of
2633
+ * the same character, at least as many, and nothing after them but blanks. A fence never closed runs
2634
+ * to the end of the text. Fences inside a list item or block quote (indented four or more, or behind
2635
+ * a `>`) are not read.
2636
+ *
2637
+ * @public
2638
+ */
2639
+ /** One fenced code block, as offsets into the scanned text. */
2640
+ interface FenceRegion {
2641
+ /** Offset of the first character of the opening line. */
2642
+ readonly start: number;
2643
+ /** Offset just past the opening line, before its line ending. */
2644
+ readonly openerEnd: number;
2645
+ /** Offset of the first character after the opening line's line ending (the first code line). */
2646
+ readonly contentStart: number;
2647
+ /** Offset just past the last character of the closing line (its line ending excluded), or the text length when never closed. */
2648
+ readonly end: number;
2649
+ /** The opening line, byte for byte. */
2650
+ readonly opener: string;
2651
+ /** The marker run that closes the block: the opening run, without its indent. */
2652
+ readonly closer: string;
2653
+ /** False when the text ends before a closing line. */
2654
+ readonly closed: boolean;
2655
+ }
2656
+ /** Every fenced region of `text`, in order. */
2657
+ declare function scanFences(text: string): readonly FenceRegion[];
2658
+
2659
+ /**
2660
+ * Grapheme-safe splitting of long text that keeps Markdown table rows whole (B-556).
2661
+ *
2662
+ * @internal
2663
+ */
2664
+ /** The unit `partLimit` is measured in. */
2665
+ interface SplitKeepingRowsOptions {
2666
+ /** How `partLimit` is measured. Default "utf16" (UTF-16 units). */
2667
+ readonly unit?: "utf16" | "codepoint";
2668
+ }
2669
+ /**
2670
+ * Parts of at most `partLimit` units (UTF-16 units, or code points with `unit: "codepoint"`), cut
2671
+ * at grapheme boundaries and before straddled rows. Shared by the SMS and LINE splitters (text no
2672
+ * longer than a part is theirs to handle). In code-point mode `partLimit` must be a positive
2673
+ * integer and a single grapheme longer than it throws `RangeError`.
2674
+ */
2675
+ declare function splitKeepingRows(text: string, partLimit: number, options?: SplitKeepingRowsOptions): string[];
2676
+
2677
+ /** The outcome of delivering one event to the runner's handlers. */
2678
+ type DeliverOutcome = "ok" | "no_handler" | "handler_threw";
2679
+ /**
2680
+ * Map the outcomes of one delivered batch to an HTTP status, worst wins: `handler_threw` is 500,
2681
+ * `no_handler` is 503 so the provider retries, `ok` and an empty batch are 200. An unknown outcome
2682
+ * throws instead of answering 200.
2683
+ */
2684
+ declare function statusForDeliver(outcomes: ReadonlyArray<DeliverOutcome>): 200 | 500 | 503;
2685
+
2686
+ /**
2687
+ * The half of an Express webhook server that is the same for every platform.
2688
+ *
2689
+ * `gateway-line` and `gateway-sms` each ship one, and they shared 101 of ~170 lines: the lazy
2690
+ * `express` load, the raw-body capture with the hang it documents, and the start/stop lifecycle.
2691
+ * What differs is signature verification, body parsing and routing, which are genuinely
2692
+ * per-platform (#89).
2693
+ *
2694
+ * The duplication had already been paid for. Commit `11000cc` fixed a write-once latch that made
2695
+ * `start()` after `stop()` return without creating a listener — a port nothing answers on, with no
2696
+ * error and no log — and it had to fix it in BOTH files, because the latch lives in the copied
2697
+ * half. That is the DRY test verbatim: change it here, change it there.
2698
+ *
2699
+ * ## Why here, and not in a new package
2700
+ *
2701
+ * The core had no HTTP concern, and `express` is a peer dependency of exactly the two packages that
2702
+ * duplicate this — so the obvious objection to putting it here is that it would impose express on
2703
+ * every adapter.
2704
+ *
2705
+ * It does not, because nothing here imports express. Every shape below is structural: a request is
2706
+ * whatever has `readableEnded` and `on`, a listener is whatever has `listen` and `close`. The
2707
+ * packages that use express keep declaring it; this module never learns the name.
2708
+ *
2709
+ * Exported rather than internal: the two packages that consume it are separate npm packages, so
2710
+ * "internal to this repository" is not a thing the module system can express.
2711
+ *
2712
+ * @public
2713
+ */
2714
+ /** What the capture middleware reads. Express's `Request` satisfies it; so does a bare stream. */
2715
+ interface RawBodyRequest {
2716
+ readonly readableEnded?: boolean;
2717
+ readonly complete?: boolean;
2718
+ readonly headers?: Readonly<Record<string, string | string[] | undefined>>;
2719
+ setEncoding(encoding: string): unknown;
2720
+ on(event: string, listener: (arg: never) => void): unknown;
2721
+ }
2722
+ /** What a started listener must be able to do. `http.Server` satisfies it. */
2723
+ interface ListenerLike {
2724
+ close(cb?: (err?: Error) => void): unknown;
2725
+ /** Where Express 4's `listen` reports a failure to bind; `http.Server` has it. */
2726
+ once?(event: "error", listener: (err: Error) => void): unknown;
2727
+ }
2728
+ /**
2729
+ * What can start a listener. Express's app satisfies it: Express 5 passes a failure to bind to the
2730
+ * callback, Express 4 only emits it on the returned server.
2731
+ */
2732
+ interface ListenableApp {
2733
+ listen(port: number, cb: (err?: Error) => void): ListenerLike;
2734
+ }
2735
+ /**
2736
+ * Load a peer dependency, or fail with a message that says what to install.
2737
+ *
2738
+ * The error is the point. A bare `Cannot find module 'express'` reaches a consumer who did not
2739
+ * write the import and cannot tell whether the package is broken or a step is missing.
2740
+ */
2741
+ declare function loadPeer<T>(load: () => Promise<unknown>, onMissing: () => never): Promise<T>;
2742
+ /**
2743
+ * Middleware that captures the RAW request body before anything parses it.
2744
+ *
2745
+ * Every provider signs the exact bytes, so a body that was parsed and re-serialised hashes
2746
+ * differently and fails verification for a correct request. The bytes are attached as `rawBody`.
2747
+ *
2748
+ * A body larger than `maxBytes` is refused before it is held. `maxBytes` defaults to
2749
+ * {@link DEFAULT_WEBHOOK_MAX_BYTES} (1 MiB); pass `Number.POSITIVE_INFINITY` for no limit. The rest
2750
+ * of the stream is read and dropped, and once it ends the middleware answers 413 with the JSON body
2751
+ * `{ "error": "request body too large" }` itself; `next` is not called. The capture runs before
2752
+ * signature verification, so without a limit any client could stream a body until the heap runs out.
2753
+ * The refusal is answered here rather than handed to `next` as an error because Express's final
2754
+ * handler writes an error as an HTML page carrying its stack whenever `NODE_ENV` is not
2755
+ * `production`, and these routes answer anyone.
2756
+ *
2757
+ * The middleware settles once: after a refusal, more data, the end of the stream or a stream
2758
+ * error do nothing, and after a stream error the end of the stream does nothing.
2759
+ *
2760
+ * @param tag the package name for the diagnostic, so a reader knows which router is complaining
2761
+ * @param options `maxBytes`, the largest body accepted; 1 MiB when absent, `Infinity` for no limit
2762
+ * @throws RangeError when `maxBytes` is NaN or negative
2763
+ */
2764
+ declare function rawBodyCapture(tag: string, options?: RawBodyCaptureOptions): (rawReq: unknown, rawRes: unknown, next: (err?: unknown) => void) => void;
2765
+ /** The body size {@link rawBodyCapture} accepts when `maxBytes` is not given: 1 MiB. */
2766
+ declare const DEFAULT_WEBHOOK_MAX_BYTES: number;
2767
+ /** Options for {@link rawBodyCapture}. */
2768
+ interface RawBodyCaptureOptions {
2769
+ /** The largest body accepted, in bytes. A larger one is refused with 413. Defaults to
2770
+ * {@link DEFAULT_WEBHOOK_MAX_BYTES}; `Number.POSITIVE_INFINITY` removes the limit. */
2771
+ readonly maxBytes?: number;
2772
+ }
2773
+ /**
2774
+ * The start/stop pair, with the latches that make a restart a restart.
2775
+ *
2776
+ * Both flags used to be write-once, in both packages. After a `stop()`, `start()` hit `if (started)`
2777
+ * and returned without creating a listener — the server was silently dead — and the next `stop()`
2778
+ * was a no-op for the same reason, in the other direction. Anything that restarts a gateway hit it:
2779
+ * a config reload, a reconnect after a network fault, a supervisor cycling a process in-band.
2780
+ *
2781
+ * `injected` is for the case where the caller owns the app: there is no listener to open or close,
2782
+ * and `start()`/`stop()` must still be callable and idempotent.
2783
+ *
2784
+ * `start()` rejects with the error the bind failed with (`EADDRINUSE` for a port another listener
2785
+ * holds), under Express 4 and 5 alike, and a later `start()` tries again.
2786
+ */
2787
+ declare function listenerLifecycle(opts: {
2788
+ readonly app: ListenableApp;
2789
+ readonly port: number;
2790
+ readonly injected: boolean;
2791
+ }): {
2792
+ start(): Promise<void>;
2793
+ stop(): Promise<void>;
2794
+ };
2795
+
2796
+ /**
2797
+ * `createWebhookHandler` — one Fetch `Request` to `Response` handler for every webhook channel.
2798
+ *
2799
+ * It routes by platform, caps the body, and answers with the descriptor's `handle`, or runs verify,
2800
+ * JSON.parse and ingest. No secret, header value or body reaches `onError` or a response.
2801
+ */
2802
+
2803
+ /** Options for `createWebhookHandler`. */
2804
+ interface WebhookHandlerOptions {
2805
+ /** The built channels; only those with `transport: "webhook"` are routed. */
2806
+ readonly channels: ReadonlyArray<BuiltChannel>;
2807
+ /** Whether the platform's runner has started; a platform that has not answers 503. */
2808
+ readonly isStarted: (platform: PlatformName) => boolean;
2809
+ /** Body cap in bytes. Default 1 MiB. */
2810
+ readonly maxBodyBytes?: number;
2811
+ /** Default: the last path segment after `/webhooks/`. */
2812
+ readonly platformFor?: (url: URL) => PlatformName | undefined;
2813
+ /** Called when a handle/ingest throws; the response is 500 with no body. */
2814
+ readonly onError?: (platform: PlatformName, error: unknown) => void;
2815
+ }
2816
+ /**
2817
+ * Build a Fetch handler for every `transport: "webhook"` channel in `channels`: 404 for an unknown
2818
+ * platform, 503 while it has not started, 405 for a method the route does not take, 413 past the
2819
+ * body cap, 400 for an unreadable body, and 500 with no body when a route throws.
2820
+ */
2821
+ declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
2822
+
2823
+ /** Text encoding of a digest as sent in a webhook header. */
2824
+ type DigestEncoding = "hex" | "base64" | "base64url";
2825
+ /** Constant-time string compare; false (never a throw) on length mismatch or an empty side. */
2826
+ declare function safeEqualString(expected: string, received: string): boolean;
2827
+ /** Options for {@link verifyHmac}. */
2828
+ interface VerifyHmacOptions {
2829
+ readonly algorithm: "sha256" | "sha1";
2830
+ /** One secret, or several to accept during rotation. An empty secret throws RangeError. */
2831
+ readonly secrets: string | readonly string[];
2832
+ readonly message: string | Uint8Array;
2833
+ /** The header value as received; `undefined` or "" fails. */
2834
+ readonly signature: string | undefined;
2835
+ readonly encoding: DigestEncoding;
2836
+ /** Stripped before compare, e.g. "sha256=". A header without it fails. */
2837
+ readonly prefix?: string;
2838
+ /** Hex compare ignores case when true. Default false. */
2839
+ readonly caseInsensitive?: boolean;
2840
+ }
2841
+ /** Verify an HMAC webhook signature in constant time, accepting any of the given secrets. */
2842
+ declare function verifyHmac(opts: VerifyHmacOptions): boolean;
2843
+ /** Plain digest (no key), for platforms that hash secret+fields: zalo, wechat, wecom. */
2844
+ declare function verifyDigest(opts: {
2845
+ algorithm: "sha256" | "sha1";
2846
+ message: string;
2847
+ signature: string | undefined;
2848
+ encoding: DigestEncoding;
2849
+ prefix?: string;
2850
+ }): boolean;
2851
+
2852
+ export { type AccessPolicyMessages, type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelConfigInput, type ChannelConfigReaders, type ChannelDeps, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type CredentialStore, DEFAULT_WEBHOOK_MAX_BYTES, type DecodedJwt, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DigestEncoding, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type EnvOptions, type FeishuLarkMessageEvent, type FenceRegion, type FetchedToken, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type GroupActivationMode, type GroupActivationOptions, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type JsonRpcChild, JsonRpcLineClient, type JwksKeySet, type JwksKeySetOptions, type JwksLookup, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, ReconnectBackoff, type ReconnectBackoffOptions, type ReconnectPolicy, type ReportDiagnosticOptions, type RpcNotification, type RpcOutcome, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendError, type SendErrorCode, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type SplitKeepingRowsOptions, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TokenCache, type TokenCacheOptions, type TwitchMessageEvent, type UncoveredShape, type VerifyHmacOptions, type VerifyJwtResult, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createTokenCache, createWebhookHandler, decodeJwt, defaultStrategy, groupActivationHook, helpText, isAuthenticatedSender, jwksKeySet, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, refuseUnsupportedAttachments, reportDiagnostic, safeEqualString, scanFences, scopedStrategy, selectVariant, sendErrorFromHttp, senderKey, splitKeepingRows, statusForDeliver, toDialect, verifyDigest, verifyHmac, verifyRs256Jwt, withMediaUnderstanding };