work-rhythm 0.1.8 → 0.2.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/notes/AGENTS.md +12 -1
- package/.agents/notes/decisions/2026-12-01-agent-runs-the-login-for-the-user.md +30 -0
- 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-question-cards-via-cli-tool-on-todays-page-answers-return-to-router.md +40 -0
- package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +42 -0
- package/.agents/notes/decisions/2026-12-01-router-runs-on-a-flash-model-with-low-effort.md +33 -0
- package/.agents/notes/decisions/2026-12-01-sync-feeds-refine-then-events-to-the-router.md +38 -0
- package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +16 -0
- package/.agents/notes/pitfalls/2026-12-02-rhythm-start-in-the-foreground-displaces-the-launchd-service.md +27 -0
- package/.agents/skills/work-rhythm/SKILL.md +20 -12
- package/README.md +32 -4
- package/collectors/local.env.example +10 -1
- package/docs/agents.md +53 -13
- package/docs/channels.md +9 -6
- package/docs/router-worker.md +263 -0
- package/docs/scheduled-tasks.md +5 -5
- package/docs/sources.md +20 -0
- package/package.json +1 -1
- package/scripts/cli.js +5 -3
- package/scripts/cmd/agent.js +188 -49
- package/scripts/cmd/ask.js +104 -0
- package/scripts/cmd/check.js +4 -0
- package/scripts/cmd/listen.js +18 -4
- package/scripts/cmd/rhythm.js +6 -2
- package/scripts/cmd/sync.js +11 -3
- package/scripts/cmd/trigger.js +143 -0
- package/scripts/lib/agent.js +482 -30
- package/scripts/lib/asks.js +145 -0
- package/scripts/lib/bot.js +140 -35
- package/scripts/lib/engine.js +707 -0
- package/scripts/lib/handoff.js +167 -0
- package/scripts/lib/markdown.js +355 -36
- package/scripts/lib/rhythm.js +576 -38
- package/scripts/lib/router.js +208 -0
- package/scripts/lib/run.js +43 -0
- package/scripts/lib/view.js +736 -0
- package/scripts/lib/worker.js +98 -0
- package/scripts/test/agent.test.js +126 -9
- package/scripts/test/check.test.js +7 -2
- package/scripts/test/harness.js +15 -1
- package/scripts/test/listen.test.js +2 -2
- package/scripts/test/rhythm.test.js +109 -6
- package/scripts/test/router-helper.js +110 -0
- package/scripts/test/router.test.js +799 -0
- package/scripts/test/stubs.js +113 -12
- package/scripts/test/timeout.test.js +99 -0
- package/tasks/daily-plan.md +1 -2
- package/templates/00-config/profile.example.yaml +9 -0
- package/templates/AGENTS.md +3 -1
- package/templates/README.md +4 -1
package/scripts/lib/rhythm.js
CHANGED
|
@@ -2,24 +2,31 @@
|
|
|
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 {
|
|
14
|
+
const { EXIT, Fail, fmtDate, fmtStamp, pad, tail, readText, writeFileAtomic, seconds } = require('./run');
|
|
15
|
+
const { createHash } = require('node:crypto');
|
|
16
|
+
const { loadProfile, loadSources } = require('./config');
|
|
15
17
|
const { logger } = require('./log');
|
|
16
|
-
const { createAgent } = require('./agent');
|
|
18
|
+
const { createAgent, roles, routerProblems } = require('./agent');
|
|
17
19
|
const { createBot } = require('./bot');
|
|
18
20
|
const { notifyChannel, pushText } = require('./notify');
|
|
21
|
+
const { createEngine, appendHistory, pruneState, historyStats, uid, pendingCards } = require('./engine');
|
|
22
|
+
const handoff = require('./handoff');
|
|
19
23
|
const md = require('./markdown');
|
|
24
|
+
const view = require('./view');
|
|
20
25
|
const launchd = require('./launchd');
|
|
21
26
|
const sync = require('../cmd/sync');
|
|
22
27
|
const today = require('../cmd/today');
|
|
28
|
+
const decisions = require('../cmd/decisions');
|
|
29
|
+
const asks = require('./asks');
|
|
23
30
|
|
|
24
31
|
const TICK_MS = 20000;
|
|
25
32
|
const CATCH_UP_MS = 5 * 60 * 1000;
|
|
@@ -34,13 +41,22 @@ const LINKS = {
|
|
|
34
41
|
'evening-review': { path: (d) => `/day/${d}`, label: '今天的文件' },
|
|
35
42
|
'weekly-rhythm': { path: () => '/rhythm', label: '工作规律' },
|
|
36
43
|
'alerts-morning': { path: (d) => `/reports/${d}-alerts.html`, label: '告警晨报' },
|
|
44
|
+
// 一批新事件之后的「今日重点与待办」:地址给「决定」页(待办卡片在那里点),手机打不开,要在自己电脑上开
|
|
45
|
+
'todos': { path: () => '/#pending-decisions', label: '今日页「待你定」(在自己电脑的浏览器里打开)' },
|
|
37
46
|
};
|
|
38
|
-
const NAV = [['/', '今日'], ['/carryover', '遗留'], ['/decisions', '决定'], ['/rhythm', '规律'], ['/goals', '目标'], ['/reports', '报告']];
|
|
47
|
+
const NAV = [['/', '今日'], ['/carryover', '遗留'], ['/decisions', '决定'], ['/rhythm', '规律'], ['/goals', '目标'], ['/reports', '报告'], ['/monitor', '监控']];
|
|
48
|
+
const NEW_KEYS = [['workers', 'rhythm.workers'], ['router-timeout', 'rhythm.router-timeout'], ['handoff-keep', 'rhythm.handoff-keep'], ['history-keep', 'rhythm.history-keep']];
|
|
49
|
+
// 状态文件的骨架:done(跑过的任务)、runs(各任务最近一次)、seq(触发短号的序号)、triggers(近两天的触发)、history(运行记录)、rounds(路由的轮数)
|
|
50
|
+
const EMPTY_STATE = () => ({ done: {}, runs: {}, seq: 0, triggers: {}, history: [], rounds: [], sources: {}, refinedAt: '', syncDigest: { date: '', digest: '' } });
|
|
39
51
|
|
|
40
52
|
const positiveInt = (value, fallback) => {
|
|
41
53
|
const n = Number(value);
|
|
42
54
|
return Number.isInteger(n) && n > 0 ? n : fallback;
|
|
43
|
-
}
|
|
55
|
+
};// 任务指令开头「任务:每日工作计划。」那一行当它的标题
|
|
56
|
+
function taskTitleOf(body) {
|
|
57
|
+
const m = /^任务[::]\s*(.+)$/m.exec(String(body || ''));
|
|
58
|
+
return m ? m[1].trim().replace(/[。.]\s*$/, '') : '';
|
|
59
|
+
}
|
|
44
60
|
const hhmm = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
45
61
|
const asList = (value) => (Array.isArray(value) ? value.map((v) => String(v).trim()).filter(Boolean) : []);
|
|
46
62
|
|
|
@@ -63,6 +79,16 @@ function loadConfig(root) {
|
|
|
63
79
|
syncTimeout: positiveInt(rhythm['sync-timeout'], 600),
|
|
64
80
|
notifyChannel: typeof preferences.notify === 'string' ? preferences.notify.trim() : '',
|
|
65
81
|
schedule,
|
|
82
|
+
// 路由和执行者(docs/router-worker.md)。router 没写就是直通(老做法)
|
|
83
|
+
router: rhythm.router === true,
|
|
84
|
+
routerTimeout: positiveInt(rhythm['router-timeout'], 120),
|
|
85
|
+
workers: positiveInt(rhythm.workers, 3),
|
|
86
|
+
// 定时采集之后:有新数据就起一轮提炼(把 01-inbox 的新数据炼成事件、新增的打包给路由)。两轮提炼之间至少隔 refine-interval 分钟
|
|
87
|
+
refine: rhythm.refine !== false,
|
|
88
|
+
refineInterval: positiveInt(rhythm['refine-interval'], 120),
|
|
89
|
+
handoffKeep: positiveInt(rhythm['handoff-keep'], 14),
|
|
90
|
+
historyKeep: positiveInt(rhythm['history-keep'], 90),
|
|
91
|
+
raw: rhythm,
|
|
66
92
|
};
|
|
67
93
|
}
|
|
68
94
|
|
|
@@ -103,6 +129,40 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
103
129
|
const log = logger(LOG_FILE);
|
|
104
130
|
const cfg = loadConfig(root);
|
|
105
131
|
const baseUrl = () => `http://127.0.0.1:${cfg.port}`;
|
|
132
|
+
// 这个对象是哪天起的(监控中心的「已跑多久」)
|
|
133
|
+
const since = Date.now();
|
|
134
|
+
// 状态(engine.js 也往里写):同一个进程里只有这一份
|
|
135
|
+
const store = { data: loadState(), save() { saveState(store.data); } };
|
|
136
|
+
// 引擎(路由 + 执行者):profile 的 rhythm.router 为 true 时才有,同一个进程里只建一个
|
|
137
|
+
let engine = null;
|
|
138
|
+
const engineCfg = () => {
|
|
139
|
+
const idle = seconds(env.YZJ_BOT_IDLE, 180);
|
|
140
|
+
return {
|
|
141
|
+
...cfg,
|
|
142
|
+
ack: env.YZJ_BOT_ACK !== '0',
|
|
143
|
+
botMode: (env.YZJ_BOT_AGENT_MODE || 'plan').trim(),
|
|
144
|
+
botTimeout: positiveInt(env.YZJ_BOT_TIMEOUT, 900),
|
|
145
|
+
// 执行者可能长时间不出声(跑构建、跑测试),静默闸给得比值守宽;硬上限还是 task-timeout。0 表示关掉
|
|
146
|
+
workerIdle: idle === 0 ? 0 : Math.max(600, idle),
|
|
147
|
+
progress: seconds(env.YZJ_BOT_PROGRESS, 90),
|
|
148
|
+
progressMax: positiveInt(env.YZJ_BOT_PROGRESS_MAX, 3),
|
|
149
|
+
replyMax: positiveInt(env.YZJ_BOT_REPLY_MAX, 2000),
|
|
150
|
+
botPreamble: (env.YZJ_BOT_PREAMBLE || '').trim(),
|
|
151
|
+
links: LINKS,
|
|
152
|
+
baseUrl: baseUrl(),
|
|
153
|
+
serviceAlive,
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
const makeEngine = () => {
|
|
157
|
+
if (!cfg.router) return null;
|
|
158
|
+
if (!engine) engine = createEngine({ root, env, cfg: engineCfg(), log, push, state: store, since });
|
|
159
|
+
return engine;
|
|
160
|
+
};
|
|
161
|
+
// 执行者用哪个 agent、模型、强度(两个角色各选各的,没单独配的用 YZJ_BOT_*)
|
|
162
|
+
const workerSpec = () => {
|
|
163
|
+
const s = (v) => String(v || '').trim();
|
|
164
|
+
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) };
|
|
165
|
+
};
|
|
106
166
|
|
|
107
167
|
// 某一天上不上班:以 work-rhythm today 为准(作息、放假都由它判),同一天只问一次
|
|
108
168
|
const workdayCache = {};
|
|
@@ -167,18 +227,35 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
167
227
|
function loadState() {
|
|
168
228
|
try {
|
|
169
229
|
const state = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
|
|
170
|
-
return
|
|
230
|
+
return state && typeof state === 'object' ? { ...EMPTY_STATE(), ...state } : EMPTY_STATE();
|
|
171
231
|
} catch {
|
|
172
|
-
return
|
|
232
|
+
return EMPTY_STATE();
|
|
173
233
|
}
|
|
174
234
|
}
|
|
175
235
|
|
|
236
|
+
// 写状态文件。命令行里的 listen handle / trigger fire 和服务可能同时写:先读盘上的那份,合起来再写——
|
|
237
|
+
// 触发按短号取并集(内存里的新),done / runs / rounds / history 也取并集,seq 取大的
|
|
176
238
|
function saveState(state) {
|
|
177
239
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
178
240
|
const cutoff = Date.now() - 2 * 24 * 3600 * 1000;
|
|
179
241
|
for (const [key, at] of Object.entries(state.done)) {
|
|
180
242
|
if (new Date(key.split('@')[1]).getTime() < cutoff) delete state.done[key];
|
|
181
243
|
}
|
|
244
|
+
pruneState(state, { historyKeep: cfg.historyKeep });
|
|
245
|
+
try {
|
|
246
|
+
const disk = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
|
|
247
|
+
if (disk && typeof disk === 'object') {
|
|
248
|
+
const union = (a, b, keyOf) => [...a, ...b.filter((x) => !a.some((y) => keyOf(x) === keyOf(y)))];
|
|
249
|
+
state.done = { ...disk.done, ...state.done };
|
|
250
|
+
state.runs = { ...disk.runs, ...state.runs };
|
|
251
|
+
state.triggers = { ...(disk.triggers || {}), ...(state.triggers || {}) };
|
|
252
|
+
state.rounds = union(disk.rounds || [], state.rounds || [], (x) => x.uid || `${x.at}|${x.n}`);
|
|
253
|
+
state.history = union(disk.history || [], state.history || [], (x) => x.uid || `${x.at}|${x.id}|${x.task}`);
|
|
254
|
+
state.seq = Math.max(Number(disk.seq) || 0, Number(state.seq) || 0);
|
|
255
|
+
}
|
|
256
|
+
} catch {
|
|
257
|
+
// 盘上没有或者读不了:就写内存里这份
|
|
258
|
+
}
|
|
182
259
|
writeFileAtomic(STATE_FILE, `${JSON.stringify(state, null, 1)}\n`);
|
|
183
260
|
}
|
|
184
261
|
|
|
@@ -195,15 +272,79 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
195
272
|
|
|
196
273
|
// ---------------------------------------------------------------- 采集、任务、推送
|
|
197
274
|
// 跑一遍 sync(在同一个进程里),最多等 cfg.syncTimeout 秒
|
|
275
|
+
const todayStr = () => fmtDate(new Date());
|
|
276
|
+
|
|
277
|
+
// 今天 01-inbox/<源>/<日期>/ 下所有文件的名字和内容搓成的指纹:采集之后跟上次比,不一样就是有新数据(采集器每次都重写文件,所以不按修改时间算)
|
|
278
|
+
function inboxDigest(date) {
|
|
279
|
+
const base = path.join(root, '01-inbox');
|
|
280
|
+
const h = createHash('sha1');
|
|
281
|
+
let names;
|
|
282
|
+
try {
|
|
283
|
+
names = fs.readdirSync(base).sort();
|
|
284
|
+
} catch {
|
|
285
|
+
return '';
|
|
286
|
+
}
|
|
287
|
+
for (const id of names) {
|
|
288
|
+
const dir = path.join(base, id, date);
|
|
289
|
+
let files;
|
|
290
|
+
try {
|
|
291
|
+
if (!fs.statSync(dir).isDirectory()) continue;
|
|
292
|
+
files = fs.readdirSync(dir).sort();
|
|
293
|
+
} catch {
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
for (const name of files) {
|
|
297
|
+
const file = path.join(dir, name);
|
|
298
|
+
if (!fs.statSync(file).isFile()) continue;
|
|
299
|
+
h.update(`${id}/${name}\n`);
|
|
300
|
+
h.update(fs.readFileSync(file));
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return h.digest('hex');
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// 每个源的运行状态记进 state.json:最近一次成败、用时、原因,连着失败几次,上次成功是什么时候
|
|
307
|
+
function recordSources(results) {
|
|
308
|
+
for (const r of results) {
|
|
309
|
+
const prev = store.data.sources[r.id] || {};
|
|
310
|
+
store.data.sources[r.id] = { at: fmtStamp(), ok: Boolean(r.ok), code: r.code || 0, seconds: r.seconds || 0, detail: tail(r.detail || '', 200), fails: r.ok ? 0 : (prev.fails || 0) + 1, lastOk: r.ok ? fmtStamp() : prev.lastOk || '' };
|
|
311
|
+
}
|
|
312
|
+
if (results.length) saveState(store.data);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// 启用的源 + 它们的运行状态(监控中心、doctor 用)。缺脚本的也标出来
|
|
316
|
+
function sourceStatus() {
|
|
317
|
+
return loadSources(root).map((src) => {
|
|
318
|
+
const collector = src.collector === 'none' ? '' : src.collector;
|
|
319
|
+
const missing = Boolean(src.enabled && collector && !sync.resolveCollector(root, packageRoot, collector));
|
|
320
|
+
return { id: src.id, name: src.name || '', signal: src.signal || '', enabled: src.enabled, collector: src.collector || '', missing, last: store.data.sources[src.id] || null };
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
|
|
198
324
|
async function runSync() {
|
|
199
325
|
const t0 = Date.now();
|
|
200
326
|
const chunks = [];
|
|
201
327
|
const capture = { write: (s) => (chunks.push(String(s)), true) };
|
|
202
|
-
const
|
|
328
|
+
const results = [];
|
|
329
|
+
const fail = await sync.run([], { root, cwd: root, env, stdout: capture, stderr: capture, packageRoot }, { deadlineMs: t0 + cfg.syncTimeout * 1000, results });
|
|
203
330
|
const seconds = Math.round((Date.now() - t0) / 1000);
|
|
331
|
+
recordSources(results);
|
|
332
|
+
// 有没有新数据:今天的指纹跟上一次比。没有文件也算一种指纹(空串),和上次不一样才是有新数据
|
|
333
|
+
const digest = inboxDigest(todayStr());
|
|
334
|
+
const prev = store.data.syncDigest || {};
|
|
335
|
+
const changed = Boolean(digest) && digest !== prev.digest;
|
|
336
|
+
store.data.syncDigest = { date: todayStr(), digest, at: fmtStamp() };
|
|
337
|
+
saveState(store.data);
|
|
338
|
+
// 留给服务的那个进程:它起提炼、把新事件打包给路由
|
|
339
|
+
try {
|
|
340
|
+
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
341
|
+
fs.writeFileSync(path.join(STATE_DIR, 'last-sync.json'), `${JSON.stringify({ at: fmtStamp(), ok: !fail, seconds, results, changed }, null, 1)}\n`);
|
|
342
|
+
} catch {
|
|
343
|
+
// 写不下就算了:服务那边没有它就不提炼
|
|
344
|
+
}
|
|
204
345
|
const out = chunks.join('');
|
|
205
|
-
if (fail) return { ok: false, failed: `退出码 ${fail}:${tail(out, 300)}`, seconds };
|
|
206
|
-
return { ok: true, seconds, detail: tail(chunks.join(''), 300).replace(/\n/g, ' · ') };
|
|
346
|
+
if (fail) return { ok: false, failed: `退出码 ${fail}:${tail(out, 300)}`, seconds, results, changed };
|
|
347
|
+
return { ok: true, seconds, detail: tail(chunks.join(''), 300).replace(/\n/g, ' · '), results, changed };
|
|
207
348
|
}
|
|
208
349
|
|
|
209
350
|
// 经消息渠道发一段文字。渠道留空时什么都不发(不算失败);发不出去记日志
|
|
@@ -254,13 +395,20 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
254
395
|
}
|
|
255
396
|
const r = await runTask(id, wantPush);
|
|
256
397
|
log('任务', `${id} ${r.ok ? `成功 用时 ${r.seconds}s${r.pushed ? ' 已推送' : ''}` : `失败 ${r.failed}`}`);
|
|
398
|
+
// 监控中心的运行记录:手动跑的也记一笔(没这个任务文件的就不记)
|
|
399
|
+
if (fs.existsSync(path.join(root, 'tasks', `${id}.md`))) {
|
|
400
|
+
const w = workerSpec();
|
|
401
|
+
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 });
|
|
402
|
+
saveState(store.data);
|
|
403
|
+
}
|
|
257
404
|
process.stdout.write(r.ok ? `${r.summary}\n${r.pushed ? '\n(已推送)\n' : ''}` : `没跑成:${r.failed}\n`);
|
|
258
405
|
return r.ok ? EXIT.OK : EXIT.FAILED;
|
|
259
406
|
}
|
|
260
407
|
|
|
261
|
-
// 跑任务的 agent
|
|
408
|
+
// 跑任务的 agent(执行者这个角色):YZJ_WORKER_AGENT,没配用 YZJ_BOT_AGENT;模型和强度先看 YZJ_WORKER_*,再看 profile 的 rhythm.agent-*,最后 YZJ_BOT_*
|
|
262
409
|
function makeAgent() {
|
|
263
|
-
|
|
410
|
+
const w = workerSpec();
|
|
411
|
+
return createAgent({ root, agent: w.agent, mode: cfg.agentMode, timeoutS: cfg.taskTimeout, log, env, model: w.model, effort: w.effort });
|
|
264
412
|
}
|
|
265
413
|
|
|
266
414
|
// 调度器用它:任务另起一个子进程跑(带着 --push),不堵住计时
|
|
@@ -274,14 +422,18 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
274
422
|
}
|
|
275
423
|
|
|
276
424
|
// ---------------------------------------------------------------- 网页服务
|
|
277
|
-
const navHtml = () => NAV.map(([href, label]) =>
|
|
425
|
+
const navHtml = (active = '') => NAV.map(([href, label]) => (
|
|
426
|
+
href === active
|
|
427
|
+
? `<a href="${href}" class="is-active" aria-current="page">${label}</a>`
|
|
428
|
+
: `<a href="${href}">${label}</a>`
|
|
429
|
+
)).join('');
|
|
278
430
|
|
|
279
431
|
function send(res, status, body, type = 'text/html; charset=utf-8') {
|
|
280
432
|
res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
281
433
|
res.end(body);
|
|
282
434
|
}
|
|
283
435
|
|
|
284
|
-
const notFound = (res, what) => send(res, 404, md.page('没有这个页面',
|
|
436
|
+
const notFound = (res, what) => send(res, 404, md.page('没有这个页面', view.renderDocPage('没有这个页面', '', { empty: what || '这个地址没有对应的页面。' }), navHtml()));
|
|
285
437
|
|
|
286
438
|
function listFiles(dir, filter) {
|
|
287
439
|
try {
|
|
@@ -291,24 +443,39 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
291
443
|
}
|
|
292
444
|
}
|
|
293
445
|
|
|
446
|
+
function listDirs(dir, filter) {
|
|
447
|
+
try {
|
|
448
|
+
return fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory() && filter(d.name)).map((d) => d.name).sort().reverse();
|
|
449
|
+
} catch {
|
|
450
|
+
return [];
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
294
454
|
function dailyDates() {
|
|
295
455
|
const dates = [];
|
|
296
|
-
for (const month of
|
|
456
|
+
for (const month of listDirs(path.join(root, '02-daily'), (n) => /^\d{4}-\d{2}$/.test(n))) {
|
|
297
457
|
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
458
|
}
|
|
299
459
|
return dates.sort().reverse();
|
|
300
460
|
}
|
|
301
461
|
|
|
302
|
-
|
|
303
|
-
|
|
462
|
+
function weekdayOf(date) {
|
|
463
|
+
const d = new Date(`${date}T12:00:00`);
|
|
464
|
+
return Number.isNaN(d.getTime()) ? '' : WEEKDAY_CN[d.getDay()];
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// 读到就渲染,读不到就回 404(所有业务页统一走 plain + stack + card 骨架)
|
|
468
|
+
function showMarkdown(res, rel, title, active = '') {
|
|
304
469
|
const text = readText(path.join(root, rel));
|
|
305
470
|
if (!text) notFound(res, `${rel} 还没有`);
|
|
306
|
-
else send(res, 200, md.page(title,
|
|
471
|
+
else send(res, 200, md.page(title, view.renderDocPage(title, text, { subtitle: rel }), navHtml(active)));
|
|
307
472
|
}
|
|
308
473
|
|
|
309
474
|
function route(req, res) {
|
|
475
|
+
// 唯一的写接口:本机今日页「待你定」卡片的回答
|
|
476
|
+
if (req.method === 'POST' && /^\/api\/asks\/answer$/.test(String(req.url || '').split('?')[0])) return answerOnPage(req, res);
|
|
310
477
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
311
|
-
return send(res, 405, md.page('只支持打开页面', '
|
|
478
|
+
return send(res, 405, md.page('只支持打开页面', view.renderDocPage('只支持打开页面', '', { empty: '这个服务只看记录;唯一能写的是今日页「待你定」卡片的回答。' }), navHtml()));
|
|
312
479
|
}
|
|
313
480
|
let pathname;
|
|
314
481
|
try {
|
|
@@ -318,24 +485,40 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
318
485
|
}
|
|
319
486
|
const now = fmtDate(new Date());
|
|
320
487
|
if (pathname === '/' || pathname === `/day/${now}`) {
|
|
321
|
-
const
|
|
488
|
+
const dates = dailyDates();
|
|
322
489
|
const text = readText(path.join(root, '02-daily', now.slice(0, 7), `${now}.md`));
|
|
323
|
-
const
|
|
324
|
-
|
|
490
|
+
const cards = asks.cardsForPage(root, pendingCards);
|
|
491
|
+
const body = view.renderDaily({ date: now, weekday: WEEKDAY_CN[new Date().getDay()], isToday: true, markdown: text, dates, asks: cards, token: webToken() });
|
|
492
|
+
return send(res, 200, md.page(`今日 · ${now}`, body, navHtml('/')));
|
|
493
|
+
}
|
|
494
|
+
if (pathname === '/asks.html') {
|
|
495
|
+
const cards = asks.cardsForPage(root, pendingCards);
|
|
496
|
+
return send(res, 200, view.renderAsksFragment(cards), 'text/html; charset=utf-8');
|
|
497
|
+
}
|
|
498
|
+
if (pathname === '/asks.json') {
|
|
499
|
+
const cards = asks.cardsForPage(root, pendingCards);
|
|
500
|
+
return send(res, 200, `${JSON.stringify(cards, null, 1)}\n`, 'application/json; charset=utf-8');
|
|
325
501
|
}
|
|
326
502
|
let m = /^\/day\/(\d{4}-\d{2}-\d{2})$/.exec(pathname);
|
|
327
|
-
if (m)
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
503
|
+
if (m) {
|
|
504
|
+
const date = m[1];
|
|
505
|
+
const text = readText(path.join(root, '02-daily', date.slice(0, 7), `${date}.md`));
|
|
506
|
+
if (!text) return notFound(res, `02-daily/${date.slice(0, 7)}/${date}.md 还没有`);
|
|
507
|
+
const body = view.renderDaily({ date, weekday: weekdayOf(date), isToday: false, markdown: text, dates: dailyDates() });
|
|
508
|
+
return send(res, 200, md.page(date, body, navHtml('/')));
|
|
509
|
+
}
|
|
510
|
+
if (pathname === '/carryover') return showMarkdown(res, '03-carryover/CARRYOVER.md', '遗留待处理', '/carryover');
|
|
511
|
+
if (pathname === '/decisions') return showMarkdown(res, '03-carryover/DECISIONS.md', '待决与决定', '/decisions');
|
|
512
|
+
if (pathname === '/rhythm') return showMarkdown(res, '04-patterns/WORK_RHYTHM.md', '工作规律', '/rhythm');
|
|
331
513
|
if (pathname === '/goals') {
|
|
332
514
|
const files = listFiles(path.join(root, '05-goals'), (n) => /^[\w-]+\.md$/.test(n));
|
|
333
515
|
if (!files.length) return notFound(res, '还没有进行中的目标');
|
|
334
|
-
|
|
516
|
+
const items = files.map((name) => ({ name, text: readText(path.join(root, '05-goals', name)) }));
|
|
517
|
+
return send(res, 200, md.page('长期目标', view.renderGoals(items), navHtml('/goals')));
|
|
335
518
|
}
|
|
336
519
|
if (pathname === '/reports') {
|
|
337
520
|
const files = listFiles(path.join(root, '01-inbox', 'reports'), (n) => /^[\w.-]+\.html$/.test(n));
|
|
338
|
-
return send(res, 200, md.page('报告',
|
|
521
|
+
return send(res, 200, md.page('报告', view.renderReports(files), navHtml('/reports')));
|
|
339
522
|
}
|
|
340
523
|
m = /^\/reports\/([\w.-]+\.html)$/.exec(pathname);
|
|
341
524
|
if (m) {
|
|
@@ -343,23 +526,103 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
343
526
|
if (!fs.existsSync(file)) return notFound(res, `没有 ${m[1]}`);
|
|
344
527
|
return send(res, 200, fs.readFileSync(file));
|
|
345
528
|
}
|
|
529
|
+
// 监控中心:同一份数据的页面和 JSON;交接文档只认 t-数字.md 和 t-数字.result.md 两种名字
|
|
530
|
+
if (pathname === '/monitor') return send(res, 200, monitorPage());
|
|
531
|
+
if (pathname === '/status.json') return send(res, 200, `${JSON.stringify(monitorData(), null, 1)}\n`, 'application/json; charset=utf-8');
|
|
532
|
+
m = /^\/handoff\/([^/]+)$/.exec(pathname);
|
|
533
|
+
if (m) {
|
|
534
|
+
const file = path.join(handoff.dir(root), m[1]);
|
|
535
|
+
if (!handoff.NAME_RE.test(m[1]) || !fs.existsSync(file)) return notFound(res, pathname);
|
|
536
|
+
return send(res, 200, md.page(m[1], view.renderDocPage(m[1].endsWith('.result.md') ? '回执' : '任务书', readText(file), { subtitle: `${handoff.DIR}/${m[1]}`, meta: '<a class="day-btn" href="/monitor">← 监控中心</a>' }), navHtml('/monitor')));
|
|
537
|
+
}
|
|
346
538
|
return notFound(res, pathname);
|
|
347
539
|
}
|
|
348
540
|
|
|
541
|
+
// 只给本机看:Host 头不是 127.0.0.1 / localhost 的请求一律拒掉,防别的网页借 DNS 重绑定读这个端口
|
|
542
|
+
const localHost = (req) => /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(String(req.headers.host || ''));
|
|
543
|
+
|
|
349
544
|
function handleRequest(req, res) {
|
|
545
|
+
if (!localHost(req)) {
|
|
546
|
+
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8', 'Connection': 'close' });
|
|
547
|
+
res.end('只给本机看:Host 头要是 127.0.0.1 或 localhost\n');
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
350
550
|
try {
|
|
351
551
|
route(req, res);
|
|
352
552
|
} catch (error) {
|
|
353
553
|
// 单个请求出错不能把服务带崩
|
|
354
554
|
log('页面出错', `${req.url} ${error.message}`);
|
|
355
555
|
try {
|
|
356
|
-
send(res, 500, md.page('页面出错了',
|
|
556
|
+
send(res, 500, md.page('页面出错了', view.renderDocPage('页面出错了', '', { empty: String(error.message) }), navHtml()));
|
|
357
557
|
} catch {
|
|
358
558
|
// 连响应都发不出去就算了
|
|
359
559
|
}
|
|
360
560
|
}
|
|
361
561
|
}
|
|
362
562
|
|
|
563
|
+
// ---------------------------------------------------------------- 「决定」页上的待办卡片:能点的
|
|
564
|
+
// 网页服务开一个写接口(点选项 = 我的决定),靠两道闸防别的网页乱点:Host 头必须是本机(防 DNS 重绑定,上面),
|
|
565
|
+
// 外加一个只在本机页面里的令牌:随机串存在 01-inbox/_rhythm/web-token,页面脚本带着它,接口只认带对的。
|
|
566
|
+
// 别的网站的页面读不到 127.0.0.1 上的这个页面(同源策略),拿不到令牌,就用图片、表单点不动
|
|
567
|
+
function webToken() {
|
|
568
|
+
const file = path.join(STATE_DIR, 'web-token');
|
|
569
|
+
try {
|
|
570
|
+
const found = readText(file).trim();
|
|
571
|
+
if (/^[0-9a-f]{32}$/.test(found)) return found;
|
|
572
|
+
} catch {
|
|
573
|
+
// 还没有,下面建一个
|
|
574
|
+
}
|
|
575
|
+
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
576
|
+
const token = createHash('sha256').update(`${Date.now()}:${Math.random()}:${process.pid}`).digest('hex').slice(0, 32);
|
|
577
|
+
fs.writeFileSync(file, `${token}\n`, { mode: 0o600 });
|
|
578
|
+
return token;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// 今日页「待你定」卡片的回答:记下答案、更新 DECISIONS.md,并作为一条 answer 触发交给路由
|
|
582
|
+
async function answerOnPage(req, res) {
|
|
583
|
+
if (String(req.headers['x-wrj-token'] || '') !== webToken()) return send(res, 403, JSON.stringify({ error: '令牌不对:这个接口只给本机页面用' }), 'application/json; charset=utf-8');
|
|
584
|
+
const body = await new Promise((resolve) => {
|
|
585
|
+
let data = '';
|
|
586
|
+
req.on('data', (c) => {
|
|
587
|
+
data += c;
|
|
588
|
+
if (data.length > 64 * 1024) req.destroy();
|
|
589
|
+
});
|
|
590
|
+
req.on('end', () => resolve(data));
|
|
591
|
+
req.on('error', () => resolve(''));
|
|
592
|
+
});
|
|
593
|
+
let parsed;
|
|
594
|
+
try {
|
|
595
|
+
parsed = JSON.parse(body || '{}');
|
|
596
|
+
} catch {
|
|
597
|
+
return send(res, 400, JSON.stringify({ error: '请求体不是 JSON' }), 'application/json; charset=utf-8');
|
|
598
|
+
}
|
|
599
|
+
const id = String(parsed.id || '').trim();
|
|
600
|
+
const item = String(parsed.item || '').trim();
|
|
601
|
+
const choice = String(parsed.choice || '').trim();
|
|
602
|
+
const note = String(parsed.note || '').trim();
|
|
603
|
+
if (!choice || (!id && !item)) return send(res, 400, JSON.stringify({ error: '要写回答和卡片标识' }), 'application/json; charset=utf-8');
|
|
604
|
+
let ask;
|
|
605
|
+
if (id) {
|
|
606
|
+
try {
|
|
607
|
+
ask = await asks.answerAsk(root, id, { choice, note, by: 'page' }, { env, packageRoot, decisions });
|
|
608
|
+
} catch (e) {
|
|
609
|
+
return send(res, 409, JSON.stringify({ error: e.message || String(e) }), 'application/json; charset=utf-8');
|
|
610
|
+
}
|
|
611
|
+
} else {
|
|
612
|
+
const err = [];
|
|
613
|
+
const code = await decisions.run(['answer', item, choice], { root, cwd: root, env, packageRoot, stdout: { write() {} }, stderr: { write: (x) => err.push(String(x)) } });
|
|
614
|
+
if (code !== 0) return send(res, 409, JSON.stringify({ error: tail(err.join(''), 300) || `decisions answer 退出码 ${code}` }), 'application/json; charset=utf-8');
|
|
615
|
+
ask = { id: '', item, question: item, context: '', options: [], record: '03-carryover/DECISIONS.md', from: {}, answer: { choice, note, at: fmtStamp(), by: 'page' } };
|
|
616
|
+
}
|
|
617
|
+
let dispatched = false;
|
|
618
|
+
const eng = engine || makeEngine();
|
|
619
|
+
if (eng) {
|
|
620
|
+
eng.answer(ask);
|
|
621
|
+
dispatched = true;
|
|
622
|
+
}
|
|
623
|
+
return send(res, 200, JSON.stringify({ ok: true, id: ask.id, item: ask.item, choice, dispatched, message: dispatched ? '已记下,已交给路由继续处理。' : '已记下(路由未开启,仅记录)。' }), 'application/json; charset=utf-8');
|
|
624
|
+
}
|
|
625
|
+
|
|
363
626
|
// 只绑 127.0.0.1:页面带着工作记录,不给别的机器看
|
|
364
627
|
const listen = (port) => new Promise((resolve, reject) => {
|
|
365
628
|
const server = http.createServer(handleRequest);
|
|
@@ -371,9 +634,188 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
371
634
|
function render(file) {
|
|
372
635
|
const full = path.resolve(root, file);
|
|
373
636
|
if (!fs.existsSync(full)) throw new Fail(EXIT.USAGE, `没有这个文件:${file}`);
|
|
374
|
-
return md.page(path.basename(full),
|
|
637
|
+
return md.page(path.basename(full), view.renderDocPage(path.basename(full), fs.readFileSync(full, 'utf8')), navHtml());
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
// ---------------------------------------------------------------- 监控中心
|
|
641
|
+
const esc = (v) => md.escapeHtml(String(v === undefined || v === null ? '' : v));
|
|
642
|
+
const fmtDur = (seconds) => {
|
|
643
|
+
const n = Number(seconds) || 0;
|
|
644
|
+
if (n < 60) return `${n} 秒`;
|
|
645
|
+
const m = Math.floor(n / 60);
|
|
646
|
+
return m >= 60 ? `${Math.floor(m / 60)} 小时 ${m % 60} 分` : `${m} 分 ${n % 60} 秒`;
|
|
647
|
+
};
|
|
648
|
+
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>`;
|
|
649
|
+
const short = (id) => `<code>${esc(id)}</code>`;
|
|
650
|
+
|
|
651
|
+
// 监控中心的数据:页面和 /status.json 是同一份
|
|
652
|
+
function monitorData() {
|
|
653
|
+
const alive = serviceAlive();
|
|
654
|
+
const st = engine ? engine.status() : null;
|
|
655
|
+
const r = roles(env);
|
|
656
|
+
return {
|
|
657
|
+
at: fmtStamp(),
|
|
658
|
+
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 },
|
|
659
|
+
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 } },
|
|
660
|
+
workers: st ? st.workers : { limit: cfg.workers, running: [], queued: [] },
|
|
661
|
+
agents: { router: { agent: r.router.agent, model: r.router.model, effort: r.router.effort }, worker: workerSpec() },
|
|
662
|
+
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) })),
|
|
663
|
+
triggers: Object.values(store.data.triggers || {}).sort((a, b) => b.at.localeCompare(a.at) || b.id.localeCompare(a.id)).slice(0, 100),
|
|
664
|
+
sources: sourceStatus(),
|
|
665
|
+
refinedAt: store.data.refinedAt || '',
|
|
666
|
+
config: { router: cfg.router, routerTimeout: cfg.routerTimeout, workers: cfg.workers, refine: cfg.refine, refineInterval: cfg.refineInterval, taskTimeout: cfg.taskTimeout, syncTimeout: cfg.syncTimeout, agentMode: cfg.agentMode, handoffKeep: cfg.handoffKeep, historyKeep: cfg.historyKeep, push: cfg.push, quiet: cfg.quiet, notifyChannel: cfg.notifyChannel },
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// 一个任务下一次什么时候跑(从现在起七天里找)
|
|
671
|
+
function nextRun(spec) {
|
|
672
|
+
if (!spec || spec.problem) return '';
|
|
673
|
+
for (let i = 0; i < 8; i += 1) {
|
|
674
|
+
const d = new Date();
|
|
675
|
+
d.setDate(d.getDate() + i);
|
|
676
|
+
d.setHours(0, 0, 0, 0);
|
|
677
|
+
for (const minute of timesOn(spec, d)) {
|
|
678
|
+
const at = new Date(d);
|
|
679
|
+
at.setHours(Math.floor(minute / 60), minute % 60, 0, 0);
|
|
680
|
+
if (at > new Date()) return i === 0 ? `今天 ${hhmm(at)}` : i === 1 ? `明天 ${hhmm(at)}` : `${WEEKDAY_CN[d.getDay()]} ${hhmm(at)}`;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
return '';
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// 监控中心的「订阅源」一块:每个源的状态、最近一次、连着失败几次
|
|
687
|
+
function sourcesCard(d) {
|
|
688
|
+
const enabled = d.sources.filter((x) => x.enabled).length;
|
|
689
|
+
const rows = d.sources.map((x) => {
|
|
690
|
+
const l = x.last;
|
|
691
|
+
let state;
|
|
692
|
+
if (!x.enabled) state = '<span class="pill">关着</span>';
|
|
693
|
+
else if (x.missing) state = '<span class="pill is-rose">采集脚本不存在</span>';
|
|
694
|
+
else if (!l) state = '<span class="pill">还没跑过</span>';
|
|
695
|
+
else if (l.ok) state = '<span class="pill is-green"><span class="dot is-green"></span>正常</span>';
|
|
696
|
+
else state = `<span class="pill is-rose">失败</span>${l.detail ? `<br><span class="muted">${esc(l.detail)}</span>` : ''}`;
|
|
697
|
+
return [
|
|
698
|
+
`<code>${esc(x.id)}</code>${x.collector ? `<br><span class="muted">${esc(x.collector)}</span>` : ''}`,
|
|
699
|
+
esc(x.signal || x.name || ''),
|
|
700
|
+
state,
|
|
701
|
+
l ? esc(l.at.slice(5, 16)) : '<span class="muted">—</span>',
|
|
702
|
+
l ? `${l.seconds} 秒` : '<span class="muted">—</span>',
|
|
703
|
+
l && l.fails ? `<span class="pill is-rose">${l.fails} 次</span>` : '<span class="muted">0</span>',
|
|
704
|
+
l && l.lastOk ? esc(l.lastOk.slice(5, 16)) : '<span class="muted">—</span>',
|
|
705
|
+
];
|
|
706
|
+
});
|
|
707
|
+
const refine = d.config.router ? ` · 有新数据就提炼${d.config.refine ? '' : '(关着)'},间隔 ${d.config.refineInterval} 分钟` : '';
|
|
708
|
+
const last = d.refinedAt ? ` · 上次提炼 ${esc(d.refinedAt.slice(5, 16))}` : '';
|
|
709
|
+
return `<section class="card">
|
|
710
|
+
<div class="card-head"><h2>订阅源 <span class="muted">采集 ${esc(d.service.sync || '不定时')}${refine}${last}</span></h2><span class="pill">${enabled} 个启用</span></div>
|
|
711
|
+
${table(['源', '反映什么', '状态', '最近一次', '用时', '连续失败', '上次成功'], rows)}
|
|
712
|
+
</section>`;
|
|
375
713
|
}
|
|
376
714
|
|
|
715
|
+
// 监控中心的「待办卡片」一块:等我拿主意的事(DECISIONS.md 里「未答」的行)
|
|
716
|
+
function monitorPage() {
|
|
717
|
+
const d = monitorData();
|
|
718
|
+
const statusPill = (t) => {
|
|
719
|
+
const s = t.worker.status;
|
|
720
|
+
if (s === 'ok') return `<span class="pill is-green">成功 ${t.worker.seconds} 秒</span>`;
|
|
721
|
+
if (s === 'running') return '<span class="pill is-accent"><span class="dot is-accent"></span>在跑</span>';
|
|
722
|
+
if (s === 'queued') return '<span class="pill">排队中</span>';
|
|
723
|
+
if (s === 'failed') return '<span class="pill is-rose">失败</span>';
|
|
724
|
+
if (s === 'stopped') return '<span class="pill is-amber">叫停</span>';
|
|
725
|
+
return `<span class="pill">${esc(s)}</span>`;
|
|
726
|
+
};
|
|
727
|
+
const workerCell = (t) => {
|
|
728
|
+
if (!t.worker) return '<span class="muted">—</span>';
|
|
729
|
+
const extra = t.worker.status === 'failed' && t.worker.reason ? `<br><span class="muted">${esc(t.worker.reason)}</span>` : '';
|
|
730
|
+
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>`;
|
|
731
|
+
return `${statusPill(t)}<br>${who}${extra}`;
|
|
732
|
+
};
|
|
733
|
+
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>');
|
|
734
|
+
const decision = (t) => `<strong>${esc(t.decision || '—')}</strong>${t.reason ? `<br><span class="muted">${esc(t.reason)}</span>` : ''}`;
|
|
735
|
+
const byId = triggersById(store.data);
|
|
736
|
+
const running = d.workers.running.map((w) => {
|
|
737
|
+
const t = byId[w.id];
|
|
738
|
+
const sid = t && t.worker && t.worker.sessionId ? ` <code>${esc(t.worker.sessionId)}</code>` : '';
|
|
739
|
+
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>`;
|
|
740
|
+
}).join('');
|
|
741
|
+
const rs = d.router;
|
|
742
|
+
const session = rs.session ? (rs.session.own ? `专属会话${rs.session.id ? ` <code>${esc(rs.session.id)}</code>` : '(还没开)'}` : `绑定 <code>${esc(rs.session.id)}</code>`) : '—';
|
|
743
|
+
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>';
|
|
744
|
+
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>';
|
|
745
|
+
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>`;
|
|
746
|
+
const body = `${view.pageHead('监控中心', { subtitle: `更新于 ${d.at}`, meta: `<label class="mon-check"><input type="checkbox" id="refresh" checked> 每 10 秒自动刷新(前台时)</label><a class="day-btn" href="/status.json">status.json</a>` })}
|
|
747
|
+
<script>(function(){var b=document.getElementById('refresh');setInterval(function(){if(b.checked&&document.visibilityState==='visible')location.reload()},10000)})();</script>
|
|
748
|
+
<div class="mon-grid">
|
|
749
|
+
<section class="card">
|
|
750
|
+
<div class="card-head"><h2>服务</h2></div>
|
|
751
|
+
<p>${svcBadge}${d.service.since ? `<br><span class="muted">起于 ${esc(d.service.since)} · 已 ${esc(fmtDur(d.service.uptimeS))}</span>` : ''}</p>
|
|
752
|
+
<p>值守 ${d.service.listen ? '开着' : '关着'} · 采集 ${esc(d.service.sync || '不定时')}<br>
|
|
753
|
+
推送 ${d.service.push ? `开着(${esc(d.service.notifyChannel || '没配渠道')})` : '关着'} · 端口 <code>${d.service.port}</code></p>
|
|
754
|
+
</section>
|
|
755
|
+
<section class="card">
|
|
756
|
+
<div class="card-head"><h2>路由</h2></div>
|
|
757
|
+
<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>
|
|
758
|
+
<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>
|
|
759
|
+
</section>
|
|
760
|
+
<section class="card">
|
|
761
|
+
<div class="card-head"><h2>执行者</h2></div>
|
|
762
|
+
<p>${workerBadge}${d.workers.queued.length ? `<br>排队 ${d.workers.queued.map(short).join(' ')}` : ''}</p>
|
|
763
|
+
${running ? `<ul style="margin:6px 0 8px;padding-left:18px;font-size:13px">${running}</ul>` : ''}
|
|
764
|
+
<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>
|
|
765
|
+
</section>
|
|
766
|
+
</div>
|
|
767
|
+
${sourcesCard(d)}
|
|
768
|
+
<section class="card">
|
|
769
|
+
<div class="card-head"><h2>定时任务 <span class="muted">近 ${d.config.historyKeep} 天</span></h2><span class="pill">${d.tasks.length} 个</span></div>
|
|
770
|
+
${table(['任务', '时间', '下一次', '今天', '成功 / 失败', '最近一次', '平均用时'], d.tasks.map((t) => [
|
|
771
|
+
`<code>${esc(t.id)}</code>${t.hasPrompt ? '' : ' <span class="pill is-amber">缺指令文件</span>'}`,
|
|
772
|
+
esc(t.problem ? `${t.spec}(${t.problem})` : t.spec || '(空)'),
|
|
773
|
+
esc(nextRun(t.problem ? null : parseSpec(t.spec)) || '—'),
|
|
774
|
+
String(t.today),
|
|
775
|
+
`${t.ok} / ${t.failed}`,
|
|
776
|
+
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>',
|
|
777
|
+
t.avgSeconds ? esc(fmtDur(t.avgSeconds)) : '<span class="muted">—</span>',
|
|
778
|
+
]))}
|
|
779
|
+
</section>
|
|
780
|
+
<section class="card">
|
|
781
|
+
<div class="card-head"><h2>触发 <span class="muted">近两天,新的在前</span></h2><span class="pill">${d.triggers.length} 条</span></div>
|
|
782
|
+
${table(['时间', '短号', '来源', '决定', '执行者', '发了', '文档'], d.triggers.map((t) => [
|
|
783
|
+
esc(t.at.slice(5, 16)),
|
|
784
|
+
short(t.id),
|
|
785
|
+
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>` : ''),
|
|
786
|
+
decision(t),
|
|
787
|
+
workerCell(t),
|
|
788
|
+
t.notified ? '<span class="pill is-green">是</span>' : '<span class="muted">—</span>',
|
|
789
|
+
docs(t),
|
|
790
|
+
]))}
|
|
791
|
+
</section>
|
|
792
|
+
<section class="card">
|
|
793
|
+
<div class="card-head"><h2>配置 <span class="muted">只读</span></h2></div>
|
|
794
|
+
<div class="mon-kv">
|
|
795
|
+
<span class="pill">router: ${d.config.router}</span>
|
|
796
|
+
<span class="pill">router-timeout: ${d.config.routerTimeout}s</span>
|
|
797
|
+
<span class="pill">workers: ${d.config.workers}</span>
|
|
798
|
+
<span class="pill">refine: ${d.config.refine}</span>
|
|
799
|
+
<span class="pill">refine-interval: ${d.config.refineInterval}m</span>
|
|
800
|
+
<span class="pill">task-timeout: ${d.config.taskTimeout}s</span>
|
|
801
|
+
<span class="pill">agent-mode: ${esc(d.config.agentMode)}</span>
|
|
802
|
+
<span class="pill">handoff-keep: ${d.config.handoffKeep}d</span>
|
|
803
|
+
<span class="pill">history-keep: ${d.config.historyKeep}d</span>
|
|
804
|
+
<span class="pill">push: ${d.config.push}</span>
|
|
805
|
+
<span class="pill">quiet: [${esc(d.config.quiet.join(', '))}]</span>
|
|
806
|
+
</div>
|
|
807
|
+
</section>
|
|
808
|
+
<section class="card mon-log">
|
|
809
|
+
<div class="card-head"><h2>日志 <span class="muted">只记时间和 id,不记消息内容</span></h2></div>
|
|
810
|
+
<h3>01-inbox/_rhythm.log 末 50 行</h3>
|
|
811
|
+
<pre><code>${esc(readText(LOG_FILE).trim().split('\n').slice(-50).join('\n') || '(暂无)')}</code></pre>
|
|
812
|
+
<h3>01-inbox/_bot.log 末 30 行</h3>
|
|
813
|
+
<pre><code>${esc(readText(path.join(root, '01-inbox', '_bot.log')).trim().split('\n').slice(-30).join('\n') || '(暂无)')}</code></pre>
|
|
814
|
+
</section>`;
|
|
815
|
+
return md.page('监控中心', body, navHtml('/monitor'));
|
|
816
|
+
}
|
|
817
|
+
const triggersById = (data) => Object.fromEntries(Object.values(data.triggers || {}).map((t) => [t.id, t]));
|
|
818
|
+
|
|
377
819
|
// 配置和依赖的问题,一条一个字符串。strict 为 false 时不把「缺指令文件的任务」算进去;bot 为 false 时不把值守的配置算进去(起服务时值守配不齐只记一笔,不拦着)
|
|
378
820
|
function doctorProblems({ strict = true, bot = true } = {}) {
|
|
379
821
|
const problems = [];
|
|
@@ -384,8 +826,8 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
384
826
|
if (!node || launchd.looksLikeElectron(node, {})) problems.push(`常驻的 plist 里绑的不是真正的 node(${node || '没读到'}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
385
827
|
else if (!fs.existsSync(node)) problems.push(`常驻的 plist 里绑的 node 不在了(${node}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
386
828
|
}
|
|
387
|
-
// 值守开着的话,它的配置(agent、钥匙串、我的 openId
|
|
388
|
-
if (bot && botWanted()) problems.push(...createBot({ root, env }).doctorProblems());
|
|
829
|
+
// 值守开着的话,它的配置(agent、钥匙串、我的 openId、渠道)也要齐。路由开着时值守用的是路由的 agent
|
|
830
|
+
if (bot && botWanted()) problems.push(...createBot({ root, env, doctorAgent: cfg.router ? routerDoctorProblems : null }).doctorProblems());
|
|
389
831
|
for (const [id, specText] of Object.entries(cfg.schedule)) {
|
|
390
832
|
if (NOT_SERVICE_TASKS.includes(id)) continue;
|
|
391
833
|
const spec = parseSpec(specText);
|
|
@@ -400,9 +842,47 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
400
842
|
problems.push(...makeAgent().doctor());
|
|
401
843
|
if (cfg.push && !cfg.notifyChannel) problems.push('rhythm.push 开着,但 preferences.notify 没配消息渠道:要么配一个,要么把 push 写成 false');
|
|
402
844
|
}
|
|
845
|
+
// 路由和执行者的新键:写了就得是正整数(没写用默认)
|
|
846
|
+
for (const [key, name] of NEW_KEYS) {
|
|
847
|
+
if (cfg.raw[key] !== undefined && !(Number.isInteger(Number(cfg.raw[key])) && Number(cfg.raw[key]) > 0)) problems.push(`${name} 要是正整数(现在是 ${cfg.raw[key]})`);
|
|
848
|
+
}
|
|
849
|
+
// 路由开着时它的 agent 也要配得对(值守开着时 bot 那边查的是同一个)
|
|
850
|
+
if (cfg.router) problems.push(...routerDoctorProblems());
|
|
851
|
+
// 启用着的源,采集脚本得在
|
|
852
|
+
for (const x of sourceStatus()) if (x.missing) problems.push(`订阅源 ${x.id} 的采集脚本不存在:${x.collector}(sources.yaml 的 collector 写错了,或者脚本没放进 collectors/)`);
|
|
403
853
|
return problems;
|
|
404
854
|
}
|
|
405
855
|
|
|
856
|
+
// 路由用的 agent 有没有配对
|
|
857
|
+
// 路由的 agent 找得到、模型和强度它认,再加上路由的硬规矩:模型必须是 flash 这类快模型、强度固定 low
|
|
858
|
+
const routerDoctorProblems = () => {
|
|
859
|
+
const r = roles(env).router;
|
|
860
|
+
return [...createAgent({ root, agent: r.agent, mode: 'plan', env, model: r.model, effort: r.effort }).doctor(), ...routerProblems({ agent: r.agent, model: r.model, effort: r.effort, env })];
|
|
861
|
+
};
|
|
862
|
+
|
|
863
|
+
// 命令行里走一遍全流程(work-rhythm listen handle,路由开着时):在命令行的进程里建引擎,这句话变成一条触发,
|
|
864
|
+
// 要发的文字交给 sink(带 push 才真发),等到队列空、执行者都结束。返回 { id, texts } 或者 null(路由没开)
|
|
865
|
+
async function handle(text, { push: really = false, timeoutMs = 600000 } = {}) {
|
|
866
|
+
const eng = makeEngine();
|
|
867
|
+
if (!eng) return null;
|
|
868
|
+
const texts = [];
|
|
869
|
+
if (!really) eng.setSink((t) => texts.push(t));
|
|
870
|
+
const t = eng.enqueue('message', { key: `handle-${Date.now()}`, msgId: 'handle', text, mode: (env.YZJ_BOT_AGENT_MODE || 'plan').trim() });
|
|
871
|
+
await eng.waitIdle(timeoutMs);
|
|
872
|
+
eng.setSink(null);
|
|
873
|
+
return { id: t ? t.id : '', texts };
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// 不算问题、但要让人知道的事(doctor 另起一行列出来,不影响退出码)。mentionOff 为 false 时不提「路由没开」
|
|
877
|
+
function doctorNotes({ mentionOff = true } = {}) {
|
|
878
|
+
if (!cfg.router) return mentionOff ? ['路由没开(profile 的 rhythm.router 没写):到点直接跑任务,IM 里的话直接答;要走「触发 → 路由 → 执行者」写上 rhythm.router: true(docs/router-worker.md)'] : [];
|
|
879
|
+
const r = roles(env).router;
|
|
880
|
+
const notes = cfg.router ? createAgent({ root, agent: r.agent, mode: 'plan', env, model: r.model, effort: r.effort }).notes() : [];
|
|
881
|
+
if (cfg.router && !cfg.notifyChannel && cfg.push) notes.push('推送关不掉又没配渠道:路由写给用户的话发不出去,只记日志');
|
|
882
|
+
for (const x of sourceStatus()) if (x.enabled && x.last && x.last.fails >= 3) notes.push(`订阅源 ${x.id} 已经连续失败 ${x.last.fails} 次(最近 ${x.last.at}):看 01-inbox/_sync.log,或者 work-rhythm sync ${x.id}`);
|
|
883
|
+
return notes;
|
|
884
|
+
}
|
|
885
|
+
|
|
406
886
|
// 前台跑:定时采集、定时整理、推送、网页服务。每 tickMs 看一次表(默认 20 秒)。收到 SIGINT / SIGTERM 后退出,返回退出码
|
|
407
887
|
async function start({ tickMs = TICK_MS } = {}) {
|
|
408
888
|
if (serviceAlive()) throw new Fail(EXIT.NOT_CONFIGURED, '服务已经在跑了(work-rhythm rhythm status 看详情)');
|
|
@@ -420,8 +900,15 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
420
900
|
// 配置有问题不拦着服务起,只记一笔——定时任务和网页照常
|
|
421
901
|
let bot = null;
|
|
422
902
|
let botTask = null;
|
|
903
|
+
// 路由开着:引擎在这个进程里跑(触发 → 路由 → 执行者 → 汇报)。上次没跑完的执行者先补失败回执,交回路由
|
|
904
|
+
const eng = makeEngine();
|
|
905
|
+
if (eng) {
|
|
906
|
+
eng.recover();
|
|
907
|
+
eng.tick();
|
|
908
|
+
log('引擎开始', `路由=${roles(env).router.agent} 执行者=${workerSpec().agent} 并发=${cfg.workers}`);
|
|
909
|
+
}
|
|
423
910
|
if (botWanted()) {
|
|
424
|
-
bot = createBot({ root, env });
|
|
911
|
+
bot = createBot({ root, env, onMessage: eng ? (m) => eng.message(m) : null, resetSession: eng ? () => eng.resetSession() : null, doctorAgent: eng ? () => eng.doctorProblems() : null });
|
|
425
912
|
const botProblems = bot.doctorProblems();
|
|
426
913
|
if (botProblems.length) log('值守没开', botProblems.join(';'));
|
|
427
914
|
else {
|
|
@@ -433,7 +920,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
433
920
|
}
|
|
434
921
|
|
|
435
922
|
const list = jobs();
|
|
436
|
-
const state =
|
|
923
|
+
const state = store.data;
|
|
437
924
|
let running = null;
|
|
438
925
|
const queue = [];
|
|
439
926
|
const startNext = () => {
|
|
@@ -442,13 +929,32 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
442
929
|
running = startJob(job);
|
|
443
930
|
running.on('exit', (code) => {
|
|
444
931
|
state.runs[job.id] = { at: fmtStamp(), ok: code === 0, code };
|
|
932
|
+
// 监控中心的运行记录
|
|
933
|
+
if (job.kind === 'task') {
|
|
934
|
+
const w = workerSpec();
|
|
935
|
+
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 });
|
|
936
|
+
}
|
|
445
937
|
saveState(state);
|
|
446
938
|
log('跑完', `${job.id} rc=${code}`);
|
|
447
939
|
running = null;
|
|
448
940
|
startNext();
|
|
941
|
+
// 采集是有新数据才提炼:子进程把每个源的结果和「有没有新数据」留在 last-sync.json,这里交给引擎
|
|
942
|
+
if (job.kind === 'sync' && eng) {
|
|
943
|
+
try {
|
|
944
|
+
const file = path.join(STATE_DIR, 'last-sync.json');
|
|
945
|
+
const st = fs.statSync(file);
|
|
946
|
+
if (Date.now() - st.mtimeMs < 10 * 60 * 1000) {
|
|
947
|
+
const last = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
948
|
+
eng.afterSync({ results: last.results || [], changed: Boolean(last.changed) });
|
|
949
|
+
}
|
|
950
|
+
} catch (error) {
|
|
951
|
+
log('采集结果读不了', error && error.message ? error.message : String(error));
|
|
952
|
+
}
|
|
953
|
+
}
|
|
449
954
|
});
|
|
450
955
|
};
|
|
451
956
|
const tick = () => {
|
|
957
|
+
if (eng) eng.tick();
|
|
452
958
|
const now = new Date();
|
|
453
959
|
for (const job of list) {
|
|
454
960
|
for (const minute of timesOn(job.spec, now)) {
|
|
@@ -464,6 +970,12 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
464
970
|
continue;
|
|
465
971
|
}
|
|
466
972
|
log('到点', `${job.id} ${hhmm(at)}`);
|
|
973
|
+
if (job.kind === 'task' && eng) {
|
|
974
|
+
// 路由开着:任务变成一条触发交给路由,由它判断再派给执行者
|
|
975
|
+
const body = fs.readFileSync(path.join(root, 'tasks', `${job.id}.md`), 'utf8');
|
|
976
|
+
eng.schedule({ id: job.id, key }, body, taskTitleOf(body));
|
|
977
|
+
continue;
|
|
978
|
+
}
|
|
467
979
|
queue.push(job);
|
|
468
980
|
}
|
|
469
981
|
}
|
|
@@ -482,8 +994,11 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
482
994
|
} catch {
|
|
483
995
|
// 已经没了
|
|
484
996
|
}
|
|
485
|
-
|
|
486
|
-
|
|
997
|
+
// 在跑的执行者是子进程,不收掉会留着:停掉它们(引擎里最多等 3 秒),再关网页
|
|
998
|
+
const close = () => server.close(() => resolve());
|
|
999
|
+
if (eng) eng.shutdown().then(close, close);
|
|
1000
|
+
else close();
|
|
1001
|
+
setTimeout(resolve, 4500).unref();
|
|
487
1002
|
};
|
|
488
1003
|
process.on('SIGINT', () => stop('SIGINT'));
|
|
489
1004
|
process.on('SIGTERM', () => stop('SIGTERM'));
|
|
@@ -522,6 +1037,21 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
522
1037
|
const botLog = readText(path.join(root, '01-inbox', '_bot.log')).trim().split('\n');
|
|
523
1038
|
const lastBot = botLog.length && botLog[botLog.length - 1] ? botLog[botLog.length - 1] : '';
|
|
524
1039
|
lines.push(`值守:${botWanted() ? `开着${lastBot ? `,最近 ${lastBot}` : ''}` : '关着(collectors/local.env 的 YZJ_BOT_LISTEN=1 打开,改完 work-rhythm rhythm restart)'}`);
|
|
1040
|
+
const r = roles(env).router;
|
|
1041
|
+
const w = workerSpec();
|
|
1042
|
+
const rounds = (store.data.rounds || []).filter((x) => x.at.startsWith(fmtDate(new Date()))).length;
|
|
1043
|
+
lines.push(`路由:${cfg.router ? `开着(${r.agent || '没绑'}${r.model ? `,模型 ${r.model}` : ''}${r.effort ? `,强度 ${r.effort}` : ''}),今天 ${rounds} 轮;实时的排队和在跑看 ${baseUrl()}/monitor` : '关着(到点直接跑任务,IM 里的话直接答;要开在 profile 的 rhythm 写 router: true)'}`);
|
|
1044
|
+
lines.push(`执行者:${w.agent || '没绑'}${w.model ? `,模型 ${w.model}` : ''}${w.effort ? `,强度 ${w.effort}` : ''},同时最多 ${cfg.workers} 个`);
|
|
1045
|
+
// 订阅源:几个正常、谁在连着失败、谁还没跑过
|
|
1046
|
+
const srcs = sourceStatus().filter((x) => x.enabled);
|
|
1047
|
+
if (srcs.length) {
|
|
1048
|
+
const okN = srcs.filter((x) => !x.missing && x.last && x.last.ok).length;
|
|
1049
|
+
const bad = srcs.filter((x) => x.missing || (x.last && !x.last.ok)).map((x) => (x.missing ? `${x.id} 缺采集脚本` : `${x.id} 失败 ${x.last.fails} 次(${x.last.at.slice(5, 16)})`));
|
|
1050
|
+
const never = srcs.filter((x) => !x.last).map((x) => x.id);
|
|
1051
|
+
lines.push(`订阅源:${okN} 个正常${bad.length ? `,${bad.join(';')}` : ''}${never.length ? `,${never.join('、')} 还没跑过` : ''};看 ${baseUrl()}/monitor`);
|
|
1052
|
+
}
|
|
1053
|
+
const triggers = Object.values(store.data.triggers || {}).filter((t) => t.worker && ['queued', 'running'].includes(t.worker.status));
|
|
1054
|
+
if (triggers.length) lines.push(`没跑完的:${triggers.map((t) => t.id).join(' ')}(下次启动时补失败回执)`);
|
|
525
1055
|
const runs = Object.entries(loadState().runs).sort((a, b) => a[1].at.localeCompare(b[1].at)).slice(-5);
|
|
526
1056
|
if (runs.length) lines.push(`最近:${runs.map(([id, r]) => `${id} ${r.at} ${r.ok ? '成功' : `失败(${r.code})`}`).join(';')}`);
|
|
527
1057
|
lines.push(`接下来:\n${due(new Date(), 1)}`);
|
|
@@ -532,9 +1062,17 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
532
1062
|
cfg,
|
|
533
1063
|
log,
|
|
534
1064
|
stateDir: STATE_DIR,
|
|
1065
|
+
store,
|
|
535
1066
|
baseUrl,
|
|
536
1067
|
serviceAlive,
|
|
537
1068
|
due,
|
|
1069
|
+
monitorData,
|
|
1070
|
+
monitorPage,
|
|
1071
|
+
doctorNotes,
|
|
1072
|
+
recordForTest: (id, r) => recordSources([{ id, ...r }]),
|
|
1073
|
+
handle,
|
|
1074
|
+
makeEngine,
|
|
1075
|
+
engine: () => engine,
|
|
538
1076
|
render,
|
|
539
1077
|
runJob,
|
|
540
1078
|
start,
|