@theokit/gateway 0.4.1 → 0.5.1
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 +39 -0
- package/LICENSE +201 -0
- package/dist/index.cjs +99 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +139 -1
- package/dist/index.d.ts +139 -1
- package/dist/index.js +97 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,44 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
|
|
9
|
+
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.
|
|
10
|
+
|
|
11
|
+
**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.
|
|
12
|
+
|
|
13
|
+
- 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
|
|
14
|
+
|
|
15
|
+
**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.
|
|
16
|
+
|
|
17
|
+
**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.
|
|
18
|
+
|
|
19
|
+
**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.
|
|
20
|
+
|
|
21
|
+
**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.
|
|
22
|
+
|
|
23
|
+
**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.
|
|
24
|
+
|
|
25
|
+
**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.
|
|
26
|
+
|
|
27
|
+
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.
|
|
28
|
+
|
|
29
|
+
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.
|
|
30
|
+
|
|
31
|
+
## 0.5.0
|
|
32
|
+
|
|
33
|
+
### Minor Changes
|
|
34
|
+
|
|
35
|
+
- Architecture-hardening (roadmap M0–M3): three new public primitives on the core barrel, plus a hook-engine relocation. No breaking changes.
|
|
36
|
+
|
|
37
|
+
- `chunkText(text, options)` — transport-agnostic, boundary-preferring text chunker. Single-sources the message-splitting logic the platform adapters share; reproduces the Slack-family (fixed window, space boundary, UTF-16 surrogate guard) and Telegram-family (soft window, newline-only) algorithms via options. Validates inputs (positive-integer `limit`, `safeLimit <= limit`) and throws `RangeError` on misuse (fail-fast — no infinite loop).
|
|
38
|
+
- `chunkByGrapheme(text, options)` — grapheme-cluster-safe (`Intl.Segmenter`) chunker shared by the LINE/SMS adapters; never severs an emoji, regional-indicator pair, or combining sequence.
|
|
39
|
+
- `GatewayConfigurationError` base + `GatewayConfigurationErrorOptions` — shared base for per-adapter `ConfigurationError` classes.
|
|
40
|
+
- `HookExecutor` moved from `hooks/types.ts` to `hooks/executor.ts` (public API byte-identical; re-exported unchanged from the barrel).
|
|
41
|
+
|
|
3
42
|
## 0.4.1
|
|
4
43
|
|
|
5
44
|
### Patch Changes
|
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 usetheo.dev
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/dist/index.cjs
CHANGED
|
@@ -35,7 +35,21 @@ var DeliveryRouter = class {
|
|
|
35
35
|
}
|
|
36
36
|
};
|
|
37
37
|
|
|
38
|
-
// src/
|
|
38
|
+
// src/errors/config-error.ts
|
|
39
|
+
var GatewayConfigurationError = class extends Error {
|
|
40
|
+
name = "GatewayConfigurationError";
|
|
41
|
+
code;
|
|
42
|
+
detail;
|
|
43
|
+
/**
|
|
44
|
+
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
45
|
+
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
46
|
+
*/
|
|
47
|
+
constructor(prefix, opts) {
|
|
48
|
+
super(opts.message ?? `${prefix}: ${opts.code}`);
|
|
49
|
+
this.code = opts.code;
|
|
50
|
+
this.detail = opts.detail;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
39
53
|
var HookExecutor = class {
|
|
40
54
|
constructor(hooks) {
|
|
41
55
|
this.hooks = hooks;
|
|
@@ -52,9 +66,13 @@ var HookExecutor = class {
|
|
|
52
66
|
try {
|
|
53
67
|
decision = await h.pre_inbound(ctx);
|
|
54
68
|
} catch (err) {
|
|
69
|
+
process.stderr.write(
|
|
70
|
+
`[gateway] pre_inbound hook "${h.name}" threw: ${sdk.Security.redact(err.message)}
|
|
71
|
+
`
|
|
72
|
+
);
|
|
55
73
|
return {
|
|
56
74
|
block: true,
|
|
57
|
-
message: `hook ${h.name}
|
|
75
|
+
message: `Request blocked: hook "${h.name}" failed.`
|
|
58
76
|
};
|
|
59
77
|
}
|
|
60
78
|
if (decision !== void 0 && decision.block === true) {
|
|
@@ -274,11 +292,90 @@ var SessionRouter = class {
|
|
|
274
292
|
}
|
|
275
293
|
};
|
|
276
294
|
|
|
295
|
+
// src/text/chunk.ts
|
|
296
|
+
function searchBoundary(remaining, window, boundaries) {
|
|
297
|
+
let cut = window;
|
|
298
|
+
for (const b of boundaries) {
|
|
299
|
+
cut = remaining.lastIndexOf(b, window);
|
|
300
|
+
if (cut >= window * 0.5) return cut;
|
|
301
|
+
}
|
|
302
|
+
return cut;
|
|
303
|
+
}
|
|
304
|
+
function assertPositiveInt(label, value) {
|
|
305
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
306
|
+
throw new RangeError(`${label} must be a positive integer, received ${value}`);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
function guardSurrogate(text, cut) {
|
|
310
|
+
if (cut >= text.length) return cut;
|
|
311
|
+
const code = text.charCodeAt(cut);
|
|
312
|
+
return code >= 56320 && code <= 57343 ? cut - 1 : cut;
|
|
313
|
+
}
|
|
314
|
+
function findCut(remaining, window, boundaries, lastResort, surrogateGuard) {
|
|
315
|
+
let cut = searchBoundary(remaining, window, boundaries);
|
|
316
|
+
if (cut < window * 0.5) {
|
|
317
|
+
cut = lastResort === "last-boundary" && cut > 0 ? cut : window;
|
|
318
|
+
}
|
|
319
|
+
if (surrogateGuard) cut = guardSurrogate(remaining, cut);
|
|
320
|
+
return cut <= 0 ? window : cut;
|
|
321
|
+
}
|
|
322
|
+
function chunkText(text, options) {
|
|
323
|
+
const {
|
|
324
|
+
limit,
|
|
325
|
+
safeLimit = limit,
|
|
326
|
+
boundaries = ["\n\n", "\n", " "],
|
|
327
|
+
lastResort = "window",
|
|
328
|
+
surrogateGuard = false,
|
|
329
|
+
stripLeading = /^\n+/,
|
|
330
|
+
trimParts = false
|
|
331
|
+
} = options;
|
|
332
|
+
assertPositiveInt("chunkText: limit", limit);
|
|
333
|
+
assertPositiveInt("chunkText: safeLimit", safeLimit);
|
|
334
|
+
if (safeLimit > limit) {
|
|
335
|
+
throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);
|
|
336
|
+
}
|
|
337
|
+
const finalize = (parts2) => trimParts ? parts2.map((p) => p.trim()).filter((p) => p.length > 0) : parts2;
|
|
338
|
+
if (text.length <= limit) {
|
|
339
|
+
return finalize([text]);
|
|
340
|
+
}
|
|
341
|
+
const parts = [];
|
|
342
|
+
let remaining = text;
|
|
343
|
+
while (remaining.length > safeLimit) {
|
|
344
|
+
const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);
|
|
345
|
+
parts.push(remaining.slice(0, cut));
|
|
346
|
+
remaining = remaining.slice(cut).replace(stripLeading, "");
|
|
347
|
+
}
|
|
348
|
+
if (remaining.length > 0) parts.push(remaining);
|
|
349
|
+
return finalize(parts);
|
|
350
|
+
}
|
|
351
|
+
function chunkByGrapheme(text, options) {
|
|
352
|
+
const { limit, partLimit = limit } = options;
|
|
353
|
+
assertPositiveInt("chunkByGrapheme: limit", limit);
|
|
354
|
+
assertPositiveInt("chunkByGrapheme: partLimit", partLimit);
|
|
355
|
+
if (text.length === 0) return [""];
|
|
356
|
+
if (text.length <= limit) return [text];
|
|
357
|
+
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
358
|
+
const parts = [];
|
|
359
|
+
let buf = "";
|
|
360
|
+
for (const { segment } of segmenter.segment(text)) {
|
|
361
|
+
if (buf.length + segment.length > partLimit) {
|
|
362
|
+
if (buf.length > 0) parts.push(buf);
|
|
363
|
+
buf = "";
|
|
364
|
+
}
|
|
365
|
+
buf += segment;
|
|
366
|
+
}
|
|
367
|
+
if (buf.length > 0) parts.push(buf);
|
|
368
|
+
return parts;
|
|
369
|
+
}
|
|
370
|
+
|
|
277
371
|
exports.BasePlatformAdapter = BasePlatformAdapter;
|
|
278
372
|
exports.DeliveryRouter = DeliveryRouter;
|
|
373
|
+
exports.GatewayConfigurationError = GatewayConfigurationError;
|
|
279
374
|
exports.GatewayRunner = GatewayRunner;
|
|
280
375
|
exports.HookExecutor = HookExecutor;
|
|
281
376
|
exports.SessionRouter = SessionRouter;
|
|
377
|
+
exports.chunkByGrapheme = chunkByGrapheme;
|
|
378
|
+
exports.chunkText = chunkText;
|
|
282
379
|
exports.defaultStrategy = defaultStrategy;
|
|
283
380
|
//# sourceMappingURL=index.cjs.map
|
|
284
381
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/hooks/types.ts","../src/runner/gateway-runner.ts","../src/session/router.ts"],"names":["Security"],"mappings":";;;;;AAqDO,IAAe,sBAAf,MAAmC;AAAA;AAAA,EAmBxC,MAAM,YAAY,UAAA,EAAmC;AAAA,EAErD;AAAA;AAAA,EAGA,MAAM,WAAW,UAAA,EAAmC;AAAA,EAEpD;AACF;;;ACvCO,IAAM,iBAAN,MAAqB;AAAA,EACT,QAAA,uBAAe,GAAA,EAAuC;AAAA,EAEvE,SAAS,OAAA,EAAoC;AAC3C,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,QAAA,EAAU,OAAO,CAAA;AAAA,EAC7C;AAAA,EAEA,MAAM,KAAK,GAAA,EAA2C;AACpD,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,IAAI,QAAQ,CAAA;AAC9C,IAAA,IAAI,YAAY,MAAA,EAAW;AACzB,M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AAQ,GAAG,IAAI,GAAG,CAAA,CAAA;AAAA;AAE1C;AAEA,SAAS,SAAS,CAAA,EAAmB;AACnC,EAAA,OAAO,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAA;AAC5B;AASO,IAAM,gBAAN,MAAoB;AAAA,EACzB,WAAA,CAA6B,WAA4B,eAAA,EAAiB;AAA7C,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA,EAA8C;AAAA,EAA9C,QAAA;AAAA,EAE7B,eAAe,KAAA,EAAoC;AACjD,IAAA,OAAO,IAAA,CAAK,SAAS,KAAK,CAAA;AAAA,EAC5B;AACF","file":"index.cjs","sourcesContent":["/**\n * `BasePlatformAdapter` — contract every transport adapter implements\n * (T1.2, ADR D172).\n *\n * Adapters share ~30% of lifecycle code (typing indicators, event\n * normalization patterns). An abstract class with concrete defaults\n * + abstract hooks is the right shape — interface-only would force\n * every adapter to copy the defaults.\n *\n * Consumers use it via `instanceof` and the public subclass exports\n * (`TelegramAdapter`, `DiscordAdapter`, ...).\n */\n\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Outbound message shape — what `sendMessage` accepts. */\nexport interface OutboundMessage {\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n readonly text: string;\n /** Markdown / HTML rendering hint. Default \"plain\". */\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n /** Optional reply target. */\n readonly replyTo?: string;\n}\n\n/** Send result — adapters return this instead of throwing on platform errors. */\nexport interface SendResult {\n readonly ok: boolean;\n readonly messageId?: string;\n readonly error?: { readonly code: string; readonly message: string };\n}\n\n/**\n * Abstract base for all platform adapters.\n *\n * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.\n * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden.\n *\n * **Contract:**\n * - `connect()` is idempotent. Calling twice returns true the second time.\n * - `disconnect()` is idempotent.\n * - `sendMessage` returns a `SendResult`; it MUST NOT throw on platform errors\n * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.\n * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling\n * `onInbound` twice replaces the previous handler — does NOT stack.\n * - `sendMessage` with empty text returns `{ ok: false, code: \"empty_text\" }`.\n *\n * @public\n */\nexport abstract class BasePlatformAdapter {\n abstract readonly platform: PlatformName;\n\n /** Open the connection. Returns `true` on success; never throws. */\n abstract connect(): Promise<boolean>;\n\n /** Close the connection. Idempotent; safe to call when never connected. */\n abstract disconnect(): Promise<void>;\n\n /** Send a message. Returns a `SendResult`; never throws on platform errors. */\n abstract sendMessage(out: OutboundMessage): Promise<SendResult>;\n\n /**\n * Subscribe to inbound events. Returns an unsubscribe function.\n * EC-H: second call REPLACES the previous handler (does not stack).\n */\n abstract onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void;\n\n /** Lifecycle: emit a typing indicator. Default: noop. */\n async startTyping(_channelId: string): Promise<void> {\n /* override */\n }\n\n /** Lifecycle: stop the typing indicator. Default: noop. */\n async stopTyping(_channelId: string): Promise<void> {\n /* override */\n }\n}\n","/**\n * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).\n *\n * The router holds a map of `platform → adapter` and forwards\n * `DeliveryRequest` to the right adapter's `sendMessage`. Composes\n * with `Cron` from `@theokit/sdk` for scheduled delivery — the\n * router is the \"WHERE to send\", Cron is the \"WHEN to fire\".\n *\n * @public\n */\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** Target for an outbound delivery. */\nexport interface DeliveryTarget {\n readonly platform: PlatformName;\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n}\n\n/** Full outbound request: target + content. */\nexport interface DeliveryRequest extends DeliveryTarget {\n readonly text: string;\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n readonly replyTo?: string;\n}\n\n/**\n * Routes outbound requests to the correct adapter.\n *\n * **Contract:**\n * - `register` is last-writer-wins by platform.\n * - `send` with unknown platform returns `{ ok: false, code: \"no_adapter\" }`.\n * - `send` never throws on platform errors (delegates to adapter's SendResult).\n *\n * @public\n */\nexport class DeliveryRouter {\n private readonly adapters = new Map<PlatformName, BasePlatformAdapter>();\n\n register(adapter: BasePlatformAdapter): void {\n this.adapters.set(adapter.platform, adapter);\n }\n\n async send(req: DeliveryRequest): Promise<SendResult> {\n const adapter = this.adapters.get(req.platform);\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for platform \"${req.platform}\"` },\n };\n }\n return adapter.sendMessage({\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n });\n }\n}\n","/**\n * Gateway hooks — own contract, not a `Plugin.kind` extension\n * (T4.1, ADRs D176, D177).\n *\n * Three fire points:\n * - `pre_inbound` — runs sequentially; first `{ block: true }` short-circuits.\n * - `post_outbound` — fire-and-forget; errors logged.\n * - `on_error` — fire-and-forget; called when the handler throws.\n *\n * Signature mirrors the SDK's `pre_tool_call` veto (D101) so consumers\n * have a single mental model for \"block or continue\" hooks.\n *\n * @public\n */\n\nimport type { OutboundMessage, SendResult } from \"../adapter/base.js\";\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Closed enum of hook fire points. */\nexport type HookName = \"pre_inbound\" | \"post_outbound\" | \"on_error\";\n\n/**\n * Decision returned by a `pre_inbound` hook.\n *\n * - `block: true` short-circuits the chain — handler does NOT run.\n * - `message` set → runner calls `ctx.reply(message)` BEFORE short-circuit (EC-D).\n * - `block: false` or `undefined` → continue.\n */\nexport interface HookDecision {\n readonly block?: boolean;\n readonly message?: string;\n}\n\n/** Context passed to `pre_inbound` hooks. */\nexport interface PreInboundContext {\n readonly event: GatewayMessageEvent;\n}\n\n/** Context passed to `post_outbound` hooks. */\nexport interface PostOutboundContext {\n readonly event: GatewayMessageEvent;\n readonly outbound: OutboundMessage;\n readonly result: SendResult;\n}\n\n/** Context passed to `on_error` hooks. */\nexport interface OnErrorContext {\n readonly event: GatewayMessageEvent;\n readonly error: Error;\n}\n\n/** A gateway hook: any of the three fire-point methods are optional. */\nexport interface GatewayHook {\n readonly name: string;\n // biome-ignore lint/suspicious/noConfusingVoidType: sync-or-async hook ergonomics — matches SDK pre_tool_call signature (D101).\n pre_inbound?(ctx: PreInboundContext): Promise<HookDecision | void> | HookDecision | void;\n post_outbound?(ctx: PostOutboundContext): Promise<void> | void;\n on_error?(ctx: OnErrorContext): Promise<void> | void;\n}\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {}\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n return {\n block: true,\n message: `hook ${h.name} threw: ${(err as Error).message}`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport { type GatewayHook, HookExecutor } from \"../hooks/types.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /** Connect all adapters and wire inbound dispatch. */\n async start(): Promise<void> {\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => setTimeout(r, drainMs)),\n ]);\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(\n `[gateway] handler error: ${Security.redact((err as Error).message)}\\n`,\n );\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n const adapter = this.adaptersByPlatform.get(event.platform);\n return {\n event,\n reply: async (text, opts) => {\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` },\n };\n }\n return adapter.sendMessage({\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n });\n },\n };\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/errors/config-error.ts","../src/hooks/executor.ts","../src/runner/gateway-runner.ts","../src/session/router.ts","../src/text/chunk.ts"],"names":["Security","parts"],"mappings":";;;;;AAqDO,IAAe,sBAAf,MAAmC;AAAA;AAAA,EAmBxC,MAAM,YAAY,UAAA,EAAmC;AAAA,EAErD;AAAA;AAAA,EAGA,MAAM,WAAW,UAAA,EAAmC;AAAA,EAEpD;AACF;;;ACvCO,IAAM,iBAAN,MAAqB;AAAA,EACT,QAAA,uBAAe,GAAA,EAAuC;A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A,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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
* }
|
|
13
13
|
* ```
|
|
14
14
|
*
|
|
15
|
+
* This union is intentionally **closed** — adding a platform edits it here
|
|
16
|
+
* rather than extending it externally. The trade-off (exhaustive narrowing over
|
|
17
|
+
* OCP purity) is recorded in `wiki/decisions/adr-0001-message-event-closed-union.md`.
|
|
18
|
+
*
|
|
15
19
|
* @public
|
|
16
20
|
*/
|
|
17
21
|
/** Closed enum of supported transport platforms. */
|
|
@@ -325,6 +329,40 @@ declare class DeliveryRouter {
|
|
|
325
329
|
send(req: DeliveryRequest): Promise<SendResult>;
|
|
326
330
|
}
|
|
327
331
|
|
|
332
|
+
/**
|
|
333
|
+
* `GatewayConfigurationError` — shared base for per-adapter configuration
|
|
334
|
+
* errors (roadmap M0/M2).
|
|
335
|
+
*
|
|
336
|
+
* Every platform adapter previously defined an identical
|
|
337
|
+
* `ConfigurationError extends Error` (same `code`/`detail` fields, same
|
|
338
|
+
* options interface, same `` `${pkg}: ${code}` `` default message) — only the
|
|
339
|
+
* package prefix differed. This base single-sources that contract. Adapters
|
|
340
|
+
* extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
|
|
341
|
+
* their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
|
|
342
|
+
*
|
|
343
|
+
* @public
|
|
344
|
+
*/
|
|
345
|
+
/** Public input shape for the {@link GatewayConfigurationError} constructor. */
|
|
346
|
+
interface GatewayConfigurationErrorOptions {
|
|
347
|
+
readonly code: string;
|
|
348
|
+
readonly message?: string;
|
|
349
|
+
readonly detail?: string;
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Base configuration error. Not thrown directly by adapters — they subclass it
|
|
353
|
+
* with a fixed package prefix.
|
|
354
|
+
*/
|
|
355
|
+
declare class GatewayConfigurationError extends Error {
|
|
356
|
+
readonly name: string;
|
|
357
|
+
readonly code: string;
|
|
358
|
+
readonly detail: string | undefined;
|
|
359
|
+
/**
|
|
360
|
+
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
361
|
+
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
362
|
+
*/
|
|
363
|
+
constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
|
|
364
|
+
}
|
|
365
|
+
|
|
328
366
|
/**
|
|
329
367
|
* Gateway hooks — own contract, not a `Plugin.kind` extension
|
|
330
368
|
* (T4.1, ADRs D176, D177).
|
|
@@ -375,6 +413,17 @@ interface GatewayHook {
|
|
|
375
413
|
post_outbound?(ctx: PostOutboundContext): Promise<void> | void;
|
|
376
414
|
on_error?(ctx: OnErrorContext): Promise<void> | void;
|
|
377
415
|
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* `HookExecutor` — runs registered gateway hooks at their fire points.
|
|
419
|
+
*
|
|
420
|
+
* Split out of `hooks/types.ts` (which now holds the contract only) so the
|
|
421
|
+
* filename predicts its contents: interfaces live in `types.ts`, the run
|
|
422
|
+
* engine lives here. Behavior is identical to the previous colocated class.
|
|
423
|
+
*
|
|
424
|
+
* @public
|
|
425
|
+
*/
|
|
426
|
+
|
|
378
427
|
/**
|
|
379
428
|
* Runs registered hooks at the right fire points. Stateless — safe to
|
|
380
429
|
* construct per-event if hooks need event-scoped storage.
|
|
@@ -525,4 +574,93 @@ declare class SessionRouter {
|
|
|
525
574
|
resolveAgentId(event: MessageEvent): string;
|
|
526
575
|
}
|
|
527
576
|
|
|
528
|
-
|
|
577
|
+
/**
|
|
578
|
+
* `chunkText` — transport-agnostic, boundary-preferring text chunker.
|
|
579
|
+
*
|
|
580
|
+
* Single-sources the message-splitting knowledge that was copy-pasted across
|
|
581
|
+
* the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two
|
|
582
|
+
* boundary-search families that existed in the adapters:
|
|
583
|
+
*
|
|
584
|
+
* - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),
|
|
585
|
+
* boundary preference `"\n\n" → "\n" → " "`, UTF-16 surrogate-pair guard,
|
|
586
|
+
* leading-whitespace strip on continuation, optional part-trim.
|
|
587
|
+
* - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),
|
|
588
|
+
* boundary preference `"\n\n" → "\n"` (no space), no surrogate guard,
|
|
589
|
+
* leading-newline strip on continuation.
|
|
590
|
+
*
|
|
591
|
+
* The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different
|
|
592
|
+
* algorithm and is intentionally NOT folded in here — those adapters keep their
|
|
593
|
+
* grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.
|
|
594
|
+
*
|
|
595
|
+
* @public
|
|
596
|
+
*/
|
|
597
|
+
/** Options for {@link chunkText}. */
|
|
598
|
+
interface ChunkTextOptions {
|
|
599
|
+
/**
|
|
600
|
+
* Hard cap. If the whole input is `<= limit`, it is returned as a single
|
|
601
|
+
* chunk (subject to `trimParts`). Continuation chunks are cut within the
|
|
602
|
+
* `safeLimit` window.
|
|
603
|
+
*/
|
|
604
|
+
readonly limit: number;
|
|
605
|
+
/**
|
|
606
|
+
* Soft window each cut searches within. Defaults to `limit`. The Telegram
|
|
607
|
+
* family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).
|
|
608
|
+
*/
|
|
609
|
+
readonly safeLimit?: number;
|
|
610
|
+
/**
|
|
611
|
+
* Boundary strings tried, in order, from most to least preferred. A boundary
|
|
612
|
+
* is accepted once its position is `>= window * 0.5`; otherwise the next one
|
|
613
|
+
* is tried. Default: `["\n\n", "\n", " "]`.
|
|
614
|
+
*/
|
|
615
|
+
readonly boundaries?: readonly string[];
|
|
616
|
+
/**
|
|
617
|
+
* When no boundary reaches the half-window threshold:
|
|
618
|
+
* - `"last-boundary"` — use the last computed boundary if it is `> 0`,
|
|
619
|
+
* else fall back to the window edge (Slack family).
|
|
620
|
+
* - `"window"` — fall back straight to the window edge (Telegram family).
|
|
621
|
+
* Default: `"window"`.
|
|
622
|
+
*/
|
|
623
|
+
readonly lastResort?: "last-boundary" | "window";
|
|
624
|
+
/**
|
|
625
|
+
* Guard against slicing through a UTF-16 low surrogate (splitting an emoji).
|
|
626
|
+
* Default: `false`.
|
|
627
|
+
*/
|
|
628
|
+
readonly surrogateGuard?: boolean;
|
|
629
|
+
/**
|
|
630
|
+
* Pattern stripped from the START of each continuation chunk. Default `/^\n+/`
|
|
631
|
+
* (Telegram family). Slack family uses `/^\s+/`.
|
|
632
|
+
*/
|
|
633
|
+
readonly stripLeading?: RegExp;
|
|
634
|
+
/**
|
|
635
|
+
* When true, each resulting part is `.trim()`-ed and empty parts are dropped
|
|
636
|
+
* (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.
|
|
637
|
+
*/
|
|
638
|
+
readonly trimParts?: boolean;
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Split `text` into chunks no longer than the configured window, preferring
|
|
642
|
+
* natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.
|
|
643
|
+
*/
|
|
644
|
+
declare function chunkText(text: string, options: ChunkTextOptions): string[];
|
|
645
|
+
/** Options for {@link chunkByGrapheme}. */
|
|
646
|
+
interface ChunkByGraphemeOptions {
|
|
647
|
+
/** If `text.length <= limit`, it is returned as a single chunk. */
|
|
648
|
+
readonly limit: number;
|
|
649
|
+
/**
|
|
650
|
+
* Max length per emitted part during the grapheme walk. Defaults to `limit`.
|
|
651
|
+
* Callers that reserve room for a per-part prefix (e.g. SMS `"(i/N) "`) pass a
|
|
652
|
+
* `partLimit` below `limit`.
|
|
653
|
+
*/
|
|
654
|
+
readonly partLimit?: number;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,
|
|
658
|
+
* regional-indicator pair, or combining sequence. Distinct algorithm from
|
|
659
|
+
* {@link chunkText} — used by adapters that must respect grapheme boundaries
|
|
660
|
+
* (LINE, SMS) rather than search for whitespace boundaries.
|
|
661
|
+
*
|
|
662
|
+
* @public
|
|
663
|
+
*/
|
|
664
|
+
declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
|
|
665
|
+
|
|
666
|
+
export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
|
package/dist/index.d.ts
CHANGED
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
* }
|
|
13
13
|
* ```
|
|
14
14
|
*
|
|
15
|
+
* This union is intentionally **closed** — adding a platform edits it here
|
|
16
|
+
* rather than extending it externally. The trade-off (exhaustive narrowing over
|
|
17
|
+
* OCP purity) is recorded in `wiki/decisions/adr-0001-message-event-closed-union.md`.
|
|
18
|
+
*
|
|
15
19
|
* @public
|
|
16
20
|
*/
|
|
17
21
|
/** Closed enum of supported transport platforms. */
|
|
@@ -325,6 +329,40 @@ declare class DeliveryRouter {
|
|
|
325
329
|
send(req: DeliveryRequest): Promise<SendResult>;
|
|
326
330
|
}
|
|
327
331
|
|
|
332
|
+
/**
|
|
333
|
+
* `GatewayConfigurationError` — shared base for per-adapter configuration
|
|
334
|
+
* errors (roadmap M0/M2).
|
|
335
|
+
*
|
|
336
|
+
* Every platform adapter previously defined an identical
|
|
337
|
+
* `ConfigurationError extends Error` (same `code`/`detail` fields, same
|
|
338
|
+
* options interface, same `` `${pkg}: ${code}` `` default message) — only the
|
|
339
|
+
* package prefix differed. This base single-sources that contract. Adapters
|
|
340
|
+
* extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
|
|
341
|
+
* their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
|
|
342
|
+
*
|
|
343
|
+
* @public
|
|
344
|
+
*/
|
|
345
|
+
/** Public input shape for the {@link GatewayConfigurationError} constructor. */
|
|
346
|
+
interface GatewayConfigurationErrorOptions {
|
|
347
|
+
readonly code: string;
|
|
348
|
+
readonly message?: string;
|
|
349
|
+
readonly detail?: string;
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Base configuration error. Not thrown directly by adapters — they subclass it
|
|
353
|
+
* with a fixed package prefix.
|
|
354
|
+
*/
|
|
355
|
+
declare class GatewayConfigurationError extends Error {
|
|
356
|
+
readonly name: string;
|
|
357
|
+
readonly code: string;
|
|
358
|
+
readonly detail: string | undefined;
|
|
359
|
+
/**
|
|
360
|
+
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
361
|
+
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
362
|
+
*/
|
|
363
|
+
constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
|
|
364
|
+
}
|
|
365
|
+
|
|
328
366
|
/**
|
|
329
367
|
* Gateway hooks — own contract, not a `Plugin.kind` extension
|
|
330
368
|
* (T4.1, ADRs D176, D177).
|
|
@@ -375,6 +413,17 @@ interface GatewayHook {
|
|
|
375
413
|
post_outbound?(ctx: PostOutboundContext): Promise<void> | void;
|
|
376
414
|
on_error?(ctx: OnErrorContext): Promise<void> | void;
|
|
377
415
|
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* `HookExecutor` — runs registered gateway hooks at their fire points.
|
|
419
|
+
*
|
|
420
|
+
* Split out of `hooks/types.ts` (which now holds the contract only) so the
|
|
421
|
+
* filename predicts its contents: interfaces live in `types.ts`, the run
|
|
422
|
+
* engine lives here. Behavior is identical to the previous colocated class.
|
|
423
|
+
*
|
|
424
|
+
* @public
|
|
425
|
+
*/
|
|
426
|
+
|
|
378
427
|
/**
|
|
379
428
|
* Runs registered hooks at the right fire points. Stateless — safe to
|
|
380
429
|
* construct per-event if hooks need event-scoped storage.
|
|
@@ -525,4 +574,93 @@ declare class SessionRouter {
|
|
|
525
574
|
resolveAgentId(event: MessageEvent): string;
|
|
526
575
|
}
|
|
527
576
|
|
|
528
|
-
|
|
577
|
+
/**
|
|
578
|
+
* `chunkText` — transport-agnostic, boundary-preferring text chunker.
|
|
579
|
+
*
|
|
580
|
+
* Single-sources the message-splitting knowledge that was copy-pasted across
|
|
581
|
+
* the platform adapters (roadmap M0/M1). It reproduces, byte-for-byte, the two
|
|
582
|
+
* boundary-search families that existed in the adapters:
|
|
583
|
+
*
|
|
584
|
+
* - **Slack family** (Slack/WhatsApp/Teams): fixed window (`safeLimit = limit`),
|
|
585
|
+
* boundary preference `"\n\n" → "\n" → " "`, UTF-16 surrogate-pair guard,
|
|
586
|
+
* leading-whitespace strip on continuation, optional part-trim.
|
|
587
|
+
* - **Telegram family** (Telegram/Discord): soft window (`safeLimit < limit`),
|
|
588
|
+
* boundary preference `"\n\n" → "\n"` (no space), no surrogate guard,
|
|
589
|
+
* leading-newline strip on continuation.
|
|
590
|
+
*
|
|
591
|
+
* The grapheme family (LINE/SMS, `Intl.Segmenter`) is a genuinely different
|
|
592
|
+
* algorithm and is intentionally NOT folded in here — those adapters keep their
|
|
593
|
+
* grapheme walk. Telegram's markdown-pair balancing likewise stays adapter-local.
|
|
594
|
+
*
|
|
595
|
+
* @public
|
|
596
|
+
*/
|
|
597
|
+
/** Options for {@link chunkText}. */
|
|
598
|
+
interface ChunkTextOptions {
|
|
599
|
+
/**
|
|
600
|
+
* Hard cap. If the whole input is `<= limit`, it is returned as a single
|
|
601
|
+
* chunk (subject to `trimParts`). Continuation chunks are cut within the
|
|
602
|
+
* `safeLimit` window.
|
|
603
|
+
*/
|
|
604
|
+
readonly limit: number;
|
|
605
|
+
/**
|
|
606
|
+
* Soft window each cut searches within. Defaults to `limit`. The Telegram
|
|
607
|
+
* family uses a `safeLimit` strictly below `limit` (e.g. 1900 < 2000).
|
|
608
|
+
*/
|
|
609
|
+
readonly safeLimit?: number;
|
|
610
|
+
/**
|
|
611
|
+
* Boundary strings tried, in order, from most to least preferred. A boundary
|
|
612
|
+
* is accepted once its position is `>= window * 0.5`; otherwise the next one
|
|
613
|
+
* is tried. Default: `["\n\n", "\n", " "]`.
|
|
614
|
+
*/
|
|
615
|
+
readonly boundaries?: readonly string[];
|
|
616
|
+
/**
|
|
617
|
+
* When no boundary reaches the half-window threshold:
|
|
618
|
+
* - `"last-boundary"` — use the last computed boundary if it is `> 0`,
|
|
619
|
+
* else fall back to the window edge (Slack family).
|
|
620
|
+
* - `"window"` — fall back straight to the window edge (Telegram family).
|
|
621
|
+
* Default: `"window"`.
|
|
622
|
+
*/
|
|
623
|
+
readonly lastResort?: "last-boundary" | "window";
|
|
624
|
+
/**
|
|
625
|
+
* Guard against slicing through a UTF-16 low surrogate (splitting an emoji).
|
|
626
|
+
* Default: `false`.
|
|
627
|
+
*/
|
|
628
|
+
readonly surrogateGuard?: boolean;
|
|
629
|
+
/**
|
|
630
|
+
* Pattern stripped from the START of each continuation chunk. Default `/^\n+/`
|
|
631
|
+
* (Telegram family). Slack family uses `/^\s+/`.
|
|
632
|
+
*/
|
|
633
|
+
readonly stripLeading?: RegExp;
|
|
634
|
+
/**
|
|
635
|
+
* When true, each resulting part is `.trim()`-ed and empty parts are dropped
|
|
636
|
+
* (WhatsApp/Teams). Also applied to the single-chunk fast path. Default `false`.
|
|
637
|
+
*/
|
|
638
|
+
readonly trimParts?: boolean;
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Split `text` into chunks no longer than the configured window, preferring
|
|
642
|
+
* natural boundaries. Behavior is fully determined by {@link ChunkTextOptions}.
|
|
643
|
+
*/
|
|
644
|
+
declare function chunkText(text: string, options: ChunkTextOptions): string[];
|
|
645
|
+
/** Options for {@link chunkByGrapheme}. */
|
|
646
|
+
interface ChunkByGraphemeOptions {
|
|
647
|
+
/** If `text.length <= limit`, it is returned as a single chunk. */
|
|
648
|
+
readonly limit: number;
|
|
649
|
+
/**
|
|
650
|
+
* Max length per emitted part during the grapheme walk. Defaults to `limit`.
|
|
651
|
+
* Callers that reserve room for a per-part prefix (e.g. SMS `"(i/N) "`) pass a
|
|
652
|
+
* `partLimit` below `limit`.
|
|
653
|
+
*/
|
|
654
|
+
readonly partLimit?: number;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Grapheme-cluster-safe chunker (`Intl.Segmenter`). Never severs an emoji,
|
|
658
|
+
* regional-indicator pair, or combining sequence. Distinct algorithm from
|
|
659
|
+
* {@link chunkText} — used by adapters that must respect grapheme boundaries
|
|
660
|
+
* (LINE, SMS) rather than search for whitespace boundaries.
|
|
661
|
+
*
|
|
662
|
+
* @public
|
|
663
|
+
*/
|
|
664
|
+
declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
|
|
665
|
+
|
|
666
|
+
export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
|
package/dist/index.js
CHANGED
|
@@ -33,7 +33,21 @@ var DeliveryRouter = class {
|
|
|
33
33
|
}
|
|
34
34
|
};
|
|
35
35
|
|
|
36
|
-
// src/
|
|
36
|
+
// src/errors/config-error.ts
|
|
37
|
+
var GatewayConfigurationError = class extends Error {
|
|
38
|
+
name = "GatewayConfigurationError";
|
|
39
|
+
code;
|
|
40
|
+
detail;
|
|
41
|
+
/**
|
|
42
|
+
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
43
|
+
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
44
|
+
*/
|
|
45
|
+
constructor(prefix, opts) {
|
|
46
|
+
super(opts.message ?? `${prefix}: ${opts.code}`);
|
|
47
|
+
this.code = opts.code;
|
|
48
|
+
this.detail = opts.detail;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
37
51
|
var HookExecutor = class {
|
|
38
52
|
constructor(hooks) {
|
|
39
53
|
this.hooks = hooks;
|
|
@@ -50,9 +64,13 @@ var HookExecutor = class {
|
|
|
50
64
|
try {
|
|
51
65
|
decision = await h.pre_inbound(ctx);
|
|
52
66
|
} catch (err) {
|
|
67
|
+
process.stderr.write(
|
|
68
|
+
`[gateway] pre_inbound hook "${h.name}" threw: ${Security.redact(err.message)}
|
|
69
|
+
`
|
|
70
|
+
);
|
|
53
71
|
return {
|
|
54
72
|
block: true,
|
|
55
|
-
message: `hook ${h.name}
|
|
73
|
+
message: `Request blocked: hook "${h.name}" failed.`
|
|
56
74
|
};
|
|
57
75
|
}
|
|
58
76
|
if (decision !== void 0 && decision.block === true) {
|
|
@@ -272,6 +290,82 @@ var SessionRouter = class {
|
|
|
272
290
|
}
|
|
273
291
|
};
|
|
274
292
|
|
|
275
|
-
|
|
293
|
+
// src/text/chunk.ts
|
|
294
|
+
function searchBoundary(remaining, window, boundaries) {
|
|
295
|
+
let cut = window;
|
|
296
|
+
for (const b of boundaries) {
|
|
297
|
+
cut = remaining.lastIndexOf(b, window);
|
|
298
|
+
if (cut >= window * 0.5) return cut;
|
|
299
|
+
}
|
|
300
|
+
return cut;
|
|
301
|
+
}
|
|
302
|
+
function assertPositiveInt(label, value) {
|
|
303
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
304
|
+
throw new RangeError(`${label} must be a positive integer, received ${value}`);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
function guardSurrogate(text, cut) {
|
|
308
|
+
if (cut >= text.length) return cut;
|
|
309
|
+
const code = text.charCodeAt(cut);
|
|
310
|
+
return code >= 56320 && code <= 57343 ? cut - 1 : cut;
|
|
311
|
+
}
|
|
312
|
+
function findCut(remaining, window, boundaries, lastResort, surrogateGuard) {
|
|
313
|
+
let cut = searchBoundary(remaining, window, boundaries);
|
|
314
|
+
if (cut < window * 0.5) {
|
|
315
|
+
cut = lastResort === "last-boundary" && cut > 0 ? cut : window;
|
|
316
|
+
}
|
|
317
|
+
if (surrogateGuard) cut = guardSurrogate(remaining, cut);
|
|
318
|
+
return cut <= 0 ? window : cut;
|
|
319
|
+
}
|
|
320
|
+
function chunkText(text, options) {
|
|
321
|
+
const {
|
|
322
|
+
limit,
|
|
323
|
+
safeLimit = limit,
|
|
324
|
+
boundaries = ["\n\n", "\n", " "],
|
|
325
|
+
lastResort = "window",
|
|
326
|
+
surrogateGuard = false,
|
|
327
|
+
stripLeading = /^\n+/,
|
|
328
|
+
trimParts = false
|
|
329
|
+
} = options;
|
|
330
|
+
assertPositiveInt("chunkText: limit", limit);
|
|
331
|
+
assertPositiveInt("chunkText: safeLimit", safeLimit);
|
|
332
|
+
if (safeLimit > limit) {
|
|
333
|
+
throw new RangeError(`chunkText: safeLimit (${safeLimit}) must be <= limit (${limit})`);
|
|
334
|
+
}
|
|
335
|
+
const finalize = (parts2) => trimParts ? parts2.map((p) => p.trim()).filter((p) => p.length > 0) : parts2;
|
|
336
|
+
if (text.length <= limit) {
|
|
337
|
+
return finalize([text]);
|
|
338
|
+
}
|
|
339
|
+
const parts = [];
|
|
340
|
+
let remaining = text;
|
|
341
|
+
while (remaining.length > safeLimit) {
|
|
342
|
+
const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);
|
|
343
|
+
parts.push(remaining.slice(0, cut));
|
|
344
|
+
remaining = remaining.slice(cut).replace(stripLeading, "");
|
|
345
|
+
}
|
|
346
|
+
if (remaining.length > 0) parts.push(remaining);
|
|
347
|
+
return finalize(parts);
|
|
348
|
+
}
|
|
349
|
+
function chunkByGrapheme(text, options) {
|
|
350
|
+
const { limit, partLimit = limit } = options;
|
|
351
|
+
assertPositiveInt("chunkByGrapheme: limit", limit);
|
|
352
|
+
assertPositiveInt("chunkByGrapheme: partLimit", partLimit);
|
|
353
|
+
if (text.length === 0) return [""];
|
|
354
|
+
if (text.length <= limit) return [text];
|
|
355
|
+
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
356
|
+
const parts = [];
|
|
357
|
+
let buf = "";
|
|
358
|
+
for (const { segment } of segmenter.segment(text)) {
|
|
359
|
+
if (buf.length + segment.length > partLimit) {
|
|
360
|
+
if (buf.length > 0) parts.push(buf);
|
|
361
|
+
buf = "";
|
|
362
|
+
}
|
|
363
|
+
buf += segment;
|
|
364
|
+
}
|
|
365
|
+
if (buf.length > 0) parts.push(buf);
|
|
366
|
+
return parts;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export { BasePlatformAdapter, DeliveryRouter, GatewayConfigurationError, GatewayRunner, HookExecutor, SessionRouter, chunkByGrapheme, chunkText, defaultStrategy };
|
|
276
370
|
//# sourceMappingURL=index.js.map
|
|
277
371
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/hooks/types.ts","../src/runner/gateway-runner.ts","../src/session/router.ts"],"names":[],"mappings":";;;AAqDO,IAAe,sBAAf,MAAmC;AAAA;AAAA,EAmBxC,MAAM,YAAY,UAAA,EAAmC;AAAA,EAErD;AAAA;AAAA,EAGA,MAAM,WAAW,UAAA,EAAmC;AAAA,EAEpD;AACF;;;ACvCO,IAAM,iBAAN,MAAqB;AAAA,EACT,QAAA,uBAAe,GAAA,EAAuC;AAAA,EAEvE,SAAS,OAAA,EAAoC;AAC3C,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,QAAA,EAAU,OAAO,CAAA;AAAA,EAC7C;AAAA,EAEA,MAAM,KAAK,GAAA,EAA2C;AACpD,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,IAAI,QAAQ,CAAA;AAC9C,IAAA,IAAI,YAAY,MAAA,EAAW;AACzB,MAAA,OAAO;AAAA,QACL,EAAA,EAAI,KAAA;AAAA,QACJ,KAAA,EAAO,EAAE,IAAA,EAAM,YAAA,EAAc,SAAS,CAAA,yBAAA,EAA4B,GAAA,CAAI,QAAQ,CAAA,CAAA,CAAA;AAAI,OACpF;AAAA,IACF;AACA,IAAA,OAAO,QAAQ,WA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A4B,eAAA,EAAiB;AAA7C,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA,EAA8C;AAAA,EAA9C,QAAA;AAAA,EAE7B,eAAe,KAAA,EAAoC;AACjD,IAAA,OAAO,IAAA,CAAK,SAAS,KAAK,CAAA;AAAA,EAC5B;AACF","file":"index.js","sourcesContent":["/**\n * `BasePlatformAdapter` — contract every transport adapter implements\n * (T1.2, ADR D172).\n *\n * Adapters share ~30% of lifecycle code (typing indicators, event\n * normalization patterns). An abstract class with concrete defaults\n * + abstract hooks is the right shape — interface-only would force\n * every adapter to copy the defaults.\n *\n * Consumers use it via `instanceof` and the public subclass exports\n * (`TelegramAdapter`, `DiscordAdapter`, ...).\n */\n\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Outbound message shape — what `sendMessage` accepts. */\nexport interface OutboundMessage {\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n readonly text: string;\n /** Markdown / HTML rendering hint. Default \"plain\". */\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n /** Optional reply target. */\n readonly replyTo?: string;\n}\n\n/** Send result — adapters return this instead of throwing on platform errors. */\nexport interface SendResult {\n readonly ok: boolean;\n readonly messageId?: string;\n readonly error?: { readonly code: string; readonly message: string };\n}\n\n/**\n * Abstract base for all platform adapters.\n *\n * Subclasses implement `connect`, `disconnect`, `sendMessage`, `onInbound`.\n * Lifecycle defaults (`startTyping`, `stopTyping`) noop unless overridden.\n *\n * **Contract:**\n * - `connect()` is idempotent. Calling twice returns true the second time.\n * - `disconnect()` is idempotent.\n * - `sendMessage` returns a `SendResult`; it MUST NOT throw on platform errors\n * (rate-limit, 4xx, network). Programmer errors (missing config) MAY throw.\n * - `onInbound(handler)` returns an unsubscribe function. EC-H: calling\n * `onInbound` twice replaces the previous handler — does NOT stack.\n * - `sendMessage` with empty text returns `{ ok: false, code: \"empty_text\" }`.\n *\n * @public\n */\nexport abstract class BasePlatformAdapter {\n abstract readonly platform: PlatformName;\n\n /** Open the connection. Returns `true` on success; never throws. */\n abstract connect(): Promise<boolean>;\n\n /** Close the connection. Idempotent; safe to call when never connected. */\n abstract disconnect(): Promise<void>;\n\n /** Send a message. Returns a `SendResult`; never throws on platform errors. */\n abstract sendMessage(out: OutboundMessage): Promise<SendResult>;\n\n /**\n * Subscribe to inbound events. Returns an unsubscribe function.\n * EC-H: second call REPLACES the previous handler (does not stack).\n */\n abstract onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void;\n\n /** Lifecycle: emit a typing indicator. Default: noop. */\n async startTyping(_channelId: string): Promise<void> {\n /* override */\n }\n\n /** Lifecycle: stop the typing indicator. Default: noop. */\n async stopTyping(_channelId: string): Promise<void> {\n /* override */\n }\n}\n","/**\n * `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).\n *\n * The router holds a map of `platform → adapter` and forwards\n * `DeliveryRequest` to the right adapter's `sendMessage`. Composes\n * with `Cron` from `@theokit/sdk` for scheduled delivery — the\n * router is the \"WHERE to send\", Cron is the \"WHEN to fire\".\n *\n * @public\n */\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport type { PlatformName } from \"../types/message-event.js\";\n\n/** Target for an outbound delivery. */\nexport interface DeliveryTarget {\n readonly platform: PlatformName;\n readonly channel: {\n readonly id: string;\n readonly type: \"dm\" | \"group\" | \"thread\";\n readonly topicId?: string;\n };\n}\n\n/** Full outbound request: target + content. */\nexport interface DeliveryRequest extends DeliveryTarget {\n readonly text: string;\n readonly format?: \"plain\" | \"markdown\" | \"html\";\n readonly replyTo?: string;\n}\n\n/**\n * Routes outbound requests to the correct adapter.\n *\n * **Contract:**\n * - `register` is last-writer-wins by platform.\n * - `send` with unknown platform returns `{ ok: false, code: \"no_adapter\" }`.\n * - `send` never throws on platform errors (delegates to adapter's SendResult).\n *\n * @public\n */\nexport class DeliveryRouter {\n private readonly adapters = new Map<PlatformName, BasePlatformAdapter>();\n\n register(adapter: BasePlatformAdapter): void {\n this.adapters.set(adapter.platform, adapter);\n }\n\n async send(req: DeliveryRequest): Promise<SendResult> {\n const adapter = this.adapters.get(req.platform);\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for platform \"${req.platform}\"` },\n };\n }\n return adapter.sendMessage({\n channel: req.channel,\n text: req.text,\n ...(req.format !== undefined ? { format: req.format } : {}),\n ...(req.replyTo !== undefined ? { replyTo: req.replyTo } : {}),\n });\n }\n}\n","/**\n * Gateway hooks — own contract, not a `Plugin.kind` extension\n * (T4.1, ADRs D176, D177).\n *\n * Three fire points:\n * - `pre_inbound` — runs sequentially; first `{ block: true }` short-circuits.\n * - `post_outbound` — fire-and-forget; errors logged.\n * - `on_error` — fire-and-forget; called when the handler throws.\n *\n * Signature mirrors the SDK's `pre_tool_call` veto (D101) so consumers\n * have a single mental model for \"block or continue\" hooks.\n *\n * @public\n */\n\nimport type { OutboundMessage, SendResult } from \"../adapter/base.js\";\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Closed enum of hook fire points. */\nexport type HookName = \"pre_inbound\" | \"post_outbound\" | \"on_error\";\n\n/**\n * Decision returned by a `pre_inbound` hook.\n *\n * - `block: true` short-circuits the chain — handler does NOT run.\n * - `message` set → runner calls `ctx.reply(message)` BEFORE short-circuit (EC-D).\n * - `block: false` or `undefined` → continue.\n */\nexport interface HookDecision {\n readonly block?: boolean;\n readonly message?: string;\n}\n\n/** Context passed to `pre_inbound` hooks. */\nexport interface PreInboundContext {\n readonly event: GatewayMessageEvent;\n}\n\n/** Context passed to `post_outbound` hooks. */\nexport interface PostOutboundContext {\n readonly event: GatewayMessageEvent;\n readonly outbound: OutboundMessage;\n readonly result: SendResult;\n}\n\n/** Context passed to `on_error` hooks. */\nexport interface OnErrorContext {\n readonly event: GatewayMessageEvent;\n readonly error: Error;\n}\n\n/** A gateway hook: any of the three fire-point methods are optional. */\nexport interface GatewayHook {\n readonly name: string;\n // biome-ignore lint/suspicious/noConfusingVoidType: sync-or-async hook ergonomics — matches SDK pre_tool_call signature (D101).\n pre_inbound?(ctx: PreInboundContext): Promise<HookDecision | void> | HookDecision | void;\n post_outbound?(ctx: PostOutboundContext): Promise<void> | void;\n on_error?(ctx: OnErrorContext): Promise<void> | void;\n}\n\n/**\n * Runs registered hooks at the right fire points. Stateless — safe to\n * construct per-event if hooks need event-scoped storage.\n *\n * @public\n */\nexport class HookExecutor {\n constructor(private readonly hooks: ReadonlyArray<GatewayHook>) {}\n\n /**\n * Fire `pre_inbound` hooks sequentially. First `{ block: true }` short-circuits.\n * A hook throwing is treated as `{ block: true }` (logged via the runner).\n */\n async firePreInbound(ctx: PreInboundContext): Promise<HookDecision> {\n for (const h of this.hooks) {\n if (h.pre_inbound === undefined) continue;\n // biome-ignore lint/suspicious/noConfusingVoidType: hook may return void (no decision) or a HookDecision.\n let decision: HookDecision | void;\n try {\n decision = await h.pre_inbound(ctx);\n } catch (err) {\n return {\n block: true,\n message: `hook ${h.name} threw: ${(err as Error).message}`,\n };\n }\n if (decision !== undefined && decision.block === true) {\n return decision;\n }\n }\n return { block: false };\n }\n\n /** Fire all `post_outbound` hooks; errors logged via stderr. */\n async firePostOutbound(ctx: PostOutboundContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.post_outbound === undefined) continue;\n try {\n await h.post_outbound(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] post_outbound hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n\n /** Fire all `on_error` hooks; errors logged via stderr. */\n async fireOnError(ctx: OnErrorContext): Promise<void> {\n for (const h of this.hooks) {\n if (h.on_error === undefined) continue;\n try {\n await h.on_error(ctx);\n } catch (err) {\n process.stderr.write(\n `[gateway] on_error hook \"${h.name}\" threw: ${(err as Error).message}\\n`,\n );\n }\n }\n }\n}\n","/**\n * `GatewayRunner` — top-level orchestrator (T1.3, ADR D170+ family).\n *\n * Owns the adapter map, dispatches inbound events through the hook chain,\n * builds a per-event `GatewayContext` whose `reply` auto-routes to the\n * adapter matching `event.platform` (EC-G).\n *\n * **Lifecycle:**\n * - `start()` connects all adapters in parallel via `Promise.all`. Partial\n * failure rolls back: connected adapters get `disconnect()`, then the\n * aggregate error rethrows.\n * - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)\n * BEFORE disconnecting (EC-E). Idempotent.\n *\n * **Hook chain on inbound:**\n * 1. `firePreInbound({ event })`\n * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.\n * 3. If `block: true` only: short-circuit silently.\n * 4. Otherwise: call user handler.\n * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).\n *\n * @public\n */\n\nimport { Security } from \"@theokit/sdk\";\n\nimport type { BasePlatformAdapter, SendResult } from \"../adapter/base.js\";\nimport { type GatewayHook, HookExecutor } from \"../hooks/types.js\";\nimport type { MessageEvent as GatewayMessageEvent, PlatformName } from \"../types/message-event.js\";\n\n/** Per-event context passed to the user handler. */\nexport interface GatewayContext {\n /** Send a reply to the originating channel (auto-routed by `event.platform`). */\n reply(text: string, opts?: { format?: \"plain\" | \"markdown\" | \"html\" }): Promise<SendResult>;\n /** The triggering event. */\n readonly event: GatewayMessageEvent;\n}\n\n/** User-supplied handler. */\nexport type GatewayHandler = (event: GatewayMessageEvent, ctx: GatewayContext) => Promise<void>;\n\n/** Runner configuration. */\nexport interface GatewayRunnerOptions {\n readonly adapters: ReadonlyArray<BasePlatformAdapter>;\n readonly handler: GatewayHandler;\n readonly hooks?: ReadonlyArray<GatewayHook>;\n /** Drain timeout for in-flight handlers on stop(). Default 10_000ms (EC-E). */\n readonly drainTimeoutMs?: number;\n /**\n * Prefixes that `runner.command(name, h)` matches on. Default `[\"/\"]`\n * (Telegram-style). Pass `[\"!\"]` for Discord, `[\"/\", \"!\"]` to accept\n * both. Word-boundary match (EC-A) applies to every prefix.\n *\n * @public\n */\n readonly commandPrefixes?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_DRAIN_MS = 10_000;\nconst DEFAULT_COMMAND_PREFIXES: ReadonlyArray<string> = [\"/\"];\n\n/**\n * Holds the registered adapters and dispatches inbound events through\n * the hook chain to the user handler. Use the sugar `runner.command(...)`\n * for slash command dispatch with word-boundary matching (EC-A).\n *\n * @public\n */\nexport class GatewayRunner {\n private readonly adaptersByPlatform = new Map<PlatformName, BasePlatformAdapter>();\n private readonly hookExecutor: HookExecutor;\n private readonly inflight = new Set<Promise<void>>();\n private readonly unsubs: Array<() => void> = [];\n /** Slash command registry: name → handler (word-boundary match, EC-A). */\n private readonly commands = new Map<string, GatewayHandler>();\n private connected = false;\n private stopped = false;\n\n constructor(private readonly opts: GatewayRunnerOptions) {\n for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);\n this.hookExecutor = new HookExecutor(opts.hooks ?? []);\n }\n\n /**\n * Register a slash command. Match rule (EC-A): text === \"/\" + name\n * OR text.startsWith(\"/\" + name + \" \") OR text.startsWith(\"/\" + name + \"@\").\n *\n * @public\n */\n command(name: string, handler: GatewayHandler): void {\n this.commands.set(name, handler);\n }\n\n /** Connect all adapters and wire inbound dispatch. */\n async start(): Promise<void> {\n if (this.connected) return;\n const connected: BasePlatformAdapter[] = [];\n try {\n await Promise.all(\n this.opts.adapters.map(async (a) => {\n const ok = await a.connect();\n if (ok) connected.push(a);\n else throw new Error(`adapter \"${a.platform}\" connect returned false`);\n }),\n );\n } catch (err) {\n // Roll back partial connections.\n await Promise.all(connected.map((a) => a.disconnect().catch(() => undefined)));\n throw err;\n }\n\n for (const a of this.opts.adapters) {\n // Fire-and-forget: grammy / discord.js await this callback. If we\n // awaited dispatch synchronously, the platform's event loop would\n // serialize all inbound messages behind whichever handler is\n // currently running (dogfood-2026-05-21 bug). Wrap the dispatch\n // promise in `inflight` synchronously so `stop()` still drains it.\n const unsub = a.onInbound(async (event) => {\n const p = this.dispatch(event);\n this.inflight.add(p);\n p.finally(() => this.inflight.delete(p));\n // Resolve immediately so the platform's event loop continues to\n // the next update. The real handler completes via the dispatch\n // promise tracked in `inflight` (preserves EC-E drain semantics).\n });\n this.unsubs.push(unsub);\n }\n this.connected = true;\n }\n\n /**\n * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,\n * then disconnects adapters. Idempotent (EC-E).\n */\n async stop(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n\n for (const unsub of this.unsubs) {\n try {\n unsub();\n } catch {\n /* ignore */\n }\n }\n this.unsubs.length = 0;\n\n const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;\n if (this.inflight.size > 0) {\n await Promise.race([\n Promise.all([...this.inflight]).then(() => undefined),\n new Promise<void>((r) => setTimeout(r, drainMs)),\n ]);\n }\n\n await Promise.all(\n [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => undefined)),\n );\n this.connected = false;\n }\n\n /** @internal */\n private async dispatch(event: GatewayMessageEvent): Promise<void> {\n const ctx = this.buildContext(event);\n\n // 1. pre_inbound hooks (EC-D auto-reply on block+message).\n const decision = await this.hookExecutor.firePreInbound({ event });\n if (decision.block === true) {\n if (decision.message !== undefined && decision.message.length > 0) {\n await ctx.reply(decision.message).catch(() => undefined);\n }\n return;\n }\n\n // 2. Slash command dispatch with word-boundary match (EC-A).\n const slashHandler = this.matchSlashCommand(event);\n const handler = slashHandler ?? this.opts.handler;\n\n // 3. Run handler with try/catch → on_error + redacted log (EC-F).\n // Note: dispatch DOES await the work internally so the dispatch promise\n // tracks completion (EC-E drain). The fire-and-forget happens at the\n // CALLER level (start()'s onInbound wrapper) so grammy/discord.js are\n // not serialized — see D192 (2026-05-21 dogfood discovery).\n const work = (async () => {\n try {\n await handler(event, ctx);\n } catch (err) {\n await this.hookExecutor.fireOnError({ event, error: err as Error });\n process.stderr.write(\n `[gateway] handler error: ${Security.redact((err as Error).message)}\\n`,\n );\n }\n })();\n this.inflight.add(work);\n work.finally(() => this.inflight.delete(work));\n await work;\n }\n\n /**\n * EC-A: word-boundary slash command match. Prevents `/skill` from\n * shadowing `/skills`. Returns the handler if a command matches,\n * undefined otherwise.\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: prefix-scan + word-boundary loop is one cohesive matcher; splitting hurts readability.\n private matchSlashCommand(event: GatewayMessageEvent): GatewayHandler | undefined {\n const text = event.text;\n const prefixes = this.opts.commandPrefixes ?? DEFAULT_COMMAND_PREFIXES;\n let activePrefix: string | undefined;\n for (const p of prefixes) {\n if (text.startsWith(p)) {\n activePrefix = p;\n break;\n }\n }\n if (activePrefix === undefined) return undefined;\n\n for (const [name, handler] of this.commands) {\n const full = `${activePrefix}${name}`;\n if (text === full) return handler;\n if (text.startsWith(`${full} `)) return handler;\n if (text.startsWith(`${full}@`)) return handler;\n }\n return undefined;\n }\n\n /** EC-G: per-event ctx whose reply routes to the matching adapter. */\n private buildContext(event: GatewayMessageEvent): GatewayContext {\n const adapter = this.adaptersByPlatform.get(event.platform);\n return {\n event,\n reply: async (text, opts) => {\n if (adapter === undefined) {\n return {\n ok: false,\n error: { code: \"no_adapter\", message: `no adapter for ${event.platform}` },\n };\n }\n return adapter.sendMessage({\n channel: event.channel,\n text,\n ...(opts?.format !== undefined ? { format: opts.format } : {}),\n });\n },\n };\n }\n}\n","/**\n * `SessionRouter` — pure routing logic: `MessageEvent → agentId`\n * (T2.1, ADR D174).\n *\n * The SDK already owns session persistence (`Agent.resume` + `agent-registry`).\n * The router's job is to produce a stable, deterministic key — the SDK then\n * hydrates the actual session.\n *\n * Default strategy format: `<platform>-<channelType>-<...key parts>`.\n *\n * **EC-B:** thread events without a `topicId` (adapter bug or non-thread\n * forum message) fall back to the group key — prevents `...-undefined`\n * split-brain sessions.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent } from \"../types/message-event.js\";\n\n/** Strategy function: pure mapping from event to agentId string. */\nexport type AgentIdStrategy = (event: GatewayMessageEvent) => string;\n\n/**\n * Default strategy. Sanitizes `-` to `_` inside ids so the format\n * remains parseable by `-` segments.\n */\nexport function defaultStrategy(event: GatewayMessageEvent): string {\n const { platform, channel, sender } = event;\n const sid = sanitize(sender.id);\n const cid = sanitize(channel.id);\n\n switch (channel.type) {\n case \"dm\":\n return `${platform}-dm-${sid}`;\n case \"thread\":\n // EC-B: missing topicId = adapter bug. Fall back to group key\n // to keep \"key absent === group session\" deterministic.\n if (channel.topicId === undefined) {\n return `${platform}-grp-${cid}-${sid}`;\n }\n return `${platform}-tpc-${cid}-${sanitize(channel.topicId)}`;\n case \"group\":\n return `${platform}-grp-${cid}-${sid}`;\n }\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/-/g, \"_\");\n}\n\n/**\n * Routes inbound events to agent ids. Defaults to `defaultStrategy`;\n * callers override per-bot to preserve legacy keys (telegram-pro keeps\n * the `tg-pro-` prefix; new bots use the default `telegram-` prefix).\n *\n * @public\n */\nexport class SessionRouter {\n constructor(private readonly strategy: AgentIdStrategy = defaultStrategy) {}\n\n resolveAgentId(event: GatewayMessageEvent): string {\n return this.strategy(event);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapter/base.ts","../src/delivery/router.ts","../src/errors/config-error.ts","../src/hooks/executor.ts","../src/runner/gateway-runner.ts","../src/session/router.ts","../src/text/chunk.ts"],"names":["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,QA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AAS,CAAA;AAC9C,EAAA,OAAO,SAAS,KAAK,CAAA;AACvB;AAsBO,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.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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "Multi-platform messaging gateway core for @theokit/sdk — transport-agnostic primitives (BasePlatformAdapter, MessageEvent, SessionRouter, DeliveryRouter, GatewayRunner, hooks). Inspired by hermes-agent/gateway. ADRs D170-D181.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|