work-rhythm 0.2.21 → 0.2.22

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.
Files changed (68) hide show
  1. package/.agents/notes/AGENTS.md +10 -3
  2. package/.agents/notes/decisions/2026-11-30-bot-inbound-uses-websocket-and-a-responder-command.md +1 -0
  3. package/.agents/notes/decisions/2026-11-30-skill-ships-with-its-template-in-a-zip.md +1 -0
  4. package/.agents/notes/decisions/2026-12-01-agent-binding-asks-for-model-and-effort.md +1 -0
  5. package/.agents/notes/decisions/2026-12-01-interjections-batch-into-one-answer-and-interrupt-reruns.md +1 -0
  6. package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +1 -0
  7. package/.agents/notes/decisions/2026-12-01-router-runs-on-a-flash-model-with-low-effort.md +1 -0
  8. package/.agents/notes/decisions/2026-12-03-codex-cli-joins-as-a-preset-verified-against-its-own-binary.md +45 -0
  9. package/.agents/notes/decisions/2026-12-03-fewer-scheduled-tasks-silent-refine-no-question-cards.md +1 -0
  10. package/.agents/notes/decisions/2026-12-03-playbook-distills-handoffs-into-ws-tool-and-skill-know-how.md +43 -0
  11. package/.agents/notes/decisions/2026-12-03-related-work-comes-back-as-one-reply.md +49 -0
  12. package/.agents/notes/decisions/2026-12-03-roster-of-worker-groups-router-picks-the-group.md +33 -0
  13. package/.agents/notes/decisions/2026-12-03-router-model-and-effort-are-configurable.md +28 -0
  14. package/.agents/notes/decisions/2026-12-03-router-only-direct-mode-removed.md +27 -0
  15. package/.agents/notes/decisions/2026-12-03-unattended-runs-decide-on-their-own.md +32 -0
  16. package/.agents/notes/decisions/2026-12-03-update-upgrades-package-and-refreshes-shipped-files.md +30 -0
  17. package/.agents/notes/decisions/2026-12-03-workers-leave-a-status-trail-that-joins-the-receipt.md +31 -0
  18. package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +2 -0
  19. package/.agents/notes/pitfalls/2026-12-03-judging-a-symlink-by-realpath-ignores-parent-links.md +18 -0
  20. package/.agents/skills/work-rhythm/SKILL.md +20 -16
  21. package/README.md +13 -10
  22. package/collectors/local.env.example +31 -36
  23. package/docs/agents.md +61 -60
  24. package/docs/channels.md +15 -19
  25. package/docs/formats.md +27 -0
  26. package/docs/router-worker.md +60 -41
  27. package/docs/scheduled-tasks.md +9 -9
  28. package/package.json +1 -1
  29. package/scripts/cli.js +9 -5
  30. package/scripts/cmd/agent.js +348 -235
  31. package/scripts/cmd/check.js +14 -7
  32. package/scripts/cmd/listen.js +33 -32
  33. package/scripts/cmd/pack.js +6 -6
  34. package/scripts/cmd/rhythm.js +13 -10
  35. package/scripts/cmd/trigger.js +23 -14
  36. package/scripts/cmd/update.js +92 -0
  37. package/scripts/lib/agent.js +235 -142
  38. package/scripts/lib/agents.js +179 -0
  39. package/scripts/lib/bot.js +44 -263
  40. package/scripts/lib/engine.js +327 -110
  41. package/scripts/lib/handoff.js +54 -8
  42. package/scripts/lib/markdown.js +19 -0
  43. package/scripts/lib/playbook.js +123 -0
  44. package/scripts/lib/rhythm.js +405 -170
  45. package/scripts/lib/router.js +45 -29
  46. package/scripts/lib/template.js +3 -3
  47. package/scripts/lib/update.js +279 -0
  48. package/scripts/lib/worker.js +11 -5
  49. package/scripts/test/agent.test.js +410 -257
  50. package/scripts/test/check.test.js +17 -6
  51. package/scripts/test/harness.js +5 -2
  52. package/scripts/test/listen.test.js +190 -158
  53. package/scripts/test/playbook.test.js +106 -0
  54. package/scripts/test/rhythm.test.js +164 -54
  55. package/scripts/test/roster.test.js +155 -0
  56. package/scripts/test/router-helper.js +17 -2
  57. package/scripts/test/router.test.js +468 -194
  58. package/scripts/test/stubs.js +51 -4
  59. package/scripts/test/timeout.test.js +160 -59
  60. package/scripts/test/update.test.js +384 -0
  61. package/tasks/daily-persona.md +30 -11
  62. package/tasks/daily-plan.md +2 -1
  63. package/tasks/noon-checkin.md +2 -1
  64. package/templates/00-config/profile.example.yaml +9 -6
  65. package/templates/04-patterns/PERSONA.md +4 -1
  66. package/templates/04-patterns/PLAYBOOK.md +13 -0
  67. package/templates/AGENTS.md +6 -2
  68. package/templates/README.md +10 -9
@@ -1,6 +1,10 @@
1
1
  // 引擎:触发 → 路由 → 执行者 → 汇报 → 发消息(docs/router-worker.md)。跑在本地服务(rhythm.js)的进程里;
2
- // listen handle 在命令行的进程里也拿它走一遍(要发的文字交给 sink,不真发)。
3
- // 触发的内容(原话、任务书正文、回执)只在内存里和 .agents/handoff/ 的文件里;state.json 只记元数据:
2
+ // listen handle 和 rhythm run 在命令行的进程里也拿它走一遍(要发的文字交给 sink,不真发)。
3
+ // 路由和有哪几组执行者在名册里(agents.js),每次派活时读:网页或命令行改了,对新的触发生效。路由点名派给哪一组(worker=<编号>),
4
+ // 没点名派给第一组。路由坏了(超时、看不懂、漏了决定)走兜底:按来源直接处理,不丢东西。
5
+ // 发给我的话尽量合成一条:同一轮里路由给的好几条话(reply、notify)攒到这一轮结束一起发;手头还有别的活在跑时,
6
+ // 先做完的汇报等一等(最多等 cfg.mergeWait 秒),一起交回路由——路由一轮看完,回的话就是一条。
7
+ // 触发的内容(原话、任务书正文、回执、执行者的过程记录)只在内存里和 .agents/handoff/ 的文件里;state.json 只记元数据:
4
8
  // triggers 每条的短号、去重键、来源、时间、决定、执行者的状态/用时/会话 id、发没发(留两天)
5
9
  // history 每跑完一条记一行元数据(留 rhythm.history-keep 天),监控中心的次数和成功率从它算
6
10
  // rounds 路由每一轮(留两天)
@@ -8,18 +12,18 @@
8
12
  'use strict';
9
13
  const fs = require('node:fs');
10
14
  const path = require('node:path');
11
- const { fmtStamp, today, humanDuration, progressPings } = require('./run');
12
- const { roles } = require('./agent');
15
+ const { fmtStamp, today, humanDuration } = require('./run');
13
16
  const handoff = require('./handoff');
17
+ const playbook = require('./playbook');
14
18
  const { createRouter } = require('./router');
