work-rhythm 0.0.0-stage → 0.1.0
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 +84 -0
- package/.agents/notes/decisions/2026-11-28-long-term-goals-ride-existing-tasks.md +36 -0
- package/.agents/notes/decisions/2026-11-29-building-a-workdir-means-cloning-the-template.md +25 -0
- package/.agents/notes/decisions/2026-11-29-find-workdir-cwd-first-then-registered.md +32 -0
- package/.agents/notes/decisions/2026-11-30-bot-inbound-uses-websocket-and-a-responder-command.md +48 -0
- package/.agents/notes/decisions/2026-11-30-cost-entry-writes-into-empty-cells-directly.md +25 -0
- package/.agents/notes/decisions/2026-11-30-dependencies-are-allowed-user-installs-missing-ones.md +30 -0
- package/.agents/notes/decisions/2026-11-30-markdown-is-the-record-html-is-only-a-view.md +25 -0
- package/.agents/notes/decisions/2026-11-30-message-channels-are-preset-in-the-skill.md +34 -0
- package/.agents/notes/decisions/2026-11-30-no-workdir-offers-to-create-one-by-default.md +34 -0
- package/.agents/notes/decisions/2026-11-30-paging-requires-coverage-only-when-enabled.md +27 -0
- package/.agents/notes/decisions/2026-11-30-pending-decisions-asked-in-a-chat-and-logged-briefly.md +39 -0
- package/.agents/notes/decisions/2026-11-30-push-via-personal-robot-webhook.md +33 -0
- package/.agents/notes/decisions/2026-11-30-scheduling-moves-to-a-local-service.md +37 -0
- package/.agents/notes/decisions/2026-11-30-skill-ships-with-its-template-in-a-zip.md +30 -0
- package/.agents/notes/decisions/2026-11-30-skill-stays-generic-user-provides-cli-or-mcp.md +25 -0
- package/.agents/notes/decisions/2026-12-01-everything-is-js-behind-work-rhythm.md +45 -0
- package/.agents/notes/pitfalls/2026-11-29-do-not-hand-roll-git-log.md +22 -0
- package/.agents/notes/pitfalls/2026-11-29-empty-or-partial-collector-output.md +23 -0
- package/.agents/notes/pitfalls/2026-11-29-skill-description-is-truncated.md +21 -0
- package/.agents/notes/pitfalls/2026-11-29-tool-shell-is-zsh.md +24 -0
- package/.agents/notes/pitfalls/2026-11-30-compare-timestamps-as-digits.md +22 -0
- package/.agents/notes/pitfalls/2026-11-30-message-search-lags-after-sending.md +18 -0
- package/.agents/notes/pitfalls/2026-11-30-rewriting-a-file-with-empty-output-after-tool-failure.md +20 -0
- package/.agents/notes/pitfalls/2026-11-30-secret-scan-false-positive-on-hyphenated-file-names.md +18 -0
- package/.agents/notes/pitfalls/2026-11-30-selftest-must-not-inherit-local-config.md +29 -0
- package/.agents/notes/pitfalls/2026-11-30-yzj-cli-list-limit-is-20.md +25 -0
- package/.agents/notes/pitfalls/2026-11-30-zsh-no-word-splitting-special-names.md +23 -0
- package/.agents/notes/pitfalls/2026-12-01-node-test-hooks-cannot-register-after-callbacks.md +22 -0
- package/.agents/notes/pitfalls/2026-12-01-spawning-node-test-inside-a-test-runs-nothing.md +18 -0
- package/.agents/skills/work-rhythm/SKILL.md +277 -0
- package/00-config/profile.example.yaml +54 -0
- package/00-config/sources.yaml +115 -0
- package/AGENTS.md +31 -0
- package/README.md +105 -2
- package/collectors/approval-yzj.js +114 -0
- package/collectors/calendar-yzj.js +48 -0
- package/collectors/file-activity.js +131 -0
- package/collectors/git-activity.js +105 -0
- package/collectors/im-yzj.js +151 -0
- package/collectors/linky-issues.js +88 -0
- package/collectors/local.env.example +52 -0
- package/docs/channels.md +95 -0
- package/docs/formats.md +285 -0
- package/docs/im-adapters.md +79 -0
- package/docs/scheduled-tasks.md +115 -0
- package/docs/sources.md +104 -0
- package/package.json +37 -4
- package/scripts/cli.js +98 -0
- package/scripts/cmd/check.js +297 -0
- package/scripts/cmd/collect.js +25 -0
- package/scripts/cmd/decisions.js +236 -0
- package/scripts/cmd/goals.js +145 -0
- package/scripts/cmd/init.js +53 -0
- package/scripts/cmd/listen.js +91 -0
- package/scripts/cmd/notify.js +42 -0
- package/scripts/cmd/pack.js +105 -0
- package/scripts/cmd/rhythm.js +102 -0
- package/scripts/cmd/selftest.js +23 -0
- package/scripts/cmd/sync.js +73 -0
- package/scripts/cmd/today.js +29 -0
- package/scripts/cmd/workdir.js +81 -0
- package/scripts/lib/agent.js +270 -0
- package/scripts/lib/bot.js +376 -0
- package/scripts/lib/collector.js +74 -0
- package/scripts/lib/config.js +250 -0
- package/scripts/lib/launchd.js +82 -0
- package/scripts/lib/log.js +22 -0
- package/scripts/lib/markdown.js +208 -0
- package/scripts/lib/notify.js +43 -0
- package/scripts/lib/rhythm.js +508 -0
- package/scripts/lib/robot.js +64 -0
- package/scripts/lib/run.js +151 -0
- package/scripts/lib/template.js +144 -0
- package/scripts/lib/workdir.js +89 -0
- package/scripts/test/check.test.js +217 -0
- package/scripts/test/collectors.test.js +574 -0
- package/scripts/test/config.test.js +119 -0
- package/scripts/test/decisions.test.js +129 -0
- package/scripts/test/fake-webhook.js +31 -0
- package/scripts/test/goals.test.js +109 -0
- package/scripts/test/harness.js +279 -0
- package/scripts/test/init.test.js +125 -0
- package/scripts/test/listen.test.js +362 -0
- package/scripts/test/notify.test.js +176 -0
- package/scripts/test/pack.test.js +141 -0
- package/scripts/test/rhythm.test.js +324 -0
- package/scripts/test/stubs.js +140 -0
- package/scripts/test/today.test.js +73 -0
- package/scripts/test/workdir.test.js +152 -0
- package/scripts/work-rhythm.js +18 -0
- package/tasks/alerts-morning.md +24 -0
- package/tasks/carryover.md +16 -0
- package/tasks/daily-plan.md +29 -0
- package/tasks/evening-review.md +27 -0
- package/tasks/linky-cost-check.md +13 -0
- package/tasks/linky-cost-fill.md +20 -0
- package/tasks/noon-checkin.md +15 -0
- package/tasks/weekly-rhythm.md +18 -0
- package/templates/03-carryover/CARRYOVER.md +14 -0
- package/templates/03-carryover/DECISIONS.md +10 -0
- package/templates/04-patterns/WORK_RHYTHM.md +16 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// 今天(或指定日期)在工作目录里的约定:日期、星期、每日文件路径、是否工作日
|
|
2
|
+
'use strict';
|
|
3
|
+
const { loadProfile } = require('../lib/config');
|
|
4
|
+
const { EXIT, UsageError, parseDate, fmtDate, today, weekdayCn, weekdayAbbr } = require('../lib/run');
|
|
5
|
+
|
|
6
|
+
const USAGE = '用法: work-rhythm today [YYYY-MM-DD]\n输出四行:DATE=、WEEKDAY=、DAILY_FILE=、IS_WORKDAY=';
|
|
7
|
+
|
|
8
|
+
// 是否工作日看 profile 的 preferences:workdays 里有没有这一天(Mon…Sun),holidays 里有没有这个日期。
|
|
9
|
+
// workdays 写成了空列表,就天天都不上班;没写这一项,就天天都上班
|
|
10
|
+
function resolve(root, dateArg) {
|
|
11
|
+
const date = dateArg ? fmtDate(parseDate(dateArg.trim())) : today();
|
|
12
|
+
const prefs = loadProfile(root).preferences || {};
|
|
13
|
+
let isWorkday = 1;
|
|
14
|
+
if (Array.isArray(prefs.workdays)) isWorkday = prefs.workdays.some((d) => String(d) === weekdayAbbr(date)) ? 1 : 0;
|
|
15
|
+
if (Array.isArray(prefs.holidays) && prefs.holidays.some((d) => String(d) === date)) isWorkday = 0;
|
|
16
|
+
return { date, weekday: weekdayCn(date), dailyFile: `02-daily/${date.slice(0, 7)}/${date}.md`, isWorkday };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const output = (info) => `DATE=${info.date}\nWEEKDAY=${info.weekday}\nDAILY_FILE=${info.dailyFile}\nIS_WORKDAY=${info.isWorkday}\n`;
|
|
20
|
+
|
|
21
|
+
module.exports = {
|
|
22
|
+
usage: USAGE,
|
|
23
|
+
resolve,
|
|
24
|
+
async run(args, ctx) {
|
|
25
|
+
if (args.length > 1) throw new UsageError(USAGE);
|
|
26
|
+
ctx.stdout.write(output(resolve(ctx.root, args[0])));
|
|
27
|
+
return EXIT.OK;
|
|
28
|
+
},
|
|
29
|
+
};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// 工作目录在哪:找、登记、扫描本机、清空白。新建用 work-rhythm init。
|
|
2
|
+
// 用法: work-rhythm workdir 找工作目录:打印 WORKDIR=<路径> 和 SOURCE=cwd|pointer;找不到时 WORKDIR 为空,退出码 1
|
|
3
|
+
// work-rhythm workdir register [目录] 把目录(默认当前目录)登记为工作目录,写进用户级配置
|
|
4
|
+
// work-rhythm workdir find [起点目录 …] 找本机疑似工作目录的目录(带 00-config/profile.yaml 的);制表符分隔:路径、初始化状态、称呼
|
|
5
|
+
// work-rhythm workdir config 打印用户级配置文件的位置
|
|
6
|
+
// work-rhythm workdir blank <目录> 把一个目录清成空白的工作目录:个人信息换成空白模板、数据源全关、记录不留
|
|
7
|
+
// 查找顺序:先从当前目录往上找带 00-config/profile.yaml 的目录,找不到再看用户级登记。
|
|
8
|
+
// 用户级配置默认在 ~/.config/work-rhythm/config.yaml,可用环境变量 WORK_RHYTHM_CONFIG 改位置
|
|
9
|
+
'use strict';
|
|
10
|
+
const fs = require('node:fs');
|
|
11
|
+
const path = require('node:path');
|
|
12
|
+
const os = require('node:os');
|
|
13
|
+
const { EXIT, Fail, UsageError } = require('../lib/run');
|
|
14
|
+
const { isWorkdir, configPath, register, resolveRoot, findAll } = require('../lib/workdir');
|
|
15
|
+
const { blank } = require('../lib/template');
|
|
16
|
+
|
|
17
|
+
const USAGE = `用法: work-rhythm workdir [子命令]
|
|
18
|
+
找工作目录:打印 WORKDIR=<路径> 和 SOURCE=cwd|pointer;找不到时 WORKDIR 为空,退出码 1
|
|
19
|
+
register [目录] 把目录(默认当前目录)登记为工作目录,写进用户级配置
|
|
20
|
+
find [起点目录 …] 找本机疑似工作目录的目录(带 00-config/profile.yaml 的);制表符分隔:路径、初始化状态、称呼
|
|
21
|
+
config 打印用户级配置文件的位置
|
|
22
|
+
blank <目录> 把一个目录清成空白的工作目录
|
|
23
|
+
新建用 work-rhythm init <目录>`;
|
|
24
|
+
|
|
25
|
+
module.exports = {
|
|
26
|
+
usage: USAGE,
|
|
27
|
+
async run(args, ctx) {
|
|
28
|
+
const { stdout, stderr, cwd, env } = ctx;
|
|
29
|
+
const [verb, ...rest] = args;
|
|
30
|
+
// 绝对路径,解析符号链接;目录不存在时是空串
|
|
31
|
+
const abs = (dir) => {
|
|
32
|
+
try {
|
|
33
|
+
return fs.realpathSync(path.resolve(dir));
|
|
34
|
+
} catch {
|
|
35
|
+
return '';
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
switch (verb) {
|
|
39
|
+
case undefined: {
|
|
40
|
+
if (rest.length) throw new UsageError(USAGE);
|
|
41
|
+
const found = resolveRoot({ cwd, env });
|
|
42
|
+
stdout.write(`WORKDIR=${found.root}\nSOURCE=${found.source}\n`);
|
|
43
|
+
if (found.problem) stderr.write(`workdir: ${found.problem}\n`);
|
|
44
|
+
return found.root ? EXIT.OK : 1;
|
|
45
|
+
}
|
|
46
|
+
case 'register': {
|
|
47
|
+
if (rest.length > 1) throw new UsageError(USAGE);
|
|
48
|
+
const dir = abs(rest[0] || cwd);
|
|
49
|
+
if (!dir) throw new Fail(EXIT.USAGE, `目录不存在: ${rest[0]}`);
|
|
50
|
+
if (!isWorkdir(dir)) throw new Fail(EXIT.USAGE, `${dir} 不是工作目录(没有 00-config/profile.yaml)`);
|
|
51
|
+
register(dir, env);
|
|
52
|
+
stdout.write(`WORKDIR=${dir}\n`);
|
|
53
|
+
stderr.write(`workdir: 已登记为工作目录(${configPath(env)})\n`);
|
|
54
|
+
return EXIT.OK;
|
|
55
|
+
}
|
|
56
|
+
case 'find': {
|
|
57
|
+
const rows = findAll(rest, env.HOME || os.homedir());
|
|
58
|
+
for (const row of rows) stdout.write(`${row.dir}\t${row.status}\t${row.name}\n`);
|
|
59
|
+
return EXIT.OK;
|
|
60
|
+
}
|
|
61
|
+
case 'config':
|
|
62
|
+
if (rest.length) throw new UsageError(USAGE);
|
|
63
|
+
stdout.write(`${configPath(env)}\n`);
|
|
64
|
+
return EXIT.OK;
|
|
65
|
+
case 'blank': {
|
|
66
|
+
if (rest.length !== 1) throw new UsageError(USAGE);
|
|
67
|
+
const dir = abs(rest[0]);
|
|
68
|
+
if (!dir) throw new Fail(EXIT.USAGE, `目录不存在: ${rest[0]}`);
|
|
69
|
+
try {
|
|
70
|
+
blank(dir);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
throw new Fail(EXIT.FAILED, error.message);
|
|
73
|
+
}
|
|
74
|
+
stderr.write(`workdir: 已把 ${dir} 清成空白的工作目录:个人信息是空白的、数据源全部关着、没有记录、没有本机配置和原始数据\n`);
|
|
75
|
+
return EXIT.OK;
|
|
76
|
+
}
|
|
77
|
+
default:
|
|
78
|
+
throw new UsageError(USAGE);
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
};
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// 让本地的 agent 跑一句话、拿回它的回复。值守(bot.js)和本地服务(rhythm.js)共用。
|
|
2
|
+
// agent 的三种值:zcode、dsh 是预置,其余当成一条命令(按空白拆开,引号里的算一个参数;消息作为最后一个参数传给它,
|
|
3
|
+
// 回复打到标准输出,退出码 0 算成功。不支持管道、重定向这类 shell 写法——要的话包一层脚本)。
|
|
4
|
+
// 只用 node 自带的能力。找预置的命令行时返回 { problem } 而不是抛错,doctor 和真正运行时共用这一段。
|
|
5
|
+
'use strict';
|
|
6
|
+
const { spawnSync } = require('node:child_process');
|
|
7
|
+
const fs = require('node:fs');
|
|
8
|
+
const os = require('node:os');
|
|
9
|
+
const path = require('node:path');
|
|
10
|
+
const { which } = require('./run');
|
|
11
|
+
|
|
12
|
+
const BUNDLED_ZCODE = '/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs';
|
|
13
|
+
|
|
14
|
+
function tail(text, max = 200) {
|
|
15
|
+
const s = String(text || '').trim();
|
|
16
|
+
return s.length > max ? s.slice(-max) : s;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// 把一条命令按空白拆成参数:单引号、双引号里面的算一个,反斜杠转义下一个字符。不展开变量,不做替换
|
|
20
|
+
function splitCommand(s) {
|
|
21
|
+
const out = [];
|
|
22
|
+
let cur = '';
|
|
23
|
+
let quote = '';
|
|
24
|
+
let started = false;
|
|
25
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
26
|
+
const c = s[i];
|
|
27
|
+
if (quote) {
|
|
28
|
+
if (c === '\\' && quote === '"' && i + 1 < s.length) cur += s[++i];
|
|
29
|
+
else if (c === quote) quote = '';
|
|
30
|
+
else cur += c;
|
|
31
|
+
} else if (c === '"' || c === "'") {
|
|
32
|
+
quote = c;
|
|
33
|
+
started = true;
|
|
34
|
+
} else if (c === '\\' && i + 1 < s.length) {
|
|
35
|
+
cur += s[++i];
|
|
36
|
+
started = true;
|
|
37
|
+
} else if (/\s/.test(c)) {
|
|
38
|
+
if (started) out.push(cur);
|
|
39
|
+
cur = '';
|
|
40
|
+
started = false;
|
|
41
|
+
} else {
|
|
42
|
+
cur += c;
|
|
43
|
+
started = true;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (started) out.push(cur);
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// DSH(DeepSeek Harness)的桌面应用把运行时装在 ~/.dsh-desktop 下,目录名是版本哈希,取最新的一个
|
|
51
|
+
function newestSubdir(dir, pick) {
|
|
52
|
+
let names;
|
|
53
|
+
try {
|
|
54
|
+
names = fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(dir, d.name));
|
|
55
|
+
} catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
let best = null;
|
|
59
|
+
for (const d of names) {
|
|
60
|
+
const file = pick(d);
|
|
61
|
+
if (!fs.existsSync(file)) continue;
|
|
62
|
+
const mtime = fs.statSync(d).mtimeMs;
|
|
63
|
+
if (!best || mtime > best.mtime) best = { dir: d, file, mtime };
|
|
64
|
+
}
|
|
65
|
+
return best;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function findZcode(env) {
|
|
69
|
+
const explicit = env.ZCODE_CLI;
|
|
70
|
+
if (explicit) {
|
|
71
|
+
if (fs.existsSync(explicit)) return { command: explicit, viaNode: /\.(c|m)?js$/.test(explicit) };
|
|
72
|
+
return { problem: `ZCODE_CLI 指的文件不存在:${explicit}` };
|
|
73
|
+
}
|
|
74
|
+
const which = spawnSync('/usr/bin/which', ['zcode'], { encoding: 'utf8', env });
|
|
75
|
+
if (which.status === 0 && which.stdout.trim()) return { command: which.stdout.trim(), viaNode: false };
|
|
76
|
+
if (fs.existsSync(BUNDLED_ZCODE)) return { command: BUNDLED_ZCODE, viaNode: true };
|
|
77
|
+
return { problem: '找不到 ZCode 的命令行:装了 ZCode 桌面版的话它自带;也可以用 ZCODE_CLI 指定路径' };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// DSH 的命令行要用它自带的 Node 跑(设 ELECTRON_RUN_AS_NODE 当普通 node 用),入口是 @deepseek-ai/dsh 的 bin.js
|
|
81
|
+
function findDsh(env) {
|
|
82
|
+
const home = env.DSH_HOME || path.join(os.homedir(), '.dsh');
|
|
83
|
+
const desktop = env.DSH_DESKTOP_DIR || path.join(os.homedir(), '.dsh-desktop');
|
|
84
|
+
let cli = env.DSH_CLI ? path.resolve(env.DSH_CLI) : '';
|
|
85
|
+
let runtimeDir = '';
|
|
86
|
+
if (cli) {
|
|
87
|
+
runtimeDir = path.resolve(path.dirname(cli), '..', '..', '..', '..'); // …/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js → …/dsh
|
|
88
|
+
} else {
|
|
89
|
+
const rt = newestSubdir(path.join(desktop, 'runtime'), (d) => path.join(d, 'dsh', 'node_modules', '@deepseek-ai', 'dsh', 'lib', 'bin.js'));
|
|
90
|
+
if (rt) {
|
|
91
|
+
cli = rt.file;
|
|
92
|
+
runtimeDir = path.join(rt.dir, 'dsh');
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
let node = env.DSH_NODE ? path.resolve(env.DSH_NODE) : '';
|
|
96
|
+
if (!node) {
|
|
97
|
+
const n = newestSubdir(path.join(desktop, 'sidecar-node'), (d) => path.join(d, 'DSH Node.app', 'Contents', 'MacOS', 'DSH Node'));
|
|
98
|
+
if (n) node = n.file;
|
|
99
|
+
}
|
|
100
|
+
if (!cli || !fs.existsSync(cli)) {
|
|
101
|
+
return { problem: '找不到 DSH 的命令行:装了 DSH 桌面版的话它在 ~/.dsh-desktop/runtime/<版本>/dsh/ 下;也可以用 DSH_CLI 指定 bin.js 的路径' };
|
|
102
|
+
}
|
|
103
|
+
if (!node || !fs.existsSync(node)) return { problem: '找不到 DSH 自带的 Node(~/.dsh-desktop/sidecar-node/ 下);也可以用 DSH_NODE 指定' };
|
|
104
|
+
return { home, node, cli, tsx: path.join(runtimeDir, 'node_modules', 'tsx', 'dist', 'esm', 'index.mjs') };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// headless 默认不带桌面应用里的模型和凭据(会去找 deepseek-official 要 API key)。把它的配置里模型那两条摘出来,
|
|
108
|
+
// 外加打开它的凭据存储,写成一份覆盖文件带进去。密钥始终在 DSH 自己的存储里,不经过这里
|
|
109
|
+
function readDshPatchEntries(home) {
|
|
110
|
+
const src = path.join(home, 'profiles', 'web', 'cordis.patch.yml');
|
|
111
|
+
let text;
|
|
112
|
+
try {
|
|
113
|
+
text = fs.readFileSync(src, 'utf8');
|
|
114
|
+
} catch {
|
|
115
|
+
return { problem: `找不到 DSH 的配置 ${src}:dsh 预置要用桌面应用里配好的模型` };
|
|
116
|
+
}
|
|
117
|
+
const picked = text.split(/^(?=- id: )/m)
|
|
118
|
+
.filter((block) => /^- id: (agent-default-model|llm-pi-ai)[ \t]*$/m.test(block))
|
|
119
|
+
.map((block) => block.trimEnd());
|
|
120
|
+
if (picked.length < 2) return { problem: `${src} 里没找齐 agent-default-model 和 llm-pi-ai 两条` };
|
|
121
|
+
return { lines: ['# 值守自动生成,不要手改:让 DSH 的 headless 模式用桌面应用里配置的模型和凭据', '- id: credentials', ' disabled: false', ...picked] };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// DSH 的 --json 是一行一个事件:session 给会话 ID,final 给回答和结束原因
|
|
125
|
+
function parseDsh(stdout) {
|
|
126
|
+
let final = null;
|
|
127
|
+
let sessionId = '';
|
|
128
|
+
for (const line of stdout.split('\n')) {
|
|
129
|
+
if (!line.trim()) continue;
|
|
130
|
+
let ev;
|
|
131
|
+
try {
|
|
132
|
+
ev = JSON.parse(line);
|
|
133
|
+
} catch {
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (ev.type === 'session' && typeof ev.sessionId === 'string') sessionId = ev.sessionId;
|
|
137
|
+
if (ev.type === 'final') final = ev;
|
|
138
|
+
}
|
|
139
|
+
if (!final) return { failed: '输出里没有 final 事件' };
|
|
140
|
+
const kind = final.reason && final.reason.kind ? final.reason.kind : 'completed';
|
|
141
|
+
if (kind !== 'completed') return { failed: `没跑完:${kind}` };
|
|
142
|
+
return {
|
|
143
|
+
reply: typeof final.text === 'string' ? final.text : '',
|
|
144
|
+
sessionId: typeof final.sessionId === 'string' ? final.sessionId : sessionId,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// 建一个 agent 对接。
|
|
149
|
+
// root 工作目录(agent 在这里跑)
|
|
150
|
+
// agent YZJ_BOT_AGENT 的值
|
|
151
|
+
// mode plan(只读,默认)、edit(允许改工作目录),或者预置自己认的名字
|
|
152
|
+
// timeoutS 一次运行最多等多少秒
|
|
153
|
+
// preamble 随每句话带给 agent 的提示(可以为空)
|
|
154
|
+
// log 记日志的函数 (event, fields)
|
|
155
|
+
// 返回 { kind, run, doctor }:
|
|
156
|
+
// run(message, { session, onSessionLost }) → { reply, sessionId } 或 { failed, config? }。
|
|
157
|
+
// 给了 session 就接着它跑;接不上(过期、被删)时调 onSessionLost(),再开新会话跑一次
|
|
158
|
+
// doctor() → 配置和依赖的问题,一条一个字符串;没有就是空数组
|
|
159
|
+
function createAgent({ root, agent, mode = 'plan', timeoutS = 300, preamble = '', log = () => {}, env = process.env }) {
|
|
160
|
+
const name = String(agent || '').trim();
|
|
161
|
+
const kind = name === 'zcode' || name === 'dsh' ? name : 'custom';
|
|
162
|
+
|
|
163
|
+
function doctor() {
|
|
164
|
+
if (!name) return ['没配 YZJ_BOT_AGENT(collectors/local.env):写 zcode、dsh,或一条把回复打到标准输出的命令'];
|
|
165
|
+
if (kind === 'zcode') {
|
|
166
|
+
const z = findZcode(env);
|
|
167
|
+
return z.problem ? [z.problem] : [];
|
|
168
|
+
}
|
|
169
|
+
if (kind === 'dsh') {
|
|
170
|
+
const d = findDsh(env);
|
|
171
|
+
if (d.problem) return [d.problem];
|
|
172
|
+
const entries = readDshPatchEntries(d.home);
|
|
173
|
+
return entries.problem ? [entries.problem] : [];
|
|
174
|
+
}
|
|
175
|
+
// 带斜杠的按工作目录里的相对路径找,其余在 PATH 上找
|
|
176
|
+
const [first] = splitCommand(name);
|
|
177
|
+
return which(first.includes('/') ? path.resolve(root, first) : first, env) ? [] : [`YZJ_BOT_AGENT 的命令找不到: ${first}`];
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function runProcess(command, args, extraEnv) {
|
|
181
|
+
let r;
|
|
182
|
+
try {
|
|
183
|
+
r = spawnSync(command, args, {
|
|
184
|
+
cwd: root, env: extraEnv, encoding: 'utf8', timeout: timeoutS * 1000, killSignal: 'SIGTERM', maxBuffer: 64 * 1024 * 1024,
|
|
185
|
+
});
|
|
186
|
+
} catch (error) {
|
|
187
|
+
return { failed: `起不来 ${path.basename(command)}:${error.message}` };
|
|
188
|
+
}
|
|
189
|
+
if (r.error && r.error.code === 'ETIMEDOUT') return { failed: `超过 ${timeoutS} 秒没返回` };
|
|
190
|
+
if (r.error) return { failed: `没跑起来:${r.error.message}` };
|
|
191
|
+
return { status: r.status, stdout: r.stdout || '', stderr: r.stderr || '' };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function planZcode(prompt) {
|
|
195
|
+
const z = findZcode(env);
|
|
196
|
+
if (z.problem) return z;
|
|
197
|
+
const base = [...(z.viaNode ? [z.command] : []), '--cwd', root, '--mode', mode];
|
|
198
|
+
return {
|
|
199
|
+
command: z.viaNode ? process.execPath : z.command,
|
|
200
|
+
env,
|
|
201
|
+
withSession: (sid) => [...base, ...(sid ? ['--resume', sid] : []), '--no-color', '--json', '-p', prompt],
|
|
202
|
+
parse: (stdout) => {
|
|
203
|
+
let out;
|
|
204
|
+
try {
|
|
205
|
+
out = JSON.parse(stdout);
|
|
206
|
+
} catch {
|
|
207
|
+
return { failed: `输出不是 JSON:${tail(stdout)}` };
|
|
208
|
+
}
|
|
209
|
+
if (!out || typeof out.response !== 'string') return { failed: '输出里没有 response' };
|
|
210
|
+
return { reply: out.response, sessionId: typeof out.sessionId === 'string' ? out.sessionId : '' };
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// dsh:用 headless 模式答一句就退出。工作目录就是当前目录,所以 tsx 用绝对路径导入;回答在 --json 事件的 final 里。
|
|
216
|
+
// 模型和凭据跟着 DSH 桌面应用里的配置走。plan → read-only,edit → workspace-write,别的值原样传给它
|
|
217
|
+
function planDsh(prompt, stateDir) {
|
|
218
|
+
const d = findDsh(env);
|
|
219
|
+
if (d.problem) return d;
|
|
220
|
+
const entries = readDshPatchEntries(d.home);
|
|
221
|
+
if (entries.problem) return entries;
|
|
222
|
+
const patchFile = path.join(stateDir, 'dsh-headless.patch.yml');
|
|
223
|
+
fs.mkdirSync(stateDir, { recursive: true });
|
|
224
|
+
fs.writeFileSync(patchFile, [...entries.lines, ''].join('\n'));
|
|
225
|
+
const permission = { plan: 'read-only', edit: 'workspace-write' }[mode] || mode;
|
|
226
|
+
const base = ['--import', `file://${d.tsx}`, d.cli, '--profile', 'headless', '--patch', patchFile, '--permission-mode', permission];
|
|
227
|
+
return {
|
|
228
|
+
command: d.node,
|
|
229
|
+
env: { ...env, ELECTRON_RUN_AS_NODE: '1', DSH_HOME: d.home },
|
|
230
|
+
withSession: (sid) => [...base, ...(sid ? ['--session-id', sid] : []), '--json', prompt],
|
|
231
|
+
parse: parseDsh,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function run(message, { session = '', onSessionLost = () => {}, stateDir = path.join(root, '01-inbox', '_bot') } = {}) {
|
|
236
|
+
const started = Date.now();
|
|
237
|
+
const secs = () => Math.round((Date.now() - started) / 1000);
|
|
238
|
+
if (kind === 'custom') {
|
|
239
|
+
// 自定义命令:按空白拆开,消息作为最后一个参数传过去,不会被当成命令的一部分
|
|
240
|
+
const [command, ...base] = splitCommand(name);
|
|
241
|
+
const r = runProcess(command, [...base, message], env);
|
|
242
|
+
if (r.failed) return r;
|
|
243
|
+
if (r.status !== 0) return { failed: `退出码 ${r.status}:${tail(r.stderr)}` };
|
|
244
|
+
const reply = r.stdout.trim();
|
|
245
|
+
log('agent 完成', `${secs()}s 自定义命令`);
|
|
246
|
+
return reply ? { reply } : { failed: '它没有输出任何回复' };
|
|
247
|
+
}
|
|
248
|
+
const prompt = preamble ? `${message}\n\n${preamble}` : message;
|
|
249
|
+
const plan = kind === 'zcode' ? planZcode(prompt) : planDsh(prompt, stateDir);
|
|
250
|
+
if (plan.problem) return { failed: plan.problem, config: true }; // 配置问题:调用方按「没配置好」处理
|
|
251
|
+
let used = session;
|
|
252
|
+
let r = runProcess(plan.command, plan.withSession(used), plan.env);
|
|
253
|
+
if (!r.failed && r.status !== 0 && used) {
|
|
254
|
+
log('agent 接不上旧会话,改开新会话', `rc=${r.status}`);
|
|
255
|
+
onSessionLost();
|
|
256
|
+
used = '';
|
|
257
|
+
r = runProcess(plan.command, plan.withSession(''), plan.env);
|
|
258
|
+
}
|
|
259
|
+
if (r.failed) return r;
|
|
260
|
+
if (r.status !== 0) return { failed: `退出码 ${r.status}:${tail(r.stderr)}` };
|
|
261
|
+
const out = plan.parse(r.stdout);
|
|
262
|
+
if (out.failed) return out;
|
|
263
|
+
log('agent 完成', `${secs()}s ${kind} mode=${mode} session=${used ? '续' : '新'}`);
|
|
264
|
+
return out.reply.trim() ? { reply: out.reply.trim(), sessionId: out.sessionId || '' } : { failed: '它回了空内容' };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return { kind, run, doctor };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
module.exports = { createAgent, splitCommand };
|