@theokit/gateway 0.17.0 → 0.19.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
@@ -830,6 +830,17 @@ interface SendResult {
830
830
  readonly message: string;
831
831
  };
832
832
  }
833
+ /** The facts about an adapter that an app picks its rendering from. */
834
+ interface AdapterCapabilities {
835
+ readonly edit: boolean;
836
+ /** The attachment kinds the adapter sends; `[]` when none. */
837
+ readonly attachments: ReadonlyArray<OutboundAttachment["kind"]>;
838
+ readonly typing: boolean;
839
+ readonly reactions: boolean;
840
+ readonly threads: boolean;
841
+ /** Longest text one message holds; `undefined` when the adapter does not know. */
842
+ readonly maxMessageChars?: number;
843
+ }
833
844
  /**
834
845
  * Abstract base for all platform adapters.
835
846
  *
@@ -957,6 +968,18 @@ declare abstract class BasePlatformAdapter {
957
968
  * `boolean` so that an adapter that sends images can override it with `true`.
958
969
  */
959
970
  readonly supportsAttachments: boolean;
971
+ /**
972
+ * The attachment kinds {@link sendMessage} can send. `undefined` means "not declared": the
973
+ * `capabilities` getter then reports `["image"]` when `supportsAttachments` is `true`, else `[]`.
974
+ */
975
+ protected readonly attachmentKinds: ReadonlyArray<OutboundAttachment["kind"]> | undefined;
976
+ /**
977
+ * What this adapter can do, for an app that renders differently per channel.
978
+ *
979
+ * Derived from the members above and from which lifecycle methods the subclass overrides; an
980
+ * adapter overrides the getter only for what derivation cannot know. Read it at call time.
981
+ */
982
+ get capabilities(): AdapterCapabilities;
960
983
  /**
961
984
  * Replace the text of a message this adapter sent, keeping its id.
962
985
  *
@@ -1106,6 +1129,19 @@ interface WebhookRequest {
1106
1129
  readonly rawBody: string;
1107
1130
  /** Request headers. Descriptors look a header up without regard to case. */
1108
1131
  readonly headers: Readonly<Record<string, string | undefined>>;
1132
+ /** The HTTP method. Always set by `createWebhookHandler`; optional so existing callers compile. */
1133
+ readonly method?: string;
1134
+ /** The full request URL, query included. Always set by `createWebhookHandler`. */
1135
+ readonly url?: string;
1136
+ }
1137
+ /** The answer a channel's `handle` gives for one webhook request. */
1138
+ interface WebhookAnswer {
1139
+ /** The HTTP status. */
1140
+ readonly status: number;
1141
+ /** The response body, when the platform expects one. */
1142
+ readonly body?: string;
1143
+ /** The response `content-type`. */
1144
+ readonly contentType?: string;
1109
1145
  }
1110
1146
  /**
1111
1147
  * What `ingest` did with a verified payload: `"delivered"` dispatched it, `"malformed"` refused it
@@ -1128,7 +1164,22 @@ interface ChannelWebhook<TAdapter extends BasePlatformAdapter> {
1128
1164
  verify(adapter: TAdapter, request: WebhookRequest): boolean;
1129
1165
  /** Dispatch a parsed, verified payload, or report it malformed without dispatching. */
1130
1166
  ingest(adapter: TAdapter, payload: unknown): Promise<IngestResult>;
1167
+ /** Methods the route takes. Default `["POST"]`. */
1168
+ readonly methods?: readonly string[];
1169
+ /** Full control of one request. When absent, the handler runs verify, JSON.parse and ingest. */
1170
+ handle?(adapter: TAdapter, request: WebhookRequest): Promise<WebhookAnswer>;
1131
1171
  }
