@theokit/gateway 0.12.0 → 0.15.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,314 @@
1
+ /**
2
+ * A bounded set of ids, oldest evicted first, so a long-running process remembers what it delivered
3
+ * without growing for ever (NFR-003).
4
+ */
5
+ /**
6
+ * The ids an adapter has already delivered, at most `limit` of them.
7
+ */
8
+ declare class SeenIds {
9
+ private readonly limit;
10
+ private readonly ids;
11
+ /** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
12
+ constructor(limit?: number);
13
+ /**
14
+ * Record `id`.
15
+ *
16
+ * @returns `true` when the id was new, `false` when it was already held
17
+ */
18
+ add(id: string): boolean;
19
+ /** Whether `id` is held. */
20
+ has(id: string): boolean;
21
+ /** How many ids are held. */
22
+ get size(): number;
23
+ }
24
+
25
+ /**
26
+ * The event variants of the platforms added in S-003: batch 1 (B-354 to B-358) and batch 2 (B-359
27
+ * to B-363).
28
+ *
29
+ * They live beside `message-event.ts` rather than in it to keep that file, which holds the registry
30
+ * and its guard, within the 500-line budget. `message-event.ts` files each of them under its key
31
+ * in `PlatformEventRegistry`; the package barrel exports them.
32
+ */
33
+
34
+ /** Signal-specific event variant (B-354), received from `signal-cli jsonRpc`. */
35
+ interface SignalMessageEvent extends BaseMessageEvent {
36
+ readonly platform: "signal";
37
+ readonly signal: {
38
+ /** Envelope timestamp (ms since epoch); Signal's own message id. */
39
+ readonly timestamp: number;
40
+ /** Sender's phone number, when signal-cli knows it. */
41
+ readonly sourceNumber?: string;
42
+ /** Sender's account UUID, when signal-cli knows it. */
43
+ readonly sourceUuid?: string;
44
+ /** Group id, present only for a group message. */
45
+ readonly groupId?: string;
46
+ /** Raw signal-cli envelope — escape hatch. */
47
+ readonly raw: unknown;
48
+ };
49
+ }
50
+ /** iMessage-specific event variant (B-355), received from `imsg rpc` on a signed-in Mac. */
51
+ interface IMessageMessageEvent extends BaseMessageEvent {
52
+ readonly platform: "imessage";
53
+ readonly imessage: {
54
+ /** `imsg`'s numeric chat id; the send target for a reply. */
55
+ readonly chatId: number;
56
+ /** Messages' own message GUID. */
57
+ readonly guid: string;
58
+ /** `imsg`'s `is_group` for the chat; agrees with `channel.type === "group"`. */
59
+ readonly isGroup: boolean;
60
+ /** Participant handles (phone numbers or emails) as `imsg` reports them for the chat. */
61
+ readonly participants: readonly string[];
62
+ /** Raw `imsg` notification payload — escape hatch. */
63
+ readonly raw: unknown;
64
+ };
65
+ }
66
+ /** Google Chat-specific event variant (B-356), posted to the Chat app's HTTPS endpoint. */
67
+ interface GoogleChatMessageEvent extends BaseMessageEvent {
68
+ readonly platform: "google_chat";
69
+ readonly google_chat: {
70
+ /** The message's resource name, `spaces/<space>/messages/<message>`. */
71
+ readonly messageName: string;
72
+ /** The space's resource name, `spaces/<space>`; the send target for a reply. */
73
+ readonly spaceName: string;
74
+ /** The space's `spaceType` (`SPACE`, `GROUP_CHAT` or `DIRECT_MESSAGE`), when Chat sent one. */
75
+ readonly spaceType?: string;
76
+ /** The thread's resource name, when the message is in a thread. */
77
+ readonly threadName?: string;
78
+ /** Raw Chat event — escape hatch. */
79
+ readonly raw: unknown;
80
+ };
81
+ }
82
+ /** IRC-specific event variant (B-357), read from a PRIVMSG on the adapter's own connection. */
83
+ interface IrcMessageEvent extends BaseMessageEvent {
84
+ readonly platform: "irc";
85
+ readonly irc: {
86
+ /** Where the PRIVMSG was addressed: a channel, `#name`, or the adapter's own nick for a DM. */
87
+ readonly target: string;
88
+ /** The sender's nick, from the line's prefix. */
89
+ readonly nick: string;
90
+ /** True for a CTCP ACTION (`/me`); `text` then holds the action without its CTCP framing. */
91
+ readonly action: boolean;
92
+ /** The line's IRCv3 message tags, unescaped; empty when the server sent none. */
93
+ readonly tags: Readonly<Record<string, string>>;
94
+ /** The raw line as the server sent it, without CRLF — escape hatch. */
95
+ readonly raw: string;
96
+ };
97
+ }
98
+ /**
99
+ * Nextcloud Talk event variant (B-358), read from a bot webhook `Create` activity that carried a
100
+ * signature the adapter verified.
101
+ */
102
+ interface NextcloudTalkMessageEvent extends BaseMessageEvent {
103
+ readonly platform: "nextcloud_talk";
104
+ readonly nextcloud_talk: {
105
+ /** The conversation's token, the `target.id` of the activity; a reply goes to it. */
106
+ readonly roomToken: string;
107
+ /** Talk's id for the message, the activity's `object.id`. */
108
+ readonly messageId: string;
109
+ /** Who wrote it, as Talk names actors: `users/<id>`, `guests/<id>`, `bots/<id>`… */
110
+ readonly actorId: string;
111
+ /** The id of the message this one answers, when it is a reply. */
112
+ readonly replyToId?: string;
113
+ /** The parsed webhook body — escape hatch. */
114
+ readonly raw: unknown;
115
+ };
116
+ }
117
+ /** Nostr event variant (B-359): a NIP-17 direct message (kind 14) or a NIP-04 one (kind 4). */
118
+ interface NostrMessageEvent extends BaseMessageEvent {
119
+ readonly platform: "nostr";
120
+ readonly nostr: {
121
+ /** The sender's public key, 64 lowercase hex characters; the send target for a reply. */
122
+ readonly pubkey: string;
123
+ /** 14 for a NIP-17 rumor unwrapped from a gift wrap, 4 for a NIP-04 encrypted message. */
124
+ readonly kind: 4 | 14;
125
+ /** The message's `created_at` in Unix seconds, as its sender stated it. */
126
+ readonly createdAt: number;
127
+ /** The decrypted rumor or kind 4 event — escape hatch. */
128
+ readonly raw: unknown;
129
+ };
130
+ }
131
+ /** Feishu/Lark event variant (B-360), an `im.message.receive_v1` event from the long connection. */
132
+ interface FeishuLarkMessageEvent extends BaseMessageEvent {
133
+ readonly platform: "feishu_lark";
134
+ readonly feishu_lark: {
135
+ /** The chat's `chat_id`; the send target for a reply. */
136
+ readonly chatId: string;
137
+ /** The message's `message_id`. */
138
+ readonly messageId: string;
139
+ /** The sender's `open_id`. */
140
+ readonly openId: string;
141
+ /** The event's `event_id`, which a redelivery repeats. */
142
+ readonly eventId: string;
143
+ /** Raw event — escape hatch. */
144
+ readonly raw: unknown;
145
+ };
146
+ }
147
+ /** Synology Chat event variant (B-361), an outgoing bot callback from the NAS. */
148
+ interface SynologyChatMessageEvent extends BaseMessageEvent {
149
+ readonly platform: "synology_chat";
150
+ readonly synology_chat: {
151
+ /** The sender's numeric user id; a reply goes to `user_ids: [userId]`. */
152
+ readonly userId: number;
153
+ /** The sender's user name. */
154
+ readonly username: string;
155
+ /** The callback's `post_id`. */
156
+ readonly postId: string;
157
+ /** The callback's `timestamp`. */
158
+ readonly timestamp: number;
159
+ /** The parsed callback body — escape hatch. */
160
+ readonly raw: unknown;
161
+ };
162
+ }
163
+ /** Tlon event variant (B-362), a DM read from the ship's `chat` app at `/v3`. */
164
+ interface TlonUrbitMessageEvent extends BaseMessageEvent {
165
+ readonly platform: "tlon_urbit";
166
+ readonly tlon_urbit: {
167
+ /** The sender's ship, `~name`; the send target for a reply. */
168
+ readonly ship: string;
169
+ /** The message id, `<ship>/<@ud>`. */
170
+ readonly messageId: string;
171
+ /** The essay's `sent` time in Unix milliseconds. */
172
+ readonly sent: number;
173
+ /** The `/v3` event — escape hatch. */
174
+ readonly raw: unknown;
175
+ };
176
+ }
177
+ /** Buzz event variant (B-367), a `message.created` realtime event. */
178
+ interface BuzzMessageEvent extends BaseMessageEvent {
179
+ readonly platform: "buzz";
180
+ readonly buzz: {
181
+ /** The message's id. */
182
+ readonly messageId: string;
183
+ /** The channel the message was posted in; for a DM, the DM channel id. */
184
+ readonly channelId: string;
185
+ /** The workspace the event belongs to, when the event names one. */
186
+ readonly workspaceId: string;
187
+ /** The parent message id when the message is a thread reply, else `""`. */
188
+ readonly threadId: string;
189
+ /** The realtime cursor of the event, `""` when absent. */
190
+ readonly cursor: string;
191
+ /** The event object — escape hatch. */
192
+ readonly raw: unknown;
193
+ };
194
+ }
195
+ /** ClickClack event variant (B-366), a `message.created` realtime event. */
196
+ interface ClickClackMessageEvent extends BaseMessageEvent {
197
+ readonly platform: "clickclack";
198
+ readonly clickclack: {
199
+ /** The message's id. */
200
+ readonly messageId: string;
201
+ /** The channel the message was posted in; for a DM, the DM channel id. */
202
+ readonly channelId: string;
203
+ /** The workspace the event belongs to, when the event names one. */
204
+ readonly workspaceId: string;
205
+ /** The parent message id when the message is a thread reply, else `""`. */
206
+ readonly threadId: string;
207
+ /** The realtime cursor of the event, `""` when absent. */
208
+ readonly cursor: string;
209
+ /** The event object — escape hatch. */
210
+ readonly raw: unknown;
211
+ };
212
+ }
213
+ /** Zalo Personal event variant (B-365), a message read from a personal Zalo account's listener. */
214
+ interface ZaloPersonalMessageEvent extends BaseMessageEvent {
215
+ readonly platform: "zalo_personal";
216
+ readonly zalo_personal: {
217
+ /** The message's `msgId`. */
218
+ readonly messageId: string;
219
+ /** The conversation's id: the peer's uid for a direct chat, the group id for a group. */
220
+ readonly threadId: string;
221
+ /** `"user"` for a direct chat, `"group"` for a group. */
222
+ readonly threadType: "user" | "group";
223
+ /** The sender's uid. */
224
+ readonly senderUid: string;
225
+ /** The listener's message object — escape hatch. */
226
+ readonly raw: unknown;
227
+ };
228
+ }
229
+ /** Zalo Official Account event variant (B-364), a `user_send_text` webhook event. */
230
+ interface ZaloMessageEvent extends BaseMessageEvent {
231
+ readonly platform: "zalo";
232
+ readonly zalo: {
233
+ /** The message's `msg_id`. */
234
+ readonly messageId: string;
235
+ /** The sender's user id for this OA; the send target for a reply. */
236
+ readonly userId: string;
237
+ /** The Official Account's id (the event's `recipient.id`). */
238
+ readonly oaId: string;
239
+ /** The webhook event — escape hatch. */
240
+ readonly raw: unknown;
241
+ };
242
+ }
243
+ /** WeChat Official Account event variant, a text message pushed to the server URL. */
244
+ interface WeChatMessageEvent extends BaseMessageEvent {
245
+ readonly platform: "wechat";
246
+ readonly wechat: {
247
+ /** The message's `MsgId`. */
248
+ readonly messageId: string;
249
+ /** The sender's OpenID for this account; the send target for a reply. */
250
+ readonly openId: string;
251
+ /** The Official Account's original id (the message's `ToUserName`). */
252
+ readonly accountId: string;
253
+ /** The parsed XML fields — escape hatch. */
254
+ readonly raw: unknown;
255
+ };
256
+ }
257
+ /** Raft event variant, one wake delivered by the Raft CLI wake bridge. */
258
+ interface RaftMessageEvent extends BaseMessageEvent {
259
+ readonly platform: "raft";
260
+ readonly raft: {
261
+ /** The wake's id. */
262
+ readonly messageId: string;
263
+ /** Who woke the agent in Raft. */
264
+ readonly senderId: string;
265
+ /** The parsed wake line — escape hatch. */
266
+ readonly raw: unknown;
267
+ };
268
+ }
269
+ /** WeCom (企业微信) self-built application event variant, a text message pushed to the callback URL. */
270
+ interface WeComMessageEvent extends BaseMessageEvent {
271
+ readonly platform: "wecom";
272
+ readonly wecom: {
273
+ /** The message's `MsgId`. */
274
+ readonly messageId: string;
275
+ /** The sender's WeCom user id; the send target for a reply. */
276
+ readonly userId: string;
277
+ /** The corp id (the message's `ToUserName`). */
278
+ readonly corpId: string;
279
+ /** The parsed XML fields — escape hatch. */
280
+ readonly raw: unknown;
281
+ };
282
+ }
283
+ /** Yuanbao (元宝) bot event variant, a text message pushed to the signed callback URL. */
284
+ interface YuanbaoMessageEvent extends BaseMessageEvent {
285
+ readonly platform: "yuanbao";
286
+ readonly yuanbao: {
287
+ /** The message's id. */
288
+ readonly messageId: string;
289
+ /** The sender's Yuanbao user id; the send target for a reply. */
290
+ readonly userId: string;
291
+ /** The callback body — escape hatch. */
292
+ readonly raw: unknown;
293
+ };
294
+ }
295
+ /** Twitch event variant (B-363), a `channel.chat.message` EventSub notification. */
296
+ interface TwitchMessageEvent extends BaseMessageEvent {
297
+ readonly platform: "twitch";
298
+ readonly twitch: {
299
+ /** The channel's broadcaster user id; the send target for a reply. */
300
+ readonly broadcasterUserId: string;
301
+ /** The chatter's user id. */
302
+ readonly chatterUserId: string;
303
+ /** The chatter's login name. */
304
+ readonly chatterLogin: string;
305
+ /** The chat message's `message_id`. */
306
+ readonly messageId: string;
307
+ /** The notification's `event` object — escape hatch. */
308
+ readonly raw: unknown;
309
+ };
310
+ }
311
+
1
312
  /**
2
313
  * `MessageEvent` — canonical inbound shape every adapter emits (T1.1, ADR D173).
3
314
  *
@@ -23,6 +334,21 @@
23
334
  *
24
335
  * @public
25
336
  */
