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.
Files changed (74) hide show
  1. package/.agents/notes/AGENTS.md +10 -3
  2. package/.agents/notes/decisions/2026-11-30-bot-inbound-uses-websocket-and-a-responder-command.md +1 -0
  3. package/.agents/notes/decisions/2026-11-30-skill-ships-with-its-template-in-a-zip.md +1 -0
  4. package/.agents/notes/decisions/2026-12-01-agent-binding-asks-for-model-and-effort.md +1 -0
  5. package/.agents/notes/decisions/2026-12-01-interjections-batch-into-one-answer-and-interrupt-reruns.md +1 -0
  6. package/.agents/notes/decisions/2026-12-01-question-cards-via-cli-tool-on-todays-page-answers-return-to-router.md +4 -0
  7. package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +1 -0
  8. package/.agents/notes/decisions/2026-12-01-router-runs-on-a-flash-model-with-low-effort.md +1 -0
  9. package/.agents/notes/decisions/2026-12-01-sync-feeds-refine-then-events-to-the-router.md +4 -0
  10. package/.agents/notes/decisions/2026-12-03-codex-cli-joins-as-a-preset-verified-against-its-own-binary.md +45 -0
  11. package/.agents/notes/decisions/2026-12-03-fewer-scheduled-tasks-silent-refine-no-question-cards.md +46 -0
  12. package/.agents/notes/decisions/2026-12-03-playbook-distills-handoffs-into-ws-tool-and-skill-know-how.md +43 -0
  13. package/.agents/notes/decisions/2026-12-03-related-work-comes-back-as-one-reply.md +49 -0
  14. package/.agents/notes/decisions/2026-12-03-roster-of-worker-groups-router-picks-the-group.md +33 -0
  15. package/.agents/notes/decisions/2026-12-03-router-model-and-effort-are-configurable.md +28 -0
  16. package/.agents/notes/decisions/2026-12-03-router-only-direct-mode-removed.md +27 -0
  17. package/.agents/notes/decisions/2026-12-03-unattended-runs-decide-on-their-own.md +32 -0
  18. package/.agents/notes/decisions/2026-12-03-update-upgrades-package-and-refreshes-shipped-files.md +30 -0
  19. package/.agents/notes/decisions/2026-12-03-workers-leave-a-status-trail-that-joins-the-receipt.md +31 -0
  20. package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +2 -0
  21. package/.agents/notes/pitfalls/2026-12-03-judging-a-symlink-by-realpath-ignores-parent-links.md +18 -0
  22. package/.agents/skills/work-rhythm/SKILL.md +21 -17
  23. package/README.md +13 -10
  24. package/collectors/local.env.example +31 -36
  25. package/docs/agents.md +61 -60
  26. package/docs/channels.md +15 -19
  27. package/docs/formats.md +28 -1
  28. package/docs/router-worker.md +67 -54
  29. package/docs/scheduled-tasks.md +14 -14
  30. package/docs/sources.md +5 -6
  31. package/package.json +1 -1
  32. package/scripts/cli.js +9 -5
  33. package/scripts/cmd/agent.js +348 -235
  34. package/scripts/cmd/ask.js +18 -76
  35. package/scripts/cmd/check.js +14 -7
  36. package/scripts/cmd/listen.js +33 -32
  37. package/scripts/cmd/pack.js +6 -6
  38. package/scripts/cmd/rhythm.js +13 -10
  39. package/scripts/cmd/trigger.js +23 -14
  40. package/scripts/cmd/update.js +92 -0
  41. package/scripts/lib/agent.js +235 -142
  42. package/scripts/lib/agents.js +179 -0
  43. package/scripts/lib/bot.js +44 -263
  44. package/scripts/lib/engine.js +345 -170
  45. package/scripts/lib/handoff.js +54 -8
  46. package/scripts/lib/markdown.js +19 -0
  47. package/scripts/lib/playbook.js +123 -0
  48. package/scripts/lib/rhythm.js +402 -260
  49. package/scripts/lib/router.js +52 -46
  50. package/scripts/lib/template.js +3 -3
  51. package/scripts/lib/update.js +279 -0
  52. package/scripts/lib/view.js +7 -152
  53. package/scripts/lib/worker.js +11 -5
  54. package/scripts/test/agent.test.js +410 -257
  55. package/scripts/test/check.test.js +17 -6
  56. package/scripts/test/harness.js +5 -2
  57. package/scripts/test/listen.test.js +190 -158
  58. package/scripts/test/playbook.test.js +106 -0
  59. package/scripts/test/rhythm.test.js +167 -109
  60. package/scripts/test/roster.test.js +155 -0
  61. package/scripts/test/router-helper.js +17 -2
  62. package/scripts/test/router.test.js +499 -414
  63. package/scripts/test/stubs.js +51 -4
  64. package/scripts/test/timeout.test.js +160 -59
  65. package/scripts/test/update.test.js +384 -0
  66. package/tasks/daily-persona.md +30 -13
  67. package/tasks/daily-plan.md +4 -3
  68. package/tasks/evening-review.md +1 -2
  69. package/tasks/noon-checkin.md +2 -1
  70. package/templates/00-config/profile.example.yaml +17 -13
  71. package/templates/04-patterns/PERSONA.md +4 -1
  72. package/templates/04-patterns/PLAYBOOK.md +13 -0
  73. package/templates/AGENTS.md +7 -3
  74. package/templates/README.md +10 -9