1172
+ /**
1173
+ * Whether a channel's `sender.id` is proven by the platform. An email From header or an SMS caller
1174
+ * id is written by the sender (CWE-290), so such a channel declares why it cannot be trusted.
1175
+ *
1176
+ * @public
1177
+ */
1178
+ type SenderIdentity = "authenticated"
1179
+ /** Why the sender id can be forged, for error messages. */
1180
+ | {
1181
+ readonly unauthenticated: string;
1182
+ };
1132
1183
  interface ChannelDescriptorBase<TAdapter extends BasePlatformAdapter> {
1133
1184
  /** The platform the built adapter reports as its `platform`. */
1134
1185
  readonly platform: PlatformName;
@@ -1139,6 +1190,11 @@ interface ChannelDescriptorBase<TAdapter extends BasePlatformAdapter> {
1139
1190
  * which `createChannels` reports as a rejected channel; it performs no network call.
1140
1191
  */
1141
1192
  create(config: Readonly<Record<string, unknown>>): TAdapter;
1193
+ /**
1194
+ * Whether `sender.id` is authenticated. Absent means unknown and is treated as not
1195
+ * authenticated (fail closed); it is optional only so descriptors in other packages keep compiling.
1196
+ */
1197
+ readonly senderIdentity?: SenderIdentity;
1142
1198
  }
1143
1199
  /**
1144
1200
  * A channel described as data. A `socket` channel opens its own connection to the platform; a
@@ -1153,6 +1209,13 @@ type ChannelDescriptor<TAdapter extends BasePlatformAdapter = BasePlatformAdapte
1153
1209
  readonly transport: "webhook";
1154
1210
  readonly webhook: ChannelWebhook<TAdapter>;
1155
1211
  });
1212
+ /**
1213
+ * True only when the descriptor declares `senderIdentity: "authenticated"`. An absent or
1214
+ * unauthenticated declaration is false.
1215
+ *
1216
+ * @public
1217
+ */
1218
+ declare function isAuthenticatedSender(descriptor: ChannelDescriptor): boolean;
1156
1219
 
1157
1220
  /**
1158
1221
  * `GatewayConfigurationError` — shared base for per-adapter configuration
@@ -1376,6 +1439,52 @@ interface GatewayHook {
1376
1439
  on_error?(ctx: OnErrorContext): Promise<void> | void;
1377
1440
  }
1378
1441
 
1442
+ /**
1443
+ * Chat command parsing and a single `pre_inbound` hook for many commands.
1444
+ *
1445
+ * Recognises a command behind one leading mention (`<@U123> /help`,
1446
+ * `@bot /help`) and with Telegram's `@botname` suffix (`/help@my_bot`).
1447
+ * The name is matched exactly: `/new chat` is `/new` with arg `chat`,
1448
+ * `/newer` is never `/new`.
1449
+ *
1450
+ * @public
1451
+ */
1452
+
1453
+ /** A parsed chat command. */
1454
+ interface ParsedChatCommand {
1455
+ /** Command name, without the prefix and without `@bot`. */
1456
+ readonly name: string;
1457
+ /** Trimmed rest of the text, `""` when none. */
1458
+ readonly arg: string;
1459
+ }
1460
+ /**
1461
+ * Strips one leading `<@U...>` or `@name` mention and a `@bot` suffix.
1462
+ * Returns `undefined` for text that is not a command.
1463
+ */
1464
+ declare function parseChatCommand(text: string, options?: {
1465
+ prefixes?: ReadonlyArray<string>;
1466
+ }): ParsedChatCommand | undefined;
1467
+ /** One command handled by {@link commandHook}. */
1468
+ interface ChatCommand {
1469
+ readonly name: string;
1470
+ readonly description: string;
1471
+ /** Default `"optional"`. */
1472
+ readonly arg?: "none" | "optional" | "required";
1473
+ /** Usage line shown in help. Default `"/<name>"`. */
1474
+ readonly usage?: string;
1475
+ run(event: MessageEvent, arg: string): HookDecision | undefined | Promise<HookDecision | undefined>;
1476
+ }
1477
+ /** Help text listing every command's usage and description, in declaration order. */
1478
+ declare function helpText(commands: ReadonlyArray<ChatCommand>): string;
1479
+ /**
1480
+ * One `pre_inbound` hook for many commands. Also answers `/help`
1481
+ * (rename with `helpCommand`, disable with `false`).
1482
+ */
1483
+ declare function commandHook(commands: ReadonlyArray<ChatCommand>, options?: {
1484
+ name?: string;
1485
+ helpCommand?: string | false;
1486
+ }): GatewayHook;
1487
+
1379
1488
  /**
1380
1489
  * `HookExecutor` — runs registered gateway hooks at their fire points.
1381
1490
  *
@@ -1480,7 +1589,37 @@ interface GatewayRunnerOptions {
1480
1589
  * @public
1481
1590
  */
1482
1591
  readonly reconnect?: ReconnectPolicy;
1592
+ /**
1593
+ * Under `connectFailure: "isolate"`, give up on one adapter's `connect()` after this many ms. The
1594
+ * adapter is reported `timed_out`, counted in `StartResult.failed`, and never wired for inbound:
1595
+ * if its `connect()` resolves `true` later, the runner disconnects it. With `reconnect` set it is
1596
+ * retried like a transient failure. Ignored under `"rollback"`, as `reconnect` is.
1597
+ *
1598
+ * @public
1599
+ */
1600
+ readonly connectTimeoutMs?: number;
1601
+ /**
1602
+ * Called as each adapter changes state, while `start()` may still be pending. `reason` is
1603
+ * redacted. A callback that throws is ignored. Ignored under `"rollback"`.
1604
+ *
1605
+ * @public
1606
+ */
1607
+ readonly onAdapterState?: (platform: PlatformName, state: AdapterState, reason?: string) => void;
1608
+ /**
1609
+ * Exact credential values masked (longest first) in every reason and log line before
1610
+ * `redactSecrets` runs.
1611
+ *
1612
+ * @public
1613
+ */
1614
+ readonly secrets?: ReadonlyArray<string>;
1483
1615
  }
