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,131 @@
1
+ #!/usr/bin/env node
2
+ // 采集文件活动:列出 WORKSPACES 下自起始日起被修改的文件,按项目(工作区下的一级目录)和扩展名汇总
3
+ // 用法: node collectors/file-activity.js <输出目录> [起始日期 YYYY-MM-DD,默认今天]
4
+ // 输出: <输出目录>/summary.tsv(项目、文件数、主要扩展名、备注)和 files.txt(命中文件,最多 MAX_FILES 条)
5
+ // macOS 上优先用 Spotlight(快);索引有延迟或目录没被索引时,用逐层扫描补上或复核
6
+ // 配置: collectors/local.env 的 FILE_ACTIVITY_WORKSPACES(扫哪些目录,| 分隔;默认 ~/workspace)、
7
+ // FILE_ACTIVITY_IGNORE_EXTS(不关心的扩展名,| 分隔)
8
+ 'use strict';
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const { EXIT, run, which, startOfDay, walkFiles } = require('../scripts/lib/run');
12
+ const { context, writeTsv } = require('../scripts/lib/collector');
13
+
14
+ const MAX_FILES = 300;
15
+ // 不关心的目录:版本库、依赖、构建产物、IDE 配置
16
+ const PRUNE = '.git node_modules dist build target out .venv venv .next .nuxt __pycache__ .cache .turbo coverage .pytest_cache .idea .vscode'.split(' ');
17
+ const DEFAULT_IGNORE = '.jsonl|.log|.map|.tsbuildinfo|.lock|.pid|.db|.sqlite|.gz|.zip|.tar|.bak|.tmp';
18
+ // 一个项目一天内改动的文件超过这个数,多半是运行或测试产物,而不是手改
19
+ const NOISE_THRESHOLD = 150;
20
+
21
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
22
+ const isDir = (p) => {
23
+ try {
24
+ return fs.statSync(p).isDirectory();
25
+ } catch {
26
+ return false;
27
+ }
28
+ };
29
+
30
+ async function collect(argv) {
31
+ const ctx = context(argv, 'file-activity', 'file-activity.js <输出目录> [起始日期]');
32
+ const { out, since, env, home } = ctx;
33
+ const workspaces = (env.FILE_ACTIVITY_WORKSPACES || path.join(home, 'workspace')).split('|').map((s) => s.trim()).filter(Boolean);
34
+ const ignoreExts = (env.FILE_ACTIVITY_IGNORE_EXTS || DEFAULT_IGNORE).split('|').map((s) => s.trim()).filter(Boolean);
35
+ const prune = new Set(PRUNE);
36
+ const pruned = new RegExp(`[/\\\\](${PRUNE.map(escapeRe).join('|')})([/\\\\]|$)`);
37
+ const sinceMs = startOfDay(since);
38
+ const recentMs = Date.now() - 30 * 60 * 1000;
39
+ const spotlight = which('mdfind', env) && which('mdls', env) ? which('mdfind', env) : '';
40
+
41
+ const files = [];
42
+ const counted = [];
43
+ let fast = 0;
44
+ let slow = 0;
45
+ let recheck = 0;
46
+ for (let ws of workspaces) {
47
+ if (!isDir(ws)) continue;
48
+ ws = ws.replace(/\/+$/, '');
49
+ // 工作区本身就是一个仓库时整个目录算一个项目;否则它下面的一级目录各算一个项目
50
+ const single = fs.existsSync(path.join(ws, '.git'));
51
+ const scan = (from) => walkFiles(ws, prune, from).filter((f) => !pruned.test(f)).sort();
52
+ let hits;
53
+ // 目录是不是被 Spotlight 索引:mdls 对没索引的目录回 (null)
54
+ const indexed = spotlight && run('mdls', ['-raw', '-name', 'kMDItemFSContentChangeDate', ws], { env }).stdout.trim() !== '(null)';
55
+ if (indexed) {
56
+ fast += 1;
57
+ // Spotlight 快,但有两处靠不住:索引有延迟,刚改的文件可能还没进去;目录没被索引时它不报错,
58
+ // 只是什么都不返回。所以最近 30 分钟改动的文件用逐层扫描补上,两路结果去重;它什么都没返回时整个改用逐层扫描。
59
+ // 查询串里的 $time 是 Spotlight 自己的语法,前面不能有反斜杠(bash 里要写 \$ 是为了不让 shell 展开;这里不经过 shell)
60
+ const found = run(spotlight, ['-onlyin', ws, `kMDItemFSContentChangeDate >= $time.iso(${since}) && kMDItemContentTypeTree != 'public.folder'`], { env })
61
+ .stdout.split('\n').filter(Boolean);
62
+ hits = [...new Set([...found, ...walkFiles(ws, prune, recentMs)])].filter((f) => !pruned.test(f)).sort();
63
+ if (!hits.length) {
64
+ recheck += 1;
65
+ hits = scan(sinceMs);
66
+ }
67
+ } else {
68
+ slow += 1;
69
+ hits = scan(sinceMs);
70
+ }
71
+ for (const f of hits) {
72
+ const dot = f.lastIndexOf('.');
73
+ const ext = dot >= 0 ? f.slice(dot) : '';
74
+ if (!/\/\.DS_Store$/.test(f) && !ignoreExts.includes(ext)) files.push(f);
75
+ }
76
+ if (!hits.length) continue;
77
+ // 项目 = 工作区下的一级目录;扩展名 = 文件名最后一个点之后(没有则记「无」)
78
+ const base = `${ws}/`;
79
+ const wsName = path.basename(ws);
80
+ for (const f of hits) {
81
+ const rel = f.startsWith(base) ? f.slice(base.length) : path.basename(f);
82
+ const fname = rel.slice(rel.lastIndexOf('/') + 1);
83
+ if (fname === '.DS_Store') continue;
84
+ const dot = fname.lastIndexOf('.');
85
+ const ext = dot > 0 ? fname.slice(dot).toLowerCase() : '(无)'; // 以点开头的文件名不算有扩展名
86
+ if (ignoreExts.includes(ext)) continue;
87
+ const proj = single || !rel.includes('/') ? wsName : `${wsName}/${rel.split('/')[0]}`;
88
+ counted.push([proj, ext]);
89
+ }
90
+ }
91
+
92
+ // 先数出「项目 × 扩展名」的条数,再按项目合并成一行,扩展名只留前三
93
+ const counts = new Map();
94
+ for (const [proj, ext] of counted) {
95
+ const key = `${proj}\t${ext}`;
96
+ counts.set(key, (counts.get(key) || 0) + 1);
97
+ }
98
+ const entries = [...counts.entries()].map(([key, n]) => {
99
+ const [proj, ext] = key.split('\t');
100
+ return { proj, ext, n };
101
+ }).sort((a, b) => (a.proj < b.proj ? -1 : a.proj > b.proj ? 1 : b.n - a.n));
102
+ const rows = [];
103
+ let cur = null;
104
+ for (const e of entries) {
105
+ if (!cur || cur.proj !== e.proj) {
106
+ cur = { proj: e.proj, total: 0, tops: [], n: 0 };
107
+ rows.push(cur);
108
+ }
109
+ cur.total += e.n;
110
+ cur.n += 1;
111
+ if (cur.n <= 3) cur.tops.push(`${e.ext} ${e.n}`);
112
+ }
113
+ const table = rows.map((r) => [r.proj, String(r.total), r.tops.join(' '), r.total > NOISE_THRESHOLD ? '文件数异常多,多半是运行或构建产物' : '']);
114
+ fs.mkdirSync(out, { recursive: true });
115
+ writeTsv(path.join(out, 'summary.tsv'), ['project', 'files', 'top_extensions', 'note'], table);
116
+ fs.writeFileSync(path.join(out, 'files.txt'), `${files.slice(0, MAX_FILES).join('\n')}${files.length ? '\n' : ''}`);
117
+ ctx.note(`自 ${since} 起 ${counted.length} 个文件改动,涉及 ${table.length} 个项目(Spotlight ${fast} 个目录,其中 ${recheck} 个没返回结果、已改用逐层扫描复核;逐层扫描 ${slow} 个目录)`);
118
+ return EXIT.OK;
119
+ }
120
+
121
+ module.exports = { collect };
122
+
123
+ if (require.main === module) {
124
+ collect(process.argv.slice(2)).then(
125
+ (code) => process.exit(code),
126
+ (error) => {
127
+ process.stderr.write(`file-activity: ${error && error.stack ? error.stack : String(error)}\n`);
128
+ process.exit(error && error.name === 'UsageError' ? EXIT.USAGE : EXIT.FAILED);
129
+ },
130
+ );
131
+ }
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ // 采集「我」的代码提交:遍历 WORKSPACES 下的 git 仓库,导出自起始日 00:00 以来我写的提交
3
+ // 子模块算在内,别的仓库的 worktree 不算(它的提交已经包含在主仓库里)
4
+ // 用法: node collectors/git-activity.js <输出目录> [起始日期 YYYY-MM-DD,默认今天]
5
+ // 输出: <输出目录>/commits.tsv —— 时间、仓库、短哈希、说明首行,按时间排序,同一提交只保留一行
6
+ // 旧提交被 rebase / cherry-pick 重新提交时不逐条列出,只压成一行汇总
7
+ // 配置: collectors/local.env 的 GIT_ACTIVITY_WORKSPACES(扫哪些目录,| 分隔;默认 ~/workspace)、
8
+ // GIT_ACTIVITY_AUTHORS(哪些邮箱或姓名算「我」,| 分隔;默认取全局 git 配置)
9
+ 'use strict';
10
+ const fs = require('node:fs');
11
+ const path = require('node:path');
12
+ const { EXIT, run } = require('../scripts/lib/run');
13
+ const { context, needTool, writeTsv } = require('../scripts/lib/collector');
14
+
15
+ const listDir = (dir) => {
16
+ try {
17
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(dir, d.name)).sort();
18
+ } catch {
19
+ return [];
20
+ }
21
+ };
22
+
23
+ // 按作者时间排,同一时间按仓库名排(字节序),和原来 LC_ALL=C sort 一致
24
+ const byTimeThenRepo = (a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[2] < b[2] ? -1 : a[2] > b[2] ? 1 : 0);
25
+
26
+ async function collect(argv) {
27
+ const ctx = context(argv, 'git-activity', 'git-activity.js <输出目录> [起始日期]');
28
+ const { out, since, env, home } = ctx;
29
+ const workspaces = (env.GIT_ACTIVITY_WORKSPACES || path.join(home, 'workspace')).split('|');
30
+ // 「我」= 全局 git 身份;公司邮箱等其它身份在 collectors/local.env 的 GIT_ACTIVITY_AUTHORS 里追加
31
+ let authors = env.GIT_ACTIVITY_AUTHORS;
32
+ if (authors === undefined) {
33
+ const email = run('git', ['config', '--global', 'user.email'], { env }).stdout.trim();
34
+ const name = run('git', ['config', '--global', 'user.name'], { env }).stdout.trim();
35
+ authors = `${email}|${name}`;
36
+ }
37
+ if (!needTool(ctx, 'git')) return EXIT.MISSING_DEP;
38
+ const authorList = authors.split('|').map((a) => a.trim()).filter(Boolean);
39
+ if (!authorList.length) {
40
+ ctx.note('无法确定作者身份,请在 collectors/local.env 设置 GIT_ACTIVITY_AUTHORS');
41
+ return EXIT.NOT_CONFIGURED;
42
+ }
43
+
44
+ const rows = [];
45
+ for (const ws of workspaces) {
46
+ if (!fs.existsSync(ws) || !fs.statSync(ws).isDirectory()) continue;
47
+ for (const repo of listDir(ws)) {
48
+ // .git 是目录的是主仓库。.git 是文件的有两种:子模块,和别的仓库的 worktree。
49
+ // worktree 的提交已经包含在主仓库的 --all 里,再数一遍就重复了,所以看它的 git 目录落在哪:
50
+ // 落在某个 .git/worktrees/ 下的是 worktree,跳过;其余的(例如父仓库的 .git/modules/<名字>)是子模块,算进来。
51
+ // 要扫到子模块,把它的上一层目录也列进 GIT_ACTIVITY_WORKSPACES,例如 "$HOME/workspace|$HOME/workspace/minutes"。
52
+ const dotGit = path.join(repo, '.git');
53
+ if (!fs.existsSync(dotGit)) continue;
54
+ if (!fs.statSync(dotGit).isDirectory()) {
55
+ const gitdir = run('git', ['-C', repo, 'rev-parse', '--absolute-git-dir'], { env }).stdout.trim();
56
+ if (!gitdir || /[/\\]\.git[/\\]worktrees[/\\]/.test(gitdir)) continue;
57
+ }
58
+ const name = path.basename(repo);
59
+ const authorArgs = authorList.map((a) => `--author=${a}`);
60
+ const log = run('git', ['-C', repo, 'log', '--all', ...authorArgs, `--since=${since} 00:00:00`, '--date=format-local:%F %T', `--pretty=format:%ad%x09%cd%x09${name}%x09%h%x09%s`], { env });
61
+ // 列:作者时间、提交时间、仓库、哈希、说明。按作者时间算「哪天写的」;
62
+ // 作者时间早于起始日但提交时间在之后的,是被重新提交的旧提交,按仓库压成一行。
63
+ for (const line of log.stdout.split('\n')) {
64
+ const f = line.split('\t');
65
+ if (f.length >= 5) rows.push(f);
66
+ }
67
+ }
68
+ }
69
+
70
+ rows.sort(byTimeThenRepo);
71
+ const seen = new Set();
72
+ const kept = [];
73
+ const carried = new Map();
74
+ for (const f of rows) {
75
+ if (seen.has(f[3])) continue;
76
+ seen.add(f[3], 1);
77
+ if (f[0] >= `${since} 00:00:00`) kept.push([f[0], f[2], f[3], f[4]]);
78
+ else {
79
+ const c = carried.get(f[2]) || { count: 0, last: '' };
80
+ c.count += 1;
81
+ if (f[1] > c.last) c.last = f[1];
82
+ carried.set(f[2], c);
83
+ }
84
+ }
85
+ const lines = kept;
86
+ for (const [repo, c] of carried) lines.push([c.last, repo, '-', `(rebase / cherry-pick:重新提交了 ${c.count} 个更早的提交)`]);
87
+ lines.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
88
+ writeTsv(path.join(out, 'commits.tsv'), ['time', 'repo', 'hash', 'subject'], lines);
89
+
90
+ const repos = new Set(lines.map((l) => l[1])).size;
91
+ ctx.note(`自 ${since} 起 ${lines.length} 条记录,涉及 ${repos} 个仓库`);
92
+ return EXIT.OK;
93
+ }
94
+
95
+ module.exports = { collect };
96
+
97
+ if (require.main === module) {
98
+ collect(process.argv.slice(2)).then(
99
+ (code) => process.exit(code),
100
+ (error) => {
101
+ process.stderr.write(`git-activity: ${error && error.stack ? error.stack : String(error)}\n`);
102
+ process.exit(error && error.name === 'UsageError' ? EXIT.USAGE : EXIT.FAILED);
103
+ },
104
+ );
105
+ }
@@ -0,0 +1,151 @@
1
+ #!/usr/bin/env node
2
+ // 采集云之家消息:拉取订阅会话里最近的 N 条消息(默认 20,也是 yzj-cli 0.1.8 的单页上限,再大会报参数错误),供 AI 提炼事件
3
+ // 用法: node collectors/im-yzj.js <输出目录> [起始日期 YYYY-MM-DD,默认今天。翻页时往前翻到这一天 0 点为止]
4
+ // 输出: <输出目录>/whoami.json、messages-<会话ID>.json —— 该会话取到的全部消息,按时间排序,同一 msgId 只留一条;
5
+ // data.coverage 记这次覆盖的时间段(from / to),下游写总结时要把它写明
6
+ // 前提: yzj-cli 已登录(yzj-cli auth login);collectors/local.env 里为这个源配置了会话 ID
7
+ // 源 id 是 im-yzj 时读 YZJ_GROUP_IDS;换成别的 id(例如 ops-yzj)读 YZJ_GROUP_IDS_<ID>(ID 转大写,- 换成 _)。
8
+ // 这样同一个脚本可以接多个源,各有各的会话和提炼规则。没配置会话 ID 时直接退出,不采集。
9
+ // 两次调用之间默认停 2 秒(YZJ_CALL_INTERVAL 可改):云之家连续调用会返回 10000429 请求过于频繁。
10
+ // 翻页: 每个会话默认只取最新的一页。消息多的群可以配页数,变量名的规则和会话 ID 一样
11
+ // (im-yzj 读 YZJ_MESSAGE_PAGES,别的源读 YZJ_MESSAGE_PAGES_<ID>),每页最多 20 条,往前翻到起始日 0 点为止。
12
+ // 配了多页就要求覆盖到起始日 0 点:翻完还差一截的按失败退出(退出码 5),不把半段当成一整天。只配 1 页时不做这个要求。
13
+ 'use strict';
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+ const { EXIT, run } = require('../scripts/lib/run');
17
+ const { context, needTool, sleep } = require('../scripts/lib/collector');
18
+
19
+ // 这一页的消息列表;调用失败、或者返回的结构不对时是 null
20
+ function pageOf(r) {
21
+ if (r.code !== 0) return null;
22
+ try {
23
+ const doc = JSON.parse(r.stdout);
24
+ return doc.success === true && doc.data && Array.isArray(doc.data.list) ? doc.data.list : null;
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ // 时间戳取成 14 位数字(到秒),按纯数字逐位比较,不受 locale 排序影响
31
+ const digits = (s) => String(s || '').replace(/\D/g, '').slice(0, 14);
32
+ const byTime = (a, b) => (String(a.sendTime) < String(b.sendTime) ? -1 : String(a.sendTime) > String(b.sendTime) ? 1 : 0);
33
+
34
+ async function collect(argv) {
35
+ const ctx = context(argv, 'im-yzj', 'im-yzj.js <输出目录> [起始日期]');
36
+ const { out, since, env } = ctx;
37
+ // 输出目录形如 01-inbox/<源id>/<日期>:从它反推这个源该读哪个变量
38
+ const sourceId = path.basename(path.dirname(out));
39
+ let groupVar;
40
+ let groupIds;
41
+ let pages;
42
+ let pagesVar;
43
+ if (sourceId === 'im-yzj') {
44
+ groupVar = 'YZJ_GROUP_IDS';
45
+ groupIds = env.YZJ_GROUP_IDS || '';
46
+ pagesVar = 'YZJ_MESSAGE_PAGES';
47
+ pages = env.YZJ_MESSAGE_PAGES || '1';
48
+ } else {
49
+ const key = sourceId.toUpperCase().replace(/-/g, '_');
50
+ groupVar = `YZJ_GROUP_IDS_${key}`;
51
+ groupIds = env[groupVar] || '';
52
+ pagesVar = `YZJ_MESSAGE_PAGES_${key}`;
53
+ pages = env[pagesVar] || env.YZJ_MESSAGE_PAGES || '1';
54
+ }
55
+ if (!/^[1-9]\d*$/.test(String(pages))) {
56
+ ctx.note(`${pagesVar} 要是正整数(现在是 '${pages}')`);
57
+ return EXIT.USAGE;
58
+ }
59
+ if (!String(groupIds).trim()) {
60
+ ctx.note(`未配置 ${groupVar}(collectors/local.env),不采集`);
61
+ return EXIT.NOT_CONFIGURED;
62
+ }
63
+ if (!needTool(ctx, 'yzj-cli')) return EXIT.MISSING_DEP;
64
+ const limit = env.YZJ_MESSAGE_LIMIT === undefined ? 20 : env.YZJ_MESSAGE_LIMIT;
65
+ const interval = Number(env.YZJ_CALL_INTERVAL === undefined ? 2 : env.YZJ_CALL_INTERVAL);
66
+ const sinceTs = digits(`${since} 00:00:00`);
67
+ let rc = EXIT.OK;
68
+ fs.mkdirSync(out, { recursive: true });
69
+ const whoami = run('yzj-cli', ['whoami'], { env });
70
+ if (whoami.code !== 0) {
71
+ ctx.note(`whoami 失败(未登录?试试 yzj-cli auth login): ${whoami.stderr.slice(0, 300)}`);
72
+ return EXIT.FAILED;
73
+ }
74
+ fs.writeFileSync(path.join(out, 'whoami.json'), whoami.stdout);
75
+
76
+ let lastWait = interval;
77
+ let first = true;
78
+ for (const gid of String(groupIds).split('|').map((s) => s.trim()).filter(Boolean)) {
79
+ const target = path.join(out, `messages-${gid}.json`);
80
+ // 同一天重复同步只留最新一份:先删掉上一次的,下面任何一步失败都不留下旧文件
81
+ fs.rmSync(target, { force: true });
82
+ const all = [];
83
+ const seen = new Set();
84
+ let page = 1;
85
+ let oldest = '';
86
+ let anchor = '';
87
+ let complete = false;
88
+ let failed = false;
89
+ while (true) {
90
+ // 每次调用之间留出间隔;失败后多等一会儿再试下一个
91
+ if (!first) await sleep(Math.max(0, lastWait) * 1000);
92
+ first = false;
93
+ const args = ['im', 'message', 'list', '--group-id', gid];
94
+ if (page === 1) args.push('--type', 'newest', '--limit', String(limit));
95
+ else args.push('--msg-id', anchor, '--type', 'old', '--limit', String(limit));
96
+ const r = run('yzj-cli', args, { env });
97
+ const messages = pageOf(r);
98
+ if (!messages) {
99
+ ctx.note(`会话 ${gid} 拉取失败: ${(r.stderr || r.stdout).slice(0, 300)}`);
100
+ lastWait = 5;
101
+ rc = EXIT.FAILED;
102
+ failed = true;
103
+ break;
104
+ }
105
+ // 这一页里有没有之前没见过的消息。一条都没有说明已经翻到这个会话的开头(接口改了、把锚点也算进来时也是这样)
106
+ const fresh = messages.filter((m) => m && m.msgId && !seen.has(m.msgId)).length;
107
+ for (const m of messages) {
108
+ if (!m || !m.msgId || seen.has(m.msgId)) continue;
109
+ seen.add(m.msgId);
110
+ all.push(m);
111
+ }
112
+ if (fresh === 0) {
113
+ complete = true;
114
+ break;
115
+ }
116
+ const oldestMsg = [...messages].sort(byTime)[0];
117
+ oldest = String(oldestMsg.sendTime);
118
+ anchor = String(oldestMsg.msgId);
119
+ // 只比到秒:时间带不带毫秒都能和起始日对齐。已经翻过起始日 0 点就停;时间字段读不出来时不下结论,接着翻
120
+ const oldestTs = digits(oldest);
121
+ if (/^\d{14}$/.test(oldestTs) && Number(oldestTs) < Number(sinceTs)) complete = true;
122
+ if (complete) break;
123
+ if (page >= Number(pages)) break;
124
+ page += 1;
125
+ }
126
+ if (failed) continue;
127
+ if (Number(pages) > 1 && !complete) {
128
+ ctx.note(`会话 ${gid} 翻了 ${page} 页只翻到 ${oldest},没覆盖到 ${since} 00:00;把 ${pagesVar} 调大再同步`);
129
+ rc = EXIT.FAILED;
130
+ continue;
131
+ }
132
+ all.sort(byTime);
133
+ const coverage = { from: all.length ? all[0].sendTime : null, to: all.length ? all[all.length - 1].sendTime : null };
134
+ fs.writeFileSync(target, `${JSON.stringify({ success: true, data: { groupId: gid, coverage, list: all } }, null, 2)}\n`);
135
+ lastWait = interval;
136
+ ctx.note(`会话 ${gid} 已拉取 ${all.length} 条(${page} 页),覆盖 ${coverage.from ?? '无'} 至 ${coverage.to ?? '无'}`);
137
+ }
138
+ return rc;
139
+ }
140
+
141
+ module.exports = { collect };
142
+
143
+ if (require.main === module) {
144
+ collect(process.argv.slice(2)).then(
145
+ (code) => process.exit(code),
146
+ (error) => {
147
+ process.stderr.write(`im-yzj: ${error && error.stack ? error.stack : String(error)}\n`);
148
+ process.exit(error && error.name === 'UsageError' ? EXIT.USAGE : EXIT.FAILED);
149
+ },
150
+ );
151
+ }
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env node
2
+ // 采集 Linky 上分配给我的未完成工作项:供 AI 提炼「工作项」事件,也给每日计划挑最该推进的那几条
3
+ // 用法: node collectors/linky-issues.js <输出目录> [起始日期 YYYY-MM-DD,只用于统计,默认今天]
4
+ // 输出: <输出目录>/issues.tsv —— 类型、编号、状态、状态分类、优先级、最近更新、模块、标题,按最近更新倒序
5
+ // 前提: linky 已登录(linky login)。要导出的类型可以在 collectors/local.env 里用 LINKY_TYPES 改,多个用 | 分隔
6
+ // 说明: 已经完成的(状态分类为 done)不导出,它们留在 Linky 里就够了。
7
+ // 导出不完整(complete=false)按失败处理:不完整的清单不能当作「我手上有多少事」。
8
+ 'use strict';
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const { EXIT, run, tail } = require('../scripts/lib/run');
12
+ const { context, needTool, tempDir, readJson, writeTsv, tsv } = require('../scripts/lib/collector');
13
+
14
+ async function collect(argv) {
15
+ const ctx = context(argv, 'linky-issues', 'linky-issues.js <输出目录> [起始日期]');
16
+ const { out, since, env } = ctx;
17
+ const types = (env.LINKY_TYPES || 'bug|user_story|requirement|task').split('|').map((s) => s.trim()).filter(Boolean).join(',');
18
+ if (!needTool(ctx, 'linky')) return EXIT.MISSING_DEP;
19
+ // 原始导出先落到临时目录:工作目录里只留那张表,导出用完即删
20
+ const work = tempDir('linky-issues-');
21
+ try {
22
+ const r = run('linky', ['issue', 'export', '--type', types, '--all-visible', '--include-personal', '--filter', 'assignee_id:current_user', '--out-dir', path.join(work, 'export'), '--omit-rich-text'], { env });
23
+ // linky 的退出码:3 结果不完整,4 需要登录,5 无权限或工作区不可见。都算远端失败,原因分开说
24
+ if (r.code === 3) {
25
+ ctx.note('导出不完整(complete=false),这份清单不能当作我手上有多少事;稍后重试');
26
+ return EXIT.FAILED;
27
+ }
28
+ if (r.code === 4) {
29
+ ctx.note('linky 未登录,先运行 linky login');
30
+ return EXIT.FAILED;
31
+ }
32
+ if (r.code !== 0) {
33
+ ctx.note(`导出失败(退出码 ${r.code};5 表示无权限或工作区不可见): ${tail(r.stderr, 300)}`);
34
+ return EXIT.FAILED;
35
+ }
36
+ fs.writeFileSync(path.join(work, 'summary.json'), r.stdout);
37
+ const metaFile = fs.existsSync(path.join(work, 'export', 'meta.json')) ? path.join(work, 'export', 'meta.json') : path.join(work, 'summary.json');
38
+ const complete = (readJson(metaFile) || {}).complete;
39
+ if (complete !== true) {
40
+ ctx.note(`导出不完整(complete=${complete === undefined ? '未知' : complete}),这份清单不能当作我手上的全部工作项;稍后重试`);
41
+ return EXIT.FAILED;
42
+ }
43
+ const exportDir = path.join(work, 'export');
44
+ const rows = [];
45
+ for (const name of fs.readdirSync(exportDir).filter((n) => n.endsWith('.jsonl')).sort()) {
46
+ for (const line of fs.readFileSync(path.join(exportDir, name), 'utf8').split('\n')) {
47
+ if (!line.trim()) continue;
48
+ let item;
49
+ try {
50
+ item = JSON.parse(line);
51
+ } catch {
52
+ continue;
53
+ }
54
+ if (String((item.status && item.status.category) || '').toLowerCase() === 'done') continue;
55
+ rows.push([
56
+ item.type || '',
57
+ item.code || '',
58
+ (item.status && item.status.name) || '',
59
+ (item.status && item.status.category) || '',
60
+ (item.labels && item.labels.gf_priority) || '',
61
+ item.updated_at || '',
62
+ String((item.labels && item.labels.tf_module) || '').replace(/\s*[((][A-Za-z0-9-]+[))]\s*$/, ''),
63
+ String(item.title || '').replace(/[\t\n\r]/g, ' '),
64
+ ].map(tsv));
65
+ }
66
+ }
67
+ rows.sort((a, b) => (a[5] < b[5] ? 1 : a[5] > b[5] ? -1 : 0)); // 按最近更新倒序
68
+ fs.mkdirSync(out, { recursive: true });
69
+ writeTsv(path.join(out, 'issues.tsv'), ['type', 'code', 'status', 'category', 'priority', 'updated', 'module', 'title'], rows);
70
+ const touched = rows.filter((row) => row[5] >= since).length;
71
+ ctx.note(`未完成工作项 ${rows.length} 条,其中 ${since} 之后更新过 ${touched} 条`);
72
+ return EXIT.OK;
73
+ } finally {
74
+ fs.rmSync(work, { recursive: true, force: true });
75
+ }
76
+ }
77
+
78
+ module.exports = { collect };
79
+
80
+ if (require.main === module) {
81
+ collect(process.argv.slice(2)).then(
82
+ (code) => process.exit(code),
83
+ (error) => {
84
+ process.stderr.write(`linky-issues: ${error && error.stack ? error.stack : String(error)}\n`);
85
+ process.exit(error && error.name === 'UsageError' ? EXIT.USAGE : EXIT.FAILED);
86
+ },
87
+ );
88
+ }
@@ -0,0 +1,52 @@
1
+ # 采集脚本的本机覆盖项。复制为 collectors/local.env 后按需修改;local.env 只放在本机,不进任何仓库。
2
+ # 多个值一律用 | 分隔,例如 "id-a|id-b"。不设置的变量用脚本里的默认值。
3
+
4
+ # git-activity:扫描哪些目录下的 git 仓库;哪些邮箱或姓名算「我」(默认取全局 git 配置)
5
+ # 每个目录只看它的下一层。要把某个仓库的子模块也扫进来,把那个仓库的目录再列一遍,例如 "$HOME/workspace|$HOME/workspace/minutes"
6
+ # GIT_ACTIVITY_WORKSPACES="$HOME/workspace"
7
+ # GIT_ACTIVITY_AUTHORS="me@company.com|张三"
8
+
9
+ # file-activity:扫描哪些目录
10
+ # FILE_ACTIVITY_WORKSPACES="$HOME/workspace"
11
+
12
+ # im-yzj:要订阅的云之家会话 ID(引导流程确认后填;留空则 im-yzj 不采集)和每个会话拉多少条(默认 20,也是 yzj-cli 0.1.8 的单页上限)
13
+ # YZJ_GROUP_IDS=""
14
+ # YZJ_MESSAGE_LIMIT=20
15
+ # 消息多的群可以往前多翻几页(每页最多 20 条),翻到起始日 0 点为止。变量名的规则和会话 ID 一样:
16
+ # im-yzj 读 YZJ_MESSAGE_PAGES,别的源读 YZJ_MESSAGE_PAGES_<源 id 转大写,- 换成 _>。
17
+ # 配了多页就要求覆盖到起始日 0 点,覆盖不到按失败处理;默认 1 页,不做这个要求
18
+ # YZJ_MESSAGE_PAGES="1"
19
+
20
+ # ops-yzj 等复用内置 im-yzj 采集器的源:变量名是 YZJ_GROUP_IDS_<源 id 转大写,- 换成 _>,只订阅那个源自己的会话
21
+ # YZJ_GROUP_IDS_OPS_YZJ=""
22
+ # YZJ_MESSAGE_PAGES_OPS_YZJ="20" # 告警群消息多:每次往前翻最多 20 页,并要求覆盖到起始日 0 点
23
+
24
+ # 两次云之家调用之间隔几秒(默认 2;连续调用会返回 10000429 请求过于频繁)
25
+ # YZJ_CALL_INTERVAL=2
26
+
27
+ # 告警跟进晨报的推送目标(可选):群 ID,或我自己的 openId。不配就只落文件、不推送。第一次推送前先把内容给自己看一眼
28
+ # YZJ_NOTIFY_TARGET=""
29
+
30
+ # 消息渠道(work-rhythm notify,渠道写在 profile 的 preferences.notify,见 docs/channels.md):云之家个人机器人私聊给我时的收件人,我自己的 openId
31
+ # (yzj-cli whoami 能查到)。写上它推送就不依赖 yzj-cli 的登录;不配就每次用 whoami 现取,登录过期时推送也会失败。
32
+ # 机器人的 Webhook 地址不在这里配:它是凭据,存进系统钥匙串,做法见 docs/channels.md「云之家」
33
+ # YZJ_MY_OPEN_ID=""
34
+
35
+ # 值守(work-rhythm listen,消息渠道的收消息一半,见 docs/channels.md「收消息:值守」):在 IM 里说的话交给本地的 agent 处理并回复。
36
+ # 不配 YZJ_BOT_AGENT 就等于没开。开了就是常驻进程,每来一条消息跑一次 agent
37
+ # 本地服务(work-rhythm rhythm)跑定时任务用的也是 YZJ_BOT_AGENT:不配的话定时任务跑不了,采集和网页照常
38
+ # YZJ_BOT_AGENT 让哪个 agent 回复,三种写法:
39
+ # "dsh" DSH(DeepSeek Harness)的 headless 模式。模型和凭据跟着 DSH 桌面应用里的配置走,你在 DSH 里默认用哪个模型,机器人就用哪个。
40
+ # 要装了 DSH 桌面版;位置不对可用 DSH_HOME、DSH_NODE、DSH_CLI 改
41
+ # "zcode" ZCode 自带的命令行。注意它的模型是命令行自己的默认选择,不是 ZCode 窗口里给会话选的(本机实测是 opencode-go 的 minimax-m3.1-flash)
42
+ # 一条自己的命令:我的消息作为最后一个参数传给它,回复打到标准输出,退出码 0 算成功。路径带空格的命令先写成一个脚本再写它的路径
43
+ # YZJ_BOT_AGENT_MODE 是权限:plan 只读(默认,能查能答能出计划,不改文件);edit 允许改工作目录,等于我在聊天里说什么它就做什么
44
+ # YZJ_BOT_TIMEOUT 每条消息最多等多少秒(默认 300);YZJ_BOT_REPLY_MAX 回复最多多少字(默认 2000,超出截断并注明)
45
+ # 消息一到机器人先回「收到,正在处理,稍等。」,YZJ_BOT_ACK=0 关掉。
46
+ # 每句话后面会带给 agent 一句提示(回复要以纯文本私聊发回,直接答、简短答),YZJ_BOT_PREAMBLE="" 关掉,或换成自己的
47
+ # 配完跑 work-rhythm listen doctor 检查
48
+ # YZJ_BOT_AGENT="dsh"
49
+ # YZJ_BOT_AGENT_MODE="plan"
50
+
51
+ # linky-issues:导出哪些类型的工作项,多个用 | 分隔
52
+ # LINKY_TYPES="bug|user_story|requirement|task"
@@ -0,0 +1,95 @@
1
+ # 消息渠道
2
+
3
+ 消息渠道是 AI 把提醒推给用户本人的那条路。[profile.yaml](../00-config/profile.yaml) 的 `preferences.notify` 写渠道的名字,每日工作计划和晚间复盘写完文件后调用 `work-rhythm notify`,按这个名字选渠道发出去(任务指令在 [scheduled-tasks.md](scheduled-tasks.md))。`notify` 留空就只写文件。
4
+
5
+ 它只做一件事:把文字推给用户本人。不往群里发,不给别人发;收消息、对话不归它管。开通和第一次推送之前都要先问用户,把要发的内容给他看一眼。
6
+
7
+ ## 怎么运转
8
+
9
+ - 调用:`work-rhythm notify "<文字>"`,或 `… | work-rhythm notify -` 从标准输入读。按 `preferences.notify` 选渠道;留空时什么都不发,退出码也是 0。
10
+ - 退出码:`0` 已发出 · `2` 用法不对,或渠道不认识 · `3` 没配置好(凭据没存、取不到收件人)· `4` 缺依赖 · `5` 发送失败。状态写到 stderr,stdout 不留东西,凭据不打印。
11
+ - 任务指令在文件写完之后才推送。发不出去就把原因记进当天文件的「## 备注」,不影响已经写好的内容。
12
+ - **推送可以带链接**:本地服务(`work-rhythm rhythm`,见 [scheduled-tasks.md](scheduled-tasks.md))在任务跑完时推送 agent 写的总结,后面附一个本机网页服务的地址。机器人发得了链接,但它指向 `127.0.0.1`,只有本机浏览器打得开。
13
+ - 凭据(Webhook 地址、token)存系统钥匙串,不进任何文件,不贴进聊天记录,`collectors/local.env` 里也不放。收件人 ID 不是凭据,放 `local.env`。
14
+ - 渠道最好不依赖用户账号的登录状态。用「用户账号给自己发消息」的办法,登录一过期,推送和「该重新登录」的提醒一起失效。
15
+
16
+ ## 预置的渠道
17
+
18
+ 「预置」指 `work-rhythm` 里已经实现了,`work-rhythm check` 会核对它配没配好,`work-rhythm selftest` 有用例,开通步骤写在下面。主 IM 有预置的就直接用。
19
+
20
+ | 主 IM | 渠道 | 收到的是什么 | 用户要做的 |
21
+ |---|---|---|---|
22
+ | 云之家 | `yzj-robot`:个人机器人私聊 | 机器人发来的纯文本,带「[有人@你]」的提醒 | 在网页端建一个机器人,把 Webhook 地址存进系统钥匙串 |
23
+
24
+ 别的 IM 还没有预置,接法见下面的「新增一个渠道」。接好之前不要打开 `notify`。
25
+
26
+ ### 云之家:个人机器人(`yzj-robot`)
27
+
28
+ 用的是云之家的个人机器人,也就是「龙虾」(OpenClaw)接入云之家的官方集成所用的那个([金蝶官网的教程](https://www.kingdee.com/resources/articles/1487206471671170113)):每个用户在自己的网页端建一个,机器人有一个 Webhook 地址,往它 POST 一段文本就能让机器人发消息。推送不经过 `yzj-cli`(0.1.8 没有机器人命令),也不需要装 OpenClaw。2026-11-30 实测可用;客户端弹不弹提醒、Webhook 的 token 会不会过期,还没有数据。
29
+
30
+ 1. **建机器人**:登录云之家网页端,打开 <https://www.yunzhijia.com/im/personalRobotCreate>,起个名字(它就是消息列表里显示的名字),复制完整的 Webhook 地址,`yzjtype`、`yzjtoken` 两段都要。
31
+ 2. **把地址存进系统钥匙串**:地址本身就是凭据,不进任何文件,也别贴进聊天记录。在自己的终端运行下面这条,末尾的 `-w` 会让它提示粘贴(不回显)。换机器人重跑同一条即可覆盖。
32
+
33
+ ```bash
34
+ security add-generic-password -a "$USER" -s work-rhythm-yzj-robot-webhook -U -w
35
+ ```
36
+
37
+ 一台电脑上要区分几个机器人,就换个服务名,并把它写进 `collectors/local.env` 的 `YZJ_ROBOT_KEYCHAIN_SERVICE`。删掉用 `security delete-generic-password -a "$USER" -s <服务名>`。
38
+ 3. **打开推送**:`00-config/profile.yaml` 的 `preferences.notify` 写 `"yzj-robot"`;`collectors/local.env` 里写 `YZJ_MY_OPEN_ID`(`yzj-cli whoami` 能查到)。写上它,推送就完全不依赖 `yzj-cli` 的登录;不写则每次用 `whoami` 现取,登录过期时推送也会失败。
39
+ 4. **核对**:`work-rhythm check` 会确认钥匙串里有地址、依赖都装了。再手动发一条 `work-rhythm notify "测试"`,确认收得到、客户端有提醒、没有弹窗要授权。
40
+
41
+ 要知道的事:
42
+
43
+ - 只能发纯文本,文件和图片发不了(要发文件仍用 `yzj-cli im message send`);每个机器人每分钟 30 条。
44
+ - 发送就是往 Webhook 地址 POST `{"msgtype": 2, "content": "<文本>", "notifyParams": [{"type": "openIds", "values": ["<我的 openId>"]}]}`。返回 `success` 为 `true`,并带上 `groupId`(机器人会话,形如 `BOT-<我的ID>-BOT-<机器人ID>`)和 `msgId`。报文取自官方插件 [kingdee/openclaw-yzj](https://github.com/kingdee/openclaw-yzj) 的源码。
45
+ - 机器人会话(`groupType` 为 3,`groupId` 以 `BOT-` 开头)的第一条消息里有完整的 Webhook 地址。不要把这个会话加进 `im.groups` 订阅,也不要用 `im message list` 把它的内容落盘;`work-rhythm check` 会扫 `yzjtoken=`。
46
+ - 要马上确认某条推送送到了没有,按返回的 `groupId` 查会话,别用 `im message search`([原因](../.agents/notes/pitfalls/2026-11-30-message-search-lags-after-sending.md))。
47
+ - 群机器人(群管理员在群设置里建的)只能发到所在的群,被通知的人不在群里就收不到([官方文档](https://open.yunzhijia.com/opendocs/docs.html#/api/im/im-robot)),不能当消息渠道用。
48
+
49
+ ## 收消息:值守
50
+
51
+ 渠道还能反过来收:我在 IM 里说的话经同一条渠道交给本地的 agent 处理,回复再发回来。这叫「值守」。它是一个常驻进程,每来一条消息跑一次 agent,所以默认不开;要开按下面配。
52
+
53
+ ### 云之家:个人机器人的长连接(`work-rhythm listen`)
54
+
55
+ 机器人收消息有两种方式。一种是回调:在机器人设置里填一个公网能访问的「消息接收地址」,云之家把消息 POST 过去,本机跑就得内网穿透;群里的「对话型机器人」建的时候就要求填它。另一种是长连接:程序主动连到云之家,云之家把消息推下来,不需要公网地址。个人机器人支持长连接,用的是和发送相同的 token,地址由发送地址推导:`wss://<发送地址的域名>/xuntong/websocket?yzjtoken=<同一个 token>`。官方的 OpenClaw 插件推荐的就是它。
56
+
57
+ 2026-11-30 实测:连上后云之家先推 `{"success":true,"cmd":"auth"}`;每 15 秒发 `{"cmd":"ping"}`,回 `{"cmd":"pong"}`;还会推 `{"cmd":"extSystemMsg",…}` 这类系统通知。我发给机器人的话是这样一帧,不带 `needAck`,不用回 ack:
58
+
59
+ ```json
60
+ {"msg":{"groupType":3,"type":2,"robotId":"BOT-…","robotName":"工作王","msgId":"…","content":"你好","operatorOpenid":"<和 whoami 一致的 openId>","operatorName":"我","time":1796046214771},"level":0,"cmd":"directPush","type":"robotMessage"}
61
+ ```
62
+
63
+ 1. **配 agent**:`collectors/local.env` 里写 `YZJ_BOT_AGENT`,三种写法。
64
+ - `"dsh"`:用 DSH(DeepSeek Harness)的 headless 模式。模型和凭据跟着 DSH 桌面应用里的配置走,你在 DSH 里默认用哪个模型,机器人就用哪个。要装了 DSH 桌面版。
65
+ - `"zcode"`:用 ZCode 自带的命令行。它的模型是命令行自己的默认选择,不是 ZCode 窗口里给会话选的,见下面「用哪个模型」。
66
+ - 一条自己的命令:我的消息作为最后一个参数传给它,回复打到标准输出,退出码 0 算成功。路径带空格的先写成一个脚本。
67
+
68
+ 写完跑 `work-rhythm listen doctor`,配置和依赖有问题它会逐条报出来。
69
+ 2. **先单跑一句**:`work-rhythm listen handle "今天怎么安排"`。它不连云之家,只看 agent 的回复对不对。
70
+ 3. **真连着看一眼**:`work-rhythm listen probe --seconds 120`,然后在云之家里给机器人发一句话,终端里应出现这一帧。
71
+ 4. **值守**:`work-rhythm listen run` 挂在终端里。要常驻就 `work-rhythm listen install`(macOS launchd:开机自启、挂了拉起),`status` 看状态,`uninstall` 卸掉。改了配置要重启一次,`install` 之后会提示命令。
72
+
73
+ - **只认本人**:入站消息里的发消息人(`operatorOpenid`)等于 `YZJ_MY_OPEN_ID` 才处理,别人的丢掉并记一行日志。回复一律私聊发给我,走 `work-rhythm notify`。群里的消息不处理。
74
+ - **先回一句收到**:消息一到,机器人先回「收到,正在处理,稍等。」,agent 的回答随后到,不用干等。`YZJ_BOT_ACK=0` 关掉。
75
+ - **带给 agent 的提示**:我的每句话后面会加一句「这句来自云之家,回复会以纯文本私聊发回,直接答、简短答」,免得它拿聊天当命令行,长篇大论或翻一堆文件。`YZJ_BOT_PREAMBLE=""` 关掉,或换成自己的。它只对两个预置生效;用自定义命令的话,提示写在你的脚本里。
76
+ - **权限**:`YZJ_BOT_AGENT_MODE` 默认 `plan`,agent 只读,能查、能答、能出计划,不改文件(zcode 是它的 plan 模式,dsh 是 `read-only`)。要在 IM 里「记一下」得改成 `edit`,那等于我在聊天里说什么它就做什么(dsh 是 `workspace-write`)。zcode 的 `build` 会停下来等确认,无界面下只能等到超时,不要用。
77
+ - **多轮**:机器人有自己的专属会话(ID 存在 `01-inbox/_bot/session-id`),第二轮起用 `--resume` 接上,不碰我正在用的会话。在聊天里发 `/new`,或运行 `work-rhythm listen reset`,开新会话。
78
+ - **代价**:每条消息是一次完整的 agent 运行,实测一句话 6–18 秒、约 8 万输入 token(大部分走缓存)。
79
+ - **用哪个模型**:`dsh` 跟着 DSH 桌面应用里的默认模型和凭据。值守只把那份配置里模型的两条摘出来、再打开它的凭据存储,写成一份覆盖文件交给 headless 模式,密钥始终在 DSH 自己的存储里,不经过值守。2026-11-30 实测是 OpenCode Go 的 `deepseek-v4.1-flash`,问「你能帮我做什么」28 秒回了一段 170 字的纯文本。
80
+ `zcode` 则只认 ZCode 命令行自己的「默认模型选择」,和窗口里每个会话选的无关:同一天实测窗口里是 GLM-5.4,值守起的会话是 `minimax-m3.1-flash`,一句宽泛的话它翻了 5 分钟没答完;命令行没有 `--model` 参数,提示词开头写 `/model` 不生效,续接窗口里建的会话报 `Select a model before sending a message`。所以要挑回答质量,用 `dsh`。
81
+ - **DSH 装在哪**:它的运行时在 `~/.dsh-desktop/runtime/<版本>/dsh/` 下,自带一个 Node,值守取最新的那个版本,用 `headless` 模式答一句就退出,多轮靠 `--session-id`。位置不对可以用 `DSH_HOME`、`DSH_NODE`、`DSH_CLI` 改。headless 的工作目录就是工作目录本身。
82
+ - **稳妥**:一条一条处理,后面的排队;按 `msgId` 去重;每条最多等 `YZJ_BOT_TIMEOUT` 秒(默认 300);agent 失败或超时回我一句「没处理成功:<原因>」;回复超过 `YZJ_BOT_REPLY_MAX` 字(默认 2000)截断并注明。
83
+ - **日志**:`01-inbox/_bot.log`,只记时间、msgId、发消息人、耗时、退出码,不记消息内容。
84
+ - **协议**(照官方插件的客户端,已对照实测):业务消息包在 `{"cmd":"directPush","type":"robotMessage","msg":{…}}` 里,`msg` 里用得上的是 `operatorOpenid`(发消息人)、`msgId`、`content`、`groupType`;不带外层、直接是 `msg` 内容的写法也认。带 `needAck` 和 `seq` 的控制帧要回 `{"cmd":"ack","seq":N}`;45 秒没动静就重连,间隔 1、2、5、10、30、60 秒。
85
+ - **快慢**:agent 的耗时看它要干什么。空目录里问一句几秒就回;带着整个工作目录的上下文,一句宽泛的话可能让它去读几十个文件。2026-11-30 实测第一条消息就跑满了 5 分钟的上限,收到的是「没处理成功:超过 300 秒没返回」。所以问得越具体越好;每条的上限是 `YZJ_BOT_TIMEOUT`。
86
+ - **依赖**:node 22 以上(内置 WebSocket)。`work-rhythm check` 在配了 `YZJ_BOT_AGENT` 时会核对钥匙串、`YZJ_MY_OPEN_ID`,以及命令找不找得到。
87
+
88
+ ## 新增一个渠道
89
+
90
+ 1. **确认那个 IM 有「机器人」这类能力**:Webhook 机器人、应用消息,能主动给指定用户发消息的接口。先问用户,再看它在本机的 skill 或官方文档,以本机 `--help` 和实测为准。没有的话如实说做不了,`notify` 保持留空。
91
+ 2. **在包里加一个渠道**:`scripts/lib/notify.js` 的 `pushText` 里加一个分支,取凭据、发请求放在 `scripts/lib/robot.js` 旁边;退出码按上面的约定。HTTP 200 不算成功,要看返回里的成功标志;凭据从钥匙串读,不打印,报错里带回的凭据要打码。只用 node 自带的能力,不引第三方包。
92
+ 3. **本机差异放 `collectors/local.env`**(收件人 ID、钥匙串的服务名),用到的变量登记到 [local.env.example](../collectors/local.env.example)。
93
+ 4. **让自检和自测认得它**:`scripts/cmd/check.js` 的「配置自检」里加上对新渠道的核对;`scripts/test/notify.test.js` 里用假的工具补一段用例,照着 `yzj-robot` 那一段写,不碰真实账号。
94
+ 5. **写进这份文档**:上面的表加一行,再照「云之家」那一节写开通步骤。
95
+ 6. 跑 `work-rhythm check` 和 `work-rhythm selftest`,再请用户照着步骤配一次、试发一条。