337
+
338
+ /**
339
+ * The audio of a voice note an inbound message carries (B-715): its bytes, their media type and
340
+ * the length the platform reported.
341
+ *
342
+ * The bytes travel by reference, as an outbound attachment's do: hooks and the handler see the
343
+ * same array.
344
+ */
345
+ interface InboundAudio {
346
+ readonly data: Uint8Array;
347
+ /** The media type of `data`, such as `audio/ogg`. */
348
+ readonly mediaType: string;
349
+ /** The length in whole seconds the platform reported; 0 when it reported none. */
350
+ readonly durationSeconds: number;
351
+ }
26
352
  /** Fields common to every platform's inbound event. */
27
353
  interface BaseMessageEvent {
28
354
  /** Stable id used as a session-key segment and for dedup. */
@@ -55,6 +381,11 @@ interface BaseMessageEvent {
55
381
  readonly receivedAt: number;
56
382
  /** Optional reply-target message id. */
57
383
  readonly replyTo?: string;
384
+ /**
385
+ * The voice note's audio, when the adapter read one (B-715). Absent for a message with no voice,
386
+ * and for a voice the adapter could not read.
387
+ */
388
+ readonly audio?: InboundAudio;
58
389
  }
59
390
  /** Telegram-specific event variant. */
60
391
  interface TelegramMessageEvent extends BaseMessageEvent {
@@ -247,89 +578,6 @@ interface MatrixMessageEvent extends BaseMessageEvent {
247
578
  readonly raw: unknown;
248
579
  };
249
580
  }
250
- /** Signal-specific event variant (B-354), received from `signal-cli jsonRpc`. */
251
- interface SignalMessageEvent extends BaseMessageEvent {
252
- readonly platform: "signal";
253
- readonly signal: {
254
- /** Envelope timestamp (ms since epoch); Signal's own message id. */
255
- readonly timestamp: number;
256
- /** Sender's phone number, when signal-cli knows it. */
257
- readonly sourceNumber?: string;
258
- /** Sender's account UUID, when signal-cli knows it. */
259
- readonly sourceUuid?: string;
260
- /** Group id, present only for a group message. */
261
- readonly groupId?: string;
262
- /** Raw signal-cli envelope — escape hatch. */
263
- readonly raw: unknown;
264
- };
265
- }
266
- /** iMessage-specific event variant (B-355), received from `imsg rpc` on a signed-in Mac. */
267
- interface IMessageMessageEvent extends BaseMessageEvent {
268
- readonly platform: "imessage";
269
- readonly imessage: {
270
- /** `imsg`'s numeric chat id; the send target for a reply. */
271
- readonly chatId: number;
272
- /** Messages' own message GUID. */
273
- readonly guid: string;
274
- /** `imsg`'s `is_group` for the chat; agrees with `channel.type === "group"`. */
275
- readonly isGroup: boolean;
276
- /** Participant handles (phone numbers or emails) as `imsg` reports them for the chat. */
277
- readonly participants: readonly string[];
278
- /** Raw `imsg` notification payload — escape hatch. */
279
- readonly raw: unknown;
280
- };
281
- }
282
- /** Google Chat-specific event variant (B-356), posted to the Chat app's HTTPS endpoint. */
283
- interface GoogleChatMessageEvent extends BaseMessageEvent {
284
- readonly platform: "google_chat";
285
- readonly google_chat: {
286
- /** The message's resource name, `spaces/<space>/messages/<message>`. */
287
- readonly messageName: string;
288
- /** The space's resource name, `spaces/<space>`; the send target for a reply. */
289
- readonly spaceName: string;
290
- /** The space's `spaceType` (`SPACE`, `GROUP_CHAT` or `DIRECT_MESSAGE`), when Chat sent one. */
291
- readonly spaceType?: string;
292
- /** The thread's resource name, when the message is in a thread. */
293
- readonly threadName?: string;
294
- /** Raw Chat event — escape hatch. */
295
- readonly raw: unknown;
296
- };
297
- }
298
- /** IRC-specific event variant (B-357), read from a PRIVMSG on the adapter's own connection. */
299
- interface IrcMessageEvent extends BaseMessageEvent {
300
- readonly platform: "irc";
301
- readonly irc: {
302
- /** Where the PRIVMSG was addressed: a channel, `#name`, or the adapter's own nick for a DM. */
303
- readonly target: string;
304
- /** The sender's nick, from the line's prefix. */
305
- readonly nick: string;
306
- /** True for a CTCP ACTION (`/me`); `text` then holds the action without its CTCP framing. */
307
- readonly action: boolean;
308
- /** The line's IRCv3 message tags, unescaped; empty when the server sent none. */
309
- readonly tags: Readonly<Record<string, string>>;
310
- /** The raw line as the server sent it, without CRLF — escape hatch. */
311
- readonly raw: string;
312
- };
313
- }
314
- /**
315
- * Nextcloud Talk event variant (B-358), read from a bot webhook `Create` activity that carried a
316
- * signature the adapter verified.
317
- */
318
- interface NextcloudTalkMessageEvent extends BaseMessageEvent {
319
- readonly platform: "nextcloud_talk";
320
- readonly nextcloud_talk: {
321
- /** The conversation's token, the `target.id` of the activity; a reply goes to it. */
322
- readonly roomToken: string;
323
- /** Talk's id for the message, the activity's `object.id`. */
324
- readonly messageId: string;
325
- /** Who wrote it, as Talk names actors: `users/<id>`, `guests/<id>`, `bots/<id>`… */
326
- readonly actorId: string;
327
- /** The id of the message this one answers, when it is a reply. */
328
- readonly replyToId?: string;
329
- /** The parsed webhook body — escape hatch. */
330
- readonly raw: unknown;
331
- };
332
- }
333
581
  /**
334
582
  * The open registry every platform's inbound event is filed under.
335
583
  *
@@ -368,6 +616,19 @@ interface PlatformEventRegistry {
368
616
  google_chat: GoogleChatMessageEvent;
369
617
  irc: IrcMessageEvent;
370
618
  nextcloud_talk: NextcloudTalkMessageEvent;
619
+ nostr: NostrMessageEvent;
620
+ feishu_lark: FeishuLarkMessageEvent;
621
+ synology_chat: SynologyChatMessageEvent;
622
+ tlon_urbit: TlonUrbitMessageEvent;
623
+ twitch: TwitchMessageEvent;
624
+ zalo_personal: ZaloPersonalMessageEvent;
625
+ zalo: ZaloMessageEvent;
626
+ wechat: WeChatMessageEvent;
627
+ wecom: WeComMessageEvent;
628
+ yuanbao: YuanbaoMessageEvent;
629
+ raft: RaftMessageEvent;
630
+ clickclack: ClickClackMessageEvent;
631
+ buzz: BuzzMessageEvent;
371
632
  }
372
633
  /**
373
634
  * `true` only for `any` — the one type that would otherwise swallow the union.
@@ -474,6 +735,32 @@ type PlatformName = MessageEvent["platform"];
474
735
  * (`TelegramAdapter`, `DiscordAdapter`, ...).
475
736
  */
476
737
 
738
+ /**
739
+ * An image an outbound message carries: its bytes and their media type (B-674).
740
+ *
741
+ * The bytes travel by reference: the runner does not copy them on the way to the adapter. The
742
+ * caller must not change `data` or the list until the send's promise settles: an adapter that
743
+ * sends several attachments reads each one only when its turn comes.
744
+ */
745
+ interface OutboundImageAttachment {
746
+ readonly kind: "image";
747
+ /** The media type of `data`, such as `image/png`. */
748
+ readonly mediaType: string;
749
+ readonly data: Uint8Array;
750
+ /** A file name the platform may show; optional. */
751
+ readonly filename?: string;
752
+ }
753
+ /** An audio clip an outbound message carries, such as a spoken reply (B-715). Same rules as an image. */
754
+ interface OutboundAudioAttachment {
755
+ readonly kind: "audio";
756
+ /** The media type of `data`, such as `audio/ogg`. */
757
+ readonly mediaType: string;
758
+ readonly data: Uint8Array;
759
+ /** A file name the platform may show; optional. */
760
+ readonly filename?: string;
761
+ }
762
+ /** An attachment an outbound message carries, told apart by `kind`. */
763
+ type OutboundAttachment = OutboundImageAttachment | OutboundAudioAttachment;
477
764
  /** Outbound message shape — what `sendMessage` accepts. */
478
765
  interface OutboundMessage {
479
766
  readonly channel: {
@@ -486,6 +773,11 @@ interface OutboundMessage {
486
773
  readonly format?: "plain" | "markdown" | "html";
487
774
  /** Optional reply target. */
488
775
  readonly replyTo?: string;
776
+ /**
777
+ * Images to send with the text. An adapter whose {@link BasePlatformAdapter.supportsAttachments}
778
+ * is `false` refuses a non-empty list with `attachments_unsupported`; it never drops it.
779
+ */
780
+ readonly attachments?: ReadonlyArray<OutboundAttachment>;
489
781
  }
490
782
  /** Send result — adapters return this instead of throwing on platform errors. */
491
783
  interface SendResult {
@@ -510,13 +802,19 @@ interface SendResult {
510
802
  * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.
511
803
  * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling
512
804
  * `onInbound` twice replaces the previous handler — does NOT stack.
513
- * - `sendMessage` with empty text returns `{ ok: false, code: "empty_text" }`.
805
+ * - `sendMessage` with empty text and no attachments returns `{ ok: false, code: "empty_text" }`.
806
+ * An adapter that refuses attachments answers `attachments_unsupported` first, and one that
807
+ * sends them (Telegram) accepts empty text with an image.
514
808
  * - `supportsEdit` says whether the adapter has an edit call. It is `false` unless the adapter
515
809
  * overrides it, and it MUST NOT change with `connect()`. `true` does not promise that every
516
810
  * edit is accepted: an adapter whose injected client lacks the edit call (Matrix) still answers
517
811
  * `edit_unsupported`, which a caller handles like any other refusal.
518
812
  * - `editMessage` returns a `SendResult` and never throws on platform errors. The default refuses
519
813
  * with `edit_unsupported` and makes no platform call.
814
+ * - `supportsAttachments` says whether `sendMessage` can send `out.attachments`. It is `false`
815
+ * unless the adapter overrides it, and it MUST NOT change with `connect()`. An adapter that
816
+ * does not support them refuses a non-empty list with `attachments_unsupported` and makes no
817
+ * platform call; an edit carrying an attachment is refused the same way.
520
818
  * - Edits are not ordered by the adapter. Two edits of one message id in flight at once reach the
521
819
  * platform in either order, so a caller awaits each edit before the next, or keeps one in flight
522
820
  * and coalesces to the latest text.
@@ -574,6 +872,33 @@ declare abstract class BasePlatformAdapter {
574
872
  * is taken from `this.platform`, which is the only part that differed between them.
575
873
  */
576
874
  protected runHandler(handler: ((event: MessageEvent) => Promise<void>) | undefined, event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
875
+ /** The handler {@link subscribe} holds; `undefined` while nobody is subscribed. */
876
+ protected subscribedHandler: ((event: MessageEvent) => Promise<void>) | undefined;
877
+ /** The body of {@link onInbound}: replace the handler, and unsubscribe only if it is still the one held. */
878
+ protected subscribe(handler: (event: MessageEvent) => Promise<void>): () => void;
879
+ /** The body of {@link deliver} for an adapter that subscribed through {@link subscribe}. */
880
+ protected deliverInbound(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
881
+ /**
882
+ * Dispatch a webhook event once: `duplicate` when `seen` holds its id, `no_handler` when nobody
883
+ * subscribed (the id is then NOT remembered, so a redelivery is handled), otherwise remember the
884
+ * id and run the handler. A handler's throw is also logged under `label`.
885
+ */
886
+ protected dispatchOnce(seen: SeenIds, event: MessageEvent, label: string): Promise<"ok" | "no_handler" | "handler_threw" | "duplicate">;
887
+ /** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */
888
+ protected outboundText(out: OutboundMessage): string;
889
+ /**
890
+ * The local checks every text-only `sendMessage` makes before a request, in this order:
891
+ * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
892
+ * Returns the refusal, or `undefined` when the message may be sent.
893
+ */
894
+ protected refuseUnsendable(out: OutboundMessage, check: {
895
+ readonly className: string;
896
+ readonly connected: boolean;
897
+ readonly channel?: {
898
+ readonly valid: (id: string) => boolean;
899
+ readonly message: string;
900
+ };
901
+ }): SendResult | undefined;
577
902
  /**
578
903
  * Whether {@link editMessage} can replace the text of a message this adapter sent.
579
904
  *
@@ -582,6 +907,14 @@ declare abstract class BasePlatformAdapter {
582
907
  * edit-capable adapter can override it with `true`.
583
908
  */
584
909
  readonly supportsEdit: boolean;
910
+ /**
911
+ * Whether {@link sendMessage} can send the images of `out.attachments` (B-674).
912
+ *
913
+ * Read it before attaching: on `false`, the adapter refuses a non-empty list with
914
+ * `attachments_unsupported`. Set at construction, never changed by `connect()`. Annotated as
915
+ * `boolean` so that an adapter that sends images can override it with `true`.
916
+ */
917
+ readonly supportsAttachments: boolean;
585
918
  /**
586
919
  * Replace the text of a message this adapter sent, keeping its id.
587
920
  *
@@ -595,12 +928,114 @@ declare abstract class BasePlatformAdapter {
595
928
  * first, so capability is answered before input.
596
929
  */
597
930
  editMessage(_messageId: string, _out: OutboundMessage): Promise<SendResult>;
931
+ /**
932
+ * React to an inbound message with an emoji (for example 👀 as an acknowledgement).
933
+ *
934
+ * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
935
+ * throws on platform errors. `channelId` is the channel the message is in and `messageId` the
936
+ * id the inbound event carried.
937
+ *
938
+ * Default: resolves `{ ok: false, error: { code: "react_unsupported" } }` and makes no
939
+ * platform call.
940
+ */
941
+ react(_channelId: string, _messageId: string, _emoji: string): Promise<SendResult>;
598
942
  /** Lifecycle: emit a typing indicator. Default: noop. */
599
943
  startTyping(_channelId: string): Promise<void>;
600
944
  /** Lifecycle: stop the typing indicator. Default: noop. */
601
945
  stopTyping(_channelId: string): Promise<void>;
602
946
  }
603
947
 
948
+ /**
949
+ * `WeixinAdapterBase` — the connect / token / send / dispatch flow that the WeChat and WeCom
950
+ * adapters share. A subclass supplies the platform's endpoints, its signature check and its event
951
+ * shape; this class owns everything else.
952
+ *
953
+ * @public
954
+ */
955
+
956
+ /** A `fetch`-shaped function; the adapter's only network seam. @public */
957
+ type WeixinFetch = (url: string, init: {
958
+ method: string;
959
+ headers: Record<string, string>;
960
+ body?: string;
961
+ }) => Promise<{
962
+ status: number;
963
+ text(): Promise<string>;
964
+ }>;
965
+ /**
966
+ * What a webhook route answers. `body` is the text to write back; anything but 200 makes the
967
+ * platform retry.
968
+ *
969
+ * @public
970
+ */
971
+ type WeixinWebhookAnswer = {
972
+ readonly status: 200 | 400 | 401 | 503;
973
+ readonly body: string;
974
+ readonly reason: string;
975
+ };
976
+ /** What a subclass tells the base about its platform. @public */
977
+ interface WeixinAdapterConfig {
978
+ /** Log prefix, e.g. `gateway-wechat`. */
979
+ readonly label: string;
980
+ /** Class name used in the `not_connected` message, e.g. `WeChatAdapter`. */
981
+ readonly className: string;
982
+ /** Brand used in messages, e.g. `WeChat`. */
983
+ readonly brand: string;
984
+ /** What `channel.id` must be, e.g. `a WeChat OpenID`. */
985
+ readonly userNoun: string;
986
+ /** API base used when `apiBase` is not set. */
987
+ readonly defaultBase: string;
988
+ readonly apiBase?: string;
989
+ readonly fetch?: WeixinFetch;
990
+ }
991
+ /** One send call: a path (with its access token) and a JSON payload. @public */
992
+ interface WeixinSendRequest {
993
+ readonly path: string;
994
+ readonly payload: unknown;
995
+ }
996
+ /**
997
+ * Shared base of the WeChat and WeCom adapters.
998
+ *
999
+ * @public
1000
+ */
1001
+ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
1002
+ private readonly cfg;
1003
+ private readonly doFetch;
1004
+ private connected;
1005
+ private accessToken;
1006
+ private readonly seen;
1007
+ constructor(cfg: WeixinAdapterConfig);
1008
+ /** Path and query of the access-token request. */
1009
+ protected abstract tokenPath(): string;
1010
+ /** The send call for one part of a reply. */
1011
+ protected abstract sendRequest(token: string, userId: string, content: string): WeixinSendRequest;
1012
+ /** Cut a reply into parts the platform accepts. */
1013
+ protected abstract split(text: string): string[];
1014
+ /** The event for a text message, `"skip"` for another type, `undefined` for a text with gaps. */
1015
+ protected abstract toEvent(fields: Record<string, string>): MessageEvent | "skip" | undefined;
1016
+ connect(): Promise<boolean>;
1017
+ disconnect(): Promise<void>;
1018
+ /** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
1019
+ protected sendText(out: OutboundMessage): Promise<SendResult>;
1020
+ private sendParts;
1021
+ onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
1022
+ /** Deliver an event that arrived out of band, through `runHandler`. */
1023
+ deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
1024
+ /** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */
1025
+ protected handleMessage(xml: string): Promise<WeixinWebhookAnswer>;
1026
+ private token;
1027
+ private call;
1028
+ }
1029
+
1030
+ /**
1031
+ * Read the flat XML the Tencent webhook platforms (WeChat, WeCom) push:
1032
+ * `<xml><Tag><![CDATA[v]]></Tag>…</xml>`. The messages these adapters take have no nesting, so a
1033
+ * tag scan is enough and no XML library is needed.
1034
+ *
1035
+ * @public
1036
+ */
1037
+ declare function parseFlatXml(xml: string): Record<string, string>;
1038
+
604
1039
  /**
605
1040
  * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).
606
1041
  *
@@ -733,9 +1168,16 @@ interface ChannelRejection {
733
1168
  readonly platform: PlatformName;
734
1169
  readonly error: GatewayConfigurationError;
735
1170
  }
1171
+ /** A built adapter paired with the descriptor that built it, so a consumer need not re-pair them. */
1172
+ interface BuiltChannel {
1173
+ readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;
1174
+ readonly adapter: BasePlatformAdapter;
1175
+ }
736
1176
  /** What `createChannels` built and what it refused. */
737
1177
  interface CreateChannelsResult {
738
1178
  readonly adapters: BasePlatformAdapter[];
1179
+ /** The same adapters, in the same order, each paired with its descriptor. */
1180
+ readonly channels: BuiltChannel[];
739
1181
  readonly rejected: ChannelRejection[];
740
1182
  }
741
1183
  /**
@@ -785,6 +1227,8 @@ interface DeliveryRequest extends DeliveryTarget {
785
1227
  readonly text: string;
786
1228
  readonly format?: "plain" | "markdown" | "html";
787
1229
  readonly replyTo?: string;
1230
+ /** Images to send with the text; an empty list is left out (B-674). */
1231
+ readonly attachments?: ReadonlyArray<OutboundAttachment>;
788
1232
  }
789
1233
  /**
790
1234
  * Routes outbound requests to the correct adapter.
@@ -793,6 +1237,8 @@ interface DeliveryRequest extends DeliveryTarget {
793
1237
  * - `register` is last-writer-wins by platform.
794
1238
  * - `send` with unknown platform returns `{ ok: false, code: "no_adapter" }`.
795
1239
  * - `send` never throws on platform errors (delegates to adapter's SendResult).
1240
+ * - `send` with attachments refuses with `attachments_unsupported`, calling no `sendMessage`, when
1241
+ * the adapter does not declare `supportsAttachments`.
796
1242
  *
797
1243
  * @public
798
1244
  */
@@ -949,6 +1395,8 @@ interface GatewayContext {
949
1395
  /** Send a reply to the originating channel (auto-routed by `event.platform`). */
950
1396
  reply(text: string, opts?: {
951
1397
  format?: "plain" | "markdown" | "html";
1398
+ /** Images to send with the text; an empty list is left out (B-674). */
1399
+ attachments?: ReadonlyArray<OutboundAttachment>;
952
1400
  }): Promise<SendResult>;
953
1401
  /** The triggering event. */
954
1402
  readonly event: MessageEvent;
@@ -979,6 +1427,33 @@ interface GatewayRunnerOptions {
979
1427
  * @public
980
1428
  */
981
1429
  readonly connectFailure?: ConnectFailure;
1430
+ /**
1431
+ * Retry, in the background, an adapter whose `connect()` threw a transient error under
1432
+ * `connectFailure: "isolate"` (network refused, DNS, 5xx), with exponential backoff and a log
1433
+ * line per attempt. An adapter that connects on a retry is wired for inbound and joins
1434
+ * `connected`. A `connect()` that resolves `false`, or throws a credential error (HTTP 401/403,
1435
+ * `M_UNKNOWN_TOKEN`, `M_FORBIDDEN`, "unauthorized"), is terminal: it is reported once and not
1436
+ * retried. Off unless set; ignored under `"rollback"`.
1437
+ *
1438
+ * @public
1439
+ */
1440
+ readonly reconnect?: ReconnectPolicy;
1441
+ }
1442
+ /**
1443
+ * Backoff for `GatewayRunnerOptions.reconnect`. The delay before attempt n is
1444
+ * `min(initialDelayMs * factor^(n-1), maxDelayMs)`.
1445
+ *
1446
+ * @public
1447
+ */
1448
+ interface ReconnectPolicy {
1449
+ /** Delay before the first retry. Default 1000ms. */
1450
+ readonly initialDelayMs?: number;
1451
+ /** Cap on the delay between attempts. Default 60_000ms. */
1452
+ readonly maxDelayMs?: number;
1453
+ /** Multiplier per attempt. Default 2. */
1454
+ readonly factor?: number;
1455
+ /** Give up after this many retries. Default: keep trying until `stop()`. */
1456
+ readonly maxAttempts?: number;
982
1457
  }
983
1458
  /**
984
1459
  * How `GatewayRunner.start()` treats an adapter that fails to connect: `"rollback"` (all or
@@ -1010,7 +1485,6 @@ interface StartResult {
1010
1485
  */
1011
1486
  declare class GatewayRunner {
1012
1487
  private readonly opts;
1013
- private readonly adaptersByPlatform;
1014
1488
  private readonly hookExecutor;
1015
1489
  private readonly inflight;
1016
1490
  private readonly unsubs;
@@ -1020,6 +1494,7 @@ declare class GatewayRunner {
1020
1494
  /** The start that has not settled yet, shared by every overlapping `start()` call. */
1021
1495
  private startInFlight;
1022
1496
  private stopped;
1497
+ private readonly retryTimers;
1023
1498
  constructor(opts: GatewayRunnerOptions);
1024
1499
  /**
1025
1500
  * Register a slash command. Match rule (EC-A): text === "/" + name
@@ -1055,6 +1530,9 @@ declare class GatewayRunner {
1055
1530
  */
1056
1531
  start(): Promise<StartResult>;
1057
1532
  private runStart;
1533
+ /** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
1534
+ private scheduleReconnect;
1535
+ private reconnectOnce;
1058
1536
  /**
1059
1537
  * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
1060
1538
  * the first failure. Every connect settles before the rollback: rolling back while one is still
@@ -1280,6 +1758,14 @@ interface ChunkTextOptions {
1280
1758
  * (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.
1281
1759
  */
1282
1760
  readonly trimParts?: boolean;
1761
+ /**
1762
+ * When true, a cut that would fall inside a Markdown table row (a line whose first non-blank
1763
+ * character is `|`) moves back to the start of that row, provided the row fits in the window and
1764
+ * does not open the chunk; the row then opens the next chunk whole and byte-identical (B-556).
1765
+ * A row longer than the window is cut by length as before. Text with no table row splits exactly
1766
+ * as without the option. Default: `false`.
1767
+ */
1768
+ readonly keepTableRows?: boolean;
1283
1769
  }
1284
1770
  /**
1285
1771
  * Split `text` into chunks no longer than the configured window, preferring
@@ -1317,6 +1803,48 @@ declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions):
1317
1803
  */
1318
1804
  declare function toDialect(text: string, platform: string): string;
1319
1805
 
1806
+ /**
1807
+ * Fenced code block scanner (B-518).
1808
+ *
1809
+ * Reads the fences of CommonMark § 4.5: a line of at most three blanks, then three or more
1810
+ * backticks or tildes (an info string after a backtick run holds no backtick), closed by a line of
1811
+ * the same character, at least as many, and nothing after them but blanks. A fence never closed runs
1812
+ * to the end of the text. Fences inside a list item or block quote (indented four or more, or behind
1813
+ * a `>`) are not read.
1814
+ *
1815
+ * @public
1816
+ */
1817
+ /** One fenced code block, as offsets into the scanned text. */
1818
+ interface FenceRegion {
1819
+ /** Offset of the first character of the opening line. */
1820
+ readonly start: number;
1821
+ /** Offset just past the opening line, before its line ending. */
1822
+ readonly openerEnd: number;
1823
+ /** Offset of the first character after the opening line's line ending (the first code line). */
1824
+ readonly contentStart: number;
1825
+ /** Offset just past the last character of the closing line (its line ending excluded), or the text length when never closed. */
1826
+ readonly end: number;
1827
+ /** The opening line, byte for byte. */
1828
+ readonly opener: string;
1829
+ /** The marker run that closes the block: the opening run, without its indent. */
1830
+ readonly closer: string;
1831
+ /** False when the text ends before a closing line. */
1832
+ readonly closed: boolean;
1833
+ }
1834
+ /** Every fenced region of `text`, in order. */
1835
+ declare function scanFences(text: string): readonly FenceRegion[];
1836
+
1837
+ /**
1838
+ * Grapheme-safe splitting of long text that keeps Markdown table rows whole (B-556).
1839
+ *
1840
+ * @internal
1841
+ */
1842
+ /**
1843
+ * Parts of at most `partLimit` units, cut at grapheme boundaries and before straddled rows.
1844
+ * Shared by the SMS and LINE splitters (text no longer than a part is theirs to handle).
1845
+ */
1846
+ declare function splitKeepingRows(text: string, partLimit: number): string[];
1847
+
1320
1848
  /**
1321
1849
  * The half of an Express webhook server that is the same for every platform.
1322
1850
  *
@@ -1423,4 +1951,4 @@ declare function listenerLifecycle(opts: {
1423
1951
  stop(): Promise<void>;
1424
1952
  };
1425
1953
 
1426
- 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 GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type IngestResult, type IrcMessageEvent, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type NextcloudTalkMessageEvent, type OnErrorContext, type OutboundMessage, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type RawBodyCaptureOptions, type RawBodyRequest, type SMSMessageEvent, type SendResult, SessionRouter, type SignalMessageEvent, 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 };
1954
+ 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 RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, type ReconnectPolicy, 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 WeChatMessageEvent, type WeComMessageEvent, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, toDialect };