1616
+ /**
1617
+ * Where one adapter stands under `connectFailure: "isolate"`, as reported to
1618
+ * `GatewayRunnerOptions.onAdapterState`.
1619
+ *
1620
+ * @public
1621
+ */
1622
+ type AdapterState = "connected" | "failed" | "retrying" | "timed_out";
1484
1623
  /**
1485
1624
  * Backoff for `GatewayRunnerOptions.reconnect`. The delay before attempt n is
1486
1625
  * `min(initialDelayMs * factor^(n-1), maxDelayMs)`.
@@ -1537,7 +1676,14 @@ declare class GatewayRunner {
1537
1676
  private startInFlight;
1538
1677
  private stopped;
1539
1678
  private readonly retryTimers;
1679
+ private readonly connectedPlatforms;
1680
+ private readonly redact;
1540
1681
  constructor(opts: GatewayRunnerOptions);
1682
+ /** The registered adapter for a platform, connected or not. */
1683
+ adapter(platform: PlatformName): BasePlatformAdapter | undefined;
1684
+ /** Platforms whose adapter is connected now; updated by connects, retries and `stop()`. */
1685
+ get connected(): ReadonlySet<PlatformName>;
1686
+ private emitState;
1541
1687
  /**
1542
1688
  * Register a slash command. Match rule (EC-A): text === "/" + name
1543
1689
  * OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
@@ -1587,6 +1733,11 @@ declare class GatewayRunner {
1587
1733
  * `a => a.connect()` would let it escape `map` and reject `start()` itself.
1588
1734
  */
1589
1735
  private connectIsolated;
1736
+ /** Connect one adapter, bounded by `connectTimeoutMs`, and report its state as it settles. */
1737
+ private connectOne;
1738
+ /** A connect that finished after the runner gave up on it must not stay connected unseen. */
1739
+ private releaseLateConnect;
1740
+ private classify;
1590
1741
  private wireInbound;
