work-rhythm 0.2.20 → 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 (74) 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-question-cards-via-cli-tool-on-todays-page-answers-return-to-router.md +4 -0
  7. package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +1 -0
  8. package/.agents/notes/decisions/2026-12-01-router-runs-on-a-flash-model-with-low-effort.md +1 -0
  9. package/.agents/notes/decisions/2026-12-01-sync-feeds-refine-then-events-to-the-router.md +4 -0
  10. package/.agents/notes/decisions/2026-12-03-codex-cli-joins-as-a-preset-verified-against-its-own-binary.md +45 -0
  11. package/.agents/notes/decisions/2026-12-03-fewer-scheduled-tasks-silent-refine-no-question-cards.md +46 -0
  12. package/.agents/notes/decisions/2026-12-03-playbook-distills-handoffs-into-ws-tool-and-skill-know-how.md +43 -0
  13. package/.agents/notes/decisions/2026-12-03-related-work-comes-back-as-one-reply.md +49 -0
  14. package/.agents/notes/decisions/2026-12-03-roster-of-worker-groups-router-picks-the-group.md +33 -0
  15. package/.agents/notes/decisions/2026-12-03-router-model-and-effort-are-configurable.md +28 -0
  16. package/.agents/notes/decisions/2026-12-03-router-only-direct-mode-removed.md +27 -0
  17. package/.agents/notes/decisions/2026-12-03-unattended-runs-decide-on-their-own.md +32 -0
  18. package/.agents/notes/decisions/2026-12-03-update-upgrades-package-and-refreshes-shipped-files.md +30 -0
  19. package/.agents/notes/decisions/2026-12-03-workers-leave-a-status-trail-that-joins-the-receipt.md +31 -0
  20. package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +2 -0
  21. package/.agents/notes/pitfalls/2026-12-03-judging-a-symlink-by-realpath-ignores-parent-links.md +18 -0
  22. package/.agents/skills/work-rhythm/SKILL.md +21 -17
  23. package/README.md +13 -10
  24. package/collectors/local.env.example +31 -36
  25. package/docs/agents.md +61 -60
  26. package/docs/channels.md +15 -19
  27. package/docs/formats.md +28 -1
  28. package/docs/router-worker.md +67 -54
  29. package/docs/scheduled-tasks.md +14 -14
  30. package/docs/sources.md +5 -6
  31. package/package.json +1 -1
  32. package/scripts/cli.js +9 -5
  33. package/scripts/cmd/agent.js +348 -235
  34. package/scripts/cmd/ask.js +18 -76
  35. package/scripts/cmd/check.js +14 -7
  36. package/scripts/cmd/listen.js +33 -32
  37. package/scripts/cmd/pack.js +6 -6
  38. package/scripts/cmd/rhythm.js +13 -10
  39. package/scripts/cmd/trigger.js +23 -14
  40. package/scripts/cmd/update.js +92 -0
  41. package/scripts/lib/agent.js +235 -142
  42. package/scripts/lib/agents.js +179 -0
  43. package/scripts/lib/bot.js +44 -263
  44. package/scripts/lib/engine.js +345 -170
  45. package/scripts/lib/handoff.js +54 -8
  46. package/scripts/lib/markdown.js +19 -0
  47. package/scripts/lib/playbook.js +123 -0
  48. package/scripts/lib/rhythm.js +402 -260
  49. package/scripts/lib/router.js +52 -46
  50. package/scripts/lib/template.js +3 -3
  51. package/scripts/lib/update.js +279 -0
  52. package/scripts/lib/view.js +7 -152
  53. package/scripts/lib/worker.js +11 -5
  54. package/scripts/test/agent.test.js +410 -257
  55. package/scripts/test/check.test.js +17 -6
  56. package/scripts/test/harness.js +5 -2
  57. package/scripts/test/listen.test.js +190 -158
  58. package/scripts/test/playbook.test.js +106 -0
  59. package/scripts/test/rhythm.test.js +167 -109
  60. package/scripts/test/roster.test.js +155 -0
  61. package/scripts/test/router-helper.js +17 -2
  62. package/scripts/test/router.test.js +499 -414
  63. package/scripts/test/stubs.js +51 -4
  64. package/scripts/test/timeout.test.js +160 -59
  65. package/scripts/test/update.test.js +384 -0
  66. package/tasks/daily-persona.md +30 -13
  67. package/tasks/daily-plan.md +4 -3
  68. package/tasks/evening-review.md +1 -2
  69. package/tasks/noon-checkin.md +2 -1
  70. package/templates/00-config/profile.example.yaml +17 -13
  71. package/templates/04-patterns/PERSONA.md +4 -1
  72. package/templates/04-patterns/PLAYBOOK.md +13 -0
  73. package/templates/AGENTS.md +7 -3
  74. 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,46 +167,29 @@ function answerBody(c) {
163
167
  return lines.join('\n');
164
168
  }
165
169
 
