work-rhythm 0.1.8 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/.agents/notes/AGENTS.md +12 -1
  2. package/.agents/notes/decisions/2026-12-01-agent-runs-the-login-for-the-user.md +30 -0
  3. package/.agents/notes/decisions/2026-12-01-interjections-batch-into-one-answer-and-interrupt-reruns.md +33 -0
  4. package/.agents/notes/decisions/2026-12-01-long-runs-are-bounded-by-silence-not-wall-clock.md +35 -0
  5. package/.agents/notes/decisions/2026-12-01-question-cards-via-cli-tool-on-todays-page-answers-return-to-router.md +40 -0
  6. package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +42 -0
  7. package/.agents/notes/decisions/2026-12-01-router-runs-on-a-flash-model-with-low-effort.md +33 -0
  8. package/.agents/notes/decisions/2026-12-01-sync-feeds-refine-then-events-to-the-router.md +38 -0
  9. package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +16 -0
  10. package/.agents/notes/pitfalls/2026-12-02-rhythm-start-in-the-foreground-displaces-the-launchd-service.md +27 -0
  11. package/.agents/skills/work-rhythm/SKILL.md +20 -12
  12. package/README.md +32 -4
  13. package/collectors/local.env.example +10 -1
  14. package/docs/agents.md +53 -13
  15. package/docs/channels.md +9 -6
  16. package/docs/router-worker.md +263 -0
  17. package/docs/scheduled-tasks.md +5 -5
  18. package/docs/sources.md +20 -0
  19. package/package.json +1 -1
  20. package/scripts/cli.js +5 -3
  21. package/scripts/cmd/agent.js +188 -49
  22. package/scripts/cmd/ask.js +104 -0
  23. package/scripts/cmd/check.js +4 -0
  24. package/scripts/cmd/listen.js +18 -4
  25. package/scripts/cmd/rhythm.js +6 -2
  26. package/scripts/cmd/sync.js +11 -3
  27. package/scripts/cmd/trigger.js +143 -0
  28. package/scripts/lib/agent.js +482 -30
  29. package/scripts/lib/asks.js +145 -0
  30. package/scripts/lib/bot.js +140 -35
  31. package/scripts/lib/engine.js +707 -0
  32. package/scripts/lib/handoff.js +167 -0
  33. package/scripts/lib/markdown.js +355 -36
  34. package/scripts/lib/rhythm.js +576 -38
  35. package/scripts/lib/router.js +208 -0
  36. package/scripts/lib/run.js +43 -0
  37. package/scripts/lib/view.js +736 -0
  38. package/scripts/lib/worker.js +98 -0
  39. package/scripts/test/agent.test.js +126 -9
  40. package/scripts/test/check.test.js +7 -2
  41. package/scripts/test/harness.js +15 -1
  42. package/scripts/test/listen.test.js +2 -2
  43. package/scripts/test/rhythm.test.js +109 -6
  44. package/scripts/test/router-helper.js +110 -0
  45. package/scripts/test/router.test.js +799 -0
  46. package/scripts/test/stubs.js +113 -12
  47. package/scripts/test/timeout.test.js +99 -0
  48. package/tasks/daily-plan.md +1 -2
  49. package/templates/00-config/profile.example.yaml +9 -0
  50. package/templates/AGENTS.md +3 -1
  51. package/templates/README.md +4 -1
