@theokit/gateway 0.5.0 → 0.6.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/errors/config-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,EAmBxC,MAAM,YAAY,UAAA,EAAmC;AAAA,EAErD;AAAA;AAAA,EAGA,MAAM,WAAW,UAAA,EAAmC;AAAA,EAEpD;AACF;;;ACvCO,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,CAAY;AAAA,MACzB,SAAS,GAAA,CAAI,OAAA;AAAA,MACb,MAAM,GAAA,CAAI,IAAA;AAAA,MACV,GAAI,IAAI,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,GAAA,CAAI,MAAA,EAAO,GAAI,EAAC;AAAA,MACzD,GAAI,IAAI,OAAA,KAAY,MAAA,GAAY,EAAE,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G;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 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 * `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 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 return {\n block: true,\n message: `hook ${h.name} threw: ${(err as Error).message}`,\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.\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 * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.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 /** Connect all adapters and wire inbound dispatch. */\n async start(): Promise<void> {\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 await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => setTimeout(r, drainMs)),\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 const adapter = this.adaptersByPlatform.get(event.platform);\n return {\n event,\n reply: async (text, opts) => {\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` },\n };\n }\n return adapter.sendMessage({\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n });\n },\n };\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/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,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,CAAC,EAAE,CAAA;AACjC,EAAA,IAAI,IAAA,CAAK,MAAA,IAAU,KAAA,EAAO,OAAO,CAAC,IAAI,CAAA;AAEtC,EAAA,MAAM,SAAA,GAAY,IAAI,IAAA,CAAK,SAAA,CAAU,QAAW,EAAE,WAAA,EAAa,YAAY,CAAA;AAC3E,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,MAAW,EAAE,OAAA,EAAQ,IAAK,SAAA,CAAU,OAAA,CAAQ,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"]}
package/dist/index.d.cts CHANGED
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * This union is intentionally **closed** — adding a platform edits it here
16
16
  * rather than extending it externally. The trade-off (exhaustive narrowing over
17
- * OCP purity) is recorded in `docs/adr/0001-message-event-closed-union.md`.
17
+ * OCP purity) is recorded in `wiki/decisions/adr-0001-message-event-closed-union.md`.
18
18
  *
19
19
  * @public
20
20
  */
@@ -97,8 +97,14 @@ interface WhatsAppMessageEvent extends BaseMessageEvent {
97
97
  readonly phoneNumberId?: string;
98
98
  /** Contact's profile name when Meta provides it. */
99
99
  readonly contactName?: string;
100
- /** Which backend produced this event. */
101
- readonly backend: "cloud" | "web";
100
+ /**
101
+ * Which backend produced this event.
102
+ *
103
+ * `baileys` joined `cloud` and `web` in 0.2: it speaks the WhatsApp Web multi-device
104
+ * protocol over a WebSocket, where `web` drives a headless browser. Consumers that
105
+ * switch exhaustively on this must handle the third case.
106
+ */
107
+ readonly backend: "cloud" | "web" | "baileys";
102
108
  /** Raw envelope — backend-specific, narrowed by the adapter package. */
103
109
  readonly raw: unknown;
104
110
  };