166
- // 重点与待办的任务书:路由把一批新事件派出去时用(路由可以再补一段)。c.root 是工作目录
167
- function focusBody(c) {
168
- const list = (c.events || []).map((e) => `- ${e.time} ${e.type} ${e.item}${e.project ? `(${e.source},${e.project})` : e.source ? `(${e.source})` : ''}`).join('\n');
169
- const bad = (c.sources || []).filter((x) => !x.ok).map((x) => `${x.id}:${x.detail || `退出码 ${x.code}`}`).join(';');
170
- const file = dailyFile(c.root || '.', c.date || today());
171
- return [
172
- '# 任务:根据新到的事件更新今日重点和待办',
173
- '',
174
- `今天新到的事件(${(c.events || []).length} 条):`,
175
- list || '(没有新事件)',
176
- ...(bad ? ['', `这次采集有源没取到数据(回执里说清,涉及的事标「未取到」):${bad}`] : []),
177
- '',
178
- `1. 读今天每日文件(${file})的「## 计划」「## 事件流」「## 备注」,03-carryover/CARRYOVER.md 的未了结,05-goals/ 里进行中的目标。`,
179
- '2. 据此更新「## 计划」里的今日重点(不超过 3 条,每条带建议时间块和理由)。只改这一处;例行的事(通勤、打卡)不算重点。「待你定」不要再写进计划文件:需要我拿主意的事走下面的卡片。',
180
- '3. 需要我拿主意的事,逐件用 work-rhythm ask 丢出来(它会成一张卡,实时显示在今日页的「待你定」里)。先 work-rhythm ask list 看有没有同一件事还没答的,有就不重复问;没有就:',
181
- ' work-rhythm ask --json \'{"question":"<一句话的问题>","context":"<两三句背景:为什么现在要定、卡在哪>","options":[{"label":"<选项>","detail":"<一句话说明>","suggested":true},{"label":"<选项>"}],"record":"<我答了之后总结记到哪,如 03-carryover/CARRYOVER.md 的未了结>","item":"<不超过 30 字的短事项>"}\'',
182
- ' 2–4 个选项,其中一个标 suggested 并在 detail 里说理由;真没有可选的就不写 options(我会自己写回答)。没有要问的就不问。',
183
- '4. 回执按这个格式写(路由会转给用户,纯文本、不放链接):',
184
- ' 今日重点:',
185
- ' - …',
186
- ' 待办卡片(我会在今日页的「待你定」里点选项,不用你催):',
187
- ' 1. <事项>:<选项,标出建议的>',
188
- ' 2. …',
189
- ' 没有卡片就不写这一段。',
190
- '',
191
- '',
192
- ].join('\n');
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') }));
193
186
  }
194
187
 
195
- // cfg 来自 rhythm.js 的 loadConfig(router、routerTimeout、workers、handoffKeep、historyKeep、taskTimeout、agentMode、agentModel、
196
- // agentEffort、push、quiet、links、baseUrl、serviceAlive、ack、botMode、botTimeout、replyMax、botPreamble、refine、refineInterval)。state 是 { data, save }
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 }
197
190
  function createEngine({ root, env, cfg, log = () => {}, push = async () => false, state, since = Date.now() }) {
198
- const routerSpec = roles(env).router;
199
- // 执行者的模型和强度:YZJ_WORKER_* > profile 的 rhythm.agent-* > YZJ_BOT_*
200
- const workerSpec = {
201
- agent: s(env.YZJ_WORKER_AGENT) || s(env.YZJ_BOT_AGENT),
202
- model: s(env.YZJ_WORKER_MODEL) || cfg.agentModel || s(env.YZJ_BOT_MODEL),
203
- effort: s(env.YZJ_WORKER_EFFORT) || cfg.agentEffort || s(env.YZJ_BOT_EFFORT),
204
- };
205
- const agentLabel = `${workerSpec.agent}${workerSpec.model ? `(${workerSpec.model})` : ''}`;
191
+ let envNow = env; // setEnv 能换:网页上保存配置之后 local.env 可能改过(路由的会话)
192
+ const roster = () => rosterLib.loadRoster(root, envNow);
206
193
  const triggers = () => state.data.triggers;
207
194
  const save = () => state.save();
208
195
  triggersStore.set(root, triggers);
@@ -216,7 +203,11 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
216
203
  let pumpScheduled = false; // 这个 tick 里已经排了一轮
217
204
  let msgBuf = null;
218
205
  let msgTimer = null;
206
+ let outbox = null; // 路由这一轮要发给用户的话先攒在这儿([{ t, body, foot }]),决定都做完了再合成尽量少的消息发
207
+ const held = []; // 攒着的汇报 [{ fields, origin }]:手头还有别的活在跑时,先做完的等一等,一起交回路由
208
+ let heldTimer = null; // 等的上限(cfg.mergeWait 秒),到点先把攒着的交回
219
209
  const activeProgress = new Map(); // id → { t, started }
210
+ const pulse = new Map(); // 在跑的执行者 → { outputAt }:上一次收到它输出的时刻(只记边跑边输出的预置,别的家最后才吐)
220
211
  let progressTimer = null;
221
212
  let progressStepMs = 0;
222
213
  const MAX_PROGRESS_STEP_MS = 30 * 60 * 1000; // 指数退避封顶 30 分钟
@@ -234,11 +225,14 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
234
225
  const all = [...activeProgress.values()];
235
226
  if (all.length === 1) {
236
227
  const { t, started } = all[0];
237
- 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 });
238
231
  } else {
239
232
  const lines = ['手头有 ' + all.length + ' 件事还在做(做完汇报):'];
240
233
  all.forEach(({ t, started }, i) => {
241
- 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}` : ''}`);
242
236
  });
