work-rhythm 0.2.20 → 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-question-cards-via-cli-tool-on-todays-page-answers-return-to-router.md +4 -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-01-sync-feeds-refine-then-events-to-the-router.md +4 -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 +46 -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 +21 -17
- 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 +28 -1
- package/docs/router-worker.md +67 -54
- package/docs/scheduled-tasks.md +14 -14
- package/docs/sources.md +5 -6
- package/package.json +1 -1
- package/scripts/cli.js +9 -5
- package/scripts/cmd/agent.js +348 -235
- package/scripts/cmd/ask.js +18 -76
- 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 +345 -170
- 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 +402 -260
- package/scripts/lib/router.js +52 -46
- package/scripts/lib/template.js +3 -3
- package/scripts/lib/update.js +279 -0
- package/scripts/lib/view.js +7 -152
- 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 +167 -109
- package/scripts/test/roster.test.js +155 -0
- package/scripts/test/router-helper.js +17 -2
- package/scripts/test/router.test.js +499 -414
- 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 -13
- package/tasks/daily-plan.md +4 -3
- package/tasks/evening-review.md +1 -2
- package/tasks/noon-checkin.md +2 -1
- package/templates/00-config/profile.example.yaml +17 -13
- package/templates/04-patterns/PERSONA.md +4 -1
- package/templates/04-patterns/PLAYBOOK.md +13 -0
- package/templates/AGENTS.md +7 -3
- 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,27 +13,28 @@ 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
|
-
const { createEngine, appendHistory, pruneState, historyStats, uid
|
|
22
|
+
const { createEngine, appendHistory, pruneState, historyStats, uid } = require('./engine');
|
|
22
23
|
const handoff = require('./handoff');
|
|
23
24
|
const md = require('./markdown');
|
|
24
25
|
const view = require('./view');
|
|
25
26
|
const launchd = require('./launchd');
|
|
26
27
|
const sync = require('../cmd/sync');
|
|
27
28
|
const today = require('../cmd/today');
|
|
28
|
-
const decisions = require('../cmd/decisions');
|
|
29
|
-
const asks = require('./asks');
|
|
30
29
|
|
|
31
30
|
const TICK_MS = 20000;
|
|
32
31
|
const CATCH_UP_MS = 5 * 60 * 1000;
|
|
33
32
|
const WEEKDAYS = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
|
|
34
33
|
const WEEKDAY_CN = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
|
|
35
|
-
//
|
|
34
|
+
// 这些要等我回答,不当定时任务:我对任何一个能读到这个工作目录的 agent 说「有什么要我定」就开始
|
|
36
35
|
const NOT_SERVICE_TASKS = ['ask-decisions'];
|
|
36
|
+
// 这些任务天生静默(后台整理归档这类):不管 profile 的 quiet 怎么写都不推送、不发消息
|
|
37
|
+
const ALWAYS_QUIET = ['daily-persona'];
|
|
37
38
|
// 任务跑完推送时附哪个页面(本机网页服务上的地址)
|
|
38
39
|
const LINKS = {
|
|
39
40
|
'daily-plan': { path: (d) => `/day/${d}`, label: '今天的文件' },
|
|
@@ -41,13 +42,14 @@ const LINKS = {
|
|
|
41
42
|
'evening-review': { path: (d) => `/day/${d}`, label: '今天的文件' },
|
|
42
43
|
'weekly-rhythm': { path: () => '/rhythm', label: '工作规律' },
|
|
43
44
|
'alerts-morning': { path: (d) => `/reports/${d}-alerts.html`, label: '告警晨报' },
|
|
44
|
-
// 一批新事件之后的「今日重点与待办」:地址给「决定」页(待办卡片在那里点),手机打不开,要在自己电脑上开
|
|
45
|
-
'todos': { path: () => '/#pending-decisions', label: '今日页「待你定」(在自己电脑的浏览器里打开)' },
|
|
46
45
|
};
|
|
47
|
-
const NAV = [['/', '今日'], ['/carryover', '遗留'], ['/decisions', '决定'], ['/rhythm', '规律'], ['/goals', '目标'], ['/reports', '报告'], ['/monitor', '监控']];
|
|
46
|
+
const NAV = [['/', '今日'], ['/carryover', '遗留'], ['/decisions', '决定'], ['/rhythm', '规律'], ['/goals', '目标'], ['/reports', '报告'], ['/monitor', '监控'], ['/agents', 'agent']];
|
|
48
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__';
|
|
49
51
|
// 状态文件的骨架:done(跑过的任务)、runs(各任务最近一次)、seq(触发短号的序号)、triggers(近两天的触发)、history(运行记录)、rounds(路由的轮数)
|
|
50
|
-
const EMPTY_STATE = () => ({ done: {}, runs: {}, seq: 0, triggers: {}, history: [], rounds: [], sources: {}, refinedAt: '', syncDigest: { date: '', digest: '' }
|
|
52
|
+
const EMPTY_STATE = () => ({ done: {}, runs: {}, seq: 0, triggers: {}, history: [], rounds: [], sources: {}, refinedAt: '', syncDigest: { date: '', digest: '' } });
|
|
51
53
|
|
|
52
54
|
const positiveInt = (value, fallback) => {
|
|
53
55
|
const n = Number(value);
|
|
@@ -70,20 +72,19 @@ function loadConfig(root) {
|
|
|
70
72
|
sync: typeof rhythm.sync === 'string' ? rhythm.sync.trim() : '',
|
|
71
73
|
port: positiveInt(rhythm.port, 8787),
|
|
72
74
|
push: rhythm.push !== false,
|
|
73
|
-
quiet: asList(rhythm.quiet),
|
|
75
|
+
quiet: [...new Set([...ALWAYS_QUIET, ...asList(rhythm.quiet)])],
|
|
74
76
|
agentMode: typeof rhythm['agent-mode'] === 'string' && rhythm['agent-mode'].trim() ? rhythm['agent-mode'].trim() : 'edit',
|
|
75
|
-
// 定时任务用的模型和思考强度(可选项,profile 里不写也行):不配就和值守一样,用 local.env 的 YZJ_BOT_MODEL / YZJ_BOT_EFFORT
|
|
76
|
-
agentModel: typeof rhythm['agent-model'] === 'string' ? rhythm['agent-model'].trim() : '',
|
|
77
|
-
agentEffort: typeof rhythm['agent-effort'] === 'string' ? rhythm['agent-effort'].trim() : '',
|
|
78
77
|
taskTimeout: seconds(rhythm['task-timeout'], 0),
|
|
78
|
+
// 手头还有别的活在跑时,先做完的汇报等一等(一起交回路由、回我的话合成一条),最多等这么多秒;0 = 不等,做完就汇报
|
|
79
|
+
mergeWait: seconds(rhythm['merge-wait'], 120),
|
|
79
80
|
syncTimeout: positiveInt(rhythm['sync-timeout'], 600),
|
|
80
81
|
notifyChannel: typeof preferences.notify === 'string' ? preferences.notify.trim() : '',
|
|
81
82
|
schedule,
|
|
82
|
-
//
|
|
83
|
-
router: rhythm.router === true,
|
|
83
|
+
// 路由和执行者用哪个 agent、模型、强度在名册里(docs/agents.md);这里只有引擎的几个旋钮
|
|
84
84
|
routerTimeout: positiveInt(rhythm['router-timeout'], 120),
|
|
85
|
-
|
|
86
|
-
|
|
85
|
+
// 老写法:没有 00-config/agents.json 时,那一组执行者同时跑几个(名册的 fromEnv 读它)
|
|
86
|
+
workers: positiveInt(rhythm.workers, rosterLib.DEFAULT_COUNT),
|
|
87
|
+
// 定时采集之后:有新数据就起一轮提炼(把 01-inbox 的新数据炼成事件)。两轮提炼之间至少隔 refine-interval 分钟
|
|
87
88
|
refine: rhythm.refine !== false,
|
|
88
89
|
refineInterval: positiveInt(rhythm['refine-interval'], 120),
|
|
89
90
|
handoffKeep: positiveInt(rhythm['handoff-keep'], 14),
|
|
@@ -118,11 +119,12 @@ function parseSpec(spec) {
|
|
|
118
119
|
return { problem: `看不懂时间写法「${s}」:支持 "08:50"、"Fri 16:30"、"工作日 09:00-18:00 每 30 分钟"` };
|
|
119
120
|
}
|
|
120
121
|
|
|
121
|
-
// 建一个本地服务对象。env 是设置(环境变量,上面盖一层 local.env
|
|
122
|
+
// 建一个本地服务对象。env 是设置(环境变量,上面盖一层 local.env)
|
|
122
123
|
function createRhythm({ root, env, packageRoot }) {
|
|
123
124
|
const STATE_DIR = path.join(root, '01-inbox', '_rhythm');
|
|
124
125
|
const STATE_FILE = path.join(STATE_DIR, 'state.json');
|
|
125
126
|
const PID_FILE = path.join(STATE_DIR, 'service.pid');
|
|
127
|
+
const TOKEN_FILE = path.join(STATE_DIR, 'web-token');
|
|
126
128
|
const LOG_FILE = path.join(root, '01-inbox', '_rhythm.log');
|
|
127
129
|
const LAUNCHD_LOG = path.join(root, '01-inbox', '_rhythm.launchd.log');
|
|
128
130
|
const ENTRY = path.join(packageRoot, 'scripts', 'work-rhythm.js');
|
|
@@ -133,7 +135,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
133
135
|
const since = Date.now();
|
|
134
136
|
// 状态(engine.js 也往里写):同一个进程里只有这一份
|
|
135
137
|
const store = { data: loadState(), save() { saveState(store.data); } };
|
|
136
|
-
// 引擎(路由 +
|
|
138
|
+
// 引擎(路由 + 执行者):同一个进程里只建一个,第一次用到才建
|
|
137
139
|
let engine = null;
|
|
138
140
|
const engineCfg = () => {
|
|
139
141
|
const idle = seconds(env.YZJ_BOT_IDLE, 180);
|
|
@@ -155,15 +157,15 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
155
157
|
};
|
|
156
158
|
};
|
|
157
159
|
const makeEngine = () => {
|
|
158
|
-
if (!cfg.router) return null;
|
|
159
160
|
if (!engine) engine = createEngine({ root, env, cfg: engineCfg(), log, push, state: store, since });
|
|
160
161
|
return engine;
|
|
161
162
|
};
|
|
162
|
-
//
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
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();
|
|
167
169
|
|
|
168
170
|
// 某一天上不上班:以 work-rhythm today 为准(作息、放假都由它判),同一天只问一次
|
|
169
171
|
const workdayCache = {};
|
|
@@ -234,7 +236,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
234
236
|
}
|
|
235
237
|
}
|
|
236
238
|
|
|
237
|
-
// 写状态文件。命令行里的 listen handle / trigger fire 和服务可能同时写:先读盘上的那份,合起来再写——
|
|
239
|
+
// 写状态文件。命令行里的 listen handle / rhythm run / trigger fire 和服务可能同时写:先读盘上的那份,合起来再写——
|
|
238
240
|
// 触发按短号取并集(内存里的新),done / runs / rounds / history 也取并集,seq 取大的
|
|
239
241
|
function saveState(state) {
|
|
240
242
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
@@ -272,7 +274,6 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
272
274
|
}
|
|
273
275
|
|
|
274
276
|
// ---------------------------------------------------------------- 采集、任务、推送
|
|
275
|
-
// 跑一遍 sync(在同一个进程里),最多等 cfg.syncTimeout 秒
|
|
276
277
|
const todayStr = () => fmtDate(new Date());
|
|
277
278
|
|
|
278
279
|
// 今天 01-inbox/<源>/<日期>/ 下所有文件的名字和内容搓成的指纹:采集之后跟上次比,不一样就是有新数据(采集器每次都重写文件,所以不按修改时间算)
|
|
@@ -328,7 +329,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
328
329
|
const capture = { write: (s) => (chunks.push(String(s)), true) };
|
|
329
330
|
const results = [];
|
|
330
331
|
const fail = await sync.run([], { root, cwd: root, env, stdout: capture, stderr: capture, packageRoot }, { deadlineMs: t0 + cfg.syncTimeout * 1000, results });
|
|
331
|
-
const
|
|
332
|
+
const secs = Math.round((Date.now() - t0) / 1000);
|
|
332
333
|
recordSources(results);
|
|
333
334
|
// 有没有新数据:今天的指纹跟上一次比。没有文件也算一种指纹(空串),和上次不一样才是有新数据
|
|
334
335
|
const digest = inboxDigest(todayStr());
|
|
@@ -336,16 +337,16 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
336
337
|
const changed = Boolean(digest) && digest !== prev.digest;
|
|
337
338
|
store.data.syncDigest = { date: todayStr(), digest, at: fmtStamp() };
|
|
338
339
|
saveState(store.data);
|
|
339
|
-
//
|
|
340
|
+
// 留给服务的那个进程:它起提炼
|
|
340
341
|
try {
|
|
341
342
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
342
|
-
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`);
|
|
343
344
|
} catch {
|
|
344
345
|
// 写不下就算了:服务那边没有它就不提炼
|
|
345
346
|
}
|
|
346
347
|
const out = chunks.join('');
|
|
347
|
-
if (fail) return { ok: false, failed: `退出码 ${fail}:${tail(out, 300)}`, seconds, results, changed };
|
|
348
|
-
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 };
|
|
349
350
|
}
|
|
350
351
|
|
|
351
352
|
// 经消息渠道发一段文字。渠道留空时什么都不发(不算失败);发不出去记日志
|
|
@@ -359,34 +360,8 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
359
360
|
return r.ok;
|
|
360
361
|
}
|
|
361
362
|
|
|
362
|
-
//
|
|
363
|
-
|
|
364
|
-
const file = path.join(root, 'tasks', `${id}.md`);
|
|
365
|
-
if (!fs.existsSync(file)) return { ok: false, failed: `缺 ${path.relative(root, file)}` };
|
|
366
|
-
const prompt = fs.readFileSync(file, 'utf8');
|
|
367
|
-
const willPush = wantPush && cfg.push && !cfg.quiet.includes(id);
|
|
368
|
-
// 服务会替它推送时在指令末尾注明,免得它自己再发一遍
|
|
369
|
-
const full = willPush ? `${prompt}\n\n(这次运行由 work-rhythm rhythm 发起:你最后写的那段总结会被它推送给用户,你自己不要再发。)` : prompt;
|
|
370
|
-
const agent = makeAgent();
|
|
371
|
-
const t0 = Date.now();
|
|
372
|
-
const r = agent.run(full, { stateDir: STATE_DIR });
|
|
373
|
-
const seconds = Math.round((Date.now() - t0) / 1000);
|
|
374
|
-
if (r.failed) {
|
|
375
|
-
if (willPush) await push(`「${id}」没跑完:${r.failed}`);
|
|
376
|
-
return { ok: false, failed: r.failed, seconds };
|
|
377
|
-
}
|
|
378
|
-
let pushed = false;
|
|
379
|
-
if (willPush) {
|
|
380
|
-
let text = r.reply.trim();
|
|
381
|
-
const link = LINKS[id];
|
|
382
|
-
// 服务没在跑时地址打不开,不附
|
|
383
|
-
if (link && serviceAlive()) text += `\n\n→ ${link.label}:${baseUrl()}${link.path(fmtDate(new Date()))}`;
|
|
384
|
-
pushed = await push(text);
|
|
385
|
-
}
|
|
386
|
-
return { ok: true, seconds, summary: r.reply.trim(), pushed };
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
// 立刻跑一次:sync 或某个任务。结果打到标准输出,返回退出码
|
|
363
|
+
// 立刻跑一次:sync 或某个任务。结果打到标准输出,返回退出码。
|
|
364
|
+
// 任务和到点的一样走路由:这条命令的进程里建引擎,这句话变成触发 → 路由 → 执行者 → 路由,要发的话带 --push 才真发
|
|
390
365
|
async function runJob(id, wantPush) {
|
|
391
366
|
if (id === 'sync') {
|
|
392
367
|
const r = await runSync();
|
|
@@ -394,25 +369,48 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
394
369
|
process.stdout.write(r.ok ? `采集完成,用时 ${r.seconds} 秒。\n${r.detail}\n` : `采集失败:${r.failed}\n`);
|
|
395
370
|
return r.ok ? EXIT.OK : EXIT.FAILED;
|
|
396
371
|
}
|
|
397
|
-
const
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
const w = workerSpec();
|
|
402
|
-
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 });
|
|
403
|
-
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 };
|
|
404
376
|
}
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
const
|
|
412
|
-
|
|
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;
|
|
413
409
|
}
|
|
410
|
+
// rhythm run 最多等多久:任务默认不限时(rhythm.task-timeout 为 0),这里给一个很大的数,等于一直等到它做完
|
|
411
|
+
const RUN_WAIT_MS = 7 * 24 * 3600 * 1000;
|
|
414
412
|
|
|
415
|
-
//
|
|
413
|
+
// 调度器用它:采集另起一个子进程跑,不堵住计时(采集是同步的脚本,会把事件循环堵住)
|
|
416
414
|
function startJob(job) {
|
|
417
415
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
418
416
|
const fd = fs.openSync(LOG_FILE, 'a');
|
|
@@ -473,33 +471,25 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
473
471
|
}
|
|
474
472
|
|
|
475
473
|
function route(req, res) {
|
|
476
|
-
//
|
|
477
|
-
if (req.method === 'POST' &&
|
|
474
|
+
// 唯一的写接口:本机页面 /agents 上保存路由和执行者的配置
|
|
475
|
+
if (req.method === 'POST' && String(req.url || '').split('?')[0] === '/agents') return saveRosterOnPage(req, res);
|
|
478
476
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
479
|
-
return send(res, 405, md.page('只支持打开页面', view.renderDocPage('只支持打开页面', '', { empty: '
|
|
477
|
+
return send(res, 405, md.page('只支持打开页面', view.renderDocPage('只支持打开页面', '', { empty: '这个服务只看记录,不改任何东西;唯一能写的是 agent 页上的配置。' }), navHtml()));
|
|
480
478
|
}
|
|
481
|
-
let
|
|
479
|
+
let url;
|
|
482
480
|
try {
|
|
483
|
-
|
|
481
|
+
url = new URL(req.url, 'http://127.0.0.1');
|
|
484
482
|
} catch {
|
|
485
483
|
return notFound(res, '地址不对');
|
|
486
484
|
}
|
|
485
|
+
const pathname = decodeURIComponent(url.pathname);
|
|
487
486
|
const now = fmtDate(new Date());
|
|
488
487
|
if (pathname === '/' || pathname === `/day/${now}`) {
|
|
489
488
|
const dates = dailyDates();
|
|
490
489
|
const text = readText(path.join(root, '02-daily', now.slice(0, 7), `${now}.md`));
|
|
491
|
-
const
|
|
492
|
-
const body = view.renderDaily({ date: now, weekday: WEEKDAY_CN[new Date().getDay()], isToday: true, markdown: text, dates, asks: cards, token: webToken() });
|
|
490
|
+
const body = view.renderDaily({ date: now, weekday: WEEKDAY_CN[new Date().getDay()], isToday: true, markdown: text, dates });
|
|
493
491
|
return send(res, 200, md.page(`今日 · ${now}`, body, navHtml('/')));
|
|
494
492
|
}
|
|
495
|
-
if (pathname === '/asks.html') {
|
|
496
|
-
const cards = asks.cardsForPage(root, pendingCards);
|
|
497
|
-
return send(res, 200, view.renderAsksFragment(cards), 'text/html; charset=utf-8');
|
|
498
|
-
}
|
|
499
|
-
if (pathname === '/asks.json') {
|
|
500
|
-
const cards = asks.cardsForPage(root, pendingCards);
|
|
501
|
-
return send(res, 200, `${JSON.stringify(cards, null, 1)}\n`, 'application/json; charset=utf-8');
|
|
502
|
-
}
|
|
503
493
|
let m = /^\/day\/(\d{4}-\d{2}-\d{2})$/.exec(pathname);
|
|
504
494
|
if (m) {
|
|
505
495
|
const date = m[1];
|
|
@@ -527,14 +517,22 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
527
517
|
if (!fs.existsSync(file)) return notFound(res, `没有 ${m[1]}`);
|
|
528
518
|
return send(res, 200, fs.readFileSync(file));
|
|
529
519
|
}
|
|
530
|
-
//
|
|
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 三种名字
|
|
531
528
|
if (pathname === '/monitor') return send(res, 200, monitorPage());
|
|
532
|
-
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);
|
|
533
530
|
m = /^\/handoff\/([^/]+)$/.exec(pathname);
|
|
534
531
|
if (m) {
|
|
535
532
|
const file = path.join(handoff.dir(root), m[1]);
|
|
536
533
|
if (!handoff.NAME_RE.test(m[1]) || !fs.existsSync(file)) return notFound(res, pathname);
|
|
537
|
-
|
|
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')));
|
|
538
536
|
}
|
|
539
537
|
return notFound(res, pathname);
|
|
540
538
|
}
|
|
@@ -561,27 +559,206 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
561
559
|
}
|
|
562
560
|
}
|
|
563
561
|
|
|
564
|
-
//
|
|
565
|
-
|
|
566
|
-
|
|
562
|
+
// 只绑 127.0.0.1:页面带着工作记录,不给别的机器看
|
|
563
|
+
const listen = (port) => new Promise((resolve, reject) => {
|
|
564
|
+
const server = http.createServer(handleRequest);
|
|
565
|
+
server.on('error', reject);
|
|
566
|
+
server.listen(port, '127.0.0.1', () => resolve(server));
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
// 把一份 Markdown 渲染成页面
|
|
570
|
+
function render(file) {
|
|
571
|
+
const full = path.resolve(root, file);
|
|
572
|
+
if (!fs.existsSync(full)) throw new Fail(EXIT.USAGE, `没有这个文件:${file}`);
|
|
573
|
+
return md.page(path.basename(full), view.renderDocPage(path.basename(full), fs.readFileSync(full, 'utf8')), navHtml());
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// ---------------------------------------------------------------- agent 页:配置路由和执行者
|
|
577
|
+
const esc = (v) => md.escapeHtml(String(v === undefined || v === null ? '' : v));
|
|
578
|
+
|
|
579
|
+
// 网页服务写接口的令牌:随机串存在 01-inbox/_rhythm/web-token,页面脚本带着它,接口只认带对的。
|
|
567
580
|
// 别的网站的页面读不到 127.0.0.1 上的这个页面(同源策略),拿不到令牌,就用图片、表单点不动
|
|
568
581
|
function webToken() {
|
|
569
|
-
const
|
|
570
|
-
|
|
571
|
-
const found = readText(file).trim();
|
|
572
|
-
if (/^[0-9a-f]{32}$/.test(found)) return found;
|
|
573
|
-
} catch {
|
|
574
|
-
// 还没有,下面建一个
|
|
575
|
-
}
|
|
582
|
+
const found = readText(TOKEN_FILE).trim();
|
|
583
|
+
if (/^[0-9a-f]{32}$/.test(found)) return found;
|
|
576
584
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
577
585
|
const token = createHash('sha256').update(`${Date.now()}:${Math.random()}:${process.pid}`).digest('hex').slice(0, 32);
|
|
578
|
-
fs.writeFileSync(
|
|
586
|
+
fs.writeFileSync(TOKEN_FILE, `${token}\n`, { mode: 0o600 });
|
|
579
587
|
return token;
|
|
580
588
|
}
|
|
581
589
|
|
|
582
|
-
//
|
|
583
|
-
|
|
584
|
-
|
|
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);
|
|
585
762
|
const body = await new Promise((resolve) => {
|
|
586
763
|
let data = '';
|
|
587
764
|
req.on('data', (c) => {
|
|
@@ -591,57 +768,52 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
591
768
|
req.on('end', () => resolve(data));
|
|
592
769
|
req.on('error', () => resolve(''));
|
|
593
770
|
});
|
|
594
|
-
let
|
|
771
|
+
let posted;
|
|
595
772
|
try {
|
|
596
|
-
|
|
597
|
-
} catch {
|
|
598
|
-
return send(res, 400, JSON.stringify({
|
|
599
|
-
}
|
|
600
|
-
const id = String(parsed.id || '').trim();
|
|
601
|
-
const item = String(parsed.item || '').trim();
|
|
602
|
-
const choice = String(parsed.choice || '').trim();
|
|
603
|
-
const note = String(parsed.note || '').trim();
|
|
604
|
-
if (!choice || (!id && !item)) return send(res, 400, JSON.stringify({ error: '要写回答和卡片标识' }), 'application/json; charset=utf-8');
|
|
605
|
-
let ask;
|
|
606
|
-
if (id) {
|
|
607
|
-
try {
|
|
608
|
-
ask = await asks.answerAsk(root, id, { choice, note, by: 'page' }, { env, packageRoot, decisions });
|
|
609
|
-
} catch (e) {
|
|
610
|
-
return send(res, 409, JSON.stringify({ error: e.message || String(e) }), 'application/json; charset=utf-8');
|
|
611
|
-
}
|
|
612
|
-
} else {
|
|
613
|
-
const err = [];
|
|
614
|
-
const code = await decisions.run(['answer', item, choice], { root, cwd: root, env, packageRoot, stdout: { write() {} }, stderr: { write: (x) => err.push(String(x)) } });
|
|
615
|
-
if (code !== 0) return send(res, 409, JSON.stringify({ error: tail(err.join(''), 300) || `decisions answer 退出码 ${code}` }), 'application/json; charset=utf-8');
|
|
616
|
-
ask = { id: '', item, question: item, context: '', options: [], record: '03-carryover/DECISIONS.md', from: {}, answer: { choice, note, at: fmtStamp(), by: 'page' } };
|
|
617
|
-
}
|
|
618
|
-
let dispatched = false;
|
|
619
|
-
const eng = engine || makeEngine();
|
|
620
|
-
if (eng) {
|
|
621
|
-
eng.answer(ask);
|
|
622
|
-
dispatched = true;
|
|
773
|
+
posted = JSON.parse(body || '{}');
|
|
774
|
+
} catch (error) {
|
|
775
|
+
return send(res, 400, JSON.stringify({ problems: [`请求体不是 JSON:${error.message}`] }), JSON_TYPE);
|
|
623
776
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
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);
|
|
639
812
|
}
|
|
640
813
|
|
|
641
814
|
// ---------------------------------------------------------------- 监控中心
|
|
642
|
-
const
|
|
643
|
-
|
|
644
|
-
const n = Number(seconds) || 0;
|
|
815
|
+
const fmtDur = (secs) => {
|
|
816
|
+
const n = Number(secs) || 0;
|
|
645
817
|
if (n < 60) return `${n} 秒`;
|
|
646
818
|
const m = Math.floor(n / 60);
|
|
647
819
|
return m >= 60 ? `${Math.floor(m / 60)} 小时 ${m % 60} 分` : `${m} 分 ${n % 60} 秒`;
|
|
@@ -652,19 +824,19 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
652
824
|
// 监控中心的数据:页面和 /status.json 是同一份
|
|
653
825
|
function monitorData() {
|
|
654
826
|
const alive = serviceAlive();
|
|
655
|
-
const st =
|
|
656
|
-
const
|
|
827
|
+
const st = makeEngine().status();
|
|
828
|
+
const team = roster();
|
|
657
829
|
return {
|
|
658
830
|
at: fmtStamp(),
|
|
659
|
-
service: { running: alive, pid: alive ? Number(readText(PID_FILE).trim()) : 0, since:
|
|
660
|
-
router: st
|
|
661
|
-
workers: st
|
|
662
|
-
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 },
|
|
663
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) })),
|
|
664
836
|
triggers: Object.values(store.data.triggers || {}).sort((a, b) => b.at.localeCompare(a.at) || b.id.localeCompare(a.id)).slice(0, 100),
|
|
665
837
|
sources: sourceStatus(),
|
|
666
838
|
refinedAt: store.data.refinedAt || '',
|
|
667
|
-
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 },
|
|
668
840
|
};
|
|
669
841
|
}
|
|
670
842
|
|
|
@@ -705,7 +877,7 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
705
877
|
l && l.lastOk ? esc(l.lastOk.slice(5, 16)) : '<span class="muted">—</span>',
|
|
706
878
|
];
|
|
707
879
|
});
|
|
708
|
-
const refine =
|
|
880
|
+
const refine = ` · 有新数据就提炼${d.config.refine ? '' : '(关着)'},间隔 ${d.config.refineInterval} 分钟`;
|
|
709
881
|
const last = d.refinedAt ? ` · 上次提炼 ${esc(d.refinedAt.slice(5, 16))}` : '';
|
|
710
882
|
return `<section class="card">
|
|
711
883
|
<div class="card-head"><h2>订阅源 <span class="muted">采集 ${esc(d.service.sync || '不定时')}${refine}${last}</span></h2><span class="pill">${enabled} 个启用</span></div>
|
|
@@ -713,7 +885,6 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
713
885
|
</section>`;
|
|
714
886
|
}
|
|
715
887
|
|
|
716
|
-
// 监控中心的「待办卡片」一块:等我拿主意的事(DECISIONS.md 里「未答」的行)
|
|
717
888
|
function monitorPage() {
|
|
718
889
|
const d = monitorData();
|
|
719
890
|
const statusPill = (t) => {
|
|
@@ -725,25 +896,32 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
725
896
|
if (s === 'stopped') return '<span class="pill is-amber">叫停</span>';
|
|
726
897
|
return `<span class="pill">${esc(s)}</span>`;
|
|
727
898
|
};
|
|
899
|
+
const runningNow = new Map(d.workers.running.map((w) => [w.id, w]));
|
|
728
900
|
const workerCell = (t) => {
|
|
729
901
|
if (!t.worker) return '<span class="muted">—</span>';
|
|
730
|
-
|
|
731
|
-
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>`;
|
|
732
906
|
return `${statusPill(t)}<br>${who}${extra}`;
|
|
733
907
|
};
|
|
734
|
-
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>');
|
|
735
909
|
const decision = (t) => `<strong>${esc(t.decision || '—')}</strong>${t.reason ? `<br><span class="muted">${esc(t.reason)}</span>` : ''}`;
|
|
736
910
|
const byId = triggersById(store.data);
|
|
911
|
+
// 每件在跑的:起于几点、已跑了多久;多久没输出(只有边跑边输出的 agent 有);最近一步是什么、几秒前记的
|
|
737
912
|
const running = d.workers.running.map((w) => {
|
|
738
913
|
const t = byId[w.id];
|
|
739
914
|
const sid = t && t.worker && t.worker.sessionId ? ` <code>${esc(t.worker.sessionId)}</code>` : '';
|
|
740
|
-
|
|
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>`;
|
|
741
918
|
}).join('');
|
|
742
919
|
const rs = d.router;
|
|
743
920
|
const session = rs.session ? (rs.session.own ? `专属会话${rs.session.id ? ` <code>${esc(rs.session.id)}</code>` : '(还没开)'}` : `绑定 <code>${esc(rs.session.id)}</code>`) : '—';
|
|
744
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>';
|
|
745
|
-
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>';
|
|
746
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('');
|
|
747
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>` })}
|
|
748
926
|
<script>(function(){var b=document.getElementById('refresh');setInterval(function(){if(b.checked&&document.visibilityState==='visible')location.reload()},10000)})();</script>
|
|
749
927
|
<div class="mon-grid">
|
|
@@ -754,15 +932,15 @@ function createRhythm({ root, env, packageRoot }) {
|
|
|
754
932
|
推送 ${d.service.push ? `开着(${esc(d.service.notifyChannel || '没配渠道')})` : '关着'} · 端口 <code>${d.service.port}</code></p>
|
|
755
933
|
</section>
|
|
756
934
|
<section class="card">
|
|
757
|
-
<div class="card-head"><h2
|
|
758
|
-
<p>${routerBadge}
|
|
759
|
-
<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>
|
|
760
938
|
</section>
|
|
761
939
|
<section class="card">
|
|
762
|
-
<div class="card-head"><h2
|
|
940
|
+
<div class="card-head"><h2>执行者 <a class="day-btn" href="/agents">配置</a></h2></div>
|
|
763
941
|
<p>${workerBadge}${d.workers.queued.length ? `<br>排队 ${d.workers.queued.map(short).join(' ')}` : ''}</p>
|
|
942
|
+
${groups ? `<ul class="ag-notes">${groups}</ul>` : ''}
|
|
764
943
|
${running ? `<ul style="margin:6px 0 8px;padding-left:18px;font-size:13px">${running}</ul>` : ''}
|
|
765
|
-
<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>
|
|
766
944
|
</section>
|
|
767
945
|
</div>
|
|
768
946
|
${sourcesCard(d)}
|
|
@@ -791,11 +969,9 @@ ${sourcesCard(d)}
|
|
|
791
969
|
]))}
|
|
792
970
|
</section>
|
|
793
971
|
<section class="card">
|
|
794
|
-
<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>
|
|
795
973
|
<div class="mon-kv">
|
|
796
|
-
<span class="pill">router: ${d.config.router}</span>
|
|
797
974
|
<span class="pill">router-timeout: ${d.config.routerTimeout}s</span>
|
|
798
|
-
<span class="pill">workers: ${d.config.workers}</span>
|
|
799
975
|
<span class="pill">refine: ${d.config.refine}</span>
|
|
800
976
|
<span class="pill">refine-interval: ${d.config.refineInterval}m</span>
|
|
801
977
|
<span class="pill">task-timeout: ${d.config.taskTimeout ? `${d.config.taskTimeout}s` : '不限'}</span>
|
|
@@ -827,8 +1003,8 @@ ${sourcesCard(d)}
|
|
|
827
1003
|
if (!node || launchd.looksLikeElectron(node, {})) problems.push(`常驻的 plist 里绑的不是真正的 node(${node || '没读到'}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
828
1004
|
else if (!fs.existsSync(node)) problems.push(`常驻的 plist 里绑的 node 不在了(${node}):work-rhythm rhythm uninstall 再 install 一次`);
|
|
829
1005
|
}
|
|
830
|
-
//
|
|
831
|
-
if (bot && botWanted()) problems.push(...
|
|
1006
|
+
// 值守开着的话,它的配置(渠道、钥匙串、我的 openId、路由和执行者的 agent)也要齐
|
|
1007
|
+
if (bot && botWanted()) problems.push(...botProblems());
|
|
832
1008
|
for (const [id, specText] of Object.entries(cfg.schedule)) {
|
|
833
1009
|
if (NOT_SERVICE_TASKS.includes(id)) continue;
|
|
834
1010
|
const spec = parseSpec(specText);
|
|
@@ -838,34 +1014,25 @@ ${sourcesCard(d)}
|
|
|
838
1014
|
}
|
|
839
1015
|
if (cfg.sync && parseSpec(cfg.sync).problem) problems.push(`采集的时间${parseSpec(cfg.sync).problem}`);
|
|
840
1016
|
if (!(cfg.port >= 1024 && cfg.port <= 65535)) problems.push(`rhythm.port 要是 1024 到 65535 之间的整数(现在是 ${cfg.port})`);
|
|
841
|
-
// 只有真有任务要跑时,agent
|
|
1017
|
+
// 只有真有任务要跑时,agent 和推送才必须配好;只采集、只看页面的用不着(值守的配置它自己查,见上)
|
|
842
1018
|
if (jobs().some((job) => job.kind === 'task' && job.hasPrompt)) {
|
|
843
|
-
problems.push(...
|
|
1019
|
+
problems.push(...agentsProblems());
|
|
844
1020
|
if (cfg.push && !cfg.notifyChannel) problems.push('rhythm.push 开着,但 preferences.notify 没配消息渠道:要么配一个,要么把 push 写成 false');
|
|
845
1021
|
}
|
|
846
|
-
//
|
|
1022
|
+
// 引擎的几个键:写了就得是正整数(没写用默认)
|
|
847
1023
|
for (const [key, name] of NEW_KEYS) {
|
|
848
1024
|
if (cfg.raw[key] !== undefined && !(Number.isInteger(Number(cfg.raw[key])) && Number(cfg.raw[key]) > 0)) problems.push(`${name} 要是正整数(现在是 ${cfg.raw[key]})`);
|
|
849
1025
|
}
|
|
850
|
-
// 路由开着时它的 agent 也要配得对(值守开着时 bot 那边查的是同一个)
|
|
851
|
-
if (cfg.router) problems.push(...routerDoctorProblems());
|
|
852
1026
|
// 启用着的源,采集脚本得在
|
|
853
1027
|
for (const x of sourceStatus()) if (x.missing) problems.push(`订阅源 ${x.id} 的采集脚本不存在:${x.collector}(sources.yaml 的 collector 写错了,或者脚本没放进 collectors/)`);
|
|
854
|
-
|
|
1028
|
+
// 值守开着时它的检查里已经带了路由和执行者的问题,别报两遍
|
|
1029
|
+
return [...new Set(problems)];
|
|
855
1030
|
}
|
|
856
1031
|
|
|
857
|
-
//
|
|
858
|
-
//
|
|
859
|
-
|
|
860
|
-
const r = roles(env).router;
|
|
861
|
-
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 })];
|
|
862
|
-
};
|
|
863
|
-
|
|
864
|
-
// 命令行里走一遍全流程(work-rhythm listen handle,路由开着时):在命令行的进程里建引擎,这句话变成一条触发,
|
|
865
|
-
// 要发的文字交给 sink(带 push 才真发),等到队列空、执行者都结束。返回 { id, texts } 或者 null(路由没开)
|
|
866
|
-
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 } = {}) {
|
|
867
1035
|
const eng = makeEngine();
|
|
868
|
-
if (!eng) return null;
|
|
869
1036
|
const texts = [];
|
|
870
1037
|
if (!really) eng.setSink((t) => texts.push(t));
|
|
871
1038
|
const t = eng.enqueue('message', { key: `handle-${Date.now()}`, msgId: 'handle', text, mode: (env.YZJ_BOT_AGENT_MODE || 'plan').trim() });
|
|
@@ -874,12 +1041,10 @@ ${sourcesCard(d)}
|
|
|
874
1041
|
return { id: t ? t.id : '', texts };
|
|
875
1042
|
}
|
|
876
1043
|
|
|
877
|
-
// 不算问题、但要让人知道的事(doctor
|
|
878
|
-
function doctorNotes(
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
const notes = cfg.router ? createAgent({ root, agent: r.agent, mode: 'plan', env, model: r.model, effort: r.effort }).notes() : [];
|
|
882
|
-
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('推送关不掉又没配渠道:路由写给用户的话发不出去,只记日志');
|
|
883
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}`);
|
|
884
1049
|
return notes;
|
|
885
1050
|
}
|
|
@@ -894,24 +1059,23 @@ ${sourcesCard(d)}
|
|
|
894
1059
|
});
|
|
895
1060
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
896
1061
|
fs.writeFileSync(PID_FILE, `${process.pid}\n`);
|
|
897
|
-
|
|
1062
|
+
const team = roster();
|
|
1063
|
+
log('服务开始', `pid=${process.pid} 页面=${baseUrl()} 路由=${team.router.agent || '(没配)'}`);
|
|
898
1064
|
process.stdout.write(`页面:${baseUrl()} 停:work-rhythm rhythm stop\n`);
|
|
899
1065
|
|
|
900
1066
|
// 值守(机器人的收消息一半)也在这里跑:一个后台进程管定时任务、推送、网页和值守。默认开着(collectors/local.env 写 YZJ_BOT_LISTEN=0 才关);
|
|
901
1067
|
// 配置有问题不拦着服务起,只记一笔——定时任务和网页照常
|
|
902
1068
|
let bot = null;
|
|
903
1069
|
let botTask = null;
|
|
904
|
-
//
|
|
1070
|
+
// 引擎在这个进程里跑(触发 → 路由 → 执行者 → 汇报)。上次没跑完的执行者先补失败回执,交回路由
|
|
905
1071
|
const eng = makeEngine();
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
log('引擎开始', `路由=${roles(env).router.agent} 执行者=${workerSpec().agent} 并发=${cfg.workers}`);
|
|
910
|
-
}
|
|
1072
|
+
eng.recover();
|
|
1073
|
+
eng.tick();
|
|
1074
|
+
log('引擎开始', `路由=${team.router.agent || '没绑'} 执行者=${team.workers.map((w) => `${w.id} ${w.agent || '没绑'}×${w.count}`).join(',') || '没有'}`);
|
|
911
1075
|
if (botWanted()) {
|
|
912
|
-
bot = createBot({ root, env, onMessage:
|
|
913
|
-
const
|
|
914
|
-
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(';'));
|
|
915
1079
|
else {
|
|
916
1080
|
botTask = bot.run({ signals: false }).then(
|
|
917
1081
|
() => log('值守结束'),
|
|
@@ -920,6 +1084,7 @@ ${sourcesCard(d)}
|
|
|
920
1084
|
}
|
|
921
1085
|
}
|
|
922
1086
|
|
|
1087
|
+
// 只有采集走这条队列(另起子进程,采集是同步的脚本);到点的任务直接交给引擎
|
|
923
1088
|
const list = jobs();
|
|
924
1089
|
const state = store.data;
|
|
925
1090
|
let running = null;
|
|
@@ -930,50 +1095,25 @@ ${sourcesCard(d)}
|
|
|
930
1095
|
running = startJob(job);
|
|
931
1096
|
running.on('exit', (code) => {
|
|
932
1097
|
state.runs[job.id] = { at: fmtStamp(), ok: code === 0, code };
|
|
933
|
-
// 监控中心的运行记录
|
|
934
|
-
if (job.kind === 'task') {
|
|
935
|
-
const w = workerSpec();
|
|
936
|
-
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 });
|
|
937
|
-
}
|
|
938
1098
|
saveState(state);
|
|
939
1099
|
log('跑完', `${job.id} rc=${code}`);
|
|
940
1100
|
running = null;
|
|
941
1101
|
startNext();
|
|
942
1102
|
// 采集是有新数据才提炼:子进程把每个源的结果和「有没有新数据」留在 last-sync.json,这里交给引擎
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
eng.afterSync({ results: last.results || [], changed: Boolean(last.changed) });
|
|
950
|
-
}
|
|
951
|
-
} catch (error) {
|
|
952
|
-
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) });
|
|
953
1109
|
}
|
|
1110
|
+
} catch (error) {
|
|
1111
|
+
log('采集结果读不了', error && error.message ? error.message : String(error));
|
|
954
1112
|
}
|
|
955
1113
|
});
|
|
956
1114
|
};
|
|
957
|
-
// 隔天过期:今天以前还没答的卡片标成「过期未答」。每天第一次看表时做一遍(服务一启动也会),做成了才记这一天
|
|
958
|
-
let expiring = false;
|
|
959
|
-
const expireOldCards = async () => {
|
|
960
|
-
const day = fmtDate(new Date());
|
|
961
|
-
if (state.cardsExpiredOn === day || expiring) return;
|
|
962
|
-
expiring = true;
|
|
963
|
-
try {
|
|
964
|
-
const n = await asks.expireCards(root, { env, packageRoot, decisions, today: day });
|
|
965
|
-
state.cardsExpiredOn = day;
|
|
966
|
-
saveState(state);
|
|
967
|
-
if (n) log('待你定', `${n} 张今天以前的卡片过期未答`);
|
|
968
|
-
} catch (error) {
|
|
969
|
-
log('卡片过期没做成', error && error.message ? error.message : String(error));
|
|
970
|
-
} finally {
|
|
971
|
-
expiring = false;
|
|
972
|
-
}
|
|
973
|
-
};
|
|
974
1115
|
const tick = () => {
|
|
975
|
-
|
|
976
|
-
if (eng) eng.tick();
|
|
1116
|
+
eng.tick();
|
|
977
1117
|
const now = new Date();
|
|
978
1118
|
for (const job of list) {
|
|
979
1119
|
for (const minute of timesOn(job.spec, now)) {
|
|
@@ -989,8 +1129,8 @@ ${sourcesCard(d)}
|
|
|
989
1129
|
continue;
|
|
990
1130
|
}
|
|
991
1131
|
log('到点', `${job.id} ${hhmm(at)}`);
|
|
992
|
-
if (job.kind === 'task'
|
|
993
|
-
//
|
|
1132
|
+
if (job.kind === 'task') {
|
|
1133
|
+
// 任务变成一条触发交给路由,由它挑一组执行者派出去
|
|
994
1134
|
const body = fs.readFileSync(path.join(root, 'tasks', `${job.id}.md`), 'utf8');
|
|
995
1135
|
eng.schedule({ id: job.id, key }, body, taskTitleOf(body));
|
|
996
1136
|
continue;
|
|
@@ -1015,8 +1155,7 @@ ${sourcesCard(d)}
|
|
|
1015
1155
|
}
|
|
1016
1156
|
// 在跑的执行者是子进程,不收掉会留着:停掉它们(引擎里最多等 3 秒),再关网页
|
|
1017
1157
|
const close = () => server.close(() => resolve());
|
|
1018
|
-
|
|
1019
|
-
else close();
|
|
1158
|
+
eng.shutdown().then(close, close);
|
|
1020
1159
|
setTimeout(resolve, 4500).unref();
|
|
1021
1160
|
};
|
|
1022
1161
|
process.on('SIGINT', () => stop('SIGINT'));
|
|
@@ -1056,11 +1195,12 @@ ${sourcesCard(d)}
|
|
|
1056
1195
|
const botLog = readText(path.join(root, '01-inbox', '_bot.log')).trim().split('\n');
|
|
1057
1196
|
const lastBot = botLog.length && botLog[botLog.length - 1] ? botLog[botLog.length - 1] : '';
|
|
1058
1197
|
lines.push(`值守:${botWanted() ? `开着${lastBot ? `,最近 ${lastBot}` : ''}` : '关着(collectors/local.env 的 YZJ_BOT_LISTEN=1 打开,改完 work-rhythm rhythm restart)'}`);
|
|
1059
|
-
const
|
|
1060
|
-
const w = workerSpec();
|
|
1198
|
+
const team = roster();
|
|
1061
1199
|
const rounds = (store.data.rounds || []).filter((x) => x.at.startsWith(fmtDate(new Date()))).length;
|
|
1062
|
-
lines.push(
|
|
1063
|
-
|
|
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`);
|
|
1064
1204
|
// 订阅源:几个正常、谁在连着失败、谁还没跑过
|
|
1065
1205
|
const srcs = sourceStatus().filter((x) => x.enabled);
|
|
1066
1206
|
if (srcs.length) {
|
|
@@ -1087,6 +1227,8 @@ ${sourcesCard(d)}
|
|
|
1087
1227
|
due,
|
|
1088
1228
|
monitorData,
|
|
1089
1229
|
monitorPage,
|
|
1230
|
+
agentsData,
|
|
1231
|
+
agentsPage,
|
|
1090
1232
|
doctorNotes,
|
|
1091
1233
|
recordForTest: (id, r) => recordSources([{ id, ...r }]),
|
|
1092
1234
|
handle,
|
|
@@ -1107,4 +1249,4 @@ ${sourcesCard(d)}
|
|
|
1107
1249
|
};
|
|
1108
1250
|
}
|
|
1109
1251
|
|
|
1110
|
-
module.exports = { createRhythm, loadConfig, parseSpec, LINKS, NOT_SERVICE_TASKS };
|
|
1252
|
+
module.exports = { createRhythm, loadConfig, parseSpec, LINKS, NOT_SERVICE_TASKS, ALWAYS_QUIET };
|