@@ -0,0 +1,179 @@
1
+ // 路由和执行者的名册:路由用哪个 agent、模型、思考强度;有哪几组执行者,每组用哪个 agent、模型、强度,同时跑几个。
2
+ // 存在 00-config/agents.json(程序读写,不碰 profile.yaml 的手写格式):本机网页 /agents 和 work-rhythm agent 写它。
3
+ // 没有这个文件时从 collectors/local.env 的老键推出一组——路由 + 一组执行者(YZJ_ROUTER_* / YZJ_WORKER_*,没单独配的落到 YZJ_BOT_*),
4
+ // 老工作目录不用改配置照常跑,第一次保存才生成这个文件。执行者每次都是新会话,名册里没有会话;路由的会话在 local.env(routerSession)。
5
+ // 只用 node 自带的能力。
6
+ 'use strict';
7
+ const path = require('node:path');
8
+ const { readText, writeFileAtomic } = require('./run');
9
+ const { loadProfile, writeLocalEnv } = require('./config');
10
+ const { createAgent, DEFAULT_ROUTER_EFFORT, MODEL_SUPPORT, presetKind, routerNotes } = require('./agent');
11
+
12
+ const REL = '00-config/agents.json';
13
+ // 一组执行者同时最多跑几个(网页和命令行都按这个上限收口)
14
+ const MAX_COUNT = 16;
15
+ // 老写法里没写 rhythm.workers 时,那一组执行者同时跑几个
16
+ const DEFAULT_COUNT = 3;
17
+
18
+ const s = (v) => String(v == null ? '' : v).trim();
19
+ const fileOf = (root) => path.join(root, REL);
20
+ const countOf = (value, fallback) => {
21
+ const n = Number(value);
22
+ return Number.isInteger(n) && n > 0 ? Math.min(n, MAX_COUNT) : fallback;
23
+ };
24
+ // 执行者编号里的数字:w2 → 2,不是这种样子是 0
25
+ const numOf = (id) => {
26
+ const m = /^w(\d+)$/.exec(String(id || ''));
27
+ return m ? Number(m[1]) : 0;
28
+ };
29
+ // 这个 agent 认不认思考强度(自定义命令和我们无关,认;zcode 的命令行没有这个参数,不认)
30
+ const takesEffort = (agent) => {
31
+ const kind = presetKind(agent);
32
+ return kind === 'custom' || Boolean(MODEL_SUPPORT[kind].effort);
33
+ };
34
+
35
+ // 一处配置(路由,或者一组执行者)的 agent、模型、强度:都当成去掉首尾空白的字符串
36
+ const entry = (x) => ({ agent: s(x && x.agent), model: s(x && x.model), effort: s(x && x.effort) });
37
+
38
+ // 把一份名册读成固定的样子:没写编号的执行者按顺序补 w1、w2…;编号重了的换个不重的;数量不是正整数就是 1。
39
+ // seq 是发过的最大编号(删掉的编号不复用:运行记录里的 w2 永远指同一组)
40
+ function normalize(doc) {
41
+ const router = entry(doc && doc.router);
42
+ const workers = [];
43
+ const seen = new Set();
44
+ for (const raw of Array.isArray(doc && doc.workers) ? doc.workers : []) {
45
+ const e = entry(raw);
46
+ if (!e.agent) continue;
47
+ const base = s(raw && raw.id) || `w${workers.length + 1}`;
48
+ let id = base;
49
+ for (let n = 2; seen.has(id); n += 1) id = `${base}-${n}`;
50
+ seen.add(id);
51
+ workers.push({ id, ...e, count: countOf(raw && raw.count, 1) });
52
+ }
53
+ return { router, workers, seq: Math.max(Number(doc && doc.seq) || 0, ...workers.map((w) => numOf(w.id))) };
54
+ }
55
+
56
+ // 配不了的(zcode 配不了模型和强度)就不给它带上:老键是给别的 agent 配的,换 agent 时会带过来
57
+ function fit(agent, model, effort) {
58
+ const kind = presetKind(agent);
59
+ if (kind === 'custom') return { model, effort };
60
+ const support = MODEL_SUPPORT[kind];
61
+ return { model: support.model ? model : '', effort: support.effort ? effort : '' };
62
+ }
63
+
64
+ // 老写法(没有 agents.json 时):路由和一组执行者都从 local.env 来,没单独配的落到 YZJ_BOT_*;那一组同时跑几个看 profile 的
65
+ // rhythm.workers(默认 3),模型和强度也认 profile 的 rhythm.agent-model / agent-effort。路由的强度不跟着 YZJ_BOT_EFFORT 走,默认 low(agent 不认强度的就不给)
66
+ function fromEnv(root, env) {
67
+ const rhythm = (loadProfile(root).rhythm || {});
68
+ const bot = { agent: s(env.YZJ_BOT_AGENT), model: s(env.YZJ_BOT_MODEL), effort: s(env.YZJ_BOT_EFFORT) };
69
+ const routerAgent = s(env.YZJ_ROUTER_AGENT) || bot.agent;
70
+ const workerAgent = s(env.YZJ_WORKER_AGENT) || bot.agent;
71
+ return {
72
+ router: { agent: routerAgent, ...fit(routerAgent, s(env.YZJ_ROUTER_MODEL) || bot.model, s(env.YZJ_ROUTER_EFFORT) || (takesEffort(routerAgent) ? DEFAULT_ROUTER_EFFORT : '')) },
73
+ workers: [{
74
+ id: 'w1',
75
+ agent: workerAgent,
76
+ ...fit(workerAgent, s(env.YZJ_WORKER_MODEL) || s(rhythm['agent-model']) || bot.model, s(env.YZJ_WORKER_EFFORT) || s(rhythm['agent-effort']) || bot.effort),
77
+ count: countOf(rhythm.workers, DEFAULT_COUNT),
78
+ }],
79
+ seq: 0,
80
+ };
81
+ }
82
+
83
+ // 路由从哪个会话接着走:YZJ_ROUTER_SESSION;没写时,路由的 agent 就是老键 YZJ_BOT_AGENT 的那个才认 YZJ_BOT_SESSION(别的 agent 的会话 id 它接不上)
84
+ function routerSession(env, routerAgent) {
85
+ return s(env.YZJ_ROUTER_SESSION) || (routerAgent && routerAgent === s(env.YZJ_BOT_AGENT) ? s(env.YZJ_BOT_SESSION) : '');
86
+ }
87
+
88
+ // 现在生效的名册:{ source: 'file' | 'env', file, router, workers, problems }。problems 是文件本身的毛病(JSON 坏了、没写路由、一组执行者都没有)
89
+ function loadRoster(root, env = process.env) {
90
+ const file = fileOf(root);
91
+ const text = readText(file);
92
+ if (!text.trim()) return { source: 'env', file, ...fromEnv(root, env), problems: [] };
93
+ let doc;
94
+ try {
95
+ doc = JSON.parse(text);
96
+ } catch (error) {
97
+ return { source: 'file', file, router: entry(null), workers: [], problems: [`${REL} 不是合法的 JSON(${error.message}):改好它,或者删掉它回到 local.env 的老写法`] };
98
+ }
99
+ const roster = { source: 'file', file, ...normalize(doc), problems: [] };
100
+ return roster;
101
+ }
102
+
103
+ // 写名册(存的是 normalize 之后的样子)。没给 seq 就接着盘上那份的:发过的编号只增不减
104
+ function saveRoster(root, cfg) {
105
+ let prev = 0;
106
+ try {
107
+ prev = Number(JSON.parse(readText(fileOf(root))).seq) || 0;
108
+ } catch {
109
+ // 还没有这个文件,或者它坏了
110
+ }
111
+ const doc = normalize({ ...cfg, seq: Math.max(prev, Number(cfg && cfg.seq) || 0) });
112
+ writeFileAtomic(fileOf(root), `${JSON.stringify(doc, null, 2)}\n`);
113
+ return doc;
114
+ }
115
+
116
+ // 名册里的配置有没有问题(doctor、check、网页保存前都用它):agent 找得到、模型和强度它认;路由和执行者都得有。
117
+ // 返回 { problems, notes }:problems 拦着不让跑,notes 只是要让人知道
118
+ function inspect(root, env, roster) {
119
+ const problems = [...roster.problems];
120
+ const notes = [];
121
+ // 每处怎么称呼:带 agent 是「路由(dsh)」,没绑是「路由 」
122
+ const name = (what, agent) => (agent ? `${what}(${agent})` : `${what} `);
123
+ const look = (where, e, mode, hint) => {
124
+ if (!e.agent) {
125
+ problems.push(`${where}没绑 agent:work-rhythm agent bind ${hint},或者在本机网页的 /agents 里配`);
126
+ return;
127
+ }
128
+ const a = createAgent({ root, agent: e.agent, mode, env, model: e.model, effort: e.effort });
129
+ for (const p of a.doctor()) problems.push(`${where}:${p}`);
130
+ for (const n of a.notes()) notes.push(`${where}:${n}`);
131
+ };
132
+ look(name('路由', roster.router.agent), roster.router, 'plan', 'router <名字>');
133
+ if (roster.router.agent) for (const n of routerNotes(roster.router)) notes.push(`路由:${n}`);
134
+ if (!roster.workers.length) problems.push('一组执行者都没有:work-rhythm agent worker add <名字> 加一组');
135
+ roster.workers.forEach((w) => look(name(`执行者 ${w.id}`, w.agent), w, 'edit', 'worker <名字>'));
136
+ return { problems, notes };
137
+ }
138
+
139
+ // 改路由,写进名册。换了 agent 就把原来绑的会话清掉(一个 agent 的会话 id 别的接不上);session 明确给了(空串也算)就照它写进 local.env。
140
+ // 返回是不是换了 agent
141
+ function setRouter(root, env, router, { session } = {}) {
142
+ const roster = loadRoster(root, env);
143
+ const changed = roster.router.agent !== entry(router).agent;
144
+ saveRoster(root, { router: entry(router), workers: roster.workers });
145
+ if (session !== undefined) writeLocalEnv(root, { YZJ_ROUTER_SESSION: session });
146
+ else if (changed) writeLocalEnv(root, { YZJ_ROUTER_SESSION: '' });
147
+ return changed;
148
+ }
149
+
150
+ // 新的一组执行者的编号:比发过的最大编号大一(删掉的不复用,日志和监控里对得上)
151
+ function nextId(workers, seq = 0) {
152
+ return `w${Math.max(Number(seq) || 0, ...workers.map((w) => numOf(w.id)), 0) + 1}`;
153
+ }
154
+
155
+ // 改一组执行者(编号对上就改那组),或者加一组(不给编号)。没给数量就沿用那组原来的,新组是 1。返回写进名册的那一组
156
+ function setWorker(root, env, worker) {
157
+ const roster = loadRoster(root, env);
158
+ const e = entry(worker);
159
+ const id = s(worker.id) || nextId(roster.workers, roster.seq);
160
+ const at = roster.workers.findIndex((w) => w.id === id);
161
+ const next = { id, ...e, count: worker.count === undefined ? (at >= 0 ? roster.workers[at].count : 1) : countOf(worker.count, 1) };
162
+ const workers = at >= 0 ? roster.workers.map((w, i) => (i === at ? next : w)) : [...roster.workers, next];
163
+ saveRoster(root, { router: roster.router, workers, seq: Math.max(roster.seq, numOf(id)) });
164
+ return next;
165
+ }
166
+
167
+ // 去掉一组执行者。至少留一组:返回 false 就是没删
168
+ function removeWorker(root, env, id) {
169
+ const roster = loadRoster(root, env);
170
+ const workers = roster.workers.filter((w) => w.id !== s(id));
171
+ if (!workers.length || workers.length === roster.workers.length) return false;
172
+ saveRoster(root, { router: roster.router, workers, seq: roster.seq });
173
+ return true;
174
+ }
175
+
176
+ // 路由实际用的思考强度:没写就是默认的 low;agent 不认强度的(zcode)是空串——用它自己的默认
177
+ const routerEffort = (router) => { const e = entry(router); return e.effort || (takesEffort(e.agent) ? DEFAULT_ROUTER_EFFORT : ''); };
178
+
179
+ module.exports = { REL, MAX_COUNT, DEFAULT_COUNT, normalize, entry, takesEffort, routerEffort, fit, fromEnv, routerSession, loadRoster, saveRoster, inspect, setRouter, setWorker, removeWorker, nextId };
@@ -1,6 +1,7 @@
1
- // 值守:消息渠道的收消息一半。和云之家个人机器人保持 WebSocket 长连接,收到我本人的消息就交给本地的 agent,回复经推送(notify.js)发回来。
1
+ // 值守:消息渠道的收消息一半。和云之家个人机器人保持 WebSocket 长连接,收到我本人的消息就交给引擎(engine.js)。
2
+ // 它只管收——本人校验、去重、/new;别的话变成触发交给路由判断、派给执行者,回复由引擎经推送(notify.js)发回来。
2
3
  // 入口是 work-rhythm listen(用法和配置写在 cmd/listen.js)。只用 node 自带的能力,需要 node 22 以上(全局 WebSocket),不装第三方包。