@@ -279,6 +285,14 @@ declare abstract class BasePlatformAdapter {
279
285
  /**
280
286
  * Subscribe to inbound events. Returns an unsubscribe function.
281
287
  * EC-H: second call REPLACES the previous handler (does not stack).
288
+ *
289
+ * The handler is user code and may throw. An adapter MUST contain that throw, report it as the
290
+ * HANDLER's failure — not the platform's — and keep delivering: one bad message never ends the
291
+ * process nor the connection. Two adapters used to discard the rejection with `void`, which under
292
+ * Node's default ends the process, and two more reported it as a platform-client error, sending
293
+ * whoever debugged their own handler to the wrong repository. Eight had converged on the right
294
+ * behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds all
295
+ * ten to it.
282
296
  */
283
297
  abstract onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
284
298
  /** Lifecycle: emit a typing indicator. Default: noop. */
@@ -363,6 +377,41 @@ declare class GatewayConfigurationError extends Error {
363
377
  constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
364
378
  }
365
379
 
380
+ /**
381
+ * `GatewayLifecycleError` — a lifecycle method was called from a state that
382
+ * cannot honour it.
383
+ *
384
+ * Distinct from {@link GatewayConfigurationError}, which reports a bad or
385
+ * missing setting at construction time. This one reports a legal call made at
386
+ * an illegal moment: the configuration is fine, the ordering is not.
387
+ *
388
+ * It exists because the alternative is worse than an error. `GatewayRunner`
389
+ * used to accept `start()` after `stop()` and quietly produce a runner that
390
+ * reconnected its adapters and then refused to disconnect them — a leak that
391
+ * reported success. Failing loudly at the call that cannot be honoured is the
392
+ * only outcome a caller can act on.
393
+ *
394
+ * @public
395
+ */
396
+ /** Public input shape for the {@link GatewayLifecycleError} constructor. */
397
+ interface GatewayLifecycleErrorOptions {
398
+ /** Stable, machine-readable discriminator (e.g. `"runner_stopped"`). */
399
+ readonly code: string;
400
+ /** Human-readable explanation, including what the caller should do instead. */
401
+ readonly message: string;
402
+ }
403
+ /**
404
+ * Thrown when a lifecycle transition is not available from the current state.
405
+ *
406
+ * @public
407
+ */
408
+ declare class GatewayLifecycleError extends Error {
409
+ readonly name: string;
410
+ /** Stable discriminator, so callers branch on `code` rather than on message text. */
411
+ readonly code: string;
412
+ constructor(opts: GatewayLifecycleErrorOptions);
413
+ }
414
+
366
415
  /**
367
416
  * Gateway hooks — own contract, not a `Plugin.kind` extension
368
417
  * (T4.1, ADRs D176, D177).
@@ -456,7 +505,8 @@ declare class HookExecutor {
456
505
  * failure rolls back: connected adapters get `disconnect()`, then the
457
506
  * aggregate error rethrows.
458
507
  * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)
459
- * BEFORE disconnecting (EC-E). Idempotent.
508
+ * BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner
509
+ * cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.
460
510
  *
461
511
  * **Hook chain on inbound:**
462
512
  * 1. `firePreInbound({ event })`
@@ -465,6 +515,11 @@ declare class HookExecutor {
465
515
  * 4. Otherwise: call user handler.
466
516
  * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).
467
517
  *
518
+ * Every reply — the handler's `ctx.reply` and the EC-D auto-reply alike — fires
519
+ * `post_outbound` with the event, the outbound and the adapter's result, once
520
+ * per attempt. The hook observes the delivery; it cannot change what the caller
521
+ * of `reply` receives.
522
+ *
468
523
  * @public
469
524
  */
470
525
 
@@ -520,7 +575,12 @@ declare class GatewayRunner {
520
575
  * @public
521
576
  */
522
577
  command(name: string, handler: GatewayHandler): void;
523
- /** Connect all adapters and wire inbound dispatch. */
578
+ /**
579
+ * Connect all adapters and wire inbound dispatch.
580
+ *
581
+ * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
582
+ * stopped. A stopped runner is spent; construct a new one.
583
+ */
524
584
  start(): Promise<void>;
525
585
  /**
526
586
  * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
@@ -663,4 +723,4 @@ interface ChunkByGraphemeOptions {
663
723
  */
664
724
  declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
665
725
 
666
- export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
726
+ export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, 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 MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
package/dist/index.d.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * This union is intentionally **closed** — adding a platform edits it here
16
16
  * rather than extending it externally. The trade-off (exhaustive narrowing over
17
- * OCP purity) is recorded in `docs/adr/0001-message-event-closed-union.md`.
17
+ * OCP purity) is recorded in `wiki/decisions/adr-0001-message-event-closed-union.md`.
18
18
  *
19
19
  * @public
20
20
  */
@@ -97,8 +97,14 @@ interface WhatsAppMessageEvent extends BaseMessageEvent {
97
97
  readonly phoneNumberId?: string;
98
98
  /** Contact's profile name when Meta provides it. */
99
99
  readonly contactName?: string;
100
- /** Which backend produced this event. */
101
- readonly backend: "cloud" | "web";
100
+ /**
101
+ * Which backend produced this event.
102
+ *
103
+ * `baileys` joined `cloud` and `web` in 0.2: it speaks the WhatsApp Web multi-device
104
+ * protocol over a WebSocket, where `web` drives a headless browser. Consumers that
105
+ * switch exhaustively on this must handle the third case.
106
+ */
107
+ readonly backend: "cloud" | "web" | "baileys";
102
108
  /** Raw envelope — backend-specific, narrowed by the adapter package. */
103
109
  readonly raw: unknown;
104
110
  };
@@ -279,6 +285,14 @@ declare abstract class BasePlatformAdapter {
279
285
  /**
280
286
  * Subscribe to inbound events. Returns an unsubscribe function.
281
287
  * EC-H: second call REPLACES the previous handler (does not stack).
288
+ *
289
+ * The handler is user code and may throw. An adapter MUST contain that throw, report it as the
290
+ * HANDLER's failure — not the platform's — and keep delivering: one bad message never ends the
291
+ * process nor the connection. Two adapters used to discard the rejection with `void`, which under
292
+ * Node's default ends the process, and two more reported it as a platform-client error, sending
293
+ * whoever debugged their own handler to the wrong repository. Eight had converged on the right
294
+ * behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds all
295
+ * ten to it.
282
296
  */
283
297
  abstract onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
284
298
  /** Lifecycle: emit a typing indicator. Default: noop. */
@@ -363,6 +377,41 @@ declare class GatewayConfigurationError extends Error {
363
377
  constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
364
378
  }
365
379
 
380
+ /**
381
+ * `GatewayLifecycleError` — a lifecycle method was called from a state that
382
+ * cannot honour it.
383
+ *
384
+ * Distinct from {@link GatewayConfigurationError}, which reports a bad or
385
+ * missing setting at construction time. This one reports a legal call made at
386
+ * an illegal moment: the configuration is fine, the ordering is not.
387
+ *
388
+ * It exists because the alternative is worse than an error. `GatewayRunner`
389
+ * used to accept `start()` after `stop()` and quietly produce a runner that
390
+ * reconnected its adapters and then refused to disconnect them — a leak that
391
+ * reported success. Failing loudly at the call that cannot be honoured is the
392
+ * only outcome a caller can act on.
393
+ *
394
+ * @public
395
+ */
396
+ /** Public input shape for the {@link GatewayLifecycleError} constructor. */
397
+ interface GatewayLifecycleErrorOptions {
398
+ /** Stable, machine-readable discriminator (e.g. `"runner_stopped"`). */
399
+ readonly code: string;
400
+ /** Human-readable explanation, including what the caller should do instead. */
401
+ readonly message: string;
402
+ }
403
+ /**
404
+ * Thrown when a lifecycle transition is not available from the current state.
405
+ *
406
+ * @public
407
+ */
408
+ declare class GatewayLifecycleError extends Error {
409
+ readonly name: string;
410
+ /** Stable discriminator, so callers branch on `code` rather than on message text. */
411
+ readonly code: string;
412
+ constructor(opts: GatewayLifecycleErrorOptions);
413
+ }
414
+
366
415
  /**
367
416
  * Gateway hooks — own contract, not a `Plugin.kind` extension
368
417
  * (T4.1, ADRs D176, D177).
@@ -456,7 +505,8 @@ declare class HookExecutor {
456
505
  * failure rolls back: connected adapters get `disconnect()`, then the
457
506
  * aggregate error rethrows.
458
507
  * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)
459
- * BEFORE disconnecting (EC-E). Idempotent.
508
+ * BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner
509
+ * cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.
460
510
  *
461
511
  * **Hook chain on inbound:**
462
512
  * 1. `firePreInbound({ event })`
@@ -465,6 +515,11 @@ declare class HookExecutor {
465
515
  * 4. Otherwise: call user handler.
466
516
  * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).
467
517
  *
518
+ * Every reply — the handler's `ctx.reply` and the EC-D auto-reply alike — fires
519
+ * `post_outbound` with the event, the outbound and the adapter's result, once
520
+ * per attempt. The hook observes the delivery; it cannot change what the caller
521
+ * of `reply` receives.
522
+ *
468
523
  * @public
469
524
  */
470
525
 
@@ -520,7 +575,12 @@ declare class GatewayRunner {
520
575
  * @public
521
576
  */
522
577
  command(name: string, handler: GatewayHandler): void;
523
- /** Connect all adapters and wire inbound dispatch. */
578
+ /**
579
+ * Connect all adapters and wire inbound dispatch.
580
+ *
581
+ * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
582
+ * stopped. A stopped runner is spent; construct a new one.
583
+ */
524
584
  start(): Promise<void>;
525
585
  /**
526
586
  * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
@@ -663,4 +723,4 @@ interface ChunkByGraphemeOptions {
663
723
  */
664
724
  declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
665
725
 
666
- export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
726
+ export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, 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 MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
package/dist/index.js CHANGED
@@ -49,7 +49,16 @@ var GatewayConfigurationError = class extends Error {
49
49
  }
50
50
  };
51
51
 
52
- // src/hooks/executor.ts
52
+ // src/errors/lifecycle-error.ts
53
+ var GatewayLifecycleError = class extends Error {
54
+ name = "GatewayLifecycleError";
55
+ /** Stable discriminator, so callers branch on `code` rather than on message text. */
56
+ code;
57
+ constructor(opts) {
58
+ super(opts.message);
59
+ this.code = opts.code;
60
+ }
61
+ };
53
62
  var HookExecutor = class {
54
63
  constructor(hooks) {
55
64
  this.hooks = hooks;
@@ -66,9 +75,13 @@ var HookExecutor = class {
66
75
  try {
67
76
  decision = await h.pre_inbound(ctx);
68
77
  } catch (err) {
78
+ process.stderr.write(
79
+ `[gateway] pre_inbound hook "${h.name}" threw: ${Security.redact(err.message)}
80
+ `
81
+ );
69
82
  return {
70
83
  block: true,
71
- message: `hook ${h.name} threw: ${err.message}`
84
+ message: `Request blocked: hook "${h.name}" failed.`
72
85
  };
73
86
  }
74
87
  if (decision !== void 0 && decision.block === true) {
@@ -132,8 +145,19 @@ var GatewayRunner = class {
132
145
  command(name, handler) {
133
146
  this.commands.set(name, handler);
134
147
  }
135
- /** Connect all adapters and wire inbound dispatch. */
148
+ /**
149
+ * Connect all adapters and wire inbound dispatch.
150
+ *
151
+ * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
152
+ * stopped. A stopped runner is spent; construct a new one.
153
+ */
136
154
  async start() {
155
+ if (this.stopped) {
156
+ throw new GatewayLifecycleError({
157
+ code: "runner_stopped",
158
+ message: "GatewayRunner.start(): this runner has already been stopped and cannot be restarted. Construct a new GatewayRunner instead."
159
+ });
160
+ }
137
161
  if (this.connected) return;
138
162
  const connected = [];
139
163
  try {
@@ -174,10 +198,17 @@ var GatewayRunner = class {
174
198
  this.unsubs.length = 0;
175
199
  const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
176
200
  if (this.inflight.size > 0) {
177
- await Promise.race([
178
- Promise.all([...this.inflight]).then(() => void 0),
179
- new Promise((r) => setTimeout(r, drainMs))
180
- ]);
201
+ let timer;
202
+ try {
203
+ await Promise.race([
204
+ Promise.all([...this.inflight]).then(() => void 0),
205
+ new Promise((r) => {
206
+ timer = setTimeout(r, drainMs);
207
+ })
208
+ ]);
209
+ } finally {
210
+ if (timer !== void 0) clearTimeout(timer);
211
+ }
181
212
  }
182
213
  await Promise.all(
183
214
  [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => void 0))
@@ -238,24 +269,36 @@ var GatewayRunner = class {
238
269
  }
239
270
  /** EC-G: per-event ctx whose reply routes to the matching adapter. */
240
271
  buildContext(event) {
241
- const adapter = this.adaptersByPlatform.get(event.platform);
242
272
  return {
243
273
  event,
244
- reply: async (text, opts) => {
245
- if (adapter === void 0) {
246
- return {
247
- ok: false,
248
- error: { code: "no_adapter", message: `no adapter for ${event.platform}` }
249
- };
250
- }
251
- return adapter.sendMessage({
252
- channel: event.channel,
253
- text,
254
- ...opts?.format !== void 0 ? { format: opts.format } : {}
255
- });
256
- }
274
+ reply: async (text, opts) => this.deliver(event, {
275
+ channel: event.channel,
276
+ text,
277
+ ...opts?.format !== void 0 ? { format: opts.format } : {}
278
+ })
257
279
  };
258
280
  }
281
+ /**
282
+ * Send one outbound on behalf of `event` and report it to `post_outbound`.
283
+ *
284
+ * Every reply leaves through here so the hook fires exactly once per attempt —
285
+ * including the EC-D auto-reply, and including the attempt that finds no
286
+ * adapter for the platform. An audit hook that counted only the deliveries
287
+ * which reached a transport would omit precisely the ones that went nowhere.
288
+ *
289
+ * `post_outbound` observes; it does not intercept. The adapter's `SendResult`
290
+ * is returned to the caller unchanged, and `HookExecutor` already contains a
291
+ * throwing hook, so a broken observer cannot turn a delivered reply into a
292
+ * failed one.
293
+ *
294
+ * @internal
295
+ */
296
+ async deliver(event, outbound) {
297
+ const adapter = this.adaptersByPlatform.get(event.platform);
298
+ const result = adapter === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : await adapter.sendMessage(outbound);
299
+ await this.hookExecutor.firePostOutbound({ event, outbound, result });
300
+ return result;
301
+ }
259
302
  };
260
303
 
261
304
  // src/session/router.ts
@@ -364,6 +407,6 @@ function chunkByGrapheme(text, options) {
364
407
  return parts;
365
408
  }
366
409
 
367
- export { BasePlatformAdapter, DeliveryRouter, GatewayConfigurationError, GatewayRunner, HookExecutor, SessionRouter, chunkByGrapheme, chunkText, defaultStrategy };
410
+ export { BasePlatformAdapter, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SessionRouter, chunkByGrapheme, chunkText, defaultStrategy };
368
411
  //# sourceMappingURL=index.js.map
369
412
  //# sourceMappingURL=index.js.map