@kadaliao/dsh-bots 0.11.0 → 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
@@ -40,7 +40,8 @@ import { createStore, initialsOf, slugify, SKILL_RE, PALETTE, MAX_SKILLS, MAX_SK
40
40
  import { catalog as appCatalog, CATEGORIES, mcpConfigFor } from './lib/apps.mjs';
41
41
  import { ABILITIES } from './lib/abilities.mjs';
42
42
  import { SKILL_SOURCES, importGithubSkill, importUrlSkill, linkLocalSkill, listGithubSkills, listLocalSkills, mergeImported, parseGithub, readLinkedSkill, resolveLocalPath } from './lib/skills.mjs';
43
- 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';
44
45
  import { maskedApp, scanExternalMcp } from './lib/mcp-import.mjs';
45
46
  import { createUnfurler } from './lib/unfurl.mjs';
46
47
  import { isLogoName, withLogo } from './lib/logos.mjs';
@@ -60,6 +61,9 @@ import { createTopics, rotationReason } from './lib/topics.mjs';
60
61
  import { chatMessageRef, createDiscussions, forkPoint, messageRef, seqByTime } from './lib/discussions.mjs';
61
62
  import { API_KINDS, CODEX_ROUTE, PI_SCOPE, ROUTE_PREFIX, codexAuthFile, createCodexSync, detectLogins, discoverModels, endpointView, keyRefFor, profileFor, readCodexAuth, codexCredential } from './lib/models.mjs';
62
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
+
63
67
  /**
64
68
  * Import one Harness package: by bare name when this directory resolves it,
65
69
  * else from the running Harness's own module tree (a linked working copy sits
@@ -265,18 +269,23 @@ export function apply(ctx, config, deps = {}) {
265
269
  const hadBots = store.list().length > 0;
266
270
  const seededFile = join(dir, 'seeded');
267
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
+ });
268
286
  if (store.list().length === 0 && !existsSync(seededFile)) {
269
287
  try {
270
- store.save({
271
- name: 'Atlas',
272
- handle: 'atlas',
273
- role: 'primary',
274
- avatar: { kind: 'initials', color: '#7c5cff' },
275
- bio: zh ? '调度员:拆解需求,分派给合适的 bot,并安排定时任务。 / Dispatcher: plans, delegates, schedules.' : 'Dispatcher: plans the work, hands it to the right bot, and keeps the schedule. / 调度员:拆解、分派、排期。',
276
- persona: zh
277
- ? '你沉稳、有条理、说话简洁。你把模糊的需求变成清楚的计划,交给合适的专家 bot,跟进进度,最后用简短的总结向用户汇报。默认用用户使用的语言回答。'
278
- : '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.',
279
- });
288
+ store.save(deskBot(zh));
280
289
  mkdirSync(dir, { recursive: true });
281
290
  writeFileSync(seededFile, String(Date.now()));
282
291
  } catch (error) {
@@ -494,7 +503,7 @@ export function apply(ctx, config, deps = {}) {
494
503
  const roster = store.list();
495
504
  const ticket = ticketId ? tickets.get(ticketId) : undefined;
496
505
  return now
497
- ? personaText(now, roster, { skillsInline, skillNames, apps: appNames, channels: channelNames(roster), dispatcher: routerActive() ? 'router' : 'hands-on', tickets: true, ...(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 } : {}) })
498
507
  : '';
499
508
  },
500
509
  }),
@@ -2607,6 +2616,8 @@ export function apply(ctx, config, deps = {}) {
2607
2616
  let startupDone = null;
2608
2617
  const startup = () => (startupDone ??= recoverTickets()
2609
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}`))
2610
2621
  .then(() => pump())
2611
2622
  .catch(() => {}));
2612
2623
  ctx.effect(() => {
@@ -4640,6 +4651,8 @@ export function apply(ctx, config, deps = {}) {
4640
4651
  // The person's requests (Bots 0.11): how many wait for them, and how many are being worked on.
4641
4652
  needs: needCounts(),
4642
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 })),
4643
4656
  // A task whose conversation waits for an answer to its question needs you too (its row says `asking`).
4644
4657
  attention: live.filter((t) => needsPerson(t) || askingIn(t.sessionId)).sort((a, b) => b.updatedAt - a.updatedAt).slice(0, 50).map(ticketRow),
4645
4658
  asks: waiting.sort((a, b) => a.at - b.at).map(askView),
@@ -4712,6 +4725,45 @@ export function apply(ctx, config, deps = {}) {
4712
4725
  }
4713
4726
 
4714
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);
4715
4767
  async function teamsView() {
4716
4768
  const names = new Set((await dshSkills()).map((x) => x.name));
4717
4769
  const appIds = new Set(templates().map((t) => t.id));
@@ -4720,14 +4772,19 @@ export function apply(ctx, config, deps = {}) {
4720
4772
 
4721
4773
  /**
4722
4774
  * Hire a team: create its bots (handles made unique), attach the Harness skills it has,
4723
- * import the GitHub skills it names, add its apps (left for the user to fill keys),
4724
- * 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.
4725
4779
  */
4726
- async function hireTeam(teamId, lang, { primary = true } = {}) {
4780
+ async function hireTeam(teamId, lang) {
4727
4781
  const team = TEAMS.find((t) => t.id === teamId);
4728
4782
  if (!team) throw new Error(`no team "${teamId}"`);
4729
4783
  const zh = lang === 'zh';
4730
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' });
4731
4788
  const have = new Map((await dshSkills()).map((x) => [x.name, x.description]));
4732
4789
  const tpl = templates();
4733
4790
  const created = [];
@@ -4761,8 +4818,8 @@ export function apply(ctx, config, deps = {}) {
4761
4818
  const deny = [];
4762
4819
  // Team bots never need to reconfigure Harness itself; plugin management starts off.
4763
4820
  for (const off of [...new Set([...(b.off ?? []), 'plugins'])]) for (const t of ABILITIES.find((a) => a.id === off)?.tools ?? []) deny.push(t);
4764
- // The seeded dispatcher (or any bot with this handle that is not in another team) becomes this member.
4765
- 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);
4766
4823
  const bot = store.save(
4767
4824
  {
4768
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] } : {}),
@@ -4772,7 +4829,7 @@ export function apply(ctx, config, deps = {}) {
4772
4829
  persona: pick(b.persona),
4773
4830
  // Same letters in both languages: from the English name ("Atlas" → AT), not "Atlas 幕僚长".
4774
4831
  avatar: { kind: 'initials', text: initialsOf(b.name.en), color: b.color },
4775
- role: b.role === 'primary' && primary ? 'primary' : existing?.role === 'primary' ? 'primary' : 'bot',
4832
+ role: existing?.role === 'primary' ? 'primary' : 'bot',
4776
4833
  ...(existing ? {} : { skills, apps }),
4777
4834
  tools: { deny },
4778
4835
  team: team.id,
@@ -4782,17 +4839,24 @@ export function apply(ctx, config, deps = {}) {
4782
4839
  created.push({ bot, spec: b });
4783
4840
  }
4784
4841
  // Scheduled tasks need each bot's conversation; create them after all bots exist.
4785
- for (const { bot, spec } of created) {
4786
- for (const task of spec.tasks ?? []) {
4787
- try {
4788
- await scheduleSave(bot, { title: pick(task.title), prompt: pick(task.prompt), timing: teamTiming(task.when, zone) });
4789
- } catch (error) {
4790
- skipped.push({ bot: bot.handle, kind: 'schedule', name: pick(task.title), reason: error?.message ?? String(error) });
4791
- }
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.
4848
+ }
4849
+ }
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) });
4792
4856
  }
