work-rhythm 0.2.21 → 0.2.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/notes/AGENTS.md +11 -3
- package/.agents/notes/decisions/2026-11-30-bot-inbound-uses-websocket-and-a-responder-command.md +1 -0
- package/.agents/notes/decisions/2026-11-30-skill-ships-with-its-template-in-a-zip.md +1 -0
- package/.agents/notes/decisions/2026-12-01-agent-binding-asks-for-model-and-effort.md +1 -0
- package/.agents/notes/decisions/2026-12-01-interjections-batch-into-one-answer-and-interrupt-reruns.md +1 -0
- package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +1 -0
- package/.agents/notes/decisions/2026-12-01-router-runs-on-a-flash-model-with-low-effort.md +1 -0
- package/.agents/notes/decisions/2026-12-03-codex-cli-joins-as-a-preset-verified-against-its-own-binary.md +45 -0
- package/.agents/notes/decisions/2026-12-03-fewer-scheduled-tasks-silent-refine-no-question-cards.md +1 -0
- package/.agents/notes/decisions/2026-12-03-playbook-distills-handoffs-into-ws-tool-and-skill-know-how.md +43 -0
- package/.agents/notes/decisions/2026-12-03-related-work-comes-back-as-one-reply.md +49 -0
- package/.agents/notes/decisions/2026-12-03-roster-of-worker-groups-router-picks-the-group.md +34 -0
- package/.agents/notes/decisions/2026-12-03-router-model-and-effort-are-configurable.md +28 -0
- package/.agents/notes/decisions/2026-12-03-router-only-direct-mode-removed.md +27 -0
- package/.agents/notes/decisions/2026-12-03-unattended-runs-decide-on-their-own.md +32 -0
- package/.agents/notes/decisions/2026-12-03-update-upgrades-package-and-refreshes-shipped-files.md +30 -0
- package/.agents/notes/decisions/2026-12-03-workers-leave-a-status-trail-that-joins-the-receipt.md +31 -0
- package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +2 -0
- package/.agents/notes/pitfalls/2026-12-03-judging-a-symlink-by-realpath-ignores-parent-links.md +18 -0
- package/.agents/notes/pitfalls/2026-12-04-selftest-sandbox-leaves-qoder-and-claude-real.md +18 -0
- package/.agents/skills/work-rhythm/SKILL.md +20 -16
- package/README.md +13 -10
- package/collectors/local.env.example +31 -36
- package/docs/agents.md +61 -60
- package/docs/channels.md +15 -19
- package/docs/formats.md +27 -0
- package/docs/router-worker.md +60 -41
- package/docs/scheduled-tasks.md +9 -9
- package/package.json +1 -1
- package/scripts/cli.js +9 -5
- package/scripts/cmd/agent.js +348 -235
- package/scripts/cmd/check.js +14 -7
- package/scripts/cmd/listen.js +33 -32
- package/scripts/cmd/pack.js +6 -6
- package/scripts/cmd/rhythm.js +13 -10
- package/scripts/cmd/trigger.js +23 -14
- package/scripts/cmd/update.js +92 -0
- package/scripts/lib/agent.js +235 -142
- package/scripts/lib/agents.js +179 -0
- package/scripts/lib/bot.js +44 -263
- package/scripts/lib/engine.js +373 -110
- package/scripts/lib/handoff.js +54 -8
- package/scripts/lib/markdown.js +19 -0
- package/scripts/lib/playbook.js +123 -0
- package/scripts/lib/rhythm.js +503 -187
- package/scripts/lib/router.js +45 -29
- package/scripts/lib/template.js +3 -3
- package/scripts/lib/update.js +279 -0
- package/scripts/lib/worker.js +11 -5
- package/scripts/test/agent.test.js +410 -257
- package/scripts/test/check.test.js +17 -6
- package/scripts/test/harness.js +6 -2
- package/scripts/test/listen.test.js +190 -158
- package/scripts/test/playbook.test.js +106 -0
- package/scripts/test/rhythm.test.js +210 -55
- package/scripts/test/roster.test.js +155 -0
- package/scripts/test/router-helper.js +17 -2
- package/scripts/test/router.test.js +469 -195
- package/scripts/test/stubs.js +56 -7
- package/scripts/test/timeout.test.js +160 -59
- package/scripts/test/update.test.js +384 -0
- package/tasks/daily-persona.md +30 -14
- package/tasks/daily-plan.md +3 -3
- package/tasks/evening-review.md +1 -7
- package/tasks/noon-checkin.md +2 -1
- package/templates/00-config/profile.example.yaml +9 -6
- package/templates/04-patterns/PERSONA.md +4 -1
- package/templates/04-patterns/PLAYBOOK.md +13 -0
- package/templates/AGENTS.md +6 -2
- package/templates/README.md +10 -9
package/scripts/lib/engine.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
// 引擎:触发 → 路由 → 执行者 → 汇报 → 发消息(docs/router-worker.md)。跑在本地服务(rhythm.js)的进程里;
|
|
2
|
-
// listen handle 在命令行的进程里也拿它走一遍(要发的文字交给 sink,不真发)。
|
|
3
|
-
//
|
|
2
|
+
// listen handle 和 rhythm run 在命令行的进程里也拿它走一遍(要发的文字交给 sink,不真发)。
|
|
3
|
+
// 路由和有哪几组执行者在名册里(agents.js),每次派活时读:网页或命令行改了,对新的触发生效。路由点名派给哪一组(worker=<编号>),
|
|
4
|
+
// 没点名派给第一组。路由坏了(超时、看不懂、漏了决定)走兜底:按来源直接处理,不丢东西。
|
|
5
|
+
// 发给我的话尽量合成一条:同一轮里路由给的好几条话(reply、notify)攒到这一轮结束一起发;手头还有别的活在跑时,
|
|
6
|
+
// 先做完的汇报等一等(最多等 cfg.mergeWait 秒),一起交回路由——路由一轮看完,回的话就是一条。
|
|
7
|
+
// 触发的内容(原话、任务书正文、回执、执行者的过程记录)只在内存里和 .agents/handoff/ 的文件里;state.json 只记元数据:
|
|
4
8
|
// triggers 每条的短号、去重键、来源、时间、决定、执行者的状态/用时/会话 id、发没发(留两天)
|
|
5
9
|
// history 每跑完一条记一行元数据(留 rhythm.history-keep 天),监控中心的次数和成功率从它算
|
|
6
10
|
// rounds 路由每一轮(留两天)
|
|
@@ -8,18 +12,18 @@
|
|
|
8
12
|
'use strict';
|
|
9
13
|
const fs = require('node:fs');
|
|
10
14
|
const path = require('node:path');
|
|
11
|
-
const { fmtStamp, today, humanDuration
|
|
12
|
-
const { roles } = require('./agent');
|
|
15
|
+
const { fmtStamp, today, humanDuration } = require('./run');
|
|
13
16
|
const handoff = require('./handoff');
|
|
17
|
+
const playbook = require('./playbook');
|
|
14
18
|
const { createRouter } = require('./router');
|
|
15
19
|
const { createPool, runWorker } = require('./worker');
|
|
20
|
+
const { PRESETS, presetKind } = require('./agent');
|
|
16
21
|
const { parseEvents } = require('../cmd/events');
|
|
17
22
|
const asks = require('./asks');
|
|
18
23
|
const ws = require('./workspace');
|
|
24
|
+
const rosterLib = require('./agents');
|
|
19
25
|
|
|
20
|
-
const ACK_TEXT = '收到,正在处理,稍等。';
|
|
21
|
-
// 上一句还没答完又来一句(插话):先回这句,告诉他会和上一句一起考虑
|
|
22
|
-
const ACK_MORE_TEXT = '收到,正在处理,稍等。';
|
|
26
|
+
const ACK_TEXT = '收到,正在处理,稍等。';
|
|
23
27
|
const TRIGGER_KEEP_DAYS = 2;
|
|
24
28
|
const OPEN_MAX = 10;
|
|
25
29
|
const OPEN_MS = 24 * 3600 * 1000;
|
|
@@ -37,7 +41,7 @@ const queueDir = (root) => path.join(root, '01-inbox', '_rhythm', 'queue');
|
|
|
37
41
|
const triggersStore = new Map();
|
|
38
42
|
const triggersOf = (root) => (triggersStore.has(root) ? triggersStore.get(root)() : {});
|
|
39
43
|
|
|
40
|
-
//
|
|
44
|
+
// 每跑完一条记一行(只有元数据)。手动跑的也记,manual 标出来
|
|
41
45
|
function appendHistory(data, row) {
|
|
42
46
|
data.history = [...(data.history || []), { at: fmtStamp(), uid: uid(), ...row }];
|
|
43
47
|
}
|
|
@@ -127,6 +131,18 @@ function pendingCards(root) {
|
|
|
127
131
|
}
|
|
128
132
|
|
|
129
133
|
// 提炼的任务书:定时采集之后,把 01-inbox 里今天的新数据按 sources.yaml 的规则炼成事件、并进事件流
|
|
134
|
+
function playbookDistillBody() {
|
|
135
|
+
return [
|
|
136
|
+
'# 任务:静默整理现场手册(PLAYBOOK.md)',
|
|
137
|
+
'',
|
|
138
|
+
'1. 读 04-patterns/PLAYBOOK.md(不存在就新建,按 docs/formats.md 的「现场手册」两张表格式)。',
|
|
139
|
+
'2. 读最近 3 天的交接文档 .agents/handoff/*.md 和 *.result.md(重点看路由选过的工作区、回执里用过的命令和 skill、踩过的坑和失败原因)、00-config/workspaces.json、00-config/sources.yaml 的 extract 规则和今日事件流的「索引」列。',
|
|
140
|
+
'3. 增量更新「按触发查」和「按来源归纳」:**只能新增和修改,绝对不要删除已有条目**。基于工作者背景沉淀有长期价值的经验;一次性的、没有长期价值的可以不记,或者只简单记一条能索引回工作现场的指针(如工作区/回执短号)。同一触发合并更新,不要编造命令和路径,不写密钥。',
|
|
141
|
+
'4. 静默完成:只改 04-patterns/PLAYBOOK.md,不发消息,不打扰用户。',
|
|
142
|
+
'',
|
|
143
|
+
].join('\n');
|
|
144
|
+
}
|
|
145
|
+
|
|
130
146
|
function refineBody(file) {
|
|
131
147
|
return [
|
|
132
148
|
'# 任务:把今天新采到的数据提炼成事件',
|
|
@@ -163,17 +179,29 @@ function answerBody(c) {
|
|
|
163
179
|
return lines.join('\n');
|
|
164
180
|
}
|
|
165
181
|
|
|
166
|
-
//
|
|
167
|
-
//
|
|
182
|
+
// 几段话(dress 出来的 { t, body, foot })装进尽量少的消息:一条的正文不超过 max 字,装不下的放下一条;页面地址相同的只附一次。
|
|
183
|
+
// 返回 [{ items, text }],text 就是要发的那条消息
|
|
184
|
+
function packOutbox(items, max) {
|
|
185
|
+
const messages = [];
|
|
186
|
+
let cur = null;
|
|
187
|
+
for (const it of items) {
|
|
188
|
+
if (cur && Array.from(`${cur.bodies.join('\n\n')}\n\n${it.body}`).length <= max) {
|
|
189
|
+
cur.bodies.push(it.body);
|
|
190
|
+
if (it.foot && !cur.feet.includes(it.foot)) cur.feet.push(it.foot);
|
|
191
|
+
cur.items.push(it);
|
|
192
|
+
} else {
|
|
193
|
+
cur = { bodies: [it.body], feet: it.foot ? [it.foot] : [], items: [it] };
|
|
194
|
+
messages.push(cur);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return messages.map((m) => ({ items: m.items, text: [m.bodies.join('\n\n'), m.feet.join('\n')].filter(Boolean).join('\n\n') }));
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// cfg 来自 rhythm.js 的 loadConfig(routerTimeout、handoffKeep、historyKeep、taskTimeout、mergeWait、agentMode、push、quiet、links、baseUrl、
|
|
201
|
+
// serviceAlive、ack、botMode、botTimeout、workerIdle、progress、progressMax、messageDebounce、replyMax、botPreamble、refine、refineInterval)。state 是 { data, save }
|
|
168
202
|
function createEngine({ root, env, cfg, log = () => {}, push = async () => false, state, since = Date.now() }) {
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
const workerSpec = {
|
|
172
|
-
agent: s(env.YZJ_WORKER_AGENT) || s(env.YZJ_BOT_AGENT),
|
|
173
|
-
model: s(env.YZJ_WORKER_MODEL) || cfg.agentModel || s(env.YZJ_BOT_MODEL),
|
|
174
|
-
effort: s(env.YZJ_WORKER_EFFORT) || cfg.agentEffort || s(env.YZJ_BOT_EFFORT),
|
|
175
|
-
};
|
|
176
|
-
const agentLabel = `${workerSpec.agent}${workerSpec.model ? `(${workerSpec.model})` : ''}`;
|
|
203
|
+
let envNow = env; // setEnv 能换:网页上保存配置之后 local.env 可能改过(路由的会话)
|
|
204
|
+
const roster = () => rosterLib.loadRoster(root, envNow);
|
|
177
205
|
const triggers = () => state.data.triggers;
|
|
178
206
|
const save = () => state.save();
|
|
179
207
|
triggersStore.set(root, triggers);
|
|
@@ -187,7 +215,11 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
187
215
|
let pumpScheduled = false; // 这个 tick 里已经排了一轮
|
|
188
216
|
let msgBuf = null;
|
|
189
217
|
let msgTimer = null;
|
|
218
|
+
let outbox = null; // 路由这一轮要发给用户的话先攒在这儿([{ t, body, foot }]),决定都做完了再合成尽量少的消息发
|
|
219
|
+
const held = []; // 攒着的汇报 [{ fields, origin }]:手头还有别的活在跑时,先做完的等一等,一起交回路由
|
|
220
|
+
let heldTimer = null; // 等的上限(cfg.mergeWait 秒),到点先把攒着的交回
|
|
190
221
|
const activeProgress = new Map(); // id → { t, started }
|
|
222
|
+
const pulse = new Map(); // 在跑的执行者 → { outputAt }:上一次收到它输出的时刻(只记边跑边输出的预置,别的家最后才吐)
|
|
191
223
|
let progressTimer = null;
|
|
192
224
|
let progressStepMs = 0;
|
|
193
225
|
const MAX_PROGRESS_STEP_MS = 30 * 60 * 1000; // 指数退避封顶 30 分钟
|
|
@@ -205,11 +237,14 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
205
237
|
const all = [...activeProgress.values()];
|
|
206
238
|
if (all.length === 1) {
|
|
207
239
|
const { t, started } = all[0];
|
|
208
|
-
|
|
240
|
+
// 带上执行者最近记的一步过程(它没记过就不带)
|
|
241
|
+
const step = handoff.lastStatus(root, t.id).line;
|
|
242
|
+
send(t, `还在做(已经 ${humanDuration((now - started) / 1000)} · 工作区 ${t.ws || '工作目录'}):${t.title || t.id}。${step ? `最近一步:${step}。` : ''}做完汇报。`, { mark: false });
|
|
209
243
|
} else {
|
|
210
244
|
const lines = ['手头有 ' + all.length + ' 件事还在做(做完汇报):'];
|
|
211
245
|
all.forEach(({ t, started }, i) => {
|
|
212
|
-
|
|
246
|
+
const step = handoff.lastStatus(root, t.id).line;
|
|
247
|
+
lines.push(`${i + 1}. [工作区 ${t.ws || '工作目录'}] ${t.title || t.id}(已 ${humanDuration((now - started) / 1000)})${step ? `:最近一步 ${step}` : ''}`);
|
|
213
248
|
});
|
|
214
249
|
send(null, lines.join('\n'), { mark: false });
|
|
215
250
|
}
|
|
@@ -232,15 +267,56 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
232
267
|
return enqueue('message', { key: b.keys[0], text: b.texts.join('\n'), mode: cfg.botMode });
|
|
233
268
|
}
|
|
234
269
|
let sink = null;
|
|
235
|
-
|
|
236
|
-
|
|
270
|
+
|
|
271
|
+
// 执行者的池子按组分:每组一个,同时最多跑它名册里的数量(数量改了跟着改)
|
|
272
|
+
const pools = new Map();
|
|
273
|
+
const poolOf = (group) => {
|
|
274
|
+
let pool = pools.get(group.id);
|
|
275
|
+
if (!pool) {
|
|
276
|
+
pool = createPool({ limit: group.count });
|
|
277
|
+
pools.set(group.id, pool);
|
|
278
|
+
}
|
|
279
|
+
pool.setLimit(group.count);
|
|
280
|
+
return pool;
|
|
281
|
+
};
|
|
282
|
+
const allPools = () => [...pools.values()];
|
|
283
|
+
const runningAll = () => allPools().flatMap((p) => p.running());
|
|
284
|
+
const queuedAll = () => allPools().flatMap((p) => p.queued());
|
|
285
|
+
|
|
286
|
+
// 路由按名册里当前的配置起。名册变了(网页或命令行改了 agent、模型、强度,换了会话)就换一个;
|
|
287
|
+
// 换了 agent 时把它自己的专属会话清掉(别的 agent 接不上那个会话)
|
|
288
|
+
let router = null;
|
|
289
|
+
let routerSig = '';
|
|
290
|
+
let routerAgent = '';
|
|
291
|
+
function routerNow() {
|
|
292
|
+
const team = roster();
|
|
293
|
+
const role = { ...team.router, effort: rosterLib.routerEffort(team.router), session: rosterLib.routerSession(envNow, team.router.agent) };
|
|
294
|
+
const sig = JSON.stringify([role.agent, role.model, role.effort, role.session]);
|
|
295
|
+
if (!router || sig !== routerSig) {
|
|
296
|
+
if (router && routerAgent !== role.agent) router.resetSession();
|
|
297
|
+
router = createRouter({ root, env: envNow, role, timeoutS: cfg.routerTimeout, preamble: cfg.botPreamble || '', log });
|
|
298
|
+
routerAgent = role.agent;
|
|
299
|
+
routerSig = sig;
|
|
300
|
+
log('路由就绪', `${role.agent || '没绑'}${role.model ? ` · ${role.model}` : ''} · ${role.effort || '强度用默认'}`);
|
|
301
|
+
}
|
|
302
|
+
return router;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// 派给哪一组执行者:路由点了名就用那组(编号不认识就派给第一组,记一笔);没点名是第一组。
|
|
306
|
+
// 续做、插话带着原来那组的编号来,所以还是原来那个 agent 接着它的会话跑
|
|
307
|
+
function groupOf(id) {
|
|
308
|
+
const groups = roster().workers;
|
|
309
|
+
const pick = groups.find((w) => w.id === id);
|
|
310
|
+
if (id && !pick) log('执行者的编号不认识', `${id},派给 ${groups[0] ? groups[0].id : 'w1'}`);
|
|
311
|
+
return pick || groups[0] || { id: 'w1', agent: '', model: '', effort: '', count: 1 };
|
|
312
|
+
}
|
|
237
313
|
|
|
238
314
|
// 权限和超时由触发来源定。重做的沿用原来那条的。
|
|
239
315
|
// IM 来的话(message)分两种:路由判成 dispatch 的是「派人做事」,事要写文件,按定时任务的权限来(rhythm.agent-mode)——
|
|
240
|
-
// 2026-12-02
|
|
316
|
+
// 2026-12-02 用户决定,原来一律只读,结果派出去的人写不了、做不成;路由没出决定时的兜底还是 YZJ_BOT_AGENT_MODE(默认 plan,只读)
|
|
241
317
|
function terms(t, { byRouter = false } = {}) {
|
|
242
318
|
if (t.kind === 'schedule') return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
|
|
243
|
-
if (t.kind === 'message' &&
|
|
319
|
+
if (t.kind === 'message' && byRouter) return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
|
|
244
320
|
if (t.kind === 'answer') {
|
|
245
321
|
const o = live.get(t.id) && live.get(t.id).ask && live.get(t.id).ask.from && triggers()[live.get(t.id).ask.from.trigger];
|
|
246
322
|
if (o && o.worker && o.worker.mode) return { mode: o.worker.mode, timeoutS: o.worker.timeoutS || cfg.taskTimeout };
|
|
@@ -254,13 +330,13 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
254
330
|
return { mode: (live.get(t.id) || {}).mode || 'plan', timeoutS: cfg.taskTimeout };
|
|
255
331
|
}
|
|
256
332
|
|
|
257
|
-
const isActive = (id) =>
|
|
333
|
+
const isActive = (id) => runningAll().some((e) => e.id === id) || queuedAll().includes(id);
|
|
258
334
|
|
|
259
|
-
//
|
|
335
|
+
// 手头的事:在跑的、排队里的、今天做完的,给路由认「同一件事」用。在跑的带上它最近记的一步过程(用户问「做到哪了」路由直接答)
|
|
260
336
|
function openItems() {
|
|
261
337
|
const now = Date.now();
|
|
262
|
-
const act = [...
|
|
263
|
-
const row = (x) => ({ id: x.id, status: STATUS_CN[x.worker.status] || '在跑', at: x.at, title: x.title || '', ws: x.ws || '' });
|
|
338
|
+
const act = [...runningAll().map((e) => e.id), ...queuedAll()];
|
|
339
|
+
const row = (x) => ({ id: x.id, status: STATUS_CN[x.worker.status] || '在跑', at: x.at, title: x.title || '', ws: x.ws || '', step: x.worker.status === 'running' ? handoff.lastStatus(root, x.id).line : '' });
|
|
264
340
|
const done = Object.values(triggers()).filter((x) => x.worker && ['ok', 'failed', 'stopped'].includes(x.worker.status) && now - stampMs(x.worker.endedAt || x.at) < OPEN_MS).sort((a, b) => b.at.localeCompare(a.at));
|
|
265
341
|
return [...act.map((id) => triggers()[id]).filter(Boolean).map(row), ...done.map(row)].slice(0, OPEN_MAX);
|
|
266
342
|
}
|
|
@@ -276,18 +352,21 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
276
352
|
}
|
|
277
353
|
|
|
278
354
|
// 新的触发进队列。key 一样的只处理一次。返回记录,或者 null(重复的)
|
|
279
|
-
|
|
355
|
+
// 这条消息是不是从 IM 里来的(listen handle 走一遍的那种不是:去重键以 handle- 开头)
|
|
356
|
+
const fromIm = (t) => !/^handle-/.test(String(t.key || ''));
|
|
357
|
+
function enqueue(kind, { key = '', text = '', task = '', taskFile = '', taskBody = '', taskTitle = '', mode = '', of = '', ok = false, seconds = 0, reason = '', opening = '', quiet = false, linkTask = '', orig = null, events = null, sources = null, ask = null, date = '', root: eventRoot, manual = false } = {}) {
|
|
280
358
|
if (key && Object.values(triggers()).some((x) => x.key === key)) return null;
|
|
281
|
-
const t = record(kind, { key, task, of, quiet });
|
|
359
|
+
const t = record(kind, { key, task, of, quiet, manual });
|
|
282
360
|
live.set(t.id, { text, taskFile, taskBody, taskTitle, mode, opening, linkTask, orig, ok, seconds, reason, events, sources, ask, date, root: eventRoot || root });
|
|
283
361
|
if (kind === 'answer' && ask) t.title = `回答:${ask.item || ask.question || ''}`;
|
|
284
362
|
queue.push(t.id);
|
|
285
363
|
save();
|
|
286
364
|
log('触发入队', `${t.id} ${kind}`);
|
|
287
|
-
//
|
|
288
|
-
|
|
365
|
+
// 有东西在做(路由在想、前面还排着、执行者在跑):这句不会马上答,先回一句「收到」,说会和上一句一起考虑。
|
|
366
|
+
// listen handle(命令行里走一遍)不是从 IM 来的,不用回这句
|
|
367
|
+
if (kind === 'message' && fromIm(t) && cfg.ack && (busy || queue.length > 1 || deferred || runningAll().length)) {
|
|
289
368
|
t.acked = true;
|
|
290
|
-
send(null,
|
|
369
|
+
send(null, ACK_TEXT, { mark: false });
|
|
291
370
|
}
|
|
292
371
|
schedulePump();
|
|
293
372
|
return t;
|
|
@@ -303,21 +382,29 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
303
382
|
});
|
|
304
383
|
}
|
|
305
384
|
|
|
306
|
-
//
|
|
307
|
-
|
|
385
|
+
// 一段话要发出去的样子:太长截断并注明;定时任务的汇报后面附本机页面地址。没内容返回 null
|
|
386
|
+
function dress(text, linkTask) {
|
|
308
387
|
const chars = Array.from(String(text || '').trim());
|
|
309
|
-
if (!chars.length) return
|
|
310
|
-
let out = chars.length > cfg.replyMax ? `${chars.slice(0, cfg.replyMax).join('')}\n…(回复太长,截到 ${cfg.replyMax} 字)` : chars.join('');
|
|
388
|
+
if (!chars.length) return null;
|
|
311
389
|
const link = linkTask && cfg.links[linkTask];
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
390
|
+
return {
|
|
391
|
+
body: chars.length > cfg.replyMax ? `${chars.slice(0, cfg.replyMax).join('')}\n…(回复太长,截到 ${cfg.replyMax} 字)` : chars.join(''),
|
|
392
|
+
foot: link && cfg.serviceAlive() ? `→ ${link.label}:${cfg.baseUrl}${link.path(today())}` : '',
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// 发出去了(或者按配置不发):这条触发记上「发了」。汇报发出去了,原来那件事也算「发了」(监控里看的就是那件事)
|
|
397
|
+
function markSent(t) {
|
|
398
|
+
if (!t) return;
|
|
399
|
+
t.notified = true;
|
|
400
|
+
const origin = t.kind === 'report' && triggers()[t.of];
|
|
401
|
+
if (origin) origin.notified = true;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// 真发出去:命令行走一遍时交给 sink;push 关着只记日志
|
|
405
|
+
async function deliver(text) {
|
|
319
406
|
if (sink) {
|
|
320
|
-
sink(
|
|
407
|
+
sink(text);
|
|
321
408
|
return true;
|
|
322
409
|
}
|
|
323
410
|
if (!cfg.push) {
|
|
@@ -325,21 +412,76 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
325
412
|
return false;
|
|
326
413
|
}
|
|
327
414
|
try {
|
|
328
|
-
return await push(
|
|
415
|
+
return await push(text);
|
|
329
416
|
} catch (error) {
|
|
330
417
|
log('推送出错', error && error.message ? error.message : String(error));
|
|
331
418
|
return false;
|
|
332
419
|
}
|
|
333
420
|
}
|
|
334
421
|
|
|
422
|
+
// 发一段文字给用户。
|
|
423
|
+
// 路由这一轮还没走完(outbox 攒着)且是要发给我的结果(reply、notify、兜底时的话):先攒着,这一轮的决定都做完了,
|
|
424
|
+
// 和同一轮里别的话合成一条发。「收到」「还在做」这类 mark 为 false 的不攒,马上发
|
|
425
|
+
async function send(t, text, { mark = true, linkTask = '' } = {}) {
|
|
426
|
+
const part = dress(text, linkTask);
|
|
427
|
+
if (!part) return false;
|
|
428
|
+
if (mark && outbox) {
|
|
429
|
+
outbox.push({ t, ...part });
|
|
430
|
+
return true;
|
|
431
|
+
}
|
|
432
|
+
if (mark) markSent(t);
|
|
433
|
+
return deliver([part.body, part.foot].filter(Boolean).join('\n\n'));
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// 一轮结束了:把攒下的话发出去(装进尽量少的消息),发过的那几条记上「发了」
|
|
437
|
+
async function flushOutbox(box) {
|
|
438
|
+
if (!box.length) return;
|
|
439
|
+
for (const m of packOutbox(box, cfg.replyMax)) {
|
|
440
|
+
m.items.forEach((it) => markSent(it.t));
|
|
441
|
+
await deliver(m.text);
|
|
442
|
+
}
|
|
443
|
+
save();
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// 手头还有哪些活在做(在跑的、排队的)——只算汇报会发给我的那些:不推送的任务、提炼、被插话停掉的不算
|
|
447
|
+
function othersRunning(id) {
|
|
448
|
+
return [...runningAll().map((e) => e.id), ...queuedAll()].filter((x) => {
|
|
449
|
+
const o = triggers()[x];
|
|
450
|
+
return x !== id && o && !o.quiet && o.kind !== 'refine' && !o.suppressReport;
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// 把攒着的汇报交回路由(建触发、排进队列,下一轮一起给路由)。先做完的排在前面
|
|
455
|
+
function flushHeld() {
|
|
456
|
+
if (heldTimer) {
|
|
457
|
+
clearTimeout(heldTimer);
|
|
458
|
+
heldTimer = null;
|
|
459
|
+
}
|
|
460
|
+
if (!held.length) return;
|
|
461
|
+
const batch = held.splice(0);
|
|
462
|
+
log('汇报一起交回', batch.map((h) => h.origin.id).join(' '));
|
|
463
|
+
for (const h of batch) {
|
|
464
|
+
delete h.origin.reportPending;
|
|
465
|
+
enqueue('report', h.fields);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// 一件结束了却不出汇报(被插话停掉的):手头没有别的活在做了,就把攒着的汇报交回
|
|
470
|
+
function settleIfIdle(t) {
|
|
471
|
+
if (!othersRunning(t.id).length) flushHeld();
|
|
472
|
+
}
|
|
473
|
+
|
|
335
474
|
// 执行者结束:补回执、记一笔、生成汇报
|
|
336
475
|
function finishWorker(t, r) {
|
|
337
476
|
const ok = r.ok;
|
|
338
|
-
|
|
477
|
+
const who = `${t.worker.agent || ''}${t.worker.model ? `(${t.worker.model})` : ''}`;
|
|
478
|
+
if (ok && !handoff.resultReady(root, t.id)) handoff.writeResult(root, t.id, r.reply, { ok: true, seconds: r.seconds, agent: who, by: 'cli' });
|
|
339
479
|
const body = r.stopped ? '用户叫停,这件事没做完。' : r.partial ? `时间到了,做到这里:\n\n${r.partial}` : '';
|
|
340
|
-
if (!ok) handoff.writeResult(root, t.id, body, { ok: false, reason: r.failed, seconds: r.seconds, agent:
|
|
480
|
+
if (!ok) handoff.writeResult(root, t.id, body, { ok: false, reason: r.failed, seconds: r.seconds, agent: who, by: 'cli-fail' });
|
|
481
|
+
// 过程记录并进回执的「## 过程」:做到哪一步停下的、一路经过了什么,回执里看得到(执行者自己写了这一节的不动)
|
|
482
|
+
handoff.attachTrail(root, t.id);
|
|
341
483
|
Object.assign(t.worker, { status: ok ? 'ok' : r.stopped ? 'stopped' : 'failed', seconds: r.seconds, sessionId: r.sessionId || t.worker.sessionId || '', reason: r.failed, endedAt: fmtStamp() });
|
|
342
|
-
appendHistory(state.data, { id: t.id, kind: t.kind, task: t.task || '', decision: t.decision, ok, seconds: r.seconds, sessionId: t.worker.sessionId, agent:
|
|
484
|
+
appendHistory(state.data, { id: t.id, kind: t.kind, task: t.task || '', decision: t.decision, ok, seconds: r.seconds, sessionId: t.worker.sessionId, agent: t.worker.agent, model: t.worker.model, effort: t.worker.effort, worker: t.worker.id, mode: t.worker.mode, manual: Boolean(t.manual) });
|
|
343
485
|
save();
|
|
344
486
|
log('执行者结束', `${t.id} ${ok ? '成功' : r.stopped ? '叫停' : '失败'} ${r.seconds}s`);
|
|
345
487
|
const c = live.get(t.id) || {};
|
|
@@ -348,10 +490,18 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
348
490
|
afterRefine(t, r);
|
|
349
491
|
return r;
|
|
350
492
|
}
|
|
493
|
+
if (t.kind === 'playbook') {
|
|
494
|
+
log('手册整理结束', r.ok ? t.id : `${t.id} 失败:${r.failed || '未知原因'}`);
|
|
495
|
+
return r;
|
|
496
|
+
}
|
|
497
|
+
if (ok && (t.kind === 'message' || t.kind === 'manual') && !t.quiet) {
|
|
498
|
+
maybeDistillPlaybook();
|
|
499
|
+
}
|
|
351
500
|
// 被插话停掉的:不汇报,接着它重跑的那次会汇报
|
|
352
501
|
if (t.suppressReport) {
|
|
353
502
|
delete t.suppressReport;
|
|
354
503
|
save();
|
|
504
|
+
settleIfIdle(t);
|
|
355
505
|
return r;
|
|
356
506
|
}
|
|
357
507
|
// 服务正在停:不再交给路由,记一笔,下次启动时 recover() 补汇报
|
|
@@ -360,26 +510,52 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
360
510
|
save();
|
|
361
511
|
return r;
|
|
362
512
|
}
|
|
363
|
-
|
|
513
|
+
const fields = {
|
|
364
514
|
key: `report-${t.id}`, of: t.id, ok, seconds: r.seconds, reason: r.stopped ? '用户叫停' : r.failed, quiet: t.quiet,
|
|
365
515
|
opening: ok ? handoff.opening(resultBody(handoff.readText(handoff.resultPath(root, t.id)))) : '', linkTask: t.kind === 'schedule' ? t.task : '', orig: t, task: c.linkTask,
|
|
366
|
-
}
|
|
516
|
+
};
|
|
517
|
+
// 手头还有别的活(汇报要发给我的)在做:这份汇报先攒着,等它们做完一起交回路由(最多等 mergeWait 秒),回我的话合成一条。
|
|
518
|
+
// 只有它一件在做、或者不等:做完就交回,和原来一样。
|
|
519
|
+
// 攒着的只是内存里的一份记录(汇报的触发到交回时才建);这件事这期间记着「还没汇报」,服务中途没了下次启动 recover() 会补
|
|
520
|
+
const others = cfg.mergeWait > 0 && !t.quiet ? othersRunning(t.id) : [];
|
|
521
|
+
if (others.length) {
|
|
522
|
+
t.reportPending = true;
|
|
523
|
+
save();
|
|
524
|
+
held.push({ fields, origin: t });
|
|
525
|
+
if (!heldTimer) {
|
|
526
|
+
heldTimer = setTimeout(flushHeld, cfg.mergeWait * 1000);
|
|
527
|
+
if (heldTimer.unref) heldTimer.unref();
|
|
528
|
+
}
|
|
529
|
+
log('汇报先攒着', `${t.id}:手头还有 ${others.join(' ')} 在做`);
|
|
530
|
+
return r;
|
|
531
|
+
}
|
|
532
|
+
// 它是手头最后做完的:先把它前面攒着的汇报交回,再排自己的——先做完的排在前面
|
|
533
|
+
flushHeld();
|
|
534
|
+
enqueue('report', fields);
|
|
367
535
|
return r;
|
|
368
536
|
}
|
|
369
537
|
|
|
370
|
-
// 排一个执行者。
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
538
|
+
// 排一个执行者。group 是名册里那一组(agent、模型、强度、同时跑几个);agentOverride 是登记的工作区自带的 agent;
|
|
539
|
+
// after 给了就等那件事做完再起(续做一件还在跑的事)
|
|
540
|
+
function launch(t, { mode, timeoutS, group, resume = '', after = '', cwd = '', agentOverride = '' }) {
|
|
541
|
+
const spec = { agent: agentOverride || group.agent, model: group.model, effort: group.effort };
|
|
542
|
+
t.worker = { id: group.id, agent: spec.agent, model: spec.model, effort: spec.effort, mode, timeoutS, sessionId: resume || '', ws: t.ws || '' };
|
|
374
543
|
save();
|
|
375
544
|
const start = () => {
|
|
376
545
|
// 续做排在后面起:起的时候再读原来那件的会话 id(它可能到做完才有)
|
|
377
546
|
const target = after ? triggers()[after] : null;
|
|
378
547
|
const sid = resume || (target && target.worker && target.worker.sessionId) || '';
|
|
379
|
-
|
|
548
|
+
if (sid && t.worker.sessionId !== sid) {
|
|
549
|
+
t.worker.sessionId = sid;
|
|
550
|
+
save();
|
|
551
|
+
}
|
|
552
|
+
const p = poolOf(group).submit(t.id, async (ctrl) => {
|
|
380
553
|
t.worker.status = 'running';
|
|
381
554
|
t.worker.startedAt = fmtStamp();
|
|
382
555
|
save();
|
|
556
|
+
// 边跑边输出的预置(dsh、kimi…)记下它最后一次出声的时刻:监控里「多久没动静」说的是它;最后才吐的那几家按静默算会冤枉正常的长任务
|
|
557
|
+
const preset = PRESETS[presetKind(spec.agent)];
|
|
558
|
+
if (preset && preset.streams === true) pulse.set(t.id, { outputAt: Date.now() });
|
|
383
559
|
// 我这边直接派出去的(消息、手动)跑得久就统一汇总说一声;定时任务的汇报本来就会来,不额外打扰
|
|
384
560
|
const trackProgress = t.kind !== 'schedule' && !t.quiet && cfg.progress > 0; // 静默的(提炼、quiet 任务)不提示
|
|
385
561
|
if (trackProgress) {
|
|
@@ -389,16 +565,21 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
389
565
|
let r;
|
|
390
566
|
try {
|
|
391
567
|
r = await runWorker({
|
|
392
|
-
root, cwd: cwd || root, env, log, id: t.id, mode, timeoutS, idleS: cfg.workerIdle, spec, resume: sid, extraEnv: { WRJ_TRIGGER: t.id, WRJ_ROLE: 'worker' },
|
|
393
|
-
onSession: (
|
|
394
|
-
if (t.worker.sessionId !==
|
|
395
|
-
t.worker.sessionId =
|
|
568
|
+
root, cwd: cwd || root, env: envNow, log, id: t.id, mode, timeoutS, idleS: cfg.workerIdle, spec, resume: sid, extraEnv: { WRJ_TRIGGER: t.id, WRJ_ROLE: 'worker' },
|
|
569
|
+
onSession: (sid2) => {
|
|
570
|
+
if (t.worker.sessionId !== sid2) {
|
|
571
|
+
t.worker.sessionId = sid2;
|
|
396
572
|
save();
|
|
397
573
|
}
|
|
398
574
|
},
|
|
575
|
+
onOutput: () => {
|
|
576
|
+
const beat = pulse.get(t.id);
|
|
577
|
+
if (beat) beat.outputAt = Date.now();
|
|
578
|
+
},
|
|
399
579
|
onKill: (fn) => ctrl.setKill(fn),
|
|
400
580
|
});
|
|
401
581
|
} finally {
|
|
582
|
+
pulse.delete(t.id);
|
|
402
583
|
if (trackProgress) {
|
|
403
584
|
activeProgress.delete(t.id);
|
|
404
585
|
if (!activeProgress.size) stopProgressTimer();
|
|
@@ -421,11 +602,12 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
421
602
|
return start();
|
|
422
603
|
}
|
|
423
604
|
|
|
424
|
-
//
|
|
425
|
-
function dispatch(t, c, handoffBody, byRouter = false, wsId = '') {
|
|
605
|
+
// 交给执行者:写任务书、起运行。路由没给任务书的(或者兜底),拿原话或指令文件当任务书
|
|
606
|
+
function dispatch(t, c, handoffBody, byRouter = false, wsId = '', workerId = '') {
|
|
426
607
|
let body = s(handoffBody);
|
|
427
608
|
const { mode, timeoutS } = terms(t, { byRouter });
|
|
428
|
-
const
|
|
609
|
+
const group = groupOf(workerId);
|
|
610
|
+
const resolvedWs = wsId ? ws.discoverWorkspaces(root, envNow).resolve(wsId) : null;
|
|
429
611
|
if (resolvedWs) {
|
|
430
612
|
t.ws = resolvedWs.id;
|
|
431
613
|
t.wsPath = resolvedWs.path;
|
|
@@ -435,16 +617,25 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
435
617
|
else if (t.kind === 'report') body = `# 任务:重做 ${t.of}\n\n上一次的结果:${c.ok ? handoff.opening(handoff.readText(handoff.resultPath(root, t.of))) : c.reason}\n旧任务书在 ${handoff.relTask(t.of)},旧回执在 ${handoff.relResult(t.of)},先读它们。\n\n${body || '按原任务书重做一遍。'}`;
|
|
436
618
|
else if (!body) body = `# 任务:照用户的话做\n\n用户原话:「${c.text}」\n\n照它做。这是一句追问、单凭这句话做不了的话,在回执里说清楚缺什么。`;
|
|
437
619
|
t.title = handoff.titleOf(body) || t.task || '';
|
|
620
|
+
const pbSec = t.kind === 'message' || t.kind === 'manual' ? playbook.section(root, `${c.text || ''}\n${body}`) : '';
|
|
621
|
+
if (pbSec) body = `${body}\n\n${pbSec}`;
|
|
438
622
|
handoff.writeTask(root, { ...t, text: c.text, taskFile: c.taskFile }, body, { mode, timeoutS });
|
|
439
623
|
save();
|
|
440
|
-
|
|
441
|
-
if (t.kind === 'message' && cfg.ack && !t.acked) send(null, ACK_TEXT, { mark: false });
|
|
624
|
+
ackMessage(t);
|
|
442
625
|
// 派出去就接着派下一条,不等它做完(汇报会自己排回来)
|
|
443
|
-
launch(t, { mode, timeoutS, cwd: t.wsPath || root, agentOverride: resolvedWs && resolvedWs.agent ? resolvedWs.agent : '' });
|
|
626
|
+
launch(t, { mode, timeoutS, cwd: t.wsPath || root, group, agentOverride: resolvedWs && resolvedWs.agent ? resolvedWs.agent : '' });
|
|
444
627
|
return undefined;
|
|
445
628
|
}
|
|
446
629
|
|
|
447
|
-
//
|
|
630
|
+
// IM 来的话要动手了(派人、续做、插话):先回一句「收到」,路由慢的话我不用干等。入队时没回过的才回
|
|
631
|
+
const ackMessage = (t) => {
|
|
632
|
+
if (t.kind === 'message' && fromIm(t) && cfg.ack && !t.acked) {
|
|
633
|
+
t.acked = true;
|
|
634
|
+
send(null, ACK_TEXT, { mark: false });
|
|
635
|
+
}
|
|
636
|
+
};
|
|
637
|
+
|
|
638
|
+
// 续做:用户这句话接着手头某件事说的。接着原来那个执行者的会话跑、还是它那一组;它还在跑就排在后面
|
|
448
639
|
function continueWith(t, c, targetId) {
|
|
449
640
|
const target = triggers()[targetId];
|
|
450
641
|
if (!target || !openItems().some((o) => o.id === targetId)) {
|
|
@@ -460,11 +651,12 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
460
651
|
if (target.ws) { t.ws = target.ws; t.wsPath = target.wsPath || ''; }
|
|
461
652
|
handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
|
|
462
653
|
save();
|
|
463
|
-
|
|
654
|
+
ackMessage(t);
|
|
655
|
+
launch(t, { mode, timeoutS, group: groupOf(target.worker && target.worker.id), resume: (target.worker && target.worker.sessionId) || '', after: isActive(targetId) ? targetId : '', cwd: t.wsPath || root });
|
|
464
656
|
return undefined;
|
|
465
657
|
}
|
|
466
658
|
|
|
467
|
-
//
|
|
659
|
+
// 插话改要求:停掉在跑的那件事,带着新要求接着它的会话重跑(还是它那一组)。被停的那次不汇报(这次的结果会覆盖它)
|
|
468
660
|
function interruptWith(t, c, targetId) {
|
|
469
661
|
const target = triggers()[targetId];
|
|
470
662
|
if (!target || !isActive(targetId)) {
|
|
@@ -478,11 +670,12 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
478
670
|
t.of = targetId;
|
|
479
671
|
if (target.ws) { t.ws = target.ws; t.wsPath = target.wsPath || ''; }
|
|
480
672
|
target.suppressReport = true;
|
|
481
|
-
|
|
673
|
+
poolOf(groupOf(target.worker && target.worker.id)).stop(targetId, '用户插话,改了要求');
|
|
482
674
|
handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
|
|
483
675
|
save();
|
|
484
676
|
log('插话', `${t.id} 停掉 ${targetId} 带着新要求重跑`);
|
|
485
|
-
|
|
677
|
+
ackMessage(t);
|
|
678
|
+
launch(t, { mode, timeoutS, group: groupOf(target.worker && target.worker.id), resume, cwd: t.wsPath || root });
|
|
486
679
|
return undefined;
|
|
487
680
|
}
|
|
488
681
|
|
|
@@ -494,20 +687,23 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
494
687
|
save();
|
|
495
688
|
return undefined;
|
|
496
689
|
}
|
|
497
|
-
const
|
|
690
|
+
const pool = target.worker && pools.get(target.worker.id);
|
|
691
|
+
const where = pool ? pool.stop(targetId, '用户叫停') : '';
|
|
498
692
|
t.reason = `叫停 ${targetId}`;
|
|
499
693
|
save();
|
|
500
694
|
log('叫停', `${targetId}(${where})`);
|
|
501
695
|
return undefined;
|
|
502
696
|
}
|
|
503
697
|
|
|
504
|
-
//
|
|
698
|
+
// 路由坏了、看不懂、漏了:按来源直接处理(兜底),不丢东西。
|
|
699
|
+
// 消息和手动塞进来的:原话当任务书派人(只读);到点的任务:指令文件当任务书;汇报:回执原样发回
|
|
505
700
|
function fallback(t, c, why) {
|
|
506
701
|
t.decision = 'fallback';
|
|
507
702
|
t.reason = s(why).slice(0, 200);
|
|
508
703
|
if (t.kind === 'report') {
|
|
509
704
|
if (c.ok) {
|
|
510
|
-
|
|
705
|
+
// 静默的标记在触发记录上(enqueue 写的),live 里没有
|
|
706
|
+
if (t.quiet || c.quiet) {
|
|
511
707
|
save();
|
|
512
708
|
return Promise.resolve();
|
|
513
709
|
}
|
|
@@ -520,7 +716,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
520
716
|
|
|
521
717
|
async function act(t, c, d) {
|
|
522
718
|
t.decision = d.action;
|
|
523
|
-
if (d.action === 'dispatch') return dispatch(t, c, d.handoff, true, d.ws || '');
|
|
719
|
+
if (d.action === 'dispatch') return dispatch(t, c, d.handoff, true, d.ws || '', d.worker || '');
|
|
524
720
|
if (d.action === 'continue') return continueWith(t, c, d.target);
|
|
525
721
|
if (d.action === 'interrupt') return interruptWith(t, c, d.target);
|
|
526
722
|
if (d.action === 'stop') return stopTask(t, d.target);
|
|
@@ -536,7 +732,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
536
732
|
}
|
|
537
733
|
if (d.action === 'notify') {
|
|
538
734
|
if (t.kind !== 'report') return fallback(t, c, 'notify 只用于汇报');
|
|
539
|
-
if (c.quiet) {
|
|
735
|
+
if (t.quiet || c.quiet) {
|
|
540
736
|
t.reason = '不推送的任务';
|
|
541
737
|
save();
|
|
542
738
|
return undefined;
|
|
@@ -547,35 +743,43 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
547
743
|
return fallback(t, c, `看不懂的决定 ${d.action || '(没写)'}`);
|
|
548
744
|
}
|
|
549
745
|
|
|
550
|
-
//
|
|
746
|
+
// 取走排队的触发交给路由(合批:一轮把排队的全部处理掉),再把决定做掉。
|
|
747
|
+
// 这一轮要发给用户的话先攒着(outbox),决定都做完了合成尽量少的消息发
|
|
551
748
|
async function pump() {
|
|
552
749
|
if (busy || closing || !queue.length) return;
|
|
553
750
|
busy = true;
|
|
554
751
|
const ids = queue.splice(0);
|
|
752
|
+
const box = [];
|
|
753
|
+
outbox = box;
|
|
555
754
|
try {
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
}
|
|
755
|
+
const r = routerNow();
|
|
756
|
+
const batch = ids.map((id) => triggers()[id]).filter(Boolean);
|
|
757
|
+
// 给路由看的几组执行者:各有几个名额、此刻在跑几个、排着几个
|
|
758
|
+
const groups = roster().workers.map((w) => {
|
|
759
|
+
const pool = pools.get(w.id);
|
|
760
|
+
return { ...w, running: pool ? pool.running().length : 0, queued: pool ? pool.queued().length : 0 };
|
|
761
|
+
});
|
|
762
|
+
const result = await r.decide(batch.map(view), openItems(), ws.discoverWorkspaces(root, envNow), groups);
|
|
763
|
+
state.data.rounds = [...(state.data.rounds || []), { at: fmtStamp(), uid: uid(), ok: result.ok, n: batch.length, seconds: (r.last() || {}).seconds || 0 }];
|
|
764
|
+
log(result.ok ? '路由出决定' : '路由没出决定', `${batch.length} 条${result.ok ? '' : `:${result.failed}`}`);
|
|
563
765
|
for (const id of ids) {
|
|
564
766
|
const t = triggers()[id];
|
|
565
767
|
if (!t) continue;
|
|
566
|
-
const d = result
|
|
768
|
+
const d = result.decisions[id];
|
|
567
769
|
if (d && d.action) await act(t, live.get(id) || {}, d);
|
|
568
|
-
else await fallback(t, live.get(id) || {}, result
|
|
770
|
+
else await fallback(t, live.get(id) || {}, result.failed || `路由漏了 ${id}`);
|
|
569
771
|
}
|
|
570
772
|
} catch (error) {
|
|
571
773
|
log('引擎出错', error && error.message ? error.message : String(error));
|
|
572
774
|
for (const id of ids) {
|
|
573
775
|
const t = triggers()[id];
|
|
574
|
-
if (t && !t.decision) await fallback(t, live.get(id) || {}, `引擎出错:${error && error.message ? error.message : error}`);
|
|
776
|
+
if (t && !t.decision) await fallback(t, live.get(id) || {}, `引擎出错:${error && error.message ? error.message : String(error)}`);
|
|
575
777
|
}
|
|
576
778
|
} finally {
|
|
577
|
-
|
|
779
|
+
outbox = null;
|
|
780
|
+
// 这一批的决定、发没发,都记下来;攒着的话这时才发。发完才算这一轮结束(waitIdle 等的就是它)
|
|
578
781
|
save();
|
|
782
|
+
await flushOutbox(box);
|
|
579
783
|
busy = false;
|
|
580
784
|
}
|
|
581
785
|
pump();
|
|
@@ -604,10 +808,37 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
604
808
|
handoff.writeTask(root, { ...t, text: '' }, refineBody(dailyFile(root, date)), { mode: cfg.agentMode, timeoutS: cfg.taskTimeout });
|
|
605
809
|
save();
|
|
606
810
|
log('提炼开始', t.id);
|
|
607
|
-
return launch(t, { mode: cfg.agentMode, timeoutS: cfg.taskTimeout });
|
|
811
|
+
return launch(t, { mode: cfg.agentMode, timeoutS: cfg.taskTimeout, group: groupOf('') });
|
|
608
812
|
}
|
|
609
813
|
|
|
610
814
|
// 提炼做完:只记一笔。失败只记日志和监控,不告诉用户(晚间复盘会自己再采一遍、炼一遍)
|
|
815
|
+
// 达到一定对话/任务次数(默认 5 次)或距上次沉淀超过间隔(默认 180 分钟且有新任务)时,静默整理一次现场手册
|
|
816
|
+
function maybeDistillPlaybook() {
|
|
817
|
+
const turns = (state.data.playbookTurns || 0) + 1;
|
|
818
|
+
state.data.playbookTurns = turns;
|
|
819
|
+
const maxTurns = cfg.playbookTurns || 10;
|
|
820
|
+
const intervalMin = cfg.playbookInterval || 180;
|
|
821
|
+
const last = state.data.playbookAt;
|
|
822
|
+
const dueByTurns = turns >= maxTurns;
|
|
823
|
+
const dueByTime = turns >= 1 && Boolean(last) && Date.now() - stampMs(last) >= intervalMin * 60000;
|
|
824
|
+
if (!dueByTurns && !dueByTime) {
|
|
825
|
+
save();
|
|
826
|
+
return null;
|
|
827
|
+
}
|
|
828
|
+
if (Object.values(triggers()).some((x) => x.kind === 'playbook' && x.worker && ['queued', 'running'].includes(x.worker.status))) {
|
|
829
|
+
save();
|
|
830
|
+
return null;
|
|
831
|
+
}
|
|
832
|
+
state.data.playbookTurns = 0;
|
|
833
|
+
state.data.playbookAt = fmtStamp();
|
|
834
|
+
const date = today();
|
|
835
|
+
const t = record('playbook', { key: `playbook-${date}-${Date.now()}`, decision: 'playbook', quiet: true, title: '静默整理现场手册' });
|
|
836
|
+
handoff.writeTask(root, { ...t, text: '' }, playbookDistillBody(), { mode: cfg.agentMode, timeoutS: cfg.taskTimeout });
|
|
837
|
+
save();
|
|
838
|
+
log('手册整理开始', `${t.id}(累计 ${turns} 次,${dueByTurns ? '达到次数' : '达到时间间隔'})`);
|
|
839
|
+
return launch(t, { mode: cfg.agentMode, timeoutS: cfg.taskTimeout, group: groupOf('') });
|
|
840
|
+
}
|
|
841
|
+
|
|
611
842
|
function afterRefine(t, r) {
|
|
612
843
|
state.data.refinedAt = fmtStamp();
|
|
613
844
|
save();
|
|
@@ -622,6 +853,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
622
853
|
if (!unfinished && !t.reportPending) continue;
|
|
623
854
|
if (unfinished) {
|
|
624
855
|
handoff.writeResult(root, t.id, '', { ok: false, reason: '服务重启时中断', by: 'cli-fail' });
|
|
856
|
+
handoff.attachTrail(root, t.id);
|
|
625
857
|
Object.assign(t.worker, { status: 'failed', reason: '服务重启时中断', endedAt: fmtStamp() });
|
|
626
858
|
}
|
|
627
859
|
delete t.reportPending;
|
|
@@ -630,15 +862,24 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
630
862
|
save();
|
|
631
863
|
}
|
|
632
864
|
|
|
633
|
-
// 服务要停了:在跑的执行者是子进程,得收掉(最多等 3
|
|
865
|
+
// 服务要停了:在跑的执行者是子进程,得收掉(最多等 3 秒)。之后不再交给路由。
|
|
866
|
+
// 攒着的汇报也不交了:那几件攒的时候就记着「还没汇报」,下次启动 recover() 补
|
|
634
867
|
async function shutdown() {
|
|
635
868
|
closing = true;
|
|
869
|
+
if (held.length) log('服务停止', `攒着的汇报 ${held.length} 条不交路由了,下次启动补`);
|
|
870
|
+
if (heldTimer) {
|
|
871
|
+
clearTimeout(heldTimer);
|
|
872
|
+
heldTimer = null;
|
|
873
|
+
}
|
|
874
|
+
held.length = 0;
|
|
636
875
|
if (msgTimer) { clearTimeout(msgTimer); msgTimer = null; }
|
|
637
876
|
msgBuf = null;
|
|
638
877
|
activeProgress.clear();
|
|
639
878
|
stopProgressTimer();
|
|
640
|
-
for (const
|
|
641
|
-
|
|
879
|
+
for (const pool of allPools()) {
|
|
880
|
+
for (const id of pool.queued()) pool.stop(id, '服务停止时中断');
|
|
881
|
+
for (const e of pool.running()) pool.stop(e.id, '服务停止时中断');
|
|
882
|
+
}
|
|
642
883
|
const pending = [...dones.values()];
|
|
643
884
|
if (pending.length) await Promise.race([Promise.allSettled(pending), new Promise((resolve) => setTimeout(resolve, 3000))]);
|
|
644
885
|
}
|
|
@@ -694,7 +935,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
694
935
|
const key = `msg-${m.msgId}`;
|
|
695
936
|
const text = s(m.content);
|
|
696
937
|
const debounceS = Number(cfg.messageDebounce) || 0;
|
|
697
|
-
if (!debounceS
|
|
938
|
+
if (!debounceS) return enqueue('message', { key, text, mode: cfg.botMode });
|
|
698
939
|
if (Object.values(triggers()).some((x) => x.key === key) || (msgBuf && msgBuf.keys.includes(key))) return null;
|
|
699
940
|
if (!msgBuf) msgBuf = { keys: [key], texts: [text], firstAt: Date.now() };
|
|
700
941
|
else { msgBuf.keys.push(key); msgBuf.texts.push(text); }
|
|
@@ -704,40 +945,62 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
|
|
|
704
945
|
return null;
|
|
705
946
|
},
|
|
706
947
|
flushMessages,
|
|
707
|
-
|
|
948
|
+
// 到点的任务变成一条触发。manual 为 true 是 work-rhythm run 手动跑的(监控里标出来)
|
|
949
|
+
schedule: (job, taskBody, taskTitle, { manual = false } = {}) => enqueue('schedule', { key: job.key, task: job.id, taskFile: `tasks/${job.id}.md`, taskBody, taskTitle, quiet: cfg.quiet.includes(job.id), manual }),
|
|
708
950
|
recover,
|
|
709
951
|
shutdown,
|
|
710
952
|
tick,
|
|
711
953
|
afterSync,
|
|
712
|
-
// 页面上答了一张卡:一条 answer 触发给路由(rhythm.js 调;ask 里带着答案)。
|
|
713
|
-
// 去重键用卡片 id;老办法登记的「未答」行没有卡片文件(id 是空的),用事项——不然第二张就会被当成重复丢掉
|
|
714
954
|
// 页面上答一张卡(work-rhythm ask 的卡):卡片这一块已经取消(2026-12-03),答了只记一笔,不再派活
|
|
715
955
|
answer: () => null,
|
|
716
956
|
// 命令行走一遍:要发的文字交到这里,不真发
|
|
717
957
|
setSink(fn) {
|
|
718
958
|
sink = fn;
|
|
719
959
|
},
|
|
720
|
-
//
|
|
960
|
+
// 网页上保存了名册之后调:换一份设置(local.env 可能改过),路由按新配置重起,执行者下一次派活就用新的
|
|
961
|
+
setEnv(next) {
|
|
962
|
+
envNow = next;
|
|
963
|
+
},
|
|
964
|
+
// 等到队列空、路由空、执行者都结束、攒着的汇报都交出去了。返回是不是等到了
|
|
721
965
|
async waitIdle(timeoutMs = 600000) {
|
|
722
966
|
const until = Date.now() + timeoutMs;
|
|
723
967
|
while (Date.now() < until) {
|
|
724
|
-
if (!busy && !queue.length && !deferred &&
|
|
968
|
+
if (!busy && !queue.length && !deferred && !held.length && allPools().every((p) => p.idle())) return true;
|
|
725
969
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
726
970
|
}
|
|
727
971
|
return false;
|
|
728
972
|
},
|
|
729
|
-
resetSession: () =>
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
973
|
+
resetSession: () => routerNow().resetSession(),
|
|
974
|
+
// 直接发一段话给用户(值守对 /new 的那句确认):不挂在那条触发上,push 关着就不发
|
|
975
|
+
say: (text) => send(null, text, { mark: false }),
|
|
976
|
+
doctorProblems: () => rosterLib.inspect(root, envNow, roster()).problems,
|
|
977
|
+
notes: () => rosterLib.inspect(root, envNow, roster()).notes,
|
|
978
|
+
status: () => {
|
|
979
|
+
const team = roster();
|
|
980
|
+
const r = routerNow();
|
|
981
|
+
const groups = team.workers.map((w) => {
|
|
982
|
+
const pool = pools.get(w.id);
|
|
983
|
+
return { ...w, running: pool ? pool.running().length : 0, queued: pool ? pool.queued().length : 0 };
|
|
984
|
+
});
|
|
985
|
+
return {
|
|
986
|
+
since,
|
|
987
|
+
router: { agent: team.router.agent, model: team.router.model, effort: rosterLib.routerEffort(team.router), session: r.describeSession(), queue: queue.length, held: held.length, busy, last: r.last(), roundsToday: roundsToday() },
|
|
988
|
+
// running 的每一条:step 是执行者最近记的一步过程(steps 一共几步、stepAge 是几秒前记的);
|
|
989
|
+
// quietFor 是它几秒没输出了(只有边跑边输出的预置才有,别的是 -1)
|
|
990
|
+
workers: {
|
|
991
|
+
limit: groups.reduce((n, g) => n + g.count, 0),
|
|
992
|
+
groups,
|
|
993
|
+
running: runningAll().map((e) => {
|
|
994
|
+
const st = handoff.lastStatus(root, e.id);
|
|
995
|
+
const beat = pulse.get(e.id);
|
|
996
|
+
const now = Date.now();
|
|
997
|
+
return { id: e.id, since: e.startedAt, kind: e.meta.kind, task: e.meta.task || '', step: st.line, steps: st.count, stepAge: st.at ? Math.max(0, Math.round((now - st.at) / 1000)) : 0, quietFor: beat ? Math.max(0, Math.round((now - beat.outputAt) / 1000)) : -1 };
|
|
998
|
+
}),
|
|
999
|
+
queued: queuedAll(),
|
|
1000
|
+
},
|
|
1001
|
+
};
|
|
1002
|
+
},
|
|
740
1003
|
};
|
|
741
1004
|
}
|
|
742
1005
|
|
|
743
|
-
module.exports = { createEngine, appendHistory, pruneState, historyStats, fire, queueDir, resultBody, pendingCards, dayEvents, eventKey, refineBody, ACK_TEXT, uid };
|
|
1006
|
+
module.exports = { createEngine, appendHistory, pruneState, historyStats, fire, queueDir, resultBody, pendingCards, dayEvents, eventKey, refineBody, packOutbox, ACK_TEXT, uid };
|