@kadaliao/dsh-bots 0.3.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,893 @@
1
+ /**
2
+ * Chat channels: people message the bot team from a chat app (Telegram,
3
+ * Discord, …) and get the bots' replies back in that chat.
4
+ *
5
+ * A channel is an app on a bot (`kind: 'channel'` in the catalog) holding a
6
+ * chat bot token. For each one the Host runs a connector,
7
+ * `lib/channels/<kind>.mjs`, which is transport only. This module decides the
8
+ * rest:
9
+ *
10
+ * - who may talk to the team: only people paired with a one-time code from
11
+ * the panel; everyone else is ignored (at most one "this bot is private"
12
+ * note per chat per day);
13
+ * - which bot a message is for: the bot owning the channel, or the one named
14
+ * by a leading `@handle`;
15
+ * - where a bot's replies go: back to the chat its latest human input came
16
+ * from, including the dispatcher's report after teammates answer by DM; a
17
+ * message typed in the panel takes the conversation back to the panel.
18
+ *
19
+ * A connector gets the app's field values (`values`; `token` is its first
20
+ * secret) and reports messages as {chatId, userId, userName, text, isDirect,
21
+ * mentioned, messageId, order?, chatTitle?, source?}. Optional module exports:
22
+ * `TEXT_LIMIT`, `MARKDOWN` (true when the chat app renders Markdown replies)
23
+ * and `links({account, code, values})` → {link?, invite?} for the panel.
24
+ *
25
+ * @module @kadaliao/dsh-bots/lib/channels
26
+ */
27
+
28
+ import { createHash, randomInt } from 'node:crypto';
29
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
30
+ import { dirname } from 'node:path';
31
+
32
+ /** Connector modules by channel kind, loaded on first use. */
33
+ const CONNECTORS = {
34
+ telegram: () => import('./channels/telegram.mjs'),
35
+ discord: () => import('./channels/discord.mjs'),
36
+ feishu: () => import('./channels/feishu.mjs'),
37
+ slack: () => import('./channels/slack.mjs'),
38
+ };
39
+ export const CHANNEL_KINDS = Object.keys(CONNECTORS);
40
+ export const CHANNEL_LABELS = { telegram: 'Telegram', discord: 'Discord', feishu: 'Feishu', slack: 'Slack' };
41
+ /** Chat apps that render Markdown themselves; the rest get replies as plain text. */
42
+ const RENDERS_MARKDOWN = new Set(['discord']);
43
+
44
+ /** What the page sees in place of a stored token. Saving it back keeps the stored value. */
45
+ export const SECRET_MASK = '••••••••';
46
+ /** How long a pairing code works. */
47
+ export const CODE_TTL_MS = 10 * 60_000;
48
+ export const CODE_LENGTH = 6;
49
+ /** No 0/O, 1/I/L: a code read off a screen and typed on a phone. */
50
+ const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
51
+ /** Wrong codes one person may try against one code. */
52
+ const MAX_TRIES_PER_PERSON = 5;
53
+ /** Wrong codes in all before the code stops working. */
54
+ const MAX_FAILS_PER_CODE = 20;
55
+ /** One "this bot is private" note per chat per this long. */
56
+ const NOTICE_EVERY_MS = 24 * 3600_000;
57
+ const TYPING_EVERY_MS = 5000;
58
+ const TYPING_MAX_MS = 10 * 60_000;
59
+ /** A delivered channel message not seen in its conversation by then is forgotten. */
60
+ const PENDING_TTL_MS = 30 * 60_000;
61
+
62
+ /** Load the connector module of `kind`. */
63
+ export async function loadConnector(kind) {
64
+ const load = CONNECTORS[kind];
65
+ if (!load) throw new Error(`no connector for "${kind}"`);
66
+ return load();
67
+ }
68
+
69
+ // --- apps --------------------------------------------------------------------------
70
+
71
+ /** The catalog entry of a channel app, or null for any other app. */
72
+ export function channelEntry(app, entries) {
73
+ const e = (entries ?? []).find((x) => x.id === app?.template);
74
+ return e && e.kind === 'channel' ? e : null;
75
+ }
76
+
77
+ /** The token of a channel app: its first secret field. */
78
+ export function tokenOf(app, entry) {
79
+ const f = (entry?.fields ?? []).find((x) => x.kind === 'secret');
80
+ const v = f ? app?.values?.[f.key] : '';
81
+ return typeof v === 'string' ? v.trim() : '';
82
+ }
83
+
84
+ /** All non-empty field values of a channel app, and its secrets (for redaction). */
85
+ export function credentialsOf(app, entry) {
86
+ const values = {};
87
+ const secrets = [];
88
+ for (const f of entry?.fields ?? []) {
89
+ const v = app?.values?.[f.key];
90
+ if (typeof v !== 'string' || v.trim() === '') continue;
91
+ values[f.key] = v.trim();
92
+ if (f.kind === 'secret') secrets.push(v.trim());
93
+ }
94
+ return { values, secrets };
95
+ }
96
+
97
+ /** Why a channel app cannot connect (a required field is empty), or ''. */
98
+ export function channelIssue(app, entry) {
99
+ const missing = (entry?.fields ?? []).filter((f) => f.required && String(app?.values?.[f.key] ?? '').trim() === '').map((f) => f.label.en);
100
+ return missing.length ? `${entry.name.en} needs: ${missing.join(', ')}` : '';
101
+ }
102
+
103
+ /** A bot as the page may see it: channel tokens masked. */
104
+ export function maskBot(bot, entries) {
105
+ if (!bot || !Array.isArray(bot.apps)) return bot;
106
+ let changed = false;
107
+ const apps = bot.apps.map((app) => {
108
+ const entry = channelEntry(app, entries);
109
+ if (!entry) return app;
110
+ const values = { ...(app.values ?? {}) };
111
+ for (const f of entry.fields ?? []) {
112
+ if (f.kind === 'secret' && String(values[f.key] ?? '') !== '') {
113
+ values[f.key] = SECRET_MASK;
114
+ changed = true;
115
+ }
116
+ }
117
+ return { ...app, values };
118
+ });
119
+ return changed ? { ...bot, apps } : bot;
120
+ }
121
+
122
+ /** Apps posted by the page: a masked token keeps the stored one of the same app. */
123
+ export function unmaskApps(apps, prevApps, entries) {
124
+ if (!Array.isArray(apps)) return apps;
125
+ return apps.map((app) => {
126
+ const entry = channelEntry(app, entries);
127
+ if (!entry || !app?.values) return app;
128
+ const prev = (prevApps ?? []).find((p) => p.id === app.id);
129
+ const values = { ...app.values };
130
+ for (const f of entry.fields ?? []) {
131
+ if (f.kind !== 'secret' || values[f.key] !== SECRET_MASK) continue;
132
+ if (prev?.values?.[f.key]) values[f.key] = prev.values[f.key];
133
+ else delete values[f.key];
134
+ }
135
+ return { ...app, values };
136
+ });
137
+ }
138
+
139
+ // --- text ----------------------------------------------------------------------------
140
+
141
+ /** Remove secrets from text bound for a log, an error or the page. */
142
+ export function redact(text, secrets = []) {
143
+ let s = String(text ?? '');
144
+ for (const secret of secrets) if (typeof secret === 'string' && secret.length >= 6) s = s.split(secret).join('<token>');
145
+ return s
146
+ .replace(/bot\d{4,}:[A-Za-z0-9_-]{20,}/g, 'bot<token>')
147
+ .replace(/\b\d{4,}:[A-Za-z0-9_-]{30,}\b/g, '<token>')
148
+ .replace(/\b[A-Za-z0-9_-]{23,28}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27,}\b/g, '<token>')
149
+ .replace(/\b(?:xox[a-z]|xapp|xoxe)(?:\.xox[a-z])?-[A-Za-z0-9-]{6,}/g, '<token>');
150
+ }
151
+
152
+ /**
153
+ * Split text into parts of at most `limit` UTF-16 units, at a blank line, a
154
+ * line break or a space when one is near, never inside a surrogate pair.
155
+ */
156
+ export function splitText(text, limit) {
157
+ const max = Math.max(16, Math.floor(Number(limit)) || 4096);
158
+ let rest = String(text ?? '').trim();
159
+ const parts = [];
160
+ while (rest.length > max) {
161
+ let cut = rest.lastIndexOf('\n\n', max);
162
+ if (cut < max * 0.5) cut = rest.lastIndexOf('\n', max);
163
+ if (cut < max * 0.5) cut = rest.lastIndexOf(' ', max);
164
+ if (cut < max * 0.5) cut = max;
165
+ const c = rest.charCodeAt(cut - 1);
166
+ if (c >= 0xd800 && c <= 0xdbff) cut -= 1;
167
+ parts.push(rest.slice(0, cut).trimEnd());
168
+ rest = rest.slice(cut).replace(/^(\n+| )/, '');
169
+ }
170
+ if (rest) parts.push(rest);
171
+ return parts.filter((p) => p !== '');
172
+ }
173
+
174
+ /** Markdown a model writes, as plain chat text: no emphasis markers, fences or heading hashes. */
175
+ export function toPlainText(md) {
176
+ const out = [];
177
+ let code = false;
178
+ for (const line of String(md ?? '').split('\n')) {
179
+ if (/^\s*(```|~~~)/.test(line)) {
180
+ code = !code;
181
+ continue;
182
+ }
183
+ if (code) {
184
+ out.push(line);
185
+ continue;
186
+ }
187
+ if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
188
+ out.push('');
189
+ continue;
190
+ }
191
+ out.push(
192
+ line
193
+ .replace(/^(\s*)#{1,6}\s+/, '$1')
194
+ .replace(/^(\s*)[-*+]\s+/, '$1• ')
195
+ .replace(/\*\*(?=\S)([^*\n]*?\S)\*\*/g, '$1')
196
+ .replace(/__(?=\S)([^_\n]*?\S)__/g, '$1')
197
+ .replace(/!?\[([^\]\n]+)\]\((\S+?)\)/g, (_, label, url) => (label === url ? url : `${label} (${url})`)),
198
+ );
199
+ }
200
+ return out.join('\n').replace(/\n{3,}/g, '\n\n').trim();
201
+ }
202
+
203
+ /** A fresh pairing code. */
204
+ export function newPairingCode(pick = randomInt) {
205
+ let code = '';
206
+ for (let i = 0; i < CODE_LENGTH; i += 1) code += CODE_ALPHABET[pick(CODE_ALPHABET.length)];
207
+ return code;
208
+ }
209
+
210
+ /** The code a message offers: `/start CODE` (a Telegram deep link) or the code alone. */
211
+ export function pairingCandidate(text) {
212
+ const t = String(text ?? '').trim();
213
+ const m = /^\/start(?:@\S+)?\s+([A-Za-z0-9]{4,12})$/i.exec(t) ?? /^([A-Za-z0-9]{6})$/.exec(t);
214
+ return m ? m[1].toUpperCase() : '';
215
+ }
216
+
217
+ /** `/start`, `/start@bot` or `/help` with nothing else. */
218
+ export function isGreeting(text) {
219
+ return /^\/(start|help)(@\S+)?$/i.test(String(text ?? '').trim());
220
+ }
221
+
222
+ /** The bot a message is for: the one named by a leading `@handle`, else `owner`. */
223
+ export function routeMessage(text, owner, roster) {
224
+ const t = String(text ?? '').trim();
225
+ const m = /^@([a-z0-9][a-z0-9-]{0,31})(?=$|[\s,,::.。!?!?;;])[\s,,::;;]*/i.exec(t);
226
+ if (m) {
227
+ const bot = (roster ?? []).find((b) => b.handle === m[1].toLowerCase());
228
+ if (bot) return { bot, text: t.slice(m[0].length).trim() };
229
+ }
230
+ return { bot: owner, text: t };
231
+ }
232
+
233
+ const cleanName = (s, max = 60) =>
234
+ String(s ?? '')
235
+ .replace(/[[\]\r\n]+/g, ' ')
236
+ .replace(/\s+/g, ' ')
237
+ .trim()
238
+ .slice(0, max);
239
+
240
+ /** The line a bot reads before a chat message: `[Telegram · Kada]`, with the group in a group. */
241
+ export function sourceHeader(kind, msg) {
242
+ const parts = [cleanName(msg?.source) || CHANNEL_LABELS[kind] || kind, cleanName(msg?.userName) || 'someone'];
243
+ if (!msg?.isDirect && cleanName(msg?.chatTitle)) parts.push(cleanName(msg.chatTitle));
244
+ return `[${parts.join(' · ')}]`;
245
+ }
246
+
247
+ const norm = (s) => String(s ?? '').replace(/\s+/g, ' ').trim();
248
+ const zhBot = (bot) => /[一-鿿]/.test(`${bot?.name ?? ''}${bot?.persona ?? ''}`);
249
+
250
+ /** What a newly paired person (or `/start`) reads. */
251
+ export function welcomeText(bot, roster, { paired = false } = {}) {
252
+ const others = (roster ?? []).filter((b) => b.id !== bot.id).slice(0, 6).map((b) => `@${b.handle}`);
253
+ if (zhBot(bot)) {
254
+ return [
255
+ `${paired ? '配对成功。' : ''}你在这里发的消息会交给 ${bot.name}(@${bot.handle})。`,
256
+ others.length ? `想直接找其他 Bot,就在开头写它的 @handle:${others.join('、')}。` : '',
257
+ ].filter(Boolean).join('');
258
+ }
259
+ return [
260
+ `${paired ? 'Paired. ' : ''}What you send here goes to ${bot.name} (@${bot.handle}).`,
261
+ others.length ? `To reach another bot directly, start with its @handle: ${others.join(', ')}.` : '',
262
+ ].filter(Boolean).join(' ');
263
+ }
264
+ export const PRIVATE_TEXT = 'This bot is private. / 这是私人 Bot,不对外开放。';
265
+
266
+ // --- hint for the panel ----------------------------------------------------------------
267
+
268
+ /** A short code the panel words in its own language, from a connector's error text. */
269
+ export function hintOf(detail) {
270
+ const d = String(detail ?? '');
271
+ if (/4014|disallowed intent|message content intent/i.test(d)) return 'intent';
272
+ if (/\b401\b|unauthori[sz]ed|4004|invalid token|token was rejected|rejected the (bot )?token/i.test(d)) return 'token';
273
+ if (/\b409\b|conflict|another program/i.test(d)) return 'conflict';
274
+ return '';
275
+ }
276
+
277
+ // --- the channel hub ---------------------------------------------------------------------
278
+
279
+ /**
280
+ * Every channel of every bot: connectors, pairing, routing and reply targets.
281
+ *
282
+ * @param {{
283
+ * file: string, // channels.json: paired people and options per channel
284
+ * bots: () => object[], // the roster
285
+ * entries: () => object[], // the app catalog
286
+ * deliver: (bot: object, msg: {header: string, body: string}) => Promise<string>, // hand a prompt to a bot; resolves to its session id
287
+ * running?: (sessionId: string) => boolean, // whether that conversation is working
288
+ * loadConnector?: (kind: string) => Promise<{createConnector: Function, TEXT_LIMIT?: number}>,
289
+ * log?: (line: string) => void,
290
+ * now?: () => number,
291
+ * random?: (n: number) => number,
292
+ * typingEveryMs?: number,
293
+ * retryMs?: number,
294
+ * }} deps
295
+ */
296
+ export function createChannels(deps) {
297
+ const now = deps.now ?? Date.now;
298
+ const log = (line) => {
299
+ try {
300
+ deps.log?.(line);
301
+ } catch {
302
+ // Logging is a convenience.
303
+ }
304
+ };
305
+ const load = deps.loadConnector ?? loadConnector;
306
+ const typingEvery = deps.typingEveryMs ?? TYPING_EVERY_MS;
307
+ const retryBase = deps.retryMs ?? 15_000;
308
+ const running = deps.running ?? (() => false);
309
+
310
+ // Persistent: {channels: {[key]: {paired: Person[], scheduleReplies: boolean, account?: {id, username}}}}
311
+ let data = { version: 1, channels: {} };
312
+ try {
313
+ const parsed = JSON.parse(readFileSync(deps.file, 'utf8'));
314
+ if (parsed && typeof parsed.channels === 'object' && parsed.channels) data = { version: 1, channels: parsed.channels };
315
+ } catch {
316
+ // First run.
317
+ }
318
+ const save = () => {
319
+ try {
320
+ mkdirSync(dirname(deps.file), { recursive: true });
321
+ const tmp = `${deps.file}.tmp`;
322
+ writeFileSync(tmp, JSON.stringify(data, null, 2), { encoding: 'utf8', mode: 0o600 });
323
+ renameSync(tmp, deps.file);
324
+ } catch (error) {
325
+ log(`channels: could not save pairings: ${error?.message ?? error}`);
326
+ }
327
+ };
328
+ const recordOf = (key) => {
329
+ const r = (data.channels[key] ??= {});
330
+ if (!Array.isArray(r.paired)) r.paired = [];
331
+ if (typeof r.scheduleReplies !== 'boolean') r.scheduleReplies = true;
332
+ return r;
333
+ };
334
+
335
+ /** key → running connector record */
336
+ const live = new Map();
337
+ /** key → {code, expiresAt, fails} */
338
+ const codes = new Map();
339
+ /** `${key}|${userId}` → {n, since} */
340
+ const tries = new Map();
341
+ /** `${key}|${chatId}` → time of the last "private" note */
342
+ const notices = new Map();
343
+ /** key → {count, lastName, lastAt} */
344
+ const ignored = new Map();
345
+ /** botId → [{text, origin, at}] channel messages handed to a bot, not yet seen in its conversation */
346
+ const pending = new Map();
347
+ /** sessionId → where its replies go */
348
+ const targets = new Map();
349
+ /** sessionId → {timer, key, chatId, claimed} */
350
+ const typing = new Map();
351
+ /** `${key}|${chatId}` → the tail of its send queue, so parts arrive in order */
352
+ const queues = new Map();
353
+ let disposed = false;
354
+
355
+ const keyOf = (botId, appId) => `${botId}/${appId}`;
356
+ const sig = (kind, token) => `${kind}:${createHash('sha256').update(token).digest('hex').slice(0, 16)}`;
357
+
358
+ /** The channels that should run now, from the roster. */
359
+ function wanted() {
360
+ const entries = deps.entries();
361
+ const out = [];
362
+ const byToken = new Map();
363
+ for (const bot of deps.bots()) {
364
+ for (const app of bot.apps ?? []) {
365
+ const entry = channelEntry(app, entries);
366
+ if (!entry || app.enabled === false) continue;
367
+ const token = tokenOf(app, entry);
368
+ if (!token || channelIssue(app, entry)) continue;
369
+ const kind = entry.channel ?? entry.id;
370
+ const { values, secrets } = credentialsOf(app, entry);
371
+ const s = sig(kind, token);
372
+ const first = byToken.get(s);
373
+ if (!first) byToken.set(s, bot);
374
+ const all = sig(kind, JSON.stringify(Object.entries(values).sort()));
375
+ out.push({ key: keyOf(bot.id, app.id), botId: bot.id, appId: app.id, kind, token, values, secrets, sig: first ? `${all}:dup` : all, duplicateOf: first ?? null });
376
+ }
377
+ }
378
+ return out;
379
+ }
380
+
381
+ /** Start, stop and restart connectors to match the roster. Cheap; call it on every change. */
382
+ function sync() {
383
+ if (disposed) return;
384
+ const want = wanted();
385
+ for (const [key, rec] of [...live]) {
386
+ const w = want.find((x) => x.key === key);
387
+ if (!w || w.sig !== rec.sig) {
388
+ live.delete(key);
389
+ void stopRecord(rec);
390
+ }
391
+ }
392
+ for (const w of want) if (!live.has(w.key)) startRecord(w);
393
+ // Pairings of a channel app that no longer exists go with it.
394
+ const entries = deps.entries();
395
+ const exists = new Set();
396
+ for (const bot of deps.bots()) for (const app of bot.apps ?? []) if (channelEntry(app, entries)) exists.add(keyOf(bot.id, app.id));
397
+ let pruned = false;
398
+ for (const key of Object.keys(data.channels)) {
399
+ if (!exists.has(key)) {
400
+ delete data.channels[key];
401
+ codes.delete(key);
402
+ ignored.delete(key);
403
+ pruned = true;
404
+ }
405
+ }
406
+ if (pruned) save();
407
+ }
408
+
409
+ function setStatus(rec, s) {
410
+ const detail = s?.detail ? redact(String(s.detail), rec.secrets).slice(0, 400) : '';
411
+ const hint = s?.hint ?? (s?.state === 'error' ? hintOf(detail) : '');
412
+ rec.status = { state: s?.state ?? 'error', ...(detail ? { detail } : {}), ...(hint ? { hint } : {}), ...(s?.fatal ? { fatal: true } : {}), at: now() };
413
+ }
414
+
415
+ function startRecord(w) {
416
+ const rec = { ...w, conn: null, gen: null, limit: 2000, status: { state: 'connecting', at: now() }, account: null, retries: 0, retryTimer: null };
417
+ live.set(w.key, rec);
418
+ if (w.duplicateOf) {
419
+ setStatus(rec, { state: 'error', detail: `This token is already connected on @${w.duplicateOf.handle}; one token can run in one place.`, hint: 'duplicate' });
420
+ return;
421
+ }
422
+ void connect(rec);
423
+ }
424
+
425
+ async function connect(rec) {
426
+ const gen = {};
427
+ rec.gen = gen;
428
+ const current = () => !disposed && live.get(rec.key) === rec && rec.gen === gen;
429
+ setStatus(rec, { state: 'connecting' });
430
+ let mod;
431
+ try {
432
+ mod = await load(rec.kind);
433
+ } catch (error) {
434
+ if (current()) setStatus(rec, { state: 'error', detail: `${CHANNEL_LABELS[rec.kind] ?? rec.kind} support could not load: ${error?.message ?? error}`, fatal: true });
435
+ return;
436
+ }
437
+ if (!current()) return;
438
+ rec.limit = Number(mod.TEXT_LIMIT) || 2000;
439
+ rec.mod = mod;
440
+ let conn;
441
+ try {
442
+ conn = mod.createConnector({
443
+ token: rec.token,
444
+ values: { ...rec.values },
445
+ onMessage: (msg) => {
446
+ if (current()) void inbound(rec, msg).catch((error) => log(`channels: ${rec.kind} message: ${redact(error?.message ?? error, rec.secrets)}`));
447
+ },
448
+ onStatus: (s) => {
449
+ if (current() && s && s.state !== 'stopped') setStatus(rec, s);
450
+ },
451
+ log: (line) => log(`channels: ${rec.kind}: ${redact(line, rec.secrets)}`),
452
+ });
453
+ } catch (error) {
454
+ if (current()) setStatus(rec, { state: 'error', detail: error?.message ?? String(error), fatal: true });
455
+ return;
456
+ }
457
+ rec.conn = conn;
458
+ try {
459
+ const account = await conn.start();
460
+ if (!current()) {
461
+ await Promise.resolve(conn.stop()).catch(() => {});
462
+ return;
463
+ }
464
+ rec.account = { id: String(account?.id ?? ''), username: String(account?.username ?? ''), name: String(account?.name ?? '') };
465
+ rec.retries = 0;
466
+ setStatus(rec, { state: 'connected' });
467
+ const record = recordOf(rec.key);
468
+ if (record.account?.id && record.account.id !== rec.account.id) {
469
+ // Another chat bot behind this app: chats with the old one are not chats with this one.
470
+ for (const p of record.paired) delete p.chatId;
471
+ delete record.seen;
472
+ }
473
+ record.account = { id: rec.account.id, username: rec.account.username };
474
+ save();
475
+ if (record.paired.length === 0 && !activeCode(rec.key)) issueCode(rec.key);
476
+ } catch (error) {
477
+ if (!current()) return;
478
+ const message = redact(error?.message ?? String(error), rec.secrets);
479
+ const fatal = error?.fatal === true || rec.status.fatal === true || hintOf(message) === 'token';
480
+ // The connector's own error status, when it gave one, words the problem best.
481
+ const detail = rec.status.state === 'error' && rec.status.detail ? rec.status.detail : message;
482
+ setStatus(rec, { state: 'error', detail, ...(rec.status.hint ? { hint: rec.status.hint } : {}), fatal });
483
+ rec.conn = null;
484
+ await Promise.resolve(conn.stop()).catch(() => {});
485
+ if (!fatal && current()) {
486
+ const wait = Math.min(300_000, retryBase * 2 ** Math.min(rec.retries, 5));
487
+ rec.retries += 1;
488
+ rec.retryTimer = setTimeout(() => {
489
+ if (current()) void connect(rec);
490
+ }, wait);
491
+ rec.retryTimer.unref?.();
492
+ }
493
+ }
494
+ }
495
+
496
+ async function stopRecord(rec) {
497
+ rec.gen = null;
498
+ if (rec.retryTimer) clearTimeout(rec.retryTimer);
499
+ for (const [sessionId, loop] of [...typing]) if (loop.key === rec.key) stopTyping(sessionId);
500
+ const conn = rec.conn;
501
+ rec.conn = null;
502
+ if (conn) {
503
+ try {
504
+ await conn.stop();
505
+ } catch (error) {
506
+ log(`channels: stopping ${rec.kind}: ${redact(error?.message ?? error, rec.secrets)}`);
507
+ }
508
+ }
509
+ }
510
+
511
+ // --- pairing -----------------------------------------------------------------------
512
+
513
+ function activeCode(key) {
514
+ const c = codes.get(key);
515
+ if (c && c.expiresAt > now()) return c;
516
+ if (c) codes.delete(key);
517
+ return null;
518
+ }
519
+ function issueCode(key) {
520
+ const c = { code: newPairingCode(deps.random), expiresAt: now() + CODE_TTL_MS, fails: 0 };
521
+ codes.set(key, c);
522
+ for (const k of [...tries.keys()]) if (k.startsWith(`${key}|`)) tries.delete(k);
523
+ return c;
524
+ }
525
+ /** Whether this person may still try a code; counts a wrong one. */
526
+ function wrongCode(key, userId, code) {
527
+ const k = `${key}|${userId}`;
528
+ const t = tries.get(k);
529
+ const n = t && now() - t.since < CODE_TTL_MS ? t.n + 1 : 1;
530
+ tries.set(k, { n, since: t && n > 1 ? t.since : now() });
531
+ code.fails += 1;
532
+ if (code.fails >= MAX_FAILS_PER_CODE) codes.delete(key);
533
+ }
534
+ const tooManyTries = (key, userId) => {
535
+ const t = tries.get(`${key}|${userId}`);
536
+ return Boolean(t && now() - t.since < CODE_TTL_MS && t.n >= MAX_TRIES_PER_PERSON);
537
+ };
538
+
539
+ async function reply(rec, chatId, text) {
540
+ if (!rec.conn) return;
541
+ await enqueue(rec, String(chatId), async () => {
542
+ for (const part of splitText(text, rec.limit)) await rec.conn?.send(String(chatId), part);
543
+ });
544
+ }
545
+
546
+ function enqueue(rec, chatId, job) {
547
+ const k = `${rec.key}|${chatId}`;
548
+ const tail = (queues.get(k) ?? Promise.resolve()).then(job).catch((error) => log(`channels: sending to ${rec.kind}: ${redact(error?.message ?? error, rec.secrets)}`));
549
+ queues.set(k, tail);
550
+ void tail.then(() => {
551
+ if (queues.get(k) === tail) queues.delete(k);
552
+ });
553
+ return tail;
554
+ }
555
+
556
+ /** `a` ≤ `b` for decimal ids without leading zeros (Telegram message ids, Discord snowflakes, a connector's `order`). */
557
+ const notAfter = (a, b) => (a.length !== b.length ? a.length < b.length : a <= b);
558
+ /**
559
+ * Whether this message was handled before. A chat app hands a message out again
560
+ * when the connector stopped before confirming it (a restart, a new token, a
561
+ * resumed session); a task must not run twice. Ids rise within a chat, so the
562
+ * highest one handled per chat is enough, and it is kept across restarts.
563
+ */
564
+ function replayed(key, chatId, messageId) {
565
+ if (!/^\d{1,30}$/.test(messageId)) return false;
566
+ const record = recordOf(key);
567
+ const seen = (record.seen ??= {});
568
+ const last = seen[chatId];
569
+ if (last && notAfter(messageId, last)) return true;
570
+ delete seen[chatId];
571
+ seen[chatId] = messageId;
572
+ const chats = Object.keys(seen);
573
+ if (chats.length > 300) delete seen[chats[0]];
574
+ save();
575
+ return false;
576
+ }
577
+
578
+ /** One message from a connector. */
579
+ async function inbound(rec, msg) {
580
+ const owner = deps.bots().find((b) => b.id === rec.botId);
581
+ if (!owner || !msg) return;
582
+ const text = String(msg.text ?? '').trim();
583
+ const userId = String(msg.userId ?? '');
584
+ const chatId = String(msg.chatId ?? '');
585
+ if (!text || !userId || !chatId) return;
586
+ // In a group the bot only listens when it is addressed.
587
+ if (!msg.isDirect && !msg.mentioned) return;
588
+ if (replayed(rec.key, chatId, String(msg.order ?? msg.messageId ?? ''))) return;
589
+ const record = recordOf(rec.key);
590
+ const person = record.paired.find((p) => p.id === userId);
591
+ const candidate = pairingCandidate(text);
592
+ const code = activeCode(rec.key);
593
+
594
+ if (!person) {
595
+ if (msg.isDirect && candidate && code && !tooManyTries(rec.key, userId)) {
596
+ if (candidate === code.code) {
597
+ codes.delete(rec.key);
598
+ record.paired.push({ id: userId, name: cleanName(msg.userName) || userId, chatId, at: now() });
599
+ save();
600
+ log(`channels: ${rec.kind}: paired ${cleanName(msg.userName) || userId} with @${owner.handle}`);
601
+ await reply(rec, chatId, welcomeText(owner, deps.bots(), { paired: true }));
602
+ return;
603
+ }
604
+ wrongCode(rec.key, userId, code);
605
+ }
606
+ const seen = ignored.get(rec.key) ?? { count: 0 };
607
+ ignored.set(rec.key, { count: seen.count + 1, lastName: cleanName(msg.userName) || userId, lastAt: now() });
608
+ if (msg.isDirect) {
609
+ const k = `${rec.key}|${chatId}`;
610
+ const last = notices.get(k);
611
+ if (!last || now() - last >= NOTICE_EVERY_MS) {
612
+ notices.set(k, now());
613
+ await reply(rec, chatId, PRIVATE_TEXT);
614
+ }
615
+ }
616
+ return;
617
+ }
618
+
619
+ // A paired person: keep where to reach them privately, and their current name.
620
+ let dirty = false;
621
+ if (msg.isDirect && person.chatId !== chatId) {
622
+ person.chatId = chatId;
623
+ dirty = true;
624
+ }
625
+ const name = cleanName(msg.userName);
626
+ if (name && person.name !== name) {
627
+ person.name = name;
628
+ dirty = true;
629
+ }
630
+ if (dirty) save();
631
+ if (code && candidate === code.code) {
632
+ codes.delete(rec.key);
633
+ await reply(rec, chatId, welcomeText(owner, deps.bots(), { paired: true }));
634
+ return;
635
+ }
636
+ if (isGreeting(text) || /^\/start(@\S+)?\s/i.test(text)) {
637
+ await reply(rec, chatId, welcomeText(owner, deps.bots()));
638
+ return;
639
+ }
640
+ const routed = routeMessage(text, owner, deps.bots());
641
+ if (!routed.text) return;
642
+ const header = sourceHeader(rec.kind, msg);
643
+ const origin = {
644
+ key: rec.key,
645
+ kind: rec.kind,
646
+ chatId,
647
+ ...(msg.isDirect ? {} : { replyTo: String(msg.messageId ?? '') }),
648
+ who: name || person.name,
649
+ body: routed.text,
650
+ };
651
+ // Noted before the hand-over: the conversation may show the message before deliver returns.
652
+ const list = (pending.get(routed.bot.id) ?? []).filter((p) => now() - p.at < PENDING_TTL_MS);
653
+ const item = { text: `${header}\n${routed.text}`, origin, at: now() };
654
+ list.push(item);
655
+ pending.set(routed.bot.id, list);
656
+ let sessionId;
657
+ try {
658
+ sessionId = await deps.deliver(routed.bot, { header, body: routed.text });
659
+ } catch (error) {
660
+ const left = pending.get(routed.bot.id) ?? [];
661
+ if (left.includes(item)) left.splice(left.indexOf(item), 1);
662
+ log(`channels: could not hand a ${rec.kind} message to @${routed.bot.handle}: ${error?.message ?? error}`);
663
+ await reply(rec, chatId, `Could not reach ${routed.bot.name}: ${redact(error?.message ?? error, rec.secrets).slice(0, 200)}`);
664
+ return;
665
+ }
666
+ if (sessionId) startTyping(sessionId, rec.key, chatId);
667
+ }
668
+
669
+ // --- typing -------------------------------------------------------------------------
670
+
671
+ function startTyping(sessionId, key, chatId) {
672
+ stopTyping(sessionId);
673
+ const started = now();
674
+ const tick = () => {
675
+ const conn = live.get(key)?.conn;
676
+ if (!conn) return void stopTyping(sessionId);
677
+ Promise.resolve()
678
+ .then(() => conn.typing(chatId))
679
+ .catch(() => {});
680
+ };
681
+ const timer = setInterval(() => {
682
+ const elapsed = now() - started;
683
+ if (elapsed > TYPING_MAX_MS || (elapsed > typingEvery * 2 && !running(sessionId))) return void stopTyping(sessionId);
684
+ tick();
685
+ }, typingEvery);
686
+ timer.unref?.();
687
+ typing.set(sessionId, { timer, key, chatId, claimed: false });
688
+ tick();
689
+ }
690
+ function stopTyping(sessionId) {
691
+ const loop = typing.get(sessionId);
692
+ if (!loop) return;
693
+ clearInterval(loop.timer);
694
+ typing.delete(sessionId);
695
+ }
696
+
697
+ // --- reply targets --------------------------------------------------------------------
698
+
699
+ /** Where a scheduled run of `bot` reports: its channel's first paired person, privately. */
700
+ function scheduleTarget(bot) {
701
+ const entries = deps.entries();
702
+ for (const app of bot.apps ?? []) {
703
+ const entry = channelEntry(app, entries);
704
+ if (!entry || app.enabled === false) continue;
705
+ const key = keyOf(bot.id, app.id);
706
+ const record = data.channels[key];
707
+ if (!record || record.scheduleReplies === false) continue;
708
+ const person = (record.paired ?? []).find((p) => p.chatId);
709
+ if (person) return { key, kind: entry.channel ?? entry.id, chatId: person.chatId, who: person.name, origin: 'schedule' };
710
+ }
711
+ return null;
712
+ }
713
+
714
+ function claim(botId, text) {
715
+ const list = (pending.get(botId) ?? []).filter((p) => now() - p.at < PENDING_TTL_MS);
716
+ const i = list.findIndex((p) => norm(p.text) === norm(text));
717
+ if (i === -1) {
718
+ pending.set(botId, list);
719
+ return null;
720
+ }
721
+ const [hit] = list.splice(i, 1);
722
+ if (list.length) pending.set(botId, list);
723
+ else pending.delete(botId);
724
+ return hit.origin;
725
+ }
726
+
727
+ /** Links a connector module offers the panel (a deep link to pair, an invite). */
728
+ function linksOf(rec, account, code) {
729
+ if (typeof rec?.mod?.links !== 'function' || !account) return {};
730
+ try {
731
+ const l = rec.mod.links({ account, code: code?.code ?? null, values: { ...rec.values } }) ?? {};
732
+ return { ...(typeof l.link === 'string' && l.link ? { link: l.link } : {}), ...(typeof l.invite === 'string' && l.invite ? { invite: l.invite } : {}) };
733
+ } catch {
734
+ return {};
735
+ }
736
+ }
737
+
738
+ return {
739
+ sync,
740
+
741
+ /**
742
+ * A message entered `bot`'s conversation. A channel message makes that chat
743
+ * the reply target (and returns where it came from); any other user message
744
+ * (the panel) takes replies back to the panel. A scheduled run reports to
745
+ * the channel's first paired person when the channel allows it.
746
+ * @param {string} sessionId
747
+ * @param {object} bot
748
+ * @param {string} kind - the message source kind ('user', 'schedule', 'agent-message', …)
749
+ * @param {string} text - the message text
750
+ */
751
+ noteUserMessage(sessionId, bot, kind, text) {
752
+ if (!sessionId || !bot) return null;
753
+ if (kind === 'user') {
754
+ const origin = claim(bot.id, text);
755
+ if (origin) {
756
+ targets.set(sessionId, { key: origin.key, kind: origin.kind, chatId: origin.chatId, ...(origin.replyTo ? { replyTo: origin.replyTo } : {}), who: origin.who, origin: 'chat' });
757
+ const loop = typing.get(sessionId);
758
+ if (loop) loop.claimed = true;
759
+ return origin;
760
+ }
761
+ targets.delete(sessionId);
762
+ return null;
763
+ }
764
+ if (kind === 'schedule') {
765
+ const t = scheduleTarget(bot);
766
+ if (t) targets.set(sessionId, t);
767
+ else targets.delete(sessionId);
768
+ }
769
+ return null;
770
+ },
771
+
772
+ /**
773
+ * A user-facing reply of the conversation `sessionId`: sent to its chat when
774
+ * its latest human input came from one. Returns the target (or null) at once;
775
+ * sending continues in the background.
776
+ */
777
+ noteReply(sessionId, text) {
778
+ const target = targets.get(sessionId);
779
+ if (!target || !String(text ?? '').trim()) return null;
780
+ const rec = live.get(target.key);
781
+ stopTyping(sessionId);
782
+ if (!rec?.conn) {
783
+ log(`channels: a reply for ${target.kind} was not sent: the channel is not connected`);
784
+ return null;
785
+ }
786
+ const plain = rec.mod?.MARKDOWN === true || RENDERS_MARKDOWN.has(target.kind) ? String(text).trim() : toPlainText(text);
787
+ void enqueue(rec, target.chatId, async () => {
788
+ let first = true;
789
+ for (const part of splitText(plain, rec.limit)) {
790
+ if (!rec.conn) break;
791
+ // A chat app that threads replies (Slack) keeps every part in the thread; elsewhere only the first part quotes.
792
+ await rec.conn.send(target.chatId, part, target.replyTo && (first || rec.mod?.THREADS === true) ? { replyTo: target.replyTo } : undefined);
793
+ first = false;
794
+ }
795
+ });
796
+ return target;
797
+ },
798
+
799
+ /** A turn of `sessionId` ended: the typing indicator of the message it answered stops. */
800
+ noteTurnEnd(sessionId) {
801
+ if (typing.get(sessionId)?.claimed) stopTyping(sessionId);
802
+ },
803
+
804
+ /** Where `sessionId`'s replies go now, if to a chat. */
805
+ targetOf(sessionId) {
806
+ return targets.get(sessionId) ?? null;
807
+ },
808
+
809
+ /** What the panel shows of `bot`'s channels: {[appId]: ChannelView}. */
810
+ view(bot) {
811
+ const entries = deps.entries();
812
+ const out = {};
813
+ for (const app of bot?.apps ?? []) {
814
+ const entry = channelEntry(app, entries);
815
+ if (!entry) continue;
816
+ const key = keyOf(bot.id, app.id);
817
+ const kind = entry.channel ?? entry.id;
818
+ const rec = live.get(key);
819
+ const record = data.channels[key] ?? { paired: [], scheduleReplies: true };
820
+ const code = activeCode(key);
821
+ const state = app.enabled === false ? 'off' : !tokenOf(app, entry) || channelIssue(app, entry) ? 'missing' : rec?.status?.state ?? 'connecting';
822
+ const account = rec?.account ?? (record.account?.username ? { id: record.account.id, username: record.account.username, name: '' } : null);
823
+ out[app.id] = {
824
+ kind,
825
+ state,
826
+ ...(state === 'error' || state === 'connecting' ? { ...(rec?.status?.detail ? { detail: rec.status.detail } : {}), ...(rec?.status?.hint ? { hint: rec.status.hint } : {}), ...(rec?.status?.fatal ? { fatal: true } : {}) } : {}),
827
+ account: account ? { username: account.username, name: account.name ?? '' } : null,
828
+ paired: (record.paired ?? []).map((p) => ({ id: p.id, name: p.name, at: p.at, direct: Boolean(p.chatId) })),
829
+ code: code ? { code: code.code, expiresAt: code.expiresAt } : null,
830
+ link: code && kind === 'telegram' && account?.username ? `https://t.me/${account.username}?start=${code.code}` : null,
831
+ invite: kind === 'discord' && account?.id ? `https://discord.com/oauth2/authorize?client_id=${account.id}&scope=bot&permissions=68608` : null,
832
+ ...linksOf(rec, account, code),
833
+ scheduleReplies: record.scheduleReplies !== false,
834
+ ignored: ignored.get(key) ?? { count: 0 },
835
+ };
836
+ }
837
+ return out;
838
+ },
839
+
840
+ /** A new pairing code for a channel (the old one stops working). */
841
+ newCode(botId, appId) {
842
+ const key = keyOf(botId, appId);
843
+ if (!deps.bots().some((b) => b.id === botId && (b.apps ?? []).some((a) => a.id === appId && channelEntry(a, deps.entries())))) throw new Error('no such chat channel');
844
+ const c = issueCode(key);
845
+ return { code: c.code, expiresAt: c.expiresAt };
846
+ },
847
+
848
+ /** Forget a paired person: their next message is ignored like a stranger's. */
849
+ unpair(botId, appId, userId) {
850
+ const record = data.channels[keyOf(botId, appId)];
851
+ if (!record) return false;
852
+ const before = record.paired.length;
853
+ record.paired = record.paired.filter((p) => p.id !== String(userId));
854
+ if (record.paired.length === before) return false;
855
+ save();
856
+ for (const [sessionId, t] of [...targets]) if (t.key === keyOf(botId, appId)) targets.delete(sessionId);
857
+ return true;
858
+ },
859
+
860
+ /** Channel options: `scheduleReplies` (scheduled runs report to the first paired person). */
861
+ setOptions(botId, appId, options) {
862
+ if (!deps.bots().some((b) => b.id === botId && (b.apps ?? []).some((a) => a.id === appId && channelEntry(a, deps.entries())))) throw new Error('no such chat channel');
863
+ const record = recordOf(keyOf(botId, appId));
864
+ if (typeof options?.scheduleReplies === 'boolean') record.scheduleReplies = options.scheduleReplies;
865
+ save();
866
+ return { scheduleReplies: record.scheduleReplies };
867
+ },
868
+
869
+ /** Drop and reconnect one channel (after fixing a setting in the chat app's own console). */
870
+ reconnect(botId, appId) {
871
+ const key = keyOf(botId, appId);
872
+ const rec = live.get(key);
873
+ if (rec) {
874
+ live.delete(key);
875
+ void stopRecord(rec);
876
+ }
877
+ sync();
878
+ return live.has(key);
879
+ },
880
+
881
+ /** Stop every connector; nothing restarts afterwards. */
882
+ async stopAll() {
883
+ disposed = true;
884
+ for (const sessionId of [...typing.keys()]) stopTyping(sessionId);
885
+ const recs = [...live.values()];
886
+ live.clear();
887
+ await Promise.all(recs.map((rec) => stopRecord(rec)));
888
+ },
889
+
890
+ /** For tests: the live record of a channel. */
891
+ _live: live,
892
+ };
893
+ }