@theokit/gateway 0.14.0 → 0.16.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.cts CHANGED
@@ -1,3 +1,27 @@
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
+
1
25
  /**
2
26
  * The event variants of the platforms added in S-003: batch 1 (B-354 to B-358) and batch 2 (B-359
3
27
  * to B-363).
@@ -202,6 +226,84 @@ interface ZaloPersonalMessageEvent extends BaseMessageEvent {
202
226
  readonly raw: unknown;
203
227
  };
204
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
+ /** QQ Bot event variant, a C2C (direct) text message pushed to the signed webhook. */
284
+ interface QQMessageEvent extends BaseMessageEvent {
285
+ readonly platform: "qq";
286
+ readonly qq: {
287
+ /** The message's id; a reply is sent as a passive reply to it. */
288
+ readonly messageId: string;
289
+ /** The sender's `user_openid`; the send target for a reply. */
290
+ readonly userOpenId: string;
291
+ /** The webhook payload — escape hatch. */
292
+ readonly raw: unknown;
293
+ };
294
+ }
295
+ /** Yuanbao (元宝) bot event variant, a text message pushed to the signed callback URL. */
296
+ interface YuanbaoMessageEvent extends BaseMessageEvent {
297
+ readonly platform: "yuanbao";
298
+ readonly yuanbao: {
299
+ /** The message's id. */
300
+ readonly messageId: string;
301
+ /** The sender's Yuanbao user id; the send target for a reply. */
302
+ readonly userId: string;
303
+ /** The callback body — escape hatch. */
304
+ readonly raw: unknown;
305
+ };
306
+ }
205
307
  /** Twitch event variant (B-363), a `channel.chat.message` EventSub notification. */
206
308
  interface TwitchMessageEvent extends BaseMessageEvent {
207
309
  readonly platform: "twitch";
@@ -218,6 +320,34 @@ interface TwitchMessageEvent extends BaseMessageEvent {
218
320
  readonly raw: unknown;
219
321
  };
220
322
  }
323
+ /** One tweet of a mention's thread, oldest first in {@link XMessageEvent.x}`.thread`. */
324
+ interface XThreadTweet {
325
+ readonly tweetId: string;
326
+ readonly authorId: string;
327
+ /** The author's handle, `""` when the API did not return it. */
328
+ readonly username: string;
329
+ readonly text: string;
330
+ }
331
+ /** X (Twitter) event variant, a tweet that mentions the bot account. */
332
+ interface XMessageEvent extends BaseMessageEvent {
333
+ readonly platform: "x";
334
+ readonly x: {
335
+ /** The mention tweet's id; a reply is posted under it. */
336
+ readonly tweetId: string;
337
+ /** The thread's conversation id; also the channel id. */
338
+ readonly conversationId: string;
339
+ /** The author's user id. */
340
+ readonly authorId: string;
341
+ /** The tweets the mention replies to, oldest first; empty when it starts a thread. */
342
+ readonly thread: readonly XThreadTweet[];
343
+ /** The tweet the mention quotes, when it quotes one. */
344
+ readonly quoted?: XThreadTweet;
345
+ /** `true` when the author is not allowlisted and was let in by guest mode. */
346
+ readonly guest: boolean;
347
+ /** The tweet object — escape hatch. */
348
+ readonly raw: unknown;
349
+ };
350
+ }
221
351
 
222
352
  /**
223
353
  * `MessageEvent` — canonical inbound shape every adapter emits (T1.1, ADR D173).
@@ -532,6 +662,13 @@ interface PlatformEventRegistry {
532
662
  tlon_urbit: TlonUrbitMessageEvent;
533
663
  twitch: TwitchMessageEvent;
534
664
  zalo_personal: ZaloPersonalMessageEvent;
665
+ zalo: ZaloMessageEvent;
666
+ wechat: WeChatMessageEvent;
667
+ wecom: WeComMessageEvent;
668
+ yuanbao: YuanbaoMessageEvent;
669
+ x: XMessageEvent;
670
+ qq: QQMessageEvent;
671
+ raft: RaftMessageEvent;
535
672
  clickclack: ClickClackMessageEvent;
536
673
  buzz: BuzzMessageEvent;
537
674
  }
@@ -777,6 +914,33 @@ declare abstract class BasePlatformAdapter {
777
914
  * is taken from `this.platform`, which is the only part that differed between them.
778
915
  */
