work-rhythm 0.1.7 → 0.2.3

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 (43) hide show
  1. package/.agents/notes/AGENTS.md +8 -1
  2. package/.agents/notes/decisions/2026-12-01-interjections-batch-into-one-answer-and-interrupt-reruns.md +33 -0
  3. package/.agents/notes/decisions/2026-12-01-long-runs-are-bounded-by-silence-not-wall-clock.md +35 -0
  4. package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +41 -0
  5. package/.agents/notes/pitfalls/2026-12-01-launchd-install-bakes-invoking-node.md +28 -0
  6. package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +16 -0
  7. package/.agents/skills/work-rhythm/SKILL.md +14 -12
  8. package/README.md +7 -4
  9. package/collectors/local.env.example +10 -1
  10. package/docs/agents.md +28 -11
  11. package/docs/channels.md +9 -6
  12. package/docs/router-worker.md +241 -0
  13. package/docs/scheduled-tasks.md +4 -4
  14. package/package.json +1 -1
  15. package/scripts/cli.js +4 -3
  16. package/scripts/cmd/agent.js +78 -40
  17. package/scripts/cmd/check.js +4 -0
  18. package/scripts/cmd/listen.js +20 -4
  19. package/scripts/cmd/rhythm.js +9 -2
  20. package/scripts/cmd/trigger.js +143 -0
  21. package/scripts/lib/agent.js +377 -30
  22. package/scripts/lib/bot.js +140 -35
  23. package/scripts/lib/engine.js +523 -0
  24. package/scripts/lib/handoff.js +165 -0
  25. package/scripts/lib/launchd.js +49 -3
  26. package/scripts/lib/markdown.js +328 -38
  27. package/scripts/lib/rhythm.js +377 -33
  28. package/scripts/lib/router.js +161 -0
  29. package/scripts/lib/run.js +43 -0
  30. package/scripts/lib/view.js +583 -0
  31. package/scripts/lib/worker.js +97 -0
  32. package/scripts/test/agent.test.js +17 -9
  33. package/scripts/test/check.test.js +7 -2
  34. package/scripts/test/harness.js +13 -1
  35. package/scripts/test/listen.test.js +3 -3
  36. package/scripts/test/rhythm.test.js +42 -8
  37. package/scripts/test/router-helper.js +80 -0
  38. package/scripts/test/router.test.js +509 -0
  39. package/scripts/test/stubs.js +82 -12
  40. package/scripts/test/timeout.test.js +99 -0
  41. package/templates/00-config/profile.example.yaml +7 -0
  42. package/templates/AGENTS.md +3 -1
  43. package/templates/README.md +4 -1