243
237
  send(null, lines.join('\n'), { mark: false });
244
238
  }
@@ -261,15 +255,56 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
261
255
  return enqueue('message', { key: b.keys[0], text: b.texts.join('\n'), mode: cfg.botMode });
262
256
  }
263
257
  let sink = null;
264
- const pool = createPool({ limit: cfg.workers });
265
- 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
+ }
266
301
 
267
302
  // 权限和超时由触发来源定。重做的沿用原来那条的。
268
303
  // IM 来的话(message)分两种:路由判成 dispatch 的是「派人做事」,事要写文件,按定时任务的权限来(rhythm.agent-mode)——
269
- // 2026-12-02 用户决定,原来一律只读,结果派出去的人写不了、做不成;路由没开时的直答(fallback)还是 YZJ_BOT_AGENT_MODE,默认只读
304
+ // 2026-12-02 用户决定,原来一律只读,结果派出去的人写不了、做不成;路由没出决定时的兜底还是 YZJ_BOT_AGENT_MODE(默认 plan,只读)
270
305
  function terms(t, { byRouter = false } = {}) {
271
- if (t.kind === 'schedule' || t.kind === 'events') return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
272
- if (t.kind === 'message' && router && byRouter) return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
306
+ if (t.kind === 'schedule') return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
307
+ if (t.kind === 'message' && byRouter) return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
273
308
  if (t.kind === 'answer') {
274
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];
275
310
  if (o && o.worker && o.worker.mode) return { mode: o.worker.mode, timeoutS: o.worker.timeoutS || cfg.taskTimeout };
@@ -283,13 +318,13 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
283
318
  return { mode: (live.get(t.id) || {}).mode || 'plan', timeoutS: cfg.taskTimeout };
284
319
  }
285
320
 
286
- 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);
287
322
 
288
- // 手头的事:在跑的、排队里的、今天做完的,给路由认「同一件事」用
323
+ // 手头的事:在跑的、排队里的、今天做完的,给路由认「同一件事」用。在跑的带上它最近记的一步过程(用户问「做到哪了」路由直接答)
289
324
  function openItems() {
290
325
  const now = Date.now();
291
- const act = [...pool.running().map((e) => e.id), ...pool.queued()];
292
- 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 : '' });
293
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));
294
329
  return [...act.map((id) => triggers()[id]).filter(Boolean).map(row), ...done.map(row)].slice(0, OPEN_MAX);
295
330
  }
@@ -305,19 +340,21 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
305
340
  }
306
341
 
307
342
  // 新的触发进队列。key 一样的只处理一次。返回记录,或者 null(重复的)
308
- 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 } = {}) {
309
346
  if (key && Object.values(triggers()).some((x) => x.key === key)) return null;
310
- const t = record(kind, { key, task, of, quiet });
347
+ const t = record(kind, { key, task, of, quiet, manual });
311
348
  live.set(t.id, { text, taskFile, taskBody, taskTitle, mode, opening, linkTask, orig, ok, seconds, reason, events, sources, ask, date, root: eventRoot || root });
312
- if (kind === 'events') t.title = `新事件 ${(events || []).length} 条 → 今日重点与待办`;
313
349
  if (kind === 'answer' && ask) t.title = `回答:${ask.item || ask.question || ''}`;
314
350
  queue.push(t.id);
315
351
  save();
316
352
  log('触发入队', `${t.id} ${kind}`);
317
- // 有东西在做(路由在想、前面还排着、执行者在跑):这句不会马上答,先回一句「收到」,说会和上一句一起考虑
318
- 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)) {
319
356
  t.acked = true;
320
- send(null, ACK_MORE_TEXT, { mark: false });
357
+ send(null, ACK_TEXT, { mark: false });
321
358
  }
322
359
  schedulePump();
323
360
  return t;
@@ -333,21 +370,29 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
333
370
  });
334
371
  }
335
372
 
