@kadaliao/dsh-bots 0.7.1 → 0.8.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,407 @@
1
+ /**
2
+ * Threads: an outside conversation a request came from, and where replies go.
3
+ *
4
+ * A Thread is a Slack thread, a Feishu topic or reply chain, a Discord reply
5
+ * chain or thread channel, a Telegram topic or private chat, or a home
6
+ * conversation in the panel. Its key is `kind:appKey:chatId[:rootId]`
7
+ * (`appKey` is the channel's record key in channels.mjs, `botId/appId`); a
8
+ * message with no thread id of its own belongs to the whole-chat thread
9
+ * `kind:appKey:chatId`. A panel conversation is `panel:<sessionId>`. Inside a
10
+ * part, `%` and `:` are written `%25` and `%3A`, so any id survives the trip.
11
+ *
12
+ * This module decides, with no I/O:
13
+ *
14
+ * - where an inbound chat message goes (`routeInbound`): a leading `@handle`
15
+ * reaches that bot's home as in 0.7; otherwise the live tickets subscribed
16
+ * to the message's thread take it (and the Router hears of it without being
17
+ * woken); otherwise the Router (the channel owner's home) does;
18
+ * - where a conversation's plain replies go (`createOrigins`): each turn
19
+ * collects the threads its inputs came from (user messages, and the origin
20
+ * threads of the tickets whose reports arrived). One chat thread: replies go
21
+ * there. Only the panel, or nothing: the panel. More than one, including the
22
+ * panel plus one chat: the panel only, and the bot names a target with
23
+ * `bot_reply` (`resolve`).
24
+ *
25
+ * @module @kadaliao/dsh-bots/lib/threads
26
+ */
27
+
28
+ /** A turn's source threads are forgotten this long after its latest input, unless its session still runs. */
29
+ export const ORIGIN_TTL_MS = 30 * 60_000;
30
+
31
+ /** How a thread's kind reads in a label. */
32
+ export const KIND_LABELS = { telegram: 'Telegram', discord: 'Discord', feishu: 'Feishu', slack: 'Slack', panel: 'Panel' };
33
+
34
+ /** Kinds are short lowercase words, so they are never escaped. */
35
+ const KIND_RE = /^[a-z][a-z0-9-]{0,31}$/;
36
+ const PANEL = 'panel';
37
+
38
+ const part = (v) => (v == null ? '' : String(v).trim());
39
+ const esc = (s) => s.replace(/%/g, '%25').replace(/:/g, '%3A');
40
+ const unesc = (s) => s.replace(/%(25|3A)/gi, (_, c) => (c === '25' ? '%' : ':'));
41
+
42
+ // --- keys ------------------------------------------------------------------------------
43
+
44
+ /**
45
+ * The key of the thread a chat message belongs to.
46
+ * @param {string} kind - 'telegram' | 'discord' | 'feishu' | 'slack' (… or 'panel', keyed by `msg.sessionId`)
47
+ * @param {string} appKey - the channel's record key (`botId/appId`)
48
+ * @param {{chatId: string|number, threadId?: string|number|null, rootId?: string|number|null, sessionId?: string}} msg
49
+ * `threadId` as a connector reports it (`rootId` is accepted too, so a parsed key rebuilds);
50
+ * none means the whole chat
51
+ * @returns {string|null} null when the kind, app or chat is missing
52
+ */
53
+ export function threadKey(kind, appKey, msg = {}) {
54
+ const k = part(kind);
55
+ if (k === PANEL) return panelThreadKey(msg?.sessionId ?? msg?.chatId);
56
+ if (!KIND_RE.test(k)) return null;
57
+ const app = part(appKey);
58
+ const chat = part(msg?.chatId);
59
+ if (!app || !chat) return null;
60
+ const root = part(msg?.threadId ?? msg?.rootId);
61
+ return [k, esc(app), esc(chat), ...(root ? [esc(root)] : [])].join(':');
62
+ }
63
+
64
+ /** The thread of a home conversation in the panel: replies to it stay in the panel. */
65
+ export function panelThreadKey(sessionId) {
66
+ const s = part(sessionId);
67
+ return s ? `${PANEL}:${esc(s)}` : null;
68
+ }
69
+
70
+ /**
71
+ * A thread key taken apart.
72
+ * @returns {{kind: string, appKey: string, chatId: string, rootId?: string} | {kind: 'panel', sessionId: string} | null}
73
+ */
74
+ export function parseThreadKey(key) {
75
+ if (typeof key !== 'string' || key === '') return null;
76
+ const parts = key.split(':');
77
+ const kind = parts[0];
78
+ if (!KIND_RE.test(kind)) return null;
79
+ if (kind === PANEL) {
80
+ if (parts.length !== 2 || parts[1] === '') return null;
81
+ return { kind: PANEL, sessionId: unesc(parts[1]) };
82
+ }
83
+ if (parts.length < 3 || parts.length > 4 || parts.slice(1).some((p) => p === '')) return null;
84
+ const [, app, chat, root] = parts;
85
+ return { kind, appKey: unesc(app), chatId: unesc(chat), ...(root !== undefined ? { rootId: unesc(root) } : {}) };
86
+ }
87
+
88
+ /**
89
+ * The canonical key of whatever names a thread: a key, a parsed key, an
90
+ * origin (`threadKey`, or kind/appKey/chatId/rootId with `key` as the 0.7
91
+ * channel key) or a stored Thread record (`key` is the thread key there).
92
+ * @returns {string|null}
93
+ */
94
+ export function toThreadKey(ref) {
95
+ if (typeof ref === 'string') {
96
+ const p = parseThreadKey(ref);
97
+ return p ? (p.kind === PANEL ? panelThreadKey(p.sessionId) : threadKey(p.kind, p.appKey, p)) : null;
98
+ }
99
+ if (!ref || typeof ref !== 'object') return null;
100
+ if (typeof ref.threadKey === 'string') return toThreadKey(ref.threadKey);
101
+ if (ref.kind === PANEL) return panelThreadKey(ref.sessionId ?? ref.chatId);
102
+ if (ref.appKey == null && typeof ref.key === 'string' && parseThreadKey(ref.key)) return toThreadKey(ref.key);
103
+ return threadKey(ref.kind, ref.appKey ?? ref.key, ref);
104
+ }
105
+
106
+ /** Whether two references (keys, origins, Thread records) name the same thread. */
107
+ export function sameThread(a, b) {
108
+ const ka = toThreadKey(a);
109
+ return ka !== null && ka === toThreadKey(b);
110
+ }
111
+
112
+ /** Whether a reference names a panel conversation. */
113
+ export function isPanelThread(ref) {
114
+ const k = toThreadKey(ref);
115
+ return k !== null && k.startsWith(`${PANEL}:`);
116
+ }
117
+
118
+ const cleanName = (s, max = 60) =>
119
+ String(s ?? '')
120
+ .replace(/[[\]\r\n]+/g, ' ')
121
+ .replace(/\s+/g, ' ')
122
+ .trim()
123
+ .slice(0, max);
124
+
125
+ /**
126
+ * How a thread reads to a person or a bot: `Slack · Acme #general · thread`,
127
+ * `Telegram · Kada`, `Panel`. The chat is its title when known (a group),
128
+ * else who wrote (a private chat), else its id.
129
+ * @param {string | {threadKey?: string, kind?: string, source?: string, chatTitle?: string, who?: string,
130
+ * chatId?: string, rootId?: string, threadTitle?: string}} meta - a key, an origin or a Thread record
131
+ */
132
+ export function threadLabel(meta) {
133
+ const parsed = typeof meta === 'string' ? parseThreadKey(meta) : parseThreadKey(meta?.threadKey ?? (meta?.appKey == null ? meta?.key : undefined));
134
+ const m = { ...(parsed ?? {}), ...(meta && typeof meta === 'object' ? meta : {}) };
135
+ const kind = part(m.kind);
136
+ const parts = [cleanName(m.source) || KIND_LABELS[kind] || cleanName(kind) || 'Chat'];
137
+ const chat = cleanName(m.chatTitle) || (kind === PANEL ? '' : cleanName(m.who) || cleanName(m.chatId));
138
+ if (chat) parts.push(chat);
139
+ if (kind !== PANEL && part(m.rootId)) parts.push(cleanName(m.threadTitle) || (kind === 'telegram' ? 'topic' : 'thread'));
140
+ return parts.join(' · ');
141
+ }
142
+
143
+ // --- inbound -----------------------------------------------------------------------------
144
+
145
+ /** A leading `@handle`: the same rule as `routeMessage` in channels.mjs (duplicated, as channels.mjs will import this module). */
146
+ const LEADING_HANDLE = /^@([a-z0-9][a-z0-9-]{0,31})(?=$|[\s,,::.。!?!?;;])[\s,,::;;]*/i;
147
+
148
+ /** The roster bot a message names with a leading `@handle`, and the text after it; null when it names none. */
149
+ export function addressedBot(text, roster) {
150
+ const t = String(text ?? '').trim();
151
+ const m = LEADING_HANDLE.exec(t);
152
+ if (!m) return null;
153
+ const bot = (roster ?? []).find((b) => b?.handle === m[1].toLowerCase());
154
+ return bot ? { bot, text: t.slice(m[0].length).trim() } : null;
155
+ }
156
+
157
+ /**
158
+ * Whether a subscribed ticket still takes its threads' messages: not
159
+ * archived and not stopped. A done ticket does (a follow-up reopens it), and
160
+ * so does a failed one (a person's answer may unblock it).
161
+ */
162
+ export function isLiveSubscriber(ticket) {
163
+ return Boolean(ticket) && !ticket.archivedAt && ticket.ended?.outcome !== 'stopped';
164
+ }
165
+
166
+ /**
167
+ * Whether an open ticket's last report is a question nobody answered yet
168
+ * (the `question` stage of `stageOf` in tickets.mjs).
169
+ */
170
+ export function awaitsAnswer(ticket) {
171
+ const t = ticket ?? {};
172
+ if (t.ended || t.archivedAt) return false;
173
+ const last = Array.isArray(t.reports) ? t.reports.at(-1) : undefined;
174
+ if (last?.status !== 'question') return false;
175
+ const ms = (v) => (Number.isFinite(Number(v)) ? Number(v) : Date.parse(v) || 0);
176
+ return Math.max(ms(t.lastHumanAt), ms(t.lastRequesterAt)) <= ms(last.at);
177
+ }
178
+
179
+ const sameBot = (a, b) => Boolean(a && b) && (a === b || (a.id != null && a.id === b.id));
180
+
181
+ /**
182
+ * Where an inbound chat message goes.
183
+ *
184
+ * 1. A leading `@handle` of a roster bot: that bot's home (`bot-home`), even on
185
+ * a subscribed thread. Naming the owner itself is `router` with
186
+ * `addressed: true`: the owner's home is the Router, and the person asked
187
+ * for it rather than the tickets.
188
+ * 2. Live tickets subscribed to the thread: `tickets`, and the Router gets a
189
+ * notice that does not wake it (`notifyRouter`). A thread that is a whole
190
+ * chat (a private chat, a group without threads) is where every new
191
+ * request arrives too, so there only a ticket waiting on an answer to its
192
+ * question takes the message, and only when it is the one such ticket
193
+ * (with two or more, nothing says which the message answers); anything
194
+ * else is the Router's to place.
195
+ * 3. Otherwise the owner's home: `router`.
196
+ *
197
+ * `text` is the message without the handle; an empty one is dropped by the
198
+ * caller, as in 0.7.
199
+ *
200
+ * @param {{text: string, threadKey?: string, mentionsHandle?: string}} msg - `mentionsHandle`: a roster
201
+ * handle the chat app's own mention markup resolved to; used only when the text has no leading handle
202
+ * @param {{subscribers?: object[] | ((threadKey: string) => object[]), owner: object, roster?: object[],
203
+ * live?: (ticket: object) => boolean}} ctx - `subscribers`: tickets (or a lookup by thread key); a ticket
204
+ * counts when `live` (default `isLiveSubscriber`) and its `threads` hold the message's thread
205
+ * @returns {{to: 'bot-home', bot: object, text: string, threadKey: string|null}
206
+ * | {to: 'tickets', tickets: object[], notifyRouter: true, router: object, text: string, threadKey: string}
207
+ * | {to: 'router', bot: object, text: string, threadKey: string|null, addressed?: true}}
208
+ */
209
+ export function routeInbound(msg, ctx = {}) {
210
+ const { owner = null, roster = [], subscribers, live = isLiveSubscriber } = ctx;
211
+ const text = String(msg?.text ?? '').trim();
212
+ const key = toThreadKey(msg?.threadKey);
213
+ let addressed = addressedBot(text, roster);
214
+ if (!addressed && msg?.mentionsHandle) {
215
+ const handle = part(msg.mentionsHandle).replace(/^@/, '').toLowerCase();
216
+ const bot = (roster ?? []).find((b) => b?.handle === handle);
217
+ if (bot) addressed = { bot, text };
218
+ }
219
+ if (addressed) {
220
+ if (sameBot(addressed.bot, owner)) return { to: 'router', bot: owner, text: addressed.text, threadKey: key, addressed: true };
221
+ return { to: 'bot-home', bot: addressed.bot, text: addressed.text, threadKey: key };
222
+ }
223
+ if (key) {
224
+ const list = typeof subscribers === 'function' ? subscribers(key) : subscribers;
225
+ const seen = new Set();
226
+ const tickets = [];
227
+ const parsed = parseThreadKey(key);
228
+ const wholeChat = Boolean(parsed) && parsed.kind !== PANEL && parsed.rootId === undefined;
229
+ for (const t of Array.isArray(list) ? list : []) {
230
+ if (!t || seen.has(t.id ?? t) || !live(t)) continue;
231
+ if (wholeChat && ctx.live === undefined && !awaitsAnswer(t)) continue;
232
+ if (!Array.isArray(t.threads) || !t.threads.some((k) => sameThread(k, key))) continue;
233
+ seen.add(t.id ?? t);
234
+ tickets.push(t);
235
+ }
236
+ // Two questions waiting on one whole chat: a bare reply cannot say which it answers; the Router places it.
237
+ if (wholeChat && ctx.live === undefined && tickets.length > 1) return { to: 'router', bot: owner, text, threadKey: key };
238
+ if (tickets.length) return { to: 'tickets', tickets, notifyRouter: true, router: owner, text, threadKey: key };
239
+ }
240
+ return { to: 'router', bot: owner, text, threadKey: key };
241
+ }
242
+
243
+ // --- a turn's source threads ----------------------------------------------------------------
244
+
245
+ /**
246
+ * An input's origin, keyed: identity fields come from the key; the rest
247
+ * (`replyTo`, `who`, `chatTitle`, …) from what the caller gave. `key` is the
248
+ * channel's record key as in 0.7's reply target (the same as `appKey`).
249
+ */
250
+ function originOf(key, given) {
251
+ const { tickets: _ticketsOfThread, threadKey: _given, ...rest } = given && typeof given === 'object' ? given : {};
252
+ const p = parseThreadKey(key);
253
+ const { rootId: _root, key: _key, appKey: _app, chatId: _chat, ...extra } = rest;
254
+ if (p.kind === PANEL) {
255
+ const { replyTo: _replyTo, ...panelExtra } = extra;
256
+ return { ...panelExtra, threadKey: key, kind: PANEL, sessionId: p.sessionId };
257
+ }
258
+ return { ...extra, threadKey: key, kind: p.kind, key: p.appKey, appKey: p.appKey, chatId: p.chatId, ...(p.rootId !== undefined ? { rootId: p.rootId } : {}) };
259
+ }
260
+
261
+ const copyOrigin = (o) => ({ ...o, ...(o.tickets ? { tickets: [...o.tickets] } : {}) });
262
+
263
+ /** `{thread: key}` or `{ticket: id}` from what `bot_reply` names: a key, `thread/<key>`, `ticket/<id>`, an id or an object. */
264
+ function refOf(ref) {
265
+ if (typeof ref === 'string') {
266
+ const r = ref.trim();
267
+ if (!r) return null;
268
+ if (r.startsWith('thread/')) return { thread: r.slice(7) };
269
+ if (r.startsWith('ticket/')) return r.length > 7 ? { ticket: r.slice(7) } : null;
270
+ return parseThreadKey(r) ? { thread: r } : { ticket: r };
271
+ }
272
+ if (!ref || typeof ref !== 'object') return null;
273
+ const thread = ref.thread ?? ref.threadKey;
274
+ if (thread != null && thread !== '') return { thread };
275
+ const ticket = part(ref.ticket ?? ref.ticketId);
276
+ return ticket ? { ticket } : null;
277
+ }
278
+
279
+ /**
280
+ * Per conversation, the threads this turn's inputs came from (plan §4.3).
281
+ *
282
+ * Rules for plain replies (`replyPlan`, `replyTarget`):
283
+ * - no input, or only panel inputs: `panel` (the text stays in the panel);
284
+ * - exactly one chat thread and no panel input: `thread`, sent there (0.7's behaviour);
285
+ * - anything more, including the panel plus one chat: `choose` (the text stays
286
+ * in the panel; `bot_reply` names where it goes).
287
+ *
288
+ * The set lives until `endTurn`. As a guard against a turn end never seen, a
289
+ * session's whole set is dropped once its latest input is `ttlMs` old, unless
290
+ * `running(sessionId)` says it still works. It is dropped whole, never entry
291
+ * by entry: losing one of two threads would turn "choose" into a wrong target.
292
+ *
293
+ * @param {{now?: () => number, ttlMs?: number, running?: (sessionId: string) => boolean,
294
+ * lookup?: (ref: {thread: string} | {ticket: string}) => object|string|null}} [opts]
295
+ * `lookup`: for `resolve`, a known thread or a ticket's origin thread outside this turn
296
+ * (a key, an origin or a Thread record); without it `resolve` only knows this turn's threads
297
+ */
298
+ export function createOrigins(opts = {}) {
299
+ const now = opts.now ?? Date.now;
300
+ const ttlMs = opts.ttlMs ?? ORIGIN_TTL_MS;
301
+ /** sessionId → {at, items: Map<threadKey, origin>} */
302
+ const sessions = new Map();
303
+
304
+ const running = (sessionId) => {
305
+ try {
306
+ return Boolean(opts.running?.(sessionId));
307
+ } catch {
308
+ return false;
309
+ }
310
+ };
311
+ /** The live set of a session, or null after dropping an expired one. */
312
+ const setOf = (sessionId) => {
313
+ const s = sessions.get(sessionId);
314
+ if (!s) return null;
315
+ if (now() - s.at >= ttlMs && !running(sessionId)) {
316
+ sessions.delete(sessionId);
317
+ return null;
318
+ }
319
+ return s;
320
+ };
321
+ const list = (sessionId) => [...(setOf(sessionId)?.items.values() ?? [])];
322
+
323
+ function replyPlan(sessionId) {
324
+ const origins = list(sessionId);
325
+ const chats = origins.filter((o) => o.kind !== PANEL);
326
+ const mode = chats.length === 0 ? 'panel' : chats.length === 1 && origins.length === 1 ? 'thread' : 'choose';
327
+ return { mode, target: mode === 'thread' ? copyOrigin(chats[0]) : null, origins: origins.map(copyOrigin) };
328
+ }
329
+
330
+ return {
331
+ /**
332
+ * An input of this turn arrived in `sessionId`: a user message (from a
333
+ * chat or the panel), or a ticket's report (pass the ticket's origin thread
334
+ * and `ticket`). The thread is `threadKey`, else the one `origin` names;
335
+ * an input with neither came from inside Harness and counts as the panel.
336
+ * The same thread twice is one entry, keeping its first place and the
337
+ * latest details (the newest message to quote).
338
+ * @param {string} sessionId
339
+ * @param {{threadKey?: string, origin?: {kind?: string, appKey?: string, key?: string, chatId?: string,
340
+ * rootId?: string, replyTo?: string, who?: string, chatTitle?: string}, ticket?: string|string[]}} input
341
+ * @returns {object|null} the origin as now stored
342
+ */
343
+ noteInput(sessionId, input = {}) {
344
+ const sid = part(sessionId);
345
+ if (!sid) return null;
346
+ for (const other of [...sessions.keys()]) setOf(other);
347
+ const key = toThreadKey(input.threadKey) ?? toThreadKey(input.origin) ?? panelThreadKey(sid);
348
+ const s = sessions.get(sid) ?? { at: now(), items: new Map() };
349
+ const prev = s.items.get(key);
350
+ const next = originOf(key, { ...(prev ?? {}), ...(input.origin ?? {}) });
351
+ const tickets = [...(prev?.tickets ?? [])];
352
+ for (const t of [input.ticket].flat()) if (part(t) && !tickets.includes(part(t))) tickets.push(part(t));
353
+ if (tickets.length) next.tickets = tickets;
354
+ s.items.set(key, next);
355
+ s.at = now();
356
+ sessions.set(sid, s);
357
+ return copyOrigin(next);
358
+ },
359
+
360
+ /** The distinct threads of this turn, in the order they first arrived. */
361
+ current(sessionId) {
362
+ return list(sessionId).map(copyOrigin);
363
+ },
364
+
365
+ /** `{mode: 'panel' | 'thread' | 'choose', target, origins}`; see the rules above. */
366
+ replyPlan,
367
+
368
+ /** Where this turn's plain replies go: the one chat thread, or null (the panel; or a choice to make). */
369
+ replyTarget(sessionId) {
370
+ return replyPlan(sessionId).target;
371
+ },
372
+
373
+ /**
374
+ * The thread `bot_reply` names: a thread key (or `thread/<key>`, `{thread}`)
375
+ * or a ticket id (or `ticket/<id>`, `{ticket}`) meaning that ticket's origin
376
+ * thread. This turn's threads first, then `lookup`; null when unknown, so a
377
+ * made-up key never becomes a target.
378
+ */
379
+ resolve(sessionId, ref) {
380
+ const r = refOf(ref);
381
+ if (!r) return null;
382
+ const items = list(sessionId);
383
+ const key = r.thread != null ? toThreadKey(r.thread) : null;
384
+ if (r.thread != null && !key) return null;
385
+ const hit = key ? items.find((o) => o.threadKey === key) : items.find((o) => (o.tickets ?? []).includes(r.ticket));
386
+ if (hit) return copyOrigin(hit);
387
+ let found = null;
388
+ try {
389
+ found = opts.lookup?.(key ? { thread: key } : { ticket: r.ticket }) ?? null;
390
+ } catch {
391
+ found = null;
392
+ }
393
+ const foundKey = toThreadKey(found);
394
+ if (!foundKey || (key && foundKey !== key)) return null;
395
+ const origin = originOf(foundKey, typeof found === 'object' ? found : {});
396
+ if (r.ticket) origin.tickets = [r.ticket];
397
+ return origin;
398
+ },
399
+
400
+ /** The turn ended: its threads are forgotten. Returns them. */
401
+ endTurn(sessionId) {
402
+ const out = list(part(sessionId)).map(copyOrigin);
403
+ sessions.delete(part(sessionId));
404
+ return out;
405
+ },
406
+ };
407
+ }