@kadaliao/dsh-bots 0.8.0 → 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.
package/lib/cards.mjs CHANGED
@@ -273,6 +273,49 @@ export function followUpNoticeText(notice, ctx = {}) {
273
273
  ].join('\n');
274
274
  }
275
275
 
276
+ /**
277
+ * Bots 0.9: a worker's report went to the person as it is, in the topic or chat its task came
278
+ * from. Its requester is told without being woken (the note is "good to know"): it need not pass
279
+ * the result on, and a `question` is the person's to answer there.
280
+ * @param {object} ticket
281
+ * @param {{status?: string, text?: string}} report
282
+ * @param {CardContext & {where?: string}} [ctx] - `where`: how that topic or chat reads ("Panel · topic …")
283
+ */
284
+ export function shownNoticeText(ticket, report, ctx = {}) {
285
+ const status = report?.status ?? 'done';
286
+ const next =
287
+ status === 'done'
288
+ ? 'The task is done. This needs no reply: do not repeat the result.'
289
+ : status === 'question'
290
+ ? 'The person answers it there, and the answer goes to the task directly. This needs no reply from you.'
291
+ : 'The person sees it there. It needs no reply from you, unless you can unblock the task: then add to it with bot_send_message (ticket: its id).';
292
+ return [
293
+ `[Shown] ${handleOf(ctx.bots, ticket.botId)}'s report on task ${ticketPhrase(ticket, ctx)} — status: ${status} — went to the person as it is${ctx.where ? `, in ${ctx.where}` : ''}:`,
294
+ quote(clip(String(report?.text ?? '').trim(), PREVIEW_CHARS).text),
295
+ next,
296
+ ].join('\n');
297
+ }
298
+
299
+ /** How many tasks a panel message header lists for the dispatcher. */
300
+ export const HEADER_TASKS = 8;
301
+
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
308
+ * @param {CardContext} [ctx]
309
+ */
310
+ export function panelHeaderText({ topic, replyTo, open = [] } = {}, ctx = {}) {
311
+ const lines = [`[Panel]${topic ? ` (thread ${topic})` : ''}`];
312
+ const quoted = String(replyTo?.text ?? '').trim();
313
+ if (quoted) lines.push(`In reply to ${replyTo.who || 'a message'}: ${quote(clip(quoted, 160).text)}`);
314
+ const listed = open.slice(0, HEADER_TASKS);
315
+ if (listed.length) lines.push(`Open tasks: ${listed.map((t) => ticketPhrase(t, ctx)).join('; ')}`);
316
+ return lines.join('\n');
317
+ }
318
+
276
319
  /**
277
320
  * Prepended when a ticket that was working is restarted after Harness came
278
321
  * back: look before repeating anything that left the conversation.
package/lib/channels.mjs CHANGED
@@ -994,12 +994,17 @@ export function createChannels(deps) {
994
994
  * @param {object} bot
995
995
  * @param {string} kind - the message source kind ('user', 'schedule', 'agent-message', …)
996
996
  * @param {string} text - the message text
997
- * @param {{id?: string, report?: boolean}} [opts] - `id`: the message id (a delivery made with a key)
997
+ * @param {{id?: string, report?: boolean, threadKey?: string}} [opts] - `id`: the message id (a delivery made
998
+ * with a key); `threadKey`: the panel topic a message typed in the panel belongs to (Bots 0.9)
998
999
  */
