work-rhythm 0.0.0-stage → 0.1.0

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 (102) hide show
  1. package/.agents/notes/AGENTS.md +84 -0
  2. package/.agents/notes/decisions/2026-11-28-long-term-goals-ride-existing-tasks.md +36 -0
  3. package/.agents/notes/decisions/2026-11-29-building-a-workdir-means-cloning-the-template.md +25 -0
  4. package/.agents/notes/decisions/2026-11-29-find-workdir-cwd-first-then-registered.md +32 -0
  5. package/.agents/notes/decisions/2026-11-30-bot-inbound-uses-websocket-and-a-responder-command.md +48 -0
  6. package/.agents/notes/decisions/2026-11-30-cost-entry-writes-into-empty-cells-directly.md +25 -0
  7. package/.agents/notes/decisions/2026-11-30-dependencies-are-allowed-user-installs-missing-ones.md +30 -0
  8. package/.agents/notes/decisions/2026-11-30-markdown-is-the-record-html-is-only-a-view.md +25 -0
  9. package/.agents/notes/decisions/2026-11-30-message-channels-are-preset-in-the-skill.md +34 -0
  10. package/.agents/notes/decisions/2026-11-30-no-workdir-offers-to-create-one-by-default.md +34 -0
  11. package/.agents/notes/decisions/2026-11-30-paging-requires-coverage-only-when-enabled.md +27 -0
  12. package/.agents/notes/decisions/2026-11-30-pending-decisions-asked-in-a-chat-and-logged-briefly.md +39 -0
  13. package/.agents/notes/decisions/2026-11-30-push-via-personal-robot-webhook.md +33 -0
  14. package/.agents/notes/decisions/2026-11-30-scheduling-moves-to-a-local-service.md +37 -0
  15. package/.agents/notes/decisions/2026-11-30-skill-ships-with-its-template-in-a-zip.md +30 -0
  16. package/.agents/notes/decisions/2026-11-30-skill-stays-generic-user-provides-cli-or-mcp.md +25 -0
  17. package/.agents/notes/decisions/2026-12-01-everything-is-js-behind-work-rhythm.md +45 -0
  18. package/.agents/notes/pitfalls/2026-11-29-do-not-hand-roll-git-log.md +22 -0
  19. package/.agents/notes/pitfalls/2026-11-29-empty-or-partial-collector-output.md +23 -0
  20. package/.agents/notes/pitfalls/2026-11-29-skill-description-is-truncated.md +21 -0
  21. package/.agents/notes/pitfalls/2026-11-29-tool-shell-is-zsh.md +24 -0
  22. package/.agents/notes/pitfalls/2026-11-30-compare-timestamps-as-digits.md +22 -0
  23. package/.agents/notes/pitfalls/2026-11-30-message-search-lags-after-sending.md +18 -0
  24. package/.agents/notes/pitfalls/2026-11-30-rewriting-a-file-with-empty-output-after-tool-failure.md +20 -0
  25. package/.agents/notes/pitfalls/2026-11-30-secret-scan-false-positive-on-hyphenated-file-names.md +18 -0
  26. package/.agents/notes/pitfalls/2026-11-30-selftest-must-not-inherit-local-config.md +29 -0
  27. package/.agents/notes/pitfalls/2026-11-30-yzj-cli-list-limit-is-20.md +25 -0
  28. package/.agents/notes/pitfalls/2026-11-30-zsh-no-word-splitting-special-names.md +23 -0
  29. package/.agents/notes/pitfalls/2026-12-01-node-test-hooks-cannot-register-after-callbacks.md +22 -0
  30. package/.agents/notes/pitfalls/2026-12-01-spawning-node-test-inside-a-test-runs-nothing.md +18 -0
  31. package/.agents/skills/work-rhythm/SKILL.md +277 -0
  32. package/00-config/profile.example.yaml +54 -0
  33. package/00-config/sources.yaml +115 -0
  34. package/AGENTS.md +31 -0
  35. package/README.md +105 -2
  36. package/collectors/approval-yzj.js +114 -0
  37. package/collectors/calendar-yzj.js +48 -0
  38. package/collectors/file-activity.js +131 -0
  39. package/collectors/git-activity.js +105 -0
  40. package/collectors/im-yzj.js +151 -0
  41. package/collectors/linky-issues.js +88 -0
  42. package/collectors/local.env.example +52 -0
  43. package/docs/channels.md +95 -0
  44. package/docs/formats.md +285 -0
  45. package/docs/im-adapters.md +79 -0
  46. package/docs/scheduled-tasks.md +115 -0
  47. package/docs/sources.md +104 -0
  48. package/package.json +37 -4
  49. package/scripts/cli.js +98 -0
  50. package/scripts/cmd/check.js +297 -0
  51. package/scripts/cmd/collect.js +25 -0
  52. package/scripts/cmd/decisions.js +236 -0
  53. package/scripts/cmd/goals.js +145 -0
  54. package/scripts/cmd/init.js +53 -0
  55. package/scripts/cmd/listen.js +91 -0
  56. package/scripts/cmd/notify.js +42 -0
  57. package/scripts/cmd/pack.js +105 -0
  58. package/scripts/cmd/rhythm.js +102 -0
  59. package/scripts/cmd/selftest.js +23 -0
  60. package/scripts/cmd/sync.js +73 -0
  61. package/scripts/cmd/today.js +29 -0
  62. package/scripts/cmd/workdir.js +81 -0
  63. package/scripts/lib/agent.js +270 -0
  64. package/scripts/lib/bot.js +376 -0
  65. package/scripts/lib/collector.js +74 -0
  66. package/scripts/lib/config.js +250 -0
  67. package/scripts/lib/launchd.js +82 -0
  68. package/scripts/lib/log.js +22 -0
  69. package/scripts/lib/markdown.js +208 -0
  70. package/scripts/lib/notify.js +43 -0
  71. package/scripts/lib/rhythm.js +508 -0
  72. package/scripts/lib/robot.js +64 -0
  73. package/scripts/lib/run.js +151 -0
  74. package/scripts/lib/template.js +144 -0
  75. package/scripts/lib/workdir.js +89 -0
  76. package/scripts/test/check.test.js +217 -0
  77. package/scripts/test/collectors.test.js +574 -0
  78. package/scripts/test/config.test.js +119 -0
  79. package/scripts/test/decisions.test.js +129 -0
  80. package/scripts/test/fake-webhook.js +31 -0
  81. package/scripts/test/goals.test.js +109 -0
  82. package/scripts/test/harness.js +279 -0
  83. package/scripts/test/init.test.js +125 -0
  84. package/scripts/test/listen.test.js +362 -0
  85. package/scripts/test/notify.test.js +176 -0
  86. package/scripts/test/pack.test.js +141 -0
  87. package/scripts/test/rhythm.test.js +324 -0
  88. package/scripts/test/stubs.js +140 -0
  89. package/scripts/test/today.test.js +73 -0
  90. package/scripts/test/workdir.test.js +152 -0
  91. package/scripts/work-rhythm.js +18 -0
  92. package/tasks/alerts-morning.md +24 -0
  93. package/tasks/carryover.md +16 -0
  94. package/tasks/daily-plan.md +29 -0
  95. package/tasks/evening-review.md +27 -0
  96. package/tasks/linky-cost-check.md +13 -0
  97. package/tasks/linky-cost-fill.md +20 -0
  98. package/tasks/noon-checkin.md +15 -0
  99. package/tasks/weekly-rhythm.md +18 -0
  100. package/templates/03-carryover/CARRYOVER.md +14 -0
  101. package/templates/03-carryover/DECISIONS.md +10 -0
  102. package/templates/04-patterns/WORK_RHYTHM.md +16 -0