336
- // 发一段文字给用户。命令行走一遍时交给 sink;push 关着只记日志
337
- async function send(t, text, { mark = true, linkTask = '' } = {}) {
373
+ // 一段话要发出去的样子:太长截断并注明;定时任务的汇报后面附本机页面地址。没内容返回 null
374
+ function dress(text, linkTask) {
338
375
  const chars = Array.from(String(text || '').trim());
339
- if (!chars.length) return false;
340
- let out = chars.length > cfg.replyMax ? `${chars.slice(0, cfg.replyMax).join('')}\n…(回复太长,截到 ${cfg.replyMax} 字)` : chars.join('');
376
+ if (!chars.length) return null;
341
377
  const link = linkTask && cfg.links[linkTask];
342
- if (link && cfg.serviceAlive()) out += `\n\n→ ${link.label}:${cfg.baseUrl}${link.path(today())}`;
343
- if (mark && t) {
344
- t.notified = true;
345
- // 汇报发出去了,原来那件事也算「发了」(监控里看的就是那件事)
346
- const origin = t.kind === 'report' && triggers()[t.of];
347
- if (origin) origin.notified = true;
348
- }
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) {
349
394
  if (sink) {
350
- sink(out);
395
+ sink(text);
351
396
  return true;
352
397
  }
353
398
  if (!cfg.push) {
@@ -355,33 +400,89 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
355
400
  return false;
356
401
  }
357
402
  try {
358
- return await push(out);
403
+ return await push(text);
359
404
  } catch (error) {
360
405
  log('推送出错', error && error.message ? error.message : String(error));
361
406
  return false;
362
407
  }
363
408
  }
364
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
+
365
462
  // 执行者结束:补回执、记一笔、生成汇报
366
463
  function finishWorker(t, r) {
367
464
  const ok = r.ok;
368
- 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' });
369
467
  const body = r.stopped ? '用户叫停,这件事没做完。' : r.partial ? `时间到了,做到这里:\n\n${r.partial}` : '';
370
- 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);
371
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() });
372
- 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) });
373
473
  save();
374
474
  log('执行者结束', `${t.id} ${ok ? '成功' : r.stopped ? '叫停' : '失败'} ${r.seconds}s`);
375
475
  const c = live.get(t.id) || {};
376
- // 提炼是 CLI 自己起的一步:做完了不算汇报,算出新增的事件打包成一条 events 触发给路由
476
+ // 提炼是 CLI 自己起的一步,静默:做完不汇报
377
477
  if (t.kind === 'refine') {
378
- afterRefine(t, r, c);
478
+ afterRefine(t, r);
379
479
  return r;
380
480
  }
381
481
  // 被插话停掉的:不汇报,接着它重跑的那次会汇报
382
482
  if (t.suppressReport) {
383
483
  delete t.suppressReport;
384
484
  save();
485
+ settleIfIdle(t);
385
486
  return r;
386
487
  }
387
488
  // 服务正在停:不再交给路由,记一笔,下次启动时 recover() 补汇报
@@ -390,28 +491,54 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
390
491
  save();
391
492
  return r;
392
493
  }
393
- enqueue('report', {
494
+ const fields = {
394
495
  key: `report-${t.id}`, of: t.id, ok, seconds: r.seconds, reason: r.stopped ? '用户叫停' : r.failed, quiet: t.quiet,
395
- opening: ok ? handoff.opening(resultBody(handoff.readText(handoff.resultPath(root, t.id)))) : '', linkTask: t.kind === 'schedule' ? t.task : t.kind === 'events' || t.kind === 'answer' ? 'todos' : '', orig: t, task: c.linkTask,
396
- });
496
+ opening: ok ? handoff.opening(resultBody(handoff.readText(handoff.resultPath(root, t.id)))) : '', linkTask: t.kind === 'schedule' ? t.task : '', orig: t, task: c.linkTask,
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);
397
516
  return r;
398
517
  }
399
518
 
400
- // 排一个执行者。after 给了就等那件事做完再起(续做一件还在跑的事)
401
- function launch(t, { mode, timeoutS, resume = '', after = '', cwd = '', agentOverride = '' }) {
402
- const spec = agentOverride ? { ...workerSpec, agent: agentOverride } : workerSpec;
403
- 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 || '' };
404
524
  save();
405
525
  const start = () => {
406
526
  // 续做排在后面起:起的时候再读原来那件的会话 id(它可能到做完才有)
407
527
  const target = after ? triggers()[after] : null;
408
528
  const sid = resume || (target && target.worker && target.worker.sessionId) || '';
409
- 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) => {
410
534
  t.worker.status = 'running';
411
535
  t.worker.startedAt = fmtStamp();
412
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() });
413
540
  // 我这边直接派出去的(消息、手动)跑得久就统一汇总说一声;定时任务的汇报本来就会来,不额外打扰