779
916
  protected runHandler(handler: ((event: MessageEvent) => Promise<void>) | undefined, event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
917
+ /** The handler {@link subscribe} holds; `undefined` while nobody is subscribed. */
918
+ protected subscribedHandler: ((event: MessageEvent) => Promise<void>) | undefined;
919
+ /** The body of {@link onInbound}: replace the handler, and unsubscribe only if it is still the one held. */
920
+ protected subscribe(handler: (event: MessageEvent) => Promise<void>): () => void;
921
+ /** The body of {@link deliver} for an adapter that subscribed through {@link subscribe}. */
922
+ protected deliverInbound(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
923
+ /**
924
+ * Dispatch a webhook event once: `duplicate` when `seen` holds its id, `no_handler` when nobody
925
+ * subscribed (the id is then NOT remembered, so a redelivery is handled), otherwise remember the
926
+ * id and run the handler. A handler's throw is also logged under `label`.
927
+ */
928
+ protected dispatchOnce(seen: SeenIds, event: MessageEvent, label: string): Promise<"ok" | "no_handler" | "handler_threw" | "duplicate">;
929
+ /** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */
930
+ protected outboundText(out: OutboundMessage): string;
931
+ /**
932
+ * The local checks every text-only `sendMessage` makes before a request, in this order:
933
+ * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
934
+ * Returns the refusal, or `undefined` when the message may be sent.
935
+ */
936
+ protected refuseUnsendable(out: OutboundMessage, check: {
937
+ readonly className: string;
938
+ readonly connected: boolean;
939
+ readonly channel?: {
940
+ readonly valid: (id: string) => boolean;
941
+ readonly message: string;
942
+ };
943
+ }): SendResult | undefined;
780
944
  /**
781
945
  * Whether {@link editMessage} can replace the text of a message this adapter sent.
782
946
  *
@@ -806,12 +970,114 @@ declare abstract class BasePlatformAdapter {
806
970
  * first, so capability is answered before input.
807
971
  */
808
972
  editMessage(_messageId: string, _out: OutboundMessage): Promise<SendResult>;
973
+ /**
974
+ * React to an inbound message with an emoji (for example 👀 as an acknowledgement).
975
+ *
976
+ * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
977
+ * throws on platform errors. `channelId` is the channel the message is in and `messageId` the
978
+ * id the inbound event carried.
979
+ *
980
+ * Default: resolves `{ ok: false, error: { code: "react_unsupported" } }` and makes no
981
+ * platform call.
982
+ */
983
+ react(_channelId: string, _messageId: string, _emoji: string): Promise<SendResult>;
809
984
  /** Lifecycle: emit a typing indicator. Default: noop. */
810
985
  startTyping(_channelId: string): Promise<void>;
811
986
  /** Lifecycle: stop the typing indicator. Default: noop. */
812
987
  stopTyping(_channelId: string): Promise<void>;
813
988
  }
814
989
 
990
+ /**
991
+ * `WeixinAdapterBase` — the connect / token / send / dispatch flow that the WeChat and WeCom
992
+ * adapters share. A subclass supplies the platform's endpoints, its signature check and its event
993
+ * shape; this class owns everything else.
994
+ *
995
+ * @public
996
+ */
997
+
998
+ /** A `fetch`-shaped function; the adapter's only network seam. @public */
999
+ type WeixinFetch = (url: string, init: {
1000
+ method: string;
1001
+ headers: Record<string, string>;
1002
+ body?: string;
1003
+ }) => Promise<{
1004
+ status: number;
1005
+ text(): Promise<string>;
1006
+ }>;
1007
+ /**
1008
+ * What a webhook route answers. `body` is the text to write back; anything but 200 makes the
1009
+ * platform retry.
1010
+ *
1011
+ * @public
1012
+ */
1013
+ type WeixinWebhookAnswer = {
1014
+ readonly status: 200 | 400 | 401 | 503;
1015
+ readonly body: string;
1016
+ readonly reason: string;
1017
+ };
1018
+ /** What a subclass tells the base about its platform. @public */
1019
+ interface WeixinAdapterConfig {
1020
+ /** Log prefix, e.g. `gateway-wechat`. */
1021
+ readonly label: string;
1022
+ /** Class name used in the `not_connected` message, e.g. `WeChatAdapter`. */
1023
+ readonly className: string;
1024
+ /** Brand used in messages, e.g. `WeChat`. */
1025
+ readonly brand: string;
1026
+ /** What `channel.id` must be, e.g. `a WeChat OpenID`. */
1027
+ readonly userNoun: string;
1028
+ /** API base used when `apiBase` is not set. */
1029
+ readonly defaultBase: string;
1030
+ readonly apiBase?: string;
1031
+ readonly fetch?: WeixinFetch;
1032
+ }
1033
+ /** One send call: a path (with its access token) and a JSON payload. @public */
1034
+ interface WeixinSendRequest {
1035
+ readonly path: string;
1036
+ readonly payload: unknown;
1037
+ }
1038
+ /**
1039
+ * Shared base of the WeChat and WeCom adapters.
1040
+ *
1041
+ * @public
1042
+ */
1043
+ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
1044
+ private readonly cfg;
1045
+ private readonly doFetch;
1046
+ private connected;
1047
+ private accessToken;
1048
+ private readonly seen;
1049
+ constructor(cfg: WeixinAdapterConfig);
1050
+ /** Path and query of the access-token request. */
1051
+ protected abstract tokenPath(): string;
1052
+ /** The send call for one part of a reply. */
1053
+ protected abstract sendRequest(token: string, userId: string, content: string): WeixinSendRequest;
1054
+ /** Cut a reply into parts the platform accepts. */
1055
+ protected abstract split(text: string): string[];
1056
+ /** The event for a text message, `"skip"` for another type, `undefined` for a text with gaps. */
1057
+ protected abstract toEvent(fields: Record<string, string>): MessageEvent | "skip" | undefined;
1058
+ connect(): Promise<boolean>;
1059
+ disconnect(): Promise<void>;
1060
+ /** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
1061
+ protected sendText(out: OutboundMessage): Promise<SendResult>;
1062
+ private sendParts;
1063
+ onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
1064
+ /** Deliver an event that arrived out of band, through `runHandler`. */
1065
+ deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
1066
+ /** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */
1067
+ protected handleMessage(xml: string): Promise<WeixinWebhookAnswer>;
1068
+ private token;
1069
+ private call;
1070
+ }
1071
+
1072
+ /**
1073
+ * Read the flat XML the Tencent webhook platforms (WeChat, WeCom) push:
1074
+ * `<xml><Tag><![CDATA[v]]></Tag>…</xml>`. The messages these adapters take have no nesting, so a
1075
+ * tag scan is enough and no XML library is needed.
1076
+ *
1077
+ * @public
1078
+ */
1079
+ declare function parseFlatXml(xml: string): Record<string, string>;
1080
+
815
1081
  /**
816
1082
  * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).
817
1083
  *
@@ -1203,6 +1469,33 @@ interface GatewayRunnerOptions {
1203
1469
  * @public
1204
1470
  */