@@ -0,0 +1,376 @@
1
+ // 值守:消息渠道的收消息一半。和云之家个人机器人保持 WebSocket 长连接,收到我本人的消息就交给本地的 agent,回复经推送(notify.js)发回来。
2
+ // 入口是 work-rhythm listen(用法和配置写在 cmd/listen.js)。只用 node 自带的能力,需要 node 22 以上(全局 WebSocket),不装第三方包。
3
+ // 怎么调起 agent 在 agent.js。协议照官方插件 kingdee/openclaw-yzj 的客户端做,2026-11-30 对照实测:
4
+ // 地址由发送地址推导:wss://<域名>/xuntong/websocket?yzjtoken=<同一个 token>;
5
+ // 业务消息包在 {"cmd":"directPush","type":"robotMessage","msg":{…}} 里,不带 needAck,不用回 ack;
6
+ // 控制帧用 cmd / type / event 表意(auth、pong、extSystemMsg…),带 needAck 和 seq 的要回 {"cmd":"ack","seq":N};
7
+ // 每 15 秒发 {"cmd":"ping"},45 秒没动静就重连,间隔 1、2、5、10、30、60 秒。
8
+ 'use strict';
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const { EXIT, Fail, fmtStamp } = require('./run');
12
+ const { logger } = require('./log');
13
+ const { notifyChannel, pushText } = require('./notify');
14
+ const { findWebhook, mask } = require('./robot');
15
+ const { createAgent } = require('./agent');
16
+
17
+ const SEEN_KEEP = 500;
18
+ const HEARTBEAT_MS = 15000;
19
+ const STALE_MS = 45000;
20
+ const RECONNECT_DELAYS_MS = [1000, 2000, 5000, 10000, 30000, 60000];
21
+ const ACK_TEXT = '收到,正在处理,稍等。';
22
+ const DEFAULT_PREAMBLE = '(这句来自云之家:你的回复会原样以纯文本私聊发给我。直接回答,不用表格,尽量简短;一件事要查很久就先说大概要多久。)';
23
+
24
+ const positiveInt = (value, fallback) => {
25
+ const n = Number(value);
26
+ return Number.isInteger(n) && n > 0 ? n : fallback;
27
+ };
28
+
29
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
30
+
31
+ // ---------------------------------------------------------------- 帧
32
+ // 认一条业务消息只要三样:谁发的、哪一条、说了什么。别的字段(robotName、operatorName、time、type…)有就用,没有也不丢
33
+ function businessMessage(r) {
34
+ if (!r || typeof r !== 'object') return null;
35
+ if (typeof r.operatorOpenid !== 'string' || typeof r.msgId !== 'string' || typeof r.content !== 'string') return null;
36
+ return {
37
+ type: typeof r.type === 'number' ? r.type : 0,
38
+ robotId: typeof r.robotId === 'string' ? r.robotId : '',
39
+ robotName: typeof r.robotName === 'string' ? r.robotName : '',
40
+ operatorOpenid: r.operatorOpenid,
41
+ operatorName: typeof r.operatorName === 'string' ? r.operatorName : '',
42
+ time: typeof r.time === 'number' ? r.time : 0,
43
+ msgId: r.msgId,
44
+ content: r.content,
45
+ groupType: typeof r.groupType === 'number' ? r.groupType : 0,
46
+ };
47
+ }
48
+
49
+ // 把一帧分成三类:业务消息(dispatch)、控制帧(control,有的要回 ack)、别的(invalid)
50
+ function classify(raw) {
51
+ const trimmed = String(raw).trim();
52
+ const lower = trimmed.toLowerCase();
53
+ if (lower === 'ping' || lower === 'pong') return { kind: 'control', reason: lower };
54
+ let p;
55
+ try {
56
+ p = JSON.parse(trimmed);
57
+ } catch {
58
+ return { kind: 'invalid' };
59
+ }
60
+ if (!p || typeof p !== 'object') return { kind: 'invalid' };
61
+ const direct = businessMessage(p);
62
+ if (direct) return { kind: 'dispatch', message: direct };
63
+ if (typeof p.type === 'string' && p.type.trim().toLowerCase() === 'robotmessage' && p.msg && typeof p.msg === 'object') {
64
+ const nested = businessMessage(p.msg);
65
+ if (nested) return { kind: 'dispatch', message: nested };
66
+ }
67
+ const cmd = typeof p.cmd === 'string' ? p.cmd.trim().toLowerCase() : '';
68
+ const type = typeof p.type === 'string' ? p.type.trim().toLowerCase() : '';
69
+ const event = typeof p.event === 'string' ? p.event.trim().toLowerCase() : '';
70
+ if (cmd === 'directpush' || type === 'msgchg') {
71
+ const ack = p.needAck === true && typeof p.seq === 'number' ? JSON.stringify({ cmd: 'ack', seq: p.seq }) : undefined;
72
+ return { kind: 'control', reason: 'directPush', ack };
73
+ }
74
+ const name = cmd || type || event;
75
+ return name ? { kind: 'control', reason: name } : { kind: 'invalid' };
76
+ }
77
+
78
+ // 由发送地址推出长连接的地址。地址缺 token 或域名时按没配置好处理
79
+ function deriveWsUrl(webhook) {
80
+ let u;
81
+ try {
82
+ u = new URL(webhook);
83
+ } catch {
84
+ throw new Fail(EXIT.NOT_CONFIGURED, '钥匙串里的地址不是一个 URL');
85
+ }
86
+ const token = (u.searchParams.get('yzjtoken') || '').trim();
87
+ if (!token || !u.host) throw new Fail(EXIT.NOT_CONFIGURED, '钥匙串里的地址缺 yzjtoken 或域名,不是机器人的 Webhook 地址');
88
+ return `wss://${u.host}/xuntong/websocket?yzjtoken=${encodeURIComponent(token)}`;
89
+ }
90
+
91
+ // 连上就 resolve { ws, closed, frames },没连上就 resolve null。closed 在断开时 resolve;frames 是收到的帧数
92
+ function openSocket(url, onFrame, log) {
93
+ return new Promise((resolve) => {
94
+ let ws;
95
+ try {
96
+ ws = new WebSocket(url);
97
+ } catch (error) {
98
+ log('建连失败', error.message);
99
+ resolve(null);
100
+ return;
101
+ }
102
+ const state = { ws, frames: 0 };
103
+ let settled = false;
104
+ let lastActivity = Date.now();
105
+ let heartbeat = null;
106
+ state.closed = new Promise((done) => {
107
+ ws.addEventListener('open', () => {
108
+ lastActivity = Date.now();
109
+ heartbeat = setInterval(() => {
110
+ if (Date.now() - lastActivity >= STALE_MS) {
111
+ log('连接 45 秒没动静,重连');
112
+ ws.close();
113
+ return;
114
+ }
115
+ if (ws.readyState === WebSocket.OPEN) {
116
+ try {
117
+ ws.send(JSON.stringify({ cmd: 'ping' }));
118
+ } catch {
119
+ // 发不出心跳就等它断开
120
+ }
121
+ }
122
+ }, HEARTBEAT_MS);
123
+ log('已连接', mask(url));
124
+ settled = true;
125
+ resolve(state);
126
+ });
127
+ ws.addEventListener('message', (event) => {
128
+ lastActivity = Date.now();
129
+ state.frames += 1;
130
+ onFrame(typeof event.data === 'string' ? event.data : String(event.data), state);
131
+ });
132
+ ws.addEventListener('error', () => log('连接出错'));
133
+ ws.addEventListener('close', (event) => {
134
+ if (heartbeat) clearInterval(heartbeat);
135
+ log('连接断开', `code=${event.code}`);
136
+ if (!settled) {
137
+ settled = true;
138
+ resolve(null);
139
+ }
140
+ done();
141
+ });
142
+ });
143
+ });
144
+ }
145
+
146
+ const reconnectDelay = (attempts) => RECONNECT_DELAYS_MS[Math.min(Math.max(attempts - 1, 0), RECONNECT_DELAYS_MS.length - 1)];
147
+
148
+ // 建一个值守对象。env 是设置(环境变量,上面盖一层 local.env),配置都在里面:
149
+ // YZJ_BOT_AGENT 让哪个 agent 回复(zcode、dsh,或一条自己的命令)、YZJ_BOT_AGENT_MODE(plan 只读 / edit 可写,默认 plan)、
150
+ // YZJ_MY_OPEN_ID 只认我本人、YZJ_BOT_TIMEOUT 一次最多等几秒、YZJ_BOT_REPLY_MAX 回复最多几个字、
151
+ // YZJ_BOT_ACK=0 关掉「收到,正在处理」那句、YZJ_BOT_PREAMBLE 换掉或清空随每句话带给 agent 的提示
152
+ function createBot({ root, env }) {
153
+ const STATE_DIR = path.join(root, '01-inbox', '_bot');
154
+ const LOG_FILE = path.join(root, '01-inbox', '_bot.log');
155
+ const SESSION_FILE = path.join(STATE_DIR, 'session-id');
156
+ const SEEN_FILE = path.join(STATE_DIR, 'seen-msgids');
157
+ const log = logger(LOG_FILE);
158
+ const OWNER = (env.YZJ_MY_OPEN_ID || '').trim();
159
+ const AGENT = (env.YZJ_BOT_AGENT || '').trim();
160
+ const AGENT_MODE = (env.YZJ_BOT_AGENT_MODE || 'plan').trim();
161
+ const TIMEOUT_S = positiveInt(env.YZJ_BOT_TIMEOUT, 300);
162
+ const REPLY_MAX = positiveInt(env.YZJ_BOT_REPLY_MAX, 2000);
163
+ // 收到就先回一句,agent 慢的时候我不用干等
164
+ const ACK = env.YZJ_BOT_ACK !== '0';
165
+ const PREAMBLE = env.YZJ_BOT_PREAMBLE !== undefined ? env.YZJ_BOT_PREAMBLE : DEFAULT_PREAMBLE;
166
+ const agent = createAgent({ root, agent: AGENT, mode: AGENT_MODE, timeoutS: TIMEOUT_S, preamble: PREAMBLE, log, env });
167
+
168
+ // ---------------------------------------------------------------- 配置
169
+ // 检查值守的配置和依赖:有问题一条一个字符串;没问题就是空数组。check 配了值守时也调它
170
+ function doctorProblems() {
171
+ const problems = [];
172
+ if (notifyChannel(root) !== 'yzj-robot') problems.push('值守属于 yzj-robot 渠道:preferences.notify 要设成 yzj-robot');
173
+ if (!findWebhook(env).webhook) problems.push(`钥匙串里没有 ${env.YZJ_ROBOT_KEYCHAIN_SERVICE || 'work-rhythm-yzj-robot-webhook'}(开通步骤见 docs/channels.md「云之家」)`);
174
+ if (!OWNER) problems.push('值守只处理我本人的消息:collectors/local.env 里要写 YZJ_MY_OPEN_ID');
175
+ problems.push(...agent.doctor());
176
+ return problems;
177
+ }
178
+
179
+ // 真正运行前的检查:没配置好就带着退出码抛出。返回长连接的地址
180
+ function requireConfig(needAgent) {
181
+ if (notifyChannel(root) !== 'yzj-robot') {
182
+ throw new Fail(EXIT.NOT_CONFIGURED, '值守是 yzj-robot 渠道的收消息一半:先把 00-config/profile.yaml 的 preferences.notify 设成 yzj-robot');
183
+ }
184
+ const found = findWebhook(env);
185
+ if (found.problem) throw new Fail(found.code, found.problem);
186
+ if (needAgent) {
187
+ if (!OWNER) throw new Fail(EXIT.NOT_CONFIGURED, '取不到我的 openId:在 collectors/local.env 里写 YZJ_MY_OPEN_ID,值守只处理我本人的消息');
188
+ if (!AGENT) throw new Fail(EXIT.NOT_CONFIGURED, '没配 YZJ_BOT_AGENT(collectors/local.env):写 zcode、dsh,或一条把回复打到标准输出的命令');
189
+ }
190
+ return deriveWsUrl(found.webhook);
191
+ }
192
+
193
+ // ---------------------------------------------------------------- 专属会话、去重
194
+ const readSession = () => {
195
+ try {
196
+ return fs.readFileSync(SESSION_FILE, 'utf8').trim();
197
+ } catch {
198
+ return '';
199
+ }
200
+ };
201
+ const writeSession = (id) => {
202
+ fs.mkdirSync(STATE_DIR, { recursive: true });
203
+ fs.writeFileSync(SESSION_FILE, `${id}\n`);
204
+ };
205
+ const clearSession = () => {
206
+ try {
207
+ fs.unlinkSync(SESSION_FILE);
208
+ } catch {
209
+ // 本来就没有
210
+ }
211
+ };
212
+ const readSeen = () => {
213
+ try {
214
+ return fs.readFileSync(SEEN_FILE, 'utf8').split('\n').filter(Boolean);
215
+ } catch {
216
+ return [];
217
+ }
218
+ };
219
+ const markSeen = (msgId) => {
220
+ fs.mkdirSync(STATE_DIR, { recursive: true });
221
+ fs.writeFileSync(SEEN_FILE, `${[...readSeen(), msgId].slice(-SEEN_KEEP).join('\n')}\n`);
222
+ };
223
+
224
+ // ---------------------------------------------------------------- 一条消息
225
+ function truncate(text) {
226
+ const chars = Array.from(String(text).trim());
227
+ if (chars.length <= REPLY_MAX) return chars.join('');
228
+ return `${chars.slice(0, REPLY_MAX).join('')}\n…(回复太长,截到 ${REPLY_MAX} 字)`;
229
+ }
230
+
231
+ // 一条消息 → 要回复的文字。agent 失败也回一句,不让我干等
232
+ function answer(message) {
233
+ const text = String(message.content || '').trim();
234
+ if (!text) return '收到一条空消息。';
235
+ if (/^\/new$/i.test(text)) {
236
+ clearSession();
237
+ return '已开新会话。';
238
+ }
239
+ const r = agent.run(text, { session: readSession(), onSessionLost: clearSession, stateDir: STATE_DIR });
240
+ if (r.sessionId) writeSession(r.sessionId);
241
+ return truncate(r.failed ? `没处理成功:${r.failed}` : r.reply);
242
+ }
243
+
244
+ // 回复经推送发出去。发不出去记一笔日志,不影响值守
245
+ async function sendReply(reply) {
246
+ const r = await pushText(root, reply, { env });
247
+ if (r.ok) return true;
248
+ log('回复没发出去', r.reason);
249
+ return false;
250
+ }
251
+
252
+ // 收到一帧之后做的事。send 为 false 时只算出回复、不发
253
+ async function processFrame(raw, send = true) {
254
+ const c = classify(raw);
255
+ if (c.kind !== 'dispatch') return { result: c.kind === 'control' ? `控制帧 ${c.reason}` : '不是业务消息', code: 2 };
256
+ const m = c.message;
257
+ if (readSeen().includes(m.msgId)) return { result: `重复 msgId=${m.msgId}`, code: 0 };
258
+ markSeen(m.msgId);
259
+ if (m.operatorOpenid !== OWNER) {
260
+ log('msg 忽略:不是本人', `msgId=${m.msgId} from=${m.operatorOpenid}`);
261
+ return { result: `忽略 msgId=${m.msgId}(不是本人)`, code: 0 };
262
+ }
263
+ const started = Date.now();
264
+ const immediate = /^\/new$/i.test(String(m.content || '').trim());
265
+ log('msg 接受', `msgId=${m.msgId} groupType=${m.groupType}`);
266
+ let sent = null;
267
+ if (send) {
268
+ // 先回一句「收到」,agent 慢的话我不用干等
269
+ if (ACK && !immediate) await sendReply(ACK_TEXT);
270
+ sent = await sendReply(answer(m));
271
+ }
272
+ log('msg 完成', `msgId=${m.msgId} ${Math.round((Date.now() - started) / 1000)}s${sent === null ? '' : ` sent=${sent}`}`);
273
+ return { result: `处理 msgId=${m.msgId}${sent === false ? ',但回复没发出去' : ''}`, code: 0, sent };
274
+ }
275
+
276
+ // 不连云之家,只走一遍「交给 agent → 回复」。回复打到标准输出;没配置好、没跑成都带着退出码抛出
277
+ function handle(text) {
278
+ requireConfig(true);
279
+ const r = agent.run(text, { session: readSession(), onSessionLost: clearSession, stateDir: STATE_DIR });
280
+ if (r.sessionId) writeSession(r.sessionId);
281
+ if (r.config) throw new Fail(EXIT.NOT_CONFIGURED, r.failed);
282
+ if (r.failed) throw new Fail(EXIT.FAILED, `没处理成功:${r.failed}`);
283
+ return truncate(r.reply);
284
+ }
285
+
286
+ // ---------------------------------------------------------------- 长连接
287
+ const needWebSocket = () => {
288
+ if (typeof WebSocket === 'undefined') throw new Fail(EXIT.MISSING_DEP, `这个 node(${process.version})没有内置的 WebSocket,需要 22 以上`);
289
+ };
290
+
291
+ // 值守:一直连着,收到消息就处理。收到 SIGINT / SIGTERM 后把手上这条处理完再退出
292
+ async function run() {
293
+ const url = requireConfig(true);
294
+ needWebSocket();
295
+ log('值守开始', `pid=${process.pid} agent=${agent.kind !== 'custom' ? `${AGENT} mode=${AGENT_MODE}` : '自定义命令'} 超时=${TIMEOUT_S}s`);
296
+ let stopping = false;
297
+ let wake = null;
298
+ const stopped = new Promise((resolve) => {
299
+ wake = resolve;
300
+ });
301
+ // 等待的时候也能被停下的信号叫醒
302
+ const pause = (ms) => Promise.race([sleep(ms), stopped]);
303
+ let current = null;
304
+ let chain = Promise.resolve();
305
+ const stop = (signal) => {
306
+ if (stopping) return;
307
+ stopping = true;
308
+ log(`收到 ${signal},准备退出`);
309
+ if (current && current.ws.readyState === WebSocket.OPEN) current.ws.close(1000, 'bye');
310
+ wake();
311
+ };
312
+ process.on('SIGINT', () => stop('SIGINT'));
313
+ process.on('SIGTERM', () => stop('SIGTERM'));
314
+ let attempts = 0;
315
+ while (!stopping) {
316
+ const conn = await openSocket(url, (raw, me) => {
317
+ const c = classify(raw);
318
+ if (c.kind === 'control' && c.ack && me.ws.readyState === WebSocket.OPEN) me.ws.send(c.ack);
319
+ // 一条一条处理,后面的排队
320
+ if (c.kind === 'dispatch') {
321
+ chain = chain.then(() => (stopping ? undefined : processFrame(raw, true)));
322
+ }
323
+ }, log);
324
+ if (!conn) {
325
+ attempts += 1;
326
+ await pause(reconnectDelay(attempts));
327
+ continue;
328
+ }
329
+ attempts = 0;
330
+ current = conn;
331
+ await Promise.race([conn.closed, stopped]);
332
+ current = null;
333
+ if (!stopping) await pause(1000);
334
+ }
335
+ await chain;
336
+ log('值守结束');
337
+ return EXIT.OK;
338
+ }
339
+
340
+ // 连上去看握手和收到的每一帧,不调 agent,到时退出。第一次验证用。返回退出码:收到过帧是 0,没收到是 5
341
+ async function probe(seconds) {
342
+ const url = requireConfig(false);
343
+ needWebSocket();
344
+ process.stdout.write(`${fmtStamp()} 连接 ${mask(url)},最多等 ${seconds} 秒。现在可以在云之家里给机器人发一句话。\n`);
345
+ const conn = await openSocket(url, (raw, me) => {
346
+ process.stdout.write(`${fmtStamp()} 收到 ${mask(raw)}\n`);
347
+ const c = classify(raw);
348
+ if (c.kind === 'control' && c.ack && me.ws.readyState === WebSocket.OPEN) me.ws.send(c.ack);
349
+ }, (event, fields) => process.stderr.write(`${event}${fields ? ` ${fields}` : ''}\n`));
350
+ if (!conn) throw new Fail(EXIT.FAILED, '没连上');
351
+ let timer;
352
+ await Promise.race([conn.closed, new Promise((done) => {
353
+ timer = setTimeout(done, seconds * 1000);
354
+ })]);
355
+ clearTimeout(timer);
356
+ process.stdout.write(`${fmtStamp()} 结束,共收到 ${conn.frames} 帧\n`);
357
+ if (conn.ws.readyState === WebSocket.OPEN) conn.ws.close(1000, 'probe done');
358
+ await sleep(300);
359
+ return conn.frames > 0 ? EXIT.OK : EXIT.FAILED;
360
+ }
361
+
362
+ return {
363
+ log,
364
+ stateDir: STATE_DIR,
365
+ sessionFile: SESSION_FILE,
366
+ doctorProblems,
367
+ requireConfig,
368
+ handle,
369
+ processFrame,
370
+ clearSession,
371
+ run,
372
+ probe,
373
+ };
374
+ }
375
+
376
+ module.exports = { createBot, classify };
@@ -0,0 +1,74 @@
1
+ // 采集器共用的东西:读参数、找设置、写文件。每个采集器是 collectors/<id>.js,导出 async collect(argv, ctx)
2
+ // 契约(docs/sources.md 的「采集脚本契约」):
3
+ // 调用 collect(<输出目录> [起始日期 YYYY-MM-DD]),起始日期缺省为今天
4
+ // 输出写进输出目录,同名覆盖;进度和错误走 stderr
5
+ // 退出码:0 成功 · 2 参数错误 · 3 未配置 · 4 依赖缺失 · 5 远端失败(没登录、没权限、网络)
6
+ // 本机差异写 collectors/local.env,不写死在脚本里;结果不完整就不算成功
7
+ 'use strict';
8
+ const fs = require('node:fs');
9
+ const os = require('node:os');
10
+ const path = require('node:path');
11
+ const { EXIT, UsageError, today, tail } = require('./run');
12
+ const { findWorkdir, settings } = require('./config');
13
+
14
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
15
+
16
+ // 采集器的运行环境:输出目录、起始日期、工作目录、设置(环境变量盖一层 local.env)
17
+ // 工作目录由 sync 用 WORK_RHYTHM_ROOT 告诉它;单独运行时从当前目录往上找,再不行从输出目录 01-inbox/<id>/<日期> 反推
18
+ function context(argv, name, usage) {
19
+ const out = argv[0];
20
+ if (!out) throw new UsageError(`${name}: 用法: ${usage}`);
21
+ let root = process.env.WORK_RHYTHM_ROOT || '';
22
+ if (!root) root = findWorkdir(process.cwd());
23
+ if (!root && /01-inbox[/\\][^/\\]+[/\\][^/\\]+$/.test(out)) root = path.resolve(out, '..', '..', '..');
24
+ return {
25
+ out: path.resolve(out),
26
+ since: argv[1] || today(),
27
+ root,
28
+ env: root ? settings(root, process.env) : { ...process.env },
29
+ name,
30
+ note: (text) => process.stderr.write(`${name}: ${text}\n`),
31
+ home: process.env.HOME || os.homedir(),
32
+ };
33
+ }
34
+
35
+ // 要求某个命令行工具装了;没装报缺依赖
36
+ function needTool(ctx, tool, hint = '') {
37
+ for (const dir of (ctx.env.PATH || '').split(path.delimiter)) {
38
+ const file = path.join(dir, tool);
39
+ try {
40
+ fs.accessSync(file, fs.constants.X_OK);
41
+ if (fs.statSync(file).isFile()) return file;
42
+ } catch {
43
+ // 这个目录里没有,接着找
44
+ }
45
+ }
46
+ ctx.note(`未安装 ${tool}${hint}`);
47
+ return '';
48
+ }
49
+
50
+ // 临时目录,用完由 ctx.cleanup 清掉
51
+ function tempDir(prefix) {
52
+ return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
53
+ }
54
+
55
+ function readJson(file) {
56
+ try {
57
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ // 像表格一样写文件:表头加各行,制表符分隔,末尾有换行
64
+ function writeTsv(file, header, rows) {
65
+ fs.mkdirSync(path.dirname(file), { recursive: true });
66
+ fs.writeFileSync(file, `${[header, ...rows].map((row) => row.join('\t')).join('\n')}\n`);
67
+ }
68
+
69
+ // 和 jq 的 @tsv 一样:字段里的反斜杠、制表符、换行、回车换成转义写法,表格不会被撑歪
70
+ const tsv = (value) => String(value ?? '').replace(/\\/g, '\\\\').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
71
+
72
+ const tailText = tail;
73
+
74
+ module.exports = { EXIT, UsageError, context, needTool, tempDir, readJson, writeTsv, tsv, sleep, tailText };