@theokit/gateway 0.10.0 → 0.11.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
@@ -483,46 +483,80 @@ declare abstract class BasePlatformAdapter {
483
483
  }
484
484
 
485
485
  /**
486
- * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).
486
+ * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).
487
487
  *
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".
488
+ * A platform package exports one static descriptor: the config fields its channel needs, how to
489
+ * build its adapter from them, and, for a channel that receives webhooks, how to verify and ingest
490
+ * a request. An app then wires every channel with the same loop (`createChannels`) instead of one
491
+ * branch per platform. The core only reads these shapes; it never names a platform.
492
492
  *
493
493
  * @public
494
494
  */
495
495
 
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
- };
496
+ /** One configuration field a channel reads. */
497
+ interface ChannelConfigField {
498
+ /** The key `create` reads from its config object. */
499
+ readonly key: string;
500
+ /** A required field that is absent, `null` or `""` rejects the channel before `create` runs. */
501
+ readonly required: boolean;
502
+ /** The value is a credential: never log it, and keep it out of anything shown to a user. */
503
+ readonly secret: boolean;
504
+ /** What the field is, for a human configuring the channel. */
505
+ readonly description: string;
504
506
  }
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;
507
+ /** A webhook request as the app's HTTP layer received it, before anything parsed the body. */
508
+ interface WebhookRequest {
509
+ /** The exact request bytes as text; signatures are computed over them. */
510
+ readonly rawBody: string;
511
+ /** Request headers. Descriptors look a header up without regard to case. */
512
+ readonly headers: Readonly<Record<string, string | undefined>>;
510
513
  }
511
514
  /**
512
- * Routes outbound requests to the correct adapter.
515
+ * What `ingest` did with a verified payload: `"delivered"` dispatched it, `"malformed"` refused it
516
+ * without dispatching, and `"no_handler"` dispatched nothing because the payload holds a message
517
+ * for the handler and none is subscribed (before the runner starts, after it stops, or for an
518
+ * adapter whose connect failed under `connectFailure: "isolate"`). Answer only `"delivered"` with
519
+ * a success status, so a platform that redelivers can send the rest again.
520
+ */
521
+ type IngestResult = "delivered" | "malformed" | "no_handler";
522
+ /**
523
+ * The webhook half of a channel: verify a request, then hand its payload to the adapter.
513
524
  *
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).
525
+ * `verify` and `ingest` are declared as methods on purpose. Method parameters are bivariant, which
526
+ * is what lets a descriptor typed for its own adapter class sit in a list of
527
+ * `ChannelDescriptor<BasePlatformAdapter>`; written as function-typed properties, that assignment
528
+ * would fail under `strictFunctionTypes`.
529
+ */
530
+ interface ChannelWebhook<TAdapter extends BasePlatformAdapter> {
531
+ /** `true` when the request carries a valid signature for this adapter's credentials. */
532
+ verify(adapter: TAdapter, request: WebhookRequest): boolean;
533
+ /** Dispatch a parsed, verified payload, or report it malformed without dispatching. */
534
+ ingest(adapter: TAdapter, payload: unknown): Promise<IngestResult>;
535
+ }
536
+ interface ChannelDescriptorBase<TAdapter extends BasePlatformAdapter> {
537
+ /** The platform the built adapter reports as its `platform`. */
538
+ readonly platform: PlatformName;
539
+ /** Every field `create` reads. */
540
+ readonly config: ReadonlyArray<ChannelConfigField>;
541
+ /**
542
+ * Build the adapter. Throws a `GatewayConfigurationError` (or a subclass) for a value it refuses,
543
+ * which `createChannels` reports as a rejected channel; it performs no network call.
544
+ */
545
+ create(config: Readonly<Record<string, unknown>>): TAdapter;
546
+ }
547
+ /**
548
+ * A channel described as data. A `socket` channel opens its own connection to the platform; a
549
+ * `webhook` channel receives requests the app routes to `webhook.verify` and `webhook.ingest`.
518
550
  *
519
551
  * @public
520
552
  */
