@theokit/gateway 0.10.0 → 0.12.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
@@ -247,6 +247,89 @@ interface MatrixMessageEvent extends BaseMessageEvent {
247
247
  readonly raw: unknown;
248
248
  };
249
249
  }
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
+ }
250
333
  /**
251
334
  * The open registry every platform's inbound event is filed under.
252
335
  *
@@ -262,7 +345,7 @@ interface MatrixMessageEvent extends BaseMessageEvent {
262
345
  * ```typescript
263
346
  * declare module "@theokit/gateway" {
264
347
  * interface PlatformEventRegistry {
265
- * signal: SignalMessageEvent;
348
+ * acmechat: AcmeChatMessageEvent;
266
349
  * }
267
350
  * }
268
351
  * ```
@@ -280,6 +363,11 @@ interface PlatformEventRegistry {
280
363
  mattermost: MattermostMessageEvent;
281
364
  line: LineMessageEvent;
282
365
  matrix: MatrixMessageEvent;
366
+ signal: SignalMessageEvent;
367
+ imessage: IMessageMessageEvent;
368
+ google_chat: GoogleChatMessageEvent;
369
+ irc: IrcMessageEvent;
370
+ nextcloud_talk: NextcloudTalkMessageEvent;
283
371
  }
284
372
  /**
285
373
  * `true` only for `any` — the one type that would otherwise swallow the union.
@@ -309,7 +397,7 @@ type LiteralKey<K> = string extends K ? never : K;
309
397
  * `TS2339: Property 'telegram' does not exist on type 'never'`.
310
398
  *
311
399
  * It also fixes a second measured defect for free. Mapping over `keyof` directly is HOMOMORPHIC, so
312
- * an OPTIONAL entry (`signal?: Event`, a shape an author writes by accident) kept its modifier and
400
+ * an OPTIONAL entry (`acmechat?: Event`, a shape an author writes by accident) kept its modifier and
313
401
  * injected `undefined` into the union — `TS18048: 'e' is possibly 'undefined'` on a plain `switch`.
314
402
  * Mapping over a computed key set is not homomorphic and drops the modifier. A `-?` was written
315
403
  * here first as an explicit belt; the gate showed it could not be made to matter while this type is
@@ -332,11 +420,11 @@ type LiteralKeysOf<R> = keyof {
332
420
  * earlier version of this docblock said it was — measured false twice over. Filtering the VALUE
333
421
  * alone left two shapes that break every consumer rather than only their author:
334
422
  * `{ [key: string]: … }` made `keyof` yield `string | number`, so the union and the platform name
335
- * both collapsed to `never`; and `signal?: …` kept its optional modifier through a homomorphic
423
+ * both collapsed to `never`; and `acmechat?: …` kept its optional modifier through a homomorphic
336
424
  * mapping and injected `undefined` into the union. Both are handled above — the first by
337
425
  * {@link LiteralKeysOf}, the second by the `-?` on the mapping. What remains true, and is the
338
426
  * honest version of the original claim:
339
- * a `Record<PlatformName, T>` written against the ten still fails to compile, because the rejected
427
+ * a `Record<PlatformName, T>` written against the first-party platforms still fails to compile, because the rejected
340
428
  * key is gone from `PlatformName` while the consumer's literal map is not. What the exclusion buys
341
429
  * is that the failure is a missing-key error at the consumer's own map rather than a silent loss
342
430
  * of narrowing everywhere.
@@ -412,7 +500,8 @@ interface SendResult {
412
500
  * Abstract base for all platform adapters.
413
501
  *
414
502
  * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.
415
- * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden.
503
+ * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden; `editMessage` refuses
504
+ * with `edit_unsupported` unless overridden.
416
505
  *
417
506
  * **Contract:**
418
507
  * - `connect()` is idempotent. Calling twice returns true the second time.
@@ -422,6 +511,15 @@ interface SendResult {
422
511
  * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling
423
512
  * `onInbound` twice replaces the previous handler — does NOT stack.
424
513
  * - `sendMessage` with empty text returns `{ ok: false, code: "empty_text" }`.
514
+ * - `supportsEdit` says whether the adapter has an edit call. It is `false` unless the adapter
515
+ * overrides it, and it MUST NOT change with `connect()`. `true` does not promise that every
516
+ * edit is accepted: an adapter whose injected client lacks the edit call (Matrix) still answers
517
+ * `edit_unsupported`, which a caller handles like any other refusal.
518
+ * - `editMessage` returns a `SendResult` and never throws on platform errors. The default refuses
519
+ * with `edit_unsupported` and makes no platform call.
520
+ * - Edits are not ordered by the adapter. Two edits of one message id in flight at once reach the
521
+ * platform in either order, so a caller awaits each edit before the next, or keeps one in flight
522
+ * and coalesces to the latest text.
425
523
  *
426
524
  * @public
427
525
  */
