@kadaliao/dsh-bots 0.10.2 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -6,19 +6,15 @@
6
6
  * open-computer-use) and scheduled tasks. One bot is the dispatcher that
7
7
  * delegates work and schedules tasks.
8
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
+ * How bots hand work to each other: `bot_send_message` from a bot's home opens
10
+ * a ticket (lib/tickets.mjs) for the other bot, which works on it in a Session
11
+ * of its own (`ticket-<id>`) and reports back with a status; the dispatcher's
12
+ * home only understands, hands out and reports (its tools are limited and it
13
+ * may not wait), once it has a teammate. At most `tickets.maxWorking` ticket
14
+ * Sessions run at once; the rest queue. A ticket Session's reports go to
15
+ * whoever asked, and asking another bot from it opens a sub-ticket. (The 0.7
16
+ * `hands-on` mode, where messages went into the other bot's home, is gone
17
+ * since 0.11; a message from outside any bot still goes into the bot's home.)
22
18
  *
23
19
  * Everything a bot is made of is applied to its Agent's own scope when that
24
20
  * Agent comes up (and re-applied when the bot changes): a persona prompt
@@ -44,25 +40,30 @@ import { createStore, initialsOf, slugify, SKILL_RE, PALETTE, MAX_SKILLS, MAX_SK
44
40
  import { catalog as appCatalog, CATEGORIES, mcpConfigFor } from './lib/apps.mjs';
45
41
  import { ABILITIES } from './lib/abilities.mjs';
46
42
  import { SKILL_SOURCES, importGithubSkill, importUrlSkill, linkLocalSkill, listGithubSkills, listLocalSkills, mergeImported, parseGithub, readLinkedSkill, resolveLocalPath } from './lib/skills.mjs';
47
- import { TEAMS, teamTiming, teamView } from './lib/teams.mjs';
43
+ import { OLD_LEADS, TEAMS, teamTiming, teamView } from './lib/teams.mjs';
44
+ import { planTeamMigration } from './lib/team-migration.mjs';
48
45
  import { maskedApp, scanExternalMcp } from './lib/mcp-import.mjs';
49
46
  import { createUnfurler } from './lib/unfurl.mjs';
50
47
  import { isLogoName, withLogo } from './lib/logos.mjs';
51
48
  import { askNoticeText, CHANNEL_LABELS, channelEntry, channelIssue, createChannels, credentialsOf, maskBot, threadNote, unmaskApps } from './lib/channels.mjs';
52
49
  import { createActivity } from './lib/activity.mjs';
53
- import { describeTiming, dmBody, dmHeader, noWaitReason, personaText, reportsGoDirect, ROUTER_DENY, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
50
+ import { describeTiming, dmBody, dmHeader, isNoReply, NO_REPLY, noWaitReason, personaText, reportsGoDirect, ROUTER_DENY, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
54
51
  import { createSettings } from './lib/settings.mjs';
55
52
  import { createPriceCatalog, priceOf } from './lib/prices.mjs';
56
53
  import { createLedger, promptTokens, report, ticketUsage, todayByBot, usageRow } from './lib/usage.mjs';
57
54
  import { createSlots, createTickets, parkedOf, REPORT_STATUSES, sessionIdOf, stageOf } from './lib/tickets.mjs';
55
+ import { clampNeedTitle, createNeeds, NEED_ID_RE, needStatus } from './lib/needs.mjs';
58
56
  import { assignmentText, clip, discussionNoteText, failedNoticeText, followUpNoticeText, NEWS_MESSAGES, nudgeText, panelHeaderText, PREVIEW_CHARS, readResource, recoveryNoteText, reminderText, reportRelayText, retryText, shownNoticeText, stalledNoticeText, threadNewsText } from './lib/cards.mjs';
59
- import { checkTickets, isTransient, requesterReminders, retryDelay } from './lib/watchdog.mjs';
57
+ import { checkTickets, isEmptyResponse, isTransient, requesterReminders, retryDelay } from './lib/watchdog.mjs';
60
58
  import { isLiveSubscriber, isPanelThread, isTopicThread, panelThreadKey, panelTopicOf, parseThreadKey, threadLabel, toThreadKey } from './lib/threads.mjs';
61
59
  import { createMemory, dreamBotPrompt, dreamTeamPrompt, KINDS as MEMORY_KINDS, languageOf, looksSecret, parseJsonReply, reflectionPrompt, searchTickets } from './lib/memory.mjs';
62
60
  import { createTopics, rotationReason } from './lib/topics.mjs';
63
61
  import { chatMessageRef, createDiscussions, forkPoint, messageRef, seqByTime } from './lib/discussions.mjs';
64
62
  import { API_KINDS, CODEX_ROUTE, PI_SCOPE, ROUTE_PREFIX, codexAuthFile, createCodexSync, detectLogins, discoverModels, endpointView, keyRefFor, profileFor, readCodexAuth, codexCredential } from './lib/models.mjs';
65
63
 
64
+ /** Team id → English name, for the roster bots read. */
65
+ const TEAM_NAMES = Object.freeze(Object.fromEntries(TEAMS.map((t) => [t.id, t.name.en])));
66
+
66
67
  /**
67
68
  * Import one Harness package: by bare name when this directory resolves it,
68
69
  * else from the running Harness's own module tree (a linked working copy sits
@@ -118,7 +119,7 @@ const AVATAR_ATTEMPTS = 3;
118
119
  /** Errors from a gateway or the network rather than from the request itself. */
119
120
  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;
120
121
 
121
- 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'];
122
+ export const TOOL_NAMES = ['bot_list', 'bot_create', 'bot_update', 'bot_delete', 'bot_send_message', 'bot_reply', 'bot_recall', 'bot_ticket', 'bot_need', 'bot_schedule', 'memory_save', 'memory_forget', 'memory_search'];
122
123
  /** Message ids of the plugin's own deliveries start with this, so a retry can tell it already delivered one. */
123
124
  const MESSAGE_PREFIX = 'bots:';
124
125
  /**
@@ -240,6 +241,8 @@ export function apply(ctx, config, deps = {}) {
240
241
  const memory = createMemory(join(dir, 'memory'));
241
242
  const topics = createTopics(dir);
242
243
  const tickets = createTickets(dir, { now: nowMs });
244
+ // What the person asked for, above the tasks that do it (Bots 0.11).
245
+ const needs = createNeeds(dir, { now: nowMs });
243
246
  // Replies to one message talked over in a forked Session of their own (Bots 0.10).
244
247
  const discussions = createDiscussions(dir, { now: nowMs });
245
248
  // A tasks file that is there but cannot be read stops the plugin now, before anything writes over it.
@@ -266,18 +269,23 @@ export function apply(ctx, config, deps = {}) {
266
269
  const hadBots = store.list().length > 0;
267
270
  const seededFile = join(dir, 'seeded');
268
271
  const zh = /^zh/i.test(String(cfg.language ?? '') || Intl.DateTimeFormat().resolvedOptions().locale || process.env.LANG || '');
272
+ /**
273
+ * The front desk Bots starts with, and the one hiring a team makes when there is no dispatcher:
274
+ * an ordinary bot, renamed and re-described in its profile like any other.
275
+ */
276
+ const deskBot = (zh) => ({
277
+ name: 'Atlas',
278
+ handle: '', // from the name: @atlas, or @atlas-2 when that is taken
279
+ role: 'primary',
280
+ avatar: { kind: 'initials', color: '#7c5cff' },
281
+ bio: zh ? '调度员:拆解需求,分派给合适的 bot,并安排定时任务。 / Dispatcher: plans, delegates, schedules.' : 'Dispatcher: plans the work, hands it to the right bot, and keeps the schedule. / 调度员:拆解、分派、排期。',
282
+ persona: zh
283
+ ? '你沉稳、有条理、说话简洁。你把模糊的需求变成清楚的计划,交给合适的专家 bot,跟进进度,最后用简短的总结向用户汇报。默认用用户使用的语言回答。'
284
+ : 'Calm, organised and brief. You turn vague requests into clear plans, delegate to specialists, follow up, and report back with a short summary. Answer in the language the user writes in.',
285
+ });
269
286
  if (store.list().length === 0 && !existsSync(seededFile)) {
270
287
  try {
271
- store.save({
272
- name: 'Atlas',
273
- handle: 'atlas',
274
- role: 'primary',
275
- avatar: { kind: 'initials', color: '#7c5cff' },
276
- bio: zh ? '调度员:拆解需求,分派给合适的 bot,并安排定时任务。 / Dispatcher: plans, delegates, schedules.' : 'Dispatcher: plans the work, hands it to the right bot, and keeps the schedule. / 调度员:拆解、分派、排期。',
277
- persona: zh
278
- ? '你沉稳、有条理、说话简洁。你把模糊的需求变成清楚的计划,交给合适的专家 bot,跟进进度,最后用简短的总结向用户汇报。默认用用户使用的语言回答。'
279
- : 'Calm, organised and brief. You turn vague requests into clear plans, delegate to specialists, follow up, and report back with a short summary. Answer in the language the user writes in.',
280
- });
288
+ store.save(deskBot(zh));
281
289
  mkdirSync(dir, { recursive: true });
282
290
  writeFileSync(seededFile, String(Date.now()));
283
291
  } catch (error) {
@@ -326,18 +334,16 @@ export function apply(ctx, config, deps = {}) {
326
334
  }
327
335
  /** Whether `sessionId` is `bot`'s home, or a discussion forked from its conversation (it talks to the person like the home). */
328
336
  const isHomeOf = (bot, sessionId) => Boolean(bot && sessionId) && (bot.sessionId === sessionId || discussions.bySession(sessionId)?.botId === bot.id);
329
- const dispatcherMode = () => settings.get().dispatcher;
330
337
  /**
331
- * Router mode is in effect: the setting says so and the dispatcher has someone to hand work to. A
332
- * dispatcher that is the only bot works hands-on (a router alone would have no hands); adding a
333
- * second bot makes it a router, removing the last teammate makes it hands-on again.
338
+ * Router mode is in effect: the dispatcher has someone to hand work to. A dispatcher that is the
339
+ * only bot does the work itself (a router alone would have no hands); adding a second bot makes it
340
+ * a router, removing the last teammate makes it work alone again. Since 0.11 there is no other
341
+ * mode: the 0.7 hands-on dispatcher is gone.
334
342
  */
335
- const routerActive = () => dispatcherMode() === 'router' && store.list().length > 1;
343
+ const routerActive = () => store.list().length > 1;
336
344
  /** The dispatcher works as a router (in its home; its ticket Sessions are ordinary workers). */
337
345
  const isRouter = (bot) => Boolean(bot) && bot.role === 'primary' && routerActive();
338
346
  const isRouterHome = (bot, sessionId) => isRouter(bot) && isHomeOf(bot, sessionId) && !ticketOf(sessionId);
339
- /** Bot-to-bot work opens tickets (router mode), or goes to the other bot's home as in 0.7 (hands-on). */
340
- const ticketsOn = () => dispatcherMode() === 'router';
341
347
 
342
348
  /**
343
349
  * Questions a bot's home or ticket Session put to the person with `ask_user_question`, by id, while
@@ -497,7 +503,7 @@ export function apply(ctx, config, deps = {}) {
497
503
  const roster = store.list();
498
504
  const ticket = ticketId ? tickets.get(ticketId) : undefined;
499
505
  return now
500
- ? personaText(now, roster, { skillsInline, skillNames, apps: appNames, channels: channelNames(roster), dispatcher: routerActive() ? 'router' : 'hands-on', tickets: ticketsOn(), ...(ticket ? { ticket } : {}) })
506
+ ? personaText(now, roster, { skillsInline, skillNames, apps: appNames, channels: channelNames(roster), dispatcher: routerActive() ? 'router' : 'hands-on', tickets: true, teamNames: TEAM_NAMES, ...(ticket ? { ticket } : {}) })
501
507
  : '';
502
508
  },
503
509
  }),
@@ -1520,7 +1526,8 @@ export function apply(ctx, config, deps = {}) {
1520
1526
  store.log({ id, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, thread: panelThreadKey(sid), sid });
1521
1527
  // The panel shows thread replies in the chat: what the person read there since, the main conversation hears first.
1522
1528
  const news = threadNewsFor(bot, sid);
1523
- const header = isRouterHome(bot, sid) ? panelHeaderText({ open: openTasksOf(bot) }, cardCtx()) : '';
1529
+ // The router reads which tasks a message may continue, and the person's open requests (Bots 0.11).
1530
+ const header = isRouterHome(bot, sid) ? [panelHeaderText({ open: openTasksOf(bot) }, cardCtx()), openNeedsLine(bot)].filter(Boolean).join('\n') : '';
1524
1531
  try {
1525
1532
  await sendTo(agent, { content: [news.text, header, body].filter(Boolean).map((text) => ({ type: 'text', text })), source: { kind: 'user' }, mode: homeMode(bot), key: `panel:${id}` });
1526
1533
  } catch (error) {
@@ -1718,6 +1725,131 @@ export function apply(ctx, config, deps = {}) {
1718
1725
  };
1719
1726
  }
1720
1727
 
1728
+ // --- needs: what the person asked for, one level above its tasks (Bots 0.11, lib/needs.mjs) ---
1729
+ /** The top-level ticket a ticket works under (itself for one that is no sub-task). */
1730
+ function rootTicketOf(t) {
1731
+ let cur = t;
1732
+ for (let hops = 0; cur?.parentId && hops < 16; hops += 1) cur = tickets.get(cur.parentId) ?? null;
1733
+ return cur ?? t;
1734
+ }
1735
+ /** The need a ticket (or the task that opened it) counts toward, if any. */
1736
+ const needOfTicket = (t) => (t ? needs.byTicket(rootTicketOf(t).id) : undefined);
1737
+ const needTasks = (n) => n.tickets.map((id) => tickets.get(id)).filter(Boolean);
1738
+ const needStatusOf = (n) => needStatus(n, needTasks(n), stageOf);
1739
+ /** Keep a need's latest status (for when its tasks are pruned). */
1740
+ const refreshNeed = (n) => (n ? needs.snapshot(n.id, needStatusOf(n)) : undefined);
1741
+ // Every change of a task may move its need.
1742
+ tickets.onChange((t) => {
1743
+ try {
1744
+ if (t) refreshNeed(needOfTicket(t));
1745
+ } catch (error) {
1746
+ ctx.logger?.debug?.(`bots: a need's status: ${error?.message ?? error}`);
1747
+ }
1748
+ });
1749
+ /** Needs the dispatcher may add to: open ones, and ones that settled in the last day (a change to a result). */
1750
+ function openNeedsOf(bot) {
1751
+ const since = nowMs() - 24 * 3600_000;
1752
+ return needs.list().filter((n) => (!bot || n.botId === bot.id) && (['waiting', 'working'].includes(needStatusOf(n).status) || n.updatedAt >= since));
1753
+ }
1754
+ /** How the dispatcher reads open needs: `n… "title" (working, 1/3 done)`. */
1755
+ const needPhrase = (n) => {
1756
+ const s = needStatusOf(n);
1757
+ return `${n.id} "${n.title}" (${s.status}${s.total > 1 ? `, ${s.done}/${s.total} done` : ''})`;
1758
+ };
1759
+ /** The line a message to the dispatcher lists its needs in, or ''. */
1760
+ const openNeedsLine = (bot) => {
1761
+ const list = openNeedsOf(bot).slice(0, 8);
1762
+ return list.length ? `Open needs: ${list.map(needPhrase).join('; ')}` : '';
1763
+ };
1764
+ /** A chat message as the person sent it: without the open-needs block the router reads before it. */
1765
+ const withoutNeedsLine = (text) => String(text ?? '').replace(/^Open needs: [^\n]*\n/, '');
1766
+ /** That line as a text block before a chat message, for the router's own conversations only. */
1767
+ const needsNoteFor = (target, sessionId) => {
1768
+ const bot = store.get(target?.id) ?? target;
1769
+ const line = bot && isRouterHome(bot, sessionId) ? openNeedsLine(bot) : '';
1770
+ return line ? [{ type: 'text', text: line }] : [];
1771
+ };
1772
+ /** One need as the panel's board lists it. */
1773
+ function needRow(n) {
1774
+ const s = needStatusOf(n);
1775
+ const list = needTasks(n);
1776
+ // The latest word from its tasks: a question waiting for the person first.
1777
+ const reports = list.flatMap((t) => t.reports.map((r) => ({ ...r, botId: t.botId, ticket: t.id }))).sort((a, b) => a.at - b.at);
1778
+ const asked = s.waiting.length ? reports.filter((r) => s.waiting.includes(r.ticket) && (r.status === 'question' || r.status === 'blocked')).at(-1) : undefined;
1779
+ const latest = asked ?? reports.at(-1);
1780
+ const first = n.asks[0];
1781
+ return {
1782
+ id: n.id,
1783
+ title: n.title,
1784
+ ...(n.auto ? { auto: true } : {}),
1785
+ status: s.status,
1786
+ done: s.done,
1787
+ total: s.total,
1788
+ ...(s.failed ? { failed: s.failed } : {}),
1789
+ ...(s.stalled ? { stalled: s.stalled } : {}),
1790
+ ...(s.waiting.length ? { waiting: s.waiting } : {}),
1791
+ bots: [...new Set(list.map((t) => t.botId))],
1792
+ ...(n.origin?.via ? { via: n.origin.via } : {}),
1793
+ ...(n.origin?.who && n.origin.who !== 'the user' ? { who: n.origin.who } : {}),
1794
+ ...(n.origin?.threadKey ? { threadKey: n.origin.threadKey } : {}),
1795
+ ...(first ? { asked: clip(first.text, 200).text } : {}),
1796
+ ...(latest ? { latest: { status: latest.status, at: latest.at, botId: latest.botId, ticket: latest.ticket, preview: clip(String(latest.text ?? '').trim(), PREVIEW_CHARS).text } } : {}),
1797
+ createdAt: n.createdAt,
1798
+ updatedAt: Math.max(n.updatedAt, ...list.map((t) => t.updatedAt)),
1799
+ ...(s.endedAt ? { endedAt: s.endedAt } : {}),
1800
+ ...(n.closed ? { closed: n.closed } : {}),
1801
+ };
1802
+ }
1803
+ /** One need in full: the row, the person's words, its tasks and what they delivered. */
1804
+ function needView(n) {
1805
+ const list = needTasks(n);
1806
+ const results = list
1807
+ .flatMap((t) => t.reports.filter((r) => r.status === 'done').map((r) => ({ at: r.at, botId: t.botId, ticket: t.id, text: clip(String(r.text ?? ''), 4000).text })))
1808
+ .sort((a, b) => a.at - b.at);
1809
+ return { ...needRow(n), asks: n.asks, tickets: list.map(ticketRow), results };
1810
+ }
1811
+ const needOr404 = (id) => {
1812
+ const n = needs.get(String(id ?? ''));
1813
+ if (!n) throw new Error('no such need');
1814
+ return n;
1815
+ };
1816
+ /** Drop a need: its open tasks stop, and it shows as dropped. */
1817
+ function dropNeed(n, by) {
1818
+ for (const t of needTasks(n)) if (!t.ended) endTicket(t, { by: by === 'user' ? 'user' : 'requester', outcome: 'stopped' });
1819
+ return needs.close(n.id, { by });
1820
+ }
1821
+ /** Where a need was asked, from the task that serves it. */
1822
+ const needOrigin = (t) => ({ ...(t?.origin?.threadKey ? { threadKey: t.origin.threadKey } : {}), via: t?.origin?.via || 'panel', ...(t?.origin?.who ? { who: t.origin.who } : {}) });
1823
+ /**
1824
+ * The need a task the dispatcher opens or adds to counts toward: the one `given` names by id; the
1825
+ * need the task already counts toward (a follow-up: the person's words join it); one this turn made
1826
+ * under the same words (parallel calls); a new one when `given` restates a request; with nothing
1827
+ * given in a turn the person spoke in, one under their own words (marked `auto`). Work nobody asked
1828
+ * for (a teammate's request, a schedule) counts toward none. Undefined then.
1829
+ */
1830
+ function needFor(bot, sessionId, given, t) {
1831
+ const n = needOfTurn(bot, sessionId, given, t);
1832
+ if (n) refreshNeed(n);
1833
+ return n ? needs.get(n.id) : undefined;
1834
+ }
1835
+ function needOfTurn(bot, sessionId, given, t) {
1836
+ const st = turnState.get(sessionId);
1837
+ const asks = st?.asks ?? [];
1838
+ const root = rootTicketOf(t);
1839
+ if (given && NEED_ID_RE.test(given)) return needs.addTicket(needs.get(given).id, root.id, asks);
1840
+ const current = needs.byTicket(root.id);
1841
+ if (current) return needs.addAsks(current.id, asks) ?? current;
1842
+ if (!given && asks.length === 0) return undefined;
1843
+ const title = given ? clampNeedTitle(given) : clampNeedTitle(asks[0].text, 60);
1844
+ const made = st ? (st.needs ??= new Map()) : new Map();
1845
+ const key = given ? title.toLowerCase() : '';
1846
+ const same = made.get(key);
1847
+ if (same && needs.get(same)) return needs.addTicket(same, root.id, asks);
1848
+ const n = needs.create({ title, botId: bot.id, origin: needOrigin(t), asks, tickets: [root.id], ...(given ? {} : { auto: true }) });
1849
+ made.set(key, n.id);
1850
+ return n;
1851
+ }
1852
+
1721
1853
  /** A Thread as a ticket subscribes to it: its key and label (`Slack · Acme #general · thread`). */
1722
1854
  const threadRecordOf = (o) => ({ key: o.threadKey, label: threadLabel(o) });
1723
1855
  /** A ticket's `origin` from one of the turn's Threads; `replyTo`: the chat message that started it, which its answer quotes. */
@@ -2029,6 +2161,15 @@ export function apply(ctx, config, deps = {}) {
2029
2161
  cur = back ?? cur;
2030
2162
  }
2031
2163
  cur = tickets.touch(cur.id, human ? { human: true } : { requester: true }) ?? cur;
2164
+ // The person's own words to a task (a chat follow-up, the panel's task box) join its need (Bots 0.11).
2165
+ if (human && !sender) {
2166
+ try {
2167
+ const n = needOfTicket(cur);
2168
+ if (n) needs.addAsks(n.id, [{ ...(key ? { id: key } : {}), at: nowMs(), text: body, ...(chat?.kind ? { via: chat.kind } : {}), ...(chat?.who ? { who: chat.who } : {}) }]);
2169
+ } catch {
2170
+ // The need is a view; the message goes on.
2171
+ }
2172
+ }
2032
2173
  const who = sender ? `@${sender.handle} (${sender.name})` : 'the user';
2033
2174
  if (!cur.startedAt) {
2034
2175
  cur = tickets.patch(cur.id, { text: `${cur.text}\n\n--- Added by ${who} ---\n${body}` }) ?? cur;
@@ -2326,6 +2467,9 @@ export function apply(ctx, config, deps = {}) {
2326
2467
  function ticketError(t, error) {
2327
2468
  if (!t || t.ended || retryTimers.has(t.id)) return;
2328
2469
  if (error?.name === 'AbortError') return; // stopped on purpose (Harness reports no cancellation here anyway)
2470
+ // Nothing to say, even after Harness's retries (some models end a turn with an empty answer after
2471
+ // a report): the turn ended quietly. The watchdog still asks a task that never reports.
2472
+ if (isEmptyResponse(error)) return;
2329
2473
  // A model failure is an `LlmError` whose `failure` holds the facts (`status`, `message`, `code`).
2330
2474
  const facts = error?.failure && typeof error.failure === 'object' ? error.failure : error;
2331
2475
  const reason = String(facts?.message ?? error?.message ?? error?.error?.message ?? (typeof error === 'string' ? error : '') ?? '').trim() || 'the model call failed';
@@ -2461,6 +2605,7 @@ export function apply(ctx, config, deps = {}) {
2461
2605
  await watch(now);
2462
2606
  tickets.flush();
2463
2607
  tickets.prune();
2608
+ needs.prune();
2464
2609
  await pump();
2465
2610
  }
2466
2611
 
@@ -2471,6 +2616,8 @@ export function apply(ctx, config, deps = {}) {
2471
2616
  let startupDone = null;
2472
2617
  const startup = () => (startupDone ??= recoverTickets()
2473
2618
  .catch((error) => ctx.logger?.warn?.(`bots: task recovery: ${error?.message ?? error}`))
2619
+ .then(() => migrateTeams())
2620
+ .catch((error) => ctx.logger?.warn?.(`bots: team migration: ${error?.message ?? error}`))
2474
2621
  .then(() => pump())
2475
2622
  .catch(() => {}));
2476
2623
  ctx.effect(() => {
@@ -2566,6 +2713,7 @@ export function apply(ctx, config, deps = {}) {
2566
2713
  const note = first ? `${discussionNoteText({})}\n` : '';
2567
2714
  const sent = await sendTo(into.agent, {
2568
2715
  content: [
2716
+ ...needsNoteFor(target, into.agent.session.id),
2569
2717
  { type: 'text', text: `${note}${header}${threadNote(meta.threadKey)}` },
2570
2718
  { type: 'text', text: body },
2571
2719
  ],
@@ -2580,6 +2728,7 @@ export function apply(ctx, config, deps = {}) {
2580
2728
  const agent = await agentOf(store.get(target.id) ?? target);
2581
2729
  const sent = await sendTo(agent, {
2582
2730
  content: [
2731
+ ...needsNoteFor(target, agent.session.id),
2583
2732
  { type: 'text', text: `${header}${threadNote(meta.threadKey)}` },
2584
2733
  { type: 'text', text: body },
2585
2734
  ],
@@ -2723,7 +2872,8 @@ export function apply(ctx, config, deps = {}) {
2723
2872
  st.answers = new Set();
2724
2873
  st.acted = false;
2725
2874
  turnState.set(session.id, st);
2726
- let said = textOf(event.data.content);
2875
+ // The router's list of open needs before a chat message is context, not what the person said.
2876
+ let said = kind === 'user' ? withoutNeedsLine(textOf(event.data.content)) : textOf(event.data.content);
2727
2877
  // A message typed in the panel (Bots 0.9) is logged already; its topic joins the turn's Threads.
2728
2878
  const panelId = kind === 'user' ? /^bots:panel:(p[a-z0-9]{8})$/.exec(id)?.[1] : undefined;
2729
2879
  const typed = panelId ? store.message(panelId) : undefined;
@@ -2751,11 +2901,17 @@ export function apply(ctx, config, deps = {}) {
2751
2901
  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 });
2752
2902
  }
2753
2903
  const thread = via ? via.threadKey : homeThreadOf(session.id);
2904
+ // The person's words in the dispatcher's turn: a need it names now keeps them (Bots 0.11).
2905
+ const asked = (m) => {
2906
+ if (isRouterHome(bot, session.id) && m?.text) st.asks = [...(st.asks ?? []), { id: m.id, at: m.at ?? nowMs(), text: m.text, ...(m.via ? { via: m.via } : {}), ...(m.who ? { who: m.who } : {}) }];
2907
+ };
2754
2908
  if (kind === 'user' && typed) {
2755
2909
  // Logged when it was sent.
2910
+ asked(typed);
2756
2911
  } else if (kind === 'user') {
2757
2912
  const topic = !via && isPanelThread(thread) ? panelTopicOf(thread) : '';
2758
2913
  const logged = store.log(via ? { from: 'user', to: bot.id, text: via.body, kind: 'user', via: via.kind, who: via.who, ...(thread ? { thread } : {}) } : { from: 'user', to: bot.id, text: said, kind: 'user', ...(thread ? { thread } : {}), ...(topic ? { topic } : {}) });
2914
+ asked(logged);
2759
2915
  if (home) {
2760
2916
  const refs = [messageRef(logged.id)];
2761
2917
  // A chat message: by its id in the chat app, and its Thread's latest exchange with the home.
@@ -2778,7 +2934,8 @@ export function apply(ctx, config, deps = {}) {
2778
2934
  if (id && st.reports.has(id)) st.answers.add(id);
2779
2935
  else st.acted = true;
2780
2936
  }
2781
- const text = calls.length > 0 ? '' : textOf(content);
2937
+ // NO_REPLY: the bot had nothing to say (an empty answer is an error in Harness), so nothing is shown or sent.
2938
+ const text = calls.length > 0 || isNoReply(textOf(content)) ? '' : textOf(content);
2782
2939
  const why = trigger.get(session.id);
2783
2940
  // Shown in the bot's chat: what it says to the user. Hidden: acknowledging a schedule notice,
2784
2941
  // the closing words of a turn that answered a bot by DM, and those of a turn whose only inputs
@@ -2832,7 +2989,7 @@ export function apply(ctx, config, deps = {}) {
2832
2989
  const task = openTasks.get(sid);
2833
2990
  if (!task) return;
2834
2991
  for (const b of Array.isArray(msg.content) ? msg.content : []) {
2835
- if (b?.type === 'text' && b.text?.trim()) logLine(task, `[assistant] ${b.text.trim()}`);
2992
+ if (b?.type === 'text' && b.text?.trim() && !isNoReply(b.text)) logLine(task, `[assistant] ${b.text.trim()}`);
2836
2993
  else if (b?.type === 'tool-call') {
2837
2994
  let args = '';
2838
2995
  try {
@@ -2853,7 +3010,10 @@ export function apply(ctx, config, deps = {}) {
2853
3010
  } else if (event.type === 'turn/end') {
2854
3011
  const task = openTasks.get(sid);
2855
3012
  const reason = event.data?.reason?.kind;
2856
- if (task && reason && reason !== 'completed') task.status = reason === 'error' ? 'error' : reason === 'aborted' ? 'stopped' : task.status;
3013
+ // A model that answered with nothing, even after Harness's retries, ended its turn quietly: no error.
3014
+ if (task && reason && reason !== 'completed' && !(reason === 'error' && isEmptyResponse(event.data?.reason?.error ?? event.data?.reason?.failure))) {
3015
+ task.status = reason === 'error' ? 'error' : reason === 'aborted' ? 'stopped' : task.status;
3016
+ }
2857
3017
  settleSoon(sid);
2858
3018
  }
2859
3019
  } catch (error) {
@@ -3471,7 +3631,7 @@ export function apply(ctx, config, deps = {}) {
3471
3631
  if (e?.type === 'assistant/message') {
3472
3632
  const parts = [];
3473
3633
  for (const b of Array.isArray(d.message?.content) ? d.message.content : []) {
3474
- if (b?.type === 'text' && b.text?.trim()) parts.push(`[assistant] ${b.text.trim()}`);
3634
+ if (b?.type === 'text' && b.text?.trim() && !isNoReply(b.text)) parts.push(`[assistant] ${b.text.trim()}`);
3475
3635
  else if (b?.type === 'tool-call') {
3476
3636
  let args = '';
3477
3637
  try {
@@ -3633,12 +3793,13 @@ export function apply(ctx, config, deps = {}) {
3633
3793
  name: 'bot_send_message',
3634
3794
  description: [
3635
3795
  '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.',
3636
- "- 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.",
3796
+ "- To delegate: `to` (the bot's @handle) and `text`. From a bot's own conversation or a task this opens a task (ticket) that the bot works on in a conversation of its own; from elsewhere it 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.",
3637
3797
  '- 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.',
3638
3798
  '- When the dispatcher only routes, a message to it opens no task: it goes into its own conversation, and it passes on to the person what they should know. Work goes to the teammate who does it.',
3639
3799
  '- 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).',
3640
3800
  '- 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`.',
3641
3801
  '- In a task conversation, to report to whoever asked: leave out `to`, give `text` and a `status` (progress, done, blocked, question).',
3802
+ '- The dispatcher names the person\'s request a task serves with `need`: a short restatement for a new request, or the id of a need already open.',
3642
3803
  ].join('\n'),
3643
3804
  parameters: {
3644
3805
  to: { type: 'string', description: '@handle (or id / name) of the bot. Leave it out to report on your own task.' },
@@ -3648,6 +3809,7 @@ export function apply(ctx, config, deps = {}) {
3648
3809
  title: { type: 'string', description: 'A short title for a new task; taken from the first line of text when left out.' },
3649
3810
  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.' },
3650
3811
  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.' },
3812
+ need: { type: 'string', description: 'Dispatcher only: the person\'s request this task serves. For a new request, restate it for the person in one short line in their language, saying what they get (not who does it); tasks for the same request pass the same line or the need id the first call returned. For more work on an open need ("Open needs: …"), its id (n…).' },
3651
3813
  },
3652
3814
  output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ to: v.to, from: v.from, ...(v.ticket ? { ticket: v.ticket } : {}) }) },
3653
3815
  isConcurrencySafe: () => true,
@@ -3671,16 +3833,24 @@ export function apply(ctx, config, deps = {}) {
3671
3833
  status === 'progress'
3672
3834
  ? `Recorded on task ${ticket.id}; progress does not interrupt whoever asked. Go on with the work.`
3673
3835
  : shown
3674
- ? `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.'}`
3836
+ ? `Shown to the person as it is, in ${shown.where}${to ? `; @${to.handle} is told` : ''}.${status === 'done' ? ` The task is done: end your turn with only ${NO_REPLY}.` : ` Their answer will arrive here by itself; end your turn now with only ${NO_REPLY}.`}`
3675
3837
  : unread
3676
- ? `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.`
3677
- : `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.'}`;
3838
+ ? `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 with only ${NO_REPLY}.`
3839
+ : `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 with only ${NO_REPLY}.` : ` An answer will arrive here by itself; end your turn now with only ${NO_REPLY}.`}`;
3678
3840
  return { ok: true, text: said, ticket: row(ticket), to: face(to), from: face(sender) };
3679
3841
  }
3680
3842
  }
3681
3843
  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');
3682
3844
 
3683
3845
  const chosen = typeof args.thread === 'string' && args.thread.trim() !== '' ? threadRef(args.thread, sessionId) : '';
3846
+ // The person's request it serves (Bots 0.11): only the dispatcher's own conversation names one.
3847
+ const routing = Boolean(sender) && !mine && isRouterHome(sender, sessionId);
3848
+ const needArg = routing ? String(args.need ?? '').trim().replace(/^need\//, '') : '';
3849
+ if (needArg && NEED_ID_RE.test(needArg) && !needs.get(needArg)) {
3850
+ const open = openNeedsOf(sender).map((n) => n.id);
3851
+ throw new Error(`no need ${needArg}${open.length ? `; open needs: ${open.join(', ')}` : ''}. For a new request, pass a short line restating it instead`);
3852
+ }
3853
+ const needText = (n) => (n ? ` It counts toward need ${n.id} ("${n.title}")${n.auto ? '; pass `need` with a short restatement to name it for the person' : ''}.` : '');
3684
3854
  // Adding to an existing ticket.
3685
3855
  if (wantTicket) {
3686
3856
  const t = tickets.get(wantTicket);
@@ -3697,7 +3867,8 @@ export function apply(ctx, config, deps = {}) {
3697
3867
  const target = store.get(next.botId);
3698
3868
  const waits = next.startedAt && parkedOf(next).length > 0 ? ': every worker slot is taken, so it is handed over when one frees' : '';
3699
3869
  const after = reportsGoDirect(next) ? `${handleOf(next.botId)} answers the person ${isPanelThread(next.showIn ?? next.origin?.threadKey) ? 'in the panel' : 'in the chat'} itself` : `${handleOf(next.botId)}'s report will arrive here by itself`;
3700
- return { ok: true, text: `Added to task ${next.id} (${stageOf(next)}${waits}). ${after}; do not wait for it.`, ticket: row(next), to: face(target), from: face(sender) };
3870
+ const need = routing ? needFor(sender, sessionId, needArg, next) : undefined;
3871
+ return { ok: true, text: `Added to task ${next.id} (${stageOf(next)}${waits}). ${after}; do not wait for it.${needText(need)}`, ticket: row(next), ...(need ? { need: { id: need.id, title: need.title } } : {}), to: face(target), from: face(sender) };
3701
3872
  }
3702
3873
  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`');
3703
3874
 
@@ -3714,9 +3885,10 @@ export function apply(ctx, config, deps = {}) {
3714
3885
  }
3715
3886
 
3716
3887
  // A new ticket: from a task conversation (a sub-task), or from a bot's home when tasks are on.
3717
- if (sender && sessionId && (mine || (ticketsOn() && isHomeOf(sender, sessionId)))) {
3888
+ if (sender && sessionId && (mine || isHomeOf(sender, sessionId))) {
3718
3889
  const relay = String(args.report_to ?? '').trim().toLowerCase() === 'me';
3719
3890
  const t = await openTicket(sender, named, args.text, sessionId, { title: args.title, thread: chosen, relay });
3891
+ const need = routing ? needFor(sender, sessionId, needArg, t) : undefined;
3720
3892
  const stage = stageOf(t);
3721
3893
  const who = named.id === sender.id ? 'yourself' : `@${named.handle}`;
3722
3894
  const answer = reportsGoDirect(t)
@@ -3725,10 +3897,10 @@ export function apply(ctx, config, deps = {}) {
3725
3897
  const said =
3726
3898
  stage === 'failed'
3727
3899
  ? `Task ${t.id} for ${who} could not start: ${t.error ?? 'unknown error'}.`
3728
- : `Opened task ${t.id} for ${who} (${stage === 'queued' ? 'queued: it starts when another task finishes' : stage}). ${answer}`;
3729
- return { ok: stage !== 'failed', text: said, ticket: row(t), stage, to: face(named), from: face(sender) };
3900
+ : `Opened task ${t.id} for ${who} (${stage === 'queued' ? 'queued: it starts when another task finishes' : stage}). ${answer}${needText(need)}`;
3901
+ return { ok: stage !== 'failed', text: said, ticket: row(t), stage, ...(need ? { need: { id: need.id, title: need.title } } : {}), to: face(named), from: face(sender) };
3730
3902
  }
3731
- // 0.7: into the other bot's home (the user from any conversation; any home in hands-on mode).
3903
+ // Into the other bot's home: the user, from a conversation that belongs to no bot.
3732
3904
  if (chosen) throw new Error('`thread` is for opening a task; this message goes to the bot\'s own conversation, so leave it out');
3733
3905
  await deliver(sender ?? null, named, args.text, sessionId);
3734
3906
  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) };
@@ -3792,12 +3964,24 @@ export function apply(ctx, config, deps = {}) {
3792
3964
  description:
3793
3965
  '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.',
3794
3966
  parameters: {
3795
- ref: { type: 'string', required: true, description: 'tickets, ticket/<id>, ticket/<id>/text, ticket/<id>/reports, ticket/<id>/transcript, thread/<key> or bot/<handle>.' },
3967
+ ref: { type: 'string', required: true, description: 'tickets, ticket/<id>, ticket/<id>/text, ticket/<id>/reports, ticket/<id>/transcript, thread/<key>, bot/<handle>, needs or need/<id>.' },
3796
3968
  offset: { type: 'number', description: 'Where the next page starts: the `next_offset` of the last one.' },
3797
3969
  },
3798
3970
  output: { schema: anyValue, render: (_a, v) => text(v.text) },
3799
3971
  isConcurrencySafe: () => true,
3800
3972
  execute: async (args, exec) => {
3973
+ const ref = String(args.ref ?? '').trim();
3974
+ // The person's requests (Bots 0.11): what each asked for and how far it got.
3975
+ if (ref === 'needs' || /^need\/n[a-z0-9]{8}$/.test(ref)) {
3976
+ if (ref === 'needs') {
3977
+ const items = needs.list().slice(0, 30).map((n) => ({ id: n.id, title: n.title, ...needStatusOf(n), tasks: n.tickets }));
3978
+ return { ok: true, items, text: JSON.stringify({ needs: items }, null, 1) };
3979
+ }
3980
+ const n = needs.get(ref.slice(5));
3981
+ if (!n) throw new Error(`no ${ref}`);
3982
+ const v = { ...needRow(n), asks: n.asks.map((a) => ({ at: a.at, text: a.text })), tasks: n.tickets };
3983
+ return { ok: true, ...v, text: JSON.stringify(v, null, 1) };
3984
+ }
3801
3985
  const result = await readResource(String(args.ref ?? ''), {
3802
3986
  viewer: viewerOf(actorOf(exec)),
3803
3987
  tickets,
@@ -3864,6 +4048,43 @@ export function apply(ctx, config, deps = {}) {
3864
4048
  return { ok: true, text: said, ticket: ticketRow(tickets.get(next.id) ?? next) };
3865
4049
  },
3866
4050
  }),
4051
+ defineTool({
4052
+ name: 'bot_need',
4053
+ description:
4054
+ 'Keep the person\'s requests (needs) as they mean them; the panel shows each with how far its tasks got. `rename` one when they change what they want (`title`: the new short line), `merge` one into another when two turn out to be the same request (`into`: the need that stays), `drop` one when they no longer want it (its open tasks stop). `bot_recall` with `needs` lists them.',
4055
+ parameters: {
4056
+ need: { type: 'string', required: true, description: 'The need id (n…).' },
4057
+ action: { type: 'string', required: true, enum: ['rename', 'merge', 'drop'] },
4058
+ title: { type: 'string', description: 'For rename: the request restated in one short line, in the person\'s language.' },
4059
+ into: { type: 'string', description: 'For merge: the id of the need that takes this one\'s tasks.' },
4060
+ },
4061
+ output: { schema: anyValue, render: (_a, v) => text(v.text) },
4062
+ execute: async (args, exec) => {
4063
+ const { sessionId, bot: sender } = actor(exec);
4064
+ if (sender && !isRouterHome(sender, sessionId)) throw new Error('only the dispatcher keeps the person\'s needs; report on your task instead');
4065
+ const n = needs.get(String(args.need ?? '').trim());
4066
+ if (!n) throw new Error(`no need ${String(args.need ?? '').trim()}. bot_recall {"ref":"needs"} lists them.`);
4067
+ const action = String(args.action ?? '').trim().toLowerCase();
4068
+ let next;
4069
+ let said;
4070
+ if (action === 'rename') {
4071
+ if (!String(args.title ?? '').trim()) throw new Error('rename needs a `title`');
4072
+ next = needs.rename(n.id, args.title);
4073
+ said = `Need ${n.id} is now "${next.title}".`;
4074
+ } else if (action === 'merge') {
4075
+ const into = needs.get(String(args.into ?? '').trim());
4076
+ if (!into) throw new Error('merge needs `into`: the id of the need that stays');
4077
+ if (into.id === n.id) throw new Error('a need cannot be merged into itself');
4078
+ next = needs.merge(n.id, into.id);
4079
+ said = `Merged need ${n.id} into ${next.id} ("${next.title}"): its tasks count toward that one now.`;
4080
+ } else if (action === 'drop') {
4081
+ const open = needTasks(n).filter((t) => !t.ended).length;
4082
+ next = dropNeed(n, sender ? 'dispatcher' : 'user');
4083
+ said = `Dropped need ${n.id} ("${n.title}")${open ? `; stopped its ${open} open task${open > 1 ? 's' : ''}` : ''}.`;
4084
+ } else throw new Error('action is one of rename, merge, drop');
4085
+ return { ok: true, text: said, need: needRow(next) };
4086
+ },
4087
+ }),
3867
4088
  defineTool({
3868
4089
  name: 'bot_schedule',
3869
4090
  description:
@@ -4425,9 +4646,13 @@ export function apply(ctx, config, deps = {}) {
4425
4646
  limits: { skills: MAX_SKILLS, skillsOn: MAX_SKILLS_ON },
4426
4647
  teamNotes: memory.notes('team').length,
4427
4648
  dispatcher: s.dispatcher,
4428
- // The setting asks for a router, and the dispatcher has a teammate to hand work to: it routes now.
4649
+ // The dispatcher has a teammate to hand work to: it routes now.
4429
4650
  routerActive: routerActive(),
4651
+ // The person's requests (Bots 0.11): how many wait for them, and how many are being worked on.
4652
+ needs: needCounts(),
4430
4653
  routerNoticePending: s.routerNotice === 'pending',
4654
+ // Leads of teams hired before 0.11.1 that only pass messages on now: offered once for removal.
4655
+ oldLeads: s.leadNotice === 'dismissed' ? [] : oldLeads().map((b) => ({ id: b.id, name: b.name, handle: b.handle, team: b.team })),
4431
4656
  // A task whose conversation waits for an answer to its question needs you too (its row says `asking`).
4432
4657
  attention: live.filter((t) => needsPerson(t) || askingIn(t.sessionId)).sort((a, b) => b.updatedAt - a.updatedAt).slice(0, 50).map(ticketRow),
4433
4658
  asks: waiting.sort((a, b) => a.at - b.at).map(askView),
@@ -4500,6 +4725,45 @@ export function apply(ctx, config, deps = {}) {
4500
4725
  }
4501
4726
 
4502
4727
  // --- teams -------------------------------------------------------------------------
4728
+ /**
4729
+ * Teams hired from the 0.3–0.11.0 templates, brought to the current ones (lib/team-migration.mjs):
4730
+ * personas and bios still as hired, the dispatcher's lead skills and apps, and the team routine,
4731
+ * which moves to the dispatcher. At every start; nothing left to do after the first. Runs one at
4732
+ * a time, so two calls never move a task twice.
4733
+ */
4734
+ let migrating = Promise.resolve();
4735
+ function migrateTeams() {
4736
+ const run = migrating.then(migrateTeamsNow, migrateTeamsNow);
4737
+ migrating = run.catch(() => {});
4738
+ return run;
4739
+ }
4740
+ async function migrateTeamsNow() {
4741
+ const desk = store.primary() ?? null;
4742
+ let entries = [];
4743
+ let scheduled = true;
4744
+ try {
4745
+ entries = await schedulesOf(null);
4746
+ } catch {
4747
+ scheduled = false; // No schedule service: the bots still change, their tasks wait for a start that has one.
4748
+ }
4749
+ const plan = planTeamMigration({ bots: store.list(), entries, deskId: desk?.id ?? null, deskText: (lang) => deskBot(lang === 'zh') });
4750
+ for (const { id, patch } of plan.bots) store.save({ id, ...patch });
4751
+ if (scheduled) {
4752
+ for (const { id, prompt } of plan.edits) await scheduleSave(null, { id, prompt });
4753
+ for (const m of plan.moves) {
4754
+ // Made on the dispatcher first: a failure leaves the task where it was, not gone.
4755
+ await scheduleSave(store.get(desk.id), { title: m.title, prompt: m.prompt, timing: m.timing });
4756
+ await schedule().edit({ id: m.id, action: 'delete' });
4757
+ }
4758
+ for (const id of plan.drops) await schedule().edit({ id, action: 'delete' });
4759
+ }
4760
+ const done = plan.bots.length + (scheduled ? plan.edits.length + plan.moves.length + plan.drops.length : 0);
4761
+ if (done) ctx.logger?.info?.(`bots: brought ${plan.bots.length} team bot(s) and ${done - plan.bots.length} scheduled task(s) to the 0.11.1 templates`);
4762
+ return plan;
4763
+ }
4764
+
4765
+ /** Bots hired as a team's lead before 0.11.1 that are not the dispatcher: they only pass messages on. */
4766
+ const oldLeads = () => store.list().filter((b) => b.role !== 'primary' && b.team && OLD_LEADS[b.team] === b.handle);
4503
4767
  async function teamsView() {
4504
4768
  const names = new Set((await dshSkills()).map((x) => x.name));
4505
4769
  const appIds = new Set(templates().map((t) => t.id));
@@ -4508,14 +4772,19 @@ export function apply(ctx, config, deps = {}) {
4508
4772
 
4509
4773
  /**
4510
4774
  * Hire a team: create its bots (handles made unique), attach the Harness skills it has,
4511
- * import the GitHub skills it names, add its apps (left for the user to fill keys),
4512
- * schedule its tasks, and make its lead the dispatcher. Returns what was skipped.
4775
+ * import the GitHub skills it names, add its apps (left for the user to fill keys), and
4776
+ * schedule its tasks. A team has no lead (0.11.1): its work goes through the one dispatcher,
4777
+ * made first when there is none, which gets the team's `desk` tasks (one it already has by
4778
+ * that title is not added twice). Returns what was made and what was skipped.
4513
4779
  */
4514
- async function hireTeam(teamId, lang, { primary = true } = {}) {
4780
+ async function hireTeam(teamId, lang) {
4515
4781
  const team = TEAMS.find((t) => t.id === teamId);
4516
4782
  if (!team) throw new Error(`no team "${teamId}"`);
4517
4783
  const zh = lang === 'zh';
4518
4784
  const pick = (v) => (zh ? v.zh : v.en);
4785
+ // Before any member: on an empty roster the first bot saved would become the dispatcher.
4786
+ const hadDesk = store.primary();
4787
+ const desk = hadDesk ?? store.save(deskBot(zh), { createdBy: 'user' });
4519
4788
  const have = new Map((await dshSkills()).map((x) => [x.name, x.description]));
4520
4789
  const tpl = templates();
4521
4790
  const created = [];
@@ -4549,8 +4818,8 @@ export function apply(ctx, config, deps = {}) {
4549
4818
  const deny = [];
4550
4819
  // Team bots never need to reconfigure Harness itself; plugin management starts off.
4551
4820
  for (const off of [...new Set([...(b.off ?? []), 'plugins'])]) for (const t of ABILITIES.find((a) => a.id === off)?.tools ?? []) deny.push(t);
4552
- // The seeded dispatcher (or any bot with this handle that is not in another team) becomes this member.
4553
- const existing = store.list().find((x) => x.handle === b.handle && (!x.team || x.team === team.id));
4821
+ // Hiring a team again updates its members; a bot of yours with the same handle is left alone.
4822
+ const existing = store.list().find((x) => x.handle === b.handle && x.team === team.id);
4554
4823
  const bot = store.save(
4555
4824
  {
4556
4825
  ...(existing ? { id: existing.id, skills: [...existing.skills.filter((x) => !skills.some((y) => y.name === x.name)), ...skills], apps: [...existing.apps.filter((x) => !apps.some((y) => y.serverName === x.serverName)), ...apps] } : {}),
@@ -4560,7 +4829,7 @@ export function apply(ctx, config, deps = {}) {
4560
4829
  persona: pick(b.persona),
4561
4830
  // Same letters in both languages: from the English name ("Atlas" → AT), not "Atlas 幕僚长".
4562
4831
  avatar: { kind: 'initials', text: initialsOf(b.name.en), color: b.color },
4563
- role: b.role === 'primary' && primary ? 'primary' : existing?.role === 'primary' ? 'primary' : 'bot',
4832
+ role: existing?.role === 'primary' ? 'primary' : 'bot',
4564
4833
  ...(existing ? {} : { skills, apps }),
4565
4834
  tools: { deny },
4566
4835
  team: team.id,
@@ -4570,17 +4839,24 @@ export function apply(ctx, config, deps = {}) {
4570
4839
  created.push({ bot, spec: b });
4571
4840
  }
4572
4841
  // Scheduled tasks need each bot's conversation; create them after all bots exist.
4573
- for (const { bot, spec } of created) {
4574
- for (const task of spec.tasks ?? []) {
4575
- try {
4576
- await scheduleSave(bot, { title: pick(task.title), prompt: pick(task.prompt), timing: teamTiming(task.when, zone) });
4577
- } catch (error) {
4578
- skipped.push({ bot: bot.handle, kind: 'schedule', name: pick(task.title), reason: error?.message ?? String(error) });
4579
- }
4842
+ const deskTitles = new Set();
4843
+ if (hadDesk && team.desk?.length) {
4844
+ try {
4845
+ for (const e of await schedulesOf(desk)) deskTitles.add(e.title);
4846
+ } catch {
4847
+ // No schedule service: saving says so below.
4580
4848
  }
4581
4849
  }
4582
- const lead = created.find((c) => c.spec.role === 'primary')?.bot;
4583
- return { team: team.id, bots: created.map((c) => store.get(c.bot.id)), leadId: lead?.id ?? null, kickoff: pick(team.kickoff), skipped };
4850
+ const jobs = [...created.flatMap(({ bot, spec }) => (spec.tasks ?? []).map((task) => ({ bot, task }))), ...(team.desk ?? []).filter((task) => !deskTitles.has(pick(task.title))).map((task) => ({ bot: desk, task }))];
4851
+ for (const { bot, task } of jobs) {
4852
+ try {
4853
+ await scheduleSave(store.get(bot.id) ?? bot, { title: pick(task.title), prompt: pick(task.prompt), timing: teamTiming(task.when, zone) });
4854
+ } catch (error) {
4855
+ skipped.push({ bot: bot.handle, kind: 'schedule', name: pick(task.title), reason: error?.message ?? String(error) });
4856
+ }
4857
+ }
4858
+ const bots = [...(hadDesk ? [] : [desk]), ...created.map((c) => c.bot)].map((b) => store.get(b.id));
4859
+ return { team: team.id, bots, dispatcherId: desk.id, kickoff: pick(team.kickoff), skipped };
4584
4860
  }
4585
4861
 
4586
4862
  const unfurlLink = createUnfurler();
@@ -4588,7 +4864,7 @@ export function apply(ctx, config, deps = {}) {
4588
4864
  teams: { get: () => teamsView() },
4589
4865
  'teams/hire': {
4590
4866
  post: async (body) => {
4591
- const r = await hireTeam(String(body.id ?? ''), body.lang === 'zh' ? 'zh' : 'en', { primary: body.primary !== false });
4867
+ const r = await hireTeam(String(body.id ?? ''), body.lang === 'zh' ? 'zh' : 'en');
4592
4868
  return { ok: true, ...r, bots: r.bots.map(publicBot) };
4593
4869
  },
4594
4870
  },
@@ -4810,8 +5086,8 @@ export function apply(ctx, config, deps = {}) {
4810
5086
  const patch = body.patch && typeof body.patch === 'object' ? { ...body.patch } : {};
4811
5087
  delete patch.codex;
4812
5088
  delete patch.prices;
4813
- // Picking a dispatcher mode is having seen the notice about it.
4814
- if (patch.dispatcher !== undefined) patch.routerNotice = 'dismissed';
5089
+ // The dispatcher always routes (0.11): there is no mode to pick.
5090
+ delete patch.dispatcher;
4815
5091
  const saved = settings.save(patch);
4816
5092
  settingsChanged();
4817
5093
  return { ok: true, settings: saved };
@@ -4819,8 +5095,11 @@ export function apply(ctx, config, deps = {}) {
4819
5095
  },
4820
5096
  // The one-time notice that an upgraded team's dispatcher now routes: dismissed for good.
4821
5097
  'router-notice/dismiss': { post: () => (settings.save({ routerNotice: 'dismissed' }), { ok: true, routerNoticePending: false }) },
5098
+ 'lead-notice/dismiss': { post: () => (settings.save({ leadNotice: 'dismissed' }), { ok: true, oldLeads: [] }) },
4822
5099
  // Tasks (tickets), PLAN-0.8 §6.3. `tickets/:id…` and `threads/:key` are under `paramRoutes`.
4823
5100
  tickets: { get: (url) => ticketList(url) },
5101
+ // The person's requests (Bots 0.11). `needs/:id…` is under `paramRoutes`.
5102
+ needs: { get: (url) => needList(url) },
4824
5103
  memory: { get: (url) => memoryView(url.searchParams.get('bot') ?? 'team') },
4825
5104
  'memory/put': {
4826
5105
  post: (body) => {
@@ -4969,8 +5248,51 @@ export function apply(ctx, config, deps = {}) {
4969
5248
  if (!t) throw new Error('no such task');
4970
5249
  return t;
4971
5250
  };
4972
- /** Routes with a path parameter: `tickets/<id>[/<action>]`, `threads/<key>` (the key URI-encoded). */
5251
+ /** GET /needs: the person's requests, newest first (`status` filters: waiting,working,…). */
5252
+ function needList(url) {
5253
+ const want = (url.searchParams.get('status') ?? '').split(',').map((x) => x.trim()).filter(Boolean);
5254
+ const limit = Math.min(300, Math.max(1, Math.floor(Number(url.searchParams.get('limit')) || 100)));
5255
+ const offset = Math.max(0, Math.floor(Number(url.searchParams.get('offset')) || 0));
5256
+ const rows = needs.list().map(needRow).filter((r) => !want.length || want.includes(r.status)).sort((a, b) => b.updatedAt - a.updatedAt);
5257
+ return { items: rows.slice(offset, offset + limit), next_offset: offset + limit < rows.length ? offset + limit : null };
5258
+ }
5259
+ /** How many of the person's requests wait for them (a question, or not done: the board's first group), and how many are being worked on. */
5260
+ function needCounts() {
5261
+ const out = { waiting: 0, working: 0 };
5262
+ try {
5263
+ for (const n of needs.list()) {
5264
+ const st = needStatusOf(n).status;
5265
+ if (st === 'waiting' || st === 'failed') out.waiting += 1;
5266
+ else if (st === 'working') out.working += 1;
5267
+ }
5268
+ } catch {
5269
+ // The rail does without.
5270
+ }
5271
+ return out;
5272
+ }
5273
+ /** Routes with a path parameter: `tickets/<id>[/<action>]`, `needs/<id>[/<action>]`, `threads/<key>` (the key URI-encoded). */
4973
5274
  const paramRoutes = {
5275
+ needs: {
5276
+ get: (rest) => {
5277
+ if (rest.length !== 1) throw new Error('no such route');
5278
+ return needView(needOr404(rest[0]));
5279
+ },
5280
+ post: (rest, body) => {
5281
+ const [id, action] = rest;
5282
+ const n = needOr404(id);
5283
+ switch (action) {
5284
+ case 'rename': {
5285
+ const next = needs.rename(n.id, body.title);
5286
+ if (!next) throw new Error('a need needs a title');
5287
+ return { ok: true, ...needView(next) };
5288
+ }
5289
+ case 'drop':
5290
+ return { ok: true, ...needView(dropNeed(n, 'user')) };
5291
+ default:
5292
+ throw new Error('no such route');
5293
+ }
5294
+ },
5295
+ },
4974
5296
  tickets: {
4975
5297
  get: (rest) => {
4976
5298
  if (rest.length !== 1) throw new Error('no such route');
@@ -5066,7 +5388,7 @@ export function apply(ctx, config, deps = {}) {
5066
5388
 
5067
5389
  /** For tests: which per-Session records this process still keeps for `sessionId`. */
5068
5390
  const tracked = (sessionId) => ({ trigger: trigger.has(sessionId), answered: answered.has(sessionId), turn: turnState.has(sessionId), delivered: deliveredIds.has(sessionId), history: historyRead.has(sessionId) });
5069
- 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 };
5391
+ 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, migrateTeams };
5070
5392
  }
5071
5393
 
5072
5394
  function serveAvatar(dir, req, res) {