521
- declare class DeliveryRouter {
522
- private readonly adapters;
523
- register(adapter: BasePlatformAdapter): void;
524
- send(req: DeliveryRequest): Promise<SendResult>;
525
- }
553
+ type ChannelDescriptor<TAdapter extends BasePlatformAdapter = BasePlatformAdapter> = (ChannelDescriptorBase<TAdapter> & {
554
+ readonly transport: "socket";
555
+ readonly webhook?: never;
556
+ }) | (ChannelDescriptorBase<TAdapter> & {
557
+ readonly transport: "webhook";
558
+ readonly webhook: ChannelWebhook<TAdapter>;
559
+ });
526
560
 
527
561
  /**
528
562
  * `GatewayConfigurationError` — shared base for per-adapter configuration
@@ -558,6 +592,87 @@ declare class GatewayConfigurationError extends Error {
558
592
  constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
559
593
  }
560
594
 
595
+ /**
596
+ * `createChannels` — build every configured channel from its descriptor (FR-002 of B-018).
597
+ *
598
+ * One loop replaces the per-platform constructor calls an app used to write. A channel whose
599
+ * configuration is refused lands in `rejected` and the others are still built, so one bad entry
600
+ * never stops the healthy ones. Nothing here connects or performs I/O (NFR-001): connecting is the
601
+ * runner's job, after the app has seen what was rejected.
602
+ *
603
+ * @public
604
+ */
605
+
606
+ /** One channel to build: its descriptor and the configuration the app supplies for it. */
607
+ interface ChannelEntry {
608
+ readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;
609
+ /** Values keyed by the descriptor's field keys. Absent means every required field is missing. */
610
+ readonly config?: Readonly<Record<string, unknown>>;
611
+ }
612
+ /** A channel that was not built, and the configuration error that says why. */
613
+ interface ChannelRejection {
614
+ readonly platform: PlatformName;
615
+ readonly error: GatewayConfigurationError;
616
+ }
617
+ /** What `createChannels` built and what it refused. */
618
+ interface CreateChannelsResult {
619
+ readonly adapters: BasePlatformAdapter[];
620
+ readonly rejected: ChannelRejection[];
621
+ }
622
+ /**
623
+ * Build an adapter for each entry whose required fields are present.
624
+ *
625
+ * An entry missing a required field (absent, `null` or `""`; `0` and `false` count as present) is
626
+ * rejected with a `GatewayConfigurationError` coded `missing_required_config` that names every
627
+ * missing key, and its `create` is never called. A `GatewayConfigurationError` thrown by `create`
628
+ * is reported the same way. Any other throw is a defect, not a configuration fault, and propagates.
629
+ *
630
+ * @public
631
+ */
632
+ declare function createChannels(entries: ReadonlyArray<ChannelEntry>): CreateChannelsResult;
633
+
634
+ /**
635
+ * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).
636
+ *
637
+ * The router holds a map of `platform → adapter` and forwards
638
+ * `DeliveryRequest` to the right adapter's `sendMessage`. Composes
639
+ * with `Cron` from `@theokit/sdk` for scheduled delivery — the
640
+ * router is the "WHERE to send", Cron is the "WHEN to fire".
641
+ *
642
+ * @public
643
+ */
644
+
645
+ /** Target for an outbound delivery. */
646
+ interface DeliveryTarget {
647
+ readonly platform: PlatformName;
648
+ readonly channel: {
649
+ readonly id: string;
650
+ readonly type: "dm" | "group" | "thread";
651
+ readonly topicId?: string;
652
+ };
653
+ }
654
+ /** Full outbound request: target + content. */
655
+ interface DeliveryRequest extends DeliveryTarget {
656
+ readonly text: string;
657
+ readonly format?: "plain" | "markdown" | "html";
658
+ readonly replyTo?: string;
659
+ }
660
+ /**
661
+ * Routes outbound requests to the correct adapter.
662
+ *
663
+ * **Contract:**
664
+ * - `register` is last-writer-wins by platform.
665
+ * - `send` with unknown platform returns `{ ok: false, code: "no_adapter" }`.
666
+ * - `send` never throws on platform errors (delegates to adapter's SendResult).
667
+ *
668
+ * @public
669
+ */
670
+ declare class DeliveryRouter {
671
+ private readonly adapters;
672
+ register(adapter: BasePlatformAdapter): void;
673
+ send(req: DeliveryRequest): Promise<SendResult>;
674
+ }
675
+
561
676
  /**
562
677
  * `GatewayLifecycleError` — a lifecycle method was called from a state that
563
678
  * cannot honour it.
@@ -676,9 +791,11 @@ declare class HookExecutor {
676
791
  * adapter matching `event.platform` (EC-G).
677
792
  *
678
793
  * **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.
794
+ * - `start()` connects all adapters in parallel and resolves a `StartResult`.
795
+ * By default (`connectFailure: "rollback"`) partial failure rolls back:
796
+ * connected adapters get `disconnect()`, then the error rethrows. Under
797
+ * `connectFailure: "isolate"` the adapters that connected keep running and
798
+ * the rest are reported in `StartResult.failed`.
682
799
  * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)
683
800
  * BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner
684
801
  * cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.
@@ -724,6 +841,36 @@ interface GatewayRunnerOptions {
724
841
  * @public
725
842
  */