15
19
  const { createPool, runWorker } = require('./worker');
20
+ const { PRESETS, presetKind } = require('./agent');
16
21
  const { parseEvents } = require('../cmd/events');
17
22
  const asks = require('./asks');
18
23
  const ws = require('./workspace');
24
+ const rosterLib = require('./agents');
19
25
 
20
- const ACK_TEXT = '收到,正在处理,稍等。'; // 和值守(bot.js)那句一样
21
- // 上一句还没答完又来一句(插话):先回这句,告诉他会和上一句一起考虑
22
- const ACK_MORE_TEXT = '收到,正在处理,稍等。';
26
+ const ACK_TEXT = '收到,正在处理,稍等。';
23
27
  const TRIGGER_KEEP_DAYS = 2;
24
28
  const OPEN_MAX = 10;
25
29
  const OPEN_MS = 24 * 3600 * 1000;
@@ -37,7 +41,7 @@ const queueDir = (root) => path.join(root, '01-inbox', '_rhythm', 'queue');
37
41
  const triggersStore = new Map();
38
42
  const triggersOf = (root) => (triggersStore.has(root) ? triggersStore.get(root)() : {});
39
43
 
40
- // 每跑完一条记一行(只有元数据)。直通模式下的 rhythm run 也记,manual 标出来
44
+ // 每跑完一条记一行(只有元数据)。手动跑的也记,manual 标出来
41
45
  function appendHistory(data, row) {
42
46
  data.history = [...(data.history || []), { at: fmtStamp(), uid: uid(), ...row }];
43
47
  }
@@ -163,17 +167,29 @@ function answerBody(c) {
163
167
  return lines.join('\n');
164
168
  }
165
169
 
166
- // cfg 来自 rhythm.js 的 loadConfig(router、routerTimeout、workers、handoffKeep、historyKeep、taskTimeout、agentMode、agentModel、
167
- // agentEffort、push、quiet、links、baseUrl、serviceAlive、ack、botMode、botTimeout、replyMax、botPreamble、refine、refineInterval)。state 是 { data, save }
170
+ // 几段话(dress 出来的 { t, body, foot })装进尽量少的消息:一条的正文不超过 max 字,装不下的放下一条;页面地址相同的只附一次。
171
+ // 返回 [{ items, text }],text 就是要发的那条消息
172
+ function packOutbox(items, max) {
173
+ const messages = [];
174
+ let cur = null;
175
+ for (const it of items) {
176
+ if (cur && Array.from(`${cur.bodies.join('\n\n')}\n\n${it.body}`).length <= max) {
177
+ cur.bodies.push(it.body);
178
+ if (it.foot && !cur.feet.includes(it.foot)) cur.feet.push(it.foot);
179
+ cur.items.push(it);
180
+ } else {
181
+ cur = { bodies: [it.body], feet: it.foot ? [it.foot] : [], items: [it] };
182
+ messages.push(cur);
183
+ }
184
+ }
185
+ return messages.map((m) => ({ items: m.items, text: [m.bodies.join('\n\n'), m.feet.join('\n')].filter(Boolean).join('\n\n') }));
186
+ }
187
+
188
+ // cfg 来自 rhythm.js 的 loadConfig(routerTimeout、handoffKeep、historyKeep、taskTimeout、mergeWait、agentMode、push、quiet、links、baseUrl、
189
+ // serviceAlive、ack、botMode、botTimeout、workerIdle、progress、progressMax、messageDebounce、replyMax、botPreamble、refine、refineInterval)。state 是 { data, save }
168
190
  function createEngine({ root, env, cfg, log = () => {}, push = async () => false, state, since = Date.now() }) {
169
- const routerSpec = roles(env).router;
170
- // 执行者的模型和强度:YZJ_WORKER_* > profile 的 rhythm.agent-* > YZJ_BOT_*
171
- const workerSpec = {
172
- agent: s(env.YZJ_WORKER_AGENT) || s(env.YZJ_BOT_AGENT),
173
- model: s(env.YZJ_WORKER_MODEL) || cfg.agentModel || s(env.YZJ_BOT_MODEL),
174
- effort: s(env.YZJ_WORKER_EFFORT) || cfg.agentEffort || s(env.YZJ_BOT_EFFORT),
175
- };
176
- const agentLabel = `${workerSpec.agent}${workerSpec.model ? `(${workerSpec.model})` : ''}`;
191
+ let envNow = env; // setEnv 能换:网页上保存配置之后 local.env 可能改过(路由的会话)
192
+ const roster = () => rosterLib.loadRoster(root, envNow);
177
193
  const triggers = () => state.data.triggers;
178
194
  const save = () => state.save();
179
195
  triggersStore.set(root, triggers);
@@ -187,7 +203,11 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
187
203
  let pumpScheduled = false; // 这个 tick 里已经排了一轮
188
204
  let msgBuf = null;
189
205
  let msgTimer = null;
206
+ let outbox = null; // 路由这一轮要发给用户的话先攒在这儿([{ t, body, foot }]),决定都做完了再合成尽量少的消息发
207
+ const held = []; // 攒着的汇报 [{ fields, origin }]:手头还有别的活在跑时,先做完的等一等,一起交回路由
208
+ let heldTimer = null; // 等的上限(cfg.mergeWait 秒),到点先把攒着的交回
190
209
  const activeProgress = new Map(); // id → { t, started }
210
+ const pulse = new Map(); // 在跑的执行者 → { outputAt }:上一次收到它输出的时刻(只记边跑边输出的预置,别的家最后才吐)
191
211
  let progressTimer = null;
192
212
  let progressStepMs = 0;
193
213
  const MAX_PROGRESS_STEP_MS = 30 * 60 * 1000; // 指数退避封顶 30 分钟
@@ -205,11 +225,14 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
205
225
  const all = [...activeProgress.values()];
206
226
  if (all.length === 1) {
207
227
  const { t, started } = all[0];
208
- send(t, `还在做(已经 ${humanDuration((now - started) / 1000)} · 工作区 ${t.ws || '工作目录'}):${t.title || t.id}。做完汇报。`, { mark: false });
228
+ // 带上执行者最近记的一步过程(它没记过就不带)
229
+ const step = handoff.lastStatus(root, t.id).line;
230
+ send(t, `还在做(已经 ${humanDuration((now - started) / 1000)} · 工作区 ${t.ws || '工作目录'}):${t.title || t.id}。${step ? `最近一步:${step}。` : ''}做完汇报。`, { mark: false });
209
231
  } else {
210
232
  const lines = ['手头有 ' + all.length + ' 件事还在做(做完汇报):'];
211
233
  all.forEach(({ t, started }, i) => {
212
- lines.push(`${i + 1}. [工作区 ${t.ws || '工作目录'}] ${t.title || t.id}(已 ${humanDuration((now - started) / 1000)})`);
234
+ const step = handoff.lastStatus(root, t.id).line;
235
+ lines.push(`${i + 1}. [工作区 ${t.ws || '工作目录'}] ${t.title || t.id}(已 ${humanDuration((now - started) / 1000)})${step ? `:最近一步 ${step}` : ''}`);
213
236
  });
214
237
  send(null, lines.join('\n'), { mark: false });
215
238
  }
@@ -232,15 +255,56 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
232
255
  return enqueue('message', { key: b.keys[0], text: b.texts.join('\n'), mode: cfg.botMode });
233
256
  }
