work-rhythm 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/.agents/notes/AGENTS.md +86 -0
  2. package/.agents/notes/decisions/2026-11-28-long-term-goals-ride-existing-tasks.md +36 -0
  3. package/.agents/notes/decisions/2026-11-29-building-a-workdir-means-cloning-the-template.md +25 -0
  4. package/.agents/notes/decisions/2026-11-29-find-workdir-cwd-first-then-registered.md +32 -0
  5. package/.agents/notes/decisions/2026-11-30-bot-inbound-uses-websocket-and-a-responder-command.md +48 -0
  6. package/.agents/notes/decisions/2026-11-30-cost-entry-writes-into-empty-cells-directly.md +25 -0
  7. package/.agents/notes/decisions/2026-11-30-dependencies-are-allowed-user-installs-missing-ones.md +30 -0
  8. package/.agents/notes/decisions/2026-11-30-markdown-is-the-record-html-is-only-a-view.md +25 -0
  9. package/.agents/notes/decisions/2026-11-30-message-channels-are-preset-in-the-skill.md +34 -0
  10. package/.agents/notes/decisions/2026-11-30-no-workdir-offers-to-create-one-by-default.md +35 -0
  11. package/.agents/notes/decisions/2026-11-30-paging-requires-coverage-only-when-enabled.md +27 -0
  12. package/.agents/notes/decisions/2026-11-30-pending-decisions-asked-in-a-chat-and-logged-briefly.md +39 -0
  13. package/.agents/notes/decisions/2026-11-30-push-via-personal-robot-webhook.md +33 -0
  14. package/.agents/notes/decisions/2026-11-30-scheduling-moves-to-a-local-service.md +37 -0
  15. package/.agents/notes/decisions/2026-11-30-skill-ships-with-its-template-in-a-zip.md +30 -0
  16. package/.agents/notes/decisions/2026-11-30-skill-stays-generic-user-provides-cli-or-mcp.md +25 -0
  17. package/.agents/notes/decisions/2026-12-01-everything-is-js-behind-work-rhythm.md +46 -0
  18. package/.agents/notes/decisions/2026-12-01-repo-is-not-a-workdir-templates-hold-workdir-files.md +29 -0
  19. package/.agents/notes/decisions/2026-12-01-repo-stays-generic-personal-data-lives-in-workdirs.md +32 -0
  20. package/.agents/notes/decisions/2026-12-01-workdir-is-not-a-git-repository.md +25 -0
  21. package/.agents/notes/pitfalls/2026-11-29-do-not-hand-roll-git-log.md +22 -0
  22. package/.agents/notes/pitfalls/2026-11-29-empty-or-partial-collector-output.md +23 -0
  23. package/.agents/notes/pitfalls/2026-11-29-skill-description-is-truncated.md +21 -0
  24. package/.agents/notes/pitfalls/2026-11-29-tool-shell-is-zsh.md +24 -0
  25. package/.agents/notes/pitfalls/2026-11-30-compare-timestamps-as-digits.md +22 -0
  26. package/.agents/notes/pitfalls/2026-11-30-message-search-lags-after-sending.md +18 -0
  27. package/.agents/notes/pitfalls/2026-11-30-rewriting-a-file-with-empty-output-after-tool-failure.md +20 -0
  28. package/.agents/notes/pitfalls/2026-11-30-secret-scan-false-positive-on-hyphenated-file-names.md +18 -0
  29. package/.agents/notes/pitfalls/2026-11-30-selftest-must-not-inherit-local-config.md +29 -0
  30. package/.agents/notes/pitfalls/2026-11-30-yzj-cli-list-limit-is-20.md +25 -0
  31. package/.agents/notes/pitfalls/2026-11-30-zsh-no-word-splitting-special-names.md +23 -0
  32. package/.agents/notes/pitfalls/2026-12-01-node-test-hooks-cannot-register-after-callbacks.md +22 -0
  33. package/.agents/notes/pitfalls/2026-12-01-spawning-node-test-inside-a-test-runs-nothing.md +18 -0
  34. package/.agents/skills/work-rhythm/SKILL.md +278 -0
  35. package/AGENTS.md +19 -0
  36. package/README.md +69 -2
  37. package/collectors/approval-yzj.js +114 -0
  38. package/collectors/calendar-yzj.js +48 -0
  39. package/collectors/file-activity.js +131 -0
  40. package/collectors/git-activity.js +105 -0
  41. package/collectors/im-yzj.js +151 -0
  42. package/collectors/linky-issues.js +88 -0
  43. package/collectors/local.env.example +52 -0
  44. package/docs/channels.md +95 -0
  45. package/docs/formats.md +285 -0
  46. package/docs/im-adapters.md +79 -0
  47. package/docs/scheduled-tasks.md +115 -0
  48. package/docs/sources.md +104 -0
  49. package/package.json +35 -4
  50. package/scripts/cli.js +101 -0
  51. package/scripts/cmd/check.js +330 -0
  52. package/scripts/cmd/collect.js +25 -0
  53. package/scripts/cmd/decisions.js +236 -0
  54. package/scripts/cmd/goals.js +145 -0
  55. package/scripts/cmd/init.js +49 -0
  56. package/scripts/cmd/listen.js +91 -0
  57. package/scripts/cmd/notify.js +42 -0
  58. package/scripts/cmd/pack.js +104 -0
  59. package/scripts/cmd/rhythm.js +102 -0
  60. package/scripts/cmd/selftest.js +23 -0
  61. package/scripts/cmd/sync.js +73 -0
  62. package/scripts/cmd/today.js +29 -0
  63. package/scripts/cmd/workdir.js +81 -0
  64. package/scripts/lib/agent.js +270 -0
  65. package/scripts/lib/bot.js +376 -0
  66. package/scripts/lib/collector.js +74 -0
  67. package/scripts/lib/config.js +250 -0
  68. package/scripts/lib/launchd.js +82 -0
  69. package/scripts/lib/log.js +22 -0
  70. package/scripts/lib/markdown.js +208 -0
  71. package/scripts/lib/notify.js +43 -0
  72. package/scripts/lib/rhythm.js +508 -0
  73. package/scripts/lib/robot.js +64 -0
  74. package/scripts/lib/run.js +151 -0
  75. package/scripts/lib/template.js +149 -0
  76. package/scripts/lib/workdir.js +98 -0
  77. package/scripts/test/check.test.js +279 -0
  78. package/scripts/test/collectors.test.js +574 -0
  79. package/scripts/test/config.test.js +118 -0
  80. package/scripts/test/decisions.test.js +129 -0
  81. package/scripts/test/fake-webhook.js +31 -0
  82. package/scripts/test/goals.test.js +109 -0
  83. package/scripts/test/harness.js +277 -0
  84. package/scripts/test/init.test.js +123 -0
  85. package/scripts/test/listen.test.js +362 -0
  86. package/scripts/test/notify.test.js +176 -0
  87. package/scripts/test/pack.test.js +141 -0
  88. package/scripts/test/rhythm.test.js +333 -0
  89. package/scripts/test/stubs.js +140 -0
  90. package/scripts/test/today.test.js +73 -0
  91. package/scripts/test/workdir.test.js +152 -0
  92. package/scripts/work-rhythm.js +18 -0
  93. package/tasks/alerts-morning.md +24 -0
  94. package/tasks/carryover.md +16 -0
  95. package/tasks/daily-plan.md +29 -0
  96. package/tasks/evening-review.md +27 -0
  97. package/tasks/linky-cost-check.md +13 -0
  98. package/tasks/linky-cost-fill.md +20 -0
  99. package/tasks/noon-checkin.md +15 -0
  100. package/tasks/weekly-rhythm.md +18 -0
  101. package/templates/00-config/profile.example.yaml +54 -0
  102. package/templates/00-config/sources.yaml +115 -0
  103. package/templates/03-carryover/CARRYOVER.md +14 -0
  104. package/templates/03-carryover/DECISIONS.md +10 -0
  105. package/templates/04-patterns/WORK_RHYTHM.md +16 -0
  106. package/templates/AGENTS.md +31 -0
  107. package/templates/README.md +73 -0