414
- const trackProgress = t.kind !== 'schedule' && !t.quiet && cfg.progress > 0;
541
+ const trackProgress = t.kind !== 'schedule' && !t.quiet && cfg.progress > 0; // 静默的(提炼、quiet 任务)不提示
415
542
  if (trackProgress) {
416
543
  activeProgress.set(t.id, { t, started: Date.now(), count: 0 });
417
544
  ensureProgressTimer();
@@ -419,16 +546,21 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
419
546
  let r;
420
547
  try {
421
548
  r = await runWorker({
422
- 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' },
423
- onSession: (sid) => {
424
- if (t.worker.sessionId !== sid) {
425
- 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;
426
553
  save();
427
554
  }
428
555
  },
556
+ onOutput: () => {
557
+ const beat = pulse.get(t.id);
558
+ if (beat) beat.outputAt = Date.now();
559
+ },
429
560
  onKill: (fn) => ctrl.setKill(fn),
430
561
  });
431
562
  } finally {
563
+ pulse.delete(t.id);
432
564
  if (trackProgress) {
433
565
  activeProgress.delete(t.id);
434
566
  if (!activeProgress.size) stopProgressTimer();
@@ -451,31 +583,40 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
451
583
  return start();
452
584
  }
453
585
 
454
- // 交给执行者:写任务书、起运行。路由没给任务书的(或者退路),拿原话或指令文件当任务书
455
- function dispatch(t, c, handoffBody, byRouter = false, wsId = '') {
586
+ // 交给执行者:写任务书、起运行。路由没给任务书的(或者兜底),拿原话或指令文件当任务书
587
+ function dispatch(t, c, handoffBody, byRouter = false, wsId = '', workerId = '') {
456
588
  let body = s(handoffBody);
457
589
  const { mode, timeoutS } = terms(t, { byRouter });
458
- 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;
459
592
  if (resolvedWs) {
460
593
  t.ws = resolvedWs.id;
461
594
  t.wsPath = resolvedWs.path;
462
595
  }
463
596
  if (t.kind === 'schedule') body = `${s(c.taskBody)}${body ? `\n\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
464
- else if (t.kind === 'events') body = `${focusBody({ ...c, root })}${body ? `\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
465
597
  else if (t.kind === 'answer') body = `${answerBody(c)}${body ? `\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
466
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 || '按原任务书重做一遍。'}`;
467
599
  else if (!body) body = `# 任务:照用户的话做\n\n用户原话:「${c.text}」\n\n照它做。这是一句追问、单凭这句话做不了的话,在回执里说清楚缺什么。`;
468
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}`;
469
603
  handoff.writeTask(root, { ...t, text: c.text, taskFile: c.taskFile }, body, { mode, timeoutS });
470
604
  save();
471
- // 消息一来先回一句「收到」,路由慢的话我不用干等
472
- if (t.kind === 'message' && cfg.ack && !t.acked) send(null, ACK_TEXT, { mark: false });
605
+ ackMessage(t);
473
606
  // 派出去就接着派下一条,不等它做完(汇报会自己排回来)
474
- 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 : '' });
475
608
  return undefined;
476
609
  }
477
610
 
478
- // 续做:用户这句话接着手头某件事说的。接着原来那个执行者的会话跑;它还在跑就排在后面
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
+ // 续做:用户这句话接着手头某件事说的。接着原来那个执行者的会话跑、还是它那一组;它还在跑就排在后面
479
620
  function continueWith(t, c, targetId) {
480
621
  const target = triggers()[targetId];
481
622
  if (!target || !openItems().some((o) => o.id === targetId)) {
@@ -491,11 +632,12 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
491
632
  if (target.ws) { t.ws = target.ws; t.wsPath = target.wsPath || ''; }
492
633
  handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
493
634
  save();
494
- 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 });
495
637
  return undefined;
496
638
  }
497
639
 
498
- // 插话改要求:停掉在跑的那件事,带着新要求接着它的会话重跑。被停的那次不汇报(这次的结果会覆盖它)
640
+ // 插话改要求:停掉在跑的那件事,带着新要求接着它的会话重跑(还是它那一组)。被停的那次不汇报(这次的结果会覆盖它)
499
641
  function interruptWith(t, c, targetId) {
500
642
  const target = triggers()[targetId];
501
643
  if (!target || !isActive(targetId)) {
@@ -509,11 +651,12 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
509
651
  t.of = targetId;
510
652
  if (target.ws) { t.ws = target.ws; t.wsPath = target.wsPath || ''; }
511
653
  target.suppressReport = true;
512
- pool.stop(targetId, '用户插话,改了要求');
654
+ poolOf(groupOf(target.worker && target.worker.id)).stop(targetId, '用户插话,改了要求');
513
655
  handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
514
656
  save();
515
657
  log('插话', `${t.id} 停掉 ${targetId} 带着新要求重跑`);
516
- 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 });
517
660
  return undefined;
518
661
  }
519
662
 
@@ -525,20 +668,23 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
525
668
  save();
526
669
  return undefined;
527
670
  }
528
- const where = pool.stop(targetId, '用户叫停');
671
+ const pool = target.worker && pools.get(target.worker.id);
672
+ const where = pool ? pool.stop(targetId, '用户叫停') : '';
529
673
  t.reason = `叫停 ${targetId}`;
530
674
  save();
531
675
  log('叫停', `${targetId}(${where})`);
532
676
  return undefined;
533
677
  }
534
678
 
535
- // 路由坏了、看不懂、漏了:按来源退回直通的做法,不丢东西
679
+ // 路由坏了、看不懂、漏了:按来源直接处理(兜底),不丢东西。
680
+ // 消息和手动塞进来的:原话当任务书派人(只读);到点的任务:指令文件当任务书;汇报:回执原样发回
536
681
  function fallback(t, c, why) {
537
682
  t.decision = 'fallback';
538
683
  t.reason = s(why).slice(0, 200);
539
684
  if (t.kind === 'report') {
540
685
  if (c.ok) {
541
- if (c.quiet) {
686
+ // 静默的标记在触发记录上(enqueue 写的),live 里没有
687
+ if (t.quiet || c.quiet) {
542
688
  save();
543
689
  return Promise.resolve();
544
690
  }
@@ -551,7 +697,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
551
697
 
552
698
  async function act(t, c, d) {
553
699
  t.decision = d.action;
554
- 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 || '');
555
701
  if (d.action === 'continue') return continueWith(t, c, d.target);
556
702
  if (d.action === 'interrupt') return interruptWith(t, c, d.target);
557
703
  if (d.action === 'stop') return stopTask(t, d.target);
@@ -567,7 +713,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
567
713
  }
568
714
  if (d.action === 'notify') {
569
715
  if (t.kind !== 'report') return fallback(t, c, 'notify 只用于汇报');
570
- if (c.quiet) {
716
+ if (t.quiet || c.quiet) {
571
717
  t.reason = '不推送的任务';
572
718
  save();
573
719
  return undefined;
@@ -578,80 +724,79 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
578
724
  return fallback(t, c, `看不懂的决定 ${d.action || '(没写)'}`);
579
725
  }
580
726
 
581
- // 取走排队的触发交给路由(合批:一轮把排队的全部处理掉),再把决定做掉
727
+ // 取走排队的触发交给路由(合批:一轮把排队的全部处理掉),再把决定做掉。
728
+ // 这一轮要发给用户的话先攒着(outbox),决定都做完了合成尽量少的消息发
582
729
  async function pump() {
583
730
  if (busy || closing || !queue.length) return;
584
731
  busy = true;
585
732
  const ids = queue.splice(0);
733
+ const box = [];
734
+ outbox = box;
586
735
  try {
587
- let result = null;
588
- if (router) {
589
- const batch = ids.map((id) => triggers()[id]).filter(Boolean);
590
- result = await router.decide(batch.map(view), openItems(), ws.discoverWorkspaces(root, env));
591
- state.data.rounds = [...(state.data.rounds || []), { at: fmtStamp(), uid: uid(), ok: result.ok, n: batch.length, seconds: (router.last() || {}).seconds || 0 }];
592
- log(result.ok ? '路由出决定' : '路由没出决定', `${batch.length} 条${result.ok ? '' : `:${result.failed}`}`);
593
- }
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}`}`);
594
746
  for (const id of ids) {
595
747
  const t = triggers()[id];
596
748
  if (!t) continue;
597
- const d = result && result.decisions[id];
749
+ const d = result.decisions[id];
598
750
  if (d && d.action) await act(t, live.get(id) || {}, d);
599
- else await fallback(t, live.get(id) || {}, result ? (result.failed || `路由漏了 ${id}`) : '直通');
751
+ else await fallback(t, live.get(id) || {}, result.failed || `路由漏了 ${id}`);
600
752
  }
601
753
  } catch (error) {
602
754
  log('引擎出错', error && error.message ? error.message : String(error));
603
755
  for (const id of ids) {
604
756
  const t = triggers()[id];
605
- 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)}`);
606
758
  }
