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