@@ -0,0 +1,102 @@
1
+ // work-rhythm 本地服务:定时采集、定时整理、推送、看页面,都由这一个常驻进程管,不再依赖 agent 运行时的定时器。
2
+ // 实现在 lib/rhythm.js,这里只管子命令、输出和退出码。
3
+ // 配置:
4
+ // profile.yaml 的 schedule 各任务的时间(已有的那一节);任务的指令在 tasks/<id>.md,一个任务一个文件
5
+ // profile.yaml 的 rhythm 采集的时间 sync、网页端口 port、推送开关 push、不推送的任务 quiet
6
+ // collectors/local.env YZJ_BOT_AGENT 让哪个 agent 整理(同值守:dsh、zcode,或一条命令)
7
+ // 推送走消息渠道(work-rhythm notify),所以 preferences.notify 要配好。任务要写文件,agent 以可写工作目录的权限跑。
8
+ // 说明见 docs/scheduled-tasks.md。
9
+ 'use strict';
10
+ const { EXIT, Fail, UsageError } = require('../lib/run');
11
+ const { settings } = require('../lib/config');
12
+ const { createRhythm } = require('../lib/rhythm');
13
+
14
+ const USAGE = `用法: work-rhythm rhythm <子命令>
15
+ start [--tick 秒] 前台跑:到点跑采集和任务,起网页服务。要常驻用 install;--tick 是多久看一次表(默认 20,调试用)
16
+ stop | status 停掉;看在不在跑、下次什么时候跑什么
17
+ due [--at 时间] [--days 天数] 从某个时间起,列出什么时候跑什么
18
+ run <任务id|sync> [--push] 立刻跑一次,不等时间;带 --push 才推送
19
+ serve [--port 端口] 只起网页服务
20
+ render <文件.md> 把一份 Markdown 渲染成页面,打到标准输出(自测、调试用)
21
+ doctor 检查配置和依赖,有问题逐条报出来
22
+ install | uninstall macOS launchd 常驻:开机自启、挂了拉起
23
+ 退出码: 0 完成;2 用法不对;3 没配置好;4 缺依赖;5 运行失败。详见 lib/rhythm.js 的文件头和 docs/scheduled-tasks.md`;
24
+
25
+ const positiveInt = (value, fallback) => {
26
+ const n = Number(value);
27
+ return Number.isInteger(n) && n > 0 ? n : fallback;
28
+ };
29
+
30
+ module.exports = {
31
+ usage: USAGE,
32
+ async run(args, ctx) {
33
+ const { root, stdout, env, packageRoot } = ctx;
34
+ const [cmd, ...rest] = args;
35
+ const service = createRhythm({ root, env: settings(root, env), packageRoot });
36
+ switch (cmd) {
37
+ case 'start': {
38
+ const tick = rest.length === 2 && rest[0] === '--tick' ? positiveInt(rest[1], 0) : rest.length === 0 ? 20 : 0;
39
+ if (!tick) throw new UsageError(USAGE);
40
+ return service.start({ tickMs: tick * 1000 });
41
+ }
42
+ case 'serve':
43
+ if (!(rest.length === 0 || (rest.length === 2 && rest[0] === '--port'))) throw new UsageError(USAGE);
44
+ return service.serve(rest.length ? Number(rest[1]) : service.cfg.port);
45
+ case 'stop':
46
+ if (rest.length) throw new UsageError(USAGE);
47
+ stdout.write(`${service.stop()}\n`);
48
+ return EXIT.OK;
49
+ case 'status':
50
+ if (rest.length) throw new UsageError(USAGE);
51
+ stdout.write(`${service.statusText()}\n`);
52
+ return EXIT.OK;
53
+ case 'due': {
54
+ let at = new Date();
55
+ let days = 1;
56
+ for (let i = 0; i < rest.length; i += 1) {
57
+ if (rest[i] === '--at' && rest[i + 1]) {
58
+ const d = new Date(rest[i + 1].replace(' ', 'T'));
59
+ if (Number.isNaN(d.getTime())) throw new UsageError('--at 后面写「YYYY-MM-DD HH:MM」');
60
+ at = d;
61
+ i += 1;
62
+ } else if (rest[i] === '--days' && rest[i + 1]) {
63
+ days = positiveInt(rest[i + 1], 1);
64
+ i += 1;
65
+ } else throw new UsageError(USAGE);
66
+ }
67
+ stdout.write(`${service.due(at, days)}\n`);
68
+ return EXIT.OK;
69
+ }
70
+ case 'run': {
71
+ const id = rest[0];
72
+ if (!id || rest.slice(1).some((a) => a !== '--push')) throw new UsageError(USAGE);
73
+ return service.runJob(id, rest.includes('--push'));
74
+ }
75
+ case 'render':
76
+ if (rest.length !== 1) throw new UsageError(USAGE);
77
+ stdout.write(service.render(rest[0]));
78
+ return EXIT.OK;
79
+ case 'doctor': {
80
+ if (rest.length) throw new UsageError(USAGE);
81
+ const problems = service.doctorProblems();
82
+ if (problems.length) stdout.write(`${problems.join('\n')}\n`);
83
+ return problems.length ? 1 : EXIT.OK;
84
+ }
85
+ case 'install': {
86
+ if (rest.length) throw new UsageError(USAGE);
87
+ const problems = service.doctorProblems();
88
+ if (problems.length) throw new Fail(EXIT.NOT_CONFIGURED, `配置有问题,先解决:\n${problems.join('\n')}`);
89
+ const plist = service.launchd.install();
90
+ stdout.write(`已装成常驻:${plist}\n页面:${service.baseUrl()} 日志:${root}/01-inbox/_rhythm.log\n`);
91
+ return EXIT.OK;
92
+ }
93
+ case 'uninstall':
94
+ if (rest.length) throw new UsageError(USAGE);
95
+ service.launchd.uninstall();
96
+ stdout.write('已卸载常驻。\n');
97
+ return EXIT.OK;
98
+ default:
99
+ throw new UsageError(USAGE);
100
+ }
101
+ },
102
+ };
@@ -0,0 +1,23 @@
1
+ // 自测:跑 scripts/test/ 下的用例(node --test),二十秒左右。改完脚本、发包之前跑一遍。
2
+ // 用法: work-rhythm selftest [传给 node --test 的参数,例如 --test-name-pattern=notify]
3
+ // 退出码就是 node --test 的:0 全过
4
+ 'use strict';
5
+ const path = require('node:path');
6
+ const { spawnSync } = require('node:child_process');
7
+ const { UsageError } = require('../lib/run');
8
+
9
+ const USAGE = '用法: work-rhythm selftest [传给 node --test 的参数]';
10
+
11
+ module.exports = {
12
+ usage: USAGE,
13
+ async run(args, ctx) {
14
+ for (const a of args) {
15
+ if (!a.startsWith('-')) throw new UsageError(USAGE);
16
+ }
17
+ // 自己就是在 node --test 里被调起来的时候(用例里跑自测),要抹掉 node 留下的标记,否则它会当成递归调用、一个用例都不跑
18
+ const env = { ...ctx.env };
19
+ delete env.NODE_TEST_CONTEXT;
20
+ const r = spawnSync(process.execPath, ['--test', '--test-reporter=spec', ...args, path.join(ctx.packageRoot, 'scripts', 'test')], { cwd: ctx.packageRoot, env, stdio: 'inherit' });
21
+ return r.status === null ? 5 : r.status;
22
+ },
23
+ };
@@ -0,0 +1,73 @@
1
+ // 同步订阅源:依次运行 00-config/sources.yaml 里已启用源的采集器,原始数据落 01-inbox/<源>/<今天>/
2
+ // 用法: work-rhythm sync [起始日期 YYYY-MM-DD,默认今天] [源 id …(默认全部已启用的源)]
3
+ // 日志:01-inbox/_sync.log。退出码等于失败的源数
4
+ 'use strict';
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const { EXIT, run: spawn, today, fmtStamp, isExecutable } = require('../lib/run');
8
+ const { loadSources } = require('../lib/config');
9
+
10
+ // collector 字段的两种写法:内置采集器写 id(如 im-yzj),自己写的写工作目录里的路径。
11
+ // 返回能直接运行的文件路径;找不到返回空串
12
+ function resolveCollector(root, packageRoot, collector) {
13
+ const spec = String(collector || '').trim();
14
+ if (!spec) return '';
15
+ const isPath = /[\\/]/.test(spec) || /\.(sh|py|bash|zsh|js|mjs|cjs)$/.test(spec);
16
+ const file = isPath ? path.resolve(root, spec) : path.join(packageRoot, 'collectors', `${spec}.js`);
17
+ return fs.existsSync(file) ? file : '';
18
+ }
19
+
20
+ // 有可执行权限的直接运行(采集器可以用任何语言写);.js 用当前这个 node 跑;其余按 bash 脚本运行。
21
+ // timeout 是最多等几秒,到了就杀掉
22
+ function spawnCollector(file, args, { cwd, env, input, timeout }) {
23
+ if (/\.(js|mjs|cjs)$/.test(file)) return spawn(process.execPath, [file, ...args], { cwd, env, input, timeout });
24
+ if (isExecutable(file)) return spawn(file, args, { cwd, env, input, timeout });
25
+ return spawn('bash', [file, ...args], { cwd, env, input, timeout });
26
+ }
27
+
28
+ // deadlineMs 给了的话,整轮采集到这个时间戳为止:每个采集器最多等剩下的秒数,到了还没完就算它失败
29
+ async function run(args, ctx, { deadlineMs } = {}) {
30
+ const { root, stdout, stderr, env, packageRoot } = ctx;
31
+ const sourcesFile = path.join(root, '00-config', 'sources.yaml');
32
+ if (!fs.existsSync(sourcesFile)) {
33
+ stderr.write('sync: 找不到 00-config/sources.yaml\n');
34
+ return EXIT.USAGE;
35
+ }
36
+ const date = today();
37
+ const since = args[0] || date;
38
+ const wanted = args.length ? args.slice(1) : [];
39
+ const log = path.join(root, '01-inbox', '_sync.log');
40
+ fs.mkdirSync(path.dirname(log), { recursive: true });
41
+ fs.appendFileSync(log, `${fmtStamp()} sync 开始 since=${since}\n`);
42
+ const sources = loadSources(root).filter((s) => s.enabled && s.collector !== 'none');
43
+ let fail = 0;
44
+ let ran = 0;
45
+ for (const src of sources) {
46
+ if (wanted.length && !wanted.includes(src.id)) continue;
47
+ const collector = resolveCollector(root, packageRoot, src.collector);
48
+ if (!collector) {
49
+ fs.appendFileSync(log, `${fmtStamp()} ${src.id} 的采集脚本不存在: ${src.collector}\n`);
50
+ stdout.write(`FAIL ${src.id}(采集脚本不存在: ${src.collector})\n`);
51
+ fail += 1;
52
+ continue;
53
+ }
54
+ ran += 1;
55
+ // 采集器的输出目录和筛选都用源 id,不用脚本的文件名:几个源可以共用一个采集脚本
56
+ const budget = deadlineMs ? Math.max(1, Math.ceil((deadlineMs - Date.now()) / 1000)) : undefined;
57
+ const r = spawnCollector(collector, [path.join('01-inbox', src.id, date), since], { cwd: root, env: { ...env, WORK_RHYTHM_ROOT: root }, timeout: budget });
58
+ fs.appendFileSync(log, `${r.stdout}${r.stdout && !r.stdout.endsWith('\n') ? '\n' : ''}${r.stderr}`);
59
+ if (r.timedOut) fs.appendFileSync(log, `${fmtStamp()} ${src.id} 超过 ${budget} 秒没跑完\n`);
60
+ if (r.code === 0) {
61
+ fs.appendFileSync(log, `${fmtStamp()} ${src.id} ok\n`);
62
+ stdout.write(`ok ${src.id}\n`);
63
+ } else {
64
+ fs.appendFileSync(log, `${fmtStamp()} ${src.id} 失败\n`);
65
+ stdout.write(`FAIL ${src.id}(详见 01-inbox/_sync.log)\n`);
66
+ fail += 1;
67
+ }
68
+ }
69
+ if (!ran) stdout.write('sync: 没有可运行的源(看 00-config/sources.yaml 里的 enabled)\n');
70
+ return fail;
71
+ }
72
+
73
+ module.exports = { usage: '用法: work-rhythm sync [起始日期] [源 id …]', run, resolveCollector, spawnCollector };
@@ -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 };