work-rhythm 0.2.21 → 0.2.22
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 +10 -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 +33 -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/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 +327 -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 +405 -170
- 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 +5 -2
- package/scripts/test/listen.test.js +190 -158
- package/scripts/test/playbook.test.js +106 -0
- package/scripts/test/rhythm.test.js +164 -54
- package/scripts/test/roster.test.js +155 -0
- package/scripts/test/router-helper.js +17 -2
- package/scripts/test/router.test.js +468 -194
- package/scripts/test/stubs.js +51 -4
- package/scripts/test/timeout.test.js +160 -59
- package/scripts/test/update.test.js +384 -0
- package/tasks/daily-persona.md +30 -11
- package/tasks/daily-plan.md +2 -1
- 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,10 +1,10 @@
|
|
|
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
10
|
const { spawn } = require('node:child_process');
|
|
@@ -13,9 +13,10 @@ 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,8 +31,10 @@ 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: '今天的文件' },
|
|
@@ -39,10 +42,12 @@ const LINKS = {
|
|
|
39
42
|
'evening-review': { path: (d) => `/day/${d}`, label: '今天的文件' },
|
|
40
43
|
'weekly-rhythm': { path: () => '/rhythm', label: '工作规律' },
|
|
41
44
|
'alerts-morning': { path: (d) => `/reports/${d}-alerts.html`, label: '告警晨报' },
|
|
42
|
-
// 一批新事件之后的「今日重点与待办」:地址给「决定」页(待办卡片在那里点),手机打不开,要在自己电脑上开
|
|
43
45
|
};
|
|
44
|
-
const NAV = [['/', '今日'], ['/carryover', '遗留'], ['/decisions', '决定'], ['/rhythm', '规律'], ['/goals', '目标'], ['/reports', '报告'], ['/monitor', '监控']];
|
|
46
|
+
const NAV = [['/', '今日'], ['/carryover', '遗留'], ['/decisions', '决定'], ['/rhythm', '规律'], ['/goals', '目标'], ['/reports', '报告'], ['/monitor', '监控'], ['/agents', 'agent']];
|
|
45
47
|
const NEW_KEYS = [['workers', 'rhythm.workers'], ['router-timeout', 'rhythm.router-timeout'], ['handoff-keep', 'rhythm.handoff-keep'], ['history-keep', 'rhythm.history-keep']];
|
|
48
|
+
const JSON_TYPE = 'application/json; charset=utf-8';
|
|
49
|
+
const EFFORTS = ['none', 'low', 'medium', 'high', 'max'];
|
|
50
|
+
const CUSTOM = '__custom__';
|
|
46
51
|
// 状态文件的骨架:done(跑过的任务)、runs(各任务最近一次)、seq(触发短号的序号)、triggers(近两天的触发)、history(运行记录)、rounds(路由的轮数)
|
|
47
52
|
const EMPTY_STATE = () => ({ done: {}, runs: {}, seq: 0, triggers: {}, history: [], rounds: [], sources: {}, refinedAt: '', syncDigest: { date: '', digest: '' } });
|
|
48
53
|
|
|
@@ -67,20 +72,19 @@ function loadConfig(root) {
|
|
|
67
72
|
sync: typeof rhythm.sync === 'string' ? rhythm.sync.trim() : '',
|
|
68
73
|
port: positiveInt(rhythm.port, 8787),
|
|
69
74
|
push: rhythm.push !== false,
|
|
70
|
-
quiet: asList(rhythm.quiet),
|
|
75
|
+
quiet: [...new Set([...ALWAYS_QUIET, ...asList(rhythm.quiet)])],
|
|
71
76
|
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
77
|
taskTimeout: seconds(rhythm['task-timeout'], 0),
|
|
78
|
+
// 手头还有别的活在跑时,先做完的汇报等一等(一起交回路由、回我的话合成一条),最多等这么多秒;0 = 不等,做完就汇报
|
|
79
|
+
mergeWait: seconds(rhythm['merge-wait'], 120),
|
|
76
80
|
syncTimeout: positiveInt(rhythm['sync-timeout'], 600),
|
|
77
81
|
notifyChannel: typeof preferences.notify === 'string' ? preferences.notify.trim() : '',
|
|
78
82
|
schedule,
|
|
79
|
-
//
|
|
80
|
-
router: rhythm.router === true,
|
|
83
|
+
// 路由和执行者用哪个 agent、模型、强度在名册里(docs/agents.md);这里只有引擎的几个旋钮
|
|
81
84
|
routerTimeout: positiveInt(rhythm['router-timeout'], 120),
|
|
82
|
-
|
|
83
|
-
|
|
85
|
+
// 老写法:没有 00-config/agents.json 时,那一组执行者同时跑几个(名册的 fromEnv 读它)
|
|
86
|
+
workers: positiveInt(rhythm.workers, rosterLib.DEFAULT_COUNT),
|
|
87
|
+
// 定时采集之后:有新数据就起一轮提炼(把 01-inbox 的新数据炼成事件)。两轮提炼之间至少隔 refine-interval 分钟
|
|
84
88
|
refine: rhythm.refine !== false,
|
|
85
89
|
refineInterval: positiveInt(rhythm['refine-interval'], 120),
|
|
86
90
|
handoffKeep: positiveInt(rhythm['handoff-keep'], 14),
|
|
@@ -115,11 +119,12 @@ function parseSpec(spec) {
|
|
|
115
119
|
return { problem: `看不懂时间写法「${s}」:支持 "08:50"、"Fri 16:30"、"工作日 09:00-18:00 每 30 分钟"` };
|
|
116
120
|
}
|
|
117
121
|
|
|
118
|
-
// 建一个本地服务对象。env 是设置(环境变量,上面盖一层 local.env
|
|
122
|
+
// 建一个本地服务对象。env 是设置(环境变量,上面盖一层 local.env)
|
|
119
123
|
function createRhythm({ root, env, packageRoot }) {
|
|
120
124
|
const STATE_DIR = path.join(root, '01-inbox', '_rhythm');
|
|
121
125
|
const STATE_FILE = path.join(STATE_DIR, 'state.json');
|
|
122
126
|
const PID_FILE = path.join(STATE_DIR, 'service.pid');
|
|
127
|
+
const TOKEN_FILE = path.join(STATE_DIR, 'web-token');
|
|
123
128
|
const LOG_FILE = path.join(root, '01-inbox', '_rhythm.log');
|
|
124
129
|
const LAUNCHD_LOG = path.join(root, '01-inbox', '_rhythm.launchd.log');
|
|
125
130
|
const ENTRY = path.join(packageRoot, 'scripts', 'work-rhythm.js');
|
|
@@ -130,7 +135,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
130
135
|
const since = Date.now();
|
|
131
136
|
// 状态(engine.js 也往里写):同一个进程里只有这一份
|
|
132
137
|
const store = { data: loadState(), save() { saveState(store.data); } };
|
|
133
|
-
// 引擎(路由 +
|
|
138
|
+
// 引擎(路由 + 执行者):同一个进程里只建一个,第一次用到才建
|
|
134
139
|
let engine = null;
|
|
135
140
|
const engineCfg = () => {
|
|
136
141
|
const idle = seconds(env.YZJ_BOT_IDLE, 180);
|
|
@@ -152,15 +157,15 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
152
157
|
};
|
|
153
158
|
};
|
|
154
159
|
const makeEngine = () => {
|
|
155
|
-
if (!cfg.router) return null;
|
|
156
160
|
if (!engine) engine = createEngine({ root, env, cfg: engineCfg(), log, push, state: store, since });
|
|
157
161
|
return engine;
|
|
158
162
|
};
|
|
159
|
-
//
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
163
|
+
// 名册:路由和有哪几组执行者。每次都现读,网页或命令行改了立刻看得到
|
|
164
|
+
const roster = () => rosterLib.loadRoster(root, env);
|
|
165
|
+
const rosterLook = () => rosterLib.inspect(root, env, roster());
|
|
166
|
+
const agentsProblems = () => rosterLook().problems;
|
|
167
|
+
// 值守的配置:渠道、钥匙串、我的 openId,加上路由和执行者的 agent
|
|
168
|
+
const botProblems = () => createBot({ root, env, onMessage: () => null, doctorAgent: agentsProblems }).doctorProblems();
|
|
164
169
|
|
|
165
170
|
// 某一天上不上班:以 work-rhythm today 为准(作息、放假都由它判),同一天只问一次
|
|
166
171
|
const workdayCache = {};
|
|
@@ -231,7 +236,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
231
236
|
}
|
|
232
237
|
}
|
|
233
238
|
|
|
234
|
-
// 写状态文件。命令行里的 listen handle / trigger fire 和服务可能同时写:先读盘上的那份,合起来再写——
|
|
239
|
+
// 写状态文件。命令行里的 listen handle / rhythm run / trigger fire 和服务可能同时写:先读盘上的那份,合起来再写——
|
|
235
240
|
// 触发按短号取并集(内存里的新),done / runs / rounds / history 也取并集,seq 取大的
|
|
236
241
|
function saveState(state) {
|
|
237
242
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
@@ -269,7 +274,6 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
269
274
|
}
|
|
270
275
|
|
|
271
276
|
// ---------------------------------------------------------------- 采集、任务、推送
|
|
272
|
-
// 跑一遍 sync(在同一个进程里),最多等 cfg.syncTimeout 秒
|
|
273
277
|
const todayStr = () => fmtDate(new Date());
|
|
274
278
|
|
|
275
279
|
// 今天 01-inbox/<源>/<日期>/ 下所有文件的名字和内容搓成的指纹:采集之后跟上次比,不一样就是有新数据(采集器每次都重写文件,所以不按修改时间算)
|
|
@@ -325,7 +329,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
325
329
|
const capture = { write: (s) => (chunks.push(String(s)), true) };
|
|
326
330
|
const results = [];
|
|
327
331
|
const fail = await sync.run([], { root, cwd: root, env, stdout: capture, stderr: capture, packageRoot }, { deadlineMs: t0 + cfg.syncTimeout * 1000, results });
|
|
328
|
-
const
|
|
332
|
+
const secs = Math.round((Date.now() - t0) / 1000);
|
|
329
333
|
recordSources(results);
|
|
330
334
|
// 有没有新数据:今天的指纹跟上一次比。没有文件也算一种指纹(空串),和上次不一样才是有新数据
|
|
331
335
|
const digest = inboxDigest(todayStr());
|
|
@@ -333,16 +337,16 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
333
337
|
const changed = Boolean(digest) && digest !== prev.digest;
|
|
334
338
|
store.data.syncDigest = { date: todayStr(), digest, at: fmtStamp() };
|
|
335
339
|
saveState(store.data);
|
|
336
|
-
//
|
|
340
|
+
// 留给服务的那个进程:它起提炼
|
|
337
341
|
try {
|
|
338
342
|
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`);
|
|
343
|
+
fs.writeFileSync(path.join(STATE_DIR, 'last-sync.json'), `${JSON.stringify({ at: fmtStamp(), ok: !fail, seconds: secs, results, changed }, null, 1)}\n`);
|
|
340
344
|
} catch {
|
|
341
345
|
// 写不下就算了:服务那边没有它就不提炼
|
|
342
346
|
}
|
|
343
347
|
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 };
|
|
348
|
+
if (fail) return { ok: false, failed: `退出码 ${fail}:${tail(out, 300)}`, seconds: secs, results, changed };
|
|
349
|
+
return { ok: true, seconds: secs, detail: tail(chunks.join(''), 300).replace(/\n/g, ' · '), results, changed };
|
|
346
350
|
}
|
|
347
351
|
|
|
348
352
|
// 经消息渠道发一段文字。渠道留空时什么都不发(不算失败);发不出去记日志
|
|
@@ -356,34 +360,8 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
356
360
|
return r.ok;
|
|
357
361
|
}
|
|
358
362
|
|
|
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 或某个任务。结果打到标准输出,返回退出码
|
|
363
|
+
// 立刻跑一次:sync 或某个任务。结果打到标准输出,返回退出码。
|
|
364
|
+
// 任务和到点的一样走路由:这条命令的进程里建引擎,这句话变成触发 → 路由 → 执行者 → 路由,要发的话带 --push 才真发
|
|
387
365
|
async function runJob(id, wantPush) {
|
|
388
366
|
if (id === 'sync') {
|
|
389
367
|
const r = await runSync();
|
|
@@ -391,25 +369,48 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
391
369
|
process.stdout.write(r.ok ? `采集完成,用时 ${r.seconds} 秒。\n${r.detail}\n` : `采集失败:${r.failed}\n`);
|
|
392
370
|
return r.ok ? EXIT.OK : EXIT.FAILED;
|
|
393
371
|
}
|
|
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);
|
|
372
|
+
const file = path.join(root, 'tasks', `${id}.md`);
|
|
373
|
+
if (!fs.existsSync(file)) {
|
|
374
|
+
process.stdout.write(`没跑成:缺 ${path.relative(root, file)}\n`);
|
|
375
|
+
return { ok: false, failed: `缺 ${path.relative(root, file)}`, seconds: 0 };
|
|
401
376
|
}
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
const
|
|
409
|
-
|
|
377
|
+
// 路由和执行者没绑好就不跑:按「没配置好」退出,说清怎么绑
|
|
378
|
+
const agentProblems = agentsProblems();
|
|
379
|
+
if (agentProblems.length) throw new Fail(EXIT.NOT_CONFIGURED, `路由和执行者的 agent 配得不对:${agentProblems.join(';')}`);
|
|
380
|
+
const body = fs.readFileSync(file, 'utf8');
|
|
381
|
+
const quiet = cfg.quiet.includes(id);
|
|
382
|
+
const willPush = Boolean(wantPush) && cfg.push && !quiet;
|
|
383
|
+
const eng = makeEngine();
|
|
384
|
+
const texts = [];
|
|
385
|
+
// 不真发的时候,要发给用户的话交到这里
|
|
386
|
+
if (!willPush) eng.setSink((t) => texts.push(t));
|
|
387
|
+
// 和到点的那次不算同一条:去重键带上手动的时间
|
|
388
|
+
const key = `${id}@manual-${Date.now()}`;
|
|
389
|
+
eng.schedule({ id, key }, body, taskTitleOf(body), { manual: true });
|
|
390
|
+
const waited = await eng.waitIdle(RUN_WAIT_MS);
|
|
391
|
+
eng.setSink(null);
|
|
392
|
+
const t = Object.values(store.data.triggers || {}).find((x) => x.key === key) || null;
|
|
393
|
+
const w = t && t.worker;
|
|
394
|
+
if (!waited) {
|
|
395
|
+
process.stdout.write(`没等它做完:work-rhythm trigger list 看它的进度\n`);
|
|
396
|
+
return EXIT.FAILED;
|
|
397
|
+
}
|
|
398
|
+
if (!w || w.status !== 'ok') {
|
|
399
|
+
process.stdout.write(`没跑成:${(w && w.reason) || '路由没把它派出去'}\n`);
|
|
400
|
+
return EXIT.FAILED;
|
|
401
|
+
}
|
|
402
|
+
log('任务', `${id} 成功 用时 ${w.seconds}s${willPush ? ' 已推送' : ''}`);
|
|
403
|
+
const out = [];
|
|
404
|
+
if (quiet) out.push(`(静默的任务,不推送;结果写在工作目录里)`);
|
|
405
|
+
else if (willPush) out.push(`(已推送)`);
|
|
406
|
+
else out.push(`要发给用户的话(没发;带 --push 才真发):\n\n${texts.join('\n\n') || '(没有:路由觉得不用发。work-rhythm trigger show 看任务书和回执)'}`);
|
|
407
|
+
process.stdout.write(`${out.join('\n')}\n`);
|
|
408
|
+
return EXIT.OK;
|
|
410
409
|
}
|
|
410
|
+
// rhythm run 最多等多久:任务默认不限时(rhythm.task-timeout 为 0),这里给一个很大的数,等于一直等到它做完
|
|
411
|
+
const RUN_WAIT_MS = 7 * 24 * 3600 * 1000;
|
|
411
412
|
|
|
412
|
-
//
|
|
413
|
+
// 调度器用它:采集另起一个子进程跑,不堵住计时(采集是同步的脚本,会把事件循环堵住)
|
|
413
414
|
function startJob(job) {
|
|
414
415
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
415
416
|
const fd = fs.openSync(LOG_FILE, 'a');
|
|
@@ -470,16 +471,18 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
470
471
|
}
|
|
471
472
|
|
|
472
473
|
function route(req, res) {
|
|
473
|
-
//
|
|
474
|
+
// 唯一的写接口:本机页面 /agents 上保存路由和执行者的配置
|
|
475
|
+
if (req.method === 'POST' && String(req.url || '').split('?')[0] === '/agents') return saveRosterOnPage(req, res);
|
|
474
476
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
475
|
-
return send(res, 405, md.page('只支持打开页面', view.renderDocPage('只支持打开页面', '', { empty: '
|
|
477
|
+
return send(res, 405, md.page('只支持打开页面', view.renderDocPage('只支持打开页面', '', { empty: '这个服务只看记录,不改任何东西;唯一能写的是 agent 页上的配置。' }), navHtml()));
|
|
476
478
|
}
|
|
477
|
-
let
|
|
479
|
+
let url;
|
|
478
480
|
try {
|
|
479
|
-
|
|
481
|
+
url = new URL(req.url, 'http://127.0.0.1');
|
|
480
482
|
} catch {
|
|
481
483
|
return notFound(res, '地址不对');
|
|
482
484
|
}
|
|
485
|
+
const pathname = decodeURIComponent(url.pathname);
|
|
483
486
|
const now = fmtDate(new Date());
|
|
484
487
|
if (pathname === '/' || pathname === `/day/${now}`) {
|
|
485
488
|
const dates = dailyDates();
|
|
@@ -514,14 +517,22 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
514
517
|
if (!fs.existsSync(file)) return notFound(res, `没有 ${m[1]}`);
|
|
515
518
|
return send(res, 200, fs.readFileSync(file));
|
|
516
519
|
}
|
|
517
|
-
//
|
|
520
|
+
// 配置路由和执行者的页面;给它取模型清单的接口;同一份配置的 JSON
|
|
521
|
+
if (pathname === '/agents') return send(res, 200, agentsPage());
|
|
522
|
+
if (pathname === '/agents.json') return send(res, 200, `${JSON.stringify(agentsData(), null, 1)}\n`, JSON_TYPE);
|
|
523
|
+
if (pathname === '/agents/models') {
|
|
524
|
+
const name = String(url.searchParams.get('agent') || '').trim();
|
|
525
|
+
return send(res, 200, `${JSON.stringify({ agent: name, ...modelList(presetKind(name), env) }, null, 1)}\n`, JSON_TYPE);
|
|
526
|
+
}
|
|
527
|
+
// 监控中心:同一份数据的页面和 JSON;交接文档只认 t-数字.md、t-数字.result.md、t-数字.status.md 三种名字
|
|
518
528
|
if (pathname === '/monitor') return send(res, 200, monitorPage());
|
|
519
|
-
if (pathname === '/status.json') return send(res, 200, `${JSON.stringify(monitorData(), null, 1)}\n`,
|
|
529
|
+
if (pathname === '/status.json') return send(res, 200, `${JSON.stringify(monitorData(), null, 1)}\n`, JSON_TYPE);
|
|
520
530
|
m = /^\/handoff\/([^/]+)$/.exec(pathname);
|
|
521
531
|
if (m) {
|
|
522
532
|
const file = path.join(handoff.dir(root), m[1]);
|
|
523
533
|
if (!handoff.NAME_RE.test(m[1]) || !fs.existsSync(file)) return notFound(res, pathname);
|
|
524
|
-
|
|
534
|
+
const docName = m[1].endsWith('.result.md') ? '回执' : m[1].endsWith('.status.md') ? '过程' : '任务书';
|
|
535
|
+
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
536
|
}
|
|
526
537
|
return notFound(res, pathname);
|
|
527
538
|
}
|
|
@@ -548,7 +559,6 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
548
559
|
}
|
|
549
560
|
}
|
|
550
561
|
|
|
551
|
-
|
|
552
562
|
// 只绑 127.0.0.1:页面带着工作记录,不给别的机器看
|
|
553
563
|
const listen = (port) => new Promise((resolve, reject) => {
|
|
554
564
|
const server = http.createServer(handleRequest);
|
|
@@ -563,10 +573,247 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
563
573
|
return md.page(path.basename(full), view.renderDocPage(path.basename(full), fs.readFileSync(full, 'utf8')), navHtml());
|
|
564
574
|
}
|
|
565
575
|
|
|
566
|
-
// ----------------------------------------------------------------
|
|
576
|
+
// ---------------------------------------------------------------- agent 页:配置路由和执行者
|
|
567
577
|
const esc = (v) => md.escapeHtml(String(v === undefined || v === null ? '' : v));
|
|
568
|
-
|
|
569
|
-
|
|
578
|
+
|
|
579
|
+
// 网页服务写接口的令牌:随机串存在 01-inbox/_rhythm/web-token,页面脚本带着它,接口只认带对的。
|
|
580
|
+
// 别的网站的页面读不到 127.0.0.1 上的这个页面(同源策略),拿不到令牌,就用图片、表单点不动
|
|
581
|
+
function webToken() {
|
|
582
|
+
const found = readText(TOKEN_FILE).trim();
|
|
583
|
+
if (/^[0-9a-f]{32}$/.test(found)) return found;
|
|
584
|
+
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
585
|
+
const token = createHash('sha256').update(`${Date.now()}:${Math.random()}:${process.pid}`).digest('hex').slice(0, 32);
|
|
586
|
+
fs.writeFileSync(TOKEN_FILE, `${token}\n`, { mode: 0o600 });
|
|
587
|
+
return token;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// 现在生效的配置和本机装了哪些 agent(页面和 /agents.json 是同一份)
|
|
591
|
+
function agentsData() {
|
|
592
|
+
const team = roster();
|
|
593
|
+
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) }));
|
|
594
|
+
return { ...team, installed, efforts: EFFORTS, maxCount: rosterLib.MAX_COUNT, session: makeEngine().status().router.session, serviceAlive: serviceAlive() };
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// 一行里的一个下拉:agent(预置 + 自定义命令)、模型(清单 + 手动填写)、强度、数量。where 是 router 或者这组执行者的编号
|
|
598
|
+
function agentFields(where, e, count) {
|
|
599
|
+
const installed = installedAgents(env);
|
|
600
|
+
const kind = presetKind(e.agent);
|
|
601
|
+
const options = installed.map((a) => `<option value="${esc(a.name)}"${a.name === e.agent ? ' selected' : ''}>${esc(a.name)}${a.found ? '' : '(没装)'}</option>`).join('');
|
|
602
|
+
const custom = e.agent && kind === 'custom';
|
|
603
|
+
const support = kind === 'custom' ? { model: true, effort: true } : MODEL_SUPPORT[kind];
|
|
604
|
+
return `<div class="ag-row" data-where="${esc(where)}">
|
|
605
|
+
<label class="ag-f">agent
|
|
606
|
+
<select class="ag-agent" aria-label="agent">${options}<option value="${CUSTOM}"${custom ? ' selected' : ''}>自定义命令…</option></select>
|
|
607
|
+
<input class="ag-custom" type="text" spellcheck="false" placeholder="一条命令:消息作为最后一个参数,回复打到标准输出" value="${custom ? esc(e.agent) : ''}"${custom ? '' : ' hidden'}>
|
|
608
|
+
</label>
|
|
609
|
+
<label class="ag-f">模型
|
|
610
|
+
<select class="ag-model" aria-label="模型"${support.model ? '' : ' disabled'}><option value="">默认(agent 自己的默认)</option>${e.model ? `<option value="${CUSTOM}" selected>手动填写…</option>` : ''}</select>
|
|
611
|
+
<input class="ag-model-text" type="text" spellcheck="false" placeholder="模型 id" value="${esc(e.model)}"${e.model ? '' : ' hidden'}>
|
|
612
|
+
<span class="ag-note"></span>
|
|
613
|
+
</label>
|
|
614
|
+
<label class="ag-f">强度
|
|
615
|
+
<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>
|
|
616
|
+
</label>
|
|
617
|
+
${count === undefined ? '' : `<label class="ag-f ag-f-n">数量
|
|
618
|
+
<input class="ag-count" type="number" min="1" max="${rosterLib.MAX_COUNT}" step="1" value="${Number(count) || 1}">
|
|
619
|
+
</label>`}
|
|
620
|
+
${where === 'router' ? '' : '<button type="button" class="ag-remove day-btn">去掉</button>'}
|
|
621
|
+
</div>`;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function agentsPage() {
|
|
625
|
+
const d = agentsData();
|
|
626
|
+
const problems = rosterLook().problems;
|
|
627
|
+
const notes = rosterLook().notes;
|
|
628
|
+
const session = d.session ? (d.session.own ? `专属会话${d.session.id ? ` <code>${esc(d.session.id)}</code>` : '(还没开)'}` : `绑定 <code>${esc(d.session.id)}</code>`) : '—';
|
|
629
|
+
const total = d.workers.reduce((n, w) => n + w.count, 0);
|
|
630
|
+
const rows = d.workers.map((w) => agentFields(w.id, w, w.count)).join('\n');
|
|
631
|
+
const body = `${view.pageHead('路由与执行者', { subtitle: `${d.source === 'file' ? esc(rosterLib.REL) : '还没保存过,现在是 local.env 老写法推出的那一组'} · 保存后对新的触发生效`, meta: '<a class="day-btn" href="/monitor">← 监控中心</a>' })}
|
|
632
|
+
${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>` : ''}
|
|
633
|
+
<section class="card">
|
|
634
|
+
<div class="card-head"><h2>路由 <span class="muted">只做判断:给每条触发一个决定、写任务书,只读</span></h2><span class="pill">${d.serviceAlive ? '在跑' : '服务没在跑'}</span></div>
|
|
635
|
+
${agentFields('router', d.router)}
|
|
636
|
+
<p class="muted">会话:${session} · 权限固定只读 · 一轮最多等 ${cfg.routerTimeout} 秒。默认用 flash 这类快模型、强度 low:路由每件事要跑两轮,慢了每件事都跟着慢。</p>
|
|
637
|
+
</section>
|
|
638
|
+
<section class="card">
|
|
639
|
+
<div class="card-head"><h2>执行者 <span class="muted">干活的一次性会话;数量是这一组同时跑几个;派活时路由自己挑组,没挑就派给第一组</span></h2><span class="pill" id="ag-count-pill">${d.workers.length} 组 · 共 ${total} 个</span></div>
|
|
640
|
+
<div id="ag-workers">
|
|
641
|
+
${rows}
|
|
642
|
+
</div>
|
|
643
|
+
<div class="ag-actions"><button type="button" class="day-btn" id="ag-add">+ 加一组</button></div>
|
|
644
|
+
</section>
|
|
645
|
+
<section class="card">
|
|
646
|
+
<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>
|
|
647
|
+
${notes.length ? `<p class="muted">注意:</p><ul class="ag-notes">${notes.map((n) => `<li>${esc(n)}</li>`).join('')}</ul>` : ''}
|
|
648
|
+
<p class="muted">写在 <code>${esc(rosterLib.REL)}</code>。在跑的那几件不受影响,新来的触发按新的配置走;改了 profile 里的时间或采集要 <code>work-rhythm rhythm restart</code>。</p>
|
|
649
|
+
</section>
|
|
650
|
+
<template id="ag-tpl">${agentFields('', rosterLib.entry(null), 1)}</template>
|
|
651
|
+
<script>(function(){
|
|
652
|
+
var TOKEN = ${JSON.stringify(webToken())};
|
|
653
|
+
var META = ${JSON.stringify(Object.fromEntries(d.installed.map((a) => [a.name, { label: a.label, modelSupported: a.modelSupported, effortSupported: a.effortSupported }])))};
|
|
654
|
+
var CUSTOM = ${JSON.stringify(CUSTOM)};
|
|
655
|
+
var MAX = ${Number(rosterLib.MAX_COUNT)};
|
|
656
|
+
var cache = {};
|
|
657
|
+
function q(sel, el) { return (el || document).querySelector(sel); }
|
|
658
|
+
function all(sel, el) { return [].slice.call((el || document).querySelectorAll(sel)); }
|
|
659
|
+
function opt(value, text) { var o = document.createElement('option'); o.value = value; o.textContent = text; return o; }
|
|
660
|
+
function agentOf(row) { var sel = q('.ag-agent', row); return sel.value === CUSTOM ? q('.ag-custom', row).value.trim() : sel.value; }
|
|
661
|
+
// 配不了模型、强度的(zcode):那两个下拉禁用、值清空
|
|
662
|
+
function support(row) {
|
|
663
|
+
var m = META[agentOf(row)] || { modelSupported: true, effortSupported: true };
|
|
664
|
+
var model = q('.ag-model', row), effort = q('.ag-effort', row);
|
|
665
|
+
model.disabled = !m.modelSupported; effort.disabled = !m.effortSupported;
|
|
666
|
+
if (!m.modelSupported) model.value = ''; if (!m.effortSupported) effort.value = '';
|
|
667
|
+
}
|
|
668
|
+
// 取这个 agent 的模型清单,画进下拉。want 是要选中的模型(没有就选「默认」);清单里没有它就转成手动填写
|
|
669
|
+
function fill(row, want) {
|
|
670
|
+
var name = agentOf(row), model = q('.ag-model', row), text = q('.ag-model-text', row), note = q('.ag-note', row);
|
|
671
|
+
var paint = function(list) {
|
|
672
|
+
while (model.options.length) model.remove(0);
|
|
673
|
+
model.add(opt('', '默认(agent 自己的默认)'));
|
|
674
|
+
// 同一个模型 id 在几家 provider 下都有(dsh 的清单):带 provider 的全名才分得清,就显示全名
|
|
675
|
+
var twice = function(id) { return list.filter(function(m) { return m.id === id; }).length > 1; };
|
|
676
|
+
list.forEach(function(m) { model.add(opt(m.full, (twice(m.id) ? m.full : m.id) + (m.name ? ' ' + m.name : '') + (m.fast ? ' · 快' : '') + (m.current ? ' · 它当前的默认' : ''))); });
|
|
677
|
+
model.add(opt(CUSTOM, '手动填写…'));
|
|
678
|
+
if (want && !list.some(function(m) { return m.full === want; })) { model.value = CUSTOM; text.value = want; } else model.value = want || '';
|
|
679
|
+
sync(row);
|
|
680
|
+
};
|
|
681
|
+
if (model.disabled) { paint([]); return; }
|
|
682
|
+
if (cache[name]) { paint(cache[name]); return; }
|
|
683
|
+
fetch('/agents/models?agent=' + encodeURIComponent(name)).then(function(r) { return r.json(); }).then(function(j) {
|
|
684
|
+
cache[name] = j.models || [];
|
|
685
|
+
if (agentOf(row) !== name) return; // 取清单的功夫又换了 agent
|
|
686
|
+
paint(cache[name]);
|
|
687
|
+
note.textContent = j.problem || (cache[name].length ? '' : '列不出模型清单,可以手动填写');
|
|
688
|
+
}).catch(function() { note.textContent = '取不到模型清单,可以手动填写'; });
|
|
689
|
+
}
|
|
690
|
+
// 手动填写的框:只在下拉选了「手动填写…」时显示
|
|
691
|
+
function sync(row) {
|
|
692
|
+
var model = q('.ag-model', row);
|
|
693
|
+
q('.ag-model-text', row).hidden = model.value !== CUSTOM;
|
|
694
|
+
}
|
|
695
|
+
function value(row) {
|
|
696
|
+
var model = q('.ag-model', row);
|
|
697
|
+
return { agent: agentOf(row), model: model.value === CUSTOM ? q('.ag-model-text', row).value.trim() : model.value, effort: q('.ag-effort', row).value };
|
|
698
|
+
}
|
|
699
|
+
function wire(row) {
|
|
700
|
+
q('.ag-agent', row).addEventListener('change', function() {
|
|
701
|
+
q('.ag-custom', row).hidden = q('.ag-agent', row).value !== CUSTOM;
|
|
702
|
+
support(row); fill(row, '');
|
|
703
|
+
});
|
|
704
|
+
q('.ag-custom', row).addEventListener('change', function() { support(row); fill(row, ''); });
|
|
705
|
+
q('.ag-model', row).addEventListener('change', function() { sync(row); });
|
|
706
|
+
q('.ag-model-text', row).addEventListener('input', function() { sync(row); });
|
|
707
|
+
var remove = q('.ag-remove', row);
|
|
708
|
+
if (remove) remove.addEventListener('click', function() {
|
|
709
|
+
row.parentNode.removeChild(row);
|
|
710
|
+
if (!all('#ag-workers .ag-row').length) add();
|
|
711
|
+
});
|
|
712
|
+
support(row);
|
|
713
|
+
}
|
|
714
|
+
function add() {
|
|
715
|
+
var row = q('#ag-tpl').content.firstElementChild.cloneNode(true);
|
|
716
|
+
q('#ag-workers').appendChild(row);
|
|
717
|
+
wire(row); fill(row, '');
|
|
718
|
+
}
|
|
719
|
+
all('.ag-row').forEach(function(row) { wire(row); fill(row, q('.ag-model-text', row).value.trim()); });
|
|
720
|
+
q('#ag-add').addEventListener('click', add);
|
|
721
|
+
q('#ag-save').addEventListener('click', function() {
|
|
722
|
+
var status = q('#ag-status');
|
|
723
|
+
var workers = all('#ag-workers .ag-row').map(function(row) {
|
|
724
|
+
var w = value(row), n = parseInt(q('.ag-count', row).value, 10);
|
|
725
|
+
w.id = row.getAttribute('data-where') || '';
|
|
726
|
+
w.count = isNaN(n) ? 0 : n;
|
|
727
|
+
return w;
|
|
728
|
+
});
|
|
729
|
+
status.className = 'ag-status'; status.textContent = '保存中…';
|
|
730
|
+
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 }) })
|
|
731
|
+
.then(function(r) { return r.json().then(function(j) { return { ok: r.ok, j: j }; }); })
|
|
732
|
+
.then(function(x) {
|
|
733
|
+
if (x.ok) {
|
|
734
|
+
status.classList.add('is-ok');
|
|
735
|
+
status.textContent = '已保存' + (x.j.notes && x.j.notes.length ? '。注意:' + x.j.notes.join(';') : ',对新的触发生效。');
|
|
736
|
+
// 保存下来的编号写回每一行:再点保存时它们还是原来那几组,不会被当成又加了几组
|
|
737
|
+
var saved = x.j.workers || [];
|
|
738
|
+
var total = 0;
|
|
739
|
+
all('#ag-workers .ag-row').forEach(function(row, i) {
|
|
740
|
+
if (!saved[i]) return;
|
|
741
|
+
row.setAttribute('data-where', saved[i].id);
|
|
742
|
+
if (q('.ag-count', row)) q('.ag-count', row).value = saved[i].count;
|
|
743
|
+
total += saved[i].count;
|
|
744
|
+
});
|
|
745
|
+
q('#ag-count-pill').textContent = saved.length + ' 组 · 共 ' + total + ' 个';
|
|
746
|
+
} else {
|
|
747
|
+
status.classList.add('is-err');
|
|
748
|
+
status.textContent = '没保存:' + ((x.j.problems || []).join(';') || '接口没答应');
|
|
749
|
+
}
|
|
750
|
+
})
|
|
751
|
+
.catch(function(e) { status.classList.add('is-err'); status.textContent = '没发出去:' + e; });
|
|
752
|
+
});
|
|
753
|
+
})();</script>`;
|
|
754
|
+
return md.page('路由与执行者', body, navHtml('/agents'));
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// 页面上点了保存:核对没有问题才写进名册。换了路由的 agent 就把它绑的会话清掉(别的 agent 接不上)。
|
|
758
|
+
// 靠三道闸防别的网页乱发:Host 头是本机(上面)、页面脚本里带的令牌、只认 JSON(跨站的表单发不出这个类型)
|
|
759
|
+
async function saveRosterOnPage(req, res) {
|
|
760
|
+
if (String(req.headers['x-wrj-token'] || '') !== webToken()) return send(res, 403, JSON.stringify({ problems: ['令牌不对:这个接口只给本机页面用'] }), JSON_TYPE);
|
|
761
|
+
if (!/application\/json/i.test(String(req.headers['content-type'] || ''))) return send(res, 415, JSON.stringify({ problems: ['只认 application/json'] }), JSON_TYPE);
|
|
762
|
+
const body = await new Promise((resolve) => {
|
|
763
|
+
let data = '';
|
|
764
|
+
req.on('data', (c) => {
|
|
765
|
+
data += c;
|
|
766
|
+
if (data.length > 64 * 1024) req.destroy();
|
|
767
|
+
});
|
|
768
|
+
req.on('end', () => resolve(data));
|
|
769
|
+
req.on('error', () => resolve(''));
|
|
770
|
+
});
|
|
771
|
+
let posted;
|
|
772
|
+
try {
|
|
773
|
+
posted = JSON.parse(body || '{}');
|
|
774
|
+
} catch (error) {
|
|
775
|
+
return send(res, 400, JSON.stringify({ problems: [`请求体不是 JSON:${error.message}`] }), JSON_TYPE);
|
|
776
|
+
}
|
|
777
|
+
const before = roster();
|
|
778
|
+
// 页面上的行:已有的带着编号,新加的没有;编号重复的或者不认识的当新组
|
|
779
|
+
const known = new Set(before.workers.map((w) => w.id));
|
|
780
|
+
const ids = new Set();
|
|
781
|
+
const rows = (Array.isArray(posted.workers) ? posted.workers : []).map((raw, i) => {
|
|
782
|
+
const id = typeof raw.id === 'string' && known.has(raw.id) && !ids.has(raw.id) ? raw.id : '';
|
|
783
|
+
if (id) ids.add(id);
|
|
784
|
+
return { raw, id, line: i + 1 };
|
|
785
|
+
});
|
|
786
|
+
let next = rosterLib.nextId(before.workers);
|
|
787
|
+
const workers = rows.map(({ raw, id }) => {
|
|
788
|
+
const use = id || next;
|
|
789
|
+
if (!id) next = rosterLib.nextId([...before.workers, { id: use }]);
|
|
790
|
+
return { id: use, agent: raw.agent, model: raw.model, effort: raw.effort, count: raw.count };
|
|
791
|
+
});
|
|
792
|
+
const clean = { router: rosterLib.entry(posted.router), workers: rosterLib.normalize({ workers }).workers };
|
|
793
|
+
const problems = [];
|
|
794
|
+
if (!clean.router.agent) problems.push('路由没选 agent');
|
|
795
|
+
rows.forEach(({ raw, line }) => { if (!String(raw.agent || '').trim()) problems.push(`第 ${line} 组执行者没选 agent`); });
|
|
796
|
+
workers.forEach((w) => {
|
|
797
|
+
if (!(Number.isInteger(w.count) && w.count >= 1 && w.count <= rosterLib.MAX_COUNT)) problems.push(`执行者 ${w.id}:数量要是 1 到 ${rosterLib.MAX_COUNT} 的整数(现在是 ${w.count})`);
|
|
798
|
+
});
|
|
799
|
+
if (!clean.workers.length) problems.push('至少留一组执行者');
|
|
800
|
+
problems.push(...rosterLib.inspect(root, env, { router: clean.router, workers: clean.workers, problems: [] }).problems);
|
|
801
|
+
if (problems.length) return send(res, 400, JSON.stringify({ problems }), JSON_TYPE);
|
|
802
|
+
const saved = rosterLib.saveRoster(root, clean);
|
|
803
|
+
if (before.router.agent !== clean.router.agent) writeLocalEnv(root, { YZJ_ROUTER_SESSION: '' });
|
|
804
|
+
// local.env 可能刚改过:重新读一遍,引擎下一次派活、下一轮路由就用新的
|
|
805
|
+
Object.assign(env, loadLocalEnv(root, env));
|
|
806
|
+
if (engine) engine.setEnv(env);
|
|
807
|
+
const notes = rosterLib.inspect(root, env, rosterLib.loadRoster(root, env)).notes;
|
|
808
|
+
notes.push(serviceAlive() ? '在跑的那几件不受影响,新来的触发按这份配置走' : '本地服务没在跑:下次启动才用上这份配置');
|
|
809
|
+
log('名册已保存', `路由=${clean.router.agent} 执行者=${clean.workers.map((w) => `${w.id} ${w.agent}×${w.count}`).join(',')}`);
|
|
810
|
+
// 把发下去的编号带回页面:新加的那几行记住自己的编号,再保存时还是原来那几组
|
|
811
|
+
return send(res, 200, JSON.stringify({ ok: true, notes, workers: saved.workers.map((w) => ({ id: w.id, count: w.count })) }), JSON_TYPE);
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
// ---------------------------------------------------------------- 监控中心
|
|
815
|
+
const fmtDur = (secs) => {
|
|
816
|
+
const n = Number(secs) || 0;
|
|
570
817
|
if (n < 60) return `${n} 秒`;
|
|
571
818
|
const m = Math.floor(n / 60);
|
|
572
819
|
return m >= 60 ? `${Math.floor(m / 60)} 小时 ${m % 60} 分` : `${m} 分 ${n % 60} 秒`;
|
|
@@ -577,19 +824,19 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
577
824
|
// 监控中心的数据:页面和 /status.json 是同一份
|
|
578
825
|
function monitorData() {
|
|
579
826
|
const alive = serviceAlive();
|
|
580
|
-
const st =
|
|
581
|
-
const
|
|
827
|
+
const st = makeEngine().status();
|
|
828
|
+
const team = roster();
|
|
582
829
|
return {
|
|
583
830
|
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:
|
|
831
|
+
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 },
|
|
832
|
+
router: st.router,
|
|
833
|
+
workers: st.workers,
|
|
834
|
+
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
835
|
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
836
|
triggers: Object.values(store.data.triggers || {}).sort((a, b) => b.at.localeCompare(a.at) || b.id.localeCompare(a.id)).slice(0, 100),
|
|
590
837
|
sources: sourceStatus(),
|
|
591
838
|
refinedAt: store.data.refinedAt || '',
|
|
592
|
-
config: {
|
|
839
|
+
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
840
|
};
|
|
594
841
|
}
|
|
595
842
|
|
|
@@ -630,7 +877,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
630
877
|
l && l.lastOk ? esc(l.lastOk.slice(5, 16)) : '<span class="muted">—</span>',
|
|
631
878
|
];
|
|
632
879
|
});
|
|
633
|
-
const refine =
|
|
880
|
+
const refine = ` · 有新数据就提炼${d.config.refine ? '' : '(关着)'},间隔 ${d.config.refineInterval} 分钟`;
|
|
634
881
|
const last = d.refinedAt ? ` · 上次提炼 ${esc(d.refinedAt.slice(5, 16))}` : '';
|
|
635
882
|
return `<section class="card">
|
|
636
883
|
<div class="card-head"><h2>订阅源 <span class="muted">采集 ${esc(d.service.sync || '不定时')}${refine}${last}</span></h2><span class="pill">${enabled} 个启用</span></div>
|
|
@@ -638,7 +885,6 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
638
885
|
</section>`;
|
|
639
886
|
}
|
|
640
887
|
|
|
641
|
-
// 监控中心的「待办卡片」一块:等我拿主意的事(DECISIONS.md 里「未答」的行)
|
|
642
888
|
function monitorPage() {
|
|
643
889
|
const d = monitorData();
|
|
644
890
|
const statusPill = (t) => {
|
|
@@ -650,25 +896,32 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
650
896
|
if (s === 'stopped') return '<span class="pill is-amber">叫停</span>';
|
|
651
897
|
return `<span class="pill">${esc(s)}</span>`;
|
|
652
898
|
};
|
|
899
|
+
const runningNow = new Map(d.workers.running.map((w) => [w.id, w]));
|
|
653
900
|
const workerCell = (t) => {
|
|
654
901
|
if (!t.worker) return '<span class="muted">—</span>';
|
|
655
|
-
|
|
656
|
-
const
|
|
902
|
+
// 在跑的带上执行者最近记的一步过程(它边做边追加的)
|
|
903
|
+
const step = runningNow.has(t.id) && runningNow.get(t.id).step ? `<br><span class="muted">最近一步:${esc(runningNow.get(t.id).step)}</span>` : '';
|
|
904
|
+
const extra = t.worker.status === 'failed' && t.worker.reason ? `<br><span class="muted">${esc(t.worker.reason)}</span>` : step;
|
|
905
|
+
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
906
|
return `${statusPill(t)}<br>${who}${extra}`;
|
|
658
907
|
};
|
|
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>');
|
|
908
|
+
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
909
|
const decision = (t) => `<strong>${esc(t.decision || '—')}</strong>${t.reason ? `<br><span class="muted">${esc(t.reason)}</span>` : ''}`;
|
|
661
910
|
const byId = triggersById(store.data);
|
|
911
|
+
// 每件在跑的:起于几点、已跑了多久;多久没输出(只有边跑边输出的 agent 有);最近一步是什么、几秒前记的
|
|
662
912
|
const running = d.workers.running.map((w) => {
|
|
663
913
|
const t = byId[w.id];
|
|
664
914
|
const sid = t && t.worker && t.worker.sessionId ? ` <code>${esc(t.worker.sessionId)}</code>` : '';
|
|
665
|
-
|
|
915
|
+
const quiet = w.quietFor >= 60 ? `,${esc(fmtDur(w.quietFor))}没输出` : '';
|
|
916
|
+
const step = w.step ? `<br><span class="muted">最近一步:${esc(w.step)}${w.stepAge >= 60 ? `(${esc(fmtDur(w.stepAge))}前)` : ''}</span>` : '';
|
|
917
|
+
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
918
|
}).join('');
|
|
667
919
|
const rs = d.router;
|
|
668
920
|
const session = rs.session ? (rs.session.own ? `专属会话${rs.session.id ? ` <code>${esc(rs.session.id)}</code>` : '(还没开)'}` : `绑定 <code>${esc(rs.session.id)}</code>`) : '—';
|
|
669
921
|
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.
|
|
922
|
+
const routerBadge = rs.busy ? '<span class="pill is-accent"><span class="dot is-accent"></span>正在想</span>' : '<span class="pill is-green">开着</span>';
|
|
671
923
|
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>`;
|
|
924
|
+
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
925
|
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
926
|
<script>(function(){var b=document.getElementById('refresh');setInterval(function(){if(b.checked&&document.visibilityState==='visible')location.reload()},10000)})();</script>
|
|
674
927
|
<div class="mon-grid">
|
|
@@ -679,15 +932,15 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
679
932
|
推送 ${d.service.push ? `开着(${esc(d.service.notifyChannel || '没配渠道')})` : '关着'} · 端口 <code>${d.service.port}</code></p>
|
|
680
933
|
</section>
|
|
681
934
|
<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)}` : ''}
|
|
935
|
+
<div class="card-head"><h2>路由 <a class="day-btn" href="/agents">配置</a></h2></div>
|
|
936
|
+
<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>
|
|
937
|
+
<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
938
|
</section>
|
|
686
939
|
<section class="card">
|
|
687
|
-
<div class="card-head"><h2
|
|
940
|
+
<div class="card-head"><h2>执行者 <a class="day-btn" href="/agents">配置</a></h2></div>
|
|
688
941
|
<p>${workerBadge}${d.workers.queued.length ? `<br>排队 ${d.workers.queued.map(short).join(' ')}` : ''}</p>
|
|
942
|
+
${groups ? `<ul class="ag-notes">${groups}</ul>` : ''}
|
|
689
943
|
${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
944
|
</section>
|
|
692
945
|
</div>
|
|
693
946
|
${sourcesCard(d)}
|
|
@@ -716,11 +969,9 @@ ${sourcesCard(d)}
|
|
|
716
969
|
]))}
|
|
717
970
|
</section>
|
|
718
971
|
<section class="card">
|
|
719
|
-
<div class="card-head"><h2>配置 <span class="muted"
|
|
972
|
+
<div class="card-head"><h2>配置 <span class="muted">只读;agent 在 <a href="/agents">agent 页</a> 配</span></h2></div>
|
|
720
973
|
<div class="mon-kv">
|
|
721
|
-
<span class="pill">router: ${d.config.router}</span>
|
|
722
974
|
<span class="pill">router-timeout: ${d.config.routerTimeout}s</span>
|
|
723
|
-
<span class="pill">workers: ${d.config.workers}</span>
|
|
724
975
|
<span class="pill">refine: ${d.config.refine}</span>
|
|
725
976
|
<span class="pill">refine-interval: ${d.config.refineInterval}m</span>
|
|
726
977
|
<span class="pill">task-timeout: ${d.config.taskTimeout ? `${d.config.taskTimeout}s` : '不限'}</span>
|
|
@@ -752,8 +1003,8 @@ ${sourcesCard(d)}
|
|
|
752
1003
|
if (!node || launchd.looksLikeElectron(node, {})) problems.push(`常驻的 plist 里绑的不是真正的 node(${node || '没读到'}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
753
1004
|
else if (!fs.existsSync(node)) problems.push(`常驻的 plist 里绑的 node 不在了(${node}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
754
1005
|
}
|
|
755
|
-
//
|
|
756
|
-
if (bot && botWanted()) problems.push(...
|
|
1006
|
+
// 值守开着的话,它的配置(渠道、钥匙串、我的 openId、路由和执行者的 agent)也要齐
|
|
1007
|
+
if (bot && botWanted()) problems.push(...botProblems());
|
|
757
1008
|
for (const [id, specText] of Object.entries(cfg.schedule)) {
|
|
758
1009
|
if (NOT_SERVICE_TASKS.includes(id)) continue;
|
|
759
1010
|
const spec = parseSpec(specText);
|
|
@@ -763,34 +1014,25 @@ ${sourcesCard(d)}
|
|
|
763
1014
|
}
|
|
764
1015
|
if (cfg.sync && parseSpec(cfg.sync).problem) problems.push(`采集的时间${parseSpec(cfg.sync).problem}`);
|
|
765
1016
|
if (!(cfg.port >= 1024 && cfg.port <= 65535)) problems.push(`rhythm.port 要是 1024 到 65535 之间的整数(现在是 ${cfg.port})`);
|
|
766
|
-
// 只有真有任务要跑时,agent
|
|
1017
|
+
// 只有真有任务要跑时,agent 和推送才必须配好;只采集、只看页面的用不着(值守的配置它自己查,见上)
|
|
767
1018
|
if (jobs().some((job) => job.kind === 'task' && job.hasPrompt)) {
|
|
768
|
-
problems.push(...
|
|
1019
|
+
problems.push(...agentsProblems());
|
|
769
1020
|
if (cfg.push && !cfg.notifyChannel) problems.push('rhythm.push 开着,但 preferences.notify 没配消息渠道:要么配一个,要么把 push 写成 false');
|
|
770
1021
|
}
|
|
771
|
-
//
|
|
1022
|
+
// 引擎的几个键:写了就得是正整数(没写用默认)
|
|
772
1023
|
for (const [key, name] of NEW_KEYS) {
|
|
773
1024
|
if (cfg.raw[key] !== undefined && !(Number.isInteger(Number(cfg.raw[key])) && Number(cfg.raw[key]) > 0)) problems.push(`${name} 要是正整数(现在是 ${cfg.raw[key]})`);
|
|
774
1025
|
}
|
|
775
|
-
// 路由开着时它的 agent 也要配得对(值守开着时 bot 那边查的是同一个)
|
|
776
|
-
if (cfg.router) problems.push(...routerDoctorProblems());
|
|
777
1026
|
// 启用着的源,采集脚本得在
|
|
778
1027
|
for (const x of sourceStatus()) if (x.missing) problems.push(`订阅源 ${x.id} 的采集脚本不存在:${x.collector}(sources.yaml 的 collector 写错了,或者脚本没放进 collectors/)`);
|
|
779
|
-
|
|
1028
|
+
// 值守开着时它的检查里已经带了路由和执行者的问题,别报两遍
|
|
1029
|
+
return [...new Set(problems)];
|
|
780
1030
|
}
|
|
781
1031
|
|
|
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 } = {}) {
|
|
1032
|
+
// 命令行里走一遍全流程(work-rhythm listen handle):在命令行的进程里建引擎,这句话变成一条触发,
|
|
1033
|
+
// 要发的文字交给 sink(带 push 才真发),等到队列空、执行者都结束。返回 { id, texts }
|
|
1034
|
+
async function handle(text, { push: really = false, timeoutMs = 3600 * 1000 } = {}) {
|
|
792
1035
|
const eng = makeEngine();
|
|
793
|
-
if (!eng) return null;
|
|
794
1036
|
const texts = [];
|
|
795
1037
|
if (!really) eng.setSink((t) => texts.push(t));
|
|
796
1038
|
const t = eng.enqueue('message', { key: `handle-${Date.now()}`, msgId: 'handle', text, mode: (env.YZJ_BOT_AGENT_MODE || 'plan').trim() });
|
|
@@ -799,12 +1041,10 @@ ${sourcesCard(d)}
|
|
|
799
1041
|
return { id: t ? t.id : '', texts };
|
|
800
1042
|
}
|
|
801
1043
|
|
|
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('推送关不掉又没配渠道:路由写给用户的话发不出去,只记日志');
|
|
1044
|
+
// 不算问题、但要让人知道的事(doctor 另起一行列出来,不影响退出码)
|
|
1045
|
+
function doctorNotes() {
|
|
1046
|
+
const notes = rosterLook().notes;
|
|
1047
|
+
if (!cfg.notifyChannel && cfg.push) notes.push('推送关不掉又没配渠道:路由写给用户的话发不出去,只记日志');
|
|
808
1048
|
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
1049
|
return notes;
|
|
810
1050
|
}
|
|
@@ -819,24 +1059,23 @@ ${sourcesCard(d)}
|
|
|
819
1059
|
});
|
|
820
1060
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
821
1061
|
fs.writeFileSync(PID_FILE, `${process.pid}\n`);
|
|
822
|
-
|
|
1062
|
+
const team = roster();
|
|
1063
|
+
log('服务开始', `pid=${process.pid} 页面=${baseUrl()} 路由=${team.router.agent || '(没配)'}`);
|
|
823
1064
|
process.stdout.write(`页面:${baseUrl()} 停:work-rhythm rhythm stop\n`);
|
|
824
1065
|
|
|
825
1066
|
// 值守(机器人的收消息一半)也在这里跑:一个后台进程管定时任务、推送、网页和值守。默认开着(collectors/local.env 写 YZJ_BOT_LISTEN=0 才关);
|
|
826
1067
|
// 配置有问题不拦着服务起,只记一笔——定时任务和网页照常
|
|
827
1068
|
let bot = null;
|
|
828
1069
|
let botTask = null;
|
|
829
|
-
//
|
|
1070
|
+
// 引擎在这个进程里跑(触发 → 路由 → 执行者 → 汇报)。上次没跑完的执行者先补失败回执,交回路由
|
|
830
1071
|
const eng = makeEngine();
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
log('引擎开始', `路由=${roles(env).router.agent} 执行者=${workerSpec().agent} 并发=${cfg.workers}`);
|
|
835
|
-
}
|
|
1072
|
+
eng.recover();
|
|
1073
|
+
eng.tick();
|
|
1074
|
+
log('引擎开始', `路由=${team.router.agent || '没绑'} 执行者=${team.workers.map((w) => `${w.id} ${w.agent || '没绑'}×${w.count}`).join(',') || '没有'}`);
|
|
836
1075
|
if (botWanted()) {
|
|
837
|
-
bot = createBot({ root, env, onMessage:
|
|
838
|
-
const
|
|
839
|
-
if (
|
|
1076
|
+
bot = createBot({ root, env, onMessage: (m) => eng.message(m), resetSession: () => eng.resetSession(), say: (text) => eng.say(text), doctorAgent: () => eng.doctorProblems() });
|
|
1077
|
+
const botProbs = bot.doctorProblems();
|
|
1078
|
+
if (botProbs.length) log('值守没开', botProbs.join(';'));
|
|
840
1079
|
else {
|
|
841
1080
|
botTask = bot.run({ signals: false }).then(
|
|
842
1081
|
() => log('值守结束'),
|
|
@@ -845,6 +1084,7 @@ ${sourcesCard(d)}
|
|
|
845
1084
|
}
|
|
846
1085
|
}
|
|
847
1086
|
|
|
1087
|
+
// 只有采集走这条队列(另起子进程,采集是同步的脚本);到点的任务直接交给引擎
|
|
848
1088
|
const list = jobs();
|
|
849
1089
|
const state = store.data;
|
|
850
1090
|
let running = null;
|
|
@@ -855,32 +1095,25 @@ ${sourcesCard(d)}
|
|
|
855
1095
|
running = startJob(job);
|
|
856
1096
|
running.on('exit', (code) => {
|
|
857
1097
|
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
1098
|
saveState(state);
|
|
864
1099
|
log('跑完', `${job.id} rc=${code}`);
|
|
865
1100
|
running = null;
|
|
866
1101
|
startNext();
|
|
867
1102
|
// 采集是有新数据才提炼:子进程把每个源的结果和「有没有新数据」留在 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));
|
|
1103
|
+
try {
|
|
1104
|
+
const file = path.join(STATE_DIR, 'last-sync.json');
|
|
1105
|
+
const st = fs.statSync(file);
|
|
1106
|
+
if (Date.now() - st.mtimeMs < 10 * 60 * 1000) {
|
|
1107
|
+
const last = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
1108
|
+
eng.afterSync({ results: last.results || [], changed: Boolean(last.changed) });
|
|
878
1109
|
}
|
|
1110
|
+
} catch (error) {
|
|
1111
|
+
log('采集结果读不了', error && error.message ? error.message : String(error));
|
|
879
1112
|
}
|
|
880
1113
|
});
|
|
881
1114
|
};
|
|
882
1115
|
const tick = () => {
|
|
883
|
-
|
|
1116
|
+
eng.tick();
|
|
884
1117
|
const now = new Date();
|
|
885
1118
|
for (const job of list) {
|
|
886
1119
|
for (const minute of timesOn(job.spec, now)) {
|
|
@@ -896,8 +1129,8 @@ ${sourcesCard(d)}
|
|
|
896
1129
|
continue;
|
|
897
1130
|
}
|
|
898
1131
|
log('到点', `${job.id} ${hhmm(at)}`);
|
|
899
|
-
if (job.kind === 'task'
|
|
900
|
-
//
|
|
1132
|
+
if (job.kind === 'task') {
|
|
1133
|
+
// 任务变成一条触发交给路由,由它挑一组执行者派出去
|
|
901
1134
|
const body = fs.readFileSync(path.join(root, 'tasks', `${job.id}.md`), 'utf8');
|
|
902
1135
|
eng.schedule({ id: job.id, key }, body, taskTitleOf(body));
|
|
903
1136
|
continue;
|
|
@@ -922,8 +1155,7 @@ ${sourcesCard(d)}
|
|
|
922
1155
|
}
|
|
923
1156
|
// 在跑的执行者是子进程,不收掉会留着:停掉它们(引擎里最多等 3 秒),再关网页
|
|
924
1157
|
const close = () => server.close(() => resolve());
|
|
925
|
-
|
|
926
|
-
else close();
|
|
1158
|
+
eng.shutdown().then(close, close);
|
|
927
1159
|
setTimeout(resolve, 4500).unref();
|
|
928
1160
|
};
|
|
929
1161
|
process.on('SIGINT', () => stop('SIGINT'));
|
|
@@ -963,11 +1195,12 @@ ${sourcesCard(d)}
|
|
|
963
1195
|
const botLog = readText(path.join(root, '01-inbox', '_bot.log')).trim().split('\n');
|
|
964
1196
|
const lastBot = botLog.length && botLog[botLog.length - 1] ? botLog[botLog.length - 1] : '';
|
|
965
1197
|
lines.push(`值守:${botWanted() ? `开着${lastBot ? `,最近 ${lastBot}` : ''}` : '关着(collectors/local.env 的 YZJ_BOT_LISTEN=1 打开,改完 work-rhythm rhythm restart)'}`);
|
|
966
|
-
const
|
|
967
|
-
const w = workerSpec();
|
|
1198
|
+
const team = roster();
|
|
968
1199
|
const rounds = (store.data.rounds || []).filter((x) => x.at.startsWith(fmtDate(new Date()))).length;
|
|
969
|
-
lines.push(
|
|
970
|
-
|
|
1200
|
+
lines.push(team.router.agent
|
|
1201
|
+
? `路由:${team.router.agent}${team.router.model ? `,模型 ${team.router.model}` : ''},强度 ${rosterLib.routerEffort(team.router) || '用它自己的默认'},今天 ${rounds} 轮;实时的排队和在跑看 ${baseUrl()}/monitor`
|
|
1202
|
+
: `路由:没绑(work-rhythm agent bind router <名字>,或者在本机网页的 /agents 里配),今天 ${rounds} 轮;实时的排队和在跑看 ${baseUrl()}/monitor`);
|
|
1203
|
+
lines.push(`执行者:${team.workers.map((w) => `${w.id} ${w.agent || '没绑'}${w.model ? `(${w.model})` : ''}${w.effort ? ` ${w.effort}` : ''} ×${w.count}`).join(';') || '没有'};改在 ${baseUrl()}/agents`);
|
|
971
1204
|
// 订阅源:几个正常、谁在连着失败、谁还没跑过
|
|
972
1205
|
const srcs = sourceStatus().filter((x) => x.enabled);
|
|
973
1206
|
if (srcs.length) {
|
|
@@ -994,6 +1227,8 @@ ${sourcesCard(d)}
|
|
|
994
1227
|
due,
|
|
995
1228
|
monitorData,
|
|
996
1229
|
monitorPage,
|
|
1230
|
+
agentsData,
|
|
1231
|
+
agentsPage,
|
|
997
1232
|
doctorNotes,
|
|
998
1233
|
recordForTest: (id, r) => recordSources([{ id, ...r }]),
|
|
999
1234
|
handle,
|
|
@@ -1014,4 +1249,4 @@ ${sourcesCard(d)}
|
|
|
1014
1249
|
};
|
|
1015
1250
|
}
|
|
1016
1251
|
|
|
1017
|
-
module.exports = { createRhythm, loadConfig, parseSpec, LINKS, NOT_SERVICE_TASKS };
|
|
1252
|
+
module.exports = { createRhythm, loadConfig, parseSpec, LINKS, NOT_SERVICE_TASKS, ALWAYS_QUIET };
|