726
843
  readonly commandPrefixes?: ReadonlyArray<string>;
844
+ /**
845
+ * What `start()` does when an adapter fails to connect. `"rollback"` (the default) disconnects
846
+ * the adapters that did connect and rethrows: all or nothing. `"isolate"` keeps the adapters that
847
+ * connected, wires inbound only for them, and reports the others in the resolved
848
+ * `StartResult.failed`, so one channel that cannot connect does not stop the healthy ones.
849
+ *
850
+ * @public
851
+ */
852
+ readonly connectFailure?: ConnectFailure;
853
+ }
854
+ /**
855
+ * How `GatewayRunner.start()` treats an adapter that fails to connect: `"rollback"` (all or
856
+ * nothing, the default) or `"isolate"` (keep the ones that connected).
857
+ *
858
+ * @public
859
+ */
860
+ type ConnectFailure = "rollback" | "isolate";
861
+ /**
862
+ * What `GatewayRunner.start()` connected. Under `"rollback"` `failed` is always empty, because a
863
+ * failure rejects instead; under `"isolate"` it names each adapter that did not connect and why,
864
+ * with any credential in the reason redacted.
865
+ *
866
+ * @public
867
+ */
868
+ interface StartResult {
869
+ readonly connected: ReadonlyArray<PlatformName>;
870
+ readonly failed: ReadonlyArray<{
871
+ readonly platform: PlatformName;
872
+ readonly reason: string;
873
+ }>;
727
874
  }
728
875
  /**
729
876
  * Holds the registered adapters and dispatches inbound events through
@@ -740,7 +887,7 @@ declare class GatewayRunner {
740
887
  private readonly unsubs;
741
888
  /** Slash command registry: name → handler (word-boundary match, EC-A). */
742
889
  private readonly commands;
743
- private connected;
890
+ private startResult;
744
891
  private stopped;
745
892
  constructor(opts: GatewayRunnerOptions);
746
893
  /**
@@ -751,12 +898,26 @@ declare class GatewayRunner {
751
898
  */
752
899
  command(name: string, handler: GatewayHandler): void;
753
900
  /**
754
- * Connect all adapters and wire inbound dispatch.
901
+ * Connect the adapters and wire inbound dispatch for the ones that connected.
902
+ *
903
+ * Resolves with what connected. A second call after the first resolved returns the same result
904
+ * without connecting again.
755
905
  *
756
906
  * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
757
907
  * stopped. A stopped runner is spent; construct a new one.
908
+ * @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after the
909
+ * adapters that did connect were disconnected.
758
910
  */