607
759
  } finally {
608
- // 这一批的决定、发没发,都记下来
760
+ outbox = null;
761
+ // 这一批的决定、发没发,都记下来;攒着的话这时才发。发完才算这一轮结束(waitIdle 等的就是它)
609
762
  save();
763
+ await flushOutbox(box);
610
764
  busy = false;
611
765
  }
612
766
  pump();
613
767
  }
614
768
 
615
- // 定时采集之后(rhythm.js 调):有新数据、或者有源没取到,就起一轮提炼;做完把新增的事件打包给路由
769
+ // 定时采集之后(rhythm.js 调):有新数据就静默起一轮提炼,把新采到的数据炼成事件(带工作现场索引)并进事件流。
770
+ // 静默:不交给路由、不打扰用户;源没取到数据只记日志和监控(2026-12-03 用户决定,看板和提醒太多)
616
771
  async function afterSync({ results = [], changed = false } = {}) {
617
- if (!router || !cfg.refine) return null;
772
+ if (!cfg.refine) return null;
618
773
  const bad = results.filter((x) => !x.ok);
619
- // 没有新数据:不炼。有源出事就把采集状态直接给路由(不用等提炼),路由决定要不要告诉用户
774
+ if (bad.length) log('采集有源没取到', bad.map((x) => `${x.id}:${x.detail || `退出码 ${x.code}`}`).join(';'));
775
+ // 没有新数据:不炼
620
776
  if (!changed) {
621
777
  log('提炼跳过', '没有新数据');
622
- if (bad.length) enqueue('events', { key: `events-sync-${Date.now()}`, ok: true, events: [], sources: results, date: today(), root });
623
778
  return null;
624
779
  }
625
- // 新数据等够间隔再炼(rhythm.refine-interval 分钟);这期间有源出事也直接告诉路由
780
+ // 新数据等够间隔再炼(rhythm.refine-interval 分钟)
626
781
  const last = state.data.refinedAt;
627
782
  if (last && Date.now() - stampMs(last) < cfg.refineInterval * 60000) {
628
783
  log('提炼跳过', `上一次 ${last},不到 ${cfg.refineInterval} 分钟`);
629
- if (bad.length) enqueue('events', { key: `events-sync-${Date.now()}`, ok: true, events: [], sources: results, date: today(), root });
630
784
  return null;
631
785
  }
632
786
  const date = today();
633
- const t = record('refine', { key: `refine-${date}-${Date.now()}`, decision: 'refine', title: '把今天新采到的数据提炼成事件' });
634
- live.set(t.id, { results, date, before: new Set(dayEvents(root, date).map(eventKey)), root });
787
+ const t = record('refine', { key: `refine-${date}-${Date.now()}`, decision: 'refine', quiet: true, title: '把今天新采到的数据提炼成事件' });
788
+ live.set(t.id, { results, date, root });
635
789
  handoff.writeTask(root, { ...t, text: '' }, refineBody(dailyFile(root, date)), { mode: cfg.agentMode, timeoutS: cfg.taskTimeout });
636
790
  save();
637
791
  log('提炼开始', t.id);
638
- return launch(t, { mode: cfg.agentMode, timeoutS: cfg.taskTimeout });
792
+ return launch(t, { mode: cfg.agentMode, timeoutS: cfg.taskTimeout, group: groupOf('') });
639
793
  }
