@theokit/gateway 0.7.1 → 0.9.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/CHANGELOG.md +121 -0
- package/README.md +82 -0
- package/dist/index.cjs +212 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +177 -8
- package/dist/index.d.ts +177 -8
- package/dist/index.js +207 -6
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/errors/config-error.ts","../src/errors/lifecycle-error.ts","../src/hooks/executor.ts","../src/runner/gateway-runner.ts","../src/session/router.ts","../src/text/chunk.ts"],"names":["Security","parts"],"mappings":";;;;;AAqDO,IAAe,sBAAf,MAAmC;AAAA;AAAA,EA2BxC,MAAM,YAAY,UAAA,EAAmC;AAAA,EAErD;AAAA;AAAA,EAGA,MAAM,WAAW,UAAA,EAAmC;AAAA,EAEpD;AACF;;;AC/CO,IAAM,iBAAN,MAAqB;AAAA,EACT,QAAA,uBAAe,GAAA,EAAuC;AAAA,EAEvE,SAAS,OAAA,EAAoC;AAC3C,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,QAAA,EAAU,OAAO,CAAA;AAAA,EAC7C;AAAA,EAEA,MAAM,KAAK,GAAA,EAA2C;AACpD,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,IAAI,QAAQ,CAAA;AAC9C,IAAA,IAAI,YAAY,MAAA,EAAW;AACzB,MAAA,OAAO;AAAA,QACL,EAAA,EAAI,KAAA;AAAA,QACJ,KAAA,EAAO,EAAE,IAAA,EAAM,YAAA,EAAc,SAAS,CAAA,yBAAA,EAA4B,GAAA,CAAI,QAAQ,CAAA,CAAA,CAAA;AAAI,OACpF;AAAA,IACF;AACA,IAAA,OAAO,QAAQ,WAAA,C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,IAAI,CAAA,EAAG;AACjD,IAAA,IAAI,GAAA,CAAI,MAAA,GAAS,OAAA,CAAQ,MAAA,GAAS,SAAA,EAAW;AAC3C,MAAA,IAAI,GAAA,CAAI,MAAA,GAAS,CAAA,EAAG,KAAA,CAAM,KAAK,GAAG,CAAA;AAClC,MAAA,GAAA,GAAM,EAAA;AAAA,IACR;AACA,IAAA,GAAA,IAAO,OAAA;AAAA,EACT;AACA,EAAA,IAAI,GAAA,CAAI,MAAA,GAAS,CAAA,EAAG,KAAA,CAAM,KAAK,GAAG,CAAA;AAClC,EAAA,OAAO,KAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * `BasePlatformAdapter` — contract every transport adapter implements\n * (T1.2, ADR D172).\n *\n * Adapters share ~30% of lifecycle code (typing indicators, event\n * normalization patterns). An abstract class with concrete defaults\n * + abstract hooks is the right shape — interface-only would force\n * every adapter to copy the defaults.\n *\n * Consumers use it via `instanceof` and the public subclass exports\n * (`TelegramAdapter`, `DiscordAdapter`, ...).\n */\n\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Outbound message shape — what `sendMessage` accepts. */\nexport interface OutboundMessage {\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n readonly text: string;\n /** Markdown / HTML rendering hint. Default \"plain\". */\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n /** Optional reply target. */\n readonly replyTo?: string;\n}\n\n/** Send result — adapters return this instead of throwing on platform errors. */\nexport interface SendResult {\n readonly ok: boolean;\n readonly messageId?: string;\n readonly error?: { readonly code: string; readonly message: string };\n}\n\n/**\n * Abstract base for all platform adapters.\n *\n * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.\n * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden.\n *\n * **Contract:**\n * - `connect()` is idempotent. Calling twice returns true the second time.\n * - `disconnect()` is idempotent.\n * - `sendMessage` returns a `SendResult`; it MUST NOT throw on platform errors\n * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.\n * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling\n * `onInbound` twice replaces the previous handler — does NOT stack.\n * - `sendMessage` with empty text returns `{ ok: false, code: \"empty_text\" }`.\n *\n * @public\n */\nexport abstract class BasePlatformAdapter {\n abstract readonly platform: PlatformName;\n\n /** Open the connection. Returns `true` on success; never throws. */\n abstract connect(): Promise<boolean>;\n\n /** Close the connection. Idempotent; safe to call when never connected. */\n abstract disconnect(): Promise<void>;\n\n /** Send a message. Returns a `SendResult`; never throws on platform errors. */\n abstract sendMessage(out: OutboundMessage): Promise<SendResult>;\n\n /**\n * Subscribe to inbound events. Returns an unsubscribe function.\n * EC-H: second call REPLACES the previous handler (does not stack).\n *\n * The handler is user code and may throw. An adapter MUST contain that throw, report it as the\n * HANDLER's failure — not the platform's — and keep delivering: one bad message never ends the\n * process nor the connection. Two adapters used to discard the rejection with `void`, which under\n * Node's default ends the process, and two more reported it as a platform-client error, sending\n * whoever debugged their own handler to the wrong repository. Eight had converged on the right\n * behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds all\n * ten to it.\n */\n abstract onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void;\n\n /** Lifecycle: emit a typing indicator. Default: noop. */\n async startTyping(_channelId: string): Promise<void> {\n /* override */\n }\n\n /** Lifecycle: stop the typing indicator. Default: noop. */\n async stopTyping(_channelId: string): Promise<void> {\n /* override */\n }\n}\n","/**\n * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).\n *\n * The router holds a map of `platform → adapter` and forwards\n * `DeliveryRequest` to the right adapter's `sendMessage`. Composes\n * with `Cron` from `@theokit/sdk` for scheduled delivery — the\n * router is the \"WHERE to send\", Cron is the \"WHEN to fire\".\n *\n * @public\n */\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** Target for an outbound delivery. */\nexport interface DeliveryTarget {\n readonly platform: PlatformName;\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n}\n\n/** Full outbound request: target + content. */\nexport interface DeliveryRequest extends DeliveryTarget {\n readonly text: string;\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n readonly replyTo?: string;\n}\n\n/**\n * Routes outbound requests to the correct adapter.\n *\n * **Contract:**\n * - `register` is last-writer-wins by platform.\n * - `send` with unknown platform returns `{ ok: false, code: \"no_adapter\" }`.\n * - `send` never throws on platform errors (delegates to adapter's SendResult).\n *\n * @public\n */\nexport class DeliveryRouter {\n private readonly adapters = new Map<PlatformName, BasePlatformAdapter>();\n\n register(adapter: BasePlatformAdapter): void {\n this.adapters.set(adapter.platform, adapter);\n }\n\n async send(req: DeliveryRequest): Promise<SendResult> {\n const adapter = this.adapters.get(req.platform);\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for platform \"${req.platform}\"` },\n };\n }\n return adapter.sendMessage({\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n });\n }\n}\n","/**\n * `GatewayConfigurationError` — shared base for per-adapter configuration\n * errors (roadmap M0/M2).\n *\n * Every platform adapter previously defined an identical\n * `ConfigurationError extends Error` (same `code`/`detail` fields, same\n * options interface, same `` `${pkg}: ${code}` `` default message) — only the\n * package prefix differed. This base single-sources that contract. Adapters\n * extend it, pin their prefix, and keep `name = \"ConfigurationError\"` plus\n * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).\n *\n * @public\n */\n\n/** Public input shape for the {@link GatewayConfigurationError} constructor. */\nexport interface GatewayConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\n/**\n * Base configuration error. Not thrown directly by adapters — they subclass it\n * with a fixed package prefix.\n */\nexport class GatewayConfigurationError extends Error {\n override readonly name: string = \"GatewayConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n\n /**\n * @param prefix Package prefix used in the default message (e.g. `\"gateway-line\"`).\n * @param opts `code` (required), optional explicit `message`, optional `detail`.\n */\n constructor(prefix: string, opts: GatewayConfigurationErrorOptions) {\n super(opts.message ?? `${prefix}: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n","/**\n * `GatewayLifecycleError` — a lifecycle method was called from a state that\n * cannot honour it.\n *\n * Distinct from {@link GatewayConfigurationError}, which reports a bad or\n * missing setting at construction time. This one reports a legal call made at\n * an illegal moment: the configuration is fine, the ordering is not.\n *\n * It exists because the alternative is worse than an error. `GatewayRunner`\n * used to accept `start()` after `stop()` and quietly produce a runner that\n * reconnected its adapters and then refused to disconnect them — a leak that\n * reported success. Failing loudly at the call that cannot be honoured is the\n * only outcome a caller can act on.\n *\n * @public\n */\n\n/** Public input shape for the {@link GatewayLifecycleError} constructor. */\nexport interface GatewayLifecycleErrorOptions {\n /** Stable, machine-readable discriminator (e.g. `\"runner_stopped\"`). */\n readonly code: string;\n /** Human-readable explanation, including what the caller should do instead. */\n readonly message: string;\n}\n\n/**\n * Thrown when a lifecycle transition is not available from the current state.\n *\n * @public\n */\nexport class GatewayLifecycleError extends Error {\n override readonly name: string = \"GatewayLifecycleError\";\n /** Stable discriminator, so callers branch on `code` rather than on message text. */\n readonly code: string;\n\n constructor(opts: GatewayLifecycleErrorOptions) {\n super(opts.message);\n this.code = opts.code;\n }\n}\n","/**\n * `HookExecutor` — runs registered gateway hooks at their fire points.\n *\n * Split out of `hooks/types.ts` (which now holds the contract only) so the\n * filename predicts its contents: interfaces live in `types.ts`, the run\n * engine lives here. Behavior is identical to the previous colocated class.\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type {\n GatewayHook,\n HookDecision,\n OnErrorContext,\n PostOutboundContext,\n PreInboundContext,\n} from \"./types.js\";\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {}\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n // `GatewayRunner.dispatch` replies with this message straight into the\n // chat, so it must never carry the exception text. It used to:\n // `hook ${h.name} threw: ${err.message}` sent whatever the hook happened\n // to throw — connection strings, internal ids, bearer tokens — to the end\n // user verbatim. The sibling handler path already logs through\n // `Security.redact` (EC-F); this one skipped redaction entirely, and the\n // test asserting the raw text appeared locked the leak in as expected\n // behaviour.\n //\n // The detail is not lost, only moved: stderr gets it, redacted.\n process.stderr.write(\n `[gateway] pre_inbound hook \"${h.name}\" threw: ${Security.redact((err as Error).message)}\\n`,\n );\n return {\n block: true,\n message: `Request blocked: hook \"${h.name}\" failed.`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner\n * cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).\n *\n * Every reply — the handler's `ctx.reply` and the EC-D auto-reply alike — fires\n * `post_outbound` with the event, the outbound and the adapter's result, once\n * per attempt. The hook observes the delivery; it cannot change what the caller\n * of `reply` receives.\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, OutboundMessage, SendResult } from \"../adapter/base.js\";\nimport { GatewayLifecycleError } from \"../errors/lifecycle-error.js\";\nimport { HookExecutor } from \"../hooks/executor.js\";\nimport type { GatewayHook } from \"../hooks/types.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /**\n * Connect all adapters and wire inbound dispatch.\n *\n * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already\n * stopped. A stopped runner is spent; construct a new one.\n */\n async start(): Promise<void> {\n if (this.stopped) {\n // Silently reconnecting here is what produced the unstoppable runner:\n // `stop()` cleared `connected` but never `stopped`, so a second start()\n // passed the guard below and rewired everything, while the next stop()\n // returned at its own guard without disconnecting anything (#39).\n throw new GatewayLifecycleError({\n code: \"runner_stopped\",\n message:\n \"GatewayRunner.start(): this runner has already been stopped and cannot be restarted. Construct a new GatewayRunner instead.\",\n });\n }\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n // The loser of the race has to be cancelled explicitly. `Promise.race`\n // settles on the first branch and abandons the other, but an abandoned\n // `setTimeout` is still a scheduled timer, and a scheduled timer keeps\n // Node's event loop alive: `stop()` returned in 0ms while the process\n // only exited `drainMs` later, so a bot stopping on SIGINT hung for the\n // whole drain window before dying (#37).\n let timer: NodeJS.Timeout | undefined;\n try {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => {\n timer = setTimeout(r, drainMs);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(\n `[gateway] handler error: ${Security.redact((err as Error).message)}\\n`,\n );\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n return {\n event,\n reply: async (text, opts) =>\n this.deliver(event, {\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n }),\n };\n }\n\n /**\n * Send one outbound on behalf of `event` and report it to `post_outbound`.\n *\n * Every reply leaves through here so the hook fires exactly once per attempt —\n * including the EC-D auto-reply, and including the attempt that finds no\n * adapter for the platform. An audit hook that counted only the deliveries\n * which reached a transport would omit precisely the ones that went nowhere.\n *\n * `post_outbound` observes; it does not intercept. The adapter's `SendResult`\n * is returned to the caller unchanged, and `HookExecutor` already contains a\n * throwing hook, so a broken observer cannot turn a delivered reply into a\n * failed one.\n *\n * @internal\n */\n private async deliver(\n event: GatewayMessageEvent,\n outbound: OutboundMessage,\n ): Promise<SendResult> {\n const adapter = this.adaptersByPlatform.get(event.platform);\n const result: SendResult =\n adapter === undefined\n ? { ok: false, error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` } }\n : await adapter.sendMessage(outbound);\n await this.hookExecutor.firePostOutbound({ event, outbound, result });\n return result;\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n","/**\n * `chunkText` — transport-agnostic, boundary-preferring text chunker.\n *\n * Single-sources the message-splitting knowledge that was copy-pasted across\n * the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two\n * boundary-search families that existed in the adapters:\n *\n * - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\" → \" \"`, UTF-16 surrogate-pair guard,\n * leading-whitespace strip on continuation, optional part-trim.\n * - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\"` (no space), no surrogate guard,\n * leading-newline strip on continuation.\n *\n * The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different\n * algorithm and is intentionally NOT folded in here — those adapters keep their\n * grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.\n *\n * @public\n */\n\n/** Options for {@link chunkText}. */\nexport interface ChunkTextOptions {\n /**\n * Hard cap. If the whole input is `<= limit`, it is returned as a single\n * chunk (subject to `trimParts`). Continuation chunks are cut within the\n * `safeLimit` window.\n */\n readonly limit: number;\n /**\n * Soft window each cut searches within. Defaults to `limit`. The Telegram\n * family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).\n */\n readonly safeLimit?: number;\n /**\n * Boundary strings tried, in order, from most to least preferred. A boundary\n * is accepted once its position is `>= window * 0.5`; otherwise the next one\n * is tried. Default: `[\"\\n\\n\", \"\\n\", \" \"]`.\n */\n readonly boundaries?: readonly string[];\n /**\n * When no boundary reaches the half-window threshold:\n * - `\"last-boundary\"` — use the last computed boundary if it is `> 0`,\n * else fall back to the window edge (Slack family).\n * - `\"window\"` — fall back straight to the window edge (Telegram family).\n * Default: `\"window\"`.\n */\n readonly lastResort?: \"last-boundary\" | \"window\";\n /**\n * Guard against slicing through a UTF-16 low surrogate (splitting an emoji).\n * Default: `false`.\n */\n readonly surrogateGuard?: boolean;\n /**\n * Pattern stripped from the START of each continuation chunk. Default `/^\\n+/`\n * (Telegram family). Slack family uses `/^\\s+/`.\n */\n readonly stripLeading?: RegExp;\n /**\n * When true, each resulting part is `.trim()`-ed and empty parts are dropped\n * (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.\n */\n readonly trimParts?: boolean;\n}\n\n/** Most-preferred boundary at `>= window*0.5`, else the last boundary tried. */\nfunction searchBoundary(remaining: string, window: number, boundaries: readonly string[]): number {\n let cut = window;\n for (const b of boundaries) {\n cut = remaining.lastIndexOf(b, window);\n if (cut >= window * 0.5) return cut;\n }\n return cut;\n}\n\n/** Fail fast on a non-positive / non-integer size argument. */\nfunction assertPositiveInt(label: string, value: number): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new RangeError(`${label} must be a positive integer, received ${value}`);\n }\n}\n\n/** Step back one code unit if `cut` would sever a UTF-16 surrogate pair. */\nfunction guardSurrogate(text: string, cut: number): number {\n if (cut >= text.length) return cut;\n const code = text.charCodeAt(cut);\n return code >= 0xdc00 && code <= 0xdfff ? cut - 1 : cut;\n}\n\nfunction findCut(\n remaining: string,\n window: number,\n boundaries: readonly string[],\n lastResort: \"last-boundary\" | \"window\",\n surrogateGuard: boolean,\n): number {\n let cut = searchBoundary(remaining, window, boundaries);\n if (cut < window * 0.5) {\n cut = lastResort === \"last-boundary\" && cut > 0 ? cut : window;\n }\n if (surrogateGuard) cut = guardSurrogate(remaining, cut);\n return cut <= 0 ? window : cut;\n}\n\n/**\n * Split `text` into chunks no longer than the configured window, preferring\n * natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.\n */\nexport function chunkText(text: string, options: ChunkTextOptions): string[] {\n const {\n limit,\n safeLimit = limit,\n boundaries = [\"\\n\\n\", \"\\n\", \" \"],\n lastResort = \"window\",\n surrogateGuard = false,\n stripLeading = /^\\n+/,\n trimParts = false,\n } = options;\n\n // Fail fast at the boundary: a non-positive `limit` would make `findCut`\n // return 0 forever and hang the loop; `safeLimit > limit` would break the\n // \"hard cap\" contract by emitting an oversized tail chunk.\n assertPositiveInt(\"chunkText: limit\", limit);\n assertPositiveInt(\"chunkText: safeLimit\", safeLimit);\n if (safeLimit > limit) {\n throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);\n }\n\n const finalize = (parts: string[]): string[] =>\n trimParts ? parts.map((p) => p.trim()).filter((p) => p.length > 0) : parts;\n\n if (text.length <= limit) {\n return finalize([text]);\n }\n\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > safeLimit) {\n const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);\n parts.push(remaining.slice(0, cut));\n remaining = remaining.slice(cut).replace(stripLeading, \"\");\n }\n if (remaining.length > 0) parts.push(remaining);\n return finalize(parts);\n}\n\n/** Options for {@link chunkByGrapheme}. */\nexport interface ChunkByGraphemeOptions {\n /** If `text.length <= limit`, it is returned as a single chunk. */\n readonly limit: number;\n /**\n * Max length per emitted part during the grapheme walk. Defaults to `limit`.\n * Callers that reserve room for a per-part prefix (e.g. SMS `\"(i/N) \"`) pass a\n * `partLimit` below `limit`.\n */\n readonly partLimit?: number;\n}\n\n/**\n * Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,\n * regional-indicator pair, or combining sequence. Distinct algorithm from\n * {@link chunkText} — used by adapters that must respect grapheme boundaries\n * (LINE, SMS) rather than search for whitespace boundaries.\n *\n * @public\n */\nexport function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[] {\n const { limit, partLimit = limit } = options;\n assertPositiveInt(\"chunkByGrapheme: limit\", limit);\n assertPositiveInt(\"chunkByGrapheme: partLimit\", partLimit);\n if (text.length === 0) return [\"\"];\n if (text.length <= limit) return [text];\n\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const parts: string[] = [];\n let buf = \"\";\n for (const { segment } of segmenter.segment(text)) {\n if (buf.length + segment.length > partLimit) {\n if (buf.length > 0) parts.push(buf);\n buf = \"\";\n }\n buf += segment;\n }\n if (buf.length > 0) parts.push(buf);\n return parts;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/errors/config-error.ts","../src/errors/lifecycle-error.ts","../src/security/credential-patterns.ts","../src/hooks/executor.ts","../src/runner/gateway-runner.ts","../src/session/router.ts","../src/text/chunk.ts","../src/webhook/express-server.ts"],"names":["Security","parts"],"mappings":";;;;;AAqDO,IAAe,sBAAf,MAAmC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwDxC,MAAgB,UAAA,CACd,OAAA,EACA,KAAA,EACgD;AAChD,IAAA,IAAI,OAAA,KAAY,QAAW,OAAO,YAAA;AAClC,IAAA,IAAI;AACF,MAAA,MAAM,QAAQ,KAAK,CAAA;AAAA,IACrB,SAAS,GAA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A,GAAU,KAAA;AACV,MAAA,MAAM,OAAA,GAAU,QAAA;AAChB,MAAA,QAAA,GAAW,MAAA;AACX,MAAA,IAAI,YAAY,MAAA,EAAW;AAC3B,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,OAAA,CAAQ,KAAA,CAAM,MAAM,OAAA,EAAS,CAAA;AAAA,MAC/B,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * `BasePlatformAdapter` — contract every transport adapter implements\n * (T1.2, ADR D172).\n *\n * Adapters share ~30% of lifecycle code (typing indicators, event\n * normalization patterns). An abstract class with concrete defaults\n * + abstract hooks is the right shape — interface-only would force\n * every adapter to copy the defaults.\n *\n * Consumers use it via `instanceof` and the public subclass exports\n * (`TelegramAdapter`, `DiscordAdapter`, ...).\n */\n\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Outbound message shape — what `sendMessage` accepts. */\nexport interface OutboundMessage {\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n readonly text: string;\n /** Markdown / HTML rendering hint. Default \"plain\". */\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n /** Optional reply target. */\n readonly replyTo?: string;\n}\n\n/** Send result — adapters return this instead of throwing on platform errors. */\nexport interface SendResult {\n readonly ok: boolean;\n readonly messageId?: string;\n readonly error?: { readonly code: string; readonly message: string };\n}\n\n/**\n * Abstract base for all platform adapters.\n *\n * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.\n * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden.\n *\n * **Contract:**\n * - `connect()` is idempotent. Calling twice returns true the second time.\n * - `disconnect()` is idempotent.\n * - `sendMessage` returns a `SendResult`; it MUST NOT throw on platform errors\n * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.\n * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling\n * `onInbound` twice replaces the previous handler — does NOT stack.\n * - `sendMessage` with empty text returns `{ ok: false, code: \"empty_text\" }`.\n *\n * @public\n */\nexport abstract class BasePlatformAdapter {\n abstract readonly platform: PlatformName;\n\n /** Open the connection. Returns `true` on success; never throws. */\n abstract connect(): Promise<boolean>;\n\n /** Close the connection. Idempotent; safe to call when never connected. */\n abstract disconnect(): Promise<void>;\n\n /** Send a message. Returns a `SendResult`; never throws on platform errors. */\n abstract sendMessage(out: OutboundMessage): Promise<SendResult>;\n\n /**\n * Subscribe to inbound events. Returns an unsubscribe function.\n * EC-H: second call REPLACES the previous handler (does not stack).\n *\n * The handler is user code and may throw. An adapter MUST contain that throw, report it as the\n * HANDLER's failure — not the platform's — and keep delivering: one bad message never ends the\n * process nor the connection. Two adapters used to discard the rejection with `void`, which under\n * Node's default ends the process, and two more reported it as a platform-client error, sending\n * whoever debugged their own handler to the wrong repository. Eight had converged on the right\n * behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds all\n * ten to it.\n */\n abstract onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void;\n\n /**\n * Deliver an inbound event that arrived OUT OF BAND, and report what the handler did with it.\n *\n * Six adapters self-deliver once connected — long polling, a gateway socket, Socket Mode, a sync\n * loop, IMAP. The webhook platforms cannot: the payload arrives on an HTTP route the application\n * owns, and until this existed there was no supported call that joined the two. `onInbound` had no\n * public counterpart, so `GatewayRunner` was reachable for eight platforms and not for LINE or\n * WhatsApp Cloud, which every app then wired by hand beside the runner instead of through it\n * (#83).\n *\n * The return value distinguishes the three outcomes a caller can act on, because they are not the\n * same problem: nobody subscribed, the handler ran, or the handler threw. Answering a webhook 200\n * for the first is wrong — the provider would stop retrying a message nothing received.\n *\n * Implementations should be one line over {@link runHandler}, which owns the containment.\n */\n abstract deliver(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\">;\n\n /**\n * Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.\n *\n * A handler is USER code and may throw. An adapter must contain that throw, name it as the\n * handler's failure rather than the platform's, and keep delivering — one bad message ends\n * neither the process nor the connection. Two adapters once discarded the rejection with `void`,\n * which under Node's default ends the process; two more reported it as a platform-client error,\n * sending whoever debugged their own handler to the wrong repository (#41).\n *\n * Ten copies of that knowledge is ten chances to get it wrong, so it lives here. The platform tag\n * is taken from `this.platform`, which is the only part that differed between them.\n */\n protected async runHandler(\n handler: ((event: GatewayMessageEvent) => Promise<void>) | undefined,\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (handler === undefined) return \"no_handler\";\n try {\n await handler(event);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[${this.platform}] handler threw: ${message}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /** Lifecycle: emit a typing indicator. Default: noop. */\n async startTyping(_channelId: string): Promise<void> {\n /* override */\n }\n\n /** Lifecycle: stop the typing indicator. Default: noop. */\n async stopTyping(_channelId: string): Promise<void> {\n /* override */\n }\n}\n","/**\n * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).\n *\n * The router holds a map of `platform → adapter` and forwards\n * `DeliveryRequest` to the right adapter's `sendMessage`. Composes\n * with `Cron` from `@theokit/sdk` for scheduled delivery — the\n * router is the \"WHERE to send\", Cron is the \"WHEN to fire\".\n *\n * @public\n */\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** Target for an outbound delivery. */\nexport interface DeliveryTarget {\n readonly platform: PlatformName;\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n}\n\n/** Full outbound request: target + content. */\nexport interface DeliveryRequest extends DeliveryTarget {\n readonly text: string;\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n readonly replyTo?: string;\n}\n\n/**\n * Routes outbound requests to the correct adapter.\n *\n * **Contract:**\n * - `register` is last-writer-wins by platform.\n * - `send` with unknown platform returns `{ ok: false, code: \"no_adapter\" }`.\n * - `send` never throws on platform errors (delegates to adapter's SendResult).\n *\n * @public\n */\nexport class DeliveryRouter {\n private readonly adapters = new Map<PlatformName, BasePlatformAdapter>();\n\n register(adapter: BasePlatformAdapter): void {\n this.adapters.set(adapter.platform, adapter);\n }\n\n async send(req: DeliveryRequest): Promise<SendResult> {\n const adapter = this.adapters.get(req.platform);\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for platform \"${req.platform}\"` },\n };\n }\n return adapter.sendMessage({\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n });\n }\n}\n","/**\n * `GatewayConfigurationError` — shared base for per-adapter configuration\n * errors (roadmap M0/M2).\n *\n * Every platform adapter previously defined an identical\n * `ConfigurationError extends Error` (same `code`/`detail` fields, same\n * options interface, same `` `${pkg}: ${code}` `` default message) — only the\n * package prefix differed. This base single-sources that contract. Adapters\n * extend it, pin their prefix, and keep `name = \"ConfigurationError\"` plus\n * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).\n *\n * @public\n */\n\n/** Public input shape for the {@link GatewayConfigurationError} constructor. */\nexport interface GatewayConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\n/**\n * Base configuration error. Not thrown directly by adapters — they subclass it\n * with a fixed package prefix.\n */\nexport class GatewayConfigurationError extends Error {\n override readonly name: string = \"GatewayConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n\n /**\n * @param prefix Package prefix used in the default message (e.g. `\"gateway-line\"`).\n * @param opts `code` (required), optional explicit `message`, optional `detail`.\n */\n constructor(prefix: string, opts: GatewayConfigurationErrorOptions) {\n super(opts.message ?? `${prefix}: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n","/**\n * `GatewayLifecycleError` — a lifecycle method was called from a state that\n * cannot honour it.\n *\n * Distinct from {@link GatewayConfigurationError}, which reports a bad or\n * missing setting at construction time. This one reports a legal call made at\n * an illegal moment: the configuration is fine, the ordering is not.\n *\n * It exists because the alternative is worse than an error. `GatewayRunner`\n * used to accept `start()` after `stop()` and quietly produce a runner that\n * reconnected its adapters and then refused to disconnect them — a leak that\n * reported success. Failing loudly at the call that cannot be honoured is the\n * only outcome a caller can act on.\n *\n * @public\n */\n\n/** Public input shape for the {@link GatewayLifecycleError} constructor. */\nexport interface GatewayLifecycleErrorOptions {\n /** Stable, machine-readable discriminator (e.g. `\"runner_stopped\"`). */\n readonly code: string;\n /** Human-readable explanation, including what the caller should do instead. */\n readonly message: string;\n}\n\n/**\n * Thrown when a lifecycle transition is not available from the current state.\n *\n * @public\n */\nexport class GatewayLifecycleError extends Error {\n override readonly name: string = \"GatewayLifecycleError\";\n /** Stable discriminator, so callers branch on `code` rather than on message text. */\n readonly code: string;\n\n constructor(opts: GatewayLifecycleErrorOptions) {\n super(opts.message);\n this.code = opts.code;\n }\n}\n","/**\n * This domain's credential shapes, masked before anything reaches a log.\n *\n * `Security.redact` ships patterns aimed at AI and cloud provider keys — OpenAI, Anthropic, GitHub,\n * AWS, Slack, Stripe and others. Measured against the credentials these packages hold, it altered\n * exactly one: Slack's `xoxb-`, because that is one of its built-ins. On a Telegram token it was\n * worse than absent: a token is `<bot_id>:<secret>`, the numeric prefix is the bot's PUBLIC user id,\n * and the SDK's `key=value` matcher stops at the colon — so `token=8123456789:AAF…` came out as\n * `token=***:AAF…`, the public half removed and the secret half preserved.\n *\n * **Why this masks rather than registering with `Security.addPattern`.** The first attempt did\n * register, and a review measured two defects in it.\n *\n * The SDK applies extra patterns BEFORE its own `key=value` rule and masks a match as\n * `first6…last4`. Claiming a value there therefore DOWNGRADED it: `password=<passphrase>` had been\n * `password=***` and became `password=hunter…aple` — ten characters of an operator's mail password\n * reaching stderr where none did before, under a changelog entry announcing that redaction was\n * fixed. A security change that reduces security is the worst shape a fix can take.\n *\n * And `addPattern` mutates module state inside the SDK. Any app importing this package would\n * inherit these shapes in its own unrelated redaction — after the first gateway error, not before,\n * so the same process would redact differently either side of one exception.\n *\n * Masking here, fully, before the text is handed over, avoids both: the value is gone rather than\n * shortened, and nothing outside this module changes behaviour.\n *\n * **What is deliberately NOT covered** is in {@link CREDENTIAL_SHAPES}.uncovered. Some credentials\n * have no format that can be told apart from an ordinary identifier, and a pattern wide enough to\n * catch them eats the dashless UUIDs and ULIDs a developer reads a log to find. Losing a\n * correlation id costs a debugging session; the gap is recorded instead.\n *\n * @module\n */\nimport { Security } from \"@theokit/sdk\";\n\n/** A credential shape this module masks, and the cost of matching it. */\nexport interface CoveredShape {\n /** The platform and field, for the reader of the table. */\n readonly field: string;\n /** Anchored to the shape. */\n readonly pattern: RegExp;\n /** What else this matches. Every entry has one — a shape narrow enough to have none is rare. */\n readonly alsoMatches: string;\n}\n\n/** A credential this repository declares and this module does not mask. */\nexport interface UncoveredShape {\n /** The platform and field. */\n readonly field: string;\n /** Why a pattern for it would cost more than it buys. */\n readonly why: string;\n}\n\n/**\n * What is masked and what is not.\n *\n * The uncovered list is the point of publishing this as data rather than burying it in a regex\n * table: a reader can see which of their credentials this protects, and a maintainer adding an\n * adapter can see the standard the new shape has to meet.\n */\nexport const CREDENTIAL_SHAPES: {\n readonly covered: readonly CoveredShape[];\n readonly uncovered: readonly UncoveredShape[];\n} = {\n covered: [\n {\n field: \"gateway-telegram `token`\",\n pattern: /(?<![A-Za-z0-9])\\d{8,10}:[A-Za-z0-9_-]{35}(?![A-Za-z0-9_-])/g,\n alsoMatches:\n \"an 8-10 digit number joined by a colon to exactly 35 url-safe characters — a timestamped identifier of that exact width would be masked\",\n },\n {\n field: \"gateway-discord `token`\",\n pattern:\n /(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{23,28}\\.[A-Za-z0-9_-]{6,7}\\.[A-Za-z0-9_-]{27,}(?![A-Za-z0-9_-])/g,\n alsoMatches: \"a three-part dotted identifier of those widths; a JWT's middle part is longer\",\n },\n {\n field: \"gateway-slack `appToken`\",\n pattern: /(?<![A-Za-z0-9-])xapp-\\d-[A-Z0-9]+-\\d+-[a-f0-9]{32,}(?![a-f0-9])/g,\n alsoMatches: \"nothing plausible — the `xapp-` prefix and the shape are Slack's\",\n },\n {\n field: \"gateway-matrix `accessToken`\",\n pattern: /(?<![A-Za-z0-9_])syt_[A-Za-z0-9_-]+_[A-Za-z0-9_-]+_[A-Za-z0-9]+(?![A-Za-z0-9_-])/g,\n alsoMatches: \"nothing plausible — `syt_` is Matrix's own prefix\",\n },\n {\n field: \"gateway-whatsapp `accessToken`\",\n pattern: /(?<![A-Za-z0-9])EAA[A-Za-z0-9]{20,}(?![A-Za-z0-9])/g,\n alsoMatches: \"any identifier beginning EAA followed by 20 or more alphanumerics\",\n },\n {\n field: \"gateway-teams `clientSecret`\",\n pattern:\n /(?<![A-Za-z0-9~])[A-Za-z0-9]{3}\\d[A-Za-z0-9]?~[A-Za-z0-9._~-]{30,}(?![A-Za-z0-9._~-])/g,\n alsoMatches: \"an Entra-style secret is the only common value with a tilde in that position\",\n },\n ],\n uncovered: [\n {\n field: \"gateway-sms `authToken` (Twilio), gateway-line `channelSecret`\",\n why: \"32 lowercase hex characters, which is also an md5 digest, a dashless UUID and half a git tree hash. Masking it would eat the correlation id a developer reads the log to find.\",\n },\n {\n field: \"gateway-mattermost `accessToken`\",\n why: \"26 lowercase alphanumerics, which is exactly a lowercase ULID — the shape of most trace ids.\",\n },\n {\n field: \"gateway-email `password`, gateway-sms `apiSecret` and `signatureSecret` (Vonage)\",\n why: \"no format of their own; a passphrase is indistinguishable from prose. The SDK's own `key=value` rule already masks these fully wherever they appear as `field=value`, and adding a pattern here made that WORSE by claiming the value first — it was masked as first6…last4 instead of removed.\",\n },\n {\n field: \"gateway-slack `botToken`\",\n why: \"already masked by one of the SDK's own twelve built-in patterns — `xoxb-` is Slack's and the SDK knows it. A pattern here would be a second one doing the first's work, and the field-level gate flagged its absence, which is the gate working.\",\n },\n {\n field: \"gateway-whatsapp `appSecret`\",\n why: \"32 lowercase hex, the same shape as the Twilio auth token above and as every md5 and dashless UUID. Masking it would eat the correlation ids in a log.\",\n },\n {\n field: \"gateway-line `channelAccessToken`, gateway-sms `authToken` (Plivo)\",\n why: \"long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message.\",\n },\n ],\n};\n\n/**\n * Replace every covered shape with `***`.\n *\n * Full replacement rather than the SDK's `first6…last4`: a partial mask of a credential is still a\n * disclosure, and the six leading characters of a token identify the account it belongs to.\n *\n * @param text\n * @returns the text with covered shapes removed\n */\nexport function maskShapes(text: string): string {\n let out = text;\n for (const { pattern } of CREDENTIAL_SHAPES.covered) out = out.replace(pattern, \"***\");\n return out;\n}\n\n/**\n * Mask this domain's shapes, then apply the SDK's redactor.\n *\n * The one function the log sites call. Order matters: ours runs first so a covered shape is gone\n * before the SDK's `key=value` rule can shorten it instead, and the SDK still contributes its own\n * twelve patterns for everything we do not know about.\n *\n * @param value the value to redact — a message, an error, anything stringifiable\n * @returns the redacted string\n */\nexport function redactSecrets(value: unknown): string {\n return Security.redact(maskShapes(typeof value === \"string\" ? value : String(value)));\n}\n","/**\n * `HookExecutor` — runs registered gateway hooks at their fire points.\n *\n * Split out of `hooks/types.ts` (which now holds the contract only) so the\n * filename predicts its contents: interfaces live in `types.ts`, the run\n * engine lives here. Behavior is identical to the previous colocated class.\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport { redactSecrets } from \"../security/credential-patterns.js\";\n\nimport type {\n GatewayHook,\n HookDecision,\n OnErrorContext,\n PostOutboundContext,\n PreInboundContext,\n} from \"./types.js\";\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nconst HOOK_PHASES = [\"pre_inbound\", \"post_outbound\", \"on_error\"] as const;\n\n/** Refusal for one bad entry in a hook list, naming WHICH entry (#80). */\nfunction malformedHook(index: number, why: string): GatewayConfigurationError {\n return new GatewayConfigurationError(\"gateway\", {\n code: \"malformed_hook\",\n message: `gateway: hooks[${index}] ${why}`,\n detail: `hooks[${index}]`,\n });\n}\n\n/**\n * Refuse one hook-list entry that is not a hook (#80).\n *\n * Every fire point below asks `if (h.<phase> === undefined) continue`, which cannot tell \"this hook\n * does not implement this phase\" from \"this is not a hook\". So an entry that failed to resolve in a\n * config-driven list used to be skipped in silence, and the gateway started with the rate limiter,\n * audit trail or error reporter its operator believed they had wired simply absent. A missing\n * security hook that says nothing is worse than a loud failure, because the deployment looks\n * correct.\n */\nfunction assertHook(entry: unknown, index: number): void {\n if (typeof entry !== \"object\" || entry === null) {\n throw malformedHook(index, `is ${entry === null ? \"null\" : typeof entry}, not a hook object`);\n }\n const hook = entry as Partial<GatewayHook>;\n if (typeof hook.name !== \"string\" || hook.name.length === 0) {\n throw malformedHook(\n index,\n \"has no name — every hook is named so a log can say which one acted\",\n );\n }\n const declared = HOOK_PHASES.filter((phase) => hook[phase] !== undefined);\n if (declared.length === 0) {\n throw malformedHook(\n index,\n `(\"${hook.name}\") declares none of ${HOOK_PHASES.join(\", \")} — it would never run`,\n );\n }\n for (const phase of declared) {\n if (typeof hook[phase] !== \"function\") {\n throw malformedHook(index, `(\"${hook.name}\") declares ${phase}, which is not callable`);\n }\n }\n}\n\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {\n // The arguments are named rather than inherited from `forEach`, which passes three. Today\n // `assertHook` takes two and the array is discarded harmlessly; the day it grows a third\n // parameter it would silently receive the whole array instead of whatever was intended.\n hooks.forEach((hook, index) => {\n assertHook(hook, index);\n });\n }\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n // `GatewayRunner.dispatch` replies with this message straight into the\n // chat, so it must never carry the exception text. It used to:\n // `hook ${h.name} threw: ${err.message}` sent whatever the hook happened\n // to throw — connection strings, internal ids, bearer tokens — to the end\n // user verbatim. The sibling handler path already logs through\n // `redactSecrets` (EC-F); this one skipped redaction entirely, and the\n // test asserting the raw text appeared locked the leak in as expected\n // behaviour.\n //\n // The detail is not lost, only moved: stderr gets it, redacted.\n process.stderr.write(\n `[gateway] pre_inbound hook \"${h.name}\" threw: ${redactSecrets((err as Error).message)}\\n`,\n );\n return {\n block: true,\n message: `Request blocked: hook \"${h.name}\" failed.`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner\n * cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `redactSecrets` (EC-F).\n *\n * Every reply — the handler's `ctx.reply` and the EC-D auto-reply alike — fires\n * `post_outbound` with the event, the outbound and the adapter's result, once\n * per attempt. The hook observes the delivery; it cannot change what the caller\n * of `reply` receives.\n *\n * @public\n */\n\nimport type { BasePlatformAdapter, OutboundMessage, SendResult } from \"../adapter/base.js\";\nimport { GatewayLifecycleError } from \"../errors/lifecycle-error.js\";\nimport { HookExecutor } from \"../hooks/executor.js\";\nimport type { GatewayHook } from \"../hooks/types.js\";\nimport { redactSecrets } from \"../security/credential-patterns.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /**\n * Connect all adapters and wire inbound dispatch.\n *\n * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already\n * stopped. A stopped runner is spent; construct a new one.\n */\n async start(): Promise<void> {\n if (this.stopped) {\n // Silently reconnecting here is what produced the unstoppable runner:\n // `stop()` cleared `connected` but never `stopped`, so a second start()\n // passed the guard below and rewired everything, while the next stop()\n // returned at its own guard without disconnecting anything (#39).\n throw new GatewayLifecycleError({\n code: \"runner_stopped\",\n message:\n \"GatewayRunner.start(): this runner has already been stopped and cannot be restarted. Construct a new GatewayRunner instead.\",\n });\n }\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n // The loser of the race has to be cancelled explicitly. `Promise.race`\n // settles on the first branch and abandons the other, but an abandoned\n // `setTimeout` is still a scheduled timer, and a scheduled timer keeps\n // Node's event loop alive: `stop()` returned in 0ms while the process\n // only exited `drainMs` later, so a bot stopping on SIGINT hung for the\n // whole drain window before dying (#37).\n let timer: NodeJS.Timeout | undefined;\n try {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => {\n timer = setTimeout(r, drainMs);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /**\n * @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a\n * settled dispatch that is never removed is a leak that grows for the life of the process, and it\n * is invisible from the outside — `stop()` drains correctly either way, because settled promises\n * resolve immediately whether or not anyone deleted them.\n */\n get _inflightSize(): number {\n return this.inflight.size;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(`[gateway] handler error: ${redactSecrets((err as Error).message)}\\n`);\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n return {\n event,\n reply: async (text, opts) =>\n this.deliver(event, {\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n }),\n };\n }\n\n /**\n * Send one outbound on behalf of `event` and report it to `post_outbound`.\n *\n * Every reply leaves through here so the hook fires exactly once per attempt —\n * including the EC-D auto-reply, and including the attempt that finds no\n * adapter for the platform. An audit hook that counted only the deliveries\n * which reached a transport would omit precisely the ones that went nowhere.\n *\n * `post_outbound` observes; it does not intercept. The adapter's `SendResult`\n * is returned to the caller unchanged, and `HookExecutor` already contains a\n * throwing hook, so a broken observer cannot turn a delivered reply into a\n * failed one.\n *\n * @internal\n */\n private async deliver(\n event: GatewayMessageEvent,\n outbound: OutboundMessage,\n ): Promise<SendResult> {\n const adapter = this.adaptersByPlatform.get(event.platform);\n const result: SendResult =\n adapter === undefined\n ? { ok: false, error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` } }\n : await adapter.sendMessage(outbound);\n await this.hookExecutor.firePostOutbound({ event, outbound, result });\n return result;\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n","/**\n * `chunkText` — transport-agnostic, boundary-preferring text chunker.\n *\n * Single-sources the message-splitting knowledge that was copy-pasted across\n * the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two\n * boundary-search families that existed in the adapters:\n *\n * - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\" → \" \"`, UTF-16 surrogate-pair guard,\n * leading-whitespace strip on continuation, optional part-trim.\n * - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\"` (no space), no surrogate guard,\n * leading-newline strip on continuation.\n *\n * The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different\n * algorithm and is intentionally NOT folded in here — those adapters keep their\n * grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.\n *\n * @public\n */\n\n/** Options for {@link chunkText}. */\nexport interface ChunkTextOptions {\n /**\n * Hard cap. If the whole input is `<= limit`, it is returned as a single\n * chunk (subject to `trimParts`). Continuation chunks are cut within the\n * `safeLimit` window.\n */\n readonly limit: number;\n /**\n * Soft window each cut searches within. Defaults to `limit`. The Telegram\n * family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).\n */\n readonly safeLimit?: number;\n /**\n * Boundary strings tried, in order, from most to least preferred. A boundary\n * is accepted once its position is `>= window * 0.5`; otherwise the next one\n * is tried. Default: `[\"\\n\\n\", \"\\n\", \" \"]`.\n */\n readonly boundaries?: readonly string[];\n /**\n * When no boundary reaches the half-window threshold:\n * - `\"last-boundary\"` — use the last computed boundary if it is `> 0`,\n * else fall back to the window edge (Slack family).\n * - `\"window\"` — fall back straight to the window edge (Telegram family).\n * Default: `\"window\"`.\n */\n readonly lastResort?: \"last-boundary\" | \"window\";\n /**\n * Guard against slicing through a UTF-16 low surrogate (splitting an emoji).\n * Default: `false`.\n */\n readonly surrogateGuard?: boolean;\n /**\n * Pattern stripped from the START of each continuation chunk. Default `/^\\n+/`\n * (Telegram family). Slack family uses `/^\\s+/`.\n */\n readonly stripLeading?: RegExp;\n /**\n * When true, each resulting part is `.trim()`-ed and empty parts are dropped\n * (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.\n */\n readonly trimParts?: boolean;\n}\n\n/** Most-preferred boundary at `>= window*0.5`, else the last boundary tried. */\nfunction searchBoundary(remaining: string, window: number, boundaries: readonly string[]): number {\n let cut = window;\n for (const b of boundaries) {\n cut = remaining.lastIndexOf(b, window);\n if (cut >= window * 0.5) return cut;\n }\n return cut;\n}\n\n/** Fail fast on a non-positive / non-integer size argument. */\nfunction assertPositiveInt(label: string, value: number): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new RangeError(`${label} must be a positive integer, received ${value}`);\n }\n}\n\n/** Step back one code unit if `cut` would sever a UTF-16 surrogate pair. */\nfunction guardSurrogate(text: string, cut: number): number {\n if (cut >= text.length) return cut;\n const code = text.charCodeAt(cut);\n return code >= 0xdc00 && code <= 0xdfff ? cut - 1 : cut;\n}\n\nfunction findCut(\n remaining: string,\n window: number,\n boundaries: readonly string[],\n lastResort: \"last-boundary\" | \"window\",\n surrogateGuard: boolean,\n): number {\n let cut = searchBoundary(remaining, window, boundaries);\n if (cut < window * 0.5) {\n cut = lastResort === \"last-boundary\" && cut > 0 ? cut : window;\n }\n if (surrogateGuard) cut = guardSurrogate(remaining, cut);\n return cut <= 0 ? window : cut;\n}\n\n/**\n * Split `text` into chunks no longer than the configured window, preferring\n * natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.\n */\nexport function chunkText(text: string, options: ChunkTextOptions): string[] {\n const {\n limit,\n safeLimit = limit,\n boundaries = [\"\\n\\n\", \"\\n\", \" \"],\n lastResort = \"window\",\n surrogateGuard = false,\n stripLeading = /^\\n+/,\n trimParts = false,\n } = options;\n\n // Fail fast at the boundary: a non-positive `limit` would make `findCut`\n // return 0 forever and hang the loop; `safeLimit > limit` would break the\n // \"hard cap\" contract by emitting an oversized tail chunk.\n assertPositiveInt(\"chunkText: limit\", limit);\n assertPositiveInt(\"chunkText: safeLimit\", safeLimit);\n if (safeLimit > limit) {\n throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);\n }\n\n const finalize = (parts: string[]): string[] =>\n trimParts ? parts.map((p) => p.trim()).filter((p) => p.length > 0) : parts;\n\n if (text.length <= limit) {\n return finalize([text]);\n }\n\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > safeLimit) {\n const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);\n parts.push(remaining.slice(0, cut));\n remaining = remaining.slice(cut).replace(stripLeading, \"\");\n }\n if (remaining.length > 0) parts.push(remaining);\n return finalize(parts);\n}\n\n/** Options for {@link chunkByGrapheme}. */\nexport interface ChunkByGraphemeOptions {\n /** If `text.length <= limit`, it is returned as a single chunk. */\n readonly limit: number;\n /**\n * Max length per emitted part during the grapheme walk. Defaults to `limit`.\n * Callers that reserve room for a per-part prefix (e.g. SMS `\"(i/N) \"`) pass a\n * `partLimit` below `limit`.\n */\n readonly partLimit?: number;\n}\n\n/**\n * Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,\n * regional-indicator pair, or combining sequence. Distinct algorithm from\n * {@link chunkText} — used by adapters that must respect grapheme boundaries\n * (LINE, SMS) rather than search for whitespace boundaries.\n *\n * @public\n */\nexport function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[] {\n const { limit, partLimit = limit } = options;\n assertPositiveInt(\"chunkByGrapheme: limit\", limit);\n assertPositiveInt(\"chunkByGrapheme: partLimit\", partLimit);\n if (text.length === 0) return [\"\"];\n if (text.length <= limit) return [text];\n\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const parts: string[] = [];\n let buf = \"\";\n for (const { segment } of segmenter.segment(text)) {\n if (buf.length + segment.length > partLimit) {\n if (buf.length > 0) parts.push(buf);\n buf = \"\";\n }\n buf += segment;\n }\n if (buf.length > 0) parts.push(buf);\n return parts;\n}\n","/**\n * The half of an Express webhook server that is the same for every platform.\n *\n * `gateway-line` and `gateway-sms` each ship one, and they shared 101 of ~170 lines: the lazy\n * `express` load, the raw-body capture with the hang it documents, and the start/stop lifecycle.\n * What differs is signature verification, body parsing and routing, which are genuinely\n * per-platform (#89).\n *\n * The duplication had already been paid for. Commit `11000cc` fixed a write-once latch that made\n * `start()` after `stop()` return without creating a listener — a port nothing answers on, with no\n * error and no log — and it had to fix it in BOTH files, because the latch lives in the copied\n * half. That is the DRY test verbatim: change it here, change it there.\n *\n * ## Why here, and not in a new package\n *\n * The core had no HTTP concern, and `express` is a peer dependency of exactly the two packages that\n * duplicate this — so the obvious objection to putting it here is that it would impose express on\n * all ten adapters.\n *\n * It does not, because nothing here imports express. Every shape below is structural: a request is\n * whatever has `readableEnded` and `on`, a listener is whatever has `listen` and `close`. The\n * packages that use express keep declaring it; this module never learns the name.\n *\n * Exported rather than internal: the two packages that consume it are separate npm packages, so\n * \"internal to this repository\" is not a thing the module system can express.\n *\n * @public\n */\n\n/** What the capture middleware reads. Express's `Request` satisfies it; so does a bare stream. */\nexport interface RawBodyRequest {\n readonly readableEnded?: boolean;\n readonly complete?: boolean;\n setEncoding(encoding: string): unknown;\n on(event: string, listener: (arg: never) => void): unknown;\n}\n\n/** What a started listener must be able to do. `http.Server` satisfies it. */\nexport interface ListenerLike {\n close(cb?: (err?: Error) => void): unknown;\n}\n\n/** What can start a listener. Express's app satisfies it. */\nexport interface ListenableApp {\n listen(port: number, cb: () => void): ListenerLike;\n}\n\n/**\n * Load a peer dependency, or fail with a message that says what to install.\n *\n * The error is the point. A bare `Cannot find module 'express'` reaches a consumer who did not\n * write the import and cannot tell whether the package is broken or a step is missing.\n */\nexport async function loadPeer<T>(\n load: () => Promise<unknown>,\n onMissing: () => never,\n): Promise<T> {\n try {\n const mod = await load();\n // Both ESM and CJS shapes: `import()` on a CJS module puts the export under `default`.\n return ((mod as { default?: T }).default ?? (mod as T)) as T;\n } catch {\n onMissing();\n }\n}\n\n/**\n * Middleware that captures the RAW request body before anything parses it.\n *\n * Every provider signs the exact bytes, so a body that was parsed and re-serialised hashes\n * differently and fails verification for a correct request. The bytes are attached as `rawBody`.\n *\n * @param tag the package name for the diagnostic, so a reader knows which router is complaining\n */\nexport function rawBodyCapture(tag: string) {\n // `unknown` rather than `RawBodyRequest`, and that is a type-system requirement rather than\n // laziness: a handler parameter is CONTRAVARIANT, so for express to accept this middleware the\n // parameter must be a SUPERTYPE of express's own `Request`. Narrowed on the first line, where the\n // shape this actually needs is stated once.\n return (rawReq: unknown, _res: unknown, next: (err?: unknown) => void): void => {\n const req = rawReq as RawBodyRequest;\n // Someone else already drained the stream — a global `express.json()` or `express.urlencoded()`\n // mounted ahead of this router is the usual cause. Without this branch `req.on(\"end\")` never\n // fires for a stream that already ended, `next()` is never called, and the request HANGS with\n // no response: the provider times out and retries, and nothing is logged anywhere. Failing\n // loudly and continuing is strictly better — verification then refuses the empty body with a\n // 401, which is at least a visible symptom pointing at the real cause.\n if (req.readableEnded === true || req.complete === true) {\n process.stderr.write(\n `[${tag}] raw body already consumed before signature capture — mount this router ` +\n \"BEFORE any global body parser, or signature verification cannot see the bytes it \" +\n \"must hash\\n\",\n );\n (req as unknown as { rawBody: string }).rawBody = \"\";\n next();\n return;\n }\n let buf = \"\";\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n buf += chunk;\n });\n req.on(\"end\", () => {\n (req as unknown as { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err: unknown) => next(err));\n };\n}\n\n/**\n * The start/stop pair, with the latches that make a restart a restart.\n *\n * Both flags used to be write-once, in both packages. After a `stop()`, `start()` hit `if (started)`\n * and returned without creating a listener — the server was silently dead — and the next `stop()`\n * was a no-op for the same reason, in the other direction. Anything that restarts a gateway hit it:\n * a config reload, a reconnect after a network fault, a supervisor cycling a process in-band.\n *\n * `injected` is for the case where the caller owns the app: there is no listener to open or close,\n * and `start()`/`stop()` must still be callable and idempotent.\n */\nexport function listenerLifecycle(opts: {\n readonly app: ListenableApp;\n readonly port: number;\n readonly injected: boolean;\n}): { start(): Promise<void>; stop(): Promise<void> } {\n let started = false;\n let stopped = false;\n let listener: ListenerLike | undefined;\n\n return {\n async start(): Promise<void> {\n if (started || opts.injected) {\n started = true;\n return;\n }\n // Cleared here rather than in stop(): a server that was stopped and is starting again is no\n // longer stopped, and leaving the flag latched made the NEXT stop() a no-op.\n stopped = false;\n await new Promise<void>((resolve) => {\n listener = opts.app.listen(opts.port, () => resolve());\n });\n started = true;\n },\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n // Resetting `started` is what makes a restart a restart.\n started = false;\n const current = listener;\n listener = undefined;\n if (current === undefined) return;\n await new Promise<void>((resolve) => {\n current.close(() => resolve());\n });\n },\n };\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -108,6 +108,23 @@ interface WhatsAppMessageEvent extends BaseMessageEvent {
|
|
|
108
108
|
readonly phoneNumberId?: string;
|
|
109
109
|
/** Contact's profile name when Meta provides it. */
|
|
110
110
|
readonly contactName?: string;
|
|
111
|
+
/**
|
|
112
|
+
* The address this arrived on, verbatim — what a reply must be sent to.
|
|
113
|
+
*
|
|
114
|
+
* `channel.id` is normalised to digits, which is what an allowlist compares and what a session
|
|
115
|
+
* key is built from. The normalisation strips the DOMAIN, and the domain is what says which
|
|
116
|
+
* kind of identifier it is: `@s.whatsapp.net` a phone, `@g.us` a group, `@lid` an account's
|
|
117
|
+
* linked identity. A note-to-self arrives addressed by LID, so answering `channel.id` rebuilds
|
|
118
|
+
* `…@s.whatsapp.net` — an address that does not exist, and a send that reports ok and lands
|
|
119
|
+
* nowhere (#84).
|
|
120
|
+
*
|
|
121
|
+
* `sendMessage` accepts this verbatim: a `to` containing `@` is already an address and is
|
|
122
|
+
* passed through untouched.
|
|
123
|
+
*
|
|
124
|
+
* Present on the baileys backend. The cloud backend addresses recipients by phone and has no
|
|
125
|
+
* JID to report.
|
|
126
|
+
*/
|
|
127
|
+
readonly channelJid?: string;
|
|
111
128
|
/**
|
|
112
129
|
* Which backend produced this event.
|
|
113
130
|
*
|
|
@@ -429,6 +446,36 @@ declare abstract class BasePlatformAdapter {
|
|
|
429
446
|
* ten to it.
|
|
430
447
|
*/
|
|
431
448
|
abstract onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
449
|
+
/**
|
|
450
|
+
* Deliver an inbound event that arrived OUT OF BAND, and report what the handler did with it.
|
|
451
|
+
*
|
|
452
|
+
* Six adapters self-deliver once connected — long polling, a gateway socket, Socket Mode, a sync
|
|
453
|
+
* loop, IMAP. The webhook platforms cannot: the payload arrives on an HTTP route the application
|
|
454
|
+
* owns, and until this existed there was no supported call that joined the two. `onInbound` had no
|
|
455
|
+
* public counterpart, so `GatewayRunner` was reachable for eight platforms and not for LINE or
|
|
456
|
+
* WhatsApp Cloud, which every app then wired by hand beside the runner instead of through it
|
|
457
|
+
* (#83).
|
|
458
|
+
*
|
|
459
|
+
* The return value distinguishes the three outcomes a caller can act on, because they are not the
|
|
460
|
+
* same problem: nobody subscribed, the handler ran, or the handler threw. Answering a webhook 200
|
|
461
|
+
* for the first is wrong — the provider would stop retrying a message nothing received.
|
|
462
|
+
*
|
|
463
|
+
* Implementations should be one line over {@link runHandler}, which owns the containment.
|
|
464
|
+
*/
|
|
465
|
+
abstract deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
466
|
+
/**
|
|
467
|
+
* Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.
|
|
468
|
+
*
|
|
469
|
+
* A handler is USER code and may throw. An adapter must contain that throw, name it as the
|
|
470
|
+
* handler's failure rather than the platform's, and keep delivering — one bad message ends
|
|
471
|
+
* neither the process nor the connection. Two adapters once discarded the rejection with `void`,
|
|
472
|
+
* which under Node's default ends the process; two more reported it as a platform-client error,
|
|
473
|
+
* sending whoever debugged their own handler to the wrong repository (#41).
|
|
474
|
+
*
|
|
475
|
+
* Ten copies of that knowledge is ten chances to get it wrong, so it lives here. The platform tag
|
|
476
|
+
* is taken from `this.platform`, which is the only part that differed between them.
|
|
477
|
+
*/
|
|
478
|
+
protected runHandler(handler: ((event: MessageEvent) => Promise<void>) | undefined, event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
432
479
|
/** Lifecycle: emit a typing indicator. Default: noop. */
|
|
433
480
|
startTyping(_channelId: string): Promise<void>;
|
|
434
481
|
/** Lifecycle: stop the typing indicator. Default: noop. */
|
|
@@ -607,12 +654,6 @@ interface GatewayHook {
|
|
|
607
654
|
* @public
|
|
608
655
|
*/
|
|
609
656
|
|
|
610
|
-
/**
|
|
611
|
-
* Runs registered hooks at the right fire points. Stateless — safe to
|
|
612
|
-
* construct per-event if hooks need event-scoped storage.
|
|
613
|
-
*
|
|
614
|
-
* @public
|
|
615
|
-
*/
|
|
616
657
|
declare class HookExecutor {
|
|
617
658
|
private readonly hooks;
|
|
618
659
|
constructor(hooks: ReadonlyArray<GatewayHook>);
|
|
@@ -647,7 +688,7 @@ declare class HookExecutor {
|
|
|
647
688
|
* 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.
|
|
648
689
|
* 3. If `block: true` only: short-circuit silently.
|
|
649
690
|
* 4. Otherwise: call user handler.
|
|
650
|
-
* 5. On handler throw: fire `on_error`, log via `
|
|
691
|
+
* 5. On handler throw: fire `on_error`, log via `redactSecrets` (EC-F).
|
|
651
692
|
*
|
|
652
693
|
* Every reply — the handler's `ctx.reply` and the EC-D auto-reply alike — fires
|
|
653
694
|
* `post_outbound` with the event, the outbound and the adapter's result, once
|
|
@@ -731,6 +772,55 @@ declare class GatewayRunner {
|
|
|
731
772
|
private buildContext;
|
|
732
773
|
}
|
|
733
774
|
|
|
775
|
+
/** A credential shape this module masks, and the cost of matching it. */
|
|
776
|
+
interface CoveredShape {
|
|
777
|
+
/** The platform and field, for the reader of the table. */
|
|
778
|
+
readonly field: string;
|
|
779
|
+
/** Anchored to the shape. */
|
|
780
|
+
readonly pattern: RegExp;
|
|
781
|
+
/** What else this matches. Every entry has one — a shape narrow enough to have none is rare. */
|
|
782
|
+
readonly alsoMatches: string;
|
|
783
|
+
}
|
|
784
|
+
/** A credential this repository declares and this module does not mask. */
|
|
785
|
+
interface UncoveredShape {
|
|
786
|
+
/** The platform and field. */
|
|
787
|
+
readonly field: string;
|
|
788
|
+
/** Why a pattern for it would cost more than it buys. */
|
|
789
|
+
readonly why: string;
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* What is masked and what is not.
|
|
793
|
+
*
|
|
794
|
+
* The uncovered list is the point of publishing this as data rather than burying it in a regex
|
|
795
|
+
* table: a reader can see which of their credentials this protects, and a maintainer adding an
|
|
796
|
+
* adapter can see the standard the new shape has to meet.
|
|
797
|
+
*/
|
|
798
|
+
declare const CREDENTIAL_SHAPES: {
|
|
799
|
+
readonly covered: readonly CoveredShape[];
|
|
800
|
+
readonly uncovered: readonly UncoveredShape[];
|
|
801
|
+
};
|
|
802
|
+
/**
|
|
803
|
+
* Replace every covered shape with `***`.
|
|
804
|
+
*
|
|
805
|
+
* Full replacement rather than the SDK's `first6…last4`: a partial mask of a credential is still a
|
|
806
|
+
* disclosure, and the six leading characters of a token identify the account it belongs to.
|
|
807
|
+
*
|
|
808
|
+
* @param text
|
|
809
|
+
* @returns the text with covered shapes removed
|
|
810
|
+
*/
|
|
811
|
+
declare function maskShapes(text: string): string;
|
|
812
|
+
/**
|
|
813
|
+
* Mask this domain's shapes, then apply the SDK's redactor.
|
|
814
|
+
*
|
|
815
|
+
* The one function the log sites call. Order matters: ours runs first so a covered shape is gone
|
|
816
|
+
* before the SDK's `key=value` rule can shorten it instead, and the SDK still contributes its own
|
|
817
|
+
* twelve patterns for everything we do not know about.
|
|
818
|
+
*
|
|
819
|
+
* @param value the value to redact — a message, an error, anything stringifiable
|
|
820
|
+
* @returns the redacted string
|
|
821
|
+
*/
|
|
822
|
+
declare function redactSecrets(value: unknown): string;
|
|
823
|
+
|
|
734
824
|
/**
|
|
735
825
|
* `SessionRouter` — pure routing logic: `MessageEvent → agentId`
|
|
736
826
|
* (T2.1, ADR D174).
|
|
@@ -857,4 +947,83 @@ interface ChunkByGraphemeOptions {
|
|
|
857
947
|
*/
|
|
858
948
|
declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
|
|
859
949
|
|
|
860
|
-
|
|
950
|
+
/**
|
|
951
|
+
* The half of an Express webhook server that is the same for every platform.
|
|
952
|
+
*
|
|
953
|
+
* `gateway-line` and `gateway-sms` each ship one, and they shared 101 of ~170 lines: the lazy
|
|
954
|
+
* `express` load, the raw-body capture with the hang it documents, and the start/stop lifecycle.
|
|
955
|
+
* What differs is signature verification, body parsing and routing, which are genuinely
|
|
956
|
+
* per-platform (#89).
|
|
957
|
+
*
|
|
958
|
+
* The duplication had already been paid for. Commit `11000cc` fixed a write-once latch that made
|
|
959
|
+
* `start()` after `stop()` return without creating a listener — a port nothing answers on, with no
|
|
960
|
+
* error and no log — and it had to fix it in BOTH files, because the latch lives in the copied
|
|
961
|
+
* half. That is the DRY test verbatim: change it here, change it there.
|
|
962
|
+
*
|
|
963
|
+
* ## Why here, and not in a new package
|
|
964
|
+
*
|
|
965
|
+
* The core had no HTTP concern, and `express` is a peer dependency of exactly the two packages that
|
|
966
|
+
* duplicate this — so the obvious objection to putting it here is that it would impose express on
|
|
967
|
+
* all ten adapters.
|
|
968
|
+
*
|
|
969
|
+
* It does not, because nothing here imports express. Every shape below is structural: a request is
|
|
970
|
+
* whatever has `readableEnded` and `on`, a listener is whatever has `listen` and `close`. The
|
|
971
|
+
* packages that use express keep declaring it; this module never learns the name.
|
|
972
|
+
*
|
|
973
|
+
* Exported rather than internal: the two packages that consume it are separate npm packages, so
|
|
974
|
+
* "internal to this repository" is not a thing the module system can express.
|
|
975
|
+
*
|
|
976
|
+
* @public
|
|
977
|
+
*/
|
|
978
|
+
/** What the capture middleware reads. Express's `Request` satisfies it; so does a bare stream. */
|
|
979
|
+
interface RawBodyRequest {
|
|
980
|
+
readonly readableEnded?: boolean;
|
|
981
|
+
readonly complete?: boolean;
|
|
982
|
+
setEncoding(encoding: string): unknown;
|
|
983
|
+
on(event: string, listener: (arg: never) => void): unknown;
|
|
984
|
+
}
|
|
985
|
+
/** What a started listener must be able to do. `http.Server` satisfies it. */
|
|
986
|
+
interface ListenerLike {
|
|
987
|
+
close(cb?: (err?: Error) => void): unknown;
|
|
988
|
+
}
|
|
989
|
+
/** What can start a listener. Express's app satisfies it. */
|
|
990
|
+
interface ListenableApp {
|
|
991
|
+
listen(port: number, cb: () => void): ListenerLike;
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Load a peer dependency, or fail with a message that says what to install.
|
|
995
|
+
*
|
|
996
|
+
* The error is the point. A bare `Cannot find module 'express'` reaches a consumer who did not
|
|
997
|
+
* write the import and cannot tell whether the package is broken or a step is missing.
|
|
998
|
+
*/
|
|
999
|
+
declare function loadPeer<T>(load: () => Promise<unknown>, onMissing: () => never): Promise<T>;
|
|
1000
|
+
/**
|
|
1001
|
+
* Middleware that captures the RAW request body before anything parses it.
|
|
1002
|
+
*
|
|
1003
|
+
* Every provider signs the exact bytes, so a body that was parsed and re-serialised hashes
|
|
1004
|
+
* differently and fails verification for a correct request. The bytes are attached as `rawBody`.
|
|
1005
|
+
*
|
|
1006
|
+
* @param tag the package name for the diagnostic, so a reader knows which router is complaining
|
|
1007
|
+
*/
|
|
1008
|
+
declare function rawBodyCapture(tag: string): (rawReq: unknown, _res: unknown, next: (err?: unknown) => void) => void;
|
|
1009
|
+
/**
|
|
1010
|
+
* The start/stop pair, with the latches that make a restart a restart.
|
|
1011
|
+
*
|
|
1012
|
+
* Both flags used to be write-once, in both packages. After a `stop()`, `start()` hit `if (started)`
|
|
1013
|
+
* and returned without creating a listener — the server was silently dead — and the next `stop()`
|
|
1014
|
+
* was a no-op for the same reason, in the other direction. Anything that restarts a gateway hit it:
|
|
1015
|
+
* a config reload, a reconnect after a network fault, a supervisor cycling a process in-band.
|
|
1016
|
+
*
|
|
1017
|
+
* `injected` is for the case where the caller owns the app: there is no listener to open or close,
|
|
1018
|
+
* and `start()`/`stop()` must still be callable and idempotent.
|
|
1019
|
+
*/
|
|
1020
|
+
declare function listenerLifecycle(opts: {
|
|
1021
|
+
readonly app: ListenableApp;
|
|
1022
|
+
readonly port: number;
|
|
1023
|
+
readonly injected: boolean;
|
|
1024
|
+
}): {
|
|
1025
|
+
start(): Promise<void>;
|
|
1026
|
+
stop(): Promise<void>;
|
|
1027
|
+
};
|
|
1028
|
+
|
|
1029
|
+
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 };
|