work-rhythm 0.2.21 → 0.2.24
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 +11 -3
- package/.agents/notes/decisions/2026-11-30-bot-inbound-uses-websocket-and-a-responder-command.md +1 -0
- package/.agents/notes/decisions/2026-11-30-skill-ships-with-its-template-in-a-zip.md +1 -0
- package/.agents/notes/decisions/2026-12-01-agent-binding-asks-for-model-and-effort.md +1 -0
- package/.agents/notes/decisions/2026-12-01-interjections-batch-into-one-answer-and-interrupt-reruns.md +1 -0
- package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +1 -0
- package/.agents/notes/decisions/2026-12-01-router-runs-on-a-flash-model-with-low-effort.md +1 -0
- package/.agents/notes/decisions/2026-12-03-codex-cli-joins-as-a-preset-verified-against-its-own-binary.md +45 -0
- package/.agents/notes/decisions/2026-12-03-fewer-scheduled-tasks-silent-refine-no-question-cards.md +1 -0
- package/.agents/notes/decisions/2026-12-03-playbook-distills-handoffs-into-ws-tool-and-skill-know-how.md +43 -0
- package/.agents/notes/decisions/2026-12-03-related-work-comes-back-as-one-reply.md +49 -0
- package/.agents/notes/decisions/2026-12-03-roster-of-worker-groups-router-picks-the-group.md +34 -0
- package/.agents/notes/decisions/2026-12-03-router-model-and-effort-are-configurable.md +28 -0
- package/.agents/notes/decisions/2026-12-03-router-only-direct-mode-removed.md +27 -0
- package/.agents/notes/decisions/2026-12-03-unattended-runs-decide-on-their-own.md +32 -0
- package/.agents/notes/decisions/2026-12-03-update-upgrades-package-and-refreshes-shipped-files.md +30 -0
- package/.agents/notes/decisions/2026-12-03-workers-leave-a-status-trail-that-joins-the-receipt.md +31 -0
- package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +2 -0
- package/.agents/notes/pitfalls/2026-12-03-judging-a-symlink-by-realpath-ignores-parent-links.md +18 -0
- package/.agents/notes/pitfalls/2026-12-04-selftest-sandbox-leaves-qoder-and-claude-real.md +18 -0
- package/.agents/skills/work-rhythm/SKILL.md +20 -16
- package/README.md +13 -10
- package/collectors/local.env.example +31 -36
- package/docs/agents.md +61 -60
- package/docs/channels.md +15 -19
- package/docs/formats.md +27 -0
- package/docs/router-worker.md +60 -41
- package/docs/scheduled-tasks.md +9 -9
- package/package.json +1 -1
- package/scripts/cli.js +9 -5
- package/scripts/cmd/agent.js +348 -235
- package/scripts/cmd/check.js +14 -7
- package/scripts/cmd/listen.js +33 -32
- package/scripts/cmd/pack.js +6 -6
- package/scripts/cmd/rhythm.js +13 -10
- package/scripts/cmd/trigger.js +23 -14
- package/scripts/cmd/update.js +92 -0
- package/scripts/lib/agent.js +235 -142
- package/scripts/lib/agents.js +179 -0
- package/scripts/lib/bot.js +44 -263
- package/scripts/lib/engine.js +373 -110
- package/scripts/lib/handoff.js +54 -8
- package/scripts/lib/markdown.js +19 -0
- package/scripts/lib/playbook.js +123 -0
- package/scripts/lib/rhythm.js +503 -187
- package/scripts/lib/router.js +45 -29
- package/scripts/lib/template.js +3 -3
- package/scripts/lib/update.js +279 -0
- package/scripts/lib/worker.js +11 -5
- package/scripts/test/agent.test.js +410 -257
- package/scripts/test/check.test.js +17 -6
- package/scripts/test/harness.js +6 -2
- package/scripts/test/listen.test.js +190 -158
- package/scripts/test/playbook.test.js +106 -0
- package/scripts/test/rhythm.test.js +210 -55
- package/scripts/test/roster.test.js +155 -0
- package/scripts/test/router-helper.js +17 -2
- package/scripts/test/router.test.js +469 -195
- package/scripts/test/stubs.js +56 -7
- package/scripts/test/timeout.test.js +160 -59
- package/scripts/test/update.test.js +384 -0
- package/tasks/daily-persona.md +30 -14
- package/tasks/daily-plan.md +3 -3
- package/tasks/evening-review.md +1 -7
- package/tasks/noon-checkin.md +2 -1
- package/templates/00-config/profile.example.yaml +9 -6
- package/templates/04-patterns/PERSONA.md +4 -1
- package/templates/04-patterns/PLAYBOOK.md +13 -0
- package/templates/AGENTS.md +6 -2
- package/templates/README.md +10 -9
package/scripts/lib/rhythm.js
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
// work-rhythm 本地服务的实现,入口是 work-rhythm rhythm(用法写在 cmd/rhythm.js)。四件事:
|
|
2
2
|
// 1 定时采集:按 profile 的 rhythm.sync 跑一遍 sync,数据落 01-inbox/;
|
|
3
|
-
// 2 定时整理:按 profile 的 schedule 把 tasks/<id>.md
|
|
4
|
-
// 3
|
|
5
|
-
// 4 看页面:只绑 127.0.0.1 的网页服务,把工作目录里的 Markdown 现渲染成 HTML(markdown.js
|
|
6
|
-
//
|
|
7
|
-
//
|
|
3
|
+
// 2 定时整理:按 profile 的 schedule 把 tasks/<id>.md 的指令变成触发,走引擎(engine.js:路由判断、派给执行者、汇报);
|
|
4
|
+
// 3 推送:路由写给我的话经消息渠道(notify.js)发给我,附一个本机地址;
|
|
5
|
+
// 4 看页面:只绑 127.0.0.1 的网页服务,把工作目录里的 Markdown 现渲染成 HTML(markdown.js),外加监控中心(/monitor)
|
|
6
|
+
// 和配置路由、执行者的 /agents(唯一的写接口,带令牌)。
|
|
7
|
+
// 任务都走路由,没有「直接跑」的做法。错过的任务在 5 分钟内还会补跑,再久就不追了。
|
|
8
8
|
// 只用 node 自带的能力。日志写 01-inbox/_rhythm.log,状态写 01-inbox/_rhythm/state.json。
|
|
9
9
|
'use strict';
|
|
10
|
-
const { spawn } = require('node:child_process');
|
|
10
|
+
const { spawn, execFile } = require('node:child_process');
|
|
11
11
|
const fs = require('node:fs');
|
|
12
12
|
const http = require('node:http');
|
|
13
13
|
const path = require('node:path');
|
|
14
14
|
const { EXIT, Fail, fmtDate, fmtStamp, pad, tail, readText, writeFileAtomic, seconds } = require('./run');
|
|
15
15
|
const { createHash } = require('node:crypto');
|
|
16
|
-
const { loadProfile, loadSources } = require('./config');
|
|
16
|
+
const { loadProfile, loadSources, loadLocalEnv, writeLocalEnv } = require('./config');
|
|
17
17
|
const { logger } = require('./log');
|
|
18
|
-
const {
|
|
18
|
+
const { installedAgents, MODEL_SUPPORT, PRESET_NAMES, presetKind, modelList } = require('./agent');
|
|
19
|
+
const rosterLib = require('./agents');
|
|
19
20
|
const { createBot } = require('./bot');
|
|
20
21
|
const { notifyChannel, pushText } = require('./notify');
|
|
21
22
|
const { createEngine, appendHistory, pruneState, historyStats, uid } = require('./engine');
|
|
@@ -30,21 +31,24 @@ const TICK_MS = 20000;
|
|
|
30
31
|
const CATCH_UP_MS = 5 * 60 * 1000;
|
|
31
32
|
const WEEKDAYS = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
|
|
32
33
|
const WEEKDAY_CN = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
|
|
33
|
-
//
|
|
34
|
+
// 这些要等我回答,不当定时任务:我对任何一个能读到这个工作目录的 agent 说「有什么要我定」就开始
|
|
34
35
|
const NOT_SERVICE_TASKS = ['ask-decisions'];
|
|
36
|
+
// 这些任务天生静默(后台整理归档这类):不管 profile 的 quiet 怎么写都不推送、不发消息
|
|
37
|
+
const ALWAYS_QUIET = ['daily-persona'];
|
|
35
38
|
// 任务跑完推送时附哪个页面(本机网页服务上的地址)
|
|
36
39
|
const LINKS = {
|
|
37
40
|
'daily-plan': { path: (d) => `/day/${d}`, label: '今天的文件' },
|
|
38
41
|
'noon-checkin': { path: (d) => `/day/${d}`, label: '今天的文件' },
|
|
39
42
|
'evening-review': { path: (d) => `/day/${d}`, label: '今天的文件' },
|
|
40
43
|
'weekly-rhythm': { path: () => '/rhythm', label: '工作规律' },
|
|
41
|
-
'alerts-morning': { path: (d) => `/reports/${d}-alerts.html`, label: '告警晨报' },
|
|
42
|
-
// 一批新事件之后的「今日重点与待办」:地址给「决定」页(待办卡片在那里点),手机打不开,要在自己电脑上开
|
|
43
44
|
};
|
|
44
|
-
const NAV = [['/', '今日'], ['/
|
|
45
|
+
const NAV = [['/', '今日'], ['/rhythm', '规律'], ['/goals', '目标'], ['/monitor', '监控'], ['/agents', 'agent']];
|
|
45
46
|
const NEW_KEYS = [['workers', 'rhythm.workers'], ['router-timeout', 'rhythm.router-timeout'], ['handoff-keep', 'rhythm.handoff-keep'], ['history-keep', 'rhythm.history-keep']];
|
|
47
|
+
const JSON_TYPE = 'application/json; charset=utf-8';
|
|
48
|
+
const EFFORTS = ['none', 'low', 'medium', 'high', 'max'];
|
|
49
|
+
const CUSTOM = '__custom__';
|
|
46
50
|
// 状态文件的骨架:done(跑过的任务)、runs(各任务最近一次)、seq(触发短号的序号)、triggers(近两天的触发)、history(运行记录)、rounds(路由的轮数)
|
|
47
|
-
const EMPTY_STATE = () => ({ done: {}, runs: {}, seq: 0, triggers: {}, history: [], rounds: [], sources: {}, refinedAt: '', syncDigest: { date: '', digest: '' } });
|
|
51
|
+
const EMPTY_STATE = () => ({ done: {}, runs: {}, seq: 0, triggers: {}, history: [], rounds: [], sources: {}, refinedAt: '', syncDigest: { date: '', digest: '' }, playbookTurns: 0, playbookAt: '' });
|
|
48
52
|
|
|
49
53
|
const positiveInt = (value, fallback) => {
|
|
50
54
|
const n = Number(value);
|
|
@@ -67,22 +71,23 @@ function loadConfig(root) {
|
|
|
67
71
|
sync: typeof rhythm.sync === 'string' ? rhythm.sync.trim() : '',
|
|
68
72
|
port: positiveInt(rhythm.port, 8787),
|
|
69
73
|
push: rhythm.push !== false,
|
|
70
|
-
quiet: asList(rhythm.quiet),
|
|
74
|
+
quiet: [...new Set([...ALWAYS_QUIET, ...asList(rhythm.quiet)])],
|
|
71
75
|
agentMode: typeof rhythm['agent-mode'] === 'string' && rhythm['agent-mode'].trim() ? rhythm['agent-mode'].trim() : 'edit',
|
|
72
|
-
// 定时任务用的模型和思考强度(可选项,profile 里不写也行):不配就和值守一样,用 local.env 的 YZJ_BOT_MODEL / YZJ_BOT_EFFORT
|
|
73
|
-
agentModel: typeof rhythm['agent-model'] === 'string' ? rhythm['agent-model'].trim() : '',
|
|
74
|
-
agentEffort: typeof rhythm['agent-effort'] === 'string' ? rhythm['agent-effort'].trim() : '',
|
|
75
76
|
taskTimeout: seconds(rhythm['task-timeout'], 0),
|
|
77
|
+
// 手头还有别的活在跑时,先做完的汇报等一等(一起交回路由、回我的话合成一条),最多等这么多秒;0 = 不等,做完就汇报
|
|
78
|
+
mergeWait: seconds(rhythm['merge-wait'], 120),
|
|
76
79
|
syncTimeout: positiveInt(rhythm['sync-timeout'], 600),
|
|
77
80
|
notifyChannel: typeof preferences.notify === 'string' ? preferences.notify.trim() : '',
|
|
78
81
|
schedule,
|
|
79
|
-
//
|
|
80
|
-
router: rhythm.router === true,
|
|
82
|
+
// 路由和执行者用哪个 agent、模型、强度在名册里(docs/agents.md);这里只有引擎的几个旋钮
|
|
81
83
|
routerTimeout: positiveInt(rhythm['router-timeout'], 120),
|
|
82
|
-
|
|
83
|
-
|
|
84
|
+
// 老写法:没有 00-config/agents.json 时,那一组执行者同时跑几个(名册的 fromEnv 读它)
|
|
85
|
+
workers: positiveInt(rhythm.workers, rosterLib.DEFAULT_COUNT),
|
|
86
|
+
// 定时采集之后:有新数据就起一轮提炼(把 01-inbox 的新数据炼成事件)。两轮提炼之间至少隔 refine-interval 分钟
|
|
84
87
|
refine: rhythm.refine !== false,
|
|
85
88
|
refineInterval: positiveInt(rhythm['refine-interval'], 120),
|
|
89
|
+
playbookTurns: positiveInt(rhythm['playbook-turns'], 10),
|
|
90
|
+
playbookInterval: positiveInt(rhythm['playbook-interval'], 180),
|
|
86
91
|
handoffKeep: positiveInt(rhythm['handoff-keep'], 14),
|
|
87
92
|
historyKeep: positiveInt(rhythm['history-keep'], 90),
|
|
88
93
|
raw: rhythm,
|
|
@@ -115,11 +120,12 @@ function parseSpec(spec) {
|
|
|
115
120
|
return { problem: `看不懂时间写法「${s}」:支持 "08:50"、"Fri 16:30"、"工作日 09:00-18:00 每 30 分钟"` };
|
|
116
121
|
}
|
|
117
122
|
|
|
118
|
-
// 建一个本地服务对象。env 是设置(环境变量,上面盖一层 local.env
|
|
123
|
+
// 建一个本地服务对象。env 是设置(环境变量,上面盖一层 local.env)
|
|
119
124
|
function createRhythm({ root, env, packageRoot }) {
|
|
120
125
|
const STATE_DIR = path.join(root, '01-inbox', '_rhythm');
|
|
121
126
|
const STATE_FILE = path.join(STATE_DIR, 'state.json');
|
|
122
127
|
const PID_FILE = path.join(STATE_DIR, 'service.pid');
|
|
128
|
+
const TOKEN_FILE = path.join(STATE_DIR, 'web-token');
|
|
123
129
|
const LOG_FILE = path.join(root, '01-inbox', '_rhythm.log');
|
|
124
130
|
const LAUNCHD_LOG = path.join(root, '01-inbox', '_rhythm.launchd.log');
|
|
125
131
|
const ENTRY = path.join(packageRoot, 'scripts', 'work-rhythm.js');
|
|
@@ -130,7 +136,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
130
136
|
const since = Date.now();
|
|
131
137
|
// 状态(engine.js 也往里写):同一个进程里只有这一份
|
|
132
138
|
const store = { data: loadState(), save() { saveState(store.data); } };
|
|
133
|
-
// 引擎(路由 +
|
|
139
|
+
// 引擎(路由 + 执行者):同一个进程里只建一个,第一次用到才建
|
|
134
140
|
let engine = null;
|
|
135
141
|
const engineCfg = () => {
|
|
136
142
|
const idle = seconds(env.YZJ_BOT_IDLE, 180);
|
|
@@ -152,15 +158,15 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
152
158
|
};
|
|
153
159
|
};
|
|
154
160
|
const makeEngine = () => {
|
|
155
|
-
if (!cfg.router) return null;
|
|
156
161
|
if (!engine) engine = createEngine({ root, env, cfg: engineCfg(), log, push, state: store, since });
|
|
157
162
|
return engine;
|
|
158
163
|
};
|
|
159
|
-
//
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
+
// 名册:路由和有哪几组执行者。每次都现读,网页或命令行改了立刻看得到
|
|
165
|
+
const roster = () => rosterLib.loadRoster(root, env);
|
|
166
|
+
const rosterLook = () => rosterLib.inspect(root, env, roster());
|
|
167
|
+
const agentsProblems = () => rosterLook().problems;
|
|
168
|
+
// 值守的配置:渠道、钥匙串、我的 openId,加上路由和执行者的 agent
|
|
169
|
+
const botProblems = () => createBot({ root, env, onMessage: () => null, doctorAgent: agentsProblems }).doctorProblems();
|
|
164
170
|
|
|
165
171
|
// 某一天上不上班:以 work-rhythm today 为准(作息、放假都由它判),同一天只问一次
|
|
166
172
|
const workdayCache = {};
|
|
@@ -231,7 +237,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
231
237
|
}
|
|
232
238
|
}
|
|
233
239
|
|
|
234
|
-
// 写状态文件。命令行里的 listen handle / trigger fire 和服务可能同时写:先读盘上的那份,合起来再写——
|
|
240
|
+
// 写状态文件。命令行里的 listen handle / rhythm run / trigger fire 和服务可能同时写:先读盘上的那份,合起来再写——
|
|
235
241
|
// 触发按短号取并集(内存里的新),done / runs / rounds / history 也取并集,seq 取大的
|
|
236
242
|
function saveState(state) {
|
|
237
243
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
@@ -269,7 +275,6 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
269
275
|
}
|
|
270
276
|
|
|
271
277
|
// ---------------------------------------------------------------- 采集、任务、推送
|
|
272
|
-
// 跑一遍 sync(在同一个进程里),最多等 cfg.syncTimeout 秒
|
|
273
278
|
const todayStr = () => fmtDate(new Date());
|
|
274
279
|
|
|
275
280
|
// 今天 01-inbox/<源>/<日期>/ 下所有文件的名字和内容搓成的指纹:采集之后跟上次比,不一样就是有新数据(采集器每次都重写文件,所以不按修改时间算)
|
|
@@ -325,7 +330,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
325
330
|
const capture = { write: (s) => (chunks.push(String(s)), true) };
|
|
326
331
|
const results = [];
|
|
327
332
|
const fail = await sync.run([], { root, cwd: root, env, stdout: capture, stderr: capture, packageRoot }, { deadlineMs: t0 + cfg.syncTimeout * 1000, results });
|
|
328
|
-
const
|
|
333
|
+
const secs = Math.round((Date.now() - t0) / 1000);
|
|
329
334
|
recordSources(results);
|
|
330
335
|
// 有没有新数据:今天的指纹跟上一次比。没有文件也算一种指纹(空串),和上次不一样才是有新数据
|
|
331
336
|
const digest = inboxDigest(todayStr());
|
|
@@ -333,16 +338,16 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
333
338
|
const changed = Boolean(digest) && digest !== prev.digest;
|
|
334
339
|
store.data.syncDigest = { date: todayStr(), digest, at: fmtStamp() };
|
|
335
340
|
saveState(store.data);
|
|
336
|
-
//
|
|
341
|
+
// 留给服务的那个进程:它起提炼
|
|
337
342
|
try {
|
|
338
343
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
339
|
-
fs.writeFileSync(path.join(STATE_DIR, 'last-sync.json'), `${JSON.stringify({ at: fmtStamp(), ok: !fail, seconds, results, changed }, null, 1)}\n`);
|
|
344
|
+
fs.writeFileSync(path.join(STATE_DIR, 'last-sync.json'), `${JSON.stringify({ at: fmtStamp(), ok: !fail, seconds: secs, results, changed }, null, 1)}\n`);
|
|
340
345
|
} catch {
|
|
341
346
|
// 写不下就算了:服务那边没有它就不提炼
|
|
342
347
|
}
|
|
343
348
|
const out = chunks.join('');
|
|
344
|
-
if (fail) return { ok: false, failed: `退出码 ${fail}:${tail(out, 300)}`, seconds, results, changed };
|
|
345
|
-
return { ok: true, seconds, detail: tail(chunks.join(''), 300).replace(/\n/g, ' · '), results, changed };
|
|
349
|
+
if (fail) return { ok: false, failed: `退出码 ${fail}:${tail(out, 300)}`, seconds: secs, results, changed };
|
|
350
|
+
return { ok: true, seconds: secs, detail: tail(chunks.join(''), 300).replace(/\n/g, ' · '), results, changed };
|
|
346
351
|
}
|
|
347
352
|
|
|
348
353
|
// 经消息渠道发一段文字。渠道留空时什么都不发(不算失败);发不出去记日志
|
|
@@ -356,34 +361,8 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
356
361
|
return r.ok;
|
|
357
362
|
}
|
|
358
363
|
|
|
359
|
-
//
|
|
360
|
-
|
|
361
|
-
const file = path.join(root, 'tasks', `${id}.md`);
|
|
362
|
-
if (!fs.existsSync(file)) return { ok: false, failed: `缺 ${path.relative(root, file)}` };
|
|
363
|
-
const prompt = fs.readFileSync(file, 'utf8');
|
|
364
|
-
const willPush = wantPush && cfg.push && !cfg.quiet.includes(id);
|
|
365
|
-
// 服务会替它推送时在指令末尾注明,免得它自己再发一遍
|
|
366
|
-
const full = willPush ? `${prompt}\n\n(这次运行由 work-rhythm rhythm 发起:你最后写的那段总结会被它推送给用户,你自己不要再发。)` : prompt;
|
|
367
|
-
const agent = makeAgent();
|
|
368
|
-
const t0 = Date.now();
|
|
369
|
-
const r = agent.run(full, { stateDir: STATE_DIR });
|
|
370
|
-
const seconds = Math.round((Date.now() - t0) / 1000);
|
|
371
|
-
if (r.failed) {
|
|
372
|
-
if (willPush) await push(`「${id}」没跑完:${r.failed}`);
|
|
373
|
-
return { ok: false, failed: r.failed, seconds };
|
|
374
|
-
}
|
|
375
|
-
let pushed = false;
|
|
376
|
-
if (willPush) {
|
|
377
|
-
let text = r.reply.trim();
|
|
378
|
-
const link = LINKS[id];
|
|
379
|
-
// 服务没在跑时地址打不开,不附
|
|
380
|
-
if (link && serviceAlive()) text += `\n\n→ ${link.label}:${baseUrl()}${link.path(fmtDate(new Date()))}`;
|
|
381
|
-
pushed = await push(text);
|
|
382
|
-
}
|
|
383
|
-
return { ok: true, seconds, summary: r.reply.trim(), pushed };
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
// 立刻跑一次:sync 或某个任务。结果打到标准输出,返回退出码
|
|
364
|
+
// 立刻跑一次:sync 或某个任务。结果打到标准输出,返回退出码。
|
|
365
|
+
// 任务和到点的一样走路由:这条命令的进程里建引擎,这句话变成触发 → 路由 → 执行者 → 路由,要发的话带 --push 才真发
|
|
387
366
|
async function runJob(id, wantPush) {
|
|
388
367
|
if (id === 'sync') {
|
|
389
368
|
const r = await runSync();
|
|
@@ -391,25 +370,48 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
391
370
|
process.stdout.write(r.ok ? `采集完成,用时 ${r.seconds} 秒。\n${r.detail}\n` : `采集失败:${r.failed}\n`);
|
|
392
371
|
return r.ok ? EXIT.OK : EXIT.FAILED;
|
|
393
372
|
}
|
|
394
|
-
const
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
const w = workerSpec();
|
|
399
|
-
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 });
|
|
400
|
-
saveState(store.data);
|
|
373
|
+
const file = path.join(root, 'tasks', `${id}.md`);
|
|
374
|
+
if (!fs.existsSync(file)) {
|
|
375
|
+
process.stdout.write(`没跑成:缺 ${path.relative(root, file)}\n`);
|
|
376
|
+
return { ok: false, failed: `缺 ${path.relative(root, file)}`, seconds: 0 };
|
|
401
377
|
}
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
const
|
|
409
|
-
|
|
378
|
+
// 路由和执行者没绑好就不跑:按「没配置好」退出,说清怎么绑
|
|
379
|
+
const agentProblems = agentsProblems();
|
|
380
|
+
if (agentProblems.length) throw new Fail(EXIT.NOT_CONFIGURED, `路由和执行者的 agent 配得不对:${agentProblems.join(';')}`);
|
|
381
|
+
const body = fs.readFileSync(file, 'utf8');
|
|
382
|
+
const quiet = cfg.quiet.includes(id);
|
|
383
|
+
const willPush = Boolean(wantPush) && cfg.push && !quiet;
|
|
384
|
+
const eng = makeEngine();
|
|
385
|
+
const texts = [];
|
|
386
|
+
// 不真发的时候,要发给用户的话交到这里
|
|
387
|
+
if (!willPush) eng.setSink((t) => texts.push(t));
|
|
388
|
+
// 和到点的那次不算同一条:去重键带上手动的时间
|
|
389
|
+
const key = `${id}@manual-${Date.now()}`;
|
|
390
|
+
eng.schedule({ id, key }, body, taskTitleOf(body), { manual: true });
|
|
391
|
+
const waited = await eng.waitIdle(RUN_WAIT_MS);
|
|
392
|
+
eng.setSink(null);
|
|
393
|
+
const t = Object.values(store.data.triggers || {}).find((x) => x.key === key) || null;
|
|
394
|
+
const w = t && t.worker;
|
|
395
|
+
if (!waited) {
|
|
396
|
+
process.stdout.write(`没等它做完:work-rhythm trigger list 看它的进度\n`);
|
|
397
|
+
return EXIT.FAILED;
|
|
398
|
+
}
|
|
399
|
+
if (!w || w.status !== 'ok') {
|
|
400
|
+
process.stdout.write(`没跑成:${(w && w.reason) || '路由没把它派出去'}\n`);
|
|
401
|
+
return EXIT.FAILED;
|
|
402
|
+
}
|
|
403
|
+
log('任务', `${id} 成功 用时 ${w.seconds}s${willPush ? ' 已推送' : ''}`);
|
|
404
|
+
const out = [];
|
|
405
|
+
if (quiet) out.push(`(静默的任务,不推送;结果写在工作目录里)`);
|
|
406
|
+
else if (willPush) out.push(`(已推送)`);
|
|
407
|
+
else out.push(`要发给用户的话(没发;带 --push 才真发):\n\n${texts.join('\n\n') || '(没有:路由觉得不用发。work-rhythm trigger show 看任务书和回执)'}`);
|
|
408
|
+
process.stdout.write(`${out.join('\n')}\n`);
|
|
409
|
+
return EXIT.OK;
|
|
410
410
|
}
|
|
411
|
+
// rhythm run 最多等多久:任务默认不限时(rhythm.task-timeout 为 0),这里给一个很大的数,等于一直等到它做完
|
|
412
|
+
const RUN_WAIT_MS = 7 * 24 * 3600 * 1000;
|
|
411
413
|
|
|
412
|
-
//
|
|
414
|
+
// 调度器用它:采集另起一个子进程跑,不堵住计时(采集是同步的脚本,会把事件循环堵住)
|
|
413
415
|
function startJob(job) {
|
|
414
416
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
415
417
|
const fd = fs.openSync(LOG_FILE, 'a');
|
|
@@ -470,16 +472,18 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
470
472
|
}
|
|
471
473
|
|
|
472
474
|
function route(req, res) {
|
|
473
|
-
//
|
|
475
|
+
// 唯一的写接口:本机页面 /agents 上保存路由和执行者的配置
|
|
476
|
+
if (req.method === 'POST' && String(req.url || '').split('?')[0] === '/agents') return saveRosterOnPage(req, res);
|
|
474
477
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
475
|
-
return send(res, 405, md.page('只支持打开页面', view.renderDocPage('只支持打开页面', '', { empty: '
|
|
478
|
+
return send(res, 405, md.page('只支持打开页面', view.renderDocPage('只支持打开页面', '', { empty: '这个服务只看记录,不改任何东西;唯一能写的是 agent 页上的配置。' }), navHtml()));
|
|
476
479
|
}
|
|
477
|
-
let
|
|
480
|
+
let url;
|
|
478
481
|
try {
|
|
479
|
-
|
|
482
|
+
url = new URL(req.url, 'http://127.0.0.1');
|
|
480
483
|
} catch {
|
|
481
484
|
return notFound(res, '地址不对');
|
|
482
485
|
}
|
|
486
|
+
const pathname = decodeURIComponent(url.pathname);
|
|
483
487
|
const now = fmtDate(new Date());
|
|
484
488
|
if (pathname === '/' || pathname === `/day/${now}`) {
|
|
485
489
|
const dates = dailyDates();
|
|
@@ -495,33 +499,35 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
495
499
|
const body = view.renderDaily({ date, weekday: weekdayOf(date), isToday: false, markdown: text, dates: dailyDates() });
|
|
496
500
|
return send(res, 200, md.page(date, body, navHtml('/')));
|
|
497
501
|
}
|
|
498
|
-
if (pathname === '/
|
|
499
|
-
|
|
500
|
-
|
|
502
|
+
if (pathname === '/rhythm') {
|
|
503
|
+
const docs = [
|
|
504
|
+
['工作规律', '04-patterns/WORK_RHYTHM.md'],
|
|
505
|
+
['个人分身', '04-patterns/PERSONA.md'],
|
|
506
|
+
['现场手册', '04-patterns/PLAYBOOK.md'],
|
|
507
|
+
].map(([title, rel]) => ({ title, rel, text: readText(path.join(root, rel)) })).filter((d) => d.text);
|
|
508
|
+
if (!docs.length) return notFound(res, '04-patterns/ 下还没有规律、分身或现场手册');
|
|
509
|
+
const body = docs.map((d) => view.renderDocPage(d.title, d.text, { subtitle: d.rel })).join('\n');
|
|
510
|
+
return send(res, 200, md.page('规律与手册', body, navHtml('/rhythm')));
|
|
511
|
+
}
|
|
501
512
|
if (pathname === '/goals') {
|
|
502
513
|
const files = listFiles(path.join(root, '05-goals'), (n) => /^[\w-]+\.md$/.test(n));
|
|
503
514
|
if (!files.length) return notFound(res, '还没有进行中的目标');
|
|
504
515
|
const items = files.map((name) => ({ name, text: readText(path.join(root, '05-goals', name)) }));
|
|
505
516
|
return send(res, 200, md.page('长期目标', view.renderGoals(items), navHtml('/goals')));
|
|
506
517
|
}
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
if (m) {
|
|
513
|
-
const file = path.join(root, '01-inbox', 'reports', m[1]);
|
|
514
|
-
if (!fs.existsSync(file)) return notFound(res, `没有 ${m[1]}`);
|
|
515
|
-
return send(res, 200, fs.readFileSync(file));
|
|
516
|
-
}
|
|
517
|
-
// 监控中心:同一份数据的页面和 JSON;交接文档只认 t-数字.md 和 t-数字.result.md 两种名字
|
|
518
|
+
// 配置路由和执行者的页面;给它取模型清单的接口;同一份配置的 JSON
|
|
519
|
+
if (pathname === '/agents') return send(res, 200, agentsPage());
|
|
520
|
+
if (pathname === '/agents.json') return send(res, 200, `${JSON.stringify(agentsData(), null, 1)}\n`, JSON_TYPE);
|
|
521
|
+
if (pathname === '/agents/models') return modelsOnPage(res, String(url.searchParams.get('agent') || '').trim());
|
|
522
|
+
// 监控中心:同一份数据的页面和 JSON;交接文档只认 t-数字.md、t-数字.result.md、t-数字.status.md 三种名字
|
|
518
523
|
if (pathname === '/monitor') return send(res, 200, monitorPage());
|
|
519
|
-
if (pathname === '/status.json') return send(res, 200, `${JSON.stringify(monitorData(), null, 1)}\n`,
|
|
524
|
+
if (pathname === '/status.json') return send(res, 200, `${JSON.stringify(monitorData(), null, 1)}\n`, JSON_TYPE);
|
|
520
525
|
m = /^\/handoff\/([^/]+)$/.exec(pathname);
|
|
521
526
|
if (m) {
|
|
522
527
|
const file = path.join(handoff.dir(root), m[1]);
|
|
523
528
|
if (!handoff.NAME_RE.test(m[1]) || !fs.existsSync(file)) return notFound(res, pathname);
|
|
524
|
-
|
|
529
|
+
const docName = m[1].endsWith('.result.md') ? '回执' : m[1].endsWith('.status.md') ? '过程' : '任务书';
|
|
530
|
+
return send(res, 200, md.page(m[1], view.renderDocPage(docName, readText(file), { subtitle: `${handoff.DIR}/${m[1]}`, meta: '<a class="day-btn" href="/monitor">← 监控中心</a>' }), navHtml('/monitor')));
|
|
525
531
|
}
|
|
526
532
|
return notFound(res, pathname);
|
|
527
533
|
}
|
|
@@ -548,7 +554,6 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
548
554
|
}
|
|
549
555
|
}
|
|
550
556
|
|
|
551
|
-
|
|
552
557
|
// 只绑 127.0.0.1:页面带着工作记录,不给别的机器看
|
|
553
558
|
const listen = (port) => new Promise((resolve, reject) => {
|
|
554
559
|
const server = http.createServer(handleRequest);
|
|
@@ -563,10 +568,328 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
563
568
|
return md.page(path.basename(full), view.renderDocPage(path.basename(full), fs.readFileSync(full, 'utf8')), navHtml());
|
|
564
569
|
}
|
|
565
570
|
|
|
566
|
-
// ----------------------------------------------------------------
|
|
571
|
+
// ---------------------------------------------------------------- agent 页:配置路由和执行者
|
|
567
572
|
const esc = (v) => md.escapeHtml(String(v === undefined || v === null ? '' : v));
|
|
568
|
-
|
|
569
|
-
|
|
573
|
+
|
|
574
|
+
// 网页服务写接口的令牌:随机串存在 01-inbox/_rhythm/web-token,页面脚本带着它,接口只认带对的。
|
|
575
|
+
// 别的网站的页面读不到 127.0.0.1 上的这个页面(同源策略),拿不到令牌,就用图片、表单点不动
|
|
576
|
+
function webToken() {
|
|
577
|
+
const found = readText(TOKEN_FILE).trim();
|
|
578
|
+
if (/^[0-9a-f]{32}$/.test(found)) return found;
|
|
579
|
+
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
580
|
+
const token = createHash('sha256').update(`${Date.now()}:${Math.random()}:${process.pid}`).digest('hex').slice(0, 32);
|
|
581
|
+
fs.writeFileSync(TOKEN_FILE, `${token}\n`, { mode: 0o600 });
|
|
582
|
+
return token;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// 一个 agent 的模型清单,给 /agents 的页面用。问一次要起一次那个 agent 自己的命令行(2026-12-04 实测 qoder --list-models 要 3.8 秒),
|
|
586
|
+
// 所以放在子进程里问,不卡这个服务(同步问的话这几秒里监控页、值守都停着);问到的留一分钟,出问题的只留 10 秒(登录完刷新一下就该好);
|
|
587
|
+
// 同一个 agent 正在问的时候,后来的请求共用它的结果
|
|
588
|
+
const modelLists = new Map(); // agent → { at, data, pending }
|
|
589
|
+
const listing = new Set(); // 正在问清单的子进程,服务停的时候收掉
|
|
590
|
+
const ASK_MODELS = 'const a = require(process.argv[1]); let r; try { r = a.modelList(process.argv[2], process.env); } catch (e) { r = { problem: String((e && e.message) || e) }; } process.stdout.write(JSON.stringify(r));';
|
|
591
|
+
function modelsOf(name) {
|
|
592
|
+
const kind = presetKind(name);
|
|
593
|
+
// 自定义命令没有清单可列,不用起子进程
|
|
594
|
+
if (kind === 'custom') return Promise.resolve(modelList(kind, env));
|
|
595
|
+
const hit = modelLists.get(name);
|
|
596
|
+
if (hit && hit.data && Date.now() - hit.at < (hit.data.problem ? 10000 : 60000)) return Promise.resolve(hit.data);
|
|
597
|
+
if (hit && hit.pending) return hit.pending;
|
|
598
|
+
const entry = hit || { at: 0, data: null, pending: null };
|
|
599
|
+
modelLists.set(name, entry);
|
|
600
|
+
entry.pending = new Promise((resolve) => {
|
|
601
|
+
const finish = (data) => {
|
|
602
|
+
entry.data = data;
|
|
603
|
+
entry.at = Date.now();
|
|
604
|
+
entry.pending = null;
|
|
605
|
+
resolve(data);
|
|
606
|
+
};
|
|
607
|
+
try {
|
|
608
|
+
const child = execFile(process.execPath, ['-e', ASK_MODELS, path.join(__dirname, 'agent.js'), kind], { cwd: root, env, timeout: 70000, maxBuffer: 8 * 1024 * 1024, killSignal: 'SIGKILL' }, (error, stdout, stderr) => {
|
|
609
|
+
listing.delete(child);
|
|
610
|
+
if (error) return finish({ problem: `取不到 ${name} 的模型清单:${error.killed ? '超过 70 秒没返回' : tail(String(stderr || error.message), 200)}` });
|
|
611
|
+
try {
|
|
612
|
+
const data = JSON.parse(stdout);
|
|
613
|
+
finish(data && typeof data === 'object' ? data : { problem: `取 ${name} 的模型清单:输出不是 JSON` });
|
|
614
|
+
} catch {
|
|
615
|
+
finish({ problem: `取 ${name} 的模型清单:输出不是 JSON` });
|
|
616
|
+
}
|
|
617
|
+
});
|
|
618
|
+
listing.add(child);
|
|
619
|
+
} catch (error) {
|
|
620
|
+
finish({ problem: `取不到 ${name} 的模型清单:${error.message}` });
|
|
621
|
+
}
|
|
622
|
+
});
|
|
623
|
+
return entry.pending;
|
|
624
|
+
}
|
|
625
|
+
// 页面脚本来取模型清单。这个是异步的,回包由它自己发
|
|
626
|
+
async function modelsOnPage(res, name) {
|
|
627
|
+
try {
|
|
628
|
+
send(res, 200, `${JSON.stringify({ agent: name, ...(await modelsOf(name)) }, null, 1)}\n`, JSON_TYPE);
|
|
629
|
+
} catch (error) {
|
|
630
|
+
send(res, 500, `${JSON.stringify({ agent: name, models: [], problem: `取不到模型清单:${error.message}` }, null, 1)}\n`, JSON_TYPE);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// 现在生效的配置和本机装了哪些 agent(页面和 /agents.json 是同一份)
|
|
635
|
+
function agentsData() {
|
|
636
|
+
const team = roster();
|
|
637
|
+
const installed = installedAgents(env).map((a) => ({ name: a.name, label: a.label, found: a.found, install: a.found ? '' : a.install, modelSupported: Boolean(MODEL_SUPPORT[a.name].model), effortSupported: Boolean(MODEL_SUPPORT[a.name].effort) }));
|
|
638
|
+
return { ...team, installed, efforts: EFFORTS, maxCount: rosterLib.MAX_COUNT, session: makeEngine().status().router.session, serviceAlive: serviceAlive() };
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// 一行里的一个下拉:agent(预置 + 自定义命令)、模型(清单 + 手动填写)、强度、数量。where 是 router 或者这组执行者的编号。
|
|
642
|
+
// 模型清单画页面的时候还没取(要起各个 agent 自己的命令行,慢,页面脚本随后取):配了的模型先当成一个选项画出来、选中它,
|
|
643
|
+
// 这样取清单前后选中的都是它;要是先画个「手动填写」占着,清单回来前那几秒看着就像模型丢了。
|
|
644
|
+
// 清单还没在手里的那几行,下拉末尾放一条取不了的提示(清单还在取),这会儿点开的人知道后面还有
|
|
645
|
+
function agentFields(where, e, count, listsPending = false) {
|
|
646
|
+
const installed = installedAgents(env);
|
|
647
|
+
const kind = presetKind(e.agent);
|
|
648
|
+
const options = installed.map((a) => `<option value="${esc(a.name)}"${a.name === e.agent ? ' selected' : ''}>${esc(a.name)}${a.found ? '' : '(没装)'}</option>`).join('');
|
|
649
|
+
const custom = e.agent && kind === 'custom';
|
|
650
|
+
const support = kind === 'custom' ? { model: true, effort: true } : MODEL_SUPPORT[kind];
|
|
651
|
+
return `<div class="ag-row" data-where="${esc(where)}">
|
|
652
|
+
<label class="ag-f">agent
|
|
653
|
+
<select class="ag-agent" aria-label="agent">${options}<option value="${CUSTOM}"${custom ? ' selected' : ''}>自定义命令…</option></select>
|
|
654
|
+
<input class="ag-custom" type="text" spellcheck="false" placeholder="一条命令:消息作为最后一个参数,回复打到标准输出" value="${custom ? esc(e.agent) : ''}"${custom ? '' : ' hidden'}>
|
|
655
|
+
</label>
|
|
656
|
+
<label class="ag-f">模型
|
|
657
|
+
<select class="ag-model" aria-label="模型"${support.model ? '' : ' disabled'}><option value="">默认(agent 自己的默认)</option>${e.model ? `<option value="${esc(e.model)}" selected>${esc(e.model)}</option>` : ''}<option value="${CUSTOM}">手动填写…</option>${listsPending && support.model ? '<option value="" disabled>(清单还在取,稍等…)</option>' : ''}</select>
|
|
658
|
+
<input class="ag-model-text" type="text" spellcheck="false" placeholder="模型 id" value="${esc(e.model)}" hidden>
|
|
659
|
+
<span class="ag-note"></span>
|
|
660
|
+
</label>
|
|
661
|
+
<label class="ag-f">强度
|
|
662
|
+
<select class="ag-effort" aria-label="思考强度"${support.effort ? '' : ' disabled'}><option value="">默认${where === 'router' ? '(low)' : ''}</option>${EFFORTS.map((x) => `<option value="${x}"${x === e.effort ? ' selected' : ''}>${x}${where === 'router' && x === 'low' ? '(默认)' : ''}</option>`).join('')}</select>
|
|
663
|
+
</label>
|
|
664
|
+
${count === undefined ? '' : `<label class="ag-f ag-f-n">数量
|
|
665
|
+
<input class="ag-count" type="number" min="1" max="${rosterLib.MAX_COUNT}" step="1" value="${Number(count) || 1}">
|
|
666
|
+
</label>`}
|
|
667
|
+
${where === 'router' ? '' : '<button type="button" class="ag-remove day-btn">去掉</button>'}
|
|
668
|
+
</div>`;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function agentsPage() {
|
|
672
|
+
const d = agentsData();
|
|
673
|
+
// 服务里已经有的模型清单直接带进页面(这些行的下拉一画出来就是全的);还没有的这就在后台取一遍(不等):下次打开页面、或者换 agent 的时候就是现成的
|
|
674
|
+
const prefilled = {};
|
|
675
|
+
for (const a of d.installed) {
|
|
676
|
+
const hit = modelLists.get(a.name);
|
|
677
|
+
if (hit && hit.data && !hit.data.problem) prefilled[a.name] = hit.data;
|
|
678
|
+
else if (a.found && a.modelSupported) modelsOf(a.name).catch(() => {});
|
|
679
|
+
}
|
|
680
|
+
const problems = rosterLook().problems;
|
|
681
|
+
const notes = rosterLook().notes;
|
|
682
|
+
const session = d.session ? (d.session.own ? `专属会话${d.session.id ? ` <code>${esc(d.session.id)}</code>` : '(还没开)'}` : `绑定 <code>${esc(d.session.id)}</code>`) : '—';
|
|
683
|
+
const total = d.workers.reduce((n, w) => n + w.count, 0);
|
|
684
|
+
const rows = d.workers.map((w) => agentFields(w.id, w, w.count, !prefilled[w.agent])).join('\n');
|
|
685
|
+
const body = `${view.pageHead('路由与执行者', { subtitle: `${d.source === 'file' ? esc(rosterLib.REL) : '还没保存过,现在是 local.env 老写法推出的那一组'} · 保存后对新的触发生效`, meta: '<a class="day-btn" href="/monitor">← 监控中心</a>' })}
|
|
686
|
+
${problems.length ? `<section class="card"><div class="card-head"><h2>有问题 <span class="muted">服务起不来,先解决</span></h2></div><ul>${problems.map((p) => `<li>${esc(p)}</li>`).join('')}</ul></section>` : ''}
|
|
687
|
+
<section class="card">
|
|
688
|
+
<div class="card-head"><h2>路由 <span class="muted">只做判断:给每条触发一个决定、写任务书,只读</span></h2><span class="pill">${d.serviceAlive ? '在跑' : '服务没在跑'}</span></div>
|
|
689
|
+
${agentFields('router', d.router, undefined, !prefilled[d.router.agent])}
|
|
690
|
+
<p class="muted">会话:${session} · 权限固定只读 · 一轮最多等 ${cfg.routerTimeout} 秒。默认用 flash 这类快模型、强度 low:路由每件事要跑两轮,慢了每件事都跟着慢。</p>
|
|
691
|
+
</section>
|
|
692
|
+
<section class="card">
|
|
693
|
+
<div class="card-head"><h2>执行者 <span class="muted">干活的一次性会话;数量是这一组同时跑几个;派活时路由自己挑组,没挑就派给第一组</span></h2><span class="pill" id="ag-count-pill">${d.workers.length} 组 · 共 ${total} 个</span></div>
|
|
694
|
+
<div id="ag-workers">
|
|
695
|
+
${rows}
|
|
696
|
+
</div>
|
|
697
|
+
<div class="ag-actions"><button type="button" class="day-btn" id="ag-add">+ 加一组</button></div>
|
|
698
|
+
</section>
|
|
699
|
+
<section class="card">
|
|
700
|
+
<div class="ag-actions"><button type="button" class="ag-save" id="ag-save">保存</button><span class="ag-status" id="ag-status" role="status"></span></div>
|
|
701
|
+
${notes.length ? `<p class="muted">注意:</p><ul class="ag-notes">${notes.map((n) => `<li>${esc(n)}</li>`).join('')}</ul>` : ''}
|
|
702
|
+
<p class="muted">写在 <code>${esc(rosterLib.REL)}</code>。在跑的那几件不受影响,新来的触发按新的配置走;改了 profile 里的时间或采集要 <code>work-rhythm rhythm restart</code>。</p>
|
|
703
|
+
</section>
|
|
704
|
+
<template id="ag-tpl">${agentFields('', rosterLib.entry(null), 1)}</template>
|
|
705
|
+
<script>(function(){
|
|
706
|
+
var TOKEN = ${JSON.stringify(webToken())};
|
|
707
|
+
var META = ${JSON.stringify(Object.fromEntries(d.installed.map((a) => [a.name, { label: a.label, found: a.found, modelSupported: a.modelSupported, effortSupported: a.effortSupported }])))};
|
|
708
|
+
var CUSTOM = ${JSON.stringify(CUSTOM)};
|
|
709
|
+
var MAX = ${Number(rosterLib.MAX_COUNT)};
|
|
710
|
+
var cache = ${JSON.stringify(prefilled).replace(/</g, '\\u003c')}; // agent → { models, problem }:服务里带的,加上这次页面里取到的(清单里的字来自各个 agent,< 转义掉,免得把 script 标签截断)
|
|
711
|
+
var pending = {}; // 正在取的清单,同一个 agent 共用一个请求
|
|
712
|
+
function q(sel, el) { return (el || document).querySelector(sel); }
|
|
713
|
+
function all(sel, el) { return [].slice.call((el || document).querySelectorAll(sel)); }
|
|
714
|
+
function opt(value, text) { var o = document.createElement('option'); o.value = value; o.textContent = text; return o; }
|
|
715
|
+
function agentOf(row) { var sel = q('.ag-agent', row); return sel.value === CUSTOM ? q('.ag-custom', row).value.trim() : sel.value; }
|
|
716
|
+
// 取一个 agent 的模型清单:取到过的直接给,正在取的共用同一个请求;没取到也不甩错误,给一份空的和一句原因
|
|
717
|
+
function load(name) {
|
|
718
|
+
if (cache[name]) return Promise.resolve(cache[name]);
|
|
719
|
+
if (!pending[name]) {
|
|
720
|
+
pending[name] = fetch('/agents/models?agent=' + encodeURIComponent(name)).then(function(r) { return r.json(); }).then(function(j) { cache[name] = j; return j; }, function() { delete pending[name]; return { models: [], problem: '取不到模型清单,可以手动填写' }; });
|
|
721
|
+
}
|
|
722
|
+
return pending[name];
|
|
723
|
+
}
|
|
724
|
+
// 配不了模型、强度的(zcode):那两个下拉禁用、值清空
|
|
725
|
+
function support(row) {
|
|
726
|
+
var m = META[agentOf(row)] || { modelSupported: true, effortSupported: true };
|
|
727
|
+
var model = q('.ag-model', row), effort = q('.ag-effort', row);
|
|
728
|
+
model.disabled = !m.modelSupported; effort.disabled = !m.effortSupported;
|
|
729
|
+
if (!m.modelSupported) model.value = ''; if (!m.effortSupported) effort.value = '';
|
|
730
|
+
}
|
|
731
|
+
// 取这个 agent 的模型清单,画进下拉。want 是要选中的模型(没有就选「默认」);清单里没有它就转成手动填写。
|
|
732
|
+
// waitEmpty:清单还没到手时先把下拉清成「正在取清单…」——换了 agent 才这么办,上一个 agent 的清单不能留着冒充;
|
|
733
|
+
// 页面刚画出来时不办:服务端已经把配了的模型当成一个选项放进去了,取清单前后选中的都是它
|
|
734
|
+
function fill(row, want, waitEmpty) {
|
|
735
|
+
var name = agentOf(row), model = q('.ag-model', row), text = q('.ag-model-text', row), note = q('.ag-note', row);
|
|
736
|
+
note.textContent = '';
|
|
737
|
+
var paint = function(list) {
|
|
738
|
+
while (model.options.length) model.remove(0);
|
|
739
|
+
model.add(opt('', '默认(agent 自己的默认)'));
|
|
740
|
+
// 同一个模型 id 在几家 provider 下都有(dsh 的清单):带 provider 的全名才分得清,就显示全名
|
|
741
|
+
var twice = function(id) { return list.filter(function(m) { return m.id === id; }).length > 1; };
|
|
742
|
+
list.forEach(function(m) { model.add(opt(m.full, (twice(m.id) ? m.full : m.id) + (m.name ? ' ' + m.name : '') + (m.fast ? ' · 快' : '') + (m.current ? ' · 它当前的默认' : ''))); });
|
|
743
|
+
model.add(opt(CUSTOM, '手动填写…'));
|
|
744
|
+
if (want && !list.some(function(m) { return m.full === want; })) { model.value = CUSTOM; text.value = want; } else model.value = want || '';
|
|
745
|
+
sync(row);
|
|
746
|
+
};
|
|
747
|
+
if (model.disabled) { paint([]); return; }
|
|
748
|
+
var shown = function(j) {
|
|
749
|
+
paint(j.models || []);
|
|
750
|
+
note.textContent = j.problem || ((j.models || []).length ? '' : '列不出模型清单,可以手动填写');
|
|
751
|
+
};
|
|
752
|
+
if (cache[name]) { shown(cache[name]); return; }
|
|
753
|
+
if (waitEmpty) {
|
|
754
|
+
while (model.options.length) model.remove(0);
|
|
755
|
+
model.add(opt('', '默认(agent 自己的默认)'));
|
|
756
|
+
var wait = opt('', '正在取清单…'); wait.disabled = true; wait.selected = true; model.add(wait);
|
|
757
|
+
text.hidden = true;
|
|
758
|
+
}
|
|
759
|
+
load(name).then(function(j) {
|
|
760
|
+
if (agentOf(row) !== name) return; // 取清单的功夫又换了 agent
|
|
761
|
+
shown(j);
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
// 手动填写的框:只在下拉选了「手动填写…」时显示
|
|
765
|
+
function sync(row) {
|
|
766
|
+
var model = q('.ag-model', row);
|
|
767
|
+
q('.ag-model-text', row).hidden = model.value !== CUSTOM;
|
|
768
|
+
}
|
|
769
|
+
function value(row) {
|
|
770
|
+
var model = q('.ag-model', row);
|
|
771
|
+
return { agent: agentOf(row), model: model.value === CUSTOM ? q('.ag-model-text', row).value.trim() : model.value, effort: q('.ag-effort', row).value };
|
|
772
|
+
}
|
|
773
|
+
function wire(row) {
|
|
774
|
+
q('.ag-agent', row).addEventListener('change', function() {
|
|
775
|
+
q('.ag-custom', row).hidden = q('.ag-agent', row).value !== CUSTOM;
|
|
776
|
+
support(row); fill(row, '', true);
|
|
777
|
+
});
|
|
778
|
+
q('.ag-custom', row).addEventListener('change', function() { support(row); fill(row, '', true); });
|
|
779
|
+
q('.ag-model', row).addEventListener('change', function() { sync(row); });
|
|
780
|
+
q('.ag-model-text', row).addEventListener('input', function() { sync(row); });
|
|
781
|
+
var remove = q('.ag-remove', row);
|
|
782
|
+
if (remove) remove.addEventListener('click', function() {
|
|
783
|
+
row.parentNode.removeChild(row);
|
|
784
|
+
if (!all('#ag-workers .ag-row').length) add();
|
|
785
|
+
});
|
|
786
|
+
support(row);
|
|
787
|
+
}
|
|
788
|
+
function add() {
|
|
789
|
+
var row = q('#ag-tpl').content.firstElementChild.cloneNode(true);
|
|
790
|
+
q('#ag-workers').appendChild(row);
|
|
791
|
+
wire(row); fill(row, '', true);
|
|
792
|
+
}
|
|
793
|
+
all('.ag-row').forEach(function(row) { wire(row); fill(row, q('.ag-model-text', row).value.trim()); });
|
|
794
|
+
// 装了的、能配模型的那些,清单先在后台取回来放着:换 agent 的时候下拉里直接就是清单,不用先等
|
|
795
|
+
Object.keys(META).forEach(function(name) { if (META[name].found && META[name].modelSupported) load(name); });
|
|
796
|
+
q('#ag-add').addEventListener('click', add);
|
|
797
|
+
q('#ag-save').addEventListener('click', function() {
|
|
798
|
+
var status = q('#ag-status');
|
|
799
|
+
var workers = all('#ag-workers .ag-row').map(function(row) {
|
|
800
|
+
var w = value(row), n = parseInt(q('.ag-count', row).value, 10);
|
|
801
|
+
w.id = row.getAttribute('data-where') || '';
|
|
802
|
+
w.count = isNaN(n) ? 0 : n;
|
|
803
|
+
return w;
|
|
804
|
+
});
|
|
805
|
+
status.className = 'ag-status'; status.textContent = '保存中…';
|
|
806
|
+
fetch('/agents', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Wrj-Token': TOKEN }, body: JSON.stringify({ router: value(q('.ag-row[data-where="router"]')), workers: workers }) })
|
|
807
|
+
.then(function(r) { return r.json().then(function(j) { return { ok: r.ok, j: j }; }); })
|
|
808
|
+
.then(function(x) {
|
|
809
|
+
if (x.ok) {
|
|
810
|
+
status.classList.add('is-ok');
|
|
811
|
+
status.textContent = '已保存' + (x.j.notes && x.j.notes.length ? '。注意:' + x.j.notes.join(';') : ',对新的触发生效。');
|
|
812
|
+
// 保存下来的编号写回每一行:再点保存时它们还是原来那几组,不会被当成又加了几组
|
|
813
|
+
var saved = x.j.workers || [];
|
|
814
|
+
var total = 0;
|
|
815
|
+
all('#ag-workers .ag-row').forEach(function(row, i) {
|
|
816
|
+
if (!saved[i]) return;
|
|
817
|
+
row.setAttribute('data-where', saved[i].id);
|
|
818
|
+
if (q('.ag-count', row)) q('.ag-count', row).value = saved[i].count;
|
|
819
|
+
total += saved[i].count;
|
|
820
|
+
});
|
|
821
|
+
q('#ag-count-pill').textContent = saved.length + ' 组 · 共 ' + total + ' 个';
|
|
822
|
+
} else {
|
|
823
|
+
status.classList.add('is-err');
|
|
824
|
+
status.textContent = '没保存:' + ((x.j.problems || []).join(';') || '接口没答应');
|
|
825
|
+
}
|
|
826
|
+
})
|
|
827
|
+
.catch(function(e) { status.classList.add('is-err'); status.textContent = '没发出去:' + e; });
|
|
828
|
+
});
|
|
829
|
+
})();</script>`;
|
|
830
|
+
return md.page('路由与执行者', body, navHtml('/agents'));
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
// 页面上点了保存:核对没有问题才写进名册。换了路由的 agent 就把它绑的会话清掉(别的 agent 接不上)。
|
|
834
|
+
// 靠三道闸防别的网页乱发:Host 头是本机(上面)、页面脚本里带的令牌、只认 JSON(跨站的表单发不出这个类型)
|
|
835
|
+
async function saveRosterOnPage(req, res) {
|
|
836
|
+
if (String(req.headers['x-wrj-token'] || '') !== webToken()) return send(res, 403, JSON.stringify({ problems: ['令牌不对:这个接口只给本机页面用'] }), JSON_TYPE);
|
|
837
|
+
if (!/application\/json/i.test(String(req.headers['content-type'] || ''))) return send(res, 415, JSON.stringify({ problems: ['只认 application/json'] }), JSON_TYPE);
|
|
838
|
+
const body = await new Promise((resolve) => {
|
|
839
|
+
let data = '';
|
|
840
|
+
req.on('data', (c) => {
|
|
841
|
+
data += c;
|
|
842
|
+
if (data.length > 64 * 1024) req.destroy();
|
|
843
|
+
});
|
|
844
|
+
req.on('end', () => resolve(data));
|
|
845
|
+
req.on('error', () => resolve(''));
|
|
846
|
+
});
|
|
847
|
+
let posted;
|
|
848
|
+
try {
|
|
849
|
+
posted = JSON.parse(body || '{}');
|
|
850
|
+
} catch (error) {
|
|
851
|
+
return send(res, 400, JSON.stringify({ problems: [`请求体不是 JSON:${error.message}`] }), JSON_TYPE);
|
|
852
|
+
}
|
|
853
|
+
const before = roster();
|
|
854
|
+
// 页面上的行:已有的带着编号,新加的没有;编号重复的或者不认识的当新组
|
|
855
|
+
const known = new Set(before.workers.map((w) => w.id));
|
|
856
|
+
const ids = new Set();
|
|
857
|
+
const rows = (Array.isArray(posted.workers) ? posted.workers : []).map((raw, i) => {
|
|
858
|
+
const id = typeof raw.id === 'string' && known.has(raw.id) && !ids.has(raw.id) ? raw.id : '';
|
|
859
|
+
if (id) ids.add(id);
|
|
860
|
+
return { raw, id, line: i + 1 };
|
|
861
|
+
});
|
|
862
|
+
let next = rosterLib.nextId(before.workers);
|
|
863
|
+
const workers = rows.map(({ raw, id }) => {
|
|
864
|
+
const use = id || next;
|
|
865
|
+
if (!id) next = rosterLib.nextId([...before.workers, { id: use }]);
|
|
866
|
+
return { id: use, agent: raw.agent, model: raw.model, effort: raw.effort, count: raw.count };
|
|
867
|
+
});
|
|
868
|
+
const clean = { router: rosterLib.entry(posted.router), workers: rosterLib.normalize({ workers }).workers };
|
|
869
|
+
const problems = [];
|
|
870
|
+
if (!clean.router.agent) problems.push('路由没选 agent');
|
|
871
|
+
rows.forEach(({ raw, line }) => { if (!String(raw.agent || '').trim()) problems.push(`第 ${line} 组执行者没选 agent`); });
|
|
872
|
+
workers.forEach((w) => {
|
|
873
|
+
if (!(Number.isInteger(w.count) && w.count >= 1 && w.count <= rosterLib.MAX_COUNT)) problems.push(`执行者 ${w.id}:数量要是 1 到 ${rosterLib.MAX_COUNT} 的整数(现在是 ${w.count})`);
|
|
874
|
+
});
|
|
875
|
+
if (!clean.workers.length) problems.push('至少留一组执行者');
|
|
876
|
+
problems.push(...rosterLib.inspect(root, env, { router: clean.router, workers: clean.workers, problems: [] }).problems);
|
|
877
|
+
if (problems.length) return send(res, 400, JSON.stringify({ problems }), JSON_TYPE);
|
|
878
|
+
const saved = rosterLib.saveRoster(root, clean);
|
|
879
|
+
if (before.router.agent !== clean.router.agent) writeLocalEnv(root, { YZJ_ROUTER_SESSION: '' });
|
|
880
|
+
// local.env 可能刚改过:重新读一遍,引擎下一次派活、下一轮路由就用新的
|
|
881
|
+
Object.assign(env, loadLocalEnv(root, env));
|
|
882
|
+
if (engine) engine.setEnv(env);
|
|
883
|
+
const notes = rosterLib.inspect(root, env, rosterLib.loadRoster(root, env)).notes;
|
|
884
|
+
notes.push(serviceAlive() ? '在跑的那几件不受影响,新来的触发按这份配置走' : '本地服务没在跑:下次启动才用上这份配置');
|
|
885
|
+
log('名册已保存', `路由=${clean.router.agent} 执行者=${clean.workers.map((w) => `${w.id} ${w.agent}×${w.count}`).join(',')}`);
|
|
886
|
+
// 把发下去的编号带回页面:新加的那几行记住自己的编号,再保存时还是原来那几组
|
|
887
|
+
return send(res, 200, JSON.stringify({ ok: true, notes, workers: saved.workers.map((w) => ({ id: w.id, count: w.count })) }), JSON_TYPE);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// ---------------------------------------------------------------- 监控中心
|
|
891
|
+
const fmtDur = (secs) => {
|
|
892
|
+
const n = Number(secs) || 0;
|
|
570
893
|
if (n < 60) return `${n} 秒`;
|
|
571
894
|
const m = Math.floor(n / 60);
|
|
572
895
|
return m >= 60 ? `${Math.floor(m / 60)} 小时 ${m % 60} 分` : `${m} 分 ${n % 60} 秒`;
|
|
@@ -577,19 +900,19 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
577
900
|
// 监控中心的数据:页面和 /status.json 是同一份
|
|
578
901
|
function monitorData() {
|
|
579
902
|
const alive = serviceAlive();
|
|
580
|
-
const st =
|
|
581
|
-
const
|
|
903
|
+
const st = makeEngine().status();
|
|
904
|
+
const team = roster();
|
|
582
905
|
return {
|
|
583
906
|
at: fmtStamp(),
|
|
584
|
-
service: { running: alive, pid: alive ? Number(readText(PID_FILE).trim()) : 0, since:
|
|
585
|
-
router: st
|
|
586
|
-
workers: st
|
|
587
|
-
agents: { router: { agent:
|
|
907
|
+
service: { running: alive, pid: alive ? Number(readText(PID_FILE).trim()) : 0, since: fmtStamp(new Date(since)), uptimeS: Math.round((Date.now() - since) / 1000), port: cfg.port, listen: botWanted(), sync: cfg.sync, push: cfg.push, notifyChannel: cfg.notifyChannel },
|
|
908
|
+
router: st.router,
|
|
909
|
+
workers: st.workers,
|
|
910
|
+
agents: { source: team.source, file: path.relative(root, team.file), router: { agent: team.router.agent, model: team.router.model, effort: rosterLib.routerEffort(team.router) }, workers: team.workers },
|
|
588
911
|
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) })),
|
|
589
912
|
triggers: Object.values(store.data.triggers || {}).sort((a, b) => b.at.localeCompare(a.at) || b.id.localeCompare(a.id)).slice(0, 100),
|
|
590
913
|
sources: sourceStatus(),
|
|
591
914
|
refinedAt: store.data.refinedAt || '',
|
|
592
|
-
config: {
|
|
915
|
+
config: { routerTimeout: cfg.routerTimeout, 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 },
|
|
593
916
|
};
|
|
594
917
|
}
|
|
595
918
|
|
|
@@ -630,7 +953,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
630
953
|
l && l.lastOk ? esc(l.lastOk.slice(5, 16)) : '<span class="muted">—</span>',
|
|
631
954
|
];
|
|
632
955
|
});
|
|
633
|
-
const refine =
|
|
956
|
+
const refine = ` · 有新数据就提炼${d.config.refine ? '' : '(关着)'},间隔 ${d.config.refineInterval} 分钟`;
|
|
634
957
|
const last = d.refinedAt ? ` · 上次提炼 ${esc(d.refinedAt.slice(5, 16))}` : '';
|
|
635
958
|
return `<section class="card">
|
|
636
959
|
<div class="card-head"><h2>订阅源 <span class="muted">采集 ${esc(d.service.sync || '不定时')}${refine}${last}</span></h2><span class="pill">${enabled} 个启用</span></div>
|
|
@@ -638,7 +961,6 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
638
961
|
</section>`;
|
|
639
962
|
}
|
|
640
963
|
|
|
641
|
-
// 监控中心的「待办卡片」一块:等我拿主意的事(DECISIONS.md 里「未答」的行)
|
|
642
964
|
function monitorPage() {
|
|
643
965
|
const d = monitorData();
|
|
644
966
|
const statusPill = (t) => {
|
|
@@ -650,25 +972,32 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
650
972
|
if (s === 'stopped') return '<span class="pill is-amber">叫停</span>';
|
|
651
973
|
return `<span class="pill">${esc(s)}</span>`;
|
|
652
974
|
};
|
|
975
|
+
const runningNow = new Map(d.workers.running.map((w) => [w.id, w]));
|
|
653
976
|
const workerCell = (t) => {
|
|
654
977
|
if (!t.worker) return '<span class="muted">—</span>';
|
|
655
|
-
|
|
656
|
-
const
|
|
978
|
+
// 在跑的带上执行者最近记的一步过程(它边做边追加的)
|
|
979
|
+
const step = runningNow.has(t.id) && runningNow.get(t.id).step ? `<br><span class="muted">最近一步:${esc(runningNow.get(t.id).step)}</span>` : '';
|
|
980
|
+
const extra = t.worker.status === 'failed' && t.worker.reason ? `<br><span class="muted">${esc(t.worker.reason)}</span>` : step;
|
|
981
|
+
const who = `<span class="muted">${esc(t.worker.id || '')} ${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>`;
|
|
657
982
|
return `${statusPill(t)}<br>${who}${extra}`;
|
|
658
983
|
};
|
|
659
|
-
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>');
|
|
984
|
+
const docs = (t) => (fs.existsSync(handoff.taskPath(root, t.id)) ? `<a href="/handoff/${t.id}.md">任务书</a>${fs.existsSync(handoff.statusPath(root, t.id)) ? ` · <a href="/handoff/${t.id}.status.md">过程</a>` : ''}${fs.existsSync(handoff.resultPath(root, t.id)) ? ` · <a href="/handoff/${t.id}.result.md">回执</a>` : ''}` : '<span class="muted">—</span>');
|
|
660
985
|
const decision = (t) => `<strong>${esc(t.decision || '—')}</strong>${t.reason ? `<br><span class="muted">${esc(t.reason)}</span>` : ''}`;
|
|
661
986
|
const byId = triggersById(store.data);
|
|
987
|
+
// 每件在跑的:起于几点、已跑了多久;多久没输出(只有边跑边输出的 agent 有);最近一步是什么、几秒前记的
|
|
662
988
|
const running = d.workers.running.map((w) => {
|
|
663
989
|
const t = byId[w.id];
|
|
664
990
|
const sid = t && t.worker && t.worker.sessionId ? ` <code>${esc(t.worker.sessionId)}</code>` : '';
|
|
665
|
-
|
|
991
|
+
const quiet = w.quietFor >= 60 ? `,${esc(fmtDur(w.quietFor))}没输出` : '';
|
|
992
|
+
const step = w.step ? `<br><span class="muted">最近一步:${esc(w.step)}${w.stepAge >= 60 ? `(${esc(fmtDur(w.stepAge))}前)` : ''}</span>` : '';
|
|
993
|
+
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))}${quiet}</span>${sid}${step}</li>`;
|
|
666
994
|
}).join('');
|
|
667
995
|
const rs = d.router;
|
|
668
996
|
const session = rs.session ? (rs.session.own ? `专属会话${rs.session.id ? ` <code>${esc(rs.session.id)}</code>` : '(还没开)'}` : `绑定 <code>${esc(rs.session.id)}</code>`) : '—';
|
|
669
997
|
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>';
|
|
670
|
-
const routerBadge = rs.
|
|
998
|
+
const routerBadge = rs.busy ? '<span class="pill is-accent"><span class="dot is-accent"></span>正在想</span>' : '<span class="pill is-green">开着</span>';
|
|
671
999
|
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>`;
|
|
1000
|
+
const groups = d.workers.groups.map((g) => `<li><code>${esc(g.id)}</code> ${esc(g.agent || '没绑')}${g.model ? ` · ${esc(g.model)}` : ''}${g.effort ? ` · ${esc(g.effort)}` : ''} <span class="muted">在跑 ${g.running} / 排队 ${g.queued} / 共 ${g.count} 个</span></li>`).join('');
|
|
672
1001
|
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>` })}
|
|
673
1002
|
<script>(function(){var b=document.getElementById('refresh');setInterval(function(){if(b.checked&&document.visibilityState==='visible')location.reload()},10000)})();</script>
|
|
674
1003
|
<div class="mon-grid">
|
|
@@ -679,15 +1008,15 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
679
1008
|
推送 ${d.service.push ? `开着(${esc(d.service.notifyChannel || '没配渠道')})` : '关着'} · 端口 <code>${d.service.port}</code></p>
|
|
680
1009
|
</section>
|
|
681
1010
|
<section class="card">
|
|
682
|
-
<div class="card-head"><h2
|
|
683
|
-
<p>${routerBadge}
|
|
684
|
-
<p class="muted">agent <code>${esc(d.agents.router.agent || '没绑')}</code>${d.agents.router.model ? ` · ${esc(d.agents.router.model)}` : ''}
|
|
1011
|
+
<div class="card-head"><h2>路由 <a class="day-btn" href="/agents">配置</a></h2></div>
|
|
1012
|
+
<p>${routerBadge}<br>${session}<br>排队 ${rs.queue} 条${rs.held ? ` · 攒着的汇报 ${rs.held} 条` : ''} · 今天 ${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>` : ''}</p>
|
|
1013
|
+
<p class="muted">agent <code>${esc(d.agents.router.agent || '没绑')}</code>${d.agents.router.model ? ` · ${esc(d.agents.router.model)}` : ''} · ${esc(d.agents.router.effort)} · 只读</p>
|
|
685
1014
|
</section>
|
|
686
1015
|
<section class="card">
|
|
687
|
-
<div class="card-head"><h2
|
|
1016
|
+
<div class="card-head"><h2>执行者 <a class="day-btn" href="/agents">配置</a></h2></div>
|
|
688
1017
|
<p>${workerBadge}${d.workers.queued.length ? `<br>排队 ${d.workers.queued.map(short).join(' ')}` : ''}</p>
|
|
1018
|
+
${groups ? `<ul class="ag-notes">${groups}</ul>` : ''}
|
|
689
1019
|
${running ? `<ul style="margin:6px 0 8px;padding-left:18px;font-size:13px">${running}</ul>` : ''}
|
|
690
|
-
<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>
|
|
691
1020
|
</section>
|
|
692
1021
|
</div>
|
|
693
1022
|
${sourcesCard(d)}
|
|
@@ -716,11 +1045,9 @@ ${sourcesCard(d)}
|
|
|
716
1045
|
]))}
|
|
717
1046
|
</section>
|
|
718
1047
|
<section class="card">
|
|
719
|
-
<div class="card-head"><h2>配置 <span class="muted"
|
|
1048
|
+
<div class="card-head"><h2>配置 <span class="muted">只读;agent 在 <a href="/agents">agent 页</a> 配</span></h2></div>
|
|
720
1049
|
<div class="mon-kv">
|
|
721
|
-
<span class="pill">router: ${d.config.router}</span>
|
|
722
1050
|
<span class="pill">router-timeout: ${d.config.routerTimeout}s</span>
|
|
723
|
-
<span class="pill">workers: ${d.config.workers}</span>
|
|
724
1051
|
<span class="pill">refine: ${d.config.refine}</span>
|
|
725
1052
|
<span class="pill">refine-interval: ${d.config.refineInterval}m</span>
|
|
726
1053
|
<span class="pill">task-timeout: ${d.config.taskTimeout ? `${d.config.taskTimeout}s` : '不限'}</span>
|
|
@@ -752,8 +1079,8 @@ ${sourcesCard(d)}
|
|
|
752
1079
|
if (!node || launchd.looksLikeElectron(node, {})) problems.push(`常驻的 plist 里绑的不是真正的 node(${node || '没读到'}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
753
1080
|
else if (!fs.existsSync(node)) problems.push(`常驻的 plist 里绑的 node 不在了(${node}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
754
1081
|
}
|
|
755
|
-
//
|
|
756
|
-
if (bot && botWanted()) problems.push(...
|
|
1082
|
+
// 值守开着的话,它的配置(渠道、钥匙串、我的 openId、路由和执行者的 agent)也要齐
|
|
1083
|
+
if (bot && botWanted()) problems.push(...botProblems());
|
|
757
1084
|
for (const [id, specText] of Object.entries(cfg.schedule)) {
|
|
758
1085
|
if (NOT_SERVICE_TASKS.includes(id)) continue;
|
|
759
1086
|
const spec = parseSpec(specText);
|
|
@@ -763,34 +1090,25 @@ ${sourcesCard(d)}
|
|
|
763
1090
|
}
|
|
764
1091
|
if (cfg.sync && parseSpec(cfg.sync).problem) problems.push(`采集的时间${parseSpec(cfg.sync).problem}`);
|
|
765
1092
|
if (!(cfg.port >= 1024 && cfg.port <= 65535)) problems.push(`rhythm.port 要是 1024 到 65535 之间的整数(现在是 ${cfg.port})`);
|
|
766
|
-
// 只有真有任务要跑时,agent
|
|
1093
|
+
// 只有真有任务要跑时,agent 和推送才必须配好;只采集、只看页面的用不着(值守的配置它自己查,见上)
|
|
767
1094
|
if (jobs().some((job) => job.kind === 'task' && job.hasPrompt)) {
|
|
768
|
-
problems.push(...
|
|
1095
|
+
problems.push(...agentsProblems());
|
|
769
1096
|
if (cfg.push && !cfg.notifyChannel) problems.push('rhythm.push 开着,但 preferences.notify 没配消息渠道:要么配一个,要么把 push 写成 false');
|
|
770
1097
|
}
|
|
771
|
-
//
|
|
1098
|
+
// 引擎的几个键:写了就得是正整数(没写用默认)
|
|
772
1099
|
for (const [key, name] of NEW_KEYS) {
|
|
773
1100
|
if (cfg.raw[key] !== undefined && !(Number.isInteger(Number(cfg.raw[key])) && Number(cfg.raw[key]) > 0)) problems.push(`${name} 要是正整数(现在是 ${cfg.raw[key]})`);
|
|
774
1101
|
}
|
|
775
|
-
// 路由开着时它的 agent 也要配得对(值守开着时 bot 那边查的是同一个)
|
|
776
|
-
if (cfg.router) problems.push(...routerDoctorProblems());
|
|
777
1102
|
// 启用着的源,采集脚本得在
|
|
778
1103
|
for (const x of sourceStatus()) if (x.missing) problems.push(`订阅源 ${x.id} 的采集脚本不存在:${x.collector}(sources.yaml 的 collector 写错了,或者脚本没放进 collectors/)`);
|
|
779
|
-
|
|
1104
|
+
// 值守开着时它的检查里已经带了路由和执行者的问题,别报两遍
|
|
1105
|
+
return [...new Set(problems)];
|
|
780
1106
|
}
|
|
781
1107
|
|
|
782
|
-
//
|
|
783
|
-
//
|
|
784
|
-
|
|
785
|
-
const r = roles(env).router;
|
|
786
|
-
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 })];
|
|
787
|
-
};
|
|
788
|
-
|
|
789
|
-
// 命令行里走一遍全流程(work-rhythm listen handle,路由开着时):在命令行的进程里建引擎,这句话变成一条触发,
|
|
790
|
-
// 要发的文字交给 sink(带 push 才真发),等到队列空、执行者都结束。返回 { id, texts } 或者 null(路由没开)
|
|
791
|
-
async function handle(text, { push: really = false, timeoutMs = 600000 } = {}) {
|
|
1108
|
+
// 命令行里走一遍全流程(work-rhythm listen handle):在命令行的进程里建引擎,这句话变成一条触发,
|
|
1109
|
+
// 要发的文字交给 sink(带 push 才真发),等到队列空、执行者都结束。返回 { id, texts }
|
|
1110
|
+
async function handle(text, { push: really = false, timeoutMs = 3600 * 1000 } = {}) {
|
|
792
1111
|
const eng = makeEngine();
|
|
793
|
-
if (!eng) return null;
|
|
794
1112
|
const texts = [];
|
|
795
1113
|
if (!really) eng.setSink((t) => texts.push(t));
|
|
796
1114
|
const t = eng.enqueue('message', { key: `handle-${Date.now()}`, msgId: 'handle', text, mode: (env.YZJ_BOT_AGENT_MODE || 'plan').trim() });
|
|
@@ -799,12 +1117,10 @@ ${sourcesCard(d)}
|
|
|
799
1117
|
return { id: t ? t.id : '', texts };
|
|
800
1118
|
}
|
|
801
1119
|
|
|
802
|
-
// 不算问题、但要让人知道的事(doctor
|
|
803
|
-
function doctorNotes(
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
const notes = cfg.router ? createAgent({ root, agent: r.agent, mode: 'plan', env, model: r.model, effort: r.effort }).notes() : [];
|
|
807
|
-
if (cfg.router && !cfg.notifyChannel && cfg.push) notes.push('推送关不掉又没配渠道:路由写给用户的话发不出去,只记日志');
|
|
1120
|
+
// 不算问题、但要让人知道的事(doctor 另起一行列出来,不影响退出码)
|
|
1121
|
+
function doctorNotes() {
|
|
1122
|
+
const notes = rosterLook().notes;
|
|
1123
|
+
if (!cfg.notifyChannel && cfg.push) notes.push('推送关不掉又没配渠道:路由写给用户的话发不出去,只记日志');
|
|
808
1124
|
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}`);
|
|
809
1125
|
return notes;
|
|
810
1126
|
}
|
|
@@ -819,24 +1135,23 @@ ${sourcesCard(d)}
|
|
|
819
1135
|
});
|
|
820
1136
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
821
1137
|
fs.writeFileSync(PID_FILE, `${process.pid}\n`);
|
|
822
|
-
|
|
1138
|
+
const team = roster();
|
|
1139
|
+
log('服务开始', `pid=${process.pid} 页面=${baseUrl()} 路由=${team.router.agent || '(没配)'}`);
|
|
823
1140
|
process.stdout.write(`页面:${baseUrl()} 停:work-rhythm rhythm stop\n`);
|
|
824
1141
|
|
|
825
1142
|
// 值守(机器人的收消息一半)也在这里跑:一个后台进程管定时任务、推送、网页和值守。默认开着(collectors/local.env 写 YZJ_BOT_LISTEN=0 才关);
|
|
826
1143
|
// 配置有问题不拦着服务起,只记一笔——定时任务和网页照常
|
|
827
1144
|
let bot = null;
|
|
828
1145
|
let botTask = null;
|
|
829
|
-
//
|
|
1146
|
+
// 引擎在这个进程里跑(触发 → 路由 → 执行者 → 汇报)。上次没跑完的执行者先补失败回执,交回路由
|
|
830
1147
|
const eng = makeEngine();
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
log('引擎开始', `路由=${roles(env).router.agent} 执行者=${workerSpec().agent} 并发=${cfg.workers}`);
|
|
835
|
-
}
|
|
1148
|
+
eng.recover();
|
|
1149
|
+
eng.tick();
|
|
1150
|
+
log('引擎开始', `路由=${team.router.agent || '没绑'} 执行者=${team.workers.map((w) => `${w.id} ${w.agent || '没绑'}×${w.count}`).join(',') || '没有'}`);
|
|
836
1151
|
if (botWanted()) {
|
|
837
|
-
bot = createBot({ root, env, onMessage:
|
|
838
|
-
const
|
|
839
|
-
if (
|
|
1152
|
+
bot = createBot({ root, env, onMessage: (m) => eng.message(m), resetSession: () => eng.resetSession(), say: (text) => eng.say(text), doctorAgent: () => eng.doctorProblems() });
|
|
1153
|
+
const botProbs = bot.doctorProblems();
|
|
1154
|
+
if (botProbs.length) log('值守没开', botProbs.join(';'));
|
|
840
1155
|
else {
|
|
841
1156
|
botTask = bot.run({ signals: false }).then(
|
|
842
1157
|
() => log('值守结束'),
|
|
@@ -845,6 +1160,7 @@ ${sourcesCard(d)}
|
|
|
845
1160
|
}
|
|
846
1161
|
}
|
|
847
1162
|
|
|
1163
|
+
// 只有采集走这条队列(另起子进程,采集是同步的脚本);到点的任务直接交给引擎
|
|
848
1164
|
const list = jobs();
|
|
849
1165
|
const state = store.data;
|
|
850
1166
|
let running = null;
|
|
@@ -855,32 +1171,25 @@ ${sourcesCard(d)}
|
|
|
855
1171
|
running = startJob(job);
|
|
856
1172
|
running.on('exit', (code) => {
|
|
857
1173
|
state.runs[job.id] = { at: fmtStamp(), ok: code === 0, code };
|
|
858
|
-
// 监控中心的运行记录
|
|
859
|
-
if (job.kind === 'task') {
|
|
860
|
-
const w = workerSpec();
|
|
861
|
-
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 });
|
|
862
|
-
}
|
|
863
1174
|
saveState(state);
|
|
864
1175
|
log('跑完', `${job.id} rc=${code}`);
|
|
865
1176
|
running = null;
|
|
866
1177
|
startNext();
|
|
867
1178
|
// 采集是有新数据才提炼:子进程把每个源的结果和「有没有新数据」留在 last-sync.json,这里交给引擎
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
eng.afterSync({ results: last.results || [], changed: Boolean(last.changed) });
|
|
875
|
-
}
|
|
876
|
-
} catch (error) {
|
|
877
|
-
log('采集结果读不了', error && error.message ? error.message : String(error));
|
|
1179
|
+
try {
|
|
1180
|
+
const file = path.join(STATE_DIR, 'last-sync.json');
|
|
1181
|
+
const st = fs.statSync(file);
|
|
1182
|
+
if (Date.now() - st.mtimeMs < 10 * 60 * 1000) {
|
|
1183
|
+
const last = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
1184
|
+
eng.afterSync({ results: last.results || [], changed: Boolean(last.changed) });
|
|
878
1185
|
}
|
|
1186
|
+
} catch (error) {
|
|
1187
|
+
log('采集结果读不了', error && error.message ? error.message : String(error));
|
|
879
1188
|
}
|
|
880
1189
|
});
|
|
881
1190
|
};
|
|
882
1191
|
const tick = () => {
|
|
883
|
-
|
|
1192
|
+
eng.tick();
|
|
884
1193
|
const now = new Date();
|
|
885
1194
|
for (const job of list) {
|
|
886
1195
|
for (const minute of timesOn(job.spec, now)) {
|
|
@@ -896,8 +1205,8 @@ ${sourcesCard(d)}
|
|
|
896
1205
|
continue;
|
|
897
1206
|
}
|
|
898
1207
|
log('到点', `${job.id} ${hhmm(at)}`);
|
|
899
|
-
if (job.kind === 'task'
|
|
900
|
-
//
|
|
1208
|
+
if (job.kind === 'task') {
|
|
1209
|
+
// 任务变成一条触发交给路由,由它挑一组执行者派出去
|
|
901
1210
|
const body = fs.readFileSync(path.join(root, 'tasks', `${job.id}.md`), 'utf8');
|
|
902
1211
|
eng.schedule({ id: job.id, key }, body, taskTitleOf(body));
|
|
903
1212
|
continue;
|
|
@@ -915,6 +1224,8 @@ ${sourcesCard(d)}
|
|
|
915
1224
|
clearInterval(timer);
|
|
916
1225
|
if (running) running.kill('SIGTERM');
|
|
917
1226
|
if (bot) bot.stop(signal);
|
|
1227
|
+
// 还在问模型清单的子进程收掉(它们的结果没人要了)
|
|
1228
|
+
listing.forEach((child) => child.kill());
|
|
918
1229
|
try {
|
|
919
1230
|
fs.unlinkSync(PID_FILE);
|
|
920
1231
|
} catch {
|
|
@@ -922,8 +1233,7 @@ ${sourcesCard(d)}
|
|
|
922
1233
|
}
|
|
923
1234
|
// 在跑的执行者是子进程,不收掉会留着:停掉它们(引擎里最多等 3 秒),再关网页
|
|
924
1235
|
const close = () => server.close(() => resolve());
|
|
925
|
-
|
|
926
|
-
else close();
|
|
1236
|
+
eng.shutdown().then(close, close);
|
|
927
1237
|
setTimeout(resolve, 4500).unref();
|
|
928
1238
|
};
|
|
929
1239
|
process.on('SIGINT', () => stop('SIGINT'));
|
|
@@ -938,7 +1248,10 @@ ${sourcesCard(d)}
|
|
|
938
1248
|
const server = await listen(port);
|
|
939
1249
|
process.stdout.write(`LISTENING http://127.0.0.1:${server.address().port}\n`);
|
|
940
1250
|
await new Promise((resolve) => {
|
|
941
|
-
const stop = () =>
|
|
1251
|
+
const stop = () => {
|
|
1252
|
+
listing.forEach((child) => child.kill());
|
|
1253
|
+
server.close(() => resolve());
|
|
1254
|
+
};
|
|
942
1255
|
process.on('SIGINT', stop);
|
|
943
1256
|
process.on('SIGTERM', stop);
|
|
944
1257
|
});
|
|
@@ -963,11 +1276,12 @@ ${sourcesCard(d)}
|
|
|
963
1276
|
const botLog = readText(path.join(root, '01-inbox', '_bot.log')).trim().split('\n');
|
|
964
1277
|
const lastBot = botLog.length && botLog[botLog.length - 1] ? botLog[botLog.length - 1] : '';
|
|
965
1278
|
lines.push(`值守:${botWanted() ? `开着${lastBot ? `,最近 ${lastBot}` : ''}` : '关着(collectors/local.env 的 YZJ_BOT_LISTEN=1 打开,改完 work-rhythm rhythm restart)'}`);
|
|
966
|
-
const
|
|
967
|
-
const w = workerSpec();
|
|
1279
|
+
const team = roster();
|
|
968
1280
|
const rounds = (store.data.rounds || []).filter((x) => x.at.startsWith(fmtDate(new Date()))).length;
|
|
969
|
-
lines.push(
|
|
970
|
-
|
|
1281
|
+
lines.push(team.router.agent
|
|
1282
|
+
? `路由:${team.router.agent}${team.router.model ? `,模型 ${team.router.model}` : ''},强度 ${rosterLib.routerEffort(team.router) || '用它自己的默认'},今天 ${rounds} 轮;实时的排队和在跑看 ${baseUrl()}/monitor`
|
|
1283
|
+
: `路由:没绑(work-rhythm agent bind router <名字>,或者在本机网页的 /agents 里配),今天 ${rounds} 轮;实时的排队和在跑看 ${baseUrl()}/monitor`);
|
|
1284
|
+
lines.push(`执行者:${team.workers.map((w) => `${w.id} ${w.agent || '没绑'}${w.model ? `(${w.model})` : ''}${w.effort ? ` ${w.effort}` : ''} ×${w.count}`).join(';') || '没有'};改在 ${baseUrl()}/agents`);
|
|
971
1285
|
// 订阅源:几个正常、谁在连着失败、谁还没跑过
|
|
972
1286
|
const srcs = sourceStatus().filter((x) => x.enabled);
|
|
973
1287
|
if (srcs.length) {
|
|
@@ -994,6 +1308,8 @@ ${sourcesCard(d)}
|
|
|
994
1308
|
due,
|
|
995
1309
|
monitorData,
|
|
996
1310
|
monitorPage,
|
|
1311
|
+
agentsData,
|
|
1312
|
+
agentsPage,
|
|
997
1313
|
doctorNotes,
|
|
998
1314
|
recordForTest: (id, r) => recordSources([{ id, ...r }]),
|
|
999
1315
|
handle,
|
|
@@ -1014,4 +1330,4 @@ ${sourcesCard(d)}
|
|
|
1014
1330
|
};
|
|
1015
1331
|
}
|
|
1016
1332
|
|
|
1017
|
-
module.exports = { createRhythm, loadConfig, parseSpec, LINKS, NOT_SERVICE_TASKS };
|
|
1333
|
+
module.exports = { createRhythm, loadConfig, parseSpec, LINKS, NOT_SERVICE_TASKS, ALWAYS_QUIET };
|