640
794
 
641
- // 提炼做完:比对话件里的事件流,新增的打包成 events 触发给路由。没新增、也没源出事就不打扰路由
642
- function afterRefine(t, r, c) {
795
+ // 提炼做完:只记一笔。失败只记日志和监控,不告诉用户(晚间复盘会自己再采一遍、炼一遍)
796
+ function afterRefine(t, r) {
643
797
  state.data.refinedAt = fmtStamp();
644
798
  save();
645
- const date = c.date || today();
646
- let events = [];
647
- if (r.ok) {
648
- const before = c.before || new Set();
649
- events = dayEvents(root, date).filter((e) => !before.has(eventKey(e)));
650
- log('提炼结束', `${t.id} 新增 ${events.length} 条事件`);
651
- }
652
- const bad = (c.results || []).filter((x) => !x.ok);
653
- if (!r.ok) enqueue('events', { key: `events-${t.id}`, of: t.id, ok: false, reason: r.failed, events: [], sources: c.results || [], date, root });
654
- else if (events.length || bad.length) enqueue('events', { key: `events-${t.id}`, of: t.id, ok: true, events, sources: c.results || [], date, root });
799
+ log('提炼结束', r.ok ? t.id : `${t.id} 失败:${r.failed || '未知原因'}`);
655
800
  }
656
801
 
657
802
  // 服务启动时:上次没跑完的执行者各补一份失败的回执,变成汇报交回路由;停服务时没来得及汇报的也补上
@@ -662,6 +807,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
662
807
  if (!unfinished && !t.reportPending) continue;
663
808
  if (unfinished) {
664
809
  handoff.writeResult(root, t.id, '', { ok: false, reason: '服务重启时中断', by: 'cli-fail' });
810
+ handoff.attachTrail(root, t.id);
665
811
  Object.assign(t.worker, { status: 'failed', reason: '服务重启时中断', endedAt: fmtStamp() });
666
812
  }
667
813
  delete t.reportPending;
@@ -670,15 +816,24 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
670
816
  save();
671
817
  }
672
818
 
673
- // 服务要停了:在跑的执行者是子进程,得收掉(最多等 3 秒)。之后不再交给路由
819
+ // 服务要停了:在跑的执行者是子进程,得收掉(最多等 3 秒)。之后不再交给路由。
820
+ // 攒着的汇报也不交了:那几件攒的时候就记着「还没汇报」,下次启动 recover() 补
674
821
  async function shutdown() {
675
822
  closing = true;
823
+ if (held.length) log('服务停止', `攒着的汇报 ${held.length} 条不交路由了,下次启动补`);
824
+ if (heldTimer) {
825
+ clearTimeout(heldTimer);
826
+ heldTimer = null;
827
+ }
828
+ held.length = 0;
676
829
  if (msgTimer) { clearTimeout(msgTimer); msgTimer = null; }
677
830
  msgBuf = null;
678
831
  activeProgress.clear();
679
832
  stopProgressTimer();
680
- for (const id of pool.queued()) pool.stop(id, '服务停止时中断');
681
- 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
+ }
682
837
  const pending = [...dones.values()];