@@ -442,8 +540,8 @@ declare abstract class BasePlatformAdapter {
442
540
  * process nor the connection. Two adapters used to discard the rejection with `void`, which under
443
541
  * Node's default ends the process, and two more reported it as a platform-client error, sending
444
542
  * whoever debugged their own handler to the wrong repository. Eight had converged on the right
445
- * behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds all
446
- * ten to it.
543
+ * behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds every
544
+ * adapter to it.
447
545
  */
448
546
  abstract onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
449
547
  /**
@@ -476,6 +574,27 @@ declare abstract class BasePlatformAdapter {
476
574
  * is taken from `this.platform`, which is the only part that differed between them.
477
575
  */
478
576
  protected runHandler(handler: ((event: MessageEvent) => Promise<void>) | undefined, event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
577
+ /**
578
+ * Whether {@link editMessage} can replace the text of a message this adapter sent.
579
+ *
580
+ * Read it before starting a preview: on `false`, send the final text instead. An adapter sets
581
+ * it at construction and MUST NOT change it with `connect()`. Annotated as `boolean` so that an
582
+ * edit-capable adapter can override it with `true`.
583
+ */
584
+ readonly supportsEdit: boolean;
585
+ /**
586
+ * Replace the text of a message this adapter sent, keeping its id.
587
+ *
588
+ * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
589
+ * throws on platform errors. An edit-capable adapter applies, with no request, the same local
590
+ * checks its `sendMessage` applies (such as `empty_text`, and `not_connected` where the send
591
+ * checks the connection), plus `invalid_message_id`, and `edit_too_long` where the adapter
592
+ * splits text: an edit that would need more than one platform message is refused, never split.
593
+ *
594
+ * Default: refuses with `edit_unsupported`, makes no platform call, and checks nothing else
595
+ * first, so capability is answered before input.
596
+ */
597
+ editMessage(_messageId: string, _out: OutboundMessage): Promise<SendResult>;
479
598
  /** Lifecycle: emit a typing indicator. Default: noop. */
480
599
  startTyping(_channelId: string): Promise<void>;
481
600
  /** Lifecycle: stop the typing indicator. Default: noop. */
@@ -483,46 +602,80 @@ declare abstract class BasePlatformAdapter {
483
602
  }
484
603
 
485
604
  /**
486
- * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).
605
+ * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).
487
606
  *
488
- * The router holds a map of `platform → adapter` and forwards
489
- * `DeliveryRequest` to the right adapter's `sendMessage`. Composes
490
- * with `Cron` from `@theokit/sdk` for scheduled delivery — the
491
- * router is the "WHERE to send", Cron is the "WHEN to fire".
607
+ * A platform package exports one static descriptor: the config fields its channel needs, how to
608
+ * build its adapter from them, and, for a channel that receives webhooks, how to verify and ingest
609
+ * a request. An app then wires every channel with the same loop (`createChannels`) instead of one
610
+ * branch per platform. The core only reads these shapes; it never names a platform.
492
611
  *
493
612
  * @public
494
613
  */
495
614
 
496
- /** Target for an outbound delivery. */
497
- interface DeliveryTarget {
498
- readonly platform: PlatformName;
499
- readonly channel: {
500
- readonly id: string;
501
- readonly type: "dm" | "group" | "thread";
502
- readonly topicId?: string;
503
- };
615
+ /** One configuration field a channel reads. */
616
+ interface ChannelConfigField {
617
+ /** The key `create` reads from its config object. */
618
+ readonly key: string;
619
+ /** A required field that is absent, `null` or `""` rejects the channel before `create` runs. */
620
+ readonly required: boolean;
621
+ /** The value is a credential: never log it, and keep it out of anything shown to a user. */
622
+ readonly secret: boolean;
623
+ /** What the field is, for a human configuring the channel. */
624
+ readonly description: string;
504
625
  }
505
- /** Full outbound request: target + content. */
506
- interface DeliveryRequest extends DeliveryTarget {
507
- readonly text: string;
508
- readonly format?: "plain" | "markdown" | "html";
509
- readonly replyTo?: string;
626
+ /** A webhook request as the app's HTTP layer received it, before anything parsed the body. */
627
+ interface WebhookRequest {
628
+ /** The exact request bytes as text; signatures are computed over them. */
629
+ readonly rawBody: string;
630
+ /** Request headers. Descriptors look a header up without regard to case. */
631
+ readonly headers: Readonly<Record<string, string | undefined>>;
510
632
  }
511
633
  /**
512
- * Routes outbound requests to the correct adapter.
634
+ * What `ingest` did with a verified payload: `"delivered"` dispatched it, `"malformed"` refused it
635
+ * without dispatching, and `"no_handler"` dispatched nothing because the payload holds a message
636
+ * for the handler and none is subscribed (before the runner starts, after it stops, or for an
637
+ * adapter whose connect failed under `connectFailure: "isolate"`). Answer only `"delivered"` with
638
+ * a success status, so a platform that redelivers can send the rest again.
639
+ */
640
+ type IngestResult = "delivered" | "malformed" | "no_handler";
641
+ /**
642
+ * The webhook half of a channel: verify a request, then hand its payload to the adapter.
513
643
  *
514
- * **Contract:**
515
- * - `register` is last-writer-wins by platform.
516
- * - `send` with unknown platform returns `{ ok: false, code: "no_adapter" }`.
517
- * - `send` never throws on platform errors (delegates to adapter's SendResult).
644
+ * `verify` and `ingest` are declared as methods on purpose. Method parameters are bivariant, which
645
+ * is what lets a descriptor typed for its own adapter class sit in a list of
646
+ * `ChannelDescriptor<BasePlatformAdapter>`; written as function-typed properties, that assignment
647
+ * would fail under `strictFunctionTypes`.
648
+ */
649
+ interface ChannelWebhook<TAdapter extends BasePlatformAdapter> {
650
+ /** `true` when the request carries a valid signature for this adapter's credentials. */
651
+ verify(adapter: TAdapter, request: WebhookRequest): boolean;
652
+ /** Dispatch a parsed, verified payload, or report it malformed without dispatching. */
653
+ ingest(adapter: TAdapter, payload: unknown): Promise<IngestResult>;
654
+ }
655
+ interface ChannelDescriptorBase<TAdapter extends BasePlatformAdapter> {
656
+ /** The platform the built adapter reports as its `platform`. */
657
+ readonly platform: PlatformName;
658
+ /** Every field `create` reads. */
659
+ readonly config: ReadonlyArray<ChannelConfigField>;
660
+ /**
661
+ * Build the adapter. Throws a `GatewayConfigurationError` (or a subclass) for a value it refuses,
662
+ * which `createChannels` reports as a rejected channel; it performs no network call.
663
+ */
664
+ create(config: Readonly<Record<string, unknown>>): TAdapter;
665
+ }
666
+ /**
667
+ * A channel described as data. A `socket` channel opens its own connection to the platform; a
668
+ * `webhook` channel receives requests the app routes to `webhook.verify` and `webhook.ingest`.
518
669
  *
519
670
  * @public
520
671
  */
521
- declare class DeliveryRouter {
522
- private readonly adapters;
523
- register(adapter: BasePlatformAdapter): void;
524
- send(req: DeliveryRequest): Promise<SendResult>;
525
- }
672
+ type ChannelDescriptor<TAdapter extends BasePlatformAdapter = BasePlatformAdapter> = (ChannelDescriptorBase<TAdapter> & {
673
+ readonly transport: "socket";
674
+ readonly webhook?: never;
675
+ }) | (ChannelDescriptorBase<TAdapter> & {
676
+ readonly transport: "webhook";
677
+ readonly webhook: ChannelWebhook<TAdapter>;
678
+ });
526
679
 
527
680
  /**
528
681
  * `GatewayConfigurationError` — shared base for per-adapter configuration
@@ -558,6 +711,97 @@ declare class GatewayConfigurationError extends Error {
558
711
  constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
559
712
  }
560
713
 
714
+ /**
715
+ * `createChannels` — build every configured channel from its descriptor (FR-002 of B-018).
716
+ *
717
+ * One loop replaces the per-platform constructor calls an app used to write. A channel whose
718
+ * configuration is refused lands in `rejected` and the others are still built, so one bad entry
719
+ * never stops the healthy ones. Nothing here connects or performs I/O (NFR-001): connecting is the
720
+ * runner's job, after the app has seen what was rejected.
721
+ *
722
+ * @public
723
+ */
724
+
725
+ /** One channel to build: its descriptor and the configuration the app supplies for it. */
726
+ interface ChannelEntry {
727
+ readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;
728
+ /** Values keyed by the descriptor's field keys. Absent means every required field is missing. */
729
+ readonly config?: Readonly<Record<string, unknown>>;
730
+ }
731
+ /** A channel that was not built, and the configuration error that says why. */
732
+ interface ChannelRejection {
733
+ readonly platform: PlatformName;
734
+ readonly error: GatewayConfigurationError;
735
+ }
736
+ /** What `createChannels` built and what it refused. */
737
+ interface CreateChannelsResult {
738
+ readonly adapters: BasePlatformAdapter[];
739
+ readonly rejected: ChannelRejection[];
740
+ }
741
+ /**
742
+ * Build an adapter for each entry whose required fields are present.
743
+ *
744
+ * An entry missing a required field (absent, `null` or `""`; `0` and `false` count as present) is
745
+ * rejected with a `GatewayConfigurationError` coded `missing_required_config` that names every
746
+ * missing key, and its `create` is never called. A `GatewayConfigurationError` thrown by `create`
747
+ * is reported the same way. Any other throw is a defect, not a configuration fault, and propagates.
748
+ *
749
+ * Only one adapter per platform is built, because the runner routes replies and `stop()` by
750
+ * platform. The first entry built for a platform wins; a later entry for that platform is rejected
751
+ * with a `GatewayConfigurationError` coded `duplicate_channel`, before its required fields are
752
+ * checked, and its `create` is never called. An entry rejected for its configuration built
753
+ * nothing, so it does not claim its platform.
754
+ *
755
+ * The runner keys adapters by the adapter's own `platform`, so an adapter must report the platform
756
+ * its descriptor declares. One that reports another is discarded unconnected and its entry is
757
+ * rejected with a `GatewayConfigurationError` coded `platform_mismatch`; it claims no platform.
758
+ *
759
+ * @public
760
+ */
761
+ declare function createChannels(entries: ReadonlyArray<ChannelEntry>): CreateChannelsResult;
762
+
763
+ /**
764
+ * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).
765
+ *
766
+ * The router holds a map of `platform → adapter` and forwards
767
+ * `DeliveryRequest` to the right adapter's `sendMessage`. Composes
768
+ * with `Cron` from `@theokit/sdk` for scheduled delivery — the
769
+ * router is the "WHERE to send", Cron is the "WHEN to fire".
770
+ *
771
+ * @public
772
+ */
773
+
774
+ /** Target for an outbound delivery. */
775
+ interface DeliveryTarget {
776
+ readonly platform: PlatformName;
777
+ readonly channel: {
778
+ readonly id: string;
779
+ readonly type: "dm" | "group" | "thread";
780
+ readonly topicId?: string;
781
+ };
782
+ }
783
+ /** Full outbound request: target + content. */
784
+ interface DeliveryRequest extends DeliveryTarget {
785
+ readonly text: string;
786
+ readonly format?: "plain" | "markdown" | "html";
787
+ readonly replyTo?: string;
788
+ }
789
+ /**
790
+ * Routes outbound requests to the correct adapter.
791
+ *
792
+ * **Contract:**
793
+ * - `register` is last-writer-wins by platform.
794
+ * - `send` with unknown platform returns `{ ok: false, code: "no_adapter" }`.
795
+ * - `send` never throws on platform errors (delegates to adapter's SendResult).
796
+ *
797
+ * @public
798
+ */
799
+ declare class DeliveryRouter {
800
+ private readonly adapters;
801
+ register(adapter: BasePlatformAdapter): void;
802
+ send(req: DeliveryRequest): Promise<SendResult>;
803
+ }
804
+
561
805
  /**
562
806
  * `GatewayLifecycleError` — a lifecycle method was called from a state that
563
807
  * cannot honour it.
@@ -676,9 +920,11 @@ declare class HookExecutor {
676
920
  * adapter matching `event.platform` (EC-G).
677
921
  *
678
922
  * **Lifecycle:**
679
- * - `start()` connects all adapters in parallel via `Promise.all`. Partial
680
- * failure rolls back: connected adapters get `disconnect()`, then the
681
- * aggregate error rethrows.
923
+ * - `start()` connects all adapters in parallel and resolves a `StartResult`.
924
+ * By default (`connectFailure: "rollback"`) partial failure rolls back:
925
+ * connected adapters get `disconnect()`, then the error rethrows. Under
926
+ * `connectFailure: "isolate"` the adapters that connected keep running and
927
+ * the rest are reported in `StartResult.failed`.
682
928
  * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)
683
929
  * BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner
684
930
  * cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.
@@ -724,6 +970,36 @@ interface GatewayRunnerOptions {
724
970
  * @public
725
971
  */
726
972
  readonly commandPrefixes?: ReadonlyArray<string>;
973
+ /**
974
+ * What `start()` does when an adapter fails to connect. `"rollback"` (the default) disconnects
975
+ * the adapters that did connect and rethrows: all or nothing. `"isolate"` keeps the adapters that
976
+ * connected, wires inbound only for them, and reports the others in the resolved
977
+ * `StartResult.failed`, so one channel that cannot connect does not stop the healthy ones.
978
+ *
979
+ * @public
980
+ */
981
+ readonly connectFailure?: ConnectFailure;
982
+ }
983
+ /**
984
+ * How `GatewayRunner.start()` treats an adapter that fails to connect: `"rollback"` (all or
985
+ * nothing, the default) or `"isolate"` (keep the ones that connected).
986
+ *
987
+ * @public
988
+ */
989
+ type ConnectFailure = "rollback" | "isolate";
990
+ /**
991
+ * What `GatewayRunner.start()` connected. Under `"rollback"` `failed` is always empty, because a
992
+ * failure rejects instead; under `"isolate"` it names each adapter that did not connect and why,
993
+ * with any credential in the reason redacted.
994
+ *
995
+ * @public
996
+ */
997
+ interface StartResult {
998
+ readonly connected: ReadonlyArray<PlatformName>;
999
+ readonly failed: ReadonlyArray<{
1000
+ readonly platform: PlatformName;
1001
+ readonly reason: string;
1002
+ }>;
727
1003
  }
728
1004
  /**
729
1005
  * Holds the registered adapters and dispatches inbound events through
@@ -740,7 +1016,9 @@ declare class GatewayRunner {
740
1016
  private readonly unsubs;
741
1017
  /** Slash command registry: name → handler (word-boundary match, EC-A). */
742
1018
  private readonly commands;
743
- private connected;
1019
+ private startResult;
1020
+ /** The start that has not settled yet, shared by every overlapping `start()` call. */
1021
+ private startInFlight;
744
1022
  private stopped;
745
1023
  constructor(opts: GatewayRunnerOptions);
746
1024
  /**
@@ -751,15 +1029,53 @@ declare class GatewayRunner {
751
1029
  */
752
1030
  command(name: string, handler: GatewayHandler): void;
753
1031
  /**
754
- * Connect all adapters and wire inbound dispatch.
1032
+ * Connect the adapters and wire inbound dispatch for the ones that connected.
1033
+ *
1034
+ * Resolves with what connected. A second call after the first resolved returns the same result
1035
+ * without connecting again.
1036
+ *
1037
+ * Overlapping calls share one start; a start overtaken by stop resolves with no adapter connected.
1038
+ * A call made before `stop()` while another is still connecting connects nothing and settles
1039
+ * with it; a call made after `stop()` throws `runner_stopped`. When `stop()` runs before the
1040
+ * connect settles, the adapters that connected are disconnected, no inbound dispatch is wired,
1041
+ * and the start resolves `{ connected: [], failed }`, keeping the `"isolate"` failures. Under
1042
+ * `"rollback"`, a connect that fails still rejects the start.
1043
+ *
1044
+ * Under `connectFailure: "rollback"`, every connect settles before the rollback, so a failing
1045
+ * start rejects only once its slowest connect settles, as a successful one resolves only then.
1046
+ *
1047
+ * An adapter whose `disconnect()` fails while a start rolls back, or while a start that `stop()`
1048
+ * overtook gives its adapters back, is named on stderr with the error redacted; how the start
1049
+ * settles does not change.
755
1050
  *
756
1051
  * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
757
1052
  * stopped. A stopped runner is spent; construct a new one.
1053
+ * @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after
1054
+ * every connect settled and the adapters that did connect were disconnected.
758
1055
  */
759
- start(): Promise<void>;
1056
+ start(): Promise<StartResult>;
1057
+ private runStart;
1058
+ /**
1059
+ * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
1060
+ * the first failure. Every connect settles before the rollback: rolling back while one is still
1061
+ * pending left that adapter live once it connected.
1062
+ */
1063
+ private connectAllOrRollback;
1064
+ /**
1065
+ * Connect every adapter and keep the ones that connected. The `async` wrapper turns a
1066
+ * synchronous throw inside `connect()` into a rejection `allSettled` sees; a bare
1067
+ * `a => a.connect()` would let it escape `map` and reject `start()` itself.
1068
+ */
1069
+ private connectIsolated;
1070
+ private wireInbound;
760
1071
  /**
761
1072
  * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
762
- * then disconnects adapters. Idempotent (EC-E).
1073
+ * then disconnects adapters. Idempotent (EC-E). A disconnect that fails does not make `stop()`
1074
+ * reject and does not stop the other disconnects; it is written to stderr, redacted, naming the
1075
+ * platform.
1076
+ *
1077
+ * An adapter still connecting under an in-flight start is released when that start settles;
1078
+ * `stop()` does not wait for it.
763
1079
  */
764
1080
  stop(): Promise<void>;
765
1081
  /**
@@ -858,6 +1174,50 @@ declare class SessionRouter {
858
1174
  resolveAgentId(event: MessageEvent): string;
859
1175
  }
860
1176
 
1177
+ /**
1178
+ * What `ChatPresenter` needs to know about one platform: how to rewrite the text, and which
1179
+ * `format` to declare on the message (B-019 FR-001, FR-002).
1180
+ *
1181
+ * `toDialect` alone is not enough, and composing it with the presenter's defaults proved it:
1182
+ * `ChatPresenter` declares `markdown` unless told otherwise, and `toDialect` passes a platform it
1183
+ * was not taught through unchanged. So matrix and email put `**bold**` on the wire as characters
1184
+ * (matrix drops `markdown` with a warning, email escapes it into `<pre>`), and telegram and slack
1185
+ * were handed a bold spelled for a dialect whose bold is a single asterisk. The text rewrite and
1186
+ * the format flag have to be chosen together, per platform, by the package that knows what each
1187
+ * adapter does with `format` — this one.
1188
+ *
1189
+ * Pure data and pure functions: no I/O, and the same input always gives the same output.
1190
+ * `@theokit/gateway` still does not depend on `@theokit/presenter`; `ChannelRendering` matches
1191
+ * the presenter's `translate` and `format` options structurally.
1192
+ */
1193
+
1194
+ /**
1195
+ * The pair a consumer spreads into `ChatPresenter`'s options for one platform.
1196
+ *
1197
+ * @public
1198
+ */
1199
+ interface ChannelRendering {
1200
+ /** The rendering hint the adapter receives as `OutboundMessage.format`. */
1201
+ readonly format: "plain" | "markdown";
1202
+ /** Rewrites the assembled answer for the platform. Pure and deterministic. */
1203
+ readonly translate: (text: string) => string;
1204
+ }
1205
+ /**
1206
+ * The rendering `ChatPresenter` needs for `platform`.
1207
+ *
1208
+ * Only the four inline markers `toDialect` knows are rewritten: bold, italic, strikethrough and
1209
+ * inline code. Headings, links, lists and block quotes pass through on every platform, and fenced
1210
+ * code is not handled yet (the inline-code rule rewrites a fence's backticks).
1211
+ *
1212
+ * @param platform - the destination, typically `event.platform` of the inbound message
1213
+ * @returns the `{ translate, format }` pair for that platform
1214
+ * @throws RangeError when `platform` is not one of the platforms this package knows. Answering with
1215
+ * nothing would let the presenter fall back to identity and `markdown`, which is the defect this
1216
+ * function exists to remove.
1217
+ * @public
1218
+ */
1219
+ declare function channelRendering(platform: PlatformName): ChannelRendering;
1220
+
861
1221
  /**
862
1222
  * `chunkText` — transport-agnostic, boundary-preferring text chunker.
863
1223
  *
@@ -947,37 +1307,6 @@ interface ChunkByGraphemeOptions {
947
1307
  */
948
1308
  declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
949
1309
 
950
- /**
951
- * Markdown → the target channel's own dialect (B-019 FR-005).
952
- *
953
- * ## Why this exists here, and not in an adapter
954
- *
955
- * Measured 2026-09-17 across every `adapter.ts` and `split.ts` in the ten packages: **no package
956
- * transforms a single character of text.** What exists is markdown ESCAPE (discord, mattermost),
957
- * HTML escape (email), phone normalisation (whatsapp) and post-cut newline cleanup (telegram's
958
- * splitter). `OutboundMessage.format` is read by all ten — `adapter-contract.test.ts` proves it —
959
- * but reading a flag is not translating a body.
960
- *
961
- * So the agent answered `**Bom Sucesso (MG)**` and both LINE and WhatsApp delivered the asterisks
962
- * to a real phone. The adapters refuse the translation deliberately and they are right to:
963
- * `gateway-whatsapp` reads `format` only to warn once, because emphasis there is inline in the
964
- * text rather than a transport flag. An adapter is transport.
965
- *
966
- * Translation is PRESENTATION — it depends on what was said and on where it is going at the same
967
- * time — so it belongs to the presenter. It is exported from here as a pure function and CALLED by
968
- * the channel presenter in `theokit`, never the reverse: `@theokit/gateway` must not depend on
969
- * `@theokit/presenter`, or a gateway stops being usable without an agent.
970
- *
971
- * ## What it deliberately does NOT do
972
- *
973
- * It is not a markdown parser. It rewrites the four inline markers that reach a chat surface in
974
- * practice — bold, italic, strikethrough, inline code — and it leaves everything else alone:
975
- * links, headings, lists, block quotes and fenced code are untouched, because no measurement here
976
- * says what they should become on a platform with no equivalent.
977
- *
978
- * A platform it has not been taught is passed through UNCHANGED. Inventing a mapping would be
979
- * wrong invisibly; passing `**bold**` through is wrong where somebody can see it.
980
- */
981
1310
  /**
982
1311
  * Rewrite `text` for `platform`.
983
1312
  *
@@ -1005,7 +1334,7 @@ declare function toDialect(text: string, platform: string): string;
1005
1334
  *
1006
1335
  * The core had no HTTP concern, and `express` is a peer dependency of exactly the two packages that
1007
1336
  * duplicate this — so the obvious objection to putting it here is that it would impose express on
1008
- * all ten adapters.
1337
+ * every adapter.
1009
1338
  *
1010
1339
  * It does not, because nothing here imports express. Every shape below is structural: a request is
1011
1340
  * whatever has `readableEnded` and `on`, a listener is whatever has `listen` and `close`. The
@@ -1020,16 +1349,22 @@ declare function toDialect(text: string, platform: string): string;
1020
1349
  interface RawBodyRequest {
1021
1350
  readonly readableEnded?: boolean;
1022
1351
  readonly complete?: boolean;
1352
+ readonly headers?: Readonly<Record<string, string | string[] | undefined>>;
1023
1353
  setEncoding(encoding: string): unknown;
1024
1354
  on(event: string, listener: (arg: never) => void): unknown;
1025
1355
  }
1026
1356
  /** What a started listener must be able to do. `http.Server` satisfies it. */
1027
1357
  interface ListenerLike {
1028
1358
  close(cb?: (err?: Error) => void): unknown;
1359
+ /** Where Express 4's `listen` reports a failure to bind; `http.Server` has it. */
1360
+ once?(event: "error", listener: (err: Error) => void): unknown;
1029
1361
  }
1030
- /** What can start a listener. Express's app satisfies it. */
1362
+ /**
1363
+ * What can start a listener. Express's app satisfies it: Express 5 passes a failure to bind to the
1364
+ * callback, Express 4 only emits it on the returned server.
1365
+ */
1031
1366
  interface ListenableApp {
1032
- listen(port: number, cb: () => void): ListenerLike;
1367
+ listen(port: number, cb: (err?: Error) => void): ListenerLike;
1033
1368
  }
1034
1369
  /**
1035
1370
  * Load a peer dependency, or fail with a message that says what to install.
@@ -1044,9 +1379,27 @@ declare function loadPeer<T>(load: () => Promise<unknown>, onMissing: () => neve
1044
1379
  * Every provider signs the exact bytes, so a body that was parsed and re-serialised hashes
1045
1380
  * differently and fails verification for a correct request. The bytes are attached as `rawBody`.
1046
1381
  *
1382
+ * With `maxBytes`, a body larger than that many bytes is refused before it is held. The rest of
1383
+ * the stream is read and dropped, and once it ends the middleware answers 413 with the JSON body
1384
+ * `{ "error": "request body too large" }` itself; `next` is not called. A route that must stay
1385
+ * public (a provider dials in) sets it, or any client can stream a body until the heap runs out.
1386
+ * The refusal is answered here rather than handed to `next` as an error because Express's final
1387
+ * handler writes an error as an HTML page carrying its stack whenever `NODE_ENV` is not
1388
+ * `production`, and these routes answer anyone.
1389
+ *
1390
+ * The middleware settles once: after a refusal, more data, the end of the stream or a stream
1391
+ * error do nothing, and after a stream error the end of the stream does nothing.
1392
+ *
1047
1393
  * @param tag the package name for the diagnostic, so a reader knows which router is complaining
1394
+ * @param options `maxBytes`, the largest body accepted; no limit when absent
1395
+ * @throws RangeError when `maxBytes` is not a finite number of zero or more
1048
1396
  */
1049
- declare function rawBodyCapture(tag: string): (rawReq: unknown, _res: unknown, next: (err?: unknown) => void) => void;
1397
+ declare function rawBodyCapture(tag: string, options?: RawBodyCaptureOptions): (rawReq: unknown, rawRes: unknown, next: (err?: unknown) => void) => void;
1398
+ /** Options for {@link rawBodyCapture}. */
1399
+ interface RawBodyCaptureOptions {
1400
+ /** The largest body accepted, in bytes. A larger one is refused with 413. No limit when absent. */
1401
+ readonly maxBytes?: number;
1402
+ }
1050
1403
  /**
1051
1404
  * The start/stop pair, with the latches that make a restart a restart.
1052
1405
  *
@@ -1057,6 +1410,9 @@ declare function rawBodyCapture(tag: string): (rawReq: unknown, _res: unknown, n
1057
1410
  *
1058
1411
  * `injected` is for the case where the caller owns the app: there is no listener to open or close,
1059
1412
  * and `start()`/`stop()` must still be callable and idempotent.
1413
+ *
1414
+ * `start()` rejects with the error the bind failed with (`EADDRINUSE` for a port another listener
1415
+ * holds), under Express 4 and 5 alike, and a later `start()` tries again.
1060
1416
  */
1061
1417
  declare function listenerLifecycle(opts: {
1062
1418
  readonly app: ListenableApp;
@@ -1067,4 +1423,4 @@ declare function listenerLifecycle(opts: {
1067
1423
  stop(): Promise<void>;
1068
1424
  };
1069
1425
 
1070
- export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, CREDENTIAL_SHAPES, type ChunkByGraphemeOptions, type ChunkTextOptions, type CoveredShape, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type RawBodyRequest, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type UncoveredShape, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets, toDialect };
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 };