1205
1471
  readonly connectFailure?: ConnectFailure;
1472
+ /**
1473
+ * Retry, in the background, an adapter whose `connect()` threw a transient error under
1474
+ * `connectFailure: "isolate"` (network refused, DNS, 5xx), with exponential backoff and a log
1475
+ * line per attempt. An adapter that connects on a retry is wired for inbound and joins
1476
+ * `connected`. A `connect()` that resolves `false`, or throws a credential error (HTTP 401/403,
1477
+ * `M_UNKNOWN_TOKEN`, `M_FORBIDDEN`, "unauthorized"), is terminal: it is reported once and not
1478
+ * retried. Off unless set; ignored under `"rollback"`.
1479
+ *
1480
+ * @public
1481
+ */
1482
+ readonly reconnect?: ReconnectPolicy;
1483
+ }
1484
+ /**
1485
+ * Backoff for `GatewayRunnerOptions.reconnect`. The delay before attempt n is
1486
+ * `min(initialDelayMs * factor^(n-1), maxDelayMs)`.
1487
+ *
1488
+ * @public
1489
+ */
1490
+ interface ReconnectPolicy {
1491
+ /** Delay before the first retry. Default 1000ms. */
1492
+ readonly initialDelayMs?: number;
1493
+ /** Cap on the delay between attempts. Default 60_000ms. */
1494
+ readonly maxDelayMs?: number;
1495
+ /** Multiplier per attempt. Default 2. */
1496
+ readonly factor?: number;
1497
+ /** Give up after this many retries. Default: keep trying until `stop()`. */
1498
+ readonly maxAttempts?: number;
1206
1499
  }
1207
1500
  /**
1208
1501
  * How `GatewayRunner.start()` treats an adapter that fails to connect: `"rollback"` (all or
@@ -1243,6 +1536,7 @@ declare class GatewayRunner {
1243
1536
  /** The start that has not settled yet, shared by every overlapping `start()` call. */
1244
1537
  private startInFlight;
1245
1538
  private stopped;
1539
+ private readonly retryTimers;
1246
1540
  constructor(opts: GatewayRunnerOptions);
1247
1541
  /**
1248
1542
  * Register a slash command. Match rule (EC-A): text === "/" + name
@@ -1278,6 +1572,9 @@ declare class GatewayRunner {
1278
1572
  */
1279
1573
  start(): Promise<StartResult>;
1280
1574
  private runStart;
1575
+ /** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
1576
+ private scheduleReconnect;
1577
+ private reconnectOnce;
1281
1578
  /**
1282
1579
  * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
1283
1580
  * the first failure. Every connect settles before the rollback: rolling back while one is still
@@ -1579,30 +1876,6 @@ interface FenceRegion {
1579
1876
  /** Every fenced region of `text`, in order. */
1580
1877
  declare function scanFences(text: string): readonly FenceRegion[];
1581
1878
 
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
1879
  /**
1607
1880
  * Grapheme-safe splitting of long text that keeps Markdown table rows whole (B-556).
1608
1881
  *
@@ -1720,4 +1993,4 @@ declare function listenerLifecycle(opts: {
1720
1993
  stop(): Promise<void>;
1721
1994
  };
1722
1995
 
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 };
1996
+ 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 QQMessageEvent, 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 XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, toDialect };