683
838
  if (pending.length) await Promise.race([Promise.allSettled(pending), new Promise((resolve) => setTimeout(resolve, 3000))]);
684
839
  }
@@ -703,13 +858,10 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
703
858
  }
704
859
  const item = JSON.parse(fs.readFileSync(file, 'utf8'));
705
860
  fs.unlinkSync(file);
706
- // 执行者用 work-rhythm ask 丢出来的卡:直接把问题推给我、带着今日页的地址(实时显示在那儿),不花路由一轮
861
+ // 执行者 work-rhythm ask 丢出来的问题:不再推给我、也不成卡(2026-12-03 用户决定,「待你定」整块取消)。只记一笔日志和监控
707
862
  if (item.kind === 'ask') {
708
863
  const ask = asks.readAsk(root, item.ask);
709
- if (ask && !ask.answer) {
710
- log('待你定', `${ask.id} ${ask.item}`);
711
- send(null, `等你定:${asks.askSummary(ask)}${ask.context ? `\n${ask.context}` : ''}`, { linkTask: 'todos' });
712
- }
864
+ if (ask && !ask.answer) log('执行者想问', `${ask.id} ${ask.item || ''}`.trim());
713
865
  continue;
714
866
  }
715
867
  enqueue('manual', { key: `fired-${name.slice(0, -5)}`, text: s(item.text), mode: s(item.mode) || 'plan' });
@@ -737,7 +889,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
737
889
  const key = `msg-${m.msgId}`;
738
890
  const text = s(m.content);
739
891
  const debounceS = Number(cfg.messageDebounce) || 0;
740
- if (!debounceS || !router) return enqueue('message', { key, text, mode: cfg.botMode });
892
+ if (!debounceS) return enqueue('message', { key, text, mode: cfg.botMode });
741
893
  if (Object.values(triggers()).some((x) => x.key === key) || (msgBuf && msgBuf.keys.includes(key))) return null;
742
894
  if (!msgBuf) msgBuf = { keys: [key], texts: [text], firstAt: Date.now() };
743
895
  else { msgBuf.keys.push(key); msgBuf.texts.push(text); }
@@ -747,39 +899,62 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
747
899
  return null;
748
900
  },
749
901
  flushMessages,
750
- 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 }),
751
904
  recover,
752
905
  shutdown,
753
906
  tick,
754
907
  afterSync,
755
- // 页面上答了一张卡:一条 answer 触发给路由(rhythm.js 调;ask 里带着答案)。
756
- // 去重键用卡片 id;老办法登记的「未答」行没有卡片文件(id 是空的),用事项——不然第二张就会被当成重复丢掉
757
- answer: (ask) => (router ? enqueue('answer', { key: `answer-${ask.id || ask.item}`, of: ask.from && ask.from.trigger ? ask.from.trigger : '', ask, root }) : null),
908
+ // 页面上答一张卡(work-rhythm ask 的卡):卡片这一块已经取消(2026-12-03),答了只记一笔,不再派活
909
+ answer: () => null,
758
910
  // 命令行走一遍:要发的文字交到这里,不真发
759
911
  setSink(fn) {
760
912
  sink = fn;
761
913
  },
762
- // 等到队列空、路由空、执行者都结束。返回是不是等到了
914
+ // 网页上保存了名册之后调:换一份设置(local.env 可能改过),路由按新配置重起,执行者下一次派活就用新的
915
+ setEnv(next) {
916
+ envNow = next;
917
+ },
918
+ // 等到队列空、路由空、执行者都结束、攒着的汇报都交出去了。返回是不是等到了
763
919
  async waitIdle(timeoutMs = 600000) {
764
920
  const until = Date.now() + timeoutMs;
765
921
  while (Date.now() < until) {
766
- if (!busy && !queue.length && !deferred && pool.idle()) return true;
922
+ if (!busy && !queue.length && !deferred && !held.length && allPools().every((p) => p.idle())) return true;
767
923
  await new Promise((resolve) => setTimeout(resolve, 100));
768
924
  }
769
925
  return false;
770
926
  },
771
- resetSession: () => router && router.resetSession(),
772
- forgetBoundLost: () => router && router.forgetBoundLost(),
773
- doctorProblems: () => (router ? router.doctorProblems() : []),
774
- notes: () => (router ? router.notes() : []),
775
- status: () => ({
776
- enabled: Boolean(router),
777
- since,
778
- 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() },
779
- 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() },
780
- worker: workerSpec,
781
- }),
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
+ },
782
957
  };
783
958
  }
784
959
 
785
- module.exports = { createEngine, appendHistory, pruneState, historyStats, fire, queueDir, resultBody, pendingCards, dayEvents, eventKey, refineBody, focusBody, ACK_TEXT, uid };
960
+ module.exports = { createEngine, appendHistory, pruneState, historyStats, fire, queueDir, resultBody, pendingCards, dayEvents, eventKey, refineBody, packOutbox, ACK_TEXT, uid };