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.
- package/.agents/notes/AGENTS.md +8 -1
- package/.agents/notes/decisions/2026-12-01-interjections-batch-into-one-answer-and-interrupt-reruns.md +33 -0
- package/.agents/notes/decisions/2026-12-01-long-runs-are-bounded-by-silence-not-wall-clock.md +35 -0
- package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +41 -0
- package/.agents/notes/pitfalls/2026-12-01-launchd-install-bakes-invoking-node.md +28 -0
- package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +16 -0
- package/.agents/skills/work-rhythm/SKILL.md +14 -12
- package/README.md +7 -4
- package/collectors/local.env.example +10 -1
- package/docs/agents.md +28 -11
- package/docs/channels.md +9 -6
- package/docs/router-worker.md +241 -0
- package/docs/scheduled-tasks.md +4 -4
- package/package.json +1 -1
- package/scripts/cli.js +4 -3
- package/scripts/cmd/agent.js +78 -40
- package/scripts/cmd/check.js +4 -0
- package/scripts/cmd/listen.js +20 -4
- package/scripts/cmd/rhythm.js +9 -2
- package/scripts/cmd/trigger.js +143 -0
- package/scripts/lib/agent.js +377 -30
- package/scripts/lib/bot.js +140 -35
- package/scripts/lib/engine.js +523 -0
- package/scripts/lib/handoff.js +165 -0
- package/scripts/lib/launchd.js +49 -3
- package/scripts/lib/markdown.js +328 -38
- package/scripts/lib/rhythm.js +377 -33
- package/scripts/lib/router.js +161 -0
- package/scripts/lib/run.js +43 -0
- package/scripts/lib/view.js +583 -0
- package/scripts/lib/worker.js +97 -0
- package/scripts/test/agent.test.js +17 -9
- package/scripts/test/check.test.js +7 -2
- package/scripts/test/harness.js +13 -1
- package/scripts/test/listen.test.js +3 -3
- package/scripts/test/rhythm.test.js +42 -8
- package/scripts/test/router-helper.js +80 -0
- package/scripts/test/router.test.js +509 -0
- package/scripts/test/stubs.js +82 -12
- package/scripts/test/timeout.test.js +99 -0
- package/templates/00-config/profile.example.yaml +7 -0
- package/templates/AGENTS.md +3 -1
- package/templates/README.md +4 -1
package/scripts/lib/rhythm.js
CHANGED
|
@@ -2,21 +2,25 @@
|
|
|
2
2
|
// 1 定时采集:按 profile 的 rhythm.sync 跑一遍 sync,数据落 01-inbox/;
|
|
3
3
|
// 2 定时整理:按 profile 的 schedule 把 tasks/<id>.md 的指令交给 agent 跑一遍(怎么调起 agent 见 agent.js);
|
|
4
4
|
// 3 推送:整理完把 agent 的总结经消息渠道(notify.js)发给我,附一个本机地址;
|
|
5
|
-
// 4 看页面:只绑 127.0.0.1 的网页服务,把工作目录里的 Markdown 现渲染成 HTML(markdown.js)。
|
|
6
|
-
//
|
|
5
|
+
// 4 看页面:只绑 127.0.0.1 的网页服务,把工作目录里的 Markdown 现渲染成 HTML(markdown.js),外加一页监控中心(/monitor)。
|
|
6
|
+
// profile 的 rhythm.router 为 true 时走引擎(engine.js):到点的任务和 IM 里的话都变成触发,交给路由判断,再派给执行者;
|
|
7
|
+
// 没写就是直通(老做法):任务是一个个子进程跑的,调度不被堵住,一次只跑一个,后面的排队。错过的任务在 5 分钟内还会补跑,再久就不追了。
|
|
7
8
|
// 只用 node 自带的能力。日志写 01-inbox/_rhythm.log,状态写 01-inbox/_rhythm/state.json。
|
|
8
9
|
'use strict';
|
|
9
10
|
const { spawn } = require('node:child_process');
|
|
10
11
|
const fs = require('node:fs');
|
|
11
12
|
const http = require('node:http');
|
|
12
13
|
const path = require('node:path');
|
|
13
|
-
const { EXIT, Fail, fmtDate, fmtStamp, pad, tail, readText, writeFileAtomic } = require('./run');
|
|
14
|
+
const { EXIT, Fail, fmtDate, fmtStamp, pad, tail, readText, writeFileAtomic, seconds } = require('./run');
|
|
14
15
|
const { loadProfile } = require('./config');
|
|
15
16
|
const { logger } = require('./log');
|
|
16
|
-
const { createAgent } = require('./agent');
|
|
17
|
+
const { createAgent, roles } = require('./agent');
|
|
17
18
|
const { createBot } = require('./bot');
|
|
18
19
|
const { notifyChannel, pushText } = require('./notify');
|
|
20
|
+
const { createEngine, appendHistory, pruneState, historyStats, uid } = require('./engine');
|
|
21
|
+
const handoff = require('./handoff');
|
|
19
22
|
const md = require('./markdown');
|
|
23
|
+
const view = require('./view');
|
|
20
24
|
const launchd = require('./launchd');
|
|
21
25
|
const sync = require('../cmd/sync');
|
|
22
26
|
const today = require('../cmd/today');
|
|
@@ -35,12 +39,19 @@ const LINKS = {
|
|
|
35
39
|
'weekly-rhythm': { path: () => '/rhythm', label: '工作规律' },
|
|
36
40
|
'alerts-morning': { path: (d) => `/reports/${d}-alerts.html`, label: '告警晨报' },
|
|
37
41
|
};
|
|
38
|
-
const NAV = [['/', '今日'], ['/carryover', '遗留'], ['/decisions', '决定'], ['/rhythm', '规律'], ['/goals', '目标'], ['/reports', '报告']];
|
|
42
|
+
const NAV = [['/', '今日'], ['/carryover', '遗留'], ['/decisions', '决定'], ['/rhythm', '规律'], ['/goals', '目标'], ['/reports', '报告'], ['/monitor', '监控']];
|
|
43
|
+
const NEW_KEYS = [['workers', 'rhythm.workers'], ['router-timeout', 'rhythm.router-timeout'], ['handoff-keep', 'rhythm.handoff-keep'], ['history-keep', 'rhythm.history-keep']];
|
|
44
|
+
// 状态文件的骨架:done(跑过的任务)、runs(各任务最近一次)、seq(触发短号的序号)、triggers(近两天的触发)、history(运行记录)、rounds(路由的轮数)
|
|
45
|
+
const EMPTY_STATE = () => ({ done: {}, runs: {}, seq: 0, triggers: {}, history: [], rounds: [] });
|
|
39
46
|
|
|
40
47
|
const positiveInt = (value, fallback) => {
|
|
41
48
|
const n = Number(value);
|
|
42
49
|
return Number.isInteger(n) && n > 0 ? n : fallback;
|
|
43
|
-
}
|
|
50
|
+
};// 任务指令开头「任务:每日工作计划。」那一行当它的标题
|
|
51
|
+
function taskTitleOf(body) {
|
|
52
|
+
const m = /^任务[::]\s*(.+)$/m.exec(String(body || ''));
|
|
53
|
+
return m ? m[1].trim().replace(/[。.]\s*$/, '') : '';
|
|
54
|
+
}
|
|
44
55
|
const hhmm = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
45
56
|
const asList = (value) => (Array.isArray(value) ? value.map((v) => String(v).trim()).filter(Boolean) : []);
|
|
46
57
|
|
|
@@ -63,6 +74,13 @@ function loadConfig(root) {
|
|
|
63
74
|
syncTimeout: positiveInt(rhythm['sync-timeout'], 600),
|
|
64
75
|
notifyChannel: typeof preferences.notify === 'string' ? preferences.notify.trim() : '',
|
|
65
76
|
schedule,
|
|
77
|
+
// 路由和执行者(docs/router-worker.md)。router 没写就是直通(老做法)
|
|
78
|
+
router: rhythm.router === true,
|
|
79
|
+
routerTimeout: positiveInt(rhythm['router-timeout'], 120),
|
|
80
|
+
workers: positiveInt(rhythm.workers, 2),
|
|
81
|
+
handoffKeep: positiveInt(rhythm['handoff-keep'], 14),
|
|
82
|
+
historyKeep: positiveInt(rhythm['history-keep'], 90),
|
|
83
|
+
raw: rhythm,
|
|
66
84
|
};
|
|
67
85
|
}
|
|
68
86
|
|
|
@@ -103,6 +121,40 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
103
121
|
const log = logger(LOG_FILE);
|
|
104
122
|
const cfg = loadConfig(root);
|
|
105
123
|
const baseUrl = () => `http://127.0.0.1:${cfg.port}`;
|
|
124
|
+
// 这个对象是哪天起的(监控中心的「已跑多久」)
|
|
125
|
+
const since = Date.now();
|
|
126
|
+
// 状态(engine.js 也往里写):同一个进程里只有这一份
|
|
127
|
+
const store = { data: loadState(), save() { saveState(store.data); } };
|
|
128
|
+
// 引擎(路由 + 执行者):profile 的 rhythm.router 为 true 时才有,同一个进程里只建一个
|
|
129
|
+
let engine = null;
|
|
130
|
+
const engineCfg = () => {
|
|
131
|
+
const idle = seconds(env.YZJ_BOT_IDLE, 180);
|
|
132
|
+
return {
|
|
133
|
+
...cfg,
|
|
134
|
+
ack: env.YZJ_BOT_ACK !== '0',
|
|
135
|
+
botMode: (env.YZJ_BOT_AGENT_MODE || 'plan').trim(),
|
|
136
|
+
botTimeout: positiveInt(env.YZJ_BOT_TIMEOUT, 900),
|
|
137
|
+
// 执行者可能长时间不出声(跑构建、跑测试),静默闸给得比值守宽;硬上限还是 task-timeout。0 表示关掉
|
|
138
|
+
workerIdle: idle === 0 ? 0 : Math.max(600, idle),
|
|
139
|
+
progress: seconds(env.YZJ_BOT_PROGRESS, 90),
|
|
140
|
+
progressMax: positiveInt(env.YZJ_BOT_PROGRESS_MAX, 3),
|
|
141
|
+
replyMax: positiveInt(env.YZJ_BOT_REPLY_MAX, 2000),
|
|
142
|
+
botPreamble: (env.YZJ_BOT_PREAMBLE || '').trim(),
|
|
143
|
+
links: LINKS,
|
|
144
|
+
baseUrl: baseUrl(),
|
|
145
|
+
serviceAlive,
|
|
146
|
+
};
|
|
147
|
+
};
|
|
148
|
+
const makeEngine = () => {
|
|
149
|
+
if (!cfg.router) return null;
|
|
150
|
+
if (!engine) engine = createEngine({ root, env, cfg: engineCfg(), log, push, state: store, since });
|
|
151
|
+
return engine;
|
|
152
|
+
};
|
|
153
|
+
// 执行者用哪个 agent、模型、强度(两个角色各选各的,没单独配的用 YZJ_BOT_*)
|
|
154
|
+
const workerSpec = () => {
|
|
155
|
+
const s = (v) => String(v || '').trim();
|
|
156
|
+
return { agent: s(env.YZJ_WORKER_AGENT) || s(env.YZJ_BOT_AGENT), model: s(env.YZJ_WORKER_MODEL) || cfg.agentModel || s(env.YZJ_BOT_MODEL), effort: s(env.YZJ_WORKER_EFFORT) || cfg.agentEffort || s(env.YZJ_BOT_EFFORT) };
|
|
157
|
+
};
|
|
106
158
|
|
|
107
159
|
// 某一天上不上班:以 work-rhythm today 为准(作息、放假都由它判),同一天只问一次
|
|
108
160
|
const workdayCache = {};
|
|
@@ -167,18 +219,35 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
167
219
|
function loadState() {
|
|
168
220
|
try {
|
|
169
221
|
const state = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
|
|
170
|
-
return
|
|
222
|
+
return state && typeof state === 'object' ? { ...EMPTY_STATE(), ...state } : EMPTY_STATE();
|
|
171
223
|
} catch {
|
|
172
|
-
return
|
|
224
|
+
return EMPTY_STATE();
|
|
173
225
|
}
|
|
174
226
|
}
|
|
175
227
|
|
|
228
|
+
// 写状态文件。命令行里的 listen handle / trigger fire 和服务可能同时写:先读盘上的那份,合起来再写——
|
|
229
|
+
// 触发按短号取并集(内存里的新),done / runs / rounds / history 也取并集,seq 取大的
|
|
176
230
|
function saveState(state) {
|
|
177
231
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
178
232
|
const cutoff = Date.now() - 2 * 24 * 3600 * 1000;
|
|
179
233
|
for (const [key, at] of Object.entries(state.done)) {
|
|
180
234
|
if (new Date(key.split('@')[1]).getTime() < cutoff) delete state.done[key];
|
|
181
235
|
}
|
|
236
|
+
pruneState(state, { historyKeep: cfg.historyKeep });
|
|
237
|
+
try {
|
|
238
|
+
const disk = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
|
|
239
|
+
if (disk && typeof disk === 'object') {
|
|
240
|
+
const union = (a, b, keyOf) => [...a, ...b.filter((x) => !a.some((y) => keyOf(x) === keyOf(y)))];
|
|
241
|
+
state.done = { ...disk.done, ...state.done };
|
|
242
|
+
state.runs = { ...disk.runs, ...state.runs };
|
|
243
|
+
state.triggers = { ...(disk.triggers || {}), ...(state.triggers || {}) };
|
|
244
|
+
state.rounds = union(disk.rounds || [], state.rounds || [], (x) => x.uid || `${x.at}|${x.n}`);
|
|
245
|
+
state.history = union(disk.history || [], state.history || [], (x) => x.uid || `${x.at}|${x.id}|${x.task}`);
|
|
246
|
+
state.seq = Math.max(Number(disk.seq) || 0, Number(state.seq) || 0);
|
|
247
|
+
}
|
|
248
|
+
} catch {
|
|
249
|
+
// 盘上没有或者读不了:就写内存里这份
|
|
250
|
+
}
|
|
182
251
|
writeFileAtomic(STATE_FILE, `${JSON.stringify(state, null, 1)}\n`);
|
|
183
252
|
}
|
|
184
253
|
|
|
@@ -254,13 +323,20 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
254
323
|
}
|
|
255
324
|
const r = await runTask(id, wantPush);
|
|
256
325
|
log('任务', `${id} ${r.ok ? `成功 用时 ${r.seconds}s${r.pushed ? ' 已推送' : ''}` : `失败 ${r.failed}`}`);
|
|
326
|
+
// 监控中心的运行记录:手动跑的也记一笔(没这个任务文件的就不记)
|
|
327
|
+
if (fs.existsSync(path.join(root, 'tasks', `${id}.md`))) {
|
|
328
|
+
const w = workerSpec();
|
|
329
|
+
appendHistory(store.data, { id: '', kind: 'schedule', task: id, decision: 'manual', ok: r.ok, seconds: r.seconds, manual: true, agent: w.agent, model: w.model, effort: w.effort, mode: cfg.agentMode });
|
|
330
|
+
saveState(store.data);
|
|
331
|
+
}
|
|
257
332
|
process.stdout.write(r.ok ? `${r.summary}\n${r.pushed ? '\n(已推送)\n' : ''}` : `没跑成:${r.failed}\n`);
|
|
258
333
|
return r.ok ? EXIT.OK : EXIT.FAILED;
|
|
259
334
|
}
|
|
260
335
|
|
|
261
|
-
// 跑任务的 agent
|
|
336
|
+
// 跑任务的 agent(执行者这个角色):YZJ_WORKER_AGENT,没配用 YZJ_BOT_AGENT;模型和强度先看 YZJ_WORKER_*,再看 profile 的 rhythm.agent-*,最后 YZJ_BOT_*
|
|
262
337
|
function makeAgent() {
|
|
263
|
-
|
|
338
|
+
const w = workerSpec();
|
|
339
|
+
return createAgent({ root, agent: w.agent, mode: cfg.agentMode, timeoutS: cfg.taskTimeout, log, env, model: w.model, effort: w.effort });
|
|
264
340
|
}
|
|
265
341
|
|
|
266
342
|
// 调度器用它:任务另起一个子进程跑(带着 --push),不堵住计时
|
|
@@ -274,14 +350,18 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
274
350
|
}
|
|
275
351
|
|
|
276
352
|
// ---------------------------------------------------------------- 网页服务
|
|
277
|
-
const navHtml = () => NAV.map(([href, label]) =>
|
|
353
|
+
const navHtml = (active = '') => NAV.map(([href, label]) => (
|
|
354
|
+
href === active
|
|
355
|
+
? `<a href="${href}" class="is-active" aria-current="page">${label}</a>`
|
|
356
|
+
: `<a href="${href}">${label}</a>`
|
|
357
|
+
)).join('');
|
|
278
358
|
|
|
279
359
|
function send(res, status, body, type = 'text/html; charset=utf-8') {
|
|
280
360
|
res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
281
361
|
res.end(body);
|
|
282
362
|
}
|
|
283
363
|
|
|
284
|
-
const notFound = (res, what) => send(res, 404, md.page('没有这个页面', `<p class="muted">${md.escapeHtml(what)}</p>`, navHtml()));
|
|
364
|
+
const notFound = (res, what) => send(res, 404, md.page('没有这个页面', `<h1>没有这个页面</h1><p class="muted">${md.escapeHtml(what)}</p>`, navHtml()));
|
|
285
365
|
|
|
286
366
|
function listFiles(dir, filter) {
|
|
287
367
|
try {
|
|
@@ -291,24 +371,37 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
291
371
|
}
|
|
292
372
|
}
|
|
293
373
|
|
|
374
|
+
function listDirs(dir, filter) {
|
|
375
|
+
try {
|
|
376
|
+
return fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory() && filter(d.name)).map((d) => d.name).sort().reverse();
|
|
377
|
+
} catch {
|
|
378
|
+
return [];
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
294
382
|
function dailyDates() {
|
|
295
383
|
const dates = [];
|
|
296
|
-
for (const month of
|
|
384
|
+
for (const month of listDirs(path.join(root, '02-daily'), (n) => /^\d{4}-\d{2}$/.test(n))) {
|
|
297
385
|
for (const f of listFiles(path.join(root, '02-daily', month), (n) => /^\d{4}-\d{2}-\d{2}\.md$/.test(n))) dates.push(f.slice(0, -3));
|
|
298
386
|
}
|
|
299
387
|
return dates.sort().reverse();
|
|
300
388
|
}
|
|
301
389
|
|
|
390
|
+
function weekdayOf(date) {
|
|
391
|
+
const d = new Date(`${date}T12:00:00`);
|
|
392
|
+
return Number.isNaN(d.getTime()) ? '' : WEEKDAY_CN[d.getDay()];
|
|
393
|
+
}
|
|
394
|
+
|
|
302
395
|
// 读到就渲染,读不到就回 404
|
|
303
|
-
function showMarkdown(res, rel, title) {
|
|
396
|
+
function showMarkdown(res, rel, title, active = '') {
|
|
304
397
|
const text = readText(path.join(root, rel));
|
|
305
398
|
if (!text) notFound(res, `${rel} 还没有`);
|
|
306
|
-
else send(res, 200, md.page(title, md.render(text), navHtml()));
|
|
399
|
+
else send(res, 200, md.page(title, md.render(text, view.MD_OPTS), navHtml(active)));
|
|
307
400
|
}
|
|
308
401
|
|
|
309
402
|
function route(req, res) {
|
|
310
403
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
311
|
-
return send(res, 405, md.page('只支持打开页面', '<p class="muted">这个服务只用来查看。</p>', navHtml()));
|
|
404
|
+
return send(res, 405, md.page('只支持打开页面', '<h1>只支持打开页面</h1><p class="muted">这个服务只用来查看。</p>', navHtml()));
|
|
312
405
|
}
|
|
313
406
|
let pathname;
|
|
314
407
|
try {
|
|
@@ -318,24 +411,31 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
318
411
|
}
|
|
319
412
|
const now = fmtDate(new Date());
|
|
320
413
|
if (pathname === '/' || pathname === `/day/${now}`) {
|
|
321
|
-
const
|
|
414
|
+
const dates = dailyDates();
|
|
322
415
|
const text = readText(path.join(root, '02-daily', now.slice(0, 7), `${now}.md`));
|
|
323
|
-
const
|
|
324
|
-
return send(res, 200, md.page(
|
|
416
|
+
const body = view.renderDaily({ date: now, weekday: WEEKDAY_CN[new Date().getDay()], isToday: true, markdown: text, dates });
|
|
417
|
+
return send(res, 200, md.page(`今日 · ${now}`, body, navHtml('/'), { surface: 'plain' }));
|
|
325
418
|
}
|
|
326
419
|
let m = /^\/day\/(\d{4}-\d{2}-\d{2})$/.exec(pathname);
|
|
327
|
-
if (m)
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
420
|
+
if (m) {
|
|
421
|
+
const date = m[1];
|
|
422
|
+
const text = readText(path.join(root, '02-daily', date.slice(0, 7), `${date}.md`));
|
|
423
|
+
if (!text) return notFound(res, `02-daily/${date.slice(0, 7)}/${date}.md 还没有`);
|
|
424
|
+
const body = view.renderDaily({ date, weekday: weekdayOf(date), isToday: false, markdown: text, dates: dailyDates() });
|
|
425
|
+
return send(res, 200, md.page(date, body, navHtml('/'), { surface: 'plain' }));
|
|
426
|
+
}
|
|
427
|
+
if (pathname === '/carryover') return showMarkdown(res, '03-carryover/CARRYOVER.md', '遗留待处理', '/carryover');
|
|
428
|
+
if (pathname === '/decisions') return showMarkdown(res, '03-carryover/DECISIONS.md', '待决与决定', '/decisions');
|
|
429
|
+
if (pathname === '/rhythm') return showMarkdown(res, '04-patterns/WORK_RHYTHM.md', '工作规律', '/rhythm');
|
|
331
430
|
if (pathname === '/goals') {
|
|
332
431
|
const files = listFiles(path.join(root, '05-goals'), (n) => /^[\w-]+\.md$/.test(n));
|
|
333
432
|
if (!files.length) return notFound(res, '还没有进行中的目标');
|
|
334
|
-
|
|
433
|
+
const items = files.map((name) => ({ name, text: readText(path.join(root, '05-goals', name)) }));
|
|
434
|
+
return send(res, 200, md.page('长期目标', view.renderGoals(items), navHtml('/goals'), { surface: 'plain' }));
|
|
335
435
|
}
|
|
336
436
|
if (pathname === '/reports') {
|
|
337
437
|
const files = listFiles(path.join(root, '01-inbox', 'reports'), (n) => /^[\w.-]+\.html$/.test(n));
|
|
338
|
-
return send(res, 200, md.page('报告',
|
|
438
|
+
return send(res, 200, md.page('报告', view.renderReports(files), navHtml('/reports'), { surface: 'plain' }));
|
|
339
439
|
}
|
|
340
440
|
m = /^\/reports\/([\w.-]+\.html)$/.exec(pathname);
|
|
341
441
|
if (m) {
|
|
@@ -343,10 +443,27 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
343
443
|
if (!fs.existsSync(file)) return notFound(res, `没有 ${m[1]}`);
|
|
344
444
|
return send(res, 200, fs.readFileSync(file));
|
|
345
445
|
}
|
|
446
|
+
// 监控中心:同一份数据的页面和 JSON;交接文档只认 t-数字.md 和 t-数字.result.md 两种名字
|
|
447
|
+
if (pathname === '/monitor') return send(res, 200, monitorPage());
|
|
448
|
+
if (pathname === '/status.json') return send(res, 200, `${JSON.stringify(monitorData(), null, 1)}\n`, 'application/json; charset=utf-8');
|
|
449
|
+
m = /^\/handoff\/([^/]+)$/.exec(pathname);
|
|
450
|
+
if (m) {
|
|
451
|
+
const file = path.join(handoff.dir(root), m[1]);
|
|
452
|
+
if (!handoff.NAME_RE.test(m[1]) || !fs.existsSync(file)) return notFound(res, pathname);
|
|
453
|
+
return send(res, 200, md.page(m[1], `${md.render(readText(file), view.MD_OPTS)}<hr><p class="muted">${m[1].endsWith('.result.md') ? '回执' : '任务书'} · <a href="/monitor">监控中心</a></p>`, navHtml('/monitor')));
|
|
454
|
+
}
|
|
346
455
|
return notFound(res, pathname);
|
|
347
456
|
}
|
|
348
457
|
|
|
458
|
+
// 只给本机看:Host 头不是 127.0.0.1 / localhost 的请求一律拒掉,防别的网页借 DNS 重绑定读这个端口
|
|
459
|
+
const localHost = (req) => /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(String(req.headers.host || ''));
|
|
460
|
+
|
|
349
461
|
function handleRequest(req, res) {
|
|
462
|
+
if (!localHost(req)) {
|
|
463
|
+
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8', 'Connection': 'close' });
|
|
464
|
+
res.end('只给本机看:Host 头要是 127.0.0.1 或 localhost\n');
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
350
467
|
try {
|
|
351
468
|
route(req, res);
|
|
352
469
|
} catch (error) {
|
|
@@ -374,12 +491,169 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
374
491
|
return md.page(path.basename(full), md.render(fs.readFileSync(full, 'utf8')), navHtml());
|
|
375
492
|
}
|
|
376
493
|
|
|
377
|
-
//
|
|
378
|
-
|
|
494
|
+
// ---------------------------------------------------------------- 监控中心
|
|
495
|
+
const esc = (v) => md.escapeHtml(String(v === undefined || v === null ? '' : v));
|
|
496
|
+
const fmtDur = (seconds) => {
|
|
497
|
+
const n = Number(seconds) || 0;
|
|
498
|
+
if (n < 60) return `${n} 秒`;
|
|
499
|
+
const m = Math.floor(n / 60);
|
|
500
|
+
return m >= 60 ? `${Math.floor(m / 60)} 小时 ${m % 60} 分` : `${m} 分 ${n % 60} 秒`;
|
|
501
|
+
};
|
|
502
|
+
const table = (head, rows) => `<div class="table-wrap"><table><thead><tr>${head.map((h) => `<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>${rows.map((r) => `<tr>${r.map((c) => `<td>${c}</td>`).join('')}</tr>`).join('') || `<tr><td colspan="${head.length}" class="muted">—</td></tr>`}</tbody></table></div>`;
|
|
503
|
+
const short = (id) => `<code>${esc(id)}</code>`;
|
|
504
|
+
|
|
505
|
+
// 监控中心的数据:页面和 /status.json 是同一份
|
|
506
|
+
function monitorData() {
|
|
507
|
+
const alive = serviceAlive();
|
|
508
|
+
const st = engine ? engine.status() : null;
|
|
509
|
+
const r = roles(env);
|
|
510
|
+
return {
|
|
511
|
+
at: fmtStamp(),
|
|
512
|
+
service: { running: alive, pid: alive ? Number(readText(PID_FILE).trim()) : 0, since: engine ? fmtStamp(new Date(since)) : '', uptimeS: engine ? Math.round((Date.now() - since) / 1000) : 0, port: cfg.port, listen: botWanted(), sync: cfg.sync, push: cfg.push, notifyChannel: cfg.notifyChannel },
|
|
513
|
+
router: st ? st.router : { enabled: cfg.router, agent: r.router.agent, model: r.router.model, effort: r.router.effort, session: null, queue: 0, busy: false, last: null, roundsToday: { total: 0, failed: 0 } },
|
|
514
|
+
workers: st ? st.workers : { limit: cfg.workers, running: [], queued: [] },
|
|
515
|
+
agents: { router: { agent: r.router.agent, model: r.router.model, effort: r.router.effort }, worker: workerSpec() },
|
|
516
|
+
tasks: jobs().filter((j) => j.kind === 'task').map((j) => ({ id: j.id, spec: cfg.schedule[j.id], hasPrompt: j.hasPrompt, problem: j.spec && j.spec.problem ? j.spec.problem : '', next: j.spec && j.spec.problem ? '' : nextRun(j.spec), ...historyStats(store.data, j.id) })),
|
|
517
|
+
triggers: Object.values(store.data.triggers || {}).sort((a, b) => b.at.localeCompare(a.at) || b.id.localeCompare(a.id)).slice(0, 100),
|
|
518
|
+
config: { router: cfg.router, routerTimeout: cfg.routerTimeout, workers: cfg.workers, taskTimeout: cfg.taskTimeout, syncTimeout: cfg.syncTimeout, agentMode: cfg.agentMode, handoffKeep: cfg.handoffKeep, historyKeep: cfg.historyKeep, push: cfg.push, quiet: cfg.quiet, notifyChannel: cfg.notifyChannel },
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// 一个任务下一次什么时候跑(从现在起七天里找)
|
|
523
|
+
function nextRun(spec) {
|
|
524
|
+
if (!spec || spec.problem) return '';
|
|
525
|
+
for (let i = 0; i < 8; i += 1) {
|
|
526
|
+
const d = new Date();
|
|
527
|
+
d.setDate(d.getDate() + i);
|
|
528
|
+
d.setHours(0, 0, 0, 0);
|
|
529
|
+
for (const minute of timesOn(spec, d)) {
|
|
530
|
+
const at = new Date(d);
|
|
531
|
+
at.setHours(Math.floor(minute / 60), minute % 60, 0, 0);
|
|
532
|
+
if (at > new Date()) return i === 0 ? `今天 ${hhmm(at)}` : i === 1 ? `明天 ${hhmm(at)}` : `${WEEKDAY_CN[d.getDay()]} ${hhmm(at)}`;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
return '';
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function monitorPage() {
|
|
539
|
+
const d = monitorData();
|
|
540
|
+
const statusPill = (t) => {
|
|
541
|
+
const s = t.worker.status;
|
|
542
|
+
if (s === 'ok') return `<span class="pill is-green">成功 ${t.worker.seconds} 秒</span>`;
|
|
543
|
+
if (s === 'running') return '<span class="pill is-accent"><span class="dot is-accent"></span>在跑</span>';
|
|
544
|
+
if (s === 'queued') return '<span class="pill">排队中</span>';
|
|
545
|
+
if (s === 'failed') return '<span class="pill is-rose">失败</span>';
|
|
546
|
+
if (s === 'stopped') return '<span class="pill is-amber">叫停</span>';
|
|
547
|
+
return `<span class="pill">${esc(s)}</span>`;
|
|
548
|
+
};
|
|
549
|
+
const workerCell = (t) => {
|
|
550
|
+
if (!t.worker) return '<span class="muted">—</span>';
|
|
551
|
+
const extra = t.worker.status === 'failed' && t.worker.reason ? `<br><span class="muted">${esc(t.worker.reason)}</span>` : '';
|
|
552
|
+
const who = `<span class="muted">${esc(t.worker.agent || '')}${t.worker.mode ? ` · ${esc(t.worker.mode)}` : ''}${t.worker.sessionId ? ` · <code>${esc(t.worker.sessionId.slice(0, 24))}${t.worker.sessionId.length > 24 ? '…' : ''}</code>` : ''}</span>`;
|
|
553
|
+
return `${statusPill(t)}<br>${who}${extra}`;
|
|
554
|
+
};
|
|
555
|
+
const docs = (t) => (fs.existsSync(handoff.taskPath(root, t.id)) ? `<a href="/handoff/${t.id}.md">任务书</a>${fs.existsSync(handoff.resultPath(root, t.id)) ? ` · <a href="/handoff/${t.id}.result.md">回执</a>` : ''}` : '<span class="muted">—</span>');
|
|
556
|
+
const decision = (t) => `<strong>${esc(t.decision || '—')}</strong>${t.reason ? `<br><span class="muted">${esc(t.reason)}</span>` : ''}`;
|
|
557
|
+
const byId = triggersById(store.data);
|
|
558
|
+
const running = d.workers.running.map((w) => {
|
|
559
|
+
const t = byId[w.id];
|
|
560
|
+
const sid = t && t.worker && t.worker.sessionId ? ` <code>${esc(t.worker.sessionId)}</code>` : '';
|
|
561
|
+
return `<li>${short(w.id)} ${esc(w.task || w.kind)} <span class="muted">起于 ${esc(fmtStamp(new Date(w.since)).slice(11))},已 ${esc(fmtDur((Date.now() - w.since) / 1000))}</span>${sid}</li>`;
|
|
562
|
+
}).join('');
|
|
563
|
+
const rs = d.router;
|
|
564
|
+
const session = rs.session ? (rs.session.own ? `专属会话${rs.session.id ? ` <code>${esc(rs.session.id)}</code>` : '(还没开)'}` : `绑定 <code>${esc(rs.session.id)}</code>`) : '—';
|
|
565
|
+
const svcBadge = d.service.running ? `<span class="pill is-green"><span class="dot is-green"></span>在跑 · pid ${d.service.pid}</span>` : '<span class="pill">没在跑</span>';
|
|
566
|
+
const routerBadge = rs.enabled ? (rs.busy ? '<span class="pill is-accent"><span class="dot is-accent"></span>正在想</span>' : '<span class="pill is-green">开着</span>') : '<span class="pill">关着</span>';
|
|
567
|
+
const workerBadge = d.workers.running.length ? `<span class="pill is-accent">在跑 ${d.workers.running.length} / ${d.workers.limit}</span>` : `<span class="pill">空闲 0 / ${d.workers.limit}</span>`;
|
|
568
|
+
const body = `
|
|
569
|
+
<div class="mon-bar">
|
|
570
|
+
<span>更新于 <code>${esc(d.at)}</code></span>
|
|
571
|
+
<div style="display:flex;align-items:center;gap:14px;flex-wrap:wrap">
|
|
572
|
+
<label><input type="checkbox" id="refresh" checked> 每 10 秒自动刷新(前台时)</label>
|
|
573
|
+
<a class="day-btn" href="/status.json">status.json</a>
|
|
574
|
+
</div>
|
|
575
|
+
</div>
|
|
576
|
+
<script>(function(){var b=document.getElementById('refresh');setInterval(function(){if(b.checked&&document.visibilityState==='visible')location.reload()},10000)})();</script>
|
|
577
|
+
<div class="mon-grid">
|
|
578
|
+
<section class="mon-card">
|
|
579
|
+
<h2>服务</h2>
|
|
580
|
+
<p>${svcBadge}${d.service.since ? `<br><span class="muted">起于 ${esc(d.service.since)} · 已 ${esc(fmtDur(d.service.uptimeS))}</span>` : ''}</p>
|
|
581
|
+
<p>值守 ${d.service.listen ? '开着' : '关着'} · 采集 ${esc(d.service.sync || '不定时')}<br>
|
|
582
|
+
推送 ${d.service.push ? `开着(${esc(d.service.notifyChannel || '没配渠道')})` : '关着'} · 端口 <code>${d.service.port}</code></p>
|
|
583
|
+
</section>
|
|
584
|
+
<section class="mon-card">
|
|
585
|
+
<h2>路由</h2>
|
|
586
|
+
<p>${routerBadge}${rs.enabled ? `<br>${session}<br>排队 ${rs.queue} 条 · 今天 ${rs.roundsToday.total} 轮${rs.roundsToday.failed ? `(失败 ${rs.roundsToday.failed})` : ''}${rs.last ? `<br><span class="muted">最近一轮 ${esc(rs.last.at.slice(11))} · ${rs.last.seconds} 秒${rs.last.ok ? '' : ',没出决定'}</span>` : ''}` : '<br><span class="muted">profile 的 rhythm.router 没写:到点直接跑任务,IM 里的话直接答</span>'}</p>
|
|
587
|
+
<p class="muted">agent <code>${esc(d.agents.router.agent || '没绑')}</code>${d.agents.router.model ? ` · ${esc(d.agents.router.model)}` : ''}${d.agents.router.effort ? ` · ${esc(d.agents.router.effort)}` : ''} · plan</p>
|
|
588
|
+
</section>
|
|
589
|
+
<section class="mon-card">
|
|
590
|
+
<h2>执行者</h2>
|
|
591
|
+
<p>${workerBadge}${d.workers.queued.length ? `<br>排队 ${d.workers.queued.map(short).join(' ')}` : ''}</p>
|
|
592
|
+
${running ? `<ul style="margin:6px 0 8px;padding-left:18px;font-size:13px">${running}</ul>` : ''}
|
|
593
|
+
<p class="muted">agent <code>${esc(d.agents.worker.agent || '没绑')}</code>${d.agents.worker.model ? ` · ${esc(d.agents.worker.model)}` : ''}${d.agents.worker.effort ? ` · ${esc(d.agents.worker.effort)}` : ''}</p>
|
|
594
|
+
</section>
|
|
595
|
+
</div>
|
|
596
|
+
<section class="card">
|
|
597
|
+
<div class="card-head"><h2>定时任务 <span class="muted">近 ${d.config.historyKeep} 天</span></h2><span class="pill">${d.tasks.length} 个</span></div>
|
|
598
|
+
${table(['任务', '时间', '下一次', '今天', '成功 / 失败', '最近一次', '平均用时'], d.tasks.map((t) => [
|
|
599
|
+
`<code>${esc(t.id)}</code>${t.hasPrompt ? '' : ' <span class="pill is-amber">缺指令文件</span>'}`,
|
|
600
|
+
esc(t.problem ? `${t.spec}(${t.problem})` : t.spec || '(空)'),
|
|
601
|
+
esc(nextRun(t.problem ? null : parseSpec(t.spec)) || '—'),
|
|
602
|
+
String(t.today),
|
|
603
|
+
`${t.ok} / ${t.failed}`,
|
|
604
|
+
t.last ? `${esc(t.last.at.slice(5, 16))} ${t.last.ok ? '<span class="pill is-green">成功</span>' : '<span class="pill is-rose">失败</span>'}${t.last.manual ? ' <span class="muted">手动</span>' : ''}` : '<span class="muted">—</span>',
|
|
605
|
+
t.avgSeconds ? esc(fmtDur(t.avgSeconds)) : '<span class="muted">—</span>',
|
|
606
|
+
]))}
|
|
607
|
+
</section>
|
|
608
|
+
<section class="card">
|
|
609
|
+
<div class="card-head"><h2>触发 <span class="muted">近两天,新的在前</span></h2><span class="pill">${d.triggers.length} 条</span></div>
|
|
610
|
+
${table(['时间', '短号', '来源', '决定', '执行者', '发了', '文档'], d.triggers.map((t) => [
|
|
611
|
+
esc(t.at.slice(5, 16)),
|
|
612
|
+
short(t.id),
|
|
613
|
+
esc(t.kind === 'schedule' && t.task ? `schedule · ${t.task}` : t.kind) + (t.of && t.kind !== 'report' ? `<br><span class="muted">续做 ${esc(t.of)}</span>` : t.of ? `<br><span class="muted">对应 ${esc(t.of)}</span>` : ''),
|
|
614
|
+
decision(t),
|
|
615
|
+
workerCell(t),
|
|
616
|
+
t.notified ? '<span class="pill is-green">是</span>' : '<span class="muted">—</span>',
|
|
617
|
+
docs(t),
|
|
618
|
+
]))}
|
|
619
|
+
</section>
|
|
620
|
+
<section class="card">
|
|
621
|
+
<div class="card-head"><h2>配置 <span class="muted">只读</span></h2></div>
|
|
622
|
+
<div class="mon-kv">
|
|
623
|
+
<span class="pill">router: ${d.config.router}</span>
|
|
624
|
+
<span class="pill">router-timeout: ${d.config.routerTimeout}s</span>
|
|
625
|
+
<span class="pill">workers: ${d.config.workers}</span>
|
|
626
|
+
<span class="pill">task-timeout: ${d.config.taskTimeout}s</span>
|
|
627
|
+
<span class="pill">agent-mode: ${esc(d.config.agentMode)}</span>
|
|
628
|
+
<span class="pill">handoff-keep: ${d.config.handoffKeep}d</span>
|
|
629
|
+
<span class="pill">history-keep: ${d.config.historyKeep}d</span>
|
|
630
|
+
<span class="pill">push: ${d.config.push}</span>
|
|
631
|
+
<span class="pill">quiet: [${esc(d.config.quiet.join(', '))}]</span>
|
|
632
|
+
</div>
|
|
633
|
+
</section>
|
|
634
|
+
<section class="card mon-log">
|
|
635
|
+
<div class="card-head"><h2>日志 <span class="muted">只记时间和 id,不记消息内容</span></h2></div>
|
|
636
|
+
<h3>01-inbox/_rhythm.log 末 50 行</h3>
|
|
637
|
+
<pre><code>${esc(readText(LOG_FILE).trim().split('\n').slice(-50).join('\n') || '(暂无)')}</code></pre>
|
|
638
|
+
<h3>01-inbox/_bot.log 末 30 行</h3>
|
|
639
|
+
<pre><code>${esc(readText(path.join(root, '01-inbox', '_bot.log')).trim().split('\n').slice(-30).join('\n') || '(暂无)')}</code></pre>
|
|
640
|
+
</section>`;
|
|
641
|
+
return md.page('监控中心', body, navHtml('/monitor'), { wide: true, surface: 'plain' });
|
|
642
|
+
}
|
|
643
|
+
const triggersById = (data) => Object.fromEntries(Object.values(data.triggers || {}).map((t) => [t.id, t]));
|
|
644
|
+
|
|
645
|
+
// 配置和依赖的问题,一条一个字符串。strict 为 false 时不把「缺指令文件的任务」算进去;bot 为 false 时不把值守的配置算进去(起服务时值守配不齐只记一笔,不拦着)
|
|
379
646
|
function doctorProblems({ strict = true, bot = true } = {}) {
|
|
380
647
|
const problems = [];
|
|
381
|
-
//
|
|
382
|
-
|
|
648
|
+
// 已经装成常驻的:plist 里绑的得是真正的 node。从 DSH 这类桌面 agent 里装过的话,绑的是它们的 Electron 包,launchd 拉不起来
|
|
649
|
+
const plist = launchd.plistPath('service', root);
|
|
650
|
+
if (fs.existsSync(plist)) {
|
|
651
|
+
const node = launchd.plistNode(plist);
|
|
652
|
+
if (!node || launchd.looksLikeElectron(node, {})) problems.push(`常驻的 plist 里绑的不是真正的 node(${node || '没读到'}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
653
|
+
else if (!fs.existsSync(node)) problems.push(`常驻的 plist 里绑的 node 不在了(${node}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
654
|
+
}
|
|
655
|
+
// 值守开着的话,它的配置(agent、钥匙串、我的 openId、渠道)也要齐。路由开着时值守用的是路由的 agent
|
|
656
|
+
if (bot && botWanted()) problems.push(...createBot({ root, env, doctorAgent: cfg.router ? routerDoctorProblems : null }).doctorProblems());
|
|
383
657
|
for (const [id, specText] of Object.entries(cfg.schedule)) {
|
|
384
658
|
if (NOT_SERVICE_TASKS.includes(id)) continue;
|
|
385
659
|
const spec = parseSpec(specText);
|
|
@@ -394,9 +668,43 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
394
668
|
problems.push(...makeAgent().doctor());
|
|
395
669
|
if (cfg.push && !cfg.notifyChannel) problems.push('rhythm.push 开着,但 preferences.notify 没配消息渠道:要么配一个,要么把 push 写成 false');
|
|
396
670
|
}
|
|
671
|
+
// 路由和执行者的新键:写了就得是正整数(没写用默认)
|
|
672
|
+
for (const [key, name] of NEW_KEYS) {
|
|
673
|
+
if (cfg.raw[key] !== undefined && !(Number.isInteger(Number(cfg.raw[key])) && Number(cfg.raw[key]) > 0)) problems.push(`${name} 要是正整数(现在是 ${cfg.raw[key]})`);
|
|
674
|
+
}
|
|
675
|
+
// 路由开着时它的 agent 也要配得对(值守开着时 bot 那边查的是同一个)
|
|
676
|
+
if (cfg.router) problems.push(...routerDoctorProblems());
|
|
397
677
|
return problems;
|
|
398
678
|
}
|
|
399
679
|
|
|
680
|
+
// 路由用的 agent 有没有配对
|
|
681
|
+
const routerDoctorProblems = () => {
|
|
682
|
+
const r = roles(env).router;
|
|
683
|
+
return createAgent({ root, agent: r.agent, mode: 'plan', env, model: r.model, effort: r.effort }).doctor();
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
// 命令行里走一遍全流程(work-rhythm listen handle,路由开着时):在命令行的进程里建引擎,这句话变成一条触发,
|
|
687
|
+
// 要发的文字交给 sink(带 push 才真发),等到队列空、执行者都结束。返回 { id, texts } 或者 null(路由没开)
|
|
688
|
+
async function handle(text, { push: really = false, timeoutMs = 600000 } = {}) {
|
|
689
|
+
const eng = makeEngine();
|
|
690
|
+
if (!eng) return null;
|
|
691
|
+
const texts = [];
|
|
692
|
+
if (!really) eng.setSink((t) => texts.push(t));
|
|
693
|
+
const t = eng.enqueue('message', { key: `handle-${Date.now()}`, msgId: 'handle', text, mode: (env.YZJ_BOT_AGENT_MODE || 'plan').trim() });
|
|
694
|
+
await eng.waitIdle(timeoutMs);
|
|
695
|
+
eng.setSink(null);
|
|
696
|
+
return { id: t ? t.id : '', texts };
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// 不算问题、但要让人知道的事(doctor 另起一行列出来,不影响退出码)。mentionOff 为 false 时不提「路由没开」
|
|
700
|
+
function doctorNotes({ mentionOff = true } = {}) {
|
|
701
|
+
if (!cfg.router) return mentionOff ? ['路由没开(profile 的 rhythm.router 没写):到点直接跑任务,IM 里的话直接答;要走「触发 → 路由 → 执行者」写上 rhythm.router: true(docs/router-worker.md)'] : [];
|
|
702
|
+
const r = roles(env).router;
|
|
703
|
+
const notes = createAgent({ root, agent: r.agent, mode: 'plan', env, model: r.model, effort: r.effort }).notes();
|
|
704
|
+
if (cfg.router && !cfg.notifyChannel && cfg.push) notes.push('推送关不掉又没配渠道:路由写给用户的话发不出去,只记日志');
|
|
705
|
+
return notes;
|
|
706
|
+
}
|
|
707
|
+
|
|
400
708
|
// 前台跑:定时采集、定时整理、推送、网页服务。每 tickMs 看一次表(默认 20 秒)。收到 SIGINT / SIGTERM 后退出,返回退出码
|
|
401
709
|
async function start({ tickMs = TICK_MS } = {}) {
|
|
402
710
|
if (serviceAlive()) throw new Fail(EXIT.NOT_CONFIGURED, '服务已经在跑了(work-rhythm rhythm status 看详情)');
|
|
@@ -414,8 +722,15 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
414
722
|
// 配置有问题不拦着服务起,只记一笔——定时任务和网页照常
|
|
415
723
|
let bot = null;
|
|
416
724
|
let botTask = null;
|
|
725
|
+
// 路由开着:引擎在这个进程里跑(触发 → 路由 → 执行者 → 汇报)。上次没跑完的执行者先补失败回执,交回路由
|
|
726
|
+
const eng = makeEngine();
|
|
727
|
+
if (eng) {
|
|
728
|
+
eng.recover();
|
|
729
|
+
eng.tick();
|
|
730
|
+
log('引擎开始', `路由=${roles(env).router.agent} 执行者=${workerSpec().agent} 并发=${cfg.workers}`);
|
|
731
|
+
}
|
|
417
732
|
if (botWanted()) {
|
|
418
|
-
bot = createBot({ root, env });
|
|
733
|
+
bot = createBot({ root, env, onMessage: eng ? (m) => eng.message(m) : null, resetSession: eng ? () => eng.resetSession() : null, doctorAgent: eng ? () => eng.doctorProblems() : null });
|
|
419
734
|
const botProblems = bot.doctorProblems();
|
|
420
735
|
if (botProblems.length) log('值守没开', botProblems.join(';'));
|
|
421
736
|
else {
|
|
@@ -427,7 +742,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
427
742
|
}
|
|
428
743
|
|
|
429
744
|
const list = jobs();
|
|
430
|
-
const state =
|
|
745
|
+
const state = store.data;
|
|
431
746
|
let running = null;
|
|
432
747
|
const queue = [];
|
|
433
748
|
const startNext = () => {
|
|
@@ -436,6 +751,11 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
436
751
|
running = startJob(job);
|
|
437
752
|
running.on('exit', (code) => {
|
|
438
753
|
state.runs[job.id] = { at: fmtStamp(), ok: code === 0, code };
|
|
754
|
+
// 监控中心的运行记录
|
|
755
|
+
if (job.kind === 'task') {
|
|
756
|
+
const w = workerSpec();
|
|
757
|
+
appendHistory(state, { id: '', kind: 'schedule', task: job.id, decision: 'direct', ok: code === 0, manual: false, agent: w.agent, model: w.model, effort: w.effort, mode: cfg.agentMode });
|
|
758
|
+
}
|
|
439
759
|
saveState(state);
|
|
440
760
|
log('跑完', `${job.id} rc=${code}`);
|
|
441
761
|
running = null;
|
|
@@ -443,6 +763,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
443
763
|
});
|
|
444
764
|
};
|
|
445
765
|
const tick = () => {
|
|
766
|
+
if (eng) eng.tick();
|
|
446
767
|
const now = new Date();
|
|
447
768
|
for (const job of list) {
|
|
448
769
|
for (const minute of timesOn(job.spec, now)) {
|
|
@@ -458,6 +779,12 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
458
779
|
continue;
|
|
459
780
|
}
|
|
460
781
|
log('到点', `${job.id} ${hhmm(at)}`);
|
|
782
|
+
if (job.kind === 'task' && eng) {
|
|
783
|
+
// 路由开着:任务变成一条触发交给路由,由它判断再派给执行者
|
|
784
|
+
const body = fs.readFileSync(path.join(root, 'tasks', `${job.id}.md`), 'utf8');
|
|
785
|
+
eng.schedule({ id: job.id, key }, body, taskTitleOf(body));
|
|
786
|
+
continue;
|
|
787
|
+
}
|
|
461
788
|
queue.push(job);
|
|
462
789
|
}
|
|
463
790
|
}
|
|
@@ -476,8 +803,11 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
476
803
|
} catch {
|
|
477
804
|
// 已经没了
|
|
478
805
|
}
|
|
479
|
-
|
|
480
|
-
|
|
806
|
+
// 在跑的执行者是子进程,不收掉会留着:停掉它们(引擎里最多等 3 秒),再关网页
|
|
807
|
+
const close = () => server.close(() => resolve());
|
|
808
|
+
if (eng) eng.shutdown().then(close, close);
|
|
809
|
+
else close();
|
|
810
|
+
setTimeout(resolve, 4500).unref();
|
|
481
811
|
};
|
|
482
812
|
process.on('SIGINT', () => stop('SIGINT'));
|
|
483
813
|
process.on('SIGTERM', () => stop('SIGTERM'));
|
|
@@ -516,6 +846,13 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
516
846
|
const botLog = readText(path.join(root, '01-inbox', '_bot.log')).trim().split('\n');
|
|
517
847
|
const lastBot = botLog.length && botLog[botLog.length - 1] ? botLog[botLog.length - 1] : '';
|
|
518
848
|
lines.push(`值守:${botWanted() ? `开着${lastBot ? `,最近 ${lastBot}` : ''}` : '关着(collectors/local.env 的 YZJ_BOT_LISTEN=1 打开,改完 work-rhythm rhythm restart)'}`);
|
|
849
|
+
const r = roles(env).router;
|
|
850
|
+
const w = workerSpec();
|
|
851
|
+
const rounds = (store.data.rounds || []).filter((x) => x.at.startsWith(fmtDate(new Date()))).length;
|
|
852
|
+
lines.push(`路由:${cfg.router ? `开着(${r.agent || '没绑'}${r.model ? `,模型 ${r.model}` : ''}${r.effort ? `,强度 ${r.effort}` : ''}),今天 ${rounds} 轮;实时的排队和在跑看 ${baseUrl()}/monitor` : '关着(到点直接跑任务,IM 里的话直接答;要开在 profile 的 rhythm 写 router: true)'}`);
|
|
853
|
+
lines.push(`执行者:${w.agent || '没绑'}${w.model ? `,模型 ${w.model}` : ''}${w.effort ? `,强度 ${w.effort}` : ''},同时最多 ${cfg.workers} 个`);
|
|
854
|
+
const triggers = Object.values(store.data.triggers || {}).filter((t) => t.worker && ['queued', 'running'].includes(t.worker.status));
|
|
855
|
+
if (triggers.length) lines.push(`没跑完的:${triggers.map((t) => t.id).join(' ')}(下次启动时补失败回执)`);
|
|
519
856
|
const runs = Object.entries(loadState().runs).sort((a, b) => a[1].at.localeCompare(b[1].at)).slice(-5);
|
|
520
857
|
if (runs.length) lines.push(`最近:${runs.map(([id, r]) => `${id} ${r.at} ${r.ok ? '成功' : `失败(${r.code})`}`).join(';')}`);
|
|
521
858
|
lines.push(`接下来:\n${due(new Date(), 1)}`);
|
|
@@ -526,9 +863,16 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
526
863
|
cfg,
|
|
527
864
|
log,
|
|
528
865
|
stateDir: STATE_DIR,
|
|
866
|
+
store,
|
|
529
867
|
baseUrl,
|
|
530
868
|
serviceAlive,
|
|
531
869
|
due,
|
|
870
|
+
monitorData,
|
|
871
|
+
monitorPage,
|
|
872
|
+
doctorNotes,
|
|
873
|
+
handle,
|
|
874
|
+
makeEngine,
|
|
875
|
+
engine: () => engine,
|
|
532
876
|
render,
|
|
533
877
|
runJob,
|
|
534
878
|
start,
|