3
- // 怎么调起 agent 在 agent.js。协议照官方插件 kingdee/openclaw-yzj 的客户端做,2026-11-30 对照实测:
4
+ // 协议照官方插件 kingdee/openclaw-yzj 的客户端做,2026-11-30 对照实测:
4
5
  // 地址由发送地址推导:wss://<域名>/xuntong/websocket?yzjtoken=<同一个 token>;
5
6
  // 业务消息包在 {"cmd":"directPush","type":"robotMessage","msg":{…}} 里,不带 needAck,不用回 ack;
6
7
  // 控制帧用 cmd / type / event 表意(auth、pong、extSystemMsg…),带 needAck 和 seq 的要回 {"cmd":"ack","seq":N};
@@ -8,25 +9,15 @@
8
9
  'use strict';
9
10
  const fs = require('node:fs');
10
11
  const path = require('node:path');
11
- const { EXIT, Fail, fmtStamp, seconds, humanDuration, progressPings } = require('./run');
12
+ const { EXIT, Fail, fmtStamp } = require('./run');
12
13
  const { logger } = require('./log');
13
- const { notifyChannel, pushText } = require('./notify');
14
+ const { notifyChannel } = require('./notify');
14
15
  const { findWebhook, mask } = require('./robot');
15
- const { createAgent } = require('./agent');
16
16
 
