@theokit/gateway 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/text/fence.ts","../src/text/dialect.ts","../src/text/channel-rendering.ts","../src/adapter/base.ts","../src/text/seen-ids.ts","../src/adapter/weixin-xml.ts","../src/adapter/weixin-base.ts","../src/errors/config-error.ts","../src/channel/channel-config-readers.ts","../src/channel/channel-descriptor.ts","../src/channel/config-from-env.ts","../src/channel/create-channels.ts","../src/delivery/attachments.ts","../src/delivery/router.ts","../src/errors/lifecycle-error.ts","../src/security/credential-patterns.ts","../src/hooks/pairing-store.ts","../src/hooks/access-policy.ts","../src/hooks/chat-command.ts","../src/hooks/executor.ts","../src/runner/gateway-runner.ts","../src/runner/media-understanding.ts","../src/security/credential-store.ts","../src/session/router.ts","../src/session/bindings.ts","../src/session/scoped-strategy.ts","../src/text/chunk.ts","../src/text/split-rows.ts","../src/webhook/deliver-status.ts","../src/webhook/express-server.ts","../src/webhook/fetch-handler.ts"],"names":["check","invalid","isAbsent","code","refused","join","parts","plain","isLineEnd","startsTableRow","rowSafeCut","load"],"mappings":";;;;;;;AA+BA,IAAM,SAAA,GAAY,uBAAA;AAClB,IAAM,OAAA,GAAU,2BAAA;AAChB,IAAM,OAAA,GAAU,6BAAA;AAEhB,SAAS,SAAA,CAAU,MAAc,IAAA,EAA6C;AAC5E,EAAA,IAAI,GAAA,GAAM,IAAA;AACV,EAAA,OAAO,GAAA,GAAM,IAAA,CAAK,MAAA,IAAU,IAAA,CAAK,GAAG,CAAA,KAAM,IAAA,IAAQ,IAAA,CAAK,GAAG,CAAA,KAAM,IAAA,EAAM,GAAA,IAAO,CAAA;AAC7E,EAAA,IAAI,IAAA,GAAO,GAAA;AACX,EAAA,IAAI,IAAA,CAAK,IAAI,CAAA,KAAM,IAAA,IAAQ,KAAK,IAAA,GAAO,CAAC,C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AAO;AACd,MAAA,OAAA,CAAQ,OAAA,GAAU,UAAU,KAAK,CAAA;AACjC,MAAA,OAAO,MAAM,GAAG,CAAA;AAAA,IAClB;AAAA,EACF,CAAA;AACF;AAEA,SAAS,YAAA,CACP,SACA,OAAA,EACsB;AACtB,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,IAAW,CAAC,MAAM,CAAA;AAC1C,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,MAAA,CAAO,WAAA,EAAY;AAC1C,EAAA,IAAI,OAAA,CAAQ,KAAK,CAAC,CAAA,KAAM,EAAE,WAAA,EAAY,KAAM,MAAM,CAAA,EAAG,OAAO,MAAA;AAC5D,EAAA,OAAO,KAAA,CAAM,KAAK,EAAE,KAAA,EAAO,QAAQ,IAAA,CAAK,IAAI,GAAG,CAAA;AACjD;AAEA,eAAe,QAAA,CACb,OAAA,EACA,OAAA,EACA,OAAA,EACmB;AACnB,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,MAAA,EAAW,OAAO,cAAA,CAAe,MAAM,OAAA,CAAQ,MAAA,CAAO,OAAA,EAAS,OAAO,CAAC,CAAA;AAC9F,EAAA,OAAO,UAAA,CAAW,OAAA,EAAS,OAAA,EAAS,OAAO,CAAA;AAC7C","file":"index.js","sourcesContent":["/**\n * Fenced code block scanner (B-518).\n *\n * Reads the fences of CommonMark § 4.5: a line of at most three blanks, then three or more\n * backticks or tildes (an info string after a backtick run holds no backtick), closed by a line of\n * the same character, at least as many, and nothing after them but blanks. A fence never closed runs\n * to the end of the text. Fences inside a list item or block quote (indented four or more, or behind\n * a `>`) are not read.\n *\n * @public\n */\n\n/** One fenced code block, as offsets into the scanned text. */\nexport interface FenceRegion {\n /** Offset of the first character of the opening line. */\n readonly start: number;\n /** Offset just past the opening line, before its line ending. */\n readonly openerEnd: number;\n /** Offset of the first character after the opening line's line ending (the first code line). */\n readonly contentStart: number;\n /** Offset just past the last character of the closing line (its line ending excluded), or the text length when never closed. */\n readonly end: number;\n /** The opening line, byte for byte. */\n readonly opener: string;\n /** The marker run that closes the block: the opening run, without its indent. */\n readonly closer: string;\n /** False when the text ends before a closing line. */\n readonly closed: boolean;\n}\n\n/** A cheap test for any line that could open a fence, so text with none costs one regex pass. */\nconst MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;\nconst OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;\nconst CLOSING = /^ {0,3}(`{3,}|~{3,})[ \\t]*$/;\n\nfunction lineEndAt(text: string, from: number): { end: number; next: number } {\n let end = from;\n while (end < text.length && text[end] !== \"\\n\" && text[end] !== \"\\r\") end += 1;\n let next = end;\n if (text[next] === \"\\r\" && text[next + 1] === \"\\n\") next += 2;\n else if (next < text.length) next += 1;\n return { end, next };\n}\n\n/** The closing line of a fence opened with `run`, searched from `from`: where it ends, and where the next line starts. */\nfunction findClose(\n text: string,\n from: number,\n run: string,\n): { end: number; next: number } | undefined {\n for (let scan = from; scan < text.length; ) {\n const line = lineEndAt(text, scan);\n const found = CLOSING.exec(text.slice(scan, line.end))?.[1];\n if (found !== undefined && found[0] === run[0] && found.length >= run.length) return line;\n scan = line.next;\n }\n return undefined;\n}\n\n/** Every fenced region of `text`, in order. */\nexport function scanFences(text: string): readonly FenceRegion[] {\n if (!MAY_FENCE.test(text)) return [];\n const regions: FenceRegion[] = [];\n let pos = 0;\n while (pos < text.length) {\n const start = pos;\n const line = lineEndAt(text, start);\n const open = OPENING.exec(text.slice(start, line.end));\n const run = open?.[1];\n if (run === undefined || (run.startsWith(\"`\") && (open?.[2] ?? \"\").includes(\"`\"))) {\n pos = line.next;\n continue;\n }\n const close = findClose(text, line.next, run);\n pos = close?.next ?? text.length;\n const end = close?.end ?? text.length;\n const closed = close !== undefined;\n regions.push({\n start,\n openerEnd: line.end,\n contentStart: line.next,\n end,\n opener: text.slice(start, line.end),\n closer: run,\n closed,\n });\n }\n return regions;\n}\n\n/** The region `offset` falls strictly inside (after its first character, before its end), if any. */\nexport function fenceAt(regions: readonly FenceRegion[], offset: number): FenceRegion | undefined {\n return regions.find((r) => r.start < offset && offset < r.end);\n}\n\n/** The line ending that follows the opening line of `region` in `text` (`\\n` when the text ends there). */\nexport function openerEol(text: string, region: FenceRegion): string {\n if (text.startsWith(\"\\r\\n\", region.openerEnd)) return \"\\r\\n\";\n return text[region.openerEnd] === \"\\r\" ? \"\\r\" : \"\\n\";\n}\n","/**\n * Markdown → the target channel's own dialect (B-019 FR-005).\n *\n * ## Why this exists here, and not in an adapter\n *\n * Measured 2026-09-17 across every `adapter.ts` and `split.ts` in the ten packages: **no package\n * transforms a single character of text.** What exists is markdown ESCAPE (discord, mattermost),\n * HTML escape (email), phone normalisation (whatsapp) and post-cut newline cleanup (telegram's\n * splitter). `OutboundMessage.format` is read by all ten — `adapter-contract.test.ts` proves it —\n * but reading a flag is not translating a body.\n *\n * So the agent answered `**Bom Sucesso (MG)**` and both LINE and WhatsApp delivered the asterisks\n * to a real phone. The adapters refuse the translation deliberately and they are right to:\n * `gateway-whatsapp` reads `format` only to warn once, because emphasis there is inline in the\n * text rather than a transport flag. An adapter is transport.\n *\n * `gateway-signal`, added later, edits a body and stays on the transport side of that line:\n * Signal carries emphasis as `textStyle` ranges sent beside the text, so the adapter moves a\n * markdown reply's markers into those ranges. Its rendering row is `markdown` with identity, and\n * nothing here translates for it.\n *\n * `gateway-imessage`, `gateway-google-chat` and `gateway-irc`, added with it, send to platforms\n * with no markup at all, and their rendering rows are `plain`. A presenter given\n * `channelRendering(platform)` hands them text already translated and declared `plain`. A caller\n * that sends `format: \"markdown\"` without that step would put the asterisks in front of the user,\n * so those three adapters apply their own row in that one case, as a fallback. The presenter is\n * still where translation is decided, and the row they apply is the one it would have applied.\n *\n * Translation is PRESENTATION — it depends on what was said and on where it is going at the same\n * time — so it belongs to the presenter. It is exported from here as a pure function and CALLED by\n * the channel presenter in `theokit`, never the reverse: `@theokit/gateway` must not depend on\n * `@theokit/presenter`, or a gateway stops being usable without an agent.\n *\n * ## What it deliberately does NOT do\n *\n * It is not a markdown parser. It rewrites the four inline markers that reach a chat surface in\n * practice — bold, italic, strikethrough, inline code — and it leaves everything else alone:\n * links, headings, lists, block quotes and fenced code are untouched, because no measurement here\n * says what they should become on a platform with no equivalent.\n *\n * A platform it has not been taught is passed through UNCHANGED. Inventing a mapping would be\n * wrong invisibly; passing `**bold**` through is wrong where somebody can see it.\n */\n\nimport { scanFences } from \"./fence.js\";\n\n/** A dialect is what each of the four markers becomes. `undefined` means \"drop the marker\". */\nexport interface Dialect {\n readonly bold?: string;\n readonly italic?: string;\n readonly strike?: string;\n readonly code?: string;\n}\n\n/**\n * Per-platform dialects, and the reason each one is what it is.\n *\n * Only platforms whose dialect was actually established appear. The ones absent — telegram,\n * discord, slack, mattermost, matrix, teams, email — either parse markdown natively or take a\n * transport flag their adapter already sets, so rewriting their text would corrupt it.\n *\n * `channelRendering` reuses the whatsapp, line and sms rows rather than spelling them again. Like\n * `Dialect` and `rewriteMarkers`, it is exported for that module only: the package entry does not\n * re-export it, so no consumer can reach it.\n */\nexport const DIALECTS = {\n // WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.\n whatsapp: { bold: \"*\", italic: \"_\", strike: \"~\", code: \"```\" },\n // LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.\n line: {},\n // SMS is plain text by definition of the medium.\n sms: {},\n} as const satisfies Readonly<Record<string, Dialect>>;\n\n/**\n * Every marker in ONE pattern, matched in a single pass.\n *\n * Sequential `replace` calls cannot work here and the failure is silent: rewriting `**a**` to\n * WhatsApp's `*a*` produces text the italic rule then matches, so bold arrives as italic. Caught by\n * the first test written against this file — `**Bom Sucesso (MG)**` came out `_Bom Sucesso (MG)_`.\n *\n * Alternation order is load-bearing: `**` before `*`, `~~` before `~`.\n */\nconst PATTERN =\n /\\*\\*(?<bold>.+?)\\*\\*|~~(?<strike>.+?)~~|(?<![*\\w])\\*(?!\\s)(?<italicStar>.+?)(?<!\\s)\\*(?!\\*)|(?<![_\\w])_(?!\\s)(?<italicUnderscore>.+?)(?<!\\s)_(?!\\w)|`(?<code>.+?)`/gu;\n\n/**\n * Which capture group becomes which dialect marker, in the order `PATTERN` alternates.\n *\n * A table rather than a chain of conditionals, because the two ITALIC spellings make a chain read as\n * five decisions when it encodes one lookup — and biome measured the enclosing function at a\n * cognitive complexity of 26 against a ceiling of 10. Adding a marker is a row here and an\n * alternative in `PATTERN`; nothing else moves.\n *\n * Order here does NOT matter, and the first draft of this comment said it did. `PATTERN` alternates,\n * so at most one group carries a value per match — which is exactly why the loop may return on the\n * first one it finds. Checked rather than asserted: moving `italicStar` above `bold` leaves all\n * seven tests green, while deleting a row fails two. Order is load-bearing in `PATTERN`, not here.\n */\nconst GROUP_MARKERS = [\n [\"bold\", \"bold\"],\n [\"strike\", \"strike\"],\n [\"italicStar\", \"italic\"],\n [\"italicUnderscore\", \"italic\"],\n [\"code\", \"code\"],\n] as const satisfies ReadonlyArray<readonly [string, keyof Dialect]>;\n\n/**\n * Rewrite `text` for `platform`.\n *\n * @param text - the assembled answer, in markdown as the model produced it\n * @param platform - the destination; one this function has not been taught passes through\n * @returns the text in the platform's dialect, or unchanged when none is known\n * @public\n */\nexport function toDialect(text: string, platform: string): string {\n const dialect = (DIALECTS as Readonly<Record<string, Dialect>>)[platform];\n if (dialect === undefined) return text;\n return rewriteMarkers(text, dialect);\n}\n\n/** What the one `PATTERN` match whose named groups are `groups` becomes in `dialect`. */\nfunction markerFor(\n matched: string,\n groups: Record<string, string | undefined> | undefined,\n dialect: Dialect,\n): string {\n if (groups === undefined) return matched;\n\n for (const [group, marker] of GROUP_MARKERS) {\n const content = groups[group];\n if (content === undefined) continue;\n const wrap = dialect[marker];\n return wrap === undefined ? content : `${wrap}${content}${wrap}`;\n }\n\n // PATTERN matched and named no group: unreachable while every alternative above carries one,\n // and returning the match unchanged is the only answer that cannot corrupt text if it stops\n // being true. The same reason the whole module passes an unknown platform through.\n return matched;\n}\n\n/**\n * A replace callback's answer for one match. `PATTERN` has named groups, so the callback's last\n * argument is the groups object.\n */\nfunction rewriteMatch(matched: string, args: readonly unknown[], dialect: Dialect): string {\n return markerFor(matched, args.at(-1) as Record<string, string | undefined> | undefined, dialect);\n}\n\n/** One replace over `text`: the single pass the module comment above requires. */\nfunction replaceMarkers(text: string, dialect: Dialect): string {\n return text.replace(PATTERN, (matched, ...args) => rewriteMatch(matched, args, dialect));\n}\n\n/**\n * A table row: optional blanks, then a pipe (GFM 0.29 § 4.10). GFM also accepts a row with no\n * leading pipe under a delimiter row; reading those would mean reading the delimiter row, and no\n * measurement here asked for it (B-556 plan, glossary and ADR D1). Sticky, so it is tested at a line\n * start without slicing the line out. A template only: each caller copies it with `new RegExp`,\n * so no `lastIndex` is shared between calls.\n *\n * The splitters of gateway-line, gateway-sms and gateway-nextcloud-talk carry their own copy of\n * this definition (`startsTableRow` in each `src/split.ts`, plan ADR D2); a change here belongs\n * there too.\n */\nconst ROW_START = /[^\\S\\r\\n]*\\|/y;\n\n/** A line ending as GFM reads one: `\\r\\n`, `\\n`, or a lone `\\r`. Captured, so a split keeps it. */\nconst LINE_ENDING = /(\\r\\n|\\r|\\n)/;\n\n/**\n * Any character a marker can start with (`\\x60` is the backtick). A row without one has nothing\n * to rewrite.\n */\nconst MARKER_CHARACTER = /[*_~\\x60]/;\n\nconst PIPE = 0x7c;\nconst BACKSLASH = 0x5c;\nconst LF = 0x0a;\nconst CR = 0x0d;\n\n/**\n * Answers \"is the line holding `offset` a table row?\" for offsets that only grow, as a replace\n * callback's do. The cursor moves forward once over the text, so one long line full of matches is\n * scanned once rather than once per match.\n */\nfunction rowLocator(text: string): (offset: number) => boolean {\n const rowStart = new RegExp(ROW_START);\n let lineStart = 0;\n let scanned = 0;\n return (offset) => {\n for (; scanned < offset; scanned += 1) {\n const code = text.charCodeAt(scanned);\n if (code === LF || code === CR) lineStart = scanned + 1;\n }\n rowStart.lastIndex = lineStart;\n return rowStart.test(text);\n };\n}\n\n/**\n * Rewrite each cell of a table row on its own, keeping every pipe. A pipe preceded by an odd run\n * of backslashes is content (`\\|`), as GFM reads it. Inline code holding an unescaped pipe is split\n * there too, as GFM splits it, so its backticks no longer pair and are kept (B-556 EC-1).\n */\nfunction rewriteTableRow(row: string, dialect: Dialect): string {\n let out = \"\";\n let from = 0;\n let backslashes = 0;\n for (let i = 0; i < row.length; i += 1) {\n const code = row.charCodeAt(i);\n if (code === BACKSLASH) {\n backslashes += 1;\n continue;\n }\n if (code === PIPE && backslashes % 2 === 0) {\n out += `${replaceMarkers(row.slice(from, i), dialect)}|`;\n from = i + 1;\n }\n backslashes = 0;\n }\n return out + replaceMarkers(row.slice(from), dialect);\n}\n\n/**\n * A table row cell by cell; any other line, or a line ending, with the single pass. `rowStart` is\n * the caller's copy of `ROW_START`.\n */\nfunction rewriteLine(line: string, dialect: Dialect, rowStart: RegExp): string {\n rowStart.lastIndex = 0;\n if (!rowStart.test(line)) return replaceMarkers(line, dialect);\n return MARKER_CHARACTER.test(line) ? rewriteTableRow(line, dialect) : line;\n}\n\n/**\n * The text line by line. Splitting a line from its neighbours changes nothing for a line that is\n * not a row: `.` in `PATTERN` stops at `\\n` and `\\r`, so no match crosses a line, and each\n * lookaround sees a line ending and a string edge alike.\n */\nfunction rewriteByLine(text: string, dialect: Dialect): string {\n const rowStart = new RegExp(ROW_START);\n return text\n .split(LINE_ENDING)\n .map((piece) => rewriteLine(piece, dialect, rowStart))\n .join(\"\");\n}\n\n/**\n * Rewrite the four inline markers of `text` into `dialect`.\n *\n * Shared by `toDialect` and `channelRendering`, so the one regex whose ordering is load-bearing\n * exists once: a second copy is where the bold-becomes-italic defect above would come back.\n *\n * A table row is rewritten cell by cell (B-556 FR-001): one pass over the whole text let `*a | b*`\n * open in one cell and close in the next, and the platform then lost both markers. Today's single\n * pass runs first and its result is kept unless one of its matches holds a pipe and sits on a\n * table row; only then is the text rewritten line by line. Where no match crosses a row's pipe the\n * two agree, because a match inside one cell is the match the replace finds in that cell alone,\n * and the fast path keeps a plain table at the cost of today's pass (plan ADR D1).\n *\n * @param text - markdown as the model produced it\n * @param dialect - what each marker becomes; an absent marker is dropped and its content kept\n * @returns the rewritten text\n */\nexport function rewriteMarkers(text: string, dialect: Dialect): string {\n const regions = scanFences(text);\n if (regions.length === 0) return rewriteUnfenced(text, dialect);\n // A fenced block is code: its markers and its lines stay byte-identical (B-518).\n let out = \"\";\n let from = 0;\n for (const region of regions) {\n out +=\n rewriteUnfenced(text.slice(from, region.start), dialect) +\n text.slice(region.start, region.end);\n from = region.end;\n }\n return out + rewriteUnfenced(text.slice(from), dialect);\n}\n\n/** The rewrite of text holding no fenced block: the single pass, or the row-by-row pass. */\nfunction rewriteUnfenced(text: string, dialect: Dialect): string {\n const onTableRow = rowLocator(text);\n let crossesRowPipe = false;\n // The third argument from the last of a replace callback is the match's offset.\n const rewritten = text.replace(PATTERN, (matched, ...args) => {\n if (!crossesRowPipe && matched.includes(\"|\")) {\n crossesRowPipe = onTableRow(args.at(-3) as number);\n }\n return rewriteMatch(matched, args, dialect);\n });\n return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;\n}\n","/**\n * What `ChatPresenter` needs to know about one platform: how to rewrite the text, and which\n * `format` to declare on the message (B-019 FR-001, FR-002).\n *\n * `toDialect` alone is not enough, and composing it with the presenter's defaults proved it:\n * `ChatPresenter` declares `markdown` unless told otherwise, and `toDialect` passes a platform it\n * was not taught through unchanged. So matrix and email put `**bold**` on the wire as characters\n * (matrix drops `markdown` with a warning, email escapes it into `<pre>`), and telegram and slack\n * were handed a bold spelled for a dialect whose bold is a single asterisk. The text rewrite and\n * the format flag have to be chosen together, per platform, by the package that knows what each\n * adapter does with `format` — this one.\n *\n * Pure data and pure functions: no I/O, and the same input always gives the same output.\n * `@theokit/gateway` still does not depend on `@theokit/presenter`; `ChannelRendering` matches\n * the presenter's `translate` and `format` options structurally.\n */\n\nimport type { PlatformName } from \"../types/message-event.js\";\nimport { DIALECTS, type Dialect, rewriteMarkers } from \"./dialect.js\";\n\n/**\n * The pair a consumer spreads into `ChatPresenter`'s options for one platform.\n *\n * @public\n */\nexport interface ChannelRendering {\n /** The rendering hint the adapter receives as `OutboundMessage.format`. */\n readonly format: \"plain\" | \"markdown\";\n /** Rewrites the assembled answer for the platform. Pure and deterministic. */\n readonly translate: (text: string) => string;\n}\n\n/**\n * Slack's mrkdwn: emphasis is a single character, `*bold*`, `_italic_`, `~strike~`, and inline\n * code keeps its backtick (https://api.slack.com/reference/surfaces/formatting).\n */\nconst SLACK: Dialect = { bold: \"*\", italic: \"_\", strike: \"~\", code: \"`\" };\n\n/** No marker survives; the content they wrapped does. */\nconst STRIP: Dialect = {};\n\nconst identity = (text: string): string => text;\n\nconst translateWith =\n (dialect: Dialect) =>\n (text: string): string =>\n rewriteMarkers(text, dialect);\n\n/**\n * One row per platform. A `Record` over `PlatformName`, so a platform added to the union without\n * a row here is a compile error rather than a silent fallback.\n *\n * - whatsapp: inline single-character emphasis in the text, and `plain`, because its adapter\n * carries no formatting flag on a text message.\n * - slack: the same emphasis, declared `markdown` so the adapter sets `mrkdwn`.\n * - discord, mattermost, teams: markdown is what they render, so the text passes through.\n * - signal: `markdown`, passed through; its adapter turns the markers into Signal's `textStyle`\n * ranges, so the text it sends carries no marker characters.\n * - line, sms: no rich text at all; the existing `toDialect` rows drop the markers.\n * - imessage: markers dropped and `plain`. `imsg` sends the text as typed, and Messages shows a\n * marker character as itself.\n * - google_chat: markers dropped and `plain`. Chat's own markup is close to, but not, markdown, and\n * how it renders a reply is unmeasured until a live run (plan Q3).\n * - nextcloud_talk: `markdown`, passed through. Talk renders the markdown a bot sends (the Q6\n * probe's inbound bodies carry `mediaType: \"text/markdown\"`).\n * - irc: markers dropped and `plain`. IRC has no markdown; its own formatting is control bytes,\n * and a marker character reaches the channel as itself.\n * - telegram: markers dropped and `plain`. Its adapter maps `markdown` to legacy Markdown, which\n * refuses a reply with an unpaired `_` or `*` and loses it with no retry; losing emphasis is the\n * cheaper failure (plan ADR D3).\n * - matrix, email: markers dropped and `plain`. Neither renders `markdown` (see the module comment),\n * and producing HTML would need a markdown renderer this package does not have.\n * - buzz: markers dropped and `plain`; this adapter does not claim Buzz renders markdown.\n * - clickclack: markers dropped and `plain`; this adapter does not claim ClickClack renders markdown.\n * - zalo_personal, zalo, wechat, wecom, yuanbao, raft, x, qq: markers dropped and `plain`. Zalo shows a marker character as itself.\n * - nostr, feishu_lark, synology_chat, tlon_urbit, twitch: markers dropped and `plain`. Nostr and\n * Twitch chat show a marker character as itself; Lark posts and Tlon inline styles are richer\n * formats this package does not map yet, so emphasis is lost rather than spelled (plan ADR D3).\n */\nconst RENDERINGS: Readonly<Record<PlatformName, ChannelRendering>> = {\n whatsapp: { format: \"plain\", translate: translateWith(DIALECTS.whatsapp) },\n slack: { format: \"markdown\", translate: translateWith(SLACK) },\n discord: { format: \"markdown\", translate: identity },\n mattermost: { format: \"markdown\", translate: identity },\n teams: { format: \"markdown\", translate: identity },\n signal: { format: \"markdown\", translate: identity },\n line: { format: \"plain\", translate: translateWith(DIALECTS.line) },\n sms: { format: \"plain\", translate: translateWith(DIALECTS.sms) },\n telegram: { format: \"plain\", translate: translateWith(STRIP) },\n matrix: { format: \"plain\", translate: translateWith(STRIP) },\n email: { format: \"plain\", translate: translateWith(STRIP) },\n imessage: { format: \"plain\", translate: translateWith(STRIP) },\n google_chat: { format: \"plain\", translate: translateWith(STRIP) },\n irc: { format: \"plain\", translate: translateWith(STRIP) },\n nextcloud_talk: { format: \"markdown\", translate: identity },\n nostr: { format: \"plain\", translate: translateWith(STRIP) },\n feishu_lark: { format: \"plain\", translate: translateWith(STRIP) },\n synology_chat: { format: \"plain\", translate: translateWith(STRIP) },\n tlon_urbit: { format: \"plain\", translate: translateWith(STRIP) },\n twitch: { format: \"plain\", translate: translateWith(STRIP) },\n buzz: { format: \"plain\", translate: translateWith(STRIP) },\n clickclack: { format: \"plain\", translate: translateWith(STRIP) },\n zalo_personal: { format: \"plain\", translate: translateWith(STRIP) },\n zalo: { format: \"plain\", translate: translateWith(STRIP) },\n wechat: { format: \"plain\", translate: translateWith(STRIP) },\n wecom: { format: \"plain\", translate: translateWith(STRIP) },\n yuanbao: { format: \"plain\", translate: translateWith(STRIP) },\n qq: { format: \"plain\", translate: translateWith(STRIP) },\n x: { format: \"plain\", translate: translateWith(STRIP) },\n raft: { format: \"plain\", translate: translateWith(STRIP) },\n};\n\n/**\n * The rendering `ChatPresenter` needs for `platform`.\n *\n * Only the four inline markers `toDialect` knows are rewritten: bold, italic, strikethrough and\n * inline code. Headings, links, lists and block quotes pass through on every platform, and fenced\n * code is not handled yet (the inline-code rule rewrites a fence's backticks).\n *\n * @param platform - the destination, typically `event.platform` of the inbound message\n * @returns the `{ translate, format }` pair for that platform\n * @throws RangeError when `platform` is not one of the platforms this package knows. Answering with\n * nothing would let the presenter fall back to identity and `markdown`, which is the defect this\n * function exists to remove.\n * @public\n */\nexport function channelRendering(platform: PlatformName): ChannelRendering {\n const rendering: ChannelRendering | undefined = Object.hasOwn(RENDERINGS, platform)\n ? RENDERINGS[platform]\n : undefined;\n if (rendering === undefined) {\n throw new RangeError(\n `channelRendering: unknown platform \"${String(platform)}\"; expected one of ${Object.keys(RENDERINGS).join(\", \")}`,\n );\n }\n return rendering;\n}\n","/**\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 { channelRendering } from \"../text/channel-rendering.js\";\nimport type { SeenIds } from \"../text/seen-ids.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/**\n * An image an outbound message carries: its bytes and their media type (B-674).\n *\n * The bytes travel by reference: the runner does not copy them on the way to the adapter. The\n * caller must not change `data` or the list until the send's promise settles: an adapter that\n * sends several attachments reads each one only when its turn comes.\n */\ninterface OutboundImageAttachment {\n readonly kind: \"image\";\n /** The media type of `data`, such as `image/png`. */\n readonly mediaType: string;\n readonly data: Uint8Array;\n /** A file name the platform may show; optional. */\n readonly filename?: string;\n}\n\n/** An audio clip an outbound message carries, such as a spoken reply (B-715). Same rules as an image. */\ninterface OutboundAudioAttachment {\n readonly kind: \"audio\";\n /** The media type of `data`, such as `audio/ogg`. */\n readonly mediaType: string;\n readonly data: Uint8Array;\n /** A file name the platform may show; optional. */\n readonly filename?: string;\n}\n\n/** An attachment an outbound message carries, told apart by `kind`. */\nexport type OutboundAttachment = OutboundImageAttachment | OutboundAudioAttachment;\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 * Images to send with the text. An adapter whose {@link BasePlatformAdapter.supportsAttachments}\n * is `false` refuses a non-empty list with `attachments_unsupported`; it never drops it.\n */\n readonly attachments?: ReadonlyArray<OutboundAttachment>;\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/** The facts about an adapter that an app picks its rendering from. */\nexport interface AdapterCapabilities {\n readonly edit: boolean;\n /** The attachment kinds the adapter sends; `[]` when none. */\n readonly attachments: ReadonlyArray<OutboundAttachment[\"kind\"]>;\n readonly typing: boolean;\n readonly reactions: boolean;\n readonly threads: boolean;\n /** Longest text one message holds; `undefined` when the adapter does not know. */\n readonly maxMessageChars?: number;\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; `editMessage` refuses\n * with `edit_unsupported` 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 and no attachments returns `{ ok: false, code: \"empty_text\" }`.\n * An adapter that refuses attachments answers `attachments_unsupported` first, and one that\n * sends them (Telegram) accepts empty text with an image.\n * - `supportsEdit` says whether the adapter has an edit call. It is `false` unless the adapter\n * overrides it, and it MUST NOT change with `connect()`. `true` does not promise that every\n * edit is accepted: an adapter whose injected client lacks the edit call (Matrix) still answers\n * `edit_unsupported`, which a caller handles like any other refusal.\n * - `editMessage` returns a `SendResult` and never throws on platform errors. The default refuses\n * with `edit_unsupported` and makes no platform call.\n * - `supportsAttachments` says whether `sendMessage` can send `out.attachments`. It is `false`\n * unless the adapter overrides it, and it MUST NOT change with `connect()`. An adapter that\n * does not support them refuses a non-empty list with `attachments_unsupported` and makes no\n * platform call; an edit carrying an attachment is refused the same way.\n * - Edits are not ordered by the adapter. Two edits of one message id in flight at once reach the\n * platform in either order, so a caller awaits each edit before the next, or keeps one in flight\n * and coalesces to the latest 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 every\n * adapter 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 /** The handler {@link subscribe} holds; `undefined` while nobody is subscribed. */\n protected subscribedHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n\n /** The body of {@link onInbound}: replace the handler, and unsubscribe only if it is still the one held. */\n protected subscribe(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n this.subscribedHandler = handler;\n return () => {\n if (this.subscribedHandler === handler) this.subscribedHandler = undefined;\n };\n }\n\n /** The body of {@link deliver} for an adapter that subscribed through {@link subscribe}. */\n protected deliverInbound(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.subscribedHandler, event);\n }\n\n /**\n * Dispatch a webhook event once: `duplicate` when `seen` holds its id, `no_handler` when nobody\n * subscribed (the id is then NOT remembered, so a redelivery is handled), otherwise remember the\n * id and run the handler. A handler's throw is also logged under `label`.\n */\n protected async dispatchOnce(\n seen: SeenIds,\n event: GatewayMessageEvent,\n label: string,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\" | \"duplicate\"> {\n if (seen.has(event.id)) return \"duplicate\";\n if (this.subscribedHandler === undefined) return \"no_handler\";\n seen.add(event.id);\n const outcome = await this.runHandler(this.subscribedHandler, event);\n if (outcome === \"handler_threw\") process.stderr.write(`[${label}] handler threw\\n`);\n return outcome;\n }\n\n /** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */\n protected outboundText(out: OutboundMessage): string {\n return out.format === \"markdown\"\n ? channelRendering(this.platform).translate(out.text)\n : out.text;\n }\n\n /**\n * The local checks every text-only `sendMessage` makes before a request, in this order:\n * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.\n * Returns the refusal, or `undefined` when the message may be sent.\n */\n protected refuseUnsendable(\n out: OutboundMessage,\n check: {\n readonly className: string;\n readonly connected: boolean;\n readonly channel?: { readonly valid: (id: string) => boolean; readonly message: string };\n },\n ): SendResult | undefined {\n const refuse = (code: string, message: string): SendResult => ({\n ok: false,\n error: { code, message },\n });\n if (out.text.length === 0) return refuse(\"empty_text\", \"outbound text is empty\");\n if (!check.connected) {\n return refuse(\"not_connected\", `${check.className}.connect() has not succeeded`);\n }\n if (check.channel !== undefined && !check.channel.valid(out.channel.id)) {\n return refuse(\"invalid_channel\", check.channel.message);\n }\n return undefined;\n }\n\n /**\n * Whether {@link editMessage} can replace the text of a message this adapter sent.\n *\n * Read it before starting a preview: on `false`, send the final text instead. An adapter sets\n * it at construction and MUST NOT change it with `connect()`. Annotated as `boolean` so that an\n * edit-capable adapter can override it with `true`.\n */\n readonly supportsEdit: boolean = false;\n\n /**\n * Whether {@link sendMessage} can send the images of `out.attachments` (B-674).\n *\n * Read it before attaching: on `false`, the adapter refuses a non-empty list with\n * `attachments_unsupported`. Set at construction, never changed by `connect()`. Annotated as\n * `boolean` so that an adapter that sends images can override it with `true`.\n */\n readonly supportsAttachments: boolean = false;\n\n /**\n * The attachment kinds {@link sendMessage} can send. `undefined` means \"not declared\": the\n * `capabilities` getter then reports `[\"image\"]` when `supportsAttachments` is `true`, else `[]`.\n */\n protected readonly attachmentKinds: ReadonlyArray<OutboundAttachment[\"kind\"]> | undefined =\n undefined;\n\n /**\n * What this adapter can do, for an app that renders differently per channel.\n *\n * Derived from the members above and from which lifecycle methods the subclass overrides; an\n * adapter overrides the getter only for what derivation cannot know. Read it at call time.\n */\n get capabilities(): AdapterCapabilities {\n const proto = BasePlatformAdapter.prototype;\n return {\n edit: this.supportsEdit,\n attachments: this.attachmentKinds ?? (this.supportsAttachments ? [\"image\"] : []),\n typing: this.startTyping !== proto.startTyping,\n reactions: this.react !== proto.react,\n threads: false,\n };\n }\n\n /**\n * Replace the text of a message this adapter sent, keeping its id.\n *\n * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never\n * throws on platform errors. An edit-capable adapter applies, with no request, the same local\n * checks its `sendMessage` applies (such as `empty_text`, and `not_connected` where the send\n * checks the connection), plus `invalid_message_id`, and `edit_too_long` where the adapter\n * splits text: an edit that would need more than one platform message is refused, never split.\n *\n * Default: refuses with `edit_unsupported`, makes no platform call, and checks nothing else\n * first, so capability is answered before input.\n */\n async editMessage(_messageId: string, _out: OutboundMessage): Promise<SendResult> {\n return {\n ok: false,\n error: {\n code: \"edit_unsupported\",\n message: `${this.platform} adapter cannot edit a sent message`,\n },\n };\n }\n\n /**\n * React to an inbound message with an emoji (for example 👀 as an acknowledgement).\n *\n * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never\n * throws on platform errors. `channelId` is the channel the message is in and `messageId` the\n * id the inbound event carried.\n *\n * Default: resolves `{ ok: false, error: { code: \"react_unsupported\" } }` and makes no\n * platform call.\n */\n async react(_channelId: string, _messageId: string, _emoji: string): Promise<SendResult> {\n return {\n ok: false,\n error: {\n code: \"react_unsupported\",\n message: `${this.platform} adapter cannot react to a message`,\n },\n };\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 * A bounded set of ids, oldest evicted first, so a long-running process remembers what it delivered\n * without growing for ever (NFR-003).\n */\n\nconst DEFAULT_LIMIT = 1_000;\n\n/**\n * The ids an adapter has already delivered, at most `limit` of them.\n */\nexport class SeenIds {\n private readonly ids = new Set<string>();\n\n /** @param limit the most ids held at once; the oldest is forgotten when one more arrives */\n constructor(private readonly limit: number = DEFAULT_LIMIT) {}\n\n /**\n * Record `id`.\n *\n * @returns `true` when the id was new, `false` when it was already held\n */\n add(id: string): boolean {\n if (this.ids.has(id)) return false;\n this.ids.add(id);\n if (this.ids.size > this.limit) {\n const oldest = this.ids.values().next().value;\n if (oldest !== undefined) this.ids.delete(oldest);\n }\n return true;\n }\n\n /** Whether `id` is held. */\n has(id: string): boolean {\n return this.ids.has(id);\n }\n\n /** How many ids are held. */\n get size(): number {\n return this.ids.size;\n }\n}\n","/**\n * Read the flat XML the Tencent webhook platforms (WeChat, WeCom) push:\n * `<xml><Tag><![CDATA[v]]></Tag>…</xml>`. The messages these adapters take have no nesting, so a\n * tag scan is enough and no XML library is needed.\n *\n * @public\n */\nexport function parseFlatXml(xml: string): Record<string, string> {\n const out: Record<string, string> = {};\n const tag = /<([A-Za-z][A-Za-z0-9]*)>(?:<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>|([^<]*))<\\/\\1>/g;\n for (const m of xml.matchAll(tag)) {\n const name = m[1];\n if (name !== undefined && name !== \"xml\") out[name] = m[2] ?? decodeEntities(m[3] ?? \"\");\n }\n return out;\n}\n\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&amp;/g, \"&\");\n}\n","/**\n * `WeixinAdapterBase` — the connect / token / send / dispatch flow that the WeChat and WeCom\n * adapters share. A subclass supplies the platform's endpoints, its signature check and its event\n * shape; this class owns everything else.\n *\n * @public\n */\n\nimport { SeenIds } from \"../text/seen-ids.js\";\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"./base.js\";\nimport { parseFlatXml } from \"./weixin-xml.js\";\n\nconst REQUEST_TIMEOUT_MS = 30_000;\n/** Refresh this long before the token's stated expiry. */\nconst TOKEN_MARGIN_MS = 60_000;\n\n/** A `fetch`-shaped function; the adapter's only network seam. @public */\nexport type WeixinFetch = (\n url: string,\n init: { method: string; headers: Record<string, string>; body?: string },\n) => Promise<{ status: number; text(): Promise<string> }>;\n\n/**\n * What a webhook route answers. `body` is the text to write back; anything but 200 makes the\n * platform retry.\n *\n * @public\n */\nexport type WeixinWebhookAnswer = {\n readonly status: 200 | 400 | 401 | 503;\n readonly body: string;\n readonly reason: string;\n};\n\n/** What a subclass tells the base about its platform. @public */\nexport interface WeixinAdapterConfig {\n /** Log prefix, e.g. `gateway-wechat`. */\n readonly label: string;\n /** Class name used in the `not_connected` message, e.g. `WeChatAdapter`. */\n readonly className: string;\n /** Brand used in messages, e.g. `WeChat`. */\n readonly brand: string;\n /** What `channel.id` must be, e.g. `a WeChat OpenID`. */\n readonly userNoun: string;\n /** API base used when `apiBase` is not set. */\n readonly defaultBase: string;\n readonly apiBase?: string;\n readonly fetch?: WeixinFetch;\n}\n\n/** One send call: a path (with its access token) and a JSON payload. @public */\nexport interface WeixinSendRequest {\n readonly path: string;\n readonly payload: unknown;\n}\n\ninterface ApiBody {\n errcode?: number;\n errmsg?: string;\n access_token?: string;\n expires_in?: number;\n}\n\nconst defaultFetch: WeixinFetch = async (url, init) => {\n const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });\n return { status: res.status, text: () => res.text() };\n};\n\nfunction weixinMessageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nfunction weixinAck(reason: string): WeixinWebhookAnswer {\n return { status: 200, body: \"success\", reason };\n}\n\n/**\n * Shared base of the WeChat and WeCom adapters.\n *\n * @public\n */\nexport abstract class WeixinAdapterBase extends BasePlatformAdapter {\n private readonly cfg: WeixinAdapterConfig;\n private readonly doFetch: WeixinFetch;\n private connected = false;\n private accessToken: { value: string; expiresAt: number } | undefined;\n private readonly seen = new SeenIds();\n\n constructor(cfg: WeixinAdapterConfig) {\n super();\n this.cfg = cfg;\n this.doFetch = cfg.fetch ?? defaultFetch;\n }\n\n /** Path and query of the access-token request. */\n protected abstract tokenPath(): string;\n /** The send call for one part of a reply. */\n protected abstract sendRequest(token: string, userId: string, content: string): WeixinSendRequest;\n /** Cut a reply into parts the platform accepts. */\n protected abstract split(text: string): string[];\n /** The event for a text message, `\"skip\"` for another type, `undefined` for a text with gaps. */\n protected abstract toEvent(\n fields: Record<string, string>,\n ): GatewayMessageEvent | \"skip\" | undefined;\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await this.token(true);\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[${this.cfg.label}] connect failed: ${weixinMessageOf(err)}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.accessToken = undefined;\n }\n\n /** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */\n protected async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (!this.connected) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: `${this.cfg.className}.connect() has not succeeded`,\n },\n };\n }\n if (out.channel.id === \"\") {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id must be ${this.cfg.userNoun}` },\n };\n }\n return this.sendParts(out);\n }\n\n private async sendParts(out: OutboundMessage): Promise<SendResult> {\n const failed = `${this.platform}_send_failed`;\n try {\n for (const content of this.split(this.outboundText(out))) {\n const token = await this.token(false);\n const req = this.sendRequest(token, out.channel.id, content);\n const body = await this.call(\"POST\", req.path, req.payload);\n if (body.errcode !== 0) {\n return {\n ok: false,\n error: {\n code: failed,\n message: `${this.cfg.brand} error ${String(body.errcode)}: ${String(body.errmsg)}`,\n },\n };\n }\n }\n } catch (err) {\n return { ok: false, error: { code: failed, message: weixinMessageOf(err) } };\n }\n // The send answer carries no message id a reply needs.\n return { ok: true, messageId: \"\" };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n return this.subscribe(handler);\n }\n\n /** Deliver an event that arrived out of band, through `runHandler`. */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.deliverInbound(event);\n }\n\n /** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */\n protected async handleMessage(xml: string): Promise<WeixinWebhookAnswer> {\n const event = this.toEvent(parseFlatXml(xml));\n if (event === \"skip\") return weixinAck(\"not a text message\");\n if (event === undefined) return { status: 400, body: \"\", reason: \"incomplete\" };\n const outcome = await this.dispatchOnce(this.seen, event, this.cfg.label);\n if (outcome === \"no_handler\") return { status: 503, body: \"\", reason: \"no handler subscribed\" };\n return weixinAck(outcome);\n }\n\n private async token(force: boolean): Promise<string> {\n const cached = this.accessToken;\n if (!force && cached !== undefined && cached.expiresAt - TOKEN_MARGIN_MS > Date.now()) {\n return cached.value;\n }\n const body = await this.call(\"GET\", this.tokenPath());\n if (body.errcode !== undefined && body.errcode !== 0) {\n throw new Error(`token answered error ${String(body.errcode)}: ${String(body.errmsg)}`);\n }\n if (!body.access_token) throw new Error(\"token answer has no access_token\");\n this.accessToken = {\n value: body.access_token,\n expiresAt: Date.now() + (body.expires_in ?? 7200) * 1000,\n };\n return body.access_token;\n }\n\n private async call(method: \"GET\" | \"POST\", path: string, payload?: unknown): Promise<ApiBody> {\n const res = await this.doFetch((this.cfg.apiBase ?? this.cfg.defaultBase) + path, {\n method,\n headers: { \"Content-Type\": \"application/json\" },\n ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),\n });\n const text = await res.text();\n try {\n return JSON.parse(text) as ApiBody;\n } catch {\n throw new Error(`${this.cfg.brand} answered HTTP ${res.status} with a non-JSON body`);\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 * `channelConfigReaders` — the config readers every channel's `create` needs, written once.\n *\n * Each channel package used to carry its own copy of `invalid`, `readString`, `requiredString`\n * and friends; only the error prefix differed. The readers throw a configuration error coded\n * `invalid_config` with the message `${prefix}: config.${key} must be ${expected}`.\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\n\n/** A channel's config object, as `create` receives it. */\nexport type ChannelConfigInput = Readonly<Record<string, unknown>>;\n\n/** The readers bound to one package prefix. */\nexport interface ChannelConfigReaders {\n /** Builds (does not throw) the `invalid_config` error for `key`. */\n invalid(key: string, expected: string): GatewayConfigurationError;\n /** `undefined`, `null` and `\"\"` are absent. */\n isAbsent(value: unknown): boolean;\n /** An optional string; absent gives `undefined`, a non-string throws. */\n readString(config: ChannelConfigInput, key: string): string | undefined;\n /** A required string; absent, empty or a non-string throws. */\n requiredString(config: ChannelConfigInput, key: string): string;\n /** An optional boolean; absent gives `undefined`, a non-boolean throws. */\n readBoolean(config: ChannelConfigInput, key: string): boolean | undefined;\n /** An optional number: a finite number or a digit string; anything else throws. */\n readNumber(config: ChannelConfigInput, key: string): number | undefined;\n /** An optional boolean as a boolean or the string `\"true\"`/`\"false\"`; anything else throws. */\n readBooleanString(config: ChannelConfigInput, key: string): boolean | undefined;\n /** An optional list of strings: an array or a comma-separated string (items trimmed). */\n readList(config: ChannelConfigInput, key: string): string[] | undefined;\n /**\n * An optional function; absent gives `undefined`, a non-function throws. Only callability is\n * checked: the caller names the signature `T` and is responsible for it.\n */\n readFunction<T extends (...args: never[]) => unknown>(\n config: ChannelConfigInput,\n key: string,\n ): T | undefined;\n}\n\n/**\n * Returns the config readers for a package.\n *\n * @param prefix Package prefix in every message, e.g. `\"gateway-line\"`.\n * @param createError Builds the error to throw; defaults to `GatewayConfigurationError`. Pass a\n * package's own subclass to keep its `instanceof` contract.\n */\nexport function channelConfigReaders(\n prefix: string,\n createError: (options: {\n readonly code: string;\n readonly message: string;\n readonly detail: string;\n }) => GatewayConfigurationError = (options) => new GatewayConfigurationError(prefix, options),\n): ChannelConfigReaders {\n const invalid = (key: string, expected: string): GatewayConfigurationError =>\n createError({\n code: \"invalid_config\",\n message: `${prefix}: config.${key} must be ${expected}`,\n detail: key,\n });\n const isAbsent = (value: unknown): boolean =>\n value === undefined || value === null || value === \"\";\n const readString = (config: ChannelConfigInput, key: string): string | undefined => {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value !== \"string\") throw invalid(key, \"a string\");\n return value;\n };\n return {\n invalid,\n isAbsent,\n readString,\n requiredString(config, key) {\n const value = config[key];\n if (typeof value !== \"string\" || value === \"\") throw invalid(key, \"a non-empty string\");\n return value;\n },\n readBoolean(config, key) {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value !== \"boolean\") throw invalid(key, \"a boolean\");\n return value;\n },\n readNumber(config, key) {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && /^\\d+$/.test(value)) return Number(value);\n throw invalid(key, \"a number or a digit string\");\n },\n readBooleanString(config, key) {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value === \"boolean\") return value;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n throw invalid(key, 'a boolean or \"true\"/\"false\"');\n },\n readList(config, key) {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value === \"string\") {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item !== \"\");\n }\n if (!Array.isArray(value) || !value.every((item) => typeof item === \"string\")) {\n throw invalid(key, \"an array of strings or a comma-separated string\");\n }\n return value;\n },\n readFunction<T extends (...args: never[]) => unknown>(\n config: ChannelConfigInput,\n key: string,\n ): T | undefined {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value !== \"function\") throw invalid(key, \"a function\");\n return value as T;\n },\n };\n}\n","/**\n * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).\n *\n * A platform package exports one static descriptor: the config fields its channel needs, how to\n * build its adapter from them, and, for a channel that receives webhooks, how to verify and ingest\n * a request. An app then wires every channel with the same loop (`createChannels`) instead of one\n * branch per platform. The core only reads these shapes; it never names a platform.\n *\n * @public\n */\n\nimport type { BasePlatformAdapter } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** One configuration field a channel reads. */\nexport interface ChannelConfigField {\n /** The key `create` reads from its config object. */\n readonly key: string;\n /** A required field that is absent, `null` or `\"\"` rejects the channel before `create` runs. */\n readonly required: boolean;\n /** The value is a credential: never log it, and keep it out of anything shown to a user. */\n readonly secret: boolean;\n /** What the field is, for a human configuring the channel. */\n readonly description: string;\n /** Variable name without the app prefix, e.g. `\"TELEGRAM_TOKEN\"`. Read by `configFromEnv`. */\n readonly env?: string;\n}\n\n/** A webhook request as the app's HTTP layer received it, before anything parsed the body. */\nexport interface WebhookRequest {\n /** The exact request bytes as text; signatures are computed over them. */\n readonly rawBody: string;\n /** Request headers. Descriptors look a header up without regard to case. */\n readonly headers: Readonly<Record<string, string | undefined>>;\n /** The HTTP method. Always set by `createWebhookHandler`; optional so existing callers compile. */\n readonly method?: string;\n /** The full request URL, query included. Always set by `createWebhookHandler`. */\n readonly url?: string;\n}\n\n/** The answer a channel's `handle` gives for one webhook request. */\nexport interface WebhookAnswer {\n /** The HTTP status. */\n readonly status: number;\n /** The response body, when the platform expects one. */\n readonly body?: string;\n /** The response `content-type`. */\n readonly contentType?: string;\n}\n\n/**\n * What `ingest` did with a verified payload: `\"delivered\"` dispatched it, `\"malformed\"` refused it\n * without dispatching, and `\"no_handler\"` dispatched nothing because the payload holds a message\n * for the handler and none is subscribed (before the runner starts, after it stops, or for an\n * adapter whose connect failed under `connectFailure: \"isolate\"`). Answer only `\"delivered\"` with\n * a success status, so a platform that redelivers can send the rest again.\n */\nexport type IngestResult = \"delivered\" | \"malformed\" | \"no_handler\";\n\n/**\n * The webhook half of a channel: verify a request, then hand its payload to the adapter.\n *\n * `verify` and `ingest` are declared as methods on purpose. Method parameters are bivariant, which\n * is what lets a descriptor typed for its own adapter class sit in a list of\n * `ChannelDescriptor<BasePlatformAdapter>`; written as function-typed properties, that assignment\n * would fail under `strictFunctionTypes`.\n */\nexport interface ChannelWebhook<TAdapter extends BasePlatformAdapter> {\n /** `true` when the request carries a valid signature for this adapter's credentials. */\n verify(adapter: TAdapter, request: WebhookRequest): boolean;\n /** Dispatch a parsed, verified payload, or report it malformed without dispatching. */\n ingest(adapter: TAdapter, payload: unknown): Promise<IngestResult>;\n /** Methods the route takes. Default `[\"POST\"]`. */\n readonly methods?: readonly string[];\n /** Full control of one request. When absent, the handler runs verify, JSON.parse and ingest. */\n handle?(adapter: TAdapter, request: WebhookRequest): Promise<WebhookAnswer>;\n}\n\n/**\n * Whether a channel's `sender.id` is proven by the platform. An email From header or an SMS caller\n * id is written by the sender (CWE-290), so such a channel declares why it cannot be trusted.\n *\n * @public\n */\nexport type SenderIdentity =\n | \"authenticated\"\n /** Why the sender id can be forged, for error messages. */\n | { readonly unauthenticated: string };\n\ninterface ChannelDescriptorBase<TAdapter extends BasePlatformAdapter> {\n /** The platform the built adapter reports as its `platform`. */\n readonly platform: PlatformName;\n /** Every field `create` reads. */\n readonly config: ReadonlyArray<ChannelConfigField>;\n /**\n * Build the adapter. Throws a `GatewayConfigurationError` (or a subclass) for a value it refuses,\n * which `createChannels` reports as a rejected channel; it performs no network call.\n */\n create(config: Readonly<Record<string, unknown>>): TAdapter;\n /**\n * Whether `sender.id` is authenticated. Absent means unknown and is treated as not\n * authenticated (fail closed); it is optional only so descriptors in other packages keep compiling.\n */\n readonly senderIdentity?: SenderIdentity;\n /**\n * Alternative config shapes for the same platform (for example WhatsApp cloud versus baileys),\n * chosen by name with `selectVariant`. Each variant reports the parent's `platform`.\n */\n readonly variants?: Readonly<Record<string, ChannelDescriptor>>;\n}\n\n/**\n * A channel described as data. A `socket` channel opens its own connection to the platform; a\n * `webhook` channel receives requests the app routes to `webhook.verify` and `webhook.ingest`.\n *\n * @public\n */\nexport type ChannelDescriptor<TAdapter extends BasePlatformAdapter = BasePlatformAdapter> =\n | (ChannelDescriptorBase<TAdapter> & { readonly transport: \"socket\"; readonly webhook?: never })\n | (ChannelDescriptorBase<TAdapter> & {\n readonly transport: \"webhook\";\n readonly webhook: ChannelWebhook<TAdapter>;\n });\n\n/**\n * True only when the descriptor declares `senderIdentity: \"authenticated\"`. An absent or\n * unauthenticated declaration is false.\n *\n * @public\n */\nexport function isAuthenticatedSender(descriptor: ChannelDescriptor): boolean {\n return descriptor.senderIdentity === \"authenticated\";\n}\n","/**\n * `configFromEnv` and `selectVariant`: bind a channel descriptor's config fields to environment\n * variables, and pick one of a platform's config shapes.\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport type { ChannelConfigField, ChannelDescriptor } from \"./channel-descriptor.js\";\n\n/** What `configFromEnv` read from the environment. Holds secret values: never log it whole. */\nexport interface EnvConfig {\n /** Trimmed, non-empty values by config key. */\n readonly config: Readonly<Record<string, string>>;\n /** Full variable names of required fields that are unset, empty or whitespace. */\n readonly missing: readonly string[];\n /** Values of present fields marked secret, for a log mask. Never logged. */\n readonly secrets: readonly string[];\n}\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** The full environment variable name for a field: `prefix + field.env`, or `undefined` without `env`. */\nexport function envVarName(field: ChannelConfigField, prefix = \"\"): string | undefined {\n return field.env === undefined ? undefined : prefix + field.env;\n}\n\n/** The trimmed value of `name`, or undefined when it is unset, empty or whitespace. */\nfunction readValue(env: Env, name: string): string | undefined {\n return env[name]?.trim() || undefined;\n}\n\n/**\n * Read a descriptor's fields from `env`, using `prefix + field.env` as the variable name. Fields\n * without `env` are skipped.\n */\nexport function configFromEnv(descriptor: ChannelDescriptor, env: Env, prefix = \"\"): EnvConfig {\n const config: Record<string, string> = {};\n const missing: string[] = [];\n const secrets: string[] = [];\n for (const field of descriptor.config) {\n const name = envVarName(field, prefix);\n if (name === undefined) continue;\n const value = readValue(env, name);\n if (value === undefined) {\n if (field.required) missing.push(name);\n continue;\n }\n config[field.key] = value;\n recordSecret(field, value, secrets);\n }\n return { config, missing, secrets };\n}\n\nfunction recordSecret(field: ChannelConfigField, value: string, secrets: string[]): void {\n if (field.secret && !secrets.includes(value)) secrets.push(value);\n}\n\nfunction mismatch(parent: ChannelDescriptor, variant: ChannelDescriptor, name: string): never {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"platform_mismatch\",\n message: `channel ${parent.platform}: variant \"${name}\" reports platform ${variant.platform}`,\n });\n}\n\nfunction unknownVariant(descriptor: ChannelDescriptor, name: string | undefined): never {\n const valid = Object.keys(descriptor.variants ?? {});\n const given = name === undefined ? \"(none given)\" : `\"${name}\"`;\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"unknown_channel_variant\",\n message: `channel ${descriptor.platform}: unknown variant ${given}; valid variants: ${\n valid.length > 0 ? valid.join(\", \") : \"(none)\"\n }`,\n });\n}\n\n/**\n * The descriptor to use for `name`: the descriptor itself when `name` is undefined and it has no\n * variants, otherwise the named variant. Throws `unknown_channel_variant` for a name that is not a\n * variant (or a missing name when variants exist) and `platform_mismatch` for a variant whose\n * platform differs from its parent's.\n */\nexport function selectVariant(\n descriptor: ChannelDescriptor,\n name: string | undefined,\n): ChannelDescriptor {\n const variants = descriptor.variants ?? {};\n if (name === undefined && Object.keys(variants).length === 0) return descriptor;\n const variant = name !== undefined && Object.hasOwn(variants, name) ? variants[name] : undefined;\n if (variant === undefined) return unknownVariant(descriptor, name);\n if (variant.platform !== descriptor.platform) mismatch(descriptor, variant, name ?? \"\");\n return variant;\n}\n","/**\n * `createChannels` — build every configured channel from its descriptor (FR-002 of B-018).\n *\n * One loop replaces the per-platform constructor calls an app used to write. A channel whose\n * configuration is refused lands in `rejected` and the others are still built, so one bad entry\n * never stops the healthy ones. Nothing here connects or performs I/O (NFR-001): connecting is the\n * runner's job, after the app has seen what was rejected.\n *\n * @public\n */\n\nimport type { BasePlatformAdapter } from \"../adapter/base.js\";\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\nimport type { ChannelDescriptor } from \"./channel-descriptor.js\";\nimport { envVarName } from \"./config-from-env.js\";\n\n/** One channel to build: its descriptor and the configuration the app supplies for it. */\nexport interface ChannelEntry {\n readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;\n /** Values keyed by the descriptor's field keys. Absent means every required field is missing. */\n readonly config?: Readonly<Record<string, unknown>>;\n /**\n * The prefix passed to `configFromEnv` for this entry, so a missing field's rejection names its\n * full environment variable. Defaults to `\"\"`.\n */\n readonly envPrefix?: string;\n}\n\n/** A channel that was not built, and the configuration error that says why. */\nexport interface ChannelRejection {\n readonly platform: PlatformName;\n readonly error: GatewayConfigurationError;\n}\n\n/** A built adapter paired with the descriptor that built it, so a consumer need not re-pair them. */\nexport interface BuiltChannel {\n readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;\n readonly adapter: BasePlatformAdapter;\n}\n\n/** What `createChannels` built and what it refused. */\nexport interface CreateChannelsResult {\n readonly adapters: BasePlatformAdapter[];\n /** The same adapters, in the same order, each paired with its descriptor. */\n readonly channels: BuiltChannel[];\n readonly rejected: ChannelRejection[];\n}\n\nfunction isAbsent(value: unknown): boolean {\n return value === undefined || value === null || value === \"\";\n}\n\nfunction missingRequiredKeys(\n entry: ChannelEntry,\n values: Readonly<Record<string, unknown>>,\n): string[] {\n return entry.descriptor.config\n .filter((field) => field.required && isAbsent(values[field.key]))\n .map((field) => {\n const name = envVarName(field, entry.envPrefix);\n return name === undefined ? field.key : `${field.key} (env ${name})`;\n });\n}\n\n/** An entry that was refused, and the rejection that says why. */\ninterface Refused {\n readonly adapter?: undefined;\n readonly refusal: ChannelRejection;\n}\n\n/** What building one entry produced: its adapter, or the rejection that refused it. */\ntype BuildOutcome =\n | { readonly adapter: BasePlatformAdapter; readonly refusal?: undefined }\n | Refused;\n\nfunction refused(platform: PlatformName, code: string, reason: string): Refused {\n return {\n refusal: {\n platform,\n error: new GatewayConfigurationError(\"gateway\", {\n code,\n message: `channel ${platform}: ${reason}`,\n }),\n },\n };\n}\n\n/**\n * The rejection an entry gets before its `create` runs, or `undefined` when it may be built. A\n * repeated platform is checked first: the platform is already served, so its config is moot.\n */\nfunction refuseBeforeCreate(\n entry: ChannelEntry,\n values: Readonly<Record<string, unknown>>,\n builtPlatforms: ReadonlySet<PlatformName>,\n): Refused | undefined {\n const platform = entry.descriptor.platform;\n if (builtPlatforms.has(platform)) {\n return refused(platform, \"duplicate_channel\", \"a channel for this platform was already built\");\n }\n const missing = missingRequiredKeys(entry, values);\n if (missing.length > 0) {\n return refused(\n platform,\n \"missing_required_config\",\n `missing required config ${missing.join(\", \")}`,\n );\n }\n return undefined;\n}\n\n/**\n * Call the descriptor's `create` and check what it built. The runner keys adapters by the\n * adapter's own `platform`, and the duplicate check keys them by the descriptor's, so an adapter\n * reporting another platform than its descriptor is refused: kept, it would reach the runner as a\n * second adapter for a platform the duplicate check never saw.\n */\nfunction createAdapter(\n entry: ChannelEntry,\n values: Readonly<Record<string, unknown>>,\n): BuildOutcome {\n const platform = entry.descriptor.platform;\n let adapter: BasePlatformAdapter;\n try {\n adapter = entry.descriptor.create(values);\n } catch (err) {\n if (!(err instanceof GatewayConfigurationError)) throw err;\n return { refusal: { platform, error: err } };\n }\n if (adapter.platform !== platform) {\n return refused(\n platform,\n \"platform_mismatch\",\n `create returned an adapter reporting platform ${adapter.platform}`,\n );\n }\n return { adapter };\n}\n\n/**\n * Build an adapter for each entry whose required fields are present.\n *\n * An entry missing a required field (absent, `null` or `\"\"`; `0` and `false` count as present) is\n * rejected with a `GatewayConfigurationError` coded `missing_required_config` that names every\n * missing key, and its `create` is never called. A `GatewayConfigurationError` thrown by `create`\n * is reported the same way. Any other throw is a defect, not a configuration fault, and propagates.\n *\n * Only one adapter per platform is built, because the runner routes replies and `stop()` by\n * platform. The first entry built for a platform wins; a later entry for that platform is rejected\n * with a `GatewayConfigurationError` coded `duplicate_channel`, before its required fields are\n * checked, and its `create` is never called. An entry rejected for its configuration built\n * nothing, so it does not claim its platform.\n *\n * The runner keys adapters by the adapter's own `platform`, so an adapter must report the platform\n * its descriptor declares. One that reports another is discarded unconnected and its entry is\n * rejected with a `GatewayConfigurationError` coded `platform_mismatch`; it claims no platform.\n *\n * @public\n */\nexport function createChannels(entries: ReadonlyArray<ChannelEntry>): CreateChannelsResult {\n const adapters: BasePlatformAdapter[] = [];\n const channels: BuiltChannel[] = [];\n const rejected: ChannelRejection[] = [];\n const builtPlatforms = new Set<PlatformName>();\n for (const entry of entries) {\n const values = entry.config ?? {};\n const outcome =\n refuseBeforeCreate(entry, values, builtPlatforms) ?? createAdapter(entry, values);\n if (outcome.refusal !== undefined) {\n rejected.push(outcome.refusal);\n continue;\n }\n adapters.push(outcome.adapter);\n channels.push({ descriptor: entry.descriptor, adapter: outcome.adapter });\n builtPlatforms.add(entry.descriptor.platform);\n }\n return { adapters, channels, rejected };\n}\n","/**\n * How the core's two outbound builders treat `attachments` (B-674): `GatewayRunner`'s `ctx.reply`\n * and `DeliveryRouter.send` both carry a non-empty list and both refuse it for an adapter that\n * does not declare `supportsAttachments`.\n *\n * The refusal here is defence in depth: every adapter in this repository refuses on its own, but an\n * adapter written elsewhere inherits `supportsAttachments = false` and may ignore the field, sending\n * the text alone and reporting success. Refusing before the adapter is called keeps the image from\n * being dropped in silence whichever adapter receives it.\n *\n * @internal\n */\n\nimport type {\n BasePlatformAdapter,\n OutboundAttachment,\n OutboundMessage,\n SendResult,\n} from \"../adapter/base.js\";\n\n/**\n * The non-empty `attachments` of a request, or nothing for absent, `null` or empty. `!== 0`, not\n * `> 0`: another non-array value from a JavaScript caller has no numeric length and is carried on,\n * to be refused, rather than dropped (EC-1).\n */\nexport function attachmentsOf(attachments: ReadonlyArray<OutboundAttachment> | undefined): {\n attachments?: ReadonlyArray<OutboundAttachment>;\n} {\n return attachments != null && attachments.length !== 0 ? { attachments } : {};\n}\n\n/**\n * `attachments_unsupported` when `outbound` carries attachments and `adapter` does not declare\n * `supportsAttachments`, otherwise `undefined`. Makes no platform call.\n */\nexport function refuseUnsupportedAttachments(\n adapter: BasePlatformAdapter,\n outbound: OutboundMessage,\n): SendResult | undefined {\n const { attachments } = outbound;\n if (adapter.supportsAttachments || attachments == null || attachments.length === 0) {\n return undefined;\n }\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: `${adapter.platform} adapter cannot send attachments`,\n },\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, OutboundAttachment, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\nimport { attachmentsOf, refuseUnsupportedAttachments } from \"./attachments.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 /** Images to send with the text; an empty list is left out (B-674). */\n readonly attachments?: ReadonlyArray<OutboundAttachment>;\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 * - `send` with attachments refuses with `attachments_unsupported`, calling no `sendMessage`, when\n * the adapter does not declare `supportsAttachments`.\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 const outbound = {\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n ...attachmentsOf(req.attachments),\n };\n return refuseUnsupportedAttachments(adapter, outbound) ?? adapter.sendMessage(outbound);\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 * The uncovered shapes as one `field :: why` row per line. A single literal rather than an object\n * per entry keeps a long list of same-shaped entries from reading as a block repeated line for line.\n */\nconst UNCOVERED_TABLE = `gateway-qq \\`appSecret\\` :: a QQ Bot AppSecret, an opaque 32-character string with no prefix or fixed shape. It travels only to the access-token endpoint and into the webhook signature derivation; the adapter never logs it.\ngateway-x \\`clientSecret\\`, \\`refreshToken\\`, \\`bearerToken\\` :: an X OAuth 2.0 client secret, a rotating refresh token and an app bearer token, opaque strings with no fixed prefix. They travel only to the X API in Authorization headers and the token request body, which the adapter never logs.\ngateway-buzz \\`token\\` :: a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs.\ngateway-clickclack \\`token\\` :: a ClickClack bot token (\\`ccb_\\` prefix) or session token with no fixed shape for the latter. It travels only in Authorization headers, which the adapter never logs.\ngateway-zalo \\`accessToken\\`, \\`oaSecretKey\\` :: a Zalo Official Account access token and OA secret key: opaque strings with no prefix or fixed shape to recognise. The token travels only in an \\`access_token\\` header and the key only into the signature check, and the adapter never logs either.\ngateway-wechat \\`appSecret\\`, \\`token\\` :: a WeChat Official Account AppSecret (32 hex characters, indistinguishable from any other hex string) and the server-URL verification token (a string the operator chooses). The secret travels only to the access-token endpoint and the token only into the signature check; the adapter never logs either.\ngateway-wecom \\`corpSecret\\`, \\`token\\`, \\`encodingAesKey\\` :: a WeCom application Secret (43 URL-safe base64 characters, indistinguishable from other opaque strings), the callback Token (a string the operator chooses) and the EncodingAESKey (43 base64 characters). The secret travels only to the access-token endpoint, the token into the signature check and the key into the decryption; the adapter never logs any of them.\ngateway-yuanbao \\`appSecret\\`, \\`callbackSecret\\` :: a Yuanbao bot AppSecret and the callback signing secret, both opaque strings with no prefix or fixed shape. The app secret travels only to the access-token endpoint and the callback secret only into the signature check; the adapter never logs either.\ngateway-zalo-personal \\`credentials\\` :: a Zalo web session: a cookie jar, an IMEI-like device id and a user agent. The cookie has no prefix or fixed shape to recognise. It travels only to the Zalo library, which the adapter never logs.\ngateway-twitch \\`accessToken\\` :: 30 lowercase alphanumerics with no prefix, the shape of many ids and hashes in a log. It travels only in Authorization headers, which the adapter never logs.\ngateway-tlon-urbit \\`code\\` :: a +code is four dash-joined phonemic syllable words, the same shape as an Urbit ship name such as ~sampel-palnet-sampel-palnet, which the logs exist to show. It travels only in the /~/login body, which the adapter never logs.\ngateway-synology-chat \\`botToken\\` and \\`incomingUrl\\` :: a bot token is a random string the NAS generates with no prefix, and the Incoming URL carries its own token as a query parameter of an ordinary entry.cgi URL. Neither has a shape to claim without eating ordinary ids and URLs; the adapter never logs the URL, and refuses a callback token before reading it.\ngateway-feishu-lark \\`appSecret\\` :: 32 alphanumerics with no prefix, the shape of many tokens and hashes; it travels only in the body of the tenant-token request, which the adapter never logs.\ngateway-nostr \\`secretKey\\` (64-hex form) :: 64 hex characters is also every Nostr public key and event id, which the logs exist to show, and a sha256 digest. The nsec1 spelling of the same key is masked above.\ngateway-sms \\`authToken\\` (Twilio), gateway-line \\`channelSecret\\` :: 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.\ngateway-mattermost \\`accessToken\\` :: 26 lowercase alphanumerics, which is exactly a lowercase ULID — the shape of most trace ids.\ngateway-email \\`password\\`, gateway-sms \\`apiSecret\\` and \\`signatureSecret\\` (Vonage) :: 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.\ngateway-slack \\`botToken\\` :: 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.\ngateway-whatsapp \\`appSecret\\` :: 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.\ngateway-nextcloud-talk \\`secret\\` :: a Talk bot secret is a string of 40 to 128 characters the administrator chose for \\`occ talk:bot:install\\`, with no prefix or format to recognise. It never travels: both sides send only an HMAC made with it, and the adapter never logs it.\ngateway-irc \\`password\\` and \\`saslPassword\\` :: a server password and a NickServ password are passphrases the operator chose, with no format to recognise. The SDK's \\`key=value\\` rule masks them as fields wherever they appear as \\`password=...\\`; the SASL payload on the wire is their base64, which the adapter never logs.\ngateway-google-chat \\`privateKey\\` :: a PEM block spans lines, and in a log it usually arrives inside a JSON string with its line breaks escaped as \\\\n, which no single-line shape can claim whole. The SDK's \\`key=value\\` rule masks it as a field wherever it appears as \\`private_key=...\\` or \\`privateKey=...\\`.\ngateway-line \\`channelAccessToken\\`, gateway-sms \\`authToken\\` (Plivo) :: long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message.`;\n\n/** Read the rows of {@link UNCOVERED_TABLE}. */\nfunction parseUncovered(table: string): readonly UncoveredShape[] {\n return table.split(\"\\n\").map((row) => {\n const [field = \"\", why = \"\"] = row.split(\" :: \");\n return { field, why };\n });\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 field: \"gateway-nostr `secretKey` (nsec1 form)\",\n pattern: /(?<![a-z0-9])nsec1[02-9ac-hj-np-z]{58}(?![a-z0-9])/g,\n alsoMatches: \"nothing plausible — `nsec1` is NIP-19's prefix for a secret key\",\n },\n ],\n uncovered: parseUncovered(UNCOVERED_TABLE),\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/**\n * Replace each exact value in `secrets` with `[redacted]`, longest value first so a value that\n * contains another is masked whole. Empty values are ignored. It does not run `redactSecrets`:\n * call that afterwards, because it shortens some shapes to a head and tail and the masked fragments\n * would otherwise survive.\n *\n * @param text the text to mask\n * @param secrets the exact credential values configured for this process\n * @returns the text with every occurrence of every value replaced\n */\nexport function maskSecrets(text: string, secrets: ReadonlyArray<string>): string {\n const ordered = [...new Set(secrets)]\n .filter((s) => s.length > 0)\n .sort((a, b) => b.length - a.length);\n let out = text;\n for (const secret of ordered) out = out.split(secret).join(\"[redacted]\");\n return out;\n}\n","/**\n * File-backed pairing store: senders approved by an owner are kept in `pairing.json`.\n * Pending codes live in memory for one hour.\n *\n * @public\n */\n\nimport { randomInt, randomUUID } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\n\n/** Pairing store used by the access policy hook. */\nexport interface PairingStore {\n /** A 6-digit code for the sender; the same code while one is pending. */\n issue(platform: string, senderId: string): string;\n approve(\n code: string,\n ): Promise<\n | { ok: true; platform: string; senderId: string }\n | { ok: false; reason: \"unknown_or_expired\" | \"write_failed\" }\n >;\n isPaired(platform: string, senderId: string): boolean;\n}\n\n/** `<platform>:<senderId>`; email ids compare case-insensitively. */\nexport function senderKey(platform: string, senderId: string): string {\n return `${platform}:${platform === \"email\" ? senderId.toLowerCase() : senderId}`;\n}\n\nconst TTL_MS = 3_600_000;\nconst FILE = \"pairing.json\";\n\nfunction unreadable(): GatewayConfigurationError {\n return new GatewayConfigurationError(\"gateway\", {\n code: \"pairing_store_unreadable\",\n message: \"gateway: pairing_store_unreadable\",\n });\n}\n\nfunction load(path: string): Set<string> {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return new Set();\n throw unreadable();\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw unreadable();\n }\n const list = (parsed as { paired?: unknown } | null)?.paired;\n if (!Array.isArray(list) || !list.every((x) => typeof x === \"string\")) throw unreadable();\n return new Set(list as string[]);\n}\n\n/** Creates a store persisted in `<dir>/pairing.json` (mode 0600). */\nexport function createFilePairingStore(options: {\n dir: string;\n clock?: () => number;\n random?: (min: number, max: number) => number;\n}): PairingStore {\n const clock = options.clock ?? Date.now;\n const random = options.random ?? randomInt;\n const path = join(options.dir, FILE);\n const paired = load(path);\n const pending = new Map<string, { platform: string; senderId: string; expires: number }>();\n let chain: Promise<unknown> = Promise.resolve();\n\n const prune = (): void => {\n const now = clock();\n for (const [code, p] of pending) if (p.expires <= now) pending.delete(code);\n };\n\n function persist(next: Set<string>): void {\n mkdirSync(options.dir, { recursive: true });\n const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;\n writeFileSync(tmp, JSON.stringify({ paired: [...next].sort((a, b) => a.localeCompare(b)) }), {\n mode: 0o600,\n flag: \"wx\",\n });\n renameSync(tmp, path);\n }\n\n return {\n issue(platform, senderId) {\n prune();\n for (const [code, p] of pending) {\n if (senderKey(p.platform, p.senderId) === senderKey(platform, senderId)) return code;\n }\n let code: string;\n do {\n code = String(random(100000, 1000000));\n } while (pending.has(code));\n pending.set(code, { platform, senderId, expires: clock() + TTL_MS });\n return code;\n },\n approve(code) {\n const run = async () => {\n prune();\n const p = pending.get(code);\n if (!p) return { ok: false as const, reason: \"unknown_or_expired\" as const };\n const next = new Set(paired);\n next.add(senderKey(p.platform, p.senderId));\n try {\n persist(next);\n } catch {\n return { ok: false as const, reason: \"write_failed\" as const };\n }\n paired.add(senderKey(p.platform, p.senderId));\n pending.delete(code);\n return { ok: true as const, platform: p.platform, senderId: p.senderId };\n };\n const result = chain.then(run, run);\n chain = result.catch(() => undefined);\n return result;\n },\n isPaired(platform, senderId) {\n return paired.has(senderKey(platform, senderId));\n },\n };\n}\n","/**\n * Access policy hook: who may talk to the agent, with sender pairing.\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport { redactSecrets } from \"../security/credential-patterns.js\";\nimport type { MessageEvent, PlatformName } from \"../types/message-event.js\";\nimport { type PairingStore, senderKey } from \"./pairing-store.js\";\nimport type { GatewayHook, HookDecision } from \"./types.js\";\n\nexport type DmPolicy = \"pairing\" | \"allowlist\" | \"open\" | \"disabled\";\n\n/** Options for {@link createAccessPolicyHook}. */\nexport interface AccessPolicyOptions {\n /** `<platform>:<senderId>` keys. */\n readonly owners: ReadonlySet<string>;\n readonly allowed?: ReadonlySet<string>;\n readonly dm: DmPolicy;\n /** Group messages from non-members: \"silent\" (default) or \"open\". */\n readonly groups?: \"silent\" | \"open\";\n /** Which platforms authenticate the sender. */\n readonly isAuthenticated: (platform: PlatformName) => boolean;\n /** Required when dm is \"pairing\". */\n readonly pairing?: PairingStore;\n readonly refusalText?: string;\n readonly refusalIntervalMs?: number;\n /** Let a message through untouched. */\n readonly passThrough?: (event: MessageEvent) => boolean;\n readonly clock?: () => number;\n readonly write?: (line: string) => void;\n}\n\nconst SILENT: HookDecision = { block: true };\nconst DEFAULT_REFUSAL = \"Sorry, you are not authorized to use this assistant.\";\n\nfunction normalize(key: string): string {\n const i = key.indexOf(\":\");\n return i < 0 ? key : senderKey(key.slice(0, i), key.slice(i + 1));\n}\n\nfunction check(keys: ReadonlySet<string>, isAuth: (p: PlatformName) => boolean): Set<string> {\n const out = new Set<string>();\n for (const key of keys) {\n const i = key.indexOf(\":\");\n const platform = i < 0 ? key : key.slice(0, i);\n if (!isAuth(platform as PlatformName)) {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"unauthenticated_owner\",\n message: `gateway: unauthenticated_owner: platform ${platform} does not authenticate the sender`,\n detail: platform,\n });\n }\n out.add(normalize(key));\n }\n return out;\n}\n\n/** Builds the `pre_inbound` access policy hook. */\nexport function createAccessPolicyHook(options: AccessPolicyOptions): GatewayHook {\n if (options.dm === \"pairing\" && !options.pairing) {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"pairing_store_required\",\n message: \"gateway: pairing_store_required\",\n });\n }\n const owners = check(options.owners, options.isAuthenticated);\n const allowed = check(options.allowed ?? new Set(), options.isAuthenticated);\n const clock = options.clock ?? Date.now;\n const interval = options.refusalIntervalMs ?? 3_600_000;\n const write = options.write ?? ((line: string) => process.stderr.write(`${line}\\n`));\n const refusal = options.refusalText ?? DEFAULT_REFUSAL;\n const store = options.pairing;\n const refused = new Map<string, number>();\n\n const mayRefuse = (key: string): boolean => {\n const now = clock();\n for (const [k, t] of refused) if (now - t >= interval) refused.delete(k);\n if (refused.has(key)) return false;\n refused.set(key, now);\n return true;\n };\n\n const pairingReply = (event: MessageEvent): HookDecision => {\n const code = (store as PairingStore).issue(event.platform, event.sender.id);\n return {\n block: true,\n message: `Your pairing code is ${code}. Ask the owner to send /approve ${code}.`,\n };\n };\n\n const groupDecision = (): HookDecision | undefined =>\n options.groups === \"open\" ? undefined : SILENT;\n\n const stranger = (event: MessageEvent, key: string): HookDecision | undefined => {\n if (event.channel.type !== \"dm\") return groupDecision();\n if (options.dm === \"open\") return undefined;\n if (options.dm === \"disabled\" || !mayRefuse(key)) return SILENT;\n if (options.dm === \"allowlist\") return { block: true, message: refusal };\n return pairingReply(event);\n };\n\n const ownerMessage = async (text: string): Promise<HookDecision | undefined> => {\n const m = /^\\/approve\\s+(\\d{6})\\s*$/.exec(text.trim());\n if (!m?.[1]) return undefined;\n if (!store) return { block: true, message: \"Pairing is not enabled.\" };\n const r = await store.approve(m[1]);\n if (r.ok) return { block: true, message: \"Paired.\" };\n return {\n block: true,\n message:\n r.reason === \"write_failed\"\n ? \"Saving the pairing failed. Check the storage and send the code again.\"\n : \"Unknown or expired code.\",\n };\n };\n\n const isPaired = (event: MessageEvent): boolean =>\n store?.isPaired(event.platform, event.sender.id) === true;\n\n const decide = async (event: MessageEvent): Promise<HookDecision | undefined> => {\n if (options.passThrough?.(event)) return undefined;\n // Never trust or answer a forgeable sender id.\n if (!options.isAuthenticated(event.platform as PlatformName)) return SILENT;\n const key = senderKey(event.platform, event.sender.id);\n if (owners.has(key)) return ownerMessage(event.text);\n if (allowed.has(key) || isPaired(event)) return undefined;\n return stranger(event, key);\n };\n\n return {\n name: \"access-policy\",\n async pre_inbound({ event }) {\n try {\n return await decide(event);\n } catch (e) {\n try {\n write(`access-policy: hook failed: ${redactSecrets(e)}`);\n } catch {\n // A failing logger must not turn the silent block into a hook-failed reply.\n }\n return SILENT;\n }\n },\n };\n}\n","/**\n * Chat command parsing and a single `pre_inbound` hook for many commands.\n *\n * Recognises a command behind one leading mention (`<@U123> /help`,\n * `@bot /help`) and with Telegram's `@botname` suffix (`/help@my_bot`).\n * The name is matched exactly: `/new chat` is `/new` with arg `chat`,\n * `/newer` is never `/new`.\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport type { MessageEvent } from \"../types/message-event.js\";\nimport type { GatewayHook, HookDecision } from \"./types.js\";\n\n/** A parsed chat command. */\nexport interface ParsedChatCommand {\n /** Command name, without the prefix and without `@bot`. */\n readonly name: string;\n /** Trimmed rest of the text, `\"\"` when none. */\n readonly arg: string;\n}\n\nconst LEADING_MENTION = /^(?:<@[^>]+>|@\\S+)\\s+/;\nconst DEFAULT_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\nfunction matchPrefix(text: string, prefixes: ReadonlyArray<string>): string | undefined {\n let best: string | undefined;\n for (const p of prefixes) {\n if (p.length > 0 && text.startsWith(p) && (best === undefined || p.length > best.length)) {\n best = p;\n }\n }\n return best;\n}\n\n/**\n * Strips one leading `<@U...>` or `@name` mention and a `@bot` suffix.\n * Returns `undefined` for text that is not a command.\n */\nexport function parseChatCommand(\n text: string,\n options?: { prefixes?: ReadonlyArray<string> },\n): ParsedChatCommand | undefined {\n const body = text.trim().replace(LEADING_MENTION, \"\");\n const prefix = matchPrefix(body, options?.prefixes ?? DEFAULT_PREFIXES);\n if (prefix === undefined) return undefined;\n const rest = body.slice(prefix.length);\n const m = /^([^\\s@]+)(?:@\\S+)?(?:\\s+([\\s\\S]*))?$/.exec(rest);\n if (!m?.[1]) return undefined;\n return { name: m[1].toLowerCase(), arg: (m[2] ?? \"\").trim() };\n}\n\n/** One command handled by {@link commandHook}. */\nexport interface ChatCommand {\n readonly name: string;\n readonly description: string;\n /** Default `\"optional\"`. */\n readonly arg?: \"none\" | \"optional\" | \"required\";\n /** Usage line shown in help. Default `\"/<name>\"`. */\n readonly usage?: string;\n run(\n event: MessageEvent,\n arg: string,\n ): HookDecision | undefined | Promise<HookDecision | undefined>;\n}\n\nfunction usageOf(c: ChatCommand): string {\n return c.usage ?? `/${c.name}`;\n}\n\n/** Help text listing every command's usage and description, in declaration order. */\nexport function helpText(commands: ReadonlyArray<ChatCommand>): string {\n return commands.map((c) => `${usageOf(c)} - ${c.description}`).join(\"\\n\");\n}\n\nfunction assertUnique(names: ReadonlyArray<string>): void {\n const seen = new Set<string>();\n for (const raw of names) {\n const name = raw.toLowerCase();\n if (seen.has(name)) {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"duplicate_command\",\n message: `gateway: duplicate_command: ${raw}`,\n detail: raw,\n });\n }\n seen.add(name);\n }\n}\n\nfunction badArity(c: ChatCommand, arg: string): boolean {\n const mode = c.arg ?? \"optional\";\n return (mode === \"none\" && arg !== \"\") || (mode === \"required\" && arg === \"\");\n}\n\n/**\n * One `pre_inbound` hook for many commands. Also answers `/help`\n * (rename with `helpCommand`, disable with `false`).\n */\nexport function commandHook(\n commands: ReadonlyArray<ChatCommand>,\n options?: { name?: string; helpCommand?: string | false },\n): GatewayHook {\n const helpName = options?.helpCommand === undefined ? \"help\" : options.helpCommand;\n assertUnique([...commands.map((c) => c.name), ...(helpName === false ? [] : [helpName])]);\n const byName = new Map(commands.map((c) => [c.name.toLowerCase(), c]));\n const help = helpText(commands);\n\n return {\n name: options?.name ?? \"chat-commands\",\n async pre_inbound({ event }) {\n const parsed = parseChatCommand(event.text);\n if (!parsed) return undefined;\n if (helpName !== false && parsed.name === helpName.toLowerCase()) {\n return { block: true, message: help };\n }\n const command = byName.get(parsed.name);\n if (!command) return undefined;\n if (badArity(command, parsed.arg)) return { block: true, message: usageOf(command) };\n return command.run(event, parsed.arg);\n },\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 { 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 and resolves a `StartResult`.\n * By default (`connectFailure: \"rollback\"`) partial failure rolls back:\n * connected adapters get `disconnect()`, then the error rethrows. Under\n * `connectFailure: \"isolate\"` the adapters that connected keep running and\n * the rest are reported in `StartResult.failed`.\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 {\n BasePlatformAdapter,\n OutboundAttachment,\n OutboundMessage,\n SendResult,\n} from \"../adapter/base.js\";\nimport { attachmentsOf, refuseUnsupportedAttachments } from \"../delivery/attachments.js\";\nimport { GatewayLifecycleError } from \"../errors/lifecycle-error.js\";\nimport { HookExecutor } from \"../hooks/executor.js\";\nimport type { GatewayHook } from \"../hooks/types.js\";\nimport { maskSecrets, 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(\n text: string,\n opts?: {\n format?: \"plain\" | \"markdown\" | \"html\";\n /** Images to send with the text; an empty list is left out (B-674). */\n attachments?: ReadonlyArray<OutboundAttachment>;\n },\n ): 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 * What `start()` does when an adapter fails to connect. `\"rollback\"` (the default) disconnects\n * the adapters that did connect and rethrows: all or nothing. `\"isolate\"` keeps the adapters that\n * connected, wires inbound only for them, and reports the others in the resolved\n * `StartResult.failed`, so one channel that cannot connect does not stop the healthy ones.\n *\n * @public\n */\n readonly connectFailure?: ConnectFailure;\n /**\n * Retry, in the background, an adapter whose `connect()` threw a transient error under\n * `connectFailure: \"isolate\"` (network refused, DNS, 5xx), with exponential backoff and a log\n * line per attempt. An adapter that connects on a retry is wired for inbound and joins\n * `connected`. A `connect()` that resolves `false`, or throws a credential error (HTTP 401/403,\n * `M_UNKNOWN_TOKEN`, `M_FORBIDDEN`, \"unauthorized\"), is terminal: it is reported once and not\n * retried. Off unless set; ignored under `\"rollback\"`.\n *\n * @public\n */\n readonly reconnect?: ReconnectPolicy;\n /**\n * Under `connectFailure: \"isolate\"`, give up on one adapter's `connect()` after this many ms. The\n * adapter is reported `timed_out`, counted in `StartResult.failed`, and never wired for inbound:\n * if its `connect()` resolves `true` later, the runner disconnects it. With `reconnect` set it is\n * retried like a transient failure. Ignored under `\"rollback\"`, as `reconnect` is.\n *\n * @public\n */\n readonly connectTimeoutMs?: number;\n /**\n * Called as each adapter changes state, while `start()` may still be pending. `reason` is\n * redacted. A callback that throws is ignored. Ignored under `\"rollback\"`.\n *\n * @public\n */\n readonly onAdapterState?: (platform: PlatformName, state: AdapterState, reason?: string) => void;\n /**\n * Exact credential values masked (longest first) in every reason and log line before\n * `redactSecrets` runs.\n *\n * @public\n */\n readonly secrets?: ReadonlyArray<string>;\n}\n\n/**\n * Where one adapter stands under `connectFailure: \"isolate\"`, as reported to\n * `GatewayRunnerOptions.onAdapterState`.\n *\n * @public\n */\nexport type AdapterState = \"connected\" | \"failed\" | \"retrying\" | \"timed_out\";\n\n/**\n * Backoff for `GatewayRunnerOptions.reconnect`. The delay before attempt n is\n * `min(initialDelayMs * factor^(n-1), maxDelayMs)`.\n *\n * @public\n */\nexport interface ReconnectPolicy {\n /** Delay before the first retry. Default 1000ms. */\n readonly initialDelayMs?: number;\n /** Cap on the delay between attempts. Default 60_000ms. */\n readonly maxDelayMs?: number;\n /** Multiplier per attempt. Default 2. */\n readonly factor?: number;\n /** Give up after this many retries. Default: keep trying until `stop()`. */\n readonly maxAttempts?: number;\n}\n\n/**\n * How `GatewayRunner.start()` treats an adapter that fails to connect: `\"rollback\"` (all or\n * nothing, the default) or `\"isolate\"` (keep the ones that connected).\n *\n * @public\n */\nexport type ConnectFailure = \"rollback\" | \"isolate\";\n\n/**\n * What `GatewayRunner.start()` connected. Under `\"rollback\"` `failed` is always empty, because a\n * failure rejects instead; under `\"isolate\"` it names each adapter that did not connect and why,\n * with any credential in the reason redacted.\n *\n * @public\n */\nexport interface StartResult {\n readonly connected: ReadonlyArray<PlatformName>;\n readonly failed: ReadonlyArray<{ readonly platform: PlatformName; readonly reason: string }>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\n\n/** Typing indicators last 5-10 s on the platforms that expire them; renew inside that. */\nconst TYPING_RENEW_MS = 4_000;\n\n/**\n * Show a typing indicator on `channelId` until the returned function is awaited. The indicator is\n * cosmetic: a failing adapter never fails the turn, and the renewal timer never keeps the process alive.\n */\nfunction keepTyping(adapter: BasePlatformAdapter, channelId: string): () => Promise<void> {\n const swallow = (p: Promise<void>): Promise<void> => p.catch(() => undefined);\n const start = (): Promise<void> =>\n swallow(Promise.resolve().then(() => adapter.startTyping(channelId)));\n void start();\n const timer = setInterval(() => void start(), TYPING_RENEW_MS);\n timer.unref();\n return async () => {\n clearInterval(timer);\n await swallow(Promise.resolve().then(() => adapter.stopTyping(channelId)));\n };\n}\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\ninterface ConnectOutcome {\n readonly connected: BasePlatformAdapter[];\n readonly failed: StartResult[\"failed\"][number][];\n /** Adapters whose connect threw a transient error, for the reconnect policy. */\n readonly retryable: BasePlatformAdapter[];\n}\n\ntype Redact = (text: string) => string;\n\ninterface IsolatedResult {\n readonly adapter: BasePlatformAdapter;\n readonly failure: StartResult[\"failed\"][number] | undefined;\n readonly retry: boolean;\n}\n\nfunction connectFailureReason(outcome: PromiseSettledResult<boolean>, redact: Redact): string {\n if (outcome.status === \"fulfilled\") return \"connect returned false\";\n const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);\n // A connect error can echo the credential it was given.\n return redact(message);\n}\n\n/** A credential refusal will fail identically on every retry, so it is never retried. */\nfunction isTerminalConnectError(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) return false;\n const e = err as Record<string, unknown>;\n for (const key of [\"status\", \"statusCode\", \"httpStatus\"]) {\n if (e[key] === 401 || e[key] === 403) return true;\n }\n if (e.errcode === \"M_UNKNOWN_TOKEN\" || e.errcode === \"M_FORBIDDEN\") return true;\n const message = typeof e.message === \"string\" ? e.message : \"\";\n return /\\b(?:http|status(?: code)?)\\s*:?\\s*(?:401|403)\\b|unauthori[sz]ed|forbidden/i.test(\n message,\n );\n}\n\n/**\n * Disconnect every adapter the runner is giving back, from a rollback, an overtaken start or\n * `stop()`. A disconnect that fails does not stop the others and does not change how the caller\n * settles, but it is reported: such an adapter may still hold its platform session, and a\n * discarded failure left that state with no trace.\n */\nasync function releaseAdapters(\n adapters: ReadonlyArray<BasePlatformAdapter>,\n during: string,\n redact: Redact = redactSecrets,\n): Promise<void> {\n await Promise.all(\n adapters.map(async (a) => {\n try {\n await a.disconnect();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(\n `[gateway] adapter \"${a.platform}\" disconnect failed while ${during}: ${redact(message)}\\n`,\n );\n }\n }),\n );\n}\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 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 startResult: StartResult | undefined;\n /** The start that has not settled yet, shared by every overlapping `start()` call. */\n private startInFlight: Promise<StartResult> | undefined;\n private stopped = false;\n private readonly retryTimers = new Set<NodeJS.Timeout>();\n private readonly connectedPlatforms = new Set<PlatformName>();\n private readonly redact: Redact;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n const secrets = opts.secrets ?? [];\n this.redact = (text) => redactSecrets(maskSecrets(text, secrets));\n }\n\n /** The registered adapter for a platform, connected or not. */\n adapter(platform: PlatformName): BasePlatformAdapter | undefined {\n return this.opts.adapters.find((a) => a.platform === platform);\n }\n\n /** Platforms whose adapter is connected now; updated by connects, retries and `stop()`. */\n get connected(): ReadonlySet<PlatformName> {\n return this.connectedPlatforms;\n }\n\n private emitState(platform: PlatformName, state: AdapterState, reason?: string): void {\n if ((this.opts.connectFailure ?? \"rollback\") !== \"isolate\") return;\n try {\n this.opts.onAdapterState?.(platform, state, reason);\n } catch {\n /* a throwing observer must not break the runner */\n }\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 the adapters and wire inbound dispatch for the ones that connected.\n *\n * Resolves with what connected. A second call after the first resolved returns the same result\n * without connecting again.\n *\n * Overlapping calls share one start; a start overtaken by stop resolves with no adapter connected.\n * A call made before `stop()` while another is still connecting connects nothing and settles\n * with it; a call made after `stop()` throws `runner_stopped`. When `stop()` runs before the\n * connect settles, the adapters that connected are disconnected, no inbound dispatch is wired,\n * and the start resolves `{ connected: [], failed }`, keeping the `\"isolate\"` failures. Under\n * `\"rollback\"`, a connect that fails still rejects the start.\n *\n * Under `connectFailure: \"rollback\"`, every connect settles before the rollback, so a failing\n * start rejects only once its slowest connect settles, as a successful one resolves only then.\n *\n * An adapter whose `disconnect()` fails while a start rolls back, or while a start that `stop()`\n * overtook gives its adapters back, is named on stderr with the error redacted; how the start\n * settles does not change.\n *\n * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already\n * stopped. A stopped runner is spent; construct a new one.\n * @throws {Error} under the default `connectFailure: \"rollback\"`, the first connect failure, after\n * every connect settled and the adapters that did connect were disconnected.\n */\n async start(): Promise<StartResult> {\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.startResult !== undefined) return this.startResult;\n if (this.startInFlight === undefined) {\n // Recorded in the same synchronous section that calls `connect()`, before anything awaits: a\n // guard on `startResult` alone, written after the connect, let an overlapping call connect\n // every adapter a second time.\n const pending = this.runStart();\n this.startInFlight = pending;\n // A rejected start is not memoised, so a later call connects again. The identity check is\n // defensive: this handler is the first reaction on `pending`, so no newer record can exist\n // yet. The returned promise still carries the rejection to every caller.\n pending.catch(() => {\n if (this.startInFlight === pending) this.startInFlight = undefined;\n });\n }\n return this.startInFlight;\n }\n\n private async runStart(): Promise<StartResult> {\n const result =\n (this.opts.connectFailure ?? \"rollback\") === \"isolate\"\n ? await this.connectIsolated()\n : await this.connectAllOrRollback();\n if (this.stopped) {\n // stop() ran while the connect was pending: it disconnected these adapters before their\n // connect settled, and a later stop() returns at its guard. Wiring them would leave a live\n // adapter on a stopped runner.\n await releaseAdapters(\n result.connected,\n \"releasing a start that stop() overtook\",\n this.redact,\n );\n this.connectedPlatforms.clear();\n this.startResult = { connected: [], failed: result.failed };\n return this.startResult;\n }\n this.wireInbound(result.connected);\n for (const a of result.connected) this.connectedPlatforms.add(a.platform);\n this.startResult = {\n connected: result.connected.map((a) => a.platform),\n failed: result.failed,\n };\n for (const adapter of result.retryable) this.scheduleReconnect(adapter, 1);\n return this.startResult;\n }\n\n /** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */\n private scheduleReconnect(adapter: BasePlatformAdapter, attempt: number): void {\n const policy = this.opts.reconnect;\n if (policy === undefined || this.stopped) return;\n if (policy.maxAttempts !== undefined && attempt > policy.maxAttempts) {\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" gave up reconnecting after ${policy.maxAttempts} attempts\\n`,\n );\n return;\n }\n const delay = Math.min(\n (policy.initialDelayMs ?? 1000) * (policy.factor ?? 2) ** (attempt - 1),\n policy.maxDelayMs ?? 60_000,\n );\n const timer = setTimeout(() => {\n this.retryTimers.delete(timer);\n void this.reconnectOnce(adapter, attempt);\n }, delay);\n // A pending retry must not keep the process alive on its own; `stop()` clears it anyway.\n timer.unref();\n this.retryTimers.add(timer);\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" reconnect attempt ${attempt} in ${delay}ms\\n`,\n );\n this.emitState(adapter.platform, \"retrying\", `reconnect attempt ${attempt} in ${delay}ms`);\n }\n\n private async reconnectOnce(adapter: BasePlatformAdapter, attempt: number): Promise<void> {\n if (this.stopped) return;\n try {\n if (await adapter.connect()) {\n if (this.stopped) {\n await releaseAdapters(\n [adapter],\n \"releasing a reconnect that stop() overtook\",\n this.redact,\n );\n return;\n }\n this.wireInbound([adapter]);\n this.connectedPlatforms.add(adapter.platform);\n this.emitState(adapter.platform, \"connected\");\n const prev = this.startResult ?? { connected: [], failed: [] };\n this.startResult = {\n connected: [...prev.connected, adapter.platform],\n failed: prev.failed.filter((f) => f.platform !== adapter.platform),\n };\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" connected on attempt ${attempt}\\n`,\n );\n return;\n }\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" refused to connect; not retrying\\n`,\n );\n return;\n } catch (err) {\n const reason = connectFailureReason({ status: \"rejected\", reason: err }, this.redact);\n if (isTerminalConnectError(err)) {\n this.emitState(adapter.platform, \"failed\", reason);\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" credentials rejected: ${reason}; not retrying\\n`,\n );\n return;\n }\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" reconnect attempt ${attempt} failed: ${reason}\\n`,\n );\n }\n this.scheduleReconnect(adapter, attempt + 1);\n }\n\n /**\n * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow\n * the first failure. Every connect settles before the rollback: rolling back while one is still\n * pending left that adapter live once it connected.\n */\n private async connectAllOrRollback(): Promise<ConnectOutcome> {\n const adapters = this.opts.adapters;\n // In the order they occur. Its length decides, never a value's truthiness, so a connect that\n // rejects with `undefined` still rolls back.\n const failures: unknown[] = [];\n const settled = await Promise.allSettled(\n adapters.map(async (a) => {\n let ok: boolean;\n try {\n // Inside the `try`, a `connect()` that throws before returning a promise lands here too.\n ok = await a.connect();\n } catch (err) {\n failures.push(err);\n throw err;\n }\n if (!ok) {\n const refusal = new Error(`adapter \"${a.platform}\" connect returned false`);\n failures.push(refusal);\n throw refusal;\n }\n }),\n );\n if (failures.length > 0) {\n // \"fulfilled\" means connected: a refusal and a throw both reject their wrapper.\n const connected = adapters.filter((_, i) => settled[i]?.status === \"fulfilled\");\n await releaseAdapters(connected, \"rolling back a failed start\", this.redact);\n throw failures[0];\n }\n return { connected: [...adapters], failed: [], retryable: [] };\n }\n\n /**\n * Connect every adapter and keep the ones that connected. The `async` wrapper turns a\n * synchronous throw inside `connect()` into a rejection `allSettled` sees; a bare\n * `a => a.connect()` would let it escape `map` and reject `start()` itself.\n */\n private async connectIsolated(): Promise<ConnectOutcome> {\n const adapters = this.opts.adapters;\n const results = await Promise.all(adapters.map((a) => this.connectOne(a)));\n const connected: BasePlatformAdapter[] = [];\n const failed: StartResult[\"failed\"][number][] = [];\n const retryable: BasePlatformAdapter[] = [];\n for (const r of results) {\n if (r.failure === undefined) connected.push(r.adapter);\n else failed.push(r.failure);\n if (r.retry) retryable.push(r.adapter);\n }\n return { connected, failed, retryable };\n }\n\n /** Connect one adapter, bounded by `connectTimeoutMs`, and report its state as it settles. */\n private async connectOne(adapter: BasePlatformAdapter): Promise<IsolatedResult> {\n const attempt = Promise.allSettled([(async () => adapter.connect())()]).then(\n ([r]) => r as PromiseSettledResult<boolean>,\n );\n const ms = this.opts.connectTimeoutMs;\n if (ms === undefined) return this.classify(adapter, await attempt);\n let timer: NodeJS.Timeout | undefined;\n const first = await Promise.race([\n attempt,\n new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), ms);\n }),\n ]);\n if (timer !== undefined) clearTimeout(timer);\n if (first !== \"timeout\") return this.classify(adapter, first);\n void attempt.then((late) => this.releaseLateConnect(adapter, late));\n const reason = `connect timed out after ${ms}ms`;\n this.emitState(adapter.platform, \"timed_out\", reason);\n return { adapter, failure: { platform: adapter.platform, reason }, retry: true };\n }\n\n /** A connect that finished after the runner gave up on it must not stay connected unseen. */\n private releaseLateConnect(\n adapter: BasePlatformAdapter,\n late: PromiseSettledResult<boolean>,\n ): void {\n if (late.status !== \"fulfilled\" || !late.value) return;\n if (this.connectedPlatforms.has(adapter.platform)) return; // a retry connected it meanwhile\n void releaseAdapters([adapter], \"releasing a connect that timed out\", this.redact);\n }\n\n private classify(\n adapter: BasePlatformAdapter,\n outcome: PromiseSettledResult<boolean>,\n ): IsolatedResult {\n if (outcome.status === \"fulfilled\" && outcome.value) {\n this.connectedPlatforms.add(adapter.platform);\n this.emitState(adapter.platform, \"connected\");\n return { adapter, failure: undefined, retry: false };\n }\n const reason = connectFailureReason(outcome, this.redact);\n this.emitState(adapter.platform, \"failed\", reason);\n const retry = outcome.status === \"rejected\" && !isTerminalConnectError(outcome.reason);\n return { adapter, failure: { platform: adapter.platform, reason }, retry };\n }\n\n private wireInbound(adapters: ReadonlyArray<BasePlatformAdapter>): void {\n for (const a of 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, a);\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 }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E). A disconnect that fails does not make `stop()`\n * reject and does not stop the other disconnects; it is written to stderr, redacted, naming the\n * platform.\n *\n * An adapter still connecting under an in-flight start is released when that start settles;\n * `stop()` does not wait for it.\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 for (const t of this.retryTimers) clearTimeout(t);\n this.retryTimers.clear();\n this.connectedPlatforms.clear();\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 releaseAdapters([...new Set(this.opts.adapters)], \"stopping the runner\", this.redact);\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, adapter: BasePlatformAdapter): Promise<void> {\n const ctx = this.buildContext(event, adapter);\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 // Reported as a handler error is (EC-F): post_outbound never fires for a rejected send.\n await ctx.reply(decision.message).catch(async (err) => {\n const error = err as Error;\n await this.hookExecutor.fireOnError({ event, error });\n process.stderr.write(`[gateway] auto-reply error: ${this.redact(error.message)}\\n`);\n });\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 const stopTyping = keepTyping(adapter, event.channel.id);\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: ${this.redact((err as Error).message)}\\n`);\n } finally {\n await stopTyping();\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, adapter: BasePlatformAdapter): GatewayContext {\n return {\n event,\n reply: async (text, opts) =>\n this.deliver(event, adapter, {\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n ...attachmentsOf(opts?.attachments),\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 * An outbound with attachments for an adapter that does not declare `supportsAttachments` is\n * refused here as `attachments_unsupported`, with no `sendMessage` call, so an adapter that\n * ignores the field cannot drop the image and report success (B-674).\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 adapter: BasePlatformAdapter | undefined,\n outbound: OutboundMessage,\n ): Promise<SendResult> {\n // The receiving adapter answers, but only for its own platform's events.\n const target = adapter?.platform === event.platform ? adapter : undefined;\n const result: SendResult =\n target === undefined\n ? { ok: false, error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` } }\n : (refuseUnsupportedAttachments(target, outbound) ?? (await target.sendMessage(outbound)));\n await this.hookExecutor.firePostOutbound({ event, outbound, result });\n return result;\n }\n}\n","/**\n * `withMediaUnderstanding`: folds a voice note's transcript (and, once events carry them, an\n * image's description) into the turn text. The gateway makes no model or network call; the\n * caller supplies the functions.\n */\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\nimport type { GatewayHandler } from \"./gateway-runner.js\";\n\n/** Options for `withMediaUnderstanding`: the functions that understand media, a size cap and a failure sink. */\nexport interface MediaUnderstandingOptions {\n /** e.g. plugin-voice's transcribe, bound to its config. */\n transcribe?(audio: { data: Uint8Array; mediaType: string }): Promise<string>;\n /** Called for each image an event carries, once inbound images exist. */\n describeImage?(image: { data: Uint8Array; mediaType: string }): Promise<string>;\n /** Largest payload sent to a function. Default 20 MiB; larger is reported as not understood. */\n readonly maxBytes?: number;\n /** Where a failure is reported, with the media type and the error name only. */\n readonly write?: (line: string) => void;\n}\n\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024;\n\nfunction sanitizeType(mediaType: string): string {\n return mediaType.replace(/[^\\w/.+-]/g, \"\");\n}\n\nfunction errorName(error: unknown): string {\n return error instanceof Error ? error.name : \"UnknownError\";\n}\n\n/** Wraps a handler: the event it receives has the transcript or description appended to text. */\nexport function withMediaUnderstanding(\n handler: GatewayHandler,\n options: MediaUnderstandingOptions,\n): GatewayHandler {\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n const write = options.write ?? ((line: string) => void process.stderr.write(`${line}\\n`));\n\n const understand = async (\n kind: \"Audio transcript\" | \"Image description\",\n media: { data: Uint8Array; mediaType: string },\n fn: ((m: { data: Uint8Array; mediaType: string }) => Promise<string>) | undefined,\n ): Promise<string> => {\n const type = sanitizeType(media.mediaType);\n if (fn === undefined) return `[Attachment of type ${type} not understood]`;\n const failed = `[Attachment of type ${type} could not be understood]`;\n if (media.data.byteLength > maxBytes) {\n report(type, \"TooLarge\");\n return failed;\n }\n try {\n const text = await fn({ data: media.data, mediaType: media.mediaType });\n return `[${kind}: ${text}]`;\n } catch (error) {\n report(type, errorName(error));\n return failed;\n }\n };\n\n const report = (type: string, name: string): void => {\n try {\n write(`[gateway] media understanding failed for ${type}: ${name}`);\n } catch {\n // a failing sink never fails the turn\n }\n };\n\n return async (event, ctx) => {\n const lines: string[] = [];\n if (event.audio !== undefined) {\n lines.push(\n await understand(\"Audio transcript\", event.audio, options.transcribe?.bind(options)),\n );\n }\n if (lines.length === 0) return handler(event, ctx);\n const text = [event.text, ...lines].filter((part) => part !== \"\").join(\"\\n\");\n const wrapped: GatewayMessageEvent = { ...event, text };\n return handler(wrapped, ctx);\n };\n}\n","/**\n * A small key/value store for credentials an adapter must keep across restarts, such as a rotated\n * OAuth refresh token.\n *\n * @public\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { chmod, mkdir, readFile, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\n\n/** Reads and writes one string credential per key. @public */\nexport interface CredentialStore {\n /** The stored value, or `undefined` when the key was never set. */\n get(key: string): Promise<string | undefined>;\n /** Store `value` under `key`, replacing any earlier value. */\n set(key: string, value: string): Promise<void>;\n}\n\nconst KEY_PATTERN = /^[A-Za-z0-9._:-]+$(?![\\s\\S])/;\n\nfunction fileFor(dir: string, key: string): string {\n // `.` and `..` name the directory itself or its parent.\n if (!KEY_PATTERN.test(key) || key === \".\" || key === \"..\") {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"invalid_credential_key\",\n message: `gateway: invalid_credential_key (keys match [A-Za-z0-9._:-]+): ${JSON.stringify(key)}`,\n });\n }\n return join(dir, key.replaceAll(\":\", \"%3A\"));\n}\n\n/** One file per key under `dir`, mode 0600, written to a temp file and renamed. @public */\nexport function createFileCredentialStore(dir: string): CredentialStore {\n return {\n async get(key) {\n const path = fileFor(dir, key);\n try {\n return await readFile(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"credential_store_unreadable\",\n message: `gateway: credential_store_unreadable: ${path}`,\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n },\n async set(key, value) {\n const path = fileFor(dir, key);\n await mkdir(dir, { recursive: true });\n const tmp = `${path}.${randomBytes(6).toString(\"hex\")}.tmp`;\n try {\n await writeFile(tmp, value, { mode: 0o600 });\n await chmod(tmp, 0o600);\n await rename(tmp, path);\n } catch (err) {\n await unlink(tmp).catch(() => undefined);\n throw err;\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. Escapes ids (`_` to `__`, `-` to `_d`) so the format\n * remains splittable on `-` and distinct ids never share a key.\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\nexport function sanitize(s: string): string {\n // Injective: every `_` in the output is followed by `_` or `d`.\n return s.replace(/_/g, \"__\").replace(/-/g, \"_d\");\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 * Rule-based agent bindings: pick the agent that answers a message by\n * platform, account and peer.\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport type { MessageEvent, PlatformName } from \"../types/message-event.js\";\nimport { type AgentIdStrategy, sanitize } from \"./router.js\";\n\nexport interface AgentBindingRule {\n readonly agent: string;\n readonly platform?: PlatformName;\n /** Matched against accountOf(event). */\n readonly account?: string;\n /** Matched against event.sender.id for a DM and event.channel.id otherwise. */\n readonly peer?: string;\n}\n\n/** Options for {@link createAgentBindings}. */\nexport interface AgentBindingsOptions {\n readonly defaultAgent: string;\n readonly rules: ReadonlyArray<AgentBindingRule>;\n /** Agents that exist; every rule and the default must name one. */\n readonly agents: ReadonlyArray<string>;\n /** Which bot account received the event, when the app runs several. Default: undefined. */\n readonly accountOf?: (event: MessageEvent) => string | undefined;\n}\n\n/** Chooses the agent that answers an event. */\nexport interface AgentBindings {\n agentFor(event: MessageEvent): string;\n}\n\nfunction unknownAgent(agent: string): GatewayConfigurationError {\n return new GatewayConfigurationError(\"gateway\", {\n code: \"unknown_agent\",\n message: `gateway: unknown_agent: ${agent}`,\n detail: agent,\n });\n}\n\n/**\n * Builds bindings from rules. The most specific matching rule wins (peer 4, account 2,\n * platform 1), ties go to the earlier rule, no match gives `defaultAgent`.\n * Throws `GatewayConfigurationError` for `unknown_agent` or `empty_binding_rule`.\n */\nexport function createAgentBindings(options: AgentBindingsOptions): AgentBindings {\n const known = new Set(options.agents);\n if (!known.has(options.defaultAgent)) throw unknownAgent(options.defaultAgent);\n for (const rule of options.rules) {\n if (!known.has(rule.agent)) throw unknownAgent(rule.agent);\n if (rule.platform === undefined && rule.account === undefined && rule.peer === undefined) {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"empty_binding_rule\",\n message: `gateway: empty_binding_rule: ${rule.agent}`,\n detail: rule.agent,\n });\n }\n }\n const rules = [...options.rules];\n const { accountOf } = options;\n\n return {\n agentFor(event) {\n const ctx = {\n platform: event.platform as string,\n account: accountOf?.(event),\n peer: event.channel.type === \"dm\" ? event.sender.id : event.channel.id,\n };\n let best = options.defaultAgent;\n let bestScore = 0;\n for (const rule of rules) {\n const score = scoreRule(rule, ctx);\n if (score > bestScore) {\n best = rule.agent;\n bestScore = score;\n }\n }\n return best;\n },\n };\n}\n\ninterface MatchContext {\n readonly platform: string;\n readonly account: string | undefined;\n readonly peer: string;\n}\n\n/** 0 when the rule does not match; otherwise peer 4 + account 2 + platform 1 for the fields it sets. */\nfunction scoreRule(rule: AgentBindingRule, ctx: MatchContext): number {\n const fields: ReadonlyArray<readonly [string | undefined, string | undefined, number]> = [\n [rule.platform, ctx.platform, 1],\n [rule.account, ctx.account, 2],\n [rule.peer, ctx.peer, 4],\n ];\n let score = 0;\n for (const [want, got, weight] of fields) {\n if (want === undefined) continue;\n if (want !== got) return 0;\n score += weight;\n }\n return score;\n}\n\n/** Prefixes another strategy's key with the bound agent, so two agents never share a session. */\nexport function bindingStrategy(bindings: AgentBindings, inner: AgentIdStrategy): AgentIdStrategy {\n return (event) => `${sanitize(bindings.agentFor(event))}-${inner(event)}`;\n}\n","/**\n * `scopedStrategy` — session keys with DM scopes, peer links and account labels.\n *\n * `dm` is always the second key segment, so no label or peer name can make a\n * DM key equal a group (`grp`) or thread (`tpc`) key. Every segment is encoded\n * with `encodeURIComponent` and joined with `:`, which it never emits, so the\n * key mapping is injective. Linked peers and `main` use a leading `@` segment,\n * which no encoded platform can start with (`@` encodes to `%40`).\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\nimport { type AgentIdStrategy, sanitize } from \"./router.js\";\n\n/** How DMs are keyed: one conversation, per peer, per channel and peer, or per account too. */\nexport type DmScope = \"main\" | \"per-peer\" | \"per-channel-peer\" | \"per-account-channel-peer\";\n\n/** Options for {@link scopedStrategy}. */\nexport interface ScopedStrategyOptions {\n readonly dmScope: DmScope;\n /** `<platform>:<senderId>` to a peer name. Used by `per-peer`. */\n readonly peerLinks?: ReadonlyMap<string, string>;\n /** Required when `dmScope` is `per-account-channel-peer`. */\n readonly accountLabel?: string;\n /** Group key: one per channel (default) or one per channel and sender. */\n readonly groupScope?: \"channel\" | \"channel-sender\";\n}\n\nconst join = (...segments: readonly string[]): string => segments.map(sanitize).join(\"-\");\n\nfunction invalid(message: string, detail?: string): GatewayConfigurationError {\n return new GatewayConfigurationError(\"gateway\", {\n code: \"invalid_session_scope\",\n message: `gateway: invalid_session_scope: ${message}`,\n ...(detail === undefined ? {} : { detail }),\n });\n}\n\n/**\n * Builds a strategy for the chosen DM scope. Keys:\n * `main` → `_m-dm`; `per-peer` linked → `_p-dm-<peer>`, unlinked → the\n * per-channel-peer key; `per-channel-peer` → `<platform>-dm-<sender>`;\n * `per-account-channel-peer` → `<platform>-dm-<account>-<sender>`.\n * Groups are `<platform>-grp-<channel>[-<sender>]`, topic threads\n * `<platform>-tpc-<channel>-<topic>`. Every segment is escaped with `sanitize`.\n * Throws `GatewayConfigurationError` (`invalid_session_scope`) on bad options, never per event.\n */\nexport function scopedStrategy(options: ScopedStrategyOptions): AgentIdStrategy {\n const { dmScope, peerLinks, accountLabel, groupScope = \"channel\" } = options;\n if (\n dmScope === \"per-account-channel-peer\" &&\n (accountLabel === undefined || accountLabel === \"\")\n ) {\n throw invalid(\"per-account-channel-peer requires a non-empty accountLabel\", \"accountLabel\");\n }\n if (peerLinks !== undefined) {\n for (const [from, peer] of peerLinks) {\n if (peer === \"\") throw invalid(`empty peer name for ${from}`, from);\n }\n }\n\n const dmKey = (platform: string, senderId: string): string => {\n switch (dmScope) {\n case \"main\":\n return \"_m-dm\";\n case \"per-peer\": {\n const peer = peerLinks?.get(`${platform}:${senderId}`);\n return peer === undefined ? join(platform, \"dm\", senderId) : `_p-dm-${sanitize(peer)}`;\n }\n case \"per-channel-peer\":\n return join(platform, \"dm\", senderId);\n case \"per-account-channel-peer\":\n return join(platform, \"dm\", accountLabel ?? \"\", senderId);\n }\n };\n\n return (event: GatewayMessageEvent): string => {\n const { platform, channel, sender } = event;\n if (channel.type === \"dm\") return dmKey(platform, sender.id);\n if (channel.type === \"thread\" && channel.topicId !== undefined) {\n return join(platform, \"tpc\", channel.id, channel.topicId);\n }\n return groupScope === \"channel-sender\"\n ? join(platform, \"grp\", channel.id, sender.id)\n : join(platform, \"grp\", channel.id);\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\nimport { type FenceRegion, fenceAt, openerEol, scanFences } from \"./fence.js\";\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 * When true, a cut that would fall inside a Markdown table row (a line whose first non-blank\n * character is `|`) moves back to the start of that row, provided the row fits in the window and\n * does not open the chunk; the row then opens the next chunk whole and byte-identical (B-556).\n * A row longer than the window is cut by length as before. Text with no table row splits exactly\n * as without the option. Default: `false`.\n */\n readonly keepTableRows?: 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`, or `\\r` alone or before `\\n`: GFM reads a lone CR as a line ending too. */\nconst isLineEnd = (ch: string | undefined): boolean => ch === \"\\n\" || ch === \"\\r\";\n\n/** True when the line starting at `from` is a table row: optional blanks, then a pipe. */\nfunction startsTableRow(text: string, from: number): boolean {\n let at = from;\n while (at < text.length && /^[^\\S\\r\\n]$/.test(text[at] ?? \"\")) at += 1;\n return text[at] === \"|\";\n}\n\n/**\n * Where to cut instead of `cut` so a table row it falls inside stays whole: `start` is the row's\n * first character (the next chunk begins there), `end` is where this chunk ends, its trailing line\n * endings dropped. Undefined when `cut` is not inside a row, the row opens the chunk, or the row\n * does not fit in `window`.\n */\nfunction rowSafeCut(\n text: string,\n cut: number,\n window: number,\n): { readonly end: number; readonly start: number } | undefined {\n const start = tableRowStart(text, cut);\n if (start === undefined || rowLength(text, start, cut, window) > window) return undefined;\n let end = start;\n while (end > 0 && isLineEnd(text[end - 1])) end -= 1;\n return end > 0 ? { end, start } : undefined;\n}\n\n/** Start of the table row `cut` falls inside, or undefined (not in a row, or the row opens the text). */\nfunction tableRowStart(text: string, cut: number): number | undefined {\n if (cut >= text.length || isLineEnd(text[cut])) return undefined;\n let start = cut;\n while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;\n return start > 0 && startsTableRow(text, start) ? start : undefined;\n}\n\n/** Length of the row from `start`, scanning no further than `window` past it. */\nfunction rowLength(text: string, start: number, cut: number, window: number): number {\n let rowEnd = cut;\n while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;\n return rowEnd - start;\n}\n\n/** What one fence-aware cut does: the chunk to emit and the text that remains. */\ninterface CutStep {\n readonly chunk: string;\n readonly remaining: string;\n}\n\n/** The table-row cut as a step, undefined when the cut is not inside a row that fits. */\nfunction rowStep(remaining: string, cut: number, window: number): CutStep | undefined {\n const moved = rowSafeCut(remaining, cut, window);\n if (moved === undefined) return undefined;\n return { chunk: remaining.slice(0, moved.end), remaining: remaining.slice(moved.start) };\n}\n\n/** A cut in a fence's opening line moves back to the fence start; undefined when nothing precedes it. */\nfunction stepBeforeFence(remaining: string, region: FenceRegion): CutStep | undefined {\n let end = region.start;\n while (end > 0 && isLineEnd(remaining[end - 1])) end -= 1;\n if (end === 0) return undefined;\n return { chunk: remaining.slice(0, end), remaining: remaining.slice(region.start) };\n}\n\n/** Close `region` at the end of the chunk and reopen it, opening line and all, at the start of the next. */\nfunction stepThroughFence(\n remaining: string,\n region: FenceRegion,\n window: number,\n surrogateGuard: boolean,\n): CutStep | undefined {\n const eol = openerEol(remaining, region);\n const room = window - region.closer.length - eol.length;\n if (room <= region.contentStart) return undefined;\n let at = remaining.lastIndexOf(\"\\n\", room);\n let rest = at + 1;\n if (at < region.contentStart) {\n at = surrogateGuard ? guardSurrogate(remaining, room) : room;\n rest = at;\n } else if (remaining[at - 1] === \"\\r\") {\n at -= 1;\n }\n return {\n chunk: `${remaining.slice(0, at)}${eol}${region.closer}`,\n remaining: `${region.opener}${eol}${remaining.slice(rest)}`,\n };\n}\n\n/**\n * The cut for a position inside a fenced block (B-518): out of the opening line, or closed and\n * reopened at a line end when one fits, so no code line is split. Undefined when `cut` is not inside\n * a fence or no room is left for the closing marker, and the caller cuts as it would without fences.\n */\nfunction fenceStep(\n remaining: string,\n cut: number,\n window: number,\n surrogateGuard: boolean,\n): CutStep | undefined {\n const region = fenceAt(scanFences(remaining), cut);\n if (region === undefined) return undefined;\n return cut <= region.openerEnd\n ? stepBeforeFence(remaining, region)\n : stepThroughFence(remaining, region, window, surrogateGuard);\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 keepTableRows = 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 const hasFence = scanFences(text).length > 0;\n let remaining = text;\n while (remaining.length > safeLimit) {\n const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);\n const step = (hasFence ? fenceStep(remaining, cut, safeLimit, surrogateGuard) : undefined) ??\n (keepTableRows ? rowStep(remaining, cut, safeLimit) : undefined) ?? {\n chunk: remaining.slice(0, cut),\n remaining: remaining.slice(cut).replace(stripLeading, \"\"),\n };\n parts.push(step.chunk);\n remaining = step.remaining;\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 regions = scanFences(text);\n if (regions.length > 0) return chunkFencedByGrapheme(text, partLimit, regions);\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/** Finds the grapheme starts of `text`: the largest in `(pos, max]`, else the next one past `pos`. */\nfunction graphemeBoundaries(text: string): (pos: number, max: number) => number {\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const starts = Array.from(segmenter.segment(text), (s) => s.index);\n starts.push(text.length);\n return (pos, max) => {\n const after = starts.filter((b) => b > pos);\n const within = after.filter((b) => b <= max);\n return within.at(-1) ?? after[0] ?? text.length;\n };\n}\n\n/** How a part ends and the next begins: the closing marker, and the opening line to put back. */\ninterface GraphemeCut {\n readonly cut: number;\n readonly suffix: string;\n readonly reopen: string;\n}\n\n/**\n * The grapheme walk when `text` holds a fence (B-518): a part cut inside a fenced block ends with the\n * closing marker and the next opens with the opening line again. A cut falls at a line end when one\n * fits. Text with no fence never reaches here.\n */\nfunction chunkFencedByGrapheme(\n text: string,\n partLimit: number,\n regions: readonly FenceRegion[],\n): string[] {\n const boundaryUpTo = graphemeBoundaries(text);\n const parts: string[] = [];\n let pos = 0;\n let prefix = \"\";\n while (prefix.length + (text.length - pos) > partLimit) {\n const room = partLimit - prefix.length;\n const plain = boundaryUpTo(pos, pos + room);\n const region = fenceAt(regions, plain);\n const next: GraphemeCut =\n region === undefined\n ? { cut: plain, suffix: \"\", reopen: \"\" }\n : fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo);\n parts.push(prefix + text.slice(pos, next.cut) + next.suffix);\n pos = next.cut;\n prefix = next.reopen;\n }\n parts.push(prefix + text.slice(pos));\n return parts;\n}\n\n/** The cut for `plain`, a grapheme cut that falls inside `region`. */\nfunction fenceGraphemeCut(\n text: string,\n region: FenceRegion,\n pos: number,\n plain: number,\n room: number,\n boundaryUpTo: (pos: number, max: number) => number,\n): GraphemeCut {\n const none: GraphemeCut = { cut: plain, suffix: \"\", reopen: \"\" };\n if (plain <= region.openerEnd) {\n return region.start > pos ? { ...none, cut: region.start } : none;\n }\n const eol = openerEol(text, region);\n const max = pos + room - region.closer.length - eol.length;\n const floor = Math.max(pos, region.contentStart);\n if (max <= floor) return none;\n let at = boundaryUpTo(pos, max);\n const nl = text.lastIndexOf(\"\\n\", at - 1);\n if (nl >= floor - 1 && nl + 1 > pos) at = nl + 1;\n if (at <= pos || at > max) return none;\n if (fenceAt([region], at) === undefined) return { ...none, cut: at };\n const closes = isLineEnd(text[at - 1]);\n return { cut: at, suffix: (closes ? \"\" : eol) + region.closer, reopen: region.opener + eol };\n}\n","/**\n * Grapheme-safe splitting of long text that keeps Markdown table rows whole (B-556).\n *\n * @internal\n */\n\n/** A blank that may precede a row's leading pipe: whitespace other than a line ending. */\nconst ROW_BLANK = /^[^\\S\\r\\n]$/;\n\n/** `\\n`, or `\\r` alone or before `\\n`: GFM reads a lone CR as a line ending too. */\nfunction isLineEnd(character: string | undefined): boolean {\n return character === \"\\n\" || character === \"\\r\";\n}\n\n/**\n * True when the line starting at `from` is a table row: optional blanks, then a pipe. The same\n * definition lives in core `ROW_START` (packages/gateway/src/text/dialect.ts) and in the\n * gateway-nextcloud-talk splitter.\n */\nfunction startsTableRow(text: string, from: number): boolean {\n let at = from;\n while (at < text.length && ROW_BLANK.test(text[at] ?? \"\")) at += 1;\n return text[at] === \"|\";\n}\n\n/** Start of the line holding `cut - 1`, or `partStart` when the line starts at or before it. */\nfunction lineStartBefore(text: string, cut: number, partStart: number): number {\n let at = cut;\n while (at > partStart && !isLineEnd(text[at - 1])) at -= 1;\n return at;\n}\n\n/** End of the line holding `cut`, without its line ending, scanning no further than `bound`. */\nfunction lineEndFrom(text: string, cut: number, bound: number): number {\n let at = cut;\n while (at < text.length && at <= bound && !isLineEnd(text[at])) at += 1;\n return at;\n}\n\n/**\n * The cut to use instead of `cut`: the start of the table row `cut` falls inside, when that row\n * starts after `partStart` and fits in `partLimit` without its line ending; `cut` otherwise. A row\n * that opens the part, or is longer than a part, is cut by length as before (FR-007).\n */\nfunction rowSafeCut(text: string, partStart: number, cut: number, partLimit: number): number {\n const lineStart = lineStartBefore(text, cut, partStart);\n if (lineStart <= partStart || lineStart === cut) return cut;\n if (isLineEnd(text[cut]) || !startsTableRow(text, lineStart)) return cut;\n const lineEnd = lineEndFrom(text, cut, lineStart + partLimit);\n return lineEnd - lineStart <= partLimit ? lineStart : cut;\n}\n\n/**\n * The last grapheme boundary at or below `start + partLimit`. When one grapheme starting at\n * `start` is longer than the part, its end: the oversized part `chunkByGrapheme` emits (ADR D3).\n */\nfunction graphemeCut(segments: Intl.Segments, start: number, partLimit: number): number {\n const cut = start + partLimit;\n const segment = segments.containing(cut);\n if (segment === undefined || segment.index >= cut) return cut;\n return segment.index > start ? segment.index : segment.index + segment.segment.length;\n}\n\n/**\n * Parts of at most `partLimit` units, cut at grapheme boundaries and before straddled rows.\n * Shared by the SMS and LINE splitters (text no longer than a part is theirs to handle).\n */\nexport function splitKeepingRows(text: string, partLimit: number): string[] {\n const segments = new Intl.Segmenter(undefined, { granularity: \"grapheme\" }).segment(text);\n const parts: string[] = [];\n let start = 0;\n while (text.length - start > partLimit) {\n const cut = rowSafeCut(text, start, graphemeCut(segments, start, partLimit), partLimit);\n /* c8 ignore next 3 -- unreachable: both cuts land after `start` (graphemeCut, rowSafeCut). */\n if (cut <= start) {\n throw new RangeError(`splitKeepingRows: no progress at offset ${start} of ${text.length}`);\n }\n parts.push(text.slice(start, cut));\n start = cut;\n }\n if (start < text.length) parts.push(text.slice(start));\n return parts;\n}\n","/** The outcome of delivering one event to the runner's handlers. */\ntype DeliverOutcome = \"ok\" | \"no_handler\" | \"handler_threw\";\n\n/**\n * Map the outcomes of one delivered batch to an HTTP status, worst wins: `handler_threw` is 500,\n * `no_handler` is 503 so the provider retries, `ok` and an empty batch are 200. An unknown outcome\n * throws instead of answering 200.\n */\nexport function statusForDeliver(outcomes: ReadonlyArray<DeliverOutcome>): 200 | 500 | 503 {\n let status: 200 | 500 | 503 = 200;\n for (const outcome of outcomes as ReadonlyArray<string>) {\n if (outcome === \"handler_threw\") {\n status = 500;\n } else if (outcome === \"no_handler\") {\n if (status === 200) status = 503;\n } else if (outcome !== \"ok\") {\n throw new Error(`unknown deliver outcome: ${outcome}`);\n }\n }\n return status;\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 * every adapter.\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 readonly headers?: Readonly<Record<string, string | string[] | undefined>>;\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 /** Where Express 4's `listen` reports a failure to bind; `http.Server` has it. */\n once?(event: \"error\", listener: (err: Error) => void): unknown;\n}\n\n/**\n * What can start a listener. Express's app satisfies it: Express 5 passes a failure to bind to the\n * callback, Express 4 only emits it on the returned server.\n */\nexport interface ListenableApp {\n listen(port: number, cb: (err?: Error) => 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 * A body larger than `maxBytes` is refused before it is held. `maxBytes` defaults to\n * {@link DEFAULT_WEBHOOK_MAX_BYTES} (1 MiB); pass `Number.POSITIVE_INFINITY` for no limit. The rest\n * of the stream is read and dropped, and once it ends the middleware answers 413 with the JSON body\n * `{ \"error\": \"request body too large\" }` itself; `next` is not called. The capture runs before\n * signature verification, so without a limit any client could stream a body until the heap runs out.\n * The refusal is answered here rather than handed to `next` as an error because Express's final\n * handler writes an error as an HTML page carrying its stack whenever `NODE_ENV` is not\n * `production`, and these routes answer anyone.\n *\n * The middleware settles once: after a refusal, more data, the end of the stream or a stream\n * error do nothing, and after a stream error the end of the stream does nothing.\n *\n * @param tag the package name for the diagnostic, so a reader knows which router is complaining\n * @param options `maxBytes`, the largest body accepted; 1 MiB when absent, `Infinity` for no limit\n * @throws RangeError when `maxBytes` is NaN or negative\n */\nexport function rawBodyCapture(tag: string, options: RawBodyCaptureOptions = {}) {\n const maxBytes = options.maxBytes ?? DEFAULT_WEBHOOK_MAX_BYTES;\n if (!(maxBytes >= 0)) {\n throw new RangeError(\n `[${tag}] rawBodyCapture: maxBytes must be a number of zero or more (Infinity allowed), got ${maxBytes}`,\n );\n }\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, rawRes: 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 let bytes = 0;\n // `refused` drops what is left of the body; `settled` keeps every path to one answer.\n let refused = declaredLength(req) > maxBytes;\n let settled = false;\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n if (refused || settled) return;\n bytes += Buffer.byteLength(chunk);\n if (bytes > maxBytes) {\n refused = true;\n buf = \"\";\n return;\n }\n buf += chunk;\n });\n req.on(\"end\", () => {\n if (settled) return;\n settled = true;\n if (refused) {\n answerTooLarge(rawRes as JsonResponse, tag, maxBytes);\n return;\n }\n (req as unknown as { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err: unknown) => {\n if (settled) return;\n settled = true;\n // A client that aborts a refused body has nobody left to answer.\n if (refused) return;\n next(err);\n });\n };\n}\n\n/** The body size {@link rawBodyCapture} accepts when `maxBytes` is not given: 1 MiB. */\nexport const DEFAULT_WEBHOOK_MAX_BYTES = 1024 * 1024;\n\n/** Options for {@link rawBodyCapture}. */\nexport interface RawBodyCaptureOptions {\n /** The largest body accepted, in bytes. A larger one is refused with 413. Defaults to\n * {@link DEFAULT_WEBHOOK_MAX_BYTES}; `Number.POSITIVE_INFINITY` removes the limit. */\n readonly maxBytes?: number;\n}\n\n/** The `content-length` the client declared, or 0 when it declared none or an unreadable one. */\nfunction declaredLength(req: RawBodyRequest): number {\n const value = req.headers?.[\"content-length\"];\n const declared = Number(Array.isArray(value) ? value[0] : value);\n return Number.isFinite(declared) ? declared : 0;\n}\n\n/** What the refusal writes to. Express's `Response` satisfies it. */\ninterface JsonResponse {\n status(code: number): { json(body: unknown): unknown };\n}\n\n/** Answer 413 as JSON, and say on stderr which router refused and at what limit. */\nfunction answerTooLarge(res: JsonResponse, tag: string, maxBytes: number): void {\n process.stderr.write(`[${tag}] refused a request (413): body larger than ${maxBytes} bytes\\n`);\n res.status(413).json({ error: \"request body too large\" });\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 *\n * `start()` rejects with the error the bind failed with (`EADDRINUSE` for a port another listener\n * holds), under Express 4 and 5 alike, and a later `start()` tries again.\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 // A port another process holds used to resolve this as started: Express 5 hands the bind\n // error to the callback, which ignored it, and `connect()` answered true over no listener.\n await new Promise<void>((resolve, reject) => {\n const settle = (err?: Error): void => {\n if (err === undefined) resolve();\n else reject(err);\n };\n const current = opts.app.listen(opts.port, settle);\n listener = current;\n current.once?.(\"error\", settle);\n }).catch((err: unknown) => {\n listener = undefined;\n throw err;\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","/**\n * `createWebhookHandler` — one Fetch `Request` to `Response` handler for every webhook channel.\n *\n * It routes by platform, caps the body, and answers with the descriptor's `handle`, or runs verify,\n * JSON.parse and ingest. No secret, header value or body reaches `onError` or a response.\n */\n\nimport type { BasePlatformAdapter } from \"../adapter/base.js\";\nimport type {\n ChannelWebhook,\n WebhookAnswer,\n WebhookRequest,\n} from \"../channel/channel-descriptor.js\";\nimport type { BuiltChannel } from \"../channel/create-channels.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\nimport { DEFAULT_WEBHOOK_MAX_BYTES } from \"./express-server.js\";\n\n/** Options for `createWebhookHandler`. */\nexport interface WebhookHandlerOptions {\n /** The built channels; only those with `transport: \"webhook\"` are routed. */\n readonly channels: ReadonlyArray<BuiltChannel>;\n /** Whether the platform's runner has started; a platform that has not answers 503. */\n readonly isStarted: (platform: PlatformName) => boolean;\n /** Body cap in bytes. Default 1 MiB. */\n readonly maxBodyBytes?: number;\n /** Default: the last path segment after `/webhooks/`. */\n readonly platformFor?: (url: URL) => PlatformName | undefined;\n /** Called when a handle/ingest throws; the response is 500 with no body. */\n readonly onError?: (platform: PlatformName, error: unknown) => void;\n}\n\nconst TOO_LARGE = Symbol(\"too-large\");\n\nfunction defaultPlatformFor(url: URL): PlatformName | undefined {\n const marker = \"/webhooks/\";\n const at = url.pathname.lastIndexOf(marker);\n if (at < 0) return undefined;\n const rest = url.pathname.slice(at + marker.length).replace(/\\/+$/, \"\");\n const last = rest.split(\"/\").pop();\n return last ? (last as PlatformName) : undefined;\n}\n\nfunction plain(status: number, extra?: Record<string, string>): Response {\n return new Response(null, { status, headers: extra });\n}\n\nfunction tooLarge(): Response {\n return plain(413, { connection: \"close\" });\n}\n\nasync function readCapped(request: Request, max: number): Promise<string | typeof TOO_LARGE> {\n const declared = request.headers.get(\"content-length\");\n if (declared !== null && Number(declared) > max) return TOO_LARGE;\n if (request.body === null) return \"\";\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > max) {\n await reader.cancel().catch(() => undefined);\n return TOO_LARGE;\n }\n chunks.push(value);\n }\n const joined = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n joined.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return new TextDecoder().decode(joined);\n}\n\nfunction answerResponse(answer: WebhookAnswer): Response {\n const headers: Record<string, string> = {};\n if (answer.contentType !== undefined) headers[\"content-type\"] = answer.contentType;\n return new Response(answer.body ?? null, { status: answer.status, headers });\n}\n\nasync function runDefault(\n webhook: ChannelWebhook<BasePlatformAdapter>,\n adapter: BasePlatformAdapter,\n request: WebhookRequest,\n): Promise<Response> {\n if (!webhook.verify(adapter, request)) return plain(401);\n let payload: unknown;\n try {\n payload = JSON.parse(request.rawBody);\n } catch {\n return plain(400);\n }\n const result = await webhook.ingest(adapter, payload);\n if (result === \"delivered\") return plain(200);\n return plain(result === \"no_handler\" ? 503 : 400);\n}\n\nfunction headersOf(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n request.headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\nasync function readBody(request: Request, max: number): Promise<string | Response> {\n let body: string | typeof TOO_LARGE;\n try {\n body = await readCapped(request, max);\n } catch {\n return plain(400);\n }\n return body === TOO_LARGE ? tooLarge() : body;\n}\n\n/**\n * Build a Fetch handler for every `transport: \"webhook\"` channel in `channels`: 404 for an unknown\n * platform, 503 while it has not started, 405 for a method the route does not take, 413 past the\n * body cap, 400 for an unreadable body, and 500 with no body when a route throws.\n */\nexport function createWebhookHandler(\n options: WebhookHandlerOptions,\n): (request: Request) => Promise<Response> {\n const max = options.maxBodyBytes ?? DEFAULT_WEBHOOK_MAX_BYTES;\n const platformFor = options.platformFor ?? defaultPlatformFor;\n const routes = new Map<PlatformName, BuiltChannel>();\n for (const channel of options.channels) {\n if (channel.descriptor.transport === \"webhook\")\n routes.set(channel.descriptor.platform, channel);\n }\n const route = (url: URL): BuiltChannel | undefined => {\n const platform = platformFor(url);\n return platform === undefined ? undefined : routes.get(platform);\n };\n return async (request) => {\n const channel = route(new URL(request.url));\n if (channel === undefined) return plain(404);\n const platform = channel.descriptor.platform;\n if (!options.isStarted(platform)) return plain(503);\n const webhook = channel.descriptor.webhook as ChannelWebhook<BasePlatformAdapter>;\n const refused = refuseMethod(webhook, request);\n if (refused !== undefined) return refused;\n const rawBody = await readBody(request, max);\n if (typeof rawBody !== \"string\") return rawBody;\n try {\n return await dispatch(webhook, channel.adapter, {\n rawBody,\n headers: headersOf(request),\n method: request.method.toUpperCase(),\n url: request.url,\n });\n } catch (error) {\n options.onError?.(platform, error);\n return plain(500);\n }\n };\n}\n\nfunction refuseMethod(\n webhook: ChannelWebhook<BasePlatformAdapter>,\n request: Request,\n): Response | undefined {\n const methods = webhook.methods ?? [\"POST\"];\n const method = request.method.toUpperCase();\n if (methods.some((m) => m.toUpperCase() === method)) return undefined;\n return plain(405, { allow: methods.join(\", \") });\n}\n\nasync function dispatch(\n webhook: ChannelWebhook<BasePlatformAdapter>,\n adapter: BasePlatformAdapter,\n request: WebhookRequest,\n): Promise<Response> {\n if (webhook.handle !== undefined) return answerResponse(await webhook.handle(adapter, request));\n return runDefault(webhook, adapter, request);\n}\n"]}
1
+ {"version":3,"sources":["../src/text/fence.ts","../src/text/dialect.ts","../src/text/channel-rendering.ts","../src/adapter/base.ts","../src/adapter/send-error.ts","../src/auth/token-cache.ts","../src/text/seen-ids.ts","../src/adapter/weixin-xml.ts","../src/adapter/weixin-base.ts","../src/errors/config-error.ts","../src/channel/channel-config-readers.ts","../src/channel/channel-descriptor.ts","../src/channel/config-from-env.ts","../src/channel/create-channels.ts","../src/delivery/attachments.ts","../src/delivery/router.ts","../src/errors/lifecycle-error.ts","../src/security/credential-patterns.ts","../src/hooks/pairing-store.ts","../src/hooks/access-policy.ts","../src/hooks/chat-command.ts","../src/hooks/executor.ts","../src/runner/reconnect-backoff.ts","../src/runner/gateway-runner.ts","../src/runner/media-understanding.ts","../src/security/credential-store.ts","../src/session/router.ts","../src/session/bindings.ts","../src/session/scoped-strategy.ts","../src/text/chunk.ts","../src/text/split-rows.ts","../src/webhook/deliver-status.ts","../src/webhook/express-server.ts","../src/webhook/fetch-handler.ts"],"names":["check","invalid","isAbsent","code","refused","join","parts","plain","isLineEnd","startsTableRow","rowSafeCut","load"],"mappings":";;;;;;;AA+BA,IAAM,SAAA,GAAY,uBAAA;AAClB,IAAM,OAAA,GAAU,2BAAA;AAChB,IAAM,OAAA,GAAU,6BAAA;AAEhB,SAAS,SAAA,CAAU,MAAc,IAAA,EAA6C;AAC5E,EAAA,IAAI,GAAA,GAAM,IAAA;AACV,EAAA,OAAO,GAAA,GAAM,IAAA,CAA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,CAAe,MAAM,CAAA;AACjE;AAEA,SAAS,YAAA,CACP,SACA,OAAA,EACsB;AACtB,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,IAAW,CAAC,MAAM,CAAA;AAC1C,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,MAAA,CAAO,WAAA,EAAY;AAC1C,EAAA,IAAI,OAAA,CAAQ,KAAK,CAAC,CAAA,KAAM,EAAE,WAAA,EAAY,KAAM,MAAM,CAAA,EAAG,OAAO,MAAA;AAC5D,EAAA,OAAO,KAAA,CAAM,KAAK,EAAE,KAAA,EAAO,QAAQ,IAAA,CAAK,IAAI,GAAG,CAAA;AACjD;AAEA,eAAe,QAAA,CACb,OAAA,EACA,OAAA,EACA,OAAA,EACmB;AACnB,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,MAAA,EAAW,OAAO,cAAA,CAAe,MAAM,OAAA,CAAQ,MAAA,CAAO,OAAA,EAAS,OAAO,CAAC,CAAA;AAC9F,EAAA,OAAO,UAAA,CAAW,OAAA,EAAS,OAAA,EAAS,OAAO,CAAA;AAC7C","file":"index.js","sourcesContent":["/**\n * Fenced code block scanner (B-518).\n *\n * Reads the fences of CommonMark § 4.5: a line of at most three blanks, then three or more\n * backticks or tildes (an info string after a backtick run holds no backtick), closed by a line of\n * the same character, at least as many, and nothing after them but blanks. A fence never closed runs\n * to the end of the text. Fences inside a list item or block quote (indented four or more, or behind\n * a `>`) are not read.\n *\n * @public\n */\n\n/** One fenced code block, as offsets into the scanned text. */\nexport interface FenceRegion {\n /** Offset of the first character of the opening line. */\n readonly start: number;\n /** Offset just past the opening line, before its line ending. */\n readonly openerEnd: number;\n /** Offset of the first character after the opening line's line ending (the first code line). */\n readonly contentStart: number;\n /** Offset just past the last character of the closing line (its line ending excluded), or the text length when never closed. */\n readonly end: number;\n /** The opening line, byte for byte. */\n readonly opener: string;\n /** The marker run that closes the block: the opening run, without its indent. */\n readonly closer: string;\n /** False when the text ends before a closing line. */\n readonly closed: boolean;\n}\n\n/** A cheap test for any line that could open a fence, so text with none costs one regex pass. */\nconst MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;\nconst OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;\nconst CLOSING = /^ {0,3}(`{3,}|~{3,})[ \\t]*$/;\n\nfunction lineEndAt(text: string, from: number): { end: number; next: number } {\n let end = from;\n while (end < text.length && text[end] !== \"\\n\" && text[end] !== \"\\r\") end += 1;\n let next = end;\n if (text[next] === \"\\r\" && text[next + 1] === \"\\n\") next += 2;\n else if (next < text.length) next += 1;\n return { end, next };\n}\n\n/** The closing line of a fence opened with `run`, searched from `from`: where it ends, and where the next line starts. */\nfunction findClose(\n text: string,\n from: number,\n run: string,\n): { end: number; next: number } | undefined {\n for (let scan = from; scan < text.length; ) {\n const line = lineEndAt(text, scan);\n const found = CLOSING.exec(text.slice(scan, line.end))?.[1];\n if (found !== undefined && found[0] === run[0] && found.length >= run.length) return line;\n scan = line.next;\n }\n return undefined;\n}\n\n/** Every fenced region of `text`, in order. */\nexport function scanFences(text: string): readonly FenceRegion[] {\n if (!MAY_FENCE.test(text)) return [];\n const regions: FenceRegion[] = [];\n let pos = 0;\n while (pos < text.length) {\n const start = pos;\n const line = lineEndAt(text, start);\n const open = OPENING.exec(text.slice(start, line.end));\n const run = open?.[1];\n if (run === undefined || (run.startsWith(\"`\") && (open?.[2] ?? \"\").includes(\"`\"))) {\n pos = line.next;\n continue;\n }\n const close = findClose(text, line.next, run);\n pos = close?.next ?? text.length;\n const end = close?.end ?? text.length;\n const closed = close !== undefined;\n regions.push({\n start,\n openerEnd: line.end,\n contentStart: line.next,\n end,\n opener: text.slice(start, line.end),\n closer: run,\n closed,\n });\n }\n return regions;\n}\n\n/** The region `offset` falls strictly inside (after its first character, before its end), if any. */\nexport function fenceAt(regions: readonly FenceRegion[], offset: number): FenceRegion | undefined {\n return regions.find((r) => r.start < offset && offset < r.end);\n}\n\n/** The line ending that follows the opening line of `region` in `text` (`\\n` when the text ends there). */\nexport function openerEol(text: string, region: FenceRegion): string {\n if (text.startsWith(\"\\r\\n\", region.openerEnd)) return \"\\r\\n\";\n return text[region.openerEnd] === \"\\r\" ? \"\\r\" : \"\\n\";\n}\n","/**\n * Markdown → the target channel's own dialect (B-019 FR-005).\n *\n * ## Why this exists here, and not in an adapter\n *\n * Measured 2026-09-17 across every `adapter.ts` and `split.ts` in the ten packages: **no package\n * transforms a single character of text.** What exists is markdown ESCAPE (discord, mattermost),\n * HTML escape (email), phone normalisation (whatsapp) and post-cut newline cleanup (telegram's\n * splitter). `OutboundMessage.format` is read by all ten — `adapter-contract.test.ts` proves it —\n * but reading a flag is not translating a body.\n *\n * So the agent answered `**Bom Sucesso (MG)**` and both LINE and WhatsApp delivered the asterisks\n * to a real phone. The adapters refuse the translation deliberately and they are right to:\n * `gateway-whatsapp` reads `format` only to warn once, because emphasis there is inline in the\n * text rather than a transport flag. An adapter is transport.\n *\n * `gateway-signal`, added later, edits a body and stays on the transport side of that line:\n * Signal carries emphasis as `textStyle` ranges sent beside the text, so the adapter moves a\n * markdown reply's markers into those ranges. Its rendering row is `markdown` with identity, and\n * nothing here translates for it.\n *\n * `gateway-imessage`, `gateway-google-chat` and `gateway-irc`, added with it, send to platforms\n * with no markup at all, and their rendering rows are `plain`. A presenter given\n * `channelRendering(platform)` hands them text already translated and declared `plain`. A caller\n * that sends `format: \"markdown\"` without that step would put the asterisks in front of the user,\n * so those three adapters apply their own row in that one case, as a fallback. The presenter is\n * still where translation is decided, and the row they apply is the one it would have applied.\n *\n * Translation is PRESENTATION — it depends on what was said and on where it is going at the same\n * time — so it belongs to the presenter. It is exported from here as a pure function and CALLED by\n * the channel presenter in `theokit`, never the reverse: `@theokit/gateway` must not depend on\n * `@theokit/presenter`, or a gateway stops being usable without an agent.\n *\n * ## What it deliberately does NOT do\n *\n * It is not a markdown parser. It rewrites the four inline markers that reach a chat surface in\n * practice — bold, italic, strikethrough, inline code — and it leaves everything else alone:\n * links, headings, lists, block quotes and fenced code are untouched, because no measurement here\n * says what they should become on a platform with no equivalent.\n *\n * A platform it has not been taught is passed through UNCHANGED. Inventing a mapping would be\n * wrong invisibly; passing `**bold**` through is wrong where somebody can see it.\n */\n\nimport { scanFences } from \"./fence.js\";\n\n/** A dialect is what each of the four markers becomes. `undefined` means \"drop the marker\". */\nexport interface Dialect {\n readonly bold?: string;\n readonly italic?: string;\n readonly strike?: string;\n readonly code?: string;\n}\n\n/**\n * Per-platform dialects, and the reason each one is what it is.\n *\n * Only platforms whose dialect was actually established appear. The ones absent — telegram,\n * discord, slack, mattermost, matrix, teams, email — either parse markdown natively or take a\n * transport flag their adapter already sets, so rewriting their text would corrupt it.\n *\n * `channelRendering` reuses the whatsapp, line and sms rows rather than spelling them again. Like\n * `Dialect` and `rewriteMarkers`, it is exported for that module only: the package entry does not\n * re-export it, so no consumer can reach it.\n */\nexport const DIALECTS = {\n // WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.\n whatsapp: { bold: \"*\", italic: \"_\", strike: \"~\", code: \"```\" },\n // LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.\n line: {},\n // SMS is plain text by definition of the medium.\n sms: {},\n} as const satisfies Readonly<Record<string, Dialect>>;\n\n/**\n * Every marker in ONE pattern, matched in a single pass.\n *\n * Sequential `replace` calls cannot work here and the failure is silent: rewriting `**a**` to\n * WhatsApp's `*a*` produces text the italic rule then matches, so bold arrives as italic. Caught by\n * the first test written against this file — `**Bom Sucesso (MG)**` came out `_Bom Sucesso (MG)_`.\n *\n * Alternation order is load-bearing: `**` before `*`, `~~` before `~`.\n */\nconst PATTERN =\n /\\*\\*(?<bold>.+?)\\*\\*|~~(?<strike>.+?)~~|(?<![*\\w])\\*(?!\\s)(?<italicStar>.+?)(?<!\\s)\\*(?!\\*)|(?<![_\\w])_(?!\\s)(?<italicUnderscore>.+?)(?<!\\s)_(?!\\w)|`(?<code>.+?)`/gu;\n\n/**\n * Which capture group becomes which dialect marker, in the order `PATTERN` alternates.\n *\n * A table rather than a chain of conditionals, because the two ITALIC spellings make a chain read as\n * five decisions when it encodes one lookup — and biome measured the enclosing function at a\n * cognitive complexity of 26 against a ceiling of 10. Adding a marker is a row here and an\n * alternative in `PATTERN`; nothing else moves.\n *\n * Order here does NOT matter, and the first draft of this comment said it did. `PATTERN` alternates,\n * so at most one group carries a value per match — which is exactly why the loop may return on the\n * first one it finds. Checked rather than asserted: moving `italicStar` above `bold` leaves all\n * seven tests green, while deleting a row fails two. Order is load-bearing in `PATTERN`, not here.\n */\nconst GROUP_MARKERS = [\n [\"bold\", \"bold\"],\n [\"strike\", \"strike\"],\n [\"italicStar\", \"italic\"],\n [\"italicUnderscore\", \"italic\"],\n [\"code\", \"code\"],\n] as const satisfies ReadonlyArray<readonly [string, keyof Dialect]>;\n\n/**\n * Rewrite `text` for `platform`.\n *\n * @param text - the assembled answer, in markdown as the model produced it\n * @param platform - the destination; one this function has not been taught passes through\n * @returns the text in the platform's dialect, or unchanged when none is known\n * @public\n */\nexport function toDialect(text: string, platform: string): string {\n const dialect = (DIALECTS as Readonly<Record<string, Dialect>>)[platform];\n if (dialect === undefined) return text;\n return rewriteMarkers(text, dialect);\n}\n\n/** What the one `PATTERN` match whose named groups are `groups` becomes in `dialect`. */\nfunction markerFor(\n matched: string,\n groups: Record<string, string | undefined> | undefined,\n dialect: Dialect,\n): string {\n if (groups === undefined) return matched;\n\n for (const [group, marker] of GROUP_MARKERS) {\n const content = groups[group];\n if (content === undefined) continue;\n const wrap = dialect[marker];\n return wrap === undefined ? content : `${wrap}${content}${wrap}`;\n }\n\n // PATTERN matched and named no group: unreachable while every alternative above carries one,\n // and returning the match unchanged is the only answer that cannot corrupt text if it stops\n // being true. The same reason the whole module passes an unknown platform through.\n return matched;\n}\n\n/**\n * A replace callback's answer for one match. `PATTERN` has named groups, so the callback's last\n * argument is the groups object.\n */\nfunction rewriteMatch(matched: string, args: readonly unknown[], dialect: Dialect): string {\n return markerFor(matched, args.at(-1) as Record<string, string | undefined> | undefined, dialect);\n}\n\n/** One replace over `text`: the single pass the module comment above requires. */\nfunction replaceMarkers(text: string, dialect: Dialect): string {\n return text.replace(PATTERN, (matched, ...args) => rewriteMatch(matched, args, dialect));\n}\n\n/**\n * A table row: optional blanks, then a pipe (GFM 0.29 § 4.10). GFM also accepts a row with no\n * leading pipe under a delimiter row; reading those would mean reading the delimiter row, and no\n * measurement here asked for it (B-556 plan, glossary and ADR D1). Sticky, so it is tested at a line\n * start without slicing the line out. A template only: each caller copies it with `new RegExp`,\n * so no `lastIndex` is shared between calls.\n *\n * The splitters of gateway-line, gateway-sms and gateway-nextcloud-talk carry their own copy of\n * this definition (`startsTableRow` in each `src/split.ts`, plan ADR D2); a change here belongs\n * there too.\n */\nconst ROW_START = /[^\\S\\r\\n]*\\|/y;\n\n/** A line ending as GFM reads one: `\\r\\n`, `\\n`, or a lone `\\r`. Captured, so a split keeps it. */\nconst LINE_ENDING = /(\\r\\n|\\r|\\n)/;\n\n/**\n * Any character a marker can start with (`\\x60` is the backtick). A row without one has nothing\n * to rewrite.\n */\nconst MARKER_CHARACTER = /[*_~\\x60]/;\n\nconst PIPE = 0x7c;\nconst BACKSLASH = 0x5c;\nconst LF = 0x0a;\nconst CR = 0x0d;\n\n/**\n * Answers \"is the line holding `offset` a table row?\" for offsets that only grow, as a replace\n * callback's do. The cursor moves forward once over the text, so one long line full of matches is\n * scanned once rather than once per match.\n */\nfunction rowLocator(text: string): (offset: number) => boolean {\n const rowStart = new RegExp(ROW_START);\n let lineStart = 0;\n let scanned = 0;\n return (offset) => {\n for (; scanned < offset; scanned += 1) {\n const code = text.charCodeAt(scanned);\n if (code === LF || code === CR) lineStart = scanned + 1;\n }\n rowStart.lastIndex = lineStart;\n return rowStart.test(text);\n };\n}\n\n/**\n * Rewrite each cell of a table row on its own, keeping every pipe. A pipe preceded by an odd run\n * of backslashes is content (`\\|`), as GFM reads it. Inline code holding an unescaped pipe is split\n * there too, as GFM splits it, so its backticks no longer pair and are kept (B-556 EC-1).\n */\nfunction rewriteTableRow(row: string, dialect: Dialect): string {\n let out = \"\";\n let from = 0;\n let backslashes = 0;\n for (let i = 0; i < row.length; i += 1) {\n const code = row.charCodeAt(i);\n if (code === BACKSLASH) {\n backslashes += 1;\n continue;\n }\n if (code === PIPE && backslashes % 2 === 0) {\n out += `${replaceMarkers(row.slice(from, i), dialect)}|`;\n from = i + 1;\n }\n backslashes = 0;\n }\n return out + replaceMarkers(row.slice(from), dialect);\n}\n\n/**\n * A table row cell by cell; any other line, or a line ending, with the single pass. `rowStart` is\n * the caller's copy of `ROW_START`.\n */\nfunction rewriteLine(line: string, dialect: Dialect, rowStart: RegExp): string {\n rowStart.lastIndex = 0;\n if (!rowStart.test(line)) return replaceMarkers(line, dialect);\n return MARKER_CHARACTER.test(line) ? rewriteTableRow(line, dialect) : line;\n}\n\n/**\n * The text line by line. Splitting a line from its neighbours changes nothing for a line that is\n * not a row: `.` in `PATTERN` stops at `\\n` and `\\r`, so no match crosses a line, and each\n * lookaround sees a line ending and a string edge alike.\n */\nfunction rewriteByLine(text: string, dialect: Dialect): string {\n const rowStart = new RegExp(ROW_START);\n return text\n .split(LINE_ENDING)\n .map((piece) => rewriteLine(piece, dialect, rowStart))\n .join(\"\");\n}\n\n/**\n * Rewrite the four inline markers of `text` into `dialect`.\n *\n * Shared by `toDialect` and `channelRendering`, so the one regex whose ordering is load-bearing\n * exists once: a second copy is where the bold-becomes-italic defect above would come back.\n *\n * A table row is rewritten cell by cell (B-556 FR-001): one pass over the whole text let `*a | b*`\n * open in one cell and close in the next, and the platform then lost both markers. Today's single\n * pass runs first and its result is kept unless one of its matches holds a pipe and sits on a\n * table row; only then is the text rewritten line by line. Where no match crosses a row's pipe the\n * two agree, because a match inside one cell is the match the replace finds in that cell alone,\n * and the fast path keeps a plain table at the cost of today's pass (plan ADR D1).\n *\n * @param text - markdown as the model produced it\n * @param dialect - what each marker becomes; an absent marker is dropped and its content kept\n * @returns the rewritten text\n */\nexport function rewriteMarkers(text: string, dialect: Dialect): string {\n const regions = scanFences(text);\n if (regions.length === 0) return rewriteUnfenced(text, dialect);\n // A fenced block is code: its markers and its lines stay byte-identical (B-518).\n let out = \"\";\n let from = 0;\n for (const region of regions) {\n out +=\n rewriteUnfenced(text.slice(from, region.start), dialect) +\n text.slice(region.start, region.end);\n from = region.end;\n }\n return out + rewriteUnfenced(text.slice(from), dialect);\n}\n\n/** The rewrite of text holding no fenced block: the single pass, or the row-by-row pass. */\nfunction rewriteUnfenced(text: string, dialect: Dialect): string {\n const onTableRow = rowLocator(text);\n let crossesRowPipe = false;\n // The third argument from the last of a replace callback is the match's offset.\n const rewritten = text.replace(PATTERN, (matched, ...args) => {\n if (!crossesRowPipe && matched.includes(\"|\")) {\n crossesRowPipe = onTableRow(args.at(-3) as number);\n }\n return rewriteMatch(matched, args, dialect);\n });\n return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;\n}\n","/**\n * What `ChatPresenter` needs to know about one platform: how to rewrite the text, and which\n * `format` to declare on the message (B-019 FR-001, FR-002).\n *\n * `toDialect` alone is not enough, and composing it with the presenter's defaults proved it:\n * `ChatPresenter` declares `markdown` unless told otherwise, and `toDialect` passes a platform it\n * was not taught through unchanged. So matrix and email put `**bold**` on the wire as characters\n * (matrix drops `markdown` with a warning, email escapes it into `<pre>`), and telegram and slack\n * were handed a bold spelled for a dialect whose bold is a single asterisk. The text rewrite and\n * the format flag have to be chosen together, per platform, by the package that knows what each\n * adapter does with `format` — this one.\n *\n * Pure data and pure functions: no I/O, and the same input always gives the same output.\n * `@theokit/gateway` still does not depend on `@theokit/presenter`; `ChannelRendering` matches\n * the presenter's `translate` and `format` options structurally.\n */\n\nimport type { PlatformName } from \"../types/message-event.js\";\nimport { DIALECTS, type Dialect, rewriteMarkers } from \"./dialect.js\";\n\n/**\n * The pair a consumer spreads into `ChatPresenter`'s options for one platform.\n *\n * @public\n */\nexport interface ChannelRendering {\n /** The rendering hint the adapter receives as `OutboundMessage.format`. */\n readonly format: \"plain\" | \"markdown\";\n /** Rewrites the assembled answer for the platform. Pure and deterministic. */\n readonly translate: (text: string) => string;\n}\n\n/**\n * Slack's mrkdwn: emphasis is a single character, `*bold*`, `_italic_`, `~strike~`, and inline\n * code keeps its backtick (https://api.slack.com/reference/surfaces/formatting).\n */\nconst SLACK: Dialect = { bold: \"*\", italic: \"_\", strike: \"~\", code: \"`\" };\n\n/** No marker survives; the content they wrapped does. */\nconst STRIP: Dialect = {};\n\nconst identity = (text: string): string => text;\n\nconst translateWith =\n (dialect: Dialect) =>\n (text: string): string =>\n rewriteMarkers(text, dialect);\n\n/**\n * One row per platform. A `Record` over `PlatformName`, so a platform added to the union without\n * a row here is a compile error rather than a silent fallback.\n *\n * - whatsapp: inline single-character emphasis in the text, and `plain`, because its adapter\n * carries no formatting flag on a text message.\n * - slack: the same emphasis, declared `markdown` so the adapter sets `mrkdwn`.\n * - discord, mattermost, teams: markdown is what they render, so the text passes through.\n * - signal: `markdown`, passed through; its adapter turns the markers into Signal's `textStyle`\n * ranges, so the text it sends carries no marker characters.\n * - line, sms: no rich text at all; the existing `toDialect` rows drop the markers.\n * - imessage: markers dropped and `plain`. `imsg` sends the text as typed, and Messages shows a\n * marker character as itself.\n * - google_chat: markers dropped and `plain`. Chat's own markup is close to, but not, markdown, and\n * how it renders a reply is unmeasured until a live run (plan Q3).\n * - nextcloud_talk: `markdown`, passed through. Talk renders the markdown a bot sends (the Q6\n * probe's inbound bodies carry `mediaType: \"text/markdown\"`).\n * - irc: markers dropped and `plain`. IRC has no markdown; its own formatting is control bytes,\n * and a marker character reaches the channel as itself.\n * - telegram: markers dropped and `plain`. Its adapter maps `markdown` to legacy Markdown, which\n * refuses a reply with an unpaired `_` or `*` and loses it with no retry; losing emphasis is the\n * cheaper failure (plan ADR D3).\n * - matrix, email: markers dropped and `plain`. Neither renders `markdown` (see the module comment),\n * and producing HTML would need a markdown renderer this package does not have.\n * - buzz: markers dropped and `plain`; this adapter does not claim Buzz renders markdown.\n * - clickclack: markers dropped and `plain`; this adapter does not claim ClickClack renders markdown.\n * - zalo_personal, zalo, wechat, wecom, yuanbao, raft, x, qq: markers dropped and `plain`. Zalo shows a marker character as itself.\n * - nostr, feishu_lark, synology_chat, tlon_urbit, twitch: markers dropped and `plain`. Nostr and\n * Twitch chat show a marker character as itself; Lark posts and Tlon inline styles are richer\n * formats this package does not map yet, so emphasis is lost rather than spelled (plan ADR D3).\n */\nconst RENDERINGS: Readonly<Record<PlatformName, ChannelRendering>> = {\n whatsapp: { format: \"plain\", translate: translateWith(DIALECTS.whatsapp) },\n slack: { format: \"markdown\", translate: translateWith(SLACK) },\n discord: { format: \"markdown\", translate: identity },\n mattermost: { format: \"markdown\", translate: identity },\n teams: { format: \"markdown\", translate: identity },\n signal: { format: \"markdown\", translate: identity },\n line: { format: \"plain\", translate: translateWith(DIALECTS.line) },\n sms: { format: \"plain\", translate: translateWith(DIALECTS.sms) },\n telegram: { format: \"plain\", translate: translateWith(STRIP) },\n matrix: { format: \"plain\", translate: translateWith(STRIP) },\n email: { format: \"plain\", translate: translateWith(STRIP) },\n imessage: { format: \"plain\", translate: translateWith(STRIP) },\n google_chat: { format: \"plain\", translate: translateWith(STRIP) },\n irc: { format: \"plain\", translate: translateWith(STRIP) },\n nextcloud_talk: { format: \"markdown\", translate: identity },\n nostr: { format: \"plain\", translate: translateWith(STRIP) },\n feishu_lark: { format: \"plain\", translate: translateWith(STRIP) },\n synology_chat: { format: \"plain\", translate: translateWith(STRIP) },\n tlon_urbit: { format: \"plain\", translate: translateWith(STRIP) },\n twitch: { format: \"plain\", translate: translateWith(STRIP) },\n buzz: { format: \"plain\", translate: translateWith(STRIP) },\n clickclack: { format: \"plain\", translate: translateWith(STRIP) },\n zalo_personal: { format: \"plain\", translate: translateWith(STRIP) },\n zalo: { format: \"plain\", translate: translateWith(STRIP) },\n wechat: { format: \"plain\", translate: translateWith(STRIP) },\n wecom: { format: \"plain\", translate: translateWith(STRIP) },\n yuanbao: { format: \"plain\", translate: translateWith(STRIP) },\n qq: { format: \"plain\", translate: translateWith(STRIP) },\n x: { format: \"plain\", translate: translateWith(STRIP) },\n raft: { format: \"plain\", translate: translateWith(STRIP) },\n};\n\n/**\n * The rendering `ChatPresenter` needs for `platform`.\n *\n * Only the four inline markers `toDialect` knows are rewritten: bold, italic, strikethrough and\n * inline code. Headings, links, lists and block quotes pass through on every platform, and fenced\n * code is not handled yet (the inline-code rule rewrites a fence's backticks).\n *\n * @param platform - the destination, typically `event.platform` of the inbound message\n * @returns the `{ translate, format }` pair for that platform\n * @throws RangeError when `platform` is not one of the platforms this package knows. Answering with\n * nothing would let the presenter fall back to identity and `markdown`, which is the defect this\n * function exists to remove.\n * @public\n */\nexport function channelRendering(platform: PlatformName): ChannelRendering {\n const rendering: ChannelRendering | undefined = Object.hasOwn(RENDERINGS, platform)\n ? RENDERINGS[platform]\n : undefined;\n if (rendering === undefined) {\n throw new RangeError(\n `channelRendering: unknown platform \"${String(platform)}\"; expected one of ${Object.keys(RENDERINGS).join(\", \")}`,\n );\n }\n return rendering;\n}\n","/**\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 { channelRendering } from \"../text/channel-rendering.js\";\nimport type { SeenIds } from \"../text/seen-ids.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/**\n * An image an outbound message carries: its bytes and their media type (B-674).\n *\n * The bytes travel by reference: the runner does not copy them on the way to the adapter. The\n * caller must not change `data` or the list until the send's promise settles: an adapter that\n * sends several attachments reads each one only when its turn comes.\n */\ninterface OutboundImageAttachment {\n readonly kind: \"image\";\n /** The media type of `data`, such as `image/png`. */\n readonly mediaType: string;\n readonly data: Uint8Array;\n /** A file name the platform may show; optional. */\n readonly filename?: string;\n}\n\n/** An audio clip an outbound message carries, such as a spoken reply (B-715). Same rules as an image. */\ninterface OutboundAudioAttachment {\n readonly kind: \"audio\";\n /** The media type of `data`, such as `audio/ogg`. */\n readonly mediaType: string;\n readonly data: Uint8Array;\n /** A file name the platform may show; optional. */\n readonly filename?: string;\n}\n\n/** An attachment an outbound message carries, told apart by `kind`. */\nexport type OutboundAttachment = OutboundImageAttachment | OutboundAudioAttachment;\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 * Images to send with the text. An adapter whose {@link BasePlatformAdapter.supportsAttachments}\n * is `false` refuses a non-empty list with `attachments_unsupported`; it never drops it.\n */\n readonly attachments?: ReadonlyArray<OutboundAttachment>;\n}\n\n/**\n * Shared failure codes for {@link SendResult}.\n *\n * - `empty_text`, `not_connected`, `invalid_channel`, `attachments_unsupported`: core refused the send.\n * - `rate_limit`: the platform throttled the send; see `retryAfterMs`.\n * - `permission_denied`: the credential is valid but may not post here (HTTP 403).\n * - `auth_failed`: the credential was rejected (HTTP 401).\n * - `timeout`: the platform or the request timed out (HTTP 408).\n * - `server_error`: the platform failed (HTTP 5xx).\n * - `network_error`: the request never got an answer.\n * - `platform_error`: any other platform refusal.\n */\nexport type SendErrorCode =\n | \"empty_text\"\n | \"not_connected\"\n | \"invalid_channel\"\n | \"attachments_unsupported\"\n | \"rate_limit\"\n | \"permission_denied\"\n | \"auth_failed\"\n | \"timeout\"\n | \"server_error\"\n | \"network_error\"\n | \"platform_error\";\n\n/** The error of a failed {@link SendResult}. */\nexport interface SendError {\n /** A known code, or a platform-specific one an adapter has not mapped yet. */\n readonly code: SendErrorCode | (string & {});\n readonly message: string;\n /** Set when the platform said how long to wait. */\n readonly retryAfterMs?: number;\n /** The platform's own code, kept for logs. */\n readonly platformCode?: string;\n}\n\n/**\n * Send result — adapters return this instead of throwing on platform errors.\n * `error.code` is a {@link SendErrorCode} or a platform-specific string.\n */\nexport interface SendResult {\n readonly ok: boolean;\n readonly messageId?: string;\n readonly error?: SendError;\n}\n\n/** The facts about an adapter that an app picks its rendering from. */\nexport interface AdapterCapabilities {\n readonly edit: boolean;\n /** The attachment kinds the adapter sends; `[]` when none. */\n readonly attachments: ReadonlyArray<OutboundAttachment[\"kind\"]>;\n readonly typing: boolean;\n readonly reactions: boolean;\n readonly threads: boolean;\n /** Longest text one message holds; `undefined` when the adapter does not know. */\n readonly maxMessageChars?: number;\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; `editMessage` refuses\n * with `edit_unsupported` 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 and no attachments returns `{ ok: false, code: \"empty_text\" }`.\n * An adapter that refuses attachments answers `attachments_unsupported` first, and one that\n * sends them (Telegram) accepts empty text with an image.\n * - `supportsEdit` says whether the adapter has an edit call. It is `false` unless the adapter\n * overrides it, and it MUST NOT change with `connect()`. `true` does not promise that every\n * edit is accepted: an adapter whose injected client lacks the edit call (Matrix) still answers\n * `edit_unsupported`, which a caller handles like any other refusal.\n * - `editMessage` returns a `SendResult` and never throws on platform errors. The default refuses\n * with `edit_unsupported` and makes no platform call.\n * - `supportsAttachments` says whether `sendMessage` can send `out.attachments`. It is `false`\n * unless the adapter overrides it, and it MUST NOT change with `connect()`. An adapter that\n * does not support them refuses a non-empty list with `attachments_unsupported` and makes no\n * platform call; an edit carrying an attachment is refused the same way.\n * - Edits are not ordered by the adapter. Two edits of one message id in flight at once reach the\n * platform in either order, so a caller awaits each edit before the next, or keeps one in flight\n * and coalesces to the latest 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 every\n * adapter 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 /** The handler {@link subscribe} holds; `undefined` while nobody is subscribed. */\n protected subscribedHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n\n /** The body of {@link onInbound}: replace the handler, and unsubscribe only if it is still the one held. */\n protected subscribe(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n this.subscribedHandler = handler;\n return () => {\n if (this.subscribedHandler === handler) this.subscribedHandler = undefined;\n };\n }\n\n /** The body of {@link deliver} for an adapter that subscribed through {@link subscribe}. */\n protected deliverInbound(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.subscribedHandler, event);\n }\n\n /**\n * Dispatch a webhook event once: `duplicate` when `seen` holds its id, `no_handler` when nobody\n * subscribed (the id is then NOT remembered, so a redelivery is handled), otherwise remember the\n * id and run the handler. A handler's throw is also logged under `label`.\n */\n protected async dispatchOnce(\n seen: SeenIds,\n event: GatewayMessageEvent,\n label: string,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\" | \"duplicate\"> {\n if (seen.has(event.id)) return \"duplicate\";\n if (this.subscribedHandler === undefined) return \"no_handler\";\n seen.add(event.id);\n const outcome = await this.runHandler(this.subscribedHandler, event);\n if (outcome === \"handler_threw\") process.stderr.write(`[${label}] handler threw\\n`);\n return outcome;\n }\n\n /** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */\n protected outboundText(out: OutboundMessage): string {\n return out.format === \"markdown\"\n ? channelRendering(this.platform).translate(out.text)\n : out.text;\n }\n\n /**\n * The local checks every text-only `sendMessage` makes before a request, in this order:\n * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.\n * Returns the refusal, or `undefined` when the message may be sent.\n */\n protected refuseUnsendable(\n out: OutboundMessage,\n check: {\n readonly className: string;\n readonly connected: boolean;\n readonly channel?: { readonly valid: (id: string) => boolean; readonly message: string };\n },\n ): SendResult | undefined {\n const refuse = (code: string, message: string): SendResult => ({\n ok: false,\n error: { code, message },\n });\n if (out.text.length === 0) return refuse(\"empty_text\", \"outbound text is empty\");\n if (!check.connected) {\n return refuse(\"not_connected\", `${check.className}.connect() has not succeeded`);\n }\n if (check.channel !== undefined && !check.channel.valid(out.channel.id)) {\n return refuse(\"invalid_channel\", check.channel.message);\n }\n return undefined;\n }\n\n /**\n * Whether {@link editMessage} can replace the text of a message this adapter sent.\n *\n * Read it before starting a preview: on `false`, send the final text instead. An adapter sets\n * it at construction and MUST NOT change it with `connect()`. Annotated as `boolean` so that an\n * edit-capable adapter can override it with `true`.\n */\n readonly supportsEdit: boolean = false;\n\n /**\n * Whether {@link sendMessage} can send the images of `out.attachments` (B-674).\n *\n * Read it before attaching: on `false`, the adapter refuses a non-empty list with\n * `attachments_unsupported`. Set at construction, never changed by `connect()`. Annotated as\n * `boolean` so that an adapter that sends images can override it with `true`.\n */\n readonly supportsAttachments: boolean = false;\n\n /**\n * The attachment kinds {@link sendMessage} can send. `undefined` means \"not declared\": the\n * `capabilities` getter then reports `[\"image\"]` when `supportsAttachments` is `true`, else `[]`.\n */\n protected readonly attachmentKinds: ReadonlyArray<OutboundAttachment[\"kind\"]> | undefined =\n undefined;\n\n /**\n * What this adapter can do, for an app that renders differently per channel.\n *\n * Derived from the members above and from which lifecycle methods the subclass overrides; an\n * adapter overrides the getter only for what derivation cannot know. Read it at call time.\n */\n get capabilities(): AdapterCapabilities {\n const proto = BasePlatformAdapter.prototype;\n return {\n edit: this.supportsEdit,\n attachments: this.attachmentKinds ?? (this.supportsAttachments ? [\"image\"] : []),\n typing: this.startTyping !== proto.startTyping,\n reactions: this.react !== proto.react,\n threads: false,\n };\n }\n\n /**\n * Replace the text of a message this adapter sent, keeping its id.\n *\n * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never\n * throws on platform errors. An edit-capable adapter applies, with no request, the same local\n * checks its `sendMessage` applies (such as `empty_text`, and `not_connected` where the send\n * checks the connection), plus `invalid_message_id`, and `edit_too_long` where the adapter\n * splits text: an edit that would need more than one platform message is refused, never split.\n *\n * Default: refuses with `edit_unsupported`, makes no platform call, and checks nothing else\n * first, so capability is answered before input.\n */\n async editMessage(_messageId: string, _out: OutboundMessage): Promise<SendResult> {\n return {\n ok: false,\n error: {\n code: \"edit_unsupported\",\n message: `${this.platform} adapter cannot edit a sent message`,\n },\n };\n }\n\n /**\n * React to an inbound message with an emoji (for example 👀 as an acknowledgement).\n *\n * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never\n * throws on platform errors. `channelId` is the channel the message is in and `messageId` the\n * id the inbound event carried.\n *\n * Default: resolves `{ ok: false, error: { code: \"react_unsupported\" } }` and makes no\n * platform call.\n */\n async react(_channelId: string, _messageId: string, _emoji: string): Promise<SendResult> {\n return {\n ok: false,\n error: {\n code: \"react_unsupported\",\n message: `${this.platform} adapter cannot react to a message`,\n },\n };\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","import type { SendResult } from \"./base.js\";\n\nfunction parseRetryAfter(value: string | null | undefined, now: number): number | undefined {\n if (value == null) return undefined;\n const v = value.trim();\n if (/^\\d+$/.test(v)) return Number(v) * 1000;\n // An HTTP date always has letters; this rejects \"-1\" and other numeric oddities.\n if (!/[A-Za-z]/.test(v)) return undefined;\n const at = Date.parse(v);\n if (Number.isNaN(at)) return undefined;\n return Math.max(0, at - now);\n}\n\nconst STATUS_CODES: Readonly<Record<number, string>> = {\n 429: \"rate_limit\",\n 401: \"auth_failed\",\n 403: \"permission_denied\",\n 408: \"timeout\",\n};\n\nfunction codeForStatus(status: number): string {\n return STATUS_CODES[status] ?? (status >= 500 ? \"server_error\" : \"platform_error\");\n}\n\n/**\n * Map an HTTP status to a failed SendResult: 429 -> rate_limit (retryAfterMs from a Retry-After\n * value in seconds or an HTTP date), 401 -> auth_failed, 403 -> permission_denied,\n * 408 -> timeout, 5xx -> server_error, other -> platform_error.\n */\nexport function sendErrorFromHttp(\n status: number,\n message: string,\n options?: { retryAfter?: string | null; platformCode?: string; now?: () => number },\n): SendResult {\n if (!Number.isInteger(status) || status < 100 || status > 599) {\n throw new RangeError(`status must be an integer in 100..599, got ${String(status)}`);\n }\n const code = codeForStatus(status);\n const retryAfterMs =\n status === 429 ? parseRetryAfter(options?.retryAfter, (options?.now ?? Date.now)()) : undefined;\n return {\n ok: false,\n error: {\n code,\n message,\n ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),\n ...(options?.platformCode !== undefined ? { platformCode: options.platformCode } : {}),\n },\n };\n}\n","/**\n * `createTokenCache` — holds one expiring access token and shares a single refresh between every\n * concurrent caller.\n *\n * @public\n */\n\n/** A token as the platform reported it. @public */\nexport interface FetchedToken {\n readonly value: string;\n /** Lifetime in seconds as the platform reported it; `defaultTtlS` when absent or not positive. */\n readonly expiresInS?: number;\n}\n\n/** Options of {@link createTokenCache}. @public */\nexport interface TokenCacheOptions {\n /** Fetch a fresh token. Receives the signal of the caller that started the fetch. */\n readonly fetchToken: (signal?: AbortSignal) => Promise<FetchedToken>;\n /** Refresh this long before expiry. Default 60_000. */\n readonly marginMs?: number;\n /** Default 7200. */\n readonly defaultTtlS?: number;\n readonly now?: () => number;\n}\n\n/** A cached expiring token. @public */\nexport interface TokenCache {\n /**\n * The cached token, or one fetch shared by every concurrent caller. `force` skips the cache\n * (but still joins a fetch already in flight). The signal of the caller that starts a fetch\n * governs it; later callers' signals do not cancel their wait.\n */\n get(options?: { force?: boolean; signal?: AbortSignal }): Promise<string>;\n /** Forget the cached token (after a 401, for example). */\n clear(): void;\n}\n\n/** Build a {@link TokenCache}. A failed fetch rejects every waiting caller and is not cached. @public */\nexport function createTokenCache(options: TokenCacheOptions): TokenCache {\n const marginMs = options.marginMs ?? 60_000;\n const defaultTtlS = options.defaultTtlS ?? 7200;\n const now = options.now ?? Date.now;\n let cached: { value: string; expiresAt: number } | undefined;\n let pending: Promise<string> | undefined;\n // Bumped by clear(), so a fetch started before it cannot repopulate the cache.\n let generation = 0;\n\n const refresh = (signal: AbortSignal | undefined): Promise<string> => {\n const started = generation;\n const run = (async () => {\n const fetched = await options.fetchToken(signal);\n const ttl =\n fetched.expiresInS !== undefined && fetched.expiresInS > 0\n ? fetched.expiresInS\n : defaultTtlS;\n if (started === generation) {\n cached = { value: fetched.value, expiresAt: now() + ttl * 1000 };\n }\n return fetched.value;\n })();\n const tracked = run.finally(() => {\n if (pending === tracked) pending = undefined;\n });\n pending = tracked;\n return tracked;\n };\n\n return {\n get(opts) {\n if (opts?.force !== true && cached !== undefined && cached.expiresAt - marginMs > now()) {\n return Promise.resolve(cached.value);\n }\n return pending ?? refresh(opts?.signal);\n },\n clear() {\n generation += 1;\n cached = undefined;\n pending = undefined;\n },\n };\n}\n","/**\n * A bounded set of ids, oldest evicted first, so a long-running process remembers what it delivered\n * without growing for ever (NFR-003).\n */\n\nconst DEFAULT_LIMIT = 1_000;\n\n/**\n * The ids an adapter has already delivered, at most `limit` of them.\n */\nexport class SeenIds {\n private readonly ids = new Set<string>();\n\n /** @param limit the most ids held at once; the oldest is forgotten when one more arrives */\n constructor(private readonly limit: number = DEFAULT_LIMIT) {}\n\n /**\n * Record `id`.\n *\n * @returns `true` when the id was new, `false` when it was already held\n */\n add(id: string): boolean {\n if (this.ids.has(id)) return false;\n this.ids.add(id);\n if (this.ids.size > this.limit) {\n const oldest = this.ids.values().next().value;\n if (oldest !== undefined) this.ids.delete(oldest);\n }\n return true;\n }\n\n /** Whether `id` is held. */\n has(id: string): boolean {\n return this.ids.has(id);\n }\n\n /** How many ids are held. */\n get size(): number {\n return this.ids.size;\n }\n}\n","/**\n * Read the flat XML the Tencent webhook platforms (WeChat, WeCom) push:\n * `<xml><Tag><![CDATA[v]]></Tag>…</xml>`. The messages these adapters take have no nesting, so a\n * tag scan is enough and no XML library is needed.\n *\n * @public\n */\nexport function parseFlatXml(xml: string): Record<string, string> {\n const out: Record<string, string> = {};\n const tag = /<([A-Za-z][A-Za-z0-9]*)>(?:<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>|([^<]*))<\\/\\1>/g;\n for (const m of xml.matchAll(tag)) {\n const name = m[1];\n if (name !== undefined && name !== \"xml\") out[name] = m[2] ?? decodeEntities(m[3] ?? \"\");\n }\n return out;\n}\n\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&amp;/g, \"&\");\n}\n","/**\n * `WeixinAdapterBase` — the connect / token / send / dispatch flow that the WeChat and WeCom\n * adapters share. A subclass supplies the platform's endpoints, its signature check and its event\n * shape; this class owns everything else.\n *\n * @public\n */\n\nimport { createTokenCache, type FetchedToken, type TokenCache } from \"../auth/token-cache.js\";\nimport { SeenIds } from \"../text/seen-ids.js\";\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"./base.js\";\nimport { parseFlatXml } from \"./weixin-xml.js\";\n\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n/** A `fetch`-shaped function; the adapter's only network seam. @public */\nexport type WeixinFetch = (\n url: string,\n init: { method: string; headers: Record<string, string>; body?: string },\n) => Promise<{ status: number; text(): Promise<string> }>;\n\n/**\n * What a webhook route answers. `body` is the text to write back; anything but 200 makes the\n * platform retry.\n *\n * @public\n */\nexport type WeixinWebhookAnswer = {\n readonly status: 200 | 400 | 401 | 503;\n readonly body: string;\n readonly reason: string;\n};\n\n/** What a subclass tells the base about its platform. @public */\nexport interface WeixinAdapterConfig {\n /** Log prefix, e.g. `gateway-wechat`. */\n readonly label: string;\n /** Class name used in the `not_connected` message, e.g. `WeChatAdapter`. */\n readonly className: string;\n /** Brand used in messages, e.g. `WeChat`. */\n readonly brand: string;\n /** What `channel.id` must be, e.g. `a WeChat OpenID`. */\n readonly userNoun: string;\n /** API base used when `apiBase` is not set. */\n readonly defaultBase: string;\n readonly apiBase?: string;\n readonly fetch?: WeixinFetch;\n}\n\n/** One send call: a path (with its access token) and a JSON payload. @public */\nexport interface WeixinSendRequest {\n readonly path: string;\n readonly payload: unknown;\n}\n\ninterface ApiBody {\n errcode?: number;\n errmsg?: string;\n access_token?: string;\n expires_in?: number;\n}\n\nconst defaultFetch: WeixinFetch = async (url, init) => {\n const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });\n return { status: res.status, text: () => res.text() };\n};\n\nfunction weixinMessageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nfunction weixinAck(reason: string): WeixinWebhookAnswer {\n return { status: 200, body: \"success\", reason };\n}\n\n/**\n * Shared base of the WeChat and WeCom adapters.\n *\n * @public\n */\nexport abstract class WeixinAdapterBase extends BasePlatformAdapter {\n private readonly cfg: WeixinAdapterConfig;\n private readonly doFetch: WeixinFetch;\n private connected = false;\n private readonly tokens: TokenCache;\n private readonly seen = new SeenIds();\n\n constructor(cfg: WeixinAdapterConfig) {\n super();\n this.cfg = cfg;\n this.doFetch = cfg.fetch ?? defaultFetch;\n this.tokens = createTokenCache({ fetchToken: () => this.requestToken() });\n }\n\n /** Path and query of the access-token request. */\n protected abstract tokenPath(): string;\n /** The send call for one part of a reply. */\n protected abstract sendRequest(token: string, userId: string, content: string): WeixinSendRequest;\n /** Cut a reply into parts the platform accepts. */\n protected abstract split(text: string): string[];\n /** The event for a text message, `\"skip\"` for another type, `undefined` for a text with gaps. */\n protected abstract toEvent(\n fields: Record<string, string>,\n ): GatewayMessageEvent | \"skip\" | undefined;\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await this.token(true);\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[${this.cfg.label}] connect failed: ${weixinMessageOf(err)}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.tokens.clear();\n }\n\n /** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */\n protected async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (!this.connected) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: `${this.cfg.className}.connect() has not succeeded`,\n },\n };\n }\n if (out.channel.id === \"\") {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id must be ${this.cfg.userNoun}` },\n };\n }\n return this.sendParts(out);\n }\n\n private async sendParts(out: OutboundMessage): Promise<SendResult> {\n const failed = `${this.platform}_send_failed`;\n try {\n for (const content of this.split(this.outboundText(out))) {\n const token = await this.token(false);\n const req = this.sendRequest(token, out.channel.id, content);\n const body = await this.call(\"POST\", req.path, req.payload);\n if (body.errcode !== 0) {\n return {\n ok: false,\n error: {\n code: failed,\n message: `${this.cfg.brand} error ${String(body.errcode)}: ${String(body.errmsg)}`,\n },\n };\n }\n }\n } catch (err) {\n return { ok: false, error: { code: failed, message: weixinMessageOf(err) } };\n }\n // The send answer carries no message id a reply needs.\n return { ok: true, messageId: \"\" };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n return this.subscribe(handler);\n }\n\n /** Deliver an event that arrived out of band, through `runHandler`. */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.deliverInbound(event);\n }\n\n /** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */\n protected async handleMessage(xml: string): Promise<WeixinWebhookAnswer> {\n const event = this.toEvent(parseFlatXml(xml));\n if (event === \"skip\") return weixinAck(\"not a text message\");\n if (event === undefined) return { status: 400, body: \"\", reason: \"incomplete\" };\n const outcome = await this.dispatchOnce(this.seen, event, this.cfg.label);\n if (outcome === \"no_handler\") return { status: 503, body: \"\", reason: \"no handler subscribed\" };\n return weixinAck(outcome);\n }\n\n private token(force: boolean): Promise<string> {\n return this.tokens.get({ force });\n }\n\n private async requestToken(): Promise<FetchedToken> {\n const body = await this.call(\"GET\", this.tokenPath());\n if (body.errcode !== undefined && body.errcode !== 0) {\n throw new Error(`token answered error ${String(body.errcode)}: ${String(body.errmsg)}`);\n }\n if (!body.access_token) throw new Error(\"token answer has no access_token\");\n return {\n value: body.access_token,\n ...(body.expires_in === undefined ? {} : { expiresInS: body.expires_in }),\n };\n }\n\n private async call(method: \"GET\" | \"POST\", path: string, payload?: unknown): Promise<ApiBody> {\n const res = await this.doFetch((this.cfg.apiBase ?? this.cfg.defaultBase) + path, {\n method,\n headers: { \"Content-Type\": \"application/json\" },\n ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),\n });\n const text = await res.text();\n try {\n return JSON.parse(text) as ApiBody;\n } catch {\n throw new Error(`${this.cfg.brand} answered HTTP ${res.status} with a non-JSON body`);\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 * `channelConfigReaders` — the config readers every channel's `create` needs, written once.\n *\n * Each channel package used to carry its own copy of `invalid`, `readString`, `requiredString`\n * and friends; only the error prefix differed. The readers throw a configuration error coded\n * `invalid_config` with the message `${prefix}: config.${key} must be ${expected}`.\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\n\n/** A channel's config object, as `create` receives it. */\nexport type ChannelConfigInput = Readonly<Record<string, unknown>>;\n\n/** The readers bound to one package prefix. */\nexport interface ChannelConfigReaders {\n /** Builds (does not throw) the `invalid_config` error for `key`. */\n invalid(key: string, expected: string): GatewayConfigurationError;\n /** `undefined`, `null` and `\"\"` are absent. */\n isAbsent(value: unknown): boolean;\n /** An optional string; absent gives `undefined`, a non-string throws. */\n readString(config: ChannelConfigInput, key: string): string | undefined;\n /** A required string; absent, empty or a non-string throws. */\n requiredString(config: ChannelConfigInput, key: string): string;\n /** An optional boolean; absent gives `undefined`, a non-boolean throws. */\n readBoolean(config: ChannelConfigInput, key: string): boolean | undefined;\n /** An optional number: a finite number or a digit string; anything else throws. */\n readNumber(config: ChannelConfigInput, key: string): number | undefined;\n /** An optional boolean as a boolean or the string `\"true\"`/`\"false\"`; anything else throws. */\n readBooleanString(config: ChannelConfigInput, key: string): boolean | undefined;\n /** An optional list of strings: an array or a comma-separated string (items trimmed). */\n readList(config: ChannelConfigInput, key: string): string[] | undefined;\n /**\n * An optional function; absent gives `undefined`, a non-function throws. Only callability is\n * checked: the caller names the signature `T` and is responsible for it.\n */\n readFunction<T extends (...args: never[]) => unknown>(\n config: ChannelConfigInput,\n key: string,\n ): T | undefined;\n}\n\n/**\n * Returns the config readers for a package.\n *\n * @param prefix Package prefix in every message, e.g. `\"gateway-line\"`.\n * @param createError Builds the error to throw; defaults to `GatewayConfigurationError`. Pass a\n * package's own subclass to keep its `instanceof` contract.\n */\nexport function channelConfigReaders(\n prefix: string,\n createError: (options: {\n readonly code: string;\n readonly message: string;\n readonly detail: string;\n }) => GatewayConfigurationError = (options) => new GatewayConfigurationError(prefix, options),\n): ChannelConfigReaders {\n const invalid = (key: string, expected: string): GatewayConfigurationError =>\n createError({\n code: \"invalid_config\",\n message: `${prefix}: config.${key} must be ${expected}`,\n detail: key,\n });\n const isAbsent = (value: unknown): boolean =>\n value === undefined || value === null || value === \"\";\n const readString = (config: ChannelConfigInput, key: string): string | undefined => {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value !== \"string\") throw invalid(key, \"a string\");\n return value;\n };\n return {\n invalid,\n isAbsent,\n readString,\n requiredString(config, key) {\n const value = config[key];\n if (typeof value !== \"string\" || value === \"\") throw invalid(key, \"a non-empty string\");\n return value;\n },\n readBoolean(config, key) {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value !== \"boolean\") throw invalid(key, \"a boolean\");\n return value;\n },\n readNumber(config, key) {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && /^\\d+$/.test(value)) return Number(value);\n throw invalid(key, \"a number or a digit string\");\n },\n readBooleanString(config, key) {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value === \"boolean\") return value;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n throw invalid(key, 'a boolean or \"true\"/\"false\"');\n },\n readList(config, key) {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value === \"string\") {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item !== \"\");\n }\n if (!Array.isArray(value) || !value.every((item) => typeof item === \"string\")) {\n throw invalid(key, \"an array of strings or a comma-separated string\");\n }\n return value;\n },\n readFunction<T extends (...args: never[]) => unknown>(\n config: ChannelConfigInput,\n key: string,\n ): T | undefined {\n const value = config[key];\n if (isAbsent(value)) return undefined;\n if (typeof value !== \"function\") throw invalid(key, \"a function\");\n return value as T;\n },\n };\n}\n","/**\n * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).\n *\n * A platform package exports one static descriptor: the config fields its channel needs, how to\n * build its adapter from them, and, for a channel that receives webhooks, how to verify and ingest\n * a request. An app then wires every channel with the same loop (`createChannels`) instead of one\n * branch per platform. The core only reads these shapes; it never names a platform.\n *\n * @public\n */\n\nimport type { BasePlatformAdapter } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** One configuration field a channel reads. */\nexport interface ChannelConfigField {\n /** The key `create` reads from its config object. */\n readonly key: string;\n /** A required field that is absent, `null` or `\"\"` rejects the channel before `create` runs. */\n readonly required: boolean;\n /** The value is a credential: never log it, and keep it out of anything shown to a user. */\n readonly secret: boolean;\n /** What the field is, for a human configuring the channel. */\n readonly description: string;\n /** Variable name without the app prefix, e.g. `\"TELEGRAM_TOKEN\"`. Read by `configFromEnv`. */\n readonly env?: string;\n}\n\n/** A webhook request as the app's HTTP layer received it, before anything parsed the body. */\nexport interface WebhookRequest {\n /** The exact request bytes as text; signatures are computed over them. */\n readonly rawBody: string;\n /** Request headers. Descriptors look a header up without regard to case. */\n readonly headers: Readonly<Record<string, string | undefined>>;\n /** The HTTP method. Always set by `createWebhookHandler`; optional so existing callers compile. */\n readonly method?: string;\n /** The full request URL, query included. Always set by `createWebhookHandler`. */\n readonly url?: string;\n}\n\n/** The answer a channel's `handle` gives for one webhook request. */\nexport interface WebhookAnswer {\n /** The HTTP status. */\n readonly status: number;\n /** The response body, when the platform expects one. */\n readonly body?: string;\n /** The response `content-type`. */\n readonly contentType?: string;\n}\n\n/**\n * What `ingest` did with a verified payload: `\"delivered\"` dispatched it, `\"malformed\"` refused it\n * without dispatching, and `\"no_handler\"` dispatched nothing because the payload holds a message\n * for the handler and none is subscribed (before the runner starts, after it stops, or for an\n * adapter whose connect failed under `connectFailure: \"isolate\"`). Answer only `\"delivered\"` with\n * a success status, so a platform that redelivers can send the rest again.\n */\nexport type IngestResult = \"delivered\" | \"malformed\" | \"no_handler\";\n\n/**\n * The webhook half of a channel: verify a request, then hand its payload to the adapter.\n *\n * `verify` and `ingest` are declared as methods on purpose. Method parameters are bivariant, which\n * is what lets a descriptor typed for its own adapter class sit in a list of\n * `ChannelDescriptor<BasePlatformAdapter>`; written as function-typed properties, that assignment\n * would fail under `strictFunctionTypes`.\n */\nexport interface ChannelWebhook<TAdapter extends BasePlatformAdapter> {\n /** `true` when the request carries a valid signature for this adapter's credentials. */\n verify(adapter: TAdapter, request: WebhookRequest): boolean | Promise<boolean>;\n /** Dispatch a parsed, verified payload, or report it malformed without dispatching. */\n ingest(adapter: TAdapter, payload: unknown): Promise<IngestResult>;\n /** Methods the route takes. Default `[\"POST\"]`. */\n readonly methods?: readonly string[];\n /**\n * Called with the method, URL and headers before the body is read. An answer refuses the request\n * there (an unreadable or oversized body never gets a 400 or 413); `undefined` lets it go on.\n */\n precheck?(adapter: TAdapter, request: Omit<WebhookRequest, \"rawBody\">): WebhookAnswer | undefined;\n /** Full control of one request. When absent, the handler runs verify, JSON.parse and ingest. */\n handle?(adapter: TAdapter, request: WebhookRequest): Promise<WebhookAnswer>;\n}\n\n/**\n * Whether a channel's `sender.id` is proven by the platform. An email From header or an SMS caller\n * id is written by the sender (CWE-290), so such a channel declares why it cannot be trusted.\n *\n * @public\n */\nexport type SenderIdentity =\n | \"authenticated\"\n /** Why the sender id can be forged, for error messages. */\n | { readonly unauthenticated: string };\n\ninterface ChannelDescriptorBase<TAdapter extends BasePlatformAdapter> {\n /** The platform the built adapter reports as its `platform`. */\n readonly platform: PlatformName;\n /** Every field `create` reads. */\n readonly config: ReadonlyArray<ChannelConfigField>;\n /**\n * Build the adapter. Throws a `GatewayConfigurationError` (or a subclass) for a value it refuses,\n * which `createChannels` reports as a rejected channel; it performs no network call.\n */\n create(config: Readonly<Record<string, unknown>>): TAdapter;\n /**\n * Whether `sender.id` is authenticated. Absent means unknown and is treated as not\n * authenticated (fail closed); it is optional only so descriptors in other packages keep compiling.\n */\n readonly senderIdentity?: SenderIdentity;\n /**\n * Alternative config shapes for the same platform (for example WhatsApp cloud versus baileys),\n * chosen by name with `selectVariant`. Each variant reports the parent's `platform`.\n */\n readonly variants?: Readonly<Record<string, ChannelDescriptor>>;\n}\n\n/**\n * A channel described as data. A `socket` channel opens its own connection to the platform; a\n * `webhook` channel receives requests the app routes to `webhook.verify` and `webhook.ingest`.\n *\n * @public\n */\nexport type ChannelDescriptor<TAdapter extends BasePlatformAdapter = BasePlatformAdapter> =\n | (ChannelDescriptorBase<TAdapter> & { readonly transport: \"socket\"; readonly webhook?: never })\n | (ChannelDescriptorBase<TAdapter> & {\n readonly transport: \"webhook\";\n readonly webhook: ChannelWebhook<TAdapter>;\n });\n\n/**\n * True only when the descriptor declares `senderIdentity: \"authenticated\"`. An absent or\n * unauthenticated declaration is false.\n *\n * @public\n */\nexport function isAuthenticatedSender(descriptor: ChannelDescriptor): boolean {\n return descriptor.senderIdentity === \"authenticated\";\n}\n","/**\n * `configFromEnv` and `selectVariant`: bind a channel descriptor's config fields to environment\n * variables, and pick one of a platform's config shapes.\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport type { ChannelConfigField, ChannelDescriptor } from \"./channel-descriptor.js\";\n\n/** What `configFromEnv` read from the environment. Holds secret values: never log it whole. */\nexport interface EnvConfig {\n /** Trimmed, non-empty values by config key. */\n readonly config: Readonly<Record<string, string>>;\n /** Full variable names of required fields that are unset, empty or whitespace. */\n readonly missing: readonly string[];\n /** Values of present fields marked secret, for a log mask. Never logged. */\n readonly secrets: readonly string[];\n}\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** The full environment variable name for a field: `prefix + field.env`, or `undefined` without `env`. */\nexport function envVarName(field: ChannelConfigField, prefix = \"\"): string | undefined {\n return field.env === undefined ? undefined : prefix + field.env;\n}\n\n/** The trimmed value of `name`, or undefined when it is unset, empty or whitespace. */\nfunction readValue(env: Env, name: string): string | undefined {\n return env[name]?.trim() || undefined;\n}\n\n/**\n * Read a descriptor's fields from `env`, using `prefix + field.env` as the variable name. Fields\n * without `env` are skipped.\n */\nexport function configFromEnv(descriptor: ChannelDescriptor, env: Env, prefix = \"\"): EnvConfig {\n const config: Record<string, string> = {};\n const missing: string[] = [];\n const secrets: string[] = [];\n for (const field of descriptor.config) {\n const name = envVarName(field, prefix);\n if (name === undefined) continue;\n const value = readValue(env, name);\n if (value === undefined) {\n if (field.required) missing.push(name);\n continue;\n }\n config[field.key] = value;\n recordSecret(field, value, secrets);\n }\n return { config, missing, secrets };\n}\n\nfunction recordSecret(field: ChannelConfigField, value: string, secrets: string[]): void {\n if (field.secret && !secrets.includes(value)) secrets.push(value);\n}\n\nfunction mismatch(parent: ChannelDescriptor, variant: ChannelDescriptor, name: string): never {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"platform_mismatch\",\n message: `channel ${parent.platform}: variant \"${name}\" reports platform ${variant.platform}`,\n });\n}\n\nfunction unknownVariant(descriptor: ChannelDescriptor, name: string | undefined): never {\n const valid = Object.keys(descriptor.variants ?? {});\n const given = name === undefined ? \"(none given)\" : `\"${name}\"`;\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"unknown_channel_variant\",\n message: `channel ${descriptor.platform}: unknown variant ${given}; valid variants: ${\n valid.length > 0 ? valid.join(\", \") : \"(none)\"\n }`,\n });\n}\n\n/**\n * The descriptor to use for `name`: the descriptor itself when `name` is undefined and it has no\n * variants, otherwise the named variant. Throws `unknown_channel_variant` for a name that is not a\n * variant (or a missing name when variants exist) and `platform_mismatch` for a variant whose\n * platform differs from its parent's.\n */\nexport function selectVariant(\n descriptor: ChannelDescriptor,\n name: string | undefined,\n): ChannelDescriptor {\n const variants = descriptor.variants ?? {};\n if (name === undefined && Object.keys(variants).length === 0) return descriptor;\n const variant = name !== undefined && Object.hasOwn(variants, name) ? variants[name] : undefined;\n if (variant === undefined) return unknownVariant(descriptor, name);\n if (variant.platform !== descriptor.platform) mismatch(descriptor, variant, name ?? \"\");\n return variant;\n}\n","/**\n * `createChannels` — build every configured channel from its descriptor (FR-002 of B-018).\n *\n * One loop replaces the per-platform constructor calls an app used to write. A channel whose\n * configuration is refused lands in `rejected` and the others are still built, so one bad entry\n * never stops the healthy ones. Nothing here connects or performs I/O (NFR-001): connecting is the\n * runner's job, after the app has seen what was rejected.\n *\n * @public\n */\n\nimport type { BasePlatformAdapter } from \"../adapter/base.js\";\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\nimport type { ChannelDescriptor } from \"./channel-descriptor.js\";\nimport { envVarName } from \"./config-from-env.js\";\n\n/** One channel to build: its descriptor and the configuration the app supplies for it. */\nexport interface ChannelEntry {\n readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;\n /** Values keyed by the descriptor's field keys. Absent means every required field is missing. */\n readonly config?: Readonly<Record<string, unknown>>;\n /**\n * The prefix passed to `configFromEnv` for this entry, so a missing field's rejection names its\n * full environment variable. Defaults to `\"\"`.\n */\n readonly envPrefix?: string;\n}\n\n/** A channel that was not built, and the configuration error that says why. */\nexport interface ChannelRejection {\n readonly platform: PlatformName;\n readonly error: GatewayConfigurationError;\n}\n\n/** A built adapter paired with the descriptor that built it, so a consumer need not re-pair them. */\nexport interface BuiltChannel {\n readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;\n readonly adapter: BasePlatformAdapter;\n}\n\n/** What `createChannels` built and what it refused. */\nexport interface CreateChannelsResult {\n readonly adapters: BasePlatformAdapter[];\n /** The same adapters, in the same order, each paired with its descriptor. */\n readonly channels: BuiltChannel[];\n readonly rejected: ChannelRejection[];\n}\n\nfunction isAbsent(value: unknown): boolean {\n return value === undefined || value === null || value === \"\";\n}\n\nfunction missingRequiredKeys(\n entry: ChannelEntry,\n values: Readonly<Record<string, unknown>>,\n): string[] {\n return entry.descriptor.config\n .filter((field) => field.required && isAbsent(values[field.key]))\n .map((field) => {\n const name = envVarName(field, entry.envPrefix);\n return name === undefined ? field.key : `${field.key} (env ${name})`;\n });\n}\n\n/** An entry that was refused, and the rejection that says why. */\ninterface Refused {\n readonly adapter?: undefined;\n readonly refusal: ChannelRejection;\n}\n\n/** What building one entry produced: its adapter, or the rejection that refused it. */\ntype BuildOutcome =\n | { readonly adapter: BasePlatformAdapter; readonly refusal?: undefined }\n | Refused;\n\nfunction refused(platform: PlatformName, code: string, reason: string): Refused {\n return {\n refusal: {\n platform,\n error: new GatewayConfigurationError(\"gateway\", {\n code,\n message: `channel ${platform}: ${reason}`,\n }),\n },\n };\n}\n\n/**\n * The rejection an entry gets before its `create` runs, or `undefined` when it may be built. A\n * repeated platform is checked first: the platform is already served, so its config is moot.\n */\nfunction refuseBeforeCreate(\n entry: ChannelEntry,\n values: Readonly<Record<string, unknown>>,\n builtPlatforms: ReadonlySet<PlatformName>,\n): Refused | undefined {\n const platform = entry.descriptor.platform;\n if (builtPlatforms.has(platform)) {\n return refused(platform, \"duplicate_channel\", \"a channel for this platform was already built\");\n }\n const missing = missingRequiredKeys(entry, values);\n if (missing.length > 0) {\n return refused(\n platform,\n \"missing_required_config\",\n `missing required config ${missing.join(\", \")}`,\n );\n }\n return undefined;\n}\n\n/**\n * Call the descriptor's `create` and check what it built. The runner keys adapters by the\n * adapter's own `platform`, and the duplicate check keys them by the descriptor's, so an adapter\n * reporting another platform than its descriptor is refused: kept, it would reach the runner as a\n * second adapter for a platform the duplicate check never saw.\n */\nfunction createAdapter(\n entry: ChannelEntry,\n values: Readonly<Record<string, unknown>>,\n): BuildOutcome {\n const platform = entry.descriptor.platform;\n let adapter: BasePlatformAdapter;\n try {\n adapter = entry.descriptor.create(values);\n } catch (err) {\n if (!(err instanceof GatewayConfigurationError)) throw err;\n return { refusal: { platform, error: err } };\n }\n if (adapter.platform !== platform) {\n return refused(\n platform,\n \"platform_mismatch\",\n `create returned an adapter reporting platform ${adapter.platform}`,\n );\n }\n return { adapter };\n}\n\n/**\n * Build an adapter for each entry whose required fields are present.\n *\n * An entry missing a required field (absent, `null` or `\"\"`; `0` and `false` count as present) is\n * rejected with a `GatewayConfigurationError` coded `missing_required_config` that names every\n * missing key, and its `create` is never called. A `GatewayConfigurationError` thrown by `create`\n * is reported the same way. Any other throw is a defect, not a configuration fault, and propagates.\n *\n * Only one adapter per platform is built, because the runner routes replies and `stop()` by\n * platform. The first entry built for a platform wins; a later entry for that platform is rejected\n * with a `GatewayConfigurationError` coded `duplicate_channel`, before its required fields are\n * checked, and its `create` is never called. An entry rejected for its configuration built\n * nothing, so it does not claim its platform.\n *\n * The runner keys adapters by the adapter's own `platform`, so an adapter must report the platform\n * its descriptor declares. One that reports another is discarded unconnected and its entry is\n * rejected with a `GatewayConfigurationError` coded `platform_mismatch`; it claims no platform.\n *\n * @public\n */\nexport function createChannels(entries: ReadonlyArray<ChannelEntry>): CreateChannelsResult {\n const adapters: BasePlatformAdapter[] = [];\n const channels: BuiltChannel[] = [];\n const rejected: ChannelRejection[] = [];\n const builtPlatforms = new Set<PlatformName>();\n for (const entry of entries) {\n const values = entry.config ?? {};\n const outcome =\n refuseBeforeCreate(entry, values, builtPlatforms) ?? createAdapter(entry, values);\n if (outcome.refusal !== undefined) {\n rejected.push(outcome.refusal);\n continue;\n }\n adapters.push(outcome.adapter);\n channels.push({ descriptor: entry.descriptor, adapter: outcome.adapter });\n builtPlatforms.add(entry.descriptor.platform);\n }\n return { adapters, channels, rejected };\n}\n","/**\n * How the core's two outbound builders treat `attachments` (B-674): `GatewayRunner`'s `ctx.reply`\n * and `DeliveryRouter.send` both carry a non-empty list and both refuse it for an adapter that\n * does not declare `supportsAttachments`.\n *\n * The refusal here is defence in depth: every adapter in this repository refuses on its own, but an\n * adapter written elsewhere inherits `supportsAttachments = false` and may ignore the field, sending\n * the text alone and reporting success. Refusing before the adapter is called keeps the image from\n * being dropped in silence whichever adapter receives it.\n *\n * @internal\n */\n\nimport type {\n BasePlatformAdapter,\n OutboundAttachment,\n OutboundMessage,\n SendResult,\n} from \"../adapter/base.js\";\n\n/**\n * The non-empty `attachments` of a request, or nothing for absent, `null` or empty. `!== 0`, not\n * `> 0`: another non-array value from a JavaScript caller has no numeric length and is carried on,\n * to be refused, rather than dropped (EC-1).\n */\nexport function attachmentsOf(attachments: ReadonlyArray<OutboundAttachment> | undefined): {\n attachments?: ReadonlyArray<OutboundAttachment>;\n} {\n return attachments != null && attachments.length !== 0 ? { attachments } : {};\n}\n\n/**\n * `attachments_unsupported` when `outbound` carries attachments and `adapter` does not declare\n * `supportsAttachments`, otherwise `undefined`. Makes no platform call.\n */\nexport function refuseUnsupportedAttachments(\n adapter: BasePlatformAdapter,\n outbound: OutboundMessage,\n): SendResult | undefined {\n const { attachments } = outbound;\n if (adapter.supportsAttachments || attachments == null || attachments.length === 0) {\n return undefined;\n }\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: `${adapter.platform} adapter cannot send attachments`,\n },\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, OutboundAttachment, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\nimport { attachmentsOf, refuseUnsupportedAttachments } from \"./attachments.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 /** Images to send with the text; an empty list is left out (B-674). */\n readonly attachments?: ReadonlyArray<OutboundAttachment>;\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 * - `send` with attachments refuses with `attachments_unsupported`, calling no `sendMessage`, when\n * the adapter does not declare `supportsAttachments`.\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 const outbound = {\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n ...attachmentsOf(req.attachments),\n };\n return refuseUnsupportedAttachments(adapter, outbound) ?? adapter.sendMessage(outbound);\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 * The uncovered shapes as one `field :: why` row per line. A single literal rather than an object\n * per entry keeps a long list of same-shaped entries from reading as a block repeated line for line.\n */\nconst UNCOVERED_TABLE = `gateway-qq \\`appSecret\\` :: a QQ Bot AppSecret, an opaque 32-character string with no prefix or fixed shape. It travels only to the access-token endpoint and into the webhook signature derivation; the adapter never logs it.\ngateway-x \\`clientSecret\\`, \\`refreshToken\\`, \\`bearerToken\\` :: an X OAuth 2.0 client secret, a rotating refresh token and an app bearer token, opaque strings with no fixed prefix. They travel only to the X API in Authorization headers and the token request body, which the adapter never logs.\ngateway-buzz \\`token\\` :: a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs.\ngateway-clickclack \\`token\\` :: a ClickClack bot token (\\`ccb_\\` prefix) or session token with no fixed shape for the latter. It travels only in Authorization headers, which the adapter never logs.\ngateway-zalo \\`accessToken\\`, \\`oaSecretKey\\` :: a Zalo Official Account access token and OA secret key: opaque strings with no prefix or fixed shape to recognise. The token travels only in an \\`access_token\\` header and the key only into the signature check, and the adapter never logs either.\ngateway-wechat \\`appSecret\\`, \\`token\\` :: a WeChat Official Account AppSecret (32 hex characters, indistinguishable from any other hex string) and the server-URL verification token (a string the operator chooses). The secret travels only to the access-token endpoint and the token only into the signature check; the adapter never logs either.\ngateway-wecom \\`corpSecret\\`, \\`token\\`, \\`encodingAesKey\\` :: a WeCom application Secret (43 URL-safe base64 characters, indistinguishable from other opaque strings), the callback Token (a string the operator chooses) and the EncodingAESKey (43 base64 characters). The secret travels only to the access-token endpoint, the token into the signature check and the key into the decryption; the adapter never logs any of them.\ngateway-yuanbao \\`appSecret\\`, \\`callbackSecret\\` :: a Yuanbao bot AppSecret and the callback signing secret, both opaque strings with no prefix or fixed shape. The app secret travels only to the access-token endpoint and the callback secret only into the signature check; the adapter never logs either.\ngateway-zalo-personal \\`credentials\\` :: a Zalo web session: a cookie jar, an IMEI-like device id and a user agent. The cookie has no prefix or fixed shape to recognise. It travels only to the Zalo library, which the adapter never logs.\ngateway-twitch \\`accessToken\\` :: 30 lowercase alphanumerics with no prefix, the shape of many ids and hashes in a log. It travels only in Authorization headers, which the adapter never logs.\ngateway-tlon-urbit \\`code\\` :: a +code is four dash-joined phonemic syllable words, the same shape as an Urbit ship name such as ~sampel-palnet-sampel-palnet, which the logs exist to show. It travels only in the /~/login body, which the adapter never logs.\ngateway-synology-chat \\`botToken\\` and \\`incomingUrl\\` :: a bot token is a random string the NAS generates with no prefix, and the Incoming URL carries its own token as a query parameter of an ordinary entry.cgi URL. Neither has a shape to claim without eating ordinary ids and URLs; the adapter never logs the URL, and refuses a callback token before reading it.\ngateway-feishu-lark \\`appSecret\\` :: 32 alphanumerics with no prefix, the shape of many tokens and hashes; it travels only in the body of the tenant-token request, which the adapter never logs.\ngateway-nostr \\`secretKey\\` (64-hex form) :: 64 hex characters is also every Nostr public key and event id, which the logs exist to show, and a sha256 digest. The nsec1 spelling of the same key is masked above.\ngateway-sms \\`authToken\\` (Twilio), gateway-line \\`channelSecret\\` :: 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.\ngateway-mattermost \\`accessToken\\` :: 26 lowercase alphanumerics, which is exactly a lowercase ULID — the shape of most trace ids.\ngateway-email \\`password\\`, gateway-sms \\`apiSecret\\` and \\`signatureSecret\\` (Vonage) :: 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.\ngateway-slack \\`botToken\\` :: 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.\ngateway-whatsapp \\`appSecret\\` :: 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.\ngateway-nextcloud-talk \\`secret\\` :: a Talk bot secret is a string of 40 to 128 characters the administrator chose for \\`occ talk:bot:install\\`, with no prefix or format to recognise. It never travels: both sides send only an HMAC made with it, and the adapter never logs it.\ngateway-irc \\`password\\` and \\`saslPassword\\` :: a server password and a NickServ password are passphrases the operator chose, with no format to recognise. The SDK's \\`key=value\\` rule masks them as fields wherever they appear as \\`password=...\\`; the SASL payload on the wire is their base64, which the adapter never logs.\ngateway-google-chat \\`privateKey\\` :: a PEM block spans lines, and in a log it usually arrives inside a JSON string with its line breaks escaped as \\\\n, which no single-line shape can claim whole. The SDK's \\`key=value\\` rule masks it as a field wherever it appears as \\`private_key=...\\` or \\`privateKey=...\\`.\ngateway-line \\`channelAccessToken\\`, gateway-sms \\`authToken\\` (Plivo) :: long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message.`;\n\n/** Read the rows of {@link UNCOVERED_TABLE}. */\nfunction parseUncovered(table: string): readonly UncoveredShape[] {\n return table.split(\"\\n\").map((row) => {\n const [field = \"\", why = \"\"] = row.split(\" :: \");\n return { field, why };\n });\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 field: \"gateway-nostr `secretKey` (nsec1 form)\",\n pattern: /(?<![a-z0-9])nsec1[02-9ac-hj-np-z]{58}(?![a-z0-9])/g,\n alsoMatches: \"nothing plausible — `nsec1` is NIP-19's prefix for a secret key\",\n },\n ],\n uncovered: parseUncovered(UNCOVERED_TABLE),\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/**\n * Replace each exact value in `secrets` with `[redacted]`, longest value first so a value that\n * contains another is masked whole. Empty values are ignored. It does not run `redactSecrets`:\n * call that afterwards, because it shortens some shapes to a head and tail and the masked fragments\n * would otherwise survive.\n *\n * @param text the text to mask\n * @param secrets the exact credential values configured for this process\n * @returns the text with every occurrence of every value replaced\n */\nexport function maskSecrets(text: string, secrets: ReadonlyArray<string>): string {\n const ordered = [...new Set(secrets)]\n .filter((s) => s.length > 0)\n .sort((a, b) => b.length - a.length);\n let out = text;\n for (const secret of ordered) out = out.split(secret).join(\"[redacted]\");\n return out;\n}\n","/**\n * File-backed pairing store: senders approved by an owner are kept in `pairing.json`.\n * Pending codes live in memory for one hour.\n *\n * @public\n */\n\nimport { randomInt, randomUUID } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\n\n/** Pairing store used by the access policy hook. */\nexport interface PairingStore {\n /** A 6-digit code for the sender; the same code while one is pending. */\n issue(platform: string, senderId: string): string;\n approve(\n code: string,\n ): Promise<\n | { ok: true; platform: string; senderId: string }\n | { ok: false; reason: \"unknown_or_expired\" | \"write_failed\" }\n >;\n isPaired(platform: string, senderId: string): boolean;\n}\n\n/** `<platform>:<senderId>`; email ids compare case-insensitively. */\nexport function senderKey(platform: string, senderId: string): string {\n return `${platform}:${platform === \"email\" ? senderId.toLowerCase() : senderId}`;\n}\n\nconst TTL_MS = 3_600_000;\nconst FILE = \"pairing.json\";\n\nfunction unreadable(): GatewayConfigurationError {\n return new GatewayConfigurationError(\"gateway\", {\n code: \"pairing_store_unreadable\",\n message: \"gateway: pairing_store_unreadable\",\n });\n}\n\nfunction load(path: string): Set<string> {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return new Set();\n throw unreadable();\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw unreadable();\n }\n const list = (parsed as { paired?: unknown } | null)?.paired;\n if (!Array.isArray(list) || !list.every((x) => typeof x === \"string\")) throw unreadable();\n return new Set(list as string[]);\n}\n\n/** Creates a store persisted in `<dir>/pairing.json` (mode 0600). */\nexport function createFilePairingStore(options: {\n dir: string;\n clock?: () => number;\n random?: (min: number, max: number) => number;\n}): PairingStore {\n const clock = options.clock ?? Date.now;\n const random = options.random ?? randomInt;\n const path = join(options.dir, FILE);\n const paired = load(path);\n const pending = new Map<string, { platform: string; senderId: string; expires: number }>();\n let chain: Promise<unknown> = Promise.resolve();\n\n const prune = (): void => {\n const now = clock();\n for (const [code, p] of pending) if (p.expires <= now) pending.delete(code);\n };\n\n function persist(next: Set<string>): void {\n mkdirSync(options.dir, { recursive: true });\n const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;\n writeFileSync(tmp, JSON.stringify({ paired: [...next].sort((a, b) => a.localeCompare(b)) }), {\n mode: 0o600,\n flag: \"wx\",\n });\n renameSync(tmp, path);\n }\n\n return {\n issue(platform, senderId) {\n prune();\n for (const [code, p] of pending) {\n if (senderKey(p.platform, p.senderId) === senderKey(platform, senderId)) return code;\n }\n let code: string;\n do {\n code = String(random(100000, 1000000));\n } while (pending.has(code));\n pending.set(code, { platform, senderId, expires: clock() + TTL_MS });\n return code;\n },\n approve(code) {\n const run = async () => {\n prune();\n const p = pending.get(code);\n if (!p) return { ok: false as const, reason: \"unknown_or_expired\" as const };\n const next = new Set(paired);\n next.add(senderKey(p.platform, p.senderId));\n try {\n persist(next);\n } catch {\n return { ok: false as const, reason: \"write_failed\" as const };\n }\n paired.add(senderKey(p.platform, p.senderId));\n pending.delete(code);\n return { ok: true as const, platform: p.platform, senderId: p.senderId };\n };\n const result = chain.then(run, run);\n chain = result.catch(() => undefined);\n return result;\n },\n isPaired(platform, senderId) {\n return paired.has(senderKey(platform, senderId));\n },\n };\n}\n","/**\n * Access policy hook: who may talk to the agent, with sender pairing.\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport { redactSecrets } from \"../security/credential-patterns.js\";\nimport type { MessageEvent, PlatformName } from \"../types/message-event.js\";\nimport { type PairingStore, senderKey } from \"./pairing-store.js\";\nimport type { GatewayHook, HookDecision } from \"./types.js\";\n\nexport type DmPolicy = \"pairing\" | \"allowlist\" | \"open\" | \"disabled\";\n\n/** Options for {@link createAccessPolicyHook}. */\nexport interface AccessPolicyOptions {\n /** `<platform>:<senderId>` keys. */\n readonly owners: ReadonlySet<string>;\n readonly allowed?: ReadonlySet<string>;\n readonly dm: DmPolicy;\n /** Group messages from non-members: \"silent\" (default) or \"open\". */\n readonly groups?: \"silent\" | \"open\";\n /** Which platforms authenticate the sender. */\n readonly isAuthenticated: (platform: PlatformName) => boolean;\n /** Required when dm is \"pairing\". */\n readonly pairing?: PairingStore;\n readonly refusalText?: string;\n readonly refusalIntervalMs?: number;\n /** Let a message through untouched. */\n readonly passThrough?: (event: MessageEvent) => boolean;\n readonly clock?: () => number;\n readonly write?: (line: string) => void;\n}\n\nconst SILENT: HookDecision = { block: true };\nconst DEFAULT_REFUSAL = \"Sorry, you are not authorized to use this assistant.\";\n\nfunction normalize(key: string): string {\n const i = key.indexOf(\":\");\n return i < 0 ? key : senderKey(key.slice(0, i), key.slice(i + 1));\n}\n\nfunction check(keys: ReadonlySet<string>, isAuth: (p: PlatformName) => boolean): Set<string> {\n const out = new Set<string>();\n for (const key of keys) {\n const i = key.indexOf(\":\");\n const platform = i < 0 ? key : key.slice(0, i);\n if (!isAuth(platform as PlatformName)) {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"unauthenticated_owner\",\n message: `gateway: unauthenticated_owner: platform ${platform} does not authenticate the sender`,\n detail: platform,\n });\n }\n out.add(normalize(key));\n }\n return out;\n}\n\n/** Builds the `pre_inbound` access policy hook. */\nexport function createAccessPolicyHook(options: AccessPolicyOptions): GatewayHook {\n if (options.dm === \"pairing\" && !options.pairing) {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"pairing_store_required\",\n message: \"gateway: pairing_store_required\",\n });\n }\n const owners = check(options.owners, options.isAuthenticated);\n const allowed = check(options.allowed ?? new Set(), options.isAuthenticated);\n const clock = options.clock ?? Date.now;\n const interval = options.refusalIntervalMs ?? 3_600_000;\n const write = options.write ?? ((line: string) => process.stderr.write(`${line}\\n`));\n const refusal = options.refusalText ?? DEFAULT_REFUSAL;\n const store = options.pairing;\n const refused = new Map<string, number>();\n\n const mayRefuse = (key: string): boolean => {\n const now = clock();\n for (const [k, t] of refused) if (now - t >= interval) refused.delete(k);\n if (refused.has(key)) return false;\n refused.set(key, now);\n return true;\n };\n\n const pairingReply = (event: MessageEvent): HookDecision => {\n const code = (store as PairingStore).issue(event.platform, event.sender.id);\n return {\n block: true,\n message: `Your pairing code is ${code}. Ask the owner to send /approve ${code}.`,\n };\n };\n\n const groupDecision = (): HookDecision | undefined =>\n options.groups === \"open\" ? undefined : SILENT;\n\n const stranger = (event: MessageEvent, key: string): HookDecision | undefined => {\n if (event.channel.type !== \"dm\") return groupDecision();\n if (options.dm === \"open\") return undefined;\n if (options.dm === \"disabled\" || !mayRefuse(key)) return SILENT;\n if (options.dm === \"allowlist\") return { block: true, message: refusal };\n return pairingReply(event);\n };\n\n const ownerMessage = async (text: string): Promise<HookDecision | undefined> => {\n const m = /^\\/approve\\s+(\\d{6})\\s*$/.exec(text.trim());\n if (!m?.[1]) return undefined;\n if (!store) return { block: true, message: \"Pairing is not enabled.\" };\n const r = await store.approve(m[1]);\n if (r.ok) return { block: true, message: \"Paired.\" };\n return {\n block: true,\n message:\n r.reason === \"write_failed\"\n ? \"Saving the pairing failed. Check the storage and send the code again.\"\n : \"Unknown or expired code.\",\n };\n };\n\n const isPaired = (event: MessageEvent): boolean =>\n store?.isPaired(event.platform, event.sender.id) === true;\n\n const decide = async (event: MessageEvent): Promise<HookDecision | undefined> => {\n if (options.passThrough?.(event)) return undefined;\n // Never trust or answer a forgeable sender id.\n if (!options.isAuthenticated(event.platform as PlatformName)) return SILENT;\n const key = senderKey(event.platform, event.sender.id);\n if (owners.has(key)) return ownerMessage(event.text);\n if (allowed.has(key) || isPaired(event)) return undefined;\n return stranger(event, key);\n };\n\n return {\n name: \"access-policy\",\n async pre_inbound({ event }) {\n try {\n return await decide(event);\n } catch (e) {\n try {\n write(`access-policy: hook failed: ${redactSecrets(e)}`);\n } catch {\n // A failing logger must not turn the silent block into a hook-failed reply.\n }\n return SILENT;\n }\n },\n };\n}\n","/**\n * Chat command parsing and a single `pre_inbound` hook for many commands.\n *\n * Recognises a command behind one leading mention (`<@U123> /help`,\n * `@bot /help`) and with Telegram's `@botname` suffix (`/help@my_bot`).\n * The name is matched exactly: `/new chat` is `/new` with arg `chat`,\n * `/newer` is never `/new`.\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport type { MessageEvent } from \"../types/message-event.js\";\nimport type { GatewayHook, HookDecision } from \"./types.js\";\n\n/** A parsed chat command. */\nexport interface ParsedChatCommand {\n /** Command name, without the prefix and without `@bot`. */\n readonly name: string;\n /** Trimmed rest of the text, `\"\"` when none. */\n readonly arg: string;\n}\n\nconst LEADING_MENTION = /^(?:<@[^>]+>|@\\S+)\\s+/;\nconst DEFAULT_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\nfunction matchPrefix(text: string, prefixes: ReadonlyArray<string>): string | undefined {\n let best: string | undefined;\n for (const p of prefixes) {\n if (p.length > 0 && text.startsWith(p) && (best === undefined || p.length > best.length)) {\n best = p;\n }\n }\n return best;\n}\n\n/**\n * Strips one leading `<@U...>` or `@name` mention and a `@bot` suffix.\n * Returns `undefined` for text that is not a command.\n */\nexport function parseChatCommand(\n text: string,\n options?: { prefixes?: ReadonlyArray<string> },\n): ParsedChatCommand | undefined {\n const body = text.trim().replace(LEADING_MENTION, \"\");\n const prefix = matchPrefix(body, options?.prefixes ?? DEFAULT_PREFIXES);\n if (prefix === undefined) return undefined;\n const rest = body.slice(prefix.length);\n const m = /^([^\\s@]+)(?:@\\S+)?(?:\\s+([\\s\\S]*))?$/.exec(rest);\n if (!m?.[1]) return undefined;\n return { name: m[1].toLowerCase(), arg: (m[2] ?? \"\").trim() };\n}\n\n/** One command handled by {@link commandHook}. */\nexport interface ChatCommand {\n readonly name: string;\n readonly description: string;\n /** Default `\"optional\"`. */\n readonly arg?: \"none\" | \"optional\" | \"required\";\n /** Usage line shown in help. Default `\"/<name>\"`. */\n readonly usage?: string;\n run(\n event: MessageEvent,\n arg: string,\n ): HookDecision | undefined | Promise<HookDecision | undefined>;\n}\n\nfunction usageOf(c: ChatCommand): string {\n return c.usage ?? `/${c.name}`;\n}\n\n/** Help text listing every command's usage and description, in declaration order. */\nexport function helpText(commands: ReadonlyArray<ChatCommand>): string {\n return commands.map((c) => `${usageOf(c)} - ${c.description}`).join(\"\\n\");\n}\n\nfunction assertUnique(names: ReadonlyArray<string>): void {\n const seen = new Set<string>();\n for (const raw of names) {\n const name = raw.toLowerCase();\n if (seen.has(name)) {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"duplicate_command\",\n message: `gateway: duplicate_command: ${raw}`,\n detail: raw,\n });\n }\n seen.add(name);\n }\n}\n\nfunction badArity(c: ChatCommand, arg: string): boolean {\n const mode = c.arg ?? \"optional\";\n return (mode === \"none\" && arg !== \"\") || (mode === \"required\" && arg === \"\");\n}\n\n/**\n * One `pre_inbound` hook for many commands. Also answers `/help`\n * (rename with `helpCommand`, disable with `false`).\n */\nexport function commandHook(\n commands: ReadonlyArray<ChatCommand>,\n options?: { name?: string; helpCommand?: string | false },\n): GatewayHook {\n const helpName = options?.helpCommand === undefined ? \"help\" : options.helpCommand;\n assertUnique([...commands.map((c) => c.name), ...(helpName === false ? [] : [helpName])]);\n const byName = new Map(commands.map((c) => [c.name.toLowerCase(), c]));\n const help = helpText(commands);\n\n return {\n name: options?.name ?? \"chat-commands\",\n async pre_inbound({ event }) {\n const parsed = parseChatCommand(event.text);\n if (!parsed) return undefined;\n if (helpName !== false && parsed.name === helpName.toLowerCase()) {\n return { block: true, message: help };\n }\n const command = byName.get(parsed.name);\n if (!command) return undefined;\n if (badArity(command, parsed.arg)) return { block: true, message: usageOf(command) };\n return command.run(event, parsed.arg);\n },\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 { 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","import type { ReconnectPolicy } from \"./gateway-runner.js\";\n\n/**\n * Options for {@link ReconnectBackoff}. Delay fields default as documented on `ReconnectPolicy`.\n *\n * @public\n */\nexport interface ReconnectBackoffOptions extends ReconnectPolicy {\n /** A connection open at least this long resets the delay. Default 60_000. */\n readonly stableAfterMs?: number;\n /** Clock in ms; defaults to `Date.now`. */\n readonly now?: () => number;\n}\n\nfunction checkNonNegativeFinite(name: string, value: number): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new RangeError(`${name} must be a finite number >= 0, got ${value}`);\n }\n}\n\n/**\n * Reconnect delay for an adapter that holds a long-lived connection: `min(initialDelayMs *\n * factor^(n-1), maxDelayMs)` for attempt n, reset after a connection that stayed open for\n * `stableAfterMs`.\n *\n * @public\n */\nexport class ReconnectBackoff {\n private readonly initialDelayMs: number;\n private readonly maxDelayMs: number;\n private readonly factor: number;\n private readonly maxAttempts: number | undefined;\n private readonly stableAfterMs: number;\n private readonly now: () => number;\n private attempts = 0;\n private openedAt: number | undefined;\n\n constructor(options: ReconnectBackoffOptions = {}) {\n this.initialDelayMs = options.initialDelayMs ?? 1000;\n this.maxDelayMs = options.maxDelayMs ?? 60_000;\n this.factor = options.factor ?? 2;\n this.maxAttempts = options.maxAttempts;\n this.stableAfterMs = options.stableAfterMs ?? 60_000;\n this.now = options.now ?? Date.now;\n checkNonNegativeFinite(\"initialDelayMs\", this.initialDelayMs);\n checkNonNegativeFinite(\"maxDelayMs\", this.maxDelayMs);\n if (!(this.factor >= 1) || !Number.isFinite(this.factor)) {\n throw new RangeError(`factor must be a finite number >= 1, got ${this.factor}`);\n }\n }\n\n /** Call when the connection opens. */\n opened(): void {\n this.openedAt = this.now();\n }\n\n /** Delay before the next attempt; `undefined` once `maxAttempts` is spent. Resets first if the last connection was stable. */\n nextDelayMs(): number | undefined {\n if (this.openedAt !== undefined) {\n if (this.now() - this.openedAt >= this.stableAfterMs) this.attempts = 0;\n this.openedAt = undefined;\n }\n if (this.maxAttempts !== undefined && this.attempts >= this.maxAttempts) return undefined;\n const delay = Math.min(this.initialDelayMs * this.factor ** this.attempts, this.maxDelayMs);\n this.attempts += 1;\n return delay;\n }\n\n /** Back to the initial delay. */\n reset(): void {\n this.attempts = 0;\n this.openedAt = undefined;\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 and resolves a `StartResult`.\n * By default (`connectFailure: \"rollback\"`) partial failure rolls back:\n * connected adapters get `disconnect()`, then the error rethrows. Under\n * `connectFailure: \"isolate\"` the adapters that connected keep running and\n * the rest are reported in `StartResult.failed`.\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 {\n BasePlatformAdapter,\n OutboundAttachment,\n OutboundMessage,\n SendResult,\n} from \"../adapter/base.js\";\nimport { attachmentsOf, refuseUnsupportedAttachments } from \"../delivery/attachments.js\";\nimport { GatewayLifecycleError } from \"../errors/lifecycle-error.js\";\nimport { HookExecutor } from \"../hooks/executor.js\";\nimport type { GatewayHook } from \"../hooks/types.js\";\nimport { maskSecrets, redactSecrets } from \"../security/credential-patterns.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\nimport { ReconnectBackoff } from \"./reconnect-backoff.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(\n text: string,\n opts?: {\n format?: \"plain\" | \"markdown\" | \"html\";\n /** Images to send with the text; an empty list is left out (B-674). */\n attachments?: ReadonlyArray<OutboundAttachment>;\n },\n ): 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 * What `start()` does when an adapter fails to connect. `\"rollback\"` (the default) disconnects\n * the adapters that did connect and rethrows: all or nothing. `\"isolate\"` keeps the adapters that\n * connected, wires inbound only for them, and reports the others in the resolved\n * `StartResult.failed`, so one channel that cannot connect does not stop the healthy ones.\n *\n * @public\n */\n readonly connectFailure?: ConnectFailure;\n /**\n * Retry, in the background, an adapter whose `connect()` threw a transient error under\n * `connectFailure: \"isolate\"` (network refused, DNS, 5xx), with exponential backoff and a log\n * line per attempt. An adapter that connects on a retry is wired for inbound and joins\n * `connected`. A `connect()` that resolves `false`, or throws a credential error (HTTP 401/403,\n * `M_UNKNOWN_TOKEN`, `M_FORBIDDEN`, \"unauthorized\"), is terminal: it is reported once and not\n * retried. Off unless set; ignored under `\"rollback\"`.\n *\n * @public\n */\n readonly reconnect?: ReconnectPolicy;\n /**\n * Under `connectFailure: \"isolate\"`, give up on one adapter's `connect()` after this many ms. The\n * adapter is reported `timed_out`, counted in `StartResult.failed`, and never wired for inbound:\n * if its `connect()` resolves `true` later, the runner disconnects it. With `reconnect` set it is\n * retried like a transient failure. Ignored under `\"rollback\"`, as `reconnect` is.\n *\n * @public\n */\n readonly connectTimeoutMs?: number;\n /**\n * Called as each adapter changes state, while `start()` may still be pending. `reason` is\n * redacted. A callback that throws is ignored. Ignored under `\"rollback\"`.\n *\n * @public\n */\n readonly onAdapterState?: (platform: PlatformName, state: AdapterState, reason?: string) => void;\n /**\n * Exact credential values masked (longest first) in every reason and log line before\n * `redactSecrets` runs.\n *\n * @public\n */\n readonly secrets?: ReadonlyArray<string>;\n}\n\n/**\n * Where one adapter stands under `connectFailure: \"isolate\"`, as reported to\n * `GatewayRunnerOptions.onAdapterState`.\n *\n * @public\n */\nexport type AdapterState = \"connected\" | \"failed\" | \"retrying\" | \"timed_out\";\n\n/**\n * Backoff for `GatewayRunnerOptions.reconnect`. The delay before attempt n is\n * `min(initialDelayMs * factor^(n-1), maxDelayMs)`.\n *\n * @public\n */\nexport interface ReconnectPolicy {\n /** Delay before the first retry. Default 1000ms. */\n readonly initialDelayMs?: number;\n /** Cap on the delay between attempts. Default 60_000ms. */\n readonly maxDelayMs?: number;\n /** Multiplier per attempt. Default 2. */\n readonly factor?: number;\n /** Give up after this many retries. Default: keep trying until `stop()`. */\n readonly maxAttempts?: number;\n}\n\n/**\n * How `GatewayRunner.start()` treats an adapter that fails to connect: `\"rollback\"` (all or\n * nothing, the default) or `\"isolate\"` (keep the ones that connected).\n *\n * @public\n */\nexport type ConnectFailure = \"rollback\" | \"isolate\";\n\n/**\n * What `GatewayRunner.start()` connected. Under `\"rollback\"` `failed` is always empty, because a\n * failure rejects instead; under `\"isolate\"` it names each adapter that did not connect and why,\n * with any credential in the reason redacted.\n *\n * @public\n */\nexport interface StartResult {\n readonly connected: ReadonlyArray<PlatformName>;\n readonly failed: ReadonlyArray<{ readonly platform: PlatformName; readonly reason: string }>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\n\n/** Typing indicators last 5-10 s on the platforms that expire them; renew inside that. */\nconst TYPING_RENEW_MS = 4_000;\n\n/**\n * Show a typing indicator on `channelId` until the returned function is awaited. The indicator is\n * cosmetic: a failing adapter never fails the turn, and the renewal timer never keeps the process alive.\n */\nfunction keepTyping(adapter: BasePlatformAdapter, channelId: string): () => Promise<void> {\n const swallow = (p: Promise<void>): Promise<void> => p.catch(() => undefined);\n const start = (): Promise<void> =>\n swallow(Promise.resolve().then(() => adapter.startTyping(channelId)));\n void start();\n const timer = setInterval(() => void start(), TYPING_RENEW_MS);\n timer.unref();\n return async () => {\n clearInterval(timer);\n await swallow(Promise.resolve().then(() => adapter.stopTyping(channelId)));\n };\n}\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\ninterface ConnectOutcome {\n readonly connected: BasePlatformAdapter[];\n readonly failed: StartResult[\"failed\"][number][];\n /** Adapters whose connect threw a transient error, for the reconnect policy. */\n readonly retryable: BasePlatformAdapter[];\n}\n\ntype Redact = (text: string) => string;\n\ninterface IsolatedResult {\n readonly adapter: BasePlatformAdapter;\n readonly failure: StartResult[\"failed\"][number] | undefined;\n readonly retry: boolean;\n}\n\nfunction connectFailureReason(outcome: PromiseSettledResult<boolean>, redact: Redact): string {\n if (outcome.status === \"fulfilled\") return \"connect returned false\";\n const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);\n // A connect error can echo the credential it was given.\n return redact(message);\n}\n\n/** A credential refusal will fail identically on every retry, so it is never retried. */\nfunction isTerminalConnectError(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) return false;\n const e = err as Record<string, unknown>;\n for (const key of [\"status\", \"statusCode\", \"httpStatus\"]) {\n if (e[key] === 401 || e[key] === 403) return true;\n }\n if (e.errcode === \"M_UNKNOWN_TOKEN\" || e.errcode === \"M_FORBIDDEN\") return true;\n const message = typeof e.message === \"string\" ? e.message : \"\";\n return /\\b(?:http|status(?: code)?)\\s*:?\\s*(?:401|403)\\b|unauthori[sz]ed|forbidden/i.test(\n message,\n );\n}\n\n/**\n * Disconnect every adapter the runner is giving back, from a rollback, an overtaken start or\n * `stop()`. A disconnect that fails does not stop the others and does not change how the caller\n * settles, but it is reported: such an adapter may still hold its platform session, and a\n * discarded failure left that state with no trace.\n */\nasync function releaseAdapters(\n adapters: ReadonlyArray<BasePlatformAdapter>,\n during: string,\n redact: Redact = redactSecrets,\n): Promise<void> {\n await Promise.all(\n adapters.map(async (a) => {\n try {\n await a.disconnect();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(\n `[gateway] adapter \"${a.platform}\" disconnect failed while ${during}: ${redact(message)}\\n`,\n );\n }\n }),\n );\n}\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 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 startResult: StartResult | undefined;\n /** The start that has not settled yet, shared by every overlapping `start()` call. */\n private startInFlight: Promise<StartResult> | undefined;\n private stopped = false;\n private readonly retryTimers = new Set<NodeJS.Timeout>();\n private readonly connectedPlatforms = new Set<PlatformName>();\n private readonly redact: Redact;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n const secrets = opts.secrets ?? [];\n this.redact = (text) => redactSecrets(maskSecrets(text, secrets));\n }\n\n /** The registered adapter for a platform, connected or not. */\n adapter(platform: PlatformName): BasePlatformAdapter | undefined {\n return this.opts.adapters.find((a) => a.platform === platform);\n }\n\n /** Platforms whose adapter is connected now; updated by connects, retries and `stop()`. */\n get connected(): ReadonlySet<PlatformName> {\n return this.connectedPlatforms;\n }\n\n private emitState(platform: PlatformName, state: AdapterState, reason?: string): void {\n if ((this.opts.connectFailure ?? \"rollback\") !== \"isolate\") return;\n try {\n this.opts.onAdapterState?.(platform, state, reason);\n } catch {\n /* a throwing observer must not break the runner */\n }\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 the adapters and wire inbound dispatch for the ones that connected.\n *\n * Resolves with what connected. A second call after the first resolved returns the same result\n * without connecting again.\n *\n * Overlapping calls share one start; a start overtaken by stop resolves with no adapter connected.\n * A call made before `stop()` while another is still connecting connects nothing and settles\n * with it; a call made after `stop()` throws `runner_stopped`. When `stop()` runs before the\n * connect settles, the adapters that connected are disconnected, no inbound dispatch is wired,\n * and the start resolves `{ connected: [], failed }`, keeping the `\"isolate\"` failures. Under\n * `\"rollback\"`, a connect that fails still rejects the start.\n *\n * Under `connectFailure: \"rollback\"`, every connect settles before the rollback, so a failing\n * start rejects only once its slowest connect settles, as a successful one resolves only then.\n *\n * An adapter whose `disconnect()` fails while a start rolls back, or while a start that `stop()`\n * overtook gives its adapters back, is named on stderr with the error redacted; how the start\n * settles does not change.\n *\n * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already\n * stopped. A stopped runner is spent; construct a new one.\n * @throws {Error} under the default `connectFailure: \"rollback\"`, the first connect failure, after\n * every connect settled and the adapters that did connect were disconnected.\n */\n async start(): Promise<StartResult> {\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.startResult !== undefined) return this.startResult;\n if (this.startInFlight === undefined) {\n // Recorded in the same synchronous section that calls `connect()`, before anything awaits: a\n // guard on `startResult` alone, written after the connect, let an overlapping call connect\n // every adapter a second time.\n const pending = this.runStart();\n this.startInFlight = pending;\n // A rejected start is not memoised, so a later call connects again. The identity check is\n // defensive: this handler is the first reaction on `pending`, so no newer record can exist\n // yet. The returned promise still carries the rejection to every caller.\n pending.catch(() => {\n if (this.startInFlight === pending) this.startInFlight = undefined;\n });\n }\n return this.startInFlight;\n }\n\n private async runStart(): Promise<StartResult> {\n const result =\n (this.opts.connectFailure ?? \"rollback\") === \"isolate\"\n ? await this.connectIsolated()\n : await this.connectAllOrRollback();\n if (this.stopped) {\n // stop() ran while the connect was pending: it disconnected these adapters before their\n // connect settled, and a later stop() returns at its guard. Wiring them would leave a live\n // adapter on a stopped runner.\n await releaseAdapters(\n result.connected,\n \"releasing a start that stop() overtook\",\n this.redact,\n );\n this.connectedPlatforms.clear();\n this.startResult = { connected: [], failed: result.failed };\n return this.startResult;\n }\n this.wireInbound(result.connected);\n for (const a of result.connected) this.connectedPlatforms.add(a.platform);\n this.startResult = {\n connected: result.connected.map((a) => a.platform),\n failed: result.failed,\n };\n for (const adapter of result.retryable) {\n const policy = this.opts.reconnect;\n if (policy === undefined) break;\n this.scheduleReconnect(adapter, 1, new ReconnectBackoff(policy));\n }\n return this.startResult;\n }\n\n /** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */\n private scheduleReconnect(\n adapter: BasePlatformAdapter,\n attempt: number,\n backoff: ReconnectBackoff,\n ): void {\n const policy = this.opts.reconnect;\n if (policy === undefined || this.stopped) return;\n const delay = backoff.nextDelayMs();\n if (delay === undefined) {\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" gave up reconnecting after ${policy.maxAttempts} attempts\\n`,\n );\n return;\n }\n const timer = setTimeout(() => {\n this.retryTimers.delete(timer);\n void this.reconnectOnce(adapter, attempt, backoff);\n }, delay);\n // A pending retry must not keep the process alive on its own; `stop()` clears it anyway.\n timer.unref();\n this.retryTimers.add(timer);\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" reconnect attempt ${attempt} in ${delay}ms\\n`,\n );\n this.emitState(adapter.platform, \"retrying\", `reconnect attempt ${attempt} in ${delay}ms`);\n }\n\n private async reconnectOnce(\n adapter: BasePlatformAdapter,\n attempt: number,\n backoff: ReconnectBackoff,\n ): Promise<void> {\n if (this.stopped) return;\n try {\n if (await adapter.connect()) {\n if (this.stopped) {\n await releaseAdapters(\n [adapter],\n \"releasing a reconnect that stop() overtook\",\n this.redact,\n );\n return;\n }\n this.wireInbound([adapter]);\n this.connectedPlatforms.add(adapter.platform);\n this.emitState(adapter.platform, \"connected\");\n const prev = this.startResult ?? { connected: [], failed: [] };\n this.startResult = {\n connected: [...prev.connected, adapter.platform],\n failed: prev.failed.filter((f) => f.platform !== adapter.platform),\n };\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" connected on attempt ${attempt}\\n`,\n );\n return;\n }\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" refused to connect; not retrying\\n`,\n );\n return;\n } catch (err) {\n const reason = connectFailureReason({ status: \"rejected\", reason: err }, this.redact);\n if (isTerminalConnectError(err)) {\n this.emitState(adapter.platform, \"failed\", reason);\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" credentials rejected: ${reason}; not retrying\\n`,\n );\n return;\n }\n process.stderr.write(\n `[gateway] adapter \"${adapter.platform}\" reconnect attempt ${attempt} failed: ${reason}\\n`,\n );\n }\n this.scheduleReconnect(adapter, attempt + 1, backoff);\n }\n\n /**\n * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow\n * the first failure. Every connect settles before the rollback: rolling back while one is still\n * pending left that adapter live once it connected.\n */\n private async connectAllOrRollback(): Promise<ConnectOutcome> {\n const adapters = this.opts.adapters;\n // In the order they occur. Its length decides, never a value's truthiness, so a connect that\n // rejects with `undefined` still rolls back.\n const failures: unknown[] = [];\n const settled = await Promise.allSettled(\n adapters.map(async (a) => {\n let ok: boolean;\n try {\n // Inside the `try`, a `connect()` that throws before returning a promise lands here too.\n ok = await a.connect();\n } catch (err) {\n failures.push(err);\n throw err;\n }\n if (!ok) {\n const refusal = new Error(`adapter \"${a.platform}\" connect returned false`);\n failures.push(refusal);\n throw refusal;\n }\n }),\n );\n if (failures.length > 0) {\n // \"fulfilled\" means connected: a refusal and a throw both reject their wrapper.\n const connected = adapters.filter((_, i) => settled[i]?.status === \"fulfilled\");\n await releaseAdapters(connected, \"rolling back a failed start\", this.redact);\n throw failures[0];\n }\n return { connected: [...adapters], failed: [], retryable: [] };\n }\n\n /**\n * Connect every adapter and keep the ones that connected. The `async` wrapper turns a\n * synchronous throw inside `connect()` into a rejection `allSettled` sees; a bare\n * `a => a.connect()` would let it escape `map` and reject `start()` itself.\n */\n private async connectIsolated(): Promise<ConnectOutcome> {\n const adapters = this.opts.adapters;\n const results = await Promise.all(adapters.map((a) => this.connectOne(a)));\n const connected: BasePlatformAdapter[] = [];\n const failed: StartResult[\"failed\"][number][] = [];\n const retryable: BasePlatformAdapter[] = [];\n for (const r of results) {\n if (r.failure === undefined) connected.push(r.adapter);\n else failed.push(r.failure);\n if (r.retry) retryable.push(r.adapter);\n }\n return { connected, failed, retryable };\n }\n\n /** Connect one adapter, bounded by `connectTimeoutMs`, and report its state as it settles. */\n private async connectOne(adapter: BasePlatformAdapter): Promise<IsolatedResult> {\n const attempt = Promise.allSettled([(async () => adapter.connect())()]).then(\n ([r]) => r as PromiseSettledResult<boolean>,\n );\n const ms = this.opts.connectTimeoutMs;\n if (ms === undefined) return this.classify(adapter, await attempt);\n let timer: NodeJS.Timeout | undefined;\n const first = await Promise.race([\n attempt,\n new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), ms);\n }),\n ]);\n if (timer !== undefined) clearTimeout(timer);\n if (first !== \"timeout\") return this.classify(adapter, first);\n void attempt.then((late) => this.releaseLateConnect(adapter, late));\n const reason = `connect timed out after ${ms}ms`;\n this.emitState(adapter.platform, \"timed_out\", reason);\n return { adapter, failure: { platform: adapter.platform, reason }, retry: true };\n }\n\n /** A connect that finished after the runner gave up on it must not stay connected unseen. */\n private releaseLateConnect(\n adapter: BasePlatformAdapter,\n late: PromiseSettledResult<boolean>,\n ): void {\n if (late.status !== \"fulfilled\" || !late.value) return;\n if (this.connectedPlatforms.has(adapter.platform)) return; // a retry connected it meanwhile\n void releaseAdapters([adapter], \"releasing a connect that timed out\", this.redact);\n }\n\n private classify(\n adapter: BasePlatformAdapter,\n outcome: PromiseSettledResult<boolean>,\n ): IsolatedResult {\n if (outcome.status === \"fulfilled\" && outcome.value) {\n this.connectedPlatforms.add(adapter.platform);\n this.emitState(adapter.platform, \"connected\");\n return { adapter, failure: undefined, retry: false };\n }\n const reason = connectFailureReason(outcome, this.redact);\n this.emitState(adapter.platform, \"failed\", reason);\n const retry = outcome.status === \"rejected\" && !isTerminalConnectError(outcome.reason);\n return { adapter, failure: { platform: adapter.platform, reason }, retry };\n }\n\n private wireInbound(adapters: ReadonlyArray<BasePlatformAdapter>): void {\n for (const a of 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, a);\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 }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E). A disconnect that fails does not make `stop()`\n * reject and does not stop the other disconnects; it is written to stderr, redacted, naming the\n * platform.\n *\n * An adapter still connecting under an in-flight start is released when that start settles;\n * `stop()` does not wait for it.\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 for (const t of this.retryTimers) clearTimeout(t);\n this.retryTimers.clear();\n this.connectedPlatforms.clear();\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 releaseAdapters([...new Set(this.opts.adapters)], \"stopping the runner\", this.redact);\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, adapter: BasePlatformAdapter): Promise<void> {\n const ctx = this.buildContext(event, adapter);\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 // Reported as a handler error is (EC-F): post_outbound never fires for a rejected send.\n await ctx.reply(decision.message).catch(async (err) => {\n const error = err as Error;\n await this.hookExecutor.fireOnError({ event, error });\n process.stderr.write(`[gateway] auto-reply error: ${this.redact(error.message)}\\n`);\n });\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 const stopTyping = keepTyping(adapter, event.channel.id);\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: ${this.redact((err as Error).message)}\\n`);\n } finally {\n await stopTyping();\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, adapter: BasePlatformAdapter): GatewayContext {\n return {\n event,\n reply: async (text, opts) =>\n this.deliver(event, adapter, {\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n ...attachmentsOf(opts?.attachments),\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 * An outbound with attachments for an adapter that does not declare `supportsAttachments` is\n * refused here as `attachments_unsupported`, with no `sendMessage` call, so an adapter that\n * ignores the field cannot drop the image and report success (B-674).\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 adapter: BasePlatformAdapter | undefined,\n outbound: OutboundMessage,\n ): Promise<SendResult> {\n // The receiving adapter answers, but only for its own platform's events.\n const target = adapter?.platform === event.platform ? adapter : undefined;\n const result: SendResult =\n target === undefined\n ? { ok: false, error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` } }\n : (refuseUnsupportedAttachments(target, outbound) ?? (await target.sendMessage(outbound)));\n await this.hookExecutor.firePostOutbound({ event, outbound, result });\n return result;\n }\n}\n","/**\n * `withMediaUnderstanding`: folds a voice note's transcript (and, once events carry them, an\n * image's description) into the turn text. The gateway makes no model or network call; the\n * caller supplies the functions.\n */\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\nimport type { GatewayHandler } from \"./gateway-runner.js\";\n\n/** Options for `withMediaUnderstanding`: the functions that understand media, a size cap and a failure sink. */\nexport interface MediaUnderstandingOptions {\n /** e.g. plugin-voice's transcribe, bound to its config. */\n transcribe?(audio: { data: Uint8Array; mediaType: string }): Promise<string>;\n /** Called for each image an event carries, once inbound images exist. */\n describeImage?(image: { data: Uint8Array; mediaType: string }): Promise<string>;\n /** Largest payload sent to a function. Default 20 MiB; larger is reported as not understood. */\n readonly maxBytes?: number;\n /** Where a failure is reported, with the media type and the error name only. */\n readonly write?: (line: string) => void;\n}\n\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024;\n\nfunction sanitizeType(mediaType: string): string {\n return mediaType.replace(/[^\\w/.+-]/g, \"\");\n}\n\nfunction errorName(error: unknown): string {\n return error instanceof Error ? error.name : \"UnknownError\";\n}\n\n/** Wraps a handler: the event it receives has the transcript or description appended to text. */\nexport function withMediaUnderstanding(\n handler: GatewayHandler,\n options: MediaUnderstandingOptions,\n): GatewayHandler {\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n const write = options.write ?? ((line: string) => void process.stderr.write(`${line}\\n`));\n\n const understand = async (\n kind: \"Audio transcript\" | \"Image description\",\n media: { data: Uint8Array; mediaType: string },\n fn: ((m: { data: Uint8Array; mediaType: string }) => Promise<string>) | undefined,\n ): Promise<string> => {\n const type = sanitizeType(media.mediaType);\n if (fn === undefined) return `[Attachment of type ${type} not understood]`;\n const failed = `[Attachment of type ${type} could not be understood]`;\n if (media.data.byteLength > maxBytes) {\n report(type, \"TooLarge\");\n return failed;\n }\n try {\n const text = await fn({ data: media.data, mediaType: media.mediaType });\n return `[${kind}: ${text}]`;\n } catch (error) {\n report(type, errorName(error));\n return failed;\n }\n };\n\n const report = (type: string, name: string): void => {\n try {\n write(`[gateway] media understanding failed for ${type}: ${name}`);\n } catch {\n // a failing sink never fails the turn\n }\n };\n\n return async (event, ctx) => {\n const lines: string[] = [];\n if (event.audio !== undefined) {\n lines.push(\n await understand(\"Audio transcript\", event.audio, options.transcribe?.bind(options)),\n );\n }\n if (lines.length === 0) return handler(event, ctx);\n const text = [event.text, ...lines].filter((part) => part !== \"\").join(\"\\n\");\n const wrapped: GatewayMessageEvent = { ...event, text };\n return handler(wrapped, ctx);\n };\n}\n","/**\n * A small key/value store for credentials an adapter must keep across restarts, such as a rotated\n * OAuth refresh token.\n *\n * @public\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { chmod, mkdir, readFile, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\n\n/** Reads and writes one string credential per key. @public */\nexport interface CredentialStore {\n /** The stored value, or `undefined` when the key was never set. */\n get(key: string): Promise<string | undefined>;\n /** Store `value` under `key`, replacing any earlier value. */\n set(key: string, value: string): Promise<void>;\n}\n\nconst KEY_PATTERN = /^[A-Za-z0-9._:-]+$(?![\\s\\S])/;\n\nfunction fileFor(dir: string, key: string): string {\n // `.` and `..` name the directory itself or its parent.\n if (!KEY_PATTERN.test(key) || key === \".\" || key === \"..\") {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"invalid_credential_key\",\n message: `gateway: invalid_credential_key (keys match [A-Za-z0-9._:-]+): ${JSON.stringify(key)}`,\n });\n }\n return join(dir, key.replaceAll(\":\", \"%3A\"));\n}\n\n/** One file per key under `dir`, mode 0600, written to a temp file and renamed. @public */\nexport function createFileCredentialStore(dir: string): CredentialStore {\n return {\n async get(key) {\n const path = fileFor(dir, key);\n try {\n return await readFile(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"credential_store_unreadable\",\n message: `gateway: credential_store_unreadable: ${path}`,\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n },\n async set(key, value) {\n const path = fileFor(dir, key);\n await mkdir(dir, { recursive: true });\n const tmp = `${path}.${randomBytes(6).toString(\"hex\")}.tmp`;\n try {\n await writeFile(tmp, value, { mode: 0o600 });\n await chmod(tmp, 0o600);\n await rename(tmp, path);\n } catch (err) {\n await unlink(tmp).catch(() => undefined);\n throw err;\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. Escapes ids (`_` to `__`, `-` to `_d`) so the format\n * remains splittable on `-` and distinct ids never share a key.\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\nexport function sanitize(s: string): string {\n // Injective: every `_` in the output is followed by `_` or `d`.\n return s.replace(/_/g, \"__\").replace(/-/g, \"_d\");\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 * Rule-based agent bindings: pick the agent that answers a message by\n * platform, account and peer.\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport type { MessageEvent, PlatformName } from \"../types/message-event.js\";\nimport { type AgentIdStrategy, sanitize } from \"./router.js\";\n\nexport interface AgentBindingRule {\n readonly agent: string;\n readonly platform?: PlatformName;\n /** Matched against accountOf(event). */\n readonly account?: string;\n /** Matched against event.sender.id for a DM and event.channel.id otherwise. */\n readonly peer?: string;\n}\n\n/** Options for {@link createAgentBindings}. */\nexport interface AgentBindingsOptions {\n readonly defaultAgent: string;\n readonly rules: ReadonlyArray<AgentBindingRule>;\n /** Agents that exist; every rule and the default must name one. */\n readonly agents: ReadonlyArray<string>;\n /** Which bot account received the event, when the app runs several. Default: undefined. */\n readonly accountOf?: (event: MessageEvent) => string | undefined;\n}\n\n/** Chooses the agent that answers an event. */\nexport interface AgentBindings {\n agentFor(event: MessageEvent): string;\n}\n\nfunction unknownAgent(agent: string): GatewayConfigurationError {\n return new GatewayConfigurationError(\"gateway\", {\n code: \"unknown_agent\",\n message: `gateway: unknown_agent: ${agent}`,\n detail: agent,\n });\n}\n\n/**\n * Builds bindings from rules. The most specific matching rule wins (peer 4, account 2,\n * platform 1), ties go to the earlier rule, no match gives `defaultAgent`.\n * Throws `GatewayConfigurationError` for `unknown_agent` or `empty_binding_rule`.\n */\nexport function createAgentBindings(options: AgentBindingsOptions): AgentBindings {\n const known = new Set(options.agents);\n if (!known.has(options.defaultAgent)) throw unknownAgent(options.defaultAgent);\n for (const rule of options.rules) {\n if (!known.has(rule.agent)) throw unknownAgent(rule.agent);\n if (rule.platform === undefined && rule.account === undefined && rule.peer === undefined) {\n throw new GatewayConfigurationError(\"gateway\", {\n code: \"empty_binding_rule\",\n message: `gateway: empty_binding_rule: ${rule.agent}`,\n detail: rule.agent,\n });\n }\n }\n const rules = [...options.rules];\n const { accountOf } = options;\n\n return {\n agentFor(event) {\n const ctx = {\n platform: event.platform as string,\n account: accountOf?.(event),\n peer: event.channel.type === \"dm\" ? event.sender.id : event.channel.id,\n };\n let best = options.defaultAgent;\n let bestScore = 0;\n for (const rule of rules) {\n const score = scoreRule(rule, ctx);\n if (score > bestScore) {\n best = rule.agent;\n bestScore = score;\n }\n }\n return best;\n },\n };\n}\n\ninterface MatchContext {\n readonly platform: string;\n readonly account: string | undefined;\n readonly peer: string;\n}\n\n/** 0 when the rule does not match; otherwise peer 4 + account 2 + platform 1 for the fields it sets. */\nfunction scoreRule(rule: AgentBindingRule, ctx: MatchContext): number {\n const fields: ReadonlyArray<readonly [string | undefined, string | undefined, number]> = [\n [rule.platform, ctx.platform, 1],\n [rule.account, ctx.account, 2],\n [rule.peer, ctx.peer, 4],\n ];\n let score = 0;\n for (const [want, got, weight] of fields) {\n if (want === undefined) continue;\n if (want !== got) return 0;\n score += weight;\n }\n return score;\n}\n\n/** Prefixes another strategy's key with the bound agent, so two agents never share a session. */\nexport function bindingStrategy(bindings: AgentBindings, inner: AgentIdStrategy): AgentIdStrategy {\n return (event) => `${sanitize(bindings.agentFor(event))}-${inner(event)}`;\n}\n","/**\n * `scopedStrategy` — session keys with DM scopes, peer links and account labels.\n *\n * `dm` is always the second key segment, so no label or peer name can make a\n * DM key equal a group (`grp`) or thread (`tpc`) key. Every segment is encoded\n * with `encodeURIComponent` and joined with `:`, which it never emits, so the\n * key mapping is injective. Linked peers and `main` use a leading `@` segment,\n * which no encoded platform can start with (`@` encodes to `%40`).\n *\n * @public\n */\n\nimport { GatewayConfigurationError } from \"../errors/config-error.js\";\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\nimport { type AgentIdStrategy, sanitize } from \"./router.js\";\n\n/** How DMs are keyed: one conversation, per peer, per channel and peer, or per account too. */\nexport type DmScope = \"main\" | \"per-peer\" | \"per-channel-peer\" | \"per-account-channel-peer\";\n\n/** Options for {@link scopedStrategy}. */\nexport interface ScopedStrategyOptions {\n readonly dmScope: DmScope;\n /** `<platform>:<senderId>` to a peer name. Used by `per-peer`. */\n readonly peerLinks?: ReadonlyMap<string, string>;\n /** Required when `dmScope` is `per-account-channel-peer`. */\n readonly accountLabel?: string;\n /** Group key: one per channel (default) or one per channel and sender. */\n readonly groupScope?: \"channel\" | \"channel-sender\";\n}\n\nconst join = (...segments: readonly string[]): string => segments.map(sanitize).join(\"-\");\n\nfunction invalid(message: string, detail?: string): GatewayConfigurationError {\n return new GatewayConfigurationError(\"gateway\", {\n code: \"invalid_session_scope\",\n message: `gateway: invalid_session_scope: ${message}`,\n ...(detail === undefined ? {} : { detail }),\n });\n}\n\n/**\n * Builds a strategy for the chosen DM scope. Keys:\n * `main` → `_m-dm`; `per-peer` linked → `_p-dm-<peer>`, unlinked → the\n * per-channel-peer key; `per-channel-peer` → `<platform>-dm-<sender>`;\n * `per-account-channel-peer` → `<platform>-dm-<account>-<sender>`.\n * Groups are `<platform>-grp-<channel>[-<sender>]`, topic threads\n * `<platform>-tpc-<channel>-<topic>`. Every segment is escaped with `sanitize`.\n * Throws `GatewayConfigurationError` (`invalid_session_scope`) on bad options, never per event.\n */\nexport function scopedStrategy(options: ScopedStrategyOptions): AgentIdStrategy {\n const { dmScope, peerLinks, accountLabel, groupScope = \"channel\" } = options;\n if (\n dmScope === \"per-account-channel-peer\" &&\n (accountLabel === undefined || accountLabel === \"\")\n ) {\n throw invalid(\"per-account-channel-peer requires a non-empty accountLabel\", \"accountLabel\");\n }\n if (peerLinks !== undefined) {\n for (const [from, peer] of peerLinks) {\n if (peer === \"\") throw invalid(`empty peer name for ${from}`, from);\n }\n }\n\n const dmKey = (platform: string, senderId: string): string => {\n switch (dmScope) {\n case \"main\":\n return \"_m-dm\";\n case \"per-peer\": {\n const peer = peerLinks?.get(`${platform}:${senderId}`);\n return peer === undefined ? join(platform, \"dm\", senderId) : `_p-dm-${sanitize(peer)}`;\n }\n case \"per-channel-peer\":\n return join(platform, \"dm\", senderId);\n case \"per-account-channel-peer\":\n return join(platform, \"dm\", accountLabel ?? \"\", senderId);\n }\n };\n\n return (event: GatewayMessageEvent): string => {\n const { platform, channel, sender } = event;\n if (channel.type === \"dm\") return dmKey(platform, sender.id);\n if (channel.type === \"thread\" && channel.topicId !== undefined) {\n return join(platform, \"tpc\", channel.id, channel.topicId);\n }\n return groupScope === \"channel-sender\"\n ? join(platform, \"grp\", channel.id, sender.id)\n : join(platform, \"grp\", channel.id);\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\nimport { type FenceRegion, fenceAt, openerEol, scanFences } from \"./fence.js\";\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 * When true, a cut that would fall inside a Markdown table row (a line whose first non-blank\n * character is `|`) moves back to the start of that row, provided the row fits in the window and\n * does not open the chunk; the row then opens the next chunk whole and byte-identical (B-556).\n * A row longer than the window is cut by length as before. Text with no table row splits exactly\n * as without the option. Default: `false`.\n */\n readonly keepTableRows?: 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`, or `\\r` alone or before `\\n`: GFM reads a lone CR as a line ending too. */\nconst isLineEnd = (ch: string | undefined): boolean => ch === \"\\n\" || ch === \"\\r\";\n\n/** True when the line starting at `from` is a table row: optional blanks, then a pipe. */\nfunction startsTableRow(text: string, from: number): boolean {\n let at = from;\n while (at < text.length && /^[^\\S\\r\\n]$/.test(text[at] ?? \"\")) at += 1;\n return text[at] === \"|\";\n}\n\n/**\n * Where to cut instead of `cut` so a table row it falls inside stays whole: `start` is the row's\n * first character (the next chunk begins there), `end` is where this chunk ends, its trailing line\n * endings dropped. Undefined when `cut` is not inside a row, the row opens the chunk, or the row\n * does not fit in `window`.\n */\nfunction rowSafeCut(\n text: string,\n cut: number,\n window: number,\n): { readonly end: number; readonly start: number } | undefined {\n const start = tableRowStart(text, cut);\n if (start === undefined || rowLength(text, start, cut, window) > window) return undefined;\n let end = start;\n while (end > 0 && isLineEnd(text[end - 1])) end -= 1;\n return end > 0 ? { end, start } : undefined;\n}\n\n/** Start of the table row `cut` falls inside, or undefined (not in a row, or the row opens the text). */\nfunction tableRowStart(text: string, cut: number): number | undefined {\n if (cut >= text.length || isLineEnd(text[cut])) return undefined;\n let start = cut;\n while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;\n return start > 0 && startsTableRow(text, start) ? start : undefined;\n}\n\n/** Length of the row from `start`, scanning no further than `window` past it. */\nfunction rowLength(text: string, start: number, cut: number, window: number): number {\n let rowEnd = cut;\n while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;\n return rowEnd - start;\n}\n\n/** What one fence-aware cut does: the chunk to emit and the text that remains. */\ninterface CutStep {\n readonly chunk: string;\n readonly remaining: string;\n}\n\n/** The table-row cut as a step, undefined when the cut is not inside a row that fits. */\nfunction rowStep(remaining: string, cut: number, window: number): CutStep | undefined {\n const moved = rowSafeCut(remaining, cut, window);\n if (moved === undefined) return undefined;\n return { chunk: remaining.slice(0, moved.end), remaining: remaining.slice(moved.start) };\n}\n\n/** A cut in a fence's opening line moves back to the fence start; undefined when nothing precedes it. */\nfunction stepBeforeFence(remaining: string, region: FenceRegion): CutStep | undefined {\n let end = region.start;\n while (end > 0 && isLineEnd(remaining[end - 1])) end -= 1;\n if (end === 0) return undefined;\n return { chunk: remaining.slice(0, end), remaining: remaining.slice(region.start) };\n}\n\n/** Close `region` at the end of the chunk and reopen it, opening line and all, at the start of the next. */\nfunction stepThroughFence(\n remaining: string,\n region: FenceRegion,\n window: number,\n surrogateGuard: boolean,\n): CutStep | undefined {\n const eol = openerEol(remaining, region);\n const room = window - region.closer.length - eol.length;\n if (room <= region.contentStart) return undefined;\n let at = remaining.lastIndexOf(\"\\n\", room);\n let rest = at + 1;\n if (at < region.contentStart) {\n at = surrogateGuard ? guardSurrogate(remaining, room) : room;\n rest = at;\n } else if (remaining[at - 1] === \"\\r\") {\n at -= 1;\n }\n return {\n chunk: `${remaining.slice(0, at)}${eol}${region.closer}`,\n remaining: `${region.opener}${eol}${remaining.slice(rest)}`,\n };\n}\n\n/**\n * The cut for a position inside a fenced block (B-518): out of the opening line, or closed and\n * reopened at a line end when one fits, so no code line is split. Undefined when `cut` is not inside\n * a fence or no room is left for the closing marker, and the caller cuts as it would without fences.\n */\nfunction fenceStep(\n remaining: string,\n cut: number,\n window: number,\n surrogateGuard: boolean,\n): CutStep | undefined {\n const region = fenceAt(scanFences(remaining), cut);\n if (region === undefined) return undefined;\n return cut <= region.openerEnd\n ? stepBeforeFence(remaining, region)\n : stepThroughFence(remaining, region, window, surrogateGuard);\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 keepTableRows = 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 const hasFence = scanFences(text).length > 0;\n let remaining = text;\n while (remaining.length > safeLimit) {\n const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);\n const step = (hasFence ? fenceStep(remaining, cut, safeLimit, surrogateGuard) : undefined) ??\n (keepTableRows ? rowStep(remaining, cut, safeLimit) : undefined) ?? {\n chunk: remaining.slice(0, cut),\n remaining: remaining.slice(cut).replace(stripLeading, \"\"),\n };\n parts.push(step.chunk);\n remaining = step.remaining;\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 regions = scanFences(text);\n if (regions.length > 0) return chunkFencedByGrapheme(text, partLimit, regions);\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/** Finds the grapheme starts of `text`: the largest in `(pos, max]`, else the next one past `pos`. */\nfunction graphemeBoundaries(text: string): (pos: number, max: number) => number {\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const starts = Array.from(segmenter.segment(text), (s) => s.index);\n starts.push(text.length);\n return (pos, max) => {\n const after = starts.filter((b) => b > pos);\n const within = after.filter((b) => b <= max);\n return within.at(-1) ?? after[0] ?? text.length;\n };\n}\n\n/** How a part ends and the next begins: the closing marker, and the opening line to put back. */\ninterface GraphemeCut {\n readonly cut: number;\n readonly suffix: string;\n readonly reopen: string;\n}\n\n/**\n * The grapheme walk when `text` holds a fence (B-518): a part cut inside a fenced block ends with the\n * closing marker and the next opens with the opening line again. A cut falls at a line end when one\n * fits. Text with no fence never reaches here.\n */\nfunction chunkFencedByGrapheme(\n text: string,\n partLimit: number,\n regions: readonly FenceRegion[],\n): string[] {\n const boundaryUpTo = graphemeBoundaries(text);\n const parts: string[] = [];\n let pos = 0;\n let prefix = \"\";\n while (prefix.length + (text.length - pos) > partLimit) {\n const room = partLimit - prefix.length;\n const plain = boundaryUpTo(pos, pos + room);\n const region = fenceAt(regions, plain);\n const next: GraphemeCut =\n region === undefined\n ? { cut: plain, suffix: \"\", reopen: \"\" }\n : fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo);\n parts.push(prefix + text.slice(pos, next.cut) + next.suffix);\n pos = next.cut;\n prefix = next.reopen;\n }\n parts.push(prefix + text.slice(pos));\n return parts;\n}\n\n/** The cut for `plain`, a grapheme cut that falls inside `region`. */\nfunction fenceGraphemeCut(\n text: string,\n region: FenceRegion,\n pos: number,\n plain: number,\n room: number,\n boundaryUpTo: (pos: number, max: number) => number,\n): GraphemeCut {\n const none: GraphemeCut = { cut: plain, suffix: \"\", reopen: \"\" };\n if (plain <= region.openerEnd) {\n return region.start > pos ? { ...none, cut: region.start } : none;\n }\n const eol = openerEol(text, region);\n const max = pos + room - region.closer.length - eol.length;\n const floor = Math.max(pos, region.contentStart);\n if (max <= floor) return none;\n let at = boundaryUpTo(pos, max);\n const nl = text.lastIndexOf(\"\\n\", at - 1);\n if (nl >= floor - 1 && nl + 1 > pos) at = nl + 1;\n if (at <= pos || at > max) return none;\n if (fenceAt([region], at) === undefined) return { ...none, cut: at };\n const closes = isLineEnd(text[at - 1]);\n return { cut: at, suffix: (closes ? \"\" : eol) + region.closer, reopen: region.opener + eol };\n}\n","/**\n * Grapheme-safe splitting of long text that keeps Markdown table rows whole (B-556).\n *\n * @internal\n */\n\n/** A blank that may precede a row's leading pipe: whitespace other than a line ending. */\nconst ROW_BLANK = /^[^\\S\\r\\n]$/;\n\n/** `\\n`, or `\\r` alone or before `\\n`: GFM reads a lone CR as a line ending too. */\nfunction isLineEnd(character: string | undefined): boolean {\n return character === \"\\n\" || character === \"\\r\";\n}\n\n/**\n * True when the line starting at `from` is a table row: optional blanks, then a pipe. The same\n * definition lives in core `ROW_START` (packages/gateway/src/text/dialect.ts) and in the\n * gateway-nextcloud-talk splitter.\n */\nfunction startsTableRow(text: string, from: number): boolean {\n let at = from;\n while (at < text.length && ROW_BLANK.test(text[at] ?? \"\")) at += 1;\n return text[at] === \"|\";\n}\n\n/** Start of the line holding `cut - 1`, or `partStart` when the line starts at or before it. */\nfunction lineStartBefore(text: string, cut: number, partStart: number): number {\n let at = cut;\n while (at > partStart && !isLineEnd(text[at - 1])) at -= 1;\n return at;\n}\n\n/** End of the line holding `cut`, without its line ending, scanning no further than `bound`. */\nfunction lineEndFrom(text: string, cut: number, bound: number): number {\n let at = cut;\n while (at < text.length && at <= bound && !isLineEnd(text[at])) at += 1;\n return at;\n}\n\n/** The unit `partLimit` is measured in. */\nexport interface SplitKeepingRowsOptions {\n /** How `partLimit` is measured. Default \"utf16\" (UTF-16 units). */\n readonly unit?: \"utf16\" | \"codepoint\";\n}\n\n/** The offset reached by moving `count` units on from `from`, or `text.length` when the text ends first. */\nfunction advance(text: string, from: number, count: number, codepoint: boolean): number {\n if (!codepoint) return Math.min(from + count, text.length);\n let at = from;\n for (let left = count; left > 0 && at < text.length; left -= 1) {\n at += (text.codePointAt(at) ?? 0) > 0xffff ? 2 : 1;\n }\n return at;\n}\n\n/**\n * The cut to use instead of `cut`: the start of the table row `cut` falls inside, when that row\n * starts after `partStart` and fits in `partLimit` without its line ending; `cut` otherwise. A row\n * that opens the part, or is longer than a part, is cut by length as before (FR-007).\n */\nfunction rowSafeCut(\n text: string,\n partStart: number,\n cut: number,\n partLimit: number,\n codepoint: boolean,\n): number {\n const lineStart = lineStartBefore(text, cut, partStart);\n if (lineStart <= partStart || lineStart === cut) return cut;\n if (isLineEnd(text[cut]) || !startsTableRow(text, lineStart)) return cut;\n const bound = advance(text, lineStart, partLimit, codepoint);\n return lineEndFrom(text, cut, bound) <= bound ? lineStart : cut;\n}\n\n/**\n * The last grapheme boundary at or below `limitCut`. When one grapheme starting at `start` is\n * longer than the part, its end: the oversized part `chunkByGrapheme` emits (ADR D3).\n */\nfunction graphemeCut(segments: Intl.Segments, start: number, limitCut: number): number {\n const segment = segments.containing(limitCut);\n if (segment === undefined || segment.index >= limitCut) return limitCut;\n return segment.index > start ? segment.index : segment.index + segment.segment.length;\n}\n\n/** The requested unit as a code-point flag; throws `RangeError` for a bad unit or limit. */\nfunction readUnit(partLimit: number, options: SplitKeepingRowsOptions): boolean {\n const unit: unknown = options.unit ?? \"utf16\";\n if (unit !== \"utf16\" && unit !== \"codepoint\") {\n throw new RangeError(\n `splitKeepingRows: unit must be \"utf16\" or \"codepoint\", got ${String(unit)}`,\n );\n }\n if (unit === \"codepoint\" && !(Number.isInteger(partLimit) && partLimit > 0)) {\n throw new RangeError(\n `splitKeepingRows: partLimit must be a positive integer, got ${partLimit}`,\n );\n }\n return unit === \"codepoint\";\n}\n\n/**\n * Parts of at most `partLimit` units (UTF-16 units, or code points with `unit: \"codepoint\"`), cut\n * at grapheme boundaries and before straddled rows. Shared by the SMS and LINE splitters (text no\n * longer than a part is theirs to handle). In code-point mode `partLimit` must be a positive\n * integer and a single grapheme longer than it throws `RangeError`.\n */\nexport function splitKeepingRows(\n text: string,\n partLimit: number,\n options: SplitKeepingRowsOptions = {},\n): string[] {\n const codepoint = readUnit(partLimit, options);\n const segments = new Intl.Segmenter(undefined, { granularity: \"grapheme\" }).segment(text);\n const parts: string[] = [];\n let start = 0;\n let limitCut = advance(text, start, partLimit, codepoint);\n while (limitCut < text.length) {\n const grapheme = graphemeCut(segments, start, limitCut);\n if (codepoint && grapheme > limitCut) {\n throw new RangeError(\n `splitKeepingRows: a grapheme at offset ${start} is longer than ${partLimit} code points`,\n );\n }\n const cut = rowSafeCut(text, start, grapheme, partLimit, codepoint);\n /* c8 ignore next 3 -- unreachable: both cuts land after `start` (graphemeCut, rowSafeCut). */\n if (cut <= start) {\n throw new RangeError(`splitKeepingRows: no progress at offset ${start} of ${text.length}`);\n }\n parts.push(text.slice(start, cut));\n start = cut;\n limitCut = advance(text, start, partLimit, codepoint);\n }\n if (start < text.length) parts.push(text.slice(start));\n return parts;\n}\n","/** The outcome of delivering one event to the runner's handlers. */\ntype DeliverOutcome = \"ok\" | \"no_handler\" | \"handler_threw\";\n\n/**\n * Map the outcomes of one delivered batch to an HTTP status, worst wins: `handler_threw` is 500,\n * `no_handler` is 503 so the provider retries, `ok` and an empty batch are 200. An unknown outcome\n * throws instead of answering 200.\n */\nexport function statusForDeliver(outcomes: ReadonlyArray<DeliverOutcome>): 200 | 500 | 503 {\n let status: 200 | 500 | 503 = 200;\n for (const outcome of outcomes as ReadonlyArray<string>) {\n if (outcome === \"handler_threw\") {\n status = 500;\n } else if (outcome === \"no_handler\") {\n if (status === 200) status = 503;\n } else if (outcome !== \"ok\") {\n throw new Error(`unknown deliver outcome: ${outcome}`);\n }\n }\n return status;\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 * every adapter.\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 readonly headers?: Readonly<Record<string, string | string[] | undefined>>;\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 /** Where Express 4's `listen` reports a failure to bind; `http.Server` has it. */\n once?(event: \"error\", listener: (err: Error) => void): unknown;\n}\n\n/**\n * What can start a listener. Express's app satisfies it: Express 5 passes a failure to bind to the\n * callback, Express 4 only emits it on the returned server.\n */\nexport interface ListenableApp {\n listen(port: number, cb: (err?: Error) => 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 * A body larger than `maxBytes` is refused before it is held. `maxBytes` defaults to\n * {@link DEFAULT_WEBHOOK_MAX_BYTES} (1 MiB); pass `Number.POSITIVE_INFINITY` for no limit. The rest\n * of the stream is read and dropped, and once it ends the middleware answers 413 with the JSON body\n * `{ \"error\": \"request body too large\" }` itself; `next` is not called. The capture runs before\n * signature verification, so without a limit any client could stream a body until the heap runs out.\n * The refusal is answered here rather than handed to `next` as an error because Express's final\n * handler writes an error as an HTML page carrying its stack whenever `NODE_ENV` is not\n * `production`, and these routes answer anyone.\n *\n * The middleware settles once: after a refusal, more data, the end of the stream or a stream\n * error do nothing, and after a stream error the end of the stream does nothing.\n *\n * @param tag the package name for the diagnostic, so a reader knows which router is complaining\n * @param options `maxBytes`, the largest body accepted; 1 MiB when absent, `Infinity` for no limit\n * @throws RangeError when `maxBytes` is NaN or negative\n */\nexport function rawBodyCapture(tag: string, options: RawBodyCaptureOptions = {}) {\n const maxBytes = options.maxBytes ?? DEFAULT_WEBHOOK_MAX_BYTES;\n if (!(maxBytes >= 0)) {\n throw new RangeError(\n `[${tag}] rawBodyCapture: maxBytes must be a number of zero or more (Infinity allowed), got ${maxBytes}`,\n );\n }\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, rawRes: 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 let bytes = 0;\n // `refused` drops what is left of the body; `settled` keeps every path to one answer.\n let refused = declaredLength(req) > maxBytes;\n let settled = false;\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n if (refused || settled) return;\n bytes += Buffer.byteLength(chunk);\n if (bytes > maxBytes) {\n refused = true;\n buf = \"\";\n return;\n }\n buf += chunk;\n });\n req.on(\"end\", () => {\n if (settled) return;\n settled = true;\n if (refused) {\n answerTooLarge(rawRes as JsonResponse, tag, maxBytes);\n return;\n }\n (req as unknown as { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err: unknown) => {\n if (settled) return;\n settled = true;\n // A client that aborts a refused body has nobody left to answer.\n if (refused) return;\n next(err);\n });\n };\n}\n\n/** The body size {@link rawBodyCapture} accepts when `maxBytes` is not given: 1 MiB. */\nexport const DEFAULT_WEBHOOK_MAX_BYTES = 1024 * 1024;\n\n/** Options for {@link rawBodyCapture}. */\nexport interface RawBodyCaptureOptions {\n /** The largest body accepted, in bytes. A larger one is refused with 413. Defaults to\n * {@link DEFAULT_WEBHOOK_MAX_BYTES}; `Number.POSITIVE_INFINITY` removes the limit. */\n readonly maxBytes?: number;\n}\n\n/** The `content-length` the client declared, or 0 when it declared none or an unreadable one. */\nfunction declaredLength(req: RawBodyRequest): number {\n const value = req.headers?.[\"content-length\"];\n const declared = Number(Array.isArray(value) ? value[0] : value);\n return Number.isFinite(declared) ? declared : 0;\n}\n\n/** What the refusal writes to. Express's `Response` satisfies it. */\ninterface JsonResponse {\n status(code: number): { json(body: unknown): unknown };\n}\n\n/** Answer 413 as JSON, and say on stderr which router refused and at what limit. */\nfunction answerTooLarge(res: JsonResponse, tag: string, maxBytes: number): void {\n process.stderr.write(`[${tag}] refused a request (413): body larger than ${maxBytes} bytes\\n`);\n res.status(413).json({ error: \"request body too large\" });\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 *\n * `start()` rejects with the error the bind failed with (`EADDRINUSE` for a port another listener\n * holds), under Express 4 and 5 alike, and a later `start()` tries again.\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 // A port another process holds used to resolve this as started: Express 5 hands the bind\n // error to the callback, which ignored it, and `connect()` answered true over no listener.\n await new Promise<void>((resolve, reject) => {\n const settle = (err?: Error): void => {\n if (err === undefined) resolve();\n else reject(err);\n };\n const current = opts.app.listen(opts.port, settle);\n listener = current;\n current.once?.(\"error\", settle);\n }).catch((err: unknown) => {\n listener = undefined;\n throw err;\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","/**\n * `createWebhookHandler` — one Fetch `Request` to `Response` handler for every webhook channel.\n *\n * It routes by platform, caps the body, and answers with the descriptor's `handle`, or runs verify,\n * JSON.parse and ingest. No secret, header value or body reaches `onError` or a response.\n */\n\nimport type { BasePlatformAdapter } from \"../adapter/base.js\";\nimport type {\n ChannelWebhook,\n WebhookAnswer,\n WebhookRequest,\n} from \"../channel/channel-descriptor.js\";\nimport type { BuiltChannel } from \"../channel/create-channels.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\nimport { DEFAULT_WEBHOOK_MAX_BYTES } from \"./express-server.js\";\n\n/** Options for `createWebhookHandler`. */\nexport interface WebhookHandlerOptions {\n /** The built channels; only those with `transport: \"webhook\"` are routed. */\n readonly channels: ReadonlyArray<BuiltChannel>;\n /** Whether the platform's runner has started; a platform that has not answers 503. */\n readonly isStarted: (platform: PlatformName) => boolean;\n /** Body cap in bytes. Default 1 MiB. */\n readonly maxBodyBytes?: number;\n /** Default: the last path segment after `/webhooks/`. */\n readonly platformFor?: (url: URL) => PlatformName | undefined;\n /** Called when a handle/ingest throws; the response is 500 with no body. */\n readonly onError?: (platform: PlatformName, error: unknown) => void;\n}\n\nconst TOO_LARGE = Symbol(\"too-large\");\n\nfunction defaultPlatformFor(url: URL): PlatformName | undefined {\n const marker = \"/webhooks/\";\n const at = url.pathname.lastIndexOf(marker);\n if (at < 0) return undefined;\n const rest = url.pathname.slice(at + marker.length).replace(/\\/+$/, \"\");\n const last = rest.split(\"/\").pop();\n return last ? (last as PlatformName) : undefined;\n}\n\nfunction plain(status: number, extra?: Record<string, string>): Response {\n return new Response(null, { status, headers: extra });\n}\n\nfunction tooLarge(): Response {\n return plain(413, { connection: \"close\" });\n}\n\nasync function readCapped(request: Request, max: number): Promise<string | typeof TOO_LARGE> {\n const declared = request.headers.get(\"content-length\");\n if (declared !== null && Number(declared) > max) return TOO_LARGE;\n if (request.body === null) return \"\";\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > max) {\n await reader.cancel().catch(() => undefined);\n return TOO_LARGE;\n }\n chunks.push(value);\n }\n const joined = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n joined.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return new TextDecoder().decode(joined);\n}\n\nfunction answerResponse(answer: WebhookAnswer): Response {\n const headers: Record<string, string> = {};\n if (answer.contentType !== undefined) headers[\"content-type\"] = answer.contentType;\n return new Response(answer.body ?? null, { status: answer.status, headers });\n}\n\nasync function runDefault(\n webhook: ChannelWebhook<BasePlatformAdapter>,\n adapter: BasePlatformAdapter,\n request: WebhookRequest,\n): Promise<Response> {\n if (!(await webhook.verify(adapter, request))) return plain(401);\n let payload: unknown;\n try {\n payload = JSON.parse(request.rawBody);\n } catch {\n return plain(400);\n }\n const result = await webhook.ingest(adapter, payload);\n if (result === \"delivered\") return plain(200);\n return plain(result === \"no_handler\" ? 503 : 400);\n}\n\nfunction headersOf(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n request.headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\nasync function readBody(request: Request, max: number): Promise<string | Response> {\n let body: string | typeof TOO_LARGE;\n try {\n body = await readCapped(request, max);\n } catch {\n return plain(400);\n }\n return body === TOO_LARGE ? tooLarge() : body;\n}\n\n/**\n * Build a Fetch handler for every `transport: \"webhook\"` channel in `channels`: 404 for an unknown\n * platform, 503 while it has not started, 405 for a method the route does not take, 413 past the\n * body cap, 400 for an unreadable body, and 500 with no body when a route throws.\n */\nexport function createWebhookHandler(\n options: WebhookHandlerOptions,\n): (request: Request) => Promise<Response> {\n const max = options.maxBodyBytes ?? DEFAULT_WEBHOOK_MAX_BYTES;\n const platformFor = options.platformFor ?? defaultPlatformFor;\n const routes = new Map<PlatformName, BuiltChannel>();\n for (const channel of options.channels) {\n if (channel.descriptor.transport === \"webhook\")\n routes.set(channel.descriptor.platform, channel);\n }\n const route = (url: URL): BuiltChannel | undefined => {\n const platform = platformFor(url);\n return platform === undefined ? undefined : routes.get(platform);\n };\n return async (request) => {\n const channel = route(new URL(request.url));\n if (channel === undefined) return plain(404);\n const platform = channel.descriptor.platform;\n if (!options.isStarted(platform)) return plain(503);\n const webhook = channel.descriptor.webhook as ChannelWebhook<BasePlatformAdapter>;\n const refused = refuseEarly(webhook, channel.adapter, request);\n if (refused !== undefined) return refused;\n const rawBody = await readBody(request, max);\n if (typeof rawBody !== \"string\") return rawBody;\n try {\n return await dispatch(webhook, channel.adapter, {\n rawBody,\n headers: headersOf(request),\n method: request.method.toUpperCase(),\n url: request.url,\n });\n } catch (error) {\n options.onError?.(platform, error);\n return plain(500);\n }\n };\n}\n\n/** The method check, then the descriptor's `precheck`; both run before the body is read. */\nfunction refuseEarly(\n webhook: ChannelWebhook<BasePlatformAdapter>,\n adapter: BasePlatformAdapter,\n request: Request,\n): Response | undefined {\n return refuseMethod(webhook, request) ?? precheckAnswer(webhook, adapter, request);\n}\n\nfunction precheckAnswer(\n webhook: ChannelWebhook<BasePlatformAdapter>,\n adapter: BasePlatformAdapter,\n request: Request,\n): Response | undefined {\n if (webhook.precheck === undefined) return undefined;\n const answer = webhook.precheck(adapter, {\n headers: headersOf(request),\n method: request.method.toUpperCase(),\n url: request.url,\n });\n return answer === undefined ? undefined : answerResponse(answer);\n}\n\nfunction refuseMethod(\n webhook: ChannelWebhook<BasePlatformAdapter>,\n request: Request,\n): Response | undefined {\n const methods = webhook.methods ?? [\"POST\"];\n const method = request.method.toUpperCase();\n if (methods.some((m) => m.toUpperCase() === method)) return undefined;\n return plain(405, { allow: methods.join(\", \") });\n}\n\nasync function dispatch(\n webhook: ChannelWebhook<BasePlatformAdapter>,\n adapter: BasePlatformAdapter,\n request: WebhookRequest,\n): Promise<Response> {\n if (webhook.handle !== undefined) return answerResponse(await webhook.handle(adapter, request));\n return runDefault(webhook, adapter, request);\n}\n"]}