work-rhythm 0.1.8 → 0.2.11

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 (51) hide show
  1. package/.agents/notes/AGENTS.md +12 -1
  2. package/.agents/notes/decisions/2026-12-01-agent-runs-the-login-for-the-user.md +30 -0
  3. package/.agents/notes/decisions/2026-12-01-interjections-batch-into-one-answer-and-interrupt-reruns.md +33 -0
  4. package/.agents/notes/decisions/2026-12-01-long-runs-are-bounded-by-silence-not-wall-clock.md +35 -0
  5. package/.agents/notes/decisions/2026-12-01-question-cards-via-cli-tool-on-todays-page-answers-return-to-router.md +40 -0
  6. package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +42 -0
  7. package/.agents/notes/decisions/2026-12-01-router-runs-on-a-flash-model-with-low-effort.md +33 -0
  8. package/.agents/notes/decisions/2026-12-01-sync-feeds-refine-then-events-to-the-router.md +38 -0
  9. package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +16 -0
  10. package/.agents/notes/pitfalls/2026-12-02-rhythm-start-in-the-foreground-displaces-the-launchd-service.md +27 -0
  11. package/.agents/skills/work-rhythm/SKILL.md +20 -12
  12. package/README.md +32 -4
  13. package/collectors/local.env.example +10 -1
  14. package/docs/agents.md +53 -13
  15. package/docs/channels.md +9 -6
  16. package/docs/router-worker.md +263 -0
  17. package/docs/scheduled-tasks.md +5 -5
  18. package/docs/sources.md +20 -0
  19. package/package.json +1 -1
  20. package/scripts/cli.js +5 -3
  21. package/scripts/cmd/agent.js +188 -49
  22. package/scripts/cmd/ask.js +104 -0
  23. package/scripts/cmd/check.js +4 -0
  24. package/scripts/cmd/listen.js +18 -4
  25. package/scripts/cmd/rhythm.js +6 -2
  26. package/scripts/cmd/sync.js +11 -3
  27. package/scripts/cmd/trigger.js +143 -0
  28. package/scripts/lib/agent.js +482 -30
  29. package/scripts/lib/asks.js +145 -0
  30. package/scripts/lib/bot.js +140 -35
  31. package/scripts/lib/engine.js +707 -0
  32. package/scripts/lib/handoff.js +167 -0
  33. package/scripts/lib/markdown.js +355 -36
  34. package/scripts/lib/rhythm.js +576 -38
  35. package/scripts/lib/router.js +208 -0
  36. package/scripts/lib/run.js +43 -0
  37. package/scripts/lib/view.js +736 -0
  38. package/scripts/lib/worker.js +98 -0
  39. package/scripts/test/agent.test.js +126 -9
  40. package/scripts/test/check.test.js +7 -2
  41. package/scripts/test/harness.js +15 -1
  42. package/scripts/test/listen.test.js +2 -2
  43. package/scripts/test/rhythm.test.js +109 -6
  44. package/scripts/test/router-helper.js +110 -0
  45. package/scripts/test/router.test.js +799 -0
  46. package/scripts/test/stubs.js +113 -12
  47. package/scripts/test/timeout.test.js +99 -0
  48. package/tasks/daily-plan.md +1 -2
  49. package/templates/00-config/profile.example.yaml +9 -0
  50. package/templates/AGENTS.md +3 -1
  51. package/templates/README.md +4 -1