4793
4857
  }
4794
- const lead = created.find((c) => c.spec.role === 'primary')?.bot;
4795
- return { team: team.id, bots: created.map((c) => store.get(c.bot.id)), leadId: lead?.id ?? null, kickoff: pick(team.kickoff), skipped };
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 };
4796
4860
  }
4797
4861
 
4798
4862
  const unfurlLink = createUnfurler();
@@ -4800,7 +4864,7 @@ export function apply(ctx, config, deps = {}) {
4800
4864
  teams: { get: () => teamsView() },
4801
4865
  'teams/hire': {
4802
4866
  post: async (body) => {
4803
- 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');
4804
4868
  return { ok: true, ...r, bots: r.bots.map(publicBot) };
4805
4869
  },
4806
4870
  },
@@ -5031,6 +5095,7 @@ export function apply(ctx, config, deps = {}) {
5031
5095
  },
5032
5096
  // The one-time notice that an upgraded team's dispatcher now routes: dismissed for good.
5033
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: [] }) },
5034
5099
  // Tasks (tickets), PLAN-0.8 §6.3. `tickets/:id…` and `threads/:key` are under `paramRoutes`.
5035
5100
  tickets: { get: (url) => ticketList(url) },
5036
5101
  // The person's requests (Bots 0.11). `needs/:id…` is under `paramRoutes`.