759
- start(): Promise<void>;
911
+ start(): Promise<StartResult>;
912
+ /** All or nothing: one failure disconnects the adapters already open, then rethrows. */
913
+ private connectAllOrRollback;
914
+ /**
915
+ * Connect every adapter and keep the ones that connected. The `async` wrapper turns a
916
+ * synchronous throw inside `connect()` into a rejection `allSettled` sees; a bare
917
+ * `a => a.connect()` would let it escape `map` and reject `start()` itself.
918
+ */
919
+ private connectIsolated;
920
+ private wireInbound;
760
921
  /**
761
922
  * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
762
923
  * then disconnects adapters. Idempotent (EC-E).
@@ -858,6 +1019,50 @@ declare class SessionRouter {
858
1019
  resolveAgentId(event: MessageEvent): string;
859
1020
  }
860
1021
 
1022
+ /**
1023
+ * What `ChatPresenter` needs to know about one platform: how to rewrite the text, and which
1024
+ * `format` to declare on the message (B-019 FR-001, FR-002).
1025
+ *
1026
+ * `toDialect` alone is not enough, and composing it with the presenter's defaults proved it:
1027
+ * `ChatPresenter` declares `markdown` unless told otherwise, and `toDialect` passes a platform it
1028
+ * was not taught through unchanged. So matrix and email put `**bold**` on the wire as characters
1029
+ * (matrix drops `markdown` with a warning, email escapes it into `<pre>`), and telegram and slack
1030
+ * were handed a bold spelled for a dialect whose bold is a single asterisk. The text rewrite and
1031
+ * the format flag have to be chosen together, per platform, by the package that knows what each
1032
+ * adapter does with `format` — this one.
1033
+ *
1034
+ * Pure data and pure functions: no I/O, and the same input always gives the same output.
1035
+ * `@theokit/gateway` still does not depend on `@theokit/presenter`; `ChannelRendering` matches
1036
+ * the presenter's `translate` and `format` options structurally.
1037
+ */
1038
+
1039
+ /**
1040
+ * The pair a consumer spreads into `ChatPresenter`'s options for one platform.
1041
+ *
1042
+ * @public
1043
+ */
1044
+ interface ChannelRendering {
1045
+ /** The rendering hint the adapter receives as `OutboundMessage.format`. */
1046
+ readonly format: "plain" | "markdown";
1047
+ /** Rewrites the assembled answer for the platform. Pure and deterministic. */
1048
+ readonly translate: (text: string) => string;
1049
+ }
1050
+ /**
1051
+ * The rendering `ChatPresenter` needs for `platform`.
1052
+ *
1053
+ * Only the four inline markers `toDialect` knows are rewritten: bold, italic, strikethrough and
1054
+ * inline code. Headings, links, lists and block quotes pass through on every platform, and fenced
1055
+ * code is not handled yet (the inline-code rule rewrites a fence's backticks).
1056
+ *
1057
+ * @param platform - the destination, typically `event.platform` of the inbound message
1058
+ * @returns the `{ translate, format }` pair for that platform
1059
+ * @throws RangeError when `platform` is not one of the ten this package knows. Answering with
1060
+ * nothing would let the presenter fall back to identity and `markdown`, which is the defect this
1061
+ * function exists to remove.
1062
+ * @public
1063
+ */
1064
+ declare function channelRendering(platform: PlatformName): ChannelRendering;
1065
+
861
1066
  /**
862
1067
  * `chunkText` — transport-agnostic, boundary-preferring text chunker.
863
1068
  *
@@ -947,37 +1152,6 @@ interface ChunkByGraphemeOptions {
947
1152
  */
948
1153
  declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
949
1154
 
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
1155
  /**
982
1156
  * Rewrite `text` for `platform`.
983
1157
  *
@@ -1067,4 +1241,4 @@ declare function listenerLifecycle(opts: {
1067
1241
  stop(): Promise<void>;
1068
1242
  };
1069
1243
 
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 };
1244
+ 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 HookDecision, HookExecutor, type HookName, type IngestResult, 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 StartResult, type TeamsMessageEvent, type TelegramMessageEvent, type UncoveredShape, type WebhookRequest, type WhatsAppMessageEvent, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets, toDialect };