234
257
  let sink = null;
235
- const pool = createPool({ limit: cfg.workers });
236
- const router = cfg.router ? createRouter({ root, env, role: routerSpec, timeoutS: cfg.routerTimeout, preamble: cfg.botPreamble || '', log }) : null;
258
+
259
+ // 执行者的池子按组分:每组一个,同时最多跑它名册里的数量(数量改了跟着改)
260
+ const pools = new Map();
261
+ const poolOf = (group) => {
262
+ let pool = pools.get(group.id);
263
+ if (!pool) {
264
+ pool = createPool({ limit: group.count });
265
+ pools.set(group.id, pool);
266
+ }
267
+ pool.setLimit(group.count);
268
+ return pool;
269
+ };
270
+ const allPools = () => [...pools.values()];
271
+ const runningAll = () => allPools().flatMap((p) => p.running());
272
+ const queuedAll = () => allPools().flatMap((p) => p.queued());
273
+
274
+ // 路由按名册里当前的配置起。名册变了(网页或命令行改了 agent、模型、强度,换了会话)就换一个;
275
+ // 换了 agent 时把它自己的专属会话清掉(别的 agent 接不上那个会话)
276
+ let router = null;
277
+ let routerSig = '';
278
+ let routerAgent = '';
279
+ function routerNow() {
280
+ const team = roster();
281
+ const role = { ...team.router, effort: rosterLib.routerEffort(team.router), session: rosterLib.routerSession(envNow, team.router.agent) };
282
+ const sig = JSON.stringify([role.agent, role.model, role.effort, role.session]);
283
+ if (!router || sig !== routerSig) {
284
+ if (router && routerAgent !== role.agent) router.resetSession();
285
+ router = createRouter({ root, env: envNow, role, timeoutS: cfg.routerTimeout, preamble: cfg.botPreamble || '', log });
286
+ routerAgent = role.agent;
287
+ routerSig = sig;
288
+ log('路由就绪', `${role.agent || '没绑'}${role.model ? ` · ${role.model}` : ''} · ${role.effort || '强度用默认'}`);
289
+ }
290
+ return router;
291
+ }
292
+
293
+ // 派给哪一组执行者:路由点了名就用那组(编号不认识就派给第一组,记一笔);没点名是第一组。
294
+ // 续做、插话带着原来那组的编号来,所以还是原来那个 agent 接着它的会话跑
295
+ function groupOf(id) {
296
+ const groups = roster().workers;
297
+ const pick = groups.find((w) => w.id === id);
298
+ if (id && !pick) log('执行者的编号不认识', `${id},派给 ${groups[0] ? groups[0].id : 'w1'}`);
299
+ return pick || groups[0] || { id: 'w1', agent: '', model: '', effort: '', count: 1 };
300
+ }
237
301
 
238
302
  // 权限和超时由触发来源定。重做的沿用原来那条的。
239
303
  // IM 来的话(message)分两种:路由判成 dispatch 的是「派人做事」,事要写文件,按定时任务的权限来(rhythm.agent-mode)——
240
- // 2026-12-02 用户决定,原来一律只读,结果派出去的人写不了、做不成;路由没开时的直答(fallback)还是 YZJ_BOT_AGENT_MODE,默认只读
304
+ // 2026-12-02 用户决定,原来一律只读,结果派出去的人写不了、做不成;路由没出决定时的兜底还是 YZJ_BOT_AGENT_MODE(默认 plan,只读)
241
305
  function terms(t, { byRouter = false } = {}) {
242
306
  if (t.kind === 'schedule') return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
243
- if (t.kind === 'message' && router && byRouter) return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
307
+ if (t.kind === 'message' && byRouter) return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
244
308
  if (t.kind === 'answer') {
245
309
  const o = live.get(t.id) && live.get(t.id).ask && live.get(t.id).ask.from && triggers()[live.get(t.id).ask.from.trigger];
246
310
  if (o && o.worker && o.worker.mode) return { mode: o.worker.mode, timeoutS: o.worker.timeoutS || cfg.taskTimeout };
@@ -254,13 +318,13 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
254
318
  return { mode: (live.get(t.id) || {}).mode || 'plan', timeoutS: cfg.taskTimeout };
255
319
  }
256
320
 
257
- const isActive = (id) => pool.running().some((e) => e.id === id) || pool.queued().includes(id);
321
+ const isActive = (id) => runningAll().some((e) => e.id === id) || queuedAll().includes(id);
258
322
 
259
- // 手头的事:在跑的、排队里的、今天做完的,给路由认「同一件事」用
323
+ // 手头的事:在跑的、排队里的、今天做完的,给路由认「同一件事」用。在跑的带上它最近记的一步过程(用户问「做到哪了」路由直接答)
260
324
  function openItems() {
261
325
  const now = Date.now();
262
- const act = [...pool.running().map((e) => e.id), ...pool.queued()];
263
- const row = (x) => ({ id: x.id, status: STATUS_CN[x.worker.status] || '在跑', at: x.at, title: x.title || '', ws: x.ws || '' });
326
+ const act = [...runningAll().map((e) => e.id), ...queuedAll()];
327
+ const row = (x) => ({ id: x.id, status: STATUS_CN[x.worker.status] || '在跑', at: x.at, title: x.title || '', ws: x.ws || '', step: x.worker.status === 'running' ? handoff.lastStatus(root, x.id).line : '' });
264
328
  const done = Object.values(triggers()).filter((x) => x.worker && ['ok', 'failed', 'stopped'].includes(x.worker.status) && now - stampMs(x.worker.endedAt || x.at) < OPEN_MS).sort((a, b) => b.at.localeCompare(a.at));
265
329
  return [...act.map((id) => triggers()[id]).filter(Boolean).map(row), ...done.map(row)].slice(0, OPEN_MAX);
266
330
  }
@@ -276,18 +340,21 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
276
340
  }
277
341
 
278
342
  // 新的触发进队列。key 一样的只处理一次。返回记录,或者 null(重复的)
