@kadaliao/dsh-bots 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,17 +1,31 @@
1
1
  /**
2
2
  * Host half of the bots bundle: Grok-style bots inside DeepSeek Harness.
3
3
  *
4
- * A bot is a named persona with its own conversation (a DSH Session), avatar,
5
- * skills, tool access, apps (MCP servers, e.g. open-computer-use) and scheduled
6
- * tasks. Bots message each other: `bot_send_message` drops the text into the
7
- * other bot's inbox, which wakes it; the reply travels back the same way. One
8
- * bot is the dispatcher that delegates work and schedules tasks.
4
+ * A bot is a named persona with its own conversation (a DSH Session, its
5
+ * "home"), avatar, skills, tool access, apps (MCP servers, e.g.
6
+ * open-computer-use) and scheduled tasks. One bot is the dispatcher that
7
+ * delegates work and schedules tasks.
8
+ *
9
+ * How bots hand work to each other depends on the team's `dispatcher` setting:
10
+ *
11
+ * - `router` (the default since 0.8): `bot_send_message` from a bot's home opens
12
+ * a ticket (lib/tickets.mjs) for the other bot, which works on it in a
13
+ * Session of its own (`ticket-<id>`) and reports back with a status; the
14
+ * dispatcher's home only understands, hands out and reports (its tools are
15
+ * limited and it may not wait). At most `tickets.maxWorking` ticket Sessions
16
+ * run at once; the rest queue.
17
+ * - `hands-on` (0.7): `bot_send_message` drops the text into the other bot's
18
+ * home inbox, which wakes it; the reply travels back the same way.
19
+ *
20
+ * A ticket Session works the same way in both modes: reports go to whoever
21
+ * asked, and asking another bot opens a sub-ticket.
9
22
  *
10
23
  * Everything a bot is made of is applied to its Agent's own scope when that
11
24
  * Agent comes up (and re-applied when the bot changes): a persona prompt
12
- * section, runtime skills, a tool restriction and agent-scoped MCP clients.
13
- * Nothing touches other conversations, except the bot tools themselves, which
14
- * every conversation gets so the user can manage bots from anywhere.
25
+ * section, runtime skills, a tool restriction and agent-scoped MCP clients. A
26
+ * ticket Session is decorated as its executing bot the same way. Nothing
27
+ * touches other conversations, except the bot tools themselves, which every
28
+ * conversation gets so the user can manage bots from anywhere.
15
29
  *
16
30
  * Chat channel apps (Telegram, Discord, Feishu / Lark, Slack) are no MCP servers: lib/channels.mjs
17
31
  * keeps a connector running for each, so paired people can message the team
@@ -22,7 +36,7 @@
22
36
 
23
37
  import { createReadStream, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
24
38
  import { homedir } from 'node:os';
25
- import { join, sep } from 'node:path';
39
+ import { isAbsolute, join, sep } from 'node:path';
26
40
  import { fileURLToPath } from 'node:url';
27
41
  import { randomUUID } from 'node:crypto';
28
42
 
@@ -34,12 +48,17 @@ import { TEAMS, teamTiming, teamView } from './lib/teams.mjs';
34
48
  import { maskedApp, scanExternalMcp } from './lib/mcp-import.mjs';
35
49
  import { createUnfurler } from './lib/unfurl.mjs';
36
50
  import { isLogoName, withLogo } from './lib/logos.mjs';
37
- import { CHANNEL_LABELS, channelEntry, channelIssue, createChannels, maskBot, unmaskApps } from './lib/channels.mjs';
38
- import { describeTiming, dmBody, dmHeader, personaText, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
51
+ import { askNoticeText, CHANNEL_LABELS, channelEntry, channelIssue, createChannels, credentialsOf, maskBot, threadNote, unmaskApps } from './lib/channels.mjs';
52
+ import { createActivity } from './lib/activity.mjs';
53
+ import { describeTiming, dmBody, dmHeader, noWaitReason, personaText, reportsGoDirect, ROUTER_DENY, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
39
54
  import { createSettings } from './lib/settings.mjs';
40
55
  import { createPriceCatalog, priceOf } from './lib/prices.mjs';
41
- import { createLedger, promptTokens, report, todayByBot, usageRow } from './lib/usage.mjs';
42
- import { createMemory, dreamBotPrompt, dreamTeamPrompt, KINDS as MEMORY_KINDS, looksSecret, parseJsonReply, reflectionPrompt } from './lib/memory.mjs';
56
+ import { createLedger, promptTokens, report, ticketUsage, todayByBot, usageRow } from './lib/usage.mjs';
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';
59
+ import { checkTickets, isTransient, requesterReminders, retryDelay } from './lib/watchdog.mjs';
60
+ import { isLiveSubscriber, isPanelThread, isTopicThread, panelThreadKey, panelTopicOf, parseThreadKey, threadLabel, toThreadKey } from './lib/threads.mjs';
61
+ import { createMemory, dreamBotPrompt, dreamTeamPrompt, KINDS as MEMORY_KINDS, looksSecret, parseJsonReply, reflectionPrompt, searchTickets } from './lib/memory.mjs';
43
62
  import { createTopics, rotationReason } from './lib/topics.mjs';
44
63
  import { API_KINDS, CODEX_ROUTE, PI_SCOPE, ROUTE_PREFIX, codexAuthFile, createCodexSync, detectLogins, discoverModels, endpointView, keyRefFor, profileFor, readCodexAuth, codexCredential } from './lib/models.mjs';
45
64
 
@@ -79,6 +98,8 @@ const scopeOf = (await harnessModule('@deepseek-ai/dsh-scope'))?.scopeOf ?? (()
79
98
  // The registry wants the compiled definition; outside a Harness the raw one stands in.
80
99
  const defineTool = toolsModule?.defineTool ?? ((definition) => definition);
81
100
  const createUserMessage = llmModule?.createUserMessage ?? ((input) => Object.freeze({ ...structuredClone(input), role: 'user', id: randomUUID() }));
101
+ /** A message whose id the caller chose (an idempotent delivery); detached and frozen like Harness's own. */
102
+ const freezeMessage = llmModule?.freezeMessage ?? ((message) => Object.freeze(structuredClone(message)));
82
103
 
83
104
  export const inject = ['tools'];
84
105
  export const name = 'bots';
@@ -96,7 +117,19 @@ const AVATAR_ATTEMPTS = 3;
96
117
  /** Errors from a gateway or the network rather than from the request itself. */
97
118
  export const TRANSIENT = /\b(408|409|429|500|502|503|504|520|522|524)\b|connection (lost|reset|closed)|ECONNRESET|ETIMEDOUT|EPIPE|socket hang up|fetch failed|could not reach|did not answer within|overloaded|temporarily/i;
98
119
 
99
- export const TOOL_NAMES = ['bot_list', 'bot_create', 'bot_update', 'bot_delete', 'bot_send_message', 'bot_schedule', 'memory_save', 'memory_forget', 'memory_search'];
120
+ export const TOOL_NAMES = ['bot_list', 'bot_create', 'bot_update', 'bot_delete', 'bot_send_message', 'bot_reply', 'bot_recall', 'bot_ticket', 'bot_schedule', 'memory_save', 'memory_forget', 'memory_search'];
121
+ /** Message ids of the plugin's own deliveries start with this, so a retry can tell it already delivered one. */
122
+ const MESSAGE_PREFIX = 'bots:';
123
+ /**
124
+ * Relays about a ticket, by the kind in their message id (`bots:<kind>:<ticketId>:…`). These are
125
+ * inputs of the requester's turn: the ticket's origin Thread joins it (replies to the person go there).
126
+ */
127
+ const RELAY_KINDS = new Set(['report', 'failed', 'stalled']);
128
+ /** When queued tickets are first launched after the plugin starts (Harness services settle first); working ones get their recovery notes then. */
129
+ const STARTUP_PUMP_MS = 3000;
130
+ /** Events read from the end of a Session's stored log for its delivered message ids, and the largest log read at all. */
131
+ const HISTORY_TAIL = 4000;
132
+ const HISTORY_MAX_BYTES = 32 * 1024 * 1024;
100
133
  const MEMORY_SECTION = 'bots:memory';
101
134
  const MEMORY_ORDER = 60;
102
135
  /** How often idle conversations are checked for a new topic, and the daily consolidation for being due. */
@@ -190,16 +223,30 @@ const service = (ctx, name) => {
190
223
  /**
191
224
  * @param {object} ctx
192
225
  * @param {object} config
193
- * @param {{loadConnector?: (kind: string) => Promise<object>, typingEveryMs?: number}} [deps] - for tests: a stand-in chat connector.
226
+ * @param {{loadConnector?: (kind: string) => Promise<object>, typingEveryMs?: number, now?: () => number,
227
+ * setTimeout?: Function, clearTimeout?: Function}} [deps] - for tests: a stand-in chat connector; the clock and
228
+ * the timers the task watchdog (status checks, retries after temporary errors) runs on.
194
229
  */
195
230
  export function apply(ctx, config, deps = {}) {
196
231
  const cfg = config && typeof config === 'object' ? config : {};
197
232
  const dir = join(homeDir(), 'cache', 'bots');
233
+ const nowMs = deps.now ?? Date.now;
234
+ const setTimer = deps.setTimeout ?? setTimeout;
235
+ const clearTimer = deps.clearTimeout ?? clearTimeout;
198
236
  const store = createStore(dir);
199
237
  const settings = createSettings(dir);
200
238
  const ledger = createLedger(dir);
201
239
  const memory = createMemory(join(dir, 'memory'));
202
240
  const topics = createTopics(dir);
241
+ const tickets = createTickets(dir, { now: nowMs });
242
+ // A tasks file that is there but cannot be read stops the plugin now, before anything writes over it.
243
+ try {
244
+ tickets.open();
245
+ } catch (error) {
246
+ (ctx.logger?.error ?? ctx.logger?.warn)?.call(ctx.logger, `bots: not starting: ${error?.message ?? error}`);
247
+ throw error;
248
+ }
249
+ const slots = createSlots(settings.get().tickets.maxWorking);
203
250
  const prices = createPriceCatalog(dir, { enabled: deps.prices !== false, ...(deps.fetch ? { fetch: deps.fetch } : {}) });
204
251
  const home = deps.home ?? homedir();
205
252
  const workdir = typeof cfg.workdir === 'string' && cfg.workdir.trim() ? cfg.workdir.trim() : join(homeDir(), 'bots', 'workspace');
@@ -212,6 +259,8 @@ export function apply(ctx, config, deps = {}) {
212
259
  })();
213
260
 
214
261
  // --- seeding: a dispatcher on the very first run ---------------------------------
262
+ /** Bots from an earlier version: this team was there before 0.8 made router mode the default. */
263
+ const hadBots = store.list().length > 0;
215
264
  const seededFile = join(dir, 'seeded');
216
265
  const zh = /^zh/i.test(String(cfg.language ?? '') || Intl.DateTimeFormat().resolvedOptions().locale || process.env.LANG || '');
217
266
  if (store.list().length === 0 && !existsSync(seededFile)) {
@@ -233,6 +282,73 @@ export function apply(ctx, config, deps = {}) {
233
282
  }
234
283
  }
235
284
 
285
+ // The first run of 0.8 decides once whether the panel tells the user that the dispatcher now routes.
286
+ if (settings.get().routerNotice === null) {
287
+ try {
288
+ settings.save({ routerNotice: hadBots ? 'pending' : 'dismissed' });
289
+ } catch {
290
+ // Asked again at the next start.
291
+ }
292
+ }
293
+
294
+ // --- which bot a conversation belongs to ---------------------------------------------
295
+ /** Ticket Sessions the controller named something other than `ticket-<id>`. */
296
+ const otherTicketSessions = new Set();
297
+ /** The ticket a Session runs, if it is a ticket Session. */
298
+ const ticketOf = (sessionId) => (typeof sessionId === 'string' && (sessionId.startsWith('ticket-') || otherTicketSessions.has(sessionId)) ? tickets.bySession(sessionId) : undefined);
299
+ // --- what each bot does right now (the panel's live status) -----------------------------
300
+ /** The tokens of every chat app, kept out of what the page is shown of a running tool. */
301
+ function channelSecrets() {
302
+ const tpl = templates();
303
+ const out = [];
304
+ for (const b of store.list()) {
305
+ for (const app of b.apps) {
306
+ const entry = channelEntry(app, tpl);
307
+ if (entry) out.push(...credentialsOf(app, entry).secrets);
308
+ }
309
+ }
310
+ return out;
311
+ }
312
+ const activity = createActivity({ now: nowMs, secrets: channelSecrets, handleOf: (ref) => (store.find(String(ref)) ? `@${store.find(String(ref)).handle}` : '') });
313
+
314
+ /** The bot of a home Session or of a ticket Session (its executing bot). */
315
+ function botOfSession(sessionId) {
316
+ if (!sessionId) return undefined;
317
+ const home = store.bySession(sessionId);
318
+ if (home) return home;
319
+ const t = ticketOf(sessionId);
320
+ return t ? store.get(t.botId) : undefined;
321
+ }
322
+ const dispatcherMode = () => settings.get().dispatcher;
323
+ /**
324
+ * Router mode is in effect: the setting says so and the dispatcher has someone to hand work to. A
325
+ * dispatcher that is the only bot works hands-on (a router alone would have no hands); adding a
326
+ * second bot makes it a router, removing the last teammate makes it hands-on again.
327
+ */
328
+ const routerActive = () => dispatcherMode() === 'router' && store.list().length > 1;
329
+ /** The dispatcher works as a router (in its home; its ticket Sessions are ordinary workers). */
330
+ const isRouter = (bot) => Boolean(bot) && bot.role === 'primary' && routerActive();
331
+ const isRouterHome = (bot, sessionId) => isRouter(bot) && Boolean(sessionId) && bot.sessionId === sessionId && !ticketOf(sessionId);
332
+ /** Bot-to-bot work opens tickets (router mode), or goes to the other bot's home as in 0.7 (hands-on). */
333
+ const ticketsOn = () => dispatcherMode() === 'router';
334
+
335
+ /**
336
+ * Questions a bot's home or ticket Session put to the person with `ask_user_question`, by id, while
337
+ * they wait (see "questions a bot asks" below). In memory only: they die with the process, as the
338
+ * tool call does.
339
+ */
340
+ const asks = new Map();
341
+ const askingIn = (sessionId) => Boolean(sessionId) && [...asks.values()].some((a) => a.sessionId === sessionId);
342
+ /** The questions still waiting. One past its timed wait (`continued`) goes with its task's end, or with its home (a new topic). */
343
+ function pendingAsks() {
344
+ for (const a of asks.values()) {
345
+ if (!a.continued) continue;
346
+ 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);
348
+ }
349
+ return [...asks.values()];
350
+ }
351
+
236
352
  // --- applying a bot to its Agent ----------------------------------------------------
237
353
  /** sessionId → {agent, signature, disposers[]} */
238
354
  const installed = new Map();
@@ -240,7 +356,9 @@ export function apply(ctx, config, deps = {}) {
240
356
  const isChannel = (app) => Boolean(channelEntry(app, templates()));
241
357
  // Chat channels run outside the Agent; changing one does not restart the bot's MCP clients.
242
358
  // A linked local skill counts by what its SKILL.md is now, so an edit there re-installs it.
243
- const signatureOf = (bot) => 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 });
359
+ // A router home also changes with the dispatcher mode and the role (its tool limits and guard).
360
+ 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 });
244
362
  /** The chat apps the team can be reached from ('Telegram'), for the persona. */
245
363
  const channelNames = (bots) => {
246
364
  const tpl = templates();
@@ -263,6 +381,10 @@ export function apply(ctx, config, deps = {}) {
263
381
 
264
382
  function install(agent, bot) {
265
383
  const actx = agent.ctx;
384
+ const sessionId = agent.session.id;
385
+ // A ticket Session is its executing bot working on one task; the persona says so.
386
+ const ticketId = ticketOf(sessionId)?.id ?? '';
387
+ const router = isRouterHome(bot, sessionId);
266
388
  const disposers = [];
267
389
  const skillNames = {};
268
390
  const skills = service(actx, 'skills');
@@ -328,7 +450,10 @@ export function apply(ctx, config, deps = {}) {
328
450
  text: () => {
329
451
  const now = store.get(bot.id);
330
452
  const roster = store.list();
331
- return now ? personaText(now, roster, { skillsInline, skillNames, apps: appNames, channels: channelNames(roster) }) : '';
453
+ const ticket = ticketId ? tickets.get(ticketId) : undefined;
454
+ return now
455
+ ? personaText(now, roster, { skillsInline, skillNames, apps: appNames, channels: channelNames(roster), dispatcher: routerActive() ? 'router' : 'hands-on', tickets: ticketsOn(), ...(ticket ? { ticket } : {}) })
456
+ : '';
332
457
  },
333
458
  }),
334
459
  );
@@ -342,30 +467,42 @@ export function apply(ctx, config, deps = {}) {
342
467
  ctx.logger?.warn?.(`bots: memory for @${bot.handle}: ${error?.message ?? error}`);
343
468
  }
344
469
  }
345
- if (bot.tools.deny.length > 0) {
470
+ // A router home is also denied the tools that do the work, except those the user gave back.
471
+ const allowed = new Set(bot.tools.routerAllow ?? []);
472
+ const wanted = [...new Set([...bot.tools.deny, ...(router ? ROUTER_DENY.filter((n) => !allowed.has(n)) : [])])];
473
+ if (wanted.length > 0) {
346
474
  const tools = service(actx, 'tools');
347
475
  try {
348
476
  const view = ctx.tools?.view?.(scopeOf(actx));
349
477
  const known = view?.restrictableNames instanceof Set ? view.restrictableNames : new Set((ctx.tools?.definitions?.() ?? []).map((d) => d.name));
350
- const deny = bot.tools.deny.filter((n) => known.has(n) && n !== 'run_code');
478
+ const deny = wanted.filter((n) => known.has(n) && n !== 'run_code');
351
479
  if (deny.length > 0 && tools?.restrict) disposers.push(tools.restrict({ deny }));
352
480
  } catch (error) {
353
481
  ctx.logger?.warn?.(`bots: tool access for @${bot.handle}: ${error?.message ?? error}`);
354
482
  }
355
483
  }
356
- installed.set(agent.session.id, { agent, signature: signatureOf(bot), disposers });
484
+ if (router) {
485
+ // Even with `bash` given back, a router may not sleep or wait long: reports arrive by themselves.
486
+ const tools = service(actx, 'tools');
487
+ try {
488
+ if (typeof tools?.guard === 'function') disposers.push(tools.guard((execution) => noWaitReason(execution)));
489
+ } catch (error) {
490
+ ctx.logger?.warn?.(`bots: dispatcher guard for @${bot.handle}: ${error?.message ?? error}`);
491
+ }
492
+ }
493
+ installed.set(sessionId, { agent, signature: signatureOf(bot, sessionId), disposers });
357
494
  }
358
495
 
359
496
  function reconcile(agent) {
360
497
  const sessionId = agent?.session?.id;
361
498
  if (!sessionId) return;
362
- const bot = store.bySession(sessionId);
499
+ const bot = botOfSession(sessionId);
363
500
  const rec = installed.get(sessionId);
364
501
  if (!bot) {
365
502
  if (rec) uninstall(sessionId);
366
503
  return;
367
504
  }
368
- if (rec && rec.agent === agent && rec.signature === signatureOf(bot)) return;
505
+ if (rec && rec.agent === agent && rec.signature === signatureOf(bot, sessionId)) return;
369
506
  if (rec) uninstall(sessionId);
370
507
  install(agent, bot);
371
508
  }
@@ -387,19 +524,24 @@ export function apply(ctx, config, deps = {}) {
387
524
  });
388
525
  ctx.effect(
389
526
  () =>
390
- store.onChange(() => {
391
- const live = agents();
392
- for (const bot of store.list()) {
393
- const agent = bot.sessionId ? live?.get?.(bot.sessionId) : undefined;
394
- if (agent) reconcile(agent);
395
- }
396
- for (const sessionId of [...installed.keys()]) if (!store.bySession(sessionId)) uninstall(sessionId);
397
- }),
527
+ store.onChange(() => reapply()),
398
528
  'bots: re-apply changed bots',
399
529
  );
400
530
  ctx.effect(() => () => {
401
531
  for (const id of [...installed.keys()]) uninstall(id);
402
532
  }, 'bots: unwind bot scopes');
533
+ /** Apply every bot again to its live home and ticket Sessions (a bot, the roles or the dispatcher mode changed). */
534
+ function reapply() {
535
+ const live = agents();
536
+ for (const bot of store.list()) {
537
+ const agent = bot.sessionId ? live?.get?.(bot.sessionId) : undefined;
538
+ if (agent) reconcile(agent);
539
+ }
540
+ for (const [sessionId, rec] of [...installed]) {
541
+ if (!botOfSession(sessionId)) uninstall(sessionId);
542
+ else reconcile(rec.agent);
543
+ }
544
+ }
403
545
 
404
546
  // --- sessions ---------------------------------------------------------------------
