@kadaliao/dsh-bots 0.8.0 → 0.10.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/index.js CHANGED
@@ -50,16 +50,17 @@ import { createUnfurler } from './lib/unfurl.mjs';
50
50
  import { isLogoName, withLogo } from './lib/logos.mjs';
51
51
  import { askNoticeText, CHANNEL_LABELS, channelEntry, channelIssue, createChannels, credentialsOf, maskBot, threadNote, unmaskApps } from './lib/channels.mjs';
52
52
  import { createActivity } from './lib/activity.mjs';
53
- import { describeTiming, dmBody, dmHeader, noWaitReason, personaText, ROUTER_DENY, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
53
+ import { describeTiming, dmBody, dmHeader, noWaitReason, personaText, reportsGoDirect, ROUTER_DENY, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
54
54
  import { createSettings } from './lib/settings.mjs';
55
55
  import { createPriceCatalog, priceOf } from './lib/prices.mjs';
56
56
  import { createLedger, promptTokens, report, ticketUsage, todayByBot, usageRow } from './lib/usage.mjs';
57
57
  import { createSlots, createTickets, parkedOf, REPORT_STATUSES, sessionIdOf, stageOf } from './lib/tickets.mjs';
58
- import { assignmentText, clip, failedNoticeText, followUpNoticeText, nudgeText, PREVIEW_CHARS, readResource, recoveryNoteText, reminderText, reportRelayText, retryText, stalledNoticeText } from './lib/cards.mjs';
58
+ import { assignmentText, clip, discussionNoteText, failedNoticeText, followUpNoticeText, NEWS_MESSAGES, nudgeText, panelHeaderText, PREVIEW_CHARS, readResource, recoveryNoteText, reminderText, reportRelayText, retryText, shownNoticeText, stalledNoticeText, threadNewsText } from './lib/cards.mjs';
59
59
  import { checkTickets, isTransient, requesterReminders, retryDelay } from './lib/watchdog.mjs';
60
- import { isPanelThread, panelThreadKey, parseThreadKey, threadLabel, toThreadKey } from './lib/threads.mjs';
60
+ import { isLiveSubscriber, isPanelThread, isTopicThread, panelThreadKey, panelTopicOf, parseThreadKey, threadLabel, toThreadKey } from './lib/threads.mjs';
61
61
  import { createMemory, dreamBotPrompt, dreamTeamPrompt, KINDS as MEMORY_KINDS, looksSecret, parseJsonReply, reflectionPrompt, searchTickets } from './lib/memory.mjs';
62
62
  import { createTopics, rotationReason } from './lib/topics.mjs';
63
+ import { chatMessageRef, createDiscussions, forkPoint, messageRef, seqByTime } from './lib/discussions.mjs';
63
64
  import { API_KINDS, CODEX_ROUTE, PI_SCOPE, ROUTE_PREFIX, codexAuthFile, createCodexSync, detectLogins, discoverModels, endpointView, keyRefFor, profileFor, readCodexAuth, codexCredential } from './lib/models.mjs';
64
65
 
65
66
  /**
@@ -239,6 +240,8 @@ export function apply(ctx, config, deps = {}) {
239
240
  const memory = createMemory(join(dir, 'memory'));
240
241
  const topics = createTopics(dir);
241
242
  const tickets = createTickets(dir, { now: nowMs });
243
+ // Replies to one message talked over in a forked Session of their own (Bots 0.10).
244
+ const discussions = createDiscussions(dir, { now: nowMs });
242
245
  // A tasks file that is there but cannot be read stops the plugin now, before anything writes over it.
243
246
  try {
244
247
  tickets.open();
@@ -311,14 +314,18 @@ export function apply(ctx, config, deps = {}) {
311
314
  }
312
315
  const activity = createActivity({ now: nowMs, secrets: channelSecrets, handleOf: (ref) => (store.find(String(ref)) ? `@${store.find(String(ref)).handle}` : '') });
313
316
 
314
- /** The bot of a home Session or of a ticket Session (its executing bot). */
317
+ /** The bot of a home Session, of a discussion (forked from its conversation), or of a ticket Session (its executing bot). */
315
318
  function botOfSession(sessionId) {
316
319
  if (!sessionId) return undefined;
317
320
  const home = store.bySession(sessionId);
318
321
  if (home) return home;
322
+ const d = discussions.bySession(sessionId);
323
+ if (d) return store.get(d.botId);
319
324
  const t = ticketOf(sessionId);
320
325
  return t ? store.get(t.botId) : undefined;
321
326
  }
327
+ /** Whether `sessionId` is `bot`'s home, or a discussion forked from its conversation (it talks to the person like the home). */
328
+ const isHomeOf = (bot, sessionId) => Boolean(bot && sessionId) && (bot.sessionId === sessionId || discussions.bySession(sessionId)?.botId === bot.id);
322
329
  const dispatcherMode = () => settings.get().dispatcher;
323
330
  /**
324
331
  * Router mode is in effect: the setting says so and the dispatcher has someone to hand work to. A
@@ -328,7 +335,7 @@ export function apply(ctx, config, deps = {}) {
328
335
  const routerActive = () => dispatcherMode() === 'router' && store.list().length > 1;
329
336
  /** The dispatcher works as a router (in its home; its ticket Sessions are ordinary workers). */
330
337
  const isRouter = (bot) => Boolean(bot) && bot.role === 'primary' && routerActive();
331
- const isRouterHome = (bot, sessionId) => isRouter(bot) && Boolean(sessionId) && bot.sessionId === sessionId && !ticketOf(sessionId);
338
+ const isRouterHome = (bot, sessionId) => isRouter(bot) && isHomeOf(bot, sessionId) && !ticketOf(sessionId);
332
339
  /** Bot-to-bot work opens tickets (router mode), or goes to the other bot's home as in 0.7 (hands-on). */
333
340
  const ticketsOn = () => dispatcherMode() === 'router';
334
341
 
@@ -344,7 +351,7 @@ export function apply(ctx, config, deps = {}) {
344
351
  for (const a of asks.values()) {
345
352
  if (!a.continued) continue;
346
353
  const t = a.ticketId ? tickets.get(a.ticketId) : null;
347
- if (a.ticketId ? !t || t.ended || t.archivedAt : store.get(a.botId)?.sessionId !== a.sessionId) asks.delete(a.id);
354
+ if (a.ticketId ? !t || t.ended || t.archivedAt : !isHomeOf(store.get(a.botId), a.sessionId)) asks.delete(a.id);
348
355
  }
349
356
  return [...asks.values()];
350
357
  }
@@ -357,8 +364,14 @@ export function apply(ctx, config, deps = {}) {
357
364
  // Chat channels run outside the Agent; changing one does not restart the bot's MCP clients.
358
365
  // A linked local skill counts by what its SKILL.md is now, so an edit there re-installs it.
359
366
  // A router home also changes with the dispatcher mode and the role (its tool limits and guard).
367
+ /** What Harness keeps of a tool's result must be plain JSON: an `undefined` field (a panel reply has no `via`) fails the whole call. */
368
+ const lossless = (o) => JSON.parse(JSON.stringify(o ?? {}));
369
+ /** A team (more than one bot): the dispatcher's helpers are its teammates, so Harness's own sub-agents are off for it (the other bots keep theirs). */
370
+ const inTeam = () => store.list().length > 1;
371
+ const noSubagents = (bot) => bot?.role === 'primary' && inTeam();
372
+ const SUBAGENT_TOOLS = ABILITIES.find((a) => a.id === 'delegate')?.tools ?? [];
360
373
  const signatureOf = (bot, sessionId) =>
361
- JSON.stringify({ s: bot.skills, l: bot.skills.filter((s) => s.linked && s.enabled).map((s) => readLinkedSkill(s.dir)?.stamp ?? ''), a: bot.apps.filter((a) => !isChannel(a)), t: bot.tools, h: bot.handle, r: isRouterHome(bot, sessionId) ? 1 : 0 });
374
+ JSON.stringify({ s: bot.skills, l: bot.skills.filter((s) => s.linked && s.enabled).map((s) => readLinkedSkill(s.dir)?.stamp ?? ''), a: bot.apps.filter((a) => !isChannel(a)), t: bot.tools, h: bot.handle, r: isRouterHome(bot, sessionId) ? 1 : 0, m: noSubagents(bot) ? 1 : 0 });
362
375
  /** The chat apps the team can be reached from ('Telegram'), for the persona. */
363
376
  const channelNames = (bots) => {
364
377
  const tpl = templates();
@@ -467,9 +480,9 @@ export function apply(ctx, config, deps = {}) {
467
480
  ctx.logger?.warn?.(`bots: memory for @${bot.handle}: ${error?.message ?? error}`);
468
481
  }
469
482
  }
470
- // A router home is also denied the tools that do the work, except those the user gave back.
483
+ // A router home is also denied the tools that do the work, except those the user gave back; a team's dispatcher starts no sub-agents.
471
484
  const allowed = new Set(bot.tools.routerAllow ?? []);
472
- const wanted = [...new Set([...bot.tools.deny, ...(router ? ROUTER_DENY.filter((n) => !allowed.has(n)) : [])])];
485
+ const wanted = [...new Set([...bot.tools.deny, ...(router ? ROUTER_DENY.filter((n) => !allowed.has(n)) : []), ...(noSubagents(bot) ? SUBAGENT_TOOLS : [])])];
473
486
  if (wanted.length > 0) {
474
487
  const tools = service(actx, 'tools');
475
488
  try {
@@ -529,6 +542,7 @@ export function apply(ctx, config, deps = {}) {
529
542
  );
530
543
  ctx.effect(() => () => {
531
544
  for (const id of [...installed.keys()]) uninstall(id);
545
+ discussions.flush();
532
546
  }, 'bots: unwind bot scopes');
533
547
  /** Apply every bot again to its live home and ticket Sessions (a bot, the roles or the dispatcher mode changed). */
534
548
  function reapply() {
@@ -715,9 +729,9 @@ export function apply(ctx, config, deps = {}) {
715
729
  }
716
730
  return firstLine(said);
717
731
  }
718
- function startTask(bot, sessionId, kind, event, via) {
732
+ function startTask(bot, sessionId, kind, event, via, typed) {
719
733
  const content = event.data?.content;
720
- const said = textOf(content);
734
+ const said = typed ?? textOf(content);
721
735
  const sched = kind === 'schedule' ? (/schedule_id_json:\s*"([^"]+)"/.exec(said)?.[1] ?? /"schedule_id":\s*"([^"]+)"/.exec(said)?.[1] ?? '') : '';
722
736
  const from = kind === 'agent-message' ? (botOfSession(event.data?.source?.senderSessionId)?.id ?? 'user') : '';
723
737
  const ticket = ticketOf(sessionId);
@@ -738,8 +752,8 @@ export function apply(ctx, config, deps = {}) {
738
752
  replied: false,
739
753
  };
740
754
  openTasks.set(sessionId, task);
741
- // A ticket Session is no topic of the bot's: rotation only ever looks at its home.
742
- if (!ticket) topics.current(bot.id, sessionId);
755
+ // A ticket Session or a discussion is no topic of the bot's: rotation only ever looks at its home.
756
+ if (!ticket && !discussions.bySession(sessionId)) topics.current(bot.id, sessionId);
743
757
  return task;
744
758
  }
745
759
  function logLine(task, line) {
@@ -755,7 +769,7 @@ export function apply(ctx, config, deps = {}) {
755
769
  const task = openTasks.get(sessionId);
756
770
  const ticketId = ticketOf(sessionId)?.id;
757
771
  ledger.record(usageRow({ at, botId: bot.id, sessionId, taskId: kind === 'chat' || kind === 'compaction' ? task?.id : undefined, ticketId, kind, provider, model, usage }));
758
- if (kind === 'chat' && !ticketId) topics.noteCall(bot.id, sessionId, promptTokens(usage));
772
+ if (kind === 'chat' && !ticketId && !discussions.bySession(sessionId)) topics.noteCall(bot.id, sessionId, promptTokens(usage));
759
773
  }
760
774
  /** The task of `sessionId` is over when its Agent is idle again. */
761
775
  function settleSoon(sessionId, delay = 1200) {
@@ -784,7 +798,7 @@ export function apply(ctx, config, deps = {}) {
784
798
  if (t?.ended) reflectTicket(t);
785
799
  return;
786
800
  }
787
- topics.noteTask(task.b, task.s, task.title);
801
+ if (!discussions.bySession(task.s)) topics.noteTask(task.b, task.s, task.title);
788
802
  if (bot) queueReflection(bot, { ...row, log });
789
803
  }
790
804
  /** ticketId → transcript lines of its finished runs, for the summary written when it ends. */
@@ -934,6 +948,8 @@ export function apply(ctx, config, deps = {}) {
934
948
 
935
949
  // --- topics ------------------------------------------------------------------------------------
936
950
  const rotating = new Map();
951
+ /** When a bot last started a new topic (ms; 0: not since this process started). */
952
+ let rotatedAt = 0;
937
953
  /**
938
954
  * Start `bot`'s next topic: a fresh conversation (the old one is archived, its
939
955
  * scheduled tasks move to the new one). Refused while the bot is working.
@@ -991,6 +1007,8 @@ export function apply(ctx, config, deps = {}) {
991
1007
  }
992
1008
  uninstall(prev);
993
1009
  forgetSession(prev);
1010
+ // Harness closes the panel when the conversation behind it is archived; the panel opens itself again.
1011
+ rotatedAt = nowMs();
994
1012
  try {
995
1013
  await service(ctx, 'workspaceRegistry')?.archiveSession?.(prev);
996
1014
  } catch (error) {
@@ -998,6 +1016,7 @@ export function apply(ctx, config, deps = {}) {
998
1016
  }
999
1017
  }
1000
1018
  topics.rotate(bot.id, next, reason);
1019
+ rotatedAt = nowMs();
1001
1020
  store.log({ from: 'system', to: bot.id, kind: 'topic', text: reason });
1002
1021
  return next;
1003
1022
  })().finally(() => rotating.delete(bot.id));
@@ -1167,24 +1186,386 @@ export function apply(ctx, config, deps = {}) {
1167
1186
  return agent.session.id;
1168
1187
  }
1169
1188
 
1189
+ // --- the panel chat (Bots 0.9; threads 0.10) ------------------------------------------
1190
+ /** A new id for a message typed in the panel: `p` and 8 letters or digits, short enough for a model to copy. */
1191
+ const newPanelId = () => {
1192
+ for (;;) {
1193
+ const id = `p${randomUUID().replace(/-/g, '').slice(0, 8)}`;
1194
+ if (!store.message(id)) return id;
1195
+ }
1196
+ };
1197
+ /** Whether a timeline message belongs to `botId`'s panel chat (lib/store.mjs `messages`). */
1198
+ const inChat = (m, botId) => Boolean(m) && (m.chat ? m.chat === botId : m.from === botId || m.to === botId);
1199
+ /**
1200
+ * The key of the panel topic `root` from its first message: its `thread` when that is the topic's
1201
+ * key, else `panelThread` (a chat app's message, whose `thread` stays its chat Thread), else ''.
1202
+ */
1203
+ const topicKeyOf = (first, root) => {
1204
+ if (first?.thread && panelTopicOf(first.thread) === root) return first.thread;
1205
+ if (first?.panelThread && panelTopicOf(first.panelThread) === root) return first.panelThread;
1206
+ return '';
1207
+ };
1208
+ /** Who wrote a timeline message, as a header names them. */
1209
+ const writerOf = (m) => (m.from === 'user' ? 'the user' : store.get(m.from) ? `@${store.get(m.from).handle}` : 'a bot');
1210
+ /** A message bots send each other (a DM or a report between two bots), not one said to the person. */
1211
+ const betweenBots = (m) => m.from !== 'user' && m.to !== 'user' && (m.kind === 'dm' || m.kind === 'report');
1212
+ /**
1213
+ * What was said in the threads of `bot`'s panel chat since its main conversation (Session `sid`)
1214
+ * last heard, as the note before the person's next message there (Bots 0.10): the panel shows those
1215
+ * replies in the chat, quoted. Since the later of the last note and the start of the current topic.
1216
+ * Returns `{text, upTo}` (`upTo`: the time of the latest message told; 0 for none).
1217
+ */
1218
+ function threadNewsFor(bot, sid) {
1219
+ const cur = topics.peek(bot.id);
1220
+ const since = Math.max(discussions.toldAt(bot.id), cur?.sessionId === sid ? Number(cur.startedAt) || 0 : 0);
1221
+ const rows = store
1222
+ .messages({ bot: bot.id, limit: 400, roots: false })
1223
+ .filter((m) => Number(m.at) > since && !m.via && m.kind !== 'system' && m.kind !== 'topic' && !betweenBots(m) && rootIdOf(m) !== m.id && String(m.text ?? '').trim())
1224
+ .slice(-NEWS_MESSAGES);
1225
+ if (!rows.length) return { text: '', upTo: 0 };
1226
+ const byRoot = new Map();
1227
+ for (const m of rows) {
1228
+ const r = rootIdOf(m);
1229
+ if (!byRoot.has(r)) {
1230
+ const root = store.message(r);
1231
+ const whose = !root ? '' : root.from === bot.id ? 'your message' : root.from === 'user' ? "the user's message" : `${writerOf(root)}'s message`;
1232
+ byRoot.set(r, { who: whose, text: root?.text ?? '', said: [] });
1233
+ }
1234
+ byRoot.get(r).said.push({ who: m.from === 'user' ? 'The user' : m.from === bot.id ? 'You' : writerOf(m), text: m.text });
1235
+ }
1236
+ return { text: threadNewsText({ threads: [...byRoot.values()] }), upTo: Math.max(...rows.map((m) => Number(m.at) || 0)) };
1237
+ }
1238
+ /** Characters of the message a reply quotes, as the chat shows it. */
1239
+ const QUOTE_CHARS = 140;
1240
+ /**
1241
+ * The message a reply in a thread quotes, as the chat shows it (Bots 0.10): the person's, the one
1242
+ * they replied to (the thread's root unless they picked another of it); a bot's, the person's
1243
+ * latest message of the thread before it, else the root. Null for a message of the main chat.
1244
+ * @param {object} m
1245
+ * @param {Map<string, object[]>} replies - per root, the thread's messages in order
1246
+ * @param {(id: string) => object | undefined} lookup
1247
+ */
1248
+ function quoteOf(m, replies, lookup) {
1249
+ const rootId = rootIdOf(m);
1250
+ if (!rootId || rootId === m.id) return null;
1251
+ let target = m.from === 'user' && m.replyTo ? lookup(m.replyTo) : null;
1252
+ if (!target && m.from !== 'user') {
1253
+ for (const x of replies.get(rootId) ?? []) {
1254
+ if (x.id === m.id) break;
1255
+ if (x.from === 'user' && x.kind === 'user') target = x;
1256
+ }
1257
+ }
1258
+ target ??= lookup(rootId);
1259
+ if (!target) return null;
1260
+ const text = clip(String(target.text ?? '').replace(/\s+/g, ' ').trim(), QUOTE_CHARS).text;
1261
+ return { id: target.id, from: target.from, text, ...(target.who ? { who: target.who } : {}), ...(target.via ? { via: target.via } : {}) };
1262
+ }
1263
+ /** The tasks a dispatcher's panel message may continue: open, or ended within a day; the latest change first. */
1264
+ function openTasksOf(bot) {
1265
+ const since = nowMs() - 24 * 3600_000;
1266
+ return tickets
1267
+ .list({ archived: false })
1268
+ .filter((t) => t.requester?.botId === bot.id && !t.requester?.ticketId && (!t.ended || t.ended.at >= since))
1269
+ .sort((a, b) => b.updatedAt - a.updatedAt);
1270
+ }
1271
+ // --- discussions: replies to one message, in a Session of their own (Bots 0.10) ----------
1272
+ /** The root of the discussion a timeline message is in; the message itself when it is in the main chat. */
1273
+ const rootIdOf = (m) => (m?.topic && m.topic !== m.id ? m.topic : m?.movedTo && m.movedTo !== m.id ? m.movedTo : m?.id ?? '');
1274
+ /** The Thread a Session's plain words go to when its turn named none: a discussion's own, else the panel. */
1275
+ const homeThreadOf = (sessionId) => discussions.bySession(sessionId)?.key ?? panelThreadKey(sessionId);
1170
1276
  /**
1171
- * The user writes to a bot from the panel: an ordinary user prompt in its conversation.
1172
- * `/new` (or `/clear`, `/新话题`) first starts a new topic; text after it goes there.
1277
+ * The Session of `bot`'s that a timeline message was said in: noted on it, the panel conversation
1278
+ * its Thread names, the bot's own task it belongs to, or else the bot's home.
1173
1279
  */
1174
- async function userSend(target, text) {
1280
+ function sessionOfMessage(m, bot) {
1281
+ if (m?.sid) return m.sid;
1282
+ const p = parseThreadKey(m?.thread);
1283
+ if (p?.kind === 'panel' && p.sessionId) return p.sessionId;
1284
+ const t = m?.ticket ? tickets.get(m.ticket) : undefined;
1285
+ if (t?.sessionId && t.botId === bot.id) return t.sessionId;
1286
+ return bot.sessionId ?? '';
1287
+ }
1288
+ /**
1289
+ * Where `m` sits in a Session of `bot`'s: its anchor (kept since 0.10), else found in that
1290
+ * Session's log by time (an older message; a person's counts with the answer its turn gave).
1291
+ * Null when it cannot be told.
1292
+ */
1293
+ async function positionOfMessage(m, bot) {
1294
+ const a = discussions.anchorOf(messageRef(m.id));
1295
+ if (a && isMine(bot, a.sessionId)) return a;
1296
+ const sessionId = sessionOfMessage(m, bot);
1297
+ if (!sessionId || !isMine(bot, sessionId)) return null;
1298
+ const seq = seqByTime(await readHistory(sessionId).catch(() => null), { at: Number(m.at), fromPerson: m.from === 'user' });
1299
+ return seq === undefined ? null : { sessionId, seq };
1300
+ }
1301
+ /** Whether a Session is `bot`'s: its home (now or an earlier topic), a discussion of it, or its task. */
1302
+ function isMine(bot, sessionId) {
1303
+ if (!sessionId) return false;
1304
+ const owner = botOfSession(sessionId);
1305
+ if (owner) return owner.id === bot.id;
1306
+ // An earlier topic of the bot's (archived): its conversations are still the bot's.
1307
+ return topics.peek(bot.id)?.sessionId === sessionId || topics.history(bot.id).some((x) => x.sessionId === sessionId);
1308
+ }
1309
+ /** Name a Session for its bot and give it the bot's model (a fork starts with Harness's default). */
1310
+ function decorate(agent, bot, title) {
1311
+ try {
1312
+ service(ctx, 'sessionTitle')?.rename?.(agent.session, title || bot.name);
1313
+ } catch {
1314
+ // A title is cosmetic.
1315
+ }
1316
+ const fresh = store.get(bot.id) ?? bot;
1317
+ if (fresh.model) {
1318
+ try {
1319
+ agent.model?.select?.(selectionOf(fresh.model));
1320
+ } catch {
1321
+ // The default model stays.
1322
+ }
1323
+ }
1324
+ }
1325
+ /** A discussion's Session again: taken out of the archive when it was put there. Null when it cannot come back. */
1326
+ async function reopenDiscussion(d) {
1327
+ const controller = service(ctx, 'sessionController');
1328
+ const reg = service(ctx, 'workspaceRegistry');
1329
+ if (d.archivedAt || (reg?.archivedSessionIds ?? []).includes(d.sessionId)) {
1330
+ try {
1331
+ await reg?.unarchiveSession?.(d.sessionId);
1332
+ } catch {
1333
+ return null;
1334
+ }
1335
+ if ((reg?.archivedSessionIds ?? []).includes(d.sessionId)) return null;
1336
+ discussions.patch(d.key, { archivedAt: null });
1337
+ }
1338
+ const found = await controller.resolveAgent(d.sessionId).catch((error) => ({ error }));
1339
+ if (!found || 'error' in found) return null;
1340
+ reconcile(found.agent);
1341
+ return found.agent;
1342
+ }
1343
+ const opening = new Map();
1344
+ /**
1345
+ * The discussion `key` is talked over in, opened the first time: `bot`'s conversation forked at
1346
+ * `point` (`{sessionId, seq?}`; no seq: its latest finished turn). One that cannot come back from
1347
+ * the archive continues from its own last turn. Returns `{discussion, agent}`.
1348
+ */
1349
+ function discussionFor(bot, key, { point, rootId, title }) {
1350
+ if (opening.has(key)) return opening.get(key);
1351
+ const job = (async () => {
1352
+ const controller = service(ctx, 'sessionController');
1353
+ if (!controller) throw new Error('threads need the Web profile (no session controller here)');
1354
+ const known = discussions.get(key);
1355
+ if (known && known.botId === bot.id) {
1356
+ const agent = await reopenDiscussion(known);
1357
+ if (agent) return { discussion: discussions.get(key), agent };
1358
+ }
1359
+ if (typeof controller.fork !== 'function') throw new Error('this DeepSeek Harness cannot fork a conversation; update it to reply in a thread');
1360
+ const from = known?.botId === bot.id ? { sessionId: known.sessionId } : point;
1361
+ if (!from?.sessionId) throw new Error('the conversation that message was said in is gone; send it as a new message instead');
1362
+ let forked;
1363
+ // Forked at the replied message: the thread sees nothing said after it. Otherwise (the place is not
1364
+ // known, or cannot be forked) at the latest turn, and the note says the conversation may go on past it.
1365
+ let exact = from.seq !== undefined;
1366
+ try {
1367
+ forked = await controller.fork({ sessionId: from.sessionId, ...(from.seq !== undefined ? { atSeq: from.seq } : {}) });
1368
+ } catch (error) {
1369
+ if (from.seq === undefined) throw error;
1370
+ ctx.logger?.warn?.(`bots: forking at event ${from.seq} of ${from.sessionId}: ${error?.message ?? error}; forking at its latest turn`);
1371
+ forked = await controller.fork({ sessionId: from.sessionId });
1372
+ exact = false;
1373
+ }
1374
+ const d = discussions.add({ key, botId: bot.id, sessionId: forked.sessionId, rootId, source: from, title });
1375
+ if (known?.noted) discussions.patch(key, { noted: true });
1376
+ if (!known && !exact) discussions.patch(key, { exact: false });
1377
+ const found = await controller.resolveAgent(d.sessionId);
1378
+ if ('error' in found) throw found.error;
1379
+ reconcile(found.agent);
1380
+ decorate(found.agent, bot, title ? `${bot.name} · ${title}` : bot.name);
1381
+ return { discussion: discussions.get(key), agent: found.agent };
1382
+ })().finally(() => opening.delete(key));
1383
+ opening.set(key, job);
1384
+ return job;
1385
+ }
1386
+ /** One line of a message, for a discussion's title. */
1387
+ const titleOf = (text) => clip(String(text ?? '').replace(/\s+/g, ' ').trim(), 40).text;
1388
+ /** A timeline message as the panel reads it: `pending` while no model has taken it yet; internal fields left out. */
1389
+ function messageView(m) {
1390
+ const { sid, ...rest } = m;
1391
+ if (m.from !== 'user' || m.kind !== 'user' || !/^p[a-z0-9]{8}$/.test(m.id)) return rest;
1392
+ const waiting = (sessionId, msgId) => pendingOf(agents()?.get?.(sessionId)).some((x) => x?.id === `${MESSAGE_PREFIX}${msgId}`);
1393
+ let pending = false;
1394
+ if (m.ticket && !sid) {
1395
+ const t = tickets.get(m.ticket);
1396
+ const key = `panel:${m.id}:${m.ticket}`;
1397
+ // Queued (its assignment carries the message), waiting for a worker slot, or not taken yet.
1398
+ pending = Boolean(t) && !t.ended && (!t.startedAt || parkedOf(t).some((x) => x.key === key) || (Boolean(t.sessionId) && waiting(t.sessionId, key)));
1399
+ } else if (sid) pending = waiting(sid, `panel:${m.id}`);
1400
+ return pending ? { ...rest, pending: true } : rest;
1401
+ }
1402
+
1403
+ /**
1404
+ * The user writes to a bot from the panel. `/new` (or `/clear`, `/新话题`) first starts a new
1405
+ * topic of its conversation; text after it goes there. Every message is logged before it is
1406
+ * handed over (the panel shows it at once, `pending` until a model takes it). A message goes
1407
+ * to the main chat: the bot's home (a router steers it, with the tasks it may continue in a
1408
+ * header; other homes take it as a turn of its own). With `replyTo` it is a reply in the thread
1409
+ * of that message (Bots 0.10, `threadSend`). Returns `{sessionId, message?}`.
1410
+ */
1411
+ async function userSend(target, text, { replyTo = '' } = {}) {
1175
1412
  let body = String(text ?? '').trim();
1176
1413
  if (body === '') throw new Error('text must not be empty');
1414
+ const ref = String(replyTo ?? '').trim();
1415
+ if (ref) return threadSend(store.get(target.id) ?? target, body, ref);
1177
1416
  const cmd = TOPIC_COMMAND.exec(body);
1178
1417
  if (cmd) {
1179
1418
  const sessionId = await newTopic(target, 'manual');
1180
1419
  body = body.slice(cmd[0].length).trim();
1181
- if (!body) return sessionId;
1420
+ if (!body) return { sessionId };
1182
1421
  } else await autoTopic(store.get(target.id) ?? target, 'user');
1183
- const agent = await agentOf(store.get(target.id) ?? target);
1184
- await sendTo(agent, { content: [{ type: 'text', text: body }], source: { kind: 'user' }, mode: homeMode(target) });
1185
- return agent.session.id;
1422
+ const bot = store.get(target.id) ?? target;
1423
+ const agent = await agentOf(bot);
1424
+ const sid = agent.session.id;
1425
+ const id = newPanelId();
1426
+ store.log({ id, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, thread: panelThreadKey(sid), sid });
1427
+ // The panel shows thread replies in the chat: what the person read there since, the main conversation hears first.
1428
+ const news = threadNewsFor(bot, sid);
1429
+ const header = isRouterHome(bot, sid) ? panelHeaderText({ open: openTasksOf(bot) }, cardCtx()) : '';
1430
+ try {
1431
+ await sendTo(agent, { content: [news.text, header, body].filter(Boolean).map((text) => ({ type: 'text', text })), source: { kind: 'user' }, mode: homeMode(bot), key: `panel:${id}` });
1432
+ } catch (error) {
1433
+ // Not handed over: it leaves the chat (the panel keeps its own copy to send again).
1434
+ store.patchMessage(id, { hidden: true });
1435
+ throw error;
1436
+ }
1437
+ if (news.upTo) discussions.markTold(bot.id, news.upTo);
1438
+ return { sessionId: sid, message: messageView(store.message(id)) };
1439
+ }
1440
+
1441
+ /**
1442
+ * A reply in the thread of message `ref` in `bot`'s chat (Bots 0.10). A message in the main chat
1443
+ * opens its thread; one in a thread stays in that thread (it is quoted). The thread of a task's
1444
+ * message, or one a task follows, goes to the task (as in 0.9); any other is a discussion: the
1445
+ * bot's conversation forked at the replied message, so it sees what came before and nothing the
1446
+ * main chat said since. Returns `{sessionId, message}`.
1447
+ */
1448
+ async function threadSend(bot, body, ref) {
1449
+ if (TOPIC_COMMAND.test(body)) throw new Error('a thread has no new topic: send /new in the main chat');
1450
+ const quoted = store.message(ref);
1451
+ if (!quoted || !inChat(quoted, bot.id)) throw new Error('that message is not in this chat');
1452
+ const rootId = rootIdOf(quoted);
1453
+ const root = rootId === quoted.id ? quoted : store.message(rootId);
1454
+ if (!root) throw new Error('the message this thread answers is gone');
1455
+ const homeSid = sessionOfMessage(root, bot);
1456
+ // The thread keeps the key it was opened with (the home may have a new topic since).
1457
+ const said = store.messages({ bot: bot.id, topic: rootId, limit: 50 }).find((m) => m.id !== rootId && panelTopicOf(m.thread) === rootId);
1458
+ const key = topicKeyOf(root, rootId) || discussions.byRoot(rootId)?.key || said?.thread || panelThreadKey(homeSid || bot.sessionId || 'panel', rootId);
1459
+ const id = newPanelId();
1460
+ const aside = quoted.id !== rootId ? quoted : null;
1461
+ store.log({ id, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, thread: key, topic: rootId, ...(aside ? { replyTo: aside.id } : {}) });
1462
+ // A task's thread (opened on the task's own message, or a 0.9 topic it follows): the person's words go to the task.
1463
+ // In a discussion they go to its bot, who has the tasks it opened there report back into it.
1464
+ const talking = discussions.get(key);
1465
+ let live = talking ? [] : tickets.subscribers(key).filter(isLiveSubscriber);
1466
+ const own = root.ticket ? tickets.get(root.ticket) : undefined;
1467
+ if (!live.length && own && isLiveSubscriber(own)) {
1468
+ tickets.subscribe(own.id, key, { label: threadLabel({ threadKey: key, threadTitle: root.text }) });
1469
+ // Its later reports are shown in this thread.
1470
+ tickets.patch(own.id, { showIn: key });
1471
+ live = [tickets.get(own.id)];
1472
+ }
1473
+ if (live.length) {
1474
+ try {
1475
+ const sessions = await toTopicTasks(bot, live, body, { key, root: rootId, id, quoted });
1476
+ return { sessionId: sessions[0] ?? bot.sessionId, message: messageView(store.message(id)) };
1477
+ } catch (error) {
1478
+ // No task took it (one ended meanwhile, say): a discussion does.
1479
+ ctx.logger?.warn?.(`bots: a reply did not reach its task (${error?.message ?? error}); @${bot.handle} takes it in a thread`);
1480
+ }
1481
+ }
1482
+ let opened;
1483
+ try {
1484
+ const at = await positionOfMessage(root, bot);
1485
+ const point = forkPoint({ root: at, fallback: isMine(bot, homeSid) ? homeSid : bot.sessionId });
1486
+ opened = await discussionFor(bot, key, { point, rootId, title: titleOf(root.text) });
1487
+ } catch (error) {
1488
+ store.patchMessage(id, { hidden: true });
1489
+ throw error;
1490
+ }
1491
+ const { discussion, agent } = opened;
1492
+ // The first message of the thread carries the note; claimed now, so a second reply at once does not repeat it.
1493
+ const first = !discussions.get(key)?.noted;
1494
+ if (first) discussions.patch(key, { noted: true });
1495
+ const header = first
1496
+ ? discussionNoteText({ who: writerOf(root), text: root.text, exact: discussion.exact !== false, ...(aside ? { quoted: { who: writerOf(aside), text: aside.text } } : {}) })
1497
+ : aside
1498
+ ? panelHeaderText({ replyTo: { who: writerOf(aside), text: aside.text } })
1499
+ : '';
1500
+ store.patchMessage(id, { sid: agent.session.id });
1501
+ try {
1502
+ await sendTo(agent, { content: header ? [{ type: 'text', text: header }, { type: 'text', text: body }] : [{ type: 'text', text: body }], source: { kind: 'user' }, mode: homeMode(bot), key: `panel:${id}` });
1503
+ } catch (error) {
1504
+ store.patchMessage(id, { hidden: true });
1505
+ if (first) discussions.patch(key, { noted: null });
1506
+ throw error;
1507
+ }
1508
+ discussions.patch(key, { lastAt: nowMs() });
1509
+ return { sessionId: agent.session.id, message: messageView(store.message(id)) };
1510
+ }
1511
+
1512
+ /**
1513
+ * A reply in a panel topic whose tasks are live: into each task's Session as the person's
1514
+ * message (a done one opens again; it may take the extra slot), and the chat's bot hears of it
1515
+ * without waking. Returns the task Sessions; throws when no task took it.
1516
+ */
1517
+ async function toTopicTasks(bot, list, body, { key, root, id, quoted }) {
1518
+ const reached = [];
1519
+ let lastError = null;
1520
+ const header = quoted && quoted.id !== root ? panelHeaderText({ replyTo: { who: writerOf(quoted), text: quoted.text } }) : '';
1521
+ for (const t of list) {
1522
+ const cur = tickets.get(t.id) ?? t;
1523
+ try {
1524
+ reached.push(await appendToTicket(cur, body, { human: true, logged: true, header, key: `panel:${id}:${cur.id}` }));
1525
+ } catch (error) {
1526
+ lastError = error;
1527
+ ctx.logger?.warn?.(`bots: a panel reply did not reach task ${cur.id}: ${error?.message ?? error}`);
1528
+ }
1529
+ }
1530
+ if (!reached.length) throw lastError ?? new Error('no task took the reply');
1531
+ store.patchMessage(id, { ticket: reached[0].id });
1532
+ // Whoever asked for the tasks hears of it without waking: the bot's home, or the thread of it that opened them.
1533
+ const told = new Set();
1534
+ for (const t of reached) {
1535
+ try {
1536
+ const asked = t.requester?.kind === 'session' && t.requester.botId === bot.id && !t.requester.ticketId ? await requesterAgent(t) : await agentOf(bot);
1537
+ if (!asked || told.has(asked.session.id)) continue;
1538
+ told.add(asked.session.id);
1539
+ const text = followUpNoticeText({ tickets: reached, thread: { key: root, label: threadLabel({ threadKey: key, threadTitle: store.message(root)?.text }) }, who: 'The user', text: body }, cardCtx());
1540
+ await sendTo(asked, { content: [{ type: 'text', text }], source: { kind: 'agent-message', form: 'relay' }, mode: 'inject', key: `followup:panel:${id}` });
1541
+ } catch (error) {
1542
+ ctx.logger?.warn?.(`bots: the follow-up notice for @${bot.handle}: ${error?.message ?? error}`);
1543
+ }
1544
+ }
1545
+ return reached.map((t) => t.sessionId).filter(Boolean);
1186
1546
  }
1187
1547
 
1548
+ /**
1549
+ * A thread a tool call names, as a key: a key as is; a panel topic by the id its header shows
1550
+ * (`p…`), or by any message in it (one filed under another topic names that one). '' for none.
1551
+ */
1552
+ function threadRef(ref, sessionId) {
1553
+ const r = String(ref ?? '').trim().replace(/^(?:thread|topic)\//, '');
1554
+ if (!r || parseThreadKey(r)) return r;
1555
+ const hit = channels.current(sessionId).find((o) => o.kind === 'panel' && o.rootId === r);
1556
+ if (hit) return hit.threadKey;
1557
+ const m = store.message(r);
1558
+ if (!m) return r;
1559
+ const root = m.movedTo || m.topic || '';
1560
+ const first = root ? store.message(root) : undefined;
1561
+ return topicKeyOf(first, root) || r;
1562
+ }
1563
+ /** The panel topics of a turn, and its chat Threads, as a tool error lists them. */
1564
+ const turnChoices = (sessionId) =>
1565
+ channels
1566
+ .current(sessionId)
1567
+ .filter((o) => o.kind !== 'panel' || o.rootId)
1568
+ .map((o) => (o.kind === 'panel' ? `${o.rootId} (${threadLabel(o)})` : `${o.threadKey} (${threadLabel(o)}${o.tickets?.length ? `; task ${o.tickets.join(', ')}` : ''})`));
1188
1569
  // --- tickets: delegated work in Sessions of their own ---------------------------------
1189
1570
  /** What cards and relays read about the team and the tickets. */
1190
1571
  const cardCtx = () => ({ bots: store.list(), threads: tickets, tickets, stageOf });
@@ -1277,6 +1658,9 @@ export function apply(ctx, config, deps = {}) {
1277
1658
  }
1278
1659
  if (plan.mode === 'thread') return originFrom(plan.target);
1279
1660
  if (plan.mode === 'choose') {
1661
+ // Several topics or chats a person is waiting in (Bots 0.9): the task must say which one is its own.
1662
+ const topics = plan.origins.filter((o) => isTopicThread(o.threadKey));
1663
+ if (topics.length > 1) throw new Error(`this turn involves several topics or chats: say which one this task is for with \`thread\`: ${turnChoices(sessionId).join('; ')}`);
1280
1664
  // Several Threads and none named: the task belongs to none of them (its report reaches the requester only).
1281
1665
  const people = [...new Set(plan.origins.map((o) => o.who).filter(Boolean))];
1282
1666
  return { origin: { ...(people.length === 1 ? { who: people[0] } : { who: 'the user' }) } };
@@ -1469,6 +1853,9 @@ export function apply(ctx, config, deps = {}) {
1469
1853
  return resolveId(parent.sessionId ?? r.sessionId);
1470
1854
  }
1471
1855
  const bot = r.botId ? store.get(r.botId) : undefined;
1856
+ // Asked from a thread of the bot's (Bots 0.10): the thread hears of it, back from the archive if need be.
1857
+ const asked = discussions.bySession(r.sessionId);
1858
+ if (bot && asked?.botId === bot.id) return (await reopenDiscussion(asked)) ?? agentOf(bot);
1472
1859
  // The asking bot may have started a new topic since: its report goes to the conversation it has now.
1473
1860
  if (bot && bot.sessionId !== r.sessionId) return agentOf(bot);
1474
1861
  return (await resolveId(r.sessionId)) ?? (bot ? agentOf(bot) : null);
@@ -1499,11 +1886,23 @@ export function apply(ctx, config, deps = {}) {
1499
1886
  if (!(t.sessionId && openTasks.has(t.sessionId))) reflectTicket(t);
1500
1887
  }
1501
1888
 
1889
+ /**
1890
+ * Where a ticket's own lines go in the panel (Bots 0.9): a ticket that came from a panel topic
1891
+ * logs its delegation, the messages added to it and its notices into that topic, in the chat of
1892
+ * the bot that asked. Others log as in 0.8 (`{}`).
1893
+ */
1894
+ const topicFieldsOf = (t) => {
1895
+ const key = t?.origin?.threadKey;
1896
+ const topic = key ? panelTopicOf(key) : '';
1897
+ return topic ? { chat: t.requester?.botId ?? t.botId, thread: key, topic } : {};
1898
+ };
1899
+
1502
1900
  /** Who may add to a ticket from `sessionId`: its requester (or the requesting bot from its current home), or the router. */
1503
1901
  function mayAppend(t, sender, sessionId) {
1504
1902
  const r = t.requester ?? {};
1505
1903
  if (r.sessionId === sessionId) return true;
1506
- if (sender && r.botId === sender.id && !r.ticketId && sender.sessionId === sessionId) return true;
1904
+ // The asking bot's home, or a thread of it (Bots 0.10): the person may carry a task on there.
1905
+ if (sender && r.botId === sender.id && !r.ticketId && isHomeOf(sender, sessionId)) return true;
1507
1906
  return Boolean(sender) && isRouterHome(sender, sessionId);
1508
1907
  }
1509
1908
 
@@ -1516,7 +1915,7 @@ export function apply(ctx, config, deps = {}) {
1516
1915
  * take the extra one); until then it waits on the ticket. A message whose `key` was delivered (or
1517
1916
  * parked) already changes nothing: a replay after a restart neither reopens nor wakes the ticket.
1518
1917
  */
1519
- async function appendToTicket(t, text, { sender = null, senderSessionId = '', human = false, force = false, header = '', chat = null, key = '' } = {}) {
1918
+ async function appendToTicket(t, text, { sender = null, senderSessionId = '', human = false, force = false, header = '', chat = null, key = '', logged = false } = {}) {
1520
1919
  const body = String(text ?? '').trim();
1521
1920
  if (body === '') throw new Error('text must not be empty');
1522
1921
  if (t.archivedAt) throw new Error(`task ${t.id} is archived; open a new task instead`);
@@ -1555,10 +1954,12 @@ export function apply(ctx, config, deps = {}) {
1555
1954
  : [{ type: 'text', text: body }];
1556
1955
  // A person's follow-up may take the extra slot (new work cannot crowd it out); a bot's may not.
1557
1956
  await toTicket(cur, { content, source: sender && senderSessionId ? { kind: 'agent-message', form: 'relay', senderSessionId } : { kind: 'user' }, key: key || `msg:${cur.id}:${randomUUID()}`, human: human && !sender });
1957
+ // A panel message is in the timeline already (logged when it was sent).
1958
+ if (logged) return tickets.get(cur.id) ?? cur;
1558
1959
  store.log(
1559
1960
  chat
1560
1961
  ? { from: 'user', to: cur.botId, text: body, kind: 'user', via: chat.kind, ...(chat.who ? { who: chat.who } : {}), ...(chat.threadKey ? { thread: chat.threadKey } : {}), ticket: cur.id }
1561
- : { from: sender ? sender.id : 'user', to: cur.botId, text: body, kind: 'dm', ticket: cur.id },
1962
+ : { from: sender ? sender.id : 'user', to: cur.botId, text: body, kind: 'dm', ticket: cur.id, ...topicFieldsOf(cur) },
1562
1963
  );
1563
1964
  return tickets.get(cur.id) ?? cur;
1564
1965
  }
@@ -1567,10 +1968,17 @@ export function apply(ctx, config, deps = {}) {
1567
1968
  * Open a ticket for `target`, asked from `senderSessionId` (a bot's home or a ticket Session),
1568
1969
  * and start it when a slot is free. Returns the ticket; a start that failed shows as stage `failed`.
1569
1970
  */
1570
- async function openTicket(sender, target, text, senderSessionId, { title, thread: chosen } = {}) {
1971
+ async function openTicket(sender, target, text, senderSessionId, { title, thread: chosen, relay = false } = {}) {
1571
1972
  const body = String(text ?? '').trim();
1572
1973
  if (body === '') throw new Error('text must not be empty');
1573
- if (sender.id === target.id) throw new Error('a bot cannot message itself');
1974
+ // The dispatcher only hands out (Bots 0.10; 0.9 let it hand work to itself): the work goes to a teammate.
1975
+ if (sender.id === target.id) {
1976
+ throw new Error(
1977
+ isRouterHome(sender, senderSessionId)
1978
+ ? 'you are the dispatcher: hand the work to a teammate, the closest fit (any of them can look things up and write); answer yourself only from what you already know'
1979
+ : 'a bot cannot message itself',
1980
+ );
1981
+ }
1574
1982
  if (!service(ctx, 'sessionController')) throw new Error('tasks need the Web profile (no session controller here)');
1575
1983
  const parent = ticketOf(senderSessionId);
1576
1984
  const { origin, thread } = originOfTurn(senderSessionId, chosen);
@@ -1582,8 +1990,9 @@ export function apply(ctx, config, deps = {}) {
1582
1990
  requester: { kind: 'session', sessionId: senderSessionId, botId: sender.id, ...(parent ? { ticketId: parent.id } : {}) },
1583
1991
  origin,
1584
1992
  threads: thread ? [thread] : [],
1993
+ relay,
1585
1994
  });
1586
- store.log({ from: sender.id, to: target.id, text: body, kind: 'dm', ticket: t.id });
1995
+ store.log({ from: sender.id, to: target.id, text: body, kind: 'dm', ticket: t.id, ...topicFieldsOf(t) });
1587
1996
  quietFailures.add(t.id);
1588
1997
  try {
1589
1998
  await pump();
@@ -1608,8 +2017,15 @@ export function apply(ctx, config, deps = {}) {
1608
2017
  // they are kept on the task (its reports) and the panel shows them.
1609
2018
  const parent = next.requester?.ticketId ? tickets.get(next.requester.ticketId) : undefined;
1610
2019
  const unread = !wasOpen ? 'ended' : next.requester?.ticketId && (!parent || parent.ended) ? 'parent' : '';
1611
- if (status !== 'progress' && !unread) {
1612
- store.log({ from: next.botId, to: next.requester?.botId ?? 'user', text: body, kind: 'dm', ticket: next.id, status });
2020
+ // Bots 0.9: the person reads it as it is, where the task came from; whoever asked is told without waking.
2021
+ const shown = status !== 'progress' && !unread && reportsGoDirect(next) ? showReport(next, report) : null;
2022
+ if (shown) {
2023
+ relayed = true;
2024
+ if (next.requester?.kind === 'session') {
2025
+ await notifyRequester(next, shownNoticeText(next, report, { ...cardCtx(), where: shown.where }), { mode: 'inject', key: `shown:${next.id}:${index}:${report.at}` });
2026
+ }
2027
+ } else if (status !== 'progress' && !unread) {
2028
+ store.log({ from: next.botId, to: next.requester?.botId ?? 'user', text: body, kind: 'dm', ticket: next.id, status, ...topicFieldsOf(next) });
1613
2029
  // A ticket the user asked for has no Session to tell: the panel shows it (attention).
1614
2030
  if (next.requester?.kind === 'session') {
1615
2031
  // The requester's turn takes this ticket's origin Thread as an input when the relay arrives in it
@@ -1618,7 +2034,39 @@ export function apply(ctx, config, deps = {}) {
1618
2034
  }
1619
2035
  }
1620
2036
  if (status === 'done' && wasOpen) ticketEnded(next);
1621
- return { ticket: next, relayed, ...(unread ? { unread, ...(parent ? { parent: parent.id } : {}) } : {}) };
2037
+ return { ticket: next, relayed, ...(shown ? { shown } : {}), ...(unread ? { unread, ...(parent ? { parent: parent.id } : {}) } : {}) };
2038
+ }
2039
+
2040
+ /**
2041
+ * Post a worker's report where its task came from (Bots 0.9): a panel topic (or the panel as a
2042
+ * whole, for a task from before topics) shows it in the chat of the bot that asked; a chat Thread
2043
+ * gets it through that chat's app, signed with the worker's name when the worker is not the one
2044
+ * the chat belongs to. Returns `{where}` (how the place reads), or null when it cannot be reached
2045
+ * (the report then goes to whoever asked, as in 0.8).
2046
+ */
2047
+ function showReport(t, report) {
2048
+ // Where the person carries the task on (a thread opened on it, Bots 0.10), else where it came from.
2049
+ const key = t.showIn || t.origin?.threadKey;
2050
+ if (!key) return null;
2051
+ const worker = store.get(t.botId);
2052
+ const owner = t.requester?.botId ? store.get(t.requester.botId) : undefined;
2053
+ const chat = owner?.id ?? t.botId;
2054
+ const body = String(report.text ?? '').trim();
2055
+ if (isPanelThread(key)) {
2056
+ const topic = panelTopicOf(key);
2057
+ store.log({ from: t.botId, to: 'user', chat, text: body, kind: 'reply', thread: key, ...(topic ? { topic } : {}), ticket: t.id, status: report.status });
2058
+ return { where: threadLabel({ threadKey: key, ...(topic ? { threadTitle: store.message(topic)?.text } : {}) }) };
2059
+ }
2060
+ const signed = worker && owner && worker.id !== owner.id ? `【${worker.name}】\n${body}` : body;
2061
+ let sent = null;
2062
+ try {
2063
+ sent = channels.post({ thread: key }, signed, { replyTo: t.origin?.replyTo ?? '', typingOf: t.sessionId ?? '' });
2064
+ } catch (error) {
2065
+ ctx.logger?.warn?.(`bots: the report on task ${t.id} was not posted to its chat: ${error?.message ?? error}`);
2066
+ }
2067
+ if (!sent) return null;
2068
+ store.log({ from: t.botId, to: 'user', chat, text: body, kind: 'reply', via: sent.kind, thread: key, ticket: t.id, status: report.status });
2069
+ return { where: tickets.thread(key)?.label ?? threadLabel(sent) };
1622
2070
  }
1623
2071
 
1624
2072
  /** A person (the panel) or the requester ends a ticket (stop, or close as done); either cancels its running turn. */
@@ -1728,7 +2176,7 @@ export function apply(ctx, config, deps = {}) {
1728
2176
  await toTicket(t, { content: [{ type: 'text', text: nudgeText(t) }], source: sourceFrom(t.requester), key: `nudge:${t.id}:${now}` });
1729
2177
  } else {
1730
2178
  const stalled = tickets.patch(t.id, { stalledAt: now });
1731
- store.log({ from: t.botId, to: t.requester?.botId ?? 'user', text: `Task ${t.id} stalled: no report after a status check.`, kind: 'dm', ticket: t.id, status: 'stalled' });
2179
+ store.log({ from: t.botId, to: t.requester?.botId ?? 'user', text: `Task ${t.id} stalled: no report after a status check.`, kind: 'dm', ticket: t.id, status: 'stalled', ...topicFieldsOf(t) });
1732
2180
  if (slots.release(t.id)) void pump();
1733
2181
  // A ticket the user asked for has no Session to tell: the panel shows it (attention).
1734
2182
  if (stalled.requester?.kind === 'session') await notifyRequester(stalled, stalledNoticeText(stalled, cardCtx()), { key: `stalled:${t.id}:${now}` });
@@ -1749,7 +2197,9 @@ export function apply(ctx, config, deps = {}) {
1749
2197
  const reportedAt = asTicket ? Number(asTicket.reports.at(-1)?.at) || 0 : bot ? lastReplyAt(bot.id) : 0;
1750
2198
  return { status: agents()?.get?.(sessionId) ? agentStatusOf(sessionId) : 'offline', reportedAt, remindedAt };
1751
2199
  };
1752
- for (const r of requesterReminders(all.map((t) => ({ ticket: t, stage: stageOf(t) })), facts, now)) {
2200
+ // A task that answers the person itself (Bots 0.9) leaves its requester nothing to pass on.
2201
+ const relayed = all.filter((t) => !reportsGoDirect(t));
2202
+ for (const r of requesterReminders(relayed.map((t) => ({ ticket: t, stage: stageOf(t) })), facts, now)) {
1753
2203
  const list = r.ticketIds.map((id) => tickets.get(id)).filter(Boolean);
1754
2204
  if (!list.length) continue;
1755
2205
  try {
@@ -1801,7 +2251,7 @@ export function apply(ctx, config, deps = {}) {
1801
2251
  }
1802
2252
  const failed = tickets.end(t.id, { by: 'system', outcome: 'failed', error: reason });
1803
2253
  if (!failed) return;
1804
- store.log({ from: failed.botId, to: failed.requester?.botId ?? 'user', text: `Task ${failed.id} failed: ${reason}`, kind: 'dm', ticket: failed.id, status: 'failed' });
2254
+ store.log({ from: failed.botId, to: failed.requester?.botId ?? 'user', text: `Task ${failed.id} failed: ${reason}`, kind: 'dm', ticket: failed.id, status: 'failed', ...topicFieldsOf(failed) });
1805
2255
  ticketEnded(failed);
1806
2256
  if (failed.requester?.kind === 'session') void notifyRequester(failed, failedNoticeText(failed, cardCtx()), { key: `failed:${failed.id}:${failed.ended.at}` });
1807
2257
  }
@@ -1898,6 +2348,20 @@ export function apply(ctx, config, deps = {}) {
1898
2348
  tickets.archive(t.id);
1899
2349
  slots.release(t.id);
1900
2350
  }
2351
+ // Threads quiet for a day leave the sidebar; a new reply brings one back (Bots 0.10).
2352
+ for (const d of discussions.idle()) {
2353
+ if (openTasks.has(d.sessionId) || agents()?.get?.(d.sessionId)?.status === 'running') continue;
2354
+ uninstall(d.sessionId);
2355
+ forgetSession(d.sessionId);
2356
+ try {
2357
+ // The panel may be shown over this conversation: it opens itself again (see `rotatedAt`).
2358
+ rotatedAt = nowMs();
2359
+ await service(ctx, 'workspaceRegistry')?.archiveSession?.(d.sessionId);
2360
+ discussions.patch(d.key, { archivedAt: now });
2361
+ } catch (error) {
2362
+ ctx.logger?.warn?.(`bots: archiving a thread of @${store.get(d.botId)?.handle ?? '?'}: ${error?.message ?? error}`);
2363
+ }
2364
+ }
1901
2365
  await watch(now);
1902
2366
  tickets.flush();
1903
2367
  tickets.prune();
@@ -1964,6 +2428,26 @@ export function apply(ctx, config, deps = {}) {
1964
2428
  return sessions;
1965
2429
  }
1966
2430
 
2431
+ /**
2432
+ * The discussion a chat message goes to (Bots 0.10), or null for the bot's home: a message in a
2433
+ * Thread (a reply chain, a group thread, a forum topic) whose conversation the bot had before in
2434
+ * its home, or that answers one of its messages, is talked over in the home forked there. The
2435
+ * Thread's first message, and one that arrives while the home is still on that Thread, go home.
2436
+ */
2437
+ async function chatDiscussion(bot, meta) {
2438
+ const key = toThreadKey(meta?.threadKey);
2439
+ const p = key ? parseThreadKey(key) : null;
2440
+ if (!p || p.kind === 'panel' || p.rootId === undefined) return null;
2441
+ const known = discussions.get(key);
2442
+ let point = null;
2443
+ if (!known || known.botId !== bot.id) {
2444
+ if (known) return null;
2445
+ if (bot.sessionId && channels.current(bot.sessionId).some((o) => o.threadKey === key)) return null;
2446
+ point = forkPoint({ thread: discussions.anchorOf(key), root: discussions.anchorOf(chatMessageRef(p.appKey, p.chatId, p.rootId)) });
2447
+ if (!point || !isMine(bot, point.sessionId)) return null;
2448
+ }
2449
+ return discussionFor(bot, key, { point, rootId: p.rootId, title: titleOf(meta?.origin?.body ?? '') });
2450
+ }
1967
2451
  const channels = createChannels({
1968
2452
  file: join(dir, 'channels.json'),
1969
2453
  bots: () => store.list(),
@@ -1972,6 +2456,30 @@ export function apply(ctx, config, deps = {}) {
1972
2456
  // and its Thread (so the bot can name it in bot_reply). Its id comes from the chat message's, so a
1973
2457
  // message handed out again after a restart is not run twice.
1974
2458
  deliver: async (target, { header, body }, meta = {}) => {
2459
+ // A reply in a chat Thread the bot spoke in before: its discussion (Bots 0.10).
2460
+ let into = null;
2461
+ try {
2462
+ into = await chatDiscussion(store.get(target.id) ?? target, meta);
2463
+ } catch (error) {
2464
+ ctx.logger?.warn?.(`bots: a chat thread could not get its own conversation (${error?.message ?? error}); @${target.handle} takes it`);
2465
+ }
2466
+ if (into) {
2467
+ // The thread's first message carries the note, claimed before the hand-over (two may arrive at once).
2468
+ const first = !discussions.get(into.discussion.key)?.noted;
2469
+ if (first) discussions.patch(into.discussion.key, { noted: true });
2470
+ const note = first ? `${discussionNoteText({})}\n` : '';
2471
+ const sent = await sendTo(into.agent, {
2472
+ content: [
2473
+ { type: 'text', text: `${note}${header}${threadNote(meta.threadKey)}` },
2474
+ { type: 'text', text: body },
2475
+ ],
2476
+ source: { kind: 'user' },
2477
+ mode: homeMode(target),
2478
+ ...(meta.key ? { key: meta.key } : {}),
2479
+ });
2480
+ discussions.patch(into.discussion.key, { lastAt: nowMs() });
2481
+ return { sessionId: into.agent.session.id, messageId: sent.message.id, ...(sent.skipped ? { skipped: true } : {}) };
2482
+ }
1975
2483
  await autoTopic(store.get(target.id) ?? target, 'user');
1976
2484
  const agent = await agentOf(store.get(target.id) ?? target);
1977
2485
  const sent = await sendTo(agent, {
@@ -1991,6 +2499,10 @@ export function apply(ctx, config, deps = {}) {
1991
2499
  ticketThread: (id) => tickets.get(String(id ?? ''))?.origin?.threadKey,
1992
2500
  running: (sessionId) => agents()?.get?.(sessionId)?.status === 'running',
1993
2501
  newTopic: (bot) => newTopic(bot, 'manual'),
2502
+ homeKey: (sessionId) => discussions.bySession(sessionId)?.key,
2503
+ onSent: ({ tag, appKey, chatId, ids }) => {
2504
+ for (const id of ids) discussions.anchor(chatMessageRef(appKey, chatId, id), tag);
2505
+ },
1994
2506
  ...(deps.loadConnector ? { loadConnector: deps.loadConnector } : {}),
1995
2507
  ...(deps.typingEveryMs ? { typingEveryMs: deps.typingEveryMs } : {}),
1996
2508
  log: (line) => ctx.logger?.info?.(`bots: ${line}`),
@@ -2038,6 +2550,7 @@ export function apply(ctx, config, deps = {}) {
2038
2550
  /** Drop what is kept per Session for one that is gone: an archived task's, a topic left behind, a removed bot's. */
2039
2551
  function forgetSession(sessionId) {
2040
2552
  if (!sessionId) return;
2553
+ lastSeq.delete(sessionId);
2041
2554
  memoText.delete(sessionId);
2042
2555
  memoStale.delete(sessionId);
2043
2556
  deliveredIds.delete(sessionId);
@@ -2061,11 +2574,19 @@ export function apply(ctx, config, deps = {}) {
2061
2574
  }
2062
2575
  /** Reminder message id → the tickets it names (their origin Threads join the requester's turn). */
2063
2576
  const reminded = new Map();
2577
+ /** sessionId → the seq of its latest event: where a tool's chat message was said, as an anchor. */
2578
+ const lastSeq = new Map();
2064
2579
  ctx.on('session/event', (session, event) => {
2580
+ if (Number.isSafeInteger(event?.seq) && session?.id) lastSeq.set(session.id, event.seq);
2581
+ // A thread's Session starts with its source's events; should Harness ever report them, they were logged already.
2582
+ const forkedFrom = session?.id ? discussions.bySession(session.id)?.source : undefined;
2583
+ if (forkedFrom?.seq !== undefined && Number.isSafeInteger(event?.seq) && event.seq <= forkedFrom.seq) return;
2065
2584
  let bot;
2066
2585
  let via = null;
2067
2586
  let kind;
2068
2587
  let ticket;
2588
+ // A panel message's own text, without the header it reached the model with.
2589
+ let typedText;
2069
2590
  try {
2070
2591
  bot = botOfSession(session?.id);
2071
2592
  if (!bot || !event) return;
@@ -2088,8 +2609,9 @@ export function apply(ctx, config, deps = {}) {
2088
2609
  const id = String(event.data?.id ?? '');
2089
2610
  // The Harness tells a session about task edits made elsewhere; that is not a delivery.
2090
2611
  if (kind === 'schedule' && /^\[SCHEDULE CHANGE\]/.test(textOf(event.data.content))) kind = 'schedule-notice';
2091
- if (/^bots:followup:/.test(id)) {
2092
- // A follow-up went to its tasks directly; this notice (injected, it woke nothing) is no input of the turn.
2612
+ if (/^bots:(?:followup|shown):/.test(id)) {
2613
+ // A follow-up went to its tasks directly, or a report went to the person (injected notes that
2614
+ // woke nothing): no input of the turn.
2093
2615
  kind = 'followup-notice';
2094
2616
  } else {
2095
2617
  // A report (or notice) on a ticket this conversation asked for: answering it is speaking to the user.
@@ -2104,12 +2626,25 @@ export function apply(ctx, config, deps = {}) {
2104
2626
  st.answers = new Set();
2105
2627
  st.acted = false;
2106
2628
  turnState.set(session.id, st);
2107
- const said = textOf(event.data.content);
2108
- // A chat message adds its Thread to the turn's; a panel message adds the panel (lib/threads.mjs).
2109
- via = channels.noteUserMessage(session.id, bot, kind, said, { id, report: isReport });
2629
+ let said = textOf(event.data.content);
2630
+ // A message typed in the panel (Bots 0.9) is logged already; its topic joins the turn's Threads.
2631
+ const panelId = kind === 'user' ? /^bots:panel:(p[a-z0-9]{8})$/.exec(id)?.[1] : undefined;
2632
+ const typed = panelId ? store.message(panelId) : undefined;
2633
+ if (typed) said = typedText = typed.text;
2634
+ // Where it sits in the conversation, so a reply to it can fork there (Bots 0.10); again at the turn's end.
2635
+ const home = bot.sessionId === session.id;
2636
+ if (typed && home) {
2637
+ discussions.anchor(messageRef(typed.id), { sessionId: session.id, seq: event.seq });
2638
+ st.anchored = [...(st.anchored ?? []), messageRef(typed.id)];
2639
+ }
2640
+ const topicTitle = typed?.thread ? store.message(panelTopicOf(typed.thread))?.text : undefined;
2641
+ // A chat message adds its Thread to the turn's; a panel message its topic, or the panel (lib/threads.mjs).
2642
+ via = channels.noteUserMessage(session.id, bot, kind, said, { id, report: isReport, ...(typed?.thread ? { threadKey: typed.thread, origin: topicTitle ? { threadTitle: clip(topicTitle, 60).text } : {} } : {}) });
2110
2643
  // A drawing's note: the answer goes to the chats the person asked for it in.
2111
2644
  for (const o of drawingOrigins.get(id) ?? []) channels.noteInput(session.id, { threadKey: o.threadKey, origin: o });
2112
2645
  drawingOrigins.delete(id);
2646
+ // What arrives in a topic or chat since bot_reply answered it needs an answer again.
2647
+ if (st.replied) for (const k of [typed?.thread, via?.threadKey, ...about.map((t) => t.origin?.threadKey)]) if (k) st.replied.delete(k);
2113
2648
  // A report's ticket came from a Thread: the answer to the person goes there (PLAN-0.8 §4.3).
2114
2649
  for (const t of about) {
2115
2650
  const key = t.origin?.threadKey;
@@ -2118,9 +2653,22 @@ export function apply(ctx, config, deps = {}) {
2118
2653
  // The answer quotes the message that started the task, not whatever was said there last.
2119
2654
  channels.noteInput(session.id, { threadKey: key, origin: { ...(t.origin?.who ? { who: t.origin.who } : {}), ...(th?.label ? { label: th.label } : {}), ...(t.origin?.replyTo ? { replyTo: t.origin.replyTo } : {}) }, ticket: t.id });
2120
2655
  }
2121
- const thread = via ? via.threadKey : panelThreadKey(session.id);
2122
- if (kind === 'user') store.log(via ? { from: 'user', to: bot.id, text: via.body, kind: 'user', via: via.kind, who: via.who, ...(thread ? { thread } : {}) } : { from: 'user', to: bot.id, text: said, kind: 'user', ...(thread ? { thread } : {}) });
2123
- else if (kind === 'schedule') store.log({ from: 'schedule', to: bot.id, text: said, kind: 'system' });
2656
+ const thread = via ? via.threadKey : homeThreadOf(session.id);
2657
+ if (kind === 'user' && typed) {
2658
+ // Logged when it was sent.
2659
+ } else if (kind === 'user') {
2660
+ const topic = !via && isPanelThread(thread) ? panelTopicOf(thread) : '';
2661
+ const logged = store.log(via ? { from: 'user', to: bot.id, text: via.body, kind: 'user', via: via.kind, who: via.who, ...(thread ? { thread } : {}) } : { from: 'user', to: bot.id, text: said, kind: 'user', ...(thread ? { thread } : {}), ...(topic ? { topic } : {}) });
2662
+ if (home) {
2663
+ const refs = [messageRef(logged.id)];
2664
+ // A chat message: by its id in the chat app, and its Thread's latest exchange with the home.
2665
+ const chatMsg = /^bots:chat:(.+):([^:]+):([^:]+)$/.exec(id);
2666
+ if (chatMsg) refs.push(chatMessageRef(chatMsg[1], chatMsg[2], chatMsg[3]));
2667
+ if (via?.threadKey) refs.push(via.threadKey);
2668
+ for (const r of refs) discussions.anchor(r, { sessionId: session.id, seq: event.seq });
2669
+ st.anchored = [...(st.anchored ?? []), ...refs];
2670
+ }
2671
+ } else if (kind === 'schedule') store.log({ from: 'schedule', to: bot.id, text: said, kind: 'system' });
2124
2672
  }
2125
2673
  } else if (event.type === 'assistant/message') {
2126
2674
  const content = event.data?.message?.content ?? [];
@@ -2140,18 +2688,32 @@ export function apply(ctx, config, deps = {}) {
2140
2688
  // were reports and that only answered those tasks (they reach no one). The dispatcher reporting
2141
2689
  // back after its teammates answered is a message to the user, and so is any bot passing on a
2142
2690
  // report from a task it asked for, also in a turn where it hands out more work.
2143
- const hidden = why === 'schedule-notice' || (why === 'agent-message' && (bot.role !== 'primary' || answered.has(session.id))) || (why === 'report' && closingOnly(session.id));
2691
+ const plan = channels.replyPlan(session.id);
2692
+ // Closing words after bot_reply answered every topic or chat of the turn (Bots 0.9): each has its answer already.
2693
+ const topicsOfTurn = plan.origins.filter((o) => isTopicThread(o.threadKey));
2694
+ const allAnswered = topicsOfTurn.length > 0 && topicsOfTurn.every((o) => st?.replied?.has(o.threadKey));
2695
+ const hidden = why === 'schedule-notice' || (why === 'agent-message' && (bot.role !== 'primary' || answered.has(session.id))) || (why === 'report' && closingOnly(session.id)) || allAnswered;
2144
2696
  if (text && !hidden) {
2145
2697
  // To the turn's one chat Thread; with several (or the panel and a chat) it stays in the panel,
2146
2698
  // and bot_reply says where each answer goes.
2147
- const plan = channels.replyPlan(session.id);
2148
- const sent = channels.noteReply(session.id, text);
2149
- const thread = sent ? sent.threadKey : panelThreadKey(session.id);
2699
+ const home = bot.sessionId === session.id;
2700
+ const at = { sessionId: session.id, seq: event.seq };
2701
+ // Sent to a chat: the ids it gets there are anchors too (a reply to one of them is a discussion).
2702
+ const sent = channels.noteReply(session.id, text, home ? at : undefined);
2703
+ const thread = sent ? sent.threadKey : homeThreadOf(session.id);
2704
+ // A thread in the panel (a discussion, or a 0.9 topic): the reply is shown in it.
2705
+ const topic = isPanelThread(thread) ? panelTopicOf(thread) : '';
2150
2706
  const choices = plan.mode === 'choose' ? plan.origins.filter((o) => o.kind !== 'panel').map((o) => o.threadKey) : [];
2151
- store.log({ from: bot.id, to: 'user', text, kind: 'reply', ...(sent ? { via: sent.kind } : {}), ...(thread ? { thread } : {}), ...(choices.length ? { notSent: true, choices } : {}) });
2707
+ const logged = store.log({ from: bot.id, to: 'user', chat: bot.id, text, kind: 'reply', ...(sent && sent.kind !== 'panel' ? { via: sent.kind } : {}), ...(thread ? { thread } : {}), ...(topic ? { topic } : {}), ...(choices.length ? { notSent: true, choices } : {}) });
2708
+ if (home) {
2709
+ discussions.anchor(messageRef(logged.id), at);
2710
+ if (sent && sent.kind !== 'panel') discussions.anchor(sent.threadKey, at);
2711
+ }
2152
2712
  }
2153
2713
  } else if (event.type === 'turn/end') {
2154
2714
  channels.noteTurnEnd(session.id);
2715
+ // What the turn took in counts with the answer it gave: a reply to it forks after that answer.
2716
+ if (bot.sessionId === session.id) for (const r of turnState.get(session.id)?.anchored ?? []) discussions.anchor(r, { sessionId: session.id, seq: event.seq });
2155
2717
  turnState.delete(session.id);
2156
2718
  }
2157
2719
  } catch {
@@ -2163,8 +2725,8 @@ export function apply(ctx, config, deps = {}) {
2163
2725
  const sid = session.id;
2164
2726
  if (event.type === 'user/message') {
2165
2727
  if (!TASK_KINDS.has(kind)) return;
2166
- const task = openTasks.get(sid) ?? startTask(bot, sid, kind, event, via);
2167
- const said = textOf(event.data?.content);
2728
+ const task = openTasks.get(sid) ?? startTask(bot, sid, kind, event, via, typedText);
2729
+ const said = typedText ?? textOf(event.data?.content);
2168
2730
  const who = kind === 'schedule' ? 'scheduled' : kind === 'agent-message' ? (ticket ? 'task message' : 'bot message') : via ? `user via ${via.kind}` : 'user';
2169
2731
  logLine(task, `[${who}] ${via ? via.body : said}`);
2170
2732
  } else if (event.type === 'assistant/message') {
@@ -2436,6 +2998,19 @@ export function apply(ctx, config, deps = {}) {
2436
2998
  // The conversation stays where it is.
2437
2999
  }
2438
3000
  }
3001
+ // Its threads go with it.
3002
+ for (const d of discussions.list({ botId: bot.id })) {
3003
+ uninstall(d.sessionId);
3004
+ forgetSession(d.sessionId);
3005
+ if (!d.archivedAt) {
3006
+ try {
3007
+ await service(ctx, 'workspaceRegistry')?.archiveSession?.(d.sessionId);
3008
+ } catch {
3009
+ // The conversation stays where it is.
3010
+ }
3011
+ }
3012
+ discussions.remove(d.key);
3013
+ }
2439
3014
  // Its tickets end with it; their conversations are archived now.
2440
3015
  for (const t of tickets.list({ botId: bot.id, archived: false })) {
2441
3016
  if (!t.ended) endTicket(t, { by: 'system', outcome: 'stopped' });
@@ -2469,7 +3044,7 @@ export function apply(ctx, config, deps = {}) {
2469
3044
  function applyModel(bot) {
2470
3045
  if (!bot.model) return;
2471
3046
  const live = agents();
2472
- const ids = [bot.sessionId, ...tickets.list({ botId: bot.id, open: true }).map((t) => t.sessionId)].filter(Boolean);
3047
+ const ids = [bot.sessionId, ...discussions.list({ botId: bot.id, archived: false }).map((d) => d.sessionId), ...tickets.list({ botId: bot.id, open: true }).map((t) => t.sessionId)].filter(Boolean);
2473
3048
  for (const id of ids) {
2474
3049
  try {
2475
3050
  live?.get?.(id)?.model?.select?.(selectionOf(bot.model));
@@ -2766,7 +3341,8 @@ export function apply(ctx, config, deps = {}) {
2766
3341
  const sessionId = caller?.sessionId;
2767
3342
  const t = ticketOf(sessionId);
2768
3343
  if (t) return { kind: 'ticket', ticketId: t.id };
2769
- const bot = store.bySession(sessionId);
3344
+ // A home, or a thread of one (Bots 0.10).
3345
+ const bot = botOfSession(sessionId);
2770
3346
  if (!bot) return undefined;
2771
3347
  return isRouterHome(bot, sessionId) ? { kind: 'router' } : { kind: 'home' };
2772
3348
  }
@@ -2854,7 +3430,7 @@ export function apply(ctx, config, deps = {}) {
2854
3430
  name: 'bot_list',
2855
3431
  description: "List the user's bots: handle, name, role, status, bio, skills, apps and scheduled tasks. Use it before delegating to find the right bot.",
2856
3432
  parameters: {},
2857
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bots: v.bots }) },
3433
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bots: v.bots }) },
2858
3434
  isConcurrencySafe: () => true,
2859
3435
  execute: async () => {
2860
3436
  const bots = store.list();
@@ -2887,7 +3463,7 @@ export function apply(ctx, config, deps = {}) {
2887
3463
  ...AVATAR_PARAMS,
2888
3464
  skills: { ...skillInput, description: 'Skills to give it.' },
2889
3465
  },
2890
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
3466
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot }) },
2891
3467
  execute: async (args, exec) => {
2892
3468
  const caller = actor(exec);
2893
3469
  const by = caller.bot;
@@ -2923,7 +3499,7 @@ export function apply(ctx, config, deps = {}) {
2923
3499
  remove_skills: { type: 'array', items: { type: 'string' }, description: 'Names of skills to remove.' },
2924
3500
  make_dispatcher: { type: 'boolean', description: 'true to make this bot the dispatcher.' },
2925
3501
  },
2926
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
3502
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot }) },
2927
3503
  execute: async (args, exec) => {
2928
3504
  // A helper whose line cannot be traced still changes bots, as before; it waits for a drawing.
2929
3505
  const caller = actorOf(exec);
@@ -2946,7 +3522,7 @@ export function apply(ctx, config, deps = {}) {
2946
3522
  name: 'bot_delete',
2947
3523
  description: 'Delete a bot, its scheduled tasks, and archive its conversation. Only when the user asked for it.',
2948
3524
  parameters: { bot: { type: 'string', required: true, description: '@handle, id or name.' } },
2949
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
3525
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot }) },
2950
3526
  execute: async (args, exec) => {
2951
3527
  const bot = resolve(args.bot);
2952
3528
  if (callerBot(exec)?.id === bot.id) throw new Error('a bot cannot delete itself; ask the dispatcher or the user');
@@ -2960,8 +3536,10 @@ export function apply(ctx, config, deps = {}) {
2960
3536
  description: [
2961
3537
  'Message another bot, or report on the task this conversation works on. Make the text self-contained: the other bot cannot see this conversation. Do not reply to acknowledgements.',
2962
3538
  "- To delegate: `to` (the bot's @handle) and `text`. Depending on how the team works, this opens a task (ticket) that the bot works on in a conversation of its own, or drops the text into that bot's own conversation; the result says which. Either way the call returns at once and the answer (a report, or a bot message) arrives here by itself: never wait or poll for it.",
2963
- '- When this turn involves several chats, name the one a new task is for with `thread` (its key), so its report answers there.',
2964
- '- To add to an open task you asked for (an answer to its question, a change): `ticket` (its id) and `text`.',
3539
+ '- When this turn involves several topics or chats, name the one a new task is for with `thread` (as its message header shows it), so its answer goes there.',
3540
+ '- The dispatcher may name itself in `to`: it then does the work in a task conversation of its own, with all its tools.',
3541
+ '- A task from a topic or chat answers the person there itself; pass `report_to: "me"` to get its reports back instead (to combine several results).',
3542
+ '- To add to an open task you asked for (an answer to its question, a change, a message of the person\'s that continues it): `ticket` (its id) and `text`.',
2965
3543
  '- In a task conversation, to report to whoever asked: leave out `to`, give `text` and a `status` (progress, done, blocked, question).',
2966
3544
  ].join('\n'),
2967
3545
  parameters: {
@@ -2970,9 +3548,10 @@ export function apply(ctx, config, deps = {}) {
2970
3548
  ticket: { type: 'string', description: 'Id of an open task to add this message to.' },
2971
3549
  status: { type: 'string', enum: REPORT_STATUSES, description: 'Required when reporting from a task conversation: progress (an update worth keeping), done (with the result), blocked, question.' },
2972
3550
  title: { type: 'string', description: 'A short title for a new task; taken from the first line of text when left out.' },
2973
- thread: { type: 'string', description: 'Only when this turn involves several chats: the key of the thread (as the message header "(thread …)" shows it) the new task is for. Its report then answers there, and follow-ups there reach the task. Left out with several chats, the task belongs to none of them.' },
3551
+ thread: { type: 'string', description: 'Only when this turn involves several topics or chats: the thread (as the message header "(thread …)" shows it) the new task, or the message added to a task, is for. A new task then answers there, and follow-ups there reach it. Left out with several, a new task belongs to none of them.' },
3552
+ report_to: { type: 'string', enum: ['thread', 'me'], description: 'For a new task: "thread" (default) — its bot answers the person in the topic or chat the request came from; "me" — its reports come back to you.' },
2974
3553
  },
2975
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ to: v.to, from: v.from, ...(v.ticket ? { ticket: v.ticket } : {}) }) },
3554
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ to: v.to, from: v.from, ...(v.ticket ? { ticket: v.ticket } : {}) }) },
2976
3555
  isConcurrencySafe: () => true,
2977
3556
  execute: async (args, exec) => {
2978
3557
  const { sessionId, bot: sender } = actor(exec);
@@ -2988,11 +3567,13 @@ export function apply(ctx, config, deps = {}) {
2988
3567
  const isReport = wantTicket ? wantTicket === mine.id : !named || (named.id === requesterBot && named.id !== sender.id);
2989
3568
  if (isReport) {
2990
3569
  if (!status) throw new Error(`a report on task ${mine.id} needs a status: progress (an update), done (with the result), blocked or question`);
2991
- const { ticket, relayed, unread, parent } = await reportTicket(mine, status, args.text);
3570
+ const { ticket, relayed, unread, parent, shown } = await reportTicket(mine, status, args.text);
2992
3571
  const to = requesterBot ? store.get(requesterBot) : null;
2993
3572
  const said =
2994
3573
  status === 'progress'
2995
3574
  ? `Recorded on task ${ticket.id}; progress does not interrupt whoever asked. Go on with the work.`
3575
+ : shown
3576
+ ? `Shown to the person as it is, in ${shown.where}${to ? `; @${to.handle} is told` : ''}.${status === 'done' ? ' The task is done: end your turn without a summary.' : ' Their answer will arrive here by itself; end your turn now.'}`
2996
3577
  : unread
2997
3578
  ? `Recorded "${status}" on task ${ticket.id}, but nobody is told: ${unread === 'ended' ? `the task has ended (${stageOf(ticket)})` : `the task that asked for it${parent ? `, ${parent},` : ''} has ended`}. The report is kept on the task; end your turn now.`
2998
3579
  : `Reported "${status}" on task ${ticket.id} to ${to ? `@${to.handle}` : 'the user'}${relayed || !to ? '' : ' (it could not be reached just now; the report is kept on the task)'}.${status === 'done' ? ' The task is done: end your turn without a summary.' : ' An answer will arrive here by itself; end your turn now.'}`;
@@ -3001,28 +3582,40 @@ export function apply(ctx, config, deps = {}) {
3001
3582
  }
3002
3583
  if (status) throw new Error(mine ? `\`status\` is for reports to whoever asked for task ${mine.id} (leave out "to"); to ask @${named?.handle ?? 'a bot'} for help, leave out \`status\`` : '`status` is only for reports from a task conversation; leave it out here');
3003
3584
 
3585
+ const chosen = typeof args.thread === 'string' && args.thread.trim() !== '' ? threadRef(args.thread, sessionId) : '';
3004
3586
  // Adding to an existing ticket.
3005
3587
  if (wantTicket) {
3006
3588
  const t = tickets.get(wantTicket);
3007
3589
  if (!t) throw new Error(`no task ${wantTicket}`);
3008
3590
  if (named && named.id !== t.botId) throw new Error(`task ${t.id} belongs to ${handleOf(t.botId)}, not @${named.handle}; leave out "to" or name its bot`);
3009
3591
  if (!mayAppend(t, sender, sessionId)) throw new Error(`task ${t.id} was not asked for from this conversation; message its bot with a new task instead`);
3010
- const next = await appendToTicket(t, args.text, { sender: sender ?? null, senderSessionId: sessionId });
3592
+ let next = await appendToTicket(t, args.text, { sender: sender ?? null, senderSessionId: sessionId });
3593
+ // Carried on from a thread (Bots 0.10): the task follows the thread, and its reports show there.
3594
+ const here = !mine ? discussions.bySession(sessionId) : undefined;
3595
+ if (here && reportsGoDirect(next) && (next.showIn ?? next.origin?.threadKey) !== here.key) {
3596
+ tickets.subscribe(next.id, here.key);
3597
+ next = tickets.patch(next.id, { showIn: here.key }) ?? next;
3598
+ }
3011
3599
  const target = store.get(next.botId);
3012
3600
  const waits = next.startedAt && parkedOf(next).length > 0 ? ': every worker slot is taken, so it is handed over when one frees' : '';
3013
- return { ok: true, text: `Added to task ${next.id} (${stageOf(next)}${waits}). ${handleOf(next.botId)}'s report will arrive here by itself; do not wait for it.`, ticket: row(next), to: face(target), from: face(sender) };
3601
+ const after = reportsGoDirect(next) ? `${handleOf(next.botId)} answers the person ${isPanelThread(next.showIn ?? next.origin?.threadKey) ? 'in the panel' : 'in the chat'} itself` : `${handleOf(next.botId)}'s report will arrive here by itself`;
3602
+ return { ok: true, text: `Added to task ${next.id} (${stageOf(next)}${waits}). ${after}; do not wait for it.`, ticket: row(next), to: face(target), from: face(sender) };
3014
3603
  }
3015
3604
  if (!named) throw new Error(mine ? 'say which bot with `to`, or leave it out and give a `status` to report on your task' : 'say which bot with `to`');
3016
3605
 
3017
3606
  // A new ticket: from a task conversation (a sub-task), or from a bot's home when tasks are on.
3018
- const chosen = typeof args.thread === 'string' && args.thread.trim() !== '' ? args.thread.trim() : '';
3019
- if (sender && sessionId && (mine || (ticketsOn() && sender.sessionId === sessionId))) {
3020
- const t = await openTicket(sender, named, args.text, sessionId, { title: args.title, thread: chosen });
3607
+ if (sender && sessionId && (mine || (ticketsOn() && isHomeOf(sender, sessionId)))) {
3608
+ const relay = String(args.report_to ?? '').trim().toLowerCase() === 'me';
3609
+ const t = await openTicket(sender, named, args.text, sessionId, { title: args.title, thread: chosen, relay });
3021
3610
  const stage = stageOf(t);
3611
+ const who = named.id === sender.id ? 'yourself' : `@${named.handle}`;
3612
+ const answer = reportsGoDirect(t)
3613
+ ? `${named.id === sender.id ? 'You answer' : `@${named.handle} answers`} the person in ${isPanelThread(t.origin?.threadKey) ? (panelTopicOf(t.origin.threadKey) ? 'the thread' : 'the panel chat') : 'the chat'} it came from, and you get a note; do not wait for it or repeat it — tell the person in one line who is on it and end your turn.`
3614
+ : 'Its report will arrive here by itself; never wait or poll for it — go on with other work or end your turn.';
3022
3615
  const said =
3023
3616
  stage === 'failed'
3024
- ? `Task ${t.id} for @${named.handle} could not start: ${t.error ?? 'unknown error'}.`
3025
- : `Opened task ${t.id} for @${named.handle} (${stage === 'queued' ? 'queued: it starts when another task finishes' : stage}). Its report will arrive here by itself; never wait or poll for it — go on with other work or end your turn.`;
3617
+ ? `Task ${t.id} for ${who} could not start: ${t.error ?? 'unknown error'}.`
3618
+ : `Opened task ${t.id} for ${who} (${stage === 'queued' ? 'queued: it starts when another task finishes' : stage}). ${answer}`;
3026
3619
  return { ok: stage !== 'failed', text: said, ticket: row(t), stage, to: face(named), from: face(sender) };
3027
3620
  }
3028
3621
  // 0.7: into the other bot's home (the user from any conversation; any home in hands-on mode).
@@ -3034,36 +3627,53 @@ export function apply(ctx, config, deps = {}) {
3034
3627
  defineTool({
3035
3628
  name: 'bot_reply',
3036
3629
  description:
3037
- 'Send text to a chat: the chat a task came from (`ticket`: its id) or a chat thread (`thread`: its key, as message headers "(thread …)" and task cards show it). Use it when this turn involves more than one chat, so each answer reaches its own chat; your plain text then stays in the panel. With a single chat in the turn, plain text goes there already.',
3630
+ 'Answer in a topic or chat: the one a task came from (`ticket`: its id), or a thread (`thread`: as message headers "(thread …)" and task cards show it — a panel topic `p…`, or a chat thread key). Use it when this turn involves more than one topic or chat, so each answer stays in its own; your plain text then reaches none of them. With a single one in the turn, plain text goes there already.',
3038
3631
  parameters: {
3039
- ticket: { type: 'string', description: 'Id of a task (t…): the reply goes to the chat that task came from.' },
3040
- thread: { type: 'string', description: 'Key of a chat thread of this turn (or of a task you know of).' },
3632
+ ticket: { type: 'string', description: 'Id of a task (t…): the reply goes to the topic or chat that task came from.' },
3633
+ thread: { type: 'string', description: 'A panel topic (p…) or chat thread key of this turn (or of a task you know of).' },
3041
3634
  text: { type: 'string', required: true, description: 'The reply, as the person should read it.' },
3042
3635
  },
3043
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ via: v.via, thread: v.thread }) },
3636
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ via: v.via, thread: v.thread }) },
3044
3637
  execute: async (args, exec) => {
3045
3638
  const { sessionId, bot } = actor(exec);
3046
3639
  if (ticketOf(sessionId)) throw new Error('a task conversation talks to no chat: report with bot_send_message (leave out "to"), and whoever asked passes it on');
3047
3640
  if (!bot) throw new Error("bot_reply answers from a bot's own conversation; this conversation has no chats");
3048
3641
  const body = String(args.text ?? '').trim();
3049
3642
  if (body === '') throw new Error('text must not be empty');
3050
- const thread = typeof args.thread === 'string' && args.thread.trim() !== '' ? args.thread.trim().replace(/^thread\//, '') : '';
3643
+ const thread = typeof args.thread === 'string' && args.thread.trim() !== '' ? threadRef(args.thread, sessionId) : '';
3051
3644
  const ticketId = typeof args.ticket === 'string' && args.ticket.trim() !== '' ? args.ticket.trim().replace(/^(?:ticket|task)\//, '') : '';
3052
3645
  const options = () => {
3053
- const list = channels.current(sessionId).filter((o) => o.kind !== 'panel');
3054
- return list.length
3055
- ? `This turn's chats: ${list.map((o) => `${o.threadKey} (${threadLabel(o)}${o.tickets?.length ? `; task ${o.tickets.join(', ')}` : ''})`).join('; ')}.`
3056
- : 'This turn has no chat; a task id names the chat it came from.';
3646
+ const list = turnChoices(sessionId);
3647
+ return list.length ? `This turn's topics and chats: ${list.join('; ')}.` : 'This turn has no topic or chat; a task id names the one it came from.';
3648
+ };
3649
+ if (!thread && !ticketId) throw new Error(`say where: \`ticket\` (a task id) or \`thread\` (a topic or thread). ${options()}`);
3650
+ // A topic in the panel (Bots 0.9): this turn's, one a task came from, or any the bot's chat has.
3651
+ const asked = ticketId ? tickets.get(ticketId) : undefined;
3652
+ const panelKey = thread ? (panelTopicOf(thread) ? thread : '') : panelTopicOf(asked?.origin?.threadKey) ? asked.origin.threadKey : '';
3653
+ // A panel topic of this bot's own chat only: one whose first message is there, or a task it asked for or does.
3654
+ if (panelKey) {
3655
+ const root = store.message(panelTopicOf(panelKey));
3656
+ const mine = thread ? Boolean(root) && inChat(root, bot.id) : Boolean(asked) && (asked.requester?.botId === bot.id || asked.botId === bot.id);
3657
+ if (!mine) throw new Error(`${thread ? `no topic "${args.thread}"` : `task ${ticketId} came from no topic`} in this bot's chat. ${options()}`);
3658
+ }
3659
+ const target = panelKey ? { kind: 'panel', threadKey: panelKey } : channels.resolveReply(sessionId, thread ? { thread } : { ticket: ticketId });
3660
+ if (!target) throw new Error(`${thread ? `no topic or chat thread "${thread}"` : `no topic or chat for task ${ticketId}`} can be reached from here. ${options()}`);
3661
+ const answeredHere = () => {
3662
+ const st = turnState.get(sessionId);
3663
+ if (st) (st.replied ??= new Set()).add(target.threadKey);
3057
3664
  };
3058
- if (!thread && !ticketId) throw new Error(`say where: \`ticket\` (a task id) or \`thread\` (a thread key). ${options()}`);
3059
- const target = channels.resolveReply(sessionId, thread ? { thread } : { ticket: ticketId });
3060
- if (!target) throw new Error(`${thread ? `no chat thread "${thread}"` : `no chat for task ${ticketId}`} can be reached from here. ${options()}`);
3061
3665
  if (target.kind === 'panel') {
3062
- store.log({ from: bot.id, to: 'user', text: body, kind: 'reply', thread: panelThreadKey(sessionId) });
3063
- return { ok: true, text: 'That thread is the panel: the reply is shown there.', thread: target.threadKey };
3666
+ const topic = panelTopicOf(target.threadKey);
3667
+ const chat = (topic && store.message(topic)?.chat) || bot.id;
3668
+ store.log({ from: bot.id, to: 'user', chat, text: body, kind: 'reply', thread: topic ? target.threadKey : panelThreadKey(sessionId), ...(topic ? { topic } : {}) });
3669
+ answeredHere();
3670
+ return { ok: true, text: topic ? `Shown in the panel, in thread ${topic}.` : 'That thread is the panel: the reply is shown there.', thread: target.threadKey };
3064
3671
  }
3065
- channels.replyTo(sessionId, target, body);
3066
- store.log({ from: bot.id, to: 'user', text: body, kind: 'reply', via: target.kind, thread: target.threadKey });
3672
+ // Said from the home: a reply to it in the chat is a thread that forks here (Bots 0.10).
3673
+ const at = bot.sessionId === sessionId && lastSeq.has(sessionId) ? { sessionId, seq: lastSeq.get(sessionId) } : undefined;
3674
+ channels.replyTo(sessionId, target, body, at);
3675
+ answeredHere();
3676
+ store.log({ from: bot.id, to: 'user', chat: bot.id, text: body, kind: 'reply', via: target.kind, thread: target.threadKey });
3067
3677
  return { ok: true, text: `Sent to ${threadLabel(target)}.`, thread: target.threadKey, via: target.kind };
3068
3678
  },
3069
3679
  }),
@@ -3099,7 +3709,7 @@ export function apply(ctx, config, deps = {}) {
3099
3709
  id: { type: 'string', required: true, description: 'The task id (t…), as on its card.' },
3100
3710
  action: { type: 'string', required: true, enum: ['stop', 'close', 'retry', 'status'] },
3101
3711
  },
3102
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ ticket: v.ticket }) },
3712
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ ticket: v.ticket }) },
3103
3713
  execute: async (args, exec) => {
3104
3714
  const caller = actor(exec);
3105
3715
  const sessionId = caller.sessionId;
@@ -3162,7 +3772,7 @@ export function apply(ctx, config, deps = {}) {
3162
3772
  cron: { type: 'string' },
3163
3773
  time_zone: { type: 'string', description: `IANA zone, default ${zone}.` },
3164
3774
  },
3165
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot, task: v.task }) },
3775
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot, task: v.task }) },
3166
3776
  execute: async (args, exec) => {
3167
3777
  const actorId = exec?.agent?.session?.id;
3168
3778
  const bot = args.bot ? resolve(args.bot) : callerBot(exec) ?? store.primary();
@@ -3204,7 +3814,7 @@ export function apply(ctx, config, deps = {}) {
3204
3814
  kind: { type: 'string', enum: MEMORY_KINDS },
3205
3815
  replace_id: { type: 'string', description: 'Id of an existing note this one corrects or replaces.' },
3206
3816
  },
3207
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ note: v.note, scope: v.scope }) },
3817
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ note: v.note, scope: v.scope }) },
3208
3818
  execute: async (args, exec) => {
3209
3819
  const me = callerBot(exec);
3210
3820
  const scope = args.scope === 'team' ? 'team' : 'self';
@@ -3389,6 +3999,8 @@ export function apply(ctx, config, deps = {}) {
3389
3999
  mcp: Boolean(mcpClient),
3390
4000
  // Off for a router dispatcher unless its bot lists them in `tools.routerAllow`.
3391
4001
  routerDeny: [...ROUTER_DENY],
4002
+ // Off for the dispatcher while the team has more than one bot: its teammates help instead.
4003
+ teamDeny: inTeam() ? [...SUBAGENT_TOOLS] : [],
3392
4004
  zone,
3393
4005
  };
3394
4006
  }
@@ -3696,6 +4308,9 @@ export function apply(ctx, config, deps = {}) {
3696
4308
  ticketMap,
3697
4309
  messageCount: store.messageCount(),
3698
4310
  version: store.version(),
4311
+ // The Bots this process loaded (the panel asks for a restart when it is newer), and the last new topic.
4312
+ botsVersion: VERSION,
4313
+ rotatedAt,
3699
4314
  limits: { skills: MAX_SKILLS, skillsOn: MAX_SKILLS_ON },
3700
4315
  teamNotes: memory.notes('team').length,
3701
4316
  dispatcher: s.dispatcher,
@@ -3926,7 +4541,7 @@ export function apply(ctx, config, deps = {}) {
3926
4541
  const text = zhText
3927
4542
  ? `请为你自己写一个新技能:${ask}\n\n如果有 skill-creator 技能,先加载它并按它的方法写。写好后调用 bot_update(bot: @${bot.handle},add_skills)保存:name 用小写英文短横线,description 一句话写清楚何时使用,content 是完整的 Markdown 指南。最后用两三句话告诉我这个技能能做什么。`
3928
4543
  : `Write a new skill for yourself: ${ask}\n\nIf the skill-creator skill is available, load it and follow it. Save the result with bot_update (bot: @${bot.handle}, add_skills): a lowercase-dashed name, a one-sentence description of when to use it, and the full Markdown instructions as content. Then tell me in two or three sentences what the skill does.`;
3929
- return { ok: true, sessionId: await userSend(bot, text) };
4544
+ return { ok: true, sessionId: (await userSend(bot, text)).sessionId };
3930
4545
  },
3931
4546
  },
3932
4547
  'apps/external': { get: () => ({ items: scanExternalMcp().map(maskedApp) }) },
@@ -3952,9 +4567,7 @@ export function apply(ctx, config, deps = {}) {
3952
4567
  catalog: { get: () => catalog() },
3953
4568
  // A link preview card for the chat: YouTube, X posts, or any page's OpenGraph meta.
3954
4569
  unfurl: { get: (url) => unfurlLink(url.searchParams.get('url') ?? '') },
3955
- messages: {
3956
- get: (url) => ({ items: store.messages({ bot: url.searchParams.get('bot') ?? '', limit: Number(url.searchParams.get('limit')) || 200 }) }),
3957
- },
4570
+ messages: { get: (url) => messagesView(url) },
3958
4571
  schedules: {
3959
4572
  get: async (url) => {
3960
4573
  const id = url.searchParams.get('bot');
@@ -3999,7 +4612,8 @@ export function apply(ctx, config, deps = {}) {
3999
4612
  post: async (body) => {
4000
4613
  const bot = store.get(String(body.to ?? ''));
4001
4614
  if (!bot) return { ok: false, reason: 'no such bot' };
4002
- return { ok: true, sessionId: await userSend(bot, body.text) };
4615
+ const sent = await userSend(bot, body.text, { replyTo: String(body.replyTo ?? '') });
4616
+ return { ok: true, sessionId: sent.sessionId, ...(sent.message ? { message: sent.message } : {}) };
4003
4617
  },
4004
4618
  },
4005
4619
  avatar: {
@@ -4116,6 +4730,15 @@ export function apply(ctx, config, deps = {}) {
4116
4730
  },
4117
4731
  },
4118
4732
  'memory/dream': { post: async () => ({ ok: true, result: await dream({ reason: 'manual' }) }) },
4733
+ 'threads/seen': {
4734
+ post: (body) => {
4735
+ const root = String(body.root ?? '');
4736
+ const m = root ? store.message(root) : undefined;
4737
+ if (!m || (body.bot && !inChat(m, String(body.bot)))) return { ok: false, reason: 'no such message' };
4738
+ discussions.markSeen(root, nowMs());
4739
+ return { ok: true, unread: 0 };
4740
+ },
4741
+ },
4119
4742
  'topic/new': {
4120
4743
  post: async (body) => {
4121
4744
  const bot = store.get(String(body.id ?? ''));
@@ -4140,6 +4763,69 @@ export function apply(ctx, config, deps = {}) {
4140
4763
  'channels/reconnect': { post: (body) => ({ ok: channels.reconnect(String(body.botId ?? ''), String(body.appId ?? '')) }) },
4141
4764
  };
4142
4765
 
4766
+ /**
4767
+ * GET /messages?bot=&limit=: a bot's chat as it was said, oldest first (Bots 0.10): a reply in a
4768
+ * thread is in it too, with the message it quotes (`quote`, like a chat app's quoted reply); and a
4769
+ * summary of the thread under each of its messages that has one. With `topic=<rootId>`: that
4770
+ * thread alone, its root first. Without `bot`: everything.
4771
+ */
4772
+ function messagesView(url) {
4773
+ const bot = url.searchParams.get('bot') ?? '';
4774
+ const topic = url.searchParams.get('topic') ?? '';
4775
+ const limit = Number(url.searchParams.get('limit')) || (topic ? 500 : 200);
4776
+ if (topic) {
4777
+ const items = store.messages({ bot, limit, topic }).map(messageView);
4778
+ const replies = store.replies(bot, [topic]);
4779
+ const sum = threadSummary(topic, replies.get(topic) ?? [], items.find((m) => m.id === topic) ?? store.message(topic));
4780
+ return { items, threads: sum ? { [topic]: sum } : {} };
4781
+ }
4782
+ const rows = store.messages({ bot, limit, roots: false });
4783
+ const byId = new Map(rows.map((m) => [m.id, m]));
4784
+ const roots = new Set(rows.map(rootIdOf).filter(Boolean));
4785
+ const replies = store.replies(bot, roots);
4786
+ const lookup = (id) => byId.get(id) ?? store.message(id);
4787
+ const items = rows.map((m) => {
4788
+ const v = messageView(m);
4789
+ const q = quoteOf(m, replies, lookup);
4790
+ return q ? { ...v, quote: q } : v;
4791
+ });
4792
+ const threads = {};
4793
+ for (const m of rows) {
4794
+ if (rootIdOf(m) !== m.id) continue;
4795
+ const sum = threadSummary(m.id, replies.get(m.id) ?? [], m);
4796
+ if (sum) threads[m.id] = sum;
4797
+ }
4798
+ return { items, threads };
4799
+ }
4800
+ /**
4801
+ * The thread under a panel message as the chat lists it (PLAN-0.10 §7.2): its key, how many
4802
+ * replies, the latest, how many of the bots' replies came since the person looked, whether a
4803
+ * bot is answering in it now, and the tasks it follows. Null when the message has no thread.
4804
+ */
4805
+ function threadSummary(rootId, replies, root) {
4806
+ const d = discussions.byRoot(rootId);
4807
+ const key = d?.key || topicKeyOf(root, rootId) || replies.find((m) => panelTopicOf(m.thread) === rootId)?.thread || '';
4808
+ const list = key ? tickets.subscribers(key).filter((t) => !t.archivedAt) : [];
4809
+ const said = replies.filter((m) => m.kind !== 'system' && m.kind !== 'topic' && !betweenBots(m) && m.from !== m.to);
4810
+ if (!said.length && !d && !list.length) return null;
4811
+ const last = said.at(-1);
4812
+ const seen = discussions.seenAt(rootId);
4813
+ const unread = said.filter((m) => m.from !== 'user' && Number(m.at) > seen).length;
4814
+ // The thread's bot answering now (the chat shows it at work); `running` counts its working tasks too.
4815
+ const answering = Boolean(d) && agents()?.get?.(d.sessionId)?.status === 'running';
4816
+ const running = answering || list.some((t) => stageOf(t) === 'working');
4817
+ return {
4818
+ key,
4819
+ count: said.length,
4820
+ lastAt: last ? Number(last.at) || 0 : 0,
4821
+ last: last ? { from: last.from, text: clip(String(last.text ?? ''), PREVIEW_CHARS).text } : null,
4822
+ unread,
4823
+ running,
4824
+ answering,
4825
+ tickets: list.map(ticketRow),
4826
+ };
4827
+ }
4828
+
4143
4829
  /** GET /tickets?bot=&stage=&limit=&offset=: rows, the latest change first; `stage` may list several (a,b). */
4144
4830
  function ticketList(url) {
4145
4831
  const bot = url.searchParams.get('bot') || undefined;
@@ -4158,9 +4844,11 @@ export function apply(ctx, config, deps = {}) {
4158
4844
  const th = tickets.thread(key);
4159
4845
  const parsed = parseThreadKey(key);
4160
4846
  if (!th && !parsed) return { ok: false, reason: 'no such thread' };
4847
+ // The panel as a whole holds its topics (`panel:<sessionId>:<root>`).
4848
+ const whole = isPanelThread(key) && !panelTopicOf(key);
4161
4849
  const recent = store
4162
4850
  .messages({ limit: 2000 })
4163
- .filter((m) => m.thread === key)
4851
+ .filter((m) => m.thread === key || (whole && String(m.thread ?? '').startsWith(`${key}:`)))
4164
4852
  .slice(-10)
4165
4853
  .map((m) => ({ at: m.at, from: m.from, to: m.to, ...(m.who ? { who: m.who } : {}), text: clip(String(m.text ?? ''), 300).text }));
4166
4854
  return { key, label: th?.label ?? threadLabel(key), kind: th?.kind ?? parsed?.kind ?? '', tickets: tickets.subscribers(key).map(ticketRow), recent };
@@ -4267,7 +4955,7 @@ export function apply(ctx, config, deps = {}) {
4267
4955
 
4268
4956
  /** For tests: which per-Session records this process still keeps for `sessionId`. */
4269
4957
  const tracked = (sessionId) => ({ trigger: trigger.has(sessionId), answered: answered.has(sessionId), turn: turnState.has(sessionId), delivered: deliveredIds.has(sessionId), history: historyRead.has(sessionId) });
4270
- return { store, state, deliver, install, reconcile, installed, routes, channels, memory, ledger, topics, settings, newTopic, dream, sweep, userSend, openTasks, codexSync, finishTask, tickets, slots, pump, botOfSession, request, ticketView, ticketUpkeep, watch, startup, recoverTickets, tracked };
4958
+ return { store, state, deliver, install, reconcile, installed, routes, channels, memory, ledger, topics, settings, newTopic, dream, sweep, userSend: async (...a) => (await userSend(...a)).sessionId, panelSend: userSend, openTasks, codexSync, finishTask, tickets, slots, pump, botOfSession, request, ticketView, ticketUpkeep, watch, startup, recoverTickets, tracked };
4271
4959
  }
4272
4960
 
4273
4961
  function serveAvatar(dir, req, res) {
@@ -4294,6 +4982,14 @@ function serveAvatar(dir, req, res) {
4294
4982
  }
4295
4983
 
4296
4984
  const LOGO_DIR = fileURLToPath(new URL('./logos/', import.meta.url));
4985
+ /** The Bots version this process loaded: the panel compares it with its own, to say when Harness needs a restart. */
4986
+ const VERSION = (() => {
4987
+ try {
4988
+ return String(JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version ?? '');
4989
+ } catch {
4990
+ return '';
4991
+ }
4992
+ })();
4297
4993
 
4298
4994
  /** `${R}/logo/<name>.png`: an app logo shipped with the plugin. */
4299
4995
  export function serveLogo(req, res) {