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.
- package/.agents/notes/AGENTS.md +86 -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 +35 -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 +46 -0
- package/.agents/notes/decisions/2026-12-01-repo-is-not-a-workdir-templates-hold-workdir-files.md +29 -0
- package/.agents/notes/decisions/2026-12-01-repo-stays-generic-personal-data-lives-in-workdirs.md +32 -0
- package/.agents/notes/decisions/2026-12-01-workdir-is-not-a-git-repository.md +25 -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 +278 -0
- package/AGENTS.md +19 -0
- package/README.md +69 -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 +35 -4
- package/scripts/cli.js +101 -0
- package/scripts/cmd/check.js +330 -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 +49 -0
- package/scripts/cmd/listen.js +91 -0
- package/scripts/cmd/notify.js +42 -0
- package/scripts/cmd/pack.js +104 -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 +149 -0
- package/scripts/lib/workdir.js +98 -0
- package/scripts/test/check.test.js +279 -0
- package/scripts/test/collectors.test.js +574 -0
- package/scripts/test/config.test.js +118 -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 +277 -0
- package/scripts/test/init.test.js +123 -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 +333 -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/00-config/profile.example.yaml +54 -0
- package/templates/00-config/sources.yaml +115 -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
- package/templates/AGENTS.md +31 -0
- package/templates/README.md +73 -0
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// 配置只在这里读:工作目录在哪、profile.yaml、sources.yaml、collectors/local.env。
|
|
2
|
+
// 这三个文件用的是 YAML 的一个子集(两格缩进的层级、单行的列表和对象、| 开头的多行文本),
|
|
3
|
+
// 所以自己写了一个够用的小解析器,不引第三方包。格式即契约:docs/formats.md 里的示例要能被它读出来。
|
|
4
|
+
'use strict';
|
|
5
|
+
const fs = require('node:fs');
|
|
6
|
+
const path = require('node:path');
|
|
7
|
+
const { readText } = require('./run');
|
|
8
|
+
|
|
9
|
+
const MARKER = '00-config/profile.yaml';
|
|
10
|
+
|
|
11
|
+
// 从某个目录往上找带 00-config/profile.yaml 的目录:站在哪个工作目录里,说的就是哪个。找不到返回空串
|
|
12
|
+
function findWorkdir(start) {
|
|
13
|
+
let dir = path.resolve(start);
|
|
14
|
+
for (;;) {
|
|
15
|
+
if (fs.existsSync(path.join(dir, MARKER))) return dir;
|
|
16
|
+
const parent = path.dirname(dir);
|
|
17
|
+
if (parent === dir) return '';
|
|
18
|
+
dir = parent;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// ---------------------------------------------------------------- YAML 子集
|
|
23
|
+
// 去掉行内注释:引号外面、前面是空白的 # 才算注释
|
|
24
|
+
function stripComment(s) {
|
|
25
|
+
let quote = '';
|
|
26
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
27
|
+
const c = s[i];
|
|
28
|
+
if (quote) {
|
|
29
|
+
if (c === '\\') i += 1;
|
|
30
|
+
else if (c === quote) quote = '';
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (c === '"' || c === "'") quote = c;
|
|
34
|
+
else if (c === '#' && (i === 0 || /\s/.test(s[i - 1]))) return s.slice(0, i).trimEnd();
|
|
35
|
+
}
|
|
36
|
+
return s.trimEnd();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function unquote(s) {
|
|
40
|
+
s = s.trim();
|
|
41
|
+
const q = s[0];
|
|
42
|
+
if (q !== '"' && q !== "'") return s;
|
|
43
|
+
if (s.length < 2 || s[s.length - 1] !== q) return s; // 引号没成对,当普通文字
|
|
44
|
+
const body = s.slice(1, -1);
|
|
45
|
+
return q === '"' ? body.replace(/\\(["\\])/g, '$1') : body.replace(/''/g, "'");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 按顶层分隔符切开,引号和括号里面的不算
|
|
49
|
+
function splitTop(s, sep) {
|
|
50
|
+
const parts = [];
|
|
51
|
+
let depth = 0;
|
|
52
|
+
let quote = '';
|
|
53
|
+
let cur = '';
|
|
54
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
55
|
+
const c = s[i];
|
|
56
|
+
if (quote) {
|
|
57
|
+
cur += c;
|
|
58
|
+
if (c === '\\') cur += s[i + 1] || '';
|
|
59
|
+
else if (c === quote) quote = '';
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (c === '"' || c === "'") quote = c;
|
|
63
|
+
else if (c === '[' || c === '{') depth += 1;
|
|
64
|
+
else if (c === ']' || c === '}') depth -= 1;
|
|
65
|
+
else if (c === sep && depth === 0) {
|
|
66
|
+
parts.push(cur);
|
|
67
|
+
cur = '';
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
cur += c;
|
|
71
|
+
}
|
|
72
|
+
parts.push(cur);
|
|
73
|
+
return parts;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// 一个值:引号字符串、true/false/null、数字、[a, b]、{k: v},其余原样
|
|
77
|
+
function scalar(s) {
|
|
78
|
+
s = stripComment(String(s)).trim();
|
|
79
|
+
if (s === '') return '';
|
|
80
|
+
if (s === 'null' || s === '~') return null;
|
|
81
|
+
if (s === 'true') return true;
|
|
82
|
+
if (s === 'false') return false;
|
|
83
|
+
if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
|
|
84
|
+
if (s.startsWith('[')) {
|
|
85
|
+
const inner = s.slice(1, s.endsWith(']') ? -1 : undefined).trim();
|
|
86
|
+
return inner === '' ? [] : splitTop(inner, ',').map(scalar);
|
|
87
|
+
}
|
|
88
|
+
if (s.startsWith('{')) {
|
|
89
|
+
const inner = s.slice(1, s.endsWith('}') ? -1 : undefined).trim();
|
|
90
|
+
const obj = {};
|
|
91
|
+
if (inner !== '') {
|
|
92
|
+
for (const part of splitTop(inner, ',')) {
|
|
93
|
+
const m = /^([^:]+):\s*(.*)$/.exec(part.trim());
|
|
94
|
+
if (m) obj[unquote(m[1].trim())] = scalar(m[2]);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return obj;
|
|
98
|
+
}
|
|
99
|
+
return unquote(s);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// 把一份 YAML 子集读成对象。空行和整行注释跳过
|
|
103
|
+
function parseYaml(text) {
|
|
104
|
+
const tokens = [];
|
|
105
|
+
for (const raw of String(text).split(/\r?\n/)) {
|
|
106
|
+
if (!raw.trim() || raw.trimStart().startsWith('#')) continue;
|
|
107
|
+
tokens.push({ indent: raw.length - raw.trimStart().length, text: raw.trimStart() });
|
|
108
|
+
}
|
|
109
|
+
let i = 0;
|
|
110
|
+
const isItem = (t) => t === '-' || t.startsWith('- ');
|
|
111
|
+
|
|
112
|
+
function block() {
|
|
113
|
+
if (i >= tokens.length) return null;
|
|
114
|
+
return isItem(tokens[i].text) ? list(tokens[i].indent) : map(tokens[i].indent);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function map(indent) {
|
|
118
|
+
const obj = {};
|
|
119
|
+
while (i < tokens.length && tokens[i].indent === indent) {
|
|
120
|
+
const t = tokens[i].text;
|
|
121
|
+
if (isItem(t)) break;
|
|
122
|
+
const m = /^([^\s#][^:]*?):(?:\s+(.*))?$/.exec(t);
|
|
123
|
+
if (!m) {
|
|
124
|
+
i += 1; // 看不懂的行跳过
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
i += 1;
|
|
128
|
+
const key = unquote(m[1].trim());
|
|
129
|
+
const rest = m[2] === undefined ? '' : stripComment(m[2]).trim();
|
|
130
|
+
if (rest === '|' || rest === '>' || rest === '|-' || rest === '>-') {
|
|
131
|
+
// 多行文本:下面缩进更深的行都算,去掉公共缩进
|
|
132
|
+
const base = i < tokens.length ? tokens[i].indent : indent + 2;
|
|
133
|
+
const lines = [];
|
|
134
|
+
while (i < tokens.length && tokens[i].indent >= base) {
|
|
135
|
+
lines.push(tokens[i].text);
|
|
136
|
+
i += 1;
|
|
137
|
+
}
|
|
138
|
+
obj[key] = lines.join('\n') + (rest.endsWith('-') ? '' : '\n');
|
|
139
|
+
} else if (rest === '') {
|
|
140
|
+
// 冒号后面没有值:下一行缩进更深就是下一层,否则是空的
|
|
141
|
+
obj[key] = i < tokens.length && tokens[i].indent > indent ? block() : null;
|
|
142
|
+
} else {
|
|
143
|
+
obj[key] = scalar(rest);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return obj;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function list(indent) {
|
|
150
|
+
const arr = [];
|
|
151
|
+
while (i < tokens.length && tokens[i].indent === indent && isItem(tokens[i].text)) {
|
|
152
|
+
const item = tokens[i].text === '-' ? '' : tokens[i].text.slice(2).trim();
|
|
153
|
+
if (item === '') {
|
|
154
|
+
i += 1;
|
|
155
|
+
arr.push(i < tokens.length && tokens[i].indent > indent ? block() : null);
|
|
156
|
+
} else if (/^[^\s"'[{#-][^:]*?:(\s|$)/.test(item)) {
|
|
157
|
+
// 「- key: value」:列表项是个对象,这一行的键和它下面缩进更深的键是同一层
|
|
158
|
+
const inner = indent + 2;
|
|
159
|
+
tokens[i] = { indent: inner, text: item };
|
|
160
|
+
const obj = map(inner);
|
|
161
|
+
if (i < tokens.length && tokens[i].indent > indent && tokens[i].indent !== inner) Object.assign(obj, block());
|
|
162
|
+
arr.push(obj);
|
|
163
|
+
} else {
|
|
164
|
+
i += 1;
|
|
165
|
+
arr.push(scalar(item));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return arr;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const out = block();
|
|
172
|
+
return out === null ? {} : out;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ---------------------------------------------------------------- 三个配置文件
|
|
176
|
+
const loadProfile = (root) => parseYaml(readText(path.join(root, MARKER)));
|
|
177
|
+
|
|
178
|
+
// sources.yaml 里的源,补上 id、enabled、collector 三个一定会有的字段,顺序照文件
|
|
179
|
+
function loadSources(root) {
|
|
180
|
+
const doc = parseYaml(readText(path.join(root, '00-config', 'sources.yaml')));
|
|
181
|
+
const list = Array.isArray(doc.sources) ? doc.sources : [];
|
|
182
|
+
return list.map((s, n) => {
|
|
183
|
+
const src = s && typeof s === 'object' ? s : {};
|
|
184
|
+
return {
|
|
185
|
+
...src,
|
|
186
|
+
id: src.id == null || src.id === '' ? `source-${n + 1}` : String(src.id),
|
|
187
|
+
enabled: src.enabled === true,
|
|
188
|
+
collector: src.collector == null ? '' : String(src.collector),
|
|
189
|
+
order: n,
|
|
190
|
+
};
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// collectors/local.env 是 KEY=VALUE 一行一个:双引号里展开 $VAR 和 ${VAR},单引号里原样,# 是注释。不支持命令替换。
|
|
195
|
+
// 只返回文件里写了的键;和环境变量合并见 settings()
|
|
196
|
+
function parseLocalEnv(text, env = process.env) {
|
|
197
|
+
const out = {};
|
|
198
|
+
const expand = (s, scope) => s.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (m, a, b) => scope[a || b] ?? '');
|
|
199
|
+
const value = (s, scope) => {
|
|
200
|
+
if (s[0] === '"') {
|
|
201
|
+
const end = s.lastIndexOf('"');
|
|
202
|
+
return expand(end > 0 ? s.slice(1, end) : s.slice(1), scope);
|
|
203
|
+
}
|
|
204
|
+
if (s[0] === "'") {
|
|
205
|
+
const end = s.lastIndexOf("'");
|
|
206
|
+
return end > 0 ? s.slice(1, end) : s.slice(1);
|
|
207
|
+
}
|
|
208
|
+
const cut = s.search(/\s#/); // 没加引号的值,到「 #」为止
|
|
209
|
+
return expand(cut >= 0 ? s.slice(0, cut) : s, scope).trim();
|
|
210
|
+
};
|
|
211
|
+
for (const raw of String(text).split(/\r?\n/)) {
|
|
212
|
+
const line = raw.trim();
|
|
213
|
+
if (!line || line.startsWith('#')) continue;
|
|
214
|
+
const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
|
|
215
|
+
if (m) out[m[1]] = value(m[2].trim(), { ...env, ...out });
|
|
216
|
+
}
|
|
217
|
+
return out;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// local.env 写得对不对:引用了没定义的变量(到头来是个空值,和你以为的配置不一样)、不是 KEY=VALUE 的行。给 work-rhythm check 用
|
|
221
|
+
function lintLocalEnv(text, env = process.env) {
|
|
222
|
+
const problems = [];
|
|
223
|
+
const defined = { ...env };
|
|
224
|
+
let n = 0;
|
|
225
|
+
for (const raw of String(text).split(/\r?\n/)) {
|
|
226
|
+
n += 1;
|
|
227
|
+
const line = raw.trim();
|
|
228
|
+
if (!line || line.startsWith('#')) continue;
|
|
229
|
+
const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
|
|
230
|
+
if (!m) {
|
|
231
|
+
problems.push(`第 ${n} 行不是 KEY=VALUE 的写法:${line}`);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
// 单引号里的 $ 是原样文字,不算引用
|
|
235
|
+
if (!m[2].trim().startsWith("'")) {
|
|
236
|
+
for (const ref of m[2].matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g)) {
|
|
237
|
+
if (defined[ref[1] || ref[2]] === undefined) problems.push(`第 ${n} 行引用了未定义的变量 ${ref[1] || ref[2]}`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
defined[m[1]] = parseLocalEnv(line, env)[m[1]] ?? '';
|
|
241
|
+
}
|
|
242
|
+
return problems;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const loadLocalEnv = (root, env = process.env) => parseLocalEnv(readText(path.join(root, 'collectors', 'local.env')), env);
|
|
246
|
+
|
|
247
|
+
// 设置 = 环境变量,上面盖一层 local.env(和原来 source 的效果一样)
|
|
248
|
+
const settings = (root, env = process.env) => ({ ...env, ...loadLocalEnv(root, env) });
|
|
249
|
+
|
|
250
|
+
module.exports = { MARKER, findWorkdir, parseYaml, parseLocalEnv, lintLocalEnv, loadProfile, loadSources, loadLocalEnv, settings };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// macOS 上让值守、本地服务常驻:写一个 launchd 的 plist,装上、卸掉、看在不在跑。
|
|
2
|
+
// 常驻的程序就是 work-rhythm 自己:<node> <入口> <子命令> --workdir <工作目录>。别的系统手动跑,或自己配 systemd
|
|
3
|
+
'use strict';
|
|
4
|
+
const { spawnSync } = require('node:child_process');
|
|
5
|
+
const fs = require('node:fs');
|
|
6
|
+
const os = require('node:os');
|
|
7
|
+
const path = require('node:path');
|
|
8
|
+
const { UsageError, tail } = require('./run');
|
|
9
|
+
|
|
10
|
+
// kind 是 bot(值守)或 service(本地服务);label 里带上工作目录的名字,几个工作目录各装各的
|
|
11
|
+
const slug = (root) => path.basename(root).toLowerCase().replace(/[^a-z0-9.-]+/g, '-');
|
|
12
|
+
const label = (kind, root) => `work-rhythm.${kind}.${slug(root)}`;
|
|
13
|
+
const plistPath = (kind, root) => path.join(os.homedir(), 'Library', 'LaunchAgents', `${label(kind, root)}.plist`);
|
|
14
|
+
const domain = () => `gui/${os.userInfo().uid}`;
|
|
15
|
+
|
|
16
|
+
function needLaunchd() {
|
|
17
|
+
if (process.platform !== 'darwin') throw new UsageError('常驻只在 macOS 上用 launchd;别的系统手动跑,或自己配 systemd');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function bootout(kind, root) {
|
|
21
|
+
spawnSync('launchctl', ['bootout', `${domain()}/${label(kind, root)}`], { encoding: 'utf8' });
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const escapeXml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
25
|
+
|
|
26
|
+
// 写 plist 并装上。args 是子命令和它的参数(跟在入口后面)。日志写进 logFile
|
|
27
|
+
function install({ kind, root, entry, args, logFile }) {
|
|
28
|
+
needLaunchd();
|
|
29
|
+
const plist = plistPath(kind, root);
|
|
30
|
+
const xml = `<?xml version="1.0" encoding="UTF-8"?>
|
|
31
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
32
|
+
<plist version="1.0">
|
|
33
|
+
<dict>
|
|
34
|
+
<key>Label</key><string>${escapeXml(label(kind, root))}</string>
|
|
35
|
+
<key>ProgramArguments</key>
|
|
36
|
+
<array>
|
|
37
|
+
<string>${escapeXml(process.execPath)}</string>
|
|
38
|
+
<string>${escapeXml(entry)}</string>
|
|
39
|
+
${args.map((a) => ` <string>${escapeXml(a)}</string>`).join('\n')}
|
|
40
|
+
</array>
|
|
41
|
+
<key>WorkingDirectory</key><string>${escapeXml(root)}</string>
|
|
42
|
+
<key>EnvironmentVariables</key>
|
|
43
|
+
<dict>
|
|
44
|
+
<key>PATH</key><string>${escapeXml(path.dirname(process.execPath))}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
|
|
45
|
+
<key>HOME</key><string>${escapeXml(os.homedir())}</string>
|
|
46
|
+
<key>LANG</key><string>zh_CN.UTF-8</string>
|
|
47
|
+
</dict>
|
|
48
|
+
<key>RunAtLoad</key><true/>
|
|
49
|
+
<key>KeepAlive</key><true/>
|
|
50
|
+
<key>ProcessType</key><string>Background</string>
|
|
51
|
+
<key>StandardOutPath</key><string>${escapeXml(logFile)}</string>
|
|
52
|
+
<key>StandardErrorPath</key><string>${escapeXml(logFile)}</string>
|
|
53
|
+
</dict>
|
|
54
|
+
</plist>
|
|
55
|
+
`;
|
|
56
|
+
fs.mkdirSync(path.dirname(plist), { recursive: true });
|
|
57
|
+
fs.writeFileSync(plist, xml);
|
|
58
|
+
bootout(kind, root);
|
|
59
|
+
const r = spawnSync('launchctl', ['bootstrap', domain(), plist], { encoding: 'utf8' });
|
|
60
|
+
if (r.status !== 0) throw new Error(`launchctl 没能启动它:${tail(r.stderr)}`);
|
|
61
|
+
return plist;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function uninstall(kind, root) {
|
|
65
|
+
needLaunchd();
|
|
66
|
+
bootout(kind, root);
|
|
67
|
+
try {
|
|
68
|
+
fs.unlinkSync(plistPath(kind, root));
|
|
69
|
+
} catch {
|
|
70
|
+
// 本来就没装
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// 在不在跑。launchctl print 的输出里有「pid = N」就是在跑
|
|
75
|
+
function status(kind, root) {
|
|
76
|
+
needLaunchd();
|
|
77
|
+
const r = spawnSync('launchctl', ['print', `${domain()}/${label(kind, root)}`], { encoding: 'utf8' });
|
|
78
|
+
const pid = r.status === 0 ? /\bpid = (\d+)/.exec(r.stdout || '') : null;
|
|
79
|
+
return { running: r.status === 0, pid: pid ? Number(pid[1]) : 0 };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
module.exports = { label, plistPath, install, uninstall, status };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// 写 01-inbox/ 下的运行日志:一行一条,同时写文件和标准错误。地址、报错里带回的 token 打码。
|
|
2
|
+
// 不记消息内容——调用方传进来的 fields 只放时间、ID、耗时、退出码这类东西
|
|
3
|
+
'use strict';
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const { fmtStamp } = require('./run');
|
|
7
|
+
const { mask } = require('./robot');
|
|
8
|
+
|
|
9
|
+
function logger(file) {
|
|
10
|
+
return (event, fields = '') => {
|
|
11
|
+
const line = mask(`${fmtStamp()} ${event}${fields ? ' ' + fields : ''}`);
|
|
12
|
+
try {
|
|
13
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
14
|
+
fs.appendFileSync(file, line + '\n');
|
|
15
|
+
} catch {
|
|
16
|
+
// 日志写不进去不影响运行
|
|
17
|
+
}
|
|
18
|
+
process.stderr.write(line + '\n');
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
module.exports = { logger };
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// 够用的 Markdown 转 HTML:标题、段落、有序无序列表(含嵌套和勾选框)、表格、代码块、引用、分隔线,
|
|
2
|
+
// 行内有粗体、斜体、代码、链接。只为把工作目录里的 Markdown 现渲染成给人看的页面(docs/formats.md 的「视图」),
|
|
3
|
+
// 不是通用解析器。只用 node 自带的能力。
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
function escapeHtml(s) {
|
|
7
|
+
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// 行内标记。代码段先换成占位符,免得里面的星号、方括号被当成标记
|
|
11
|
+
function inline(text) {
|
|
12
|
+
const codes = [];
|
|
13
|
+
let s = String(text).replace(/`([^`]+)`/g, (m, code) => {
|
|
14
|
+
codes.push(`<code>${escapeHtml(code)}</code>`);
|
|
15
|
+
return `\u0000${codes.length - 1}\u0000`;
|
|
16
|
+
});
|
|
17
|
+
s = escapeHtml(s);
|
|
18
|
+
s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, label, url) => {
|
|
19
|
+
// 只放行 http(s)、mailto、本站相对地址;别的协议(javascript: 之类)当文字显示
|
|
20
|
+
if (!/^(https?:|mailto:|\/|\.\/|\.\.\/|#)/i.test(url)) return m;
|
|
21
|
+
return `<a href="${url}">${label}</a>`;
|
|
22
|
+
});
|
|
23
|
+
s = s.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
|
|
24
|
+
s = s.replace(/(^|[\s((])\*([^*\s][^*\n]*)\*/g, '$1<em>$2</em>');
|
|
25
|
+
return s.replace(/\u0000(\d+)\u0000/g, (m, i) => codes[i]);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function cells(line) {
|
|
29
|
+
let s = line.trim();
|
|
30
|
+
if (s.startsWith('|')) s = s.slice(1);
|
|
31
|
+
if (s.endsWith('|')) s = s.slice(0, -1);
|
|
32
|
+
return s.split('|').map((c) => c.trim());
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isSeparator(line) {
|
|
36
|
+
return /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(line) && line.includes('-');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isBlockStart(line) {
|
|
40
|
+
return /^(#{1,6})\s/.test(line) || /^```/.test(line) || /^>\s?/.test(line) || /^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(line)
|
|
41
|
+
|| /^(\s*)([-*+]|\d+[.)])\s+/.test(line);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// 从第 i 行起解析一个列表,返回 [html, 下一个下标]。缩进更深的是上一项的子内容
|
|
45
|
+
function parseList(lines, i) {
|
|
46
|
+
const first = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(lines[i]);
|
|
47
|
+
const base = first[1].length;
|
|
48
|
+
const ordered = /\d/.test(first[2]);
|
|
49
|
+
const items = [];
|
|
50
|
+
while (i < lines.length) {
|
|
51
|
+
const m = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(lines[i]);
|
|
52
|
+
if (!m || m[1].length !== base || /\d/.test(m[2]) !== ordered) break;
|
|
53
|
+
let head = m[3];
|
|
54
|
+
i += 1;
|
|
55
|
+
const rest = [];
|
|
56
|
+
// 接下来缩进更深的行、以及夹在中间的空行,都属于这一项
|
|
57
|
+
while (i < lines.length) {
|
|
58
|
+
const l = lines[i];
|
|
59
|
+
if (!l.trim()) {
|
|
60
|
+
const next = lines.slice(i + 1).find((x) => x.trim());
|
|
61
|
+
if (next && /^ */.exec(next)[0].length > base) rest.push('');
|
|
62
|
+
else break;
|
|
63
|
+
i += 1;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (/^ */.exec(l)[0].length > base) rest.push(l.slice(Math.min(base + 2, /^ */.exec(l)[0].length)));
|
|
67
|
+
else break;
|
|
68
|
+
i += 1;
|
|
69
|
+
}
|
|
70
|
+
while (rest.length && !rest[rest.length - 1].trim()) rest.pop();
|
|
71
|
+
items.push({ head, body: rest.join('\n') });
|
|
72
|
+
}
|
|
73
|
+
const html = items.map((it) => {
|
|
74
|
+
let head = it.head;
|
|
75
|
+
let box = '';
|
|
76
|
+
const cb = /^\[( |x|X)\]\s+(.*)$/.exec(head);
|
|
77
|
+
if (cb) {
|
|
78
|
+
box = `<input type="checkbox" disabled${cb[1] === ' ' ? '' : ' checked'}> `;
|
|
79
|
+
head = cb[2];
|
|
80
|
+
}
|
|
81
|
+
const inner = inline(head) + (it.body.trim() ? `\n${render(it.body)}` : '');
|
|
82
|
+
return `<li>${box}${inner}</li>`;
|
|
83
|
+
}).join('\n');
|
|
84
|
+
return [`<${ordered ? 'ol' : 'ul'}>\n${html}\n</${ordered ? 'ol' : 'ul'}>`, i];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function table(lines, i) {
|
|
88
|
+
const head = cells(lines[i]);
|
|
89
|
+
const sep = cells(lines[i + 1]);
|
|
90
|
+
const align = sep.map((c) => (c.startsWith(':') && c.endsWith(':') ? 'center' : c.endsWith(':') ? 'right' : c.startsWith(':') ? 'left' : ''));
|
|
91
|
+
i += 2;
|
|
92
|
+
const rows = [];
|
|
93
|
+
while (i < lines.length && lines[i].includes('|') && lines[i].trim()) {
|
|
94
|
+
rows.push(cells(lines[i]));
|
|
95
|
+
i += 1;
|
|
96
|
+
}
|
|
97
|
+
const th = head.map((c, k) => `<th${align[k] ? ` style="text-align:${align[k]}"` : ''}>${inline(c)}</th>`).join('');
|
|
98
|
+
const tr = rows.map((r) => `<tr>${head.map((_, k) => `<td${align[k] ? ` style="text-align:${align[k]}"` : ''}>${inline(r[k] ?? '')}</td>`).join('')}</tr>`).join('\n');
|
|
99
|
+
return [`<table>\n<thead><tr>${th}</tr></thead>\n<tbody>\n${tr}\n</tbody>\n</table>`, i];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function render(md) {
|
|
103
|
+
const lines = String(md).replace(/\r\n?/g, '\n').split('\n');
|
|
104
|
+
const n = lines.length;
|
|
105
|
+
const out = [];
|
|
106
|
+
let i = 0;
|
|
107
|
+
while (i < n) {
|
|
108
|
+
const line = lines[i];
|
|
109
|
+
if (!line.trim()) {
|
|
110
|
+
i += 1;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const fence = /^```\s*(\w*)\s*$/.exec(line);
|
|
114
|
+
if (fence) {
|
|
115
|
+
i += 1;
|
|
116
|
+
const buf = [];
|
|
117
|
+
while (i < n && !/^```\s*$/.test(lines[i])) {
|
|
118
|
+
buf.push(lines[i]);
|
|
119
|
+
i += 1;
|
|
120
|
+
}
|
|
121
|
+
i += 1;
|
|
122
|
+
out.push(`<pre><code>${escapeHtml(buf.join('\n'))}</code></pre>`);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const h = /^(#{1,6})\s+(.*)$/.exec(line);
|
|
126
|
+
if (h) {
|
|
127
|
+
const level = h[1].length;
|
|
128
|
+
out.push(`<h${level}>${inline(h[2])}</h${level}>`);
|
|
129
|
+
i += 1;
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(line)) {
|
|
133
|
+
out.push('<hr>');
|
|
134
|
+
i += 1;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (/^>\s?/.test(line)) {
|
|
138
|
+
const buf = [];
|
|
139
|
+
while (i < n && /^>\s?/.test(lines[i])) {
|
|
140
|
+
buf.push(lines[i].replace(/^>\s?/, ''));
|
|
141
|
+
i += 1;
|
|
142
|
+
}
|
|
143
|
+
out.push(`<blockquote>\n${render(buf.join('\n'))}\n</blockquote>`);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (line.includes('|') && i + 1 < n && isSeparator(lines[i + 1])) {
|
|
147
|
+
const [html, next] = table(lines, i);
|
|
148
|
+
out.push(html);
|
|
149
|
+
i = next;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (/^(\s*)([-*+]|\d+[.)])\s+/.test(line)) {
|
|
153
|
+
const [html, next] = parseList(lines, i);
|
|
154
|
+
out.push(html);
|
|
155
|
+
i = next;
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const buf = [line];
|
|
159
|
+
i += 1;
|
|
160
|
+
while (i < n && lines[i].trim() && !isBlockStart(lines[i])) {
|
|
161
|
+
buf.push(lines[i]);
|
|
162
|
+
i += 1;
|
|
163
|
+
}
|
|
164
|
+
out.push(`<p>${buf.map(inline).join('<br>')}</p>`);
|
|
165
|
+
}
|
|
166
|
+
return out.join('\n');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 整页:样式内联,不引外部资源(docs/formats.md 的「视图」)
|
|
170
|
+
function page(title, body, nav = '') {
|
|
171
|
+
return `<!doctype html>
|
|
172
|
+
<html lang="zh-CN">
|
|
173
|
+
<head>
|
|
174
|
+
<meta charset="utf-8">
|
|
175
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
176
|
+
<meta name="robots" content="noindex, nofollow">
|
|
177
|
+
<title>${escapeHtml(title)}</title>
|
|
178
|
+
<style>
|
|
179
|
+
body{margin:0;padding:24px;background:#f6f7f9;color:#1f2328;font:16px/1.65 -apple-system,BlinkMacSystemFont,"PingFang SC","Helvetica Neue",Arial,sans-serif}
|
|
180
|
+
main{max-width:860px;margin:0 auto;background:#fff;border-radius:8px;padding:28px 32px;box-shadow:0 1px 3px rgba(0,0,0,.06)}
|
|
181
|
+
nav{max-width:860px;margin:0 auto 12px;font-size:14px;color:#57606a}
|
|
182
|
+
nav a{color:#0969da;text-decoration:none;margin-right:14px}
|
|
183
|
+
h1{font-size:26px;margin:0 0 16px}
|
|
184
|
+
h2{font-size:20px;margin:28px 0 10px;padding-bottom:6px;border-bottom:1px solid #d0d7de}
|
|
185
|
+
h3{font-size:17px;margin:20px 0 8px}
|
|
186
|
+
table{border-collapse:collapse;width:100%;margin:10px 0;font-size:14px}
|
|
187
|
+
th,td{border:1px solid #d0d7de;padding:6px 10px;text-align:left;vertical-align:top}
|
|
188
|
+
th{background:#f6f8fa}
|
|
189
|
+
tbody tr:nth-child(even){background:#fafbfc}
|
|
190
|
+
code{background:#eff1f3;border-radius:4px;padding:1px 5px;font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
191
|
+
pre{background:#f6f8fa;border-radius:6px;padding:12px;overflow:auto}
|
|
192
|
+
pre code{background:none;padding:0}
|
|
193
|
+
blockquote{margin:10px 0;padding:6px 14px;border-left:4px solid #d0d7de;color:#57606a;background:#fafbfc}
|
|
194
|
+
hr{border:0;border-top:1px solid #d0d7de;margin:20px 0}
|
|
195
|
+
.muted{color:#57606a;font-size:14px}
|
|
196
|
+
</style>
|
|
197
|
+
</head>
|
|
198
|
+
<body>
|
|
199
|
+
${nav ? `<nav>${nav}</nav>` : ''}
|
|
200
|
+
<main>
|
|
201
|
+
${body}
|
|
202
|
+
</main>
|
|
203
|
+
</body>
|
|
204
|
+
</html>
|
|
205
|
+
`;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
module.exports = { render, page, inline, escapeHtml };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// 推送的出口:按 profile 的 preferences.notify 选渠道,把一段文字发给我本人。
|
|
2
|
+
// notify 命令、值守(bot.js)、本地服务(rhythm.js)都走这里,钥匙串读取、打码、失败处理只维护一处
|
|
3
|
+
'use strict';
|
|
4
|
+
const { EXIT, which, run, tail } = require('./run');
|
|
5
|
+
const { loadProfile } = require('./config');
|
|
6
|
+
const { findWebhook, mask, postRobot } = require('./robot');
|
|
7
|
+
|
|
8
|
+
// profile 里 preferences.notify 的值:渠道的名字,没配是空串
|
|
9
|
+
function notifyChannel(root) {
|
|
10
|
+
const value = loadProfile(root).preferences;
|
|
11
|
+
return value && typeof value.notify === 'string' ? value.notify.trim() : '';
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// 渠道 yzj-robot:收件人 openId 取 collectors/local.env 的 YZJ_MY_OPEN_ID,没配就用 yzj-cli whoami 现取
|
|
15
|
+
function resolveOpenId(env) {
|
|
16
|
+
if (env.YZJ_MY_OPEN_ID && env.YZJ_MY_OPEN_ID.trim()) return env.YZJ_MY_OPEN_ID.trim();
|
|
17
|
+
if (!which('yzj-cli', env)) return '';
|
|
18
|
+
const r = run('yzj-cli', ['whoami', '--jq', '.data.openId'], { env });
|
|
19
|
+
return r.code === 0 ? r.stdout.trim() : '';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// 发一段文字。返回 { ok, msgId, groupId };没发成时 { ok: false, code, reason },code 是该用的退出码。
|
|
23
|
+
// 渠道留空时 skipped 为 true(什么都不发,不算错)。env 是设置(环境变量,上面盖一层 local.env)
|
|
24
|
+
async function pushText(root, text, { env, fetchImpl } = {}) {
|
|
25
|
+
const channel = notifyChannel(root);
|
|
26
|
+
if (!channel) return { ok: false, skipped: true, code: EXIT.OK, reason: 'preferences.notify 留空,不推送(只写文件)' };
|
|
27
|
+
if (channel !== 'yzj-robot') {
|
|
28
|
+
return { ok: false, code: EXIT.USAGE, reason: `不认识的渠道「${channel}」。内置的只有 yzj-robot;别的 IM 先按 docs/channels.md「新增一个渠道」接好` };
|
|
29
|
+
}
|
|
30
|
+
const found = findWebhook(env);
|
|
31
|
+
if (found.problem) return { ok: false, code: found.code, reason: found.problem };
|
|
32
|
+
const openId = resolveOpenId(env);
|
|
33
|
+
if (!openId) return { ok: false, code: EXIT.NOT_CONFIGURED, reason: '取不到我的 openId。在 collectors/local.env 里写 YZJ_MY_OPEN_ID,或重新 yzj-cli auth login' };
|
|
34
|
+
const r = await postRobot(found.webhook, { msgtype: 2, content: text, notifyParams: [{ type: 'openIds', values: [openId] }] }, { fetchImpl });
|
|
35
|
+
if (r.ok) {
|
|
36
|
+
const data = (r.body && r.body.data) || {};
|
|
37
|
+
return { ok: true, msgId: data.msgId || '-', groupId: data.groupId || '-' };
|
|
38
|
+
}
|
|
39
|
+
const reason = r.status === 0 ? `请求没发出去: ${r.error}` : `云之家没有接受这条消息(HTTP ${r.status}): ${tail(r.text, 300)}`;
|
|
40
|
+
return { ok: false, code: EXIT.FAILED, reason: mask(reason) };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
module.exports = { notifyChannel, resolveOpenId, pushText };
|