1591
1742
  /**
1592
1743
  * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
@@ -1608,6 +1759,26 @@ declare class GatewayRunner {
1608
1759
  private buildContext;
1609
1760
  }
1610
1761
 
1762
+ /** Options for `withMediaUnderstanding`: the functions that understand media, a size cap and a failure sink. */
1763
+ interface MediaUnderstandingOptions {
1764
+ /** e.g. plugin-voice's transcribe, bound to its config. */
1765
+ transcribe?(audio: {
1766
+ data: Uint8Array;
1767
+ mediaType: string;
1768
+ }): Promise<string>;
1769
+ /** Called for each image an event carries, once inbound images exist. */
1770
+ describeImage?(image: {
1771
+ data: Uint8Array;
1772
+ mediaType: string;
1773
+ }): Promise<string>;
1774
+ /** Largest payload sent to a function. Default 20 MiB; larger is reported as not understood. */
1775
+ readonly maxBytes?: number;
1776
+ /** Where a failure is reported, with the media type and the error name only. */
1777
+ readonly write?: (line: string) => void;
1778
+ }
1779
+ /** Wraps a handler: the event it receives has the transcript or description appended to text. */
1780
+ declare function withMediaUnderstanding(handler: GatewayHandler, options: MediaUnderstandingOptions): GatewayHandler;
1781
+
1611
1782
  /** A credential shape this module masks, and the cost of matching it. */