17
17
  const SEEN_KEEP = 500;
18
18
  const HEARTBEAT_MS = 15000;
19
19
  const STALE_MS = 45000;
20
20
  const RECONNECT_DELAYS_MS = [1000, 2000, 5000, 10000, 30000, 60000];
21
- const ACK_TEXT = '收到,正在处理,稍等。';
22
- // 上一句还没答完又来一句:先回这句,告诉他会和上一句一起考虑
23
- const ACK_MORE_TEXT = '收到,上一句还在答,这句会和它一起考虑。';
24
- const DEFAULT_PREAMBLE = '(这句来自云之家:你的回复会原样以纯文本私聊发给人类看。务必简洁明了、直说结论,去掉背景铺垫和内部过程,不用表格,以一眼看懂为准;要查很久就先说大概要多久。)';
25
-
26
- const positiveInt = (value, fallback) => {
27
- const n = Number(value);
28
- return Number.isInteger(n) && n > 0 ? n : fallback;
29
- };
30
21
 
31
22
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
32
23
 
@@ -147,97 +138,48 @@ function openSocket(url, onFrame, log) {
147
138
 
148
139
  const reconnectDelay = (attempts) => RECONNECT_DELAYS_MS[Math.min(Math.max(attempts - 1, 0), RECONNECT_DELAYS_MS.length - 1)];
149
140
 
150
- // 建一个值守对象。env 是设置(环境变量,上面盖一层 local.env),配置都在里面:
151
- // YZJ_BOT_AGENT 让哪个 agent 回复(zcode、dsh,或一条自己的命令)、YZJ_BOT_AGENT_MODE(plan 只读 / edit 可写,默认 plan)、
152
- // YZJ_MY_OPEN_ID 只认我本人、YZJ_BOT_TIMEOUT 一次最多等几秒(硬上限,默认 900)、YZJ_BOT_IDLE 多久没输出算卡住(默认 180,0 不查)、
153
- // YZJ_BOT_PROGRESS 跑多久先说一声还在做(默认 90 秒,0 不说)、YZJ_BOT_REPLY_MAX 回复最多几个字、
154
- // YZJ_BOT_ACK=0 关掉「收到,正在处理」那句、YZJ_BOT_PREAMBLE 换掉或清空随每句话带给 agent 的提示
155
- // 路由开着时(profile 的 rhythm.router,本地服务传进来):值守只管收——本人校验、去重、/new——收到的话变成触发交给
156
- // onMessage(engine.js),由路由判断再派给执行者,回复也由引擎发。这时配置查的是路由的 agent(doctorAgent),/new 调 resetSession
157
- function createBot({ root, env, onMessage = null, resetSession = null, doctorAgent = null }) {
141
+ // 建一个值守对象。env 是设置(环境变量,上面盖一层 local.env):YZJ_MY_OPEN_ID 只认我本人的消息。
142
+ // onMessage({ msgId, content, time, groupType }) 把我的一句话交给引擎,返回那条触发的记录(重复的、还在防抖里合成的返回 null);
143
+ // resetSession 是聊天里发 /new 时调的(丢掉路由自己的专属会话),say(text) 把那句确认发回 IM(引擎的发法:命令行走一遍时打到屏幕上);
144
+ // doctorAgent 查路由和执行者的配置,返回问题的数组。
145
+ // 别的回复不从值守发:引擎交给路由判断,要发的话它自己经 work-rhythm notify 发
146
+ const NEW_TEXT = '已开新会话,下一句从绑定的那个会话接着走。';
147
+ function createBot({ root, env, onMessage, resetSession = null, say = null, doctorAgent = null }) {
158
148
  const STATE_DIR = path.join(root, '01-inbox', '_bot');
159
149
  const LOG_FILE = path.join(root, '01-inbox', '_bot.log');
160
- const SESSION_FILE = path.join(STATE_DIR, 'session-id');
161
150
  const SEEN_FILE = path.join(STATE_DIR, 'seen-msgids');
162
151
  const log = logger(LOG_FILE);
163
152
  const OWNER = (env.YZJ_MY_OPEN_ID || '').trim();
164
- const AGENT = (env.YZJ_BOT_AGENT || '').trim();
165
- const AGENT_MODE = (env.YZJ_BOT_AGENT_MODE || 'plan').trim();
166
- const TIMEOUT_S = positiveInt(env.YZJ_BOT_TIMEOUT, 900);
167
- // 静默闸:一直在吐输出的 agent(dsh、kimi)多久没动静才算卡住;0 关掉,只看硬上限
168
- const IDLE_S = seconds(env.YZJ_BOT_IDLE, 180);
169
- // 跑得久先说一声,省得我对着屏幕猜它死没死。第一条 PROGRESS_S 秒后,之后每条隔 2 倍
170
- const PROGRESS_S = seconds(env.YZJ_BOT_PROGRESS, 90);
171
- const PROGRESS_MAX = positiveInt(env.YZJ_BOT_PROGRESS_MAX, 3);
172
- const REPLY_MAX = positiveInt(env.YZJ_BOT_REPLY_MAX, 2000);
173
- // 收到就先回一句,agent 慢的时候我不用干等
174
- const ACK = env.YZJ_BOT_ACK !== '0';
175
- // 绑定的会话(collectors/local.env 的 YZJ_BOT_SESSION):绑 agent 时顺手把用户当时所在的会话绑上,
176
- // IM 里的话就从那个会话接着走,上下文是连着的。没绑就用值守自己的专属会话;绑的接不上(被删、过期)就退回专属会话
177
- const BOUND_SESSION = (env.YZJ_BOT_SESSION || '').trim();
178
- const PREAMBLE = env.YZJ_BOT_PREAMBLE !== undefined ? env.YZJ_BOT_PREAMBLE : DEFAULT_PREAMBLE;
179
- // 模型和思考强度(collectors/local.env 的 YZJ_BOT_MODEL / YZJ_BOT_EFFORT),只有支持的预置才认;不写就用 agent 自己的默认
180
- const agent = createAgent({ root, agent: AGENT, mode: AGENT_MODE, timeoutS: TIMEOUT_S, idleS: IDLE_S, preamble: PREAMBLE, log, env, model: (env.YZJ_BOT_MODEL || '').trim(), effort: (env.YZJ_BOT_EFFORT || '').trim() });
181
153
 
182
154
  // ---------------------------------------------------------------- 配置
183
155
  // 检查值守的配置和依赖:有问题一条一个字符串;没问题就是空数组。check 配了值守时也调它
184
156
  function doctorProblems() {
185
157
  const problems = [];
158
+ if (!onMessage) problems.push('值守没有交给谁:它只管收,消息要交给路由(本地服务里才有引擎)');
186
159
  if (notifyChannel(root) !== 'yzj-robot') problems.push('值守属于 yzj-robot 渠道:preferences.notify 要设成 yzj-robot');
187
160
  if (!findWebhook(env).webhook) problems.push(`钥匙串里没有 ${env.YZJ_ROBOT_KEYCHAIN_SERVICE || 'work-rhythm-yzj-robot-webhook'}(开通步骤见 docs/channels.md「云之家」)`);
188
161
  if (!OWNER) problems.push('值守只处理我本人的消息:collectors/local.env 里要写 YZJ_MY_OPEN_ID');
189
- problems.push(...(doctorAgent ? doctorAgent() : agent.doctor()));
162
+ if (doctorAgent) problems.push(...doctorAgent());
190
163
  return problems;
191
164
  }
192
165
 
193
- // 真正运行前的检查:没配置好就带着退出码抛出。返回长连接的地址
194
- function requireConfig(needAgent) {
166
+ // 真正运行前的检查:没配置好就带着退出码抛出。返回长连接的地址。needAgent 为 false 时不查路由和执行者(probe 只看握手,不交消息)
167
+ function requireConfig({ needAgent = true } = {}) {
168
+ if (needAgent && !onMessage) throw new Fail(EXIT.NOT_CONFIGURED, '值守只管收,消息要交给路由:单独跑用 work-rhythm rhythm start,或者 work-rhythm listen run');
195
169
  if (notifyChannel(root) !== 'yzj-robot') {
196
170
  throw new Fail(EXIT.NOT_CONFIGURED, '值守是 yzj-robot 渠道的收消息一半:先把 00-config/profile.yaml 的 preferences.notify 设成 yzj-robot');
197
171
  }
198
172
  const found = findWebhook(env);
199
173
  if (found.problem) throw new Fail(found.code, found.problem);
200
- if (needAgent) {
201
- if (!OWNER) throw new Fail(EXIT.NOT_CONFIGURED, '取不到我的 openId:在 collectors/local.env 里写 YZJ_MY_OPEN_ID,值守只处理我本人的消息');
202
- if (doctorAgent) {
203
- const problems = doctorAgent();
204
- if (problems.length) throw new Fail(EXIT.NOT_CONFIGURED, `路由用的 agent 配得不对:${problems.join(';')}`);
205
- } else if (!AGENT) throw new Fail(EXIT.NOT_CONFIGURED, '没绑 agent,值守开不了:先 work-rhythm agent detect 看本机有哪些,再 work-rhythm agent bind <名字>(写进 collectors/local.env 的 YZJ_BOT_AGENT);也可以手写它,值是预置的名字或一条把回复打到标准输出的命令');
174
+ if (!OWNER) throw new Fail(EXIT.NOT_CONFIGURED, '取不到我的 openId:在 collectors/local.env 里写 YZJ_MY_OPEN_ID,值守只处理我本人的消息');
175
+ if (needAgent && doctorAgent) {
176
+ const problems = doctorAgent();
177
+ if (problems.length) throw new Fail(EXIT.NOT_CONFIGURED, `路由和执行者的 agent 配得不对:${problems.join(';')}`);
206
178
  }
207
179
  return deriveWsUrl(found.webhook);
208
180
  }
209
181
 
210
- // ---------------------------------------------------------------- 专属会话、去重
211
- const readText = (file) => {
212
- try {
213
- return fs.readFileSync(file, 'utf8');
214
- } catch {
215
- return '';
216
- }
217
- };
218
- const readSession = () => {
219
- try {
220
- return fs.readFileSync(SESSION_FILE, 'utf8').trim();
221
- } catch {
222
- return '';
223
- }
224
- };
225
- const writeSession = (id) => {
226
- fs.mkdirSync(STATE_DIR, { recursive: true });
227
- fs.writeFileSync(SESSION_FILE, `${id}\n`);
228
- };
229
- // 丢掉专属会话。路由开着时专属会话归路由管(01-inbox/_bot/session-id),交还给它清
230
- const clearSession = () => {
231
- if (resetSession) {
232
- resetSession();
233
- return;
234
- }
235
- try {
236
- fs.unlinkSync(SESSION_FILE);
237
- } catch {
238
- // 本来就没有
239
- }
240
- };
182
+ // ---------------------------------------------------------------- 去重
241
183
  const readSeen = () => {
242
184
  try {
243
185
  return fs.readFileSync(SEEN_FILE, 'utf8').split('\n').filter(Boolean);
@@ -250,124 +192,8 @@ function createBot({ root, env, onMessage = null, resetSession = null, doctorAge
250
192
  fs.writeFileSync(SEEN_FILE, `${[...readSeen(), msgId].slice(-SEEN_KEEP).join('\n')}\n`);
251
193
  };
252
194
 
253
- // ---------------------------------------------------------------- 一条消息
254
- function truncate(text) {
255
- const chars = Array.from(String(text).trim());
256
- if (chars.length <= REPLY_MAX) return chars.join('');
257
- return `${chars.slice(0, REPLY_MAX).join('')}\n…(回复太长,截到 ${REPLY_MAX} 字)`;
258
- }
259
-
260
- // 这一轮从哪个会话接着走:绑定的优先,它接不上过一次就不再试,用专属会话。
261
- // 「接不上过」记在 01-inbox/_bot/bound-session-lost 里(内容是那个会话 id):listen handle 是一次一个进程,光靠内存里的标记下一句又会去试
262
- const LOST_FILE = path.join(STATE_DIR, 'bound-session-lost');
263
- let boundLost = BOUND_SESSION && readText(LOST_FILE).trim() === BOUND_SESSION;
264
- const startSession = () => (BOUND_SESSION && !boundLost ? BOUND_SESSION : readSession());
265
- const markBoundLost = () => {
266
- boundLost = true;
267
- try {
268
- fs.mkdirSync(STATE_DIR, { recursive: true });
269
- fs.writeFileSync(LOST_FILE, `${BOUND_SESSION}\n`);
270
- } catch {
271
- // 记不下来就只在这次进程里有效
272
- }
273
- };
274
- const forgetBoundLost = () => {
275
- boundLost = false;
276
- try {
277
- fs.unlinkSync(LOST_FILE);
278
- } catch {
279
- // 本来就没有
280
- }
281
- };
282
- const sessionLost = (used) => {
283
- if (used && used === BOUND_SESSION) markBoundLost();
284
- clearSession();
285
- };
286
-
287
- // 回复经推送发出去。发不出去记一笔日志,不影响值守
288
- async function sendReply(reply) {
289
- const r = await pushText(root, reply, { env });
290
- if (r.ok) return true;
291
- log('回复没发出去', r.reason);
292
- return false;
293
- }
294
-
295
- // ---------------------------------------------------------------- 排队答(值守用)
296
- // 一条一条答,但不卡住事件循环:agent 用异步的 start(),等的期间长连接、网页、定时看表都照常。
297
- // 上一句还在答的时候又来了几句:先各回一句「收到,会和上一句一起考虑」,等上一句答完,把排着的几句合成一次运行——
298
- // 它们都是在我回答之前插进来的,一起看(promptOf)。每句的 Promise 在它那一批答完时给出 { text, speak }
299
- const promptOf = (items) => {
300
- const [first, ...rest] = items;
301
- if (!rest.length) return first.text;
302
- return `${first.text}\n\n(你回答之前,用户又插了下面这些话,一起看完再答:\n${rest.map((x) => `- ${x.text}`).join('\n')}\n)`;
303
- };
304
- const waiting = []; // 排着没答的:{ msgId, text, resolve }
305
- let running = null; // 正在跑的那次:{ handle }
306
- let halted = false; // 服务在停:答了一半的不再发出去,排着的也不再答
307
- const idleWaiters = [];
308
- // 答一批。返回 { text, speak }:speak 为 false 时这句话不发(服务在停)
309
- async function runBatch(items) {
310
- const used = startSession();
311
- const started = Date.now();
312
- const h = agent.start(promptOf(items), { session: used, onSessionLost: () => sessionLost(used), stateDir: STATE_DIR });
313
- running = { handle: h };
314
- // 跑得久先说一声:第一条在 PROGRESS_S 秒后,之后每条隔 2 倍,最多 PROGRESS_MAX 条
315
- const pings = progressPings({ firstS: PROGRESS_S, everyS: PROGRESS_S * 2, max: PROGRESS_MAX, say: () => sendReply(`还在做(已经 ${humanDuration((Date.now() - started) / 1000)}),做完就发给你。`) });
316
- let r;
317
- try {
318
- r = await h.done;
319
- } finally {
320
- pings.stop();
321
- running = null;
322
- }
323
- if (halted) return { text: '', speak: false };
324
- if (r.sessionId) writeSession(r.sessionId);
325
- // 被时限停掉的:已经说出口的话先发给我,别只剩一句「没处理成功」
326
- if (r.failed && r.partial) return { text: `时间到了,先给你说到这:\n\n${r.partial}`, speak: true };
327
- return { text: r.failed ? `没处理成功:${r.failed}` : truncate(r.reply), speak: true };
328
- }
329
- async function drain() {
330
- if (running) return;
331
- while (waiting.length) {
332
- const batch = waiting.splice(0);
333
- let out;
334
- try {
335
- out = await runBatch(batch);
336
- } catch (error) {
337
- out = { text: `没处理成功:${error && error.message ? error.message : String(error)}`, speak: !halted };
338
- }
339
- // 一批只答一次:合成的那句由这一批的第一条发出去,后面的不再各发一遍
340
- batch.forEach((item, i) => item.resolve({ ...out, speak: out.speak && i === 0 }));
341
- }
342
- for (const w of idleWaiters.splice(0)) w();
343
- }
344
- // 排进队列。返回的 Promise 在它那一批答完时给出 { text, speak }
345
- function enqueue(msgId, text) {
346
- return new Promise((resolve) => {
347
- waiting.push({ msgId, text, resolve });
348
- });
349
- }
350
- // 等到排着的都答完。timeoutMs 为 0 时一直等
351
- function idle(timeoutMs = 0) {
352
- if (!running && !waiting.length) return Promise.resolve(true);
353
- return new Promise((resolve) => {
354
- let timer = null;
355
- idleWaiters.push(() => {
356
- if (timer) clearTimeout(timer);
357
- resolve(true);
358
- });
359
- if (timeoutMs) timer = setTimeout(() => resolve(false), timeoutMs);
360
- });
361
- }
362
- // 停掉正在答的那次(服务要停时):答了一半的不发,排着的也不再答
363
- function abort(reason = '服务停止') {
364
- halted = true;
365
- if (running) running.handle.kill(reason);
366
- for (const item of waiting.splice(0)) item.resolve({ text: '', speak: false });
367
- }
368
-
369
- // 收到一帧之后做的事。send 为 false 时只算出回复、不发
370
- async function processFrame(raw, send = true) {
195
+ // 收到一帧之后做的事:本人的话交给引擎,回复由它发
196
+ async function processFrame(raw) {
371
197
  const c = classify(raw);
372
198
  if (c.kind !== 'dispatch') return { result: c.kind === 'control' ? `控制帧 ${c.reason}` : '不是业务消息', code: 2 };
373
199
  const m = c.message;
@@ -377,59 +203,22 @@ function createBot({ root, env, onMessage = null, resetSession = null, doctorAge
377
203
  log('msg 忽略:不是本人', `msgId=${m.msgId} from=${m.operatorOpenid}`);
378
204
  return { result: `忽略 msgId=${m.msgId}(不是本人)`, code: 0 };
379
205
  }
380
- const started = Date.now();
381
206
  const text = String(m.content || '').trim();
382
- const immediate = /^\/new$/i.test(text);
383
207
  log('msg 接受', `msgId=${m.msgId} groupType=${m.groupType}`);
384
- // 路由开着:/new 丢掉路由的专属会话;别的话变成一条触发交给引擎,回复由它发(「收到」也在那边)
385
- if (onMessage) {
386
- if (immediate) {
387
- if (resetSession) resetSession();
388
- log('msg 完成', `msgId=${m.msgId} /new`);
389
- return { result: '已丢掉路由自己的专属会话,下一句从绑定的那个会话接着走。', code: 0 };
390
- }
391
- const t = onMessage({ msgId: m.msgId, content: text, time: m.time, groupType: m.groupType });
392
- log('msg 交给路由', `msgId=${m.msgId} ${t ? t.id : '重复的'}`);
393
- return { result: `msgId=${m.msgId} 已交给路由(${t ? t.id : '重复的'})`, code: 0 };
208
+ // /new 丢掉路由自己的专属会话,回一句确认;别的话变成一条触发交给引擎,回复由它发(「收到」也在那边)
209
+ if (/^\/new$/i.test(text)) {
210
+ if (resetSession) resetSession();
211
+ const sent = say ? await say(NEW_TEXT) : true;
212
+ log('msg 完成', `msgId=${m.msgId} /new${sent ? '' : ' 回复没发出去'}`);
213
+ return { result: `已丢掉路由自己的专属会话,下一句从绑定的那个会话接着走${sent ? '。' : ',但这句没发出去。'}`, code: 0 };
394
214
  }
395
- let reply = '';
396
- let speak = true;
397
- let sent = null;
398
- // /new 丢掉专属会话:马上回一句,不排队
399
- if (immediate) {
400
- clearSession();
401
- if (BOUND_SESSION) forgetBoundLost();
402
- reply = BOUND_SESSION ? '已丢掉值守自己开的会话,下一句从绑定的那个会话接着走。' : '已开新会话。';
403
- } else if (!text) {
404
- reply = '收到一条空消息。';
405
- } else {
406
- // 先排进去:同一刻到来的后一句看得到前面还排着
407
- const answered = enqueue(m.msgId, text);
408
- if (send) {
409
- // 收到就回一句「收到」,agent 慢的话我不用干等;上一句还在答、或者前面还排着,就说明会和它一起考虑。
410
- // 回完再开跑,顺序才是「收到」在前、回复在后
411
- const first = waiting.length === 1 && !running;
412
- if (ACK) await sendReply(first ? ACK_TEXT : ACK_MORE_TEXT);
413
- }
414
- drain();
415
- const a = await answered;
416
- reply = a.text;
417
- speak = a.speak;
215
+ if (!text) {
216
+ log('msg 忽略:空消息', `msgId=${m.msgId}`);
217
+ return { result: `忽略 msgId=${m.msgId}(空消息)`, code: 0 };
418
218
  }
419
- if (send && speak) sent = await sendReply(reply);
420
- log('msg 完成', `msgId=${m.msgId} ${Math.round((Date.now() - started) / 1000)}s${sent === null ? '' : ` sent=${sent}`}`);
421
- return { result: `处理 msgId=${m.msgId}${sent === false ? ',但回复没发出去' : ''}`, code: 0, sent };
422
- }
423
-
424
- // 不连云之家,只走一遍「交给 agent → 回复」。回复打到标准输出;没配置好、没跑成都带着退出码抛出
425
- function handle(text) {
426
- requireConfig(true);
427
- const used = startSession();
428
- const r = agent.run(text, { session: used, onSessionLost: () => sessionLost(used), stateDir: STATE_DIR });
429
- if (r.sessionId) writeSession(r.sessionId);
430
- if (r.config) throw new Fail(EXIT.NOT_CONFIGURED, r.failed);
431
- if (r.failed) throw new Fail(EXIT.FAILED, `没处理成功:${r.failed}`);
432
- return truncate(r.reply);
219
+ const t = onMessage({ msgId: m.msgId, content: text, time: m.time, groupType: m.groupType });
220
+ log('msg 交给路由', `msgId=${m.msgId}${t ? ` ${t.id}` : '(和连着发的几句合起来看)'}`);
221
+ return { result: `msgId=${m.msgId} 已交给路由${t ? `(${t.id})` : '(和连着发的几句合起来看)'}`, code: 0 };
433
222
  }
434
223
 
435
224
  // ---------------------------------------------------------------- 长连接
@@ -437,14 +226,13 @@ function createBot({ root, env, onMessage = null, resetSession = null, doctorAge
437
226
  if (typeof WebSocket === 'undefined') throw new Fail(EXIT.MISSING_DEP, `这个 node(${process.version})没有内置的 WebSocket,需要 22 以上`);
438
227
  };
439
228
 
440
- // 值守:一直连着,收到消息就处理。收到 SIGINT / SIGTERM 后把手上这条处理完再退出
441
229
  // 值守:一直连着,收到消息就处理,直到 stop() 或(signals 为 true 时)SIGINT / SIGTERM。
442
230
  // 单独跑(work-rhythm listen run)时自己管信号;并进本地服务时 signals 为 false,由服务调 stop()
443
231
  let stopFn = null;
444
232
  async function run({ signals = true } = {}) {
445
- const url = requireConfig(true);
233
+ const url = requireConfig();
446
234
  needWebSocket();
447
- log('值守开始', `pid=${process.pid} ${onMessage ? '回复交给路由(profile 的 rhythm.router)' : `agent=${agent.kind !== 'custom' ? `${AGENT} mode=${AGENT_MODE}` : '自定义命令'} 超时=${TIMEOUT_S}s`} 会话=${BOUND_SESSION ? `绑定 ${BOUND_SESSION}` : '值守自己的专属会话'}`);
235
+ log('值守开始', `pid=${process.pid} 消息交给路由`);
448
236
  let stopping = false;
449
237
  let wake = null;
450
238
  const stopped = new Promise((resolve) => {
@@ -458,7 +246,6 @@ function createBot({ root, env, onMessage = null, resetSession = null, doctorAge
458
246
  stopping = true;
459
247
  log(`收到 ${signal},准备退出`);
460
248
  if (current && current.ws.readyState === WebSocket.OPEN) current.ws.close(1000, 'bye');
461
- abort(`收到 ${signal}`);
462
249
  wake();
463
250
  };
464
251
  stopFn = stop;
@@ -471,8 +258,8 @@ function createBot({ root, env, onMessage = null, resetSession = null, doctorAge
471
258
  const conn = await openSocket(url, (raw, me) => {
472
259
  const c = classify(raw);
473
260
  if (c.kind === 'control' && c.ack && me.ws.readyState === WebSocket.OPEN) me.ws.send(c.ack);
474
- // 一到就处理:去重、回「收到」在这里,排队交给 enqueue / drain;值守在停了就不再接
475
- if (c.kind === 'dispatch' && !stopping) processFrame(raw, true).catch((error) => log('msg 出错', error && error.message ? error.message : String(error)));
261
+ // 一到就处理:去重、交给引擎在这里;值守在停了就不再接
262
+ if (c.kind === 'dispatch' && !stopping) processFrame(raw).catch((error) => log('msg 出错', error && error.message ? error.message : String(error)));
476
263
  }, log);
477
264
  if (!conn) {
478
265
  attempts += 1;
@@ -485,18 +272,17 @@ function createBot({ root, env, onMessage = null, resetSession = null, doctorAge
485
272
  current = null;
486
273
  if (!stopping) await pause(1000);
487
274
  }
488
- await idle(2000);
489
275
  log('值守结束');
490
276
  return EXIT.OK;
491
277
  }
492
- // 从外面停掉它(本地服务结束时调);还没跑起来或已经停了就什么都不做
278
+ // 从外面停掉它(本地服务结束时调);还没跑起来或者已经停了就什么都不做
493
279
  function stop(reason = '服务结束') {
494
280
  if (stopFn) stopFn(reason);
495
281
  }
496
282
 
497
- // 连上去看握手和收到的每一帧,不调 agent,到时退出。第一次验证用。返回退出码:收到过帧是 0,没收到是 5
283
+ // 连上去看握手和收到的每一帧,不交给引擎,到时退出。第一次验证用。返回退出码:收到过帧是 0,没收到是 5
498
284
  async function probe(seconds) {
499
- const url = requireConfig(false);
285
+ const url = requireConfig({ needAgent: false });
500
286
  needWebSocket();
501
287
  process.stdout.write(`${fmtStamp()} 连接 ${mask(url)},最多等 ${seconds} 秒。现在可以在云之家里给机器人发一句话。\n`);
502
288
  const conn = await openSocket(url, (raw, me) => {
@@ -519,18 +305,13 @@ function createBot({ root, env, onMessage = null, resetSession = null, doctorAge
519
305
  return {
520
306
  log,
521
307
  stateDir: STATE_DIR,
522
- sessionFile: SESSION_FILE,
523
308
  doctorProblems,
524
309
  requireConfig,
525
- handle,
526
310
  processFrame,
527
- clearSession,
528
- // 换绑了会话之后调:忘掉「接不上过」
529
- forgetBoundLost,
530
311
  run,
531
312
  stop,
532
313
  probe,
533
314
  };
534
315
  }
535
316
 
536
- module.exports = { createBot, classify };
317
+ module.exports = { createBot, classify, NEW_TEXT };