@theokit/gateway 0.14.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,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,72 @@ 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
+ /** 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
+ }
205
295
  /** Twitch event variant (B-363), a `channel.chat.message` EventSub notification. */
206
296
  interface TwitchMessageEvent extends BaseMessageEvent {
207
297
  readonly platform: "twitch";
@@ -532,6 +622,11 @@ interface PlatformEventRegistry {
532
622
  tlon_urbit: TlonUrbitMessageEvent;
533
623
  twitch: TwitchMessageEvent;
534
624
  zalo_personal: ZaloPersonalMessageEvent;
625
+ zalo: ZaloMessageEvent;
626
+ wechat: WeChatMessageEvent;
627
+ wecom: WeComMessageEvent;
628
+ yuanbao: YuanbaoMessageEvent;
629
+ raft: RaftMessageEvent;
535
630
  clickclack: ClickClackMessageEvent;
536
631
  buzz: BuzzMessageEvent;
537
632
  }
@@ -777,6 +872,33 @@ declare abstract class BasePlatformAdapter {
777
872
  * is taken from `this.platform`, which is the only part that differed between them.
778
873
  */
779
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;
780
902
  /**
781
903
  * Whether {@link editMessage} can replace the text of a message this adapter sent.
782
904
  *
@@ -806,12 +928,114 @@ declare abstract class BasePlatformAdapter {
806
928
  * first, so capability is answered before input.
807
929
  */
808
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>;
809
942
  /** Lifecycle: emit a typing indicator. Default: noop. */
810
943
  startTyping(_channelId: string): Promise<void>;
811
944
  /** Lifecycle: stop the typing indicator. Default: noop. */
812
945
  stopTyping(_channelId: string): Promise<void>;
813
946
  }
814
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
+
815
1039
  /**
816
1040
  * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).
817
1041
  *
@@ -1203,6 +1427,33 @@ interface GatewayRunnerOptions {
1203
1427
  * @public
1204
1428
  */
1205
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;
1206
1457
  }
1207
1458
  /**
1208
1459
  * How `GatewayRunner.start()` treats an adapter that fails to connect: `"rollback"` (all or
@@ -1243,6 +1494,7 @@ declare class GatewayRunner {
1243
1494
  /** The start that has not settled yet, shared by every overlapping `start()` call. */
1244
1495
  private startInFlight;
1245
1496
  private stopped;
1497
+ private readonly retryTimers;
1246
1498
  constructor(opts: GatewayRunnerOptions);
1247
1499
  /**
1248
1500
  * Register a slash command. Match rule (EC-A): text === "/" + name
@@ -1278,6 +1530,9 @@ declare class GatewayRunner {
1278
1530
  */
1279
1531
  start(): Promise<StartResult>;
1280
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;
1281
1536
  /**
1282
1537
  * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
1283
1538
  * the first failure. Every connect settles before the rollback: rolling back while one is still
@@ -1579,30 +1834,6 @@ interface FenceRegion {
1579
1834
  /** Every fenced region of `text`, in order. */
1580
1835
  declare function scanFences(text: string): readonly FenceRegion[];
1581
1836
 
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
1837
  /**
1607
1838
  * Grapheme-safe splitting of long text that keeps Markdown table rows whole (B-556).
1608
1839
  *
@@ -1720,4 +1951,4 @@ declare function listenerLifecycle(opts: {
1720
1951
  stop(): Promise<void>;
1721
1952
  };
1722
1953
 
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 };
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 };