279
- function enqueue(kind, { key = '', text = '', task = '', taskFile = '', taskBody = '', taskTitle = '', mode = '', of = '', ok = false, seconds = 0, reason = '', opening = '', quiet = false, linkTask = '', orig = null, events = null, sources = null, ask = null, date = '', root: eventRoot } = {}) {
343
+ // 这条消息是不是从 IM 里来的(listen handle 走一遍的那种不是:去重键以 handle- 开头)
344
+ const fromIm = (t) => !/^handle-/.test(String(t.key || ''));
345
+ function enqueue(kind, { key = '', text = '', task = '', taskFile = '', taskBody = '', taskTitle = '', mode = '', of = '', ok = false, seconds = 0, reason = '', opening = '', quiet = false, linkTask = '', orig = null, events = null, sources = null, ask = null, date = '', root: eventRoot, manual = false } = {}) {
280
346
  if (key && Object.values(triggers()).some((x) => x.key === key)) return null;
281
- const t = record(kind, { key, task, of, quiet });
347
+ const t = record(kind, { key, task, of, quiet, manual });
282
348
  live.set(t.id, { text, taskFile, taskBody, taskTitle, mode, opening, linkTask, orig, ok, seconds, reason, events, sources, ask, date, root: eventRoot || root });
283
349
  if (kind === 'answer' && ask) t.title = `回答:${ask.item || ask.question || ''}`;
284
350
  queue.push(t.id);
285
351
  save();
286
352
  log('触发入队', `${t.id} ${kind}`);
287
- // 有东西在做(路由在想、前面还排着、执行者在跑):这句不会马上答,先回一句「收到」,说会和上一句一起考虑
288
- if (kind === 'message' && cfg.ack && (busy || queue.length > 1 || deferred || pool.running().length)) {
353
+ // 有东西在做(路由在想、前面还排着、执行者在跑):这句不会马上答,先回一句「收到」,说会和上一句一起考虑。
354
+ // listen handle(命令行里走一遍)不是从 IM 来的,不用回这句
355
+ if (kind === 'message' && fromIm(t) && cfg.ack && (busy || queue.length > 1 || deferred || runningAll().length)) {
289
356
  t.acked = true;
290
- send(null, ACK_MORE_TEXT, { mark: false });
357
+ send(null, ACK_TEXT, { mark: false });
291
358
  }
292
359
  schedulePump();
293
360
  return t;
@@ -303,21 +370,29 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
303
370
  });
304
371
  }
305
372
 
306
- // 发一段文字给用户。命令行走一遍时交给 sink;push 关着只记日志
307
- async function send(t, text, { mark = true, linkTask = '' } = {}) {
373
+ // 一段话要发出去的样子:太长截断并注明;定时任务的汇报后面附本机页面地址。没内容返回 null
374
+ function dress(text, linkTask) {
308
375
  const chars = Array.from(String(text || '').trim());
309
- if (!chars.length) return false;
310
- let out = chars.length > cfg.replyMax ? `${chars.slice(0, cfg.replyMax).join('')}\n…(回复太长,截到 ${cfg.replyMax} 字)` : chars.join('');
376
+ if (!chars.length) return null;
311
377
  const link = linkTask && cfg.links[linkTask];
312
- if (link && cfg.serviceAlive()) out += `\n\n→ ${link.label}:${cfg.baseUrl}${link.path(today())}`;
313
- if (mark && t) {
314
- t.notified = true;
315
- // 汇报发出去了,原来那件事也算「发了」(监控里看的就是那件事)
316
- const origin = t.kind === 'report' && triggers()[t.of];
317
- if (origin) origin.notified = true;
318
- }
378
+ return {
379
+ body: chars.length > cfg.replyMax ? `${chars.slice(0, cfg.replyMax).join('')}\n…(回复太长,截到 ${cfg.replyMax} 字)` : chars.join(''),
380
+ foot: link && cfg.serviceAlive() ? `→ ${link.label}:${cfg.baseUrl}${link.path(today())}` : '',
381
+ };
382
+ }
383
+
384
+ // 发出去了(或者按配置不发):这条触发记上「发了」。汇报发出去了,原来那件事也算「发了」(监控里看的就是那件事)
385
+ function markSent(t) {
386
+ if (!t) return;
387
+ t.notified = true;
388
+ const origin = t.kind === 'report' && triggers()[t.of];
389
+ if (origin) origin.notified = true;
390
+ }
391
+
392
+ // 真发出去:命令行走一遍时交给 sink;push 关着只记日志
393
+ async function deliver(text) {
319
394
  if (sink) {
320
- sink(out);
395
+ sink(text);
321
396
  return true;
322
397
  }
323
398
  if (!cfg.push) {
@@ -325,21 +400,76 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
325
400
  return false;
326
401
  }
327
402
  try {
328
- return await push(out);
403
+ return await push(text);
329
404
  } catch (error) {
330
405
  log('推送出错', error && error.message ? error.message : String(error));
331
406
  return false;
332
407
  }
333
408
  }
334
409
 
410
+ // 发一段文字给用户。
411
+ // 路由这一轮还没走完(outbox 攒着)且是要发给我的结果(reply、notify、兜底时的话):先攒着,这一轮的决定都做完了,
412
+ // 和同一轮里别的话合成一条发。「收到」「还在做」这类 mark 为 false 的不攒,马上发
413
+ async function send(t, text, { mark = true, linkTask = '' } = {}) {
414
+ const part = dress(text, linkTask);
415
+ if (!part) return false;
416
+ if (mark && outbox) {
417
+ outbox.push({ t, ...part });
418
+ return true;
419
+ }
420
+ if (mark) markSent(t);
421
+ return deliver([part.body, part.foot].filter(Boolean).join('\n\n'));
422
+ }
423
+
424
+ // 一轮结束了:把攒下的话发出去(装进尽量少的消息),发过的那几条记上「发了」
425
+ async function flushOutbox(box) {
426
+ if (!box.length) return;
427
+ for (const m of packOutbox(box, cfg.replyMax)) {
428
+ m.items.forEach((it) => markSent(it.t));
429
+ await deliver(m.text);
430
+ }
431
+ save();
432
+ }
433
+
434
+ // 手头还有哪些活在做(在跑的、排队的)——只算汇报会发给我的那些:不推送的任务、提炼、被插话停掉的不算
435
+ function othersRunning(id) {
436
+ return [...runningAll().map((e) => e.id), ...queuedAll()].filter((x) => {
437
+ const o = triggers()[x];
438
+ return x !== id && o && !o.quiet && o.kind !== 'refine' && !o.suppressReport;
439
+ });
440
+ }
441
+
442
+ // 把攒着的汇报交回路由(建触发、排进队列,下一轮一起给路由)。先做完的排在前面
443
+ function flushHeld() {
444
+ if (heldTimer) {
445
+ clearTimeout(heldTimer);
446
+ heldTimer = null;
447
+ }
448
+ if (!held.length) return;
449
+ const batch = held.splice(0);
450
+ log('汇报一起交回', batch.map((h) => h.origin.id).join(' '));
451
+ for (const h of batch) {
452
+ delete h.origin.reportPending;
453
+ enqueue('report', h.fields);
454
+ }
455
+ }
456
+
457
+ // 一件结束了却不出汇报(被插话停掉的):手头没有别的活在做了,就把攒着的汇报交回
458
+ function settleIfIdle(t) {
459
+ if (!othersRunning(t.id).length) flushHeld();
460
+ }
461
+
335
462
  // 执行者结束:补回执、记一笔、生成汇报
336
463
  function finishWorker(t, r) {
337
464
  const ok = r.ok;
338
- if (ok && !handoff.resultReady(root, t.id)) handoff.writeResult(root, t.id, r.reply, { ok: true, seconds: r.seconds, agent: agentLabel, by: 'cli' });
465
+ const who = `${t.worker.agent || ''}${t.worker.model ? `(${t.worker.model})` : ''}`;
466
+ if (ok && !handoff.resultReady(root, t.id)) handoff.writeResult(root, t.id, r.reply, { ok: true, seconds: r.seconds, agent: who, by: 'cli' });
339
467
  const body = r.stopped ? '用户叫停,这件事没做完。' : r.partial ? `时间到了,做到这里:\n\n${r.partial}` : '';
340
- if (!ok) handoff.writeResult(root, t.id, body, { ok: false, reason: r.failed, seconds: r.seconds, agent: agentLabel, by: 'cli-fail' });
468
+ if (!ok) handoff.writeResult(root, t.id, body, { ok: false, reason: r.failed, seconds: r.seconds, agent: who, by: 'cli-fail' });
469
+ // 过程记录并进回执的「## 过程」:做到哪一步停下的、一路经过了什么,回执里看得到(执行者自己写了这一节的不动)
470
+ handoff.attachTrail(root, t.id);
341
471
  Object.assign(t.worker, { status: ok ? 'ok' : r.stopped ? 'stopped' : 'failed', seconds: r.seconds, sessionId: r.sessionId || t.worker.sessionId || '', reason: r.failed, endedAt: fmtStamp() });
342
- appendHistory(state.data, { id: t.id, kind: t.kind, task: t.task || '', decision: t.decision, ok, seconds: r.seconds, sessionId: t.worker.sessionId, agent: workerSpec.agent, model: workerSpec.model, effort: workerSpec.effort, mode: t.worker.mode, manual: t.kind === 'manual' });
472
+ appendHistory(state.data, { id: t.id, kind: t.kind, task: t.task || '', decision: t.decision, ok, seconds: r.seconds, sessionId: t.worker.sessionId, agent: t.worker.agent, model: t.worker.model, effort: t.worker.effort, worker: t.worker.id, mode: t.worker.mode, manual: Boolean(t.manual) });
343
473
  save();
344
474
  log('执行者结束', `${t.id} ${ok ? '成功' : r.stopped ? '叫停' : '失败'} ${r.seconds}s`);
345
475
  const c = live.get(t.id) || {};
@@ -352,6 +482,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
352
482
  if (t.suppressReport) {
353
483
  delete t.suppressReport;
354
484
  save();
485
+ settleIfIdle(t);
355
486
  return r;
356
487
  }
357
488
  // 服务正在停:不再交给路由,记一笔,下次启动时 recover() 补汇报
@@ -360,26 +491,52 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
360
491
  save();
361
492
  return r;
362
493
  }
363
- enqueue('report', {
494
+ const fields = {
364
495
  key: `report-${t.id}`, of: t.id, ok, seconds: r.seconds, reason: r.stopped ? '用户叫停' : r.failed, quiet: t.quiet,
365
496
  opening: ok ? handoff.opening(resultBody(handoff.readText(handoff.resultPath(root, t.id)))) : '', linkTask: t.kind === 'schedule' ? t.task : '', orig: t, task: c.linkTask,
366
- });
497
+ };
498
+ // 手头还有别的活(汇报要发给我的)在做:这份汇报先攒着,等它们做完一起交回路由(最多等 mergeWait 秒),回我的话合成一条。
499
+ // 只有它一件在做、或者不等:做完就交回,和原来一样。
500
+ // 攒着的只是内存里的一份记录(汇报的触发到交回时才建);这件事这期间记着「还没汇报」,服务中途没了下次启动 recover() 会补
501
+ const others = cfg.mergeWait > 0 && !t.quiet ? othersRunning(t.id) : [];
502
+ if (others.length) {
503
+ t.reportPending = true;
504
+ save();
505
+ held.push({ fields, origin: t });
506
+ if (!heldTimer) {
507
+ heldTimer = setTimeout(flushHeld, cfg.mergeWait * 1000);
508
+ if (heldTimer.unref) heldTimer.unref();
509
+ }
510
+ log('汇报先攒着', `${t.id}:手头还有 ${others.join(' ')} 在做`);
511
+ return r;
512
+ }
513
+ // 它是手头最后做完的:先把它前面攒着的汇报交回,再排自己的——先做完的排在前面
514
+ flushHeld();
515
+ enqueue('report', fields);
367
516
  return r;
368
517
  }
