@theokit/gateway 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/dist/index.cjs +96 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +139 -1
- package/dist/index.d.ts +139 -1
- package/dist/index.js +94 -2
- package/dist/index.js.map +1 -1
- package/package.json +5 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Architecture-hardening (roadmap M0–M3): three new public primitives on the core barrel, plus a hook-engine relocation. No breaking changes.
|
|
8
|
+
|
|
9
|
+
- `chunkText(text, options)` — transport-agnostic, boundary-preferring text chunker. Single-sources the message-splitting logic the platform adapters share; reproduces the Slack-family (fixed window, space boundary, UTF-16 surrogate guard) and Telegram-family (soft window, newline-only) algorithms via options. Validates inputs (positive-integer `limit`, `safeLimit <= limit`) and throws `RangeError` on misuse (fail-fast — no infinite loop).
|
|
10
|
+
- `chunkByGrapheme(text, options)` — grapheme-cluster-safe (`Intl.Segmenter`) chunker shared by the LINE/SMS adapters; never severs an emoji, regional-indicator pair, or combining sequence.
|
|
11
|
+
- `GatewayConfigurationError` base + `GatewayConfigurationErrorOptions` — shared base for per-adapter `ConfigurationError` classes.
|
|
12
|
+
- `HookExecutor` moved from `hooks/types.ts` to `hooks/executor.ts` (public API byte-identical; re-exported unchanged from the barrel).
|
|
13
|
+
|
|
14
|
+
## 0.4.1
|
|
15
|
+
|
|
16
|
+
### Patch Changes
|
|
17
|
+
|
|
18
|
+
- e926cd9: Align the gateway cluster to the hardened `@theokit/sdk` 2.18.0 Harness (ecosystem M6). Bumped the `@theokit/sdk` peer + dev dependency from `^1.9.0` to `^2.18.0` across all 11 packages. The only consumed SDK surface is `Security.redact` (in the gateway core runner) — a stable public API (ADR D68) unchanged across 1.x→2.x — so the alignment is a pin bump, not a migration. Validated: all 11 packages typecheck + build + test green against 2.18.0 (543 tests passed). No dead/unwired surfaces (`no-stubs-no-mocks-no-wired` checklist clean).
|
|
19
|
+
|
|
20
|
+
## [Unreleased]
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- **Documentation only:** added `src/README.md` documenting the 6 single-file sub-folder cluster (`adapter/`, `delivery/`, `hooks/`, `runner/`, `session/`, `types/`) as intentional bounded future-extensibility scaffold (T10.2 of plan `arch-review-fixes-2026-06-06`; FO#4 of 2026-06-06 architecture audit). Rationale + ADR cross-references (D170-D177) + 12-month re-evaluation trigger documented. No code change.
|
|
25
|
+
|
|
3
26
|
## 2.0.0
|
|
4
27
|
|
|
5
28
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -35,7 +35,23 @@ var DeliveryRouter = class {
|
|
|
35
35
|
}
|
|
36
36
|
};
|
|
37
37
|
|
|
38
|
-
// src/
|
|
38
|
+
// src/errors/config-error.ts
|
|
39
|
+
var GatewayConfigurationError = class extends Error {
|
|
40
|
+
name = "GatewayConfigurationError";
|
|
41
|
+
code;
|
|
42
|
+
detail;
|
|
43
|
+
/**
|
|
44
|
+
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
45
|
+
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
46
|
+
*/
|
|
47
|
+
constructor(prefix, opts) {
|
|
48
|
+
super(opts.message ?? `${prefix}: ${opts.code}`);
|
|
49
|
+
this.code = opts.code;
|
|
50
|
+
this.detail = opts.detail;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// src/hooks/executor.ts
|
|
39
55
|
var HookExecutor = class {
|
|
40
56
|
constructor(hooks) {
|
|
41
57
|
this.hooks = hooks;
|
|
@@ -274,11 +290,90 @@ var SessionRouter = class {
|
|
|
274
290
|
}
|
|
275
291
|
};
|
|
276
292
|
|
|
293
|
+
// src/text/chunk.ts
|
|
294
|
+
function searchBoundary(remaining, window, boundaries) {
|
|
295
|
+
let cut = window;
|
|
296
|
+
for (const b of boundaries) {
|
|
297
|
+
cut = remaining.lastIndexOf(b, window);
|
|
298
|
+
if (cut >= window * 0.5) return cut;
|
|
299
|
+
}
|
|
300
|
+
return cut;
|
|
301
|
+
}
|
|
302
|
+
function assertPositiveInt(label, value) {
|
|
303
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
304
|
+
throw new RangeError(`${label} must be a positive integer, received ${value}`);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
function guardSurrogate(text, cut) {
|
|
308
|
+
if (cut >= text.length) return cut;
|
|
309
|
+
const code = text.charCodeAt(cut);
|
|
310
|
+
return code >= 56320 && code <= 57343 ? cut - 1 : cut;
|
|
311
|
+
}
|
|
312
|
+
function findCut(remaining, window, boundaries, lastResort, surrogateGuard) {
|
|
313
|
+
let cut = searchBoundary(remaining, window, boundaries);
|
|
314
|
+
if (cut < window * 0.5) {
|
|
315
|
+
cut = lastResort === "last-boundary" && cut > 0 ? cut : window;
|
|
316
|
+
}
|
|
317
|
+
if (surrogateGuard) cut = guardSurrogate(remaining, cut);
|
|
318
|
+
return cut <= 0 ? window : cut;
|
|
319
|
+
}
|
|
320
|
+
function chunkText(text, options) {
|
|
321
|
+
const {
|
|
322
|
+
limit,
|
|
323
|
+
safeLimit = limit,
|
|
324
|
+
boundaries = ["\n\n", "\n", " "],
|
|
325
|
+
lastResort = "window",
|
|
326
|
+
surrogateGuard = false,
|
|
327
|
+
stripLeading = /^\n+/,
|
|
328
|
+
trimParts = false
|
|
329
|
+
} = options;
|
|
330
|
+
assertPositiveInt("chunkText: limit", limit);
|
|
331
|
+
assertPositiveInt("chunkText: safeLimit", safeLimit);
|
|
332
|
+
if (safeLimit > limit) {
|
|
333
|
+
throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);
|
|
334
|
+
}
|
|
335
|
+
const finalize = (parts2) => trimParts ? parts2.map((p) => p.trim()).filter((p) => p.length > 0) : parts2;
|
|
336
|
+
if (text.length <= limit) {
|
|
337
|
+
return finalize([text]);
|
|
338
|
+
}
|
|
339
|
+
const parts = [];
|
|
340
|
+
let remaining = text;
|
|
341
|
+
while (remaining.length > safeLimit) {
|
|
342
|
+
const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);
|
|
343
|
+
parts.push(remaining.slice(0, cut));
|
|
344
|
+
remaining = remaining.slice(cut).replace(stripLeading, "");
|
|
345
|
+
}
|
|
346
|
+
if (remaining.length > 0) parts.push(remaining);
|
|
347
|
+
return finalize(parts);
|
|
348
|
+
}
|
|
349
|
+
function chunkByGrapheme(text, options) {
|
|
350
|
+
const { limit, partLimit = limit } = options;
|
|
351
|
+
assertPositiveInt("chunkByGrapheme: limit", limit);
|
|
352
|
+
assertPositiveInt("chunkByGrapheme: partLimit", partLimit);
|
|
353
|
+
if (text.length === 0) return [""];
|
|
354
|
+
if (text.length <= limit) return [text];
|
|
355
|
+
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
356
|
+
const parts = [];
|
|
357
|
+
let buf = "";
|
|
358
|
+
for (const { segment } of segmenter.segment(text)) {
|
|
359
|
+
if (buf.length + segment.length > partLimit) {
|
|
360
|
+
if (buf.length > 0) parts.push(buf);
|
|
361
|
+
buf = "";
|
|
362
|
+
}
|
|
363
|
+
buf += segment;
|
|
364
|
+
}
|
|
365
|
+
if (buf.length > 0) parts.push(buf);
|
|
366
|
+
return parts;
|
|
367
|
+
}
|
|
368
|
+
|
|
277
369
|
exports.BasePlatformAdapter = BasePlatformAdapter;
|
|
278
370
|
exports.DeliveryRouter = DeliveryRouter;
|
|
371
|
+
exports.GatewayConfigurationError = GatewayConfigurationError;
|
|
279
372
|
exports.GatewayRunner = GatewayRunner;
|
|
280
373
|
exports.HookExecutor = HookExecutor;
|
|
281
374
|
exports.SessionRouter = SessionRouter;
|
|
375
|
+
exports.chunkByGrapheme = chunkByGrapheme;
|
|
376
|
+
exports.chunkText = chunkText;
|
|
282
377
|
exports.defaultStrategy = defaultStrategy;
|
|
283
378
|
//# sourceMappingURL=index.cjs.map
|
|
284
379
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/hooks/types.ts","../src/runner/gateway-runner.ts","../src/session/router.ts"],"names":["Security"],"mappings":";;;;;AAqDO,IAAe,sBAAf,MAAmC;AAAA;AAAA,EAmBxC,MAAM,YAAY,UAAA,EAAmC;AAAA,EAErD;AAAA;AAAA,EAGA,MAAM,WAAW,UAAA,EAAmC;AAAA,EAEpD;AACF;;;ACvCO,IAAM,iBAAN,MAAqB;AAAA,EACT,QAAA,uBAAe,GAAA,EAAuC;AAAA,EAEvE,SAAS,OAAA,EAAoC;AAC3C,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,QAAA,EAAU,OAAO,CAAA;AAAA,EAC7C;AAAA,EAEA,MAAM,KAAK,GAAA,EAA2C;AACpD,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,IAAI,QAAQ,CAAA;AAC9C,IAAA,IAAI,YAAY,MAAA,EAAW;AACzB,MAAA,OAAO;AAAA,QACL,EAAA,EAAI,KAAA;AAAA,QACJ,KAAA,EAAO,EAAE,IAAA,EAAM,YAAA,EAAc,SAAS,CAAA,yBAAA,EAA4B,GAAA,CAAI,QAAQ,CAAA,CAAA,CAAA;AAAI,OACpF;AAAA,IACF;AACA,IAAA,OAAO,QAAQ,WAAA,CAAY;AAAA,MACzB,SAAS,GAAA,CAAI,OAAA;AAAA,MACb,MAAM,GAAA,CAAI,IAAA;AAAA,MACV,GAAI,IAAI,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,GAAA,CAAI,MAAA,EAAO,GAAI,EAAC;A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C5B;AACF","file":"index.cjs","sourcesContent":["/**\n * `BasePlatformAdapter` — contract every transport adapter implements\n * (T1.2, ADR D172).\n *\n * Adapters share ~30% of lifecycle code (typing indicators, event\n * normalization patterns). An abstract class with concrete defaults\n * + abstract hooks is the right shape — interface-only would force\n * every adapter to copy the defaults.\n *\n * Consumers use it via `instanceof` and the public subclass exports\n * (`TelegramAdapter`, `DiscordAdapter`, ...).\n */\n\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Outbound message shape — what `sendMessage` accepts. */\nexport interface OutboundMessage {\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n readonly text: string;\n /** Markdown / HTML rendering hint. Default \"plain\". */\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n /** Optional reply target. */\n readonly replyTo?: string;\n}\n\n/** Send result — adapters return this instead of throwing on platform errors. */\nexport interface SendResult {\n readonly ok: boolean;\n readonly messageId?: string;\n readonly error?: { readonly code: string; readonly message: string };\n}\n\n/**\n * Abstract base for all platform adapters.\n *\n * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.\n * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden.\n *\n * **Contract:**\n * - `connect()` is idempotent. Calling twice returns true the second time.\n * - `disconnect()` is idempotent.\n * - `sendMessage` returns a `SendResult`; it MUST NOT throw on platform errors\n * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.\n * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling\n * `onInbound` twice replaces the previous handler — does NOT stack.\n * - `sendMessage` with empty text returns `{ ok: false, code: \"empty_text\" }`.\n *\n * @public\n */\nexport abstract class BasePlatformAdapter {\n abstract readonly platform: PlatformName;\n\n /** Open the connection. Returns `true` on success; never throws. */\n abstract connect(): Promise<boolean>;\n\n /** Close the connection. Idempotent; safe to call when never connected. */\n abstract disconnect(): Promise<void>;\n\n /** Send a message. Returns a `SendResult`; never throws on platform errors. */\n abstract sendMessage(out: OutboundMessage): Promise<SendResult>;\n\n /**\n * Subscribe to inbound events. Returns an unsubscribe function.\n * EC-H: second call REPLACES the previous handler (does not stack).\n */\n abstract onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void;\n\n /** Lifecycle: emit a typing indicator. Default: noop. */\n async startTyping(_channelId: string): Promise<void> {\n /* override */\n }\n\n /** Lifecycle: stop the typing indicator. Default: noop. */\n async stopTyping(_channelId: string): Promise<void> {\n /* override */\n }\n}\n","/**\n * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).\n *\n * The router holds a map of `platform → adapter` and forwards\n * `DeliveryRequest` to the right adapter's `sendMessage`. Composes\n * with `Cron` from `@theokit/sdk` for scheduled delivery — the\n * router is the \"WHERE to send\", Cron is the \"WHEN to fire\".\n *\n * @public\n */\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** Target for an outbound delivery. */\nexport interface DeliveryTarget {\n readonly platform: PlatformName;\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n}\n\n/** Full outbound request: target + content. */\nexport interface DeliveryRequest extends DeliveryTarget {\n readonly text: string;\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n readonly replyTo?: string;\n}\n\n/**\n * Routes outbound requests to the correct adapter.\n *\n * **Contract:**\n * - `register` is last-writer-wins by platform.\n * - `send` with unknown platform returns `{ ok: false, code: \"no_adapter\" }`.\n * - `send` never throws on platform errors (delegates to adapter's SendResult).\n *\n * @public\n */\nexport class DeliveryRouter {\n private readonly adapters = new Map<PlatformName, BasePlatformAdapter>();\n\n register(adapter: BasePlatformAdapter): void {\n this.adapters.set(adapter.platform, adapter);\n }\n\n async send(req: DeliveryRequest): Promise<SendResult> {\n const adapter = this.adapters.get(req.platform);\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for platform \"${req.platform}\"` },\n };\n }\n return adapter.sendMessage({\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n });\n }\n}\n","/**\n * Gateway hooks — own contract, not a `Plugin.kind` extension\n * (T4.1, ADRs D176, D177).\n *\n * Three fire points:\n * - `pre_inbound` — runs sequentially; first `{ block: true }` short-circuits.\n * - `post_outbound` — fire-and-forget; errors logged.\n * - `on_error` — fire-and-forget; called when the handler throws.\n *\n * Signature mirrors the SDK's `pre_tool_call` veto (D101) so consumers\n * have a single mental model for \"block or continue\" hooks.\n *\n * @public\n */\n\nimport type { OutboundMessage, SendResult } from \"../adapter/base.js\";\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Closed enum of hook fire points. */\nexport type HookName = \"pre_inbound\" | \"post_outbound\" | \"on_error\";\n\n/**\n * Decision returned by a `pre_inbound` hook.\n *\n * - `block: true` short-circuits the chain — handler does NOT run.\n * - `message` set → runner calls `ctx.reply(message)` BEFORE short-circuit (EC-D).\n * - `block: false` or `undefined` → continue.\n */\nexport interface HookDecision {\n readonly block?: boolean;\n readonly message?: string;\n}\n\n/** Context passed to `pre_inbound` hooks. */\nexport interface PreInboundContext {\n readonly event: GatewayMessageEvent;\n}\n\n/** Context passed to `post_outbound` hooks. */\nexport interface PostOutboundContext {\n readonly event: GatewayMessageEvent;\n readonly outbound: OutboundMessage;\n readonly result: SendResult;\n}\n\n/** Context passed to `on_error` hooks. */\nexport interface OnErrorContext {\n readonly event: GatewayMessageEvent;\n readonly error: Error;\n}\n\n/** A gateway hook: any of the three fire-point methods are optional. */\nexport interface GatewayHook {\n readonly name: string;\n // biome-ignore lint/suspicious/noConfusingVoidType: sync-or-async hook ergonomics — matches SDK pre_tool_call signature (D101).\n pre_inbound?(ctx: PreInboundContext): Promise<HookDecision | void> | HookDecision | void;\n post_outbound?(ctx: PostOutboundContext): Promise<void> | void;\n on_error?(ctx: OnErrorContext): Promise<void> | void;\n}\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {}\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n return {\n block: true,\n message: `hook ${h.name} threw: ${(err as Error).message}`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport { type GatewayHook, HookExecutor } from \"../hooks/types.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /** Connect all adapters and wire inbound dispatch. */\n async start(): Promise<void> {\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => setTimeout(r, drainMs)),\n ]);\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(\n `[gateway] handler error: ${Security.redact((err as Error).message)}\\n`,\n );\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n const adapter = this.adaptersByPlatform.get(event.platform);\n return {\n event,\n reply: async (text, opts) => {\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` },\n };\n }\n return adapter.sendMessage({\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n });\n },\n };\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/errors/config-error.ts","../src/hooks/executor.ts","../src/runner/gateway-runner.ts","../src/session/router.ts","../src/text/chunk.ts"],"names":["Security","parts"],"mappings":";;;;;AAqDO,IAAe,sBAAf,MAAmC;AAAA;AAAA,EAmBxC,MAAM,YAAY,UAAA,EAAmC;AAAA,EAErD;AAAA;AAAA,EAGA,MAAM,WAAW,UAAA,EAAmC;AAAA,EAEpD;AACF;;;ACvCO,IAAM,iBAAN,MAAqB;AAAA,EACT,QAAA,uBAAe,GAAA,EAAuC;AAAA,EAEvE,SAAS,OAAA,EAAoC;AAC3C,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,QAAA,EAAU,OAAO,CAAA;AAAA,EAC7C;AAAA,EAEA,MAAM,KAAK,GAAA,EAA2C;AACpD,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,IAAI,QAAQ,CAAA;AAC9C,IAAA,IAAI,YAAY,MAAA,EAAW;AACzB,MAAA,OAAO;AAAA,QACL,EAAA,EAAI,KAAA;AAAA,QACJ,KAAA,EAAO,EAAE,IAAA,EAAM,YAAA,EAAc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CAAC,EAAE,CAAA;AACjC,EAAA,IAAI,IAAA,CAAK,MAAA,IAAU,KAAA,EAAO,OAAO,CAAC,IAAI,CAAA;AAEtC,EAAA,MAAM,SAAA,GAAY,IAAI,IAAA,CAAK,SAAA,CAAU,QAAW,EAAE,WAAA,EAAa,YAAY,CAAA;AAC3E,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,MAAW,EAAE,OAAA,EAAQ,IAAK,SAAA,CAAU,OAAA,CAAQ,IAAI,CAAA,EAAG;AACjD,IAAA,IAAI,GAAA,CAAI,MAAA,GAAS,OAAA,CAAQ,MAAA,GAAS,SAAA,EAAW;AAC3C,MAAA,IAAI,GAAA,CAAI,MAAA,GAAS,CAAA,EAAG,KAAA,CAAM,KAAK,GAAG,CAAA;AAClC,MAAA,GAAA,GAAM,EAAA;AAAA,IACR;AACA,IAAA,GAAA,IAAO,OAAA;AAAA,EACT;AACA,EAAA,IAAI,GAAA,CAAI,MAAA,GAAS,CAAA,EAAG,KAAA,CAAM,KAAK,GAAG,CAAA;AAClC,EAAA,OAAO,KAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * `BasePlatformAdapter` — contract every transport adapter implements\n * (T1.2, ADR D172).\n *\n * Adapters share ~30% of lifecycle code (typing indicators, event\n * normalization patterns). An abstract class with concrete defaults\n * + abstract hooks is the right shape — interface-only would force\n * every adapter to copy the defaults.\n *\n * Consumers use it via `instanceof` and the public subclass exports\n * (`TelegramAdapter`, `DiscordAdapter`, ...).\n */\n\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Outbound message shape — what `sendMessage` accepts. */\nexport interface OutboundMessage {\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n readonly text: string;\n /** Markdown / HTML rendering hint. Default \"plain\". */\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n /** Optional reply target. */\n readonly replyTo?: string;\n}\n\n/** Send result — adapters return this instead of throwing on platform errors. */\nexport interface SendResult {\n readonly ok: boolean;\n readonly messageId?: string;\n readonly error?: { readonly code: string; readonly message: string };\n}\n\n/**\n * Abstract base for all platform adapters.\n *\n * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.\n * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden.\n *\n * **Contract:**\n * - `connect()` is idempotent. Calling twice returns true the second time.\n * - `disconnect()` is idempotent.\n * - `sendMessage` returns a `SendResult`; it MUST NOT throw on platform errors\n * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.\n * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling\n * `onInbound` twice replaces the previous handler — does NOT stack.\n * - `sendMessage` with empty text returns `{ ok: false, code: \"empty_text\" }`.\n *\n * @public\n */\nexport abstract class BasePlatformAdapter {\n abstract readonly platform: PlatformName;\n\n /** Open the connection. Returns `true` on success; never throws. */\n abstract connect(): Promise<boolean>;\n\n /** Close the connection. Idempotent; safe to call when never connected. */\n abstract disconnect(): Promise<void>;\n\n /** Send a message. Returns a `SendResult`; never throws on platform errors. */\n abstract sendMessage(out: OutboundMessage): Promise<SendResult>;\n\n /**\n * Subscribe to inbound events. Returns an unsubscribe function.\n * EC-H: second call REPLACES the previous handler (does not stack).\n */\n abstract onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void;\n\n /** Lifecycle: emit a typing indicator. Default: noop. */\n async startTyping(_channelId: string): Promise<void> {\n /* override */\n }\n\n /** Lifecycle: stop the typing indicator. Default: noop. */\n async stopTyping(_channelId: string): Promise<void> {\n /* override */\n }\n}\n","/**\n * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).\n *\n * The router holds a map of `platform → adapter` and forwards\n * `DeliveryRequest` to the right adapter's `sendMessage`. Composes\n * with `Cron` from `@theokit/sdk` for scheduled delivery — the\n * router is the \"WHERE to send\", Cron is the \"WHEN to fire\".\n *\n * @public\n */\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** Target for an outbound delivery. */\nexport interface DeliveryTarget {\n readonly platform: PlatformName;\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n}\n\n/** Full outbound request: target + content. */\nexport interface DeliveryRequest extends DeliveryTarget {\n readonly text: string;\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n readonly replyTo?: string;\n}\n\n/**\n * Routes outbound requests to the correct adapter.\n *\n * **Contract:**\n * - `register` is last-writer-wins by platform.\n * - `send` with unknown platform returns `{ ok: false, code: \"no_adapter\" }`.\n * - `send` never throws on platform errors (delegates to adapter's SendResult).\n *\n * @public\n */\nexport class DeliveryRouter {\n private readonly adapters = new Map<PlatformName, BasePlatformAdapter>();\n\n register(adapter: BasePlatformAdapter): void {\n this.adapters.set(adapter.platform, adapter);\n }\n\n async send(req: DeliveryRequest): Promise<SendResult> {\n const adapter = this.adapters.get(req.platform);\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for platform \"${req.platform}\"` },\n };\n }\n return adapter.sendMessage({\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n });\n }\n}\n","/**\n * `GatewayConfigurationError` — shared base for per-adapter configuration\n * errors (roadmap M0/M2).\n *\n * Every platform adapter previously defined an identical\n * `ConfigurationError extends Error` (same `code`/`detail` fields, same\n * options interface, same `` `${pkg}: ${code}` `` default message) — only the\n * package prefix differed. This base single-sources that contract. Adapters\n * extend it, pin their prefix, and keep `name = \"ConfigurationError\"` plus\n * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).\n *\n * @public\n */\n\n/** Public input shape for the {@link GatewayConfigurationError} constructor. */\nexport interface GatewayConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\n/**\n * Base configuration error. Not thrown directly by adapters — they subclass it\n * with a fixed package prefix.\n */\nexport class GatewayConfigurationError extends Error {\n override readonly name: string = \"GatewayConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n\n /**\n * @param prefix Package prefix used in the default message (e.g. `\"gateway-line\"`).\n * @param opts `code` (required), optional explicit `message`, optional `detail`.\n */\n constructor(prefix: string, opts: GatewayConfigurationErrorOptions) {\n super(opts.message ?? `${prefix}: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n","/**\n * `HookExecutor` — runs registered gateway hooks at their fire points.\n *\n * Split out of `hooks/types.ts` (which now holds the contract only) so the\n * filename predicts its contents: interfaces live in `types.ts`, the run\n * engine lives here. Behavior is identical to the previous colocated class.\n *\n * @public\n */\n\nimport type {\n GatewayHook,\n HookDecision,\n OnErrorContext,\n PostOutboundContext,\n PreInboundContext,\n} from \"./types.js\";\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {}\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n return {\n block: true,\n message: `hook ${h.name} threw: ${(err as Error).message}`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport { HookExecutor } from \"../hooks/executor.js\";\nimport type { GatewayHook } from \"../hooks/types.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /** Connect all adapters and wire inbound dispatch. */\n async start(): Promise<void> {\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => setTimeout(r, drainMs)),\n ]);\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(\n `[gateway] handler error: ${Security.redact((err as Error).message)}\\n`,\n );\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n const adapter = this.adaptersByPlatform.get(event.platform);\n return {\n event,\n reply: async (text, opts) => {\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` },\n };\n }\n return adapter.sendMessage({\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n });\n },\n };\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n","/**\n * `chunkText` — transport-agnostic, boundary-preferring text chunker.\n *\n * Single-sources the message-splitting knowledge that was copy-pasted across\n * the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two\n * boundary-search families that existed in the adapters:\n *\n * - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\" → \" \"`, UTF-16 surrogate-pair guard,\n * leading-whitespace strip on continuation, optional part-trim.\n * - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\"` (no space), no surrogate guard,\n * leading-newline strip on continuation.\n *\n * The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different\n * algorithm and is intentionally NOT folded in here — those adapters keep their\n * grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.\n *\n * @public\n */\n\n/** Options for {@link chunkText}. */\nexport interface ChunkTextOptions {\n /**\n * Hard cap. If the whole input is `<= limit`, it is returned as a single\n * chunk (subject to `trimParts`). Continuation chunks are cut within the\n * `safeLimit` window.\n */\n readonly limit: number;\n /**\n * Soft window each cut searches within. Defaults to `limit`. The Telegram\n * family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).\n */\n readonly safeLimit?: number;\n /**\n * Boundary strings tried, in order, from most to least preferred. A boundary\n * is accepted once its position is `>= window * 0.5`; otherwise the next one\n * is tried. Default: `[\"\\n\\n\", \"\\n\", \" \"]`.\n */\n readonly boundaries?: readonly string[];\n /**\n * When no boundary reaches the half-window threshold:\n * - `\"last-boundary\"` — use the last computed boundary if it is `> 0`,\n * else fall back to the window edge (Slack family).\n * - `\"window\"` — fall back straight to the window edge (Telegram family).\n * Default: `\"window\"`.\n */\n readonly lastResort?: \"last-boundary\" | \"window\";\n /**\n * Guard against slicing through a UTF-16 low surrogate (splitting an emoji).\n * Default: `false`.\n */\n readonly surrogateGuard?: boolean;\n /**\n * Pattern stripped from the START of each continuation chunk. Default `/^\\n+/`\n * (Telegram family). Slack family uses `/^\\s+/`.\n */\n readonly stripLeading?: RegExp;\n /**\n * When true, each resulting part is `.trim()`-ed and empty parts are dropped\n * (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.\n */\n readonly trimParts?: boolean;\n}\n\n/** Most-preferred boundary at `>= window*0.5`, else the last boundary tried. */\nfunction searchBoundary(remaining: string, window: number, boundaries: readonly string[]): number {\n let cut = window;\n for (const b of boundaries) {\n cut = remaining.lastIndexOf(b, window);\n if (cut >= window * 0.5) return cut;\n }\n return cut;\n}\n\n/** Fail fast on a non-positive / non-integer size argument. */\nfunction assertPositiveInt(label: string, value: number): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new RangeError(`${label} must be a positive integer, received ${value}`);\n }\n}\n\n/** Step back one code unit if `cut` would sever a UTF-16 surrogate pair. */\nfunction guardSurrogate(text: string, cut: number): number {\n if (cut >= text.length) return cut;\n const code = text.charCodeAt(cut);\n return code >= 0xdc00 && code <= 0xdfff ? cut - 1 : cut;\n}\n\nfunction findCut(\n remaining: string,\n window: number,\n boundaries: readonly string[],\n lastResort: \"last-boundary\" | \"window\",\n surrogateGuard: boolean,\n): number {\n let cut = searchBoundary(remaining, window, boundaries);\n if (cut < window * 0.5) {\n cut = lastResort === \"last-boundary\" && cut > 0 ? cut : window;\n }\n if (surrogateGuard) cut = guardSurrogate(remaining, cut);\n return cut <= 0 ? window : cut;\n}\n\n/**\n * Split `text` into chunks no longer than the configured window, preferring\n * natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.\n */\nexport function chunkText(text: string, options: ChunkTextOptions): string[] {\n const {\n limit,\n safeLimit = limit,\n boundaries = [\"\\n\\n\", \"\\n\", \" \"],\n lastResort = \"window\",\n surrogateGuard = false,\n stripLeading = /^\\n+/,\n trimParts = false,\n } = options;\n\n // Fail fast at the boundary: a non-positive `limit` would make `findCut`\n // return 0 forever and hang the loop; `safeLimit > limit` would break the\n // \"hard cap\" contract by emitting an oversized tail chunk.\n assertPositiveInt(\"chunkText: limit\", limit);\n assertPositiveInt(\"chunkText: safeLimit\", safeLimit);\n if (safeLimit > limit) {\n throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);\n }\n\n const finalize = (parts: string[]): string[] =>\n trimParts ? parts.map((p) => p.trim()).filter((p) => p.length > 0) : parts;\n\n if (text.length <= limit) {\n return finalize([text]);\n }\n\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > safeLimit) {\n const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);\n parts.push(remaining.slice(0, cut));\n remaining = remaining.slice(cut).replace(stripLeading, \"\");\n }\n if (remaining.length > 0) parts.push(remaining);\n return finalize(parts);\n}\n\n/** Options for {@link chunkByGrapheme}. */\nexport interface ChunkByGraphemeOptions {\n /** If `text.length <= limit`, it is returned as a single chunk. */\n readonly limit: number;\n /**\n * Max length per emitted part during the grapheme walk. Defaults to `limit`.\n * Callers that reserve room for a per-part prefix (e.g. SMS `\"(i/N) \"`) pass a\n * `partLimit` below `limit`.\n */\n readonly partLimit?: number;\n}\n\n/**\n * Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,\n * regional-indicator pair, or combining sequence. Distinct algorithm from\n * {@link chunkText} — used by adapters that must respect grapheme boundaries\n * (LINE, SMS) rather than search for whitespace boundaries.\n *\n * @public\n */\nexport function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[] {\n const { limit, partLimit = limit } = options;\n assertPositiveInt(\"chunkByGrapheme: limit\", limit);\n assertPositiveInt(\"chunkByGrapheme: partLimit\", partLimit);\n if (text.length === 0) return [\"\"];\n if (text.length <= limit) return [text];\n\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const parts: string[] = [];\n let buf = \"\";\n for (const { segment } of segmenter.segment(text)) {\n if (buf.length + segment.length > partLimit) {\n if (buf.length > 0) parts.push(buf);\n buf = \"\";\n }\n buf += segment;\n }\n if (buf.length > 0) parts.push(buf);\n return parts;\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
* }
|
|
13
13
|
* ```
|
|
14
14
|
*
|
|
15
|
+
* This union is intentionally **closed** — adding a platform edits it here
|
|
16
|
+
* rather than extending it externally. The trade-off (exhaustive narrowing over
|
|
17
|
+
* OCP purity) is recorded in `docs/adr/0001-message-event-closed-union.md`.
|
|
18
|
+
*
|
|
15
19
|
* @public
|
|
16
20
|
*/
|
|
17
21
|
/** Closed enum of supported transport platforms. */
|
|
@@ -325,6 +329,40 @@ declare class DeliveryRouter {
|
|
|
325
329
|
send(req: DeliveryRequest): Promise<SendResult>;
|
|
326
330
|
}
|
|
327
331
|
|
|
332
|
+
/**
|
|
333
|
+
* `GatewayConfigurationError` — shared base for per-adapter configuration
|
|
334
|
+
* errors (roadmap M0/M2).
|
|
335
|
+
*
|
|
336
|
+
* Every platform adapter previously defined an identical
|
|
337
|
+
* `ConfigurationError extends Error` (same `code`/`detail` fields, same
|
|
338
|
+
* options interface, same `` `${pkg}: ${code}` `` default message) — only the
|
|
339
|
+
* package prefix differed. This base single-sources that contract. Adapters
|
|
340
|
+
* extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
|
|
341
|
+
* their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
|
|
342
|
+
*
|
|
343
|
+
* @public
|
|
344
|
+
*/
|
|
345
|
+
/** Public input shape for the {@link GatewayConfigurationError} constructor. */
|
|
346
|
+
interface GatewayConfigurationErrorOptions {
|
|
347
|
+
readonly code: string;
|
|
348
|
+
readonly message?: string;
|
|
349
|
+
readonly detail?: string;
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Base configuration error. Not thrown directly by adapters — they subclass it
|
|
353
|
+
* with a fixed package prefix.
|
|
354
|
+
*/
|
|
355
|
+
declare class GatewayConfigurationError extends Error {
|
|
356
|
+
readonly name: string;
|
|
357
|
+
readonly code: string;
|
|
358
|
+
readonly detail: string | undefined;
|
|
359
|
+
/**
|
|
360
|
+
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
361
|
+
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
362
|
+
*/
|
|
363
|
+
constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
|
|
364
|
+
}
|
|
365
|
+
|
|
328
366
|
/**
|
|
329
367
|
* Gateway hooks — own contract, not a `Plugin.kind` extension
|
|
330
368
|
* (T4.1, ADRs D176, D177).
|
|
@@ -375,6 +413,17 @@ interface GatewayHook {
|
|
|
375
413
|
post_outbound?(ctx: PostOutboundContext): Promise<void> | void;
|
|
376
414
|
on_error?(ctx: OnErrorContext): Promise<void> | void;
|
|
377
415
|
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* `HookExecutor` — runs registered gateway hooks at their fire points.
|
|
419
|
+
*
|
|
420
|
+
* Split out of `hooks/types.ts` (which now holds the contract only) so the
|
|
421
|
+
* filename predicts its contents: interfaces live in `types.ts`, the run
|
|
422
|
+
* engine lives here. Behavior is identical to the previous colocated class.
|
|
423
|
+
*
|
|
424
|
+
* @public
|
|
425
|
+
*/
|
|
426
|
+
|
|
378
427
|
/**
|
|
379
428
|
* Runs registered hooks at the right fire points. Stateless — safe to
|
|
380
429
|
* construct per-event if hooks need event-scoped storage.
|
|
@@ -525,4 +574,93 @@ declare class SessionRouter {
|
|
|
525
574
|
resolveAgentId(event: MessageEvent): string;
|
|
526
575
|
}
|
|
527
576
|
|
|
528
|
-
|
|
577
|
+
/**
|
|
578
|
+
* `chunkText` — transport-agnostic, boundary-preferring text chunker.
|
|
579
|
+
*
|
|
580
|
+
* Single-sources the message-splitting knowledge that was copy-pasted across
|
|
581
|
+
* the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two
|
|
582
|
+
* boundary-search families that existed in the adapters:
|
|
583
|
+
*
|
|
584
|
+
* - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),
|
|
585
|
+
* boundary preference `"\n\n" → "\n" → " "`, UTF-16 surrogate-pair guard,
|
|
586
|
+
* leading-whitespace strip on continuation, optional part-trim.
|
|
587
|
+
* - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),
|
|
588
|
+
* boundary preference `"\n\n" → "\n"` (no space), no surrogate guard,
|
|
589
|
+
* leading-newline strip on continuation.
|
|
590
|
+
*
|
|
591
|
+
* The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different
|
|
592
|
+
* algorithm and is intentionally NOT folded in here — those adapters keep their
|
|
593
|
+
* grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.
|
|
594
|
+
*
|
|
595
|
+
* @public
|
|
596
|
+
*/
|
|
597
|
+
/** Options for {@link chunkText}. */
|
|
598
|
+
interface ChunkTextOptions {
|
|
599
|
+
/**
|
|
600
|
+
* Hard cap. If the whole input is `<= limit`, it is returned as a single
|
|
601
|
+
* chunk (subject to `trimParts`). Continuation chunks are cut within the
|
|
602
|
+
* `safeLimit` window.
|
|
603
|
+
*/
|
|
604
|
+
readonly limit: number;
|
|
605
|
+
/**
|
|
606
|
+
* Soft window each cut searches within. Defaults to `limit`. The Telegram
|
|
607
|
+
* family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).
|
|
608
|
+
*/
|
|
609
|
+
readonly safeLimit?: number;
|
|
610
|
+
/**
|
|
611
|
+
* Boundary strings tried, in order, from most to least preferred. A boundary
|
|
612
|
+
* is accepted once its position is `>= window * 0.5`; otherwise the next one
|
|
613
|
+
* is tried. Default: `["\n\n", "\n", " "]`.
|
|
614
|
+
*/
|
|
615
|
+
readonly boundaries?: readonly string[];
|
|
616
|
+
/**
|
|
617
|
+
* When no boundary reaches the half-window threshold:
|
|
618
|
+
* - `"last-boundary"` — use the last computed boundary if it is `> 0`,
|
|
619
|
+
* else fall back to the window edge (Slack family).
|
|
620
|
+
* - `"window"` — fall back straight to the window edge (Telegram family).
|
|
621
|
+
* Default: `"window"`.
|
|
622
|
+
*/
|
|
623
|
+
readonly lastResort?: "last-boundary" | "window";
|
|
624
|
+
/**
|
|
625
|
+
* Guard against slicing through a UTF-16 low surrogate (splitting an emoji).
|
|
626
|
+
* Default: `false`.
|
|
627
|
+
*/
|
|
628
|
+
readonly surrogateGuard?: boolean;
|
|
629
|
+
/**
|
|
630
|
+
* Pattern stripped from the START of each continuation chunk. Default `/^\n+/`
|
|
631
|
+
* (Telegram family). Slack family uses `/^\s+/`.
|
|
632
|
+
*/
|
|
633
|
+
readonly stripLeading?: RegExp;
|
|
634
|
+
/**
|
|
635
|
+
* When true, each resulting part is `.trim()`-ed and empty parts are dropped
|
|
636
|
+
* (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.
|
|
637
|
+
*/
|
|
638
|
+
readonly trimParts?: boolean;
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Split `text` into chunks no longer than the configured window, preferring
|
|
642
|
+
* natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.
|
|
643
|
+
*/
|
|
644
|
+
declare function chunkText(text: string, options: ChunkTextOptions): string[];
|
|
645
|
+
/** Options for {@link chunkByGrapheme}. */
|
|
646
|
+
interface ChunkByGraphemeOptions {
|
|
647
|
+
/** If `text.length <= limit`, it is returned as a single chunk. */
|
|
648
|
+
readonly limit: number;
|
|
649
|
+
/**
|
|
650
|
+
* Max length per emitted part during the grapheme walk. Defaults to `limit`.
|
|
651
|
+
* Callers that reserve room for a per-part prefix (e.g. SMS `"(i/N) "`) pass a
|
|
652
|
+
* `partLimit` below `limit`.
|
|
653
|
+
*/
|
|
654
|
+
readonly partLimit?: number;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,
|
|
658
|
+
* regional-indicator pair, or combining sequence. Distinct algorithm from
|
|
659
|
+
* {@link chunkText} — used by adapters that must respect grapheme boundaries
|
|
660
|
+
* (LINE, SMS) rather than search for whitespace boundaries.
|
|
661
|
+
*
|
|
662
|
+
* @public
|
|
663
|
+
*/
|
|
664
|
+
declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
|
|
665
|
+
|
|
666
|
+
export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
|
package/dist/index.d.ts
CHANGED
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
* }
|
|
13
13
|
* ```
|
|
14
14
|
*
|
|
15
|
+
* This union is intentionally **closed** — adding a platform edits it here
|
|
16
|
+
* rather than extending it externally. The trade-off (exhaustive narrowing over
|
|
17
|
+
* OCP purity) is recorded in `docs/adr/0001-message-event-closed-union.md`.
|
|
18
|
+
*
|
|
15
19
|
* @public
|
|
16
20
|
*/
|
|
17
21
|
/** Closed enum of supported transport platforms. */
|
|
@@ -325,6 +329,40 @@ declare class DeliveryRouter {
|
|
|
325
329
|
send(req: DeliveryRequest): Promise<SendResult>;
|
|
326
330
|
}
|
|
327
331
|
|
|
332
|
+
/**
|
|
333
|
+
* `GatewayConfigurationError` — shared base for per-adapter configuration
|
|
334
|
+
* errors (roadmap M0/M2).
|
|
335
|
+
*
|
|
336
|
+
* Every platform adapter previously defined an identical
|
|
337
|
+
* `ConfigurationError extends Error` (same `code`/`detail` fields, same
|
|
338
|
+
* options interface, same `` `${pkg}: ${code}` `` default message) — only the
|
|
339
|
+
* package prefix differed. This base single-sources that contract. Adapters
|
|
340
|
+
* extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
|
|
341
|
+
* their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
|
|
342
|
+
*
|
|
343
|
+
* @public
|
|
344
|
+
*/
|
|
345
|
+
/** Public input shape for the {@link GatewayConfigurationError} constructor. */
|
|
346
|
+
interface GatewayConfigurationErrorOptions {
|
|
347
|
+
readonly code: string;
|
|
348
|
+
readonly message?: string;
|
|
349
|
+
readonly detail?: string;
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Base configuration error. Not thrown directly by adapters — they subclass it
|
|
353
|
+
* with a fixed package prefix.
|
|
354
|
+
*/
|
|
355
|
+
declare class GatewayConfigurationError extends Error {
|
|
356
|
+
readonly name: string;
|
|
357
|
+
readonly code: string;
|
|
358
|
+
readonly detail: string | undefined;
|
|
359
|
+
/**
|
|
360
|
+
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
361
|
+
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
362
|
+
*/
|
|
363
|
+
constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
|
|
364
|
+
}
|
|
365
|
+
|
|
328
366
|
/**
|
|
329
367
|
* Gateway hooks — own contract, not a `Plugin.kind` extension
|
|
330
368
|
* (T4.1, ADRs D176, D177).
|
|
@@ -375,6 +413,17 @@ interface GatewayHook {
|
|
|
375
413
|
post_outbound?(ctx: PostOutboundContext): Promise<void> | void;
|
|
376
414
|
on_error?(ctx: OnErrorContext): Promise<void> | void;
|
|
377
415
|
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* `HookExecutor` — runs registered gateway hooks at their fire points.
|
|
419
|
+
*
|
|
420
|
+
* Split out of `hooks/types.ts` (which now holds the contract only) so the
|
|
421
|
+
* filename predicts its contents: interfaces live in `types.ts`, the run
|
|
422
|
+
* engine lives here. Behavior is identical to the previous colocated class.
|
|
423
|
+
*
|
|
424
|
+
* @public
|
|
425
|
+
*/
|
|
426
|
+
|
|
378
427
|
/**
|
|
379
428
|
* Runs registered hooks at the right fire points. Stateless — safe to
|
|
380
429
|
* construct per-event if hooks need event-scoped storage.
|
|
@@ -525,4 +574,93 @@ declare class SessionRouter {
|
|
|
525
574
|
resolveAgentId(event: MessageEvent): string;
|
|
526
575
|
}
|
|
527
576
|
|
|
528
|
-
|
|
577
|
+
/**
|
|
578
|
+
* `chunkText` — transport-agnostic, boundary-preferring text chunker.
|
|
579
|
+
*
|
|
580
|
+
* Single-sources the message-splitting knowledge that was copy-pasted across
|
|
581
|
+
* the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two
|
|
582
|
+
* boundary-search families that existed in the adapters:
|
|
583
|
+
*
|
|
584
|
+
* - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),
|
|
585
|
+
* boundary preference `"\n\n" → "\n" → " "`, UTF-16 surrogate-pair guard,
|
|
586
|
+
* leading-whitespace strip on continuation, optional part-trim.
|
|
587
|
+
* - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),
|
|
588
|
+
* boundary preference `"\n\n" → "\n"` (no space), no surrogate guard,
|
|
589
|
+
* leading-newline strip on continuation.
|
|
590
|
+
*
|
|
591
|
+
* The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different
|
|
592
|
+
* algorithm and is intentionally NOT folded in here — those adapters keep their
|
|
593
|
+
* grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.
|
|
594
|
+
*
|
|
595
|
+
* @public
|
|
596
|
+
*/
|
|
597
|
+
/** Options for {@link chunkText}. */
|
|
598
|
+
interface ChunkTextOptions {
|
|
599
|
+
/**
|
|
600
|
+
* Hard cap. If the whole input is `<= limit`, it is returned as a single
|
|
601
|
+
* chunk (subject to `trimParts`). Continuation chunks are cut within the
|
|
602
|
+
* `safeLimit` window.
|
|
603
|
+
*/
|
|
604
|
+
readonly limit: number;
|
|
605
|
+
/**
|
|
606
|
+
* Soft window each cut searches within. Defaults to `limit`. The Telegram
|
|
607
|
+
* family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).
|
|
608
|
+
*/
|
|
609
|
+
readonly safeLimit?: number;
|
|
610
|
+
/**
|
|
611
|
+
* Boundary strings tried, in order, from most to least preferred. A boundary
|
|
612
|
+
* is accepted once its position is `>= window * 0.5`; otherwise the next one
|
|
613
|
+
* is tried. Default: `["\n\n", "\n", " "]`.
|
|
614
|
+
*/
|
|
615
|
+
readonly boundaries?: readonly string[];
|
|
616
|
+
/**
|
|
617
|
+
* When no boundary reaches the half-window threshold:
|
|
618
|
+
* - `"last-boundary"` — use the last computed boundary if it is `> 0`,
|
|
619
|
+
* else fall back to the window edge (Slack family).
|
|
620
|
+
* - `"window"` — fall back straight to the window edge (Telegram family).
|
|
621
|
+
* Default: `"window"`.
|
|
622
|
+
*/
|
|
623
|
+
readonly lastResort?: "last-boundary" | "window";
|
|
624
|
+
/**
|
|
625
|
+
* Guard against slicing through a UTF-16 low surrogate (splitting an emoji).
|
|
626
|
+
* Default: `false`.
|
|
627
|
+
*/
|
|
628
|
+
readonly surrogateGuard?: boolean;
|
|
629
|
+
/**
|
|
630
|
+
* Pattern stripped from the START of each continuation chunk. Default `/^\n+/`
|
|
631
|
+
* (Telegram family). Slack family uses `/^\s+/`.
|
|
632
|
+
*/
|
|
633
|
+
readonly stripLeading?: RegExp;
|
|
634
|
+
/**
|
|
635
|
+
* When true, each resulting part is `.trim()`-ed and empty parts are dropped
|
|
636
|
+
* (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.
|
|
637
|
+
*/
|
|
638
|
+
readonly trimParts?: boolean;
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Split `text` into chunks no longer than the configured window, preferring
|
|
642
|
+
* natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.
|
|
643
|
+
*/
|
|
644
|
+
declare function chunkText(text: string, options: ChunkTextOptions): string[];
|
|
645
|
+
/** Options for {@link chunkByGrapheme}. */
|
|
646
|
+
interface ChunkByGraphemeOptions {
|
|
647
|
+
/** If `text.length <= limit`, it is returned as a single chunk. */
|
|
648
|
+
readonly limit: number;
|
|
649
|
+
/**
|
|
650
|
+
* Max length per emitted part during the grapheme walk. Defaults to `limit`.
|
|
651
|
+
* Callers that reserve room for a per-part prefix (e.g. SMS `"(i/N) "`) pass a
|
|
652
|
+
* `partLimit` below `limit`.
|
|
653
|
+
*/
|
|
654
|
+
readonly partLimit?: number;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,
|
|
658
|
+
* regional-indicator pair, or combining sequence. Distinct algorithm from
|
|
659
|
+
* {@link chunkText} — used by adapters that must respect grapheme boundaries
|
|
660
|
+
* (LINE, SMS) rather than search for whitespace boundaries.
|
|
661
|
+
*
|
|
662
|
+
* @public
|
|
663
|
+
*/
|
|
664
|
+
declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
|
|
665
|
+
|
|
666
|
+
export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
|
package/dist/index.js
CHANGED
|
@@ -33,7 +33,23 @@ var DeliveryRouter = class {
|
|
|
33
33
|
}
|
|
34
34
|
};
|
|
35
35
|
|
|
36
|
-
// src/
|
|
36
|
+
// src/errors/config-error.ts
|
|
37
|
+
var GatewayConfigurationError = class extends Error {
|
|
38
|
+
name = "GatewayConfigurationError";
|
|
39
|
+
code;
|
|
40
|
+
detail;
|
|
41
|
+
/**
|
|
42
|
+
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
43
|
+
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
44
|
+
*/
|
|
45
|
+
constructor(prefix, opts) {
|
|
46
|
+
super(opts.message ?? `${prefix}: ${opts.code}`);
|
|
47
|
+
this.code = opts.code;
|
|
48
|
+
this.detail = opts.detail;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// src/hooks/executor.ts
|
|
37
53
|
var HookExecutor = class {
|
|
38
54
|
constructor(hooks) {
|
|
39
55
|
this.hooks = hooks;
|
|
@@ -272,6 +288,82 @@ var SessionRouter = class {
|
|
|
272
288
|
}
|
|
273
289
|
};
|
|
274
290
|
|
|
275
|
-
|
|
291
|
+
// src/text/chunk.ts
|
|
292
|
+
function searchBoundary(remaining, window, boundaries) {
|
|
293
|
+
let cut = window;
|
|
294
|
+
for (const b of boundaries) {
|
|
295
|
+
cut = remaining.lastIndexOf(b, window);
|
|
296
|
+
if (cut >= window * 0.5) return cut;
|
|
297
|
+
}
|
|
298
|
+
return cut;
|
|
299
|
+
}
|
|
300
|
+
function assertPositiveInt(label, value) {
|
|
301
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
302
|
+
throw new RangeError(`${label} must be a positive integer, received ${value}`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
function guardSurrogate(text, cut) {
|
|
306
|
+
if (cut >= text.length) return cut;
|
|
307
|
+
const code = text.charCodeAt(cut);
|
|
308
|
+
return code >= 56320 && code <= 57343 ? cut - 1 : cut;
|
|
309
|
+
}
|
|
310
|
+
function findCut(remaining, window, boundaries, lastResort, surrogateGuard) {
|
|
311
|
+
let cut = searchBoundary(remaining, window, boundaries);
|
|
312
|
+
if (cut < window * 0.5) {
|
|
313
|
+
cut = lastResort === "last-boundary" && cut > 0 ? cut : window;
|
|
314
|
+
}
|
|
315
|
+
if (surrogateGuard) cut = guardSurrogate(remaining, cut);
|
|
316
|
+
return cut <= 0 ? window : cut;
|
|
317
|
+
}
|
|
318
|
+
function chunkText(text, options) {
|
|
319
|
+
const {
|
|
320
|
+
limit,
|
|
321
|
+
safeLimit = limit,
|
|
322
|
+
boundaries = ["\n\n", "\n", " "],
|
|
323
|
+
lastResort = "window",
|
|
324
|
+
surrogateGuard = false,
|
|
325
|
+
stripLeading = /^\n+/,
|
|
326
|
+
trimParts = false
|
|
327
|
+
} = options;
|
|
328
|
+
assertPositiveInt("chunkText: limit", limit);
|
|
329
|
+
assertPositiveInt("chunkText: safeLimit", safeLimit);
|
|
330
|
+
if (safeLimit > limit) {
|
|
331
|
+
throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);
|
|
332
|
+
}
|
|
333
|
+
const finalize = (parts2) => trimParts ? parts2.map((p) => p.trim()).filter((p) => p.length > 0) : parts2;
|
|
334
|
+
if (text.length <= limit) {
|
|
335
|
+
return finalize([text]);
|
|
336
|
+
}
|
|
337
|
+
const parts = [];
|
|
338
|
+
let remaining = text;
|
|
339
|
+
while (remaining.length > safeLimit) {
|
|
340
|
+
const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);
|
|
341
|
+
parts.push(remaining.slice(0, cut));
|
|
342
|
+
remaining = remaining.slice(cut).replace(stripLeading, "");
|
|
343
|
+
}
|
|
344
|
+
if (remaining.length > 0) parts.push(remaining);
|
|
345
|
+
return finalize(parts);
|
|
346
|
+
}
|
|
347
|
+
function chunkByGrapheme(text, options) {
|
|
348
|
+
const { limit, partLimit = limit } = options;
|
|
349
|
+
assertPositiveInt("chunkByGrapheme: limit", limit);
|
|
350
|
+
assertPositiveInt("chunkByGrapheme: partLimit", partLimit);
|
|
351
|
+
if (text.length === 0) return [""];
|
|
352
|
+
if (text.length <= limit) return [text];
|
|
353
|
+
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
354
|
+
const parts = [];
|
|
355
|
+
let buf = "";
|
|
356
|
+
for (const { segment } of segmenter.segment(text)) {
|
|
357
|
+
if (buf.length + segment.length > partLimit) {
|
|
358
|
+
if (buf.length > 0) parts.push(buf);
|
|
359
|
+
buf = "";
|
|
360
|
+
}
|
|
361
|
+
buf += segment;
|
|
362
|
+
}
|
|
363
|
+
if (buf.length > 0) parts.push(buf);
|
|
364
|
+
return parts;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export { BasePlatformAdapter, DeliveryRouter, GatewayConfigurationError, GatewayRunner, HookExecutor, SessionRouter, chunkByGrapheme, chunkText, defaultStrategy };
|
|
276
368
|
//# sourceMappingURL=index.js.map
|
|
277
369
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/hooks/types.ts","../src/runner/gateway-runner.ts","../src/session/router.ts"],"names":[],"mappings":";;;AAqDO,IAAe,sBAAf,MAAmC;AAAA;AAAA,EAmBxC,MAAM,YAAY,UAAA,EAAmC;AAAA,EAErD;AAAA;AAAA,EAGA,MAAM,WAAW,UAAA,EAAmC;AAAA,EAEpD;AACF;;;ACvCO,IAAM,iBAAN,MAAqB;AAAA,EACT,QAAA,uBAAe,GAAA,EAAuC;AAAA,EAEvE,SAAS,OAAA,EAAoC;AAC3C,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,QAAA,EAAU,OAAO,CAAA;AAAA,EAC7C;AAAA,EAEA,MAAM,KAAK,GAAA,EAA2C;AACpD,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,IAAI,QAAQ,CAAA;AAC9C,IAAA,IAAI,YAAY,MAAA,EAAW;AACzB,MAAA,OAAO;AAAA,QACL,EAAA,EAAI,KAAA;AAAA,QACJ,KAAA,EAAO,EAAE,IAAA,EAAM,YAAA,EAAc,SAAS,CAAA,yBAAA,EAA4B,GAAA,CAAI,QAAQ,CAAA,CAAA,CAAA;AAAI,OACpF;AAAA,IACF;AACA,IAAA,OAAO,QAAQ,WAAA,CAAY;AAAA,MACzB,SAAS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AAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA,EAA8C;AAAA,EAA9C,QAAA;AAAA,EAE7B,eAAe,KAAA,EAAoC;AACjD,IAAA,OAAO,IAAA,CAAK,SAAS,KAAK,CAAA;AAAA,EAC5B;AACF","file":"index.js","sourcesContent":["/**\n * `BasePlatformAdapter` — contract every transport adapter implements\n * (T1.2, ADR D172).\n *\n * Adapters share ~30% of lifecycle code (typing indicators, event\n * normalization patterns). An abstract class with concrete defaults\n * + abstract hooks is the right shape — interface-only would force\n * every adapter to copy the defaults.\n *\n * Consumers use it via `instanceof` and the public subclass exports\n * (`TelegramAdapter`, `DiscordAdapter`, ...).\n */\n\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Outbound message shape — what `sendMessage` accepts. */\nexport interface OutboundMessage {\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n readonly text: string;\n /** Markdown / HTML rendering hint. Default \"plain\". */\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n /** Optional reply target. */\n readonly replyTo?: string;\n}\n\n/** Send result — adapters return this instead of throwing on platform errors. */\nexport interface SendResult {\n readonly ok: boolean;\n readonly messageId?: string;\n readonly error?: { readonly code: string; readonly message: string };\n}\n\n/**\n * Abstract base for all platform adapters.\n *\n * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.\n * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden.\n *\n * **Contract:**\n * - `connect()` is idempotent. Calling twice returns true the second time.\n * - `disconnect()` is idempotent.\n * - `sendMessage` returns a `SendResult`; it MUST NOT throw on platform errors\n * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.\n * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling\n * `onInbound` twice replaces the previous handler — does NOT stack.\n * - `sendMessage` with empty text returns `{ ok: false, code: \"empty_text\" }`.\n *\n * @public\n */\nexport abstract class BasePlatformAdapter {\n abstract readonly platform: PlatformName;\n\n /** Open the connection. Returns `true` on success; never throws. */\n abstract connect(): Promise<boolean>;\n\n /** Close the connection. Idempotent; safe to call when never connected. */\n abstract disconnect(): Promise<void>;\n\n /** Send a message. Returns a `SendResult`; never throws on platform errors. */\n abstract sendMessage(out: OutboundMessage): Promise<SendResult>;\n\n /**\n * Subscribe to inbound events. Returns an unsubscribe function.\n * EC-H: second call REPLACES the previous handler (does not stack).\n */\n abstract onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void;\n\n /** Lifecycle: emit a typing indicator. Default: noop. */\n async startTyping(_channelId: string): Promise<void> {\n /* override */\n }\n\n /** Lifecycle: stop the typing indicator. Default: noop. */\n async stopTyping(_channelId: string): Promise<void> {\n /* override */\n }\n}\n","/**\n * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).\n *\n * The router holds a map of `platform → adapter` and forwards\n * `DeliveryRequest` to the right adapter's `sendMessage`. Composes\n * with `Cron` from `@theokit/sdk` for scheduled delivery — the\n * router is the \"WHERE to send\", Cron is the \"WHEN to fire\".\n *\n * @public\n */\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** Target for an outbound delivery. */\nexport interface DeliveryTarget {\n readonly platform: PlatformName;\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n}\n\n/** Full outbound request: target + content. */\nexport interface DeliveryRequest extends DeliveryTarget {\n readonly text: string;\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n readonly replyTo?: string;\n}\n\n/**\n * Routes outbound requests to the correct adapter.\n *\n * **Contract:**\n * - `register` is last-writer-wins by platform.\n * - `send` with unknown platform returns `{ ok: false, code: \"no_adapter\" }`.\n * - `send` never throws on platform errors (delegates to adapter's SendResult).\n *\n * @public\n */\nexport class DeliveryRouter {\n private readonly adapters = new Map<PlatformName, BasePlatformAdapter>();\n\n register(adapter: BasePlatformAdapter): void {\n this.adapters.set(adapter.platform, adapter);\n }\n\n async send(req: DeliveryRequest): Promise<SendResult> {\n const adapter = this.adapters.get(req.platform);\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for platform \"${req.platform}\"` },\n };\n }\n return adapter.sendMessage({\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n });\n }\n}\n","/**\n * Gateway hooks — own contract, not a `Plugin.kind` extension\n * (T4.1, ADRs D176, D177).\n *\n * Three fire points:\n * - `pre_inbound` — runs sequentially; first `{ block: true }` short-circuits.\n * - `post_outbound` — fire-and-forget; errors logged.\n * - `on_error` — fire-and-forget; called when the handler throws.\n *\n * Signature mirrors the SDK's `pre_tool_call` veto (D101) so consumers\n * have a single mental model for \"block or continue\" hooks.\n *\n * @public\n */\n\nimport type { OutboundMessage, SendResult } from \"../adapter/base.js\";\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Closed enum of hook fire points. */\nexport type HookName = \"pre_inbound\" | \"post_outbound\" | \"on_error\";\n\n/**\n * Decision returned by a `pre_inbound` hook.\n *\n * - `block: true` short-circuits the chain — handler does NOT run.\n * - `message` set → runner calls `ctx.reply(message)` BEFORE short-circuit (EC-D).\n * - `block: false` or `undefined` → continue.\n */\nexport interface HookDecision {\n readonly block?: boolean;\n readonly message?: string;\n}\n\n/** Context passed to `pre_inbound` hooks. */\nexport interface PreInboundContext {\n readonly event: GatewayMessageEvent;\n}\n\n/** Context passed to `post_outbound` hooks. */\nexport interface PostOutboundContext {\n readonly event: GatewayMessageEvent;\n readonly outbound: OutboundMessage;\n readonly result: SendResult;\n}\n\n/** Context passed to `on_error` hooks. */\nexport interface OnErrorContext {\n readonly event: GatewayMessageEvent;\n readonly error: Error;\n}\n\n/** A gateway hook: any of the three fire-point methods are optional. */\nexport interface GatewayHook {\n readonly name: string;\n // biome-ignore lint/suspicious/noConfusingVoidType: sync-or-async hook ergonomics — matches SDK pre_tool_call signature (D101).\n pre_inbound?(ctx: PreInboundContext): Promise<HookDecision | void> | HookDecision | void;\n post_outbound?(ctx: PostOutboundContext): Promise<void> | void;\n on_error?(ctx: OnErrorContext): Promise<void> | void;\n}\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {}\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n return {\n block: true,\n message: `hook ${h.name} threw: ${(err as Error).message}`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport { type GatewayHook, HookExecutor } from \"../hooks/types.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /** Connect all adapters and wire inbound dispatch. */\n async start(): Promise<void> {\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => setTimeout(r, drainMs)),\n ]);\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(\n `[gateway] handler error: ${Security.redact((err as Error).message)}\\n`,\n );\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n const adapter = this.adaptersByPlatform.get(event.platform);\n return {\n event,\n reply: async (text, opts) => {\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` },\n };\n }\n return adapter.sendMessage({\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n });\n },\n };\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/errors/config-error.ts","../src/hooks/executor.ts","../src/runner/gateway-runner.ts","../src/session/router.ts","../src/text/chunk.ts"],"names":["parts"],"mappings":";;;AAqDO,IAAe,sBAAf,MAAmC;AAAA;AAAA,EAmBxC,MAAM,YAAY,UAAA,EAAmC;AAAA,EAErD;AAAA;AAAA,EAGA,MAAM,WAAW,UAAA,EAAmC;AAAA,EAEpD;AACF;;;ACvCO,IAAM,iBAAN,MAAqB;AAAA,EACT,QAAA,uBAAe,GAAA,EAAuC;AAAA,EAEvE,SAAS,OAAA,EAAoC;AAC3C,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,QAAA,EAAU,OAAO,CAAA;AAAA,EAC7C;AAAA,EAEA,MAAM,KAAK,GAAA,EAA2C;AACpD,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,IAAI,QA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AAA,iBAAA,CAAkB,0BAA0B,KAAK,CAAA;AACjD,EAAA,iBAAA,CAAkB,8BAA8B,SAAS,CAAA;AACzD,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,CAAC,EAAE,CAAA;AACjC,EAAA,IAAI,IAAA,CAAK,MAAA,IAAU,KAAA,EAAO,OAAO,CAAC,IAAI,CAAA;AAEtC,EAAA,MAAM,SAAA,GAAY,IAAI,IAAA,CAAK,SAAA,CAAU,QAAW,EAAE,WAAA,EAAa,YAAY,CAAA;AAC3E,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,MAAW,EAAE,OAAA,EAAQ,IAAK,SAAA,CAAU,OAAA,CAAQ,IAAI,CAAA,EAAG;AACjD,IAAA,IAAI,GAAA,CAAI,MAAA,GAAS,OAAA,CAAQ,MAAA,GAAS,SAAA,EAAW;AAC3C,MAAA,IAAI,GAAA,CAAI,MAAA,GAAS,CAAA,EAAG,KAAA,CAAM,KAAK,GAAG,CAAA;AAClC,MAAA,GAAA,GAAM,EAAA;AAAA,IACR;AACA,IAAA,GAAA,IAAO,OAAA;AAAA,EACT;AACA,EAAA,IAAI,GAAA,CAAI,MAAA,GAAS,CAAA,EAAG,KAAA,CAAM,KAAK,GAAG,CAAA;AAClC,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["/**\n * `BasePlatformAdapter` — contract every transport adapter implements\n * (T1.2, ADR D172).\n *\n * Adapters share ~30% of lifecycle code (typing indicators, event\n * normalization patterns). An abstract class with concrete defaults\n * + abstract hooks is the right shape — interface-only would force\n * every adapter to copy the defaults.\n *\n * Consumers use it via `instanceof` and the public subclass exports\n * (`TelegramAdapter`, `DiscordAdapter`, ...).\n */\n\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Outbound message shape — what `sendMessage` accepts. */\nexport interface OutboundMessage {\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n readonly text: string;\n /** Markdown / HTML rendering hint. Default \"plain\". */\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n /** Optional reply target. */\n readonly replyTo?: string;\n}\n\n/** Send result — adapters return this instead of throwing on platform errors. */\nexport interface SendResult {\n readonly ok: boolean;\n readonly messageId?: string;\n readonly error?: { readonly code: string; readonly message: string };\n}\n\n/**\n * Abstract base for all platform adapters.\n *\n * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.\n * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden.\n *\n * **Contract:**\n * - `connect()` is idempotent. Calling twice returns true the second time.\n * - `disconnect()` is idempotent.\n * - `sendMessage` returns a `SendResult`; it MUST NOT throw on platform errors\n * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.\n * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling\n * `onInbound` twice replaces the previous handler — does NOT stack.\n * - `sendMessage` with empty text returns `{ ok: false, code: \"empty_text\" }`.\n *\n * @public\n */\nexport abstract class BasePlatformAdapter {\n abstract readonly platform: PlatformName;\n\n /** Open the connection. Returns `true` on success; never throws. */\n abstract connect(): Promise<boolean>;\n\n /** Close the connection. Idempotent; safe to call when never connected. */\n abstract disconnect(): Promise<void>;\n\n /** Send a message. Returns a `SendResult`; never throws on platform errors. */\n abstract sendMessage(out: OutboundMessage): Promise<SendResult>;\n\n /**\n * Subscribe to inbound events. Returns an unsubscribe function.\n * EC-H: second call REPLACES the previous handler (does not stack).\n */\n abstract onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void;\n\n /** Lifecycle: emit a typing indicator. Default: noop. */\n async startTyping(_channelId: string): Promise<void> {\n /* override */\n }\n\n /** Lifecycle: stop the typing indicator. Default: noop. */\n async stopTyping(_channelId: string): Promise<void> {\n /* override */\n }\n}\n","/**\n * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).\n *\n * The router holds a map of `platform → adapter` and forwards\n * `DeliveryRequest` to the right adapter's `sendMessage`. Composes\n * with `Cron` from `@theokit/sdk` for scheduled delivery — the\n * router is the \"WHERE to send\", Cron is the \"WHEN to fire\".\n *\n * @public\n */\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** Target for an outbound delivery. */\nexport interface DeliveryTarget {\n readonly platform: PlatformName;\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n}\n\n/** Full outbound request: target + content. */\nexport interface DeliveryRequest extends DeliveryTarget {\n readonly text: string;\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n readonly replyTo?: string;\n}\n\n/**\n * Routes outbound requests to the correct adapter.\n *\n * **Contract:**\n * - `register` is last-writer-wins by platform.\n * - `send` with unknown platform returns `{ ok: false, code: \"no_adapter\" }`.\n * - `send` never throws on platform errors (delegates to adapter's SendResult).\n *\n * @public\n */\nexport class DeliveryRouter {\n private readonly adapters = new Map<PlatformName, BasePlatformAdapter>();\n\n register(adapter: BasePlatformAdapter): void {\n this.adapters.set(adapter.platform, adapter);\n }\n\n async send(req: DeliveryRequest): Promise<SendResult> {\n const adapter = this.adapters.get(req.platform);\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for platform \"${req.platform}\"` },\n };\n }\n return adapter.sendMessage({\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n });\n }\n}\n","/**\n * `GatewayConfigurationError` — shared base for per-adapter configuration\n * errors (roadmap M0/M2).\n *\n * Every platform adapter previously defined an identical\n * `ConfigurationError extends Error` (same `code`/`detail` fields, same\n * options interface, same `` `${pkg}: ${code}` `` default message) — only the\n * package prefix differed. This base single-sources that contract. Adapters\n * extend it, pin their prefix, and keep `name = \"ConfigurationError\"` plus\n * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).\n *\n * @public\n */\n\n/** Public input shape for the {@link GatewayConfigurationError} constructor. */\nexport interface GatewayConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\n/**\n * Base configuration error. Not thrown directly by adapters — they subclass it\n * with a fixed package prefix.\n */\nexport class GatewayConfigurationError extends Error {\n override readonly name: string = \"GatewayConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n\n /**\n * @param prefix Package prefix used in the default message (e.g. `\"gateway-line\"`).\n * @param opts `code` (required), optional explicit `message`, optional `detail`.\n */\n constructor(prefix: string, opts: GatewayConfigurationErrorOptions) {\n super(opts.message ?? `${prefix}: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n","/**\n * `HookExecutor` — runs registered gateway hooks at their fire points.\n *\n * Split out of `hooks/types.ts` (which now holds the contract only) so the\n * filename predicts its contents: interfaces live in `types.ts`, the run\n * engine lives here. Behavior is identical to the previous colocated class.\n *\n * @public\n */\n\nimport type {\n GatewayHook,\n HookDecision,\n OnErrorContext,\n PostOutboundContext,\n PreInboundContext,\n} from \"./types.js\";\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {}\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n return {\n block: true,\n message: `hook ${h.name} threw: ${(err as Error).message}`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport { HookExecutor } from \"../hooks/executor.js\";\nimport type { GatewayHook } from \"../hooks/types.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /** Connect all adapters and wire inbound dispatch. */\n async start(): Promise<void> {\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => setTimeout(r, drainMs)),\n ]);\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(\n `[gateway] handler error: ${Security.redact((err as Error).message)}\\n`,\n );\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n const adapter = this.adaptersByPlatform.get(event.platform);\n return {\n event,\n reply: async (text, opts) => {\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` },\n };\n }\n return adapter.sendMessage({\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n });\n },\n };\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n","/**\n * `chunkText` — transport-agnostic, boundary-preferring text chunker.\n *\n * Single-sources the message-splitting knowledge that was copy-pasted across\n * the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two\n * boundary-search families that existed in the adapters:\n *\n * - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\" → \" \"`, UTF-16 surrogate-pair guard,\n * leading-whitespace strip on continuation, optional part-trim.\n * - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\"` (no space), no surrogate guard,\n * leading-newline strip on continuation.\n *\n * The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different\n * algorithm and is intentionally NOT folded in here — those adapters keep their\n * grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.\n *\n * @public\n */\n\n/** Options for {@link chunkText}. */\nexport interface ChunkTextOptions {\n /**\n * Hard cap. If the whole input is `<= limit`, it is returned as a single\n * chunk (subject to `trimParts`). Continuation chunks are cut within the\n * `safeLimit` window.\n */\n readonly limit: number;\n /**\n * Soft window each cut searches within. Defaults to `limit`. The Telegram\n * family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).\n */\n readonly safeLimit?: number;\n /**\n * Boundary strings tried, in order, from most to least preferred. A boundary\n * is accepted once its position is `>= window * 0.5`; otherwise the next one\n * is tried. Default: `[\"\\n\\n\", \"\\n\", \" \"]`.\n */\n readonly boundaries?: readonly string[];\n /**\n * When no boundary reaches the half-window threshold:\n * - `\"last-boundary\"` — use the last computed boundary if it is `> 0`,\n * else fall back to the window edge (Slack family).\n * - `\"window\"` — fall back straight to the window edge (Telegram family).\n * Default: `\"window\"`.\n */\n readonly lastResort?: \"last-boundary\" | \"window\";\n /**\n * Guard against slicing through a UTF-16 low surrogate (splitting an emoji).\n * Default: `false`.\n */\n readonly surrogateGuard?: boolean;\n /**\n * Pattern stripped from the START of each continuation chunk. Default `/^\\n+/`\n * (Telegram family). Slack family uses `/^\\s+/`.\n */\n readonly stripLeading?: RegExp;\n /**\n * When true, each resulting part is `.trim()`-ed and empty parts are dropped\n * (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.\n */\n readonly trimParts?: boolean;\n}\n\n/** Most-preferred boundary at `>= window*0.5`, else the last boundary tried. */\nfunction searchBoundary(remaining: string, window: number, boundaries: readonly string[]): number {\n let cut = window;\n for (const b of boundaries) {\n cut = remaining.lastIndexOf(b, window);\n if (cut >= window * 0.5) return cut;\n }\n return cut;\n}\n\n/** Fail fast on a non-positive / non-integer size argument. */\nfunction assertPositiveInt(label: string, value: number): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new RangeError(`${label} must be a positive integer, received ${value}`);\n }\n}\n\n/** Step back one code unit if `cut` would sever a UTF-16 surrogate pair. */\nfunction guardSurrogate(text: string, cut: number): number {\n if (cut >= text.length) return cut;\n const code = text.charCodeAt(cut);\n return code >= 0xdc00 && code <= 0xdfff ? cut - 1 : cut;\n}\n\nfunction findCut(\n remaining: string,\n window: number,\n boundaries: readonly string[],\n lastResort: \"last-boundary\" | \"window\",\n surrogateGuard: boolean,\n): number {\n let cut = searchBoundary(remaining, window, boundaries);\n if (cut < window * 0.5) {\n cut = lastResort === \"last-boundary\" && cut > 0 ? cut : window;\n }\n if (surrogateGuard) cut = guardSurrogate(remaining, cut);\n return cut <= 0 ? window : cut;\n}\n\n/**\n * Split `text` into chunks no longer than the configured window, preferring\n * natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.\n */\nexport function chunkText(text: string, options: ChunkTextOptions): string[] {\n const {\n limit,\n safeLimit = limit,\n boundaries = [\"\\n\\n\", \"\\n\", \" \"],\n lastResort = \"window\",\n surrogateGuard = false,\n stripLeading = /^\\n+/,\n trimParts = false,\n } = options;\n\n // Fail fast at the boundary: a non-positive `limit` would make `findCut`\n // return 0 forever and hang the loop; `safeLimit > limit` would break the\n // \"hard cap\" contract by emitting an oversized tail chunk.\n assertPositiveInt(\"chunkText: limit\", limit);\n assertPositiveInt(\"chunkText: safeLimit\", safeLimit);\n if (safeLimit > limit) {\n throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);\n }\n\n const finalize = (parts: string[]): string[] =>\n trimParts ? parts.map((p) => p.trim()).filter((p) => p.length > 0) : parts;\n\n if (text.length <= limit) {\n return finalize([text]);\n }\n\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > safeLimit) {\n const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);\n parts.push(remaining.slice(0, cut));\n remaining = remaining.slice(cut).replace(stripLeading, \"\");\n }\n if (remaining.length > 0) parts.push(remaining);\n return finalize(parts);\n}\n\n/** Options for {@link chunkByGrapheme}. */\nexport interface ChunkByGraphemeOptions {\n /** If `text.length <= limit`, it is returned as a single chunk. */\n readonly limit: number;\n /**\n * Max length per emitted part during the grapheme walk. Defaults to `limit`.\n * Callers that reserve room for a per-part prefix (e.g. SMS `\"(i/N) \"`) pass a\n * `partLimit` below `limit`.\n */\n readonly partLimit?: number;\n}\n\n/**\n * Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,\n * regional-indicator pair, or combining sequence. Distinct algorithm from\n * {@link chunkText} — used by adapters that must respect grapheme boundaries\n * (LINE, SMS) rather than search for whitespace boundaries.\n *\n * @public\n */\nexport function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[] {\n const { limit, partLimit = limit } = options;\n assertPositiveInt(\"chunkByGrapheme: limit\", limit);\n assertPositiveInt(\"chunkByGrapheme: partLimit\", partLimit);\n if (text.length === 0) return [\"\"];\n if (text.length <= limit) return [text];\n\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const parts: string[] = [];\n let buf = \"\";\n for (const { segment } of segmenter.segment(text)) {\n if (buf.length + segment.length > partLimit) {\n if (buf.length > 0) parts.push(buf);\n buf = \"\";\n }\n buf += segment;\n }\n if (buf.length > 0) parts.push(buf);\n return parts;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Multi-platform messaging gateway core for @theokit/sdk — transport-agnostic primitives (BasePlatformAdapter, MessageEvent, SessionRouter, DeliveryRouter, GatewayRunner, hooks). Inspired by hermes-agent/gateway. ADRs D170-D181.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -34,12 +34,13 @@
|
|
|
34
34
|
"test": "vitest run"
|
|
35
35
|
},
|
|
36
36
|
"peerDependencies": {
|
|
37
|
-
"@theokit/sdk": "
|
|
37
|
+
"@theokit/sdk": "^2.18.0"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
|
-
"@theokit/sdk": "
|
|
40
|
+
"@theokit/sdk": "^2.18.0",
|
|
41
41
|
"tsup": "^8.5.0",
|
|
42
42
|
"typescript": "^5.8.0",
|
|
43
|
-
"vitest": "^
|
|
43
|
+
"vitest": "^4.1.8",
|
|
44
|
+
"zod": "^4.0.0"
|
|
44
45
|
}
|
|
45
46
|
}
|