405
547
  async function workspaceId() {
@@ -544,7 +686,7 @@ export function apply(ctx, config, deps = {}) {
544
686
  function memoryTextFor(sessionId) {
545
687
  let text = memoText.get(sessionId);
546
688
  if (text === undefined) {
547
- const bot = store.bySession(sessionId);
689
+ const bot = botOfSession(sessionId);
548
690
  try {
549
691
  text = bot ? memory.promptFor(bot, { tz: tzMinutes() }) : '';
550
692
  } catch {
@@ -573,15 +715,17 @@ export function apply(ctx, config, deps = {}) {
573
715
  }
574
716
  return firstLine(said);
575
717
  }
576
- function startTask(bot, sessionId, kind, event, via) {
718
+ function startTask(bot, sessionId, kind, event, via, typed) {
577
719
  const content = event.data?.content;
578
- const said = textOf(content);
720
+ const said = typed ?? textOf(content);
579
721
  const sched = kind === 'schedule' ? (/schedule_id_json:\s*"([^"]+)"/.exec(said)?.[1] ?? /"schedule_id":\s*"([^"]+)"/.exec(said)?.[1] ?? '') : '';
580
- const from = kind === 'agent-message' ? (store.bySession(event.data?.source?.senderSessionId)?.id ?? 'user') : '';
722
+ const from = kind === 'agent-message' ? (botOfSession(event.data?.source?.senderSessionId)?.id ?? 'user') : '';
723
+ const ticket = ticketOf(sessionId);
581
724
  const task = {
582
725
  id: `task-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
583
726
  b: bot.id,
584
727
  s: sessionId,
728
+ ...(ticket ? { t: ticket.id } : {}),
585
729
  trigger: kind === 'schedule' ? 'schedule' : kind === 'agent-message' ? 'dm' : via ? 'chat' : 'user',
586
730
  ...(via ? { via: via.kind } : {}),
587
731
  ...(from ? { from } : {}),
@@ -594,7 +738,8 @@ export function apply(ctx, config, deps = {}) {
594
738
  replied: false,
595
739
  };
596
740
  openTasks.set(sessionId, task);
597
- topics.current(bot.id, sessionId);
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);
598
743
  return task;
599
744
  }
600
745
  function logLine(task, line) {
@@ -608,8 +753,9 @@ export function apply(ctx, config, deps = {}) {
608
753
  function recordUsage(bot, sessionId, { at, kind, provider, model, usage }) {
609
754
  if (!usage) return;
610
755
  const task = openTasks.get(sessionId);
611
- ledger.record(usageRow({ at, botId: bot.id, sessionId, taskId: kind === 'chat' || kind === 'compaction' ? task?.id : undefined, kind, provider, model, usage }));
612
- if (kind === 'chat') topics.noteCall(bot.id, sessionId, promptTokens(usage));
756
+ const ticketId = ticketOf(sessionId)?.id;
757
+ 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));
613
759
  }
614
760
  /** The task of `sessionId` is over when its Agent is idle again. */
615
761
  function settleSoon(sessionId, delay = 1200) {
@@ -631,9 +777,38 @@ export function apply(ctx, config, deps = {}) {
631
777
  row.end = Date.now();
632
778
  row.status = status ?? (task.status === 'running' ? 'done' : task.status);
633
779
  ledger.finishTask(row);
780
+ if (task.t) {
781
+ // A run of a ticket: its transcript waits for the ticket's end, which is summarized once.
782
+ keepTicketLog(task.t, log);
783
+ const t = tickets.get(task.t);
784
+ if (t?.ended) reflectTicket(t);
785
+ return;
786
+ }
634
787
  topics.noteTask(task.b, task.s, task.title);
635
788
  if (bot) queueReflection(bot, { ...row, log });
636
789
  }
790
+ /** ticketId → transcript lines of its finished runs, for the summary written when it ends. */
791
+ const ticketLogs = new Map();
792
+ function keepTicketLog(ticketId, lines) {
793
+ const rec = ticketLogs.get(ticketId) ?? { log: [], size: 0 };
794
+ for (const line of lines ?? []) logLine(rec, line);
795
+ ticketLogs.set(ticketId, rec);
796
+ }
797
+ /** ticketId → the transcript lines of an ended ticket, kept for bot_recall when Harness keeps no log (the latest 50). */
798
+ const doneLogs = new Map();
799
+ /** A ticket ended: its executing bot summarizes the work into its memory, as after any task. */
800
+ function reflectTicket(t) {
801
+ const rec = ticketLogs.get(t.id);
802
+ ticketLogs.delete(t.id);
803
+ if (rec?.log.length) {
804
+ doneLogs.delete(t.id);
805
+ doneLogs.set(t.id, [...rec.log]);
806
+ if (doneLogs.size > 50) doneLogs.delete(doneLogs.keys().next().value);
807
+ }
808
+ const bot = store.get(t.botId);
809
+ if (!bot || !rec?.log.length) return;
810
+ queueReflection(bot, { id: t.id, ticket: t.id, b: bot.id, s: t.sessionId, trigger: 'ticket', from: t.requester?.botId ?? 'user', title: t.title, log: rec.log });
811
+ }
637
812
 
638
813
  // --- memory ----------------------------------------------------------------------------------
639
814
  const reflecting = new Map();
@@ -650,7 +825,15 @@ export function apply(ctx, config, deps = {}) {
650
825
  return next;
651
826
  }
652
827
  const triggerWords = (task) =>
653
- task.trigger === 'schedule' ? 'a scheduled task' : task.trigger === 'dm' ? `a message from ${task.from === 'user' ? 'the user' : `@${store.get(task.from)?.handle ?? 'another bot'}`}` : task.trigger === 'chat' ? `a ${task.via ?? 'chat'} message from the user` : 'a message from the user';
828
+ task.trigger === 'ticket'
829
+ ? `task ${task.ticket} from ${task.from === 'user' ? 'the user' : `@${store.get(task.from)?.handle ?? 'another bot'}`}`
830
+ : task.trigger === 'schedule'
831
+ ? 'a scheduled task'
832
+ : task.trigger === 'dm'
833
+ ? `a message from ${task.from === 'user' ? 'the user' : `@${store.get(task.from)?.handle ?? 'another bot'}`}`
834
+ : task.trigger === 'chat'
835
+ ? `a ${task.via ?? 'chat'} message from the user`
836
+ : 'a message from the user';
654
837
  async function reflect(bot, task) {
655
838
  // A bot deleted while its summary waited keeps nothing.
656
839
  if (!store.get(bot.id)) return;
@@ -664,7 +847,7 @@ export function apply(ctx, config, deps = {}) {
664
847
  try {
665
848
  const p = reflectionPrompt({ bot, notes: memory.notes(bot.id), team: memory.notes('team'), transcript, trigger: triggerWords(task) });
666
849
  const r = await complete(sel, p.system, p.user, { purpose: 'bots-memory', sessionId: task.s });
667
- ledger.record(usageRow({ botId: bot.id, sessionId: task.s, taskId: task.id, kind: 'memory', provider: sel.provider, model: sel.model, usage: r.usage }));
850
+ ledger.record(usageRow({ botId: bot.id, sessionId: task.s, taskId: task.id, ticketId: task.ticket, kind: 'memory', provider: sel.provider, model: sel.model, usage: r.usage }));
668
851
  const parsed = parseJsonReply(r.text) ?? {};
669
852
  summary = String(parsed.summary ?? '').trim();
670
853
  if (Array.isArray(parsed.notes) && parsed.notes.length) memory.edit(bot.id, parsed.notes, { source: 'auto' });
@@ -673,7 +856,7 @@ export function apply(ctx, config, deps = {}) {
673
856
  ctx.logger?.warn?.(`bots: summarizing a task of @${bot.handle} failed: ${error?.message ?? error}`);
674
857
  }
675
858
  }
676
- if (worth || summary) memory.addJournal({ bot: bot.id, task: task.id, trigger: task.trigger, title: task.title, summary: summary || task.title });
859
+ if (worth || summary) memory.addJournal({ bot: bot.id, task: task.id, trigger: task.trigger, ...(task.ticket ? { ticket: task.ticket } : {}), title: task.title, summary: summary || task.title });
677
860
  // The bot started a new topic before this summary was written: that topic reads its memory again.
678
861
  const now = store.get(bot.id)?.sessionId;
679
862
  if (now && now !== task.s) staleMemory(now);
@@ -807,8 +990,7 @@ export function apply(ctx, config, deps = {}) {
807
990
  throw new Error(`could not move the scheduled tasks of @${bot.handle} to a new topic (${failed?.message ?? failed}); it stays in the current one`);
808
991
  }
809
992
  uninstall(prev);
810
- memoText.delete(prev);
811
- memoStale.delete(prev);
993
+ forgetSession(prev);
812
994
  try {
813
995
  await service(ctx, 'workspaceRegistry')?.archiveSession?.(prev);
814
996
  } catch (error) {
@@ -856,60 +1038,1186 @@ export function apply(ctx, config, deps = {}) {
856
1038
  return true;
857
1039
  }
858
1040
 
859
- /** A DM from `sender` (a bot, or null for the user) to `target`. */
1041
+ const pairRefusal = (sender, target) => new Error(`@${sender.handle} and @${target.handle} exchanged ${PAIR_LIMIT} messages in the last 10 minutes; stop and report to the user instead of continuing.`);
1042
+
1043
+ /**
1044
+ * Deliveries the plugin made with an id of its own, per Session: what this process handed over
1045
+ * or saw arrive, and (read once per Session, see `loadHistory`) what its stored log says arrived
1046
+ * before a restart. With the Agent's pending inbox (durable too) it tells a retry the message is
1047
+ * there already.
1048
+ */
1049
+ const deliveredIds = new Map();
1050
+ /**
1051
+ * The tail of a Session's stored log (Harness `sessionPersistence`, a read handle beside the live
1052
+ * writer), or null when there is no such service, no such Session, the log is too large to read
1053
+ * cheaply, or the read comes back in a shape not known here. `deps.history(sessionId)` stands in for tests.
1054
+ * @returns {Promise<object[]|null>}
1055
+ */
1056
+ async function readHistory(sessionId) {
1057
+ if (!sessionId) return null;
1058
+ if (typeof deps.history === 'function') return (await deps.history(sessionId)) ?? null;
1059
+ const persistence = service(ctx, 'sessionPersistence');
1060
+ if (typeof persistence?.open !== 'function') return null;
1061
+ let snap;
1062
+ try {
1063
+ snap = await persistence.stat?.(sessionId);
1064
+ } catch {
1065
+ snap = undefined;
1066
+ }
1067
+ if (persistence.stat && snap === undefined) return null;
1068
+ if (Number(snap?.sizeBytes) > HISTORY_MAX_BYTES) return null;
1069
+ let handle;
1070
+ try {
1071
+ handle = await persistence.open(sessionId, 'read');
1072
+ const count = Number(snap?.eventCount);
1073
+ const offset = Number.isSafeInteger(count) && count > HISTORY_TAIL ? count - HISTORY_TAIL : 0;
1074
+ let read = await handle.read(offset, HISTORY_TAIL);
1075
+ if (offset > 0 && !(read?.events?.length > 0)) read = await handle.read(0);
1076
+ // A read in a shape not known here tells nothing (null), rather than an empty log.
1077
+ return Array.isArray(read?.events) ? read.events : null;
1078
+ } catch {
1079
+ return null;
1080
+ } finally {
1081
+ try {
1082
+ await handle?.close?.();
1083
+ } catch {
1084
+ // Closed with the process.
1085
+ }
1086
+ }
1087
+ }
1088
+ /** Sessions whose stored log was read for delivered ids in this process. */
1089
+ const historyRead = new Map();
1090
+ /** Read the delivered ids of `sessionId`'s stored log once per process (cheap: its tail; nothing without the service). */
1091
+ function loadHistory(sessionId) {
1092
+ if (!sessionId) return Promise.resolve();
1093
+ if (!historyRead.has(sessionId)) {
1094
+ historyRead.set(
1095
+ sessionId,
1096
+ readHistory(sessionId)
1097
+ .then((events) => {
1098
+ for (const e of events ?? []) if (e?.type === 'user/message') noteDelivered(sessionId, e.data?.id);
1099
+ })
1100
+ .catch(() => {}),
1101
+ );
1102
+ }
1103
+ return historyRead.get(sessionId);
1104
+ }
1105
+ const noteDelivered = (sessionId, id) => {
1106
+ if (!sessionId || typeof id !== 'string' || !id.startsWith(MESSAGE_PREFIX)) return;
1107
+ const set = deliveredIds.get(sessionId) ?? new Set();
1108
+ set.add(id);
1109
+ // Bounded: ids are only needed while a retry of the same request may come.
1110
+ if (set.size > 2000) set.delete(set.values().next().value);
1111
+ deliveredIds.set(sessionId, set);
1112
+ };
1113
+ /** An Agent's pending messages: Harness's `{nextTurn, nextStep}` (or a plain list). */
1114
+ const pendingOf = (agent) => {
1115
+ const inbox = agent?.inbox;
1116
+ if (Array.isArray(inbox)) return inbox;
1117
+ return [...(Array.isArray(inbox?.nextTurn) ? inbox.nextTurn : []), ...(Array.isArray(inbox?.nextStep) ? inbox.nextStep : [])];
1118
+ };
1119
+ const holds = (agent, id) => Boolean(deliveredIds.get(agent?.session?.id)?.has(id)) || pendingOf(agent).some((m) => m?.id === id);
1120
+
1121
+ /**
1122
+ * Hand one message to an Agent.
1123
+ * - `mode`: 'steer' (the current turn's next step, or a new turn when idle: messages that arrive
1124
+ * while it works are taken together), 'followup' (a turn of its own; 0.7's only way) or 'inject'
1125
+ * (into the conversation without waking it). A Harness without `steer` gets a followup; one
1126
+ * without `inject` gets nothing for an 'inject' (`dropped`): such a note never wakes a turn.
1127
+ * - `key`: makes the message id `bots:<key>`; a message with that id already pending or delivered
1128
+ * is not delivered again, so a retried request is harmless.
1129
+ * @returns {{message: object, mode: string, skipped: boolean, dropped?: true}}
1130
+ */
1131
+ async function sendTo(agent, { content: blocks, source, mode = 'followup', key }) {
1132
+ // Providers that take a message as one string join its blocks with nothing in between:
1133
+ // a header block ends its line itself, so the text under it starts on a new one.
1134
+ const content = blocks.map((b, i) => (i < blocks.length - 1 && b?.type === 'text' && !b.text.endsWith('\n') ? { ...b, text: `${b.text}\n` } : b));
1135
+ const message = key ? freezeMessage({ id: `${MESSAGE_PREFIX}${key}`, role: 'user', content, source }) : createUserMessage({ content, source });
1136
+ // A note that must not wake anyone is dropped where Harness cannot inject: it is "good to know", never worth a turn.
1137
+ if (mode === 'inject' && typeof agent.inject !== 'function') return { message, mode, skipped: true, dropped: true };
1138
+ if (key) await loadHistory(agent.session?.id);
1139
+ if (key && holds(agent, message.id)) return { message, mode, skipped: true };
1140
+ const how = mode === 'inject' ? 'inject' : mode !== 'followup' && typeof agent.steer === 'function' ? 'steer' : 'followup';
1141
+ agent[how](message);
1142
+ if (key) noteDelivered(agent.session?.id, message.id);
1143
+ await flush(agent);
1144
+ return { message, mode: how, skipped: false };
1145
+ }
1146
+ /** How a bot's home takes new input: a router steers (backlog is handled together), every other home as in 0.7. */
1147
+ const homeMode = (bot) => (isRouter(store.get(bot.id) ?? bot) ? 'steer' : 'followup');
1148
+
1149
+ /** A DM from `sender` (a bot, or null for the user) to `target`'s home: 0.7's bot-to-bot message. */
860
1150
  async function deliver(sender, target, text, senderSessionId) {
861
1151
  const body = String(text ?? '').trim();
862
1152
  if (body === '') throw new Error('text must not be empty');
863
1153
  if (sender && sender.id === target.id) throw new Error('a bot cannot message itself');
864
- if (sender && !admitPair(sender.id, target.id)) throw new Error(`@${sender.handle} and @${target.handle} exchanged ${PAIR_LIMIT} messages in the last 10 minutes; stop and report to the user instead of continuing.`);
1154
+ if (sender && !admitPair(sender.id, target.id)) throw pairRefusal(sender, target);
865
1155
  // A teammate's message may answer this bot's own question: only a long quiet starts a new topic here.
866
1156
  await autoTopic(store.get(target.id) ?? target, sender ? 'dm' : 'user');
867
1157
  const agent = await agentOf(store.get(target.id) ?? target);
868
- const message = createUserMessage({
1158
+ await sendTo(agent, {
869
1159
  content: [
870
1160
  { type: 'text', text: dmHeader(sender) },
871
1161
  { type: 'text', text: dmBody(body, sender) },
872
1162
  ],
873
1163
  source: senderSessionId ? { kind: 'agent-message', form: 'relay', senderSessionId } : { kind: 'user' },
1164
+ mode: homeMode(target),
874
1165
  });
875
- agent.followup(message);
876
- await flush(agent);
877
1166
  store.log({ from: sender ? sender.id : 'user', to: target.id, text: body, kind: 'dm' });
878
1167
  return agent.session.id;
879
1168
  }
880
1169
 
1170
+ // --- the panel chat: topics (Bots 0.9) -------------------------------------------------
1171
+ /** A new id for a message typed in the panel: `p` and 8 letters or digits, short enough for a model to copy. */
1172
+ const newPanelId = () => {
1173
+ for (;;) {
1174
+ const id = `p${randomUUID().replace(/-/g, '').slice(0, 8)}`;
1175
+ if (!store.message(id)) return id;
1176
+ }
1177
+ };
1178
+ /** Whether a timeline message belongs to `botId`'s panel chat (lib/store.mjs `messages`). */
1179
+ const inChat = (m, botId) => Boolean(m) && (m.chat ? m.chat === botId : m.from === botId || m.to === botId);
1180
+ /**
1181
+ * The key of the panel topic `root` from its first message: its `thread` when that is the topic's
1182
+ * key, else `panelThread` (a chat app's message, whose `thread` stays its chat Thread), else ''.
1183
+ */
1184
+ const topicKeyOf = (first, root) => {
1185
+ if (first?.thread && panelTopicOf(first.thread) === root) return first.thread;
1186
+ if (first?.panelThread && panelTopicOf(first.panelThread) === root) return first.panelThread;
1187
+ return '';
1188
+ };
1189
+ /** Who wrote a timeline message, as a header names them. */
1190
+ const writerOf = (m) => (m.from === 'user' ? 'the user' : store.get(m.from) ? `@${store.get(m.from).handle}` : 'a bot');
1191
+ /** The tasks a dispatcher's panel message may continue: open, or ended within a day; the latest change first. */
1192
+ function openTasksOf(bot) {
1193
+ const since = nowMs() - 24 * 3600_000;
1194
+ return tickets
1195
+ .list({ archived: false })
1196
+ .filter((t) => t.requester?.botId === bot.id && !t.requester?.ticketId && (!t.ended || t.ended.at >= since))
1197
+ .sort((a, b) => b.updatedAt - a.updatedAt);
1198
+ }
1199
+ /**
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}`.
1203
+ */
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 });
1216
+ }
1217
+ return { root, key, quoted };
1218
+ }
1219
+ /** A timeline message as the panel reads it: `pending` while no model has taken it yet; internal fields left out. */
1220
+ function messageView(m) {
1221
+ const { sid, ...rest } = m;
1222
+ if (m.from !== 'user' || m.kind !== 'user' || !/^p[a-z0-9]{8}$/.test(m.id)) return rest;
1223
+ const waiting = (sessionId, msgId) => pendingOf(agents()?.get?.(sessionId)).some((x) => x?.id === `${MESSAGE_PREFIX}${msgId}`);
1224
+ let pending = false;
1225
+ if (m.ticket && !sid) {
1226
+ const t = tickets.get(m.ticket);
1227
+ const key = `panel:${m.id}:${m.ticket}`;
1228
+ // Queued (its assignment carries the message), waiting for a worker slot, or not taken yet.
1229
+ pending = Boolean(t) && !t.ended && (!t.startedAt || parkedOf(t).some((x) => x.key === key) || (Boolean(t.sessionId) && waiting(t.sessionId, key)));
1230
+ } else if (sid) pending = waiting(sid, `panel:${m.id}`);
1231
+ return pending ? { ...rest, pending: true } : rest;
1232
+ }
1233
+
1234
+ /**
1235
+ * The user writes to a bot from the panel. `/new` (or `/clear`, `/新话题`) first starts a new
1236
+ * 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?}`.
1242
+ */
1243
+ async function userSend(target, text, { replyTo = '' } = {}) {
1244
+ let body = String(text ?? '').trim();
1245
+ if (body === '') throw new Error('text must not be empty');
1246
+ const cmd = TOPIC_COMMAND.exec(body);
1247
+ if (cmd) {
1248
+ const sessionId = await newTopic(target, 'manual');
1249
+ body = body.slice(cmd[0].length).trim();
1250
+ if (!body) return { sessionId };
1251
+ } else await autoTopic(store.get(target.id) ?? target, 'user');
1252
+ const bot = store.get(target.id) ?? target;
1253
+ const agent = await agentOf(bot);
1254
+ const sid = agent.session.id;
1255
+ 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);
1260
+ if (live.length) {
1261
+ try {
1262
+ const sessions = await toTopicTasks(bot, live, body, { key, root, id, quoted });
1263
+ return { sessionId: sessions[0] ?? sid, message: messageView(store.message(id)) };
1264
+ } 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`);
1267
+ }
1268
+ }
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()) : '';
1272
+ try {
1273
+ 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
+ } catch (error) {
1275
+ // Not handed over: it leaves the chat (the panel keeps its own copy to send again).
1276
+ store.patchMessage(id, { hidden: true });
1277
+ throw error;
1278
+ }
1279
+ return { sessionId: sid, message: messageView(store.message(id)) };
1280
+ }
1281
+
1282
+ /**
1283
+ * A reply in a panel topic whose tasks are live: into each task's Session as the person's
1284
+ * message (a done one opens again; it may take the extra slot), and the chat's bot hears of it
1285
+ * without waking. Returns the task Sessions; throws when no task took it.
1286
+ */
1287
+ async function toTopicTasks(bot, list, body, { key, root, id, quoted }) {
1288
+ const reached = [];
1289
+ let lastError = null;
1290
+ const header = quoted && quoted.id !== root ? panelHeaderText({ replyTo: { who: writerOf(quoted), text: quoted.text } }) : '';
1291
+ for (const t of list) {
1292
+ const cur = tickets.get(t.id) ?? t;
1293
+ try {
1294
+ reached.push(await appendToTicket(cur, body, { human: true, logged: true, header, key: `panel:${id}:${cur.id}` }));
1295
+ } catch (error) {
1296
+ lastError = error;
1297
+ ctx.logger?.warn?.(`bots: a panel reply did not reach task ${cur.id}: ${error?.message ?? error}`);
1298
+ }
1299
+ }
1300
+ if (!reached.length) throw lastError ?? new Error('no task took the reply');
1301
+ store.patchMessage(id, { ticket: reached[0].id });
1302
+ if (bot.sessionId) {
1303
+ 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
+ }
1309
+ } catch (error) {
1310
+ ctx.logger?.warn?.(`bots: the follow-up notice for @${bot.handle}: ${error?.message ?? error}`);
1311
+ }
1312
+ }
1313
+ return reached.map((t) => t.sessionId).filter(Boolean);
1314
+ }
1315
+
1316
+ /**
1317
+ * A thread a tool call names, as a key: a key as is; a panel topic by the id its header shows
1318
+ * (`p…`), or by any message in it (one filed under another topic names that one). '' for none.
1319
+ */
1320
+ function threadRef(ref, sessionId) {
1321
+ const r = String(ref ?? '').trim().replace(/^(?:thread|topic)\//, '');
1322
+ if (!r || parseThreadKey(r)) return r;
1323
+ const hit = channels.current(sessionId).find((o) => o.kind === 'panel' && o.rootId === r);
1324
+ if (hit) return hit.threadKey;
1325
+ const m = store.message(r);
1326
+ if (!m) return r;
1327
+ const root = m.movedTo || m.topic || '';
1328
+ const first = root ? store.message(root) : undefined;
1329
+ return topicKeyOf(first, root) || r;
1330
+ }
1331
+ /** The panel topics of a turn, and its chat Threads, as a tool error lists them. */
1332
+ const turnChoices = (sessionId) =>
1333
+ channels
1334
+ .current(sessionId)
1335
+ .filter((o) => o.kind !== 'panel' || o.rootId)
1336
+ .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
+ // --- tickets: delegated work in Sessions of their own ---------------------------------
1360
+ /** What cards and relays read about the team and the tickets. */
1361
+ const cardCtx = () => ({ bots: store.list(), threads: tickets, tickets, stageOf });
1362
+ const handleOf = (botId) => (store.get(botId) ? `@${store.get(botId).handle}` : 'a removed bot');
1363
+
1364
+ /** A ticket as the panel lists it (PLAN-0.8 §6.3 `TicketRow`). */
1365
+ function ticketRow(t) {
1366
+ const last = t.reports.at(-1);
1367
+ return {
1368
+ id: t.id,
1369
+ title: t.title,
1370
+ botId: t.botId,
1371
+ stage: stageOf(t),
1372
+ requester: t.requester?.kind === 'session' && t.requester.botId ? { kind: 'bot', botId: t.requester.botId } : { kind: 'user' },
1373
+ ...(t.origin?.via ? { via: t.origin.via } : {}),
1374
+ // Its conversation waits for the person's answer to a question (state `asks`): it needs you.
1375
+ ...(askingIn(t.sessionId) ? { asking: true } : {}),
1376
+ // What its conversation does right now (lib/activity.mjs), while it runs.
1377
+ ...(!t.ended && activity.get(t.sessionId) ? { activity: activity.get(t.sessionId) } : {}),
1378
+ createdAt: t.createdAt,
1379
+ updatedAt: t.updatedAt,
1380
+ ...(last ? { lastReport: { status: last.status, preview: clip(String(last.text ?? '').trim(), PREVIEW_CHARS).text } } : {}),
1381
+ };
1382
+ }
1383
+ const threadView = (key) => {
1384
+ const th = tickets.thread(key);
1385
+ const parsed = parseThreadKey(key);
1386
+ return { key, kind: th?.kind ?? parsed?.kind ?? '', label: th?.label ?? threadLabel(key) };
1387
+ };
1388
+ /** One ticket in full for the panel (`TicketView`): the row, the text, reports, Threads, runs with their cost. */
1389
+ function ticketView(t) {
1390
+ const overrides = settings.get().prices;
1391
+ const catalog = prices.peek();
1392
+ const running = [...openTasks.values()].map(({ log, size, replied, ...x }) => x);
1393
+ const use = ticketUsage({ calls: ledger.calls(), tasks: ledger.tasks(), running }, t.id, (m) => priceOf(m, overrides, catalog));
1394
+ return {
1395
+ ...ticketRow(t),
1396
+ text: t.text,
1397
+ ...(t.parentId ? { parentId: t.parentId } : {}),
1398
+ children: tickets.children(t.id).map((c) => c.id),
1399
+ requesterSessionId: t.requester?.sessionId ?? null,
1400
+ origin: t.origin ?? {},
1401
+ ...(t.startedAt ? { startedAt: t.startedAt } : {}),
1402
+ ...(t.ended ? { ended: t.ended } : {}),
1403
+ ...(t.error ? { error: t.error } : {}),
1404
+ ...(t.archivedAt ? { archivedAt: t.archivedAt } : {}),
1405
+ ...(t.nudgedAt ? { nudgedAt: t.nudgedAt } : {}),
1406
+ ...(t.stalledAt ? { stalledAt: t.stalledAt } : {}),
1407
+ ...(t.retries ? { retries: t.retries } : {}),
1408
+ reports: t.reports.map((r) => ({ at: r.at, status: r.status, text: r.text })),
1409
+ threads: t.threads.map(threadView),
1410
+ runs: use.runs,
1411
+ usage: { tokens: use.tokens, calls: use.calls, cost: use.cost },
1412
+ sessionId: t.sessionId,
1413
+ running: Boolean(t.sessionId && agents()?.get?.(t.sessionId)?.status === 'running'),
1414
+ };
1415
+ }
1416
+
1417
+ /** A Thread as a ticket subscribes to it: its key and label (`Slack · Acme #general · thread`). */
1418
+ const threadRecordOf = (o) => ({ key: o.threadKey, label: threadLabel(o) });
1419
+ /** A ticket's `origin` from one of the turn's Threads; `replyTo`: the chat message that started it, which its answer quotes. */
1420
+ const originFrom = (o) =>
1421
+ o.kind === 'panel'
1422
+ ? { origin: { threadKey: o.threadKey, who: 'the user' }, thread: threadRecordOf(o) }
1423
+ : { origin: { threadKey: o.threadKey, via: o.kind, ...(o.who ? { who: o.who } : {}), ...(o.replyTo ? { replyTo: String(o.replyTo) } : {}) }, thread: threadRecordOf(o) };
1424
+ /** The choices a delegating call may name with `thread`, for an error. */
1425
+ const threadChoices = (list) => list.map((o) => `${o.threadKey} (${threadLabel(o)})`).join(', ');
1426
+
1427
+ /**
1428
+ * Where the turn that is delegating now came from (PLAN-0.8 §4.3, §10 `origin`): its one chat
1429
+ * Thread (which the ticket then subscribes to); the Thread the call names with `thread` when the
1430
+ * turn has several; the panel conversation when only the panel spoke; no Thread at all for a
1431
+ * scheduled run without a chat, or several Threads and none named. A sub-ticket tells who it is
1432
+ * for but takes no Thread: follow-ups on it reach the parent.
1433
+ * @param {string} sessionId
1434
+ * @param {string} [chosen] - a Thread key of this turn the delegating call named
1435
+ */
1436
+ function originOfTurn(sessionId, chosen) {
1437
+ const parent = ticketOf(sessionId);
1438
+ if (parent) {
1439
+ if (chosen) throw new Error('a sub-task takes no thread: follow-ups reach the task that asked for it; leave out `thread`');
1440
+ return { origin: { ...(parent.origin?.via ? { via: parent.origin.via } : {}), ...(parent.origin?.who ? { who: parent.origin.who } : {}) } };
1441
+ }
1442
+ const plan = channels.replyPlan(sessionId);
1443
+ if (chosen) {
1444
+ const key = toThreadKey(String(chosen).trim().replace(/^thread\//, ''));
1445
+ const hit = key ? plan.origins.find((o) => o.threadKey === key) : undefined;
1446
+ if (!hit) throw new Error(`\`thread\` must be one of this turn's threads: ${threadChoices(plan.origins) || 'none (this turn has no thread); leave it out'}`);
1447
+ return originFrom(hit);
1448
+ }
1449
+ if (plan.mode === 'thread') return originFrom(plan.target);
1450
+ if (plan.mode === 'choose') {
1451
+ // Several topics or chats a person is waiting in (Bots 0.9): the task must say which one is its own.
1452
+ const topics = plan.origins.filter((o) => isTopicThread(o.threadKey));
1453
+ 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('; ')}`);
1454
+ // Several Threads and none named: the task belongs to none of them (its report reaches the requester only).
1455
+ const people = [...new Set(plan.origins.map((o) => o.who).filter(Boolean))];
1456
+ return { origin: { ...(people.length === 1 ? { who: people[0] } : { who: 'the user' }) } };
1457
+ }
1458
+ if (trigger.get(sessionId) === 'schedule') return { origin: { who: 'the user', via: 'schedule' } };
1459
+ return originFrom({ threadKey: panelThreadKey(sessionId), kind: 'panel' });
1460
+ }
1461
+
1462
+ /**
1463
+ * The Session a ticket works in: resolved when it exists, else made in the Bots workspace and
1464
+ * decorated as its bot. `info.created` says it had to be made.
1465
+ */
1466
+ async function ticketAgent(t, info = {}) {
1467
+ const controller = service(ctx, 'sessionController');
1468
+ if (!controller) throw new Error('tasks need the Web profile (no session controller here)');
1469
+ const bot = store.get(t.botId);
1470
+ if (!bot) throw new Error('the bot of this task was removed');
1471
+ const wanted = t.sessionId ?? sessionIdOf(t.id);
1472
+ const archived = service(ctx, 'workspaceRegistry')?.archivedSessionIds ?? [];
1473
+ // Also when nothing is stored yet: a crash may have come between making the Session and recording it.
1474
+ if (!archived.includes(wanted)) {
1475
+ const found = await controller.resolveAgent(wanted).catch((error) => ({ error }));
1476
+ if (found && !('error' in found) && found.agent) {
1477
+ reconcile(found.agent);
1478
+ return found.agent;
1479
+ }
1480
+ }
1481
+ const wsId = await workspaceId().catch(() => undefined);
1482
+ // The Agent's creation already finds the ticket by the `ticket-<id>` name and installs the bot.
1483
+ const created = await controller.create({ sessionId: wanted, ...(wsId ? { workspaceId: wsId } : { cwd: workdir }) });
1484
+ info.created = true;
1485
+ const id = created?.sessionId ?? wanted;
1486
+ if (id !== wanted) {
1487
+ otherTicketSessions.add(id);
1488
+ tickets.patch(t.id, { sessionId: id });
1489
+ }
1490
+ let agent = agents()?.get?.(id);
1491
+ if (!agent) {
1492
+ const found = await controller.resolveAgent(id).catch((error) => ({ error }));
1493
+ if (!found || 'error' in found) throw found?.error ?? new Error('the task conversation did not start');
1494
+ agent = found.agent;
1495
+ }
1496
+ reconcile(agent);
1497
+ const title = t.title;
1498
+ try {
1499
+ const titles = service(ctx, 'sessionTitle');
1500
+ if (typeof titles?.rename === 'function') titles.rename(agent.session, title);
1501
+ else await controller.rename?.({ sessionId: id, title });
1502
+ } catch {
1503
+ // A title is cosmetic.
1504
+ }
1505
+ if (bot.model) {
1506
+ try {
1507
+ agent.model?.select?.(selectionOf(bot.model));
1508
+ } catch {
1509
+ // The default model stays.
1510
+ }
1511
+ }
1512
+ return agent;
1513
+ }
1514
+
1515
+ /** How a ticket's requester appears as a message source in the worker's Session. */
1516
+ const sourceFrom = (requester) => (requester?.kind === 'session' && requester.sessionId ? { kind: 'agent-message', form: 'relay', senderSessionId: requester.sessionId } : { kind: 'user' });
1517
+
1518
+ /** Failures of tickets the caller is opening right now: its tool result says so, no notice is sent. */
1519
+ const quietFailures = new Set();
1520
+
1521
+ /**
1522
+ * Start a queued ticket that holds a slot: its Session, then the assignment as the first message.
1523
+ * One ended while its Session was being made (a person stopped it) does not start, and frees the slot.
1524
+ */
1525
+ async function launch(t) {
1526
+ try {
1527
+ const agent = await ticketAgent(t);
1528
+ const now = tickets.get(t.id);
1529
+ if (!now || now.ended || now.startedAt) {
1530
+ // Its Session stays known to it, so upkeep archives it with the ticket.
1531
+ if (now && !now.startedAt && !now.sessionId) tickets.patch(now.id, { sessionId: agent.session.id });
1532
+ if (!now?.startedAt) slots.release(t.id);
1533
+ return false;
1534
+ }
1535
+ const started = tickets.start(t.id, { sessionId: agent.session.id });
1536
+ await sendTo(agent, { content: [{ type: 'text', text: assignmentText(started, cardCtx()) }], source: sourceFrom(started.requester), mode: 'steer', key: `assign:${t.id}` });
1537
+ return true;
1538
+ } catch (error) {
1539
+ const reason = String(error?.message ?? error);
1540
+ ctx.logger?.warn?.(`bots: task ${t.id} for ${handleOf(t.botId)} did not start: ${reason}`);
1541
+ slots.release(t.id);
1542
+ // Stopped while it was starting: it stays as the person left it.
1543
+ if (tickets.get(t.id)?.ended) return false;
1544
+ const failed = tickets.end(t.id, { by: 'system', outcome: 'failed', error: `did not start: ${reason}` });
1545
+ if (failed && !quietFailures.has(t.id)) void notifyRequester(failed, `[Failed] Task ${t.id} (${handleOf(t.botId)}: ${t.title}) could not start: ${reason}`, { key: `failed:${t.id}:${failed.ended.at}` });
1546
+ return false;
1547
+ }
1548
+ }
1549
+
1550
+ /**
1551
+ * Hand a message to a started ticket's Session once it holds a worker slot: at once when it has one
1552
+ * or one is free (`human`: a person's message may take the extra slot), else parked on the ticket
1553
+ * (`parked`, kept in tickets.json, so it outlasts a restart) for the pump to deliver in order when a
1554
+ * slot frees. Messages already parked go first. Returns `{parked}`.
1555
+ */
1556
+ async function toTicket(t, { content, source, key, human = false }) {
1557
+ const waiting = parkedOf(tickets.get(t.id) ?? t);
1558
+ if (waiting.some((m) => m.key === key)) return { parked: true };
1559
+ if (waiting.length === 0 && slots.acquire(t.id, { human })) {
1560
+ const agent = await ticketAgent(t);
1561
+ await sendTo(agent, { content, source, mode: 'steer', key });
1562
+ return { parked: false };
1563
+ }
1564
+ tickets.patch(t.id, { parked: [...waiting, { key, content, source, at: nowMs(), ...(human ? { human: true } : {}) }] });
1565
+ void pump();
1566
+ return { parked: true };
1567
+ }
1568
+
1569
+ /** Deliver the messages parked on a ticket that now holds a slot, oldest first; stops if it ends meanwhile. */
1570
+ async function deliverParked(t) {
1571
+ try {
1572
+ const agent = await ticketAgent(t);
1573
+ for (;;) {
1574
+ const cur = tickets.get(t.id);
1575
+ const [next, ...rest] = parkedOf(cur);
1576
+ if (!cur || cur.ended || !next) break;
1577
+ await sendTo(agent, { content: next.content, source: next.source, mode: 'steer', key: next.key });
1578
+ tickets.patch(cur.id, { parked: rest.length ? rest : undefined });
1579
+ }
1580
+ } catch (error) {
1581
+ ctx.logger?.warn?.(`bots: messages for task ${t.id} wait for the next try: ${error?.message ?? error}`);
1582
+ slots.release(t.id);
1583
+ }
1584
+ }
1585
+
1586
+ let pumping = null;
1587
+ let pumpAgain = false;
1588
+ /**
1589
+ * While slots are free, oldest first: launch queued tickets, and hand started ones the messages parked
1590
+ * for them. A full pass still lets a person's parked message take the extra slot.
1591
+ */
1592
+ function pump() {
1593
+ if (pumping) {
1594
+ pumpAgain = true;
1595
+ return pumping;
1596
+ }
1597
+ pumping = (async () => {
1598
+ do {
1599
+ pumpAgain = false;
1600
+ // No Session controller (yet, or in this profile): queued tickets wait for the next pump.
1601
+ if (!service(ctx, 'sessionController')) break;
1602
+ let full = false;
1603
+ for (const listed of tickets.open()) {
1604
+ // Read again: an earlier launch awaited, and a person may have stopped this one meanwhile.
1605
+ const t = tickets.get(listed.id);
1606
+ if (!t || t.ended) continue;
1607
+ const waiting = parkedOf(t);
1608
+ if (t.startedAt && waiting.length === 0) continue;
1609
+ if (!t.startedAt && !store.get(t.botId)) {
1610
+ tickets.end(t.id, { by: 'system', outcome: 'stopped', error: 'the bot was removed' });
1611
+ continue;
1612
+ }
1613
+ const human = waiting.some((m) => m.human);
1614
+ if (full && !human) continue;
1615
+ if (!slots.acquire(t.id, { human })) {
1616
+ if (!human) full = true;
1617
+ continue;
1618
+ }
1619
+ if (t.startedAt) await deliverParked(t);
1620
+ else await launch(t);
1621
+ }
1622
+ } while (pumpAgain);
1623
+ })().finally(() => {
1624
+ pumping = null;
1625
+ });
1626
+ return pumping;
1627
+ }
1628
+
1629
+ /** The Agent of whoever asked for a ticket: a parent ticket's Session, or a bot's current home. */
1630
+ async function requesterAgent(t) {
1631
+ const r = t.requester ?? {};
1632
+ if (r.kind !== 'session' || !r.sessionId) return null;
1633
+ const controller = service(ctx, 'sessionController');
1634
+ // An archived conversation (a removed bot's, an old topic's) is nobody's to wake.
1635
+ const archived = service(ctx, 'workspaceRegistry')?.archivedSessionIds ?? [];
1636
+ const resolveId = async (id) => {
1637
+ const found = id && !archived.includes(id) ? await controller?.resolveAgent?.(id).catch((error) => ({ error })) : null;
1638
+ return found && !('error' in found) ? found.agent : null;
1639
+ };
1640
+ if (r.ticketId) {
1641
+ const parent = tickets.get(r.ticketId);
1642
+ if (!parent || parent.archivedAt) return null;
1643
+ return resolveId(parent.sessionId ?? r.sessionId);
1644
+ }
1645
+ const bot = r.botId ? store.get(r.botId) : undefined;
1646
+ // The asking bot may have started a new topic since: its report goes to the conversation it has now.
1647
+ if (bot && bot.sessionId !== r.sessionId) return agentOf(bot);
1648
+ return (await resolveId(r.sessionId)) ?? (bot ? agentOf(bot) : null);
1649
+ }
1650
+
1651
+ /** A notice for the requester's Session (steered; `inject` for one that need not wake it). */
1652
+ async function notifyRequester(t, text, { key, mode = 'steer' } = {}) {
1653
+ try {
1654
+ const agent = await requesterAgent(t);
1655
+ if (!agent) return false;
1656
+ await sendTo(agent, { content: [{ type: 'text', text }], source: { kind: 'agent-message', form: 'relay', ...(t.sessionId ? { senderSessionId: t.sessionId } : {}) }, mode, key });
1657
+ return true;
1658
+ } catch (error) {
1659
+ ctx.logger?.warn?.(`bots: a notice about task ${t.id} did not reach its requester: ${error?.message ?? error}`);
1660
+ return false;
1661
+ }
1662
+ }
1663
+
1664
+ /**
1665
+ * A ticket ended (done, stopped, failed; by anyone): its slot frees for the next queued one, and
1666
+ * its bot's memory summary runs now, or after the run still being recorded in its Session.
1667
+ */
1668
+ function ticketEnded(t) {
1669
+ slots.release(t.id);
1670
+ // Messages still waiting for a slot were for work that is over now.
1671
+ if (parkedOf(t).length) tickets.patch(t.id, { parked: undefined });
1672
+ void pump();
1673
+ if (!(t.sessionId && openTasks.has(t.sessionId))) reflectTicket(t);
1674
+ }
1675
+
1676
+ /**
1677
+ * Where a ticket's own lines go in the panel (Bots 0.9): a ticket that came from a panel topic
1678
+ * logs its delegation, the messages added to it and its notices into that topic, in the chat of
1679
+ * the bot that asked. Others log as in 0.8 (`{}`).
1680
+ */
1681
+ const topicFieldsOf = (t) => {
1682
+ const key = t?.origin?.threadKey;
1683
+ const topic = key ? panelTopicOf(key) : '';
1684
+ return topic ? { chat: t.requester?.botId ?? t.botId, thread: key, topic } : {};
1685
+ };
1686
+
1687
+ /** Who may add to a ticket from `sessionId`: its requester (or the requesting bot from its current home), or the router. */
1688
+ function mayAppend(t, sender, sessionId) {
1689
+ const r = t.requester ?? {};
1690
+ if (r.sessionId === sessionId) return true;
1691
+ if (sender && r.botId === sender.id && !r.ticketId && sender.sessionId === sessionId) return true;
1692
+ return Boolean(sender) && isRouterHome(sender, sessionId);
1693
+ }
1694
+
1695
+ /**
1696
+ * Add a message to a ticket: from its requester (a bot), or from a person (`human`: the panel, or a
1697
+ * follow-up on one of its chat Threads, which brings its `header` line and `chat` details for the
1698
+ * timeline, and a delivery `key`). An ended ticket is opened again unless it is archived, or a
1699
+ * person stopped it and this is not a person asking (`force`). A ticket still queued keeps the
1700
+ * text for its assignment. A started one gets it once it holds a worker slot (a person's message may
1701
+ * take the extra one); until then it waits on the ticket. A message whose `key` was delivered (or
1702
+ * parked) already changes nothing: a replay after a restart neither reopens nor wakes the ticket.
1703
+ */
1704
+ async function appendToTicket(t, text, { sender = null, senderSessionId = '', human = false, force = false, header = '', chat = null, key = '', logged = false } = {}) {
1705
+ const body = String(text ?? '').trim();
1706
+ if (body === '') throw new Error('text must not be empty');
1707
+ if (t.archivedAt) throw new Error(`task ${t.id} is archived; open a new task instead`);
1708
+ if (key && t.sessionId) {
1709
+ await loadHistory(t.sessionId);
1710
+ const live = agents()?.get?.(t.sessionId) ?? { session: { id: t.sessionId } };
1711
+ if (holds(live, `${MESSAGE_PREFIX}${key}`) || parkedOf(tickets.get(t.id) ?? t).some((m) => m.key === key)) return tickets.get(t.id) ?? t;
1712
+ }
1713
+ if (sender && t.botId !== sender.id) {
1714
+ const target = store.get(t.botId);
1715
+ if (target && !admitPair(sender.id, target.id)) throw pairRefusal(sender, target);
1716
+ }
1717
+ let cur = t;
1718
+ if (cur.ended) {
1719
+ const back = tickets.resume(cur.id, { force });
1720
+ if (back === null) throw new Error(`task ${t.id} was stopped by the user; it stays stopped (open a new task if the work is still wanted)`);
1721
+ cur = back ?? cur;
1722
+ }
1723
+ cur = tickets.touch(cur.id, human ? { human: true } : { requester: true }) ?? cur;
1724
+ const who = sender ? `@${sender.handle} (${sender.name})` : 'the user';
1725
+ if (!cur.startedAt) {
1726
+ cur = tickets.patch(cur.id, { text: `${cur.text}\n\n--- Added by ${who} ---\n${body}` }) ?? cur;
1727
+ void pump();
1728
+ return cur;
1729
+ }
1730
+ const content = sender
1731
+ ? [
1732
+ { type: 'text', text: `Bot message from ${who} about task ${cur.id}:` },
1733
+ { type: 'text', text: `${body}\n\n(Answer in a report: bot_send_message with a status, without "to".)` },
1734
+ ]
1735
+ : header
1736
+ ? [
1737
+ { type: 'text', text: header },
1738
+ { type: 'text', text: body },
1739
+ ]
1740
+ : [{ type: 'text', text: body }];
1741
+ // A person's follow-up may take the extra slot (new work cannot crowd it out); a bot's may not.
1742
+ await toTicket(cur, { content, source: sender && senderSessionId ? { kind: 'agent-message', form: 'relay', senderSessionId } : { kind: 'user' }, key: key || `msg:${cur.id}:${randomUUID()}`, human: human && !sender });
1743
+ // A panel message is in the timeline already (logged when it was sent).
1744
+ if (logged) return tickets.get(cur.id) ?? cur;
1745
+ store.log(
1746
+ chat
1747
+ ? { 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 }
1748
+ : { from: sender ? sender.id : 'user', to: cur.botId, text: body, kind: 'dm', ticket: cur.id, ...topicFieldsOf(cur) },
1749
+ );
1750
+ return tickets.get(cur.id) ?? cur;
1751
+ }
1752
+
1753
+ /**
1754
+ * Open a ticket for `target`, asked from `senderSessionId` (a bot's home or a ticket Session),
1755
+ * and start it when a slot is free. Returns the ticket; a start that failed shows as stage `failed`.
1756
+ */
1757
+ async function openTicket(sender, target, text, senderSessionId, { title, thread: chosen, relay = false } = {}) {
1758
+ const body = String(text ?? '').trim();
1759
+ 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');
1762
+ if (!service(ctx, 'sessionController')) throw new Error('tasks need the Web profile (no session controller here)');
1763
+ const parent = ticketOf(senderSessionId);
1764
+ const { origin, thread } = originOfTurn(senderSessionId, chosen);
1765
+ if (!admitPair(sender.id, target.id)) throw pairRefusal(sender, target);
1766
+ const t = tickets.create({
1767
+ title,
1768
+ text: body,
1769
+ botId: target.id,
1770
+ requester: { kind: 'session', sessionId: senderSessionId, botId: sender.id, ...(parent ? { ticketId: parent.id } : {}) },
1771
+ origin,
1772
+ threads: thread ? [thread] : [],
1773
+ relay,
1774
+ });
1775
+ store.log({ from: sender.id, to: target.id, text: body, kind: 'dm', ticket: t.id, ...topicFieldsOf(t) });
1776
+ quietFailures.add(t.id);
1777
+ try {
1778
+ await pump();
1779
+ } finally {
1780
+ quietFailures.delete(t.id);
1781
+ }
1782
+ return tickets.get(t.id) ?? t;
1783
+ }
1784
+
1785
+ /** A worker reports on its ticket. `progress` is only recorded; the rest reach the requester. */
1786
+ async function reportTicket(t, status, text) {
1787
+ if (!REPORT_STATUSES.includes(status)) throw new Error('a report to whoever asked needs a status: progress, done, blocked or question');
1788
+ const body = String(text ?? '').trim();
1789
+ if (body === '') throw new Error('text must not be empty');
1790
+ if (t.archivedAt) throw new Error(`task ${t.id} is archived; nobody reads reports on it`);
1791
+ const wasOpen = !t.ended;
1792
+ const next = tickets.addReport(t.id, { status, text: body });
1793
+ const index = next.reports.length - 1;
1794
+ const report = next.reports[index];
1795
+ let relayed = false;
1796
+ // An ended task's late words, or a sub-task's report to a task that has ended since, wake no one:
1797
+ // they are kept on the task (its reports) and the panel shows them.
1798
+ const parent = next.requester?.ticketId ? tickets.get(next.requester.ticketId) : undefined;
1799
+ const unread = !wasOpen ? 'ended' : next.requester?.ticketId && (!parent || parent.ended) ? 'parent' : '';
1800
+ // Bots 0.9: the person reads it as it is, where the task came from; whoever asked is told without waking.
1801
+ const shown = status !== 'progress' && !unread && reportsGoDirect(next) ? showReport(next, report) : null;
1802
+ if (shown) {
1803
+ relayed = true;
1804
+ if (next.requester?.kind === 'session') {
1805
+ await notifyRequester(next, shownNoticeText(next, report, { ...cardCtx(), where: shown.where }), { mode: 'inject', key: `shown:${next.id}:${index}:${report.at}` });
1806
+ }
1807
+ } else if (status !== 'progress' && !unread) {
1808
+ store.log({ from: next.botId, to: next.requester?.botId ?? 'user', text: body, kind: 'dm', ticket: next.id, status, ...topicFieldsOf(next) });
1809
+ // A ticket the user asked for has no Session to tell: the panel shows it (attention).
1810
+ if (next.requester?.kind === 'session') {
1811
+ // The requester's turn takes this ticket's origin Thread as an input when the relay arrives in it
1812
+ // (its `user/message`, see RELAY_KINDS below), not here: a turn ending in between would lose it.
1813
+ relayed = await notifyRequester(next, reportRelayText(next, report, cardCtx()), { key: `report:${next.id}:${index}:${report.at}` });
1814
+ }
1815
+ }
1816
+ if (status === 'done' && wasOpen) ticketEnded(next);
1817
+ return { ticket: next, relayed, ...(shown ? { shown } : {}), ...(unread ? { unread, ...(parent ? { parent: parent.id } : {}) } : {}) };
1818
+ }
1819
+
1820
+ /**
1821
+ * Post a worker's report where its task came from (Bots 0.9): a panel topic (or the panel as a
1822
+ * whole, for a task from before topics) shows it in the chat of the bot that asked; a chat Thread
1823
+ * gets it through that chat's app, signed with the worker's name when the worker is not the one
1824
+ * the chat belongs to. Returns `{where}` (how the place reads), or null when it cannot be reached
1825
+ * (the report then goes to whoever asked, as in 0.8).
1826
+ */
1827
+ function showReport(t, report) {
1828
+ const key = t.origin?.threadKey;
1829
+ if (!key) return null;
1830
+ const worker = store.get(t.botId);
1831
+ const owner = t.requester?.botId ? store.get(t.requester.botId) : undefined;
1832
+ const chat = owner?.id ?? t.botId;
1833
+ const body = String(report.text ?? '').trim();
1834
+ if (isPanelThread(key)) {
1835
+ const topic = panelTopicOf(key);
1836
+ store.log({ from: t.botId, to: 'user', chat, text: body, kind: 'reply', thread: key, ...(topic ? { topic } : {}), ticket: t.id, status: report.status });
1837
+ return { where: threadLabel({ threadKey: key, ...(topic ? { threadTitle: store.message(topic)?.text } : {}) }) };
1838
+ }
1839
+ const signed = worker && owner && worker.id !== owner.id ? `【${worker.name}】\n${body}` : body;
1840
+ let sent = null;
1841
+ try {
1842
+ sent = channels.post({ thread: key }, signed, { replyTo: t.origin?.replyTo ?? '', typingOf: t.sessionId ?? '' });
1843
+ } catch (error) {
1844
+ ctx.logger?.warn?.(`bots: the report on task ${t.id} was not posted to its chat: ${error?.message ?? error}`);
1845
+ }
1846
+ if (!sent) return null;
1847
+ store.log({ from: t.botId, to: 'user', chat, text: body, kind: 'reply', via: sent.kind, thread: key, ticket: t.id, status: report.status });
1848
+ return { where: tickets.thread(key)?.label ?? threadLabel(sent) };
1849
+ }
1850
+
1851
+ /** A person (the panel) or the requester ends a ticket (stop, or close as done); either cancels its running turn. */
1852
+ function endTicket(t, { by, outcome, error }) {
1853
+ const wasOpen = !t.ended;
1854
+ const next = tickets.end(t.id, { by, outcome, ...(error ? { error } : {}) });
1855
+ if (next.sessionId) {
1856
+ try {
1857
+ agents()?.get?.(next.sessionId)?.cancel?.(by === 'user' ? { kind: 'user' } : { kind: 'hook', reason: `bots: task ${t.id} ${outcome === 'done' ? 'closed' : 'stopped'}` });
1858
+ } catch {
1859
+ // Nothing running.
1860
+ }
1861
+ }
1862
+ if (wasOpen) ticketEnded(next);
1863
+ else slots.release(next.id);
1864
+ // The requester learns of it next time it works; it need not wake for it.
1865
+ if (by === 'user' && next.requester?.kind === 'session') {
1866
+ void notifyRequester(next, `[${outcome === 'done' ? 'Closed' : 'Stopped'}] The user ${outcome === 'done' ? 'closed' : 'stopped'} task ${next.id} (${handleOf(next.botId)}: ${next.title}).`, { mode: 'inject', key: `ended:${next.id}:${next.ended.at}` });
1867
+ }
1868
+ return next;
1869
+ }
1870
+
1871
+ /**
1872
+ * A retry: open the ticket again and hand the assignment over afresh. From the panel (`by`
1873
+ * 'user', even one the user stopped), or from the requester (`sender`, a bot, with its Session);
1874
+ * a requester cannot retry a ticket the user stopped.
1875
+ */
1876
+ async function retryTicket(t, { sender = null, senderSessionId = '' } = {}) {
1877
+ const back = tickets.resume(t.id, { force: !sender });
1878
+ if (back === null && sender && !t.archivedAt) throw new Error(`task ${t.id} was stopped by the user; it stays stopped (open a new task if the work is still wanted)`);
1879
+ if (!back) throw new Error(`task ${t.id} is archived; open a new task instead`);
1880
+ tickets.touch(back.id, sender ? { requester: true } : { human: true });
1881
+ if (!back.startedAt) {
1882
+ await pump();
1883
+ return tickets.get(back.id) ?? back;
1884
+ }
1885
+ const who = sender ? `@${sender.handle}` : 'The user';
1886
+ const note = `[Retry] ${who} asked you to take task ${back.id} up again. Check what is already done before you repeat anything, then go on and report as usual.\n\n${assignmentText(back, cardCtx())}`;
1887
+ const source = sender && senderSessionId ? { kind: 'agent-message', form: 'relay', senderSessionId } : { kind: 'user' };
1888
+ // A person's retry may take the extra slot; the requester's waits for a free one like new work.
1889
+ await toTicket(back, { content: [{ type: 'text', text: note }], source, key: `retry:${back.id}:${back.updatedAt}`, human: !sender });
1890
+ return tickets.get(back.id) ?? back;
1891
+ }
1892
+
1893
+ /** A ticket Session went idle: a ticket that waits on others (question, blocked, stalled) gives its slot back. */
1894
+ function ticketIdle(t) {
1895
+ if (!t || t.ended) return;
1896
+ const stage = stageOf(t);
1897
+ if ((stage === 'question' || stage === 'failed' || stage === 'stalled') && slots.release(t.id)) void pump();
1898
+ }
1899
+
1900
+ // --- the task watchdog (PLAN-0.8 §4.5): deterministic rules from lib/watchdog.mjs ---------------
1901
+ const agentStatusOf = (sessionId) => (sessionId && agents()?.get?.(sessionId)?.status === 'running' ? 'running' : 'idle');
1902
+
1903
+ /**
1904
+ * What keeps a ticket Session busy in the background: its shell jobs still running (Harness
1905
+ * `jobs.list`) and its subagents still running (`subagents.listChildren`, or `listDescendants` as
1906
+ * Harness 0.2.2 has it). Nothing is waited for; a service that is missing counts nothing.
1907
+ */
1908
+ async function backgroundOf(sessionId) {
1909
+ let n = 0;
1910
+ const jobs = service(ctx, 'jobs');
1911
+ try {
1912
+ if (typeof jobs?.list === 'function') n += (jobs.list(sessionId) ?? []).filter((j) => j?.owner === sessionId && (j.status === 'running' || j.status === 'stopping')).length;
1913
+ } catch {
1914
+ // No job registry view for this Session.
1915
+ }
1916
+ const subagents = service(ctx, 'subagents');
1917
+ try {
1918
+ const list = typeof subagents?.listChildren === 'function' ? subagents.listChildren.bind(subagents) : typeof subagents?.listDescendants === 'function' ? subagents.listDescendants.bind(subagents) : null;
1919
+ if (list) n += ((await list(sessionId, AbortSignal.timeout(5000))) ?? []).filter((c) => c && c.kind !== 'diagnostic' && c.activity === 'running').length;
1920
+ } catch {
1921
+ // A catalog that cannot be read counts nothing.
1922
+ }
1923
+ return n;
1924
+ }
1925
+
1926
+ /** The time a bot's home last spoke to a person (a reply in the timeline), for reminders. */
1927
+ function lastReplyAt(botId) {
1928
+ const rows = store.messages({ bot: botId, limit: 2000 });
1929
+ // Plain text that reached no chat (`notSent`: the turn had several) told nobody.
1930
+ for (let i = rows.length - 1; i >= 0; i -= 1) if (rows[i].from === botId && rows[i].kind === 'reply' && !rows[i].notSent) return Number(rows[i].at) || 0;
1931
+ return 0;
1932
+ }
1933
+
1934
+ /** One watchdog pass (the 5-minute sweep): status checks, stalls, and reminders for requesters with nothing left to wait for. */
1935
+ async function watch(now = nowMs()) {
1936
+ const stallMinutes = settings.get().tickets.stallMinutes;
1937
+ const open = tickets.open();
1938
+ const items = [];
1939
+ for (const t of open) {
1940
+ // A ticket whose messages wait for a slot is `queued`: it is not judged until it has one. One
1941
+ // waiting for the person's answer to its question is not quiet either.
1942
+ const stage = stageOf(t);
1943
+ if (stage !== 'working' || askingIn(t.sessionId)) continue;
1944
+ const status = agentStatusOf(t.sessionId);
1945
+ // A sub-task still working (or waiting for a slot) is this ticket's background work too: it waits for its report.
1946
+ const children = tickets.children(t.id).filter((c) => ['working', 'queued'].includes(stageOf(c))).length;
1947
+ items.push({ ticket: t, stage, agentStatus: status, backgroundJobs: status === 'idle' ? children + (t.sessionId ? await backgroundOf(t.sessionId) : 0) : 0 });
1948
+ }
1949
+ for (const action of checkTickets(items, { stallMinutes }, now)) {
1950
+ const t = tickets.get(action.ticketId);
1951
+ if (!t || t.ended) continue;
1952
+ try {
1953
+ if (action.kind === 'nudge') {
1954
+ tickets.patch(t.id, { nudgedAt: now });
1955
+ await toTicket(t, { content: [{ type: 'text', text: nudgeText(t) }], source: sourceFrom(t.requester), key: `nudge:${t.id}:${now}` });
1956
+ } else {
1957
+ const stalled = tickets.patch(t.id, { stalledAt: now });
1958
+ 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) });
1959
+ if (slots.release(t.id)) void pump();
1960
+ // A ticket the user asked for has no Session to tell: the panel shows it (attention).
1961
+ if (stalled.requester?.kind === 'session') await notifyRequester(stalled, stalledNoticeText(stalled, cardCtx()), { key: `stalled:${t.id}:${now}` });
1962
+ }
1963
+ } catch (error) {
1964
+ ctx.logger?.warn?.(`bots: watchdog on task ${t.id}: ${error?.message ?? error}`);
1965
+ }
1966
+ }
1967
+ // Requesters whose every task settled and who have said nothing since: one reminder per batch.
1968
+ const all = tickets.list({ archived: false });
1969
+ const facts = (sessionId) => {
1970
+ const asTicket = ticketOf(sessionId);
1971
+ // A task that has ended asks nothing more of anyone: it is not reminded.
1972
+ if (asTicket?.ended) return { status: 'idle', ended: true };
1973
+ const bot = botOfSession(sessionId);
1974
+ const mine = all.filter((x) => x.requester?.sessionId === sessionId);
1975
+ const remindedAt = Math.max(0, ...mine.map((x) => Number(x.remindedAt) || 0));
1976
+ const reportedAt = asTicket ? Number(asTicket.reports.at(-1)?.at) || 0 : bot ? lastReplyAt(bot.id) : 0;
1977
+ return { status: agents()?.get?.(sessionId) ? agentStatusOf(sessionId) : 'offline', reportedAt, remindedAt };
1978
+ };
1979
+ // A task that answers the person itself (Bots 0.9) leaves its requester nothing to pass on.
1980
+ const relayed = all.filter((t) => !reportsGoDirect(t));
1981
+ for (const r of requesterReminders(relayed.map((t) => ({ ticket: t, stage: stageOf(t) })), facts, now)) {
1982
+ const list = r.ticketIds.map((id) => tickets.get(id)).filter(Boolean);
1983
+ if (!list.length) continue;
1984
+ try {
1985
+ const key = `remind:${r.sessionId}:${now}`;
1986
+ reminded.set(`${MESSAGE_PREFIX}${key}`, list.map((t) => t.id));
1987
+ if (reminded.size > 200) reminded.delete(reminded.keys().next().value);
1988
+ if (await notifyRequester(list[0], reminderText(list, cardCtx()), { key })) {
1989
+ for (const t of list) tickets.patch(t.id, { remindedAt: now });
1990
+ }
1991
+ } catch (error) {
1992
+ ctx.logger?.warn?.(`bots: reminder for ${r.sessionId}: ${error?.message ?? error}`);
1993
+ }
1994
+ }
1995
+ }
1996
+
1997
+ /** ticketId → the pending "continue" after a temporary error. Cleared on dispose. */
1998
+ const retryTimers = new Map();
1999
+ ctx.effect(() => () => {
2000
+ for (const timer of retryTimers.values()) clearTimer(timer);
2001
+ retryTimers.clear();
2002
+ }, 'bots: task retry timers');
2003
+
2004
+ /**
2005
+ * A ticket Session's turn failed (`agent/error`). A temporary error (HTTP 408, 429, 5xx, a dropped
2006
+ * connection) gets a "continue" after 15, 30 and 60 s; then, or for any other error, the ticket
2007
+ * fails and its requester hears of it.
2008
+ */
2009
+ function ticketError(t, error) {
2010
+ if (!t || t.ended || retryTimers.has(t.id)) return;
2011
+ if (error?.name === 'AbortError') return; // stopped on purpose (Harness reports no cancellation here anyway)
2012
+ // A model failure is an `LlmError` whose `failure` holds the facts (`status`, `message`, `code`).
2013
+ const facts = error?.failure && typeof error.failure === 'object' ? error.failure : error;
2014
+ const reason = String(facts?.message ?? error?.message ?? error?.error?.message ?? (typeof error === 'string' ? error : '') ?? '').trim() || 'the model call failed';
2015
+ const delay = isTransient(facts) || isTransient(error) ? retryDelay(t.retries) : undefined;
2016
+ if (delay !== undefined) {
2017
+ const attempt = (t.retries ?? 0) + 1;
2018
+ const timer = setTimer(() => {
2019
+ retryTimers.delete(t.id);
2020
+ const cur = tickets.get(t.id);
2021
+ if (!cur || cur.ended || agentStatusOf(cur.sessionId) === 'running') return;
2022
+ tickets.patch(cur.id, { retries: attempt, error: reason });
2023
+ void toTicket(cur, { content: [{ type: 'text', text: retryText(cur, { attempt, error: reason }) }], source: sourceFrom(cur.requester), key: `continue:${cur.id}:${attempt}:${nowMs()}` }).catch((e) =>
2024
+ ctx.logger?.warn?.(`bots: retrying task ${cur.id}: ${e?.message ?? e}`),
2025
+ );
2026
+ }, delay);
2027
+ timer?.unref?.();
2028
+ retryTimers.set(t.id, timer);
2029
+ return;
2030
+ }
2031
+ const failed = tickets.end(t.id, { by: 'system', outcome: 'failed', error: reason });
2032
+ if (!failed) return;
2033
+ 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) });
2034
+ ticketEnded(failed);
2035
+ if (failed.requester?.kind === 'session') void notifyRequester(failed, failedNoticeText(failed, cardCtx()), { key: `failed:${failed.id}:${failed.ended.at}` });
2036
+ }
2037
+ ctx.on('agent/error', (payload) => {
2038
+ try {
2039
+ ticketError(ticketOf(payload?.agent?.session?.id), payload?.error);
2040
+ } catch (error) {
2041
+ ctx.logger?.warn?.(`bots: a task error: ${error?.message ?? error}`);
2042
+ }
2043
+ });
2044
+ // A ticket's background jobs starting or ending are events of that ticket (the watchdog's clock).
2045
+ ctx.inject?.(['jobs'], (scope) => {
2046
+ const jobs = scope?.jobs ?? service(scope, 'jobs');
2047
+ if (typeof jobs?.events?.subscribe !== 'function') return;
2048
+ const off = jobs.events.subscribe({ owners: 'all' }, (event) => {
2049
+ const owner = event?.job?.owner ?? event?.owner;
2050
+ const t = owner ? ticketOf(owner) : undefined;
2051
+ if (t && (event.type === 'registered' || event.type === 'settled')) tickets.touch(t.id);
2052
+ });
2053
+ if (typeof off !== 'function') return;
2054
+ if (typeof scope.effect === 'function') scope.effect(() => off, 'bots: task background jobs');
2055
+ else ctx.effect(() => off, 'bots: task background jobs');
2056
+ });
2057
+
2058
+ /**
2059
+ * After a restart (PLAN-0.8 §4.5): a working ticket whose Session was in the middle of a turn
2060
+ * (its stored log ends inside a turn, or with the turn Harness closed as `interrupted` when it
2061
+ * resumed it), or holds input it never took, gets one recovery note: look before repeating
2062
+ * anything, then go on. A Session that had to be made anew gets its assignment again, and so does
2063
+ * one whose stored log holds no message at all (the assignment never landed). Idle tickets that
2064
+ * had reported stay as they are. The note's id names the interrupted turn, so a second restart
2065
+ * before it is read sends nothing new, while a recovery turn cut off again gets its own note.
2066
+ */
2067
+ async function recoverTickets() {
2068
+ if (!service(ctx, 'sessionController')) return;
2069
+ for (const t of tickets.open()) {
2070
+ if (!t.startedAt || !t.sessionId || stageOf(t) !== 'working') continue;
2071
+ try {
2072
+ const events = await readHistory(t.sessionId);
2073
+ const info = {};
2074
+ const agent = await ticketAgent(t, info);
2075
+ const cur = tickets.get(t.id) ?? t;
2076
+ const pending = pendingOf(agent).length > 0;
2077
+ // The first event of the latest turn that did not end cleanly: one the log ends inside, or one
2078
+ // Harness closed as `interrupted` with no turn after it (none: the log ends after a clean turn).
2079
+ // A recovery turn cut off by a second restart is a turn of its own, so it gets a note of its own.
2080
+ let interrupted = null;
2081
+ let inTurn = false;
2082
+ let lastEnd = 0;
2083
+ (events ?? []).forEach((e, i) => {
2084
+ const seq = e?.seq ?? i;
2085
+ if (e?.type === 'turn/end') {
2086
+ lastEnd = seq;
2087
+ inTurn = false;
2088
+ if (e.data?.reason?.kind !== 'interrupted') interrupted = null;
2089
+ } else if (!inTurn && ['turn/start', 'user/message', 'assistant/message', 'tool/call', 'tool/result'].includes(e?.type)) {
2090
+ inTurn = true;
2091
+ interrupted = seq;
2092
+ }
2093
+ });
2094
+ // A stored log, read whole (shorter than the tail read), without a single message: the Session was
2095
+ // made and the start recorded, but the assignment never landed (Harness went down in between). Its
2096
+ // own id keeps one still in the inbox from doubling.
2097
+ const neverTook = Array.isArray(events) && events.length < HISTORY_TAIL && !events.some((e) => e?.type === 'user/message');
2098
+ if (info.created) {
2099
+ await sendTo(agent, { content: [{ type: 'text', text: `${recoveryNoteText(cur)}\n\n${assignmentText(cur, cardCtx())}` }], source: sourceFrom(cur.requester), mode: 'steer', key: `recover:${cur.id}:new` });
2100
+ } else if (neverTook) {
2101
+ await sendTo(agent, { content: [{ type: 'text', text: assignmentText(cur, cardCtx()) }], source: sourceFrom(cur.requester), mode: 'steer', key: `assign:${cur.id}` });
2102
+ } else if (interrupted !== null || pending) {
2103
+ const mark = interrupted !== null ? `t${interrupted}` : `p${lastEnd}`;
2104
+ await sendTo(agent, { content: [{ type: 'text', text: recoveryNoteText(cur) }], source: sourceFrom(cur.requester), mode: 'steer', key: `recover:${cur.id}:${mark}` });
2105
+ }
2106
+ } catch (error) {
2107
+ ctx.logger?.warn?.(`bots: recovering task ${t.id}: ${error?.message ?? error}`);
2108
+ }
2109
+ }
2110
+ }
2111
+
2112
+ /** Archive the Sessions of tickets ended `archiveHours` ago, run the watchdog; keep the file small. */
2113
+ async function ticketUpkeep(now = nowMs()) {
2114
+ const hours = settings.get().tickets.archiveHours;
2115
+ for (const t of tickets.list({ open: false, archived: false })) {
2116
+ if (now - (t.ended?.at ?? 0) < hours * 3_600_000) continue;
2117
+ if (t.sessionId && (openTasks.has(t.sessionId) || agents()?.get?.(t.sessionId)?.status === 'running')) continue;
2118
+ if (t.sessionId) {
2119
+ uninstall(t.sessionId);
2120
+ forgetSession(t.sessionId);
2121
+ try {
2122
+ await service(ctx, 'workspaceRegistry')?.archiveSession?.(t.sessionId);
2123
+ } catch (error) {
2124
+ ctx.logger?.warn?.(`bots: archiving the conversation of task ${t.id}: ${error?.message ?? error}`);
2125
+ }
2126
+ }
2127
+ tickets.archive(t.id);
2128
+ slots.release(t.id);
2129
+ }
2130
+ await watch(now);
2131
+ tickets.flush();
2132
+ tickets.prune();
2133
+ await pump();
2134
+ }
2135
+
2136
+ // After a restart: tickets that were working keep their slots and, once Harness is up, get their
2137
+ // recovery notes; queued ones start then.
2138
+ for (const t of tickets.open()) if (t.startedAt && stageOf(t) === 'working') slots.acquire(t.id);
2139
+ /** The startup pass, once: recovery notes, then the queue. Resolves when done (tests wait on it). */
2140
+ let startupDone = null;
2141
+ const startup = () => (startupDone ??= recoverTickets()
2142
+ .catch((error) => ctx.logger?.warn?.(`bots: task recovery: ${error?.message ?? error}`))
2143
+ .then(() => pump())
2144
+ .catch(() => {}));
2145
+ ctx.effect(() => {
2146
+ const timer = setTimer(() => void startup(), deps.startupPumpMs ?? STARTUP_PUMP_MS);
2147
+ timer?.unref?.();
2148
+ return () => clearTimer(timer);
2149
+ }, 'bots: recover working tasks, start queued ones');
2150
+
2151
+ // --- chat channels: Telegram, Discord, Feishu / Lark, Slack -------------------------------
881
2152
  /**
882
- * The user writes to a bot from the panel: an ordinary user prompt in its conversation.
883
- * `/new` (or `/clear`, `/新话题`) first starts a new topic; text after it goes there.
2153
+ * A person's follow-up on a Thread with live tickets (lib/threads.mjs `routeInbound`): it goes
2154
+ * into each ticket Session as their message (a done ticket opens again; a follow-up may take the
2155
+ * extra slot), and the Router (the channel owner's home) is told without being woken. That notice
2156
+ * is no input of its turn: its replies do not go to that Thread because of it.
884
2157
  */
885
- async function userSend(target, text) {
886
- let body = String(text ?? '').trim();
887
- if (body === '') throw new Error('text must not be empty');
888
- const cmd = TOPIC_COMMAND.exec(body);
889
- if (cmd) {
890
- const sessionId = await newTopic(target, 'manual');
891
- body = body.slice(cmd[0].length).trim();
892
- if (!body) return sessionId;
893
- } else await autoTopic(store.get(target.id) ?? target, 'user');
894
- const agent = await agentOf(store.get(target.id) ?? target);
895
- agent.followup(createUserMessage({ content: [{ type: 'text', text: body }], source: { kind: 'user' } }));
896
- await flush(agent);
897
- return agent.session.id;
2158
+ async function followUp(list, { header, body }, { threadKey: key, origin, owner, key: messageKey }) {
2159
+ const router = owner ? store.get(owner.id) : null;
2160
+ // A message handed out again after a restart that the Router already took (it opened these very
2161
+ // tickets) is no follow-up: it is not run twice.
2162
+ if (messageKey && router?.sessionId) {
2163
+ await loadHistory(router.sessionId);
2164
+ if (deliveredIds.get(router.sessionId)?.has(`${MESSAGE_PREFIX}${messageKey}`)) return [];
2165
+ }
2166
+ const sessions = [];
2167
+ const reached = [];
2168
+ let lastError = null;
2169
+ for (const t of list) {
2170
+ const cur = tickets.get(t.id) ?? t;
2171
+ try {
2172
+ const next = await appendToTicket(cur, body, { human: true, header: `${header}${threadNote(key)}`, chat: { kind: origin?.kind, who: origin?.who, threadKey: key }, ...(messageKey ? { key: `${messageKey}:${cur.id}` } : {}) });
2173
+ reached.push(next);
2174
+ if (next.sessionId) sessions.push(next.sessionId);
2175
+ } catch (error) {
2176
+ lastError = error;
2177
+ ctx.logger?.warn?.(`bots: a follow-up did not reach task ${cur.id}: ${error?.message ?? error}`);
2178
+ }
2179
+ }
2180
+ if (!reached.length) throw lastError ?? new Error('no task took the follow-up');
2181
+ if (router?.sessionId) {
2182
+ try {
2183
+ const found = await service(ctx, 'sessionController')?.resolveAgent?.(router.sessionId);
2184
+ if (found?.agent) {
2185
+ // The Thread's label names the chat app already ("Telegram · Kada"), so no `via` beside it.
2186
+ const text = followUpNoticeText({ tickets: reached, thread: key, who: origin?.who, ...(tickets.thread(key)?.label ? {} : { via: CHANNEL_LABELS[origin?.kind] ?? origin?.kind }), text: body }, cardCtx());
2187
+ await sendTo(found.agent, { content: [{ type: 'text', text }], source: { kind: 'agent-message', form: 'relay' }, mode: 'inject', key: `followup:${messageKey ?? randomUUID()}` });
2188
+ }
2189
+ } catch (error) {
2190
+ ctx.logger?.warn?.(`bots: the follow-up notice for @${router.handle}: ${error?.message ?? error}`);
2191
+ }
2192
+ }
2193
+ return sessions;
898
2194
  }
899
2195
 
900
- // --- chat channels: Telegram, Discord, Feishu / Lark, Slack -------------------------------
901
2196
  const channels = createChannels({
902
2197
  file: join(dir, 'channels.json'),
903
2198
  bots: () => store.list(),
904
2199
  entries: () => templates(),
905
- // A chat message is a user prompt like one typed in the panel, after a line naming where it came from.
906
- deliver: async (target, { header, body }) => {
2200
+ // A chat message is a user prompt like one typed in the panel, after a line naming where it came from
2201
+ // and its Thread (so the bot can name it in bot_reply). Its id comes from the chat message's, so a
2202
+ // message handed out again after a restart is not run twice.
2203
+ deliver: async (target, { header, body }, meta = {}) => {
907
2204
  await autoTopic(store.get(target.id) ?? target, 'user');
908
2205
  const agent = await agentOf(store.get(target.id) ?? target);
909
- agent.followup(createUserMessage({ content: [{ type: 'text', text: header }, { type: 'text', text: body }], source: { kind: 'user' } }));
910
- await flush(agent);
911
- return agent.session.id;
2206
+ const sent = await sendTo(agent, {
2207
+ content: [
2208
+ { type: 'text', text: `${header}${threadNote(meta.threadKey)}` },
2209
+ { type: 'text', text: body },
2210
+ ],
2211
+ source: { kind: 'user' },
2212
+ mode: homeMode(target),
2213
+ ...(meta.key ? { key: meta.key } : {}),
2214
+ });
2215
+ return { sessionId: agent.session.id, messageId: sent.message.id, ...(sent.skipped ? { skipped: true } : {}) };
912
2216
  },
2217
+ toTickets: (list, msg, meta) => followUp(list, msg, meta),
2218
+ subscribers: (key) => tickets.subscribers(key),
2219
+ knownThread: (key) => tickets.thread(key),
2220
+ ticketThread: (id) => tickets.get(String(id ?? ''))?.origin?.threadKey,
913
2221
  running: (sessionId) => agents()?.get?.(sessionId)?.status === 'running',
914
2222
  newTopic: (bot) => newTopic(bot, 'manual'),
915
2223
  ...(deps.loadConnector ? { loadConnector: deps.loadConnector } : {}),
@@ -929,43 +2237,168 @@ export function apply(ctx, config, deps = {}) {
929
2237
  const trigger = new Map();
930
2238
  /** Sessions whose current turn already sent a bot_send_message. */
931
2239
  const answered = new Set();
2240
+ /**
2241
+ * Per home Session, its turn so far (dropped at the turn's end): `other`, an input that was no report
2242
+ * or note about a task (a person's message, a schedule run, a teammate's DM); `reports`, the tasks
2243
+ * whose reports or notes came in; and since the latest input, `answers`, those of them it messaged
2244
+ * with bot_send_message (`ticket`), and `acted`, any other bot_send_message (a new task, say).
2245
+ */
2246
+ const turnState = new Map();
2247
+ /**
2248
+ * Closing words that reach no one: the turn's only inputs were reports, and all the bot did about
2249
+ * them was answer those tasks. Anything more (a person in the turn, a new task) and its text is a
2250
+ * message to the person.
2251
+ */
2252
+ const closingOnly = (sessionId) => {
2253
+ const st = turnState.get(sessionId);
2254
+ return Boolean(st) && !st.other && st.reports.size > 0 && st.answers.size > 0 && !st.acted;
2255
+ };
2256
+ /** A tool call's arguments as an object (`argsRaw` or Harness's `arguments`, a JSON string). */
2257
+ const callArgs = (b) => {
2258
+ const raw = b?.argsRaw ?? b?.arguments ?? b?.args ?? b?.input;
2259
+ if (raw && typeof raw === 'object') return raw;
2260
+ try {
2261
+ const v = JSON.parse(String(raw ?? ''));
2262
+ return v && typeof v === 'object' ? v : {};
2263
+ } catch {
2264
+ return {};
2265
+ }
2266
+ };
2267
+ /** Drop what is kept per Session for one that is gone: an archived task's, a topic left behind, a removed bot's. */
2268
+ function forgetSession(sessionId) {
2269
+ if (!sessionId) return;
2270
+ memoText.delete(sessionId);
2271
+ memoStale.delete(sessionId);
2272
+ deliveredIds.delete(sessionId);
2273
+ historyRead.delete(sessionId);
2274
+ trigger.delete(sessionId);
2275
+ answered.delete(sessionId);
2276
+ turnState.delete(sessionId);
2277
+ activity.clear(sessionId);
2278
+ }
932
2279
  /** Kinds of user message that start (or join) a task. */
933
2280
  const TASK_KINDS = new Set(['user', 'schedule', 'agent-message']);
2281
+ /** The tickets a relay is about, from its message id (`bots:report:<id>:…`) or its sender (a ticket Session). */
2282
+ function relayTickets(message) {
2283
+ const id = String(message?.id ?? '');
2284
+ const m = /^bots:([a-z-]+):(t[a-z0-9]{8}):/.exec(id);
2285
+ if (m && RELAY_KINDS.has(m[1])) return [tickets.get(m[2])].filter(Boolean);
2286
+ if (/^bots:remind:/.test(id)) return [...(reminded.get(id) ?? [])].map((x) => tickets.get(x)).filter(Boolean);
2287
+ if (/^bots:/.test(id)) return [];
2288
+ const sender = ticketOf(message?.source?.senderSessionId);
2289
+ return sender ? [sender] : [];
2290
+ }
2291
+ /** Reminder message id → the tickets it names (their origin Threads join the requester's turn). */
2292
+ const reminded = new Map();
934
2293
  ctx.on('session/event', (session, event) => {
935
2294
  let bot;
936
2295
  let via = null;
937
2296
  let kind;
2297
+ let ticket;
2298
+ // A panel message's own text, without the header it reached the model with.
2299
+ let typedText;
938
2300
  try {
939
- bot = store.bySession(session?.id);
2301
+ bot = botOfSession(session?.id);
940
2302
  if (!bot || !event) return;
941
- if (event.type === 'user/message') {
2303
+ ticket = ticketOf(session.id);
2304
+ if (event.type === 'user/message') noteDelivered(session.id, event.data?.id);
2305
+ if (ticket) {
2306
+ // A ticket Session talks to no one directly: its reports go through bot_send_message, its
2307
+ // plain text stays in it (no timeline reply, nothing to a chat app).
2308
+ tickets.touch(ticket.id);
2309
+ if (event.type === 'user/message') {
2310
+ kind = event.data?.source?.kind;
2311
+ trigger.set(session.id, kind);
2312
+ } else if (event.type === 'turn/end') {
2313
+ channels.noteTurnEnd(session.id);
2314
+ // A turn that went through ends a run of temporary errors.
2315
+ if (event.data?.reason?.kind === 'completed' && ticket.retries > 0 && !ticket.ended) tickets.patch(ticket.id, { retries: 0 });
2316
+ }
2317
+ } else if (event.type === 'user/message') {
942
2318
  kind = event.data?.source?.kind;
2319
+ const id = String(event.data?.id ?? '');
943
2320
  // The Harness tells a session about task edits made elsewhere; that is not a delivery.
944
2321
  if (kind === 'schedule' && /^\[SCHEDULE CHANGE\]/.test(textOf(event.data.content))) kind = 'schedule-notice';
945
- trigger.set(session.id, kind);
946
- answered.delete(session.id);
947
- const said = textOf(event.data.content);
948
- // A chat message makes its chat where replies go; any other user message brings them back here.
949
- via = channels.noteUserMessage(session.id, bot, kind, said);
950
- if (kind === 'user') store.log(via ? { from: 'user', to: bot.id, text: via.body, kind: 'user', via: via.kind, who: via.who } : { from: 'user', to: bot.id, text: said, kind: 'user' });
951
- else if (kind === 'schedule') store.log({ from: 'schedule', to: bot.id, text: said, kind: 'system' });
2322
+ if (/^bots:(?:followup|shown):/.test(id)) {
2323
+ // A follow-up went to its tasks directly, or a report went to the person (injected notes that
2324
+ // woke nothing): no input of the turn.
2325
+ kind = 'followup-notice';
2326
+ } else {
2327
+ // A report (or notice) on a ticket this conversation asked for: answering it is speaking to the user.
2328
+ const about = kind === 'agent-message' ? relayTickets(event.data) : [];
2329
+ // A note that a drawing the bot asked for ended is news for the person too, like a report.
2330
+ const isReport = kind === 'agent-message' && (about.length > 0 || /^bots:(?:report|failed|ended|stalled|remind|avatar):/.test(id));
2331
+ trigger.set(session.id, isReport ? 'report' : kind);
2332
+ answered.delete(session.id);
2333
+ const st = turnState.get(session.id) ?? { other: false, reports: new Set() };
2334
+ if (isReport) for (const t of about) st.reports.add(t.id);
2335
+ else if (kind !== 'schedule-notice') st.other = true;
2336
+ st.answers = new Set();
2337
+ st.acted = false;
2338
+ turnState.set(session.id, st);
2339
+ let said = textOf(event.data.content);
2340
+ // A message typed in the panel (Bots 0.9) is logged already; its topic joins the turn's Threads.
2341
+ const panelId = kind === 'user' ? /^bots:panel:(p[a-z0-9]{8})$/.exec(id)?.[1] : undefined;
2342
+ const typed = panelId ? store.message(panelId) : undefined;
2343
+ if (typed) said = typedText = typed.text;
2344
+ const topicTitle = typed?.thread ? store.message(panelTopicOf(typed.thread))?.text : undefined;
2345
+ // A chat message adds its Thread to the turn's; a panel message its topic, or the panel (lib/threads.mjs).
2346
+ via = channels.noteUserMessage(session.id, bot, kind, said, { id, report: isReport, ...(typed?.thread ? { threadKey: typed.thread, origin: topicTitle ? { threadTitle: clip(topicTitle, 60).text } : {} } : {}) });
2347
+ // A drawing's note: the answer goes to the chats the person asked for it in.
2348
+ for (const o of drawingOrigins.get(id) ?? []) channels.noteInput(session.id, { threadKey: o.threadKey, origin: o });
2349
+ drawingOrigins.delete(id);
2350
+ // What arrives in a topic or chat since bot_reply answered it needs an answer again.
2351
+ if (st.replied) for (const k of [typed?.thread, via?.threadKey, ...about.map((t) => t.origin?.threadKey)]) if (k) st.replied.delete(k);
2352
+ // A report's ticket came from a Thread: the answer to the person goes there (PLAN-0.8 §4.3).
2353
+ for (const t of about) {
2354
+ const key = t.origin?.threadKey;
2355
+ if (!key) continue;
2356
+ const th = tickets.thread(key);
2357
+ // The answer quotes the message that started the task, not whatever was said there last.
2358
+ 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
+ }
2360
+ const thread = via ? via.threadKey : panelThreadKey(session.id);
2361
+ if (kind === 'user' && typed) {
2362
+ // 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' });
2365
+ }
952
2366
  } else if (event.type === 'assistant/message') {
953
2367
  const content = event.data?.message?.content ?? [];
954
2368
  const calls = content.filter((b) => b?.type === 'tool-call');
955
2369
  if (calls.some((b) => (b.name ?? b.toolName) === 'bot_send_message')) answered.add(session.id);
2370
+ const st = turnState.get(session.id);
2371
+ for (const b of calls) {
2372
+ if (!st || (b.name ?? b.toolName) !== 'bot_send_message') continue;
2373
+ const id = String(callArgs(b).ticket ?? '').trim().replace(/^(?:ticket|task)\//, '');
2374
+ if (id && st.reports.has(id)) st.answers.add(id);
2375
+ else st.acted = true;
2376
+ }
956
2377
  const text = calls.length > 0 ? '' : textOf(content);
957
2378
  const why = trigger.get(session.id);
958
2379
  // Shown in the bot's chat: what it says to the user. Hidden: acknowledging a schedule notice,
959
- // and the closing words of a turn that answered a bot by DM (they reach no one). The
960
- // dispatcher reporting back after its teammates answered is a message to the user.
961
- const hidden = why === 'schedule-notice' || (why === 'agent-message' && (bot.role !== 'primary' || answered.has(session.id)));
2380
+ // the closing words of a turn that answered a bot by DM, and those of a turn whose only inputs
2381
+ // were reports and that only answered those tasks (they reach no one). The dispatcher reporting
2382
+ // back after its teammates answered is a message to the user, and so is any bot passing on a
2383
+ // report from a task it asked for, also in a turn where it hands out more work.
2384
+ const plan = channels.replyPlan(session.id);
2385
+ // Closing words after bot_reply answered every topic or chat of the turn (Bots 0.9): each has its answer already.
2386
+ const topicsOfTurn = plan.origins.filter((o) => isTopicThread(o.threadKey));
2387
+ const allAnswered = topicsOfTurn.length > 0 && topicsOfTurn.every((o) => st?.replied?.has(o.threadKey));
2388
+ const hidden = why === 'schedule-notice' || (why === 'agent-message' && (bot.role !== 'primary' || answered.has(session.id))) || (why === 'report' && closingOnly(session.id)) || allAnswered;
962
2389
  if (text && !hidden) {
963
- // Also to the chat the user wrote from, when that is where the conversation is.
2390
+ // To the turn's one chat Thread; with several (or the panel and a chat) it stays in the panel,
2391
+ // and bot_reply says where each answer goes.
964
2392
  const sent = channels.noteReply(session.id, text);
965
- store.log({ from: bot.id, to: 'user', text, kind: 'reply', ...(sent ? { via: sent.kind } : {}) });
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) : '';
2396
+ 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 } : {}) });
966
2398
  }
967
2399
  } else if (event.type === 'turn/end') {
968
2400
  channels.noteTurnEnd(session.id);
2401
+ turnState.delete(session.id);
969
2402
  }
970
2403
  } catch {
971
2404
  // The timeline must never disturb a conversation.
@@ -976,9 +2409,9 @@ export function apply(ctx, config, deps = {}) {
976
2409
  const sid = session.id;
977
2410
  if (event.type === 'user/message') {
978
2411
  if (!TASK_KINDS.has(kind)) return;
979
- const task = openTasks.get(sid) ?? startTask(bot, sid, kind, event, via);
980
- const said = textOf(event.data?.content);
981
- const who = kind === 'schedule' ? 'scheduled' : kind === 'agent-message' ? 'bot message' : via ? `user via ${via.kind}` : 'user';
2412
+ const task = openTasks.get(sid) ?? startTask(bot, sid, kind, event, via, typedText);
2413
+ const said = typedText ?? textOf(event.data?.content);
2414
+ const who = kind === 'schedule' ? 'scheduled' : kind === 'agent-message' ? (ticket ? 'task message' : 'bot message') : via ? `user via ${via.kind}` : 'user';
982
2415
  logLine(task, `[${who}] ${via ? via.body : said}`);
983
2416
  } else if (event.type === 'assistant/message') {
984
2417
  const msg = event.data?.message ?? {};
@@ -1014,17 +2447,178 @@ export function apply(ctx, config, deps = {}) {
1014
2447
  ctx.logger?.debug?.(`bots: usage: ${error?.message ?? error}`);
1015
2448
  }
1016
2449
  });
2450
+ // What a bot's home or task Session does right now, for the panel (lib/activity.mjs).
2451
+ ctx.on('session/event', (session, event) => {
2452
+ try {
2453
+ if (session?.id && botOfSession(session.id)) activity.note(session.id, event);
2454
+ } catch {
2455
+ // Live status is a nicety.
2456
+ }
2457
+ });
1017
2458
  // The surest sign a task is over: the bot's Agent went idle.
1018
2459
  ctx.on('agent/status', (payload) => {
1019
2460
  try {
1020
2461
  const sid = payload?.agent?.session?.id;
2462
+ if (sid && payload.status === 'idle') activity.clear(sid);
1021
2463
  if (sid && payload.status === 'idle' && openTasks.has(sid)) settleSoon(sid, 300);
1022
2464
  else if (sid && payload.status === 'idle' && memoStale.delete(sid)) memoText.delete(sid);
2465
+ if (sid && payload.status === 'idle') ticketIdle(ticketOf(sid));
1023
2466
  } catch {
1024
2467
  // Ignored.
1025
2468
  }
1026
2469
  });
1027
2470
 
2471
+ // --- questions a bot asks (Harness's ask_user_question), answered from the panel too --------------
2472
+ /** The code of a user-questions error (`UserQuestionError`, or one a Client sent back as plain data). */
2473
+ const codeOf = (error) => (error && typeof error === 'object' && typeof error.code === 'string' ? error.code : '');
2474
+ /** One question as the panel shows it; an approval or a plan review only by its text (the conversation answers it). */
2475
+ function askItem(q, native) {
2476
+ const options = Array.isArray(q?.options) ? q.options.filter((o) => typeof o?.label === 'string').map((o) => ({ label: o.label, ...(typeof o.description === 'string' && o.description ? { description: o.description } : {}) })) : null;
2477
+ return {
2478
+ id: String(q?.id ?? ''),
2479
+ question: String(q?.question ?? ''),
2480
+ ...(native
2481
+ ? {}
2482
+ : {
2483
+ ...(typeof q.header === 'string' && q.header ? { header: q.header } : {}),
2484
+ ...(typeof q.detail === 'string' && q.detail ? { detail: q.detail } : {}),
2485
+ ...(options ? { options } : {}),
2486
+ ...(q.multiSelect === true ? { multiSelect: true } : {}),
2487
+ }),
2488
+ };
2489
+ }
2490
+ /** A waiting question in state (`asks`). */
2491
+ const askView = (a) => ({ id: a.id, botId: a.botId, sessionId: a.sessionId, ...(a.ticketId ? { ticketId: a.ticketId } : {}), at: a.at, ...(a.native ? { native: true } : {}), ...(a.continued ? { continued: true } : {}), questions: a.questions });
2492
+ /** The chats the asking turn came from (a home's), or the chat its task came from, hear once that it waits for an answer in Harness. */
2493
+ function askNotice(ask, bot) {
2494
+ const targets = ask.ticketId ? [channels.resolveReply(ask.sessionId, { ticket: ask.ticketId })] : channels.current(ask.sessionId);
2495
+ for (const target of targets) {
2496
+ if (!target || target.kind === 'panel' || !target.chatId) continue;
2497
+ try {
2498
+ channels.replyTo(ask.sessionId, target, askNoticeText(bot, ask.questions));
2499
+ } catch (error) {
2500
+ ctx.logger?.info?.(`bots: question notice: ${error?.message ?? error}`);
2501
+ }
2502
+ }
2503
+ }
2504
+ /**
2505
+ * One `user-questions/request` (the Agent-scoped waterfall `ctx.userQuestions.ask` runs). A request
2506
+ * from a bot's home or a task Session is recorded and settles with whichever answers first: the
2507
+ * rest of the chain (`next()`: the Harness window's card) or the panel (`answerAsk`). When no window
2508
+ * can ask (`NO_PROVIDER`) it waits for the panel; the request's abort, or any other failure, ends
2509
+ * it. The chain gets a signal that also aborts once the panel answered, so the window's card closes.
2510
+ * A timed question whose wait ran out (`ASK_TIMED_OUT`) stays answerable (`continued`): the panel
2511
+ * answers it through `userQuestions.answer`. Approvals and plan reviews are only recorded; the
2512
+ * conversation answers them.
2513
+ */
2514
+ function askRequest(request, next) {
2515
+ const sessionId = request?.agent?.session?.id;
2516
+ const bot = botOfSession(sessionId);
2517
+ const questions = Array.isArray(request?.questions) ? request.questions : [];
2518
+ if (!bot || questions.length === 0) return next();
2519
+ const native = questions.some((q) => q?.intent?.kind === 'approval' || q?.intent?.kind === 'plan-review');
2520
+ const ticket = ticketOf(sessionId);
2521
+ const ask = { id: `ask-${randomUUID()}`, botId: bot.id, sessionId, ...(ticket ? { ticketId: ticket.id } : {}), at: nowMs(), ...(native ? { native: true } : {}), questions: questions.map((q) => askItem(q, native)) };
2522
+ asks.set(ask.id, ask);
2523
+ askNotice(ask, bot);
2524
+ const chain = () => {
2525
+ try {
2526
+ return Promise.resolve(next());
2527
+ } catch (error) {
2528
+ return Promise.reject(error);
2529
+ }
2530
+ };
2531
+ if (native) return chain().finally(() => asks.delete(ask.id));
2532
+ const original = request.signal instanceof AbortSignal ? request.signal : undefined;
2533
+ const panel = new AbortController();
2534
+ try {
2535
+ request.signal = original ? AbortSignal.any([original, panel.signal]) : panel.signal;
2536
+ } catch {
2537
+ // A frozen request keeps its own signal: the window's card then stays until the call ends.
2538
+ }
2539
+ const callId = request.wait?.timed === true && typeof request.wait.callId === 'string' ? request.wait.callId : '';
2540
+ return new Promise((resolve, reject) => {
2541
+ let done = false;
2542
+ const finish = (ok, value) => {
2543
+ if (done) return;
2544
+ done = true;
2545
+ original?.removeEventListener('abort', onAbort);
2546
+ delete ask.settle;
2547
+ if (!ok && callId && codeOf(value) === 'ASK_TIMED_OUT') Object.assign(ask, { continued: true, callId });
2548
+ else asks.delete(ask.id);
2549
+ panel.abort(new Error('the question was settled'));
2550
+ (ok ? resolve : reject)(value);
2551
+ };
2552
+ const onAbort = () => finish(false, original.reason);
2553
+ ask.settle = (answer) => finish(true, answer);
2554
+ if (original?.aborted) return onAbort();
2555
+ original?.addEventListener('abort', onAbort, { once: true });
2556
+ chain().then(
2557
+ (answer) => finish(true, answer),
2558
+ (error) => {
2559
+ if (codeOf(error) !== 'NO_PROVIDER') finish(false, error);
2560
+ },
2561
+ );
2562
+ });
2563
+ }
2564
+ // First in the chain: the Harness forwards the request to its window and holds it there until that
2565
+ // card is answered, so a listener after it would never hear of the question while a window is open.
2566
+ ctx.on('user-questions/request', (request, next) => askRequest(request, next), { prepend: true });
2567
+ // A continued question answered in the conversation: its reply reaches the Session.
2568
+ ctx.on('session/event', (session, event) => {
2569
+ const source = event?.type === 'user/message' ? event.data?.source : null;
2570
+ if (source?.kind !== 'user-question-reply') return;
2571
+ for (const a of asks.values()) if (a.continued && a.sessionId === session?.id && a.callId === source.callId) asks.delete(a.id);
2572
+ });
2573
+
2574
+ /** One item per question, ids matching; labels among its options; a single-select question takes one answer. A reason when not. */
2575
+ function checkAnswers(questions, answers) {
2576
+ if (!Array.isArray(answers) || answers.length !== questions.length) return `give one answer for each of the ${questions.length} question(s)`;
2577
+ const out = [];
2578
+ for (const q of questions) {
2579
+ const mine = answers.filter((a) => a && typeof a === 'object' && a.id === q.id);
2580
+ if (mine.length !== 1) return `answer question "${q.id}" exactly once`;
2581
+ const a = mine[0];
2582
+ if (!Array.isArray(a.selected) || a.selected.some((s) => typeof s !== 'string')) return `"selected" of question "${q.id}" must be a list of option labels`;
2583
+ const selected = [...new Set(a.selected)];
2584
+ const custom = typeof a.custom === 'string' ? a.custom.trim().slice(0, 4000) : '';
2585
+ const unknown = selected.find((s) => !(q.options ?? []).some((o) => o.label === s));
2586
+ if (unknown !== undefined) return `"${unknown}" is not an option of question "${q.id}"`;
2587
+ if (selected.length === 0 && !custom) return `question "${q.id}" has no answer`;
2588
+ if (!q.multiSelect && selected.length + (custom ? 1 : 0) > 1) return `question "${q.id}" takes one answer`;
2589
+ out.push({ id: q.id, selected, ...(custom ? { custom } : {}) });
2590
+ }
2591
+ return out;
2592
+ }
2593
+ /** POST /asks/:id/answer `{answers}`: the panel answers a waiting question; the timeline shows what was answered. */
2594
+ async function answerAsk(id, body) {
2595
+ const ask = asks.get(String(id ?? ''));
2596
+ if (!ask) return { ok: false, reason: 'no such question: it was answered already or is no longer waiting' };
2597
+ if (ask.native) return { ok: false, reason: 'this one is answered in the conversation' };
2598
+ const items = checkAnswers(ask.questions, body?.answers);
2599
+ if (typeof items === 'string') return { ok: false, reason: items };
2600
+ if (ask.continued) {
2601
+ const uq = service(ctx, 'userQuestions');
2602
+ const agent = agents()?.get?.(ask.sessionId);
2603
+ if (typeof uq?.answer !== 'function' || !agent) return { ok: false, reason: 'the conversation is not running; answer the question there' };
2604
+ try {
2605
+ const taken = await uq.answer(agent, ask.callId, { answers: items });
2606
+ asks.delete(ask.id);
2607
+ if (!taken) return { ok: false, reason: 'the question is no longer waiting for an answer' };
2608
+ } catch (error) {
2609
+ if (codeOf(error) === 'REPLY_QUEUED') asks.delete(ask.id);
2610
+ return { ok: false, reason: error?.message ?? String(error) };
2611
+ }
2612
+ } else if (ask.settle) ask.settle({ answers: items });
2613
+ else return { ok: false, reason: 'the question is no longer waiting for an answer' };
2614
+ const said = (q) => {
2615
+ const a = items.find((x) => x.id === q.id);
2616
+ return `${q.question}\n→ ${[...a.selected, ...(a.custom ? [a.custom] : [])].join(', ')}`;
2617
+ };
2618
+ store.log({ from: 'user', to: ask.botId, text: ask.questions.map(said).join('\n\n'), kind: 'user', ...(ask.ticketId ? { ticket: ask.ticketId } : { thread: panelThreadKey(ask.sessionId) }) });
2619
+ return { ok: true };
2620
+ }
2621
+
1028
2622
  // --- schedules ------------------------------------------------------------------------
1029
2623
  const schedule = () => {
1030
2624
  const s = service(ctx, 'schedule');
@@ -1073,6 +2667,7 @@ export function apply(ctx, config, deps = {}) {
1073
2667
 
1074
2668
  // --- bot lifecycle helpers -----------------------------------------------------------
1075
2669
  async function removeBot(bot) {
2670
+ dropDrawing(bot.id, 'deleted');
1076
2671
  try {
1077
2672
  for (const task of await schedulesOf(bot)) await schedule().edit({ id: task.id, action: 'delete' });
1078
2673
  } catch {
@@ -1080,12 +2675,32 @@ export function apply(ctx, config, deps = {}) {
1080
2675
  }
1081
2676
  if (bot.sessionId) {
1082
2677
  uninstall(bot.sessionId);
2678
+ forgetSession(bot.sessionId);
1083
2679
  try {
1084
2680
  service(ctx, 'workspaceRegistry')?.archiveSession?.(bot.sessionId);
1085
2681
  } catch {
1086
2682
  // The conversation stays where it is.
1087
2683
  }
1088
2684
  }
2685
+ // Its tickets end with it; their conversations are archived now.
2686
+ for (const t of tickets.list({ botId: bot.id, archived: false })) {
2687
+ if (!t.ended) endTicket(t, { by: 'system', outcome: 'stopped' });
2688
+ if (t.sessionId) {
2689
+ uninstall(t.sessionId);
2690
+ forgetSession(t.sessionId);
2691
+ try {
2692
+ await service(ctx, 'workspaceRegistry')?.archiveSession?.(t.sessionId);
2693
+ } catch {
2694
+ // Archived at the next upkeep, or left as it is.
2695
+ }
2696
+ }
2697
+ tickets.archive(t.id);
2698
+ }
2699
+ // The tasks it asked for (from its home or its tasks) end too: nobody is left to read their reports.
2700
+ // They stay in the panel, stopped, where the user can still retry one.
2701
+ for (const t of tickets.list({ open: true })) {
2702
+ if (t.requester?.botId === bot.id) endTicket(t, { by: 'system', outcome: 'stopped', error: `@${bot.handle}, who asked for it, was removed` });
2703
+ }
1089
2704
  store.remove(bot.id);
1090
2705
  memory.dropBot(bot.id);
1091
2706
  topics.drop(bot.id);
@@ -1098,10 +2713,12 @@ export function apply(ctx, config, deps = {}) {
1098
2713
  }
1099
2714
 
1100
2715
  function applyModel(bot) {
1101
- const agent = bot.sessionId ? agents()?.get?.(bot.sessionId) : undefined;
1102
- if (agent && bot.model) {
2716
+ if (!bot.model) return;
2717
+ const live = agents();
2718
+ const ids = [bot.sessionId, ...tickets.list({ botId: bot.id, open: true }).map((t) => t.sessionId)].filter(Boolean);
2719
+ for (const id of ids) {
1103
2720
  try {
1104
- agent.model?.select?.(selectionOf(bot.model));
2721
+ live?.get?.(id)?.model?.select?.(selectionOf(bot.model));
1105
2722
  } catch {
1106
2723
  // Kept on its current model.
1107
2724
  }
@@ -1128,11 +2745,15 @@ export function apply(ctx, config, deps = {}) {
1128
2745
  'It must read clearly at 32×32 pixels.',
1129
2746
  ].join(' ');
1130
2747
  }
1131
- async function generateAvatar(bot, extra) {
2748
+ /** Draw a picture for `bot` with the Images plugin's generate_image; its bytes and type. `signal` gives up on it. */
2749
+ async function drawAvatar(bot, extra, signal) {
1132
2750
  const tool = imageTool();
1133
2751
  if (!tool) throw new Error('the Images plugin (generate_image) is not installed or turned off');
1134
2752
  const controller = new AbortController();
1135
- const timer = setTimeout(() => controller.abort(), 300_000);
2753
+ const timer = setTimeout(() => controller.abort(new Error('the image service did not answer within 5 minutes')), 300_000);
2754
+ const stop = () => controller.abort(signal?.reason ?? new Error('stopped'));
2755
+ if (signal?.aborted) stop();
2756
+ else signal?.addEventListener?.('abort', stop, { once: true });
1136
2757
  let value;
1137
2758
  try {
1138
2759
  for (let attempt = 1; ; attempt += 1) {
@@ -1142,7 +2763,9 @@ export function apply(ctx, config, deps = {}) {
1142
2763
  } catch (error) {
1143
2764
  const message = String(error?.message ?? error);
1144
2765
  // Gateways drop long image requests now and then; those are worth another try.
1145
- if (attempt >= AVATAR_ATTEMPTS || controller.signal.aborted || !TRANSIENT.test(message)) {
2766
+ // Given up on (out of time, or replaced): why, rather than the tool's own abort message.
2767
+ if (controller.signal.aborted) throw new Error(controller.signal.reason instanceof Error ? controller.signal.reason.message : message);
2768
+ if (attempt >= AVATAR_ATTEMPTS || !TRANSIENT.test(message)) {
1146
2769
  throw new Error(TRANSIENT.test(message) ? `the image service failed ${attempt} times in a row (${message}); try again in a moment` : message);
1147
2770
  }
1148
2771
  ctx.logger?.warn?.(`bots: avatar for @${bot.handle}, attempt ${attempt} failed: ${message}; retrying`);
@@ -1151,20 +2774,305 @@ export function apply(ctx, config, deps = {}) {
1151
2774
  }
1152
2775
  } finally {
1153
2776
  clearTimeout(timer);
2777
+ signal?.removeEventListener?.('abort', stop);
1154
2778
  }
1155
2779
  const path = value?.images?.[0]?.path;
1156
2780
  const type = value?.images?.[0]?.mediaType;
1157
2781
  if (!path || !/^image\/(png|jpeg|webp|gif)$/.test(String(type))) throw new Error('the image model returned no picture');
1158
2782
  const bytes = readFileSync(path);
1159
2783
  if (bytes.length > 8 * 1024 * 1024) throw new Error('the generated picture is too large');
2784
+ return { bytes, type };
2785
+ }
2786
+
2787
+ /**
2788
+ * Drawings under way, by bot: only the latest asked for a bot counts. `sessionId`: the bot
2789
+ * conversation that asked (it gets a note when the drawing ends), none for a person's own
2790
+ * conversation or the panel (they wait for it). Kept in memory only: a restart drops them, and
2791
+ * nobody hears of one dropped that way.
2792
+ */
2793
+ const drawings = new Map();
2794
+ /** Message id of a drawing's note → the Threads of the turn that asked for it (the answer to the person goes there). */
2795
+ const drawingOrigins = new Map();
2796
+ /** One drawing whose outcome nobody waits for any more: an avatar change since replaced it. */
2797
+ function dropDrawing(botId, by) {
2798
+ const job = drawings.get(botId);
2799
+ if (!job) return;
2800
+ drawings.delete(botId);
2801
+ job.droppedBy = by ?? 'panel';
2802
+ job.controller.abort(new Error('replaced by a newer avatar change'));
2803
+ }
2804
+ /**
2805
+ * Draw `bot`'s avatar: the drawing replaces any still under way for it, and its picture is saved
2806
+ * when it is still the latest asked once it is ready. `job.done` resolves to the bot with its new
2807
+ * picture, or rejects with why not (`dropped`: replaced meanwhile, or the bot is gone).
2808
+ */
2809
+ function startDrawing(bot, extra, { sessionId = null, by = null } = {}) {
2810
+ dropDrawing(bot.id, sessionId ?? 'panel');
2811
+ const job = { id: `a${randomUUID().replace(/-/g, '').slice(0, 12)}`, botId: bot.id, handle: bot.handle, name: bot.name, sessionId, by, at: nowMs(), controller: new AbortController() };
2812
+ drawings.set(bot.id, job);
2813
+ const current = () => drawings.get(bot.id) === job;
2814
+ job.done = (async () => {
2815
+ try {
2816
+ const { bytes, type } = await drawAvatar(store.get(bot.id) ?? bot, extra, job.controller.signal);
2817
+ const now = store.get(bot.id);
2818
+ if (!current() || !now) throw Object.assign(new Error(now ? 'its avatar was changed meanwhile' : 'the bot was deleted'), { dropped: true });
2819
+ return savePicture(now, bytes, type, 'ai');
2820
+ } catch (error) {
2821
+ if (error?.dropped || (current() && store.get(bot.id))) throw error;
2822
+ throw Object.assign(new Error(store.get(bot.id) ? 'its avatar was changed meanwhile' : 'the bot was deleted'), { dropped: true });
2823
+ } finally {
2824
+ if (current()) drawings.delete(bot.id);
2825
+ }
2826
+ })();
2827
+ return job;
2828
+ }
2829
+ /** Draw `bot`'s avatar and wait for it (the panel, a person's own conversation): the bot with its picture. */
2830
+ async function generateAvatar(bot, extra) {
2831
+ if (!imageTool()) throw new Error('the Images plugin (generate_image) is not installed or turned off');
2832
+ try {
2833
+ return await startDrawing(bot, extra).done;
2834
+ } catch (error) {
2835
+ throw new Error(error?.dropped ? `no picture was saved: ${error.message}` : String(error?.message ?? error));
2836
+ }
2837
+ }
2838
+ /**
2839
+ * A drawing a bot asked for goes on without it: the caller's turn goes on, and its conversation
2840
+ * gets one note when the drawing ends (ready, or why not). A home takes it steered, so drawings that
2841
+ * end together arrive together; a task's Session takes it like any message for its task (once it
2842
+ * has a worker slot), unless the task has ended. A drawing replaced from the same conversation, or
2843
+ * dropped by a restart, sends nothing.
2844
+ */
2845
+ function drawInBackground(bot, extra, caller) {
2846
+ const job = startDrawing(bot, extra, { sessionId: caller.sessionId, by: caller.bot.id });
2847
+ // The Threads of the asking turn: the note's answer goes back where the person asked.
2848
+ const origins = (() => {
2849
+ try {
2850
+ return channels.replyPlan(caller.sessionId).origins.map(({ body: _b, tickets: _t, ...o }) => o).filter((o) => o.threadKey);
2851
+ } catch {
2852
+ return [];
2853
+ }
2854
+ })();
2855
+ const who = `@${job.handle}`;
2856
+ job.done.then(
2857
+ (saved) => noteDrawing(job, origins, `[Avatar ready] The new avatar of ${who} (${saved?.name ?? job.name}) is ready and shows in Bots now. Tell the person if they are waiting for it.`),
2858
+ (error) => {
2859
+ const reason = String(error?.message ?? error).slice(0, 300);
2860
+ if (!error?.dropped) return noteDrawing(job, origins, `[Avatar failed] The picture for ${who} could not be drawn: ${reason}. Its avatar is unchanged.`);
2861
+ if (job.droppedBy !== job.sessionId) return noteDrawing(job, origins, `[Avatar dropped] The picture for ${who} was not used: ${reason}.`);
2862
+ return undefined;
2863
+ },
2864
+ );
2865
+ return job;
2866
+ }
2867
+ /** A drawing's note to the conversation that asked for it (`job.sessionId`): see `drawInBackground`. */
2868
+ async function noteDrawing(job, origins, text) {
2869
+ try {
2870
+ const key = `avatar:${job.id}`;
2871
+ const content = [{ type: 'text', text }];
2872
+ const source = { kind: 'agent-message', form: 'relay' };
2873
+ const t = ticketOf(job.sessionId);
2874
+ if (t) {
2875
+ const cur = tickets.get(t.id);
2876
+ if (cur && !cur.ended && !cur.archivedAt) await toTicket(cur, { content, source, key });
2877
+ return;
2878
+ }
2879
+ const asker = store.get(job.by);
2880
+ if (!asker) return;
2881
+ if (origins.length) {
2882
+ drawingOrigins.set(`${MESSAGE_PREFIX}${key}`, origins);
2883
+ // A note never delivered (Harness gone meanwhile) leaves nothing behind for long.
2884
+ while (drawingOrigins.size > 200) drawingOrigins.delete(drawingOrigins.keys().next().value);
2885
+ }
2886
+ // The asking bot may have started a new topic since: the note goes to the conversation it has now.
2887
+ await sendTo(await agentOf(asker), { content, source, mode: 'steer', key });
2888
+ } catch (error) {
2889
+ ctx.logger?.warn?.(`bots: the note about @${job.handle}'s avatar did not arrive: ${error?.message ?? error}`);
2890
+ }
2891
+ }
2892
+ /** Store `bytes` as the bot's picture avatar. */
2893
+ function savePicture(bot, bytes, type, source) {
1160
2894
  mkdirSync(join(dir, 'avatars'), { recursive: true });
1161
2895
  writeFileSync(join(dir, 'avatars', bot.id), bytes);
1162
2896
  writeFileSync(join(dir, 'avatars', `${bot.id}.type`), type);
1163
- return store.patch(bot.id, { avatar: { kind: 'image', source: 'ai', url: `${R}/avatar/${bot.id}?v=${Date.now().toString(36)}`, color: bot.avatar.color } });
2897
+ return store.patch(bot.id, { avatar: { kind: 'image', ...(source ? { source } : {}), url: `${R}/avatar/${bot.id}?v=${Date.now().toString(36)}`, color: bot.avatar.color } });
2898
+ }
2899
+ /** The image type of `bytes` by its first bytes: PNG, JPEG, WebP or GIF; else ''. */
2900
+ function pictureType(bytes) {
2901
+ if (bytes.length > 8 && bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'image/png';
2902
+ if (bytes.length > 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
2903
+ if (bytes.length > 12 && bytes.toString('latin1', 0, 4) === 'RIFF' && bytes.toString('latin1', 8, 12) === 'WEBP') return 'image/webp';
2904
+ if (bytes.length > 6 && /^GIF8[79]a$/.test(bytes.toString('latin1', 0, 6))) return 'image/gif';
2905
+ return '';
2906
+ }
2907
+ /** A picture file on this computer becomes the bot's avatar (a tool's `avatar_file`). */
2908
+ function avatarFromFile(bot, file) {
2909
+ const path = String(file ?? '').trim().replace(/^~(?=\/)/, homedir());
2910
+ if (!isAbsolute(path)) throw new Error('avatar_file must be an absolute path to an image file');
2911
+ let bytes;
2912
+ try {
2913
+ if (statSync(path).size > MAX_AVATAR) throw new Error('the image is larger than 2 MB');
2914
+ bytes = readFileSync(path);
2915
+ } catch (error) {
2916
+ throw new Error(/2 MB/.test(String(error?.message)) ? error.message : `cannot read ${path}: ${error?.code ?? error?.message ?? error}`);
2917
+ }
2918
+ const type = pictureType(bytes);
2919
+ if (!type) throw new Error('avatar_file must be a PNG, JPEG, WebP or GIF image');
2920
+ return savePicture(bot, bytes, type);
2921
+ }
2922
+ /** Back to letters: the picture is removed. */
2923
+ function clearPicture(bot) {
2924
+ for (const f of [bot.id, `${bot.id}.type`]) rmSync(join(dir, 'avatars', f), { force: true });
2925
+ return store.patch(bot.id, { avatar: { kind: 'initials', color: bot.avatar.color } });
2926
+ }
2927
+ const AVATAR_PARAMS = {
2928
+ avatar_prompt: {
2929
+ type: 'string',
2930
+ description:
2931
+ 'Draw a picture avatar with AI from this description of the look and style (e.g. "photorealistic portrait of a woman in her thirties, studio light"). Needs the Images plugin (the result says so when it is not available). Called from a bot\'s conversation, the drawing runs in the background: the call returns at once and a note arrives in this conversation when the picture is ready (or why it failed), so never wait or poll for it. A restart of Harness drops a drawing still under way, without a note.',
2932
+ },
2933
+ avatar_file: { type: 'string', description: 'Absolute path of an image file on this computer (PNG, JPEG, WebP or GIF, at most 2 MB) to use as the avatar picture.' },
2934
+ };
2935
+ /**
2936
+ * Apply a tool's picture arguments to `bot`; the note says what happened (a failed drawing leaves
2937
+ * the rest of the change in place). From a bot's conversation (`caller.bot`), a drawing runs in the
2938
+ * background and the note says a message will come; from a person's own conversation it is awaited.
2939
+ * Any other avatar change replaces a drawing still under way.
2940
+ */
2941
+ async function applyPicture(bot, args, caller = {}) {
2942
+ const by = caller.sessionId ?? 'panel';
2943
+ if (typeof args.avatar_file === 'string' && args.avatar_file.trim()) {
2944
+ const saved = avatarFromFile(bot, args.avatar_file);
2945
+ dropDrawing(bot.id, by);
2946
+ return { bot: saved, note: ' Its avatar is now that picture.' };
2947
+ }
2948
+ if (typeof args.avatar_prompt === 'string' && args.avatar_prompt.trim()) {
2949
+ if (!imageGenAvailable()) return { bot, note: ' No picture was drawn: AI avatars need the Images plugin (generate_image), which is not installed or is turned off. The user can install it from the plugin market, or upload a picture on the bot\'s Profile page; avatar_file takes an image file.' };
2950
+ if (caller.bot && caller.sessionId) {
2951
+ drawInBackground(bot, args.avatar_prompt, caller);
2952
+ return { bot, drawing: true, note: ' Its avatar picture is being drawn in the background (often a minute or more); the current avatar stays until then. A note arrives in this conversation when it is ready, or with the reason if it fails: do not wait or poll for it, carry on.' };
2953
+ }
2954
+ try {
2955
+ return { bot: await generateAvatar(bot, args.avatar_prompt), note: ' Its avatar is now a picture drawn from that description.' };
2956
+ } catch (error) {
2957
+ return { bot, note: ` The picture could not be drawn: ${String(error?.message ?? error).slice(0, 300)}` };
2958
+ }
2959
+ }
2960
+ if (args.avatar_clear === true && bot.avatar.kind === 'image') {
2961
+ dropDrawing(bot.id, by);
2962
+ return { bot: clearPicture(bot), note: ' Its avatar is back to letters.' };
2963
+ }
2964
+ if (args.avatar_clear === true || args.initials || args.color) dropDrawing(bot.id, by);
2965
+ return { bot, note: '' };
2966
+ }
2967
+
2968
+ // --- who calls a tool ----------------------------------------------------------------------
2969
+ /**
2970
+ * Who calls a tool: the conversation it runs in; or, for a Harness subagent or fork (its Session
2971
+ * header says `origin: 'subagent'` and names the `parentSession` that made it), the bot home or task
2972
+ * Session it descends from, which it then acts as (a helper inside task t1 is task t1, with its
2973
+ * limits). `bot`: that conversation's bot; none for a person's own conversation (a top-level Session
2974
+ * no bot owns, or a helper of one). `restricted`: a helper whose line cannot be traced to a
2975
+ * conversation (a creator that is gone was no bot's, or a loop); it acts for no one.
2976
+ * @returns {{sessionId: string|undefined, bot?: object, restricted?: true}}
2977
+ */
2978
+ function actorOf(exec) {
2979
+ const own = exec?.agent?.session?.id;
2980
+ const ownBot = botOfSession(own);
2981
+ if (!own || ownBot) return { sessionId: own, ...(ownBot ? { bot: ownBot } : {}) };
2982
+ const live = agents();
2983
+ let header = exec.agent.session.header ?? live?.get?.(own)?.session?.header;
2984
+ const seen = new Set([own]);
2985
+ while (header?.origin === 'subagent' && typeof header.parentSession === 'string' && header.parentSession !== '') {
2986
+ const parent = header.parentSession;
2987
+ if (seen.has(parent)) return { sessionId: own, restricted: true };
2988
+ seen.add(parent);
2989
+ const bot = botOfSession(parent);
2990
+ if (bot) return { sessionId: parent, bot };
2991
+ const up = live?.get?.(parent);
2992
+ if (!up) return { sessionId: own, restricted: true };
2993
+ // A live creator without a header cannot be a helper itself: a top-level conversation.
2994
+ header = up.session?.header ?? {};
2995
+ }
2996
+ return { sessionId: own };
2997
+ }
2998
+ /** The caller (`actorOf`); one that acts for no one is refused. */
2999
+ function actor(exec) {
3000
+ const a = actorOf(exec);
3001
+ if (a.restricted) throw new Error('this conversation is a helper whose starting conversation cannot be traced (it is gone), so it cannot act on bots or tasks; report what you found to whoever started you instead');
3002
+ return a;
3003
+ }
3004
+
3005
+ // --- what bot_recall reads ---------------------------------------------------------------
3006
+ /**
3007
+ * Who reads with bot_recall (an `actorOf` caller): a ticket Session (limited to its task), the router
3008
+ * home, another home; a helper that cannot be traced reads nothing; else unlimited (the user).
3009
+ */
3010
+ function viewerOf(caller) {
3011
+ if (caller?.restricted) return { kind: 'restricted' };
3012
+ const sessionId = caller?.sessionId;
3013
+ const t = ticketOf(sessionId);
3014
+ if (t) return { kind: 'ticket', ticketId: t.id };
3015
+ const bot = store.bySession(sessionId);
3016
+ if (!bot) return undefined;
3017
+ return isRouterHome(bot, sessionId) ? { kind: 'router' } : { kind: 'home' };
3018
+ }
3019
+ /** Threads as bot_recall reads them: stored with tickets, seen lately in a chat, or a panel conversation; the timeline's latest messages there. */
3020
+ const recallThreads = {
3021
+ thread: (key) => {
3022
+ const stored = tickets.thread(key);
3023
+ if (stored) return stored;
3024
+ const info = channels.threadInfo(key);
3025
+ if (info) return { key, kind: info.kind, label: threadLabel(info) };
3026
+ return isPanelThread(key) ? { key, kind: 'panel', label: threadLabel(key) } : undefined;
3027
+ },
3028
+ subscribers: (key) => tickets.subscribers(key),
3029
+ recent: (key) =>
3030
+ store
3031
+ .messages({ limit: 2000 })
3032
+ .filter((m) => m.thread === key)
3033
+ .slice(-10)
3034
+ .map((m) => ({ at: m.at, who: m.from === 'user' ? m.who || 'the user' : m.from === 'schedule' ? 'schedule' : handleOf(m.from), text: m.text })),
3035
+ };
3036
+ /** One stored Session event as a transcript line, or ''. */
3037
+ function eventLine(e) {
3038
+ const d = e?.data ?? {};
3039
+ if (e?.type === 'user/message') {
3040
+ const said = textOf(d.content);
3041
+ return said ? `[${d.source?.kind === 'user' ? 'user' : 'message'}] ${said}` : '';
3042
+ }
3043
+ if (e?.type === 'assistant/message') {
3044
+ const parts = [];
3045
+ for (const b of Array.isArray(d.message?.content) ? d.message.content : []) {
3046
+ if (b?.type === 'text' && b.text?.trim()) parts.push(`[assistant] ${b.text.trim()}`);
3047
+ else if (b?.type === 'tool-call') {
3048
+ let args = '';
3049
+ try {
3050
+ args = typeof b.argsRaw === 'string' ? b.argsRaw : JSON.stringify(b.args ?? b.arguments ?? b.input ?? {});
3051
+ } catch {
3052
+ args = '';
3053
+ }
3054
+ parts.push(`[tool] ${b.name ?? b.toolName ?? 'tool'} ${args.slice(0, 400)}`);
3055
+ }
3056
+ }
3057
+ return parts.join('\n');
3058
+ }
3059
+ if (e?.type === 'tool/result') {
3060
+ const said = textOf(d.message?.content ?? d.content);
3061
+ return said ? `[result] ${said.slice(0, 600)}` : '';
3062
+ }
3063
+ return '';
3064
+ }
3065
+ /** A ticket Session's conversation: from its stored log when Harness has one, else from the runs this process recorded. */
3066
+ async function transcriptOf(t) {
3067
+ const events = t.sessionId ? await readHistory(t.sessionId).catch(() => null) : null;
3068
+ const fromLog = (events ?? []).map(eventLine).filter(Boolean);
3069
+ if (fromLog.length) return fromLog;
3070
+ const lines = [...(doneLogs.get(t.id) ?? []), ...(ticketLogs.get(t.id)?.log ?? []), ...(t.sessionId ? openTasks.get(t.sessionId)?.log ?? [] : [])];
3071
+ return lines.length ? lines : `(No transcript of task ${t.id} is kept here; its reports are at ticket/${t.id}/reports.)`;
1164
3072
  }
1165
3073
 
1166
3074
  // --- the model's tools ------------------------------------------------------------------
1167
- const callerBot = (exec) => store.bySession(exec?.agent?.session?.id);
3075
+ const callerBot = (exec) => actor(exec).bot;
1168
3076
  const resolve = (ref, what = 'bot') => {
1169
3077
  const bot = store.find(ref);
1170
3078
  if (!bot) throw new Error(`no ${what} "${ref}". Known bots: ${store.list().map((b) => `@${b.handle}`).join(', ') || 'none'}`);
@@ -1206,7 +3114,8 @@ export function apply(ctx, config, deps = {}) {
1206
3114
  const sk = b.skills.filter((s) => s.enabled).map((s) => s.name);
1207
3115
  const ap = b.apps.filter((a) => a.enabled).map((a) => a.name);
1208
3116
  const ts = tasks.filter((t) => t.botId === b.id).map((t) => `${t.title} (${t.describe}${t.status !== 'active' ? `, ${t.status}` : ''})`);
1209
- return [`${card(b)} [${botStatus(b)}]${b.bio ? `: ${b.bio}` : ''}`, sk.length ? ` skills: ${sk.join(', ')}` : '', ap.length ? ` apps: ${ap.join(', ')}` : '', ts.length ? ` scheduled: ${ts.join('; ')}` : ''].filter(Boolean).join('\n');
3117
+ const open = tickets.list({ botId: b.id, open: true }).length;
3118
+ return [`${card(b)} [${botStatus(b)}${open ? `, ${open} open task${open === 1 ? '' : 's'}` : ''}]${b.bio ? `: ${b.bio}` : ''}`, sk.length ? ` skills: ${sk.join(', ')}` : '', ap.length ? ` apps: ${ap.join(', ')}` : '', ts.length ? ` scheduled: ${ts.join('; ')}` : ''].filter(Boolean).join('\n');
1210
3119
  });
1211
3120
  return { ok: true, text: lines.length ? lines.join('\n') : 'No bots yet.', bots: bots.map(face) };
1212
3121
  },
@@ -1221,11 +3130,13 @@ export function apply(ctx, config, deps = {}) {
1221
3130
  persona: { type: 'string', description: 'Who the bot is and how it works, in the second person ("You are …"). Several sentences.' },
1222
3131
  initials: { type: 'string', description: 'Avatar letters, at most two; derived from the name (pinyin initials for a Chinese name) when left out.' },
1223
3132
  color: { type: 'string', description: 'Avatar background colour, CSS hex.' },
3133
+ ...AVATAR_PARAMS,
1224
3134
  skills: { ...skillInput, description: 'Skills to give it.' },
1225
3135
  },
1226
3136
  output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
1227
3137
  execute: async (args, exec) => {
1228
- const by = callerBot(exec);
3138
+ const caller = actor(exec);
3139
+ const by = caller.bot;
1229
3140
  tooManySkills((args.skills ?? []).length);
1230
3141
  const bot = store.save(
1231
3142
  {
@@ -1238,12 +3149,13 @@ export function apply(ctx, config, deps = {}) {
1238
3149
  },
1239
3150
  { createdBy: by?.id ?? 'user' },
1240
3151
  );
1241
- return { ok: true, text: `Created ${card(bot)}. Message it with bot_send_message to @${bot.handle}.${offNote(args.skills, bot)}`, bot: face(bot) };
3152
+ const pic = await applyPicture(bot, args, caller);
3153
+ return { ok: true, text: `Created ${card(pic.bot)}. Message it with bot_send_message to @${bot.handle}.${pic.note}${offNote(args.skills, bot)}`, bot: face(pic.bot) };
1242
3154
  },
1243
3155
  }),
1244
3156
  defineTool({
1245
3157
  name: 'bot_update',
1246
- description: "Change a bot: name, bio, persona, avatar, skills, or make it the dispatcher. Only the fields you pass change.",
3158
+ description: "Change a bot (yourself included): name, bio, persona, avatar (letters and colour, a picture drawn by AI, or an image file), skills, or make it the dispatcher. Only the fields you pass change.",
1247
3159
  parameters: {
1248
3160
  bot: { type: 'string', required: true, description: '@handle, id or name of the bot.' },
1249
3161
  name: { type: 'string' },
@@ -1251,12 +3163,16 @@ export function apply(ctx, config, deps = {}) {
1251
3163
  persona: { type: 'string', description: 'Replaces the whole persona.' },
1252
3164
  initials: { type: 'string', description: 'Avatar letters, at most two.' },
1253
3165
  color: { type: 'string', description: 'Avatar background colour, CSS hex.' },
3166
+ ...AVATAR_PARAMS,
3167
+ avatar_clear: { type: 'boolean', description: 'true to remove the avatar picture and go back to letters.' },
1254
3168
  add_skills: { ...skillInput, description: `Skills to add (a skill with the same name is replaced). At most ${MAX_SKILLS_ON} can be on at once; past that they are added switched off.` },
1255
3169
  remove_skills: { type: 'array', items: { type: 'string' }, description: 'Names of skills to remove.' },
1256
3170
  make_dispatcher: { type: 'boolean', description: 'true to make this bot the dispatcher.' },
1257
3171
  },
1258
3172
  output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
1259
- execute: async (args) => {
3173
+ execute: async (args, exec) => {
3174
+ // A helper whose line cannot be traced still changes bots, as before; it waits for a drawing.
3175
+ const caller = actorOf(exec);
1260
3176
  const bot = resolve(args.bot);
1261
3177
  const next = { id: bot.id };
1262
3178
  for (const k of ['name', 'bio', 'persona']) if (typeof args[k] === 'string') next[k] = args[k];
@@ -1267,8 +3183,9 @@ export function apply(ctx, config, deps = {}) {
1267
3183
  tooManySkills(next.skills.length);
1268
3184
  }
1269
3185
  if (args.make_dispatcher === true) next.role = 'primary';
1270
- const saved = store.save(next);
1271
- return { ok: true, text: `Updated ${card(saved)}.${offNote(args.add_skills, saved)}`, bot: face(saved) };
3186
+ const pic = await applyPicture(store.save(next), args, caller.restricted ? {} : caller);
3187
+ const saved = pic.bot;
3188
+ return { ok: true, text: `Updated ${card(saved)}.${pic.note}${offNote(args.add_skills, saved)}`, bot: face(saved) };
1272
3189
  },
1273
3190
  }),
1274
3191
  defineTool({
@@ -1286,19 +3203,219 @@ export function apply(ctx, config, deps = {}) {
1286
3203
  }),
1287
3204
  defineTool({
1288
3205
  name: 'bot_send_message',
3206
+ description: [
3207
+ '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
+ "- 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
+ '- 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.',
3211
+ '- 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
+ '- 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
+ '- In a task conversation, to report to whoever asked: leave out `to`, give `text` and a `status` (progress, done, blocked, question).',
3214
+ ].join('\n'),
3215
+ parameters: {
3216
+ to: { type: 'string', description: '@handle (or id / name) of the bot. Leave it out to report on your own task.' },
3217
+ text: { type: 'string', required: true, description: 'The whole message or report.' },
3218
+ ticket: { type: 'string', description: 'Id of an open task to add this message to.' },
3219
+ 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.' },
3220
+ title: { type: 'string', description: 'A short title for a new task; taken from the first line of text when left out.' },
3221
+ 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
+ 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
+ },
3224
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ to: v.to, from: v.from, ...(v.ticket ? { ticket: v.ticket } : {}) }) },
3225
+ isConcurrencySafe: () => true,
3226
+ execute: async (args, exec) => {
3227
+ const { sessionId, bot: sender } = actor(exec);
3228
+ const mine = ticketOf(sessionId);
3229
+ const named = args.to !== undefined && String(args.to).trim() !== '' ? resolve(args.to) : null;
3230
+ const wantTicket = typeof args.ticket === 'string' && args.ticket.trim() !== '' ? args.ticket.trim().replace(/^ticket\//, '') : '';
3231
+ const row = (t) => ticketRow(t);
3232
+ const status = typeof args.status === 'string' && args.status.trim() !== '' ? args.status.trim().toLowerCase() : '';
3233
+
3234
+ // In a ticket Session: a report to whoever asked (no `to`, the requester, or its own ticket).
3235
+ if (mine && sender) {
3236
+ const requesterBot = mine.requester?.botId;
3237
+ const isReport = wantTicket ? wantTicket === mine.id : !named || (named.id === requesterBot && named.id !== sender.id);
3238
+ if (isReport) {
3239
+ if (!status) throw new Error(`a report on task ${mine.id} needs a status: progress (an update), done (with the result), blocked or question`);
3240
+ const { ticket, relayed, unread, parent, shown } = await reportTicket(mine, status, args.text);
3241
+ const to = requesterBot ? store.get(requesterBot) : null;
3242
+ const said =
3243
+ status === 'progress'
3244
+ ? `Recorded on task ${ticket.id}; progress does not interrupt whoever asked. Go on with the work.`
3245
+ : shown
3246
+ ? `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.'}`
3247
+ : unread
3248
+ ? `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.`
3249
+ : `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.'}`;
3250
+ return { ok: true, text: said, ticket: row(ticket), to: face(to), from: face(sender) };
3251
+ }
3252
+ }
3253
+ 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');
3254
+
3255
+ const chosen = typeof args.thread === 'string' && args.thread.trim() !== '' ? threadRef(args.thread, sessionId) : '';
3256
+ // Adding to an existing ticket.
3257
+ if (wantTicket) {
3258
+ const t = tickets.get(wantTicket);
3259
+ if (!t) throw new Error(`no task ${wantTicket}`);
3260
+ 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
+ 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 });
3263
+ const target = store.get(next.botId);
3264
+ 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) };
3269
+ }
3270
+ 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
+
3272
+ // 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))) {
3274
+ const relay = String(args.report_to ?? '').trim().toLowerCase() === 'me';
3275
+ const t = await openTicket(sender, named, args.text, sessionId, { title: args.title, thread: chosen, relay });
3276
+ const stage = stageOf(t);
3277
+ const who = named.id === sender.id ? 'yourself' : `@${named.handle}`;
3278
+ 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.`
3280
+ : 'Its report will arrive here by itself; never wait or poll for it — go on with other work or end your turn.';
3281
+ const said =
3282
+ stage === 'failed'
3283
+ ? `Task ${t.id} for ${who} could not start: ${t.error ?? 'unknown error'}.`
3284
+ : `Opened task ${t.id} for ${who} (${stage === 'queued' ? 'queued: it starts when another task finishes' : stage}). ${answer}`;
3285
+ return { ok: stage !== 'failed', text: said, ticket: row(t), stage, to: face(named), from: face(sender) };
3286
+ }
3287
+ // 0.7: into the other bot's home (the user from any conversation; any home in hands-on mode).
3288
+ if (chosen) throw new Error('`thread` is for opening a task; this message goes to the bot\'s own conversation, so leave it out');
3289
+ await deliver(sender ?? null, named, args.text, sessionId);
3290
+ return { ok: true, text: `Delivered to @${named.handle}. Its answer will arrive as a new message; continue with other work or end your turn.`, to: face(named), from: face(sender) };
3291
+ },
3292
+ }),
3293
+ defineTool({
3294
+ name: 'bot_reply',
3295
+ description:
3296
+ '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.',
3297
+ parameters: {
3298
+ ticket: { type: 'string', description: 'Id of a task (t…): the reply goes to the topic or chat that task came from.' },
3299
+ thread: { type: 'string', description: 'A panel topic (p…) or chat thread key of this turn (or of a task you know of).' },
3300
+ text: { type: 'string', required: true, description: 'The reply, as the person should read it.' },
3301
+ },
3302
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ via: v.via, thread: v.thread }) },
3303
+ execute: async (args, exec) => {
3304
+ const { sessionId, bot } = actor(exec);
3305
+ 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');
3306
+ if (!bot) throw new Error("bot_reply answers from a bot's own conversation; this conversation has no chats");
3307
+ const body = String(args.text ?? '').trim();
3308
+ if (body === '') throw new Error('text must not be empty');
3309
+ const thread = typeof args.thread === 'string' && args.thread.trim() !== '' ? threadRef(args.thread, sessionId) : '';
3310
+ const ticketId = typeof args.ticket === 'string' && args.ticket.trim() !== '' ? args.ticket.trim().replace(/^(?:ticket|task)\//, '') : '';
3311
+ const options = () => {
3312
+ const list = turnChoices(sessionId);
3313
+ 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.';
3314
+ };
3315
+ if (!thread && !ticketId) throw new Error(`say where: \`ticket\` (a task id) or \`thread\` (a topic or thread). ${options()}`);
3316
+ // A topic in the panel (Bots 0.9): this turn's, one a task came from, or any the bot's chat has.
3317
+ const asked = ticketId ? tickets.get(ticketId) : undefined;
3318
+ const panelKey = thread ? (panelTopicOf(thread) ? thread : '') : panelTopicOf(asked?.origin?.threadKey) ? asked.origin.threadKey : '';
3319
+ // A panel topic of this bot's own chat only: one whose first message is there, or a task it asked for or does.
3320
+ if (panelKey) {
3321
+ const root = store.message(panelTopicOf(panelKey));
3322
+ const mine = thread ? Boolean(root) && inChat(root, bot.id) : Boolean(asked) && (asked.requester?.botId === bot.id || asked.botId === bot.id);
3323
+ if (!mine) throw new Error(`${thread ? `no topic "${args.thread}"` : `task ${ticketId} came from no topic`} in this bot's chat. ${options()}`);
3324
+ }
3325
+ const target = panelKey ? { kind: 'panel', threadKey: panelKey } : channels.resolveReply(sessionId, thread ? { thread } : { ticket: ticketId });
3326
+ 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()}`);
3327
+ const answeredHere = () => {
3328
+ const st = turnState.get(sessionId);
3329
+ if (st) (st.replied ??= new Set()).add(target.threadKey);
3330
+ };
3331
+ if (target.kind === 'panel') {
3332
+ const topic = panelTopicOf(target.threadKey);
3333
+ const chat = (topic && store.message(topic)?.chat) || bot.id;
3334
+ store.log({ from: bot.id, to: 'user', chat, text: body, kind: 'reply', thread: topic ? target.threadKey : panelThreadKey(sessionId), ...(topic ? { topic } : {}) });
3335
+ 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 };
3337
+ }
3338
+ channels.replyTo(sessionId, target, body);
3339
+ answeredHere();
3340
+ store.log({ from: bot.id, to: 'user', chat: bot.id, text: body, kind: 'reply', via: target.kind, thread: target.threadKey });
3341
+ return { ok: true, text: `Sent to ${threadLabel(target)}.`, thread: target.threadKey, via: target.kind };
3342
+ },
3343
+ }),
3344
+ defineTool({
3345
+ name: 'bot_recall',
1289
3346
  description:
1290
- "Send a direct message to another bot. It lands in that bot's own conversation and wakes it; it works on it there and answers you with its own bot_send_message, which arrives here as a new message. Use it to delegate, ask, or report back. Make the text self-contained — the other bot cannot see this conversation. Do not reply to acknowledgements.",
3347
+ 'Read tasks (tickets) and chat threads by reference instead of guessing: `tickets` (a page of them, open ones first), `ticket/<id>` (its card), `ticket/<id>/text` (what was asked), `ticket/<id>/reports`, `ticket/<id>/transcript` (its conversation), `thread/<key>` (a chat thread: its tasks and latest messages), `bot/<handle>` (that bot\'s tasks). Every id on a card can be read this way; long text comes in pages (`offset`). From a task conversation you can read that task, its parent and sub-tasks, and its threads.',
1291
3348
  parameters: {
1292
- to: { type: 'string', required: true, description: '@handle (or id / name) of the bot.' },
1293
- text: { type: 'string', required: true, description: 'The whole message.' },
3349
+ ref: { type: 'string', required: true, description: 'tickets, ticket/<id>, ticket/<id>/text, ticket/<id>/reports, ticket/<id>/transcript, thread/<key> or bot/<handle>.' },
3350
+ offset: { type: 'number', description: 'Where the next page starts: the `next_offset` of the last one.' },
1294
3351
  },
1295
- output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ to: v.to, from: v.from }) },
3352
+ output: { schema: anyValue, render: (_a, v) => text(v.text) },
1296
3353
  isConcurrencySafe: () => true,
1297
3354
  execute: async (args, exec) => {
1298
- const target = resolve(args.to);
1299
- const sender = callerBot(exec);
1300
- await deliver(sender ?? null, target, args.text, exec?.agent?.session?.id);
1301
- return { ok: true, text: `Delivered to @${target.handle}. Its answer will arrive as a new message; continue with other work or end your turn.`, to: face(target), from: face(sender) };
3355
+ const result = await readResource(String(args.ref ?? ''), {
3356
+ viewer: viewerOf(actorOf(exec)),
3357
+ tickets,
3358
+ threads: recallThreads,
3359
+ bots: store.list(),
3360
+ stageOf,
3361
+ transcript: (t) => transcriptOf(t),
3362
+ offset: args.offset,
3363
+ now: nowMs(),
3364
+ });
3365
+ return { ok: true, ...result, text: JSON.stringify(result, null, 1) };
3366
+ },
3367
+ }),
3368
+ defineTool({
3369
+ name: 'bot_ticket',
3370
+ description:
3371
+ 'Act on a task (ticket) you asked for: `stop` it (its work is cancelled), `close` it as done, `retry` it (its bot takes it up again from the assignment), or `status` (asks its bot for a report when it is idle; the report arrives here by itself, never wait for it). From a task conversation you can act only on the sub-tasks it opened.',
3372
+ parameters: {
3373
+ id: { type: 'string', required: true, description: 'The task id (t…), as on its card.' },
3374
+ action: { type: 'string', required: true, enum: ['stop', 'close', 'retry', 'status'] },
3375
+ },
3376
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ ticket: v.ticket }) },
3377
+ execute: async (args, exec) => {
3378
+ const caller = actor(exec);
3379
+ const sessionId = caller.sessionId;
3380
+ const sender = caller.bot ?? null;
3381
+ const id = String(args.id ?? '').trim().replace(/^(?:ticket|task)\//, '');
3382
+ const action = String(args.action ?? '').trim().toLowerCase();
3383
+ if (!['stop', 'close', 'retry', 'status'].includes(action)) throw new Error('action is one of stop, close, retry, status');
3384
+ const t = tickets.get(id);
3385
+ if (!t) throw new Error(`no task ${id}. bot_recall {"ref":"tickets"} lists them.`);
3386
+ const mine = ticketOf(sessionId);
3387
+ if (mine) {
3388
+ if (t.parentId !== mine.id) throw new Error(`from task ${mine.id} you can act only on the sub-tasks it opened${t.id === mine.id ? '; to finish this task, report "done" with bot_send_message' : ''}`);
3389
+ } else if (sender && !mayAppend(t, sender, sessionId)) {
3390
+ throw new Error(`task ${t.id} was not asked for from this conversation; only whoever asked for it (or the dispatcher) can ${action} it`);
3391
+ }
3392
+ if (t.archivedAt) throw new Error(`task ${t.id} is archived; open a new task instead`);
3393
+ const by = sender ? 'requester' : 'user';
3394
+ const bot = handleOf(t.botId);
3395
+ let next = t;
3396
+ let said = '';
3397
+ if (action === 'stop' || action === 'close') {
3398
+ next = endTicket(t, { by, outcome: action === 'stop' ? 'stopped' : 'done' });
3399
+ said = action === 'stop' ? `Stopped task ${t.id} (${bot}).` : `Closed task ${t.id} (${bot}) as done.`;
3400
+ } else if (action === 'retry') {
3401
+ next = await retryTicket(t, sender ? { sender, senderSessionId: sessionId } : {});
3402
+ said = `Task ${t.id} (${bot}) is ${stageOf(next)} again; its report will arrive here by itself.`;
3403
+ } else if (t.ended) {
3404
+ said = `Task ${t.id} (${bot}) is ${stageOf(t)}; there is no work to report on. bot_recall reads its reports.`;
3405
+ } else if (!t.startedAt) {
3406
+ said = `Task ${t.id} (${bot}) is queued: it has not started yet.`;
3407
+ } else if (parkedOf(t).length > 0) {
3408
+ said = `Task ${t.id} (${bot}) waits for a free worker slot; the messages for it are handed over then, and its report arrives here by itself.`;
3409
+ } else if (agentStatusOf(t.sessionId) === 'running') {
3410
+ said = `${bot} is working on task ${t.id} right now; its next report arrives here by itself.`;
3411
+ } else {
3412
+ const who = sender ? `@${sender.handle}` : 'The user';
3413
+ const ask = `[Status request] ${who} asks how task ${t.id} ("${t.title}") stands. Report now with bot_send_message: "progress" with what is done and what is left, "done" with the result if it is finished, "blocked" or "question" if you are stuck.`;
3414
+ // A person's question may take the extra slot; a bot's waits for a free one.
3415
+ const { parked } = await toTicket(t, { content: [{ type: 'text', text: ask }], source: sender && sessionId ? { kind: 'agent-message', form: 'relay', senderSessionId: sessionId } : { kind: 'user' }, key: `status:${t.id}:${nowMs()}`, human: !sender });
3416
+ said = parked ? `Every worker slot is taken: ${bot} gets the status request on task ${t.id} when one frees; the report arrives here by itself, do not wait for it.` : `Asked ${bot} for a status report on task ${t.id}; it arrives here by itself, do not wait for it.`;
3417
+ }
3418
+ return { ok: true, text: said, ticket: ticketRow(tickets.get(next.id) ?? next) };
1302
3419
  },
1303
3420
  }),
1304
3421
  defineTool({
@@ -1321,7 +3438,7 @@ export function apply(ctx, config, deps = {}) {
1321
3438
  },
1322
3439
  output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot, task: v.task }) },
1323
3440
  execute: async (args, exec) => {
1324
- const actor = exec?.agent?.session?.id;
3441
+ const actorId = exec?.agent?.session?.id;
1325
3442
  const bot = args.bot ? resolve(args.bot) : callerBot(exec) ?? store.primary();
1326
3443
  if (!bot && (args.action === 'create' || args.action === 'list')) throw new Error('say which bot with `bot`');
1327
3444
  switch (args.action) {
@@ -1332,15 +3449,15 @@ export function apply(ctx, config, deps = {}) {
1332
3449
  case 'create':
1333
3450
  case 'update': {
1334
3451
  const timing = args.kind ? timingFrom(args, zone) : undefined;
1335
- const task = await scheduleSave(bot, { id: args.action === 'update' ? args.id : undefined, title: args.title, prompt: args.prompt, timing }, actor);
3452
+ const task = await scheduleSave(bot, { id: args.action === 'update' ? args.id : undefined, title: args.title, prompt: args.prompt, timing }, actorId);
1336
3453
  return { ok: true, bot: face(bot), task, text: `${args.action === 'create' ? 'Scheduled' : 'Updated'} "${task.title}" for @${bot.handle}: ${task.describe}; next at ${task.scheduledAt} (id ${task.id}).` };
1337
3454
  }
1338
3455
  case 'delete':
1339
- checkEntry(await schedule().edit({ id: String(args.id ?? ''), action: 'delete' }, actor));
3456
+ checkEntry(await schedule().edit({ id: String(args.id ?? ''), action: 'delete' }, actorId));
1340
3457
  return { ok: true, text: `Deleted task ${args.id}.` };
1341
3458
  case 'pause':
1342
3459
  case 'resume': {
1343
- const task = entryView(checkEntry(await schedule().edit({ id: String(args.id ?? ''), action: 'update', patch: { active: args.action === 'resume' } }, actor)));
3460
+ const task = entryView(checkEntry(await schedule().edit({ id: String(args.id ?? ''), action: 'update', patch: { active: args.action === 'resume' } }, actorId)));
1344
3461
  return { ok: true, task, text: `${args.action === 'pause' ? 'Paused' : 'Resumed'} "${task.title}".` };
1345
3462
  }
1346
3463
  case 'run':
@@ -1397,21 +3514,30 @@ export function apply(ctx, config, deps = {}) {
1397
3514
  }),
1398
3515
  defineTool({
1399
3516
  name: 'memory_search',
1400
- description: "Search long-term memory and the team's work journal (what every bot did, task by task) and daily digests, for words in the query. Use it when the user refers to earlier work that is not in this conversation.",
3517
+ description:
3518
+ "Search long-term memory, the team's work journal (what every bot did, task by task), daily digests, and tasks (their titles and reports), for words in the query. Use it when the user refers to earlier work that is not in this conversation; a task it finds can be read with bot_recall (ticket/<id>).",
1401
3519
  parameters: { query: { type: 'string', required: true, description: 'Words that should all appear.' } },
1402
3520
  output: { schema: anyValue, render: (_a, v) => text(v.text) },
1403
3521
  isConcurrencySafe: () => true,
1404
3522
  execute: async (args, exec) => {
1405
- const me = callerBot(exec);
3523
+ const { sessionId, bot: me } = actor(exec);
1406
3524
  const r = memory.search(args.query, { bot: me?.id ?? '' });
1407
3525
  const tz = tzMinutes();
1408
3526
  const when = (ms) => new Date(ms + tz * 60_000).toISOString().slice(0, 16).replace('T', ' ');
3527
+ // A task conversation finds only what it may read with bot_recall: its task, the parent, the sub-tasks;
3528
+ // journal lines of those tasks, none of other work (lines without a task, digests of everyone's day).
3529
+ const mine = ticketOf(sessionId);
3530
+ const scope = mine ? new Set([mine.id, mine.parentId, ...tickets.children(mine.id).map((c) => c.id)].filter(Boolean)) : null;
3531
+ const found = searchTickets(args.query, tickets.list().filter((t) => !scope || scope.has(t.id)));
3532
+ const journal = scope ? r.journal.filter((j) => j.ticket && scope.has(j.ticket)) : r.journal;
3533
+ const digests = scope ? [] : r.digests;
1409
3534
  const lines = [
1410
3535
  ...r.notes.map((n) => `[${n.id}] (${n.scope === 'team' ? 'team' : 'yours'}) ${n.text}`),
1411
- ...r.journal.map((j) => `${when(j.at)} @${store.get(j.bot)?.handle ?? 'removed'}: ${j.summary || j.title}`),
1412
- ...r.digests.map((d) => `Digest ${d.date}: ${d.text.slice(0, 600)}`),
3536
+ ...journal.map((j) => `${when(j.at)} @${store.get(j.bot)?.handle ?? 'removed'}: ${j.summary || j.title}${j.ticket ? ` (task ${j.ticket})` : ''}`),
3537
+ ...digests.map((d) => `Digest ${d.date}: ${d.text.slice(0, 600)}`),
3538
+ ...found.map((f) => `Task ${f.ticket.id} (${handleOf(f.ticket.botId)}, ${stageOf(f.ticket)}): ${f.ticket.title}${f.where === 'report' ? ` — ${f.status} report: ${f.snippet}` : ''} [bot_recall "ticket/${f.ticket.id}"]`),
1413
3539
  ];
1414
- return { ok: true, text: lines.length ? lines.join('\n') : `Nothing in memory matches "${args.query}".` };
3540
+ return { ok: true, text: lines.length ? lines.join('\n') : `Nothing in memory matches "${args.query}".`, tickets: found.map((f) => f.ticket.id) };
1415
3541
  },
1416
3542
  }),
1417
3543
  ];
@@ -1535,6 +3661,8 @@ export function apply(ctx, config, deps = {}) {
1535
3661
  skills: skills.map((s) => ({ name: s.name, description: String(s.description ?? '').slice(0, 300) })),
1536
3662
  ocu: { installed: ocu !== '', path: ocu || OCU_PATHS[0] },
1537
3663
  mcp: Boolean(mcpClient),
3664
+ // Off for a router dispatcher unless its bot lists them in `tools.routerAllow`.
3665
+ routerDeny: [...ROUTER_DENY],
1538
3666
  zone,
1539
3667
  };
1540
3668
  }
@@ -1695,6 +3823,7 @@ export function apply(ctx, config, deps = {}) {
1695
3823
  sweeping = true;
1696
3824
  try {
1697
3825
  for (const bot of store.list()) await autoTopic(bot, 'sweep');
3826
+ await ticketUpkeep().catch((error) => ctx.logger?.warn?.(`bots: task upkeep: ${error?.message ?? error}`));
1698
3827
  if (dreamDue()) await dream({ reason: 'schedule' }).catch((error) => ctx.logger?.warn?.(`bots: dream: ${error?.message ?? error}`));
1699
3828
  if (settings.get().codex.sync) await codexSync.syncOnce().catch((error) => ctx.logger?.warn?.(`bots: codex login sync: ${error?.message ?? error}`));
1700
3829
  } finally {
@@ -1720,9 +3849,10 @@ export function apply(ctx, config, deps = {}) {
1720
3849
  const overrides = settings.get().prices;
1721
3850
  const catalog = prices.peek();
1722
3851
  const running = [...openTasks.values()].map(({ log, size, replied, ...t }) => t);
3852
+ const names = new Map(tickets.list().map((t) => [t.id, { title: t.title, botId: t.botId }]));
1723
3853
  const r = report(
1724
3854
  { calls: ledger.calls(), tasks: ledger.tasks(), running },
1725
- { range: url.searchParams.get('range') || '7d', bot: url.searchParams.get('bot') || '', tz: Number.isFinite(tz) ? tz : tzMinutes(), price: (m) => priceOf(m, overrides, catalog), schedules: scheduleTitles },
3855
+ { range: url.searchParams.get('range') || '7d', bot: url.searchParams.get('bot') || '', tz: Number.isFinite(tz) ? tz : tzMinutes(), price: (m) => priceOf(m, overrides, catalog), schedules: scheduleTitles, tickets: names },
1726
3856
  );
1727
3857
  return { ...r, priceList: prices.status() };
1728
3858
  }
@@ -1760,9 +3890,29 @@ export function apply(ctx, config, deps = {}) {
1760
3890
  /** A bot as the page sees it: channel tokens masked. */
1761
3891
  const publicBot = (bot) => (bot ? maskBot(bot, templates()) : bot);
1762
3892
 
3893
+ /**
3894
+ * Tickets that need a person (not archived): an unanswered question, a failure, a stall; and a
3895
+ * ticket the user asked for whose latest report (done, blocked, question) has no Session to go to,
3896
+ * until the user answers it or closes the ticket.
3897
+ */
3898
+ const ATTENTION = new Set(['question', 'failed', 'stalled']);
3899
+ const needsPerson = (t) => {
3900
+ if (ATTENTION.has(stageOf(t))) return true;
3901
+ if (t.requester?.kind === 'session') return false;
3902
+ const last = t.reports.at(-1);
3903
+ return Boolean(last && last.status !== 'progress' && t.ended?.by !== 'user' && !((t.lastHumanAt ?? 0) > last.at));
3904
+ };
1763
3905
  function state() {
1764
3906
  const tpl = templates();
1765
3907
  const today = todayByBot(ledger.calls(), tzMinutes());
3908
+ const live = tickets.list({ archived: false });
3909
+ const waiting = pendingAsks();
3910
+ const counts = new Map();
3911
+ for (const t of live) {
3912
+ const stage = stageOf(t);
3913
+ const c = counts.get(t.botId) ?? counts.set(t.botId, { working: 0, question: 0, stalled: 0, queued: 0 }).get(t.botId);
3914
+ if (stage in c) c[stage] += 1;
3915
+ }
1766
3916
  const bots = store.list().map((b) => {
1767
3917
  const appIssues = {};
1768
3918
  for (const app of b.apps) {
@@ -1795,11 +3945,69 @@ export function apply(ctx, config, deps = {}) {
1795
3945
  topic: topic && topic.sessionId === b.sessionId ? { startedAt: topic.startedAt, lastActiveAt: topic.lastActiveAt, tasks: topic.tasks, context: topic.lastPrompt } : null,
1796
3946
  usageToday: today[b.id] ?? 0,
1797
3947
  memoryNotes: memory.notes(b.id).length,
3948
+ tickets: counts.get(b.id) ?? { working: 0, question: 0, stalled: 0, queued: 0 },
3949
+ // Questions its own conversation waits to have answered (`asks`); a task's count under `attention`.
3950
+ asking: waiting.filter((a) => a.botId === b.id && !a.ticketId).length,
3951
+ ...liveOf(b),
1798
3952
  };
1799
3953
  });
1800
3954
  const sessionMap = {};
1801
3955
  for (const b of bots) if (b.sessionId) sessionMap[b.sessionId] = b.id;
1802
- return { bots, primaryId: store.primary()?.id ?? null, sessionMap, messageCount: store.messageCount(), version: store.version(), limits: { skills: MAX_SKILLS, skillsOn: MAX_SKILLS_ON }, teamNotes: memory.notes('team').length };
3956
+ // Ticket Sessions carry their bot's badge in Harness too; `ticketMap` says which task each one is.
3957
+ const ticketMap = {};
3958
+ for (const t of live) {
3959
+ if (!t.sessionId || !store.get(t.botId)) continue;
3960
+ sessionMap[t.sessionId] = t.botId;
3961
+ ticketMap[t.sessionId] = t.id;
3962
+ }
3963
+ const s = settings.get();
3964
+ return {
3965
+ // The Host's clock, so the page can time what runs.
3966
+ at: nowMs(),
3967
+ bots,
3968
+ primaryId: store.primary()?.id ?? null,
3969
+ sessionMap,
3970
+ ticketMap,
3971
+ messageCount: store.messageCount(),
3972
+ version: store.version(),
3973
+ limits: { skills: MAX_SKILLS, skillsOn: MAX_SKILLS_ON },
3974
+ teamNotes: memory.notes('team').length,
3975
+ dispatcher: s.dispatcher,
3976
+ // The setting asks for a router, and the dispatcher has a teammate to hand work to: it routes now.
3977
+ routerActive: routerActive(),
3978
+ routerNoticePending: s.routerNotice === 'pending',
3979
+ // A task whose conversation waits for an answer to its question needs you too (its row says `asking`).
3980
+ attention: live.filter((t) => needsPerson(t) || askingIn(t.sessionId)).sort((a, b) => b.updatedAt - a.updatedAt).slice(0, 50).map(ticketRow),
3981
+ asks: waiting.sort((a, b) => a.at - b.at).map(askView),
3982
+ // What each running task Session does now, by task id (with its bot); a bot's home under `bots[].activity`.
3983
+ taskActivity: taskActivity(),
3984
+ // How the panel shows what bots say to each other ('line' | 'short' | 'full').
3985
+ display: s.display,
3986
+ };
3987
+ }
3988
+ /** A bot's live fields in state: what its home does now (`activity`), and a picture being drawn for it (`avatarPending`). */
3989
+ function liveOf(b) {
3990
+ const now = activity.get(b.sessionId);
3991
+ return { ...(now ? { activity: now } : {}), ...(drawings.has(b.id) ? { avatarPending: true } : {}) };
3992
+ }
3993
+ /** Task id → what its running Session does now, with the task's bot and title. */
3994
+ function taskActivity() {
3995
+ const out = {};
3996
+ for (const sid of activity.sessions()) {
3997
+ const t = ticketOf(sid);
3998
+ const now = t && !t.ended ? activity.get(sid) : undefined;
3999
+ if (now) out[t.id] = { ...now, botId: t.botId, title: t.title };
4000
+ }
4001
+ return out;
4002
+ }
4003
+ /**
4004
+ * GET /activity: only what moves while bots work, for the panel to poll often while something
4005
+ * runs: each bot's status and live fields, and the running tasks' activity.
4006
+ */
4007
+ function activityView() {
4008
+ const bots = {};
4009
+ for (const b of store.list()) bots[b.id] = { status: botStatus(b), ...liveOf(b) };
4010
+ return { ok: true, at: nowMs(), bots, taskActivity: taskActivity() };
1803
4011
  }
1804
4012
 
1805
4013
  let ocuInstalling = false;
@@ -1992,7 +4200,7 @@ export function apply(ctx, config, deps = {}) {
1992
4200
  const text = zhText
1993
4201
  ? `请为你自己写一个新技能:${ask}\n\n如果有 skill-creator 技能,先加载它并按它的方法写。写好后调用 bot_update(bot: @${bot.handle},add_skills)保存:name 用小写英文短横线,description 一句话写清楚何时使用,content 是完整的 Markdown 指南。最后用两三句话告诉我这个技能能做什么。`
1994
4202
  : `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.`;
1995
- return { ok: true, sessionId: await userSend(bot, text) };
4203
+ return { ok: true, sessionId: (await userSend(bot, text)).sessionId };
1996
4204
  },
1997
4205
  },
1998
4206
  'apps/external': { get: () => ({ items: scanExternalMcp().map(maskedApp) }) },
@@ -2018,9 +4226,7 @@ export function apply(ctx, config, deps = {}) {
2018
4226
  catalog: { get: () => catalog() },
2019
4227
  // A link preview card for the chat: YouTube, X posts, or any page's OpenGraph meta.
2020
4228
  unfurl: { get: (url) => unfurlLink(url.searchParams.get('url') ?? '') },
2021
- messages: {
2022
- get: (url) => ({ items: store.messages({ bot: url.searchParams.get('bot') ?? '', limit: Number(url.searchParams.get('limit')) || 200 }) }),
2023
- },
4229
+ messages: { get: (url) => messagesView(url) },
2024
4230
  schedules: {
2025
4231
  get: async (url) => {
2026
4232
  const id = url.searchParams.get('bot');
@@ -2065,7 +4271,8 @@ export function apply(ctx, config, deps = {}) {
2065
4271
  post: async (body) => {
2066
4272
  const bot = store.get(String(body.to ?? ''));
2067
4273
  if (!bot) return { ok: false, reason: 'no such bot' };
2068
- return { ok: true, sessionId: await userSend(bot, body.text) };
4274
+ const sent = await userSend(bot, body.text, { replyTo: String(body.replyTo ?? '') });
4275
+ return { ok: true, sessionId: sent.sessionId, ...(sent.message ? { message: sent.message } : {}) };
2069
4276
  },
2070
4277
  },
2071
4278
  avatar: {
@@ -2076,11 +4283,8 @@ export function apply(ctx, config, deps = {}) {
2076
4283
  if (!m) return { ok: false, reason: 'send a PNG, JPEG, WebP or GIF image' };
2077
4284
  const bytes = Buffer.from(m[2], 'base64');
2078
4285
  if (bytes.length > MAX_AVATAR) return { ok: false, reason: 'the image is larger than 2 MB' };
2079
- mkdirSync(join(dir, 'avatars'), { recursive: true });
2080
- writeFileSync(join(dir, 'avatars', bot.id), bytes);
2081
- writeFileSync(join(dir, 'avatars', `${bot.id}.type`), m[1]);
2082
- const saved = store.patch(bot.id, { avatar: { kind: 'image', url: `${R}/avatar/${bot.id}?v=${Date.now().toString(36)}`, color: bot.avatar.color } });
2083
- return { ok: true, bot: publicBot(saved) };
4286
+ dropDrawing(bot.id, 'panel');
4287
+ return { ok: true, bot: publicBot(savePicture(bot, bytes, m[1])) };
2084
4288
  },
2085
4289
  },
2086
4290
  'avatar/generate': {
@@ -2094,8 +4298,8 @@ export function apply(ctx, config, deps = {}) {
2094
4298
  post: (body) => {
2095
4299
  const bot = store.get(String(body.id ?? ''));
2096
4300
  if (!bot) return { ok: false, reason: 'no such bot' };
2097
- for (const f of [bot.id, `${bot.id}.type`]) rmSync(join(dir, 'avatars', f), { force: true });
2098
- return { ok: true, bot: publicBot(store.patch(bot.id, { avatar: { kind: 'initials', color: bot.avatar.color } })) };
4301
+ dropDrawing(bot.id, 'panel');
4302
+ return { ok: true, bot: publicBot(clearPicture(bot)) };
2099
4303
  },
2100
4304
  },
2101
4305
  'ocu/install': {
@@ -2133,6 +4337,8 @@ export function apply(ctx, config, deps = {}) {
2133
4337
  'schedules/run': { post: async (body) => (checkEntry(await schedule().run({ id: String(body.id ?? '') })), { ok: true }) },
2134
4338
  // Usage, prices, memory, topics, settings, model sources.
2135
4339
  usage: { get: (url) => usageReport(url) },
4340
+ // The live part of `state`, cheap enough to poll every second or two while bots work.
4341
+ activity: { get: () => activityView() },
2136
4342
  prices: {
2137
4343
  get: () => pricesView(),
2138
4344
  post: (body) => {
@@ -2152,9 +4358,17 @@ export function apply(ctx, config, deps = {}) {
2152
4358
  const patch = body.patch && typeof body.patch === 'object' ? { ...body.patch } : {};
2153
4359
  delete patch.codex;
2154
4360
  delete patch.prices;
2155
- return { ok: true, settings: settings.save(patch) };
4361
+ // Picking a dispatcher mode is having seen the notice about it.
4362
+ if (patch.dispatcher !== undefined) patch.routerNotice = 'dismissed';
4363
+ const saved = settings.save(patch);
4364
+ settingsChanged();
4365
+ return { ok: true, settings: saved };
2156
4366
  },
2157
4367
  },
4368
+ // The one-time notice that an upgraded team's dispatcher now routes: dismissed for good.
4369
+ 'router-notice/dismiss': { post: () => (settings.save({ routerNotice: 'dismissed' }), { ok: true, routerNoticePending: false }) },
4370
+ // Tasks (tickets), PLAN-0.8 §6.3. `tickets/:id…` and `threads/:key` are under `paramRoutes`.
4371
+ tickets: { get: (url) => ticketList(url) },
2158
4372
  memory: { get: (url) => memoryView(url.searchParams.get('bot') ?? 'team') },
2159
4373
  'memory/put': {
2160
4374
  post: (body) => {
@@ -2199,9 +4413,132 @@ export function apply(ctx, config, deps = {}) {
2199
4413
  'channels/reconnect': { post: (body) => ({ ok: channels.reconnect(String(body.botId ?? ''), String(body.appId ?? '')) }) },
2200
4414
  };
2201
4415
 
4416
+ /**
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).
4419
+ */
4420
+ function messagesView(url) {
4421
+ const bot = url.searchParams.get('bot') ?? '';
4422
+ const topic = url.searchParams.get('topic') ?? '';
4423
+ 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) };
4432
+ }
4433
+ return { items, topics };
4434
+ }
4435
+
4436
+ /** GET /tickets?bot=&stage=&limit=&offset=: rows, the latest change first; `stage` may list several (a,b). */
4437
+ function ticketList(url) {
4438
+ const bot = url.searchParams.get('bot') || undefined;
4439
+ const stage = (url.searchParams.get('stage') ?? '').split(',').map((x) => x.trim()).filter(Boolean);
4440
+ const archived = url.searchParams.get('archived');
4441
+ const limit = Math.min(200, Math.max(1, Math.floor(Number(url.searchParams.get('limit')) || 50)));
4442
+ const offset = Math.max(0, Math.floor(Number(url.searchParams.get('offset')) || 0));
4443
+ const all = tickets
4444
+ .list({ botId: bot, ...(stage.length ? { stage } : {}), ...(archived === '0' || archived === 'false' ? { archived: false } : archived === '1' || archived === 'true' ? { archived: true } : {}) })
4445
+ .sort((a, b) => b.updatedAt - a.updatedAt || b.createdAt - a.createdAt);
4446
+ const items = all.slice(offset, offset + limit).map(ticketRow);
4447
+ return { items, next_offset: offset + limit < all.length ? offset + limit : null };
4448
+ }
4449
+ /** GET /threads/:key: a Thread, the tickets subscribed to it and what was said there lately. */
4450
+ function threadRoute(key) {
4451
+ const th = tickets.thread(key);
4452
+ const parsed = parseThreadKey(key);
4453
+ if (!th && !parsed) return { ok: false, reason: 'no such thread' };
4454
+ // The panel as a whole holds its topics (`panel:<sessionId>:<root>`).
4455
+ const whole = isPanelThread(key) && !panelTopicOf(key);
4456
+ const recent = store
4457
+ .messages({ limit: 2000 })
4458
+ .filter((m) => m.thread === key || (whole && String(m.thread ?? '').startsWith(`${key}:`)))
4459
+ .slice(-10)
4460
+ .map((m) => ({ at: m.at, from: m.from, to: m.to, ...(m.who ? { who: m.who } : {}), text: clip(String(m.text ?? ''), 300).text }));
4461
+ return { key, label: th?.label ?? threadLabel(key), kind: th?.kind ?? parsed?.kind ?? '', tickets: tickets.subscribers(key).map(ticketRow), recent };
4462
+ }
4463
+ const ticketOr404 = (id) => {
4464
+ const t = tickets.get(String(id ?? ''));
4465
+ if (!t) throw new Error('no such task');
4466
+ return t;
4467
+ };
4468
+ /** Routes with a path parameter: `tickets/<id>[/<action>]`, `threads/<key>` (the key URI-encoded). */
4469
+ const paramRoutes = {
4470
+ tickets: {
4471
+ get: (rest) => {
4472
+ if (rest.length !== 1) throw new Error('no such route');
4473
+ return ticketView(ticketOr404(rest[0]));
4474
+ },
4475
+ post: async (rest, body) => {
4476
+ const [id, action] = rest;
4477
+ const t = ticketOr404(id);
4478
+ switch (action) {
4479
+ case 'stop':
4480
+ return { ok: true, ...ticketView(endTicket(t, { by: 'user', outcome: 'stopped' })) };
4481
+ case 'close':
4482
+ return { ok: true, ...ticketView(endTicket(t, { by: 'user', outcome: 'done' })) };
4483
+ case 'retry':
4484
+ return { ok: true, ...ticketView(await retryTicket(t)) };
4485
+ case 'message':
4486
+ return { ok: true, ...ticketView(await appendToTicket(t, body.text, { human: true, force: true })) };
4487
+ default:
4488
+ throw new Error('no such route');
4489
+ }
4490
+ },
4491
+ },
4492
+ threads: {
4493
+ get: (rest) => threadRoute(rest.join('/')),
4494
+ },
4495
+ // `asks/<id>/answer`: the panel answers a bot's question (state `asks`).
4496
+ asks: {
4497
+ post: (rest, body) => {
4498
+ if (rest.length !== 2 || rest[1] !== 'answer') throw new Error('no such route');
4499
+ return answerAsk(rest[0], body);
4500
+ },
4501
+ },
4502
+ };
4503
+ /** One request as the web server would route it (also for tests): exact routes, then the parameter ones. */
4504
+ async function request(method, path, body = {}) {
4505
+ const url = new URL(path, 'http://localhost');
4506
+ const rel = url.pathname.startsWith(`${R}/`) ? url.pathname.slice(R.length + 1) : url.pathname.replace(/^\//, '');
4507
+ const exact = routes[rel];
4508
+ if (exact) return method === 'GET' ? exact.get(url) : exact.post(body);
4509
+ const [head, ...parts] = rel.split('/');
4510
+ const route = paramRoutes[head];
4511
+ if (!route) throw new Error('no such route');
4512
+ const rest = head === 'threads' ? [decodeURIComponent(parts.join('/'))] : parts.map((p) => decodeURIComponent(p));
4513
+ if (method === 'GET' && route.get) return route.get(rest, url);
4514
+ if (method === 'POST' && route.post) return route.post(rest, body);
4515
+ throw new Error('no such route');
4516
+ }
4517
+ /** The ticket settings or the dispatcher mode changed: slots, router homes and the queue follow. */
4518
+ function settingsChanged() {
4519
+ slots.setMax(settings.get().tickets.maxWorking);
4520
+ reapply();
4521
+ void pump();
4522
+ }
4523
+
2202
4524
  const mountRoutes = (scope) => {
2203
4525
  const web = scope.webServer;
2204
4526
  if (!web?.register) return;
4527
+ for (const head of Object.keys(paramRoutes)) {
4528
+ scope.effect(() =>
4529
+ web.register({
4530
+ kind: 'prefix',
4531
+ path: `${R}/${head}`,
4532
+ handler: (req, res) => {
4533
+ const url = new URL(req.url ?? '/', 'http://localhost');
4534
+ if (req.method === 'GET') return serveJson(res, () => request('GET', `${url.pathname}${url.search}`));
4535
+ if (req.method === 'POST') return postJson(req, res, (body) => request('POST', url.pathname, body));
4536
+ res.statusCode = 405;
4537
+ res.end();
4538
+ },
4539
+ }),
4540
+ );
4541
+ }
2205
4542
  for (const [path, route] of Object.entries(routes)) {
2206
4543
  scope.effect(() =>
2207
4544
  web.register({
@@ -2223,7 +4560,9 @@ export function apply(ctx, config, deps = {}) {
2223
4560
  if (typeof ctx.inject === 'function') ctx.inject(['webServer'], mountRoutes);
2224
4561
  else if (ctx.webServer) mountRoutes({ webServer: ctx.webServer, effect: (fn) => ctx.effect(fn) });
2225
4562
 
2226
- return { store, state, deliver, install, reconcile, installed, routes, channels, memory, ledger, topics, settings, newTopic, dream, sweep, userSend, openTasks, codexSync, finishTask };
4563
+ /** For tests: which per-Session records this process still keeps for `sessionId`. */
4564
+ const tracked = (sessionId) => ({ trigger: trigger.has(sessionId), answered: answered.has(sessionId), turn: turnState.has(sessionId), delivered: deliveredIds.has(sessionId), history: historyRead.has(sessionId) });
4565
+ 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 };
2227
4566
  }
2228
4567
 
2229
4568
  function serveAvatar(dir, req, res) {