@@ -0,0 +1,523 @@
1
+ // 引擎:触发 → 路由 → 执行者 → 汇报 → 发消息(docs/router-worker.md)。跑在本地服务(rhythm.js)的进程里;
2
+ // listen handle 在命令行的进程里也拿它走一遍(要发的文字交给 sink,不真发)。
3
+ // 触发的内容(原话、任务书正文、回执)只在内存里和 .agents/handoff/ 的文件里;state.json 只记元数据:
4
+ // triggers 每条的短号、去重键、来源、时间、决定、执行者的状态/用时/会话 id、发没发(留两天)
5
+ // history 每跑完一条记一行元数据(留 rhythm.history-keep 天),监控中心的次数和成功率从它算
6
+ // rounds 路由每一轮(留两天)
7
+ // seq 短号的序号
8
+ 'use strict';
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const { fmtStamp, today, humanDuration, progressPings } = require('./run');
12
+ const { roles } = require('./agent');
13
+ const handoff = require('./handoff');
14
+ const { createRouter } = require('./router');
15
+ const { createPool, runWorker } = require('./worker');
16
+
17
+ const ACK_TEXT = '收到,正在处理,稍等。'; // 和值守(bot.js)那句一样
18
+ // 上一句还没答完又来一句(插话):先回这句,告诉他会和上一句一起考虑
19
+ const ACK_MORE_TEXT = '收到,上一句还在答,这句会和它一起考虑。';
20
+ const TRIGGER_KEEP_DAYS = 2;
21
+ const OPEN_MAX = 10;
22
+ const OPEN_MS = 24 * 3600 * 1000;
23
+ const NOTE_BY_SERVICE = '(这次运行由 work-rhythm rhythm 发起:你最后写的那段总结写进回执,它会交给路由转述给用户,你自己不要再发。)';
24
+ const STATUS_CN = { queued: '排队中', running: '在跑', ok: '做完', failed: '没做成', stopped: '叫停' };
25
+ const DAY_MS = 24 * 3600 * 1000;
26
+ // 运行记录和路由轮数每一行的唯一 id:命令行和服务两个进程都会写状态文件,合并时靠它区分
27
+ let uidSeq = 0;
28
+ const uid = () => `${process.pid}:${Date.now().toString(36)}:${(uidSeq += 1)}`;
29
+
30
+ const pad6 = (n) => String(n).padStart(6, '0');
31
+ const s = (v) => String(v || '').trim();
32
+ const stampMs = (stamp) => new Date(String(stamp).replace(' ', 'T')).getTime();
33
+ const queueDir = (root) => path.join(root, '01-inbox', '_rhythm', 'queue');
34
+
35
+ // 每跑完一条记一行(只有元数据)。直通模式下的 rhythm run 也记,manual 标出来
36
+ function appendHistory(data, row) {
37
+ data.history = [...(data.history || []), { at: fmtStamp(), uid: uid(), ...row }];
38
+ }
39
+
40
+ // 清掉过期的:触发留两天,路由的轮数留两天,运行记录留 historyKeep 天
41
+ function pruneState(data, { historyKeep = 90, now = Date.now() } = {}) {
42
+ const cutoff = fmtStamp(new Date(now - TRIGGER_KEEP_DAYS * DAY_MS));
43
+ for (const [id, t] of Object.entries(data.triggers || {})) if (String(t.at || '') < cutoff) delete data.triggers[id];
44
+ data.rounds = (data.rounds || []).filter((r) => String(r.at || '') >= cutoff);
45
+ const old = fmtStamp(new Date(now - historyKeep * DAY_MS));
46
+ data.history = (data.history || []).filter((r) => String(r.at || '') >= old);
47
+ }
48
+
49
+ // 从历史里算一个任务的次数、成败、最近一次、平均用时(给监控中心)
50
+ function historyStats(data, taskId, now = new Date()) {
51
+ const p = (n) => String(n).padStart(2, '0');
52
+ const date = `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}`;
53
+ const rows = (data.history || []).filter((r) => r.task === taskId && r.kind === 'schedule');
54
+ const ok = rows.filter((r) => r.ok);
55
+ const done = rows.filter((r) => typeof r.seconds === 'number');
56
+ return {
57
+ today: rows.filter((r) => String(r.at).startsWith(date)).length,
58
+ ok: ok.length,
59
+ failed: rows.length - ok.length,
60
+ last: rows.length ? rows[rows.length - 1] : null,
61
+ avgSeconds: done.length ? Math.round(done.reduce((sum, r) => sum + r.seconds, 0) / done.length) : 0,
62
+ };
63
+ }
64
+
65
+ // work-rhythm trigger fire:写下一条等着服务的触发。服务没在跑就等着,起来后取走;超过一天的启动时清掉
66
+ function fire(root, { text, mode = 'plan' }) {
67
+ const dir = queueDir(root);
68
+ fs.mkdirSync(dir, { recursive: true });
69
+ const key = `manual-${Date.now()}-${Math.random().toString(16).slice(2, 6)}`;
70
+ fs.writeFileSync(path.join(dir, `${key}.json`), `${JSON.stringify({ text, mode, at: fmtStamp() })}\n`);
71
+ return key;
72
+ }
73
+
74
+ // 回执的正文:去掉开头那几行表头
75
+ function resultBody(text) {
76
+ const lines = String(text || '').split('\n');
77
+ let i = 0;
78
+ while (i < lines.length && (lines[i].startsWith('# ') || lines[i].startsWith('- ') || !lines[i].trim())) i += 1;
79
+ return lines.slice(i).join('\n').trim();
80
+ }
81
+
82
+ // cfg 来自 rhythm.js 的 loadConfig(router、routerTimeout、workers、handoffKeep、historyKeep、taskTimeout、agentMode、agentModel、
83
+ // agentEffort、push、quiet、links、baseUrl、serviceAlive、ack、botMode、botTimeout、replyMax、botPreamble)。state 是 { data, save }
84
+ function createEngine({ root, env, cfg, log = () => {}, push = async () => false, state, since = Date.now() }) {
85
+ const routerSpec = roles(env).router;
86
+ // 执行者的模型和强度:YZJ_WORKER_* > profile 的 rhythm.agent-* > YZJ_BOT_*
87
+ const workerSpec = {
88
+ agent: s(env.YZJ_WORKER_AGENT) || s(env.YZJ_BOT_AGENT),
89
+ model: s(env.YZJ_WORKER_MODEL) || cfg.agentModel || s(env.YZJ_BOT_MODEL),
90
+ effort: s(env.YZJ_WORKER_EFFORT) || cfg.agentEffort || s(env.YZJ_BOT_EFFORT),
91
+ };
92
+ const agentLabel = `${workerSpec.agent}${workerSpec.model ? `(${workerSpec.model})` : ''}`;
93
+ const triggers = () => state.data.triggers;
94
+ const save = () => state.save();
95
+ // 内存里的正文:短号 → { text, taskBody, taskFile, taskTitle, opening, linkTask, orig }
96
+ const live = new Map();
97
+ const queue = []; // 等路由的短号
98
+ const dones = new Map(); // 短号 → 执行者那次运行的 Promise(续做要等它做完)
99
+ let deferred = 0; // 等着前面那件做完才起的续做
100
+ let busy = false;
101
+ let closing = false; // 服务在停:不再交给路由
102
+ let pumpScheduled = false; // 这个 tick 里已经排了一轮
103
+ let sink = null;
104
+ const pool = createPool({ limit: cfg.workers });
105
+ const router = cfg.router ? createRouter({ root, env, role: routerSpec, timeoutS: cfg.routerTimeout, preamble: cfg.botPreamble || '', log }) : null;
106
+
107
+ // 权限和超时由触发来源定。重做的沿用原来那条的
108
+ function terms(t) {
109
+ if (t.kind === 'schedule') return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
110
+ if (t.kind === 'message') return { mode: cfg.botMode, timeoutS: cfg.botTimeout };
111
+ if (t.kind === 'report') {
112
+ const o = live.get(t.id) && live.get(t.id).orig;
113
+ if (o && o.worker && o.worker.mode) return { mode: o.worker.mode, timeoutS: o.worker.timeoutS || cfg.taskTimeout };
114
+ }
115
+ return { mode: (live.get(t.id) || {}).mode || 'plan', timeoutS: cfg.taskTimeout };
116
+ }
117
+
118
+ const isActive = (id) => pool.running().some((e) => e.id === id) || pool.queued().includes(id);
119
+
120
+ // 手头的事:在跑的、排队里的、今天做完的,给路由认「同一件事」用
121
+ function openItems() {
122
+ const now = Date.now();
123
+ const act = [...pool.running().map((e) => e.id), ...pool.queued()];
124
+ const row = (x) => ({ id: x.id, status: STATUS_CN[x.worker.status] || '在跑', at: x.at, title: x.title || '' });
125
+ 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));
126
+ return [...act.map((id) => triggers()[id]).filter(Boolean).map(row), ...done.map(row)].slice(0, OPEN_MAX);
127
+ }
128
+
129
+ // 给路由看的一条
130
+ const view = (t) => ({ id: t.id, kind: t.kind, at: t.at, quiet: t.quiet, task: t.task, of: t.of, ...live.get(t.id) });
131
+
132
+ function record(kind, fields) {
133
+ state.data.seq = (Number(state.data.seq) || 0) + 1;
134
+ const t = { id: `t-${pad6(state.data.seq)}`, kind, at: fmtStamp(), key: '', decision: '', reason: '', title: '', notified: false, ...fields };
135
+ triggers()[t.id] = t;
136
+ return t;
137
+ }
138
+
139
+ // 新的触发进队列。key 一样的只处理一次。返回记录,或者 null(重复的)
140
+ function enqueue(kind, { key = '', text = '', task = '', taskFile = '', taskBody = '', taskTitle = '', mode = '', of = '', ok = false, seconds = 0, reason = '', opening = '', quiet = false, linkTask = '', orig = null } = {}) {
141
+ if (key && Object.values(triggers()).some((x) => x.key === key)) return null;
142
+ const t = record(kind, { key, task, of, quiet });
143
+ live.set(t.id, { text, taskFile, taskBody, taskTitle, mode, opening, linkTask, orig, ok, seconds, reason });
144
+ queue.push(t.id);
145
+ save();
146
+ log('触发入队', `${t.id} ${kind}`);
147
+ // 有东西在做(路由在想、前面还排着、执行者在跑):这句不会马上答,先回一句「收到」,说会和上一句一起考虑
148
+ if (kind === 'message' && cfg.ack && (busy || queue.length > 1 || deferred || pool.running().length)) {
149
+ t.acked = true;
150
+ send(null, ACK_MORE_TEXT, { mark: false });
151
+ }
152
+ schedulePump();
153
+ return t;
154
+ }
155
+
156
+ // 同一个 tick 里到的触发合成一批:等到这个 tick 的最后再开始一轮
157
+ function schedulePump() {
158
+ if (pumpScheduled) return;
159
+ pumpScheduled = true;
160
+ setImmediate(() => {
161
+ pumpScheduled = false;
162
+ pump();
163
+ });
164
+ }
165
+
166
+ // 发一段文字给用户。命令行走一遍时交给 sink;push 关着只记日志
167
+ async function send(t, text, { mark = true, linkTask = '' } = {}) {
168
+ const chars = Array.from(String(text || '').trim());
169
+ if (!chars.length) return false;
170
+ let out = chars.length > cfg.replyMax ? `${chars.slice(0, cfg.replyMax).join('')}\n…(回复太长,截到 ${cfg.replyMax} 字)` : chars.join('');
171
+ const link = linkTask && cfg.links[linkTask];
172
+ if (link && cfg.serviceAlive()) out += `\n\n→ ${link.label}:${cfg.baseUrl}${link.path(today())}`;
173
+ if (mark && t) {
174
+ t.notified = true;
175
+ // 汇报发出去了,原来那件事也算「发了」(监控里看的就是那件事)
176
+ const origin = t.kind === 'report' && triggers()[t.of];
177
+ if (origin) origin.notified = true;
178
+ }
179
+ if (sink) {
180
+ sink(out);
181
+ return true;
182
+ }
183
+ if (!cfg.push) {
184
+ log('不推送', 'rhythm.push 关着');
185
+ return false;
186
+ }
187
+ try {
188
+ return await push(out);
189
+ } catch (error) {
190
+ log('推送出错', error && error.message ? error.message : String(error));
191
+ return false;
192
+ }
193
+ }
194
+
195
+ // 执行者结束:补回执、记一笔、生成汇报
196
+ function finishWorker(t, r) {
197
+ const ok = r.ok;
198
+ if (ok && !handoff.resultReady(root, t.id)) handoff.writeResult(root, t.id, r.reply, { ok: true, seconds: r.seconds, agent: agentLabel, by: 'cli' });
199
+ const body = r.stopped ? '用户叫停,这件事没做完。' : r.partial ? `时间到了,做到这里:\n\n${r.partial}` : '';
200
+ if (!ok) handoff.writeResult(root, t.id, body, { ok: false, reason: r.failed, seconds: r.seconds, agent: agentLabel, by: 'cli-fail' });
201
+ 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() });
202
+ 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' });
203
+ save();
204
+ log('执行者结束', `${t.id} ${ok ? '成功' : r.stopped ? '叫停' : '失败'} ${r.seconds}s`);
205
+ const c = live.get(t.id) || {};
206
+ // 被插话停掉的:不汇报,接着它重跑的那次会汇报
207
+ if (t.suppressReport) {
208
+ delete t.suppressReport;
209
+ save();
210
+ return r;
211
+ }
212
+ // 服务正在停:不再交给路由,记一笔,下次启动时 recover() 补汇报
213
+ if (closing) {
214
+ t.reportPending = true;
215
+ save();
216
+ return r;
217
+ }
218
+ enqueue('report', {
219
+ key: `report-${t.id}`, of: t.id, ok, seconds: r.seconds, reason: r.stopped ? '用户叫停' : r.failed, quiet: t.quiet,
220
+ opening: ok ? handoff.opening(resultBody(handoff.readText(handoff.resultPath(root, t.id)))) : '', linkTask: t.kind === 'schedule' ? t.task : '', orig: t, task: c.linkTask,
221
+ });
222
+ return r;
223
+ }
224
+
225
+ // 排一个执行者。after 给了就等那件事做完再起(续做一件还在跑的事)
226
+ function launch(t, { mode, timeoutS, resume = '', after = '' }) {
227
+ t.worker = { status: 'queued', mode, timeoutS, agent: workerSpec.agent, model: workerSpec.model, effort: workerSpec.effort, sessionId: resume || '' };
228
+ save();
229
+ const start = () => {
230
+ // 续做排在后面起:起的时候再读原来那件的会话 id(它可能到做完才有)
231
+ const target = after ? triggers()[after] : null;
232
+ const sid = resume || (target && target.worker && target.worker.sessionId) || '';
233
+ const p = pool.submit(t.id, async (ctrl) => {
234
+ t.worker.status = 'running';
235
+ t.worker.startedAt = fmtStamp();
236
+ save();
237
+ // 我这边直接派出去的(消息、手动)跑得久就先说一声;定时任务的汇报本来就会来,不额外打扰
238
+ const started = Date.now();
239
+ const pings = t.kind === 'schedule' || t.quiet ? { stop() {} } : progressPings({
240
+ firstS: cfg.progress, everyS: cfg.progress * 2, max: cfg.progressMax,
241
+ say: () => send(t, `还在做(已经 ${humanDuration((Date.now() - started) / 1000)}):${t.title || t.id}。做完汇报。`, { mark: false }),
242
+ });
243
+ let r;
244
+ try {
245
+ r = await runWorker({
246
+ root, env, log, id: t.id, mode, timeoutS, idleS: cfg.workerIdle, spec: workerSpec, resume: sid,
247
+ onSession: (sid) => {
248
+ if (t.worker.sessionId !== sid) {
249
+ t.worker.sessionId = sid;
250
+ save();
251
+ }
252
+ },
253
+ onKill: (fn) => ctrl.setKill(fn),
254
+ });
255
+ } finally {
256
+ pings.stop();
257
+ }
258
+ return finishWorker(t, r);
259
+ }, { kind: t.kind, task: t.task || '' });
260
+ dones.set(t.id, p);
261
+ return p;
262
+ };
263
+ const prev = after && dones.get(after);
264
+ if (prev && isActive(after)) {
265
+ log('续做排队', `${t.id} 等 ${after} 做完`);
266
+ deferred += 1;
267
+ return prev.then(() => {
268
+ deferred -= 1;
269
+ return start();
270
+ });
271
+ }
272
+ return start();
273
+ }
274
+
275
+ // 交给执行者:写任务书、起运行。路由没给任务书的(或者退路),拿原话或指令文件当任务书
276
+ function dispatch(t, c, handoffBody) {
277
+ let body = s(handoffBody);
278
+ const { mode, timeoutS } = terms(t);
279
+ if (t.kind === 'schedule') body = `${s(c.taskBody)}${body ? `\n\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
280
+ 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 || '按原任务书重做一遍。'}`;
281
+ else if (!body) body = `# 任务:照用户的话做\n\n用户原话:「${c.text}」\n\n照它做。这是一句追问、单凭这句话做不了的话,在回执里说清楚缺什么。`;
282
+ t.title = handoff.titleOf(body) || t.task || '';
283
+ handoff.writeTask(root, { ...t, text: c.text, taskFile: c.taskFile }, body, { mode, timeoutS });
284
+ save();
285
+ // 消息一来先回一句「收到」,路由慢的话我不用干等
286
+ if (t.kind === 'message' && cfg.ack && !t.acked) send(null, ACK_TEXT, { mark: false });
287
+ // 派出去就接着派下一条,不等它做完(汇报会自己排回来)
288
+ launch(t, { mode, timeoutS });
289
+ return undefined;
290
+ }
291
+
292
+ // 续做:用户这句话接着手头某件事说的。接着原来那个执行者的会话跑;它还在跑就排在后面
293
+ function continueWith(t, c, targetId) {
294
+ const target = triggers()[targetId];
295
+ if (!target || !openItems().some((o) => o.id === targetId)) {
296
+ return fallback(t, c, `continue 指向的 ${targetId || '(没写)'} 不在手头的事里`);
297
+ }
298
+ const body = `接着 ${targetId} 那件事做。旧任务书在 ${handoff.relTask(targetId)},旧回执在 ${handoff.relResult(targetId)},先读它们。\n\n用户追加:「${c.text}」\n\n按追加的要求继续。这次的结果单独写进回执,不要改旧回执。`;
299
+ const mode = (target.worker && target.worker.mode) || cfg.botMode;
300
+ const timeoutS = (target.worker && target.worker.timeoutS) || cfg.taskTimeout;
301
+ t.title = `${target.title || targetId}(续)`;
302
+ t.of = targetId;
303
+ handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
304
+ save();
305
+ launch(t, { mode, timeoutS, resume: (target.worker && target.worker.sessionId) || '', after: isActive(targetId) ? targetId : '' });
306
+ return undefined;
307
+ }
308
+
309
+ // 插话改要求:停掉在跑的那件事,带着新要求接着它的会话重跑。被停的那次不汇报(这次的结果会覆盖它)
310
+ function interruptWith(t, c, targetId) {
311
+ const target = triggers()[targetId];
312
+ if (!target || !isActive(targetId)) {
313
+ return fallback(t, c, `interrupt 指向的 ${targetId || '(没写)'} 不在跑`);
314
+ }
315
+ const body = `接着 ${targetId} 那件事做,但要求变了。旧任务书在 ${handoff.relTask(targetId)},先读它;上一次做到一半被用户叫停,回执在 ${handoff.relResult(targetId)}。\n\n用户插话:「${c.text}」\n\n按新的要求把这件事做完:上一次已经做过的部分,对了就沿用,不对就改。这次的结果单独写进回执,不要改旧回执。`;
316
+ const mode = target.worker.mode || cfg.botMode;
317
+ const timeoutS = target.worker.timeoutS || cfg.taskTimeout;
318
+ const resume = target.worker.sessionId || '';
319
+ t.title = `${target.title || targetId}(插话)`;
320
+ t.of = targetId;
321
+ target.suppressReport = true;
322
+ pool.stop(targetId, '用户插话,改了要求');
323
+ handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
324
+ save();
325
+ log('插话', `${t.id} 停掉 ${targetId} 带着新要求重跑`);
326
+ launch(t, { mode, timeoutS, resume });
327
+ return undefined;
328
+ }
329
+
330
+ // 叫停:排队里的拿掉,在跑的杀掉。它的回执和汇报照常生成
331
+ function stopTask(t, targetId) {
332
+ const target = triggers()[targetId];
333
+ if (!target || !isActive(targetId)) {
334
+ t.reason = `想叫停 ${targetId || '(没写)'},它已经不在跑了`;
335
+ save();
336
+ return undefined;
337
+ }
338
+ const where = pool.stop(targetId, '用户叫停');
339
+ t.reason = `叫停 ${targetId}`;
340
+ save();
341
+ log('叫停', `${targetId}(${where})`);
342
+ return undefined;
343
+ }
344
+
345
+ // 路由坏了、看不懂、漏了:按来源退回直通的做法,不丢东西
346
+ function fallback(t, c, why) {
347
+ t.decision = 'fallback';
348
+ t.reason = s(why).slice(0, 200);
349
+ if (t.kind === 'report') {
350
+ if (c.ok) {
351
+ if (c.quiet) {
352
+ save();
353
+ return Promise.resolve();
354
+ }
355
+ return send(t, resultBody(handoff.readText(handoff.resultPath(root, t.of))), { linkTask: c.linkTask });
356
+ }
357
+ return send(t, `「${c.linkTask || t.of}」没跑完:${c.reason}`);
358
+ }
359
+ return dispatch(t, c, '');
360
+ }
361
+
362
+ async function act(t, c, d) {
363
+ t.decision = d.action;
364
+ if (d.action === 'dispatch') return dispatch(t, c, d.handoff);
365
+ if (d.action === 'continue') return continueWith(t, c, d.target);
366
+ if (d.action === 'interrupt') return interruptWith(t, c, d.target);
367
+ if (d.action === 'stop') return stopTask(t, d.target);
368
+ if (d.action === 'reply') {
369
+ t.reason = '';
370
+ if (!s(d.text)) return fallback(t, c, '路由的 reply 没带文字');
371
+ return send(t, d.text);
372
+ }
373
+ if (d.action === 'ignore') {
374
+ t.reason = s(d.text).slice(0, 200);
375
+ save();
376
+ return undefined;
377
+ }
378
+ if (d.action === 'notify') {
379
+ if (t.kind !== 'report') return fallback(t, c, 'notify 只用于汇报');
380
+ if (c.quiet) {
381
+ t.reason = '不推送的任务';
382
+ save();
383
+ return undefined;
384
+ }
385
+ if (!s(d.text)) return fallback(t, c, '路由的 notify 没带文字');
386
+ return send(t, d.text, { linkTask: c.linkTask });
387
+ }
388
+ return fallback(t, c, `看不懂的决定 ${d.action || '(没写)'}`);
389
+ }
390
+
391
+ // 取走排队的触发交给路由(合批:一轮把排队的全部处理掉),再把决定做掉
392
+ async function pump() {
393
+ if (busy || closing || !queue.length) return;
394
+ busy = true;
395
+ const ids = queue.splice(0);
396
+ try {
397
+ let result = null;
398
+ if (router) {
399
+ const batch = ids.map((id) => triggers()[id]).filter(Boolean);
400
+ result = await router.decide(batch.map(view), openItems());
401
+ state.data.rounds = [...(state.data.rounds || []), { at: fmtStamp(), uid: uid(), ok: result.ok, n: batch.length, seconds: (router.last() || {}).seconds || 0 }];
402
+ log(result.ok ? '路由出决定' : '路由没出决定', `${batch.length} 条${result.ok ? '' : `:${result.failed}`}`);
403
+ }
404
+ for (const id of ids) {
405
+ const t = triggers()[id];
406
+ if (!t) continue;
407
+ const d = result && result.decisions[id];
408
+ if (d && d.action) await act(t, live.get(id) || {}, d);
409
+ else await fallback(t, live.get(id) || {}, result ? (result.failed || `路由漏了 ${id}`) : '直通');
410
+ }
411
+ } catch (error) {
412
+ log('引擎出错', error && error.message ? error.message : String(error));
413
+ for (const id of ids) {
414
+ const t = triggers()[id];
415
+ if (t && !t.decision) await fallback(t, live.get(id) || {}, `引擎出错:${error && error.message ? error.message : error}`);
416
+ }
417
+ } finally {
418
+ // 这一批的决定、发没发,都记下来
419
+ save();
420
+ busy = false;
421
+ }
422
+ pump();
423
+ }
424
+
425
+ // 服务启动时:上次没跑完的执行者各补一份失败的回执,变成汇报交回路由;停服务时没来得及汇报的也补上
426
+ function recover() {
427
+ for (const t of Object.values(triggers())) {
428
+ if (!t.worker) continue;
429
+ const unfinished = ['queued', 'running'].includes(t.worker.status);
430
+ if (!unfinished && !t.reportPending) continue;
431
+ if (unfinished) {
432
+ handoff.writeResult(root, t.id, '', { ok: false, reason: '服务重启时中断', by: 'cli-fail' });
433
+ Object.assign(t.worker, { status: 'failed', reason: '服务重启时中断', endedAt: fmtStamp() });
434
+ }
435
+ delete t.reportPending;
436
+ enqueue('report', { key: `report-${t.id}`, of: t.id, ok: t.worker.status === 'ok', seconds: t.worker.seconds || 0, reason: t.worker.reason || '', quiet: t.quiet, linkTask: t.kind === 'schedule' ? t.task : '', orig: t });
437
+ }
438
+ save();
439
+ }
440
+
441
+ // 服务要停了:在跑的执行者是子进程,得收掉(最多等 3 秒)。之后不再交给路由
442
+ async function shutdown() {
443
+ closing = true;
444
+ for (const id of pool.queued()) pool.stop(id, '服务停止时中断');
445
+ for (const e of pool.running()) pool.stop(e.id, '服务停止时中断');
446
+ const pending = [...dones.values()];
447
+ if (pending.length) await Promise.race([Promise.allSettled(pending), new Promise((resolve) => setTimeout(resolve, 3000))]);
448
+ }
449
+
450
+ // 取走 trigger fire 写下的触发;超过一天的清掉
451
+ function collectQueue() {
452
+ const dir = queueDir(root);
453
+ let names;
454
+ try {
455
+ names = fs.readdirSync(dir);
456
+ } catch {
457
+ return;
458
+ }
459
+ const cutoff = Date.now() - DAY_MS;
460
+ for (const name of names) {
461
+ const file = path.join(dir, name);
462
+ try {
463
+ if (!name.endsWith('.json')) continue;
464
+ if (fs.statSync(file).mtimeMs < cutoff) {
465
+ fs.unlinkSync(file);
466
+ continue;
467
+ }
468
+ const item = JSON.parse(fs.readFileSync(file, 'utf8'));
469
+ fs.unlinkSync(file);
470
+ enqueue('manual', { key: `fired-${name.slice(0, -5)}`, text: s(item.text), mode: s(item.mode) || 'plan' });
471
+ } catch (error) {
472
+ log('排队文件读不了', `${name} ${error.message}`);
473
+ }
474
+ }
475
+ }
476
+
477
+ // 服务每次看表时调:清过期的交接文档、取走排队的触发
478
+ function tick() {
479
+ handoff.cleanup(root, cfg.handoffKeep);
480
+ collectQueue();
481
+ }
482
+
483
+ const roundsToday = () => {
484
+ const date = today();
485
+ const rounds = (state.data.rounds || []).filter((r) => String(r.at).startsWith(date));
486
+ return { total: rounds.length, failed: rounds.filter((r) => !r.ok).length };
487
+ };
488
+
489
+ return {
490
+ enqueue,
491
+ message: (m) => enqueue('message', { key: `msg-${m.msgId}`, text: s(m.content), mode: cfg.botMode }),
492
+ 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) }),
493
+ recover,
494
+ shutdown,
495
+ tick,
496
+ // 命令行走一遍:要发的文字交到这里,不真发
497
+ setSink(fn) {
498
+ sink = fn;
499
+ },
500
+ // 等到队列空、路由空、执行者都结束。返回是不是等到了
501
+ async waitIdle(timeoutMs = 600000) {
502
+ const until = Date.now() + timeoutMs;
503
+ while (Date.now() < until) {
504
+ if (!busy && !queue.length && !deferred && pool.idle()) return true;
505
+ await new Promise((resolve) => setTimeout(resolve, 100));
506
+ }
507
+ return false;
508
+ },
509
+ resetSession: () => router && router.resetSession(),
510
+ forgetBoundLost: () => router && router.forgetBoundLost(),
511
+ doctorProblems: () => (router ? router.doctorProblems() : []),
512
+ notes: () => (router ? router.notes() : []),
513
+ status: () => ({
514
+ enabled: Boolean(router),
515
+ since,
516
+ 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() },
517
+ 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() },
518
+ worker: workerSpec,
519
+ }),
520
+ };
521
+ }
522
+
523
+ module.exports = { createEngine, appendHistory, pruneState, historyStats, fire, queueDir, resultBody, ACK_TEXT, uid };