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,161 @@
1
+ // 路由:一个常驻的 agent 会话,收到一批触发,回一批决定(docs/router-worker.md 的「路由」)。
2
+ // 只读,不查数据不改文件,给用户的话也只是写出来、由 CLI 发。会话就是绑定的那个(YZJ_ROUTER_SESSION,没写看 YZJ_BOT_SESSION),
3
+ // 它记得桌面上聊过什么;没绑、或者绑的接不上,用它自己的专属会话(01-inbox/_bot/session-id)。
4
+ // 它回一段 Markdown:先列决定行(「- t-000123 dispatch」),要文字的决定各给一个小节(「## handoff t-000123」),解析在 handoff.js。
5
+ 'use strict';
6
+ const fs = require('node:fs');
7
+ const path = require('node:path');
8
+ const { createAgent } = require('./agent');
9
+ const { fmtStamp } = require('./run');
10
+ const handoff = require('./handoff');
11
+
12
+ const PROMPT = `${handoff.MARKER}下面是到达的触发,前面是「手头的事」。你是路由,只做判断和分派,不自己动手:读文件、查数据、改文件、发消息都交给执行者去做。执行者是全新的会话,看不到这里的对话,只看得到你写给它的任务书。
13
+ 每条触发给一个决定,七种:
14
+ - dispatch:交给一个执行者。写一个「## handoff <短号>」小节当任务书,把要做的事写全:目标、相关背景(日期、涉及的文件、之前做到哪一步、我在 IM 里说过的要求)、完成标准。任务书开头用一级标题写一句标题。执行者不能向我提问,取不到的数据它会写「未取到」。
15
+ - continue:用户这句话是接着「手头的事」里某一件说的(追问、改要求、让它接着做)。只写一行「- <触发的短号> continue <那件事的短号>」,不用写任务书——CLI 会把原话和旧任务书、旧回执的路径交给原来那个执行者。那件事还在跑的话,续做会排在它后面。拿不准是不是同一件事,就当新的 dispatch。
16
+ - interrupt:用户这句话改了「手头的事」里正在跑的那件事的要求(改主意、纠正、补了关键信息),等它做完就来不及。只写一行「- <触发的短号> interrupt <那件事的短号>」,不用写任务书——CLI 会停掉在跑的执行者,带着新要求接着它的会话重跑。只是补充一句、不影响它在做的,用 continue(排在它后面);完全不要了,用 stop。
17
+ - stop:用户叫停「手头的事」里的某一件。只写一行「- <触发的短号> stop <那件事的短号>」。
18
+ - reply:不用动手、一句话能答的(打招呼、道谢、确认、凭你已经知道的信息直接回答),写「## reply <短号>」。
19
+ - ignore:不用处理,写「## ignore <短号>」和一句原因。
20
+ - notify:只用于「汇报」类触发。先读回执再写「## notify <短号>」:发给用户的纯文本(IM 私聊),简短直接,不用表格、不放链接,要用户拿主意的事列在最后。执行者失败时说明是什么没做成、为什么;想重做就用 dispatch 并写任务书。
21
+ 规则:message 来源的是用户刚说的话,要有回音;schedule 来源的是用户自己定下的定时任务,默认 dispatch、不用写任务书(CLI 直接把指令文件当任务书),只有同一件事刚刚做过才可以 ignore;要补充要求(比如我今天说过下午请假)才写「## handoff」,它会接在指令后面;标了「不推送」的汇报不能 notify。
22
+ 只输出决定和小节,不要别的话;决定写成「- <短号> <决定>」;小节标题严格写成「## <决定> <短号>」,任务书正文里别用这个样子的小节标题。`;
23
+
24
+ const short = (stamp) => String(stamp || '').slice(5, 16);
25
+ const readText = (file) => {
26
+ try {
27
+ return fs.readFileSync(file, 'utf8');
28
+ } catch {
29
+ return '';
30
+ }
31
+ };
32
+
33
+ // 一条触发在提示词里的样子:短的全带上,长的只给路径和开头
34
+ function triggerLine(t) {
35
+ const when = short(t.at);
36
+ if (t.kind === 'message') return `[${t.id}] 来源=message 时间=${when} 原话:${t.text}`;
37
+ if (t.kind === 'manual') return `[${t.id}] 来源=manual 时间=${when} 原话:${t.text}`;
38
+ if (t.kind === 'schedule') return `[${t.id}] 来源=schedule 时间=${when} 任务=${t.task} 指令=${t.taskFile}${t.taskTitle ? `(${t.taskTitle})` : ''}`;
39
+ const head = `[${t.id}] 来源=report 时间=${when} 对应=${t.of} 结果=${t.ok ? '成功' : '失败'}${t.ok ? ` 用时=${t.seconds}s` : ` 原因=${t.reason}`} 回执=${handoff.relResult(t.of)}${t.quiet ? '(不推送)' : ''}`;
40
+ return t.ok ? `${head}\n 开头:${t.opening}` : head;
41
+ }
42
+
43
+ // 一轮的提示词:固定的说明 + 手头的事 + 这一批触发。extra 是重试时的一句提醒
44
+ function turnPrompt(triggers, open, extra = '') {
45
+ const lines = [PROMPT];
46
+ if (extra) lines.push('', extra);
47
+ lines.push('', '手头的事(在跑的和今天做完的):');
48
+ if (!open.length) lines.push('- (没有)');
49
+ for (const o of open) lines.push(`- ${o.id} ${o.status},${short(o.at)}:${o.title || '(没写标题)'}`);
50
+ lines.push('', '触发:');
51
+ for (const t of triggers) lines.push(triggerLine(t));
52
+ return lines.join('\n');
53
+ }
54
+
55
+ // role 是 agent.roles(env).router:{ agent, model, effort, session }
56
+ function createRouter({ root, env, role, timeoutS = 120, preamble = '', log = () => {} }) {
57
+ const STATE_DIR = path.join(root, '01-inbox', '_bot');
58
+ const SESSION_FILE = path.join(STATE_DIR, 'session-id');
59
+ const LOST_FILE = path.join(STATE_DIR, 'bound-session-lost');
60
+ // 绑定的会话接不上过一次就不再试,用专属会话;「接不上过」记在 bound-session-lost 里(换绑或 /new 时清掉)
61
+ const BOUND = role.session;
62
+ let boundLost = Boolean(BOUND) && readText(LOST_FILE).trim() === BOUND;
63
+ const agent = createAgent({ root, agent: role.agent, mode: 'plan', timeoutS, preamble, log, env, model: role.model, effort: role.effort });
64
+ let last = null;
65
+
66
+ const startSession = () => (BOUND && !boundLost ? BOUND : readText(SESSION_FILE).trim());
67
+ function markBoundLost() {
68
+ boundLost = true;
69
+ try {
70
+ fs.mkdirSync(STATE_DIR, { recursive: true });
71
+ fs.writeFileSync(LOST_FILE, `${BOUND}\n`);
72
+ } catch {
73
+ // 记不下来就只在这次进程里有效
74
+ }
75
+ }
76
+ function forgetBoundLost() {
77
+ boundLost = false;
78
+ try {
79
+ fs.unlinkSync(LOST_FILE);
80
+ } catch {
81
+ // 本来就没有
82
+ }
83
+ }
84
+ function clearSession() {
85
+ try {
86
+ fs.unlinkSync(SESSION_FILE);
87
+ } catch {
88
+ // 本来就没有
89
+ }
90
+ }
91
+ const sessionLost = (used) => {
92
+ if (used && used === BOUND) markBoundLost();
93
+ clearSession();
94
+ };
95
+ // /new:丢掉专属会话;绑了会话的,下一句又从绑的那个开始
96
+ function resetSession() {
97
+ clearSession();
98
+ if (BOUND) forgetBoundLost();
99
+ }
100
+
101
+ // 跑一轮。返回 { reply } 或 { failed, config? }
102
+ async function turn(prompt) {
103
+ const used = startSession();
104
+ const r = await agent.start(prompt, { session: used, onSessionLost: () => sessionLost(used), stateDir: STATE_DIR }).done;
105
+ if (!r.failed && r.sessionId && !(BOUND && !boundLost)) {
106
+ try {
107
+ fs.mkdirSync(STATE_DIR, { recursive: true });
108
+ fs.writeFileSync(SESSION_FILE, `${r.sessionId}\n`);
109
+ } catch {
110
+ // 记不下会话 id 就每次新开
111
+ }
112
+ }
113
+ return r;
114
+ }
115
+
116
+ // 对一批触发出决定。解析不出来、或者漏了触发,带着一句提醒再来一轮;再不行返回 ok 为 false(missing 是漏掉的短号)
117
+ async function decide(triggers, open) {
118
+ const started = Date.now();
119
+ const ids = triggers.map((t) => t.id);
120
+ let extra = '';
121
+ let lastReply = '';
122
+ for (let attempt = 0; attempt < 2; attempt += 1) {
123
+ const r = await turn(turnPrompt(triggers, open, extra));
124
+ if (r.failed) {
125
+ last = { at: fmtStamp(), seconds: Math.round((Date.now() - started) / 1000), ok: false };
126
+ return { ok: false, failed: r.failed, config: r.config, decisions: {}, missing: ids };
127
+ }
128
+ lastReply = r.reply;
129
+ const list = handoff.parseRouterReply(r.reply);
130
+ const decisions = {};
131
+ for (const d of list) decisions[d.id] = d;
132
+ const missing = ids.filter((id) => !decisions[id] || !decisions[id].action);
133
+ if (!missing.length) {
134
+ last = { at: fmtStamp(), seconds: Math.round((Date.now() - started) / 1000), ok: true };
135
+ return { ok: true, decisions, missing: [] };
136
+ }
137
+ extra = `上一轮的输出里没有这些触发的决定:${missing.join('、')}。每条都要有「- <短号> <决定>」,照上面的格式重新给出全部决定。`;
138
+ log('路由漏了', missing.join('、'));
139
+ }
140
+ last = { at: fmtStamp(), seconds: Math.round((Date.now() - started) / 1000), ok: false };
141
+ const decisions = {};
142
+ for (const d of handoff.parseRouterReply(lastReply)) decisions[d.id] = d;
143
+ return { ok: false, failed: `路由两轮都没给全决定(漏了 ${ids.filter((id) => !decisions[id] || !decisions[id].action).join('、')})`, decisions, missing: ids.filter((id) => !decisions[id] || !decisions[id].action) };
144
+ }
145
+
146
+ return {
147
+ agent,
148
+ startSession,
149
+ resetSession,
150
+ forgetBoundLost,
151
+ sessionFile: SESSION_FILE,
152
+ doctorProblems: () => agent.doctor(),
153
+ notes: () => agent.notes(),
154
+ // 现在用的是哪个会话:{ bound, own, id }
155
+ describeSession: () => ({ bound: BOUND, own: !BOUND || boundLost, id: startSession() }),
156
+ last: () => last,
157
+ decide,
158
+ };
159
+ }
160
+
161
+ module.exports = { createRouter, turnPrompt, triggerLine, PROMPT };
@@ -145,7 +145,50 @@ function walkFiles(root, prune, sinceMs, out = []) {
145
145
  return out;
146
146
  }
