@kadaliao/dsh-bots 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -55,11 +55,12 @@ 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, panelHeaderText, PREVIEW_CHARS, readResource, recoveryNoteText, reminderText, reportRelayText, retryText, shownNoticeText, 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
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
  }
@@ -352,13 +359,51 @@ export function apply(ctx, config, deps = {}) {
352
359
  // --- applying a bot to its Agent ----------------------------------------------------
353
360
  /** sessionId → {agent, signature, disposers[]} */
354
361
  const installed = new Map();
362
+ /**
363
+ * The first sentence of each Harness tool's description, by name, as a bot's conversation has it
364
+ * before Bots limits it: noted when a conversation is set up (before its limits apply) and when the
365
+ * catalog is read. A router home's own view lacks `bash` or `web_search`; the profile still lists
366
+ * them, marked off in Router mode (0.10.1).
367
+ */
368
+ const toolInfo = new Map();
369
+ const toolLine = (d) => String(d?.description ?? '').split(/(?<=\.)\s/)[0].slice(0, 200);
370
+ /** Note the definitions `scope` sees; returns their names. */
371
+ function noteTools(scope) {
372
+ const names = [];
373
+ try {
374
+ for (const d of ctx.tools?.definitions?.(scope) ?? []) {
375
+ toolInfo.set(d.name, toolLine(d));
376
+ names.push(d.name);
377
+ }
378
+ } catch {
379
+ // No registry view.
380
+ }
381
+ return names;
382
+ }
383
+ /** The tools `scope` would have with no limits: what it sees, and the names a limit hides (Harness `restrictableNames`). */
384
+ function unlimitedTools(scope) {
385
+ const names = new Set(noteTools(scope));
386
+ try {
387
+ const hidden = ctx.tools?.view?.(scope)?.restrictableNames;
388
+ if (hidden instanceof Set) for (const n of hidden) names.add(n);
389
+ } catch {
390
+ // A Harness without the view lists what the scope sees.
391
+ }
392
+ return [...names];
393
+ }
355
394
 
356
395
  const isChannel = (app) => Boolean(channelEntry(app, templates()));
357
396
  // Chat channels run outside the Agent; changing one does not restart the bot's MCP clients.
358
397
  // A linked local skill counts by what its SKILL.md is now, so an edit there re-installs it.
359
398
  // A router home also changes with the dispatcher mode and the role (its tool limits and guard).
399
+ /** 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. */
400
+ const lossless = (o) => JSON.parse(JSON.stringify(o ?? {}));
401
+ /** 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). */
402
+ const inTeam = () => store.list().length > 1;
403
+ const noSubagents = (bot) => bot?.role === 'primary' && inTeam();
404
+ const SUBAGENT_TOOLS = ABILITIES.find((a) => a.id === 'delegate')?.tools ?? [];
360
405
  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 });
406
+ 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
407
  /** The chat apps the team can be reached from ('Telegram'), for the persona. */
363
408
  const channelNames = (bots) => {
364
409
  const tpl = templates();
@@ -467,9 +512,11 @@ export function apply(ctx, config, deps = {}) {
467
512
  ctx.logger?.warn?.(`bots: memory for @${bot.handle}: ${error?.message ?? error}`);
468
513
  }
469
514
  }
470
- // A router home is also denied the tools that do the work, except those the user gave back.
515
+ // What this conversation has before any limit below: the profile lists the denied tools too.
516
+ noteTools(scopeOf(actx));
517
+ // 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
518
  const allowed = new Set(bot.tools.routerAllow ?? []);
472
- const wanted = [...new Set([...bot.tools.deny, ...(router ? ROUTER_DENY.filter((n) => !allowed.has(n)) : [])])];
519
+ const wanted = [...new Set([...bot.tools.deny, ...(router ? ROUTER_DENY.filter((n) => !allowed.has(n)) : []), ...(noSubagents(bot) ? SUBAGENT_TOOLS : [])])];
473
520
  if (wanted.length > 0) {
474
521
  const tools = service(actx, 'tools');
475
522
  try {
@@ -529,6 +576,7 @@ export function apply(ctx, config, deps = {}) {
529
576
  );
530
577
  ctx.effect(() => () => {
531
578
  for (const id of [...installed.keys()]) uninstall(id);
579
+ discussions.flush();
532
580
  }, 'bots: unwind bot scopes');
533
581
  /** Apply every bot again to its live home and ticket Sessions (a bot, the roles or the dispatcher mode changed). */
534
582
  function reapply() {
@@ -738,8 +786,8 @@ export function apply(ctx, config, deps = {}) {
738
786
  replied: false,
739
787
  };
740
788
  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);
789
+ // A ticket Session or a discussion is no topic of the bot's: rotation only ever looks at its home.
790
+ if (!ticket && !discussions.bySession(sessionId)) topics.current(bot.id, sessionId);
743
791
  return task;
744
792
  }
745
793
  function logLine(task, line) {
@@ -755,7 +803,7 @@ export function apply(ctx, config, deps = {}) {
755
803
  const task = openTasks.get(sessionId);
756
804
  const ticketId = ticketOf(sessionId)?.id;
757
805
  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));
806
+ if (kind === 'chat' && !ticketId && !discussions.bySession(sessionId)) topics.noteCall(bot.id, sessionId, promptTokens(usage));
759
807
  }
760
808
  /** The task of `sessionId` is over when its Agent is idle again. */
761
809
  function settleSoon(sessionId, delay = 1200) {
@@ -784,7 +832,7 @@ export function apply(ctx, config, deps = {}) {
784
832
  if (t?.ended) reflectTicket(t);
785
833
  return;
786
834
  }
787
- topics.noteTask(task.b, task.s, task.title);
835
+ if (!discussions.bySession(task.s)) topics.noteTask(task.b, task.s, task.title);
788
836
  if (bot) queueReflection(bot, { ...row, log });
789
837
  }
790
838
  /** ticketId → transcript lines of its finished runs, for the summary written when it ends. */
