@theokit/gateway 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +106 -0
- package/dist/index.cjs +61 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +65 -5
- package/dist/index.d.ts +65 -5
- package/dist/index.js +61 -20
- package/dist/index.js.map +1 -1
- package/package.json +14 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,111 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 08abaed: **`GatewayRunner.stop()` is now terminal, and says so instead of leaving a runner nothing can stop.**
|
|
8
|
+
|
|
9
|
+
`start()` and `stop()` were each written to be idempotent, but they guarded on different flags. `stop()` cleared `connected` and set `stopped`; nothing ever cleared `stopped`. So a second `start()` sailed past its `connected` guard, reconnected every adapter and rewired inbound dispatch — while the next `stop()` returned at its own `stopped` guard without disconnecting anything. Measured on the previous release: two connects, one disconnect, and a live inbound handler that no call could take down.
|
|
10
|
+
|
|
11
|
+
Nothing reported this. The adapters stayed connected, the events kept arriving, and both methods returned normally. A process that reloads configuration or reconnects after a network failure by restarting the runner leaked a connection every cycle.
|
|
12
|
+
|
|
13
|
+
`start()` on a stopped runner now throws `GatewayLifecycleError` with `code: "runner_stopped"`, and the message says to construct a new runner. That is the whole of the behaviour change: a call that previously appeared to succeed while corrupting state now fails at the call that cannot be honoured, which is the only point where a caller can still do something about it.
|
|
14
|
+
|
|
15
|
+
Adds `GatewayLifecycleError` and `GatewayLifecycleErrorOptions` to the public API. It is deliberately separate from `GatewayConfigurationError`: that one reports a bad setting, this one reports a fine setting used at an impossible moment.
|
|
16
|
+
|
|
17
|
+
- 66e08ba: **A third WhatsApp backend: `WhatsAppBaileysBackend`.** It speaks the WhatsApp Web multi-device protocol over a WebSocket. Where the `web` backend drives a headless Chromium through `whatsapp-web.js`, this holds a socket — that is the whole difference in kind.
|
|
18
|
+
|
|
19
|
+
Reach it with `WhatsAppAdapter.fromBaileys({ sessionDir })`, or through `WhatsAppAdapter.from({ backend: "baileys", baileys: { … } })` when the choice arrives as configuration rather than as a decision in code. `baileys` is an **optional peer dependency** (`>=7.0.0-rc14`), loaded lazily at connect: a consumer who never constructs this never needs it installed.
|
|
20
|
+
|
|
21
|
+
**Added rather than replacing**, for three reasons a substitution would not give. Nobody loses a paired session — a Puppeteer profile and a multi-file auth state are not interchangeable. The comparison against the incumbent becomes measurable rather than asserted, which is the whole point: no comparison has been made yet, and this changeset does not claim one. And retreat stays cheap, because nobody is forced onto it.
|
|
22
|
+
|
|
23
|
+
**Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session, which Meta's terms do not sanction and which can get a number banned. Use a number created for this and nothing else, never a personal one.
|
|
24
|
+
|
|
25
|
+
Three decisions worth naming:
|
|
26
|
+
|
|
27
|
+
_Sends are serialised_ — one `sendMessage` in flight per socket, including when one times out. That last clause was not true when this was first written: the queue advanced on the raced result, and a timeout does not cancel a `sendMessage`, so a timed-out send stayed on the socket while the next one started — reaching the exact hazard the serialisation exists to prevent, through the timeout meant to bound it. A review found it; there is now a test that fails if the queue goes back to advancing on the race. Honest about provenance: both peer gateways studied do this and one records that concurrent sends on a single socket can misdeliver to the wrong chat. **We have not measured that in our own code**, so it is precaution rather than a reproduction of our own bug. Kept because the cost is one promise chain and the failure it guards against is a message reaching the wrong person.
|
|
28
|
+
|
|
29
|
+
_A timed-out send reports undetermined delivery, and is never retried._ A local timeout says the acknowledgement did not arrive, not that the message did not; retrying can duplicate — the failure this repository already shipped once, in the email backend re-answering its inbox.
|
|
30
|
+
|
|
31
|
+
_A connect that fails or is superseded tears its socket down._ A timed-out connect used to leave a live socket behind: it kept feeding inbound into the handler, and the retry opened a second live session — which on an unofficial automation is ban surface, not merely a leak. The same generation counter makes `disconnect()` during an in-flight `connect()` safe; without it the late success set `connected` over a backend with no socket, and every later send was refused until the object was rebuilt.
|
|
32
|
+
|
|
33
|
+
_The backend depends on a three-member socket contract we declare_, not on Baileys' types. That is what lets every test in this backend drive a fake and run with `baileys` absent — which matters, because a backend that could only be exercised with the real library installed is a backend exercised by nothing, and that is exactly how the `web` backend reached production unable to start.
|
|
34
|
+
|
|
35
|
+
_A retired connection attempt is ended, not merely silenced._ Retiring by generation made an abandoned attempt's listeners no-ops — including the one that resolves it — so nothing could settle it but the timeout. A `disconnect()` during pairing therefore blocked shutdown for the full 60s default while the socket it asked to close stayed live. And a socket that closed under the backend kept its reference until the next `connect()` overwrote it, so it was never ended and no later `disconnect()` could reach it. Both are fixed, as is a third window a later round found: a `disconnect()` landing while the factory itself was still awaiting — a dynamic import, the auth state off disk, and a network round-trip for the protocol version all happen before a socket exists — could not see an attempt that had no socket yet. Each has a test that fails when its fix alone is reverted.
|
|
36
|
+
|
|
37
|
+
_A failed connect says why._ `false` with no output cannot distinguish a network blip from a device the operator unlinked from their phone, and only one of those is worth retrying — a supervisor that cannot tell them apart retries forever against a session that can only be re-paired.
|
|
38
|
+
|
|
39
|
+
_Pairing has somewhere to go._ `printQRInTerminal` stays off — a library writing to stdout decides where a host's output goes — so the QR is handed to an `onQr` callback, defaulting to stderr. Without it a fresh session directory could only ever time out: there is no other way to pair.
|
|
40
|
+
|
|
41
|
+
**What no test here proves.** Nothing in this repository touches WhatsApp. Pairing needs a QR scan by a human and there is no WhatsApp in Docker, so protocol conformance, delivery, receipts and ban behaviour are unproven by this changeset and by every gate in this repository. A green suite means our logic does what we think — not that WhatsApp agrees.
|
|
42
|
+
|
|
43
|
+
The socket contract this backend depends on lost a member: `logout()` was declared and called by nothing, and on WhatsApp `logout()` **unpairs the device** — the opposite of what `disconnect()` means here. A dead member advertising a destructive capability is worse than an absent one.
|
|
44
|
+
|
|
45
|
+
`WhatsAppMessageEvent.whatsapp.backend` and `WhatsAppBackend.kind` gain a third member, so an exhaustive `switch` over either stops compiling until the case is handled. No call site in this repository switches on them.
|
|
46
|
+
|
|
47
|
+
### Patch Changes
|
|
48
|
+
|
|
49
|
+
- e682180: **A message whose handler throws no longer kills the bot.** On Teams and on WhatsApp's web backend it did — not degraded delivery, an exit code. `Error: ... / Node.js v22.22.2`, and the next message never arrived.
|
|
50
|
+
|
|
51
|
+
Both dispatched with `void handler(event)`. `void` reads as "I am not waiting for this"; what it tells the runtime is "I am not handling the error", and under Node 22's default an unhandled rejection ends the process. Measured against both adapters through their own injection seams before the fix, and again after: the throw is now contained, named, and delivery continues.
|
|
52
|
+
|
|
53
|
+
**Discord and Telegram contained it but blamed the wrong thing.** The rejection escaped into the platform library's error channel, so a bug in the consumer's own handler surfaced as `[discord] client error` / `[telegram] bot error`. Anyone debugging that went looking in discord.js and grammy for a fault that was in their own code. Both now report `handler threw` and return `"handler_threw"` from the internal dispatch seam.
|
|
54
|
+
|
|
55
|
+
**WhatsApp Cloud dropped the rest of the batch, and made the platform resend it.** Meta packs several messages and their delivery receipts into one webhook, and the dispatch loop awaited each handler with nothing around it. One throw skipped every remaining message in the payload, skipped the status receipts, and rejected `handleWebhookPayload` — so the caller's route answered 500 and Meta redelivered the whole batch, replaying the messages that had already been handled. That is a duplicate-reply bug reached through a different door than the one fixed in #11. The same method also now answers `false` on a signed body that is not JSON, instead of throwing out of a method whose contract is `true`/`false`.
|
|
56
|
+
|
|
57
|
+
**Email gained a net it did not strictly need.** Its drain is written never to reject, and it does not — but both launch sites discard the promise, so that property was the only thing between a future edit and the same fatal rejection, and nothing enforced it. The catch now lives at the site that would pay for it.
|
|
58
|
+
|
|
59
|
+
**The contract is written down, and held to.** `BasePlatformAdapter.onInbound` now states it: a handler may throw, and an adapter must contain that throw, report it as the handler's failure rather than the platform's, and keep delivering. Eight of ten adapters had converged on exactly that with nothing recording it. `tests/lint/adapter-contract.test.ts` gains two invariants — every adapter names a handler throw as the handler's, and no adapter launches a user callback with a bare `void` — and both were checked against a deliberately reverted adapter to confirm they fire rather than pass vacuously.
|
|
60
|
+
|
|
61
|
+
- 9c35372: **Slack now answers `empty_text` for empty text, like the other nine adapters.** The contract states it without a condition — `sendMessage` with empty text returns `{ ok: false, code: "empty_text" }` — but Slack checked the connection first, so the same call answered `not_connected` there and `empty_text` everywhere else.
|
|
62
|
+
|
|
63
|
+
Nobody lost a delivery over it: both results are already `ok: false`. What broke is code that branches on the code — treating a caller's bad input one way and an unavailable transport another, with a retry or an alert behind the second. Written against the contract, that code did the right thing on nine platforms and the wrong thing on the tenth, with nothing to say why.
|
|
64
|
+
|
|
65
|
+
The connection guard keeps its reason (`this.app` is set before `app.start()` resolves, so a send in that window would otherwise leak through); only the order changed. Input first, transport second, which is what `rules/error-handling.md` § 2 asks for and what the other nine already did.
|
|
66
|
+
|
|
67
|
+
The cross-adapter gate gains the invariant, and it is checked against a deliberately reverted adapter. That check earned its keep immediately: the first version of the invariant read a window of raw source that its own explanatory comment filled, so it passed against the reverted adapter by matching the prose describing the rule. It now strips comments before asking — a gate answered by a comment is worse than no gate, because it reports coverage it does not have.
|
|
68
|
+
|
|
69
|
+
- b8ef098: **Every package now ships the licence it declares.** All twelve manifests in this repository declare `Apache-2.0`, and the repository had no `LICENSE` file at all — not at the root, and not in any package directory except `gateway-email`. So each published tarball asserted a licence while carrying none of its terms, and §4(a) of that licence requires a copy to travel with the distribution. Worse than a missing file: with no licence text anywhere, everything outside the manifests fell back to default copyright, which grants a recipient nothing.
|
|
70
|
+
|
|
71
|
+
The text is now at the repository root and inside every publishable package, byte-identical to the canonical Apache License 2.0 with the appendix filled in (`Copyright 2026 usetheo.dev`). The one pre-existing copy, in `gateway-email`, was replaced along with the rest: it carried the same truncated paragraph 4(d) found across the ecosystem, dropping "reasonable and customary use" from the NOTICE clause — a modified body under an unmodified SPDX identifier.
|
|
72
|
+
|
|
73
|
+
**The repository moved to the official `usetheokit` organization.** Existing clones and published URLs keep working through GitHub's permanent redirect; the root manifest now declares `Apache-2.0` explicitly rather than leaving the workspace root silent.
|
|
74
|
+
|
|
75
|
+
- 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
|
|
76
|
+
|
|
77
|
+
**LINE — no outbound message was ever delivered.** The adapter called the v9 SDK client with positional arguments while that client takes a single request object, so LINE received an empty request and rejected every send with a 400. Upgrade if you use this adapter at all: nothing it sent reached anyone.
|
|
78
|
+
|
|
79
|
+
**Telegram — the bot froze on long replies.** Any message over 4096 characters that began with an unclosed code span (a stray backtick) put the splitter into an infinite loop, hanging the process until it ran out of memory. Long agent answers now split correctly whatever markdown they contain.
|
|
80
|
+
|
|
81
|
+
**Mattermost — long messages silently vanished.** The adapter never split anything, so any reply over 16,383 characters was rejected by the server and the user simply saw nothing. Long replies are now split into parts Mattermost accepts.
|
|
82
|
+
|
|
83
|
+
**SMS — long messages were rejected from the hundredth part onward.** The `(i/N)` prefix outgrew the space reserved for it, pushing every later part past the provider's limit.
|
|
84
|
+
|
|
85
|
+
**Matrix and LINE — `connect()` reported success with an invalid token.** Both now verify the credential with the server before returning `true`, so a wrong token fails at startup instead of silently receiving nothing forever.
|
|
86
|
+
|
|
87
|
+
**Email and Teams — the bot could go permanently deaf.** Replacing an inbound handler and then disposing of the previous one removed the new handler as well, and the gateway stopped receiving messages with nothing logged.
|
|
88
|
+
|
|
89
|
+
Also: a `pre_inbound` hook that threw put its raw error text into the user's chat, which could expose internal details such as connection strings or tokens. Users now see only which hook failed; the detail goes to the server log, redacted.
|
|
90
|
+
|
|
91
|
+
WhatsApp additionally stops opening a second session when `connect()` is called twice, and its group mention filter no longer treats unrelated digits scattered through a message as a mention of the bot.
|
|
92
|
+
|
|
93
|
+
- 144b2ba: **The `post_outbound` hook now fires.** It is one of the three fire points `GatewayHook` documents and exports, and no production code had ever called it: `HookExecutor.firePostOutbound` existed, was typed, was unit-tested, and had exactly one caller in the repository — its own test.
|
|
94
|
+
|
|
95
|
+
That is the worst shape a broken contract can take. Registering a `post_outbound` hook for delivery auditing, outbound metrics or reply logging raised no error and produced no warning. The hook was simply never invoked, and the instrumentation a consumer believed they had did not exist.
|
|
96
|
+
|
|
97
|
+
Every reply now leaves through one path that sends and then reports, so the hook fires exactly once per attempt with `{ event, outbound, result }` — including the EC-D auto-reply sent when a `pre_inbound` hook blocks with a message, and including the attempt that finds no adapter registered for the event's platform. That last case matters more than it looks: a hook counting deliveries would otherwise omit precisely the replies that went nowhere.
|
|
98
|
+
|
|
99
|
+
The hook observes; it does not intercept. The adapter's `SendResult` reaches the caller of `reply` unchanged, and a hook that throws is contained by `HookExecutor`, so a broken observer cannot turn a delivered reply into a failed one.
|
|
100
|
+
|
|
101
|
+
- 111f837: **`stop()` no longer holds the process open for the whole drain window.** A bot that stopped on `SIGINT` sat there for ten more seconds before the process exited, with nothing running and nothing to wait for.
|
|
102
|
+
|
|
103
|
+
`stop()` drains in-flight handlers by racing them against a `drainTimeoutMs` timer. `Promise.race` settles on whichever branch finishes first and abandons the other — but an abandoned `setTimeout` is still a scheduled timer, and a scheduled timer keeps Node's event loop alive. The drain finished in under a millisecond; the timer it beat kept the process running for the remaining ten seconds. Measured before the fix: `stop()` returned after 0 ms, the process exited after 10 001 ms. After: 1 ms.
|
|
104
|
+
|
|
105
|
+
The delay only appeared once at least one event had been dispatched, since the drain branch is guarded on there being something in flight — which is to say, on every real bot rather than on any test that stopped a runner it had never used. Under an orchestrator that sends `SIGTERM` and then `SIGKILL`, the difference is whether shutdown is clean or forced.
|
|
106
|
+
|
|
107
|
+
The timer handle is now cleared in a `finally`, so the cleanup does not depend on which branch of the race won.
|
|
108
|
+
|
|
3
109
|
## 0.5.1
|
|
4
110
|
|
|
5
111
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -50,6 +50,17 @@ var GatewayConfigurationError = class extends Error {
|
|
|
50
50
|
this.detail = opts.detail;
|
|
51
51
|
}
|
|
52
52
|
};
|
|
53
|
+
|
|
54
|
+
// src/errors/lifecycle-error.ts
|
|
55
|
+
var GatewayLifecycleError = class extends Error {
|
|
56
|
+
name = "GatewayLifecycleError";
|
|
57
|
+
/** Stable discriminator, so callers branch on `code` rather than on message text. */
|
|
58
|
+
code;
|
|
59
|
+
constructor(opts) {
|
|
60
|
+
super(opts.message);
|
|
61
|
+
this.code = opts.code;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
53
64
|
var HookExecutor = class {
|
|
54
65
|
constructor(hooks) {
|
|
55
66
|
this.hooks = hooks;
|
|
@@ -136,8 +147,19 @@ var GatewayRunner = class {
|
|
|
136
147
|
command(name, handler) {
|
|
137
148
|
this.commands.set(name, handler);
|
|
138
149
|
}
|
|
139
|
-
/**
|
|
150
|
+
/**
|
|
151
|
+
* Connect all adapters and wire inbound dispatch.
|
|
152
|
+
*
|
|
153
|
+
* @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
|
|
154
|
+
* stopped. A stopped runner is spent; construct a new one.
|
|
155
|
+
*/
|
|
140
156
|
async start() {
|
|
157
|
+
if (this.stopped) {
|
|
158
|
+
throw new GatewayLifecycleError({
|
|
159
|
+
code: "runner_stopped",
|
|
160
|
+
message: "GatewayRunner.start(): this runner has already been stopped and cannot be restarted. Construct a new GatewayRunner instead."
|
|
161
|
+
});
|
|
162
|
+
}
|
|
141
163
|
if (this.connected) return;
|
|
142
164
|
const connected = [];
|
|
143
165
|
try {
|
|
@@ -178,10 +200,17 @@ var GatewayRunner = class {
|
|
|
178
200
|
this.unsubs.length = 0;
|
|
179
201
|
const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
|
|
180
202
|
if (this.inflight.size > 0) {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
203
|
+
let timer;
|
|
204
|
+
try {
|
|
205
|
+
await Promise.race([
|
|
206
|
+
Promise.all([...this.inflight]).then(() => void 0),
|
|
207
|
+
new Promise((r) => {
|
|
208
|
+
timer = setTimeout(r, drainMs);
|
|
209
|
+
})
|
|
210
|
+
]);
|
|
211
|
+
} finally {
|
|
212
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
213
|
+
}
|
|
185
214
|
}
|
|
186
215
|
await Promise.all(
|
|
187
216
|
[...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => void 0))
|
|
@@ -242,24 +271,36 @@ var GatewayRunner = class {
|
|
|
242
271
|
}
|
|
243
272
|
/** EC-G: per-event ctx whose reply routes to the matching adapter. */
|
|
244
273
|
buildContext(event) {
|
|
245
|
-
const adapter = this.adaptersByPlatform.get(event.platform);
|
|
246
274
|
return {
|
|
247
275
|
event,
|
|
248
|
-
reply: async (text, opts) => {
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
};
|
|
254
|
-
}
|
|
255
|
-
return adapter.sendMessage({
|
|
256
|
-
channel: event.channel,
|
|
257
|
-
text,
|
|
258
|
-
...opts?.format !== void 0 ? { format: opts.format } : {}
|
|
259
|
-
});
|
|
260
|
-
}
|
|
276
|
+
reply: async (text, opts) => this.deliver(event, {
|
|
277
|
+
channel: event.channel,
|
|
278
|
+
text,
|
|
279
|
+
...opts?.format !== void 0 ? { format: opts.format } : {}
|
|
280
|
+
})
|
|
261
281
|
};
|
|
262
282
|
}
|
|
283
|
+
/**
|
|
284
|
+
* Send one outbound on behalf of `event` and report it to `post_outbound`.
|
|
285
|
+
*
|
|
286
|
+
* Every reply leaves through here so the hook fires exactly once per attempt —
|
|
287
|
+
* including the EC-D auto-reply, and including the attempt that finds no
|
|
288
|
+
* adapter for the platform. An audit hook that counted only the deliveries
|
|
289
|
+
* which reached a transport would omit precisely the ones that went nowhere.
|
|
290
|
+
*
|
|
291
|
+
* `post_outbound` observes; it does not intercept. The adapter's `SendResult`
|
|
292
|
+
* is returned to the caller unchanged, and `HookExecutor` already contains a
|
|
293
|
+
* throwing hook, so a broken observer cannot turn a delivered reply into a
|
|
294
|
+
* failed one.
|
|
295
|
+
*
|
|
296
|
+
* @internal
|
|
297
|
+
*/
|
|
298
|
+
async deliver(event, outbound) {
|
|
299
|
+
const adapter = this.adaptersByPlatform.get(event.platform);
|
|
300
|
+
const result = adapter === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : await adapter.sendMessage(outbound);
|
|
301
|
+
await this.hookExecutor.firePostOutbound({ event, outbound, result });
|
|
302
|
+
return result;
|
|
303
|
+
}
|
|
263
304
|
};
|
|
264
305
|
|
|
265
306
|
// src/session/router.ts
|
|
@@ -371,6 +412,7 @@ function chunkByGrapheme(text, options) {
|
|
|
371
412
|
exports.BasePlatformAdapter = BasePlatformAdapter;
|
|
372
413
|
exports.DeliveryRouter = DeliveryRouter;
|
|
373
414
|
exports.GatewayConfigurationError = GatewayConfigurationError;
|
|
415
|
+
exports.GatewayLifecycleError = GatewayLifecycleError;
|
|
374
416
|
exports.GatewayRunner = GatewayRunner;
|
|
375
417
|
exports.HookExecutor = HookExecutor;
|
|
376
418
|
exports.SessionRouter = SessionRouter;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/errors/config-error.ts","../src/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,Y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,SAAS,eAAA,CAAgB,MAAc,OAAA,EAA2C;AACvF,EAAA,MAAM,EAAE,KAAA,EAAO,SAAA,GAAY,KAAA,EAAM,GAAI,OAAA;AACrC,EAAA,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.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 { Security } from \"@theokit/sdk\";\n\nimport type {\n GatewayHook,\n HookDecision,\n OnErrorContext,\n PostOutboundContext,\n PreInboundContext,\n} from \"./types.js\";\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {}\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n // `GatewayRunner.dispatch` replies with this message straight into the\n // chat, so it must never carry the exception text. It used to:\n // `hook ${h.name} threw: ${err.message}` sent whatever the hook happened\n // to throw — connection strings, internal ids, bearer tokens — to the end\n // user verbatim. The sibling handler path already logs through\n // `Security.redact` (EC-F); this one skipped redaction entirely, and the\n // test asserting the raw text appeared locked the leak in as expected\n // behaviour.\n //\n // The detail is not lost, only moved: stderr gets it, redacted.\n process.stderr.write(\n `[gateway] pre_inbound hook \"${h.name}\" threw: ${Security.redact((err as Error).message)}\\n`,\n );\n return {\n block: true,\n message: `Request blocked: hook \"${h.name}\" failed.`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport { HookExecutor } from \"../hooks/executor.js\";\nimport type { GatewayHook } from \"../hooks/types.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /** Connect all adapters and wire inbound dispatch. */\n async start(): Promise<void> {\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => setTimeout(r, drainMs)),\n ]);\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(\n `[gateway] handler error: ${Security.redact((err as Error).message)}\\n`,\n );\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n const adapter = this.adaptersByPlatform.get(event.platform);\n return {\n event,\n reply: async (text, opts) => {\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` },\n };\n }\n return adapter.sendMessage({\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n });\n },\n };\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n","/**\n * `chunkText` — transport-agnostic, boundary-preferring text chunker.\n *\n * Single-sources the message-splitting knowledge that was copy-pasted across\n * the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two\n * boundary-search families that existed in the adapters:\n *\n * - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\" → \" \"`, UTF-16 surrogate-pair guard,\n * leading-whitespace strip on continuation, optional part-trim.\n * - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\"` (no space), no surrogate guard,\n * leading-newline strip on continuation.\n *\n * The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different\n * algorithm and is intentionally NOT folded in here — those adapters keep their\n * grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.\n *\n * @public\n */\n\n/** Options for {@link chunkText}. */\nexport interface ChunkTextOptions {\n /**\n * Hard cap. If the whole input is `<= limit`, it is returned as a single\n * chunk (subject to `trimParts`). Continuation chunks are cut within the\n * `safeLimit` window.\n */\n readonly limit: number;\n /**\n * Soft window each cut searches within. Defaults to `limit`. The Telegram\n * family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).\n */\n readonly safeLimit?: number;\n /**\n * Boundary strings tried, in order, from most to least preferred. A boundary\n * is accepted once its position is `>= window * 0.5`; otherwise the next one\n * is tried. Default: `[\"\\n\\n\", \"\\n\", \" \"]`.\n */\n readonly boundaries?: readonly string[];\n /**\n * When no boundary reaches the half-window threshold:\n * - `\"last-boundary\"` — use the last computed boundary if it is `> 0`,\n * else fall back to the window edge (Slack family).\n * - `\"window\"` — fall back straight to the window edge (Telegram family).\n * Default: `\"window\"`.\n */\n readonly lastResort?: \"last-boundary\" | \"window\";\n /**\n * Guard against slicing through a UTF-16 low surrogate (splitting an emoji).\n * Default: `false`.\n */\n readonly surrogateGuard?: boolean;\n /**\n * Pattern stripped from the START of each continuation chunk. Default `/^\\n+/`\n * (Telegram family). Slack family uses `/^\\s+/`.\n */\n readonly stripLeading?: RegExp;\n /**\n * When true, each resulting part is `.trim()`-ed and empty parts are dropped\n * (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.\n */\n readonly trimParts?: boolean;\n}\n\n/** Most-preferred boundary at `>= window*0.5`, else the last boundary tried. */\nfunction searchBoundary(remaining: string, window: number, boundaries: readonly string[]): number {\n let cut = window;\n for (const b of boundaries) {\n cut = remaining.lastIndexOf(b, window);\n if (cut >= window * 0.5) return cut;\n }\n return cut;\n}\n\n/** Fail fast on a non-positive / non-integer size argument. */\nfunction assertPositiveInt(label: string, value: number): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new RangeError(`${label} must be a positive integer, received ${value}`);\n }\n}\n\n/** Step back one code unit if `cut` would sever a UTF-16 surrogate pair. */\nfunction guardSurrogate(text: string, cut: number): number {\n if (cut >= text.length) return cut;\n const code = text.charCodeAt(cut);\n return code >= 0xdc00 && code <= 0xdfff ? cut - 1 : cut;\n}\n\nfunction findCut(\n remaining: string,\n window: number,\n boundaries: readonly string[],\n lastResort: \"last-boundary\" | \"window\",\n surrogateGuard: boolean,\n): number {\n let cut = searchBoundary(remaining, window, boundaries);\n if (cut < window * 0.5) {\n cut = lastResort === \"last-boundary\" && cut > 0 ? cut : window;\n }\n if (surrogateGuard) cut = guardSurrogate(remaining, cut);\n return cut <= 0 ? window : cut;\n}\n\n/**\n * Split `text` into chunks no longer than the configured window, preferring\n * natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.\n */\nexport function chunkText(text: string, options: ChunkTextOptions): string[] {\n const {\n limit,\n safeLimit = limit,\n boundaries = [\"\\n\\n\", \"\\n\", \" \"],\n lastResort = \"window\",\n surrogateGuard = false,\n stripLeading = /^\\n+/,\n trimParts = false,\n } = options;\n\n // Fail fast at the boundary: a non-positive `limit` would make `findCut`\n // return 0 forever and hang the loop; `safeLimit > limit` would break the\n // \"hard cap\" contract by emitting an oversized tail chunk.\n assertPositiveInt(\"chunkText: limit\", limit);\n assertPositiveInt(\"chunkText: safeLimit\", safeLimit);\n if (safeLimit > limit) {\n throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);\n }\n\n const finalize = (parts: string[]): string[] =>\n trimParts ? parts.map((p) => p.trim()).filter((p) => p.length > 0) : parts;\n\n if (text.length <= limit) {\n return finalize([text]);\n }\n\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > safeLimit) {\n const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);\n parts.push(remaining.slice(0, cut));\n remaining = remaining.slice(cut).replace(stripLeading, \"\");\n }\n if (remaining.length > 0) parts.push(remaining);\n return finalize(parts);\n}\n\n/** Options for {@link chunkByGrapheme}. */\nexport interface ChunkByGraphemeOptions {\n /** If `text.length <= limit`, it is returned as a single chunk. */\n readonly limit: number;\n /**\n * Max length per emitted part during the grapheme walk. Defaults to `limit`.\n * Callers that reserve room for a per-part prefix (e.g. SMS `\"(i/N) \"`) pass a\n * `partLimit` below `limit`.\n */\n readonly partLimit?: number;\n}\n\n/**\n * Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,\n * regional-indicator pair, or combining sequence. Distinct algorithm from\n * {@link chunkText} — used by adapters that must respect grapheme boundaries\n * (LINE, SMS) rather than search for whitespace boundaries.\n *\n * @public\n */\nexport function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[] {\n const { limit, partLimit = limit } = options;\n assertPositiveInt(\"chunkByGrapheme: limit\", limit);\n assertPositiveInt(\"chunkByGrapheme: partLimit\", partLimit);\n if (text.length === 0) return [\"\"];\n if (text.length <= limit) return [text];\n\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const parts: string[] = [];\n let buf = \"\";\n for (const { segment } of segmenter.segment(text)) {\n if (buf.length + segment.length > partLimit) {\n if (buf.length > 0) parts.push(buf);\n buf = \"\";\n }\n buf += segment;\n }\n if (buf.length > 0) parts.push(buf);\n return parts;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/errors/config-error.ts","../src/errors/lifecycle-error.ts","../src/hooks/executor.ts","../src/runner/gateway-runner.ts","../src/session/router.ts","../src/text/chunk.ts"],"names":["Security","parts"],"mappings":";;;;;AAqDO,IAAe,sBAAf,MAAmC;AAAA;AAAA,EA2BxC,MAAM,YAAY,UAAA,EAAmC;AAAA,EAErD;AAAA;AAAA,EAGA,MAAM,WAAW,UAAA,EAAmC;AAAA,EAEpD;AACF;;;AC/CO,IAAM,iBAAN,MAAqB;AAAA,EACT,QAAA,uBAAe,GAAA,EAAuC;AAAA,EAEvE,SAAS,OAAA,EAAoC;AAC3C,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,QAAA,EAAU,OAAO,CAAA;AAAA,EAC7C;AAAA,EAEA,MAAM,KAAK,GAAA,EAA2C;AACpD,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,GA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AAA,GAAM,EAAA;AACV,EAAA,KAAA,MAAW,EAAE,OAAA,EAAQ,IAAK,SAAA,CAAU,OAAA,CAAQ,IAAI,CAAA,EAAG;AACjD,IAAA,IAAI,GAAA,CAAI,MAAA,GAAS,OAAA,CAAQ,MAAA,GAAS,SAAA,EAAW;AAC3C,MAAA,IAAI,GAAA,CAAI,MAAA,GAAS,CAAA,EAAG,KAAA,CAAM,KAAK,GAAG,CAAA;AAClC,MAAA,GAAA,GAAM,EAAA;AAAA,IACR;AACA,IAAA,GAAA,IAAO,OAAA;AAAA,EACT;AACA,EAAA,IAAI,GAAA,CAAI,MAAA,GAAS,CAAA,EAAG,KAAA,CAAM,KAAK,GAAG,CAAA;AAClC,EAAA,OAAO,KAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * `BasePlatformAdapter` — contract every transport adapter implements\n * (T1.2, ADR D172).\n *\n * Adapters share ~30% of lifecycle code (typing indicators, event\n * normalization patterns). An abstract class with concrete defaults\n * + abstract hooks is the right shape — interface-only would force\n * every adapter to copy the defaults.\n *\n * Consumers use it via `instanceof` and the public subclass exports\n * (`TelegramAdapter`, `DiscordAdapter`, ...).\n */\n\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Outbound message shape — what `sendMessage` accepts. */\nexport interface OutboundMessage {\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n readonly text: string;\n /** Markdown / HTML rendering hint. Default \"plain\". */\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n /** Optional reply target. */\n readonly replyTo?: string;\n}\n\n/** Send result — adapters return this instead of throwing on platform errors. */\nexport interface SendResult {\n readonly ok: boolean;\n readonly messageId?: string;\n readonly error?: { readonly code: string; readonly message: string };\n}\n\n/**\n * Abstract base for all platform adapters.\n *\n * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.\n * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden.\n *\n * **Contract:**\n * - `connect()` is idempotent. Calling twice returns true the second time.\n * - `disconnect()` is idempotent.\n * - `sendMessage` returns a `SendResult`; it MUST NOT throw on platform errors\n * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.\n * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling\n * `onInbound` twice replaces the previous handler — does NOT stack.\n * - `sendMessage` with empty text returns `{ ok: false, code: \"empty_text\" }`.\n *\n * @public\n */\nexport abstract class BasePlatformAdapter {\n abstract readonly platform: PlatformName;\n\n /** Open the connection. Returns `true` on success; never throws. */\n abstract connect(): Promise<boolean>;\n\n /** Close the connection. Idempotent; safe to call when never connected. */\n abstract disconnect(): Promise<void>;\n\n /** Send a message. Returns a `SendResult`; never throws on platform errors. */\n abstract sendMessage(out: OutboundMessage): Promise<SendResult>;\n\n /**\n * Subscribe to inbound events. Returns an unsubscribe function.\n * EC-H: second call REPLACES the previous handler (does not stack).\n *\n * The handler is user code and may throw. An adapter MUST contain that throw, report it as the\n * HANDLER's failure — not the platform's — and keep delivering: one bad message never ends the\n * process nor the connection. Two adapters used to discard the rejection with `void`, which under\n * Node's default ends the process, and two more reported it as a platform-client error, sending\n * whoever debugged their own handler to the wrong repository. Eight had converged on the right\n * behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds all\n * ten to it.\n */\n abstract onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void;\n\n /** Lifecycle: emit a typing indicator. Default: noop. */\n async startTyping(_channelId: string): Promise<void> {\n /* override */\n }\n\n /** Lifecycle: stop the typing indicator. Default: noop. */\n async stopTyping(_channelId: string): Promise<void> {\n /* override */\n }\n}\n","/**\n * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).\n *\n * The router holds a map of `platform → adapter` and forwards\n * `DeliveryRequest` to the right adapter's `sendMessage`. Composes\n * with `Cron` from `@theokit/sdk` for scheduled delivery — the\n * router is the \"WHERE to send\", Cron is the \"WHEN to fire\".\n *\n * @public\n */\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** Target for an outbound delivery. */\nexport interface DeliveryTarget {\n readonly platform: PlatformName;\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n}\n\n/** Full outbound request: target + content. */\nexport interface DeliveryRequest extends DeliveryTarget {\n readonly text: string;\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n readonly replyTo?: string;\n}\n\n/**\n * Routes outbound requests to the correct adapter.\n *\n * **Contract:**\n * - `register` is last-writer-wins by platform.\n * - `send` with unknown platform returns `{ ok: false, code: \"no_adapter\" }`.\n * - `send` never throws on platform errors (delegates to adapter's SendResult).\n *\n * @public\n */\nexport class DeliveryRouter {\n private readonly adapters = new Map<PlatformName, BasePlatformAdapter>();\n\n register(adapter: BasePlatformAdapter): void {\n this.adapters.set(adapter.platform, adapter);\n }\n\n async send(req: DeliveryRequest): Promise<SendResult> {\n const adapter = this.adapters.get(req.platform);\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for platform \"${req.platform}\"` },\n };\n }\n return adapter.sendMessage({\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n });\n }\n}\n","/**\n * `GatewayConfigurationError` — shared base for per-adapter configuration\n * errors (roadmap M0/M2).\n *\n * Every platform adapter previously defined an identical\n * `ConfigurationError extends Error` (same `code`/`detail` fields, same\n * options interface, same `` `${pkg}: ${code}` `` default message) — only the\n * package prefix differed. This base single-sources that contract. Adapters\n * extend it, pin their prefix, and keep `name = \"ConfigurationError\"` plus\n * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).\n *\n * @public\n */\n\n/** Public input shape for the {@link GatewayConfigurationError} constructor. */\nexport interface GatewayConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\n/**\n * Base configuration error. Not thrown directly by adapters — they subclass it\n * with a fixed package prefix.\n */\nexport class GatewayConfigurationError extends Error {\n override readonly name: string = \"GatewayConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n\n /**\n * @param prefix Package prefix used in the default message (e.g. `\"gateway-line\"`).\n * @param opts `code` (required), optional explicit `message`, optional `detail`.\n */\n constructor(prefix: string, opts: GatewayConfigurationErrorOptions) {\n super(opts.message ?? `${prefix}: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n","/**\n * `GatewayLifecycleError` — a lifecycle method was called from a state that\n * cannot honour it.\n *\n * Distinct from {@link GatewayConfigurationError}, which reports a bad or\n * missing setting at construction time. This one reports a legal call made at\n * an illegal moment: the configuration is fine, the ordering is not.\n *\n * It exists because the alternative is worse than an error. `GatewayRunner`\n * used to accept `start()` after `stop()` and quietly produce a runner that\n * reconnected its adapters and then refused to disconnect them — a leak that\n * reported success. Failing loudly at the call that cannot be honoured is the\n * only outcome a caller can act on.\n *\n * @public\n */\n\n/** Public input shape for the {@link GatewayLifecycleError} constructor. */\nexport interface GatewayLifecycleErrorOptions {\n /** Stable, machine-readable discriminator (e.g. `\"runner_stopped\"`). */\n readonly code: string;\n /** Human-readable explanation, including what the caller should do instead. */\n readonly message: string;\n}\n\n/**\n * Thrown when a lifecycle transition is not available from the current state.\n *\n * @public\n */\nexport class GatewayLifecycleError extends Error {\n override readonly name: string = \"GatewayLifecycleError\";\n /** Stable discriminator, so callers branch on `code` rather than on message text. */\n readonly code: string;\n\n constructor(opts: GatewayLifecycleErrorOptions) {\n super(opts.message);\n this.code = opts.code;\n }\n}\n","/**\n * `HookExecutor` — runs registered gateway hooks at their fire points.\n *\n * Split out of `hooks/types.ts` (which now holds the contract only) so the\n * filename predicts its contents: interfaces live in `types.ts`, the run\n * engine lives here. Behavior is identical to the previous colocated class.\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type {\n GatewayHook,\n HookDecision,\n OnErrorContext,\n PostOutboundContext,\n PreInboundContext,\n} from \"./types.js\";\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {}\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n // `GatewayRunner.dispatch` replies with this message straight into the\n // chat, so it must never carry the exception text. It used to:\n // `hook ${h.name} threw: ${err.message}` sent whatever the hook happened\n // to throw — connection strings, internal ids, bearer tokens — to the end\n // user verbatim. The sibling handler path already logs through\n // `Security.redact` (EC-F); this one skipped redaction entirely, and the\n // test asserting the raw text appeared locked the leak in as expected\n // behaviour.\n //\n // The detail is not lost, only moved: stderr gets it, redacted.\n process.stderr.write(\n `[gateway] pre_inbound hook \"${h.name}\" threw: ${Security.redact((err as Error).message)}\\n`,\n );\n return {\n block: true,\n message: `Request blocked: hook \"${h.name}\" failed.`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner\n * cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).\n *\n * Every reply — the handler's `ctx.reply` and the EC-D auto-reply alike — fires\n * `post_outbound` with the event, the outbound and the adapter's result, once\n * per attempt. The hook observes the delivery; it cannot change what the caller\n * of `reply` receives.\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, OutboundMessage, SendResult } from \"../adapter/base.js\";\nimport { GatewayLifecycleError } from \"../errors/lifecycle-error.js\";\nimport { HookExecutor } from \"../hooks/executor.js\";\nimport type { GatewayHook } from \"../hooks/types.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /**\n * Connect all adapters and wire inbound dispatch.\n *\n * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already\n * stopped. A stopped runner is spent; construct a new one.\n */\n async start(): Promise<void> {\n if (this.stopped) {\n // Silently reconnecting here is what produced the unstoppable runner:\n // `stop()` cleared `connected` but never `stopped`, so a second start()\n // passed the guard below and rewired everything, while the next stop()\n // returned at its own guard without disconnecting anything (#39).\n throw new GatewayLifecycleError({\n code: \"runner_stopped\",\n message:\n \"GatewayRunner.start(): this runner has already been stopped and cannot be restarted. Construct a new GatewayRunner instead.\",\n });\n }\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n // The loser of the race has to be cancelled explicitly. `Promise.race`\n // settles on the first branch and abandons the other, but an abandoned\n // `setTimeout` is still a scheduled timer, and a scheduled timer keeps\n // Node's event loop alive: `stop()` returned in 0ms while the process\n // only exited `drainMs` later, so a bot stopping on SIGINT hung for the\n // whole drain window before dying (#37).\n let timer: NodeJS.Timeout | undefined;\n try {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => {\n timer = setTimeout(r, drainMs);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(\n `[gateway] handler error: ${Security.redact((err as Error).message)}\\n`,\n );\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n return {\n event,\n reply: async (text, opts) =>\n this.deliver(event, {\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n }),\n };\n }\n\n /**\n * Send one outbound on behalf of `event` and report it to `post_outbound`.\n *\n * Every reply leaves through here so the hook fires exactly once per attempt —\n * including the EC-D auto-reply, and including the attempt that finds no\n * adapter for the platform. An audit hook that counted only the deliveries\n * which reached a transport would omit precisely the ones that went nowhere.\n *\n * `post_outbound` observes; it does not intercept. The adapter's `SendResult`\n * is returned to the caller unchanged, and `HookExecutor` already contains a\n * throwing hook, so a broken observer cannot turn a delivered reply into a\n * failed one.\n *\n * @internal\n */\n private async deliver(\n event: GatewayMessageEvent,\n outbound: OutboundMessage,\n ): Promise<SendResult> {\n const adapter = this.adaptersByPlatform.get(event.platform);\n const result: SendResult =\n adapter === undefined\n ? { ok: false, error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` } }\n : await adapter.sendMessage(outbound);\n await this.hookExecutor.firePostOutbound({ event, outbound, result });\n return result;\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n","/**\n * `chunkText` — transport-agnostic, boundary-preferring text chunker.\n *\n * Single-sources the message-splitting knowledge that was copy-pasted across\n * the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two\n * boundary-search families that existed in the adapters:\n *\n * - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\" → \" \"`, UTF-16 surrogate-pair guard,\n * leading-whitespace strip on continuation, optional part-trim.\n * - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\"` (no space), no surrogate guard,\n * leading-newline strip on continuation.\n *\n * The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different\n * algorithm and is intentionally NOT folded in here — those adapters keep their\n * grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.\n *\n * @public\n */\n\n/** Options for {@link chunkText}. */\nexport interface ChunkTextOptions {\n /**\n * Hard cap. If the whole input is `<= limit`, it is returned as a single\n * chunk (subject to `trimParts`). Continuation chunks are cut within the\n * `safeLimit` window.\n */\n readonly limit: number;\n /**\n * Soft window each cut searches within. Defaults to `limit`. The Telegram\n * family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).\n */\n readonly safeLimit?: number;\n /**\n * Boundary strings tried, in order, from most to least preferred. A boundary\n * is accepted once its position is `>= window * 0.5`; otherwise the next one\n * is tried. Default: `[\"\\n\\n\", \"\\n\", \" \"]`.\n */\n readonly boundaries?: readonly string[];\n /**\n * When no boundary reaches the half-window threshold:\n * - `\"last-boundary\"` — use the last computed boundary if it is `> 0`,\n * else fall back to the window edge (Slack family).\n * - `\"window\"` — fall back straight to the window edge (Telegram family).\n * Default: `\"window\"`.\n */\n readonly lastResort?: \"last-boundary\" | \"window\";\n /**\n * Guard against slicing through a UTF-16 low surrogate (splitting an emoji).\n * Default: `false`.\n */\n readonly surrogateGuard?: boolean;\n /**\n * Pattern stripped from the START of each continuation chunk. Default `/^\\n+/`\n * (Telegram family). Slack family uses `/^\\s+/`.\n */\n readonly stripLeading?: RegExp;\n /**\n * When true, each resulting part is `.trim()`-ed and empty parts are dropped\n * (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.\n */\n readonly trimParts?: boolean;\n}\n\n/** Most-preferred boundary at `>= window*0.5`, else the last boundary tried. */\nfunction searchBoundary(remaining: string, window: number, boundaries: readonly string[]): number {\n let cut = window;\n for (const b of boundaries) {\n cut = remaining.lastIndexOf(b, window);\n if (cut >= window * 0.5) return cut;\n }\n return cut;\n}\n\n/** Fail fast on a non-positive / non-integer size argument. */\nfunction assertPositiveInt(label: string, value: number): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new RangeError(`${label} must be a positive integer, received ${value}`);\n }\n}\n\n/** Step back one code unit if `cut` would sever a UTF-16 surrogate pair. */\nfunction guardSurrogate(text: string, cut: number): number {\n if (cut >= text.length) return cut;\n const code = text.charCodeAt(cut);\n return code >= 0xdc00 && code <= 0xdfff ? cut - 1 : cut;\n}\n\nfunction findCut(\n remaining: string,\n window: number,\n boundaries: readonly string[],\n lastResort: \"last-boundary\" | \"window\",\n surrogateGuard: boolean,\n): number {\n let cut = searchBoundary(remaining, window, boundaries);\n if (cut < window * 0.5) {\n cut = lastResort === \"last-boundary\" && cut > 0 ? cut : window;\n }\n if (surrogateGuard) cut = guardSurrogate(remaining, cut);\n return cut <= 0 ? window : cut;\n}\n\n/**\n * Split `text` into chunks no longer than the configured window, preferring\n * natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.\n */\nexport function chunkText(text: string, options: ChunkTextOptions): string[] {\n const {\n limit,\n safeLimit = limit,\n boundaries = [\"\\n\\n\", \"\\n\", \" \"],\n lastResort = \"window\",\n surrogateGuard = false,\n stripLeading = /^\\n+/,\n trimParts = false,\n } = options;\n\n // Fail fast at the boundary: a non-positive `limit` would make `findCut`\n // return 0 forever and hang the loop; `safeLimit > limit` would break the\n // \"hard cap\" contract by emitting an oversized tail chunk.\n assertPositiveInt(\"chunkText: limit\", limit);\n assertPositiveInt(\"chunkText: safeLimit\", safeLimit);\n if (safeLimit > limit) {\n throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);\n }\n\n const finalize = (parts: string[]): string[] =>\n trimParts ? parts.map((p) => p.trim()).filter((p) => p.length > 0) : parts;\n\n if (text.length <= limit) {\n return finalize([text]);\n }\n\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > safeLimit) {\n const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);\n parts.push(remaining.slice(0, cut));\n remaining = remaining.slice(cut).replace(stripLeading, \"\");\n }\n if (remaining.length > 0) parts.push(remaining);\n return finalize(parts);\n}\n\n/** Options for {@link chunkByGrapheme}. */\nexport interface ChunkByGraphemeOptions {\n /** If `text.length <= limit`, it is returned as a single chunk. */\n readonly limit: number;\n /**\n * Max length per emitted part during the grapheme walk. Defaults to `limit`.\n * Callers that reserve room for a per-part prefix (e.g. SMS `\"(i/N) \"`) pass a\n * `partLimit` below `limit`.\n */\n readonly partLimit?: number;\n}\n\n/**\n * Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,\n * regional-indicator pair, or combining sequence. Distinct algorithm from\n * {@link chunkText} — used by adapters that must respect grapheme boundaries\n * (LINE, SMS) rather than search for whitespace boundaries.\n *\n * @public\n */\nexport function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[] {\n const { limit, partLimit = limit } = options;\n assertPositiveInt(\"chunkByGrapheme: limit\", limit);\n assertPositiveInt(\"chunkByGrapheme: partLimit\", partLimit);\n if (text.length === 0) return [\"\"];\n if (text.length <= limit) return [text];\n\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const parts: string[] = [];\n let buf = \"\";\n for (const { segment } of segmenter.segment(text)) {\n if (buf.length + segment.length > partLimit) {\n if (buf.length > 0) parts.push(buf);\n buf = \"\";\n }\n buf += segment;\n }\n if (buf.length > 0) parts.push(buf);\n return parts;\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -97,8 +97,14 @@ interface WhatsAppMessageEvent extends BaseMessageEvent {
|
|
|
97
97
|
readonly phoneNumberId?: string;
|
|
98
98
|
/** Contact's profile name when Meta provides it. */
|
|
99
99
|
readonly contactName?: string;
|
|
100
|
-
/**
|
|
101
|
-
|
|
100
|
+
/**
|
|
101
|
+
* Which backend produced this event.
|
|
102
|
+
*
|
|
103
|
+
* `baileys` joined `cloud` and `web` in 0.2: it speaks the WhatsApp Web multi-device
|
|
104
|
+
* protocol over a WebSocket, where `web` drives a headless browser. Consumers that
|
|
105
|
+
* switch exhaustively on this must handle the third case.
|
|
106
|
+
*/
|
|
107
|
+
readonly backend: "cloud" | "web" | "baileys";
|
|
102
108
|
/** Raw envelope — backend-specific, narrowed by the adapter package. */
|
|
103
109
|
readonly raw: unknown;
|
|
104
110
|
};
|
|
@@ -279,6 +285,14 @@ declare abstract class BasePlatformAdapter {
|
|
|
279
285
|
/**
|
|
280
286
|
* Subscribe to inbound events. Returns an unsubscribe function.
|
|
281
287
|
* EC-H: second call REPLACES the previous handler (does not stack).
|
|
288
|
+
*
|
|
289
|
+
* The handler is user code and may throw. An adapter MUST contain that throw, report it as the
|
|
290
|
+
* HANDLER's failure — not the platform's — and keep delivering: one bad message never ends the
|
|
291
|
+
* process nor the connection. Two adapters used to discard the rejection with `void`, which under
|
|
292
|
+
* Node's default ends the process, and two more reported it as a platform-client error, sending
|
|
293
|
+
* whoever debugged their own handler to the wrong repository. Eight had converged on the right
|
|
294
|
+
* behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds all
|
|
295
|
+
* ten to it.
|
|
282
296
|
*/
|
|
283
297
|
abstract onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
284
298
|
/** Lifecycle: emit a typing indicator. Default: noop. */
|
|
@@ -363,6 +377,41 @@ declare class GatewayConfigurationError extends Error {
|
|
|
363
377
|
constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
|
|
364
378
|
}
|
|
365
379
|
|
|
380
|
+
/**
|
|
381
|
+
* `GatewayLifecycleError` — a lifecycle method was called from a state that
|
|
382
|
+
* cannot honour it.
|
|
383
|
+
*
|
|
384
|
+
* Distinct from {@link GatewayConfigurationError}, which reports a bad or
|
|
385
|
+
* missing setting at construction time. This one reports a legal call made at
|
|
386
|
+
* an illegal moment: the configuration is fine, the ordering is not.
|
|
387
|
+
*
|
|
388
|
+
* It exists because the alternative is worse than an error. `GatewayRunner`
|
|
389
|
+
* used to accept `start()` after `stop()` and quietly produce a runner that
|
|
390
|
+
* reconnected its adapters and then refused to disconnect them — a leak that
|
|
391
|
+
* reported success. Failing loudly at the call that cannot be honoured is the
|
|
392
|
+
* only outcome a caller can act on.
|
|
393
|
+
*
|
|
394
|
+
* @public
|
|
395
|
+
*/
|
|
396
|
+
/** Public input shape for the {@link GatewayLifecycleError} constructor. */
|
|
397
|
+
interface GatewayLifecycleErrorOptions {
|
|
398
|
+
/** Stable, machine-readable discriminator (e.g. `"runner_stopped"`). */
|
|
399
|
+
readonly code: string;
|
|
400
|
+
/** Human-readable explanation, including what the caller should do instead. */
|
|
401
|
+
readonly message: string;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Thrown when a lifecycle transition is not available from the current state.
|
|
405
|
+
*
|
|
406
|
+
* @public
|
|
407
|
+
*/
|
|
408
|
+
declare class GatewayLifecycleError extends Error {
|
|
409
|
+
readonly name: string;
|
|
410
|
+
/** Stable discriminator, so callers branch on `code` rather than on message text. */
|
|
411
|
+
readonly code: string;
|
|
412
|
+
constructor(opts: GatewayLifecycleErrorOptions);
|
|
413
|
+
}
|
|
414
|
+
|
|
366
415
|
/**
|
|
367
416
|
* Gateway hooks — own contract, not a `Plugin.kind` extension
|
|
368
417
|
* (T4.1, ADRs D176, D177).
|
|
@@ -456,7 +505,8 @@ declare class HookExecutor {
|
|
|
456
505
|
* failure rolls back: connected adapters get `disconnect()`, then the
|
|
457
506
|
* aggregate error rethrows.
|
|
458
507
|
* - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)
|
|
459
|
-
* BEFORE disconnecting (EC-E). Idempotent
|
|
508
|
+
* BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner
|
|
509
|
+
* cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.
|
|
460
510
|
*
|
|
461
511
|
* **Hook chain on inbound:**
|
|
462
512
|
* 1. `firePreInbound({ event })`
|
|
@@ -465,6 +515,11 @@ declare class HookExecutor {
|
|
|
465
515
|
* 4. Otherwise: call user handler.
|
|
466
516
|
* 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).
|
|
467
517
|
*
|
|
518
|
+
* Every reply — the handler's `ctx.reply` and the EC-D auto-reply alike — fires
|
|
519
|
+
* `post_outbound` with the event, the outbound and the adapter's result, once
|
|
520
|
+
* per attempt. The hook observes the delivery; it cannot change what the caller
|
|
521
|
+
* of `reply` receives.
|
|
522
|
+
*
|
|
468
523
|
* @public
|
|
469
524
|
*/
|
|
470
525
|
|
|
@@ -520,7 +575,12 @@ declare class GatewayRunner {
|
|
|
520
575
|
* @public
|
|
521
576
|
*/
|
|
522
577
|
command(name: string, handler: GatewayHandler): void;
|
|
523
|
-
/**
|
|
578
|
+
/**
|
|
579
|
+
* Connect all adapters and wire inbound dispatch.
|
|
580
|
+
*
|
|
581
|
+
* @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
|
|
582
|
+
* stopped. A stopped runner is spent; construct a new one.
|
|
583
|
+
*/
|
|
524
584
|
start(): Promise<void>;
|
|
525
585
|
/**
|
|
526
586
|
* Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
|
|
@@ -663,4 +723,4 @@ interface ChunkByGraphemeOptions {
|
|
|
663
723
|
*/
|
|
664
724
|
declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
|
|
665
725
|
|
|
666
|
-
export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
|
|
726
|
+
export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
|
package/dist/index.d.ts
CHANGED
|
@@ -97,8 +97,14 @@ interface WhatsAppMessageEvent extends BaseMessageEvent {
|
|
|
97
97
|
readonly phoneNumberId?: string;
|
|
98
98
|
/** Contact's profile name when Meta provides it. */
|
|
99
99
|
readonly contactName?: string;
|
|
100
|
-
/**
|
|
101
|
-
|
|
100
|
+
/**
|
|
101
|
+
* Which backend produced this event.
|
|
102
|
+
*
|
|
103
|
+
* `baileys` joined `cloud` and `web` in 0.2: it speaks the WhatsApp Web multi-device
|
|
104
|
+
* protocol over a WebSocket, where `web` drives a headless browser. Consumers that
|
|
105
|
+
* switch exhaustively on this must handle the third case.
|
|
106
|
+
*/
|
|
107
|
+
readonly backend: "cloud" | "web" | "baileys";
|
|
102
108
|
/** Raw envelope — backend-specific, narrowed by the adapter package. */
|
|
103
109
|
readonly raw: unknown;
|
|
104
110
|
};
|
|
@@ -279,6 +285,14 @@ declare abstract class BasePlatformAdapter {
|
|
|
279
285
|
/**
|
|
280
286
|
* Subscribe to inbound events. Returns an unsubscribe function.
|
|
281
287
|
* EC-H: second call REPLACES the previous handler (does not stack).
|
|
288
|
+
*
|
|
289
|
+
* The handler is user code and may throw. An adapter MUST contain that throw, report it as the
|
|
290
|
+
* HANDLER's failure — not the platform's — and keep delivering: one bad message never ends the
|
|
291
|
+
* process nor the connection. Two adapters used to discard the rejection with `void`, which under
|
|
292
|
+
* Node's default ends the process, and two more reported it as a platform-client error, sending
|
|
293
|
+
* whoever debugged their own handler to the wrong repository. Eight had converged on the right
|
|
294
|
+
* behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds all
|
|
295
|
+
* ten to it.
|
|
282
296
|
*/
|
|
283
297
|
abstract onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
284
298
|
/** Lifecycle: emit a typing indicator. Default: noop. */
|
|
@@ -363,6 +377,41 @@ declare class GatewayConfigurationError extends Error {
|
|
|
363
377
|
constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
|
|
364
378
|
}
|
|
365
379
|
|
|
380
|
+
/**
|
|
381
|
+
* `GatewayLifecycleError` — a lifecycle method was called from a state that
|
|
382
|
+
* cannot honour it.
|
|
383
|
+
*
|
|
384
|
+
* Distinct from {@link GatewayConfigurationError}, which reports a bad or
|
|
385
|
+
* missing setting at construction time. This one reports a legal call made at
|
|
386
|
+
* an illegal moment: the configuration is fine, the ordering is not.
|
|
387
|
+
*
|
|
388
|
+
* It exists because the alternative is worse than an error. `GatewayRunner`
|
|
389
|
+
* used to accept `start()` after `stop()` and quietly produce a runner that
|
|
390
|
+
* reconnected its adapters and then refused to disconnect them — a leak that
|
|
391
|
+
* reported success. Failing loudly at the call that cannot be honoured is the
|
|
392
|
+
* only outcome a caller can act on.
|
|
393
|
+
*
|
|
394
|
+
* @public
|
|
395
|
+
*/
|
|
396
|
+
/** Public input shape for the {@link GatewayLifecycleError} constructor. */
|
|
397
|
+
interface GatewayLifecycleErrorOptions {
|
|
398
|
+
/** Stable, machine-readable discriminator (e.g. `"runner_stopped"`). */
|
|
399
|
+
readonly code: string;
|
|
400
|
+
/** Human-readable explanation, including what the caller should do instead. */
|
|
401
|
+
readonly message: string;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Thrown when a lifecycle transition is not available from the current state.
|
|
405
|
+
*
|
|
406
|
+
* @public
|
|
407
|
+
*/
|
|
408
|
+
declare class GatewayLifecycleError extends Error {
|
|
409
|
+
readonly name: string;
|
|
410
|
+
/** Stable discriminator, so callers branch on `code` rather than on message text. */
|
|
411
|
+
readonly code: string;
|
|
412
|
+
constructor(opts: GatewayLifecycleErrorOptions);
|
|
413
|
+
}
|
|
414
|
+
|
|
366
415
|
/**
|
|
367
416
|
* Gateway hooks — own contract, not a `Plugin.kind` extension
|
|
368
417
|
* (T4.1, ADRs D176, D177).
|
|
@@ -456,7 +505,8 @@ declare class HookExecutor {
|
|
|
456
505
|
* failure rolls back: connected adapters get `disconnect()`, then the
|
|
457
506
|
* aggregate error rethrows.
|
|
458
507
|
* - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)
|
|
459
|
-
* BEFORE disconnecting (EC-E). Idempotent
|
|
508
|
+
* BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner
|
|
509
|
+
* cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.
|
|
460
510
|
*
|
|
461
511
|
* **Hook chain on inbound:**
|
|
462
512
|
* 1. `firePreInbound({ event })`
|
|
@@ -465,6 +515,11 @@ declare class HookExecutor {
|
|
|
465
515
|
* 4. Otherwise: call user handler.
|
|
466
516
|
* 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).
|
|
467
517
|
*
|
|
518
|
+
* Every reply — the handler's `ctx.reply` and the EC-D auto-reply alike — fires
|
|
519
|
+
* `post_outbound` with the event, the outbound and the adapter's result, once
|
|
520
|
+
* per attempt. The hook observes the delivery; it cannot change what the caller
|
|
521
|
+
* of `reply` receives.
|
|
522
|
+
*
|
|
468
523
|
* @public
|
|
469
524
|
*/
|
|
470
525
|
|
|
@@ -520,7 +575,12 @@ declare class GatewayRunner {
|
|
|
520
575
|
* @public
|
|
521
576
|
*/
|
|
522
577
|
command(name: string, handler: GatewayHandler): void;
|
|
523
|
-
/**
|
|
578
|
+
/**
|
|
579
|
+
* Connect all adapters and wire inbound dispatch.
|
|
580
|
+
*
|
|
581
|
+
* @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
|
|
582
|
+
* stopped. A stopped runner is spent; construct a new one.
|
|
583
|
+
*/
|
|
524
584
|
start(): Promise<void>;
|
|
525
585
|
/**
|
|
526
586
|
* Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
|
|
@@ -663,4 +723,4 @@ interface ChunkByGraphemeOptions {
|
|
|
663
723
|
*/
|
|
664
724
|
declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
|
|
665
725
|
|
|
666
|
-
export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
|
|
726
|
+
export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
|
package/dist/index.js
CHANGED
|
@@ -48,6 +48,17 @@ var GatewayConfigurationError = class extends Error {
|
|
|
48
48
|
this.detail = opts.detail;
|
|
49
49
|
}
|
|
50
50
|
};
|
|
51
|
+
|
|
52
|
+
// src/errors/lifecycle-error.ts
|
|
53
|
+
var GatewayLifecycleError = class extends Error {
|
|
54
|
+
name = "GatewayLifecycleError";
|
|
55
|
+
/** Stable discriminator, so callers branch on `code` rather than on message text. */
|
|
56
|
+
code;
|
|
57
|
+
constructor(opts) {
|
|
58
|
+
super(opts.message);
|
|
59
|
+
this.code = opts.code;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
51
62
|
var HookExecutor = class {
|
|
52
63
|
constructor(hooks) {
|
|
53
64
|
this.hooks = hooks;
|
|
@@ -134,8 +145,19 @@ var GatewayRunner = class {
|
|
|
134
145
|
command(name, handler) {
|
|
135
146
|
this.commands.set(name, handler);
|
|
136
147
|
}
|
|
137
|
-
/**
|
|
148
|
+
/**
|
|
149
|
+
* Connect all adapters and wire inbound dispatch.
|
|
150
|
+
*
|
|
151
|
+
* @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
|
|
152
|
+
* stopped. A stopped runner is spent; construct a new one.
|
|
153
|
+
*/
|
|
138
154
|
async start() {
|
|
155
|
+
if (this.stopped) {
|
|
156
|
+
throw new GatewayLifecycleError({
|
|
157
|
+
code: "runner_stopped",
|
|
158
|
+
message: "GatewayRunner.start(): this runner has already been stopped and cannot be restarted. Construct a new GatewayRunner instead."
|
|
159
|
+
});
|
|
160
|
+
}
|
|
139
161
|
if (this.connected) return;
|
|
140
162
|
const connected = [];
|
|
141
163
|
try {
|
|
@@ -176,10 +198,17 @@ var GatewayRunner = class {
|
|
|
176
198
|
this.unsubs.length = 0;
|
|
177
199
|
const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
|
|
178
200
|
if (this.inflight.size > 0) {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
201
|
+
let timer;
|
|
202
|
+
try {
|
|
203
|
+
await Promise.race([
|
|
204
|
+
Promise.all([...this.inflight]).then(() => void 0),
|
|
205
|
+
new Promise((r) => {
|
|
206
|
+
timer = setTimeout(r, drainMs);
|
|
207
|
+
})
|
|
208
|
+
]);
|
|
209
|
+
} finally {
|
|
210
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
211
|
+
}
|
|
183
212
|
}
|
|
184
213
|
await Promise.all(
|
|
185
214
|
[...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => void 0))
|
|
@@ -240,24 +269,36 @@ var GatewayRunner = class {
|
|
|
240
269
|
}
|
|
241
270
|
/** EC-G: per-event ctx whose reply routes to the matching adapter. */
|
|
242
271
|
buildContext(event) {
|
|
243
|
-
const adapter = this.adaptersByPlatform.get(event.platform);
|
|
244
272
|
return {
|
|
245
273
|
event,
|
|
246
|
-
reply: async (text, opts) => {
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
};
|
|
252
|
-
}
|
|
253
|
-
return adapter.sendMessage({
|
|
254
|
-
channel: event.channel,
|
|
255
|
-
text,
|
|
256
|
-
...opts?.format !== void 0 ? { format: opts.format } : {}
|
|
257
|
-
});
|
|
258
|
-
}
|
|
274
|
+
reply: async (text, opts) => this.deliver(event, {
|
|
275
|
+
channel: event.channel,
|
|
276
|
+
text,
|
|
277
|
+
...opts?.format !== void 0 ? { format: opts.format } : {}
|
|
278
|
+
})
|
|
259
279
|
};
|
|
260
280
|
}
|
|
281
|
+
/**
|
|
282
|
+
* Send one outbound on behalf of `event` and report it to `post_outbound`.
|
|
283
|
+
*
|
|
284
|
+
* Every reply leaves through here so the hook fires exactly once per attempt —
|
|
285
|
+
* including the EC-D auto-reply, and including the attempt that finds no
|
|
286
|
+
* adapter for the platform. An audit hook that counted only the deliveries
|
|
287
|
+
* which reached a transport would omit precisely the ones that went nowhere.
|
|
288
|
+
*
|
|
289
|
+
* `post_outbound` observes; it does not intercept. The adapter's `SendResult`
|
|
290
|
+
* is returned to the caller unchanged, and `HookExecutor` already contains a
|
|
291
|
+
* throwing hook, so a broken observer cannot turn a delivered reply into a
|
|
292
|
+
* failed one.
|
|
293
|
+
*
|
|
294
|
+
* @internal
|
|
295
|
+
*/
|
|
296
|
+
async deliver(event, outbound) {
|
|
297
|
+
const adapter = this.adaptersByPlatform.get(event.platform);
|
|
298
|
+
const result = adapter === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : await adapter.sendMessage(outbound);
|
|
299
|
+
await this.hookExecutor.firePostOutbound({ event, outbound, result });
|
|
300
|
+
return result;
|
|
301
|
+
}
|
|
261
302
|
};
|
|
262
303
|
|
|
263
304
|
// src/session/router.ts
|
|
@@ -366,6 +407,6 @@ function chunkByGrapheme(text, options) {
|
|
|
366
407
|
return parts;
|
|
367
408
|
}
|
|
368
409
|
|
|
369
|
-
export { BasePlatformAdapter, DeliveryRouter, GatewayConfigurationError, GatewayRunner, HookExecutor, SessionRouter, chunkByGrapheme, chunkText, defaultStrategy };
|
|
410
|
+
export { BasePlatformAdapter, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SessionRouter, chunkByGrapheme, chunkText, defaultStrategy };
|
|
370
411
|
//# sourceMappingURL=index.js.map
|
|
371
412
|
//# 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/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":";;;AAqD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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 { Security } from \"@theokit/sdk\";\n\nimport type {\n GatewayHook,\n HookDecision,\n OnErrorContext,\n PostOutboundContext,\n PreInboundContext,\n} from \"./types.js\";\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {}\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n // `GatewayRunner.dispatch` replies with this message straight into the\n // chat, so it must never carry the exception text. It used to:\n // `hook ${h.name} threw: ${err.message}` sent whatever the hook happened\n // to throw — connection strings, internal ids, bearer tokens — to the end\n // user verbatim. The sibling handler path already logs through\n // `Security.redact` (EC-F); this one skipped redaction entirely, and the\n // test asserting the raw text appeared locked the leak in as expected\n // behaviour.\n //\n // The detail is not lost, only moved: stderr gets it, redacted.\n process.stderr.write(\n `[gateway] pre_inbound hook \"${h.name}\" threw: ${Security.redact((err as Error).message)}\\n`,\n );\n return {\n block: true,\n message: `Request blocked: hook \"${h.name}\" failed.`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport { HookExecutor } from \"../hooks/executor.js\";\nimport type { GatewayHook } from \"../hooks/types.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /** Connect all adapters and wire inbound dispatch. */\n async start(): Promise<void> {\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => setTimeout(r, drainMs)),\n ]);\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(\n `[gateway] handler error: ${Security.redact((err as Error).message)}\\n`,\n );\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n const adapter = this.adaptersByPlatform.get(event.platform);\n return {\n event,\n reply: async (text, opts) => {\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` },\n };\n }\n return adapter.sendMessage({\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n });\n },\n };\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n","/**\n * `chunkText` — transport-agnostic, boundary-preferring text chunker.\n *\n * Single-sources the message-splitting knowledge that was copy-pasted across\n * the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two\n * boundary-search families that existed in the adapters:\n *\n * - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\" → \" \"`, UTF-16 surrogate-pair guard,\n * leading-whitespace strip on continuation, optional part-trim.\n * - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\"` (no space), no surrogate guard,\n * leading-newline strip on continuation.\n *\n * The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different\n * algorithm and is intentionally NOT folded in here — those adapters keep their\n * grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.\n *\n * @public\n */\n\n/** Options for {@link chunkText}. */\nexport interface ChunkTextOptions {\n /**\n * Hard cap. If the whole input is `<= limit`, it is returned as a single\n * chunk (subject to `trimParts`). Continuation chunks are cut within the\n * `safeLimit` window.\n */\n readonly limit: number;\n /**\n * Soft window each cut searches within. Defaults to `limit`. The Telegram\n * family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).\n */\n readonly safeLimit?: number;\n /**\n * Boundary strings tried, in order, from most to least preferred. A boundary\n * is accepted once its position is `>= window * 0.5`; otherwise the next one\n * is tried. Default: `[\"\\n\\n\", \"\\n\", \" \"]`.\n */\n readonly boundaries?: readonly string[];\n /**\n * When no boundary reaches the half-window threshold:\n * - `\"last-boundary\"` — use the last computed boundary if it is `> 0`,\n * else fall back to the window edge (Slack family).\n * - `\"window\"` — fall back straight to the window edge (Telegram family).\n * Default: `\"window\"`.\n */\n readonly lastResort?: \"last-boundary\" | \"window\";\n /**\n * Guard against slicing through a UTF-16 low surrogate (splitting an emoji).\n * Default: `false`.\n */\n readonly surrogateGuard?: boolean;\n /**\n * Pattern stripped from the START of each continuation chunk. Default `/^\\n+/`\n * (Telegram family). Slack family uses `/^\\s+/`.\n */\n readonly stripLeading?: RegExp;\n /**\n * When true, each resulting part is `.trim()`-ed and empty parts are dropped\n * (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.\n */\n readonly trimParts?: boolean;\n}\n\n/** Most-preferred boundary at `>= window*0.5`, else the last boundary tried. */\nfunction searchBoundary(remaining: string, window: number, boundaries: readonly string[]): number {\n let cut = window;\n for (const b of boundaries) {\n cut = remaining.lastIndexOf(b, window);\n if (cut >= window * 0.5) return cut;\n }\n return cut;\n}\n\n/** Fail fast on a non-positive / non-integer size argument. */\nfunction assertPositiveInt(label: string, value: number): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new RangeError(`${label} must be a positive integer, received ${value}`);\n }\n}\n\n/** Step back one code unit if `cut` would sever a UTF-16 surrogate pair. */\nfunction guardSurrogate(text: string, cut: number): number {\n if (cut >= text.length) return cut;\n const code = text.charCodeAt(cut);\n return code >= 0xdc00 && code <= 0xdfff ? cut - 1 : cut;\n}\n\nfunction findCut(\n remaining: string,\n window: number,\n boundaries: readonly string[],\n lastResort: \"last-boundary\" | \"window\",\n surrogateGuard: boolean,\n): number {\n let cut = searchBoundary(remaining, window, boundaries);\n if (cut < window * 0.5) {\n cut = lastResort === \"last-boundary\" && cut > 0 ? cut : window;\n }\n if (surrogateGuard) cut = guardSurrogate(remaining, cut);\n return cut <= 0 ? window : cut;\n}\n\n/**\n * Split `text` into chunks no longer than the configured window, preferring\n * natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.\n */\nexport function chunkText(text: string, options: ChunkTextOptions): string[] {\n const {\n limit,\n safeLimit = limit,\n boundaries = [\"\\n\\n\", \"\\n\", \" \"],\n lastResort = \"window\",\n surrogateGuard = false,\n stripLeading = /^\\n+/,\n trimParts = false,\n } = options;\n\n // Fail fast at the boundary: a non-positive `limit` would make `findCut`\n // return 0 forever and hang the loop; `safeLimit > limit` would break the\n // \"hard cap\" contract by emitting an oversized tail chunk.\n assertPositiveInt(\"chunkText: limit\", limit);\n assertPositiveInt(\"chunkText: safeLimit\", safeLimit);\n if (safeLimit > limit) {\n throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);\n }\n\n const finalize = (parts: string[]): string[] =>\n trimParts ? parts.map((p) => p.trim()).filter((p) => p.length > 0) : parts;\n\n if (text.length <= limit) {\n return finalize([text]);\n }\n\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > safeLimit) {\n const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);\n parts.push(remaining.slice(0, cut));\n remaining = remaining.slice(cut).replace(stripLeading, \"\");\n }\n if (remaining.length > 0) parts.push(remaining);\n return finalize(parts);\n}\n\n/** Options for {@link chunkByGrapheme}. */\nexport interface ChunkByGraphemeOptions {\n /** If `text.length <= limit`, it is returned as a single chunk. */\n readonly limit: number;\n /**\n * Max length per emitted part during the grapheme walk. Defaults to `limit`.\n * Callers that reserve room for a per-part prefix (e.g. SMS `\"(i/N) \"`) pass a\n * `partLimit` below `limit`.\n */\n readonly partLimit?: number;\n}\n\n/**\n * Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,\n * regional-indicator pair, or combining sequence. Distinct algorithm from\n * {@link chunkText} — used by adapters that must respect grapheme boundaries\n * (LINE, SMS) rather than search for whitespace boundaries.\n *\n * @public\n */\nexport function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[] {\n const { limit, partLimit = limit } = options;\n assertPositiveInt(\"chunkByGrapheme: limit\", limit);\n assertPositiveInt(\"chunkByGrapheme: partLimit\", partLimit);\n if (text.length === 0) return [\"\"];\n if (text.length <= limit) return [text];\n\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const parts: string[] = [];\n let buf = \"\";\n for (const { segment } of segmenter.segment(text)) {\n if (buf.length + segment.length > partLimit) {\n if (buf.length > 0) parts.push(buf);\n buf = \"\";\n }\n buf += segment;\n }\n if (buf.length > 0) parts.push(buf);\n return parts;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/errors/config-error.ts","../src/errors/lifecycle-error.ts","../src/hooks/executor.ts","../src/runner/gateway-runner.ts","../src/session/router.ts","../src/text/chunk.ts"],"names":["Security","parts"],"mappings":";;;AAqDO,IAAe,sBAAf,MAAmC;AAAA;AAAA,EA2BxC,MAAM,YAAY,UAAA,EAAmC;AAAA,EAErD;AAAA;AAAA,EAGA,MAAM,WAAW,UAAA,EAAmC;AAAA,EAEpD;AACF;;;AC/CO,I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AA2C;AACvF,EAAA,MAAM,EAAE,KAAA,EAAO,SAAA,GAAY,KAAA,EAAM,GAAI,OAAA;AACrC,EAAA,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 * The handler is user code and may throw. An adapter MUST contain that throw, report it as the\n * HANDLER's failure — not the platform's — and keep delivering: one bad message never ends the\n * process nor the connection. Two adapters used to discard the rejection with `void`, which under\n * Node's default ends the process, and two more reported it as a platform-client error, sending\n * whoever debugged their own handler to the wrong repository. Eight had converged on the right\n * behaviour without anything writing it down; `tests/lint/adapter-contract.test.ts` now holds all\n * ten to it.\n */\n abstract onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void;\n\n /** Lifecycle: emit a typing indicator. Default: noop. */\n async startTyping(_channelId: string): Promise<void> {\n /* override */\n }\n\n /** Lifecycle: stop the typing indicator. Default: noop. */\n async stopTyping(_channelId: string): Promise<void> {\n /* override */\n }\n}\n","/**\n * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).\n *\n * The router holds a map of `platform → adapter` and forwards\n * `DeliveryRequest` to the right adapter's `sendMessage`. Composes\n * with `Cron` from `@theokit/sdk` for scheduled delivery — the\n * router is the \"WHERE to send\", Cron is the \"WHEN to fire\".\n *\n * @public\n */\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** Target for an outbound delivery. */\nexport interface DeliveryTarget {\n readonly platform: PlatformName;\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n}\n\n/** Full outbound request: target + content. */\nexport interface DeliveryRequest extends DeliveryTarget {\n readonly text: string;\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n readonly replyTo?: string;\n}\n\n/**\n * Routes outbound requests to the correct adapter.\n *\n * **Contract:**\n * - `register` is last-writer-wins by platform.\n * - `send` with unknown platform returns `{ ok: false, code: \"no_adapter\" }`.\n * - `send` never throws on platform errors (delegates to adapter's SendResult).\n *\n * @public\n */\nexport class DeliveryRouter {\n private readonly adapters = new Map<PlatformName, BasePlatformAdapter>();\n\n register(adapter: BasePlatformAdapter): void {\n this.adapters.set(adapter.platform, adapter);\n }\n\n async send(req: DeliveryRequest): Promise<SendResult> {\n const adapter = this.adapters.get(req.platform);\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for platform \"${req.platform}\"` },\n };\n }\n return adapter.sendMessage({\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n });\n }\n}\n","/**\n * `GatewayConfigurationError` — shared base for per-adapter configuration\n * errors (roadmap M0/M2).\n *\n * Every platform adapter previously defined an identical\n * `ConfigurationError extends Error` (same `code`/`detail` fields, same\n * options interface, same `` `${pkg}: ${code}` `` default message) — only the\n * package prefix differed. This base single-sources that contract. Adapters\n * extend it, pin their prefix, and keep `name = \"ConfigurationError\"` plus\n * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).\n *\n * @public\n */\n\n/** Public input shape for the {@link GatewayConfigurationError} constructor. */\nexport interface GatewayConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\n/**\n * Base configuration error. Not thrown directly by adapters — they subclass it\n * with a fixed package prefix.\n */\nexport class GatewayConfigurationError extends Error {\n override readonly name: string = \"GatewayConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n\n /**\n * @param prefix Package prefix used in the default message (e.g. `\"gateway-line\"`).\n * @param opts `code` (required), optional explicit `message`, optional `detail`.\n */\n constructor(prefix: string, opts: GatewayConfigurationErrorOptions) {\n super(opts.message ?? `${prefix}: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n","/**\n * `GatewayLifecycleError` — a lifecycle method was called from a state that\n * cannot honour it.\n *\n * Distinct from {@link GatewayConfigurationError}, which reports a bad or\n * missing setting at construction time. This one reports a legal call made at\n * an illegal moment: the configuration is fine, the ordering is not.\n *\n * It exists because the alternative is worse than an error. `GatewayRunner`\n * used to accept `start()` after `stop()` and quietly produce a runner that\n * reconnected its adapters and then refused to disconnect them — a leak that\n * reported success. Failing loudly at the call that cannot be honoured is the\n * only outcome a caller can act on.\n *\n * @public\n */\n\n/** Public input shape for the {@link GatewayLifecycleError} constructor. */\nexport interface GatewayLifecycleErrorOptions {\n /** Stable, machine-readable discriminator (e.g. `\"runner_stopped\"`). */\n readonly code: string;\n /** Human-readable explanation, including what the caller should do instead. */\n readonly message: string;\n}\n\n/**\n * Thrown when a lifecycle transition is not available from the current state.\n *\n * @public\n */\nexport class GatewayLifecycleError extends Error {\n override readonly name: string = \"GatewayLifecycleError\";\n /** Stable discriminator, so callers branch on `code` rather than on message text. */\n readonly code: string;\n\n constructor(opts: GatewayLifecycleErrorOptions) {\n super(opts.message);\n this.code = opts.code;\n }\n}\n","/**\n * `HookExecutor` — runs registered gateway hooks at their fire points.\n *\n * Split out of `hooks/types.ts` (which now holds the contract only) so the\n * filename predicts its contents: interfaces live in `types.ts`, the run\n * engine lives here. Behavior is identical to the previous colocated class.\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type {\n GatewayHook,\n HookDecision,\n OnErrorContext,\n PostOutboundContext,\n PreInboundContext,\n} from \"./types.js\";\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {}\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n // `GatewayRunner.dispatch` replies with this message straight into the\n // chat, so it must never carry the exception text. It used to:\n // `hook ${h.name} threw: ${err.message}` sent whatever the hook happened\n // to throw — connection strings, internal ids, bearer tokens — to the end\n // user verbatim. The sibling handler path already logs through\n // `Security.redact` (EC-F); this one skipped redaction entirely, and the\n // test asserting the raw text appeared locked the leak in as expected\n // behaviour.\n //\n // The detail is not lost, only moved: stderr gets it, redacted.\n process.stderr.write(\n `[gateway] pre_inbound hook \"${h.name}\" threw: ${Security.redact((err as Error).message)}\\n`,\n );\n return {\n block: true,\n message: `Request blocked: hook \"${h.name}\" failed.`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner\n * cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).\n *\n * Every reply — the handler's `ctx.reply` and the EC-D auto-reply alike — fires\n * `post_outbound` with the event, the outbound and the adapter's result, once\n * per attempt. The hook observes the delivery; it cannot change what the caller\n * of `reply` receives.\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, OutboundMessage, SendResult } from \"../adapter/base.js\";\nimport { GatewayLifecycleError } from \"../errors/lifecycle-error.js\";\nimport { HookExecutor } from \"../hooks/executor.js\";\nimport type { GatewayHook } from \"../hooks/types.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /**\n * Connect all adapters and wire inbound dispatch.\n *\n * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already\n * stopped. A stopped runner is spent; construct a new one.\n */\n async start(): Promise<void> {\n if (this.stopped) {\n // Silently reconnecting here is what produced the unstoppable runner:\n // `stop()` cleared `connected` but never `stopped`, so a second start()\n // passed the guard below and rewired everything, while the next stop()\n // returned at its own guard without disconnecting anything (#39).\n throw new GatewayLifecycleError({\n code: \"runner_stopped\",\n message:\n \"GatewayRunner.start(): this runner has already been stopped and cannot be restarted. Construct a new GatewayRunner instead.\",\n });\n }\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n // The loser of the race has to be cancelled explicitly. `Promise.race`\n // settles on the first branch and abandons the other, but an abandoned\n // `setTimeout` is still a scheduled timer, and a scheduled timer keeps\n // Node's event loop alive: `stop()` returned in 0ms while the process\n // only exited `drainMs` later, so a bot stopping on SIGINT hung for the\n // whole drain window before dying (#37).\n let timer: NodeJS.Timeout | undefined;\n try {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => {\n timer = setTimeout(r, drainMs);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(\n `[gateway] handler error: ${Security.redact((err as Error).message)}\\n`,\n );\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n return {\n event,\n reply: async (text, opts) =>\n this.deliver(event, {\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n }),\n };\n }\n\n /**\n * Send one outbound on behalf of `event` and report it to `post_outbound`.\n *\n * Every reply leaves through here so the hook fires exactly once per attempt —\n * including the EC-D auto-reply, and including the attempt that finds no\n * adapter for the platform. An audit hook that counted only the deliveries\n * which reached a transport would omit precisely the ones that went nowhere.\n *\n * `post_outbound` observes; it does not intercept. The adapter's `SendResult`\n * is returned to the caller unchanged, and `HookExecutor` already contains a\n * throwing hook, so a broken observer cannot turn a delivered reply into a\n * failed one.\n *\n * @internal\n */\n private async deliver(\n event: GatewayMessageEvent,\n outbound: OutboundMessage,\n ): Promise<SendResult> {\n const adapter = this.adaptersByPlatform.get(event.platform);\n const result: SendResult =\n adapter === undefined\n ? { ok: false, error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` } }\n : await adapter.sendMessage(outbound);\n await this.hookExecutor.firePostOutbound({ event, outbound, result });\n return result;\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n","/**\n * `chunkText` — transport-agnostic, boundary-preferring text chunker.\n *\n * Single-sources the message-splitting knowledge that was copy-pasted across\n * the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two\n * boundary-search families that existed in the adapters:\n *\n * - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\" → \" \"`, UTF-16 surrogate-pair guard,\n * leading-whitespace strip on continuation, optional part-trim.\n * - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),\n * boundary preference `\"\\n\\n\" → \"\\n\"` (no space), no surrogate guard,\n * leading-newline strip on continuation.\n *\n * The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different\n * algorithm and is intentionally NOT folded in here — those adapters keep their\n * grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.\n *\n * @public\n */\n\n/** Options for {@link chunkText}. */\nexport interface ChunkTextOptions {\n /**\n * Hard cap. If the whole input is `<= limit`, it is returned as a single\n * chunk (subject to `trimParts`). Continuation chunks are cut within the\n * `safeLimit` window.\n */\n readonly limit: number;\n /**\n * Soft window each cut searches within. Defaults to `limit`. The Telegram\n * family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).\n */\n readonly safeLimit?: number;\n /**\n * Boundary strings tried, in order, from most to least preferred. A boundary\n * is accepted once its position is `>= window * 0.5`; otherwise the next one\n * is tried. Default: `[\"\\n\\n\", \"\\n\", \" \"]`.\n */\n readonly boundaries?: readonly string[];\n /**\n * When no boundary reaches the half-window threshold:\n * - `\"last-boundary\"` — use the last computed boundary if it is `> 0`,\n * else fall back to the window edge (Slack family).\n * - `\"window\"` — fall back straight to the window edge (Telegram family).\n * Default: `\"window\"`.\n */\n readonly lastResort?: \"last-boundary\" | \"window\";\n /**\n * Guard against slicing through a UTF-16 low surrogate (splitting an emoji).\n * Default: `false`.\n */\n readonly surrogateGuard?: boolean;\n /**\n * Pattern stripped from the START of each continuation chunk. Default `/^\\n+/`\n * (Telegram family). Slack family uses `/^\\s+/`.\n */\n readonly stripLeading?: RegExp;\n /**\n * When true, each resulting part is `.trim()`-ed and empty parts are dropped\n * (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.\n */\n readonly trimParts?: boolean;\n}\n\n/** Most-preferred boundary at `>= window*0.5`, else the last boundary tried. */\nfunction searchBoundary(remaining: string, window: number, boundaries: readonly string[]): number {\n let cut = window;\n for (const b of boundaries) {\n cut = remaining.lastIndexOf(b, window);\n if (cut >= window * 0.5) return cut;\n }\n return cut;\n}\n\n/** Fail fast on a non-positive / non-integer size argument. */\nfunction assertPositiveInt(label: string, value: number): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new RangeError(`${label} must be a positive integer, received ${value}`);\n }\n}\n\n/** Step back one code unit if `cut` would sever a UTF-16 surrogate pair. */\nfunction guardSurrogate(text: string, cut: number): number {\n if (cut >= text.length) return cut;\n const code = text.charCodeAt(cut);\n return code >= 0xdc00 && code <= 0xdfff ? cut - 1 : cut;\n}\n\nfunction findCut(\n remaining: string,\n window: number,\n boundaries: readonly string[],\n lastResort: \"last-boundary\" | \"window\",\n surrogateGuard: boolean,\n): number {\n let cut = searchBoundary(remaining, window, boundaries);\n if (cut < window * 0.5) {\n cut = lastResort === \"last-boundary\" && cut > 0 ? cut : window;\n }\n if (surrogateGuard) cut = guardSurrogate(remaining, cut);\n return cut <= 0 ? window : cut;\n}\n\n/**\n * Split `text` into chunks no longer than the configured window, preferring\n * natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.\n */\nexport function chunkText(text: string, options: ChunkTextOptions): string[] {\n const {\n limit,\n safeLimit = limit,\n boundaries = [\"\\n\\n\", \"\\n\", \" \"],\n lastResort = \"window\",\n surrogateGuard = false,\n stripLeading = /^\\n+/,\n trimParts = false,\n } = options;\n\n // Fail fast at the boundary: a non-positive `limit` would make `findCut`\n // return 0 forever and hang the loop; `safeLimit > limit` would break the\n // \"hard cap\" contract by emitting an oversized tail chunk.\n assertPositiveInt(\"chunkText: limit\", limit);\n assertPositiveInt(\"chunkText: safeLimit\", safeLimit);\n if (safeLimit > limit) {\n throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);\n }\n\n const finalize = (parts: string[]): string[] =>\n trimParts ? parts.map((p) => p.trim()).filter((p) => p.length > 0) : parts;\n\n if (text.length <= limit) {\n return finalize([text]);\n }\n\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > safeLimit) {\n const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);\n parts.push(remaining.slice(0, cut));\n remaining = remaining.slice(cut).replace(stripLeading, \"\");\n }\n if (remaining.length > 0) parts.push(remaining);\n return finalize(parts);\n}\n\n/** Options for {@link chunkByGrapheme}. */\nexport interface ChunkByGraphemeOptions {\n /** If `text.length <= limit`, it is returned as a single chunk. */\n readonly limit: number;\n /**\n * Max length per emitted part during the grapheme walk. Defaults to `limit`.\n * Callers that reserve room for a per-part prefix (e.g. SMS `\"(i/N) \"`) pass a\n * `partLimit` below `limit`.\n */\n readonly partLimit?: number;\n}\n\n/**\n * Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,\n * regional-indicator pair, or combining sequence. Distinct algorithm from\n * {@link chunkText} — used by adapters that must respect grapheme boundaries\n * (LINE, SMS) rather than search for whitespace boundaries.\n *\n * @public\n */\nexport function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[] {\n const { limit, partLimit = limit } = options;\n assertPositiveInt(\"chunkByGrapheme: limit\", limit);\n assertPositiveInt(\"chunkByGrapheme: partLimit\", partLimit);\n if (text.length === 0) return [\"\"];\n if (text.length <= limit) return [text];\n\n const segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n const parts: string[] = [];\n let buf = \"\";\n for (const { segment } of segmenter.segment(text)) {\n if (buf.length + segment.length > partLimit) {\n if (buf.length > 0) parts.push(buf);\n buf = \"\";\n }\n buf += segment;\n }\n if (buf.length > 0) parts.push(buf);\n return parts;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/usetheokit/theokit-gateways.git",
|
|
9
|
+
"directory": "packages/gateway"
|
|
10
|
+
},
|
|
6
11
|
"type": "module",
|
|
7
12
|
"engines": {
|
|
8
13
|
"node": ">=22.12.0"
|
|
@@ -32,15 +37,22 @@
|
|
|
32
37
|
"@theokit/sdk": "^2.18.0"
|
|
33
38
|
},
|
|
34
39
|
"devDependencies": {
|
|
40
|
+
"@stryker-mutator/core": "10",
|
|
41
|
+
"@stryker-mutator/vitest-runner": "10",
|
|
35
42
|
"@theokit/sdk": "^2.18.0",
|
|
36
43
|
"tsup": "^8.5.0",
|
|
37
44
|
"typescript": "^5.8.0",
|
|
38
45
|
"vitest": "^4.1.8",
|
|
39
46
|
"zod": "^4.0.0"
|
|
40
47
|
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public",
|
|
50
|
+
"provenance": true
|
|
51
|
+
},
|
|
41
52
|
"scripts": {
|
|
42
53
|
"build": "tsup",
|
|
43
54
|
"typecheck": "tsc --noEmit",
|
|
44
|
-
"test": "vitest run"
|
|
55
|
+
"test": "vitest run",
|
|
56
|
+
"test:mutation": "stryker run"
|
|
45
57
|
}
|
|
46
58
|
}
|