@@ -0,0 +1,208 @@
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, ROUTER_EFFORT } = require('./agent');
9
+ const { fmtStamp } = require('./run');
10
+ const handoff = require('./handoff');
11
+
12
+ const PROMPT = `${handoff.MARKER}下面是到达的触发,前面是「手头的事」。
13
+
14
+ 你是路由。你只做一件事:给每条触发一个决定;要动手的事,写成任务书派人。你自己不查资料、不改文件、不发消息——这些由执行者去做。执行者是全新的会话,看不到这里的对话,只能看到你写的任务书。
15
+
16
+ 一、每种触发默认怎么判
17
+ - 来源=message(用户在 IM 里刚说的话):要么 reply(一句话能答的),要么 dispatch(要动手的)。必须有回音,不能不理。
18
+ - 来源=manual(用户从命令行塞进来的一句话):同 message。
19
+ - 来源=schedule(用户自己定的定时任务):一律 dispatch,不用写任务书(CLI 直接用指令文件)。只有同一件事今天刚做过才 ignore。
20
+ - 来源=report(执行者做完了):读回执,写 notify 告诉用户结果;失败了说清什么没做成、为什么;想让它重做就 dispatch 并写任务书。
21
+ - 来源=events(定时采集之后一批新到的事件,外加这次采集的状态):这是「今天有什么新情况」的例行汇报。默认 dispatch,不用写任务书(CLI 用固定的任务书让执行者更新今日重点、用 work-rhythm ask 登记待办卡片);采集出了故障才在「## handoff」里补一句让执行者顺带说清哪个源没取到;新事件全是无关紧要的(通勤、打卡)可以 ignore。
22
+ - 来源=answer(用户在页面上回答了一张待办卡片):看「原执行者」是不是还在「手头的事」里——在就 continue <原执行者短号>;不在就 dispatch,不用写任务书(CLI 会把原问题、我的回答、要记到哪里写成任务书交给执行者)。
23
+ - message 里是在回答某张待办卡片(「1 选 2」这种):dispatch,task 写清是哪一条事项、选了第几个选项;执行者会 work-rhythm decisions answer 并照选项做。
24
+
25
+ 二、七种决定(每条触发只能选一种)
26
+ - dispatch:派人做。要写一个「## handoff <短号>」小节当任务书。
27
+ - reply:不用动手、一句话直接答。写「## reply <短号>」。只用于 message / manual。
28
+ - ignore:不用处理。写「## ignore <短号>」和一句原因。
29
+ - notify:给用户的话。写「## notify <短号>」。只用于 report。
30
+ - continue <短号>:这句话是接着「手头的事」里某一件说的(追问、补充,不改它在做的)。不用写任务书,CLI 会把原话交给原来那个执行者;那件还在跑就排在它后面。
31
+ - interrupt <短号>:这句话改了某件正在跑的事的要求(改主意、纠正),等它做完就来不及。CLI 会停掉它、带着新要求重跑。不用写任务书。
32
+ - stop <短号>:用户不要某件正在跑的事了。
33
+
34
+ 三、任务书怎么写(dispatch 的时候)
35
+ 第一行是一级标题,一句话说清要做什么。下面写:1)目标;2)背景——日期、涉及的文件、之前做到哪一步、用户在 IM 里说过的要求;3)做法(有必要才写);4)完成标准。把用户原话里的要求都写进去,别让执行者去猜。执行者不能向用户提问,取不到的数据它会写「未取到」。
36
+
37
+ 四、输出格式(严格遵守,别的什么都不写)
38
+ 决定:
39
+ - <短号> <决定>
40
+ - <短号> <决定> <目标那件事的短号>
41
+
42
+ ## handoff <短号>
43
+ # 一句话标题
44
+ 任务书正文……
45
+
46
+ ## reply <短号>
47
+ 一句话……
48
+
49
+ ## notify <短号>
50
+ 给用户的话(纯文本,简短直接,不用表格、不放链接,要用户拿主意的事放在最后)……
51
+
52
+ 五、硬规则
53
+ 1. 每条触发都要有、且只有一个决定,写在最前面的「决定:」下面。
54
+ 2. 决定行写成「- <短号> <决定>」;小节标题严格是「## <决定> <短号>」。
55
+ 3. 任务书正文里不要出现「## reply / ignore / handoff / notify <短号>」这样的标题。
56
+ 4. continue / interrupt / stop 后面的短号,必须是「手头的事」里列出来的。
57
+ 5. 标了「不推送」的汇报不能 notify。`;
58
+
59
+ const short = (stamp) => String(stamp || '').slice(5, 16);
60
+ const readText = (file) => {
61
+ try {
62
+ return fs.readFileSync(file, 'utf8');
63
+ } catch {
64
+ return '';
65
+ }
66
+ };
67
+
68
+ // 一条触发在提示词里的样子:短的全带上,长的只给路径和开头
69
+ function triggerLine(t) {
70
+ const when = short(t.at);
71
+ if (t.kind === 'message') return `[${t.id}] 来源=message 时间=${when} 原话:${t.text}`;
72
+ if (t.kind === 'manual') return `[${t.id}] 来源=manual 时间=${when} 原话:${t.text}`;
73
+ if (t.kind === 'schedule') return `[${t.id}] 来源=schedule 时间=${when} 任务=${t.task} 指令=${t.taskFile}${t.taskTitle ? `(${t.taskTitle})` : ''}`;
74
+ if (t.kind === 'events') {
75
+ const health = (t.sources || []).map((x) => `${x.id} ${x.ok ? '成功' : `失败:${x.detail || `退出码 ${x.code}`}`}`).join('、');
76
+ const head = `[${t.id}] 来源=events 时间=${when} ${t.ok ? `新事件 ${(t.events || []).length} 条` : `提炼没成:${t.reason}`};这次采集:${health || '(没跑)'}`;
77
+ const list = (t.events || []).slice(0, 40).map((e) => ` - ${e.time} ${e.type} ${e.item}(${[e.source, e.project].filter(Boolean).join(',')})`);
78
+ return [head, ...list].join('\n');
79
+ }
80
+ if (t.kind === 'answer') {
81
+ const a = t.ask || {};
82
+ const ans = a.answer || {};
83
+ return `[${t.id}] 来源=answer 时间=${when} 卡片=${a.id || '(老卡片)'}${t.of ? ` 原执行者=${t.of}` : ''} 问题:「${a.question || a.item || ''}」 回答:「${ans.choice || ''}」${ans.note ? ` 附言:「${ans.note}」` : ''}${a.record ? ` 记到:${a.record}` : ''}`;
84
+ }
85
+ const head = `[${t.id}] 来源=report 时间=${when} 对应=${t.of} 结果=${t.ok ? '成功' : '失败'}${t.ok ? ` 用时=${t.seconds}s` : ` 原因=${t.reason}`} 回执=${handoff.relResult(t.of)}${t.quiet ? '(不推送)' : ''}`;
86
+ return t.ok ? `${head}\n 开头:${t.opening}` : head;
87
+ }
88
+
89
+ // 一轮的提示词:固定的说明 + 手头的事 + 这一批触发。extra 是重试时的一句提醒
90
+ function turnPrompt(triggers, open, extra = '') {
91
+ const lines = [PROMPT];
92
+ if (extra) lines.push('', extra);
93
+ lines.push('', '手头的事(在跑的和今天做完的):');
94
+ if (!open.length) lines.push('- (没有)');
95
+ for (const o of open) lines.push(`- ${o.id} ${o.status},${short(o.at)}:${o.title || '(没写标题)'}`);
96
+ lines.push('', '触发:');
97
+ for (const t of triggers) lines.push(triggerLine(t));
98
+ return lines.join('\n');
99
+ }
100
+
101
+ // role 是 agent.roles(env).router:{ agent, model, effort, session }
102
+ function createRouter({ root, env, role, timeoutS = 120, preamble = '', log = () => {} }) {
103
+ const STATE_DIR = path.join(root, '01-inbox', '_bot');
104
+ const SESSION_FILE = path.join(STATE_DIR, 'session-id');
105
+ const LOST_FILE = path.join(STATE_DIR, 'bound-session-lost');
106
+ // 绑定的会话接不上过一次就不再试,用专属会话;「接不上过」记在 bound-session-lost 里(换绑或 /new 时清掉)
107
+ const BOUND = role.session;
108
+ let boundLost = Boolean(BOUND) && readText(LOST_FILE).trim() === BOUND;
109
+ // 思考强度固定 low:路由只做判断,配置里写了别的也不认(docs/agents.md 的「两个角色」)
110
+ const agent = createAgent({ root, agent: role.agent, mode: 'plan', timeoutS, preamble, log, env, model: role.model, effort: ROUTER_EFFORT });
111
+ let last = null;
112
+
113
+ const startSession = () => (BOUND && !boundLost ? BOUND : readText(SESSION_FILE).trim());
114
+ function markBoundLost() {
115
+ boundLost = true;
116
+ try {
117
+ fs.mkdirSync(STATE_DIR, { recursive: true });
118
+ fs.writeFileSync(LOST_FILE, `${BOUND}\n`);
119
+ } catch {
120
+ // 记不下来就只在这次进程里有效
121
+ }
122
+ }
123
+ function forgetBoundLost() {
124
+ boundLost = false;
125
+ try {
126
+ fs.unlinkSync(LOST_FILE);
127
+ } catch {
128
+ // 本来就没有
129
+ }
130
+ }
131
+ function clearSession() {
132
+ try {
133
+ fs.unlinkSync(SESSION_FILE);
134
+ } catch {
135
+ // 本来就没有
136
+ }
137
+ }
138
+ const sessionLost = (used) => {
139
+ if (used && used === BOUND) markBoundLost();
140
+ clearSession();
141
+ };
142
+ // /new:丢掉专属会话;绑了会话的,下一句又从绑的那个开始
143
+ function resetSession() {
144
+ clearSession();
145
+ if (BOUND) forgetBoundLost();
146
+ }
147
+
148
+ // 跑一轮。返回 { reply } 或 { failed, config? }
149
+ async function turn(prompt) {
150
+ const used = startSession();
151
+ const r = await agent.start(prompt, { session: used, onSessionLost: () => sessionLost(used), stateDir: STATE_DIR }).done;
152
+ if (!r.failed && r.sessionId && !(BOUND && !boundLost)) {
153
+ try {
154
+ fs.mkdirSync(STATE_DIR, { recursive: true });
155
+ fs.writeFileSync(SESSION_FILE, `${r.sessionId}\n`);
156
+ } catch {
157
+ // 记不下会话 id 就每次新开
158
+ }
159
+ }
160
+ return r;
161
+ }
162
+
163
+ // 对一批触发出决定。解析不出来、或者漏了触发,带着一句提醒再来一轮;再不行返回 ok 为 false(missing 是漏掉的短号)
164
+ async function decide(triggers, open) {
165
+ const started = Date.now();
166
+ const ids = triggers.map((t) => t.id);
167
+ let extra = '';
168
+ let lastReply = '';
169
+ for (let attempt = 0; attempt < 2; attempt += 1) {
170
+ const r = await turn(turnPrompt(triggers, open, extra));
171
+ if (r.failed) {
172
+ last = { at: fmtStamp(), seconds: Math.round((Date.now() - started) / 1000), ok: false };
173
+ return { ok: false, failed: r.failed, config: r.config, decisions: {}, missing: ids };
174
+ }
175
+ lastReply = r.reply;
176
+ const list = handoff.parseRouterReply(r.reply);
177
+ const decisions = {};
178
+ for (const d of list) decisions[d.id] = d;
179
+ const missing = ids.filter((id) => !decisions[id] || !decisions[id].action);
180
+ if (!missing.length) {
181
+ last = { at: fmtStamp(), seconds: Math.round((Date.now() - started) / 1000), ok: true };
182
+ return { ok: true, decisions, missing: [] };
183
+ }
184
+ extra = `上一轮的输出里没有这些触发的决定:${missing.join('、')}。每条都要有「- <短号> <决定>」,照上面的格式重新给出全部决定。`;
185
+ log('路由漏了', missing.join('、'));
186
+ }
187
+ last = { at: fmtStamp(), seconds: Math.round((Date.now() - started) / 1000), ok: false };
188
+ const decisions = {};
189
+ for (const d of handoff.parseRouterReply(lastReply)) decisions[d.id] = d;
190
+ return { ok: false, failed: `路由两轮都没给全决定(漏了 ${ids.filter((id) => !decisions[id] || !decisions[id].action).join('、')})`, decisions, missing: ids.filter((id) => !decisions[id] || !decisions[id].action) };
191
+ }
192
+
193
+ return {
194
+ agent,
195
+ startSession,
196
+ resetSession,
197
+ forgetBoundLost,
198
+ sessionFile: SESSION_FILE,
199
+ doctorProblems: () => agent.doctor(),
200
+ notes: () => agent.notes(),
201
+ // 现在用的是哪个会话:{ bound, own, id }
202
+ describeSession: () => ({ bound: BOUND, own: !BOUND || boundLost, id: startSession() }),
203
+ last: () => last,
204
+ decide,
205
+ };
206
+ }
207
+
208
+ 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
  };