work-rhythm 0.1.8 → 0.2.3
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 +7 -1
- 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-router-and-worker-pass-content-in-handoff-docs.md +41 -0
- package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +16 -0
- package/.agents/skills/work-rhythm/SKILL.md +14 -12
- package/README.md +7 -4
- package/collectors/local.env.example +10 -1
- package/docs/agents.md +28 -11
- package/docs/channels.md +9 -6
- package/docs/router-worker.md +241 -0
- package/docs/scheduled-tasks.md +4 -4
- package/package.json +1 -1
- package/scripts/cli.js +4 -3
- package/scripts/cmd/agent.js +78 -40
- package/scripts/cmd/check.js +4 -0
- package/scripts/cmd/listen.js +18 -4
- package/scripts/cmd/rhythm.js +6 -2
- package/scripts/cmd/trigger.js +143 -0
- package/scripts/lib/agent.js +377 -30
- package/scripts/lib/bot.js +140 -35
- package/scripts/lib/engine.js +523 -0
- package/scripts/lib/handoff.js +165 -0
- package/scripts/lib/markdown.js +328 -38
- package/scripts/lib/rhythm.js +369 -31
- package/scripts/lib/router.js +161 -0
- package/scripts/lib/run.js +43 -0
- package/scripts/lib/view.js +583 -0
- package/scripts/lib/worker.js +97 -0
- package/scripts/test/agent.test.js +17 -9
- package/scripts/test/check.test.js +7 -2
- package/scripts/test/harness.js +13 -1
- package/scripts/test/listen.test.js +2 -2
- package/scripts/test/rhythm.test.js +28 -6
- package/scripts/test/router-helper.js +80 -0
- package/scripts/test/router.test.js +509 -0
- package/scripts/test/stubs.js +82 -12
- package/scripts/test/timeout.test.js +99 -0
- package/templates/00-config/profile.example.yaml +7 -0
- package/templates/AGENTS.md +3 -1
- package/templates/README.md +4 -1
package/scripts/lib/agent.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// 让本地的 agent 跑一句话、拿回它的回复。值守(bot.js)和本地服务(rhythm.js)共用,定时任务和机器人都靠它。
|
|
2
|
-
// agent 的值:zcode、dsh、qoder、claude 是预置(PRESETS,各家的无界面调用方式、续会话、权限模式都写在那里);
|
|
2
|
+
// agent 的值:zcode、dsh、qoder、claude、kimi 是预置(PRESETS,各家的无界面调用方式、续会话、权限模式都写在那里);
|
|
3
3
|
// 其余当成一条命令(按空白拆开,引号里的算一个参数;消息作为最后一个参数传给它,回复打到标准输出,退出码 0 算成功。
|
|
4
4
|
// 不支持管道、重定向这类 shell 写法——要的话包一层脚本)。
|
|
5
5
|
// 这里还管「本机装了哪些 agent」「现在是哪个 agent 在调这个 skill」(它给工具留的环境变量)、「把选定的 agent 绑进 local.env」,
|
|
6
6
|
// 给 work-rhythm agent 用。只用 node 自带的能力。找预置的命令行时返回 { problem } 而不是抛错,doctor 和真正运行时共用这一段。
|
|
7
|
+
// 路由和执行者两个角色各选各的 agent(roles),没单独配的都用 YZJ_BOT_AGENT 那一个。
|
|
7
8
|
'use strict';
|
|
8
|
-
const { spawnSync } = require('node:child_process');
|
|
9
|
+
const { spawnSync, spawn } = require('node:child_process');
|
|
10
|
+
const crypto = require('node:crypto');
|
|
9
11
|
const fs = require('node:fs');
|
|
10
12
|
const os = require('node:os');
|
|
11
13
|
const path = require('node:path');
|
|
@@ -119,6 +121,43 @@ function findClaude(env) {
|
|
|
119
121
|
return { problem: '找不到 Claude Code 的命令行:装了的话 claude 在 PATH 上;也可以用 CLAUDE_CLI 指定路径' };
|
|
120
122
|
}
|
|
121
123
|
|
|
124
|
+
const kimiHome = (env) => env.KIMI_CODE_HOME || path.join(os.homedir(), '.kimi-code');
|
|
125
|
+
|
|
126
|
+
// Kimi Code 的命令行(命令叫 kimi)。官方安装脚本 curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash,
|
|
127
|
+
// 或者 npm install -g @moonshot-ai/kimi-code。装了 Kimi Code 的桌面版不等于装了它的命令行
|
|
128
|
+
function findKimi(env) {
|
|
129
|
+
const explicit = env.KIMI_CLI;
|
|
130
|
+
if (explicit) {
|
|
131
|
+
if (fs.existsSync(explicit)) return { command: path.resolve(explicit), home: kimiHome(env) };
|
|
132
|
+
return { problem: `KIMI_CLI 指的文件不存在:${explicit}` };
|
|
133
|
+
}
|
|
134
|
+
const found = onPath('kimi', env);
|
|
135
|
+
if (found) return { command: found, home: kimiHome(env) };
|
|
136
|
+
const local = path.join(kimiHome(env), 'bin', 'kimi');
|
|
137
|
+
if (fs.existsSync(local)) return { command: local, home: kimiHome(env) };
|
|
138
|
+
const desktop = fs.existsSync('/Applications/Kimi Code.app') ? '本机装了 Kimi Code 的桌面版,但它的命令行是另装的:' : '';
|
|
139
|
+
return { problem: `找不到 Kimi Code 的命令行。${desktop}安装:curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash(或 npm install -g @moonshot-ai/kimi-code),装完 kimi login;也可以用 KIMI_CLI 指定路径` };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Kimi 的 --output-format stream-json 是一行一个 JSON:回答在 role 为 assistant、没有 tool_calls 的 content 里,
|
|
143
|
+
// 会话在末尾 type 为 session.resume_hint 那行的 session_id(照官方 kimi 命令参考页的写法,没在真机上跑过)
|
|
144
|
+
function parseKimi(stdout) {
|
|
145
|
+
let reply = '';
|
|
146
|
+
let sessionId = '';
|
|
147
|
+
for (const line of String(stdout).split('\n')) {
|
|
148
|
+
if (!line.trim()) continue;
|
|
149
|
+
let ev;
|
|
150
|
+
try {
|
|
151
|
+
ev = JSON.parse(line);
|
|
152
|
+
} catch {
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (ev.type === 'session.resume_hint' && typeof ev.session_id === 'string') sessionId = ev.session_id;
|
|
156
|
+
if (ev.role === 'assistant' && typeof ev.content === 'string' && ev.content.trim() && !ev.tool_calls) reply = ev.content;
|
|
157
|
+
}
|
|
158
|
+
return reply.trim() ? { reply, sessionId } : { failed: `输出里没有回答:${tail(stdout)}` };
|
|
159
|
+
}
|
|
160
|
+
|
|
122
161
|
// Qoder 和 Claude Code 的 --output-format json 都是一个 JSON:回答在 result,会话在 session_id,出错时 is_error / subtype 会说。
|
|
123
162
|
// 字段名按各家文档写的;多认几个常见名字,免得版本之间改名就解析不出
|
|
124
163
|
function parseResultJson(stdout) {
|
|
@@ -136,14 +175,18 @@ function parseResultJson(stdout) {
|
|
|
136
175
|
return { reply, sessionId: typeof out.session_id === 'string' ? out.session_id : typeof out.sessionId === 'string' ? out.sessionId : '' };
|
|
137
176
|
}
|
|
138
177
|
|
|
139
|
-
// 预置。find 找命令行;plan 拼出一次无界面运行的参数;modes 是我们的权限名(plan 只读 / edit
|
|
140
|
-
//
|
|
178
|
+
// 预置。find 找命令行;plan 拼出一次无界面运行的参数;modes 是我们的权限名(plan 只读 / edit 可写工作目录)换成各家的叫法;
|
|
179
|
+
// readOnly 为 false 的是无界面模式下没有只读档的(plan 也拦不住它改文件),doctor 把它列成注意
|
|
180
|
+
// install:没装时怎么装(引导里把五个摆出来让用户选,没装的带安装步骤)
|
|
141
181
|
const PRESETS = {
|
|
142
182
|
zcode: { label: 'ZCode 自带的命令行', modes: { plan: 'plan', edit: 'edit' }, find: findZcode, install: '装 ZCode 桌面版,命令行随它自带,不用另装(注意它配不了模型和思考强度)' },
|
|
143
|
-
dsh: { label: 'DSH(DeepSeek Harness)的 headless 模式', modes: { plan: 'read-only', edit: 'workspace-write' }, find: findDsh, install: '装 DSH(DeepSeek Harness)桌面版,在它里面配好模型;命令行随桌面版带,不用另装' },
|
|
183
|
+
dsh: { label: 'DSH(DeepSeek Harness)的 headless 模式', streams: true, modes: { plan: 'read-only', edit: 'workspace-write' }, find: findDsh, install: '装 DSH(DeepSeek Harness)桌面版,在它里面配好模型;命令行随桌面版带,不用另装' },
|
|
144
184
|
// Qoder:edit 用 accept_edits(改文件自动放行,shell 命令在无界面下会被拒);任务里要跑命令的话把 YZJ_BOT_AGENT_MODE 写成 auto
|
|
145
185
|
qoder: { label: 'Qoder CLI', modes: { plan: 'plan', edit: 'accept_edits' }, find: findQoder, install: '装了 Qoder 的 IDE 不算,命令行要另装:curl -fsSL https://qoder.com/install | bash(或 npm install -g @qoder-ai/qodercli),装完 qoder login' },
|
|
146
186
|
claude: { label: 'Claude Code 的命令行', modes: { plan: 'plan', edit: 'acceptEdits' }, find: findClaude, install: 'npm install -g @anthropic-ai/claude-code,装完 claude login' },
|
|
187
|
+
// kimi:无界面模式(-p)默认自动放行改文件和跑命令,--prompt 不能和 --plan 同用,所以没有只读档。它的社区准则把「脚本化的无人值守」
|
|
188
|
+
// 列在订阅范围之外,当执行者跑定时任务量很小,但要在引导里说清楚
|
|
189
|
+
kimi: { label: 'Kimi Code 的命令行', readOnly: false, streams: true, modes: {}, find: findKimi, install: '装了 Kimi Code 的桌面版不算,命令行要另装:curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash(或 npm install -g @moonshot-ai/kimi-code),装完 kimi login' },
|
|
147
190
|
};
|
|
148
191
|
const PRESET_NAMES = Object.keys(PRESETS);
|
|
149
192
|
const presetKind = (name) => (PRESET_NAMES.includes(name) ? name : 'custom');
|
|
@@ -167,20 +210,51 @@ function installedAgents(env) {
|
|
|
167
210
|
});
|
|
168
211
|
}
|
|
169
212
|
|
|
170
|
-
// 本机装着哪家的桌面应用却没装它的命令行(Qoder 的 IDE 和 Qoder CLI
|
|
213
|
+
// 本机装着哪家的桌面应用却没装它的命令行(Qoder 的 IDE 和 Qoder CLI 是两回事,Kimi Code 也一样):提醒引导别把它漏了
|
|
171
214
|
function ideOnly(env) {
|
|
172
215
|
const out = [];
|
|
173
216
|
if (fs.existsSync('/Applications/Qoder.app') && findQoder(env).problem) out.push('qoder');
|
|
217
|
+
if (fs.existsSync('/Applications/Kimi Code.app') && findKimi(env).problem) out.push('kimi');
|
|
174
218
|
return out;
|
|
175
219
|
}
|
|
176
220
|
|
|
177
|
-
//
|
|
178
|
-
//
|
|
179
|
-
function
|
|
221
|
+
// 两个角色各用哪个 agent、模型、强度、会话。没单独配的(YZJ_ROUTER_* / YZJ_WORKER_*)都用 YZJ_BOT_* 那一套。
|
|
222
|
+
// 路由的会话:路由的 agent 就是 YZJ_BOT_AGENT 时才认 YZJ_BOT_SESSION(别的 agent 的会话 id 它接不上)
|
|
223
|
+
function roles(env) {
|
|
224
|
+
const s = (v) => String(v || '').trim();
|
|
225
|
+
const bot = { agent: s(env.YZJ_BOT_AGENT), model: s(env.YZJ_BOT_MODEL), effort: s(env.YZJ_BOT_EFFORT), session: s(env.YZJ_BOT_SESSION) };
|
|
226
|
+
const routerAgent = s(env.YZJ_ROUTER_AGENT) || bot.agent;
|
|
227
|
+
return {
|
|
228
|
+
bot,
|
|
229
|
+
router: {
|
|
230
|
+
agent: routerAgent,
|
|
231
|
+
model: s(env.YZJ_ROUTER_MODEL) || bot.model,
|
|
232
|
+
effort: s(env.YZJ_ROUTER_EFFORT) || bot.effort,
|
|
233
|
+
session: s(env.YZJ_ROUTER_SESSION) || (routerAgent === bot.agent ? bot.session : ''),
|
|
234
|
+
},
|
|
235
|
+
worker: { agent: s(env.YZJ_WORKER_AGENT) || bot.agent, model: s(env.YZJ_WORKER_MODEL) || bot.model, effort: s(env.YZJ_WORKER_EFFORT) || bot.effort },
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// local.env 里三个角色各写哪几个键:agent、模型、强度、会话(执行者每次都是新会话,没有会话键)
|
|
240
|
+
const ROLE_KEYS = {
|
|
241
|
+
'': ['YZJ_BOT_AGENT', 'YZJ_BOT_MODEL', 'YZJ_BOT_EFFORT', 'YZJ_BOT_SESSION'],
|
|
242
|
+
router: ['YZJ_ROUTER_AGENT', 'YZJ_ROUTER_MODEL', 'YZJ_ROUTER_EFFORT', 'YZJ_ROUTER_SESSION'],
|
|
243
|
+
worker: ['YZJ_WORKER_AGENT', 'YZJ_WORKER_MODEL', 'YZJ_WORKER_EFFORT', ''],
|
|
244
|
+
};
|
|
245
|
+
const ROLE_LABEL = { '': '', router: '路由', worker: '执行者' };
|
|
246
|
+
|
|
247
|
+
// 把选定的 agent 写进 collectors/local.env(没有这个文件就从样例复制一份),顺带可以写模型、思考强度和会话。
|
|
248
|
+
// role 是 router / worker 时只写那个角色的键,不写就是两个角色共用的那套(YZJ_BOT_*)。
|
|
249
|
+
// 先确认它在本机找得到、模型和强度它认。返回 { name, kind, file, model, effort } 或 { problems }
|
|
250
|
+
function bindAgent(root, env, name, { model, effort, session, role } = {}) {
|
|
180
251
|
session = session === undefined ? undefined : String(session).trim();
|
|
181
252
|
// undefined = 不动原来的;空串 = 清掉
|
|
182
253
|
model = model === undefined ? undefined : String(model).trim();
|
|
183
254
|
effort = effort === undefined ? undefined : String(effort).trim();
|
|
255
|
+
const keys = ROLE_KEYS[role] || ROLE_KEYS[''];
|
|
256
|
+
if (role === 'worker') session = undefined;
|
|
257
|
+
if (role === 'router' && session === undefined && roles(env).router.agent !== name) session = ''; // 换了 agent 就把原来的会话清掉,没换不动
|
|
184
258
|
const problems = createAgent({ root, agent: name, env, model: model || '', effort: effort || '' }).doctor();
|
|
185
259
|
if (problems.length) return { problems };
|
|
186
260
|
const dir = path.join(root, 'collectors');
|
|
@@ -192,13 +266,13 @@ function bindAgent(root, env, name, { model, effort, session } = {}) {
|
|
|
192
266
|
}
|
|
193
267
|
const value = quote(name);
|
|
194
268
|
let lines = fs.readFileSync(file, 'utf8').split('\n');
|
|
195
|
-
lines = setLocalEnvKey(lines,
|
|
269
|
+
lines = setLocalEnvKey(lines, keys[0], value);
|
|
196
270
|
// 模型和思考强度:给了字符串就写(空串是清掉),没给(undefined)不动原来的
|
|
197
|
-
if (model !== undefined) lines = setLocalEnvKey(lines,
|
|
198
|
-
if (effort !== undefined) lines = setLocalEnvKey(lines,
|
|
199
|
-
if (session !== undefined) lines = setLocalEnvKey(lines,
|
|
271
|
+
if (model !== undefined) lines = setLocalEnvKey(lines, keys[1], quote(model));
|
|
272
|
+
if (effort !== undefined) lines = setLocalEnvKey(lines, keys[2], quote(effort));
|
|
273
|
+
if (session !== undefined && keys[3]) lines = setLocalEnvKey(lines, keys[3], quote(session));
|
|
200
274
|
fs.writeFileSync(file, `${lines.join('\n').replace(/\n*$/, '')}\n`);
|
|
201
|
-
return { name, kind: presetKind(name), file, model, effort };
|
|
275
|
+
return { name, kind: presetKind(name), file, model, effort, keys };
|
|
202
276
|
}
|
|
203
277
|
|
|
204
278
|
const quote = (value) => (value === '' ? '""' : /[\s"'$`]/.test(value) ? `'${value.replace(/'/g, `'\\''`)}'` : `"${value}"`);
|
|
@@ -323,7 +397,50 @@ function dshSessions(home, root) {
|
|
|
323
397
|
return names.map((id) => ({ id, mtime: fs.statSync(path.join(dir, id)).mtimeMs })).sort((a, b) => b.mtime - a.mtime);
|
|
324
398
|
}
|
|
325
399
|
|
|
400
|
+
// Kimi Code 的会话按工作目录存:<KIMI_CODE_HOME>/session_index.jsonl 一行一个 { sessionId, sessionDir, workDir },
|
|
401
|
+
// 标题和时间在每个会话目录的 state.json 里(title、updatedAt,毫秒)。列出这个工作目录里的,新的在前:[{ id, mtime, title }]
|
|
402
|
+
function kimiSessions(home, root) {
|
|
403
|
+
let lines;
|
|
404
|
+
try {
|
|
405
|
+
lines = fs.readFileSync(path.join(home, 'session_index.jsonl'), 'utf8').split('\n').filter(Boolean);
|
|
406
|
+
} catch {
|
|
407
|
+
return [];
|
|
408
|
+
}
|
|
409
|
+
const want = path.resolve(root);
|
|
410
|
+
const out = [];
|
|
411
|
+
for (const line of lines) {
|
|
412
|
+
let rec;
|
|
413
|
+
try {
|
|
414
|
+
rec = JSON.parse(line);
|
|
415
|
+
} catch {
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
if (!rec || typeof rec.sessionId !== 'string' || path.resolve(String(rec.workDir || '')) !== want) continue;
|
|
419
|
+
const dir = rec.sessionDir || path.join(home, 'sessions', rec.sessionId);
|
|
420
|
+
let mtime = 0;
|
|
421
|
+
let title = '';
|
|
422
|
+
try {
|
|
423
|
+
const state = JSON.parse(fs.readFileSync(path.join(dir, 'state.json'), 'utf8'));
|
|
424
|
+
title = typeof state.title === 'string' ? state.title : '';
|
|
425
|
+
mtime = Number(state.updatedAt) || 0;
|
|
426
|
+
} catch {
|
|
427
|
+
try {
|
|
428
|
+
mtime = fs.statSync(dir).mtimeMs;
|
|
429
|
+
} catch {
|
|
430
|
+
// 会话目录也没了
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
out.push({ id: rec.sessionId, mtime, title });
|
|
434
|
+
}
|
|
435
|
+
return out.sort((a, b) => b.mtime - a.mtime);
|
|
436
|
+
}
|
|
437
|
+
|
|
326
438
|
function listSessions(kind, env, root) {
|
|
439
|
+
if (kind === 'kimi') {
|
|
440
|
+
const found = findKimi(env);
|
|
441
|
+
if (found.problem) return { problem: found.problem };
|
|
442
|
+
return { sessions: kimiSessions(found.home, root) };
|
|
443
|
+
}
|
|
327
444
|
if (kind !== 'dsh') return { sessions: [] };
|
|
328
445
|
const found = findDsh(env);
|
|
329
446
|
if (found.problem) return { problem: found.problem };
|
|
@@ -346,6 +463,14 @@ const MODEL_SUPPORT = {
|
|
|
346
463
|
via: 'args',
|
|
347
464
|
args: (model, effort) => [...(model ? ['--model', model] : []), ...(EFFORTS.includes(effort) && effort !== 'none' ? ['--effort', effort] : [])],
|
|
348
465
|
},
|
|
466
|
+
// kimi:模型用 -m(写它在 config.toml 里 [models] 的别名);强度没有命令行参数,只有环境变量 KIMI_MODEL_THINKING_EFFORT(按官方文档带上,没实测)
|
|
467
|
+
kimi: {
|
|
468
|
+
model: true,
|
|
469
|
+
effort: true,
|
|
470
|
+
via: 'args',
|
|
471
|
+
args: (model) => (model ? ['-m', model] : []),
|
|
472
|
+
env: (effort) => (EFFORTS.includes(effort) && effort !== 'none' ? { KIMI_MODEL_THINKING_EFFORT: effort } : {}),
|
|
473
|
+
},
|
|
349
474
|
};
|
|
350
475
|
|
|
351
476
|
// DSH 的 --json 是一行一个事件:session 给会话 ID,final 给回答和结束原因
|
|
@@ -372,30 +497,76 @@ function parseDsh(stdout) {
|
|
|
372
497
|
};
|
|
373
498
|
}
|
|
374
499
|
|
|
500
|
+
// 被时限停掉时已经说出口的话:dsh 取最后一个 text 事件,kimi 取最后一条不带工具调用的 assistant 消息。别的家最后才输出,没有
|
|
501
|
+
function parseDshPartial(stdout) {
|
|
502
|
+
let said = '';
|
|
503
|
+
for (const line of String(stdout).split('\n')) {
|
|
504
|
+
if (!line.trim()) continue;
|
|
505
|
+
let ev;
|
|
506
|
+
try {
|
|
507
|
+
ev = JSON.parse(line);
|
|
508
|
+
} catch {
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
if (ev.type === 'text' && typeof ev.text === 'string') said = ev.text;
|
|
512
|
+
}
|
|
513
|
+
return said.trim();
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function parseKimiPartial(stdout) {
|
|
517
|
+
let said = '';
|
|
518
|
+
for (const line of String(stdout).split('\n')) {
|
|
519
|
+
if (!line.trim()) continue;
|
|
520
|
+
let ev;
|
|
521
|
+
try {
|
|
522
|
+
ev = JSON.parse(line);
|
|
523
|
+
} catch {
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
if (ev.role === 'assistant' && typeof ev.content === 'string' && ev.content.trim() && !ev.tool_calls) said = ev.content;
|
|
527
|
+
}
|
|
528
|
+
return said.trim();
|
|
529
|
+
}
|
|
530
|
+
|
|
375
531
|
// 建一个 agent 对接。
|
|
376
532
|
// root 工作目录(agent 在这里跑)
|
|
377
533
|
// agent YZJ_BOT_AGENT 的值
|
|
378
534
|
// mode plan(只读,默认)、edit(允许改工作目录),或者预置自己认的名字
|
|
379
|
-
// timeoutS
|
|
535
|
+
// timeoutS 一次运行最多等多少秒(硬上限)
|
|
536
|
+
// idleS 多久没有任何输出算卡住(0 不查)。只有会边跑边输出的预置(dsh、kimi)用得上:
|
|
537
|
+
// 它们一直在吐事件,来一块输出就把闸往后推;zcode / qoder / claude 跑到最后才输出,按静默算会误杀正常的长任务
|
|
380
538
|
// preamble 随每句话带给 agent 的提示(可以为空)
|
|
381
539
|
// log 记日志的函数 (event, fields)
|
|
382
540
|
// model 用哪个模型(各家的模型 id;空串用它自己的默认)
|
|
383
541
|
// effort 思考强度:none / low / medium / high / max(空串用它自己的默认)
|
|
384
|
-
// 返回 { kind, run, doctor }:
|
|
542
|
+
// 返回 { kind, run, start, doctor, notes }:
|
|
385
543
|
// run(message, { session, onSessionLost }) → { reply, sessionId } 或 { failed, config? }。
|
|
386
544
|
// 给了 session 就接着它跑;接不上(过期、被删)时调 onSessionLost(),再开新会话跑一次
|
|
545
|
+
// start(message, { session, onSessionLost, onSession }) → { done, kill },异步版的 run:done 是同一个结果的 Promise,
|
|
546
|
+
// kill(原因) 停掉它。onSession 在拿到会话 id 时调一次(dsh 一开始就打出来,别的跑完才有)。路由和执行者用它。
|
|
547
|
+
// done 以 { failed, timedOut: 'idle'|'max', partial } 结算时是被时限停掉的,partial 是已经说出口的话(取得到的才有)
|
|
387
548
|
// doctor() → 配置和依赖的问题,一条一个字符串;没有就是空数组
|
|
388
|
-
|
|
549
|
+
// notes() → 不算问题的注意事项(比如这个 agent 无界面下没有只读档),给 doctor 列出来
|
|
550
|
+
function createAgent({ root, agent, mode = 'plan', timeoutS = 300, idleS = 0, preamble = '', log = () => {}, env = process.env, model = '', effort = '' }) {
|
|
389
551
|
const name = String(agent || '').trim();
|
|
390
552
|
const kind = presetKind(name);
|
|
391
553
|
model = String(model || '').trim();
|
|
392
554
|
effort = String(effort || '').trim();
|
|
555
|
+
const stateDirOf = (given) => given || path.join(root, '01-inbox', '_bot');
|
|
556
|
+
|
|
557
|
+
// 不算问题、但要让人知道的事
|
|
558
|
+
function notes() {
|
|
559
|
+
if (kind !== 'custom' && PRESETS[kind].readOnly === false && mode === 'plan') {
|
|
560
|
+
return [`${kind} 的无界面模式没有只读档,这次虽然按 plan 跑,它实际能改文件、能跑命令(换 dsh / zcode / qoder / claude 才有只读)`];
|
|
561
|
+
}
|
|
562
|
+
return [];
|
|
563
|
+
}
|
|
393
564
|
|
|
394
565
|
function doctor() {
|
|
395
|
-
if (model && kind !== 'custom' && !MODEL_SUPPORT[kind].model) return [`预置 ${kind} 不支持指定模型(${kind === 'zcode' ? 'ZCode 的命令行没有这个参数,用的是它自己的默认模型' : '见 docs/agents.md'}):把 collectors/local.env 里的 YZJ_BOT_MODEL 去掉,或者换一个支持的 agent`];
|
|
396
|
-
if (effort && kind !== 'custom' && !MODEL_SUPPORT[kind].effort) return [`预置 ${kind} 不支持指定思考强度:把 collectors/local.env 里的 YZJ_BOT_EFFORT 去掉`];
|
|
397
|
-
if (effort && kind !== 'custom' && !EFFORTS.includes(effort)) return [`思考强度写的是「${effort}」,只能是 ${EFFORTS.join(' / ')}`];
|
|
398
566
|
if (!name) return [`没绑 agent:定时任务和机器人值守都要一个 agent 来跑。先 work-rhythm agent detect 看本机有哪些,再 work-rhythm agent bind <${PRESET_NAMES.join('|')}|命令>(写进 collectors/local.env 的 YZJ_BOT_AGENT)`];
|
|
567
|
+
if (kind !== 'custom' && !MODEL_SUPPORT[kind].model && model) return [`预置 ${kind} 不支持指定模型(${kind === 'zcode' ? 'ZCode 的命令行没有这个参数,用的是它自己的默认模型' : '见 docs/agents.md'}):把 collectors/local.env 里的 YZJ_BOT_MODEL 去掉,或者换一个支持的 agent`];
|
|
568
|
+
if (kind !== 'custom' && !MODEL_SUPPORT[kind].effort && effort) return [`预置 ${kind} 不支持指定思考强度:把 collectors/local.env 里的 YZJ_BOT_EFFORT 去掉`];
|
|
569
|
+
if (effort && kind !== 'custom' && !EFFORTS.includes(effort)) return [`思考强度写的是「${effort}」,只能是 ${EFFORTS.join(' / ')}`];
|
|
399
570
|
if (kind !== 'custom') {
|
|
400
571
|
const found = PRESETS[kind].find(env);
|
|
401
572
|
if (found.problem) return [found.problem];
|
|
@@ -483,7 +654,9 @@ function createAgent({ root, agent, mode = 'plan', timeoutS = 300, preamble = ''
|
|
|
483
654
|
if (d.problem) return d;
|
|
484
655
|
const entries = readDshPatchEntries(d.home, { model, effort });
|
|
485
656
|
if (entries.problem) return entries;
|
|
486
|
-
|
|
657
|
+
// 覆盖文件按模型和强度分文件名:路由和执行者用的模型不一样、又并发跑的时候,不会互相覆盖
|
|
658
|
+
const tag = model || effort ? `-${crypto.createHash('sha1').update(`${model}\n${effort}`).digest('hex').slice(0, 8)}` : '';
|
|
659
|
+
const patchFile = path.join(stateDir, `dsh-headless${tag}.patch.yml`);
|
|
487
660
|
fs.mkdirSync(stateDir, { recursive: true });
|
|
488
661
|
fs.writeFileSync(patchFile, [...entries.lines, ''].join('\n'));
|
|
489
662
|
const permission = { plan: 'read-only', edit: 'workspace-write' }[mode] || mode;
|
|
@@ -493,10 +666,49 @@ function createAgent({ root, agent, mode = 'plan', timeoutS = 300, preamble = ''
|
|
|
493
666
|
env: { ...env, ELECTRON_RUN_AS_NODE: '1', DSH_HOME: d.home },
|
|
494
667
|
withSession: (sid) => [...base, ...(sid ? ['--session-id', sid] : []), '--json', prompt],
|
|
495
668
|
parse: parseDsh,
|
|
669
|
+
partial: parseDshPartial,
|
|
670
|
+
// --json 的第一行就是 session 事件:一开始就能拿到会话 id
|
|
671
|
+
parseSession: (line) => {
|
|
672
|
+
try {
|
|
673
|
+
const ev = JSON.parse(line);
|
|
674
|
+
return ev.type === 'session' && typeof ev.sessionId === 'string' ? ev.sessionId : '';
|
|
675
|
+
} catch {
|
|
676
|
+
return '';
|
|
677
|
+
}
|
|
678
|
+
},
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// kimi:kimi [-m <模型>] [-S <会话>] --output-format stream-json -p <这句话>。模型用 -m,强度用环境变量。
|
|
683
|
+
// 无界面模式默认自动放行,--prompt 不能和 --plan 同用,所以没有只读档(notes() 会说)。会话被别的进程占着时退出码 4
|
|
684
|
+
function planKimi(prompt) {
|
|
685
|
+
const k = findKimi(env);
|
|
686
|
+
if (k.problem) return k;
|
|
687
|
+
const base = MODEL_SUPPORT.kimi.args(model);
|
|
688
|
+
return {
|
|
689
|
+
command: k.command,
|
|
690
|
+
env: { ...env, ...MODEL_SUPPORT.kimi.env(effort) },
|
|
691
|
+
busyExit: 4,
|
|
692
|
+
withSession: (sid) => [...base, ...(sid ? ['-S', sid] : []), '--output-format', 'stream-json', '-p', prompt],
|
|
693
|
+
parse: parseKimi,
|
|
694
|
+
partial: parseKimiPartial,
|
|
496
695
|
};
|
|
497
696
|
}
|
|
498
697
|
|
|
499
|
-
|
|
698
|
+
const planFor = (prompt, stateDir) => ({ zcode: planZcode, dsh: planDsh, qoder: planQoder, claude: planClaude, kimi: planKimi }[kind](prompt, stateDir));
|
|
699
|
+
|
|
700
|
+
// 一次运行的结果:进程的退出状态 + 解析。run 和 start 共用
|
|
701
|
+
function settle(plan, r, used) {
|
|
702
|
+
if (r.failed) return r;
|
|
703
|
+
// 会话被别的进程占着(kimi 的退出码 4):不是「接不上」,不能退回新会话
|
|
704
|
+
if (plan.busyExit && r.status === plan.busyExit) return { failed: '这个会话正被别的进程占着(比如桌面端正开着它),等它放开再试', busy: true };
|
|
705
|
+
if (r.status !== 0) return { failed: `退出码 ${r.status}:${tail(r.stderr)}` };
|
|
706
|
+
const out = plan.parse(r.stdout);
|
|
707
|
+
if (out.failed) return out;
|
|
708
|
+
return out.reply.trim() ? { reply: out.reply.trim(), sessionId: out.sessionId || '' } : { failed: '它回了空内容' };
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
function run(message, { session = '', onSessionLost = () => {}, stateDir } = {}) {
|
|
500
712
|
const started = Date.now();
|
|
501
713
|
const secs = () => Math.round((Date.now() - started) / 1000);
|
|
502
714
|
if (kind === 'custom') {
|
|
@@ -510,25 +722,148 @@ function createAgent({ root, agent, mode = 'plan', timeoutS = 300, preamble = ''
|
|
|
510
722
|
return reply ? { reply } : { failed: '它没有输出任何回复' };
|
|
511
723
|
}
|
|
512
724
|
const prompt = preamble ? `${message}\n\n${preamble}` : message;
|
|
513
|
-
const plan =
|
|
725
|
+
const plan = planFor(prompt, stateDirOf(stateDir));
|
|
514
726
|
if (plan.problem) return { failed: plan.problem, config: true }; // 配置问题:调用方按「没配置好」处理
|
|
515
727
|
let used = session;
|
|
516
728
|
let r = runProcess(plan.command, plan.withSession(used), plan.env);
|
|
517
|
-
if (!r.failed && r.status !== 0 && used) {
|
|
729
|
+
if (!r.failed && r.status !== 0 && used && !(plan.busyExit && r.status === plan.busyExit)) {
|
|
518
730
|
log('agent 接不上旧会话,改开新会话', `rc=${r.status}`);
|
|
519
731
|
onSessionLost();
|
|
520
732
|
used = '';
|
|
521
733
|
r = runProcess(plan.command, plan.withSession(''), plan.env);
|
|
522
734
|
}
|
|
523
|
-
|
|
524
|
-
if (r.status !== 0) return { failed: `退出码 ${r.status}:${tail(r.stderr)}` };
|
|
525
|
-
const out = plan.parse(r.stdout);
|
|
735
|
+
const out = settle(plan, r, used);
|
|
526
736
|
if (out.failed) return out;
|
|
527
737
|
log('agent 完成', `${secs()}s ${kind} mode=${mode}${model ? ` model=${model}` : ''}${effort ? ` effort=${effort}` : ''} session=${used ? '续' : '新'}`);
|
|
528
|
-
return out
|
|
738
|
+
return out;
|
|
529
739
|
}
|
|
530
740
|
|
|
531
|
-
|
|
741
|
+
// 起一个子进程、攒输出,不阻塞事件循环。两个闸:
|
|
742
|
+
// idleS 多久没有任何输出就算卡住(0 不查)。每来一块输出就往后推,所以一直在干活的不会被误杀
|
|
743
|
+
// timeoutS 硬上限,一次运行最多等多少秒
|
|
744
|
+
// 谁先到就杀掉谁。done 是 { status, stdout, stderr } 或 { failed, timedOut: 'idle'|'max', partial: 原始输出 };
|
|
745
|
+
// kill(原因) 之后 done 以 { failed: 原因, stopped: true } 结算。onSession 在 stdout 里出现会话 id 时调(plan.parseSession 按行认)
|
|
746
|
+
function spawnAsync(plan, args, { timeoutS: maxS = 300, idleS = 0, onSession = () => {} } = {}) {
|
|
747
|
+
let child;
|
|
748
|
+
try {
|
|
749
|
+
child = spawn(plan.command, args, { cwd: root, env: plan.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
750
|
+
} catch (error) {
|
|
751
|
+
return { done: Promise.resolve({ failed: `起不来 ${path.basename(plan.command)}:${error.message}` }), kill() {} };
|
|
752
|
+
}
|
|
753
|
+
let out = '';
|
|
754
|
+
let size = 0;
|
|
755
|
+
let pending = '';
|
|
756
|
+
let settled = null;
|
|
757
|
+
let wake = () => {};
|
|
758
|
+
let idleTimer = null;
|
|
759
|
+
const finish = (r) => {
|
|
760
|
+
if (settled) return;
|
|
761
|
+
settled = r;
|
|
762
|
+
clearTimeout(maxTimer);
|
|
763
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
764
|
+
wake(r);
|
|
765
|
+
};
|
|
766
|
+
// 停了就带上已经说出口的话(能取到的才有),调用方决定要不要用它
|
|
767
|
+
const giveUp = (reason, timedOut) => {
|
|
768
|
+
if (settled) return;
|
|
769
|
+
finish({ failed: reason, timedOut, partial: out });
|
|
770
|
+
child.kill('SIGTERM');
|
|
771
|
+
};
|
|
772
|
+
const bump = () => {
|
|
773
|
+
if (!idleS || settled) return;
|
|
774
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
775
|
+
idleTimer = setTimeout(() => giveUp(`超过 ${idleS} 秒没有任何输出`, 'idle'), idleS * 1000);
|
|
776
|
+
};
|
|
777
|
+
const maxTimer = setTimeout(() => giveUp(`超过 ${maxS} 秒没做完`, 'max'), maxS * 1000);
|
|
778
|
+
bump();
|
|
779
|
+
child.stdout.on('data', (chunk) => {
|
|
780
|
+
if (settled) return;
|
|
781
|
+
bump();
|
|
782
|
+
size += chunk.length;
|
|
783
|
+
if (size > 64 * 1024 * 1024) return;
|
|
784
|
+
out += chunk;
|
|
785
|
+
if (!plan.parseSession) return;
|
|
786
|
+
pending += chunk;
|
|
787
|
+
const lines = pending.split('\n');
|
|
788
|
+
pending = lines.pop();
|
|
789
|
+
for (const line of lines) {
|
|
790
|
+
const sid = plan.parseSession(line);
|
|
791
|
+
if (sid) onSession(sid);
|
|
792
|
+
}
|
|
793
|
+
});
|
|
794
|
+
const errChunks = [];
|
|
795
|
+
child.stderr.on('data', (chunk) => {
|
|
796
|
+
if (settled) return;
|
|
797
|
+
bump();
|
|
798
|
+
errChunks.push(chunk);
|
|
799
|
+
});
|
|
800
|
+
child.on('error', (error) => finish({ failed: `没跑起来:${error.message}` }));
|
|
801
|
+
child.on('close', (code) => finish({ status: code, stdout: out, stderr: Buffer.concat(errChunks).toString('utf8') }));
|
|
802
|
+
return {
|
|
803
|
+
done: new Promise((resolve) => {
|
|
804
|
+
wake = resolve;
|
|
805
|
+
if (settled) resolve(settled);
|
|
806
|
+
}),
|
|
807
|
+
kill(reason = '已停止') {
|
|
808
|
+
finish({ failed: reason, stopped: true });
|
|
809
|
+
child.kill('SIGTERM');
|
|
810
|
+
},
|
|
811
|
+
};
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
// 异步版的 run:路由和执行者用它,本地服务的事件循环不被一次运行卡住。
|
|
815
|
+
// 会边跑边输出的预置(dsh、kimi)才用静默闸——别的家跑到最后才吐,按静默算会把正常的长任务误杀
|
|
816
|
+
function start(message, { session = '', onSessionLost = () => {}, onSession = () => {}, stateDir } = {}) {
|
|
817
|
+
const streamy = kind !== 'custom' && PRESETS[kind].streams === true;
|
|
818
|
+
const idle = streamy ? idleS : 0;
|
|
819
|
+
if (kind === 'custom') {
|
|
820
|
+
const [command, ...base] = splitCommand(name);
|
|
821
|
+
const h = spawnAsync({ command, env }, [...base, message], { timeoutS });
|
|
822
|
+
const done = h.done.then((r) => {
|
|
823
|
+
if (r.failed) return r;
|
|
824
|
+
if (r.status !== 0) return { failed: `退出码 ${r.status}:${tail(r.stderr)}` };
|
|
825
|
+
return r.stdout.trim() ? { reply: r.stdout.trim() } : { failed: '它没有输出任何回复' };
|
|
826
|
+
});
|
|
827
|
+
return { done, kill: h.kill };
|
|
828
|
+
}
|
|
829
|
+
const prompt = preamble ? `${message}\n\n${preamble}` : message;
|
|
830
|
+
const plan = planFor(prompt, stateDirOf(stateDir));
|
|
831
|
+
if (plan.problem) return { done: Promise.resolve({ failed: plan.problem, config: true }), kill() {} };
|
|
832
|
+
let handle = null;
|
|
833
|
+
let killed = '';
|
|
834
|
+
const again = (sid) => {
|
|
835
|
+
handle = spawnAsync(plan, plan.withSession(sid), { timeoutS, idleS: idle, onSession });
|
|
836
|
+
return handle.done;
|
|
837
|
+
};
|
|
838
|
+
const started = Date.now();
|
|
839
|
+
const done = (async () => {
|
|
840
|
+
const used = session;
|
|
841
|
+
let r = await again(used);
|
|
842
|
+
if (killed) return { failed: killed, stopped: true };
|
|
843
|
+
if (!r.failed && r.status !== 0 && used && !(plan.busyExit && r.status === plan.busyExit)) {
|
|
844
|
+
log('agent 接不上旧会话,改开新会话', `rc=${r.status}`);
|
|
845
|
+
onSessionLost();
|
|
846
|
+
r = await again('');
|
|
847
|
+
}
|
|
848
|
+
const out = settle(plan, r, used);
|
|
849
|
+
if (out.failed) {
|
|
850
|
+
// 被时限停掉的:把已经说出口的话取出来,调用方可以拿来先回一句
|
|
851
|
+
if (out.timedOut && plan.partial) out.partial = plan.partial(out.partial || '');
|
|
852
|
+
return out;
|
|
853
|
+
}
|
|
854
|
+
log('agent 完成', `${Math.round((Date.now() - started) / 1000)}s ${kind} mode=${mode}${model ? ` model=${model}` : ''}${effort ? ` effort=${effort}` : ''} session=${used ? '续' : '新'}`);
|
|
855
|
+
return out;
|
|
856
|
+
})();
|
|
857
|
+
return {
|
|
858
|
+
done,
|
|
859
|
+
kill(reason) {
|
|
860
|
+
killed = reason || '已停止';
|
|
861
|
+
if (handle) handle.kill(killed);
|
|
862
|
+
},
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
return { kind, run, start, doctor, notes };
|
|
532
867
|
}
|
|
533
868
|
|
|
534
869
|
// 一个预置能选哪些模型:[{ provider, id, name, reasoning }]。dsh 读它的配置;qoder 问命令行(--list-models);claude 给常见的几个别名;
|
|
@@ -552,10 +887,22 @@ function listModels(kind, env) {
|
|
|
552
887
|
if (r.status !== 0) return { problem: `qoder --list-models 没跑成:${tail(r.stderr || r.stdout, 200)}` };
|
|
553
888
|
return { text: r.stdout.trim() };
|
|
554
889
|
}
|
|
890
|
+
if (kind === 'kimi') {
|
|
891
|
+
// kimi provider list --json 给 providers 和 models 两张表(models 的键是模型别名);表的结构按文档猜的,解析不出来就把原文带出来
|
|
892
|
+
const r = spawnSync(found.command, ['provider', 'list', '--json'], { encoding: 'utf8', env, timeout: 60000 });
|
|
893
|
+
if (r.status !== 0) return { problem: `kimi provider list --json 没跑成:${tail(r.stderr || r.stdout, 200)}` };
|
|
894
|
+
try {
|
|
895
|
+
const data = JSON.parse(r.stdout);
|
|
896
|
+
const models = data.models && typeof data.models === 'object' ? data.models : {};
|
|
897
|
+
return { models: Object.entries(models).map(([id, m]) => ({ id, name: m && typeof m === 'object' && m.name ? String(m.name) : '', reasoning: Boolean(m && typeof m === 'object' && m.reasoning) })) };
|
|
898
|
+
} catch {
|
|
899
|
+
return { text: r.stdout.trim() };
|
|
900
|
+
}
|
|
901
|
+
}
|
|
555
902
|
if (kind === 'claude') {
|
|
556
903
|
return { models: ['opus', 'sonnet', 'haiku'].map((id) => ({ id, name: id === 'opus' ? 'Opus(最强)' : id === 'sonnet' ? 'Sonnet(均衡)' : 'Haiku(最快)', reasoning: true })) };
|
|
557
904
|
}
|
|
558
905
|
return { models: [] };
|
|
559
906
|
}
|
|
560
907
|
|
|
561
|
-
module.exports = { createAgent, splitCommand, PRESETS, PRESET_NAMES, MODEL_SUPPORT, EFFORTS, SESSION_ENV, invokingAgent, invokingSession, installedAgents, ideOnly, bindAgent, listModels, listSessions, dshSessions, findZcode, findDsh, findQoder, findClaude };
|
|
908
|
+
module.exports = { createAgent, splitCommand, PRESETS, PRESET_NAMES, MODEL_SUPPORT, EFFORTS, SESSION_ENV, ROLE_KEYS, ROLE_LABEL, invokingAgent, invokingSession, installedAgents, ideOnly, roles, bindAgent, listModels, listSessions, dshSessions, kimiSessions, findZcode, findDsh, findQoder, findClaude, findKimi, parseKimi };
|