@kadaliao/dsh-bots 0.7.0 → 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.
package/lib/channels.mjs CHANGED
@@ -10,17 +10,27 @@
10
10
  * - who may talk to the team: only people paired with a one-time code from
11
11
  * the panel; everyone else is ignored (at most one "this bot is private"
12
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.
13
+ * - which Thread a message belongs to (PLAN-0.8 §12): the connector's
14
+ * `threadId`; else, for a Slack, Discord or Feishu group message, the
15
+ * message itself (the bot's answer hangs under it); else the whole chat;
16
+ * - where a message goes (lib/threads.mjs `routeInbound`): a leading
17
+ * `@handle` reaches that bot's home; a Thread with live subscribed tickets
18
+ * hands it to them (`deps.toTickets`); otherwise the bot owning the channel
19
+ * (`deps.deliver`);
20
+ * - where a conversation's plain replies go (lib/threads.mjs `createOrigins`):
21
+ * each turn collects the Threads its inputs came from; with exactly one
22
+ * chat Thread the reply goes there, otherwise it stays in the panel and the
23
+ * bot names a target (`replyTo`, behind `bot_reply`). A scheduled run
24
+ * reports to the channel's first paired person, and a teammate's DM answers
25
+ * where the conversation's last human input came from (0.7).
18
26
  *
19
27
  * A connector gets the app's field values (`values`; `token` is its first
20
28
  * 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.
29
+ * mentioned, messageId, threadId?, order?, chatTitle?, source?}; `send` and
30
+ * `typing` take `{threadId, replyTo}`. Optional module exports: `TEXT_LIMIT`,
31
+ * `MARKDOWN` (true when the chat app renders Markdown replies), `THREADS`
32
+ * (every part of a reply keeps `replyTo`) and `links({account, code, values})`
33
+ * → {link?, invite?} for the panel.
24
34
  *
25
35
  * @module @kadaliao/dsh-bots/lib/channels
26
36
  */
@@ -29,6 +39,8 @@ import { createHash, randomInt } from 'node:crypto';
29
39
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
30
40
  import { dirname } from 'node:path';
31
41
 
42
+ import { addressedBot, createOrigins, isPanelThread, parseThreadKey, routeInbound, threadKey, toThreadKey } from './threads.mjs';
43
+
32
44
  /** Connector modules by channel kind, loaded on first use. */
33
45
  const CONNECTORS = {
34
46
  telegram: () => import('./channels/telegram.mjs'),
@@ -58,6 +70,10 @@ const TYPING_EVERY_MS = 5000;
58
70
  const TYPING_MAX_MS = 10 * 60_000;
59
71
  /** A delivered channel message not seen in its conversation by then is forgotten. */
60
72
  const PENDING_TTL_MS = 30 * 60_000;
73
+ /** Chat apps where the bot answers a group message under that message: it is the root of its Thread. */
74
+ const ROOT_IN_GROUPS = new Set(['slack', 'discord', 'feishu']);
75
+ /** Threads the hub remembers details of (who wrote there, which message to answer). */
76
+ const KNOWN_THREADS = 500;
61
77
 
62
78
  /** Load the connector module of `kind`. */
63
79
  export async function loadConnector(kind) {
@@ -222,14 +238,31 @@ export function isGreeting(text) {
222
238
  /** The bot a message is for: the one named by a leading `@handle`, else `owner`. */
223
239
  export function routeMessage(text, owner, roster) {
224
240
  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 };
241
+ const hit = addressedBot(t, roster);
242
+ return hit ? { bot: hit.bot, text: hit.text } : { bot: owner, text: t };
243
+ }
244
+
245
+ /**
246
+ * The root of the Thread an inbound message belongs to (PLAN-0.8 §12): the
247
+ * connector's `threadId`; else, for a Slack, Discord or Feishu group message,
248
+ * the message's own id (the bot's answer hangs under it, so follow-ups there
249
+ * report it as their thread); else '' (the whole chat: a private chat, a
250
+ * Telegram group without topics).
251
+ * @param {string} kind - the channel kind
252
+ * @param {{threadId?: string|number|null, messageId?: string|number, isDirect?: boolean}} msg
253
+ */
254
+ export function threadRootOf(kind, msg) {
255
+ const own = msg?.threadId == null ? '' : String(msg.threadId).trim();
256
+ if (own) return own;
257
+ const id = msg?.messageId == null ? '' : String(msg.messageId).trim();
258
+ return !msg?.isDirect && ROOT_IN_GROUPS.has(kind) && id ? id : '';
231
259
  }
232
260
 
261
+ /** The Thread key a message names in the header line a bot reads, after the source: ` (thread <key>)`. */
262
+ export const threadNote = (key) => (key ? ` (thread ${key})` : '');
263
+ /** A header line without its thread note, so a message reads the same with or without it. */
264
+ const withoutThreadNote = (s) => String(s ?? '').replace(/^(\[[^\n]*\]) \(thread [^\n)]*\)/, '$1');
265
+
233
266
  const cleanName = (s, max = 60) =>
234
267
  String(s ?? '')
235
268
  .replace(/[[\]\r\n]+/g, ' ')
@@ -280,6 +313,21 @@ export function newTopicText(bot) {
280
313
  : `New topic: ${bot.name} starts a fresh conversation and keeps what it remembers.`;
281
314
  }
282
315
 
316
+ /**
317
+ * What a chat hears once when a bot waits for an answer in DeepSeek Harness (`ask_user_question`):
318
+ * each question with its options, as plain text. A reply in the chat does not answer it.
319
+ */
320
+ export function askNoticeText(bot, questions) {
321
+ const zh = zhBot(bot);
322
+ const lines = [zh ? `${bot.name}(@${bot.handle})在 DeepSeek Harness 里等你回答:` : `${bot.name} (@${bot.handle}) is waiting for your answer in DeepSeek Harness:`];
323
+ for (const q of questions ?? []) {
324
+ lines.push('', `${q.header ? `${q.header}: ` : ''}${q.question}`);
325
+ for (const o of q.options ?? []) lines.push(`- ${o.label}`);
326
+ }
327
+ lines.push('', zh ? '请到 DeepSeek Harness 里回答,在这里回复不算作答。' : 'Answer it in DeepSeek Harness; a reply here does not answer it.');
328
+ return lines.join('\n');
329
+ }
330
+
283
331
  // --- hint for the panel ----------------------------------------------------------------
284
332
 
285
333
  /** A short code the panel words in its own language, from a connector's error text. */
@@ -296,11 +344,24 @@ export function hintOf(detail) {
296
344
  /**
297
345
  * Every channel of every bot: connectors, pairing, routing and reply targets.
298
346
  *
347
+ * A message's `meta` (the third argument of `deliver` and `toTickets`):
348
+ * `{threadKey, origin, key?}` — the Thread it belongs to, where it came from
349
+ * (`{threadKey, kind, key, chatId, rootId?, replyTo?, who, chatTitle?, direct?,
350
+ * body}`) and, when the chat app gave the message an id, a stable delivery key
351
+ * (`chat:<appKey>:<chatId>:<messageId>`) the host can make its message id from,
352
+ * so a message handed out again after a restart is not run twice.
353
+ *
299
354
  * @param {{
300
355
  * file: string, // channels.json: paired people and options per channel
301
356
  * bots: () => object[], // the roster
302
357
  * entries: () => object[], // the app catalog
303
- * deliver: (bot: object, msg: {header: string, body: string}) => Promise<string>, // hand a prompt to a bot; resolves to its session id
358
+ * deliver: (bot: object, msg: {header: string, body: string}, meta: object) =>
359
+ * Promise<string | {sessionId: string, messageId?: string, skipped?: boolean}>, // hand a prompt to a bot's home
360
+ * toTickets?: (tickets: object[], msg: {header: string, body: string}, meta: object & {owner: object}) =>
361
+ * Promise<string[]>, // hand a follow-up to the tickets on its Thread; their session ids
362
+ * subscribers?: (threadKey: string) => object[], // tickets subscribed to a Thread
363
+ * knownThread?: (threadKey: string) => object|undefined, // a stored Thread record (bot_reply targets beyond this turn)
364
+ * ticketThread?: (ticketId: string) => string|undefined, // the origin Thread key of a ticket
304
365
  * running?: (sessionId: string) => boolean, // whether that conversation is working
305
366
  * loadConnector?: (kind: string) => Promise<{createConnector: Function, TEXT_LIMIT?: number}>,
306
367
  * log?: (line: string) => void,
@@ -359,12 +420,22 @@ export function createChannels(deps) {
359
420
  const notices = new Map();
360
421
  /** key → {count, lastName, lastAt} */
361
422
  const ignored = new Map();
362
- /** botId → [{text, origin, at}] channel messages handed to a bot, not yet seen in its conversation */
423
+ /** botId → [{text, origin, at, id?}] channel messages handed to a bot's home, not yet seen in its conversation */
363
424
  const pending = new Map();
364
- /** sessionId → where its replies go */
365
- const targets = new Map();
366
- /** sessionId → {timer, key, chatId, claimed} */
425
+ /** `${sessionId}|${threadKey}` → {timer, sessionId, threadKey, key, chatId, rootId, claimed}: a typing loop per Thread */
367
426
  const typing = new Map();
427
+ /** threadKey → what the latest message there told of it (who, the message to answer, the chat's title) */
428
+ const known = new Map();
429
+ /** 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) });
431
+ /** Conversations that noted a chat Thread (dropped on unpair). */
432
+ const noted = new Set();
433
+ /** Conversations whose current turn had a person's input (a chat or panel message, a scheduled run). */
434
+ const humanTurns = new Set();
435
+ /** sessionId → the Threads of its last turn with a person's input: a teammate's DM in a later turn answers there (0.7). */
436
+ const lastThreads = new Map();
437
+ /** sessionId → `${threadKey}|${text}` sent with `replyTo` this turn: the same words are not sent there twice. */
438
+ const sentThisTurn = new Map();
368
439
  /** `${key}|${chatId}` → the tail of its send queue, so parts arrive in order */
369
440
  const queues = new Map();
370
441
  let disposed = false;
@@ -513,7 +584,7 @@ export function createChannels(deps) {
513
584
  async function stopRecord(rec) {
514
585
  rec.gen = null;
515
586
  if (rec.retryTimer) clearTimeout(rec.retryTimer);
516
- for (const [sessionId, loop] of [...typing]) if (loop.key === rec.key) stopTyping(sessionId);
587
+ for (const [id, loop] of [...typing]) if (loop.key === rec.key) stopLoop(id);
517
588
  const conn = rec.conn;
518
589
  rec.conn = null;
519
590
  if (conn) {
@@ -654,76 +725,146 @@ export function createChannels(deps) {
654
725
  await reply(rec, chatId, welcomeText(owner, deps.bots()));
655
726
  return;
656
727
  }
657
- const routed = routeMessage(text, owner, deps.bots());
728
+ const roster = deps.bots();
729
+ const rootId = threadRootOf(rec.kind, msg);
730
+ const thread = threadKey(rec.kind, rec.key, { chatId, ...(rootId ? { threadId: rootId } : {}) });
731
+ const routed = routeInbound({ text, threadKey: thread }, { owner, roster, subscribers: subscribersOf });
658
732
  if (!routed.text) return;
659
- // `/new` starts the bot's next topic; text after it goes to the new one.
660
- const cmd = typeof deps.newTopic === 'function' ? topicCommand(routed.text) : null;
733
+ // A home conversation takes it (the named bot's, or the owner's); null: the tickets on the Thread do.
734
+ let home = routed.to === 'tickets' ? null : routed.bot;
735
+ let body = routed.text;
736
+ // `/new` starts the bot's next topic; text after it goes to the new one (its home, never a task's).
737
+ const cmd = typeof deps.newTopic === 'function' ? topicCommand(body) : null;
661
738
  if (cmd) {
739
+ home ??= owner;
662
740
  try {
663
- await deps.newTopic(routed.bot);
741
+ await deps.newTopic(home);
664
742
  } catch (error) {
665
743
  await reply(rec, chatId, redact(error?.message ?? error, rec.secrets).slice(0, 200));
666
744
  return;
667
745
  }
668
746
  if (!cmd.rest) {
669
- await reply(rec, chatId, newTopicText(routed.bot));
747
+ await reply(rec, chatId, newTopicText(home));
670
748
  return;
671
749
  }
672
- routed.text = cmd.rest;
750
+ body = cmd.rest;
673
751
  }
674
752
  const header = sourceHeader(rec.kind, msg);
753
+ const messageId = String(msg.messageId ?? '');
754
+ const title = msg.isDirect ? '' : cleanName(msg.chatTitle);
675
755
  const origin = {
756
+ threadKey: thread,
676
757
  key: rec.key,
677
758
  kind: rec.kind,
678
759
  chatId,
679
- ...(msg.isDirect ? {} : { replyTo: String(msg.messageId ?? '') }),
760
+ ...(rootId ? { rootId } : {}),
761
+ ...(msg.isDirect || !messageId ? {} : { replyTo: messageId }),
680
762
  who: name || person.name,
681
- body: routed.text,
763
+ ...(title ? { chatTitle: title } : {}),
764
+ ...(msg.isDirect ? { direct: true } : {}),
765
+ origin: 'chat',
766
+ body,
682
767
  };
768
+ remember(thread, origin);
769
+ const meta = { threadKey: thread, origin, ...(messageId ? { key: `chat:${rec.key}:${chatId}:${messageId}` } : {}) };
770
+
771
+ if (!home && typeof deps.toTickets === 'function') {
772
+ // A follow-up on a Thread with live tickets goes to them; the Router hears of it without waking.
773
+ try {
774
+ const sessions = (await deps.toTickets(routed.tickets, { header, body }, { ...meta, owner })) ?? [];
775
+ if (sessions[0]) startTyping(sessions[0], rec, chatId, thread, rootId, true);
776
+ return;
777
+ } catch (error) {
778
+ log(`channels: a ${rec.kind} follow-up did not reach its task (${error?.message ?? error}); @${owner.handle} takes it`);
779
+ }
780
+ }
781
+ home ??= owner;
683
782
  // Noted before the hand-over: the conversation may show the message before deliver returns.
684
- const list = (pending.get(routed.bot.id) ?? []).filter((p) => now() - p.at < PENDING_TTL_MS);
685
- const item = { text: `${header}\n${routed.text}`, origin, at: now() };
783
+ const list = (pending.get(home.id) ?? []).filter((p) => now() - p.at < PENDING_TTL_MS);
784
+ const item = { text: `${header}\n${body}`, origin, at: now() };
686
785
  list.push(item);
687
- pending.set(routed.bot.id, list);
688
- let sessionId;
786
+ pending.set(home.id, list);
787
+ const unpend = () => {
788
+ const left = pending.get(home.id) ?? [];
789
+ if (left.includes(item)) left.splice(left.indexOf(item), 1);
790
+ };
791
+ let result;
689
792
  try {
690
- sessionId = await deps.deliver(routed.bot, { header, body: routed.text });
793
+ result = await deps.deliver(home, { header, body }, meta);
691
794
  } catch (error) {
692
- const left = pending.get(routed.bot.id) ?? [];
693
- if (left.includes(item)) left.splice(left.indexOf(item), 1);
694
- log(`channels: could not hand a ${rec.kind} message to @${routed.bot.handle}: ${error?.message ?? error}`);
695
- await reply(rec, chatId, `Could not reach ${routed.bot.name}: ${redact(error?.message ?? error, rec.secrets).slice(0, 200)}`);
795
+ unpend();
796
+ log(`channels: could not hand a ${rec.kind} message to @${home.handle}: ${error?.message ?? error}`);
797
+ await reply(rec, chatId, `Could not reach ${home.name}: ${redact(error?.message ?? error, rec.secrets).slice(0, 200)}`);
696
798
  return;
697
799
  }
698
- if (sessionId) startTyping(sessionId, rec.key, chatId);
800
+ const sessionId = typeof result === 'string' ? result : result?.sessionId;
801
+ if (result && typeof result === 'object' && result.skipped) {
802
+ // Handed over once already (a replay after a restart): nothing new to work on.
803
+ unpend();
804
+ return;
805
+ }
806
+ if (result && typeof result === 'object' && typeof result.messageId === 'string') item.id = result.messageId;
807
+ if (sessionId) startTyping(sessionId, rec, chatId, thread, rootId);
808
+ }
809
+
810
+ /** Tickets subscribed to a Thread, as the host lists them; none when it cannot. */
811
+ function subscribersOf(key) {
812
+ try {
813
+ return deps.subscribers?.(key) ?? [];
814
+ } catch {
815
+ return [];
816
+ }
817
+ }
818
+
819
+ /** Keep what an inbound message told of its Thread (the newest wins; the oldest go past the limit). */
820
+ function remember(key, origin) {
821
+ if (!key) return;
822
+ const { body: _body, ...rest } = origin;
823
+ known.delete(key);
824
+ known.set(key, rest);
825
+ if (known.size > KNOWN_THREADS) known.delete(known.keys().next().value);
699
826
  }
827
+ /** An origin with what is known of its Thread filled in (who wrote there, the message to answer). */
828
+ const withKnown = (o) => (o && o.threadKey && known.has(o.threadKey) ? { ...known.get(o.threadKey), ...o } : o);
700
829
 
701
830
  // --- typing -------------------------------------------------------------------------
702
831
 
703
- function startTyping(sessionId, key, chatId) {
704
- stopTyping(sessionId);
832
+ /** "Typing…" in a Thread while `sessionId` works on its message; `claimed` loops stop when its turn ends. */
833
+ function startTyping(sessionId, rec, chatId, threadKeyOf, rootId, claimed = false) {
834
+ const id = `${sessionId}|${threadKeyOf ?? chatId}`;
835
+ stopLoop(id);
836
+ const key = rec.key;
705
837
  const started = now();
706
838
  const tick = () => {
707
839
  const conn = live.get(key)?.conn;
708
- if (!conn) return void stopTyping(sessionId);
840
+ if (!conn) return void stopLoop(id);
709
841
  Promise.resolve()
710
- .then(() => conn.typing(chatId))
842
+ .then(() => (rootId ? conn.typing(chatId, { threadId: rootId }) : conn.typing(chatId)))
711
843
  .catch(() => {});
712
844
  };
713
845
  const timer = setInterval(() => {
714
846
  const elapsed = now() - started;
715
- if (elapsed > TYPING_MAX_MS || (elapsed > typingEvery * 2 && !running(sessionId))) return void stopTyping(sessionId);
847
+ if (elapsed > TYPING_MAX_MS || (elapsed > typingEvery * 2 && !running(sessionId))) return void stopLoop(id);
716
848
  tick();
717
849
  }, typingEvery);
718
850
  timer.unref?.();
719
- typing.set(sessionId, { timer, key, chatId, claimed: false });
851
+ typing.set(id, { timer, sessionId, threadKey: threadKeyOf, key, chatId, rootId, claimed });
720
852
  tick();
721
853
  }
722
- function stopTyping(sessionId) {
723
- const loop = typing.get(sessionId);
854
+ function stopLoop(id) {
855
+ const loop = typing.get(id);
724
856
  if (!loop) return;
725
857
  clearInterval(loop.timer);
726
- typing.delete(sessionId);
858
+ typing.delete(id);
859
+ }
860
+ /** Stop the typing of `sessionId`: in one Thread, or everywhere; `claimedOnly`: only loops whose message it has seen. */
861
+ function stopTyping(sessionId, threadKeyOf, { claimedOnly = false } = {}) {
862
+ for (const [id, loop] of [...typing]) {
863
+ if (loop.sessionId !== sessionId) continue;
864
+ if (threadKeyOf && loop.threadKey !== threadKeyOf) continue;
865
+ if (claimedOnly && !loop.claimed) continue;
866
+ stopLoop(id);
867
+ }
727
868
  }
728
869
 
729
870
  // --- reply targets --------------------------------------------------------------------
@@ -743,9 +884,11 @@ export function createChannels(deps) {
743
884
  return null;
744
885
  }
745
886
 
746
- function claim(botId, text) {
887
+ /** The channel message a user message in `botId`'s conversation is: by its id when the host gave one, else by its text. */
888
+ function claim(botId, text, id) {
747
889
  const list = (pending.get(botId) ?? []).filter((p) => now() - p.at < PENDING_TTL_MS);
748
- const i = list.findIndex((p) => norm(p.text) === norm(text));
890
+ let i = id ? list.findIndex((p) => p.id === id) : -1;
891
+ if (i === -1) i = list.findIndex((p) => norm(p.text) === norm(withoutThreadNote(text)));
749
892
  if (i === -1) {
750
893
  pending.set(botId, list);
751
894
  return null;
@@ -756,6 +899,74 @@ export function createChannels(deps) {
756
899
  return hit.origin;
757
900
  }
758
901
 
902
+ /** Note an input's Thread in `sessionId`'s turn, with what is known of it. */
903
+ function noteInput(sessionId, input) {
904
+ const key = toThreadKey(input?.threadKey) ?? toThreadKey(input?.origin);
905
+ const origin = key ? { ...(known.get(key) ?? {}), ...(input?.origin ?? {}) } : input?.origin;
906
+ const stored = origins.noteInput(sessionId, { ...input, ...(key ? { threadKey: key } : {}), ...(origin ? { origin } : {}) });
907
+ if (stored && stored.kind !== 'panel') noted.add(sessionId);
908
+ return stored;
909
+ }
910
+
911
+ /**
912
+ * A Thread `bot_reply` may name outside this turn: one stored (a ticket's, or seen
913
+ * here lately) whose channel is connected and has someone paired. A panel
914
+ * conversation, a made-up key or a chat of a removed channel is none.
915
+ */
916
+ function lookupThread(ref) {
917
+ let key = null;
918
+ try {
919
+ key = ref?.thread != null ? toThreadKey(ref.thread) : toThreadKey(deps.ticketThread?.(ref?.ticket) ?? null);
920
+ } catch {
921
+ key = null;
922
+ }
923
+ if (!key || isPanelThread(key)) return null;
924
+ let stored = known.get(key);
925
+ if (!stored) {
926
+ try {
927
+ stored = deps.knownThread?.(key);
928
+ } catch {
929
+ stored = undefined;
930
+ }
931
+ }
932
+ if (!stored) return null;
933
+ const p = parseThreadKey(key);
934
+ if (!p?.appKey || !live.get(p.appKey)?.conn) return null;
935
+ if (!(data.channels[p.appKey]?.paired ?? []).length) return null;
936
+ return { ...(known.get(key) ?? {}), threadKey: key };
937
+ }
938
+
939
+ /** 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) {
941
+ const rec = live.get(target.key ?? target.appKey);
942
+ stopTyping(sessionId, target.threadKey);
943
+ if (!rec?.conn) {
944
+ log(`channels: a reply for ${target.kind} was not sent: the channel is not connected`);
945
+ return false;
946
+ }
947
+ const plain = rec.mod?.MARKDOWN === true || RENDERS_MARKDOWN.has(target.kind) ? String(text).trim() : toPlainText(text);
948
+ const root = target.rootId ? String(target.rootId) : '';
949
+ const replyTo = target.replyTo ? String(target.replyTo) : '';
950
+ void enqueue(rec, target.chatId, async () => {
951
+ let first = true;
952
+ for (const part of splitText(plain, rec.limit)) {
953
+ if (!rec.conn) break;
954
+ // A chat app that threads replies (Slack) keeps `replyTo` on every part; elsewhere only the first part quotes.
955
+ 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);
957
+ first = false;
958
+ }
959
+ });
960
+ return true;
961
+ }
962
+
963
+ /** Who a chat target is, for the timeline: `{key, kind, chatId, threadKey, who, …}` without the message body. */
964
+ const targetView = (o) => {
965
+ if (!o) return null;
966
+ const { body: _body, tickets: _tickets, ...rest } = o;
967
+ return rest;
968
+ };
969
+
759
970
  /** Links a connector module offers the panel (a deep link to pair, an invite). */
760
971
  function linksOf(rec, account, code) {
761
972
  if (typeof rec?.mod?.links !== 'function' || !account) return {};
@@ -771,71 +982,125 @@ export function createChannels(deps) {
771
982
  sync,
772
983
 
773
984
  /**
774
- * A message entered `bot`'s conversation. A channel message makes that chat
775
- * the reply target (and returns where it came from); any other user message
776
- * (the panel) takes replies back to the panel. A scheduled run reports to
777
- * the channel's first paired person when the channel allows it.
985
+ * A message entered `bot`'s home conversation; its Thread joins the turn's
986
+ * (lib/threads.mjs `createOrigins`). A channel message adds its chat Thread
987
+ * (and returns where it came from, with `body`); any other user message adds
988
+ * the panel. A scheduled run adds the DM of the channel's first paired
989
+ * person when the channel allows it. A teammate's DM (`agent-message`, not a
990
+ * ticket's report: `report`) in a turn with no other input answers where the
991
+ * last turn with a person's input did, as in 0.7. Reports and notices about
992
+ * tickets are noted by the host with `noteInput` (the ticket's origin Thread).
778
993
  * @param {string} sessionId
779
994
  * @param {object} bot
780
995
  * @param {string} kind - the message source kind ('user', 'schedule', 'agent-message', …)
781
996
  * @param {string} text - the message text
997
+ * @param {{id?: string, report?: boolean}} [opts] - `id`: the message id (a delivery made with a key)
782
998
  */
783
- noteUserMessage(sessionId, bot, kind, text) {
999
+ noteUserMessage(sessionId, bot, kind, text, opts = {}) {
784
1000
  if (!sessionId || !bot) return null;
785
1001
  if (kind === 'user') {
786
- const origin = claim(bot.id, text);
1002
+ humanTurns.add(sessionId);
1003
+ const origin = claim(bot.id, text, opts.id);
787
1004
  if (origin) {
788
- targets.set(sessionId, { key: origin.key, kind: origin.kind, chatId: origin.chatId, ...(origin.replyTo ? { replyTo: origin.replyTo } : {}), who: origin.who, origin: 'chat' });
789
- const loop = typing.get(sessionId);
790
- if (loop) loop.claimed = true;
1005
+ noteInput(sessionId, { threadKey: origin.threadKey, origin: targetView(origin) });
1006
+ for (const loop of typing.values()) if (loop.sessionId === sessionId && loop.threadKey === origin.threadKey) loop.claimed = true;
791
1007
  return origin;
792
1008
  }
793
- targets.delete(sessionId);
1009
+ noteInput(sessionId, {});
794
1010
  return null;
795
1011
  }
796
1012
  if (kind === 'schedule') {
1013
+ humanTurns.add(sessionId);
797
1014
  const t = scheduleTarget(bot);
798
- if (t) targets.set(sessionId, t);
799
- else targets.delete(sessionId);
1015
+ const key = t ? threadKey(t.kind, t.key, { chatId: t.chatId }) : null;
1016
+ if (key) noteInput(sessionId, { threadKey: key, origin: { ...t, threadKey: key } });
1017
+ return null;
1018
+ }
1019
+ if (kind === 'agent-message' && !opts.report && origins.current(sessionId).length === 0) {
1020
+ for (const o of lastThreads.get(sessionId) ?? []) noteInput(sessionId, { threadKey: o.threadKey, origin: targetView(o) });
800
1021
  }
801
1022
  return null;
802
1023
  },
803
1024
 
804
1025
  /**
805
- * A user-facing reply of the conversation `sessionId`: sent to its chat when
806
- * its latest human input came from one. Returns the target (or null) at once;
807
- * sending continues in the background.
1026
+ * Another input of `sessionId`'s turn: a ticket's report or notice (pass the
1027
+ * ticket's origin Thread as `threadKey`, and `ticket`). Returns the origin as stored.
1028
+ */
1029
+ noteInput,
1030
+
1031
+ /** `{mode: 'panel' | 'thread' | 'choose', target, origins}` for `sessionId`'s plain replies now (lib/threads.mjs). */
1032
+ replyPlan(sessionId) {
1033
+ const plan = origins.replyPlan(sessionId);
1034
+ return { ...plan, target: withKnown(plan.target), origins: plan.origins.map(withKnown) };
1035
+ },
1036
+
1037
+ /** The distinct Threads of `sessionId`'s turn, in the order they arrived. */
1038
+ current(sessionId) {
1039
+ return origins.current(sessionId).map(withKnown);
1040
+ },
1041
+
1042
+ /**
1043
+ * A plain reply of the conversation `sessionId`: sent to its turn's one chat
1044
+ * Thread (`replyPlan` mode `thread`), in that Thread. Returns the target (or
1045
+ * null: the panel) at once; sending continues in the background. Words
1046
+ * `replyTo` already sent there this turn are not sent again.
808
1047
  */
809
1048
  noteReply(sessionId, text) {
810
- const target = targets.get(sessionId);
811
- if (!target || !String(text ?? '').trim()) return null;
812
- const rec = live.get(target.key);
813
- stopTyping(sessionId);
814
- if (!rec?.conn) {
815
- log(`channels: a reply for ${target.kind} was not sent: the channel is not connected`);
816
- return null;
817
- }
818
- const plain = rec.mod?.MARKDOWN === true || RENDERS_MARKDOWN.has(target.kind) ? String(text).trim() : toPlainText(text);
819
- void enqueue(rec, target.chatId, async () => {
820
- let first = true;
821
- for (const part of splitText(plain, rec.limit)) {
822
- if (!rec.conn) break;
823
- // A chat app that threads replies (Slack) keeps every part in the thread; elsewhere only the first part quotes.
824
- await rec.conn.send(target.chatId, part, target.replyTo && (first || rec.mod?.THREADS === true) ? { replyTo: target.replyTo } : undefined);
825
- first = false;
826
- }
827
- });
828
- return target;
1049
+ if (!String(text ?? '').trim()) return null;
1050
+ const plan = origins.replyPlan(sessionId);
1051
+ if (plan.mode !== 'thread') return null;
1052
+ const target = withKnown(plan.target);
1053
+ if (sentThisTurn.get(sessionId)?.has(`${target.threadKey}|${norm(text)}`)) return targetView(target);
1054
+ return sendText(sessionId, target, text) ? targetView(target) : null;
1055
+ },
1056
+
1057
+ /**
1058
+ * The Thread `bot_reply` names from `sessionId` (a thread key or a ticket id,
1059
+ * see lib/threads.mjs `resolve`): this turn's Threads first, then stored ones
1060
+ * with a connected channel and someone paired. Null when unknown.
1061
+ */
1062
+ resolveReply(sessionId, ref) {
1063
+ return targetView(withKnown(origins.resolve(sessionId, ref)));
1064
+ },
1065
+
1066
+ /**
1067
+ * Send `text` from `sessionId` to a chat Thread (`resolveReply`'s answer).
1068
+ * Throws when the channel is not connected. Returns the target.
1069
+ */
1070
+ replyTo(sessionId, target, text) {
1071
+ if (!target || target.kind === 'panel' || !target.chatId) throw new Error('no chat to send to');
1072
+ if (!String(text ?? '').trim()) throw new Error('text must not be empty');
1073
+ if (!sendText(sessionId, target, text)) throw new Error(`${CHANNEL_LABELS[target.kind] ?? target.kind} is not connected right now; the reply was not sent`);
1074
+ const sent = sentThisTurn.get(sessionId) ?? new Set();
1075
+ sent.add(`${target.threadKey}|${norm(text)}`);
1076
+ sentThisTurn.set(sessionId, sent);
1077
+ return targetView(target);
1078
+ },
1079
+
1080
+ /** What is known of a chat Thread from its latest message (who, chat title, …), or undefined. */
1081
+ threadInfo(key) {
1082
+ return known.has(key) ? { ...known.get(key) } : undefined;
829
1083
  },
830
1084
 
831
- /** A turn of `sessionId` ended: the typing indicator of the message it answered stops. */
1085
+ /**
1086
+ * A turn of `sessionId` ended: the typing indicators of the messages it saw
1087
+ * stop, and its Threads are forgotten (a teammate's DM in a later turn still
1088
+ * answers where its last human input came from).
1089
+ */
832
1090
  noteTurnEnd(sessionId) {
833
- if (typing.get(sessionId)?.claimed) stopTyping(sessionId);
1091
+ stopTyping(sessionId, undefined, { claimedOnly: true });
1092
+ const ended = origins.endTurn(sessionId);
1093
+ if (humanTurns.delete(sessionId)) {
1094
+ if (ended.length) lastThreads.set(sessionId, ended);
1095
+ else lastThreads.delete(sessionId);
1096
+ }
1097
+ sentThisTurn.delete(sessionId);
1098
+ if (origins.current(sessionId).length === 0) noted.delete(sessionId);
834
1099
  },
835
1100
 
836
- /** Where `sessionId`'s replies go now, if to a chat. */
1101
+ /** Where `sessionId`'s plain replies go now, if to one chat. */
837
1102
  targetOf(sessionId) {
838
- return targets.get(sessionId) ?? null;
1103
+ return targetView(withKnown(origins.replyTarget(sessionId)));
839
1104
  },
840
1105
 
841
1106
  /** What the panel shows of `bot`'s channels: {[appId]: ChannelView}. */
@@ -885,7 +1150,17 @@ export function createChannels(deps) {
885
1150
  record.paired = record.paired.filter((p) => p.id !== String(userId));
886
1151
  if (record.paired.length === before) return false;
887
1152
  save();
888
- for (const [sessionId, t] of [...targets]) if (t.key === keyOf(botId, appId)) targets.delete(sessionId);
1153
+ // Replies stop going to this channel's chats: a turn's Threads are dropped whole (never one of several).
1154
+ const app = keyOf(botId, appId);
1155
+ const ofApp = (o) => o?.kind !== 'panel' && (o?.key ?? o?.appKey) === app;
1156
+ for (const sessionId of [...noted]) {
1157
+ if (origins.current(sessionId).some(ofApp)) {
1158
+ origins.endTurn(sessionId);
1159
+ noted.delete(sessionId);
1160
+ }
1161
+ }
1162
+ for (const [sessionId, list] of [...lastThreads]) if (list.some(ofApp)) lastThreads.delete(sessionId);
1163
+ for (const [key, o] of [...known]) if (ofApp(o)) known.delete(key);
889
1164
  return true;
890
1165
  },
891
1166
 
@@ -913,7 +1188,7 @@ export function createChannels(deps) {
913
1188
  /** Stop every connector; nothing restarts afterwards. */
914
1189
  async stopAll() {
915
1190
  disposed = true;
916
- for (const sessionId of [...typing.keys()]) stopTyping(sessionId);
1191
+ for (const id of [...typing.keys()]) stopLoop(id);
917
1192
  const recs = [...live.values()];
918
1193
  live.clear();
919
1194
  await Promise.all(recs.map((rec) => stopRecord(rec)));