@theokit/gateway 0.11.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,224 @@
1
+ /**
2
+ * The event variants of the platforms added in S-003: batch 1 (B-354 to B-358) and batch 2 (B-359
3
+ * to B-363).
4
+ *
5
+ * They live beside `message-event.ts` rather than in it to keep that file, which holds the registry
6
+ * and its guard, within the 500-line budget. `message-event.ts` files each of them under its key
7
+ * in `PlatformEventRegistry`; the package barrel exports them.
8
+ */
9
+
10
+ /** Signal-specific event variant (B-354), received from `signal-cli jsonRpc`. */
11
+ interface SignalMessageEvent extends BaseMessageEvent {
12
+ readonly platform: "signal";
13
+ readonly signal: {
14
+ /** Envelope timestamp (ms since epoch); Signal's own message id. */
15
+ readonly timestamp: number;
16
+ /** Sender's phone number, when signal-cli knows it. */
17
+ readonly sourceNumber?: string;
18
+ /** Sender's account UUID, when signal-cli knows it. */
19
+ readonly sourceUuid?: string;
20
+ /** Group id, present only for a group message. */
21
+ readonly groupId?: string;
22
+ /** Raw signal-cli envelope — escape hatch. */
23
+ readonly raw: unknown;
24
+ };
25
+ }
26
+ /** iMessage-specific event variant (B-355), received from `imsg rpc` on a signed-in Mac. */
27
+ interface IMessageMessageEvent extends BaseMessageEvent {
28
+ readonly platform: "imessage";
29
+ readonly imessage: {
30
+ /** `imsg`'s numeric chat id; the send target for a reply. */
31
+ readonly chatId: number;
32
+ /** Messages' own message GUID. */
33
+ readonly guid: string;
34
+ /** `imsg`'s `is_group` for the chat; agrees with `channel.type === "group"`. */
35
+ readonly isGroup: boolean;
36
+ /** Participant handles (phone numbers or emails) as `imsg` reports them for the chat. */
37
+ readonly participants: readonly string[];
38
+ /** Raw `imsg` notification payload — escape hatch. */
39
+ readonly raw: unknown;
40
+ };
41
+ }
42
+ /** Google Chat-specific event variant (B-356), posted to the Chat app's HTTPS endpoint. */
43
+ interface GoogleChatMessageEvent extends BaseMessageEvent {
44
+ readonly platform: "google_chat";
45
+ readonly google_chat: {
46
+ /** The message's resource name, `spaces/<space>/messages/<message>`. */
47
+ readonly messageName: string;
48
+ /** The space's resource name, `spaces/<space>`; the send target for a reply. */
49
+ readonly spaceName: string;
50
+ /** The space's `spaceType` (`SPACE`, `GROUP_CHAT` or `DIRECT_MESSAGE`), when Chat sent one. */
51
+ readonly spaceType?: string;
52
+ /** The thread's resource name, when the message is in a thread. */
53
+ readonly threadName?: string;
54
+ /** Raw Chat event — escape hatch. */
55
+ readonly raw: unknown;
56
+ };
57
+ }
58
+ /** IRC-specific event variant (B-357), read from a PRIVMSG on the adapter's own connection. */
59
+ interface IrcMessageEvent extends BaseMessageEvent {
60
+ readonly platform: "irc";
61
+ readonly irc: {
62
+ /** Where the PRIVMSG was addressed: a channel, `#name`, or the adapter's own nick for a DM. */
63
+ readonly target: string;
64
+ /** The sender's nick, from the line's prefix. */
65
+ readonly nick: string;
66
+ /** True for a CTCP ACTION (`/me`); `text` then holds the action without its CTCP framing. */
67
+ readonly action: boolean;
68
+ /** The line's IRCv3 message tags, unescaped; empty when the server sent none. */
69
+ readonly tags: Readonly<Record<string, string>>;
70
+ /** The raw line as the server sent it, without CRLF — escape hatch. */
71
+ readonly raw: string;
72
+ };
73
+ }
74
+ /**
75
+ * Nextcloud Talk event variant (B-358), read from a bot webhook `Create` activity that carried a
76
+ * signature the adapter verified.
77
+ */
78
+ interface NextcloudTalkMessageEvent extends BaseMessageEvent {
79
+ readonly platform: "nextcloud_talk";
80
+ readonly nextcloud_talk: {
81
+ /** The conversation's token, the `target.id` of the activity; a reply goes to it. */
82
+ readonly roomToken: string;
83
+ /** Talk's id for the message, the activity's `object.id`. */
84
+ readonly messageId: string;
85
+ /** Who wrote it, as Talk names actors: `users/<id>`, `guests/<id>`, `bots/<id>`… */
86
+ readonly actorId: string;
87
+ /** The id of the message this one answers, when it is a reply. */
88
+ readonly replyToId?: string;
89
+ /** The parsed webhook body — escape hatch. */
90
+ readonly raw: unknown;
91
+ };
92
+ }
93
+ /** Nostr event variant (B-359): a NIP-17 direct message (kind 14) or a NIP-04 one (kind 4). */
94
+ interface NostrMessageEvent extends BaseMessageEvent {
95
+ readonly platform: "nostr";
96
+ readonly nostr: {
97
+ /** The sender's public key, 64 lowercase hex characters; the send target for a reply. */
98
+ readonly pubkey: string;
99
+ /** 14 for a NIP-17 rumor unwrapped from a gift wrap, 4 for a NIP-04 encrypted message. */
100
+ readonly kind: 4 | 14;
101
+ /** The message's `created_at` in Unix seconds, as its sender stated it. */
102
+ readonly createdAt: number;
103
+ /** The decrypted rumor or kind 4 event — escape hatch. */
104
+ readonly raw: unknown;
105
+ };
106
+ }
107
+ /** Feishu/Lark event variant (B-360), an `im.message.receive_v1` event from the long connection. */
108
+ interface FeishuLarkMessageEvent extends BaseMessageEvent {
109
+ readonly platform: "feishu_lark";
110
+ readonly feishu_lark: {
111
+ /** The chat's `chat_id`; the send target for a reply. */
112
+ readonly chatId: string;
113
+ /** The message's `message_id`. */
114
+ readonly messageId: string;
115
+ /** The sender's `open_id`. */
116
+ readonly openId: string;
117
+ /** The event's `event_id`, which a redelivery repeats. */
118
+ readonly eventId: string;
119
+ /** Raw event — escape hatch. */
120
+ readonly raw: unknown;
121
+ };
122
+ }
123
+ /** Synology Chat event variant (B-361), an outgoing bot callback from the NAS. */
124
+ interface SynologyChatMessageEvent extends BaseMessageEvent {
125
+ readonly platform: "synology_chat";
126
+ readonly synology_chat: {
127
+ /** The sender's numeric user id; a reply goes to `user_ids: [userId]`. */
128
+ readonly userId: number;
129
+ /** The sender's user name. */
130
+ readonly username: string;
131
+ /** The callback's `post_id`. */
132
+ readonly postId: string;
133
+ /** The callback's `timestamp`. */
134
+ readonly timestamp: number;
135
+ /** The parsed callback body — escape hatch. */
136
+ readonly raw: unknown;
137
+ };
138
+ }
139
+ /** Tlon event variant (B-362), a DM read from the ship's `chat` app at `/v3`. */
140
+ interface TlonUrbitMessageEvent extends BaseMessageEvent {
141
+ readonly platform: "tlon_urbit";
142
+ readonly tlon_urbit: {
143
+ /** The sender's ship, `~name`; the send target for a reply. */
144
+ readonly ship: string;
145
+ /** The message id, `<ship>/<@ud>`. */
146
+ readonly messageId: string;
147
+ /** The essay's `sent` time in Unix milliseconds. */
148
+ readonly sent: number;
149
+ /** The `/v3` event — escape hatch. */
150
+ readonly raw: unknown;
151
+ };
152
+ }
153
+ /** Buzz event variant (B-367), a `message.created` realtime event. */
154
+ interface BuzzMessageEvent extends BaseMessageEvent {
155
+ readonly platform: "buzz";
156
+ readonly buzz: {
157
+ /** The message's id. */
158
+ readonly messageId: string;
159
+ /** The channel the message was posted in; for a DM, the DM channel id. */
160
+ readonly channelId: string;
161
+ /** The workspace the event belongs to, when the event names one. */
162
+ readonly workspaceId: string;
163
+ /** The parent message id when the message is a thread reply, else `""`. */
164
+ readonly threadId: string;
165
+ /** The realtime cursor of the event, `""` when absent. */
166
+ readonly cursor: string;
167
+ /** The event object — escape hatch. */
168
+ readonly raw: unknown;
169
+ };
170
+ }
171
+ /** ClickClack event variant (B-366), a `message.created` realtime event. */
172
+ interface ClickClackMessageEvent extends BaseMessageEvent {
173
+ readonly platform: "clickclack";
174
+ readonly clickclack: {
175
+ /** The message's id. */
176
+ readonly messageId: string;
177
+ /** The channel the message was posted in; for a DM, the DM channel id. */
178
+ readonly channelId: string;
179
+ /** The workspace the event belongs to, when the event names one. */
180
+ readonly workspaceId: string;
181
+ /** The parent message id when the message is a thread reply, else `""`. */
182
+ readonly threadId: string;
183
+ /** The realtime cursor of the event, `""` when absent. */
184
+ readonly cursor: string;
185
+ /** The event object — escape hatch. */
186
+ readonly raw: unknown;
187
+ };
188
+ }
189
+ /** Zalo Personal event variant (B-365), a message read from a personal Zalo account's listener. */
190
+ interface ZaloPersonalMessageEvent extends BaseMessageEvent {
191
+ readonly platform: "zalo_personal";
192
+ readonly zalo_personal: {
193
+ /** The message's `msgId`. */
194
+ readonly messageId: string;
195
+ /** The conversation's id: the peer's uid for a direct chat, the group id for a group. */
196
+ readonly threadId: string;
197
+ /** `"user"` for a direct chat, `"group"` for a group. */
198
+ readonly threadType: "user" | "group";
199
+ /** The sender's uid. */
200
+ readonly senderUid: string;
201
+ /** The listener's message object — escape hatch. */
202
+ readonly raw: unknown;
203
+ };
204
+ }
205
+ /** Twitch event variant (B-363), a `channel.chat.message` EventSub notification. */
206
+ interface TwitchMessageEvent extends BaseMessageEvent {
207
+ readonly platform: "twitch";
208
+ readonly twitch: {
209
+ /** The channel's broadcaster user id; the send target for a reply. */
210
+ readonly broadcasterUserId: string;
211
+ /** The chatter's user id. */
212
+ readonly chatterUserId: string;
213
+ /** The chatter's login name. */
214
+ readonly chatterLogin: string;
215
+ /** The chat message's `message_id`. */
216
+ readonly messageId: string;
217
+ /** The notification's `event` object — escape hatch. */
218
+ readonly raw: unknown;
219
+ };
220
+ }
221
+
1
222
  /**
2
223
  * `MessageEvent` — canonical inbound shape every adapter emits (T1.1, ADR D173).
3
224
  *
@@ -23,6 +244,21 @@
23
244
  *
24
245
  * @public
25
246
  */
