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.
- package/.agents/notes/AGENTS.md +12 -1
- package/.agents/notes/decisions/2026-12-01-agent-runs-the-login-for-the-user.md +30 -0
- package/.agents/notes/decisions/2026-12-01-interjections-batch-into-one-answer-and-interrupt-reruns.md +33 -0
- package/.agents/notes/decisions/2026-12-01-long-runs-are-bounded-by-silence-not-wall-clock.md +35 -0
- package/.agents/notes/decisions/2026-12-01-question-cards-via-cli-tool-on-todays-page-answers-return-to-router.md +40 -0
- package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +42 -0
- package/.agents/notes/decisions/2026-12-01-router-runs-on-a-flash-model-with-low-effort.md +33 -0
- package/.agents/notes/decisions/2026-12-01-sync-feeds-refine-then-events-to-the-router.md +38 -0
- package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +16 -0
- package/.agents/notes/pitfalls/2026-12-02-rhythm-start-in-the-foreground-displaces-the-launchd-service.md +27 -0
- package/.agents/skills/work-rhythm/SKILL.md +20 -12
- package/README.md +32 -4
- package/collectors/local.env.example +10 -1
- package/docs/agents.md +53 -13
- package/docs/channels.md +9 -6
- package/docs/router-worker.md +263 -0
- package/docs/scheduled-tasks.md +5 -5
- package/docs/sources.md +20 -0
- package/package.json +1 -1
- package/scripts/cli.js +5 -3
- package/scripts/cmd/agent.js +188 -49
- package/scripts/cmd/ask.js +104 -0
- package/scripts/cmd/check.js +4 -0
- package/scripts/cmd/listen.js +18 -4
- package/scripts/cmd/rhythm.js +6 -2
- package/scripts/cmd/sync.js +11 -3
- package/scripts/cmd/trigger.js +143 -0
- package/scripts/lib/agent.js +482 -30
- package/scripts/lib/asks.js +145 -0
- package/scripts/lib/bot.js +140 -35
- package/scripts/lib/engine.js +707 -0
- package/scripts/lib/handoff.js +167 -0
- package/scripts/lib/markdown.js +355 -36
- package/scripts/lib/rhythm.js +576 -38
- package/scripts/lib/router.js +208 -0
- package/scripts/lib/run.js +43 -0
- package/scripts/lib/view.js +736 -0
- package/scripts/lib/worker.js +98 -0
- package/scripts/test/agent.test.js +126 -9
- package/scripts/test/check.test.js +7 -2
- package/scripts/test/harness.js +15 -1
- package/scripts/test/listen.test.js +2 -2
- package/scripts/test/rhythm.test.js +109 -6
- package/scripts/test/router-helper.js +110 -0
- package/scripts/test/router.test.js +799 -0
- package/scripts/test/stubs.js +113 -12
- package/scripts/test/timeout.test.js +99 -0
- package/tasks/daily-plan.md +1 -2
- package/templates/00-config/profile.example.yaml +9 -0
- package/templates/AGENTS.md +3 -1
- package/templates/README.md +4 -1
|
@@ -0,0 +1,707 @@
|
|
|
1
|
+
// 引擎:触发 → 路由 → 执行者 → 汇报 → 发消息(docs/router-worker.md)。跑在本地服务(rhythm.js)的进程里;
|
|
2
|
+
// listen handle 在命令行的进程里也拿它走一遍(要发的文字交给 sink,不真发)。
|
|
3
|
+
// 触发的内容(原话、任务书正文、回执)只在内存里和 .agents/handoff/ 的文件里;state.json 只记元数据:
|
|
4
|
+
// triggers 每条的短号、去重键、来源、时间、决定、执行者的状态/用时/会话 id、发没发(留两天)
|
|
5
|
+
// history 每跑完一条记一行元数据(留 rhythm.history-keep 天),监控中心的次数和成功率从它算
|
|
6
|
+
// rounds 路由每一轮(留两天)
|
|
7
|
+
// seq 短号的序号
|
|
8
|
+
'use strict';
|
|
9
|
+
const fs = require('node:fs');
|
|
10
|
+
const path = require('node:path');
|
|
11
|
+
const { fmtStamp, today, humanDuration, progressPings } = require('./run');
|
|
12
|
+
const { roles } = require('./agent');
|
|
13
|
+
const handoff = require('./handoff');
|
|
14
|
+
const { createRouter } = require('./router');
|
|
15
|
+
const { createPool, runWorker } = require('./worker');
|
|
16
|
+
const { parseEvents } = require('../cmd/events');
|
|
17
|
+
const asks = require('./asks');
|
|
18
|
+
|
|
19
|
+
const ACK_TEXT = '收到,正在处理,稍等。'; // 和值守(bot.js)那句一样
|
|
20
|
+
// 上一句还没答完又来一句(插话):先回这句,告诉他会和上一句一起考虑
|
|
21
|
+
const ACK_MORE_TEXT = '收到,上一句还在答,这句会和它一起考虑。';
|
|
22
|
+
const TRIGGER_KEEP_DAYS = 2;
|
|
23
|
+
const OPEN_MAX = 10;
|
|
24
|
+
const OPEN_MS = 24 * 3600 * 1000;
|
|
25
|
+
const NOTE_BY_SERVICE = '(这次运行由 work-rhythm rhythm 发起:你最后写的那段总结写进回执,它会交给路由转述给用户,你自己不要再发。)';
|
|
26
|
+
const STATUS_CN = { queued: '排队中', running: '在跑', ok: '做完', failed: '没做成', stopped: '叫停' };
|
|
27
|
+
const DAY_MS = 24 * 3600 * 1000;
|
|
28
|
+
// 运行记录和路由轮数每一行的唯一 id:命令行和服务两个进程都会写状态文件,合并时靠它区分
|
|
29
|
+
let uidSeq = 0;
|
|
30
|
+
const uid = () => `${process.pid}:${Date.now().toString(36)}:${(uidSeq += 1)}`;
|
|
31
|
+
|
|
32
|
+
const pad6 = (n) => String(n).padStart(6, '0');
|
|
33
|
+
const s = (v) => String(v || '').trim();
|
|
34
|
+
const stampMs = (stamp) => new Date(String(stamp).replace(' ', 'T')).getTime();
|
|
35
|
+
const queueDir = (root) => path.join(root, '01-inbox', '_rhythm', 'queue');
|
|
36
|
+
const triggersStore = new Map();
|
|
37
|
+
const triggersOf = (root) => (triggersStore.has(root) ? triggersStore.get(root)() : {});
|
|
38
|
+
|
|
39
|
+
// 每跑完一条记一行(只有元数据)。直通模式下的 rhythm run 也记,manual 标出来
|
|
40
|
+
function appendHistory(data, row) {
|
|
41
|
+
data.history = [...(data.history || []), { at: fmtStamp(), uid: uid(), ...row }];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// 清掉过期的:触发留两天,路由的轮数留两天,运行记录留 historyKeep 天
|
|
45
|
+
function pruneState(data, { historyKeep = 90, now = Date.now() } = {}) {
|
|
46
|
+
const cutoff = fmtStamp(new Date(now - TRIGGER_KEEP_DAYS * DAY_MS));
|
|
47
|
+
for (const [id, t] of Object.entries(data.triggers || {})) if (String(t.at || '') < cutoff) delete data.triggers[id];
|
|
48
|
+
data.rounds = (data.rounds || []).filter((r) => String(r.at || '') >= cutoff);
|
|
49
|
+
const old = fmtStamp(new Date(now - historyKeep * DAY_MS));
|
|
50
|
+
data.history = (data.history || []).filter((r) => String(r.at || '') >= old);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// 从历史里算一个任务的次数、成败、最近一次、平均用时(给监控中心)
|
|
54
|
+
function historyStats(data, taskId, now = new Date()) {
|
|
55
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
56
|
+
const date = `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}`;
|
|
57
|
+
const rows = (data.history || []).filter((r) => r.task === taskId && r.kind === 'schedule');
|
|
58
|
+
const ok = rows.filter((r) => r.ok);
|
|
59
|
+
const done = rows.filter((r) => typeof r.seconds === 'number');
|
|
60
|
+
return {
|
|
61
|
+
today: rows.filter((r) => String(r.at).startsWith(date)).length,
|
|
62
|
+
ok: ok.length,
|
|
63
|
+
failed: rows.length - ok.length,
|
|
64
|
+
last: rows.length ? rows[rows.length - 1] : null,
|
|
65
|
+
avgSeconds: done.length ? Math.round(done.reduce((sum, r) => sum + r.seconds, 0) / done.length) : 0,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// work-rhythm trigger fire:写下一条等着服务的触发。服务没在跑就等着,起来后取走;超过一天的启动时清掉
|
|
70
|
+
function fire(root, { text, mode = 'plan' }) {
|
|
71
|
+
const dir = queueDir(root);
|
|
72
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
73
|
+
const key = `manual-${Date.now()}-${Math.random().toString(16).slice(2, 6)}`;
|
|
74
|
+
fs.writeFileSync(path.join(dir, `${key}.json`), `${JSON.stringify({ text, mode, at: fmtStamp() })}\n`);
|
|
75
|
+
return key;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 回执的正文:去掉开头那几行表头
|
|
79
|
+
function resultBody(text) {
|
|
80
|
+
const lines = String(text || '').split('\n');
|
|
81
|
+
let i = 0;
|
|
82
|
+
while (i < lines.length && (lines[i].startsWith('# ') || lines[i].startsWith('- ') || !lines[i].trim())) i += 1;
|
|
83
|
+
return lines.slice(i).join('\n').trim();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ---------------------------------------------------------------- 采集之后:提炼、新事件、待办卡片
|
|
87
|
+
const dailyFile = (root, date) => path.join(root, '02-daily', date.slice(0, 7), `${date}.md`);
|
|
88
|
+
const eventKey = (e) => `${e.date}|${e.time}|${e.type}|${e.item}|${e.source}`;
|
|
89
|
+
const readOrNull = (file) => {
|
|
90
|
+
try {
|
|
91
|
+
return fs.readFileSync(file, 'utf8');
|
|
92
|
+
} catch {
|
|
93
|
+
return '';
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
// 今天每日文件里的事件流(docs/formats.md),文件还没有就是空
|
|
97
|
+
function dayEvents(root, date) {
|
|
98
|
+
return parseEvents(readOrNull(dailyFile(root, date)), date);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// 待办卡片:DECISIONS.md 里「决定」还是「未答」的行(work-rhythm decisions add --choice 未答 登记的)。
|
|
102
|
+
// 返回 [{ date, item, options, by }],新的在前
|
|
103
|
+
function pendingCards(root) {
|
|
104
|
+
const lines = readOrNull(path.join(root, '03-carryover', 'DECISIONS.md')).split('\n');
|
|
105
|
+
const start = lines.findIndex((l) => /^##\s*决定\s*$/.test(l));
|
|
106
|
+
if (start < 0) return [];
|
|
107
|
+
const NAMES = { 日期: 'date', 事项: 'item', 选项: 'options', 决定: 'choice', 理由: 'reason', 谁来做: 'by', 落实: 'done' };
|
|
108
|
+
const out = [];
|
|
109
|
+
let columns = null;
|
|
110
|
+
for (let i = start + 1; i < lines.length && !/^##\s/.test(lines[i]); i += 1) {
|
|
111
|
+
const line = lines[i].trim();
|
|
112
|
+
if (!line.startsWith('|')) continue;
|
|
113
|
+
const cells = line.replace(/\\\|/g, '\u0000').split('|').slice(1, -1).map((c) => c.trim().replace(/\u0000/g, '|'));
|
|
114
|
+
if (!cells.length || cells.every((c) => /^:?-+:?$/.test(c))) continue;
|
|
115
|
+
if (!columns) {
|
|
116
|
+
columns = cells.map((name) => NAMES[name] || '');
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const row = {};
|
|
120
|
+
columns.forEach((field, n) => {
|
|
121
|
+
if (field) row[field] = cells[n] || '';
|
|
122
|
+
});
|
|
123
|
+
if (row.item && row.choice === '未答') out.push({ date: row.date, item: row.item, options: row.options || '', by: row.by || '' });
|
|
124
|
+
}
|
|
125
|
+
return out.reverse();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// 提炼的任务书:定时采集之后,把 01-inbox 里今天的新数据按 sources.yaml 的规则炼成事件、并进事件流
|
|
129
|
+
function refineBody(file) {
|
|
130
|
+
return [
|
|
131
|
+
'# 任务:把今天新采到的数据提炼成事件',
|
|
132
|
+
'',
|
|
133
|
+
'1. 读 00-config/sources.yaml:每个启用的源有「提炼成什么事件」的规则(extract)。',
|
|
134
|
+
'2. 读 01-inbox/<源id>/<今天>/ 下各源的输出(刚同步过;哪个源没有目录就跳过)。',
|
|
135
|
+
'3. 按各源的规则提炼事件,对照 docs/formats.md 的「事件流」:类型用词表里的词,一行一事、不记内容细节;项目能归就归。',
|
|
136
|
+
`4. 合并进今天每日文件(${file})的「## 事件流」:替换同来源同时段的旧事件,保留来源是「口述」的行,按时间排序;文件不存在就按格式创建。只改这一节。`,
|
|
137
|
+
'5. 回执里写:各源分别提炼出几条、合并后事件流一共几条;哪个源的数据读不到就写「未取到」,不要编。',
|
|
138
|
+
'',
|
|
139
|
+
'',
|
|
140
|
+
].join('\n');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// 回答之后的任务书:我在页面上答了一张卡。带着原问题、选项、我的回答、要记到哪;问这件事的执行者的任务书和回执也指给它
|
|
144
|
+
function answerBody(c) {
|
|
145
|
+
const ask = c.ask || {};
|
|
146
|
+
const opts = (ask.options || []).map((o, i) => `${['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩'][i] || `${i + 1}.`}${o.label}${o.suggested ? '(当时建议的)' : ''}`).join(' ');
|
|
147
|
+
const from = ask.from && ask.from.trigger ? triggersOf(c.root)[ask.from.trigger] : null;
|
|
148
|
+
const lines = [
|
|
149
|
+
'# 任务:我回答了,接着做',
|
|
150
|
+
'',
|
|
151
|
+
`当时问我的:「${ask.question}」${opts ? ` 选项:${opts}` : ''}${ask.context ? `\n背景:${ask.context}` : ''}`,
|
|
152
|
+
'',
|
|
153
|
+
`我的回答:${ask.answer ? ask.answer.choice : ''}${ask.answer && ask.answer.note ? ` 附言:${ask.answer.note}` : ''}`,
|
|
154
|
+
'',
|
|
155
|
+
from ? `这是执行者 ${ask.from.trigger} 问的:它的任务书在 ${handoff.relTask(ask.from.trigger)},回执在 ${handoff.relResult(ask.from.trigger)},先读它们,接着它做到的地方往下做。` : '这是我(或桌面上某个 agent)问的:按原问题把该做的做完。',
|
|
156
|
+
ask.record ? `把这次的结果记到:${ask.record}(按那里的格式;记完在回执里写明记到了哪里)。` : '把这次的结果按 docs/formats.md 记进该记的地方;记完在回执里写明记到了哪里。',
|
|
157
|
+
'',
|
|
158
|
+
'能当场做的当场做;要动外部系统(发消息、改日程、流转工作项)的,先把要发、要改的内容写进回执给我看,不要自己发。取不到的数据写「未取到」,不要编。',
|
|
159
|
+
'',
|
|
160
|
+
'',
|
|
161
|
+
];
|
|
162
|
+
return lines.join('\n');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// 重点与待办的任务书:路由把一批新事件派出去时用(路由可以再补一段)。c.root 是工作目录
|
|
166
|
+
function focusBody(c) {
|
|
167
|
+
const list = (c.events || []).map((e) => `- ${e.time} ${e.type} ${e.item}${e.project ? `(${e.source},${e.project})` : e.source ? `(${e.source})` : ''}`).join('\n');
|
|
168
|
+
const bad = (c.sources || []).filter((x) => !x.ok).map((x) => `${x.id}:${x.detail || `退出码 ${x.code}`}`).join(';');
|
|
169
|
+
const file = dailyFile(c.root || '.', c.date || today());
|
|
170
|
+
return [
|
|
171
|
+
'# 任务:根据新到的事件更新今日重点和待办',
|
|
172
|
+
'',
|
|
173
|
+
`今天新到的事件(${(c.events || []).length} 条):`,
|
|
174
|
+
list || '(没有新事件)',
|
|
175
|
+
...(bad ? ['', `这次采集有源没取到数据(回执里说清,涉及的事标「未取到」):${bad}`] : []),
|
|
176
|
+
'',
|
|
177
|
+
`1. 读今天每日文件(${file})的「## 计划」「## 事件流」「## 备注」,03-carryover/CARRYOVER.md 的未了结,05-goals/ 里进行中的目标。`,
|
|
178
|
+
'2. 据此更新「## 计划」里的今日重点(不超过 3 条,每条带建议时间块和理由)。只改这一处;例行的事(通勤、打卡)不算重点。「待你定」不要再写进计划文件:需要我拿主意的事走下面的卡片。',
|
|
179
|
+
'3. 需要我拿主意的事,逐件用 work-rhythm ask 丢出来(它会成一张卡,实时显示在今日页的「待你定」里)。先 work-rhythm ask list 看有没有同一件事还没答的,有就不重复问;没有就:',
|
|
180
|
+
' work-rhythm ask --json \'{"question":"<一句话的问题>","context":"<两三句背景:为什么现在要定、卡在哪>","options":[{"label":"<选项>","detail":"<一句话说明>","suggested":true},{"label":"<选项>"}],"record":"<我答了之后总结记到哪,如 03-carryover/CARRYOVER.md 的未了结>","item":"<不超过 30 字的短事项>"}\'',
|
|
181
|
+
' 2–4 个选项,其中一个标 suggested 并在 detail 里说理由;真没有可选的就不写 options(我会自己写回答)。没有要问的就不问。',
|
|
182
|
+
'4. 回执按这个格式写(路由会转给用户,纯文本、不放链接):',
|
|
183
|
+
' 今日重点:',
|
|
184
|
+
' - …',
|
|
185
|
+
' 待办卡片(我会在今日页的「待你定」里点选项,不用你催):',
|
|
186
|
+
' 1. <事项>:<选项,标出建议的>',
|
|
187
|
+
' 2. …',
|
|
188
|
+
' 没有卡片就不写这一段。',
|
|
189
|
+
'',
|
|
190
|
+
'',
|
|
191
|
+
].join('\n');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// cfg 来自 rhythm.js 的 loadConfig(router、routerTimeout、workers、handoffKeep、historyKeep、taskTimeout、agentMode、agentModel、
|
|
195
|
+
// agentEffort、push、quiet、links、baseUrl、serviceAlive、ack、botMode、botTimeout、replyMax、botPreamble、refine、refineInterval)。state 是 { data, save }
|
|
196
|
+
function createEngine({ root, env, cfg, log = () => {}, push = async () => false, state, since = Date.now() }) {
|
|
197
|
+
const routerSpec = roles(env).router;
|
|
198
|
+
// 执行者的模型和强度:YZJ_WORKER_* > profile 的 rhythm.agent-* > YZJ_BOT_*
|
|
199
|
+
const workerSpec = {
|
|
200
|
+
agent: s(env.YZJ_WORKER_AGENT) || s(env.YZJ_BOT_AGENT),
|
|
201
|
+
model: s(env.YZJ_WORKER_MODEL) || cfg.agentModel || s(env.YZJ_BOT_MODEL),
|
|
202
|
+
effort: s(env.YZJ_WORKER_EFFORT) || cfg.agentEffort || s(env.YZJ_BOT_EFFORT),
|
|
203
|
+
};
|
|
204
|
+
const agentLabel = `${workerSpec.agent}${workerSpec.model ? `(${workerSpec.model})` : ''}`;
|
|
205
|
+
const triggers = () => state.data.triggers;
|
|
206
|
+
const save = () => state.save();
|
|
207
|
+
triggersStore.set(root, triggers);
|
|
208
|
+
// 内存里的正文:短号 → { text, taskBody, taskFile, taskTitle, opening, linkTask, orig }
|
|
209
|
+
const live = new Map();
|
|
210
|
+
const queue = []; // 等路由的短号
|
|
211
|
+
const dones = new Map(); // 短号 → 执行者那次运行的 Promise(续做要等它做完)
|
|
212
|
+
let deferred = 0; // 等着前面那件做完才起的续做
|
|
213
|
+
let busy = false;
|
|
214
|
+
let closing = false; // 服务在停:不再交给路由
|
|
215
|
+
let pumpScheduled = false; // 这个 tick 里已经排了一轮
|
|
216
|
+
let sink = null;
|
|
217
|
+
const pool = createPool({ limit: cfg.workers });
|
|
218
|
+
const router = cfg.router ? createRouter({ root, env, role: routerSpec, timeoutS: cfg.routerTimeout, preamble: cfg.botPreamble || '', log }) : null;
|
|
219
|
+
|
|
220
|
+
// 权限和超时由触发来源定。重做的沿用原来那条的
|
|
221
|
+
function terms(t) {
|
|
222
|
+
if (t.kind === 'schedule' || t.kind === 'events') return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
|
|
223
|
+
if (t.kind === 'answer') {
|
|
224
|
+
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];
|
|
225
|
+
if (o && o.worker && o.worker.mode) return { mode: o.worker.mode, timeoutS: o.worker.timeoutS || cfg.taskTimeout };
|
|
226
|
+
return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
|
|
227
|
+
}
|
|
228
|
+
if (t.kind === 'message') return { mode: cfg.botMode, timeoutS: cfg.botTimeout };
|
|
229
|
+
if (t.kind === 'report') {
|
|
230
|
+
const o = live.get(t.id) && live.get(t.id).orig;
|
|
231
|
+
if (o && o.worker && o.worker.mode) return { mode: o.worker.mode, timeoutS: o.worker.timeoutS || cfg.taskTimeout };
|
|
232
|
+
}
|
|
233
|
+
return { mode: (live.get(t.id) || {}).mode || 'plan', timeoutS: cfg.taskTimeout };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const isActive = (id) => pool.running().some((e) => e.id === id) || pool.queued().includes(id);
|
|
237
|
+
|
|
238
|
+
// 手头的事:在跑的、排队里的、今天做完的,给路由认「同一件事」用
|
|
239
|
+
function openItems() {
|
|
240
|
+
const now = Date.now();
|
|
241
|
+
const act = [...pool.running().map((e) => e.id), ...pool.queued()];
|
|
242
|
+
const row = (x) => ({ id: x.id, status: STATUS_CN[x.worker.status] || '在跑', at: x.at, title: x.title || '' });
|
|
243
|
+
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));
|
|
244
|
+
return [...act.map((id) => triggers()[id]).filter(Boolean).map(row), ...done.map(row)].slice(0, OPEN_MAX);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// 给路由看的一条
|
|
248
|
+
const view = (t) => ({ id: t.id, kind: t.kind, at: t.at, quiet: t.quiet, task: t.task, of: t.of, ...live.get(t.id) });
|
|
249
|
+
|
|
250
|
+
function record(kind, fields) {
|
|
251
|
+
state.data.seq = (Number(state.data.seq) || 0) + 1;
|
|
252
|
+
const t = { id: `t-${pad6(state.data.seq)}`, kind, at: fmtStamp(), key: '', decision: '', reason: '', title: '', notified: false, ...fields };
|
|
253
|
+
triggers()[t.id] = t;
|
|
254
|
+
return t;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// 新的触发进队列。key 一样的只处理一次。返回记录,或者 null(重复的)
|
|
258
|
+
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 } = {}) {
|
|
259
|
+
if (key && Object.values(triggers()).some((x) => x.key === key)) return null;
|
|
260
|
+
const t = record(kind, { key, task, of, quiet });
|
|
261
|
+
live.set(t.id, { text, taskFile, taskBody, taskTitle, mode, opening, linkTask, orig, ok, seconds, reason, events, sources, ask, date, root: eventRoot || root });
|
|
262
|
+
if (kind === 'events') t.title = `新事件 ${(events || []).length} 条 → 今日重点与待办`;
|
|
263
|
+
if (kind === 'answer' && ask) t.title = `回答:${ask.item || ask.question || ''}`;
|
|
264
|
+
queue.push(t.id);
|
|
265
|
+
save();
|
|
266
|
+
log('触发入队', `${t.id} ${kind}`);
|
|
267
|
+
// 有东西在做(路由在想、前面还排着、执行者在跑):这句不会马上答,先回一句「收到」,说会和上一句一起考虑
|
|
268
|
+
if (kind === 'message' && cfg.ack && (busy || queue.length > 1 || deferred || pool.running().length)) {
|
|
269
|
+
t.acked = true;
|
|
270
|
+
send(null, ACK_MORE_TEXT, { mark: false });
|
|
271
|
+
}
|
|
272
|
+
schedulePump();
|
|
273
|
+
return t;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// 同一个 tick 里到的触发合成一批:等到这个 tick 的最后再开始一轮
|
|
277
|
+
function schedulePump() {
|
|
278
|
+
if (pumpScheduled) return;
|
|
279
|
+
pumpScheduled = true;
|
|
280
|
+
setImmediate(() => {
|
|
281
|
+
pumpScheduled = false;
|
|
282
|
+
pump();
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// 发一段文字给用户。命令行走一遍时交给 sink;push 关着只记日志
|
|
287
|
+
async function send(t, text, { mark = true, linkTask = '' } = {}) {
|
|
288
|
+
const chars = Array.from(String(text || '').trim());
|
|
289
|
+
if (!chars.length) return false;
|
|
290
|
+
let out = chars.length > cfg.replyMax ? `${chars.slice(0, cfg.replyMax).join('')}\n…(回复太长,截到 ${cfg.replyMax} 字)` : chars.join('');
|
|
291
|
+
const link = linkTask && cfg.links[linkTask];
|
|
292
|
+
if (link && cfg.serviceAlive()) out += `\n\n→ ${link.label}:${cfg.baseUrl}${link.path(today())}`;
|
|
293
|
+
if (mark && t) {
|
|
294
|
+
t.notified = true;
|
|
295
|
+
// 汇报发出去了,原来那件事也算「发了」(监控里看的就是那件事)
|
|
296
|
+
const origin = t.kind === 'report' && triggers()[t.of];
|
|
297
|
+
if (origin) origin.notified = true;
|
|
298
|
+
}
|
|
299
|
+
if (sink) {
|
|
300
|
+
sink(out);
|
|
301
|
+
return true;
|
|
302
|
+
}
|
|
303
|
+
if (!cfg.push) {
|
|
304
|
+
log('不推送', 'rhythm.push 关着');
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
try {
|
|
308
|
+
return await push(out);
|
|
309
|
+
} catch (error) {
|
|
310
|
+
log('推送出错', error && error.message ? error.message : String(error));
|
|
311
|
+
return false;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// 执行者结束:补回执、记一笔、生成汇报
|
|
316
|
+
function finishWorker(t, r) {
|
|
317
|
+
const ok = r.ok;
|
|
318
|
+
if (ok && !handoff.resultReady(root, t.id)) handoff.writeResult(root, t.id, r.reply, { ok: true, seconds: r.seconds, agent: agentLabel, by: 'cli' });
|
|
319
|
+
const body = r.stopped ? '用户叫停,这件事没做完。' : r.partial ? `时间到了,做到这里:\n\n${r.partial}` : '';
|
|
320
|
+
if (!ok) handoff.writeResult(root, t.id, body, { ok: false, reason: r.failed, seconds: r.seconds, agent: agentLabel, by: 'cli-fail' });
|
|
321
|
+
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() });
|
|
322
|
+
appendHistory(state.data, { id: t.id, kind: t.kind, task: t.task || '', decision: t.decision, ok, seconds: r.seconds, sessionId: t.worker.sessionId, agent: workerSpec.agent, model: workerSpec.model, effort: workerSpec.effort, mode: t.worker.mode, manual: t.kind === 'manual' });
|
|
323
|
+
save();
|
|
324
|
+
log('执行者结束', `${t.id} ${ok ? '成功' : r.stopped ? '叫停' : '失败'} ${r.seconds}s`);
|
|
325
|
+
const c = live.get(t.id) || {};
|
|
326
|
+
// 提炼是 CLI 自己起的一步:做完了不算汇报,算出新增的事件打包成一条 events 触发给路由
|
|
327
|
+
if (t.kind === 'refine') {
|
|
328
|
+
afterRefine(t, r, c);
|
|
329
|
+
return r;
|
|
330
|
+
}
|
|
331
|
+
// 被插话停掉的:不汇报,接着它重跑的那次会汇报
|
|
332
|
+
if (t.suppressReport) {
|
|
333
|
+
delete t.suppressReport;
|
|
334
|
+
save();
|
|
335
|
+
return r;
|
|
336
|
+
}
|
|
337
|
+
// 服务正在停:不再交给路由,记一笔,下次启动时 recover() 补汇报
|
|
338
|
+
if (closing) {
|
|
339
|
+
t.reportPending = true;
|
|
340
|
+
save();
|
|
341
|
+
return r;
|
|
342
|
+
}
|
|
343
|
+
enqueue('report', {
|
|
344
|
+
key: `report-${t.id}`, of: t.id, ok, seconds: r.seconds, reason: r.stopped ? '用户叫停' : r.failed, quiet: t.quiet,
|
|
345
|
+
opening: ok ? handoff.opening(resultBody(handoff.readText(handoff.resultPath(root, t.id)))) : '', linkTask: t.kind === 'schedule' ? t.task : t.kind === 'events' || t.kind === 'answer' ? 'todos' : '', orig: t, task: c.linkTask,
|
|
346
|
+
});
|
|
347
|
+
return r;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// 排一个执行者。after 给了就等那件事做完再起(续做一件还在跑的事)
|
|
351
|
+
function launch(t, { mode, timeoutS, resume = '', after = '' }) {
|
|
352
|
+
t.worker = { status: 'queued', mode, timeoutS, agent: workerSpec.agent, model: workerSpec.model, effort: workerSpec.effort, sessionId: resume || '' };
|
|
353
|
+
save();
|
|
354
|
+
const start = () => {
|
|
355
|
+
// 续做排在后面起:起的时候再读原来那件的会话 id(它可能到做完才有)
|
|
356
|
+
const target = after ? triggers()[after] : null;
|
|
357
|
+
const sid = resume || (target && target.worker && target.worker.sessionId) || '';
|
|
358
|
+
const p = pool.submit(t.id, async (ctrl) => {
|
|
359
|
+
t.worker.status = 'running';
|
|
360
|
+
t.worker.startedAt = fmtStamp();
|
|
361
|
+
save();
|
|
362
|
+
// 我这边直接派出去的(消息、手动)跑得久就先说一声;定时任务的汇报本来就会来,不额外打扰
|
|
363
|
+
const started = Date.now();
|
|
364
|
+
const pings = t.kind === 'schedule' || t.quiet ? { stop() {} } : progressPings({
|
|
365
|
+
firstS: cfg.progress, everyS: cfg.progress * 2, max: cfg.progressMax,
|
|
366
|
+
say: () => send(t, `还在做(已经 ${humanDuration((Date.now() - started) / 1000)}):${t.title || t.id}。做完汇报。`, { mark: false }),
|
|
367
|
+
});
|
|
368
|
+
let r;
|
|
369
|
+
try {
|
|
370
|
+
r = await runWorker({
|
|
371
|
+
root, env, log, id: t.id, mode, timeoutS, idleS: cfg.workerIdle, spec: workerSpec, resume: sid, extraEnv: { WRJ_TRIGGER: t.id, WRJ_ROLE: 'worker' },
|
|
372
|
+
onSession: (sid) => {
|
|
373
|
+
if (t.worker.sessionId !== sid) {
|
|
374
|
+
t.worker.sessionId = sid;
|
|
375
|
+
save();
|
|
376
|
+
}
|
|
377
|
+
},
|
|
378
|
+
onKill: (fn) => ctrl.setKill(fn),
|
|
379
|
+
});
|
|
380
|
+
} finally {
|
|
381
|
+
pings.stop();
|
|
382
|
+
}
|
|
383
|
+
return finishWorker(t, r);
|
|
384
|
+
}, { kind: t.kind, task: t.task || '' });
|
|
385
|
+
dones.set(t.id, p);
|
|
386
|
+
return p;
|
|
387
|
+
};
|
|
388
|
+
const prev = after && dones.get(after);
|
|
389
|
+
if (prev && isActive(after)) {
|
|
390
|
+
log('续做排队', `${t.id} 等 ${after} 做完`);
|
|
391
|
+
deferred += 1;
|
|
392
|
+
return prev.then(() => {
|
|
393
|
+
deferred -= 1;
|
|
394
|
+
return start();
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
return start();
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// 交给执行者:写任务书、起运行。路由没给任务书的(或者退路),拿原话或指令文件当任务书
|
|
401
|
+
function dispatch(t, c, handoffBody) {
|
|
402
|
+
let body = s(handoffBody);
|
|
403
|
+
const { mode, timeoutS } = terms(t);
|
|
404
|
+
if (t.kind === 'schedule') body = `${s(c.taskBody)}${body ? `\n\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
|
|
405
|
+
else if (t.kind === 'events') body = `${focusBody({ ...c, root })}${body ? `\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
|
|
406
|
+
else if (t.kind === 'answer') body = `${answerBody(c)}${body ? `\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
|
|
407
|
+
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 || '按原任务书重做一遍。'}`;
|
|
408
|
+
else if (!body) body = `# 任务:照用户的话做\n\n用户原话:「${c.text}」\n\n照它做。这是一句追问、单凭这句话做不了的话,在回执里说清楚缺什么。`;
|
|
409
|
+
t.title = handoff.titleOf(body) || t.task || '';
|
|
410
|
+
handoff.writeTask(root, { ...t, text: c.text, taskFile: c.taskFile }, body, { mode, timeoutS });
|
|
411
|
+
save();
|
|
412
|
+
// 消息一来先回一句「收到」,路由慢的话我不用干等
|
|
413
|
+
if (t.kind === 'message' && cfg.ack && !t.acked) send(null, ACK_TEXT, { mark: false });
|
|
414
|
+
// 派出去就接着派下一条,不等它做完(汇报会自己排回来)
|
|
415
|
+
launch(t, { mode, timeoutS });
|
|
416
|
+
return undefined;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// 续做:用户这句话接着手头某件事说的。接着原来那个执行者的会话跑;它还在跑就排在后面
|
|
420
|
+
function continueWith(t, c, targetId) {
|
|
421
|
+
const target = triggers()[targetId];
|
|
422
|
+
if (!target || !openItems().some((o) => o.id === targetId)) {
|
|
423
|
+
return fallback(t, c, `continue 指向的 ${targetId || '(没写)'} 不在手头的事里`);
|
|
424
|
+
}
|
|
425
|
+
const body = t.kind === 'answer'
|
|
426
|
+
? `接着 ${targetId} 那件事做——它问了我一句话,我答了。旧任务书在 ${handoff.relTask(targetId)},旧回执在 ${handoff.relResult(targetId)},先读它们。\n\n${answerBody(c)}\n\n这次的结果单独写进回执,不要改旧回执。`
|
|
427
|
+
: `接着 ${targetId} 那件事做。旧任务书在 ${handoff.relTask(targetId)},旧回执在 ${handoff.relResult(targetId)},先读它们。\n\n用户追加:「${c.text}」\n\n按追加的要求继续。这次的结果单独写进回执,不要改旧回执。`;
|
|
428
|
+
const mode = (target.worker && target.worker.mode) || cfg.botMode;
|
|
429
|
+
const timeoutS = (target.worker && target.worker.timeoutS) || cfg.taskTimeout;
|
|
430
|
+
t.title = `${target.title || targetId}(续)`;
|
|
431
|
+
t.of = targetId;
|
|
432
|
+
handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
|
|
433
|
+
save();
|
|
434
|
+
launch(t, { mode, timeoutS, resume: (target.worker && target.worker.sessionId) || '', after: isActive(targetId) ? targetId : '' });
|
|
435
|
+
return undefined;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// 插话改要求:停掉在跑的那件事,带着新要求接着它的会话重跑。被停的那次不汇报(这次的结果会覆盖它)
|
|
439
|
+
function interruptWith(t, c, targetId) {
|
|
440
|
+
const target = triggers()[targetId];
|
|
441
|
+
if (!target || !isActive(targetId)) {
|
|
442
|
+
return fallback(t, c, `interrupt 指向的 ${targetId || '(没写)'} 不在跑`);
|
|
443
|
+
}
|
|
444
|
+
const body = `接着 ${targetId} 那件事做,但要求变了。旧任务书在 ${handoff.relTask(targetId)},先读它;上一次做到一半被用户叫停,回执在 ${handoff.relResult(targetId)}。\n\n用户插话:「${c.text}」\n\n按新的要求把这件事做完:上一次已经做过的部分,对了就沿用,不对就改。这次的结果单独写进回执,不要改旧回执。`;
|
|
445
|
+
const mode = target.worker.mode || cfg.botMode;
|
|
446
|
+
const timeoutS = target.worker.timeoutS || cfg.taskTimeout;
|
|
447
|
+
const resume = target.worker.sessionId || '';
|
|
448
|
+
t.title = `${target.title || targetId}(插话)`;
|
|
449
|
+
t.of = targetId;
|
|
450
|
+
target.suppressReport = true;
|
|
451
|
+
pool.stop(targetId, '用户插话,改了要求');
|
|
452
|
+
handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
|
|
453
|
+
save();
|
|
454
|
+
log('插话', `${t.id} 停掉 ${targetId} 带着新要求重跑`);
|
|
455
|
+
launch(t, { mode, timeoutS, resume });
|
|
456
|
+
return undefined;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// 叫停:排队里的拿掉,在跑的杀掉。它的回执和汇报照常生成
|
|
460
|
+
function stopTask(t, targetId) {
|
|
461
|
+
const target = triggers()[targetId];
|
|
462
|
+
if (!target || !isActive(targetId)) {
|
|
463
|
+
t.reason = `想叫停 ${targetId || '(没写)'},它已经不在跑了`;
|
|
464
|
+
save();
|
|
465
|
+
return undefined;
|
|
466
|
+
}
|
|
467
|
+
const where = pool.stop(targetId, '用户叫停');
|
|
468
|
+
t.reason = `叫停 ${targetId}`;
|
|
469
|
+
save();
|
|
470
|
+
log('叫停', `${targetId}(${where})`);
|
|
471
|
+
return undefined;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// 路由坏了、看不懂、漏了:按来源退回直通的做法,不丢东西
|
|
475
|
+
function fallback(t, c, why) {
|
|
476
|
+
t.decision = 'fallback';
|
|
477
|
+
t.reason = s(why).slice(0, 200);
|
|
478
|
+
if (t.kind === 'report') {
|
|
479
|
+
if (c.ok) {
|
|
480
|
+
if (c.quiet) {
|
|
481
|
+
save();
|
|
482
|
+
return Promise.resolve();
|
|
483
|
+
}
|
|
484
|
+
return send(t, resultBody(handoff.readText(handoff.resultPath(root, t.of))), { linkTask: c.linkTask });
|
|
485
|
+
}
|
|
486
|
+
return send(t, `「${c.linkTask || t.of}」没跑完:${c.reason}`);
|
|
487
|
+
}
|
|
488
|
+
return dispatch(t, c, '');
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
async function act(t, c, d) {
|
|
492
|
+
t.decision = d.action;
|
|
493
|
+
if (d.action === 'dispatch') return dispatch(t, c, d.handoff);
|
|
494
|
+
if (d.action === 'continue') return continueWith(t, c, d.target);
|
|
495
|
+
if (d.action === 'interrupt') return interruptWith(t, c, d.target);
|
|
496
|
+
if (d.action === 'stop') return stopTask(t, d.target);
|
|
497
|
+
if (d.action === 'reply') {
|
|
498
|
+
t.reason = '';
|
|
499
|
+
if (!s(d.text)) return fallback(t, c, '路由的 reply 没带文字');
|
|
500
|
+
return send(t, d.text);
|
|
501
|
+
}
|
|
502
|
+
if (d.action === 'ignore') {
|
|
503
|
+
t.reason = s(d.text).slice(0, 200);
|
|
504
|
+
save();
|
|
505
|
+
return undefined;
|
|
506
|
+
}
|
|
507
|
+
if (d.action === 'notify') {
|
|
508
|
+
if (t.kind !== 'report') return fallback(t, c, 'notify 只用于汇报');
|
|
509
|
+
if (c.quiet) {
|
|
510
|
+
t.reason = '不推送的任务';
|
|
511
|
+
save();
|
|
512
|
+
return undefined;
|
|
513
|
+
}
|
|
514
|
+
if (!s(d.text)) return fallback(t, c, '路由的 notify 没带文字');
|
|
515
|
+
return send(t, d.text, { linkTask: c.linkTask });
|
|
516
|
+
}
|
|
517
|
+
return fallback(t, c, `看不懂的决定 ${d.action || '(没写)'}`);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// 取走排队的触发交给路由(合批:一轮把排队的全部处理掉),再把决定做掉
|
|
521
|
+
async function pump() {
|
|
522
|
+
if (busy || closing || !queue.length) return;
|
|
523
|
+
busy = true;
|
|
524
|
+
const ids = queue.splice(0);
|
|
525
|
+
try {
|
|
526
|
+
let result = null;
|
|
527
|
+
if (router) {
|
|
528
|
+
const batch = ids.map((id) => triggers()[id]).filter(Boolean);
|
|
529
|
+
result = await router.decide(batch.map(view), openItems());
|
|
530
|
+
state.data.rounds = [...(state.data.rounds || []), { at: fmtStamp(), uid: uid(), ok: result.ok, n: batch.length, seconds: (router.last() || {}).seconds || 0 }];
|
|
531
|
+
log(result.ok ? '路由出决定' : '路由没出决定', `${batch.length} 条${result.ok ? '' : `:${result.failed}`}`);
|
|
532
|
+
}
|
|
533
|
+
for (const id of ids) {
|
|
534
|
+
const t = triggers()[id];
|
|
535
|
+
if (!t) continue;
|
|
536
|
+
const d = result && result.decisions[id];
|
|
537
|
+
if (d && d.action) await act(t, live.get(id) || {}, d);
|
|
538
|
+
else await fallback(t, live.get(id) || {}, result ? (result.failed || `路由漏了 ${id}`) : '直通');
|
|
539
|
+
}
|
|
540
|
+
} catch (error) {
|
|
541
|
+
log('引擎出错', error && error.message ? error.message : String(error));
|
|
542
|
+
for (const id of ids) {
|
|
543
|
+
const t = triggers()[id];
|
|
544
|
+
if (t && !t.decision) await fallback(t, live.get(id) || {}, `引擎出错:${error && error.message ? error.message : error}`);
|
|
545
|
+
}
|
|
546
|
+
} finally {
|
|
547
|
+
// 这一批的决定、发没发,都记下来
|
|
548
|
+
save();
|
|
549
|
+
busy = false;
|
|
550
|
+
}
|
|
551
|
+
pump();
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// 定时采集之后(rhythm.js 调):有新数据、或者有源没取到,就起一轮提炼;做完把新增的事件打包给路由
|
|
555
|
+
async function afterSync({ results = [], changed = false } = {}) {
|
|
556
|
+
if (!router || !cfg.refine) return null;
|
|
557
|
+
const bad = results.filter((x) => !x.ok);
|
|
558
|
+
// 没有新数据:不炼。有源出事就把采集状态直接给路由(不用等提炼),路由决定要不要告诉用户
|
|
559
|
+
if (!changed) {
|
|
560
|
+
log('提炼跳过', '没有新数据');
|
|
561
|
+
if (bad.length) enqueue('events', { key: `events-sync-${Date.now()}`, ok: true, events: [], sources: results, date: today(), root });
|
|
562
|
+
return null;
|
|
563
|
+
}
|
|
564
|
+
// 新数据等够间隔再炼(rhythm.refine-interval 分钟);这期间有源出事也直接告诉路由
|
|
565
|
+
const last = state.data.refinedAt;
|
|
566
|
+
if (last && Date.now() - stampMs(last) < cfg.refineInterval * 60000) {
|
|
567
|
+
log('提炼跳过', `上一次 ${last},不到 ${cfg.refineInterval} 分钟`);
|
|
568
|
+
if (bad.length) enqueue('events', { key: `events-sync-${Date.now()}`, ok: true, events: [], sources: results, date: today(), root });
|
|
569
|
+
return null;
|
|
570
|
+
}
|
|
571
|
+
const date = today();
|
|
572
|
+
const t = record('refine', { key: `refine-${date}-${Date.now()}`, decision: 'refine', title: '把今天新采到的数据提炼成事件' });
|
|
573
|
+
live.set(t.id, { results, date, before: new Set(dayEvents(root, date).map(eventKey)), root });
|
|
574
|
+
handoff.writeTask(root, { ...t, text: '' }, refineBody(dailyFile(root, date)), { mode: cfg.agentMode, timeoutS: cfg.taskTimeout });
|
|
575
|
+
save();
|
|
576
|
+
log('提炼开始', t.id);
|
|
577
|
+
return launch(t, { mode: cfg.agentMode, timeoutS: cfg.taskTimeout });
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// 提炼做完:比对话件里的事件流,新增的打包成 events 触发给路由。没新增、也没源出事就不打扰路由
|
|
581
|
+
function afterRefine(t, r, c) {
|
|
582
|
+
state.data.refinedAt = fmtStamp();
|
|
583
|
+
save();
|
|
584
|
+
const date = c.date || today();
|
|
585
|
+
let events = [];
|
|
586
|
+
if (r.ok) {
|
|
587
|
+
const before = c.before || new Set();
|
|
588
|
+
events = dayEvents(root, date).filter((e) => !before.has(eventKey(e)));
|
|
589
|
+
log('提炼结束', `${t.id} 新增 ${events.length} 条事件`);
|
|
590
|
+
}
|
|
591
|
+
const bad = (c.results || []).filter((x) => !x.ok);
|
|
592
|
+
if (!r.ok) enqueue('events', { key: `events-${t.id}`, of: t.id, ok: false, reason: r.failed, events: [], sources: c.results || [], date, root });
|
|
593
|
+
else if (events.length || bad.length) enqueue('events', { key: `events-${t.id}`, of: t.id, ok: true, events, sources: c.results || [], date, root });
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// 服务启动时:上次没跑完的执行者各补一份失败的回执,变成汇报交回路由;停服务时没来得及汇报的也补上
|
|
597
|
+
function recover() {
|
|
598
|
+
for (const t of Object.values(triggers())) {
|
|
599
|
+
if (!t.worker) continue;
|
|
600
|
+
const unfinished = ['queued', 'running'].includes(t.worker.status);
|
|
601
|
+
if (!unfinished && !t.reportPending) continue;
|
|
602
|
+
if (unfinished) {
|
|
603
|
+
handoff.writeResult(root, t.id, '', { ok: false, reason: '服务重启时中断', by: 'cli-fail' });
|
|
604
|
+
Object.assign(t.worker, { status: 'failed', reason: '服务重启时中断', endedAt: fmtStamp() });
|
|
605
|
+
}
|
|
606
|
+
delete t.reportPending;
|
|
607
|
+
enqueue('report', { key: `report-${t.id}`, of: t.id, ok: t.worker.status === 'ok', seconds: t.worker.seconds || 0, reason: t.worker.reason || '', quiet: t.quiet, linkTask: t.kind === 'schedule' ? t.task : '', orig: t });
|
|
608
|
+
}
|
|
609
|
+
save();
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// 服务要停了:在跑的执行者是子进程,得收掉(最多等 3 秒)。之后不再交给路由
|
|
613
|
+
async function shutdown() {
|
|
614
|
+
closing = true;
|
|
615
|
+
for (const id of pool.queued()) pool.stop(id, '服务停止时中断');
|
|
616
|
+
for (const e of pool.running()) pool.stop(e.id, '服务停止时中断');
|
|
617
|
+
const pending = [...dones.values()];
|
|
618
|
+
if (pending.length) await Promise.race([Promise.allSettled(pending), new Promise((resolve) => setTimeout(resolve, 3000))]);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// 取走 trigger fire 写下的触发;超过一天的清掉
|
|
622
|
+
function collectQueue() {
|
|
623
|
+
const dir = queueDir(root);
|
|
624
|
+
let names;
|
|
625
|
+
try {
|
|
626
|
+
names = fs.readdirSync(dir);
|
|
627
|
+
} catch {
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
const cutoff = Date.now() - DAY_MS;
|
|
631
|
+
for (const name of names) {
|
|
632
|
+
const file = path.join(dir, name);
|
|
633
|
+
try {
|
|
634
|
+
if (!name.endsWith('.json')) continue;
|
|
635
|
+
if (fs.statSync(file).mtimeMs < cutoff) {
|
|
636
|
+
fs.unlinkSync(file);
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
const item = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
640
|
+
fs.unlinkSync(file);
|
|
641
|
+
// 执行者用 work-rhythm ask 丢出来的卡:直接把问题推给我、带着今日页的地址(实时显示在那儿),不花路由一轮
|
|
642
|
+
if (item.kind === 'ask') {
|
|
643
|
+
const ask = asks.readAsk(root, item.ask);
|
|
644
|
+
if (ask && !ask.answer) {
|
|
645
|
+
log('待你定', `${ask.id} ${ask.item}`);
|
|
646
|
+
send(null, `等你定:${asks.askSummary(ask)}${ask.context ? `\n${ask.context}` : ''}`, { linkTask: 'todos' });
|
|
647
|
+
}
|
|
648
|
+
continue;
|
|
649
|
+
}
|
|
650
|
+
enqueue('manual', { key: `fired-${name.slice(0, -5)}`, text: s(item.text), mode: s(item.mode) || 'plan' });
|
|
651
|
+
} catch (error) {
|
|
652
|
+
log('排队文件读不了', `${name} ${error.message}`);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// 服务每次看表时调:清过期的交接文档、取走排队的触发
|
|
658
|
+
function tick() {
|
|
659
|
+
handoff.cleanup(root, cfg.handoffKeep);
|
|
660
|
+
collectQueue();
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
const roundsToday = () => {
|
|
664
|
+
const date = today();
|
|
665
|
+
const rounds = (state.data.rounds || []).filter((r) => String(r.at).startsWith(date));
|
|
666
|
+
return { total: rounds.length, failed: rounds.filter((r) => !r.ok).length };
|
|
667
|
+
};
|
|
668
|
+
|
|
669
|
+
return {
|
|
670
|
+
enqueue,
|
|
671
|
+
message: (m) => enqueue('message', { key: `msg-${m.msgId}`, text: s(m.content), mode: cfg.botMode }),
|
|
672
|
+
schedule: (job, taskBody, taskTitle) => enqueue('schedule', { key: job.key, task: job.id, taskFile: `tasks/${job.id}.md`, taskBody, taskTitle, quiet: cfg.quiet.includes(job.id) }),
|
|
673
|
+
recover,
|
|
674
|
+
shutdown,
|
|
675
|
+
tick,
|
|
676
|
+
afterSync,
|
|
677
|
+
// 页面上答了一张卡:一条 answer 触发给路由(rhythm.js 调;ask 里带着答案)。
|
|
678
|
+
// 去重键用卡片 id;老办法登记的「未答」行没有卡片文件(id 是空的),用事项——不然第二张就会被当成重复丢掉
|
|
679
|
+
answer: (ask) => (router ? enqueue('answer', { key: `answer-${ask.id || ask.item}`, of: ask.from && ask.from.trigger ? ask.from.trigger : '', ask, root }) : null),
|
|
680
|
+
// 命令行走一遍:要发的文字交到这里,不真发
|
|
681
|
+
setSink(fn) {
|
|
682
|
+
sink = fn;
|
|
683
|
+
},
|
|
684
|
+
// 等到队列空、路由空、执行者都结束。返回是不是等到了
|
|
685
|
+
async waitIdle(timeoutMs = 600000) {
|
|
686
|
+
const until = Date.now() + timeoutMs;
|
|
687
|
+
while (Date.now() < until) {
|
|
688
|
+
if (!busy && !queue.length && !deferred && pool.idle()) return true;
|
|
689
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
690
|
+
}
|
|
691
|
+
return false;
|
|
692
|
+
},
|
|
693
|
+
resetSession: () => router && router.resetSession(),
|
|
694
|
+
forgetBoundLost: () => router && router.forgetBoundLost(),
|
|
695
|
+
doctorProblems: () => (router ? router.doctorProblems() : []),
|
|
696
|
+
notes: () => (router ? router.notes() : []),
|
|
697
|
+
status: () => ({
|
|
698
|
+
enabled: Boolean(router),
|
|
699
|
+
since,
|
|
700
|
+
router: { enabled: Boolean(router), agent: routerSpec.agent, model: routerSpec.model, effort: routerSpec.effort, session: router ? router.describeSession() : null, queue: queue.length, busy, last: router ? router.last() : null, roundsToday: roundsToday() },
|
|
701
|
+
workers: { limit: cfg.workers, running: pool.running().map((e) => ({ id: e.id, since: e.startedAt, kind: e.meta.kind, task: e.meta.task || '' })), queued: pool.queued() },
|
|
702
|
+
worker: workerSpec,
|
|
703
|
+
}),
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
module.exports = { createEngine, appendHistory, pruneState, historyStats, fire, queueDir, resultBody, pendingCards, dayEvents, eventKey, refineBody, focusBody, ACK_TEXT, uid };
|