@@ -0,0 +1,145 @@
1
+ // 问用户:执行者干到一半要我拿主意,不自己憋着,把问题以 JSON 丢出来(work-rhythm ask),页面上成一张卡,
2
+ // 我在页面上答了,回答变成一条触发回到路由(docs/router-worker.md 的「问用户:待办卡片」)。
3
+ // 一张卡是一个文件:01-inbox/_rhythm/asks/<id>.json,答了也留着(带着答案),监控和页面从这儿读;
4
+ // 同时在 03-carryover/DECISIONS.md 记一行「未答」——那是给人看的历史,答了再改成我的决定。
5
+ // 内容(问题、背景、我的附言)只在这个目录和 DECISIONS.md 里,不进 state.json、不进日志。
6
+ 'use strict';
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+ const { EXIT, Fail, UsageError, fmtStamp, today } = require('./run');
10
+ // 给服务的信号放 01-inbox/_rhythm/queue/(和 trigger fire 同一个目录,engine.js 的 collectQueue 取走)
11
+ const queueDir = (root) => path.join(root, '01-inbox', '_rhythm', 'queue');
12
+
13
+ const ASKS_DIR = ['01-inbox', '_rhythm', 'asks'];
14
+ const CIRCLED = ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩'];
15
+ const MAX_QUESTION = 200;
16
+ const MAX_ITEM = 30;
17
+
18
+ const asksDir = (root) => path.join(root, ...ASKS_DIR);
19
+ const askPath = (root, id) => path.join(asksDir(root), `${id}.json`);
20
+ const ID_RE = /^a-\d{8}-\d{6}-[0-9a-f]{4}$/;
21
+
22
+ const readOrNull = (file) => {
23
+ try {
24
+ return fs.readFileSync(file, 'utf8');
25
+ } catch {
26
+ return '';
27
+ }
28
+ };
29
+
30
+ // 选项统一成 { label, detail, suggested }:传进来的可以是字符串,或 { label, detail, suggested },suggested 也可以写成序号
31
+ function normalizeOptions(options, suggested) {
32
+ const list = (Array.isArray(options) ? options : []).map((o) => (typeof o === 'string' ? { label: o } : o && typeof o === 'object' ? { ...o } : null)).filter((o) => o && String(o.label || '').trim());
33
+ const pick = suggested === undefined ? -1 : typeof suggested === 'number' ? suggested : list.findIndex((o) => o.label === suggested || String(o.label).trim() === String(suggested).trim());
34
+ return list.map((o, i) => ({ label: String(o.label).trim(), detail: String(o.detail || '').trim(), suggested: Boolean(o.suggested) || i === pick }));
35
+ }
36
+
37
+ // DECISIONS.md 的「选项」那一格:①… ②… ③…
38
+ const optionsText = (options) => options.map((o, i) => `${CIRCLED[i] || `${i + 1}.`}${o.label}`).join(' ');
39
+
40
+ // 全部的卡:没答的在前(新的在前),答过的在后(新的在前)
41
+ function listAsks(root) {
42
+ let names;
43
+ try {
44
+ names = fs.readdirSync(asksDir(root));
45
+ } catch {
46
+ return [];
47
+ }
48
+ const asks = [];
49
+ for (const name of names) {
50
+ if (!/^a-.*\.json$/.test(name)) continue;
51
+ try {
52
+ const ask = JSON.parse(fs.readFileSync(path.join(asksDir(root), name), 'utf8'));
53
+ if (ask && ask.id) asks.push(ask);
54
+ } catch {
55
+ // 写了一半的、坏掉的:跳过
56
+ }
57
+ }
58
+ return asks.sort((a, b) => (Boolean(a.answer) === Boolean(b.answer) ? b.at.localeCompare(a.at) : a.answer ? 1 : -1));
59
+ }
60
+
61
+ function readAsk(root, id) {
62
+ if (!ID_RE.test(String(id || ''))) return null;
63
+ try {
64
+ return JSON.parse(fs.readFileSync(askPath(root, id), 'utf8'));
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ // 校验一份传进来的 JSON,返回规范化后的字段;不对就抛用法错
71
+ function validate(input) {
72
+ const o = input && typeof input === 'object' && !Array.isArray(input) ? input : {};
73
+ const question = String(o.question || o.item || '').trim();
74
+ if (!question) throw new UsageError('ask 要有 question(问题本身,一句话)');
75
+ if (question.length > MAX_QUESTION) throw new UsageError(`question 太长了(${question.length} 字,最多 ${MAX_QUESTION}):背景放 context`);
76
+ const options = normalizeOptions(o.options, o.suggested);
77
+ if (options.length > 10) throw new UsageError('选项最多 10 个');
78
+ const item = String(o.item || '').trim() || question;
79
+ if (item.length > MAX_ITEM) throw new UsageError(`item(记进 DECISIONS.md 的那一句话)不能超过 ${MAX_ITEM} 字:现在「${item}」;问题长的话另起一个短的 item`);
80
+ if (/[|]/.test(item)) throw new UsageError('item 不能含竖线');
81
+ return { question, context: String(o.context || '').trim(), options, record: String(o.record || '').trim(), item, from: o.from && typeof o.from === 'object' ? o.from : {} };
82
+ }
83
+
84
+ // 登记一张卡:写文件、记 DECISIONS.md(未答)、给服务留个信号(它把卡片推给我、带着页面地址)。
85
+ // 返回卡。decisions 是 cmd/decisions.js 的 run:这里直接调它,不另起进程
86
+ async function createAsk(root, input, { env = process.env, packageRoot, decisions } = {}) {
87
+ const v = validate(input);
88
+ const now = new Date();
89
+ const p = (n) => String(n).padStart(2, '0');
90
+ const stamp = `${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}-${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`;
91
+ const id = `a-${stamp}-${Math.random().toString(16).slice(2, 6)}`;
92
+ const from = { ...v.from };
93
+ // 执行者问的:服务给它留了 WRJ_TRIGGER(是哪条触发),顺手记上
94
+ if (!from.trigger && env.WRJ_TRIGGER) from.trigger = String(env.WRJ_TRIGGER);
95
+ const ask = { id, at: fmtStamp(now), question: v.question, context: v.context, options: v.options, record: v.record, item: v.item, from, answer: null };
96
+ fs.mkdirSync(asksDir(root), { recursive: true });
97
+ fs.writeFileSync(askPath(root, id), `${JSON.stringify(ask, null, 1)}\n`);
98
+ const err = [];
99
+ const code = decisions ? await decisions.run(['add', '--item', v.item, '--options', optionsText(v.options), '--choice', '未答'], { root, cwd: root, env, packageRoot, stdout: { write() {} }, stderr: { write: (x) => err.push(String(x)) } }) : 0;
100
+ if (decisions && code !== 0) throw new Fail(EXIT.FAILED, `卡片写下了(${id}),但 DECISIONS.md 没记上:${err.join('').trim()}`);
101
+ // 服务下一次看表(最多 20 秒)取走它,把卡片推给我(带着页面地址)
102
+ fs.mkdirSync(queueDir(root), { recursive: true });
103
+ fs.writeFileSync(path.join(queueDir(root), `ask-${id}.json`), `${JSON.stringify({ kind: 'ask', ask: id, text: `ask ${id}`, mode: 'plan', at: fmtStamp(now) })}\n`);
104
+ return ask;
105
+ }
106
+
107
+ // 答了:卡片里记下答案,DECISIONS.md 那一行改成我的决定
108
+ async function answerAsk(root, id, { choice, note = '', by = 'page' } = {}, { env = process.env, packageRoot, decisions } = {}) {
109
+ const ask = readAsk(root, id);
110
+ if (!ask) throw new Fail(EXIT.USAGE, `没有 ${id} 这张卡`);
111
+ const picked = String(choice || '').trim();
112
+ if (!picked) throw new UsageError('要写选了哪个选项(或者你的回答)');
113
+ if (!ask.answer) {
114
+ ask.answer = { choice: picked, note: String(note || '').trim(), at: fmtStamp(), by };
115
+ fs.writeFileSync(askPath(root, id), `${JSON.stringify(ask, null, 1)}\n`);
116
+ }
117
+ const err = [];
118
+ const code = decisions ? await decisions.run(['answer', ask.item, ask.answer.choice], { root, cwd: root, env, packageRoot, stdout: { write() {} }, stderr: { write: (x) => err.push(String(x)) } }) : 0;
119
+ if (decisions && code !== 0) throw new Fail(EXIT.FAILED, `卡片记下了答案,但 DECISIONS.md 没改成我的决定:${err.join('').trim()}`);
120
+ return ask;
121
+ }
122
+
123
+ // 给路由、给推送看的一行
124
+ function askSummary(ask) {
125
+ const opts = ask.options.map((o, i) => `${CIRCLED[i] || `${i + 1}.`}${o.label}`).join(' ');
126
+ return `「${ask.question}」${opts ? ` 选项:${opts}` : ''}`;
127
+ }
128
+
129
+ // 页面和监控的卡片:没答的卡,加上 DECISIONS.md 里「未答」但没有对应卡片的行(老办法登记的)
130
+ function cardsForPage(root, pendingCards) {
131
+ const asks = listAsks(root).filter((a) => !a.answer);
132
+ const items = new Set(asks.map((a) => a.item));
133
+ const legacy = pendingCards(root).filter((c) => !items.has(c.item)).map((c) => ({ id: '', question: c.item, context: '', options: normalizeOptions(c.options ? splitOptions(c.options) : []), record: '', item: c.item, from: {}, answer: null, at: '', date: c.date, legacy: true }));
134
+ return [...asks, ...legacy];
135
+ }
136
+
137
+ // 老办法的选项是一串「①发上游 ②周会提」或「周二;周四」
138
+ function splitOptions(text) {
139
+ const parts = String(text || '').split(/(?=[①②③④⑤⑥⑦⑧⑨⑩])/).map((x) => x.trim()).filter(Boolean);
140
+ if (parts.length > 1) return parts;
141
+ const semi = String(text || '').split(/[;;]\s*/).map((x) => x.trim()).filter(Boolean);
142
+ return semi.length > 1 ? semi : [String(text || '').trim()].filter(Boolean);
143
+ }
144
+
145
+ module.exports = { ASKS_DIR, ID_RE, asksDir, askPath, normalizeOptions, optionsText, listAsks, readAsk, createAsk, answerAsk, askSummary, cardsForPage, splitOptions, validate };
@@ -8,7 +8,7 @@
8
8
  'use strict';
9
9
  const fs = require('node:fs');
10
10
  const path = require('node:path');
11
- const { EXIT, Fail, fmtStamp } = require('./run');
11
+ const { EXIT, Fail, fmtStamp, seconds, humanDuration, progressPings } = require('./run');
12
12
  const { logger } = require('./log');
13
13
  const { notifyChannel, pushText } = require('./notify');
14
14
  const { findWebhook, mask } = require('./robot');
@@ -19,6 +19,8 @@ const HEARTBEAT_MS = 15000;
19
19
  const STALE_MS = 45000;
20
20
  const RECONNECT_DELAYS_MS = [1000, 2000, 5000, 10000, 30000, 60000];
21
21
  const ACK_TEXT = '收到,正在处理,稍等。';
22
+ // 上一句还没答完又来一句:先回这句,告诉他会和上一句一起考虑
23
+ const ACK_MORE_TEXT = '收到,上一句还在答,这句会和它一起考虑。';
22
24
  const DEFAULT_PREAMBLE = '(这句来自云之家:你的回复会原样以纯文本私聊发给我。直接回答,不用表格,尽量简短;一件事要查很久就先说大概要多久。)';
23
25
 
24
26
  const positiveInt = (value, fallback) => {
@@ -147,9 +149,12 @@ const reconnectDelay = (attempts) => RECONNECT_DELAYS_MS[Math.min(Math.max(attem
147
149
 
148
150
  // 建一个值守对象。env 是设置(环境变量,上面盖一层 local.env),配置都在里面:
149
151
  // YZJ_BOT_AGENT 让哪个 agent 回复(zcode、dsh,或一条自己的命令)、YZJ_BOT_AGENT_MODE(plan 只读 / edit 可写,默认 plan)、
150
- // YZJ_MY_OPEN_ID 只认我本人、YZJ_BOT_TIMEOUT 一次最多等几秒、YZJ_BOT_REPLY_MAX 回复最多几个字、
152
+ // YZJ_MY_OPEN_ID 只认我本人、YZJ_BOT_TIMEOUT 一次最多等几秒(硬上限,默认 900)、YZJ_BOT_IDLE 多久没输出算卡住(默认 180,0 不查)、
153
+ // YZJ_BOT_PROGRESS 跑多久先说一声还在做(默认 90 秒,0 不说)、YZJ_BOT_REPLY_MAX 回复最多几个字、
151
154
  // YZJ_BOT_ACK=0 关掉「收到,正在处理」那句、YZJ_BOT_PREAMBLE 换掉或清空随每句话带给 agent 的提示
152
- function createBot({ root, env }) {
155
+ // 路由开着时(profile 的 rhythm.router,本地服务传进来):值守只管收——本人校验、去重、/new——收到的话变成触发交给
156
+ // onMessage(engine.js),由路由判断再派给执行者,回复也由引擎发。这时配置查的是路由的 agent(doctorAgent),/new 调 resetSession
157
+ function createBot({ root, env, onMessage = null, resetSession = null, doctorAgent = null }) {
153
158
  const STATE_DIR = path.join(root, '01-inbox', '_bot');
154
159
  const LOG_FILE = path.join(root, '01-inbox', '_bot.log');
155
160
  const SESSION_FILE = path.join(STATE_DIR, 'session-id');
@@ -158,7 +163,12 @@ function createBot({ root, env }) {
158
163
  const OWNER = (env.YZJ_MY_OPEN_ID || '').trim();
159
164
  const AGENT = (env.YZJ_BOT_AGENT || '').trim();
160
165
  const AGENT_MODE = (env.YZJ_BOT_AGENT_MODE || 'plan').trim();
161
- const TIMEOUT_S = positiveInt(env.YZJ_BOT_TIMEOUT, 300);
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);
162
172
  const REPLY_MAX = positiveInt(env.YZJ_BOT_REPLY_MAX, 2000);
163
173
  // 收到就先回一句,agent 慢的时候我不用干等
164
174
  const ACK = env.YZJ_BOT_ACK !== '0';
@@ -167,7 +177,7 @@ function createBot({ root, env }) {
167
177
  const BOUND_SESSION = (env.YZJ_BOT_SESSION || '').trim();
168
178
  const PREAMBLE = env.YZJ_BOT_PREAMBLE !== undefined ? env.YZJ_BOT_PREAMBLE : DEFAULT_PREAMBLE;
169
179
  // 模型和思考强度(collectors/local.env 的 YZJ_BOT_MODEL / YZJ_BOT_EFFORT),只有支持的预置才认;不写就用 agent 自己的默认
170
- const agent = createAgent({ root, agent: AGENT, mode: AGENT_MODE, timeoutS: TIMEOUT_S, preamble: PREAMBLE, log, env, model: (env.YZJ_BOT_MODEL || '').trim(), effort: (env.YZJ_BOT_EFFORT || '').trim() });
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() });
171
181
 
172
182
  // ---------------------------------------------------------------- 配置
173
183
  // 检查值守的配置和依赖:有问题一条一个字符串;没问题就是空数组。check 配了值守时也调它
@@ -176,7 +186,7 @@ function createBot({ root, env }) {
176
186
  if (notifyChannel(root) !== 'yzj-robot') problems.push('值守属于 yzj-robot 渠道:preferences.notify 要设成 yzj-robot');
177
187
  if (!findWebhook(env).webhook) problems.push(`钥匙串里没有 ${env.YZJ_ROBOT_KEYCHAIN_SERVICE || 'work-rhythm-yzj-robot-webhook'}(开通步骤见 docs/channels.md「云之家」)`);
178
188
  if (!OWNER) problems.push('值守只处理我本人的消息:collectors/local.env 里要写 YZJ_MY_OPEN_ID');
179
- problems.push(...agent.doctor());
189
+ problems.push(...(doctorAgent ? doctorAgent() : agent.doctor()));
180
190
  return problems;
181
191
  }
182
192
 
@@ -189,7 +199,10 @@ function createBot({ root, env }) {
189
199
  if (found.problem) throw new Fail(found.code, found.problem);
190
200
  if (needAgent) {
191
201
  if (!OWNER) throw new Fail(EXIT.NOT_CONFIGURED, '取不到我的 openId:在 collectors/local.env 里写 YZJ_MY_OPEN_ID,值守只处理我本人的消息');
192
- if (!AGENT) throw new Fail(EXIT.NOT_CONFIGURED, '没绑 agent,值守开不了:先 work-rhythm agent detect 看本机有哪些,再 work-rhythm agent bind <名字>(写进 collectors/local.env 的 YZJ_BOT_AGENT);也可以手写它,值是预置的名字或一条把回复打到标准输出的命令');
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);也可以手写它,值是预置的名字或一条把回复打到标准输出的命令');
193
206
  }
194
207
  return deriveWsUrl(found.webhook);
195
208
  }
@@ -213,7 +226,12 @@ function createBot({ root, env }) {
213
226
  fs.mkdirSync(STATE_DIR, { recursive: true });
214
227
  fs.writeFileSync(SESSION_FILE, `${id}\n`);
215
228
  };
229
+ // 丢掉专属会话。路由开着时专属会话归路由管(01-inbox/_bot/session-id),交还给它清
216
230
  const clearSession = () => {
231
+ if (resetSession) {
232
+ resetSession();
233
+ return;
234
+ }
217
235
  try {
218
236
  fs.unlinkSync(SESSION_FILE);
219
237
  } catch {
@@ -266,22 +284,6 @@ function createBot({ root, env }) {
266
284
  clearSession();
267
285
  };
268
286
 
269
- // 一条消息 → 要回复的文字。agent 失败也回一句,不让我干等
270
- function answer(message) {
271
- const text = String(message.content || '').trim();
272
- if (!text) return '收到一条空消息。';
273
- if (/^\/new$/i.test(text)) {
274
- clearSession();
275
- if (!BOUND_SESSION) return '已开新会话。';
276
- forgetBoundLost();
277
- return '已丢掉值守自己开的会话,下一句从绑定的那个会话接着走。';
278
- }
279
- const used = startSession();
280
- const r = agent.run(text, { session: used, onSessionLost: () => sessionLost(used), stateDir: STATE_DIR });
281
- if (r.sessionId) writeSession(r.sessionId);
282
- return truncate(r.failed ? `没处理成功:${r.failed}` : r.reply);
283
- }
284
-
285
287
  // 回复经推送发出去。发不出去记一笔日志,不影响值守
286
288
  async function sendReply(reply) {
287
289
  const r = await pushText(root, reply, { env });
@@ -290,6 +292,80 @@ function createBot({ root, env }) {
290
292
  return false;
291
293
  }
292
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
+
293
369
  // 收到一帧之后做的事。send 为 false 时只算出回复、不发
294
370
  async function processFrame(raw, send = true) {
295
371
  const c = classify(raw);
@@ -302,14 +378,45 @@ function createBot({ root, env }) {
302
378
  return { result: `忽略 msgId=${m.msgId}(不是本人)`, code: 0 };
303
379
  }
304
380
  const started = Date.now();
305
- const immediate = /^\/new$/i.test(String(m.content || '').trim());
381
+ const text = String(m.content || '').trim();
382
+ const immediate = /^\/new$/i.test(text);
306
383
  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 };
394
+ }
395
+ let reply = '';
396
+ let speak = true;
307
397
  let sent = null;
308
- if (send) {
309
- // 先回一句「收到」,agent 慢的话我不用干等
310
- if (ACK && !immediate) await sendReply(ACK_TEXT);
311
- sent = await sendReply(answer(m));
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;
312
418
  }
419
+ if (send && speak) sent = await sendReply(reply);
313
420
  log('msg 完成', `msgId=${m.msgId} ${Math.round((Date.now() - started) / 1000)}s${sent === null ? '' : ` sent=${sent}`}`);
314
421
  return { result: `处理 msgId=${m.msgId}${sent === false ? ',但回复没发出去' : ''}`, code: 0, sent };
315
422
  }
@@ -337,7 +444,7 @@ function createBot({ root, env }) {
337
444
  async function run({ signals = true } = {}) {
338
445
  const url = requireConfig(true);
339
446
  needWebSocket();
340
- log('值守开始', `pid=${process.pid} agent=${agent.kind !== 'custom' ? `${AGENT} mode=${AGENT_MODE}` : '自定义命令'} 超时=${TIMEOUT_S}s 会话=${BOUND_SESSION ? `绑定 ${BOUND_SESSION}` : '值守自己的专属会话'}`);
447
+ log('值守开始', `pid=${process.pid} ${onMessage ? '回复交给路由(profile 的 rhythm.router)' : `agent=${agent.kind !== 'custom' ? `${AGENT} mode=${AGENT_MODE}` : '自定义命令'} 超时=${TIMEOUT_S}s`} 会话=${BOUND_SESSION ? `绑定 ${BOUND_SESSION}` : '值守自己的专属会话'}`);
341
448
  let stopping = false;
342
449
  let wake = null;
343
450
  const stopped = new Promise((resolve) => {
@@ -346,12 +453,12 @@ function createBot({ root, env }) {
346
453
  // 等待的时候也能被停下的信号叫醒
347
454
  const pause = (ms) => Promise.race([sleep(ms), stopped]);
348
455
  let current = null;
349
- let chain = Promise.resolve();
350
456
  const stop = (signal) => {
351
457
  if (stopping) return;
352
458
  stopping = true;
353
459
  log(`收到 ${signal},准备退出`);
354
460
  if (current && current.ws.readyState === WebSocket.OPEN) current.ws.close(1000, 'bye');
461
+ abort(`收到 ${signal}`);
355
462
  wake();
356
463
  };
357
464
  stopFn = stop;
@@ -364,10 +471,8 @@ function createBot({ root, env }) {
364
471
  const conn = await openSocket(url, (raw, me) => {
365
472
  const c = classify(raw);
366
473
  if (c.kind === 'control' && c.ack && me.ws.readyState === WebSocket.OPEN) me.ws.send(c.ack);
367
- // 一条一条处理,后面的排队
368
- if (c.kind === 'dispatch') {
369
- chain = chain.then(() => (stopping ? undefined : processFrame(raw, true)));
370
- }
474
+ // 一到就处理:去重、回「收到」在这里,排队交给 enqueue / drain;值守在停了就不再接
475
+ if (c.kind === 'dispatch' && !stopping) processFrame(raw, true).catch((error) => log('msg 出错', error && error.message ? error.message : String(error)));
371
476
  }, log);
372
477
  if (!conn) {
373
478
  attempts += 1;
@@ -380,7 +485,7 @@ function createBot({ root, env }) {
380
485
  current = null;
381
486
  if (!stopping) await pause(1000);
382
487
  }
383
- await chain;
488
+ await idle(2000);
384
489
  log('值守结束');
385
490
  return EXIT.OK;
386
491
  }