1612
1783
  interface CoveredShape {
1613
1784
  /** The platform and field, for the reader of the table. */
@@ -1656,6 +1827,17 @@ declare function maskShapes(text: string): string;
1656
1827
  * @returns the redacted string
1657
1828
  */
1658
1829
  declare function redactSecrets(value: unknown): string;
1830
+ /**
1831
+ * Replace each exact value in `secrets` with `[redacted]`, longest value first so a value that
1832
+ * contains another is masked whole. Empty values are ignored. It does not run `redactSecrets`:
1833
+ * call that afterwards, because it shortens some shapes to a head and tail and the masked fragments
1834
+ * would otherwise survive.
1835
+ *
1836
+ * @param text the text to mask
1837
+ * @param secrets the exact credential values configured for this process
1838
+ * @returns the text with every occurrence of every value replaced
1839
+ */
1840
+ declare function maskSecrets(text: string, secrets: ReadonlyArray<string>): string;
1659
1841
 
1660
1842
  /**
1661
1843
  * `SessionRouter` — pure routing logic: `MessageEvent → agentId`
@@ -1694,6 +1876,43 @@ declare class SessionRouter {
1694
1876
  resolveAgentId(event: MessageEvent): string;
1695
1877
  }
1696
1878
 
1879
+ /**
1880
+ * Rule-based agent bindings: pick the agent that answers a message by
1881
+ * platform, account and peer.
1882
+ *
1883
+ * @public
1884
+ */
1885
+
1886
+ interface AgentBindingRule {
1887
+ readonly agent: string;
1888
+ readonly platform?: PlatformName;
1889
+ /** Matched against accountOf(event). */
1890
+ readonly account?: string;
1891
+ /** Matched against event.sender.id for a DM and event.channel.id otherwise. */
1892
+ readonly peer?: string;
1893
+ }
1894
+ /** Options for {@link createAgentBindings}. */
1895
+ interface AgentBindingsOptions {
1896
+ readonly defaultAgent: string;
1897
+ readonly rules: ReadonlyArray<AgentBindingRule>;
1898
+ /** Agents that exist; every rule and the default must name one. */
1899
+ readonly agents: ReadonlyArray<string>;
1900
+ /** Which bot account received the event, when the app runs several. Default: undefined. */
1901
+ readonly accountOf?: (event: MessageEvent) => string | undefined;
1902
+ }
1903
+ /** Chooses the agent that answers an event. */
1904
+ interface AgentBindings {
1905
+ agentFor(event: MessageEvent): string;
1906
+ }
1907
+ /**
1908
+ * Builds bindings from rules. The most specific matching rule wins (peer 4, account 2,
1909
+ * platform 1), ties go to the earlier rule, no match gives `defaultAgent`.
1910
+ * Throws `GatewayConfigurationError` for `unknown_agent` or `empty_binding_rule`.
1911
+ */
1912
+ declare function createAgentBindings(options: AgentBindingsOptions): AgentBindings;
1913
+ /** Prefixes another strategy's key with the bound agent, so two agents never share a session. */
1914
+ declare function bindingStrategy(bindings: AgentBindings, inner: AgentIdStrategy): AgentIdStrategy;
1915
+
1697
1916
  /**
1698
1917
  * What `ChatPresenter` needs to know about one platform: how to rewrite the text, and which
1699
1918
  * `format` to declare on the message (B-019 FR-001, FR-002).
@@ -1887,6 +2106,15 @@ declare function scanFences(text: string): readonly FenceRegion[];
1887
2106
  */
1888
2107
  declare function splitKeepingRows(text: string, partLimit: number): string[];
1889
2108
 
2109
+ /** The outcome of delivering one event to the runner's handlers. */
2110
+ type DeliverOutcome = "ok" | "no_handler" | "handler_threw";
2111
+ /**
2112
+ * Map the outcomes of one delivered batch to an HTTP status, worst wins: `handler_threw` is 500,
2113
+ * `no_handler` is 503 so the provider retries, `ok` and an empty batch are 200. An unknown outcome
2114
+ * throws instead of answering 200.
2115
+ */
2116
+ declare function statusForDeliver(outcomes: ReadonlyArray<DeliverOutcome>): 200 | 500 | 503;
2117
+
1890
2118
  /**
1891
2119
  * The half of an Express webhook server that is the same for every platform.
1892
2120
  *
@@ -1997,4 +2225,31 @@ declare function listenerLifecycle(opts: {
1997
2225
  stop(): Promise<void>;
1998
2226
  };
1999
2227
 
2000
- 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, DEFAULT_WEBHOOK_MAX_BYTES, 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 };
2228
+ /**
2229
+ * `createWebhookHandler` — one Fetch `Request` to `Response` handler for every webhook channel.
2230
+ *
2231
+ * It routes by platform, caps the body, and answers with the descriptor's `handle`, or runs verify,
2232
+ * JSON.parse and ingest. No secret, header value or body reaches `onError` or a response.
2233
+ */
2234
+
2235
+ /** Options for `createWebhookHandler`. */
2236
+ interface WebhookHandlerOptions {
2237
+ /** The built channels; only those with `transport: "webhook"` are routed. */
2238
+ readonly channels: ReadonlyArray<BuiltChannel>;
2239
+ /** Whether the platform's runner has started; a platform that has not answers 503. */
2240
+ readonly isStarted: (platform: PlatformName) => boolean;
2241
+ /** Body cap in bytes. Default 1 MiB. */
2242
+ readonly maxBodyBytes?: number;
2243
+ /** Default: the last path segment after `/webhooks/`. */
2244
+ readonly platformFor?: (url: URL) => PlatformName | undefined;
2245
+ /** Called when a handle/ingest throws; the response is 500 with no body. */
2246
+ readonly onError?: (platform: PlatformName, error: unknown) => void;
2247
+ }
2248
+ /**
2249
+ * Build a Fetch handler for every `transport: "webhook"` channel in `channels`: 404 for an unknown
2250
+ * platform, 503 while it has not started, 405 for a method the route does not take, 413 past the
2251
+ * body cap, 400 for an unreadable body, and 500 with no body when a route throws.
2252
+ */
2253
+ declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
2254
+
2255
+ export { type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, DEFAULT_WEBHOOK_MAX_BYTES, 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 MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, type ReconnectPolicy, type SMSMessageEvent, SeenIds, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TwitchMessageEvent, type UncoveredShape, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelRendering, chunkByGrapheme, chunkText, commandHook, createAgentBindings, createChannels, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };