work-rhythm 0.1.6 → 0.1.8
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.
- package/.agents/notes/AGENTS.md +3 -0
- package/.agents/notes/decisions/2026-11-30-bot-inbound-uses-websocket-and-a-responder-command.md +1 -0
- package/.agents/notes/decisions/2026-11-30-scheduling-moves-to-a-local-service.md +1 -0
- package/.agents/notes/decisions/2026-12-01-binding-carries-the-current-session.md +29 -0
- package/.agents/notes/decisions/2026-12-01-bot-lives-in-the-service-process.md +28 -0
- package/.agents/notes/pitfalls/2026-12-01-launchd-install-bakes-invoking-node.md +28 -0
- package/.agents/skills/work-rhythm/SKILL.md +1 -1
- package/collectors/local.env.example +6 -1
- package/docs/agents.md +10 -1
- package/docs/channels.md +5 -2
- package/docs/scheduled-tasks.md +1 -1
- package/package.json +1 -1
- package/scripts/cmd/agent.js +66 -5
- package/scripts/cmd/listen.js +48 -14
- package/scripts/cmd/rhythm.js +15 -2
- package/scripts/lib/agent.js +33 -3
- package/scripts/lib/bot.js +61 -7
- package/scripts/lib/config.js +22 -1
- package/scripts/lib/launchd.js +56 -3
- package/scripts/lib/rhythm.js +40 -3
- package/scripts/test/agent.test.js +66 -1
- package/scripts/test/harness.js +1 -0
- package/scripts/test/listen.test.js +97 -0
- package/scripts/test/rhythm.test.js +77 -0
- package/scripts/test/stubs.js +11 -1
package/scripts/lib/bot.js
CHANGED
|
@@ -162,6 +162,9 @@ function createBot({ root, env }) {
|
|
|
162
162
|
const REPLY_MAX = positiveInt(env.YZJ_BOT_REPLY_MAX, 2000);
|
|
163
163
|
// 收到就先回一句,agent 慢的时候我不用干等
|
|
164
164
|
const ACK = env.YZJ_BOT_ACK !== '0';
|
|
165
|
+
// 绑定的会话(collectors/local.env 的 YZJ_BOT_SESSION):绑 agent 时顺手把用户当时所在的会话绑上,
|
|
166
|
+
// IM 里的话就从那个会话接着走,上下文是连着的。没绑就用值守自己的专属会话;绑的接不上(被删、过期)就退回专属会话
|
|
167
|
+
const BOUND_SESSION = (env.YZJ_BOT_SESSION || '').trim();
|
|
165
168
|
const PREAMBLE = env.YZJ_BOT_PREAMBLE !== undefined ? env.YZJ_BOT_PREAMBLE : DEFAULT_PREAMBLE;
|
|
166
169
|
// 模型和思考强度(collectors/local.env 的 YZJ_BOT_MODEL / YZJ_BOT_EFFORT),只有支持的预置才认;不写就用 agent 自己的默认
|
|
167
170
|
const agent = createAgent({ root, agent: AGENT, mode: AGENT_MODE, timeoutS: TIMEOUT_S, preamble: PREAMBLE, log, env, model: (env.YZJ_BOT_MODEL || '').trim(), effort: (env.YZJ_BOT_EFFORT || '').trim() });
|
|
@@ -192,6 +195,13 @@ function createBot({ root, env }) {
|
|
|
192
195
|
}
|
|
193
196
|
|
|
194
197
|
// ---------------------------------------------------------------- 专属会话、去重
|
|
198
|
+
const readText = (file) => {
|
|
199
|
+
try {
|
|
200
|
+
return fs.readFileSync(file, 'utf8');
|
|
201
|
+
} catch {
|
|
202
|
+
return '';
|
|
203
|
+
}
|
|
204
|
+
};
|
|
195
205
|
const readSession = () => {
|
|
196
206
|
try {
|
|
197
207
|
return fs.readFileSync(SESSION_FILE, 'utf8').trim();
|
|
@@ -229,15 +239,45 @@ function createBot({ root, env }) {
|
|
|
229
239
|
return `${chars.slice(0, REPLY_MAX).join('')}\n…(回复太长,截到 ${REPLY_MAX} 字)`;
|
|
230
240
|
}
|
|
231
241
|
|
|
242
|
+
// 这一轮从哪个会话接着走:绑定的优先,它接不上过一次就不再试,用专属会话。
|
|
243
|
+
// 「接不上过」记在 01-inbox/_bot/bound-session-lost 里(内容是那个会话 id):listen handle 是一次一个进程,光靠内存里的标记下一句又会去试
|
|
244
|
+
const LOST_FILE = path.join(STATE_DIR, 'bound-session-lost');
|
|
245
|
+
let boundLost = BOUND_SESSION && readText(LOST_FILE).trim() === BOUND_SESSION;
|
|
246
|
+
const startSession = () => (BOUND_SESSION && !boundLost ? BOUND_SESSION : readSession());
|
|
247
|
+
const markBoundLost = () => {
|
|
248
|
+
boundLost = true;
|
|
249
|
+
try {
|
|
250
|
+
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
251
|
+
fs.writeFileSync(LOST_FILE, `${BOUND_SESSION}\n`);
|
|
252
|
+
} catch {
|
|
253
|
+
// 记不下来就只在这次进程里有效
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
const forgetBoundLost = () => {
|
|
257
|
+
boundLost = false;
|
|
258
|
+
try {
|
|
259
|
+
fs.unlinkSync(LOST_FILE);
|
|
260
|
+
} catch {
|
|
261
|
+
// 本来就没有
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
const sessionLost = (used) => {
|
|
265
|
+
if (used && used === BOUND_SESSION) markBoundLost();
|
|
266
|
+
clearSession();
|
|
267
|
+
};
|
|
268
|
+
|
|
232
269
|
// 一条消息 → 要回复的文字。agent 失败也回一句,不让我干等
|
|
233
270
|
function answer(message) {
|
|
234
271
|
const text = String(message.content || '').trim();
|
|
235
272
|
if (!text) return '收到一条空消息。';
|
|
236
273
|
if (/^\/new$/i.test(text)) {
|
|
237
274
|
clearSession();
|
|
238
|
-
return '已开新会话。';
|
|
275
|
+
if (!BOUND_SESSION) return '已开新会话。';
|
|
276
|
+
forgetBoundLost();
|
|
277
|
+
return '已丢掉值守自己开的会话,下一句从绑定的那个会话接着走。';
|
|
239
278
|
}
|
|
240
|
-
const
|
|
279
|
+
const used = startSession();
|
|
280
|
+
const r = agent.run(text, { session: used, onSessionLost: () => sessionLost(used), stateDir: STATE_DIR });
|
|
241
281
|
if (r.sessionId) writeSession(r.sessionId);
|
|
242
282
|
return truncate(r.failed ? `没处理成功:${r.failed}` : r.reply);
|
|
243
283
|
}
|
|
@@ -277,7 +317,8 @@ function createBot({ root, env }) {
|
|
|
277
317
|
// 不连云之家,只走一遍「交给 agent → 回复」。回复打到标准输出;没配置好、没跑成都带着退出码抛出
|
|
278
318
|
function handle(text) {
|
|
279
319
|
requireConfig(true);
|
|
280
|
-
const
|
|
320
|
+
const used = startSession();
|
|
321
|
+
const r = agent.run(text, { session: used, onSessionLost: () => sessionLost(used), stateDir: STATE_DIR });
|
|
281
322
|
if (r.sessionId) writeSession(r.sessionId);
|
|
282
323
|
if (r.config) throw new Fail(EXIT.NOT_CONFIGURED, r.failed);
|
|
283
324
|
if (r.failed) throw new Fail(EXIT.FAILED, `没处理成功:${r.failed}`);
|
|
@@ -290,10 +331,13 @@ function createBot({ root, env }) {
|
|
|
290
331
|
};
|
|
291
332
|
|
|
292
333
|
// 值守:一直连着,收到消息就处理。收到 SIGINT / SIGTERM 后把手上这条处理完再退出
|
|
293
|
-
|
|
334
|
+
// 值守:一直连着,收到消息就处理,直到 stop() 或(signals 为 true 时)SIGINT / SIGTERM。
|
|
335
|
+
// 单独跑(work-rhythm listen run)时自己管信号;并进本地服务时 signals 为 false,由服务调 stop()
|
|
336
|
+
let stopFn = null;
|
|
337
|
+
async function run({ signals = true } = {}) {
|
|
294
338
|
const url = requireConfig(true);
|
|
295
339
|
needWebSocket();
|
|
296
|
-
log('值守开始', `pid=${process.pid} agent=${agent.kind !== 'custom' ? `${AGENT} mode=${AGENT_MODE}` : '自定义命令'} 超时=${TIMEOUT_S}s`);
|
|
340
|
+
log('值守开始', `pid=${process.pid} agent=${agent.kind !== 'custom' ? `${AGENT} mode=${AGENT_MODE}` : '自定义命令'} 超时=${TIMEOUT_S}s 会话=${BOUND_SESSION ? `绑定 ${BOUND_SESSION}` : '值守自己的专属会话'}`);
|
|
297
341
|
let stopping = false;
|
|
298
342
|
let wake = null;
|
|
299
343
|
const stopped = new Promise((resolve) => {
|
|
@@ -310,8 +354,11 @@ function createBot({ root, env }) {
|
|
|
310
354
|
if (current && current.ws.readyState === WebSocket.OPEN) current.ws.close(1000, 'bye');
|
|
311
355
|
wake();
|
|
312
356
|
};
|
|
313
|
-
|
|
314
|
-
|
|
357
|
+
stopFn = stop;
|
|
358
|
+
if (signals) {
|
|
359
|
+
process.on('SIGINT', () => stop('SIGINT'));
|
|
360
|
+
process.on('SIGTERM', () => stop('SIGTERM'));
|
|
361
|
+
}
|
|
315
362
|
let attempts = 0;
|
|
316
363
|
while (!stopping) {
|
|
317
364
|
const conn = await openSocket(url, (raw, me) => {
|
|
@@ -337,6 +384,10 @@ function createBot({ root, env }) {
|
|
|
337
384
|
log('值守结束');
|
|
338
385
|
return EXIT.OK;
|
|
339
386
|
}
|
|
387
|
+
// 从外面停掉它(本地服务结束时调);还没跑起来或已经停了就什么都不做
|
|
388
|
+
function stop(reason = '服务结束') {
|
|
389
|
+
if (stopFn) stopFn(reason);
|
|
390
|
+
}
|
|
340
391
|
|
|
341
392
|
// 连上去看握手和收到的每一帧,不调 agent,到时退出。第一次验证用。返回退出码:收到过帧是 0,没收到是 5
|
|
342
393
|
async function probe(seconds) {
|
|
@@ -369,7 +420,10 @@ function createBot({ root, env }) {
|
|
|
369
420
|
handle,
|
|
370
421
|
processFrame,
|
|
371
422
|
clearSession,
|
|
423
|
+
// 换绑了会话之后调:忘掉「接不上过」
|
|
424
|
+
forgetBoundLost,
|
|
372
425
|
run,
|
|
426
|
+
stop,
|
|
373
427
|
probe,
|
|
374
428
|
};
|
|
375
429
|
}
|
package/scripts/lib/config.js
CHANGED
|
@@ -244,7 +244,28 @@ function lintLocalEnv(text, env = process.env) {
|
|
|
244
244
|
|
|
245
245
|
const loadLocalEnv = (root, env = process.env) => parseLocalEnv(readText(path.join(root, 'collectors', 'local.env')), env);
|
|
246
246
|
|
|
247
|
+
// 往 collectors/local.env 写几个键(没有这个文件就从 local.env.example 复制一份):值是字符串就写(空串写成分空的),
|
|
248
|
+
// 注释掉的那行一起换掉。返回文件路径
|
|
249
|
+
function writeLocalEnv(root, values) {
|
|
250
|
+
const dir = path.join(root, 'collectors');
|
|
251
|
+
const file = path.join(dir, 'local.env');
|
|
252
|
+
if (!fs.existsSync(file)) {
|
|
253
|
+
const example = path.join(dir, 'local.env.example');
|
|
254
|
+
if (fs.existsSync(example)) fs.copyFileSync(example, file);
|
|
255
|
+
else fs.writeFileSync(file, '');
|
|
256
|
+
}
|
|
257
|
+
let lines = fs.readFileSync(file, 'utf8').split('\n');
|
|
258
|
+
for (const [key, value] of Object.entries(values)) {
|
|
259
|
+
const quoted = value === '' ? '""' : /[\s"'$`]/.test(value) ? `'${value.replace(/'/g, `'\\''`)}'` : `"${value}"`;
|
|
260
|
+
const at = lines.findIndex((l) => new RegExp(`^#?\\s*${key}=`).test(l));
|
|
261
|
+
if (at >= 0) lines[at] = `${key}=${quoted}`;
|
|
262
|
+
else lines.push(`${key}=${quoted}`);
|
|
263
|
+
}
|
|
264
|
+
fs.writeFileSync(file, `${lines.join('\n').replace(/\n*$/, '')}\n`);
|
|
265
|
+
return file;
|
|
266
|
+
}
|
|
267
|
+
|
|
247
268
|
// 设置 = 环境变量,上面盖一层 local.env(和原来 source 的效果一样)
|
|
248
269
|
const settings = (root, env = process.env) => ({ ...env, ...loadLocalEnv(root, env) });
|
|
249
270
|
|
|
250
|
-
module.exports = { MARKER, findWorkdir, parseYaml, parseLocalEnv, lintLocalEnv, loadProfile, loadSources, loadLocalEnv, settings };
|
|
271
|
+
module.exports = { MARKER, findWorkdir, parseYaml, parseLocalEnv, lintLocalEnv, loadProfile, loadSources, loadLocalEnv, writeLocalEnv, settings };
|
package/scripts/lib/launchd.js
CHANGED
|
@@ -23,6 +23,26 @@ function bootout(kind, root) {
|
|
|
23
23
|
|
|
24
24
|
const escapeXml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
25
25
|
|
|
26
|
+
// 看着像 Electron 包的可执行文件(…/DSH Node.app/Contents/MacOS/DSH Node):靠 ELECTRON_RUN_AS_NODE 当 node 用,
|
|
27
|
+
// 被 launchd 直接拉起时找不到 helper app,启动即退
|
|
28
|
+
const looksLikeElectron = (file, env) => /\.app\//.test(file) || env.ELECTRON_RUN_AS_NODE === '1' && !/(^|\/)node$/.test(file);
|
|
29
|
+
|
|
30
|
+
// 写进 plist 的 node:要真正的 node。从桌面 agent(DSH、ZCode)的工具里跑 install 时 process.execPath 是它们自带的 Electron 包,
|
|
31
|
+
// 所以 execPath 看着像 Electron 就另找一个:先 PATH 上的 node,再 homebrew / usr/local 的常见位置。都找不到才用它,并让 doctor 报出来
|
|
32
|
+
function nodeForLaunchd(env = process.env) {
|
|
33
|
+
const current = process.execPath;
|
|
34
|
+
if (!looksLikeElectron(current, env)) return current;
|
|
35
|
+
const onPath = spawnSync('/usr/bin/which', ['node'], { encoding: 'utf8', env });
|
|
36
|
+
const candidates = [onPath.status === 0 ? onPath.stdout.trim() : '', '/opt/homebrew/bin/node', '/usr/local/bin/node'];
|
|
37
|
+
return candidates.find((c) => c && fs.existsSync(c) && !looksLikeElectron(c, env)) || current;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// 已经装好的 plist 里绑的是什么 node:读 ProgramArguments 的第一项
|
|
41
|
+
function plistNode(plist) {
|
|
42
|
+
const m = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]+)<\/string>/.exec(fs.readFileSync(plist, 'utf8'));
|
|
43
|
+
return m ? m[1] : '';
|
|
44
|
+
}
|
|
45
|
+
|
|
26
46
|
// 写 plist 并装上。args 是子命令和它的参数(跟在入口后面)。日志写进 logFile
|
|
27
47
|
function install({ kind, root, entry, args, logFile }) {
|
|
28
48
|
needLaunchd();
|
|
@@ -34,14 +54,14 @@ function install({ kind, root, entry, args, logFile }) {
|
|
|
34
54
|
<key>Label</key><string>${escapeXml(label(kind, root))}</string>
|
|
35
55
|
<key>ProgramArguments</key>
|
|
36
56
|
<array>
|
|
37
|
-
<string>${escapeXml(
|
|
57
|
+
<string>${escapeXml(nodeForLaunchd())}</string>
|
|
38
58
|
<string>${escapeXml(entry)}</string>
|
|
39
59
|
${args.map((a) => ` <string>${escapeXml(a)}</string>`).join('\n')}
|
|
40
60
|
</array>
|
|
41
61
|
<key>WorkingDirectory</key><string>${escapeXml(root)}</string>
|
|
42
62
|
<key>EnvironmentVariables</key>
|
|
43
63
|
<dict>
|
|
44
|
-
<key>PATH</key><string>${escapeXml(path.dirname(
|
|
64
|
+
<key>PATH</key><string>${escapeXml(path.dirname(nodeForLaunchd()))}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
|
|
45
65
|
<key>HOME</key><string>${escapeXml(os.homedir())}</string>
|
|
46
66
|
<key>LANG</key><string>zh_CN.UTF-8</string>
|
|
47
67
|
</dict>
|
|
@@ -61,6 +81,32 @@ ${args.map((a) => ` <string>${escapeXml(a)}</string>`).join('\n')}
|
|
|
61
81
|
return plist;
|
|
62
82
|
}
|
|
63
83
|
|
|
84
|
+
// 装完核对它真的起来了:launchd 拉起失败(绑错了 node、端口被占)时 install 也会报「已装成常驻」,要等几秒看一眼。
|
|
85
|
+
// 返回问题(空串就是起来了)
|
|
86
|
+
function startupProblem(kind, root, logFile, { waitMs = 4000 } = {}) {
|
|
87
|
+
const until = Date.now() + waitMs;
|
|
88
|
+
const syncWait = (ms) => spawnSync(process.execPath, ['-e', `setTimeout(() => {}, ${ms})`]);
|
|
89
|
+
let last = '';
|
|
90
|
+
for (;;) {
|
|
91
|
+
const s = status(kind, root);
|
|
92
|
+
if (s.running) return '';
|
|
93
|
+
last = tail(readText(logFile), 300);
|
|
94
|
+
if (Date.now() >= until) break;
|
|
95
|
+
syncWait(500);
|
|
96
|
+
}
|
|
97
|
+
const node = plistNode(plistPath(kind, root));
|
|
98
|
+
const why = looksLikeElectron(node, {}) ? `plist 里绑的不是真正的 node(${node})` : '';
|
|
99
|
+
return `装是装上了,但 launchd 没能把它拉起来${why ? `:${why}` : ''}。先看 ${logFile}${last ? `,最后几行是:${last}` : ''}`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const readText = (file) => {
|
|
103
|
+
try {
|
|
104
|
+
return fs.readFileSync(file, 'utf8');
|
|
105
|
+
} catch {
|
|
106
|
+
return '';
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
|
|
64
110
|
function uninstall(kind, root) {
|
|
65
111
|
needLaunchd();
|
|
66
112
|
bootout(kind, root);
|
|
@@ -71,6 +117,13 @@ function uninstall(kind, root) {
|
|
|
71
117
|
}
|
|
72
118
|
}
|
|
73
119
|
|
|
120
|
+
// 重启已经装成常驻的(改了配置要让它重新读):launchctl kickstart -k。成功返回 true
|
|
121
|
+
function kickstart(kind, root) {
|
|
122
|
+
needLaunchd();
|
|
123
|
+
const r = spawnSync('launchctl', ['kickstart', '-k', `${domain()}/${label(kind, root)}`], { encoding: 'utf8' });
|
|
124
|
+
return r.status === 0;
|
|
125
|
+
}
|
|
126
|
+
|
|
74
127
|
// 在不在跑。launchctl print 的输出里有「pid = N」就是在跑
|
|
75
128
|
function status(kind, root) {
|
|
76
129
|
needLaunchd();
|
|
@@ -79,4 +132,4 @@ function status(kind, root) {
|
|
|
79
132
|
return { running: r.status === 0, pid: pid ? Number(pid[1]) : 0 };
|
|
80
133
|
}
|
|
81
134
|
|
|
82
|
-
module.exports = { label, plistPath, install, uninstall, status };
|
|
135
|
+
module.exports = { label, plistPath, looksLikeElectron, nodeForLaunchd, plistNode, install, uninstall, kickstart, startupProblem, status };
|
package/scripts/lib/rhythm.js
CHANGED
|
@@ -14,6 +14,7 @@ const { EXIT, Fail, fmtDate, fmtStamp, pad, tail, readText, writeFileAtomic } =
|
|
|
14
14
|
const { loadProfile } = require('./config');
|
|
15
15
|
const { logger } = require('./log');
|
|
16
16
|
const { createAgent } = require('./agent');
|
|
17
|
+
const { createBot } = require('./bot');
|
|
17
18
|
const { notifyChannel, pushText } = require('./notify');
|
|
18
19
|
const md = require('./markdown');
|
|
19
20
|
const launchd = require('./launchd');
|
|
@@ -373,9 +374,18 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
373
374
|
return md.page(path.basename(full), md.render(fs.readFileSync(full, 'utf8')), navHtml());
|
|
374
375
|
}
|
|
375
376
|
|
|
376
|
-
// 配置和依赖的问题,一条一个字符串。strict 为 false
|
|
377
|
-
function doctorProblems({ strict = true } = {}) {
|
|
377
|
+
// 配置和依赖的问题,一条一个字符串。strict 为 false 时不把「缺指令文件的任务」算进去;bot 为 false 时不把值守的配置算进去(起服务时值守配不齐只记一笔,不拦着)
|
|
378
|
+
function doctorProblems({ strict = true, bot = true } = {}) {
|
|
378
379
|
const problems = [];
|
|
380
|
+
// 已经装成常驻的:plist 里绑的得是真正的 node。从 DSH 这类桌面 agent 里装过的话,绑的是它们的 Electron 包,launchd 拉不起来
|
|
381
|
+
const plist = launchd.plistPath('service', root);
|
|
382
|
+
if (fs.existsSync(plist)) {
|
|
383
|
+
const node = launchd.plistNode(plist);
|
|
384
|
+
if (!node || launchd.looksLikeElectron(node, {})) problems.push(`常驻的 plist 里绑的不是真正的 node(${node || '没读到'}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
385
|
+
else if (!fs.existsSync(node)) problems.push(`常驻的 plist 里绑的 node 不在了(${node}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
386
|
+
}
|
|
387
|
+
// 值守开着的话,它的配置(agent、钥匙串、我的 openId、渠道)也要齐
|
|
388
|
+
if (bot && botWanted()) problems.push(...createBot({ root, env }).doctorProblems());
|
|
379
389
|
for (const [id, specText] of Object.entries(cfg.schedule)) {
|
|
380
390
|
if (NOT_SERVICE_TASKS.includes(id)) continue;
|
|
381
391
|
const spec = parseSpec(specText);
|
|
@@ -396,7 +406,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
396
406
|
// 前台跑:定时采集、定时整理、推送、网页服务。每 tickMs 看一次表(默认 20 秒)。收到 SIGINT / SIGTERM 后退出,返回退出码
|
|
397
407
|
async function start({ tickMs = TICK_MS } = {}) {
|
|
398
408
|
if (serviceAlive()) throw new Fail(EXIT.NOT_CONFIGURED, '服务已经在跑了(work-rhythm rhythm status 看详情)');
|
|
399
|
-
const problems = doctorProblems({ strict: false }).filter((p) => !p.startsWith('任务 '));
|
|
409
|
+
const problems = doctorProblems({ strict: false, bot: false }).filter((p) => !p.startsWith('任务 '));
|
|
400
410
|
if (problems.length) throw new Fail(EXIT.NOT_CONFIGURED, `配置有问题,先跑 work-rhythm rhythm doctor:\n${problems.join('\n')}`);
|
|
401
411
|
const server = await listen(cfg.port).catch((error) => {
|
|
402
412
|
throw new Fail(EXIT.FAILED, `网页服务起不来(${cfg.port} 端口):${error.message}`);
|
|
@@ -406,6 +416,22 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
406
416
|
log('服务开始', `pid=${process.pid} 页面=${baseUrl()} agent=${env.YZJ_BOT_AGENT || '(没配)'}`);
|
|
407
417
|
process.stdout.write(`页面:${baseUrl()} 停:work-rhythm rhythm stop\n`);
|
|
408
418
|
|
|
419
|
+
// 值守(机器人的收消息一半)也在这里跑:一个后台进程管定时任务、推送、网页和值守。collectors/local.env 的 YZJ_BOT_LISTEN=1 才开;
|
|
420
|
+
// 配置有问题不拦着服务起,只记一笔——定时任务和网页照常
|
|
421
|
+
let bot = null;
|
|
422
|
+
let botTask = null;
|
|
423
|
+
if (botWanted()) {
|
|
424
|
+
bot = createBot({ root, env });
|
|
425
|
+
const botProblems = bot.doctorProblems();
|
|
426
|
+
if (botProblems.length) log('值守没开', botProblems.join(';'));
|
|
427
|
+
else {
|
|
428
|
+
botTask = bot.run({ signals: false }).then(
|
|
429
|
+
() => log('值守结束'),
|
|
430
|
+
(error) => log('值守出错', error && error.message ? error.message : String(error)),
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
409
435
|
const list = jobs();
|
|
410
436
|
const state = loadState();
|
|
411
437
|
let running = null;
|
|
@@ -450,6 +476,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
450
476
|
log(`收到 ${signal},服务结束`);
|
|
451
477
|
clearInterval(timer);
|
|
452
478
|
if (running) running.kill('SIGTERM');
|
|
479
|
+
if (bot) bot.stop(signal);
|
|
453
480
|
try {
|
|
454
481
|
fs.unlinkSync(PID_FILE);
|
|
455
482
|
} catch {
|
|
@@ -461,6 +488,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
461
488
|
process.on('SIGINT', () => stop('SIGINT'));
|
|
462
489
|
process.on('SIGTERM', () => stop('SIGTERM'));
|
|
463
490
|
});
|
|
491
|
+
if (botTask) await Promise.race([botTask, new Promise((resolve) => setTimeout(resolve, 2000))]);
|
|
464
492
|
return EXIT.OK;
|
|
465
493
|
}
|
|
466
494
|
|
|
@@ -483,8 +511,17 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
483
511
|
return `已让它停下(pid ${pid})。`;
|
|
484
512
|
}
|
|
485
513
|
|
|
514
|
+
// 值守要不要跟着服务一起开
|
|
515
|
+
function botWanted() {
|
|
516
|
+
return (env.YZJ_BOT_LISTEN || '').trim() === '1';
|
|
517
|
+
}
|
|
518
|
+
|
|
486
519
|
function statusText() {
|
|
487
520
|
const lines = [serviceAlive() ? `在跑(pid ${readText(PID_FILE).trim()}),页面 ${baseUrl()}` : '没在跑。'];
|
|
521
|
+
// 值守:开关、最近一条日志(它自己记在 01-inbox/_bot.log)
|
|
522
|
+
const botLog = readText(path.join(root, '01-inbox', '_bot.log')).trim().split('\n');
|
|
523
|
+
const lastBot = botLog.length && botLog[botLog.length - 1] ? botLog[botLog.length - 1] : '';
|
|
524
|
+
lines.push(`值守:${botWanted() ? `开着${lastBot ? `,最近 ${lastBot}` : ''}` : '关着(collectors/local.env 的 YZJ_BOT_LISTEN=1 打开,改完 work-rhythm rhythm restart)'}`);
|
|
488
525
|
const runs = Object.entries(loadState().runs).sort((a, b) => a[1].at.localeCompare(b[1].at)).slice(-5);
|
|
489
526
|
if (runs.length) lines.push(`最近:${runs.map(([id, r]) => `${id} ${r.at} ${r.ok ? '成功' : `失败(${r.code})`}`).join(';')}`);
|
|
490
527
|
lines.push(`接下来:\n${due(new Date(), 1)}`);
|
|
@@ -103,7 +103,9 @@ test('agent bind:不给名字就绑正在调的这个;没标记就绑装了
|
|
|
103
103
|
assert.equal(exists(`${s.box.work}/collectors/local.env`), false);
|
|
104
104
|
const r = s.run(['agent', 'bind'], { ...env, DSH_SESSION_ID: 'sess-1' });
|
|
105
105
|
assert.equal(r.code, 0, r.out);
|
|
106
|
-
assert.match(r.stdout, /已绑定 dsh(DSH(DeepSeek Harness)的 headless 模式),写进了 collectors\/local\.env 的 YZJ_BOT_AGENT。\n 模型用它自己的默认,思考强度用它自己的默认\n 模型和思考强度还没配:work-rhythm agent models dsh 看能用哪些[\s\S]*\n下一步:work-rhythm agent test/);
|
|
106
|
+
assert.match(r.stdout, /已绑定 dsh(DSH(DeepSeek Harness)的 headless 模式),写进了 collectors\/local\.env 的 YZJ_BOT_AGENT。\n 模型用它自己的默认,思考强度用它自己的默认\n 会话:绑着 sess-1,机器人的话从这个会话接着走(刚绑上)\n 模型和思考强度还没配:work-rhythm agent models dsh 看能用哪些[\s\S]*\n下一步:work-rhythm agent test/);
|
|
107
|
+
// 正在调的这个 agent 的当前会话(DSH_SESSION_ID)顺手绑上了
|
|
108
|
+
assert.match(read(`${s.box.work}/collectors/local.env`), /^YZJ_BOT_SESSION="sess-1"$/m);
|
|
107
109
|
// local.env 原来没有:从样例复制一份,再把样例里注释掉的那行换成真的
|
|
108
110
|
const text = read(`${s.box.work}/collectors/local.env`);
|
|
109
111
|
assert.match(text, /^YZJ_BOT_AGENT="dsh"$/m);
|
|
@@ -337,3 +339,66 @@ test('agent --json:带模型、强度,以及这个 agent 支不支持', (t)
|
|
|
337
339
|
assert.equal(zcode.effortSupported, false);
|
|
338
340
|
assert.equal(doc.agents.find((a) => a.name === 'dsh').modelSupported, true);
|
|
339
341
|
});
|
|
342
|
+
|
|
343
|
+
// ---------------------------------------------------------------- 会话绑定
|
|
344
|
+
test('agent bind:绑的正好是正在调这个 skill 的 agent 时,自动把它当前的会话绑上;别的 agent 不绑;--no-session / --session <id> 可控', (t) => {
|
|
345
|
+
const s = setup(t);
|
|
346
|
+
const env = s.bindEnv();
|
|
347
|
+
// 现在是 dsh 在调(DSH_SESSION_ID),绑 dsh → 自动绑会话
|
|
348
|
+
const a = s.run(['agent', 'bind', 'dsh'], { ...env, DSH_SESSION_ID: 'session-desktop' });
|
|
349
|
+
assert.match(a.stdout, /会话:绑着 session-desktop,机器人的话从这个会话接着走(刚绑上)/);
|
|
350
|
+
assert.match(read(`${s.box.work}/collectors/local.env`), /^YZJ_BOT_SESSION="session-desktop"$/m);
|
|
351
|
+
// 是 dsh 在调,却绑 qoder:qoder 的当前会话认不出来,不绑
|
|
352
|
+
const b = s.run(['agent', 'bind', 'qoder'], { ...env, DSH_SESSION_ID: 'session-desktop' });
|
|
353
|
+
assert.match(b.stdout, /会话:没绑,机器人用自己的专属会话/);
|
|
354
|
+
assert.match(read(`${s.box.work}/collectors/local.env`), /^YZJ_BOT_SESSION=""$/m);
|
|
355
|
+
// 各家给工具留的会话 id 都认
|
|
356
|
+
assert.equal(s.run(['agent', 'bind', 'zcode'], { ...env, ZCODE_SESSION_ID: 'sess_z' }).stdout.includes('绑着 sess_z'), true);
|
|
357
|
+
assert.equal(s.run(['agent', 'bind', 'claude'], { ...env, CLAUDE_CODE_SESSION_ID: 'sess_c' }).stdout.includes('绑着 sess_c'), true);
|
|
358
|
+
assert.equal(s.run(['agent', 'bind', 'qoder'], { ...env, QODER_SESSION_ID: 'sess_q' }).stdout.includes('绑着 sess_q'), true);
|
|
359
|
+
// 不想绑:--no-session;或者指定一个
|
|
360
|
+
s.run(['agent', 'bind', 'dsh'], { ...env, DSH_SESSION_ID: 'session-desktop' });
|
|
361
|
+
assert.match(s.run(['agent', 'bind', 'dsh', '--no-session'], { ...env, DSH_SESSION_ID: 'session-desktop' }).stdout, /会话:没绑/);
|
|
362
|
+
const pick = s.run(['agent', 'bind', 'dsh', '--session', 'session-old'], { ...env, DSH_SESSION_ID: 'session-desktop' });
|
|
363
|
+
assert.match(pick.stdout, /会话:绑着 session-old/);
|
|
364
|
+
// --json 里也有
|
|
365
|
+
const doc = JSON.parse(s.run(['agent', '--json'], env).stdout);
|
|
366
|
+
assert.equal(doc.session, 'session-old');
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
test('agent session / sessions:看、换、清;dsh 按工作区列出会话,新的在前,标出绑着的和值守自己的', (t) => {
|
|
370
|
+
const s = setup(t);
|
|
371
|
+
const env = s.bindEnv();
|
|
372
|
+
// 夹具:在假的 DSH_HOME 下按 DSH 的目录规则放三个会话(新的在前)
|
|
373
|
+
const dir = path.join(s.stubs.DSH_HOME, 'sessions', `-${`${fs.realpathSync(s.box.work)}/`.replace(/[^A-Za-z0-9]/g, '-')}-`);
|
|
374
|
+
for (const [name, age] of [['session-old', 3000], ['session-mid', 2000], ['session-new', 1000]]) {
|
|
375
|
+
fs.mkdirSync(path.join(dir, name), { recursive: true });
|
|
376
|
+
const when = new Date(Date.now() - age);
|
|
377
|
+
fs.utimesSync(path.join(dir, name), when, when);
|
|
378
|
+
}
|
|
379
|
+
// 没绑时
|
|
380
|
+
assert.equal(s.run(['agent', 'session'], env).code, 3);
|
|
381
|
+
assert.equal(s.run(['agent', 'sessions'], env).code, 3);
|
|
382
|
+
s.run(['agent', 'bind', 'dsh'], env);
|
|
383
|
+
const show = s.run(['agent', 'session'], { ...env, DSH_SESSION_ID: 'session-now' });
|
|
384
|
+
assert.equal(show.code, 0);
|
|
385
|
+
assert.match(show.stdout, /会话:没绑,机器人用自己的专属会话。当前这个会话(如果是从 dsh 里跑的):session-now/);
|
|
386
|
+
const list = s.run(['agent', 'sessions'], env);
|
|
387
|
+
assert.equal(list.code, 0, list.out);
|
|
388
|
+
assert.match(list.stdout, /^dsh 在这个工作区的会话,新的在前:\n session-new .*\n session-mid .*\n session-old .*\n绑哪个:work-rhythm agent session <id>/);
|
|
389
|
+
// 换一个,再列就标出来
|
|
390
|
+
const bind = s.run(['agent', 'session', 'session-mid'], env);
|
|
391
|
+
assert.match(bind.stdout, /会话已绑为 session-mid,写进了 collectors\/local\.env。机器人下一句从这个会话接着走。/);
|
|
392
|
+
assert.match(read(`${s.box.work}/collectors/local.env`), /^YZJ_BOT_SESSION="session-mid"$/m);
|
|
393
|
+
const listed = s.run(['agent', 'sessions'], env).stdout;
|
|
394
|
+
assert.match(listed, / session-mid .* 绑着的\n/);
|
|
395
|
+
const newLine = listed.split('\n').find((l) => l.startsWith(' session-new'));
|
|
396
|
+
assert.ok(newLine && !/绑着的|值守自己的/.test(newLine), '没绑的、也不是值守自己的不带标记');
|
|
397
|
+
// 值守自己的会话(01-inbox/_bot/session-id)也标出来
|
|
398
|
+
write(`${s.box.work}/01-inbox/_bot/session-id`, 'session-new\n');
|
|
399
|
+
assert.match(s.run(['agent', 'sessions'], env).stdout, / session-new .* 值守自己的\n/);
|
|
400
|
+
// 清掉
|
|
401
|
+
assert.match(s.run(['agent', 'session', '--clear'], env).stdout, /会话已清掉,机器人用自己的专属会话。/);
|
|
402
|
+
assert.equal(s.run(['agent', 'session', 'a', 'b'], env).code, 2);
|
|
403
|
+
assert.equal(s.run(['agent', 'sessions', 'x'], env).code, 2);
|
|
404
|
+
});
|
package/scripts/test/harness.js
CHANGED
|
@@ -364,3 +364,100 @@ test('agent:自定义命令按空白拆开,引号里的算一个参数,消
|
|
|
364
364
|
assert.equal(r.code, 0, r.out);
|
|
365
365
|
assert.equal(r.stdout, '--name\na b\nc d\n一句话\n');
|
|
366
366
|
});
|
|
367
|
+
|
|
368
|
+
// ---------------------------------------------------------------- 会话:接着绑定的那个走
|
|
369
|
+
function botReady(s, hook, localEnv) {
|
|
370
|
+
s.setNotify('"yzj-robot"');
|
|
371
|
+
write(`${s.box.work}/collectors/local.env`, localEnv);
|
|
372
|
+
return { ...s.stubs, STUB_KEYCHAIN: 'ok', STUB_ROBOT_URL: hook.url, YZJ_BOT_PREAMBLE: '' };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
test('listen:绑了会话(YZJ_BOT_SESSION)时,机器人的每句话都从那个会话接着走,不用值守自己的', async (t) => {
|
|
376
|
+
const hook = await webhook(t);
|
|
377
|
+
const s = setup(t);
|
|
378
|
+
const env = botReady(s, hook, 'YZJ_MY_OPEN_ID="me-0001"\nYZJ_BOT_AGENT="dsh"\nYZJ_BOT_SESSION="session-desktop"\n');
|
|
379
|
+
const first = s.listen(['handle', '第一句'], env);
|
|
380
|
+
assert.equal(first.code, 0, first.out);
|
|
381
|
+
assert.match(read(s.stubs.STUB_DSH_ARGS), /--session-id session-desktop --json 第一句\n$/);
|
|
382
|
+
s.listen(['handle', '第二句'], env);
|
|
383
|
+
// 第二句还是从绑定的那个会话走(不是 fake 回的 session_fake)
|
|
384
|
+
assert.match(read(s.stubs.STUB_DSH_ARGS), /--session-id session-desktop --json 第二句\n$/);
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
test('listen:绑定的会话接不上时退回归值守自己的专属会话,以后不再去试那个绑定的;/new 之后又从绑定的开始', async (t) => {
|
|
388
|
+
const hook = await webhook(t);
|
|
389
|
+
const s = setup(t);
|
|
390
|
+
const env = { ...botReady(s, hook, 'YZJ_MY_OPEN_ID="me-0001"\nYZJ_BOT_AGENT="dsh"\nYZJ_BOT_SESSION="session-gone"\n'), STUB_DSH_REJECT_SESSION: 'session-gone' };
|
|
391
|
+
// 第一句:先试绑定的(被拒),改开新会话(fake 回 session_fake),记下来
|
|
392
|
+
const first = s.listen(['handle', '第一句'], env);
|
|
393
|
+
assert.equal(first.code, 0, first.out);
|
|
394
|
+
assert.equal(s.session(), 'session_fake');
|
|
395
|
+
assert.match(s.botLog(), /agent 接不上旧会话,改开新会话/);
|
|
396
|
+
// 第二句:直接用自己的 session_fake,不再碰绑定的(「接不上」还是只记了一次)
|
|
397
|
+
s.listen(['handle', '第二句'], env);
|
|
398
|
+
assert.match(read(s.stubs.STUB_DSH_ARGS), /--session-id session_fake --json 第二句\n$/);
|
|
399
|
+
assert.equal(s.botLog().split('agent 接不上旧会话').length - 1, 1);
|
|
400
|
+
assert.equal(exists(`${s.box.work}/01-inbox/_bot/bound-session-lost`), true, '接不上这件事要记下来,下一个进程才知道');
|
|
401
|
+
// /new:丢掉自己的,下一句又从绑定的开始(绑定的还是接不上,就再退回来)
|
|
402
|
+
const reset = s.listen(['handle-frame', JSON.stringify({ operatorOpenid: 'me-0001', msgId: 'n1', content: '/new' })], env);
|
|
403
|
+
assert.equal(reset.code, 0);
|
|
404
|
+
assert.equal(hook.contents().at(-1), '已丢掉值守自己开的会话,下一句从绑定的那个会话接着走。');
|
|
405
|
+
s.listen(['handle', '第三句'], env);
|
|
406
|
+
assert.equal(s.session(), 'session_fake');
|
|
407
|
+
assert.equal(s.botLog().split('agent 接不上旧会话').length - 1, 2, '第三句又试了绑定的那个(/new 把记录清了)');
|
|
408
|
+
// 换绑一个会话(agent session <id>):记录也清掉,下一句从新绑的开始
|
|
409
|
+
s.box.run(['agent', 'session', 'session-desktop2'], { env });
|
|
410
|
+
assert.equal(exists(`${s.box.work}/01-inbox/_bot/bound-session-lost`), false);
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
test('listen install / uninstall / status:值守跑在本地服务那一个进程里——开关写进 local.env,老的单独常驻收掉,服务没装就装', (t) => {
|
|
414
|
+
const s = setup(t);
|
|
415
|
+
s.setNotify('"yzj-robot"');
|
|
416
|
+
write(`${s.box.work}/collectors/local.env`, 'YZJ_MY_OPEN_ID="me-0001"\nYZJ_BOT_AGENT="dsh"\n');
|
|
417
|
+
const home = path.join(s.box.root, 'home');
|
|
418
|
+
fs.mkdirSync(path.join(home, 'Library', 'LaunchAgents'), { recursive: true });
|
|
419
|
+
const env = { ...s.stubs, HOME: home, STUB_KEYCHAIN: 'ok', STUB_LAUNCHCTL_RUNNING: '1', STUB_ROBOT_URL: 'http://127.0.0.1:1/send?yzjtoken=stubtoken0123456789abcd' };
|
|
420
|
+
const agents = path.join(home, 'Library', 'LaunchAgents');
|
|
421
|
+
// 老的单独常驻还在:install 要把它收掉
|
|
422
|
+
write(path.join(agents, 'work-rhythm.bot.work.plist'), '<plist/>');
|
|
423
|
+
assert.equal(s.listen(['status'], env).code, 1);
|
|
424
|
+
assert.match(s.listen(['status'], env).stdout, /本地服务没在跑(work-rhythm rhythm status 看详情);值守关着。\n提醒:还有一个老的单独常驻/);
|
|
425
|
+
const r = s.listen(['install'], env);
|
|
426
|
+
assert.equal(r.code, 0, r.out);
|
|
427
|
+
assert.match(r.stdout, /值守已打开(collectors\/local.env 的 YZJ_BOT_LISTEN=1),跑在本地服务里。本地服务已装成常驻/);
|
|
428
|
+
assert.match(read(`${s.box.work}/collectors/local.env`), /^YZJ_BOT_LISTEN="1"$/m);
|
|
429
|
+
assert.equal(exists(path.join(agents, 'work-rhythm.bot.work.plist')), false, '老的单独常驻收掉');
|
|
430
|
+
assert.ok(exists(path.join(agents, 'work-rhythm.service.work.plist')), '装的是服务那一个');
|
|
431
|
+
const calls = read(s.stubs.STUB_LAUNCHCTL);
|
|
432
|
+
assert.match(calls, /bootout gui\/\d+\/work-rhythm\.bot\.work\n/);
|
|
433
|
+
assert.match(calls, /bootstrap gui\/\d+ .*work-rhythm\.service\.work\.plist\n/);
|
|
434
|
+
// plist 里的程序是服务(rhythm start),不是 listen run
|
|
435
|
+
assert.match(read(path.join(agents, 'work-rhythm.service.work.plist')), /<string>rhythm<\/string>\s*<string>start<\/string>/);
|
|
436
|
+
assert.ok(!read(path.join(agents, 'work-rhythm.service.work.plist')).includes('<string>listen</string>'));
|
|
437
|
+
// 服务在跑(pid 文件里有活着的进程,launchd 说在):改开关只重启服务,不重装
|
|
438
|
+
write(`${s.box.work}/01-inbox/_rhythm/service.pid`, `${process.pid}\n`);
|
|
439
|
+
write(s.stubs.STUB_LAUNCHCTL, '');
|
|
440
|
+
const off = s.listen(['uninstall'], { ...env, STUB_LAUNCHCTL_RUNNING: '1' });
|
|
441
|
+
assert.equal(off.code, 0, off.out);
|
|
442
|
+
assert.match(off.stdout, /值守已关掉(YZJ_BOT_LISTEN=0)。本地服务已重启,值守的改动生效。/);
|
|
443
|
+
assert.match(read(`${s.box.work}/collectors/local.env`), /^YZJ_BOT_LISTEN="0"$/m);
|
|
444
|
+
assert.match(read(s.stubs.STUB_LAUNCHCTL), /bootout gui\/\d+\/work-rhythm\.bot\.work\nkickstart -k gui\/\d+\/work-rhythm\.service\.work\n/);
|
|
445
|
+
assert.equal(s.listen(['status'], { ...env, STUB_LAUNCHCTL_RUNNING: '1' }).stdout, '本地服务在跑(work-rhythm rhythm status 看详情);值守关着。\n');
|
|
446
|
+
// 配置不齐不让开:开关都不写
|
|
447
|
+
write(`${s.box.work}/collectors/local.env`, 'YZJ_BOT_AGENT="dsh"\n');
|
|
448
|
+
const bad = s.listen(['install'], env);
|
|
449
|
+
assert.equal(bad.code, 3);
|
|
450
|
+
assert.ok(!/YZJ_BOT_LISTEN=1/.test(read(`${s.box.work}/collectors/local.env`)));
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
test('listen:agent 是在工作目录里跑的(dsh 的 cwd、zcode / qoder / claude 的 --cwd 都是工作目录)', async (t) => {
|
|
454
|
+
const s = setup(t);
|
|
455
|
+
const env = { ...botReady(s, await webhook(t), 'YZJ_MY_OPEN_ID="me-0001"\n'), QODER_CLI: path.join(s.box.bin, 'fake-qoder'), CLAUDE_CLI: path.join(s.box.bin, 'fake-claude') };
|
|
456
|
+
for (const name of ['dsh', 'zcode', 'qoder', 'claude']) {
|
|
457
|
+
write(`${s.box.work}/collectors/local.env`, `YZJ_MY_OPEN_ID="me-0001"\nYZJ_BOT_AGENT="${name}"\n`);
|
|
458
|
+
const r = s.listen(['handle', '在吗'], env);
|
|
459
|
+
assert.equal(r.code, 0, `${name}: ${r.out}`);
|
|
460
|
+
if (name === 'dsh') assert.equal(read(`${s.stubs.STUB_DSH_ARGS}.cwd`).trim(), fs.realpathSync(s.box.work));
|
|
461
|
+
else assert.ok(read(s.stubs[`STUB_${name.toUpperCase()}_ARGS`]).startsWith(`--cwd ${fs.realpathSync(s.box.work)} `), `${name} 的 --cwd`);
|
|
462
|
+
}
|
|
463
|
+
});
|
|
@@ -352,3 +352,80 @@ test('rhythm:profile 的 agent-model / agent-effort 给定时任务另配一
|
|
|
352
352
|
assert.equal(s.rhythm(['run', 'daily-plan'], env).code, 0);
|
|
353
353
|
assert.match(read(`${s.box.work}/01-inbox/_rhythm/dsh-headless.patch.yml`), / model: deepseek-v4\.1-flash\n reasoningEffort: high\n/);
|
|
354
354
|
});
|
|
355
|
+
|
|
356
|
+
// ---------------------------------------------------------------- 值守跟着服务一起跑
|
|
357
|
+
test('rhythm:YZJ_BOT_LISTEN=1 时值守在服务的同一个进程里跑;配置不齐只记一笔,服务照常;status 里看得到', async (t) => {
|
|
358
|
+
const hook = await webhook(t);
|
|
359
|
+
const s = setup(t);
|
|
360
|
+
const port = await freePort();
|
|
361
|
+
s.set('port', String(port));
|
|
362
|
+
const profile = `${s.box.work}/00-config/profile.yaml`;
|
|
363
|
+
write(profile, read(profile).replace(/^ notify:.*$/m, ' notify: "yzj-robot"'));
|
|
364
|
+
write(`${s.box.work}/collectors/local.env`, 'YZJ_BOT_AGENT="dsh"\n');
|
|
365
|
+
const botEnv = { ...s.env, STUB_ROBOT_URL: 'wss://127.0.0.1:1/xuntong/websocket?yzjtoken=stubtoken0123456789abcd' };
|
|
366
|
+
// 值守开着、配置齐:服务日志里有「值守开始」,同一个 pid;机器人连不上(假地址)只是重连,不影响服务和网页
|
|
367
|
+
const proc = s.box.spawn(['rhythm', 'start', '--tick', '1'], { env: { ...botEnv, YZJ_BOT_LISTEN: '1', YZJ_MY_OPEN_ID: 'me-0001' } });
|
|
368
|
+
t.after(async () => {
|
|
369
|
+
s.rhythm(['stop'], botEnv);
|
|
370
|
+
await proc.exited;
|
|
371
|
+
});
|
|
372
|
+
assert.ok(await proc.waitFor('页面:'), proc.text());
|
|
373
|
+
assert.ok(await proc.waitFor('值守开始', 8000), proc.text());
|
|
374
|
+
const servicePid = read(`${s.box.work}/01-inbox/_rhythm/service.pid`).trim();
|
|
375
|
+
const botLog = read(`${s.box.work}/01-inbox/_bot.log`);
|
|
376
|
+
assert.match(botLog, new RegExp(`值守开始 pid=${servicePid} agent=dsh mode=plan`), '值守和服务是同一个进程');
|
|
377
|
+
assert.match(botLog, /会话=值守自己的专属会话/);
|
|
378
|
+
assert.equal((await fetch(`http://127.0.0.1:${port}/`)).status, 200);
|
|
379
|
+
assert.match(s.rhythm(['status'], { ...botEnv, YZJ_BOT_LISTEN: '1' }).stdout, /值守:开着,最近 .*/);
|
|
380
|
+
assert.match(s.rhythm(['doctor'], { ...botEnv, YZJ_BOT_LISTEN: '1', YZJ_MY_OPEN_ID: 'me-0001' }).stdout, /^$/);
|
|
381
|
+
// 关着的时候什么都不起
|
|
382
|
+
assert.match(s.rhythm(['status'], botEnv).stdout, /值守:关着/);
|
|
383
|
+
// 配置不齐(没写我的 openId):doctor 报出来;服务照样起,只记「值守没开」
|
|
384
|
+
const bad = s.rhythm(['doctor'], { ...botEnv, YZJ_BOT_LISTEN: '1', YZJ_MY_OPEN_ID: '' });
|
|
385
|
+
assert.equal(bad.code, 1);
|
|
386
|
+
assert.match(bad.stdout, /值守只处理我本人的消息:collectors\/local\.env 里要写 YZJ_MY_OPEN_ID/);
|
|
387
|
+
// 先把前一个停掉,再起一个配置不齐的
|
|
388
|
+
s.rhythm(['stop'], botEnv);
|
|
389
|
+
await proc.exited;
|
|
390
|
+
const proc2 = s.box.spawn(['rhythm', 'start', '--tick', '1'], { env: { ...botEnv, YZJ_BOT_LISTEN: '1', YZJ_MY_OPEN_ID: '' } });
|
|
391
|
+
t.after(async () => {
|
|
392
|
+
s.rhythm(['stop'], botEnv);
|
|
393
|
+
await proc2.exited;
|
|
394
|
+
});
|
|
395
|
+
assert.ok(await proc2.waitFor('页面:'), proc2.text());
|
|
396
|
+
assert.ok(await proc2.waitFor('值守没开', 8000), proc2.text());
|
|
397
|
+
assert.equal((await fetch(`http://127.0.0.1:${port}/`)).status, 200);
|
|
398
|
+
s.rhythm(['stop'], botEnv);
|
|
399
|
+
await proc2.exited;
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
test('rhythm install:装的是服务那一个常驻,老的单独值守常驻顺手收掉;restart 在 launchd 管着时重启', (t) => {
|
|
403
|
+
const s = setup(t);
|
|
404
|
+
const home = path.join(s.box.root, 'home');
|
|
405
|
+
const agents = path.join(home, 'Library', 'LaunchAgents');
|
|
406
|
+
fs.mkdirSync(agents, { recursive: true });
|
|
407
|
+
write(path.join(agents, 'work-rhythm.bot.work.plist'), '<plist/>');
|
|
408
|
+
const env = { ...s.env, HOME: home, STUB_LAUNCHCTL_RUNNING: '1' };
|
|
409
|
+
assert.equal(s.rhythm(['install'], env).code, 0, s.rhythm(['install'], env).out);
|
|
410
|
+
// 装完核对过真的起来了(假的 launchctl 说在跑);plist 里绑的是真正的 node
|
|
411
|
+
assert.equal(require('../lib/launchd').plistNode(path.join(agents, 'work-rhythm.service.work.plist')), process.execPath);
|
|
412
|
+
assert.equal(s.rhythm(['doctor'], env).code, 0, s.rhythm(['doctor'], env).out);
|
|
413
|
+
// launchd 说没在跑:install 不报成功,带着日志说清
|
|
414
|
+
const notUp = s.rhythm(['install'], { ...s.env, HOME: home });
|
|
415
|
+
assert.equal(notUp.code, 5);
|
|
416
|
+
assert.match(notUp.stderr, /装是装上了,但 launchd 没能把它拉起来。先看 .*_rhythm\.launchd\.log/);
|
|
417
|
+
// 装坏的 plist(绑的是 DSH 的 Electron 包):doctor 报出来
|
|
418
|
+
write(path.join(agents, 'work-rhythm.service.work.plist'), '<key>ProgramArguments</key><array><string>/Users/x/.dsh-desktop/sidecar-node/1/DSH Node.app/Contents/MacOS/DSH Node</string></array>');
|
|
419
|
+
const bad = s.rhythm(['doctor'], env);
|
|
420
|
+
assert.equal(bad.code, 1);
|
|
421
|
+
assert.match(bad.stdout, /常驻的 plist 里绑的不是真正的 node(.*DSH Node\.app\/Contents\/MacOS\/DSH Node):work-rhythm rhythm uninstall 再 install 一次/);
|
|
422
|
+
assert.ok(exists(path.join(agents, 'work-rhythm.service.work.plist')));
|
|
423
|
+
assert.equal(exists(path.join(agents, 'work-rhythm.bot.work.plist')), false, '老的单独值守常驻收掉');
|
|
424
|
+
assert.match(read(s.env.STUB_LAUNCHCTL), /bootout gui\/\d+\/work-rhythm\.bot\.work\n/);
|
|
425
|
+
const restart = s.rhythm(['restart'], { ...s.env, HOME: home });
|
|
426
|
+
assert.equal(restart.code, 3, 'launchd 说没在跑就不重启');
|
|
427
|
+
assert.match(restart.stderr, /服务不是 launchd 管的常驻/);
|
|
428
|
+
const again = s.rhythm(['restart'], { ...env, STUB_LAUNCHCTL_RUNNING: '1' });
|
|
429
|
+
assert.equal(again.code, 0, again.out);
|
|
430
|
+
assert.match(read(s.env.STUB_LAUNCHCTL), /kickstart -k gui\/\d+\/work-rhythm\.service\.work\n$/);
|
|
431
|
+
});
|