@@ -5323,7 +5388,7 @@ export function apply(ctx, config, deps = {}) {
5323
5388
 
5324
5389
  /** For tests: which per-Session records this process still keeps for `sessionId`. */
5325
5390
  const tracked = (sessionId) => ({ trigger: trigger.has(sessionId), answered: answered.has(sessionId), turn: turnState.has(sessionId), delivered: deliveredIds.has(sessionId), history: historyRead.has(sessionId) });
5326
- 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 };
5327
5392
  }
5328
5393
 
5329
5394
  function serveAvatar(dir, req, res) {
package/lib/prompt.mjs CHANGED
@@ -15,6 +15,21 @@ export function rosterLine(bot, selfId) {
15
15
  return `- @${bot.handle} — ${bot.name}${tags.length ? ` (${tags.join(', ')})` : ''}${bot.bio ? `: ${bot.bio}` : ''}`;
16
16
  }
17
17
 
18
+ /**
19
+ * The roster as a bot reads it. Bots hired as a team (`teamNames`: team id → name) are listed under
20
+ * their team, so that with several teams hired the dispatcher still sees who belongs together; the
21
+ * dispatcher and bots of no team come first. Without teams it is one line per bot.
22
+ */
23
+ export function rosterLines(roster, selfId, teamNames = {}) {
24
+ const named = (b) => b.role !== 'primary' && Boolean(teamNames[b.team]);
25
+ const lines = roster.filter((b) => !named(b)).map((b) => rosterLine(b, selfId));
26
+ for (const id of [...new Set(roster.filter(named).map((b) => b.team))]) {
27
+ lines.push(`- ${teamNames[id]}:`);
28
+ for (const b of roster.filter((x) => named(x) && x.team === id)) lines.push(` ${rosterLine(b, selfId)}`);
29
+ }
30
+ return lines;
31
+ }
32
+
18
33
  const LANGUAGE_LINE = '- Write to the user in the language they use (Chinese or English). Between bots, use the language of the task you were given.';
19
34
  const MANAGE_LINE = '- `bot_list` shows the team with each bot\'s skills and apps; `bot_create`, `bot_update` and `bot_delete` manage bots when the user asks for it or a new specialist is clearly needed.';
20
35
  const SCHEDULE_NOTICE_LINE = '- Ignore "[SCHEDULE CHANGE]" notices: they need no reply.';
@@ -120,8 +135,9 @@ function originPhrase(ticket) {
120
135
  * bot's conversation only.
121
136
  * @param {object} bot
122
137
  * @param {object[]} roster - every bot, the bot itself included.
123
- * @param {{skillsInline?: boolean, apps?: string[], skillNames?: object, channels?: string[], dispatcher?: 'router'|'hands-on', tickets?: boolean, ticket?: object}} [extra]
138
+ * @param {{skillsInline?: boolean, apps?: string[], skillNames?: object, channels?: string[], dispatcher?: 'router'|'hands-on', tickets?: boolean, ticket?: object, teamNames?: object}} [extra]
124
139
  * `channels`: chat apps the team is reachable from ('Telegram').
140
+ * `teamNames`: team id → name, to list hired teams' bots under their team.
125
141
  * `dispatcher`: how the dispatcher (role 'primary') works in its home conversation: 'router' (it has teammates) only understands, hands out and reports; 'hands-on' (default: it works alone) is the 0.7 text. Ignored for other bots.
126
142
  * `tickets`: delegating from a home opens a task whose answer arrives as a report (router mode); a non-dispatcher bot's home then says so. Without it (hands-on) the 0.7 text stands.
127
143
  * `ticket`: the ticket (see PLAN-0.8 §10) when this conversation is that ticket's session; the text then frames the conversation as one task, whatever the bot's role.
@@ -136,7 +152,7 @@ export function personaText(bot, roster, extra = {}) {
136
152
  const others = roster.filter((b) => b.id !== bot.id);
137
153
  lines.push('', '## The bot team');
138
154
  lines.push(roster.length > 1 ? 'These bots work for the same user and can message each other:' : 'You are the only bot so far.');
139
- if (roster.length > 1) for (const b of roster) lines.push(rosterLine(b, bot.id));
155
+ if (roster.length > 1) lines.push(...rosterLines(roster, bot.id, extra.teamNames));
140
156
  lines.push('', '## Working with other bots', ...(ticket ? TICKET_TEAM : router ? routerTeam(bot.handle) : homeTickets ? HOME_TICKETS_TEAM : HANDS_ON_TEAM));
141
157
  if (others.length && bot.role === 'primary') lines.push(teamHelpersLine(router));
142
158
  if (ticket) {
package/lib/settings.mjs CHANGED
@@ -32,6 +32,12 @@ export const DEFAULTS = Object.freeze({
32
32
  * to the old hands-on mode gets it (again) when it is moved to router mode (0.11).
33
33
  */
34
34
  routerNotice: null,
35
+ /**
36
+ * The one-time panel notice that team templates lost their leads (0.11.1), shown while a team
37
+ * hired before still has a lead that is not the dispatcher: null until the user answers it,
38
+ * 'dismissed' after (whether the leads were removed or kept).
39
+ */
40
+ leadNotice: null,
35
41
  topics: Object.freeze({
36
42
  /** A conversation quiet for this many hours starts a new topic before its next task; 0 = never. */
37
43
  idleHours: 6,
@@ -118,6 +124,7 @@ export function normalizeSettings(input) {
118
124
  },
119
125
  // A team that had picked hands-on is told once that its dispatcher now only hands out the work.
120
126
  routerNotice: s.dispatcher === 'hands-on' ? 'pending' : s.routerNotice === 'pending' || s.routerNotice === 'dismissed' ? s.routerNotice : null,
127
+ leadNotice: s.leadNotice === 'dismissed' ? 'dismissed' : null,
121
128
  topics: {
122
129
  idleHours: num(t.idleHours, DEFAULTS.topics.idleHours, 0, 24 * 30),
123
130
  maxContextK: Math.round(num(t.maxContextK, DEFAULTS.topics.maxContextK, 0, 4096)),
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Bringing teams hired from the 0.3–0.11.0 templates to the current ones (0.11.1), where a team has
3
+ * no lead and its routine belongs to the dispatcher. Only what still reads exactly as it was hired
4
+ * changes, so a persona, bio or scheduled task someone edited is left as it is; anything already
5
+ * brought over no longer matches, so running it again does nothing. Pure: the plan, not its doing.
6
+ *
7
+ * @module @kadaliao/dsh-bots/lib/team-migration
8
+ */
9
+
10
+ import { TEAMS } from './teams.mjs';
11
+ import { TEAMS_0_11 } from './teams-0.11.mjs';
12
+
13
+ const LANGS = ['en', 'zh'];
14
+
15
+ /** The language a text is in when it is exactly one of a bilingual pair's texts, else null. */
16
+ const langOf = (text, pair) => LANGS.find((l) => pair?.[l] && text === pair[l]) ?? null;
17
+
18
+ /** Where a 0.11.0 task of `teamId` is now, by its title in `lang`: `{desk: true, prompt}` or `{handle, prompt}`, or null. */
19
+ function taskNow(teamId, title, lang) {
20
+ const team = TEAMS.find((t) => t.id === teamId);
21
+ if (!team) return null;
22
+ const desk = (team.desk ?? []).find((t) => t.title[lang] === title);
23
+ if (desk) return { desk: true, prompt: desk.prompt[lang] };
24
+ for (const b of team.bots) {
25
+ const t = (b.tasks ?? []).find((x) => x.title[lang] === title);
26
+ if (t) return { handle: b.handle, prompt: t.prompt[lang] };
27
+ }
28
+ return null;
29
+ }
30
+
31
+ /**
32
+ * The migration plan.
33
+ * @param {{bots: object[], entries: {id: string, botId: string|null, title: string, prompt: string, timing: object}[], deskId: string|null, deskText: (lang: 'en'|'zh') => {persona: string, bio: string}}} input
34
+ * `entries`: the bots' scheduled tasks; `deskText`: the front desk's persona and bio in a language.
35
+ * @returns {{bots: {id: string, patch: object}[], edits: {id: string, prompt: string}[], moves: {id: string, title: string, prompt: string, timing: object}[], drops: string[]}}
36
+ * `bots`: patches to save; `edits`: new prompts for tasks that stay where they are; `moves`: tasks
37
+ * to delete and make again on the dispatcher; `drops`: tasks to delete, the dispatcher already has one by that title.
38
+ */
39
+ export function planTeamMigration({ bots, entries, deskId, deskText }) {
40
+ const plan = { bots: [], edits: [], moves: [], drops: [] };
41
+ const deskTitles = new Set(entries.filter((e) => e.botId && e.botId === deskId).map((e) => e.title));
42
+ for (const bot of bots) {
43
+ const was = TEAMS_0_11[bot.team]?.[bot.handle];
44
+ if (!was) continue;
45
+ const isDesk = bot.id === deskId;
46
+ const now = TEAMS.find((t) => t.id === bot.team)?.bots.find((b) => b.handle === bot.handle);
47
+ const patch = {};
48
+ for (const k of ['persona', 'bio']) {
49
+ const lang = langOf(bot[k], was[k]);
50
+ if (!lang) continue;
51
+ // A lead that is the dispatcher reads as the front desk; a member as its current template.
52
+ const text = was.lead ? (isDesk ? deskText(lang)[k] : null) : now?.[k]?.[lang];
53
+ if (text && text !== bot[k]) patch[k] = text;
54
+ }
55
+ // A lead's work skills and apps do not fit the dispatcher (an app is turned off, its keys kept).
56
+ if (was.lead && isDesk) {
57
+ const skills = (bot.skills ?? []).filter((s) => !(s.source === 'dsh' && was.dshSkills.includes(s.name)));
58
+ if (skills.length !== (bot.skills ?? []).length) patch.skills = skills;
59
+ if ((bot.apps ?? []).some((a) => a.enabled && was.apps.includes(a.template))) patch.apps = bot.apps.map((a) => (was.apps.includes(a.template) ? { ...a, enabled: false } : a));
60
+ }
61
+ if (Object.keys(patch).length) plan.bots.push({ id: bot.id, patch });
62
+ for (const e of entries.filter((x) => x.botId === bot.id)) {
63
+ const task = was.tasks.find((t) => langOf(e.title, t.title) && langOf(e.prompt, t.prompt) === langOf(e.title, t.title));
64
+ if (!task) continue;
65
+ const lang = langOf(e.title, task.title);
66
+ const where = taskNow(bot.team, e.title, lang);
67
+ if (!where) continue;
68
+ if (!where.desk || isDesk) {
69
+ if (where.prompt !== e.prompt) plan.edits.push({ id: e.id, prompt: where.prompt });
70
+ } else if (!deskId) continue;
71
+ else if (deskTitles.has(e.title)) plan.drops.push(e.id);
72
+ else {
73
+ plan.moves.push({ id: e.id, title: e.title, prompt: where.prompt, timing: e.timing });
74
+ deskTitles.add(e.title);
75
+ }
76
+ }
77
+ }
78
+ return plan;
79
+ }