@kadaliao/dsh-bots 0.9.0 → 0.10.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/lib/cards.mjs CHANGED
@@ -274,12 +274,12 @@ export function followUpNoticeText(notice, ctx = {}) {
274
274
  }
275
275
 
276
276
  /**
277
- * Bots 0.9: a worker's report went to the person as it is, in the topic or chat its task came
277
+ * Bots 0.9: a worker's report went to the person as it is, in the panel, thread or chat its task came
278
278
  * from. Its requester is told without being woken (the note is "good to know"): it need not pass
279
279
  * the result on, and a `question` is the person's to answer there.
280
280
  * @param {object} ticket
281
281
  * @param {{status?: string, text?: string}} report
282
- * @param {CardContext & {where?: string}} [ctx] - `where`: how that topic or chat reads ("Panel · topic …")
282
+ * @param {CardContext & {where?: string}} [ctx] - `where`: how that place reads ("Panel · thread …")
283
283
  */
284
284
  export function shownNoticeText(ticket, report, ctx = {}) {
285
285
  const status = report?.status ?? 'done';
@@ -300,11 +300,11 @@ export function shownNoticeText(ticket, report, ctx = {}) {
300
300
  export const HEADER_TASKS = 8;
301
301
 
302
302
  /**
303
- * The line a message typed in the panel reaches a bot's home with (Bots 0.9): its topic, as
304
- * `bot_reply` and `bot_send_message` name it (`[Panel] (thread p…)`); for a reply in a topic,
305
- * the message it answers; and for the dispatcher the tasks a message may continue (`open`: open
306
- * ones, or ones that finished lately; at most `HEADER_TASKS`).
307
- * @param {{topic: string, replyTo?: {who?: string, text?: string}, open?: object[]}} what
303
+ * The lines a message typed in the panel reaches a bot with: for the dispatcher's main chat the
304
+ * tasks a message may continue (`open`: open ones, or ones that finished lately; at most
305
+ * `HEADER_TASKS`); in a thread, the message of it the person quotes (`replyTo`). `topic` (a
306
+ * thread id to name, as 0.9 did) is optional.
307
+ * @param {{topic?: string, replyTo?: {who?: string, text?: string}, open?: object[]}} what
308
308
  * @param {CardContext} [ctx]
309
309
  */
310
310
  export function panelHeaderText({ topic, replyTo, open = [] } = {}, ctx = {}) {
@@ -316,6 +316,52 @@ export function panelHeaderText({ topic, replyTo, open = [] } = {}, ctx = {}) {
316
316
  return lines.join('\n');
317
317
  }
318
318
 
319
+ /**
320
+ * The lines before the first message of a discussion (Bots 0.10, after open-super-agent's
321
+ * THREAD_NOTE): the person replies to one message, the conversation up to it is what the bot
322
+ * sees, and the main conversation after it is out of sight. `text`: the replied message (none
323
+ * when a chat app did not say); `quoted`: another message of the thread the person points at;
324
+ * `exact: false` when the fork could not be made at that message (it sees the conversation past it).
325
+ * @param {{who?: string, text?: string, quoted?: {who?: string, text?: string}, exact?: boolean}} [p]
326
+ */
327
+ export function discussionNoteText({ who, text, quoted, exact = true } = {}) {
328
+ const t = String(text ?? '').trim();
329
+ const lines = [
330
+ t
331
+ ? `[Thread] From here on this is a thread: the user replies to this message of ${who || 'the conversation'}${exact ? ' above' : ''}: ${quote(clip(t, 200).text)}. Answer about it.`
332
+ : '[Thread] From here on this is a thread: the user replies to an earlier message of the conversation above. Answer about it.',
333
+ exact
334
+ ? 'What the main conversation said after that message is not visible here.'
335
+ : 'The conversation above may go on past that message; stay on that message.',
336
+ ];
337
+ const q = String(quoted?.text ?? '').trim();
338
+ if (q) lines.push(`In reply to ${quoted.who || 'a message'}: ${quote(clip(q, 160).text)}`);
339
+ return lines.join('\n');
340
+ }
341
+
342
+ /** Messages of the threads a news note lists at most, the latest kept. */
343
+ export const NEWS_MESSAGES = 16;
344
+
345
+ /**
346
+ * Before the person's next message in a bot's main conversation (Bots 0.10): what was said in the
347
+ * threads of its panel chat since it last heard. The panel shows a reply in the chat, quoting the
348
+ * message it answers, so what the person reads there the main conversation knows too; each thread
349
+ * is a conversation of its own and is not to be answered here.
350
+ * @param {{threads?: {who?: string, text?: string, said: {who: string, text: string}[]}[]}} [p]
351
+ * per thread: whose message it answers ("your message"), that message, and what was said in it, in order
352
+ */
353
+ export function threadNewsText({ threads = [] } = {}) {
354
+ const list = threads.filter((th) => th?.said?.length);
355
+ if (!list.length) return '';
356
+ const lines = ['[Threads] Since your last message here, the user replied to messages of this chat in threads (each its own conversation, which answered there). So you know what was said; nothing to answer:'];
357
+ for (const th of list) {
358
+ const on = String(th.text ?? '').trim();
359
+ lines.push(on ? `- On ${th.who || 'a message'}: ${quote(clip(on.replace(/\s+/g, ' '), 80).text)}` : '- On an earlier message:');
360
+ for (const x of th.said) lines.push(` ${x.who}: ${quote(clip(String(x.text ?? '').trim(), 300).text)}`);
361
+ }
362
+ return lines.join('\n');
363
+ }
364
+
319
365
  /**
320
366
  * Prepended when a ticket that was working is restarted after Harness came
321
367
  * back: look before repeating anything that left the conversation.
@@ -643,6 +643,7 @@ export function createConnector(opts = {}) {
643
643
  const chain = root || (replyTo && channel === chat ? roots.get(replyTo) || replyTo : '');
644
644
  const path = `/channels/${encodeURIComponent(channel)}/messages`;
645
645
  const chunks = splitMessage(text);
646
+ const ids = [];
646
647
  for (let i = 0; i < chunks.length; i += 1) {
647
648
  const body = { content: chunks[i], allowed_mentions: { parse: [] } };
648
649
  const quote = i === 0 && replyTo ? replyTo : root && latest.get(channel)?.root !== root ? root : '';
@@ -651,7 +652,9 @@ export function createConnector(opts = {}) {
651
652
  const id = sent?.id ? String(sent.id) : '';
652
653
  if (id && chain) remember(roots, id, chain, 2000);
653
654
  if (id) noteLatest(channel, id, { mine: true, root: chain });
655
+ if (id) ids.push(id);
654
656
  }
657
+ return { ids };
655
658
  }
656
659
 
657
660
  /** Show "bot is typing…" for about ten seconds (in the thread channel `threadId`, if it is one). Failures are logged and ignored. */
@@ -1254,9 +1254,11 @@ export function createConnector(opts = {}) {
1254
1254
  const root = sendOpts?.threadId ? String(sendOpts.threadId) : '';
1255
1255
  const gone = new Set();
1256
1256
  let first = true;
1257
+ const ids = [];
1257
1258
  try {
1258
1259
  for (const part of partsOf(text)) {
1259
- await sendPart(chatId, part, first ? [replyTo, root] : [root], gone);
1260
+ const r = await sendPart(chatId, part, first ? [replyTo, root] : [root], gone);
1261
+ if (r?.data?.message_id) ids.push(String(r.data.message_id));
1260
1262
  first = false;
1261
1263
  }
1262
1264
  if (sendTrouble) {
@@ -1269,6 +1271,7 @@ export function createConnector(opts = {}) {
1269
1271
  } finally {
1270
1272
  void removeMark(chatId);
1271
1273
  }
1274
+ return { ids };
1272
1275
  },
1273
1276
 
1274
1277
  /** Called every ~5 s while a bot works: a "Typing" reaction on the person's message, removed when the work stops. */
@@ -866,12 +866,12 @@ export function createConnector(opts = {}) {
866
866
  async function post(channel, md, thread) {
867
867
  const where = { channel, ...(thread ? { thread_ts: thread } : {}) };
868
868
  try {
869
- await api('chat.postMessage', { ...where, text: fallbackText(md), blocks: [{ type: 'markdown', text: defuse(md) }] });
869
+ return (await api('chat.postMessage', { ...where, text: fallbackText(md), blocks: [{ type: 'markdown', text: defuse(md) }] }))?.ts;
870
870
  } catch (e) {
871
871
  if (BOT_AUTH_ERRORS.has(e.code)) failBotToken();
872
872
  if (!BLOCK_ERRORS.has(e.code)) throw e;
873
873
  log(`slack: Slack did not take the Markdown block (${e.code}); sending plain text`);
874
- await api('chat.postMessage', { ...where, text: fallbackText(md) });
874
+ return (await api('chat.postMessage', { ...where, text: fallbackText(md) }))?.ts;
875
875
  }
876
876
  }
877
877
 
@@ -889,7 +889,12 @@ export function createConnector(opts = {}) {
889
889
  const replyTo = sendOpts?.replyTo ? String(sendOpts.replyTo) : '';
890
890
  const threadId = sendOpts?.threadId ? String(sendOpts.threadId) : '';
891
891
  const thread = (replyTo && roots.get(`${channel}|${replyTo}`)) || threadId || replyTo;
892
- for (const part of splitMessage(text, PART_LIMIT)) await post(channel, part, thread);
892
+ const ids = [];
893
+ for (const part of splitMessage(text, PART_LIMIT)) {
894
+ const ts = await post(channel, part, thread);
895
+ if (ts) ids.push(String(ts));
896
+ }
897
+ return { ids };
893
898
  }
894
899
 
895
900
  const statusAt = new Map();
@@ -302,6 +302,10 @@ export function createConnector(opts) {
302
302
  async send(chatId, text, sendOpts = {}) {
303
303
  let first = true;
304
304
  let topic = topicOf(sendOpts?.threadId);
305
+ const ids = [];
306
+ const keep = (r) => {
307
+ if (r?.message_id != null) ids.push(String(r.message_id));
308
+ };
305
309
  for (const part of splitText(text, TEXT_LIMIT)) {
306
310
  const replyTo = first && sendOpts?.replyTo && /^\d+$/.test(String(sendOpts.replyTo)) ? Number(sendOpts.replyTo) : null;
307
311
  const body = {
@@ -310,16 +314,17 @@ export function createConnector(opts) {
310
314
  ...(replyTo ? { reply_parameters: { message_id: replyTo, allow_sending_without_reply: true } } : {}),
311
315
  };
312
316
  try {
313
- await polite('sendMessage', topic ? { ...body, message_thread_id: topic } : body);
317
+ keep(await polite('sendMessage', topic ? { ...body, message_thread_id: topic } : body));
314
318
  } catch (error) {
315
319
  // The topic was deleted: the reply still reaches the chat.
316
320
  if (!topic || error.code !== 400 || !THREAD_GONE.test(error.description ?? '')) throw error;
317
321
  log(`telegram: topic ${topic} is gone; sending to the chat`);
318
322
  topic = null;
319
- await polite('sendMessage', body);
323
+ keep(await polite('sendMessage', body));
320
324
  }
321
325
  first = false;
322
326
  }
327
+ return { ids };
323
328
  },
324
329
 
325
330
  /** "typing…" in the chat (or its topic `threadId`) for about five seconds. */
package/lib/channels.mjs CHANGED
@@ -363,6 +363,8 @@ export function hintOf(detail) {
363
363
  * knownThread?: (threadKey: string) => object|undefined, // a stored Thread record (bot_reply targets beyond this turn)
364
364
  * ticketThread?: (ticketId: string) => string|undefined, // the origin Thread key of a ticket
365
365
  * running?: (sessionId: string) => boolean, // whether that conversation is working
366
+ * homeKey?: (sessionId: string) => string|undefined, // the Thread a Session's input without one belongs to (a discussion's own)
367
+ * onSent?: (sent: {tag: any, appKey: string, chatId: string, threadKey?: string, ids: string[]}) => void, // ids of messages a tagged send made
366
368
  * loadConnector?: (kind: string) => Promise<{createConnector: Function, TEXT_LIMIT?: number}>,
367
369
  * log?: (line: string) => void,
368
370
  * now?: () => number,
@@ -427,7 +429,7 @@ export function createChannels(deps) {
427
429
  /** threadKey → what the latest message there told of it (who, the message to answer, the chat's title) */
428
430
  const known = new Map();
429
431
  /** Per conversation, the Threads of this turn's inputs (lib/threads.mjs). */
430
- const origins = createOrigins({ now, running: (sessionId) => running(sessionId), lookup: (ref) => lookupThread(ref) });
432
+ const origins = createOrigins({ now, running: (sessionId) => running(sessionId), lookup: (ref) => lookupThread(ref), homeKey: (sessionId) => deps.homeKey?.(sessionId) });
431
433
  /** Conversations that noted a chat Thread (dropped on unpair). */
432
434
  const noted = new Set();
433
435
  /** Conversations whose current turn had a person's input (a chat or panel message, a scheduled run). */
@@ -937,7 +939,12 @@ export function createChannels(deps) {
937
939
  }
938
940
 
939
941
  /** Send a reply to a chat Thread, in its thread (topic, reply chain) and parts in order; false when its channel is down. */
940
- function sendText(sessionId, target, text) {
942
+ /**
943
+ * Send `text` to a chat target in order with the chat's other sends. `tag` (anything) comes back
944
+ * with the ids of the messages the chat app made (`deps.onSent({tag, appKey, chatId, threadKey,
945
+ * ids})`), for connectors that tell them: a reply to one of them is a discussion (Bots 0.10).
946
+ */
947
+ function sendText(sessionId, target, text, tag) {
941
948
  const rec = live.get(target.key ?? target.appKey);
942
949
  stopTyping(sessionId, target.threadKey);
943
950
  if (!rec?.conn) {
@@ -949,13 +956,22 @@ export function createChannels(deps) {
949
956
  const replyTo = target.replyTo ? String(target.replyTo) : '';
950
957
  void enqueue(rec, target.chatId, async () => {
951
958
  let first = true;
959
+ const ids = [];
952
960
  for (const part of splitText(plain, rec.limit)) {
953
961
  if (!rec.conn) break;
954
962
  // A chat app that threads replies (Slack) keeps `replyTo` on every part; elsewhere only the first part quotes.
955
963
  const opts = { ...(root ? { threadId: root } : {}), ...(replyTo && (first || rec.mod?.THREADS === true) ? { replyTo } : {}) };
956
- await rec.conn.send(target.chatId, part, Object.keys(opts).length ? opts : undefined);
964
+ const sent = await rec.conn.send(target.chatId, part, Object.keys(opts).length ? opts : undefined);
965
+ for (const id of Array.isArray(sent?.ids) ? sent.ids : []) if (id != null && String(id)) ids.push(String(id));
957
966
  first = false;
958
967
  }
968
+ if (ids.length && tag !== undefined && typeof deps.onSent === 'function') {
969
+ try {
970
+ deps.onSent({ tag, appKey: rec.key, chatId: String(target.chatId), threadKey: target.threadKey, ids });
971
+ } catch {
972
+ // Only a note for later replies.
973
+ }
974
+ }
959
975
  });
960
976
  return true;
961
977
  }
@@ -1048,9 +1064,10 @@ export function createChannels(deps) {
1048
1064
  * A plain reply of the conversation `sessionId`: sent to its turn's one chat
1049
1065
  * Thread (`replyPlan` mode `thread`), in that Thread. Returns the target (or
1050
1066
  * null: the panel) at once; sending continues in the background. Words
1051
- * `replyTo` already sent there this turn are not sent again.
1067
+ * `replyTo` already sent there this turn are not sent again. `tag` comes back
1068
+ * with the ids of what was sent (`deps.onSent`).
1052
1069
  */
1053
- noteReply(sessionId, text) {
1070
+ noteReply(sessionId, text, tag) {
1054
1071
  if (!String(text ?? '').trim()) return null;
1055
1072
  const plan = origins.replyPlan(sessionId);
1056
1073
  if (plan.mode !== 'thread') return null;
@@ -1058,7 +1075,7 @@ export function createChannels(deps) {
1058
1075
  if (plan.target.kind === 'panel') return targetView(plan.target);
1059
1076
  const target = withKnown(plan.target);
1060
1077
  if (sentThisTurn.get(sessionId)?.has(`${target.threadKey}|${norm(text)}`)) return targetView(target);
1061
- return sendText(sessionId, target, text) ? targetView(target) : null;
1078
+ return sendText(sessionId, target, text, tag) ? targetView(target) : null;
1062
1079
  },
1063
1080
 
1064
1081
  /**
@@ -1074,10 +1091,10 @@ export function createChannels(deps) {
1074
1091
  * Send `text` from `sessionId` to a chat Thread (`resolveReply`'s answer).
1075
1092
  * Throws when the channel is not connected. Returns the target.
1076
1093
  */
1077
- replyTo(sessionId, target, text) {
1094
+ replyTo(sessionId, target, text, tag) {
1078
1095
  if (!target || target.kind === 'panel' || !target.chatId) throw new Error('no chat to send to');
1079
1096
  if (!String(text ?? '').trim()) throw new Error('text must not be empty');
1080
- if (!sendText(sessionId, target, text)) throw new Error(`${CHANNEL_LABELS[target.kind] ?? target.kind} is not connected right now; the reply was not sent`);
1097
+ if (!sendText(sessionId, target, text, tag)) throw new Error(`${CHANNEL_LABELS[target.kind] ?? target.kind} is not connected right now; the reply was not sent`);
1081
1098
  const sent = sentThisTurn.get(sessionId) ?? new Set();
1082
1099
  sent.add(`${target.threadKey}|${norm(text)}`);
1083
1100
  sentThisTurn.set(sessionId, sent);
@@ -1099,7 +1116,7 @@ export function createChannels(deps) {
1099
1116
  * and someone paired (see `lookupThread`). Typing shown there for `typingOf` (a Session) stops.
1100
1117
  * Returns the target, or null when it cannot be reached.
1101
1118
  */
1102
- post(ref, text, { replyTo = '', typingOf = '' } = {}) {
1119
+ post(ref, text, { replyTo = '', typingOf = '', tag } = {}) {
1103
1120
  if (!String(text ?? '').trim()) return null;
1104
1121
  const found = lookupThread(ref);
1105
1122
  if (!found) return null;
@@ -1107,7 +1124,7 @@ export function createChannels(deps) {
1107
1124
  const p = parseThreadKey(found.threadKey);
1108
1125
  const fromKey = { kind: p.kind, key: p.appKey, appKey: p.appKey, chatId: p.chatId, ...(p.rootId !== undefined ? { rootId: p.rootId } : {}) };
1109
1126
  const target = withKnown({ ...fromKey, ...found, ...(replyTo ? { replyTo: String(replyTo) } : {}) });
1110
- const sent = sendText(typingOf || '', target, text);
1127
+ const sent = sendText(typingOf || '', target, text, tag);
1111
1128
  if (typingOf) stopTyping(typingOf, target.threadKey);
1112
1129
  return sent ? targetView(target) : null;
1113
1130
  },
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Discussions (讨论串, Bots 0.10): a reply to one message, talked over in a
3
+ * Session of its own.
4
+ *
5
+ * As in open-super-agent, a discussion sees the conversation it branched from
6
+ * up to the message it answers, then its own messages; what the main
7
+ * conversation says later never reaches it, and what is said in it never
8
+ * reaches the main conversation. Bots gets that from Harness's
9
+ * `sessionController.fork({sessionId, atSeq})`: the bot's conversation is
10
+ * forked at the replied message, and the fork is the discussion.
11
+ *
12
+ * A discussion is keyed by its Thread key (lib/threads.mjs): in the panel
13
+ * `panel:<homeSessionId>:<rootId>`, in a chat app `kind:appKey:chatId:rootId`.
14
+ *
15
+ * Anchors say where a message sits in a Session (`{sessionId, seq}`), so a
16
+ * discussion can be forked at it:
17
+ * - `msg:<id>`: a timeline message (the panel's own ids);
18
+ * - `chat:<appKey>:<chatId>:<messageId>`: a chat app's message, one the bot
19
+ * took in or one it sent;
20
+ * - a Thread key: where that Thread last spoke with the bot's home (a group
21
+ * thread the bot answered in before anyone replied).
22
+ *
23
+ * The file `discussions.json` holds `{items, anchors, seen, told, since}`; anchors and old
24
+ * discussions are bounded. `told`: per bot, when its main conversation last heard what was said
25
+ * in its threads (the panel shows those replies in the chat, so the main conversation hears of
26
+ * them with the person's next message there); `since`: when the file began, the default.
27
+ *
28
+ * @module @kadaliao/dsh-bots/lib/discussions
29
+ */
30
+
31
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
32
+ import { join } from 'node:path';
33
+
34
+ /** A discussion with no message for this long has its Session archived (it opens again on the next reply). */
35
+ export const IDLE_ARCHIVE_MS = 24 * 3600_000;
36
+ /** Anchors kept: the newest win. */
37
+ export const KEEP_ANCHORS = 4000;
38
+ /** Discussions kept: the most recently active win; an archived one past this is forgotten. */
39
+ export const KEEP_DISCUSSIONS = 2000;
40
+
41
+ const str = (v) => (v == null ? '' : String(v).trim());
42
+ const seqOf = (v) => (Number.isSafeInteger(Number(v)) && Number(v) >= 0 ? Number(v) : undefined);
43
+
44
+ /** The anchor ref of a timeline message. */
45
+ export const messageRef = (id) => `msg:${str(id)}`;
46
+ /** The anchor ref of a chat app's message. */
47
+ export const chatMessageRef = (appKey, chatId, messageId) => `chat:${str(appKey)}:${str(chatId)}:${str(messageId)}`;
48
+
49
+ /** A position `{sessionId, seq}` when both parts are valid, else null. */
50
+ export function positionOf(p) {
51
+ const sessionId = str(p?.sessionId);
52
+ const seq = seqOf(p?.seq);
53
+ return sessionId && seq !== undefined ? { sessionId, seq } : null;
54
+ }
55
+
56
+ /**
57
+ * Where a discussion forks, first match wins:
58
+ * 1. `thread`: where its Thread last spoke with the home (a chat thread answered there before);
59
+ * 2. `root`: the replied message itself;
60
+ * 3. `fallback`: a Session to fork at its latest completed turn (`seq` left out).
61
+ * Returns `{sessionId, seq?}`, or null when there is nothing to fork.
62
+ */
63
+ export function forkPoint({ thread, root, fallback } = {}) {
64
+ return positionOf(thread) ?? positionOf(root) ?? (str(fallback) ? { sessionId: str(fallback) } : null);
65
+ }
66
+
67
+ /**
68
+ * The event of a timeline message in a Session's log, by time, for a message logged before
69
+ * anchors were kept (Bots 0.9 and older). A bot's message sits at the last event at or before
70
+ * the moment it was logged; a person's message at the end of the turn that took it, so the
71
+ * discussion includes the answer it got (or at the message itself while that turn runs).
72
+ * @param {object[]} events - the Session's log (or its tail), oldest first, with `seq`, `time`, `type`
73
+ * @param {{at: number, fromPerson?: boolean}} message
74
+ * @param {number} [slackMs] - how far after `at` an event still counts as the message's own
75
+ * @returns {number|undefined} the seq
76
+ */
77
+ export function seqByTime(events, { at, fromPerson = false }, slackMs = 1500) {
78
+ const list = Array.isArray(events) ? events : [];
79
+ const t = Number(at);
80
+ if (!Number.isFinite(t) || list.length === 0) return undefined;
81
+ const timeOf = (e) => (typeof e?.time === 'number' ? e.time : Date.parse(e?.time ?? '') || 0);
82
+ let mine = -1;
83
+ for (let i = 0; i < list.length; i += 1) {
84
+ if (timeOf(list[i]) <= t + slackMs) mine = i;
85
+ else break;
86
+ }
87
+ if (mine < 0) return undefined;
88
+ if (fromPerson) {
89
+ // Logged when it was sent, maybe a while before a model took it: its own event is the first
90
+ // person's message from that moment on, and the end of the turn that took it counts.
91
+ const own = list.findIndex((e) => e?.type === 'user/message' && timeOf(e) >= t - 50);
92
+ if (own < 0) return seqOf(list[mine].seq);
93
+ for (let i = own; i < list.length; i += 1) if (list[i]?.type === 'turn/end') return seqOf(list[i].seq);
94
+ return seqOf(list[own].seq);
95
+ }
96
+ return seqOf(list[mine].seq);
97
+ }
98
+
99
+ /**
100
+ * The discussions file.
101
+ * @param {string} dir
102
+ * @param {{now?: () => number}} [opts]
103
+ */
104
+ export function createDiscussions(dir, { now = Date.now } = {}) {
105
+ const file = join(dir, 'discussions.json');
106
+ /** @type {{items: Record<string, object>, anchors: Record<string, {sessionId: string, seq: number, at: number}>, seen: Record<string, number>, told: Record<string, number>, since: number}} */
107
+ let state = { items: {}, anchors: {}, seen: {}, told: {}, since: now() };
108
+ try {
109
+ if (existsSync(file)) {
110
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
111
+ state = {
112
+ items: raw?.items && typeof raw.items === 'object' ? raw.items : {},
113
+ anchors: raw?.anchors && typeof raw.anchors === 'object' ? raw.anchors : {},
114
+ seen: raw?.seen && typeof raw.seen === 'object' ? raw.seen : {},
115
+ told: raw?.told && typeof raw.told === 'object' ? raw.told : {},
116
+ since: Number(raw?.since) || now(),
117
+ };
118
+ }
119
+ } catch {
120
+ // A damaged file starts over: discussions are reopened by forking again.
121
+ }
122
+ const bySid = new Map();
123
+ const index = () => {
124
+ bySid.clear();
125
+ for (const d of Object.values(state.items)) if (d?.sessionId) bySid.set(d.sessionId, d.key);
126
+ };
127
+ index();
128
+
129
+ let timer = null;
130
+ const write = () => {
131
+ timer = null;
132
+ try {
133
+ mkdirSync(dir, { recursive: true });
134
+ const tmp = `${file}.tmp`;
135
+ writeFileSync(tmp, JSON.stringify(state));
136
+ renameSync(tmp, file);
137
+ } catch {
138
+ // Kept in memory; written with the next change.
139
+ }
140
+ };
141
+ /** Written soon, not at once: anchors change on every message. */
142
+ const save = () => {
143
+ if (timer) return;
144
+ timer = setTimeout(write, 200);
145
+ timer.unref?.();
146
+ };
147
+
148
+ const prune = () => {
149
+ const refs = Object.keys(state.anchors);
150
+ if (refs.length > KEEP_ANCHORS) {
151
+ refs.sort((a, b) => (state.anchors[a].at ?? 0) - (state.anchors[b].at ?? 0));
152
+ for (const r of refs.slice(0, refs.length - KEEP_ANCHORS)) delete state.anchors[r];
153
+ }
154
+ const keys = Object.keys(state.items);
155
+ if (keys.length > KEEP_DISCUSSIONS) {
156
+ const old = keys.filter((k) => state.items[k].archivedAt).sort((a, b) => (state.items[a].lastAt ?? 0) - (state.items[b].lastAt ?? 0));
157
+ for (const k of old.slice(0, keys.length - KEEP_DISCUSSIONS)) {
158
+ delete state.seen[state.items[k].rootId];
159
+ delete state.items[k];
160
+ }
161
+ index();
162
+ }
163
+ };
164
+
165
+ const copy = (d) => (d ? { ...d, ...(d.source ? { source: { ...d.source } } : {}) } : undefined);
166
+
167
+ return {
168
+ /** The discussion of a Thread key, or undefined. */
169
+ get(key) {
170
+ return copy(state.items[str(key)]);
171
+ },
172
+ /** The discussion a Session is, or undefined. */
173
+ bySession(sessionId) {
174
+ const key = bySid.get(str(sessionId));
175
+ return key ? copy(state.items[key]) : undefined;
176
+ },
177
+ /** The discussion of a panel root message, or undefined. */
178
+ byRoot(rootId) {
179
+ const r = str(rootId);
180
+ return copy(Object.values(state.items).find((d) => d.rootId === r));
181
+ },
182
+ /** Discussions, the most recently active first; `botId` narrows. */
183
+ list({ botId = '', archived } = {}) {
184
+ return Object.values(state.items)
185
+ .filter((d) => (!botId || d.botId === botId) && (archived === undefined || Boolean(d.archivedAt) === archived))
186
+ .sort((a, b) => (b.lastAt ?? 0) - (a.lastAt ?? 0))
187
+ .map(copy);
188
+ },
189
+ /**
190
+ * Add a discussion. `{key, botId, sessionId, rootId, source: {sessionId, seq?}, title?}`;
191
+ * `createdAt` and `lastAt` are set here. Replaces one with the same key.
192
+ */
193
+ add(rec) {
194
+ const key = str(rec?.key);
195
+ const sessionId = str(rec?.sessionId);
196
+ if (!key || !sessionId || !str(rec?.botId)) throw new Error('a discussion needs a key, a bot and a Session');
197
+ const at = now();
198
+ const prev = state.items[key];
199
+ if (prev?.sessionId) bySid.delete(prev.sessionId);
200
+ const d = {
201
+ key,
202
+ botId: str(rec.botId),
203
+ sessionId,
204
+ rootId: str(rec.rootId),
205
+ ...(rec.source?.sessionId ? { source: { sessionId: str(rec.source.sessionId), ...(seqOf(rec.source.seq) !== undefined ? { seq: seqOf(rec.source.seq) } : {}) } } : {}),
206
+ ...(str(rec.title) ? { title: str(rec.title).slice(0, 200) } : {}),
207
+ createdAt: prev?.createdAt ?? at,
208
+ lastAt: at,
209
+ };
210
+ state.items[key] = d;
211
+ bySid.set(sessionId, key);
212
+ prune();
213
+ // Written at once: a fork whose record is lost would be a conversation no bot owns.
214
+ if (timer) clearTimeout(timer);
215
+ write();
216
+ return copy(d);
217
+ },
218
+ /** Change fields of a discussion (`lastAt`, `archivedAt`, `noted`, …); `null` removes a field. */
219
+ patch(key, fields = {}) {
220
+ const d = state.items[str(key)];
221
+ if (!d) return undefined;
222
+ for (const [k, v] of Object.entries(fields)) {
223
+ if (k === 'key' || k === 'sessionId' || k === 'botId') continue;
224
+ if (v === null || v === undefined) delete d[k];
225
+ else d[k] = v;
226
+ }
227
+ save();
228
+ return copy(d);
229
+ },
230
+ /** A message was said in the discussion now: it is active. */
231
+ touch(key) {
232
+ const d = state.items[str(key)];
233
+ if (!d) return undefined;
234
+ d.lastAt = now();
235
+ save();
236
+ return copy(d);
237
+ },
238
+ /** Forget a discussion (its Session is someone else's to archive). */
239
+ remove(key) {
240
+ const d = state.items[str(key)];
241
+ if (!d) return false;
242
+ bySid.delete(d.sessionId);
243
+ delete state.items[str(key)];
244
+ save();
245
+ return true;
246
+ },
247
+ /** Discussions quiet for `idleMs` and not archived yet: the ones to archive. */
248
+ idle(idleMs = IDLE_ARCHIVE_MS) {
249
+ const cut = now() - idleMs;
250
+ return Object.values(state.items)
251
+ .filter((d) => !d.archivedAt && (d.lastAt ?? 0) < cut)
252
+ .map(copy);
253
+ },
254
+
255
+ /** Note where `ref` (see the module notes) sits: `{sessionId, seq}`. The newest note wins. */
256
+ anchor(ref, pos) {
257
+ const r = str(ref);
258
+ const p = positionOf(pos);
259
+ if (!r || !p) return;
260
+ state.anchors[r] = { ...p, at: now() };
261
+ prune();
262
+ save();
263
+ },
264
+ /** Where `ref` sits, or null. */
265
+ anchorOf(ref) {
266
+ const a = state.anchors[str(ref)];
267
+ return a ? positionOf(a) : null;
268
+ },
269
+
270
+ /** When the person last looked at the discussion under `rootId` (0: never). */
271
+ seenAt(rootId) {
272
+ return Number(state.seen[str(rootId)]) || 0;
273
+ },
274
+ /** The person looked at the discussion under `rootId` at `at` (default now). */
275
+ markSeen(rootId, at = now()) {
276
+ const r = str(rootId);
277
+ if (!r) return;
278
+ state.seen[r] = Math.max(Number(state.seen[r]) || 0, Number(at) || 0);
279
+ save();
280
+ },
281
+
282
+ /** When `botId`'s main conversation last heard what was said in its threads (at first: when this file began). */
283
+ toldAt(botId) {
284
+ return Number(state.told[str(botId)]) || Number(state.since) || 0;
285
+ },
286
+ /** `botId`'s main conversation heard what was said in its threads up to `at` (default now). */
287
+ markTold(botId, at = now()) {
288
+ const b = str(botId);
289
+ if (!b) return;
290
+ state.told[b] = Math.max(Number(state.told[b]) || 0, Number(at) || 0);
291
+ save();
292
+ },
293
+
294
+ /** Write now (tests, shutdown). */
295
+ flush() {
296
+ if (timer) clearTimeout(timer);
297
+ write();
298
+ },
299
+ };
300
+ }