@@ -934,6 +982,8 @@ export function apply(ctx, config, deps = {}) {
934
982
 
935
983
  // --- topics ------------------------------------------------------------------------------------
936
984
  const rotating = new Map();
985
+ /** When a bot last started a new topic (ms; 0: not since this process started). */
986
+ let rotatedAt = 0;
937
987
  /**
938
988
  * Start `bot`'s next topic: a fresh conversation (the old one is archived, its
939
989
  * scheduled tasks move to the new one). Refused while the bot is working.
@@ -991,6 +1041,8 @@ export function apply(ctx, config, deps = {}) {
991
1041
  }
992
1042
  uninstall(prev);
993
1043
  forgetSession(prev);
1044
+ // Harness closes the panel when the conversation behind it is archived; the panel opens itself again.
1045
+ rotatedAt = nowMs();
994
1046
  try {
995
1047
  await service(ctx, 'workspaceRegistry')?.archiveSession?.(prev);
996
1048
  } catch (error) {
@@ -998,6 +1050,7 @@ export function apply(ctx, config, deps = {}) {
998
1050
  }
999
1051
  }
1000
1052
  topics.rotate(bot.id, next, reason);
1053
+ rotatedAt = nowMs();
1001
1054
  store.log({ from: 'system', to: bot.id, kind: 'topic', text: reason });
1002
1055
  return next;
1003
1056
  })().finally(() => rotating.delete(bot.id));
@@ -1126,7 +1179,9 @@ export function apply(ctx, config, deps = {}) {
1126
1179
  * without `inject` gets nothing for an 'inject' (`dropped`): such a note never wakes a turn.
1127
1180
  * - `key`: makes the message id `bots:<key>`; a message with that id already pending or delivered
1128
1181
  * is not delivered again, so a retried request is harmless.
1129
- * @returns {{message: object, mode: string, skipped: boolean, dropped?: true}}
1182
+ * An 'inject' for a conversation in the middle of a turn is held until it is idle (`held`, see
1183
+ * `holdNote`).
1184
+ * @returns {{message: object, mode: string, skipped: boolean, dropped?: true, held?: true}}
1130
1185
  */
1131
1186
  async function sendTo(agent, { content: blocks, source, mode = 'followup', key }) {
1132
1187
  // Providers that take a message as one string join its blocks with nothing in between:
@@ -1138,15 +1193,55 @@ export function apply(ctx, config, deps = {}) {
1138
1193
  if (key) await loadHistory(agent.session?.id);
1139
1194
  if (key && holds(agent, message.id)) return { message, mode, skipped: true };
1140
1195
  const how = mode === 'inject' ? 'inject' : mode !== 'followup' && typeof agent.steer === 'function' ? 'steer' : 'followup';
1196
+ if (how === 'inject' && agent.status === 'running') {
1197
+ holdNote(agent, message);
1198
+ if (key) noteDelivered(agent.session?.id, message.id);
1199
+ return { message, mode: how, skipped: false, held: true };
1200
+ }
1141
1201
  agent[how](message);
1142
1202
  if (key) noteDelivered(agent.session?.id, message.id);
1143
1203
  await flush(agent);
1144
1204
  return { message, mode: how, skipped: false };
1145
1205
  }
1206
+ /**
1207
+ * Notes ("[Shown]", "[follow_up]", "[Closed]") for conversations that were working when they came,
1208
+ * by Session: `{agent, messages}`. Injected into a running turn, a note is the newest input of its
1209
+ * next step, and the model answers it, to the person ("[已展示]: nothing for me to do…", 0.10.1).
1210
+ * They need no answer, so they wait for the turn's end and go in then, waking nothing. In memory
1211
+ * only: a note lost with the process was only good to know.
1212
+ */
1213
+ const heldNotes = new Map();
1214
+ function holdNote(agent, message) {
1215
+ const sid = agent.session?.id;
1216
+ if (!sid) return;
1217
+ const held = heldNotes.get(sid) ?? { agent, messages: [] };
1218
+ held.agent = agent;
1219
+ held.messages.push(message);
1220
+ heldNotes.set(sid, held);
1221
+ }
1222
+ /** The conversation `sessionId` went idle: its held notes go in now, in the order they came. */
1223
+ function releaseNotes(sessionId, agent) {
1224
+ const held = heldNotes.get(sessionId);
1225
+ if (!held) return;
1226
+ heldNotes.delete(sessionId);
1227
+ const to = agent ?? held.agent;
1228
+ for (const m of held.messages) {
1229
+ try {
1230
+ to.inject(m);
1231
+ } catch (error) {
1232
+ ctx.logger?.info?.(`bots: a held note did not reach ${sessionId}: ${error?.message ?? error}`);
1233
+ }
1234
+ }
1235
+ void flush(to);
1236
+ }
1146
1237
  /** How a bot's home takes new input: a router steers (backlog is handled together), every other home as in 0.7. */
1147
1238
  const homeMode = (bot) => (isRouter(store.get(bot.id) ?? bot) ? 'steer' : 'followup');
1148
1239
 
1149
- /** A DM from `sender` (a bot, or null for the user) to `target`'s home: 0.7's bot-to-bot message. */
1240
+ /**
1241
+ * A DM from `sender` (a bot, or null for the user) to `target`'s home: 0.7's bot-to-bot message,
1242
+ * and (0.10.1) a teammate's message to the router dispatcher. One sent from a task names it, so the
1243
+ * answer goes to that task. Its id (`bots:dm:…`) keeps it a message, not a report on the sender's task.
1244
+ */
1150
1245
  async function deliver(sender, target, text, senderSessionId) {
1151
1246
  const body = String(text ?? '').trim();
1152
1247
  if (body === '') throw new Error('text must not be empty');
@@ -1155,19 +1250,21 @@ export function apply(ctx, config, deps = {}) {
1155
1250
  // A teammate's message may answer this bot's own question: only a long quiet starts a new topic here.
1156
1251
  await autoTopic(store.get(target.id) ?? target, sender ? 'dm' : 'user');
1157
1252
  const agent = await agentOf(store.get(target.id) ?? target);
1253
+ const fromTask = sender ? ticketOf(senderSessionId) : undefined;
1158
1254
  await sendTo(agent, {
1159
1255
  content: [
1160
- { type: 'text', text: dmHeader(sender) },
1161
- { type: 'text', text: dmBody(body, sender) },
1256
+ { type: 'text', text: dmHeader(sender, fromTask) },
1257
+ { type: 'text', text: dmBody(body, sender, fromTask) },
1162
1258
  ],
1163
1259
  source: senderSessionId ? { kind: 'agent-message', form: 'relay', senderSessionId } : { kind: 'user' },
1164
1260
  mode: homeMode(target),
1261
+ key: `dm:${randomUUID()}`,
1165
1262
  });
1166
1263
  store.log({ from: sender ? sender.id : 'user', to: target.id, text: body, kind: 'dm' });
1167
1264
  return agent.session.id;
1168
1265
  }
1169
1266
 
1170
- // --- the panel chat: topics (Bots 0.9) -------------------------------------------------
1267
+ // --- the panel chat (Bots 0.9; threads 0.10) ------------------------------------------
1171
1268
  /** A new id for a message typed in the panel: `p` and 8 letters or digits, short enough for a model to copy. */
1172
1269
  const newPanelId = () => {
1173
1270
  for (;;) {
@@ -1188,6 +1285,59 @@ export function apply(ctx, config, deps = {}) {
1188
1285
  };
1189
1286
  /** Who wrote a timeline message, as a header names them. */
1190
1287
  const writerOf = (m) => (m.from === 'user' ? 'the user' : store.get(m.from) ? `@${store.get(m.from).handle}` : 'a bot');
1288
+ /** A message bots send each other (a DM or a report between two bots), not one said to the person. */
1289
+ const betweenBots = (m) => m.from !== 'user' && m.to !== 'user' && (m.kind === 'dm' || m.kind === 'report');
1290
+ /**
1291
+ * What was said in the threads of `bot`'s panel chat since its main conversation (Session `sid`)
1292
+ * last heard, as the note before the person's next message there (Bots 0.10): the panel shows those
1293
+ * replies in the chat, quoted. Since the later of the last note and the start of the current topic.
1294
+ * Returns `{text, upTo}` (`upTo`: the time of the latest message told; 0 for none).
1295
+ */
1296
+ function threadNewsFor(bot, sid) {
1297
+ const cur = topics.peek(bot.id);
1298
+ const since = Math.max(discussions.toldAt(bot.id), cur?.sessionId === sid ? Number(cur.startedAt) || 0 : 0);
1299
+ const rows = store
1300
+ .messages({ bot: bot.id, limit: 400, roots: false })
1301
+ .filter((m) => Number(m.at) > since && !m.via && m.kind !== 'system' && m.kind !== 'topic' && !betweenBots(m) && rootIdOf(m) !== m.id && String(m.text ?? '').trim())
1302
+ .slice(-NEWS_MESSAGES);
1303
+ if (!rows.length) return { text: '', upTo: 0 };
1304
+ const byRoot = new Map();
1305
+ for (const m of rows) {
1306
+ const r = rootIdOf(m);
1307
+ if (!byRoot.has(r)) {
1308
+ const root = store.message(r);
1309
+ const whose = !root ? '' : root.from === bot.id ? 'your message' : root.from === 'user' ? "the user's message" : `${writerOf(root)}'s message`;
1310
+ byRoot.set(r, { who: whose, text: root?.text ?? '', said: [] });
1311
+ }
1312
+ byRoot.get(r).said.push({ who: m.from === 'user' ? 'The user' : m.from === bot.id ? 'You' : writerOf(m), text: m.text });
1313
+ }
1314
+ return { text: threadNewsText({ threads: [...byRoot.values()] }), upTo: Math.max(...rows.map((m) => Number(m.at) || 0)) };
1315
+ }
1316
+ /** Characters of the message a reply quotes, as the chat shows it. */
1317
+ const QUOTE_CHARS = 140;
1318
+ /**
1319
+ * The message a reply in a thread quotes, as the chat shows it (Bots 0.10): the person's, the one
1320
+ * they replied to (the thread's root unless they picked another of it); a bot's, the person's
1321
+ * latest message of the thread before it, else the root. Null for a message of the main chat.
1322
+ * @param {object} m
1323
+ * @param {Map<string, object[]>} replies - per root, the thread's messages in order
1324
+ * @param {(id: string) => object | undefined} lookup
1325
+ */
1326
+ function quoteOf(m, replies, lookup) {
1327
+ const rootId = rootIdOf(m);
1328
+ if (!rootId || rootId === m.id) return null;
1329
+ let target = m.from === 'user' && m.replyTo ? lookup(m.replyTo) : null;
1330
+ if (!target && m.from !== 'user') {
1331
+ for (const x of replies.get(rootId) ?? []) {
1332
+ if (x.id === m.id) break;
1333
+ if (x.from === 'user' && x.kind === 'user') target = x;
1334
+ }
1335
+ }
1336
+ target ??= lookup(rootId);
1337
+ if (!target) return null;
1338
+ const text = clip(String(target.text ?? '').replace(/\s+/g, ' ').trim(), QUOTE_CHARS).text;
1339
+ return { id: target.id, from: target.from, text, ...(target.who ? { who: target.who } : {}), ...(target.via ? { via: target.via } : {}) };
1340
+ }
1191
1341
  /** The tasks a dispatcher's panel message may continue: open, or ended within a day; the latest change first. */
1192
1342
  function openTasksOf(bot) {
1193
1343
  const since = nowMs() - 24 * 3600_000;
@@ -1196,26 +1346,123 @@ export function apply(ctx, config, deps = {}) {
1196
1346
  .filter((t) => t.requester?.botId === bot.id && !t.requester?.ticketId && (!t.ended || t.ended.at >= since))
1197
1347
  .sort((a, b) => b.updatedAt - a.updatedAt);
1198
1348
  }
1349
+ // --- discussions: replies to one message, in a Session of their own (Bots 0.10) ----------
1350
+ /** The root of the discussion a timeline message is in; the message itself when it is in the main chat. */
1351
+ const rootIdOf = (m) => (m?.topic && m.topic !== m.id ? m.topic : m?.movedTo && m.movedTo !== m.id ? m.movedTo : m?.id ?? '');
1352
+ /** The Thread a Session's plain words go to when its turn named none: a discussion's own, else the panel. */
1353
+ const homeThreadOf = (sessionId) => discussions.bySession(sessionId)?.key ?? panelThreadKey(sessionId);
1199
1354
  /**
1200
- * The topic a panel message goes into: a new one it starts, or for a reply the topic of the
1201
- * message it answers (one filed under another topic counts as there). A message that was in no
1202
- * topic becomes the first of one. `{root, key, quoted}`.
1355
+ * The Session of `bot`'s that a timeline message was said in: noted on it, the panel conversation
1356
+ * its Thread names, the bot's own task it belongs to, or else the bot's home.
1203
1357
  */
1204
- function topicFor(bot, sessionId, id, replyTo) {
1205
- if (!replyTo) return { root: id, key: panelThreadKey(sessionId, id), quoted: null };
1206
- const quoted = store.message(replyTo);
1207
- if (!quoted || !inChat(quoted, bot.id)) throw new Error('that message is not in this chat');
1208
- const root = quoted.movedTo || quoted.topic || quoted.id;
1209
- const first = root === quoted.id ? quoted : store.message(root);
1210
- // Its first message names the key; one gone from the log leaves it on the message replied to (an older topic of the bot's).
1211
- const key = topicKeyOf(first, root) || (panelTopicOf(quoted.thread) === root ? quoted.thread : '') || panelThreadKey(sessionId, root);
1212
- if (first && first.topic !== root) {
1213
- // A chat app's message keeps its chat Thread: the topic's key goes beside it.
1214
- const chatThread = first.thread && !isPanelThread(first.thread);
1215
- store.patchMessage(first.id, chatThread ? { topic: root, panelThread: key } : { topic: root, thread: key });
1358
+ function sessionOfMessage(m, bot) {
1359
+ if (m?.sid) return m.sid;
1360
+ const p = parseThreadKey(m?.thread);
1361
+ if (p?.kind === 'panel' && p.sessionId) return p.sessionId;
1362
+ const t = m?.ticket ? tickets.get(m.ticket) : undefined;
1363
+ if (t?.sessionId && t.botId === bot.id) return t.sessionId;
1364
+ return bot.sessionId ?? '';
1365
+ }
1366
+ /**
1367
+ * Where `m` sits in a Session of `bot`'s: its anchor (kept since 0.10), else found in that
1368
+ * Session's log by time (an older message; a person's counts with the answer its turn gave).
1369
+ * Null when it cannot be told.
1370
+ */
1371
+ async function positionOfMessage(m, bot) {
1372
+ const a = discussions.anchorOf(messageRef(m.id));
1373
+ if (a && isMine(bot, a.sessionId)) return a;
1374
+ const sessionId = sessionOfMessage(m, bot);
1375
+ if (!sessionId || !isMine(bot, sessionId)) return null;
1376
+ const seq = seqByTime(await readHistory(sessionId).catch(() => null), { at: Number(m.at), fromPerson: m.from === 'user' });
1377
+ return seq === undefined ? null : { sessionId, seq };
1378
+ }
1379
+ /** Whether a Session is `bot`'s: its home (now or an earlier topic), a discussion of it, or its task. */
1380
+ function isMine(bot, sessionId) {
1381
+ if (!sessionId) return false;
1382
+ const owner = botOfSession(sessionId);
1383
+ if (owner) return owner.id === bot.id;
1384
+ // An earlier topic of the bot's (archived): its conversations are still the bot's.
1385
+ return topics.peek(bot.id)?.sessionId === sessionId || topics.history(bot.id).some((x) => x.sessionId === sessionId);
1386
+ }
1387
+ /** Name a Session for its bot and give it the bot's model (a fork starts with Harness's default). */
1388
+ function decorate(agent, bot, title) {
1389
+ try {
1390
+ service(ctx, 'sessionTitle')?.rename?.(agent.session, title || bot.name);
1391
+ } catch {
1392
+ // A title is cosmetic.
1393
+ }
1394
+ const fresh = store.get(bot.id) ?? bot;
1395
+ if (fresh.model) {
1396
+ try {
1397
+ agent.model?.select?.(selectionOf(fresh.model));
1398
+ } catch {
1399
+ // The default model stays.
1400
+ }
1401
+ }
1402
+ }
1403
+ /** A discussion's Session again: taken out of the archive when it was put there. Null when it cannot come back. */
1404
+ async function reopenDiscussion(d) {
1405
+ const controller = service(ctx, 'sessionController');
1406
+ const reg = service(ctx, 'workspaceRegistry');
1407
+ if (d.archivedAt || (reg?.archivedSessionIds ?? []).includes(d.sessionId)) {
1408
+ try {
1409
+ await reg?.unarchiveSession?.(d.sessionId);
1410
+ } catch {
1411
+ return null;
1412
+ }
1413
+ if ((reg?.archivedSessionIds ?? []).includes(d.sessionId)) return null;
1414
+ discussions.patch(d.key, { archivedAt: null });
1216
1415
  }
1217
- return { root, key, quoted };
1416
+ const found = await controller.resolveAgent(d.sessionId).catch((error) => ({ error }));
1417
+ if (!found || 'error' in found) return null;
1418
+ reconcile(found.agent);
1419
+ return found.agent;
1420
+ }
1421
+ const opening = new Map();
1422
+ /**
1423
+ * The discussion `key` is talked over in, opened the first time: `bot`'s conversation forked at
1424
+ * `point` (`{sessionId, seq?}`; no seq: its latest finished turn). One that cannot come back from
1425
+ * the archive continues from its own last turn. Returns `{discussion, agent}`.
1426
+ */
1427
+ function discussionFor(bot, key, { point, rootId, title }) {
1428
+ if (opening.has(key)) return opening.get(key);
1429
+ const job = (async () => {
1430
+ const controller = service(ctx, 'sessionController');
1431
+ if (!controller) throw new Error('threads need the Web profile (no session controller here)');
1432
+ const known = discussions.get(key);
1433
+ if (known && known.botId === bot.id) {
1434
+ const agent = await reopenDiscussion(known);
1435
+ if (agent) return { discussion: discussions.get(key), agent };
1436
+ }
1437
+ if (typeof controller.fork !== 'function') throw new Error('this DeepSeek Harness cannot fork a conversation; update it to reply in a thread');
1438
+ const from = known?.botId === bot.id ? { sessionId: known.sessionId } : point;
1439
+ if (!from?.sessionId) throw new Error('the conversation that message was said in is gone; send it as a new message instead');
1440
+ let forked;
1441
+ // Forked at the replied message: the thread sees nothing said after it. Otherwise (the place is not
1442
+ // known, or cannot be forked) at the latest turn, and the note says the conversation may go on past it.
1443
+ let exact = from.seq !== undefined;
1444
+ try {
1445
+ forked = await controller.fork({ sessionId: from.sessionId, ...(from.seq !== undefined ? { atSeq: from.seq } : {}) });
1446
+ } catch (error) {
1447
+ if (from.seq === undefined) throw error;
1448
+ ctx.logger?.warn?.(`bots: forking at event ${from.seq} of ${from.sessionId}: ${error?.message ?? error}; forking at its latest turn`);
1449
+ forked = await controller.fork({ sessionId: from.sessionId });
1450
+ exact = false;
1451
+ }
1452
+ const d = discussions.add({ key, botId: bot.id, sessionId: forked.sessionId, rootId, source: from, title });
1453
+ if (known?.noted) discussions.patch(key, { noted: true });
1454
+ if (!known && !exact) discussions.patch(key, { exact: false });
1455
+ const found = await controller.resolveAgent(d.sessionId);
1456
+ if ('error' in found) throw found.error;
1457
+ reconcile(found.agent);
1458
+ decorate(found.agent, bot, title ? `${bot.name} · ${title}` : bot.name);
1459
+ return { discussion: discussions.get(key), agent: found.agent };
1460
+ })().finally(() => opening.delete(key));
1461
+ opening.set(key, job);
1462
+ return job;
1218
1463
  }
1464
+ /** One line of a message, for a discussion's title. */
1465
+ const titleOf = (text) => clip(String(text ?? '').replace(/\s+/g, ' ').trim(), 40).text;
1219
1466
  /** A timeline message as the panel reads it: `pending` while no model has taken it yet; internal fields left out. */
1220
1467
  function messageView(m) {
1221
1468
  const { sid, ...rest } = m;
@@ -1234,15 +1481,16 @@ export function apply(ctx, config, deps = {}) {
1234
1481
  /**
1235
1482
  * The user writes to a bot from the panel. `/new` (or `/clear`, `/新话题`) first starts a new
1236
1483
  * topic of its conversation; text after it goes there. Every message is logged before it is
1237
- * handed over (the panel shows it at once, `pending` until a model takes it) and is a topic of
1238
- * its own, or with `replyTo` joins the topic of that message. A reply in a topic with live tasks
1239
- * goes to them directly (the bot's home hears of it without waking); anything else goes to the
1240
- * bot's home: a router steers it (a header names its topic and the tasks it may continue), other
1241
- * homes take it as a turn of its own. Returns `{sessionId, message?}`.
1484
+ * handed over (the panel shows it at once, `pending` until a model takes it). A message goes
1485
+ * to the main chat: the bot's home (a router steers it, with the tasks it may continue in a
1486
+ * header; other homes take it as a turn of its own). With `replyTo` it is a reply in the thread
1487
+ * of that message (Bots 0.10, `threadSend`). Returns `{sessionId, message?}`.
1242
1488
  */
1243
1489
  async function userSend(target, text, { replyTo = '' } = {}) {
1244
1490
  let body = String(text ?? '').trim();
1245
1491
  if (body === '') throw new Error('text must not be empty');
1492
+ const ref = String(replyTo ?? '').trim();
1493
+ if (ref) return threadSend(store.get(target.id) ?? target, body, ref);
1246
1494
  const cmd = TOPIC_COMMAND.exec(body);
1247
1495
  if (cmd) {
1248
1496
  const sessionId = await newTopic(target, 'manual');
@@ -1253,30 +1501,90 @@ export function apply(ctx, config, deps = {}) {
1253
1501
  const agent = await agentOf(bot);
1254
1502
  const sid = agent.session.id;
1255
1503
  const id = newPanelId();
1256
- const { root, key, quoted } = topicFor(bot, sid, id, String(replyTo ?? '').trim());
1257
- const live = quoted ? tickets.subscribers(key).filter(isLiveSubscriber) : [];
1258
- const base = { id, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, thread: key, topic: root, ...(quoted ? { replyTo: quoted.id } : {}) };
1259
- store.log(base);
1504
+ store.log({ id, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, thread: panelThreadKey(sid), sid });
1505
+ // The panel shows thread replies in the chat: what the person read there since, the main conversation hears first.
1506
+ const news = threadNewsFor(bot, sid);
1507
+ const header = isRouterHome(bot, sid) ? panelHeaderText({ open: openTasksOf(bot) }, cardCtx()) : '';
1508
+ try {
1509
+ await sendTo(agent, { content: [news.text, header, body].filter(Boolean).map((text) => ({ type: 'text', text })), source: { kind: 'user' }, mode: homeMode(bot), key: `panel:${id}` });
1510
+ } catch (error) {
1511
+ // Not handed over: it leaves the chat (the panel keeps its own copy to send again).
1512
+ store.patchMessage(id, { hidden: true });
1513
+ throw error;
1514
+ }
1515
+ if (news.upTo) discussions.markTold(bot.id, news.upTo);
1516
+ return { sessionId: sid, message: messageView(store.message(id)) };
1517
+ }
1518
+
1519
+ /**
1520
+ * A reply in the thread of message `ref` in `bot`'s chat (Bots 0.10). A message in the main chat
1521
+ * opens its thread; one in a thread stays in that thread (it is quoted). The thread of a task's
1522
+ * message, or one a task follows, goes to the task (as in 0.9); any other is a discussion: the
1523
+ * bot's conversation forked at the replied message, so it sees what came before and nothing the
1524
+ * main chat said since. Returns `{sessionId, message}`.
1525
+ */
1526
+ async function threadSend(bot, body, ref) {
1527
+ if (TOPIC_COMMAND.test(body)) throw new Error('a thread has no new topic: send /new in the main chat');
1528
+ const quoted = store.message(ref);
1529
+ if (!quoted || !inChat(quoted, bot.id)) throw new Error('that message is not in this chat');
1530
+ const rootId = rootIdOf(quoted);
1531
+ const root = rootId === quoted.id ? quoted : store.message(rootId);
1532
+ if (!root) throw new Error('the message this thread answers is gone');
1533
+ const homeSid = sessionOfMessage(root, bot);
1534
+ // The thread keeps the key it was opened with (the home may have a new topic since).
1535
+ const said = store.messages({ bot: bot.id, topic: rootId, limit: 50 }).find((m) => m.id !== rootId && panelTopicOf(m.thread) === rootId);
1536
+ const key = topicKeyOf(root, rootId) || discussions.byRoot(rootId)?.key || said?.thread || panelThreadKey(homeSid || bot.sessionId || 'panel', rootId);
1537
+ const id = newPanelId();
1538
+ const aside = quoted.id !== rootId ? quoted : null;
1539
+ store.log({ id, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, thread: key, topic: rootId, ...(aside ? { replyTo: aside.id } : {}) });
1540
+ // 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.
1541
+ // In a discussion they go to its bot, who has the tasks it opened there report back into it.
1542
+ const talking = discussions.get(key);
1543
+ let live = talking ? [] : tickets.subscribers(key).filter(isLiveSubscriber);
1544
+ const own = root.ticket ? tickets.get(root.ticket) : undefined;
1545
+ if (!live.length && own && isLiveSubscriber(own)) {
1546
+ tickets.subscribe(own.id, key, { label: threadLabel({ threadKey: key, threadTitle: root.text }) });
1547
+ // Its later reports are shown in this thread.
1548
+ tickets.patch(own.id, { showIn: key });
1549
+ live = [tickets.get(own.id)];
1550
+ }
1260
1551
  if (live.length) {
1261
1552
  try {
1262
- const sessions = await toTopicTasks(bot, live, body, { key, root, id, quoted });
1263
- return { sessionId: sessions[0] ?? sid, message: messageView(store.message(id)) };
1553
+ const sessions = await toTopicTasks(bot, live, body, { key, root: rootId, id, quoted });
1554
+ return { sessionId: sessions[0] ?? bot.sessionId, message: messageView(store.message(id)) };
1264
1555
  } catch (error) {
1265
- // No task took it (one ended meanwhile, say): the bot's home does.
1266
- ctx.logger?.warn?.(`bots: a panel reply did not reach its task (${error?.message ?? error}); @${bot.handle} takes it`);
1556
+ // No task took it (one ended meanwhile, say): a discussion does.
1557
+ ctx.logger?.warn?.(`bots: a reply did not reach its task (${error?.message ?? error}); @${bot.handle} takes it in a thread`);
1267
1558
  }
1268
1559
  }
1269
- store.patchMessage(id, { sid });
1270
- const router = isRouterHome(bot, sid);
1271
- const header = router || quoted ? panelHeaderText({ topic: root, ...(quoted ? { replyTo: { who: writerOf(quoted), text: quoted.text } } : {}), open: router ? openTasksOf(bot) : [] }, cardCtx()) : '';
1560
+ let opened;
1561
+ try {
1562
+ const at = await positionOfMessage(root, bot);
1563
+ const point = forkPoint({ root: at, fallback: isMine(bot, homeSid) ? homeSid : bot.sessionId });
1564
+ opened = await discussionFor(bot, key, { point, rootId, title: titleOf(root.text) });
1565
+ } catch (error) {
1566
+ store.patchMessage(id, { hidden: true });
1567
+ throw error;
1568
+ }
1569
+ const { discussion, agent } = opened;
1570
+ // The first message of the thread carries the note; claimed now, so a second reply at once does not repeat it.
1571
+ const first = !discussions.get(key)?.noted;
1572
+ if (first) discussions.patch(key, { noted: true });
1573
+ const header = first
1574
+ ? discussionNoteText({ who: writerOf(root), text: root.text, exact: discussion.exact !== false, ...(aside ? { quoted: { who: writerOf(aside), text: aside.text } } : {}) })
1575
+ : aside
1576
+ ? panelHeaderText({ replyTo: { who: writerOf(aside), text: aside.text } })
1577
+ : '';
1578
+ store.patchMessage(id, { sid: agent.session.id });
1272
1579
  try {
1273
1580
  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}` });
1274
1581
  } catch (error) {
1275
- // Not handed over: it leaves the chat (the panel keeps its own copy to send again).
1276
1582
  store.patchMessage(id, { hidden: true });
1583
+ if (first) discussions.patch(key, { noted: null });
1277
1584
  throw error;
1278
1585
  }
1279
- return { sessionId: sid, message: messageView(store.message(id)) };
1586
+ discussions.patch(key, { lastAt: nowMs() });
1587
+ return { sessionId: agent.session.id, message: messageView(store.message(id)) };
1280
1588
  }
1281
1589
 
1282
1590
  /**
@@ -1299,13 +1607,15 @@ export function apply(ctx, config, deps = {}) {
1299
1607
  }
1300
1608
  if (!reached.length) throw lastError ?? new Error('no task took the reply');
1301
1609
  store.patchMessage(id, { ticket: reached[0].id });
1302
- if (bot.sessionId) {
1610
+ // Whoever asked for the tasks hears of it without waking: the bot's home, or the thread of it that opened them.
1611
+ const told = new Set();
1612
+ for (const t of reached) {
1303
1613
  try {
1304
- const found = await service(ctx, 'sessionController')?.resolveAgent?.(bot.sessionId);
1305
- if (found?.agent) {
1306
- const text = followUpNoticeText({ tickets: reached, thread: { key: root, label: threadLabel({ threadKey: key, threadTitle: store.message(root)?.text }) }, who: 'The user', text: body }, cardCtx());
1307
- await sendTo(found.agent, { content: [{ type: 'text', text }], source: { kind: 'agent-message', form: 'relay' }, mode: 'inject', key: `followup:panel:${id}` });
1308
- }
1614
+ const asked = t.requester?.kind === 'session' && t.requester.botId === bot.id && !t.requester.ticketId ? await requesterAgent(t) : await agentOf(bot);
1615
+ if (!asked || told.has(asked.session.id)) continue;
1616
+ told.add(asked.session.id);
1617
+ const text = followUpNoticeText({ tickets: reached, thread: { key: root, label: threadLabel({ threadKey: key, threadTitle: store.message(root)?.text }) }, who: 'The user', text: body }, cardCtx());
1618
+ await sendTo(asked, { content: [{ type: 'text', text }], source: { kind: 'agent-message', form: 'relay' }, mode: 'inject', key: `followup:panel:${id}` });
1309
1619
  } catch (error) {
1310
1620
  ctx.logger?.warn?.(`bots: the follow-up notice for @${bot.handle}: ${error?.message ?? error}`);
1311
1621
  }
@@ -1334,28 +1644,6 @@ export function apply(ctx, config, deps = {}) {
1334
1644
  .current(sessionId)
1335
1645
  .filter((o) => o.kind !== 'panel' || o.rootId)
1336
1646
  .map((o) => (o.kind === 'panel' ? `${o.rootId} (${threadLabel(o)})` : `${o.threadKey} (${threadLabel(o)}${o.tickets?.length ? `; task ${o.tickets.join(', ')}` : ''})`));
1337
- /**
1338
- * A home added a person's new message to an open task (`bot_send_message` with `ticket`): when
1339
- * that task came from a panel topic and this turn has one other panel topic that is only that
1340
- * message (or the one `chosen` names), the message is filed under the task's topic (`movedTo`),
1341
- * and this turn's replies go there. Returns the task's topic root, or ''.
1342
- */
1343
- function fileUnder(t, sessionId, chosen) {
1344
- const target = t.origin?.threadKey;
1345
- const toRoot = target ? panelTopicOf(target) : '';
1346
- if (!toRoot) return '';
1347
- const candidates = channels.current(sessionId).filter((o) => o.kind === 'panel' && o.rootId && o.threadKey !== target && tickets.subscribers(o.threadKey).length === 0);
1348
- const pick = chosen ? candidates.find((o) => o.threadKey === chosen) : candidates.length === 1 ? candidates[0] : undefined;
1349
- if (!pick) return '';
1350
- const first = store.message(pick.rootId);
1351
- if (!first || first.from !== 'user' || first.movedTo) return '';
1352
- // Only a topic nobody answered in yet is filed away whole.
1353
- if (store.messages({ topic: pick.rootId, limit: 5 }).some((m) => m.id !== pick.rootId)) return '';
1354
- store.patchMessage(pick.rootId, { movedTo: toRoot });
1355
- channels.retarget(sessionId, pick.threadKey, target, { threadTitle: clip(store.message(toRoot)?.text ?? '', 60).text });
1356
- return toRoot;
1357
- }
1358
-
1359
1647
  // --- tickets: delegated work in Sessions of their own ---------------------------------
1360
1648
  /** What cards and relays read about the team and the tickets. */
1361
1649
  const cardCtx = () => ({ bots: store.list(), threads: tickets, tickets, stageOf });
@@ -1643,6 +1931,9 @@ export function apply(ctx, config, deps = {}) {
1643
1931
  return resolveId(parent.sessionId ?? r.sessionId);
1644
1932
  }
1645
1933
  const bot = r.botId ? store.get(r.botId) : undefined;
1934
+ // Asked from a thread of the bot's (Bots 0.10): the thread hears of it, back from the archive if need be.
1935
+ const asked = discussions.bySession(r.sessionId);
1936
+ if (bot && asked?.botId === bot.id) return (await reopenDiscussion(asked)) ?? agentOf(bot);
1646
1937
  // The asking bot may have started a new topic since: its report goes to the conversation it has now.
1647
1938
  if (bot && bot.sessionId !== r.sessionId) return agentOf(bot);
1648
1939
  return (await resolveId(r.sessionId)) ?? (bot ? agentOf(bot) : null);
@@ -1688,7 +1979,8 @@ export function apply(ctx, config, deps = {}) {
1688
1979
  function mayAppend(t, sender, sessionId) {
1689
1980
  const r = t.requester ?? {};
1690
1981
  if (r.sessionId === sessionId) return true;
1691
- if (sender && r.botId === sender.id && !r.ticketId && sender.sessionId === sessionId) return true;
1982
+ // The asking bot's home, or a thread of it (Bots 0.10): the person may carry a task on there.
1983
+ if (sender && r.botId === sender.id && !r.ticketId && isHomeOf(sender, sessionId)) return true;
1692
1984
  return Boolean(sender) && isRouterHome(sender, sessionId);
1693
1985
  }
1694
1986
 
@@ -1757,8 +2049,16 @@ export function apply(ctx, config, deps = {}) {
1757
2049
  async function openTicket(sender, target, text, senderSessionId, { title, thread: chosen, relay = false } = {}) {
1758
2050
  const body = String(text ?? '').trim();
1759
2051
  if (body === '') throw new Error('text must not be empty');
1760
- // The dispatcher may hand work to itself (Bots 0.9): it does it in a task of its own, with all its tools.
1761
- if (sender.id === target.id && !isRouterHome(sender, senderSessionId)) throw new Error('a bot cannot message itself');
2052
+ // The dispatcher only hands out (Bots 0.10; 0.9 let it hand work to itself): the work goes to a teammate.
2053
+ if (sender.id === target.id) {
2054
+ throw new Error(
2055
+ isRouterHome(sender, senderSessionId)
2056
+ ? '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'
2057
+ : 'a bot cannot message itself',
2058
+ );
2059
+ }
2060
+ // Nor does it take tasks from its teammates (0.10.1): their messages go into its conversation (bot_send_message).
2061
+ if (isRouter(target)) throw new Error(`@${target.handle} is the dispatcher and takes no tasks; message it without a task, or give the work to the teammate who does it`);
1762
2062
  if (!service(ctx, 'sessionController')) throw new Error('tasks need the Web profile (no session controller here)');
1763
2063
  const parent = ticketOf(senderSessionId);
1764
2064
  const { origin, thread } = originOfTurn(senderSessionId, chosen);
@@ -1825,7 +2125,8 @@ export function apply(ctx, config, deps = {}) {
1825
2125
  * (the report then goes to whoever asked, as in 0.8).
1826
2126
  */
1827
2127
  function showReport(t, report) {
1828
- const key = t.origin?.threadKey;
2128
+ // Where the person carries the task on (a thread opened on it, Bots 0.10), else where it came from.
2129
+ const key = t.showIn || t.origin?.threadKey;
1829
2130
  if (!key) return null;
1830
2131
  const worker = store.get(t.botId);
1831
2132
  const owner = t.requester?.botId ? store.get(t.requester.botId) : undefined;
@@ -2127,6 +2428,20 @@ export function apply(ctx, config, deps = {}) {
2127
2428
  tickets.archive(t.id);
2128
2429
  slots.release(t.id);
2129
2430
  }
2431
+ // Threads quiet for a day leave the sidebar; a new reply brings one back (Bots 0.10).
2432
+ for (const d of discussions.idle()) {
2433
+ if (openTasks.has(d.sessionId) || agents()?.get?.(d.sessionId)?.status === 'running') continue;
2434
+ uninstall(d.sessionId);
2435
+ forgetSession(d.sessionId);
2436
+ try {
2437
+ // The panel may be shown over this conversation: it opens itself again (see `rotatedAt`).
2438
+ rotatedAt = nowMs();
2439
+ await service(ctx, 'workspaceRegistry')?.archiveSession?.(d.sessionId);
2440
+ discussions.patch(d.key, { archivedAt: now });
2441
+ } catch (error) {
2442
+ ctx.logger?.warn?.(`bots: archiving a thread of @${store.get(d.botId)?.handle ?? '?'}: ${error?.message ?? error}`);
2443
+ }
2444
+ }
2130
2445
  await watch(now);
2131
2446
  tickets.flush();
2132
2447
  tickets.prune();
@@ -2193,6 +2508,26 @@ export function apply(ctx, config, deps = {}) {
2193
2508
  return sessions;
2194
2509
  }
2195
2510
 
2511
+ /**
2512
+ * The discussion a chat message goes to (Bots 0.10), or null for the bot's home: a message in a
2513
+ * Thread (a reply chain, a group thread, a forum topic) whose conversation the bot had before in
2514
+ * its home, or that answers one of its messages, is talked over in the home forked there. The
2515
+ * Thread's first message, and one that arrives while the home is still on that Thread, go home.
2516
+ */
2517
+ async function chatDiscussion(bot, meta) {
2518
+ const key = toThreadKey(meta?.threadKey);
2519
+ const p = key ? parseThreadKey(key) : null;
2520
+ if (!p || p.kind === 'panel' || p.rootId === undefined) return null;
2521
+ const known = discussions.get(key);
2522
+ let point = null;
2523
+ if (!known || known.botId !== bot.id) {
2524
+ if (known) return null;
2525
+ if (bot.sessionId && channels.current(bot.sessionId).some((o) => o.threadKey === key)) return null;
2526
+ point = forkPoint({ thread: discussions.anchorOf(key), root: discussions.anchorOf(chatMessageRef(p.appKey, p.chatId, p.rootId)) });
2527
+ if (!point || !isMine(bot, point.sessionId)) return null;
2528
+ }
2529
+ return discussionFor(bot, key, { point, rootId: p.rootId, title: titleOf(meta?.origin?.body ?? '') });
2530
+ }
2196
2531
  const channels = createChannels({
2197
2532
  file: join(dir, 'channels.json'),
2198
2533
  bots: () => store.list(),
@@ -2201,6 +2536,30 @@ export function apply(ctx, config, deps = {}) {
2201
2536
  // and its Thread (so the bot can name it in bot_reply). Its id comes from the chat message's, so a
2202
2537
  // message handed out again after a restart is not run twice.
2203
2538
  deliver: async (target, { header, body }, meta = {}) => {
2539
+ // A reply in a chat Thread the bot spoke in before: its discussion (Bots 0.10).
2540
+ let into = null;
2541
+ try {
2542
+ into = await chatDiscussion(store.get(target.id) ?? target, meta);
2543
+ } catch (error) {
2544
+ ctx.logger?.warn?.(`bots: a chat thread could not get its own conversation (${error?.message ?? error}); @${target.handle} takes it`);
2545
+ }
2546
+ if (into) {
2547
+ // The thread's first message carries the note, claimed before the hand-over (two may arrive at once).
2548
+ const first = !discussions.get(into.discussion.key)?.noted;
2549
+ if (first) discussions.patch(into.discussion.key, { noted: true });
2550
+ const note = first ? `${discussionNoteText({})}\n` : '';
2551
+ const sent = await sendTo(into.agent, {
2552
+ content: [
2553
+ { type: 'text', text: `${note}${header}${threadNote(meta.threadKey)}` },
2554
+ { type: 'text', text: body },
2555
+ ],
2556
+ source: { kind: 'user' },
2557
+ mode: homeMode(target),
2558
+ ...(meta.key ? { key: meta.key } : {}),
2559
+ });
2560
+ discussions.patch(into.discussion.key, { lastAt: nowMs() });
2561
+ return { sessionId: into.agent.session.id, messageId: sent.message.id, ...(sent.skipped ? { skipped: true } : {}) };
2562
+ }
2204
2563
  await autoTopic(store.get(target.id) ?? target, 'user');
2205
2564
  const agent = await agentOf(store.get(target.id) ?? target);
2206
2565
  const sent = await sendTo(agent, {
@@ -2220,6 +2579,10 @@ export function apply(ctx, config, deps = {}) {
2220
2579
  ticketThread: (id) => tickets.get(String(id ?? ''))?.origin?.threadKey,
2221
2580
  running: (sessionId) => agents()?.get?.(sessionId)?.status === 'running',
2222
2581
  newTopic: (bot) => newTopic(bot, 'manual'),
2582
+ homeKey: (sessionId) => discussions.bySession(sessionId)?.key,
2583
+ onSent: ({ tag, appKey, chatId, ids }) => {
2584
+ for (const id of ids) discussions.anchor(chatMessageRef(appKey, chatId, id), tag);
2585
+ },
2223
2586
  ...(deps.loadConnector ? { loadConnector: deps.loadConnector } : {}),
2224
2587
  ...(deps.typingEveryMs ? { typingEveryMs: deps.typingEveryMs } : {}),
2225
2588
  log: (line) => ctx.logger?.info?.(`bots: ${line}`),
@@ -2267,6 +2630,7 @@ export function apply(ctx, config, deps = {}) {
2267
2630
  /** Drop what is kept per Session for one that is gone: an archived task's, a topic left behind, a removed bot's. */
2268
2631
  function forgetSession(sessionId) {
2269
2632
  if (!sessionId) return;
2633
+ lastSeq.delete(sessionId);
2270
2634
  memoText.delete(sessionId);
2271
2635
  memoStale.delete(sessionId);
2272
2636
  deliveredIds.delete(sessionId);
@@ -2275,6 +2639,7 @@ export function apply(ctx, config, deps = {}) {
2275
2639
  answered.delete(sessionId);
2276
2640
  turnState.delete(sessionId);
2277
2641
  activity.clear(sessionId);
2642
+ heldNotes.delete(sessionId);
2278
2643
  }
2279
2644
  /** Kinds of user message that start (or join) a task. */
2280
2645
  const TASK_KINDS = new Set(['user', 'schedule', 'agent-message']);
@@ -2290,7 +2655,13 @@ export function apply(ctx, config, deps = {}) {
2290
2655
  }
2291
2656
  /** Reminder message id → the tickets it names (their origin Threads join the requester's turn). */
2292
2657
  const reminded = new Map();
2658
+ /** sessionId → the seq of its latest event: where a tool's chat message was said, as an anchor. */
2659
+ const lastSeq = new Map();
2293
2660
  ctx.on('session/event', (session, event) => {
2661
+ if (Number.isSafeInteger(event?.seq) && session?.id) lastSeq.set(session.id, event.seq);
2662
+ // A thread's Session starts with its source's events; should Harness ever report them, they were logged already.
2663
+ const forkedFrom = session?.id ? discussions.bySession(session.id)?.source : undefined;
2664
+ if (forkedFrom?.seq !== undefined && Number.isSafeInteger(event?.seq) && event.seq <= forkedFrom.seq) return;
2294
2665
  let bot;
2295
2666
  let via = null;
2296
2667
  let kind;
@@ -2341,6 +2712,12 @@ export function apply(ctx, config, deps = {}) {
2341
2712
  const panelId = kind === 'user' ? /^bots:panel:(p[a-z0-9]{8})$/.exec(id)?.[1] : undefined;
2342
2713
  const typed = panelId ? store.message(panelId) : undefined;
2343
2714
  if (typed) said = typedText = typed.text;
2715
+ // Where it sits in the conversation, so a reply to it can fork there (Bots 0.10); again at the turn's end.
2716
+ const home = bot.sessionId === session.id;
2717
+ if (typed && home) {
2718
+ discussions.anchor(messageRef(typed.id), { sessionId: session.id, seq: event.seq });
2719
+ st.anchored = [...(st.anchored ?? []), messageRef(typed.id)];
2720
+ }
2344
2721
  const topicTitle = typed?.thread ? store.message(panelTopicOf(typed.thread))?.text : undefined;
2345
2722
  // A chat message adds its Thread to the turn's; a panel message its topic, or the panel (lib/threads.mjs).
2346
2723
  via = channels.noteUserMessage(session.id, bot, kind, said, { id, report: isReport, ...(typed?.thread ? { threadKey: typed.thread, origin: topicTitle ? { threadTitle: clip(topicTitle, 60).text } : {} } : {}) });
@@ -2357,11 +2734,22 @@ export function apply(ctx, config, deps = {}) {
2357
2734
  // The answer quotes the message that started the task, not whatever was said there last.
2358
2735
  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 });
2359
2736
  }
2360
- const thread = via ? via.threadKey : panelThreadKey(session.id);
2737
+ const thread = via ? via.threadKey : homeThreadOf(session.id);
2361
2738
  if (kind === 'user' && typed) {
2362
2739
  // Logged when it was sent.
2363
- } else 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 } : {}) });
2364
- else if (kind === 'schedule') store.log({ from: 'schedule', to: bot.id, text: said, kind: 'system' });
2740
+ } else if (kind === 'user') {
2741
+ const topic = !via && isPanelThread(thread) ? panelTopicOf(thread) : '';
2742
+ 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 } : {}) });
2743
+ if (home) {
2744
+ const refs = [messageRef(logged.id)];
2745
+ // A chat message: by its id in the chat app, and its Thread's latest exchange with the home.
2746
+ const chatMsg = /^bots:chat:(.+):([^:]+):([^:]+)$/.exec(id);
2747
+ if (chatMsg) refs.push(chatMessageRef(chatMsg[1], chatMsg[2], chatMsg[3]));
2748
+ if (via?.threadKey) refs.push(via.threadKey);
2749
+ for (const r of refs) discussions.anchor(r, { sessionId: session.id, seq: event.seq });
2750
+ st.anchored = [...(st.anchored ?? []), ...refs];
2751
+ }
2752
+ } else if (kind === 'schedule') store.log({ from: 'schedule', to: bot.id, text: said, kind: 'system' });
2365
2753
  }
2366
2754
  } else if (event.type === 'assistant/message') {
2367
2755
  const content = event.data?.message?.content ?? [];
@@ -2389,15 +2777,24 @@ export function apply(ctx, config, deps = {}) {
2389
2777
  if (text && !hidden) {
2390
2778
  // To the turn's one chat Thread; with several (or the panel and a chat) it stays in the panel,
2391
2779
  // and bot_reply says where each answer goes.
2392
- const sent = channels.noteReply(session.id, text);
2393
- const thread = sent ? sent.threadKey : panelThreadKey(session.id);
2394
- // A topic in the panel (Bots 0.9): the reply is shown in it.
2395
- const topic = sent?.kind === 'panel' ? panelTopicOf(sent.threadKey) : '';
2780
+ const home = bot.sessionId === session.id;
2781
+ const at = { sessionId: session.id, seq: event.seq };
2782
+ // Sent to a chat: the ids it gets there are anchors too (a reply to one of them is a discussion).
2783
+ const sent = channels.noteReply(session.id, text, home ? at : undefined);
2784
+ const thread = sent ? sent.threadKey : homeThreadOf(session.id);
2785
+ // A thread in the panel (a discussion, or a 0.9 topic): the reply is shown in it.
2786
+ const topic = isPanelThread(thread) ? panelTopicOf(thread) : '';
2396
2787
  const choices = plan.mode === 'choose' ? plan.origins.filter((o) => o.kind !== 'panel').map((o) => o.threadKey) : [];
2397
- 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 } : {}) });
2788
+ 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 } : {}) });
2789
+ if (home) {
2790
+ discussions.anchor(messageRef(logged.id), at);
2791
+ if (sent && sent.kind !== 'panel') discussions.anchor(sent.threadKey, at);
2792
+ }
2398
2793
  }
2399
2794
  } else if (event.type === 'turn/end') {
2400
2795
  channels.noteTurnEnd(session.id);
2796
+ // What the turn took in counts with the answer it gave: a reply to it forks after that answer.
2797
+ if (bot.sessionId === session.id) for (const r of turnState.get(session.id)?.anchored ?? []) discussions.anchor(r, { sessionId: session.id, seq: event.seq });
2401
2798
  turnState.delete(session.id);
2402
2799
  }
2403
2800
  } catch {
@@ -2459,6 +2856,7 @@ export function apply(ctx, config, deps = {}) {
2459
2856
  ctx.on('agent/status', (payload) => {
2460
2857
  try {
2461
2858
  const sid = payload?.agent?.session?.id;
2859
+ if (sid && payload.status === 'idle') releaseNotes(sid, payload.agent);
2462
2860
  if (sid && payload.status === 'idle') activity.clear(sid);
2463
2861
  if (sid && payload.status === 'idle' && openTasks.has(sid)) settleSoon(sid, 300);
2464
2862
  else if (sid && payload.status === 'idle' && memoStale.delete(sid)) memoText.delete(sid);
@@ -2682,6 +3080,19 @@ export function apply(ctx, config, deps = {}) {
2682
3080
  // The conversation stays where it is.
2683
3081
  }
2684
3082
  }
3083
+ // Its threads go with it.
3084
+ for (const d of discussions.list({ botId: bot.id })) {
3085
+ uninstall(d.sessionId);
3086
+ forgetSession(d.sessionId);
3087
+ if (!d.archivedAt) {
3088
+ try {
3089
+ await service(ctx, 'workspaceRegistry')?.archiveSession?.(d.sessionId);
3090
+ } catch {
3091
+ // The conversation stays where it is.
3092
+ }
3093
+ }
3094
+ discussions.remove(d.key);
3095
+ }
2685
3096
  // Its tickets end with it; their conversations are archived now.
2686
3097
  for (const t of tickets.list({ botId: bot.id, archived: false })) {
2687
3098
  if (!t.ended) endTicket(t, { by: 'system', outcome: 'stopped' });
@@ -2715,7 +3126,7 @@ export function apply(ctx, config, deps = {}) {
2715
3126
  function applyModel(bot) {
2716
3127
  if (!bot.model) return;
2717
3128
  const live = agents();
2718
- const ids = [bot.sessionId, ...tickets.list({ botId: bot.id, open: true }).map((t) => t.sessionId)].filter(Boolean);
3129
+ 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);
2719
3130
  for (const id of ids) {
2720
3131
  try {
2721
3132
  live?.get?.(id)?.model?.select?.(selectionOf(bot.model));
@@ -3012,7 +3423,8 @@ export function apply(ctx, config, deps = {}) {
3012
3423
  const sessionId = caller?.sessionId;
3013
3424
  const t = ticketOf(sessionId);
3014
3425
  if (t) return { kind: 'ticket', ticketId: t.id };
3015
- const bot = store.bySession(sessionId);
3426
+ // A home, or a thread of one (Bots 0.10).
3427
+ const bot = botOfSession(sessionId);
3016
3428
  if (!bot) return undefined;
3017
3429
  return isRouterHome(bot, sessionId) ? { kind: 'router' } : { kind: 'home' };
3018
3430
  }
@@ -3100,7 +3512,7 @@ export function apply(ctx, config, deps = {}) {
3100
3512
  name: 'bot_list',
3101
3513
  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.",
3102
3514
  parameters: {},
3103
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bots: v.bots }) },
3515
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bots: v.bots }) },
3104
3516
  isConcurrencySafe: () => true,
3105
3517
  execute: async () => {
3106
3518
  const bots = store.list();
@@ -3133,7 +3545,7 @@ export function apply(ctx, config, deps = {}) {
3133
3545
  ...AVATAR_PARAMS,
3134
3546
  skills: { ...skillInput, description: 'Skills to give it.' },
3135
3547
  },
3136
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
3548
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot }) },
3137
3549
  execute: async (args, exec) => {
3138
3550
  const caller = actor(exec);
3139
3551
  const by = caller.bot;
@@ -3169,7 +3581,7 @@ export function apply(ctx, config, deps = {}) {
3169
3581
  remove_skills: { type: 'array', items: { type: 'string' }, description: 'Names of skills to remove.' },
3170
3582
  make_dispatcher: { type: 'boolean', description: 'true to make this bot the dispatcher.' },
3171
3583
  },
3172
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
3584
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot }) },
3173
3585
  execute: async (args, exec) => {
3174
3586
  // A helper whose line cannot be traced still changes bots, as before; it waits for a drawing.
3175
3587
  const caller = actorOf(exec);
@@ -3192,7 +3604,7 @@ export function apply(ctx, config, deps = {}) {
3192
3604
  name: 'bot_delete',
3193
3605
  description: 'Delete a bot, its scheduled tasks, and archive its conversation. Only when the user asked for it.',
3194
3606
  parameters: { bot: { type: 'string', required: true, description: '@handle, id or name.' } },
3195
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
3607
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot }) },
3196
3608
  execute: async (args, exec) => {
3197
3609
  const bot = resolve(args.bot);
3198
3610
  if (callerBot(exec)?.id === bot.id) throw new Error('a bot cannot delete itself; ask the dispatcher or the user');
@@ -3207,7 +3619,7 @@ export function apply(ctx, config, deps = {}) {
3207
3619
  '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.',
3208
3620
  "- 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.",
3209
3621
  '- 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.',
3210
- '- The dispatcher may name itself in `to`: it then does the work in a task conversation of its own, with all its tools.',
3622
+ '- When the dispatcher only routes, a message to it opens no task: it goes into its own conversation, and it passes on to the person what they should know. Work goes to the teammate who does it.',
3211
3623
  '- 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).',
3212
3624
  '- 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`.',
3213
3625
  '- In a task conversation, to report to whoever asked: leave out `to`, give `text` and a `status` (progress, done, blocked, question).',
@@ -3221,7 +3633,7 @@ export function apply(ctx, config, deps = {}) {
3221
3633
  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.' },
3222
3634
  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.' },
3223
3635
  },
3224
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ to: v.to, from: v.from, ...(v.ticket ? { ticket: v.ticket } : {}) }) },
3636
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ to: v.to, from: v.from, ...(v.ticket ? { ticket: v.ticket } : {}) }) },
3225
3637
  isConcurrencySafe: () => true,
3226
3638
  execute: async (args, exec) => {
3227
3639
  const { sessionId, bot: sender } = actor(exec);
@@ -3259,24 +3671,40 @@ export function apply(ctx, config, deps = {}) {
3259
3671
  if (!t) throw new Error(`no task ${wantTicket}`);
3260
3672
  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`);
3261
3673
  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`);
3262
- const next = await appendToTicket(t, args.text, { sender: sender ?? null, senderSessionId: sessionId });
3674
+ let next = await appendToTicket(t, args.text, { sender: sender ?? null, senderSessionId: sessionId });
3675
+ // Carried on from a thread (Bots 0.10): the task follows the thread, and its reports show there.
3676
+ const here = !mine ? discussions.bySession(sessionId) : undefined;
3677
+ if (here && reportsGoDirect(next) && (next.showIn ?? next.origin?.threadKey) !== here.key) {
3678
+ tickets.subscribe(next.id, here.key);
3679
+ next = tickets.patch(next.id, { showIn: here.key }) ?? next;
3680
+ }
3263
3681
  const target = store.get(next.botId);
3264
3682
  const waits = next.startedAt && parkedOf(next).length > 0 ? ': every worker slot is taken, so it is handed over when one frees' : '';
3265
- // The person's new message that continues this task joins the task's topic (Bots 0.9).
3266
- const filed = !mine && sender ? fileUnder(next, sessionId, chosen) : '';
3267
- const after = reportsGoDirect(next) ? `${handleOf(next.botId)} answers the person in the task's ${isPanelThread(next.origin?.threadKey) ? 'topic' : 'chat'} itself` : `${handleOf(next.botId)}'s report will arrive here by itself`;
3268
- return { ok: true, text: `Added to task ${next.id} (${stageOf(next)}${waits}).${filed ? " The person's message is filed under that task's topic." : ''} ${after}; do not wait for it.`, ticket: row(next), to: face(target), from: face(sender) };
3683
+ 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`;
3684
+ 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) };
3269
3685
  }
3270
3686
  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`');
3271
3687
 
3688
+ // A teammate's message to the router dispatcher (0.10.1): no task for it (it does no work itself),
3689
+ // the text goes into its own conversation, where its router limits hold and it routes it.
3690
+ if (sender && named.id !== sender.id && isRouter(named)) {
3691
+ await deliver(sender, named, args.text, sessionId);
3692
+ return {
3693
+ ok: true,
3694
+ text: `Delivered to @${named.handle}, the dispatcher, in its own conversation: it does no work itself, so this opens no task. It tells the person what they should know; if it answers you, the answer ${mine ? 'arrives here' : 'reaches you'} by itself (do not wait for it). Work you need done goes to the teammate who does it.`,
3695
+ to: face(named),
3696
+ from: face(sender),
3697
+ };
3698
+ }
3699
+
3272
3700
  // A new ticket: from a task conversation (a sub-task), or from a bot's home when tasks are on.
3273
- if (sender && sessionId && (mine || (ticketsOn() && sender.sessionId === sessionId))) {
3701
+ if (sender && sessionId && (mine || (ticketsOn() && isHomeOf(sender, sessionId)))) {
3274
3702
  const relay = String(args.report_to ?? '').trim().toLowerCase() === 'me';
3275
3703
  const t = await openTicket(sender, named, args.text, sessionId, { title: args.title, thread: chosen, relay });
3276
3704
  const stage = stageOf(t);
3277
3705
  const who = named.id === sender.id ? 'yourself' : `@${named.handle}`;
3278
3706
  const answer = reportsGoDirect(t)
3279
- ? `${named.id === sender.id ? 'You answer' : `@${named.handle} answers`} the person in ${isPanelThread(t.origin?.threadKey) ? 'the topic' : '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.`
3707
+ ? `${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.`
3280
3708
  : 'Its report will arrive here by itself; never wait or poll for it — go on with other work or end your turn.';
3281
3709
  const said =
3282
3710
  stage === 'failed'
@@ -3299,7 +3727,7 @@ export function apply(ctx, config, deps = {}) {
3299
3727
  thread: { type: 'string', description: 'A panel topic (p…) or chat thread key of this turn (or of a task you know of).' },
3300
3728
  text: { type: 'string', required: true, description: 'The reply, as the person should read it.' },
3301
3729
  },
3302
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ via: v.via, thread: v.thread }) },
3730
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ via: v.via, thread: v.thread }) },
3303
3731
  execute: async (args, exec) => {
3304
3732
  const { sessionId, bot } = actor(exec);
3305
3733
  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');
@@ -3333,9 +3761,11 @@ export function apply(ctx, config, deps = {}) {
3333
3761
  const chat = (topic && store.message(topic)?.chat) || bot.id;
3334
3762
  store.log({ from: bot.id, to: 'user', chat, text: body, kind: 'reply', thread: topic ? target.threadKey : panelThreadKey(sessionId), ...(topic ? { topic } : {}) });
3335
3763
  answeredHere();
3336
- return { ok: true, text: topic ? `Shown in the panel, in topic ${topic}.` : 'That thread is the panel: the reply is shown there.', thread: target.threadKey };
3764
+ 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 };
3337
3765
  }
3338
- channels.replyTo(sessionId, target, body);
3766
+ // Said from the home: a reply to it in the chat is a thread that forks here (Bots 0.10).
3767
+ const at = bot.sessionId === sessionId && lastSeq.has(sessionId) ? { sessionId, seq: lastSeq.get(sessionId) } : undefined;
3768
+ channels.replyTo(sessionId, target, body, at);
3339
3769
  answeredHere();
3340
3770
  store.log({ from: bot.id, to: 'user', chat: bot.id, text: body, kind: 'reply', via: target.kind, thread: target.threadKey });
3341
3771
  return { ok: true, text: `Sent to ${threadLabel(target)}.`, thread: target.threadKey, via: target.kind };
@@ -3373,7 +3803,7 @@ export function apply(ctx, config, deps = {}) {
3373
3803
  id: { type: 'string', required: true, description: 'The task id (t…), as on its card.' },
3374
3804
  action: { type: 'string', required: true, enum: ['stop', 'close', 'retry', 'status'] },
3375
3805
  },
3376
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ ticket: v.ticket }) },
3806
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ ticket: v.ticket }) },
3377
3807
  execute: async (args, exec) => {
3378
3808
  const caller = actor(exec);
3379
3809
  const sessionId = caller.sessionId;
@@ -3436,7 +3866,7 @@ export function apply(ctx, config, deps = {}) {
3436
3866
  cron: { type: 'string' },
3437
3867
  time_zone: { type: 'string', description: `IANA zone, default ${zone}.` },
3438
3868
  },
3439
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot, task: v.task }) },
3869
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot, task: v.task }) },
3440
3870
  execute: async (args, exec) => {
3441
3871
  const actorId = exec?.agent?.session?.id;
3442
3872
  const bot = args.bot ? resolve(args.bot) : callerBot(exec) ?? store.primary();
@@ -3478,7 +3908,7 @@ export function apply(ctx, config, deps = {}) {
3478
3908
  kind: { type: 'string', enum: MEMORY_KINDS },
3479
3909
  replace_id: { type: 'string', description: 'Id of an existing note this one corrects or replaces.' },
3480
3910
  },
3481
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ note: v.note, scope: v.scope }) },
3911
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ note: v.note, scope: v.scope }) },
3482
3912
  execute: async (args, exec) => {
3483
3913
  const me = callerBot(exec);
3484
3914
  const scope = args.scope === 'team' ? 'team' : 'self';
@@ -3598,9 +4028,10 @@ export function apply(ctx, config, deps = {}) {
3598
4028
  const live = agents();
3599
4029
  const sample = store.list().map((b) => (b.sessionId ? live?.get?.(b.sessionId) : undefined)).find(Boolean) ?? live?.list?.()?.[0];
3600
4030
  const scope = sample ? scopeOf(sample.ctx) : undefined;
3601
- for (const d of ctx.tools.definitions(scope)) {
3602
- if (TOOL_NAMES.includes(d.name) || d.name.startsWith('mcp__') || d.name === 'run_code') continue;
3603
- toolRows.push({ name: d.name, description: String(d.description ?? '').split(/(?<=\.)\s/)[0].slice(0, 200) });
4031
+ // Before the sample's limits (a router home's would hide what Router mode turns off, 0.10.1).
4032
+ for (const name of unlimitedTools(scope)) {
4033
+ if (TOOL_NAMES.includes(name) || name.startsWith('mcp__') || name === 'run_code') continue;
4034
+ toolRows.push({ name, description: toolInfo.get(name) ?? '' });
3604
4035
  }
3605
4036
  } catch {
3606
4037
  // No registry view.
@@ -3663,6 +4094,8 @@ export function apply(ctx, config, deps = {}) {
3663
4094
  mcp: Boolean(mcpClient),
3664
4095
  // Off for a router dispatcher unless its bot lists them in `tools.routerAllow`.
3665
4096
  routerDeny: [...ROUTER_DENY],
4097
+ // Off for the dispatcher while the team has more than one bot: its teammates help instead.
4098
+ teamDeny: inTeam() ? [...SUBAGENT_TOOLS] : [],
3666
4099
  zone,
3667
4100
  };
3668
4101
  }
@@ -3970,6 +4403,9 @@ export function apply(ctx, config, deps = {}) {
3970
4403
  ticketMap,
3971
4404
  messageCount: store.messageCount(),
3972
4405
  version: store.version(),
4406
+ // The Bots this process loaded (the panel asks for a restart when it is newer), and the last new topic.
4407
+ botsVersion: VERSION,
4408
+ rotatedAt,
3973
4409
  limits: { skills: MAX_SKILLS, skillsOn: MAX_SKILLS_ON },
3974
4410
  teamNotes: memory.notes('team').length,
3975
4411
  dispatcher: s.dispatcher,
@@ -4389,6 +4825,15 @@ export function apply(ctx, config, deps = {}) {
4389
4825
  },
4390
4826
  },
4391
4827
  'memory/dream': { post: async () => ({ ok: true, result: await dream({ reason: 'manual' }) }) },
4828
+ 'threads/seen': {
4829
+ post: (body) => {
4830
+ const root = String(body.root ?? '');
4831
+ const m = root ? store.message(root) : undefined;
4832
+ if (!m || (body.bot && !inChat(m, String(body.bot)))) return { ok: false, reason: 'no such message' };
4833
+ discussions.markSeen(root, nowMs());
4834
+ return { ok: true, unread: 0 };
4835
+ },
4836
+ },
4392
4837
  'topic/new': {
4393
4838
  post: async (body) => {
4394
4839
  const bot = store.get(String(body.id ?? ''));
@@ -4414,23 +4859,66 @@ export function apply(ctx, config, deps = {}) {
4414
4859
  };
4415
4860
 
4416
4861
  /**
4417
- * GET /messages?bot=&topic=&limit=: a bot's chat (or one topic of it, or everything), oldest first,
4418
- * and per topic seen there its key and the tasks it has (PLAN-0.9 §7.3).
4862
+ * GET /messages?bot=&limit=: a bot's chat as it was said, oldest first (Bots 0.10): a reply in a
4863
+ * thread is in it too, with the message it quotes (`quote`, like a chat app's quoted reply); and a
4864
+ * summary of the thread under each of its messages that has one. With `topic=<rootId>`: that
4865
+ * thread alone, its root first. Without `bot`: everything.
4419
4866
  */
4420
4867
  function messagesView(url) {
4421
4868
  const bot = url.searchParams.get('bot') ?? '';
4422
4869
  const topic = url.searchParams.get('topic') ?? '';
4423
4870
  const limit = Number(url.searchParams.get('limit')) || (topic ? 500 : 200);
4424
- const items = store.messages({ bot, limit, topic }).map(messageView);
4425
- const roots = new Set(items.flatMap((m) => [m.topic, m.movedTo]).filter(Boolean));
4426
- const topics = {};
4427
- for (const root of roots) {
4428
- const first = items.find((m) => m.id === root) ?? store.message(root);
4429
- const key = topicKeyOf(first, root) || items.find((m) => m.topic === root && m.id !== root && panelTopicOf(m.thread) === root)?.thread;
4430
- if (!key) continue;
4431
- topics[root] = { key, tickets: tickets.subscribers(key).filter((t) => !t.archivedAt).map(ticketRow) };
4871
+ if (topic) {
4872
+ const items = store.messages({ bot, limit, topic }).map(messageView);
4873
+ const replies = store.replies(bot, [topic]);
4874
+ const sum = threadSummary(topic, replies.get(topic) ?? [], items.find((m) => m.id === topic) ?? store.message(topic));
4875
+ return { items, threads: sum ? { [topic]: sum } : {} };
4876
+ }
4877
+ const rows = store.messages({ bot, limit, roots: false });
4878
+ const byId = new Map(rows.map((m) => [m.id, m]));
4879
+ const roots = new Set(rows.map(rootIdOf).filter(Boolean));
4880
+ const replies = store.replies(bot, roots);
4881
+ const lookup = (id) => byId.get(id) ?? store.message(id);
4882
+ const items = rows.map((m) => {
4883
+ const v = messageView(m);
4884
+ const q = quoteOf(m, replies, lookup);
4885
+ return q ? { ...v, quote: q } : v;
4886
+ });
4887
+ const threads = {};
4888
+ for (const m of rows) {
4889
+ if (rootIdOf(m) !== m.id) continue;
4890
+ const sum = threadSummary(m.id, replies.get(m.id) ?? [], m);
4891
+ if (sum) threads[m.id] = sum;
4432
4892
  }
4433
- return { items, topics };
4893
+ return { items, threads };
4894
+ }
4895
+ /**
4896
+ * The thread under a panel message as the chat lists it (PLAN-0.10 §7.2): its key, how many
4897
+ * replies, the latest, how many of the bots' replies came since the person looked, whether a
4898
+ * bot is answering in it now, and the tasks it follows. Null when the message has no thread.
4899
+ */
4900
+ function threadSummary(rootId, replies, root) {
4901
+ const d = discussions.byRoot(rootId);
4902
+ const key = d?.key || topicKeyOf(root, rootId) || replies.find((m) => panelTopicOf(m.thread) === rootId)?.thread || '';
4903
+ const list = key ? tickets.subscribers(key).filter((t) => !t.archivedAt) : [];
4904
+ const said = replies.filter((m) => m.kind !== 'system' && m.kind !== 'topic' && !betweenBots(m) && m.from !== m.to);
4905
+ if (!said.length && !d && !list.length) return null;
4906
+ const last = said.at(-1);
4907
+ const seen = discussions.seenAt(rootId);
4908
+ const unread = said.filter((m) => m.from !== 'user' && Number(m.at) > seen).length;
4909
+ // The thread's bot answering now (the chat shows it at work); `running` counts its working tasks too.
4910
+ const answering = Boolean(d) && agents()?.get?.(d.sessionId)?.status === 'running';
4911
+ const running = answering || list.some((t) => stageOf(t) === 'working');
4912
+ return {
4913
+ key,
4914
+ count: said.length,
4915
+ lastAt: last ? Number(last.at) || 0 : 0,
4916
+ last: last ? { from: last.from, text: clip(String(last.text ?? ''), PREVIEW_CHARS).text } : null,
4917
+ unread,
4918
+ running,
4919
+ answering,
4920
+ tickets: list.map(ticketRow),
4921
+ };
4434
4922
  }
4435
4923
 
4436
4924
  /** GET /tickets?bot=&stage=&limit=&offset=: rows, the latest change first; `stage` may list several (a,b). */
@@ -4589,6 +5077,14 @@ function serveAvatar(dir, req, res) {
4589
5077
  }
4590
5078
 
4591
5079
  const LOGO_DIR = fileURLToPath(new URL('./logos/', import.meta.url));
5080
+ /** The Bots version this process loaded: the panel compares it with its own, to say when Harness needs a restart. */
5081
+ const VERSION = (() => {
5082
+ try {
5083
+ return String(JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version ?? '');
5084
+ } catch {
5085
+ return '';
5086
+ }
5087
+ })();
4592
5088
 
4593
5089
  /** `${R}/logo/<name>.png`: an app logo shipped with the plugin. */
4594
5090
  export function serveLogo(req, res) {