147
147
 
148
+ // 0 也是有效值(关掉某个闸)的秒数:没写(undefined / 空串)用默认,写了 0 就是 0
149
+ const seconds = (value, fallback) => {
150
+ const text = String(value ?? '').trim();
151
+ if (!text) return fallback;
152
+ const n = Number(text);
153
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
154
+ };
155
+
156
+ // 一段秒数说成人话:「25 秒」「1 分 30 秒」「12 分」
157
+ function humanDuration(totalSeconds) {
158
+ const s = Math.max(0, Math.round(Number(totalSeconds) || 0));
159
+ if (s < 60) return `${s} 秒`;
160
+ const m = Math.floor(s / 60);
161
+ const rest = s % 60;
162
+ return rest ? `${m} 分 ${rest} 秒` : `${m} 分`;
163
+ }
164
+
165
+ // 跑得久的时候隔一阵说一声:firstS 秒后第一条,之后每 everyS 秒一条,最多 max 条;max 为 0 或 firstS 为 0 就不发。
166
+ // say(第几条) 里自己算要说的话,发不出去(抛错)也不影响正在跑的事。返回 { stop() },跑完记得叫停
167
+ function progressPings({ firstS = 0, everyS = 0, max = 3, say = () => {} } = {}) {
168
+ let count = 0;
169
+ let timer = null;
170
+ const stop = () => {
171
+ if (timer) clearTimeout(timer);
172
+ timer = null;
173
+ count = max; // 叫停之后再到点的也不再发
174
+ };
175
+ const tick = () => {
176
+ timer = null;
177
+ if (count >= max) return;
178
+ count += 1;
179
+ try {
180
+ say(count);
181
+ } catch {
182
+ // 发不出去就算了,别把正在跑的事搅了
183
+ }
184
+ if (count < max && everyS > 0) timer = setTimeout(tick, everyS * 1000);
185
+ };
186
+ if (firstS > 0 && max > 0) timer = setTimeout(tick, firstS * 1000);
187
+ return { stop };
188
+ }
189
+
148
190
  module.exports = {
149
191
  EXIT, Fail, UsageError, noon, pad, fmtDate, fmtStamp, today, parseDate, addDays, daysBetween,
150
192
  weekdayCn, weekdayAbbr, run, which, isExecutable, readText, writeFileAtomic, tail, startOfDay, walkFiles,
193
+ seconds, humanDuration, progressPings,
151
194
  };