369
518
 
370
- // 排一个执行者。after 给了就等那件事做完再起(续做一件还在跑的事)
371
- function launch(t, { mode, timeoutS, resume = '', after = '', cwd = '', agentOverride = '' }) {
372
- const spec = agentOverride ? { ...workerSpec, agent: agentOverride } : workerSpec;
373
- t.worker = { status: 'queued', mode, timeoutS, agent: spec.agent, model: spec.model, effort: spec.effort, sessionId: resume || '', ws: t.ws || '' };
519
+ // 排一个执行者。group 是名册里那一组(agent、模型、强度、同时跑几个);agentOverride 是登记的工作区自带的 agent;
520
+ // after 给了就等那件事做完再起(续做一件还在跑的事)
521
+ function launch(t, { mode, timeoutS, group, resume = '', after = '', cwd = '', agentOverride = '' }) {
522
+ const spec = { agent: agentOverride || group.agent, model: group.model, effort: group.effort };
523
+ t.worker = { id: group.id, agent: spec.agent, model: spec.model, effort: spec.effort, mode, timeoutS, sessionId: resume || '', ws: t.ws || '' };
374
524
  save();
375
525
  const start = () => {
376
526
  // 续做排在后面起:起的时候再读原来那件的会话 id(它可能到做完才有)
377
527
  const target = after ? triggers()[after] : null;
378
528
  const sid = resume || (target && target.worker && target.worker.sessionId) || '';
379
- const p = pool.submit(t.id, async (ctrl) => {
529
+ if (sid && t.worker.sessionId !== sid) {
530
+ t.worker.sessionId = sid;
531
+ save();
532
+ }
533
+ const p = poolOf(group).submit(t.id, async (ctrl) => {
380
534
  t.worker.status = 'running';
381
535
  t.worker.startedAt = fmtStamp();
382
536
  save();
537
+ // 边跑边输出的预置(dsh、kimi…)记下它最后一次出声的时刻:监控里「多久没动静」说的是它;最后才吐的那几家按静默算会冤枉正常的长任务
538
+ const preset = PRESETS[presetKind(spec.agent)];
539
+ if (preset && preset.streams === true) pulse.set(t.id, { outputAt: Date.now() });
383
540
  // 我这边直接派出去的(消息、手动)跑得久就统一汇总说一声;定时任务的汇报本来就会来,不额外打扰
384
541
  const trackProgress = t.kind !== 'schedule' && !t.quiet && cfg.progress > 0; // 静默的(提炼、quiet 任务)不提示
385
542
  if (trackProgress) {
@@ -389,16 +546,21 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
389
546
  let r;
390
547
  try {
391
548
  r = await runWorker({
392
- root, cwd: cwd || root, env, log, id: t.id, mode, timeoutS, idleS: cfg.workerIdle, spec, resume: sid, extraEnv: { WRJ_TRIGGER: t.id, WRJ_ROLE: 'worker' },
393
- onSession: (sid) => {
394
- if (t.worker.sessionId !== sid) {
395
- t.worker.sessionId = sid;
549
+ root, cwd: cwd || root, env: envNow, log, id: t.id, mode, timeoutS, idleS: cfg.workerIdle, spec, resume: sid, extraEnv: { WRJ_TRIGGER: t.id, WRJ_ROLE: 'worker' },
550
+ onSession: (sid2) => {
551
+ if (t.worker.sessionId !== sid2) {
552
+ t.worker.sessionId = sid2;
396
553
  save();
397
554
  }
398
555
  },
556
+ onOutput: () => {
557
+ const beat = pulse.get(t.id);
558
+ if (beat) beat.outputAt = Date.now();
559
+ },
399
560
  onKill: (fn) => ctrl.setKill(fn),
400
561
  });
401
562
  } finally {
563
+ pulse.delete(t.id);
402
564
  if (trackProgress) {
403
565
  activeProgress.delete(t.id);
404
566
  if (!activeProgress.size) stopProgressTimer();
@@ -421,11 +583,12 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
421
583
  return start();
422
584
  }
423
585
 
424
- // 交给执行者:写任务书、起运行。路由没给任务书的(或者退路),拿原话或指令文件当任务书
425
- function dispatch(t, c, handoffBody, byRouter = false, wsId = '') {
586
+ // 交给执行者:写任务书、起运行。路由没给任务书的(或者兜底),拿原话或指令文件当任务书
587
+ function dispatch(t, c, handoffBody, byRouter = false, wsId = '', workerId = '') {
426
588
  let body = s(handoffBody);
427
589
  const { mode, timeoutS } = terms(t, { byRouter });
428
- const resolvedWs = wsId ? ws.discoverWorkspaces(root, env).resolve(wsId) : null;
590
+ const group = groupOf(workerId);
591
+ const resolvedWs = wsId ? ws.discoverWorkspaces(root, envNow).resolve(wsId) : null;
429
592
  if (resolvedWs) {
430
593
  t.ws = resolvedWs.id;
431
594
  t.wsPath = resolvedWs.path;
@@ -435,16 +598,25 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
435
598
  else if (t.kind === 'report') body = `# 任务:重做 ${t.of}\n\n上一次的结果:${c.ok ? handoff.opening(handoff.readText(handoff.resultPath(root, t.of))) : c.reason}\n旧任务书在 ${handoff.relTask(t.of)},旧回执在 ${handoff.relResult(t.of)},先读它们。\n\n${body || '按原任务书重做一遍。'}`;
436
599
  else if (!body) body = `# 任务:照用户的话做\n\n用户原话:「${c.text}」\n\n照它做。这是一句追问、单凭这句话做不了的话,在回执里说清楚缺什么。`;
437
600
  t.title = handoff.titleOf(body) || t.task || '';
601
+ const pbSec = t.kind === 'message' || t.kind === 'manual' ? playbook.section(root, `${c.text || ''}\n${body}`) : '';
602
+ if (pbSec) body = `${body}\n\n${pbSec}`;
438
603
  handoff.writeTask(root, { ...t, text: c.text, taskFile: c.taskFile }, body, { mode, timeoutS });
439
604
  save();
440
- // 消息一来先回一句「收到」,路由慢的话我不用干等
441
- if (t.kind === 'message' && cfg.ack && !t.acked) send(null, ACK_TEXT, { mark: false });
605
+ ackMessage(t);
442
606
  // 派出去就接着派下一条,不等它做完(汇报会自己排回来)
443
- launch(t, { mode, timeoutS, cwd: t.wsPath || root, agentOverride: resolvedWs && resolvedWs.agent ? resolvedWs.agent : '' });
607
+ launch(t, { mode, timeoutS, cwd: t.wsPath || root, group, agentOverride: resolvedWs && resolvedWs.agent ? resolvedWs.agent : '' });
444
608
  return undefined;
445
609
  }
446
610
 
447
- // 续做:用户这句话接着手头某件事说的。接着原来那个执行者的会话跑;它还在跑就排在后面
611
+ // IM 来的话要动手了(派人、续做、插话):先回一句「收到」,路由慢的话我不用干等。入队时没回过的才回
612
+ const ackMessage = (t) => {
613
+ if (t.kind === 'message' && fromIm(t) && cfg.ack && !t.acked) {
614
+ t.acked = true;
615
+ send(null, ACK_TEXT, { mark: false });
616
+ }
617
+ };
618
+
619
+ // 续做:用户这句话接着手头某件事说的。接着原来那个执行者的会话跑、还是它那一组;它还在跑就排在后面
448
620
  function continueWith(t, c, targetId) {
449
621
  const target = triggers()[targetId];
450
622
  if (!target || !openItems().some((o) => o.id === targetId)) {
@@ -460,11 +632,12 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
460
632
  if (target.ws) { t.ws = target.ws; t.wsPath = target.wsPath || ''; }
461
633
  handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
462
634
  save();
463
- launch(t, { mode, timeoutS, resume: (target.worker && target.worker.sessionId) || '', after: isActive(targetId) ? targetId : '', cwd: t.wsPath || root });
635
+ ackMessage(t);
636
+ launch(t, { mode, timeoutS, group: groupOf(target.worker && target.worker.id), resume: (target.worker && target.worker.sessionId) || '', after: isActive(targetId) ? targetId : '', cwd: t.wsPath || root });
464
637
  return undefined;
465
638
  }
466
639
 
467
- // 插话改要求:停掉在跑的那件事,带着新要求接着它的会话重跑。被停的那次不汇报(这次的结果会覆盖它)
640
+ // 插话改要求:停掉在跑的那件事,带着新要求接着它的会话重跑(还是它那一组)。被停的那次不汇报(这次的结果会覆盖它)
468
641
  function interruptWith(t, c, targetId) {
469
642
  const target = triggers()[targetId];
470
643
  if (!target || !isActive(targetId)) {
@@ -478,11 +651,12 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
478
651
  t.of = targetId;
479
652
  if (target.ws) { t.ws = target.ws; t.wsPath = target.wsPath || ''; }
480
653
  target.suppressReport = true;
481
- pool.stop(targetId, '用户插话,改了要求');
654
+ poolOf(groupOf(target.worker && target.worker.id)).stop(targetId, '用户插话,改了要求');
482
655
  handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
483
656
  save();
484
657
  log('插话', `${t.id} 停掉 ${targetId} 带着新要求重跑`);
485
- launch(t, { mode, timeoutS, resume, cwd: t.wsPath || root });
658
+ ackMessage(t);
659
+ launch(t, { mode, timeoutS, group: groupOf(target.worker && target.worker.id), resume, cwd: t.wsPath || root });
486
660
  return undefined;
487
661
  }
488
662
 
@@ -494,20 +668,23 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
494
668
  save();
495
669
  return undefined;
496
670
  }
497
- const where = pool.stop(targetId, '用户叫停');
671
+ const pool = target.worker && pools.get(target.worker.id);
672
+ const where = pool ? pool.stop(targetId, '用户叫停') : '';
498
673
  t.reason = `叫停 ${targetId}`;
499
674
  save();
500
675
  log('叫停', `${targetId}(${where})`);
501
676
  return undefined;
502
677
  }
503
678
 
504
- // 路由坏了、看不懂、漏了:按来源退回直通的做法,不丢东西
679
+ // 路由坏了、看不懂、漏了:按来源直接处理(兜底),不丢东西。
680
+ // 消息和手动塞进来的:原话当任务书派人(只读);到点的任务:指令文件当任务书;汇报:回执原样发回
505
681
  function fallback(t, c, why) {
506
682
  t.decision = 'fallback';
507
683
  t.reason = s(why).slice(0, 200);
508
684
  if (t.kind === 'report') {
509
685
  if (c.ok) {
510
- if (c.quiet) {
686
+ // 静默的标记在触发记录上(enqueue 写的),live 里没有
687
+ if (t.quiet || c.quiet) {
511
688
  save();
512
689
  return Promise.resolve();
513
690
  }
@@ -520,7 +697,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
520
697
 
521
698
  async function act(t, c, d) {
522
699
  t.decision = d.action;
523
- if (d.action === 'dispatch') return dispatch(t, c, d.handoff, true, d.ws || '');
700
+ if (d.action === 'dispatch') return dispatch(t, c, d.handoff, true, d.ws || '', d.worker || '');
524
701
  if (d.action === 'continue') return continueWith(t, c, d.target);
525
702
  if (d.action === 'interrupt') return interruptWith(t, c, d.target);
526
703
  if (d.action === 'stop') return stopTask(t, d.target);
@@ -536,7 +713,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
536
713
  }
537
714
  if (d.action === 'notify') {
538
715
  if (t.kind !== 'report') return fallback(t, c, 'notify 只用于汇报');
539
- if (c.quiet) {
716
+ if (t.quiet || c.quiet) {
540
717
  t.reason = '不推送的任务';
541
718
  save();
542
719
  return undefined;
@@ -547,35 +724,43 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
547
724
  return fallback(t, c, `看不懂的决定 ${d.action || '(没写)'}`);
548
725
  }
549
726
 
550
- // 取走排队的触发交给路由(合批:一轮把排队的全部处理掉),再把决定做掉
727
+ // 取走排队的触发交给路由(合批:一轮把排队的全部处理掉),再把决定做掉。
728
+ // 这一轮要发给用户的话先攒着(outbox),决定都做完了合成尽量少的消息发
551
729
  async function pump() {
552
730
  if (busy || closing || !queue.length) return;
553
731
  busy = true;
554
732
  const ids = queue.splice(0);
733
+ const box = [];
734
+ outbox = box;
555
735
  try {
556
- let result = null;
557
- if (router) {
558
- const batch = ids.map((id) => triggers()[id]).filter(Boolean);
559
- result = await router.decide(batch.map(view), openItems(), ws.discoverWorkspaces(root, env));
560
- state.data.rounds = [...(state.data.rounds || []), { at: fmtStamp(), uid: uid(), ok: result.ok, n: batch.length, seconds: (router.last() || {}).seconds || 0 }];
561
- log(result.ok ? '路由出决定' : '路由没出决定', `${batch.length} 条${result.ok ? '' : `:${result.failed}`}`);
562
- }
736
+ const r = routerNow();
737
+ const batch = ids.map((id) => triggers()[id]).filter(Boolean);
738
+ // 给路由看的几组执行者:各有几个名额、此刻在跑几个、排着几个
739
+ const groups = roster().workers.map((w) => {
740
+ const pool = pools.get(w.id);
741
+ return { ...w, running: pool ? pool.running().length : 0, queued: pool ? pool.queued().length : 0 };
742
+ });
743
+ const result = await r.decide(batch.map(view), openItems(), ws.discoverWorkspaces(root, envNow), groups);
744
+ state.data.rounds = [...(state.data.rounds || []), { at: fmtStamp(), uid: uid(), ok: result.ok, n: batch.length, seconds: (r.last() || {}).seconds || 0 }];
745
+ log(result.ok ? '路由出决定' : '路由没出决定', `${batch.length} 条${result.ok ? '' : `:${result.failed}`}`);
563
746
  for (const id of ids) {
564
747
  const t = triggers()[id];
565
748
  if (!t) continue;
566
- const d = result && result.decisions[id];
749
+ const d = result.decisions[id];
567
750
  if (d && d.action) await act(t, live.get(id) || {}, d);
568
- else await fallback(t, live.get(id) || {}, result ? (result.failed || `路由漏了 ${id}`) : '直通');
751
+ else await fallback(t, live.get(id) || {}, result.failed || `路由漏了 ${id}`);
569
752
  }
570
753
  } catch (error) {
571
754
  log('引擎出错', error && error.message ? error.message : String(error));
572
755
  for (const id of ids) {
573
756
  const t = triggers()[id];
574
- if (t && !t.decision) await fallback(t, live.get(id) || {}, `引擎出错:${error && error.message ? error.message : error}`);
757
+ if (t && !t.decision) await fallback(t, live.get(id) || {}, `引擎出错:${error && error.message ? error.message : String(error)}`);
575
758
  }
576
759
  } finally {
577
- // 这一批的决定、发没发,都记下来
760
+ outbox = null;
761
+ // 这一批的决定、发没发,都记下来;攒着的话这时才发。发完才算这一轮结束(waitIdle 等的就是它)
578
762
  save();
763
+ await flushOutbox(box);
579
764
  busy = false;
580
765
  }
581
766
  pump();
@@ -604,7 +789,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
604
789
  handoff.writeTask(root, { ...t, text: '' }, refineBody(dailyFile(root, date)), { mode: cfg.agentMode, timeoutS: cfg.taskTimeout });
605
790
  save();
606
791
  log('提炼开始', t.id);
607
- return launch(t, { mode: cfg.agentMode, timeoutS: cfg.taskTimeout });
792
+ return launch(t, { mode: cfg.agentMode, timeoutS: cfg.taskTimeout, group: groupOf('') });
608
793
  }
609
794
 
610
795
  // 提炼做完:只记一笔。失败只记日志和监控,不告诉用户(晚间复盘会自己再采一遍、炼一遍)
@@ -622,6 +807,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
622
807
  if (!unfinished && !t.reportPending) continue;
623
808
  if (unfinished) {
624
809
  handoff.writeResult(root, t.id, '', { ok: false, reason: '服务重启时中断', by: 'cli-fail' });
810
+ handoff.attachTrail(root, t.id);
625
811
  Object.assign(t.worker, { status: 'failed', reason: '服务重启时中断', endedAt: fmtStamp() });
626
812
  }
627
813
  delete t.reportPending;
@@ -630,15 +816,24 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
630
816
  save();
631
817
  }
632
818
 
633
- // 服务要停了:在跑的执行者是子进程,得收掉(最多等 3 秒)。之后不再交给路由
819
+ // 服务要停了:在跑的执行者是子进程,得收掉(最多等 3 秒)。之后不再交给路由。
820
+ // 攒着的汇报也不交了:那几件攒的时候就记着「还没汇报」,下次启动 recover() 补
634
821
  async function shutdown() {
635
822
  closing = true;
823
+ if (held.length) log('服务停止', `攒着的汇报 ${held.length} 条不交路由了,下次启动补`);
824
+ if (heldTimer) {
825
+ clearTimeout(heldTimer);
826
+ heldTimer = null;
827
+ }
828
+ held.length = 0;
636
829
  if (msgTimer) { clearTimeout(msgTimer); msgTimer = null; }
637
830
  msgBuf = null;
638
831
  activeProgress.clear();
639
832
  stopProgressTimer();
640
- for (const id of pool.queued()) pool.stop(id, '服务停止时中断');
641
- for (const e of pool.running()) pool.stop(e.id, '服务停止时中断');
833
+ for (const pool of allPools()) {
834
+ for (const id of pool.queued()) pool.stop(id, '服务停止时中断');
835
+ for (const e of pool.running()) pool.stop(e.id, '服务停止时中断');
836
+ }
642
837
  const pending = [...dones.values()];
643
838
  if (pending.length) await Promise.race([Promise.allSettled(pending), new Promise((resolve) => setTimeout(resolve, 3000))]);
644
839
  }
@@ -694,7 +889,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
694
889
  const key = `msg-${m.msgId}`;
695
890
  const text = s(m.content);
696
891
  const debounceS = Number(cfg.messageDebounce) || 0;
697
- if (!debounceS || !router) return enqueue('message', { key, text, mode: cfg.botMode });
892
+ if (!debounceS) return enqueue('message', { key, text, mode: cfg.botMode });
698
893
  if (Object.values(triggers()).some((x) => x.key === key) || (msgBuf && msgBuf.keys.includes(key))) return null;
699
894
  if (!msgBuf) msgBuf = { keys: [key], texts: [text], firstAt: Date.now() };
700
895
  else { msgBuf.keys.push(key); msgBuf.texts.push(text); }
@@ -704,40 +899,62 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
704
899
  return null;
705
900
  },
706
901
  flushMessages,
707
- schedule: (job, taskBody, taskTitle) => enqueue('schedule', { key: job.key, task: job.id, taskFile: `tasks/${job.id}.md`, taskBody, taskTitle, quiet: cfg.quiet.includes(job.id) }),
902
+ // 到点的任务变成一条触发。manual 为 true 是 work-rhythm run 手动跑的(监控里标出来)
903
+ schedule: (job, taskBody, taskTitle, { manual = false } = {}) => enqueue('schedule', { key: job.key, task: job.id, taskFile: `tasks/${job.id}.md`, taskBody, taskTitle, quiet: cfg.quiet.includes(job.id), manual }),
708
904
  recover,
709
905
  shutdown,
710
906
  tick,
711
907
  afterSync,
712
- // 页面上答了一张卡:一条 answer 触发给路由(rhythm.js 调;ask 里带着答案)。
713
- // 去重键用卡片 id;老办法登记的「未答」行没有卡片文件(id 是空的),用事项——不然第二张就会被当成重复丢掉
714
908
  // 页面上答一张卡(work-rhythm ask 的卡):卡片这一块已经取消(2026-12-03),答了只记一笔,不再派活
715
909
  answer: () => null,
716
910
  // 命令行走一遍:要发的文字交到这里,不真发
717
911
  setSink(fn) {
718
912
  sink = fn;
719
913
  },
720
- // 等到队列空、路由空、执行者都结束。返回是不是等到了
914
+ // 网页上保存了名册之后调:换一份设置(local.env 可能改过),路由按新配置重起,执行者下一次派活就用新的
915
+ setEnv(next) {
916
+ envNow = next;
917
+ },
918
+ // 等到队列空、路由空、执行者都结束、攒着的汇报都交出去了。返回是不是等到了
721
919
  async waitIdle(timeoutMs = 600000) {
722
920
  const until = Date.now() + timeoutMs;
723
921
  while (Date.now() < until) {
724
- if (!busy && !queue.length && !deferred && pool.idle()) return true;
922
+ if (!busy && !queue.length && !deferred && !held.length && allPools().every((p) => p.idle())) return true;
725
923
  await new Promise((resolve) => setTimeout(resolve, 100));
726
924
  }
727
925
  return false;
728
926
  },
729
- resetSession: () => router && router.resetSession(),
730
- forgetBoundLost: () => router && router.forgetBoundLost(),
731
- doctorProblems: () => (router ? router.doctorProblems() : []),
732
- notes: () => (router ? router.notes() : []),
733
- status: () => ({
734
- enabled: Boolean(router),
735
- since,
736
- router: { enabled: Boolean(router), agent: routerSpec.agent, model: routerSpec.model, effort: routerSpec.effort, session: router ? router.describeSession() : null, queue: queue.length, busy, last: router ? router.last() : null, roundsToday: roundsToday() },
737
- workers: { limit: cfg.workers, running: pool.running().map((e) => ({ id: e.id, since: e.startedAt, kind: e.meta.kind, task: e.meta.task || '' })), queued: pool.queued() },
738
- worker: workerSpec,
739
- }),
927
+ resetSession: () => routerNow().resetSession(),
928
+ // 直接发一段话给用户(值守对 /new 的那句确认):不挂在那条触发上,push 关着就不发
929
+ say: (text) => send(null, text, { mark: false }),
930
+ doctorProblems: () => rosterLib.inspect(root, envNow, roster()).problems,
931
+ notes: () => rosterLib.inspect(root, envNow, roster()).notes,
932
+ status: () => {
933
+ const team = roster();
934
+ const r = routerNow();
935
+ const groups = team.workers.map((w) => {
936
+ const pool = pools.get(w.id);
937
+ return { ...w, running: pool ? pool.running().length : 0, queued: pool ? pool.queued().length : 0 };
938
+ });
939
+ return {
940
+ since,
941
+ router: { agent: team.router.agent, model: team.router.model, effort: rosterLib.routerEffort(team.router), session: r.describeSession(), queue: queue.length, held: held.length, busy, last: r.last(), roundsToday: roundsToday() },
942
+ // running 的每一条:step 是执行者最近记的一步过程(steps 一共几步、stepAge 是几秒前记的);
943
+ // quietFor 是它几秒没输出了(只有边跑边输出的预置才有,别的是 -1)
944
+ workers: {
945
+ limit: groups.reduce((n, g) => n + g.count, 0),
946
+ groups,
947
+ running: runningAll().map((e) => {
948
+ const st = handoff.lastStatus(root, e.id);
949
+ const beat = pulse.get(e.id);
950
+ const now = Date.now();
951
+ return { id: e.id, since: e.startedAt, kind: e.meta.kind, task: e.meta.task || '', step: st.line, steps: st.count, stepAge: st.at ? Math.max(0, Math.round((now - st.at) / 1000)) : 0, quietFor: beat ? Math.max(0, Math.round((now - beat.outputAt) / 1000)) : -1 };
952
+ }),
953
+ queued: queuedAll(),
954
+ },
955
+ };
956
+ },
740
957
  };
741
958
  }
742
959
 
743
- module.exports = { createEngine, appendHistory, pruneState, historyStats, fire, queueDir, resultBody, pendingCards, dayEvents, eventKey, refineBody, ACK_TEXT, uid };
960
+ module.exports = { createEngine, appendHistory, pruneState, historyStats, fire, queueDir, resultBody, pendingCards, dayEvents, eventKey, refineBody, packOutbox, ACK_TEXT, uid };