247
+
248
+ /**
249
+ * The audio of a voice note an inbound message carries (B-715): its bytes, their media type and
250
+ * the length the platform reported.
251
+ *
252
+ * The bytes travel by reference, as an outbound attachment's do: hooks and the handler see the
253
+ * same array.
254
+ */
255
+ interface InboundAudio {
256
+ readonly data: Uint8Array;
257
+ /** The media type of `data`, such as `audio/ogg`. */
258
+ readonly mediaType: string;
259
+ /** The length in whole seconds the platform reported; 0 when it reported none. */
260
+ readonly durationSeconds: number;
261
+ }
26
262
  /** Fields common to every platform's inbound event. */
27
263
  interface BaseMessageEvent {
28
264
  /** Stable id used as a session-key segment and for dedup. */
@@ -55,6 +291,11 @@ interface BaseMessageEvent {
55
291
  readonly receivedAt: number;
56
292
  /** Optional reply-target message id. */
57
293
  readonly replyTo?: string;
294
+ /**
295
+ * The voice note's audio, when the adapter read one (B-715). Absent for a message with no voice,
296
+ * and for a voice the adapter could not read.
297
+ */
298
+ readonly audio?: InboundAudio;
58
299
  }
59
300
  /** Telegram-specific event variant. */
60
301
  interface TelegramMessageEvent extends BaseMessageEvent {
@@ -262,7 +503,7 @@ interface MatrixMessageEvent extends BaseMessageEvent {
262
503
  * ```typescript
263
504
  * declare module "@theokit/gateway" {
264
505
  * interface PlatformEventRegistry {
265
- * signal: SignalMessageEvent;
506
+ * acmechat: AcmeChatMessageEvent;
266
507
  * }
267
508
  * }
268
509
  * ```
@@ -280,6 +521,19 @@ interface PlatformEventRegistry {
280
521
  mattermost: MattermostMessageEvent;
281
522
  line: LineMessageEvent;
282
523
  matrix: MatrixMessageEvent;
524
+ signal: SignalMessageEvent;
525
+ imessage: IMessageMessageEvent;
526
+ google_chat: GoogleChatMessageEvent;
527
+ irc: IrcMessageEvent;
528
+ nextcloud_talk: NextcloudTalkMessageEvent;
529
+ nostr: NostrMessageEvent;
530
+ feishu_lark: FeishuLarkMessageEvent;
531
+ synology_chat: SynologyChatMessageEvent;
532
+ tlon_urbit: TlonUrbitMessageEvent;
533
+ twitch: TwitchMessageEvent;
534
+ zalo_personal: ZaloPersonalMessageEvent;
535
+ clickclack: ClickClackMessageEvent;
536
+ buzz: BuzzMessageEvent;
283
537
  }
284
538
  /**
285
539
  * `true` only for `any` — the one type that would otherwise swallow the union.
@@ -309,7 +563,7 @@ type LiteralKey<K> = string extends K ? never : K;
309
563
  * `TS2339: Property 'telegram' does not exist on type 'never'`.
310
564
  *
311
565
  * It also fixes a second measured defect for free. Mapping over `keyof` directly is HOMOMORPHIC, so
312
- * an OPTIONAL entry (`signal?: Event`, a shape an author writes by accident) kept its modifier and
566
+ * an OPTIONAL entry (`acmechat?: Event`, a shape an author writes by accident) kept its modifier and
313
567
  * injected `undefined` into the union — `TS18048: 'e' is possibly 'undefined'` on a plain `switch`.
314
568
  * Mapping over a computed key set is not homomorphic and drops the modifier. A `-?` was written
315
569
  * here first as an explicit belt; the gate showed it could not be made to matter while this type is
@@ -332,11 +586,11 @@ type LiteralKeysOf<R> = keyof {
332
586
  * earlier version of this docblock said it was — measured false twice over. Filtering the VALUE
333
587
  * alone left two shapes that break every consumer rather than only their author:
334
588
  * `{ [key: string]: … }` made `keyof` yield `string | number`, so the union and the platform name
335
- * both collapsed to `never`; and `signal?: …` kept its optional modifier through a homomorphic
589
+ * both collapsed to `never`; and `acmechat?: …` kept its optional modifier through a homomorphic
336
590
  * mapping and injected `undefined` into the union. Both are handled above — the first by
337
591
  * {@link LiteralKeysOf}, the second by the `-?` on the mapping. What remains true, and is the
338
592
  * honest version of the original claim:
339
- * a `Record<PlatformName, T>` written against the ten still fails to compile, because the rejected
593
+ * a `Record<PlatformName, T>` written against the first-party platforms still fails to compile, because the rejected
340
594
  * key is gone from `PlatformName` while the consumer's literal map is not. What the exclusion buys
341
595
  * is that the failure is a missing-key error at the consumer's own map rather than a silent loss
342
596
  * of narrowing everywhere.
@@ -386,6 +640,32 @@ type PlatformName = MessageEvent["platform"];
386
640
  * (`TelegramAdapter`, `DiscordAdapter`, ...).
387
641
  */
388
642
 
643
+ /**
644
+ * An image an outbound message carries: its bytes and their media type (B-674).
645
+ *
646
+ * The bytes travel by reference: the runner does not copy them on the way to the adapter. The
647
+ * caller must not change `data` or the list until the send's promise settles: an adapter that
648
+ * sends several attachments reads each one only when its turn comes.
649
+ */
650
+ interface OutboundImageAttachment {
651
+ readonly kind: "image";
652
+ /** The media type of `data`, such as `image/png`. */
653
+ readonly mediaType: string;
654
+ readonly data: Uint8Array;
655
+ /** A file name the platform may show; optional. */
656
+ readonly filename?: string;
657
+ }
658
+ /** An audio clip an outbound message carries, such as a spoken reply (B-715). Same rules as an image. */
659
+ interface OutboundAudioAttachment {
660
+ readonly kind: "audio";
661
+ /** The media type of `data`, such as `audio/ogg`. */
662
+ readonly mediaType: string;
663
+ readonly data: Uint8Array;
664
+ /** A file name the platform may show; optional. */
665
+ readonly filename?: string;
666
+ }
667
+ /** An attachment an outbound message carries, told apart by `kind`. */
668
+ type OutboundAttachment = OutboundImageAttachment | OutboundAudioAttachment;
389
669
  /** Outbound message shape — what `sendMessage` accepts. */
390
670
  interface OutboundMessage {
391
671
  readonly channel: {
@@ -398,6 +678,11 @@ interface OutboundMessage {
398
678
  readonly format?: "plain" | "markdown" | "html";
399
679
  /** Optional reply target. */
400
680
  readonly replyTo?: string;
681
+ /**
682
+ * Images to send with the text. An adapter whose {@link BasePlatformAdapter.supportsAttachments}
683
+ * is `false` refuses a non-empty list with `attachments_unsupported`; it never drops it.
684
+ */
685
+ readonly attachments?: ReadonlyArray<OutboundAttachment>;
401
686
  }
402
687
  /** Send result — adapters return this instead of throwing on platform errors. */
403
688
  interface SendResult {
@@ -412,7 +697,8 @@ interface SendResult {
412
697
  * Abstract base for all platform adapters.
413
698
  *
414
699
  * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.
415
- * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden.
700
+ * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden; `editMessage` refuses
701
+ * with `edit_unsupported` unless overridden.
416
702
  *
417
703
  * **Contract:**
418
704
  * - `connect()` is idempotent. Calling twice returns true the second time.
@@ -421,7 +707,22 @@ interface SendResult {
421
707
  * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.
422
708
  * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling
423
709
  * `onInbound` twice replaces the previous handler — does NOT stack.
424
- * - `sendMessage` with empty text returns `{ ok: false, code: "empty_text" }`.
710
+ * - `sendMessage` with empty text and no attachments returns `{ ok: false, code: "empty_text" }`.
711
+ * An adapter that refuses attachments answers `attachments_unsupported` first, and one that
712
+ * sends them (Telegram) accepts empty text with an image.
713
+ * - `supportsEdit` says whether the adapter has an edit call. It is `false` unless the adapter
714
+ * overrides it, and it MUST NOT change with `connect()`. `true` does not promise that every
715
+ * edit is accepted: an adapter whose injected client lacks the edit call (Matrix) still answers
716
+ * `edit_unsupported`, which a caller handles like any other refusal.
717
+ * - `editMessage` returns a `SendResult` and never throws on platform errors. The default refuses
718
+ * with `edit_unsupported` and makes no platform call.
719
+ * - `supportsAttachments` says whether `sendMessage` can send `out.attachments`. It is `false`
720
+ * unless the adapter overrides it, and it MUST NOT change with `connect()`. An adapter that
721
+ * does not support them refuses a non-empty list with `attachments_unsupported` and makes no
722
+ * platform call; an edit carrying an attachment is refused the same way.
723
+ * - Edits are not ordered by the adapter. Two edits of one message id in flight at once reach the
724
+ * platform in either order, so a caller awaits each edit before the next, or keeps one in flight
725
+ * and coalesces to the latest text.
425
726
  *
426
727
  * @public
427
728
  */
@@ -442,8 +743,8 @@ declare abstract class BasePlatformAdapter {
442
743
  * process nor the connection. Two adapters used to discard the rejection with `void`, which under
443
744
  * Node's default ends the process, and two more reported it as a platform-client error, sending
444
745
  * whoever debugged their own handler to the wrong repository. Eight had converged on the right
445
- * behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds all
446
- * ten to it.
746
+ * behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds every
747
+ * adapter to it.
447
748
  */
448
749
  abstract onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
449
750
  /**
@@ -476,6 +777,35 @@ declare abstract class BasePlatformAdapter {
476
777
  * is taken from `this.platform`, which is the only part that differed between them.
477
778
  */
478
779
  protected runHandler(handler: ((event: MessageEvent) => Promise<void>) | undefined, event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
780
+ /**
781
+ * Whether {@link editMessage} can replace the text of a message this adapter sent.
782
+ *
783
+ * Read it before starting a preview: on `false`, send the final text instead. An adapter sets
784
+ * it at construction and MUST NOT change it with `connect()`. Annotated as `boolean` so that an
785
+ * edit-capable adapter can override it with `true`.
786
+ */
787
+ readonly supportsEdit: boolean;
788
+ /**
789
+ * Whether {@link sendMessage} can send the images of `out.attachments` (B-674).
790
+ *
791
+ * Read it before attaching: on `false`, the adapter refuses a non-empty list with
792
+ * `attachments_unsupported`. Set at construction, never changed by `connect()`. Annotated as
793
+ * `boolean` so that an adapter that sends images can override it with `true`.
794
+ */
795
+ readonly supportsAttachments: boolean;
796
+ /**
797
+ * Replace the text of a message this adapter sent, keeping its id.
798
+ *
799
+ * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
800
+ * throws on platform errors. An edit-capable adapter applies, with no request, the same local
801
+ * checks its `sendMessage` applies (such as `empty_text`, and `not_connected` where the send
802
+ * checks the connection), plus `invalid_message_id`, and `edit_too_long` where the adapter
803
+ * splits text: an edit that would need more than one platform message is refused, never split.
804
+ *
805
+ * Default: refuses with `edit_unsupported`, makes no platform call, and checks nothing else
806
+ * first, so capability is answered before input.
807
+ */
808
+ editMessage(_messageId: string, _out: OutboundMessage): Promise<SendResult>;
479
809
  /** Lifecycle: emit a typing indicator. Default: noop. */
480
810
  startTyping(_channelId: string): Promise<void>;
481
811
  /** Lifecycle: stop the typing indicator. Default: noop. */
@@ -614,9 +944,16 @@ interface ChannelRejection {
614
944
  readonly platform: PlatformName;
615
945
  readonly error: GatewayConfigurationError;
616
946
  }
947
+ /** A built adapter paired with the descriptor that built it, so a consumer need not re-pair them. */
948
+ interface BuiltChannel {
949
+ readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;
950
+ readonly adapter: BasePlatformAdapter;
951
+ }
617
952
  /** What `createChannels` built and what it refused. */
618
953
  interface CreateChannelsResult {
619
954
  readonly adapters: BasePlatformAdapter[];
955
+ /** The same adapters, in the same order, each paired with its descriptor. */
956
+ readonly channels: BuiltChannel[];
620
957
  readonly rejected: ChannelRejection[];
621
958
  }
622
959
  /**
@@ -627,6 +964,16 @@ interface CreateChannelsResult {
627
964
  * missing key, and its `create` is never called. A `GatewayConfigurationError` thrown by `create`
628
965
  * is reported the same way. Any other throw is a defect, not a configuration fault, and propagates.
629
966
  *
967
+ * Only one adapter per platform is built, because the runner routes replies and `stop()` by
968
+ * platform. The first entry built for a platform wins; a later entry for that platform is rejected
969
+ * with a `GatewayConfigurationError` coded `duplicate_channel`, before its required fields are
970
+ * checked, and its `create` is never called. An entry rejected for its configuration built
971
+ * nothing, so it does not claim its platform.
972
+ *
973
+ * The runner keys adapters by the adapter's own `platform`, so an adapter must report the platform
974
+ * its descriptor declares. One that reports another is discarded unconnected and its entry is
975
+ * rejected with a `GatewayConfigurationError` coded `platform_mismatch`; it claims no platform.
976
+ *
630
977
  * @public
631
978
  */
632
979
  declare function createChannels(entries: ReadonlyArray<ChannelEntry>): CreateChannelsResult;
@@ -656,6 +1003,8 @@ interface DeliveryRequest extends DeliveryTarget {
656
1003
  readonly text: string;
657
1004
  readonly format?: "plain" | "markdown" | "html";
658
1005
  readonly replyTo?: string;
1006
+ /** Images to send with the text; an empty list is left out (B-674). */
1007
+ readonly attachments?: ReadonlyArray<OutboundAttachment>;
659
1008
  }
660
1009
  /**
661
1010
  * Routes outbound requests to the correct adapter.
@@ -664,6 +1013,8 @@ interface DeliveryRequest extends DeliveryTarget {
664
1013
  * - `register` is last-writer-wins by platform.
665
1014
  * - `send` with unknown platform returns `{ ok: false, code: "no_adapter" }`.
666
1015
  * - `send` never throws on platform errors (delegates to adapter's SendResult).
1016
+ * - `send` with attachments refuses with `attachments_unsupported`, calling no `sendMessage`, when
1017
+ * the adapter does not declare `supportsAttachments`.
667
1018
  *
668
1019
  * @public
669
1020
  */
@@ -820,6 +1171,8 @@ interface GatewayContext {
820
1171
  /** Send a reply to the originating channel (auto-routed by `event.platform`). */
821
1172
  reply(text: string, opts?: {
822
1173
  format?: "plain" | "markdown" | "html";
1174
+ /** Images to send with the text; an empty list is left out (B-674). */
1175
+ attachments?: ReadonlyArray<OutboundAttachment>;
823
1176
  }): Promise<SendResult>;
824
1177
  /** The triggering event. */
825
1178
  readonly event: MessageEvent;
@@ -881,13 +1234,14 @@ interface StartResult {
881
1234
  */
882
1235
  declare class GatewayRunner {
883
1236
  private readonly opts;
884
- private readonly adaptersByPlatform;
885
1237
  private readonly hookExecutor;
886
1238
  private readonly inflight;
887
1239
  private readonly unsubs;
888
1240
  /** Slash command registry: name → handler (word-boundary match, EC-A). */
889
1241
  private readonly commands;
890
1242
  private startResult;
1243
+ /** The start that has not settled yet, shared by every overlapping `start()` call. */
1244
+ private startInFlight;
891
1245
  private stopped;
892
1246
  constructor(opts: GatewayRunnerOptions);
893
1247
  /**
@@ -903,13 +1257,32 @@ declare class GatewayRunner {
903
1257
  * Resolves with what connected. A second call after the first resolved returns the same result
904
1258
  * without connecting again.
905
1259
  *
1260
+ * Overlapping calls share one start; a start overtaken by stop resolves with no adapter connected.
1261
+ * A call made before `stop()` while another is still connecting connects nothing and settles
1262
+ * with it; a call made after `stop()` throws `runner_stopped`. When `stop()` runs before the
1263
+ * connect settles, the adapters that connected are disconnected, no inbound dispatch is wired,
1264
+ * and the start resolves `{ connected: [], failed }`, keeping the `"isolate"` failures. Under
1265
+ * `"rollback"`, a connect that fails still rejects the start.
1266
+ *
1267
+ * Under `connectFailure: "rollback"`, every connect settles before the rollback, so a failing
1268
+ * start rejects only once its slowest connect settles, as a successful one resolves only then.
1269
+ *
1270
+ * An adapter whose `disconnect()` fails while a start rolls back, or while a start that `stop()`
1271
+ * overtook gives its adapters back, is named on stderr with the error redacted; how the start
1272
+ * settles does not change.
1273
+ *
906
1274
  * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
907
1275
  * stopped. A stopped runner is spent; construct a new one.
908
- * @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after the
909
- * adapters that did connect were disconnected.
1276
+ * @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after
1277
+ * every connect settled and the adapters that did connect were disconnected.
910
1278
  */
911
1279
  start(): Promise<StartResult>;
912
- /** All or nothing: one failure disconnects the adapters already open, then rethrows. */
1280
+ private runStart;
1281
+ /**
1282
+ * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
1283
+ * the first failure. Every connect settles before the rollback: rolling back while one is still
1284
+ * pending left that adapter live once it connected.
1285
+ */
913
1286
  private connectAllOrRollback;
914
1287
  /**
915
1288
  * Connect every adapter and keep the ones that connected. The `async` wrapper turns a
@@ -920,7 +1293,12 @@ declare class GatewayRunner {
920
1293
  private wireInbound;
921
1294
  /**
922
1295
  * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
923
- * then disconnects adapters. Idempotent (EC-E).
1296
+ * then disconnects adapters. Idempotent (EC-E). A disconnect that fails does not make `stop()`
1297
+ * reject and does not stop the other disconnects; it is written to stderr, redacted, naming the
1298
+ * platform.
1299
+ *
1300
+ * An adapter still connecting under an in-flight start is released when that start settles;
1301
+ * `stop()` does not wait for it.
924
1302
  */
925
1303
  stop(): Promise<void>;
926
1304
  /**
@@ -1056,7 +1434,7 @@ interface ChannelRendering {
1056
1434
  *
1057
1435
  * @param platform - the destination, typically `event.platform` of the inbound message
1058
1436
  * @returns the `{ translate, format }` pair for that platform
1059
- * @throws RangeError when `platform` is not one of the ten this package knows. Answering with
1437
+ * @throws RangeError when `platform` is not one of the platforms this package knows. Answering with
1060
1438
  * nothing would let the presenter fall back to identity and `markdown`, which is the defect this
1061
1439
  * function exists to remove.
1062
1440
  * @public
@@ -1125,6 +1503,14 @@ interface ChunkTextOptions {
1125
1503
  * (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.
1126
1504
  */
1127
1505
  readonly trimParts?: boolean;
1506
+ /**
1507
+ * When true, a cut that would fall inside a Markdown table row (a line whose first non-blank
1508
+ * character is `|`) moves back to the start of that row, provided the row fits in the window and
1509
+ * does not open the chunk; the row then opens the next chunk whole and byte-identical (B-556).
1510
+ * A row longer than the window is cut by length as before. Text with no table row splits exactly
1511
+ * as without the option. Default: `false`.
1512
+ */
1513
+ readonly keepTableRows?: boolean;
1128
1514
  }
1129
1515
  /**
1130
1516
  * Split `text` into chunks no longer than the configured window, preferring
@@ -1162,6 +1548,72 @@ declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions):
1162
1548
  */
1163
1549
  declare function toDialect(text: string, platform: string): string;
1164
1550
 
1551
+ /**
1552
+ * Fenced code block scanner (B-518).
1553
+ *
1554
+ * Reads the fences of CommonMark § 4.5: a line of at most three blanks, then three or more
1555
+ * backticks or tildes (an info string after a backtick run holds no backtick), closed by a line of
1556
+ * the same character, at least as many, and nothing after them but blanks. A fence never closed runs
1557
+ * to the end of the text. Fences inside a list item or block quote (indented four or more, or behind
1558
+ * a `>`) are not read.
1559
+ *
1560
+ * @public
1561
+ */
1562
+ /** One fenced code block, as offsets into the scanned text. */
1563
+ interface FenceRegion {
1564
+ /** Offset of the first character of the opening line. */
1565
+ readonly start: number;
1566
+ /** Offset just past the opening line, before its line ending. */
1567
+ readonly openerEnd: number;
1568
+ /** Offset of the first character after the opening line's line ending (the first code line). */
1569
+ readonly contentStart: number;
1570
+ /** Offset just past the last character of the closing line (its line ending excluded), or the text length when never closed. */
1571
+ readonly end: number;
1572
+ /** The opening line, byte for byte. */
1573
+ readonly opener: string;
1574
+ /** The marker run that closes the block: the opening run, without its indent. */
1575
+ readonly closer: string;
1576
+ /** False when the text ends before a closing line. */
1577
+ readonly closed: boolean;
1578
+ }
1579
+ /** Every fenced region of `text`, in order. */
1580
+ declare function scanFences(text: string): readonly FenceRegion[];
1581
+
1582
+ /**
1583
+ * A bounded set of ids, oldest evicted first, so a long-running process remembers what it delivered
1584
+ * without growing for ever (NFR-003).
1585
+ */
1586
+ /**
1587
+ * The ids an adapter has already delivered, at most `limit` of them.
1588
+ */
1589
+ declare class SeenIds {
1590
+ private readonly limit;
1591
+ private readonly ids;
1592
+ /** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
1593
+ constructor(limit?: number);
1594
+ /**
1595
+ * Record `id`.
1596
+ *
1597
+ * @returns `true` when the id was new, `false` when it was already held
1598
+ */
1599
+ add(id: string): boolean;
1600
+ /** Whether `id` is held. */
1601
+ has(id: string): boolean;
1602
+ /** How many ids are held. */
1603
+ get size(): number;
1604
+ }
1605
+
1606
+ /**
1607
+ * Grapheme-safe splitting of long text that keeps Markdown table rows whole (B-556).
1608
+ *
1609
+ * @internal
1610
+ */
1611
+ /**
1612
+ * Parts of at most `partLimit` units, cut at grapheme boundaries and before straddled rows.
1613
+ * Shared by the SMS and LINE splitters (text no longer than a part is theirs to handle).
1614
+ */
1615
+ declare function splitKeepingRows(text: string, partLimit: number): string[];
1616
+
1165
1617
  /**
1166
1618
  * The half of an Express webhook server that is the same for every platform.
1167
1619
  *
@@ -1179,7 +1631,7 @@ declare function toDialect(text: string, platform: string): string;
1179
1631
  *
1180
1632
  * The core had no HTTP concern, and `express` is a peer dependency of exactly the two packages that
1181
1633
  * duplicate this — so the obvious objection to putting it here is that it would impose express on
1182
- * all ten adapters.
1634
+ * every adapter.
1183
1635
  *
1184
1636
  * It does not, because nothing here imports express. Every shape below is structural: a request is
1185
1637
  * whatever has `readableEnded` and `on`, a listener is whatever has `listen` and `close`. The
@@ -1194,16 +1646,22 @@ declare function toDialect(text: string, platform: string): string;
1194
1646
  interface RawBodyRequest {
1195
1647
  readonly readableEnded?: boolean;
1196
1648
  readonly complete?: boolean;
1649
+ readonly headers?: Readonly<Record<string, string | string[] | undefined>>;
1197
1650
  setEncoding(encoding: string): unknown;
1198
1651
  on(event: string, listener: (arg: never) => void): unknown;
1199
1652
  }
1200
1653
  /** What a started listener must be able to do. `http.Server` satisfies it. */
1201
1654
  interface ListenerLike {
1202
1655
  close(cb?: (err?: Error) => void): unknown;
1656
+ /** Where Express 4's `listen` reports a failure to bind; `http.Server` has it. */
1657
+ once?(event: "error", listener: (err: Error) => void): unknown;
1203
1658
  }
1204
- /** What can start a listener. Express's app satisfies it. */
1659
+ /**
1660
+ * What can start a listener. Express's app satisfies it: Express 5 passes a failure to bind to the
1661
+ * callback, Express 4 only emits it on the returned server.
1662
+ */
1205
1663
  interface ListenableApp {
1206
- listen(port: number, cb: () => void): ListenerLike;
1664
+ listen(port: number, cb: (err?: Error) => void): ListenerLike;
1207
1665
  }
1208
1666
  /**
1209
1667
  * Load a peer dependency, or fail with a message that says what to install.
@@ -1218,9 +1676,27 @@ declare function loadPeer<T>(load: () => Promise<unknown>, onMissing: () => neve
1218
1676
  * Every provider signs the exact bytes, so a body that was parsed and re-serialised hashes
1219
1677
  * differently and fails verification for a correct request. The bytes are attached as `rawBody`.
1220
1678
  *
1679
+ * With `maxBytes`, a body larger than that many bytes is refused before it is held. The rest of
1680
+ * the stream is read and dropped, and once it ends the middleware answers 413 with the JSON body
1681
+ * `{ "error": "request body too large" }` itself; `next` is not called. A route that must stay
1682
+ * public (a provider dials in) sets it, or any client can stream a body until the heap runs out.
1683
+ * The refusal is answered here rather than handed to `next` as an error because Express's final
1684
+ * handler writes an error as an HTML page carrying its stack whenever `NODE_ENV` is not
1685
+ * `production`, and these routes answer anyone.
1686
+ *
1687
+ * The middleware settles once: after a refusal, more data, the end of the stream or a stream
1688
+ * error do nothing, and after a stream error the end of the stream does nothing.
1689
+ *
1221
1690
  * @param tag the package name for the diagnostic, so a reader knows which router is complaining
1691
+ * @param options `maxBytes`, the largest body accepted; no limit when absent
1692
+ * @throws RangeError when `maxBytes` is not a finite number of zero or more
1222
1693
  */
1223
- declare function rawBodyCapture(tag: string): (rawReq: unknown, _res: unknown, next: (err?: unknown) => void) => void;
1694
+ declare function rawBodyCapture(tag: string, options?: RawBodyCaptureOptions): (rawReq: unknown, rawRes: unknown, next: (err?: unknown) => void) => void;
1695
+ /** Options for {@link rawBodyCapture}. */
1696
+ interface RawBodyCaptureOptions {
1697
+ /** The largest body accepted, in bytes. A larger one is refused with 413. No limit when absent. */
1698
+ readonly maxBytes?: number;
1699
+ }
1224
1700
  /**
1225
1701
  * The start/stop pair, with the latches that make a restart a restart.
1226
1702
  *
@@ -1231,6 +1707,9 @@ declare function rawBodyCapture(tag: string): (rawReq: unknown, _res: unknown, n
1231
1707
  *
1232
1708
  * `injected` is for the case where the caller owns the app: there is no listener to open or close,
1233
1709
  * and `start()`/`stop()` must still be callable and idempotent.
1710
+ *
1711
+ * `start()` rejects with the error the bind failed with (`EADDRINUSE` for a port another listener
1712
+ * holds), under Express 4 and 5 alike, and a later `start()` tries again.
1234
1713
  */
1235
1714
  declare function listenerLifecycle(opts: {
1236
1715
  readonly app: ListenableApp;
@@ -1241,4 +1720,4 @@ declare function listenerLifecycle(opts: {
1241
1720
  stop(): Promise<void>;
1242
1721
  };
1243
1722
 
1244
- export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChunkByGraphemeOptions, type ChunkTextOptions, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type IngestResult, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type RawBodyRequest, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type StartResult, type TeamsMessageEvent, type TelegramMessageEvent, type UncoveredShape, type WebhookRequest, type WhatsAppMessageEvent, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets, toDialect };
1723
+ export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, type FeishuLarkMessageEvent, type FenceRegion, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type RawBodyCaptureOptions, type RawBodyRequest, type SMSMessageEvent, SeenIds, type SendResult, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TwitchMessageEvent, type UncoveredShape, type WebhookRequest, type WhatsAppMessageEvent, type ZaloPersonalMessageEvent, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, toDialect };