999
1000
  noteUserMessage(sessionId, bot, kind, text, opts = {}) {
1000
1001
  if (!sessionId || !bot) return null;
1001
1002
  if (kind === 'user') {
1002
1003
  humanTurns.add(sessionId);
1004
+ if (opts.threadKey) {
1005
+ noteInput(sessionId, { threadKey: opts.threadKey, ...(opts.origin ? { origin: opts.origin } : {}) });
1006
+ return null;
1007
+ }
1003
1008
  const origin = claim(bot.id, text, opts.id);
1004
1009
  if (origin) {
1005
1010
  noteInput(sessionId, { threadKey: origin.threadKey, origin: targetView(origin) });
@@ -1049,6 +1054,8 @@ export function createChannels(deps) {
1049
1054
  if (!String(text ?? '').trim()) return null;
1050
1055
  const plan = origins.replyPlan(sessionId);
1051
1056
  if (plan.mode !== 'thread') return null;
1057
+ // A topic in the panel: the timeline is where it is shown, nothing is sent.
1058
+ if (plan.target.kind === 'panel') return targetView(plan.target);
1052
1059
  const target = withKnown(plan.target);
1053
1060
  if (sentThisTurn.get(sessionId)?.has(`${target.threadKey}|${norm(text)}`)) return targetView(target);
1054
1061
  return sendText(sessionId, target, text) ? targetView(target) : null;
@@ -1077,6 +1084,34 @@ export function createChannels(deps) {
1077
1084
  return targetView(target);
1078
1085
  },
1079
1086
 
1087
+ /**
1088
+ * One of `sessionId`'s turn Threads turned out to belong to another (lib/threads.mjs
1089
+ * `retarget`): plain replies go to `to` instead. Returns the stored origin, or null.
1090
+ */
1091
+ retarget(sessionId, from, to, origin) {
1092
+ return origins.retarget(sessionId, from, to, origin);
1093
+ },
1094
+
1095
+ /**
1096
+ * Post `text` to a chat Thread outside any turn (Bots 0.9: a worker's report shown where its
1097
+ * task came from). `ref`: `{thread}` (a key) and `replyTo` (the chat message to quote, when the
1098
+ * chat app threads by replies). The Thread must be known here or stored, its channel connected
1099
+ * and someone paired (see `lookupThread`). Typing shown there for `typingOf` (a Session) stops.
1100
+ * Returns the target, or null when it cannot be reached.
1101
+ */
1102
+ post(ref, text, { replyTo = '', typingOf = '' } = {}) {
1103
+ if (!String(text ?? '').trim()) return null;
1104
+ const found = lookupThread(ref);
1105
+ if (!found) return null;
1106
+ // What the key itself says (kind, app, chat, root), under what was seen of the Thread lately.
1107
+ const p = parseThreadKey(found.threadKey);
1108
+ const fromKey = { kind: p.kind, key: p.appKey, appKey: p.appKey, chatId: p.chatId, ...(p.rootId !== undefined ? { rootId: p.rootId } : {}) };
1109
+ const target = withKnown({ ...fromKey, ...found, ...(replyTo ? { replyTo: String(replyTo) } : {}) });
1110
+ const sent = sendText(typingOf || '', target, text);
1111
+ if (typingOf) stopTyping(typingOf, target.threadKey);
1112
+ return sent ? targetView(target) : null;
1113
+ },
1114
+
1080
1115
  /** What is known of a chat Thread from its latest message (who, chat title, …), or undefined. */
1081
1116
  threadInfo(key) {
1082
1117
  return known.has(key) ? { ...known.get(key) } : undefined;
package/lib/prompt.mjs CHANGED
@@ -31,10 +31,10 @@ const HANDS_ON_TEAM = [
31
31
  MANAGE_LINE,
32
32
  ];
33
33
 
34
- /** "Working with other bots" as a router dispatcher reads it. */
35
- const ROUTER_TEAM = [
36
- '- Hand work to another bot with `bot_send_message` (to: its @handle). Each message opens a task (ticket) for that bot, which works on it in a conversation of its own; the call returns at once with the ticket id and stage. To add to a task that is still open, pass `ticket` (its id) instead of `to`.',
37
- '- Keep messages self-contained: the other bot cannot see your conversation.',
34
+ /** "Working with other bots" as a router dispatcher reads it (`self`: its own @handle). */
35
+ const routerTeam = (self) => [
36
+ `- Hand work to a bot with \`bot_send_message\` (to: its @handle, or your own, @${self}, when no teammate fits: you then do it yourself in a task conversation of your own, with all your tools). Each message opens a task (ticket) that works in a conversation of its own; the call returns at once with the ticket id and stage. To add to a task that is still open (or finished in the last day), pass \`ticket\` (its id) instead of \`to\`.`,
37
+ '- Keep messages self-contained: the bot (you too, in a task) cannot see this conversation.',
38
38
  SCHEDULE_NOTICE_LINE,
39
39
  LANGUAGE_LINE,
40
40
  MANAGE_LINE,
@@ -42,7 +42,8 @@ const ROUTER_TEAM = [
42
42
 
43
43
  /** "Working with other bots" as a bot's own home reads it when delegating opens tasks (router mode), the dispatcher aside. */
44
44
  const HOME_TICKETS_TEAM = [
45
- '- Message another bot with `bot_send_message` (to: its @handle). That opens a task (ticket) for it, which it works on in a conversation of its own; the call returns at once, and its answer comes back to you as a "Report from @… on task …" message. Never wait or poll for it. To add to a task you opened, pass `ticket` (its id) instead of `to`.',
45
+ '- Message another bot with `bot_send_message` (to: its @handle). That opens a task (ticket) for it, which it works on in a conversation of its own; the call returns at once. Never wait or poll for its answer. To add to a task you opened, pass `ticket` (its id) instead of `to`.',
46
+ '- When the request came from the person (a topic in the panel, or a chat), that bot answers them there itself and you get a "[Shown]" note, which needs no reply. Pass `report_to: "me"` when you need the result back yourself; it then arrives as a "Report from @… on task …" message.',
46
47
  '- A message that starts with "Report from @…" or "Bot message from @…" was sent by that bot, not by the user. Pass a report\'s result on to whoever asked; a `question` or `blocked` report needs an answer with `bot_send_message` (ticket: its id).',
47
48
  '- Keep messages self-contained: the other bot cannot see your conversation.',
48
49
  SCHEDULE_NOTICE_LINE,
@@ -71,6 +72,19 @@ function requesterPhrase(ticket, roster) {
71
72
  return handle;
72
73
  }
73
74
 
75
+ /**
76
+ * Whether a ticket's `done`, `question` and `blocked` reports are posted as they are in the topic
77
+ * or chat its request came from (Bots 0.9), rather than handed to whoever asked to pass on: it has
78
+ * a Thread, it is no sub-task, and its requester did not ask for the reports (`relay`).
79
+ */
80
+ export function reportsGoDirect(ticket) {
81
+ const t = ticket ?? {};
82
+ return !t.relay && Boolean(t.origin?.threadKey) && !t.parentId && !t.requester?.ticketId;
83
+ }
84
+
85
+ /** Where a ticket's direct reports are shown, as its worker reads it. */
86
+ const shownWhere = (ticket) => (String(ticket.origin?.threadKey ?? '').startsWith('panel:') ? 'in the panel, in the topic the request came from' : `in the chat${ticket.origin?.via ? ` (${ticket.origin.via})` : ''} the request came from`);
87
+
74
88
  /** `, for Kada on Slack` from a ticket's origin, or ''. */
75
89
  function originPhrase(ticket) {
76
90
  const { who, via } = ticket.origin ?? {};
@@ -100,14 +114,20 @@ export function personaText(bot, roster, extra = {}) {
100
114
  lines.push('', '## The bot team');
101
115
  lines.push(roster.length > 1 ? 'These bots work for the same user and can message each other:' : 'You are the only bot so far.');
102
116
  if (roster.length > 1) for (const b of roster) lines.push(rosterLine(b, bot.id));
103
- lines.push('', '## Working with other bots', ...(ticket ? TICKET_TEAM : router ? ROUTER_TEAM : homeTickets ? HOME_TICKETS_TEAM : HANDS_ON_TEAM));
117
+ lines.push('', '## Working with other bots', ...(ticket ? TICKET_TEAM : router ? routerTeam(bot.handle) : homeTickets ? HOME_TICKETS_TEAM : HANDS_ON_TEAM));
104
118
  if (ticket) {
119
+ const direct = reportsGoDirect(ticket);
105
120
  lines.push(
106
121
  '',
107
122
  '## This conversation is one task',
108
123
  `It is task ${ticket.id}: "${String(ticket.title ?? '').trim()}", asked by ${requesterPhrase(ticket, roster)}${originPhrase(ticket)}. Its first message says what to do.`,
109
124
  '- Report to whoever asked with `bot_send_message`: leave out `to` and give a `status`, which is required — `progress` for an update worth keeping, `done` with the result when you are finished, `blocked` when you cannot go on, `question` when you need an answer.',
110
- '- Your plain text reaches no one: only reports do. Put everything the requester needs in the report (it cannot see this conversation); after a `done` report, end your turn without a summary.',
125
+ ...(direct
126
+ ? [
127
+ `- Your \`done\`, \`question\` and \`blocked\` reports are shown to the person as they are, ${shownWhere(ticket)}, and whoever asked is told. Write them for the person: the whole answer, in their language, nothing addressed to a bot. Their replies come back here.`,
128
+ '- Your plain text reaches no one: only reports do. Put everything the person needs in the report (nobody sees this conversation); after a `done` report, end your turn without a summary.',
129
+ ]
130
+ : ['- Your plain text reaches no one: only reports do. Put everything the requester needs in the report (it cannot see this conversation); after a `done` report, end your turn without a summary.']),
111
131
  '- Asking another bot opens a sub-task; its report comes back here by itself.',
112
132
  '- Messages from the person about this task may arrive here directly. Take them into account and answer them in a report.',
113
133
  `- \`bot_recall\` reads this task (\`ticket/${ticket.id}\`), its parent and sub-tasks, and the threads it belongs to.`,
@@ -116,13 +136,15 @@ export function personaText(bot, roster, extra = {}) {
116
136
  lines.push(
117
137
  '',
118
138
  '## You are the dispatcher',
119
- 'The user treats you as the main bot, and you run the team. You do three things: understand what the person wants, hand the work out, and report back. Do not do the work yourself, not even small tasks: your own tools are for reading and looking things up. When no bot fits a recurring kind of work, propose creating one.',
120
- '- Every delegation with `bot_send_message` opens a task (ticket) for that bot and returns at once. Hand independent parts to several bots in parallel, tell the person in one line who is on it, and end your turn.',
121
- '- Reports ("Report from @…"), follow-up notices ("[follow_up]") and new messages arrive by themselves. Never wait, sleep or poll for them: end your turn, and you are woken when something arrives.',
122
- '- When a report arrives, pass the result on to whoever asked. A `question` or `blocked` report needs an answer: give it with `bot_send_message` (ticket: its id), or ask the person. A follow-up notice needs no reply: the message already went to the task; stop the task only if the person asks.',
123
- '- When a turn involves more than one chat, answer each with `bot_reply` (ticket or thread, and text) so every answer reaches its own chat; plain text then stays in the panel.',
139
+ 'The user treats you as the main bot, and you run the team as its front desk. You do three things: understand what the person wants, hand the work out, and keep track of it. Every message gets your answer within a step or two, so you never do the work in this conversation, not even a quick lookup: searching the web, reading or changing files and running anything is a task (yours, when no teammate fits). When no bot fits a recurring kind of work, propose creating one.',
140
+ '- Every message is its own request, with its topic or chat in its header ("[Panel] (thread p…)", "[Telegram · Kada] (thread …)"), unless it clearly continues one of the open tasks listed with it. When several messages arrive together, handle every one of them: never drop a request because another came after it.',
141
+ '- For each request do one of these, then end your turn: answer it yourself when you can from what you already know (a greeting, a quick fact, a question about the team or its tasks); hand it out with `bot_send_message` and say in one line who is on it; or, when it continues an open task, add it to that task with `bot_send_message` (ticket: its id), which files the message under that task\'s topic.',
142
+ '- Every delegation with `bot_send_message` opens a task (ticket) for that bot and returns at once. Hand independent parts to several bots in parallel.',
143
+ '- The bot doing a task answers the person itself, in the topic or chat the request came from, and the person\'s replies there go straight to it. You get a "[Shown]" note: it needs no reply, so do not repeat the result. Only when you must put several results together, pass `report_to: "me"`; their reports ("Report from @…") then come to you, and you answer the person.',
144
+ '- Reports, notes ("[Shown]", "[follow_up]") and new messages arrive by themselves. Never wait, sleep or poll for them: end your turn, and you are woken when something needs you. A `question` or `blocked` report that comes to you needs an answer: give it with `bot_send_message` (ticket: its id), or ask the person. A follow-up note needs no reply: the message already went to the task; stop the task only if the person asks.',
145
+ '- When a turn involves more than one topic or chat, answer each with `bot_reply` (thread: the id its header shows, or ticket: a task id) so every answer stays in its own topic; plain text then reaches none of them.',
124
146
  '- Use `bot_recall` to look up tasks and threads (`tickets`, `ticket/<id>`, `thread/<key>`, `bot/<handle>`) instead of guessing.',
125
- '- Keep chat replies short: 100 words at most, no tables.',
147
+ '- Keep your own replies short: 100 words at most, no tables.',
126
148
  SCHEDULE_LINE,
127
149
  );
128
150
  } else if (bot.role === 'primary') {
@@ -153,7 +175,9 @@ export function personaText(bot, roster, extra = {}) {
153
175
  if (extra.channels?.length) {
154
176
  const first = extra.channels[0];
155
177
  const how = ticket
156
- ? 'It is a follow-up about this task. Your plain text does not reach that chat: answer in a report, and the requester passes it on.'
178
+ ? reportsGoDirect(ticket)
179
+ ? 'It is a follow-up about this task. Your plain text does not reach that chat: answer in a report, which is posted there.'
180
+ : 'It is a follow-up about this task. Your plain text does not reach that chat: answer in a report, and the requester passes it on.'
157
181
  : 'Treat it like any request from the user: your reply is sent back to that chat as plain text, so keep it short, skip tables, and say plainly what you did or who is on it.';
158
182
  lines.push(
159
183
  '',
@@ -285,11 +309,12 @@ const OTHER_WORK_TOOLS = ['pwsh', 'terminal_open', 'terminal_send', 'terminal_re
285
309
  * Tools a router dispatcher is denied by default: running commands (and the
286
310
  * job tools that go with them; `pwsh` and the terminals too), writing and
287
311
  * editing files (`apply_patch` and `str_replace_editor` too), sub-agents and
288
- * workflows, image generation and Office tools. It keeps `read`,
289
- * `read_image`, `glob`, `grep`, `skill`, `web_search` and `web_fetch`.
312
+ * workflows, image generation and Office tools, and (0.9) the web: a search
313
+ * takes long enough to keep the person waiting, so it is a task too. It keeps
314
+ * `read`, `read_image`, `glob`, `grep` and `skill`.
290
315
  */
291
316
  export const ROUTER_DENY = Object.freeze([
292
- ...new Set([...abilityTools('code'), 'write', 'edit', ...abilityTools('delegate'), ...abilityTools('images'), ...abilityTools('office'), ...OTHER_WORK_TOOLS]),
317
+ ...new Set([...abilityTools('code'), 'write', 'edit', ...abilityTools('delegate'), ...abilityTools('images'), ...abilityTools('office'), ...abilityTools('web'), ...OTHER_WORK_TOOLS]),
293
318
  ]);
294
319
 
295
320
  /** Longest `bash` / `pwsh` timeout a router may ask for, in ms. */
package/lib/store.mjs CHANGED
@@ -276,12 +276,24 @@ export function createStore(dir) {
276
276
  if (messages !== null && now === logSeen) return messages;
277
277
  logSeen = now;
278
278
  messages = [];
279
+ const index = new Map();
279
280
  try {
280
281
  for (const line of readFileSync(log, 'utf8').split('\n')) {
281
282
  if (!line) continue;
282
283
  try {
283
284
  const m = JSON.parse(line);
284
- if (m && typeof m.id === 'string') messages.push(m);
285
+ if (!m || typeof m.id !== 'string') continue;
286
+ // A later line changing an earlier message (`patchMessage`): merged into it.
287
+ if (m.patch === true) {
288
+ const at = index.get(m.id);
289
+ if (at !== undefined) {
290
+ const { id: _id, patch: _patch, ...fields } = m;
291
+ Object.assign(messages[at], fields);
292
+ }
293
+ continue;
294
+ }
295
+ index.set(m.id, messages.length);
296
+ messages.push(m);
285
297
  } catch {
286
298
  // Skip a torn line.
287
299
  }
@@ -406,11 +418,49 @@ export function createStore(dir) {
406
418
  }
407
419
  return m;
408
420
  },
409
- /** Oldest first; `bot` limits to messages from or to that bot. */
410
- messages({ bot = '', limit = 200 } = {}) {
421
+ /**
422
+ * Change fields of a logged message (`movedTo` when it was filed under another topic, …):
423
+ * an appended line, merged when the log is read. Returns the message as it is now, or null.
424
+ */
425
+ patchMessage(id, fields = {}) {
411
426
  const all = readLog();
412
- const rows = bot ? all.filter((m) => m.from === bot || m.to === bot) : all;
413
- return rows.slice(-Math.max(1, Math.min(2000, limit)));
427
+ const m = all.find((x) => x.id === id);
428
+ if (!m) return null;
429
+ const { id: _id, patch: _patch, ...rest } = fields;
430
+ Object.assign(m, rest);
431
+ try {
432
+ mkdirSync(dir, { recursive: true });
433
+ appendFileSync(log, JSON.stringify({ id, patch: true, ...rest }) + '\n', 'utf8');
434
+ logSeen = mtime(log);
435
+ } catch {
436
+ // The timeline is a convenience.
437
+ }
438
+ return { ...m };
439
+ },
440
+ /** One logged message by id, or undefined. */
441
+ message(id) {
442
+ const m = readLog().find((x) => x.id === id);
443
+ return m ? { ...m } : undefined;
444
+ },
445
+ /**
446
+ * Oldest first. `bot` limits to that bot's chat: messages that name it as their `chat`, and
447
+ * those with no `chat` sent from or to it. `topic` limits to one panel topic: its first
448
+ * message, the replies in it and the messages filed under it (`movedTo`). Without `topic`, a
449
+ * reply in the window whose topic began earlier brings that first message along, before the rest.
450
+ */
451
+ messages({ bot = '', limit = 200, topic = '' } = {}) {
452
+ const all = readLog();
453
+ // A message that was never handed over (`hidden`) is in no chat.
454
+ const mine = (m) => !m.hidden && (!bot || (m.chat ? m.chat === bot : m.from === bot || m.to === bot));
455
+ const cap = Math.max(1, Math.min(2000, Number(limit) || 200));
456
+ if (topic) return all.filter((m) => mine(m) && (m.id === topic || m.topic === topic || m.movedTo === topic)).slice(-cap);
457
+ const rows = all.filter(mine);
458
+ const window = rows.slice(-cap);
459
+ const have = new Set(window.map((m) => m.id));
460
+ const missing = new Set();
461
+ for (const m of window) for (const r of [m.topic, m.movedTo]) if (r && !have.has(r)) missing.add(r);
462
+ if (missing.size === 0) return window;
463
+ return [...rows.filter((m) => missing.has(m.id)), ...window];
414
464
  },
415
465
  messageCount() {
416
466
  return readLog().length;
package/lib/threads.mjs CHANGED
@@ -6,8 +6,11 @@
6
6
  * conversation in the panel. Its key is `kind:appKey:chatId[:rootId]`
7
7
  * (`appKey` is the channel's record key in channels.mjs, `botId/appId`); a
8
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.
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.
11
14
  *
12
15
  * This module decides, with no I/O:
13
16
  *
@@ -17,10 +20,10 @@
17
20
  * woken); otherwise the Router (the channel owner's home) does;
18
21
  * - where a conversation's plain replies go (`createOrigins`): each turn
19
22
  * 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`).
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`).
24
27
  *
25
28
  * @module @kadaliao/dsh-bots/lib/threads
26
29
  */
@@ -52,7 +55,7 @@ const unesc = (s) => s.replace(/%(25|3A)/gi, (_, c) => (c === '25' ? '%' : ':'))
52
55
  */
53
56
  export function threadKey(kind, appKey, msg = {}) {
54
57
  const k = part(kind);
55
- if (k === PANEL) return panelThreadKey(msg?.sessionId ?? msg?.chatId);
58
+ if (k === PANEL) return panelThreadKey(msg?.sessionId ?? msg?.chatId, msg?.rootId ?? msg?.threadId);
56
59
  if (!KIND_RE.test(k)) return null;
57
60
  const app = part(appKey);
58
61
  const chat = part(msg?.chatId);
@@ -61,15 +64,20 @@ export function threadKey(kind, appKey, msg = {}) {
61
64
  return [k, esc(app), esc(chat), ...(root ? [esc(root)] : [])].join(':');
62
65
  }
63
66
 
64
- /** The thread of a home conversation in the panel: replies to it stay in the panel. */
65
- export function panelThreadKey(sessionId) {
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) {
66
72
  const s = part(sessionId);
67
- return s ? `${PANEL}:${esc(s)}` : null;
73
+ if (!s) return null;
74
+ const r = part(rootId);
75
+ return r ? `${PANEL}:${esc(s)}:${esc(r)}` : `${PANEL}:${esc(s)}`;
68
76
  }
69
77
 
70
78
  /**
71
79
  * A thread key taken apart.
72
- * @returns {{kind: string, appKey: string, chatId: string, rootId?: string} | {kind: 'panel', sessionId: string} | null}
80
+ * @returns {{kind: string, appKey: string, chatId: string, rootId?: string} | {kind: 'panel', sessionId: string, rootId?: string} | null}
73
81
  */
74
82
  export function parseThreadKey(key) {
75
83
  if (typeof key !== 'string' || key === '') return null;
@@ -77,8 +85,8 @@ export function parseThreadKey(key) {
77
85
  const kind = parts[0];
78
86
  if (!KIND_RE.test(kind)) return null;
79
87
  if (kind === PANEL) {
80
- if (parts.length !== 2 || parts[1] === '') return null;
81
- return { kind: PANEL, sessionId: unesc(parts[1]) };
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]) } : {}) };
82
90
  }
83
91
  if (parts.length < 3 || parts.length > 4 || parts.slice(1).some((p) => p === '')) return null;
84
92
  const [, app, chat, root] = parts;
@@ -94,11 +102,11 @@ export function parseThreadKey(key) {
94
102
  export function toThreadKey(ref) {
95
103
  if (typeof ref === 'string') {
96
104
  const p = parseThreadKey(ref);
97
- return p ? (p.kind === PANEL ? panelThreadKey(p.sessionId) : threadKey(p.kind, p.appKey, p)) : null;
105
+ return p ? (p.kind === PANEL ? panelThreadKey(p.sessionId, p.rootId) : threadKey(p.kind, p.appKey, p)) : null;
98
106
  }
99
107
  if (!ref || typeof ref !== 'object') return null;
100
108
  if (typeof ref.threadKey === 'string') return toThreadKey(ref.threadKey);
101
- if (ref.kind === PANEL) return panelThreadKey(ref.sessionId ?? ref.chatId);
109
+ if (ref.kind === PANEL) return panelThreadKey(ref.sessionId ?? ref.chatId, ref.rootId);
102
110
  if (ref.appKey == null && typeof ref.key === 'string' && parseThreadKey(ref.key)) return toThreadKey(ref.key);
103
111
  return threadKey(ref.kind, ref.appKey ?? ref.key, ref);
104
112
  }
@@ -109,12 +117,24 @@ export function sameThread(a, b) {
109
117
  return ka !== null && ka === toThreadKey(b);
110
118
  }
111
119
 
112
- /** Whether a reference names a panel conversation. */
120
+ /** Whether a reference names a panel conversation (a whole one, or a topic in it). */
113
121
  export function isPanelThread(ref) {
114
122
  const k = toThreadKey(ref);
115
123
  return k !== null && k.startsWith(`${PANEL}:`);
116
124
  }
117
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
+
118
138
  const cleanName = (s, max = 60) =>
119
139
  String(s ?? '')
120
140
  .replace(/[[\]\r\n]+/g, ' ')
@@ -136,7 +156,8 @@ export function threadLabel(meta) {
136
156
  const parts = [cleanName(m.source) || KIND_LABELS[kind] || cleanName(kind) || 'Chat'];
137
157
  const chat = cleanName(m.chatTitle) || (kind === PANEL ? '' : cleanName(m.who) || cleanName(m.chatId));
138
158
  if (chat) parts.push(chat);
139
- if (kind !== PANEL && part(m.rootId)) parts.push(cleanName(m.threadTitle) || (kind === 'telegram' ? 'topic' : 'thread'));
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'));
140
161
  return parts.join(' · ');
141
162
  }
142
163
 
@@ -253,7 +274,7 @@ function originOf(key, given) {
253
274
  const { rootId: _root, key: _key, appKey: _app, chatId: _chat, ...extra } = rest;
254
275
  if (p.kind === PANEL) {
255
276
  const { replyTo: _replyTo, ...panelExtra } = extra;
256
- return { ...panelExtra, threadKey: key, kind: PANEL, sessionId: p.sessionId };
277
+ return { ...panelExtra, threadKey: key, kind: PANEL, sessionId: p.sessionId, ...(p.rootId !== undefined ? { rootId: p.rootId } : {}) };
257
278
  }
258
279
  return { ...extra, threadKey: key, kind: p.kind, key: p.appKey, appKey: p.appKey, chatId: p.chatId, ...(p.rootId !== undefined ? { rootId: p.rootId } : {}) };
259
280
  }
@@ -280,8 +301,9 @@ function refOf(ref) {
280
301
  * Per conversation, the threads this turn's inputs came from (plan §4.3).
281
302
  *
282
303
  * 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);
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);
285
307
  * - anything more, including the panel plus one chat: `choose` (the text stays
286
308
  * in the panel; `bot_reply` names where it goes).
287
309
  *
@@ -322,9 +344,9 @@ export function createOrigins(opts = {}) {
322
344
 
323
345
  function replyPlan(sessionId) {
324
346
  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) };
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) };
328
350
  }
329
351
 
330
352
  return {
@@ -397,6 +419,37 @@ export function createOrigins(opts = {}) {
397
419
  return origin;
398
420
  },
399
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
+
400
453
  /** The turn ended: its threads are forgotten. Returns them. */
401
454
  endTurn(sessionId) {
402
455
  const out = list(part(sessionId)).map(copyOrigin);
package/lib/tickets.mjs CHANGED
@@ -177,7 +177,8 @@ export function createSlots(max = DEFAULT_MAX_WORKING) {
177
177
  /** Kind, app, chat and root from a Thread key (`kind:appKey:chatId[:rootId]`, `panel:<sessionId>`). */
178
178
  function partsOfKey(key) {
179
179
  const [kind = '', ...rest] = key.split(':');
180
- if (kind === 'panel') return { kind, appKey: '', chatId: rest.join(':') };
180
+ // A panel conversation, or a topic in it (`panel:<sessionId>:<rootId>`).
181
+ if (kind === 'panel') return { kind, appKey: '', chatId: rest[0] ?? '', ...(rest.length > 1 && rest.slice(1).join(':') !== '' ? { rootId: rest.slice(1).join(':') } : {}) };
181
182
  const [appKey = '', chatId = '', ...root] = rest;
182
183
  return { kind, appKey, chatId, ...(root.length > 0 && root.join(':') !== '' ? { rootId: root.join(':') } : {}) };
183
184
  }
@@ -408,9 +409,11 @@ export function createTickets(dir, { now = Date.now } = {}) {
408
409
  * `parentId` defaults to the requesting ticket (`requester.ticketId`); the
409
410
  * origin Thread is subscribed, as is each of `threads` (keys, or Thread
410
411
  * metadata with a `key`).
411
- * @param {{title?: string, text: string, botId: string, requester?: object, parentId?: string, origin?: {threadKey?: string, via?: string, who?: string}, threads?: Array<string|{key: string}>}} input
412
+ * `relay`: its requester asked for the reports (`report_to: "me"`), so they go to it rather
413
+ * than to the person in the origin Thread (Bots 0.9).
414
+ * @param {{title?: string, text: string, botId: string, requester?: object, parentId?: string, origin?: {threadKey?: string, via?: string, who?: string}, threads?: Array<string|{key: string}>, relay?: boolean}} input
412
415
  */
413
- create({ title, text, botId, requester, parentId, origin, threads = [] } = {}) {
416
+ create({ title, text, botId, requester, parentId, origin, threads = [], relay = false } = {}) {
414
417
  load();
415
418
  if (typeof botId !== 'string' || botId === '') throw new Error('a ticket needs the bot that does the work');
416
419
  const body = str(text);
@@ -432,6 +435,7 @@ export function createTickets(dir, { now = Date.now } = {}) {
432
435
  origin: normalizeOrigin(origin),
433
436
  threads: [],
434
437
  reports: [],
438
+ ...(relay ? { relay: true } : {}),
435
439
  createdAt: at,
436
440
  updatedAt: at,
437
441
  retries: 0,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kadaliao/dsh-bots",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "description": "Grok-style bots for DeepSeek Harness: create bots with their own avatar, persona, model, skills, apps, scheduled tasks and memory; they message each other, a dispatcher bot hands out the work, and a usage view counts tokens by bot, task and day.",
6
6
  "exports": {