@online-tools/work-agent-runner 0.0.4-alpha-1 → 0.0.5-alpha-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/README.md +34 -10
- package/bin/main.mjs +346 -95
- package/lib/config.mjs +211 -36
- package/lib/doctor.mjs +3 -1
- package/lib/fs-safe.mjs +163 -0
- package/lib/jobs.mjs +50 -4
- package/lib/lock.mjs +114 -15
- package/lib/sandbox.mjs +6 -3
- package/lib/service.mjs +85 -26
- package/lib/skill-tree.mjs +24 -6
- package/lib/work-agent.mjs +380 -76
- package/package.json +1 -1
package/lib/lock.mjs
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// Lock files holding their owner's pid: run.lock (one running instance per
|
|
2
|
+
// program home), work-agent.lock (the clone), config.lock (read-modify-write
|
|
3
|
+
// of config.json). A lock whose pid is gone (or now belongs to some other
|
|
4
|
+
// program) is taken over.
|
|
5
|
+
//
|
|
6
|
+
// A lock is created with its content in one step (a temporary file
|
|
7
|
+
// hard-linked into place), so nobody ever reads an empty lock and takes it
|
|
8
|
+
// for a dead one; taking over a dead lock happens under <lock>.takeover, so
|
|
9
|
+
// two processes cannot both take it over.
|
|
3
10
|
|
|
4
11
|
import { spawnSync } from 'node:child_process';
|
|
12
|
+
import crypto from 'node:crypto';
|
|
5
13
|
import fs from 'node:fs';
|
|
6
14
|
|
|
15
|
+
// A takeover directory older than this was left by a process that died taking over.
|
|
16
|
+
const TAKEOVER_STALE_MS = 30_000;
|
|
17
|
+
const NO_HARD_LINKS = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS']);
|
|
18
|
+
|
|
7
19
|
export class LockedError extends Error {
|
|
8
|
-
constructor(pid) {
|
|
9
|
-
super(`已有实例在运行(pid ${pid},可能是后台服务,见 work-agent-runner service status)`);
|
|
20
|
+
constructor(pid, message = '') {
|
|
21
|
+
super(message || `已有实例在运行(pid ${pid},可能是后台服务,见 work-agent-runner service status)`);
|
|
10
22
|
this.pid = pid;
|
|
11
23
|
}
|
|
12
24
|
}
|
|
@@ -47,24 +59,111 @@ export function lockHolder(file) {
|
|
|
47
59
|
}
|
|
48
60
|
}
|
|
49
61
|
|
|
62
|
+
function sleepSync(ms) {
|
|
63
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Creates `file` holding `pid` in one step; false when it already exists. */
|
|
67
|
+
function createLockFile(file, pid) {
|
|
68
|
+
const temp = `${file}.${pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
69
|
+
fs.writeFileSync(temp, String(pid), { mode: 0o600 });
|
|
70
|
+
try {
|
|
71
|
+
fs.linkSync(temp, file);
|
|
72
|
+
return true;
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (error.code === 'EEXIST') return false;
|
|
75
|
+
if (!NO_HARD_LINKS.has(error.code)) throw error;
|
|
76
|
+
// No hard links on this filesystem: exclusive create, then the pid.
|
|
77
|
+
try {
|
|
78
|
+
const fd = fs.openSync(file, 'wx', 0o600);
|
|
79
|
+
try {
|
|
80
|
+
fs.writeSync(fd, String(pid));
|
|
81
|
+
} finally {
|
|
82
|
+
fs.closeSync(fd);
|
|
83
|
+
}
|
|
84
|
+
return true;
|
|
85
|
+
} catch (fallback) {
|
|
86
|
+
if (fallback.code === 'EEXIST') return false;
|
|
87
|
+
throw fallback;
|
|
88
|
+
}
|
|
89
|
+
} finally {
|
|
90
|
+
fs.rmSync(temp, { force: true });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Removes a dead holder's lock; one taker at a time, and only if it is still that holder's. */
|
|
95
|
+
function takeOver(file, deadHolder) {
|
|
96
|
+
const guard = `${file}.takeover`;
|
|
97
|
+
try {
|
|
98
|
+
fs.mkdirSync(guard);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (error.code !== 'EEXIST') throw error;
|
|
101
|
+
try {
|
|
102
|
+
if (Date.now() - fs.statSync(guard).mtimeMs > TAKEOVER_STALE_MS) fs.rmdirSync(guard);
|
|
103
|
+
} catch {
|
|
104
|
+
// Gone already.
|
|
105
|
+
}
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
const holder = lockHolder(file);
|
|
110
|
+
const stillDead = holder === deadHolder || !Number.isInteger(holder) || holder <= 0;
|
|
111
|
+
if (stillDead) fs.rmSync(file, { force: true });
|
|
112
|
+
} finally {
|
|
113
|
+
fs.rmSync(guard, { recursive: true, force: true });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
50
117
|
/** Takes the lock or throws LockedError. Returns { release() }. */
|
|
51
118
|
export function acquireLock(file, { pid = process.pid, isAlive = isRunnerAlive } = {}) {
|
|
52
119
|
const release = () => {
|
|
53
120
|
if (lockHolder(file) === pid) fs.rmSync(file, { force: true });
|
|
54
121
|
};
|
|
55
|
-
for (let attempt = 0; attempt <
|
|
56
|
-
|
|
57
|
-
const fd = fs.openSync(file, 'wx', 0o600);
|
|
58
|
-
fs.writeSync(fd, String(pid));
|
|
59
|
-
fs.closeSync(fd);
|
|
60
|
-
return { release };
|
|
61
|
-
} catch (error) {
|
|
62
|
-
if (error.code !== 'EEXIST') throw error;
|
|
63
|
-
}
|
|
122
|
+
for (let attempt = 0; attempt < 10; attempt += 1) {
|
|
123
|
+
if (createLockFile(file, pid)) return { release };
|
|
64
124
|
const holder = lockHolder(file);
|
|
65
125
|
if (holder === pid) return { release };
|
|
66
126
|
if (Number.isInteger(holder) && holder > 0 && isAlive(holder)) throw new LockedError(holder);
|
|
67
|
-
|
|
127
|
+
takeOver(file, holder); // left behind by a dead process
|
|
128
|
+
if (attempt > 0) sleepSync(20);
|
|
129
|
+
}
|
|
130
|
+
throw new Error(`无法获取锁 ${file}`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** acquireLock, retried for up to `timeoutMs` while someone else holds it. */
|
|
134
|
+
export async function acquireLockWaiting(file, { timeoutMs = 0, pollMs = 1000, onWait = () => {}, ...options } = {}) {
|
|
135
|
+
const deadline = Date.now() + timeoutMs;
|
|
136
|
+
let told = false;
|
|
137
|
+
for (;;) {
|
|
138
|
+
try {
|
|
139
|
+
return acquireLock(file, options);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (!(error instanceof LockedError) || Date.now() >= deadline) throw error;
|
|
142
|
+
if (!told) {
|
|
143
|
+
told = true;
|
|
144
|
+
onWait(error.pid);
|
|
145
|
+
}
|
|
146
|
+
await new Promise((resolve) => setTimeout(resolve, Math.max(1, Math.min(pollMs, deadline - Date.now()))));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Runs `fn` under the lock, waiting (synchronously, briefly) for it; for short critical sections. */
|
|
152
|
+
export function withFileLockSync(file, fn, { timeoutMs = 10_000, ...options } = {}) {
|
|
153
|
+
const deadline = Date.now() + timeoutMs;
|
|
154
|
+
let lock;
|
|
155
|
+
for (;;) {
|
|
156
|
+
try {
|
|
157
|
+
lock = acquireLock(file, options);
|
|
158
|
+
break;
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (!(error instanceof LockedError) || Date.now() >= deadline) throw error;
|
|
161
|
+
sleepSync(50);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
return fn();
|
|
166
|
+
} finally {
|
|
167
|
+
lock.release();
|
|
68
168
|
}
|
|
69
|
-
throw new Error(`无法获取运行锁 ${file}`);
|
|
70
169
|
}
|
package/lib/sandbox.mjs
CHANGED
|
@@ -153,10 +153,13 @@ export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], po
|
|
|
153
153
|
];
|
|
154
154
|
const deny = [];
|
|
155
155
|
if (paths) {
|
|
156
|
-
// The access token, and the clone every job copies from
|
|
156
|
+
// The access token, and the clone every job copies from: by the path the
|
|
157
|
+
// program uses and by the real one, so a home behind a symlink (/home ->
|
|
158
|
+
// /data/home) cannot open them by the other name.
|
|
157
159
|
for (const file of [paths.configFile, paths.repoDir]) {
|
|
158
|
-
|
|
159
|
-
|
|
160
|
+
for (const at of new Set([path.resolve(file), realpathOr(file)])) {
|
|
161
|
+
deny.push(`Read(//${fromRoot(at)}/**)`, `Read(//${fromRoot(at)})`, `Edit(//${fromRoot(at)}/**)`, `Edit(//${fromRoot(at)})`);
|
|
162
|
+
}
|
|
160
163
|
}
|
|
161
164
|
}
|
|
162
165
|
// The pool is shared with the user's own work-agent: read it, never write it.
|
package/lib/service.mjs
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
// Background service: a systemd user unit (Linux) or a launchd agent (macOS).
|
|
2
|
-
// Services do not inherit the shell environment, so PATH
|
|
3
|
-
//
|
|
4
|
-
// written into the definition (file mode 0600: proxy URLs may hold
|
|
2
|
+
// Services do not inherit the shell environment, so PATH, the pass-through
|
|
3
|
+
// variables (proxies, CA bundles, language) and WORK_AGENT_RUNNER_HOME present
|
|
4
|
+
// now are written into the definition (file mode 0600: proxy URLs may hold
|
|
5
|
+
// passwords). A program home other than the default gets a service of its
|
|
6
|
+
// own, named with a short hash of its path.
|
|
5
7
|
|
|
6
8
|
import { spawnSync } from 'node:child_process';
|
|
9
|
+
import crypto from 'node:crypto';
|
|
7
10
|
import fs from 'node:fs';
|
|
8
11
|
import os from 'node:os';
|
|
9
12
|
import path from 'node:path';
|
|
10
13
|
|
|
14
|
+
import { PROGRAM_DIR, configPaths } from './config.mjs';
|
|
11
15
|
import { PASS_THROUGH_VARIABLES, PROXY_VARIABLES } from './sandbox.mjs';
|
|
12
16
|
import { redactUrl } from './log.mjs';
|
|
13
17
|
|
|
@@ -23,16 +27,35 @@ export function serviceExitCode(code, env = process.env) {
|
|
|
23
27
|
return code === EXIT_NEEDS_ATTENTION && env.GC_RUNNER_SERVICE === 'launchd' ? 0 : code;
|
|
24
28
|
}
|
|
25
29
|
|
|
30
|
+
function realpathOr(value) {
|
|
31
|
+
try {
|
|
32
|
+
return fs.realpathSync(value);
|
|
33
|
+
} catch {
|
|
34
|
+
return path.resolve(value);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
26
38
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
|
|
39
|
+
* '' for the default program home (~/.work-agent-runner), else '-' and the
|
|
40
|
+
* first 8 hex digits of the SHA-256 of its real path: one service per program
|
|
41
|
+
* home, and two homes never share a definition.
|
|
42
|
+
*/
|
|
43
|
+
export function serviceSuffix({ env = process.env, home = os.homedir() } = {}) {
|
|
44
|
+
const programHome = configPaths(env, home).baseDir;
|
|
45
|
+
if (realpathOr(programHome) === realpathOr(path.join(home, PROGRAM_DIR))) return '';
|
|
46
|
+
return `-${crypto.createHash('sha256').update(realpathOr(programHome)).digest('hex').slice(0, 8)}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* PATH, the pass-through variables that are set, WORK_AGENT_RUNNER_HOME when
|
|
51
|
+
* the program's home is not the default one (else the service would read
|
|
52
|
+
* another home, without the token), NODE_USE_ENV_PROXY with a proxy, and the
|
|
53
|
+
* service marker. WORK_AGENT_HOME is not needed: config.json records it.
|
|
31
54
|
*/
|
|
32
55
|
export function serviceEnvironment(env, kind) {
|
|
33
56
|
const out = { PATH: env.PATH || '/usr/local/bin:/usr/bin:/bin' };
|
|
34
57
|
for (const name of PASS_THROUGH_VARIABLES) if (env[name]) out[name] = env[name];
|
|
35
|
-
if (env.
|
|
58
|
+
if (env.WORK_AGENT_RUNNER_HOME) out.WORK_AGENT_RUNNER_HOME = path.resolve(env.WORK_AGENT_RUNNER_HOME);
|
|
36
59
|
if (PROXY_VARIABLES.some((name) => env[name] && !/^no_proxy$/i.test(name))) out.NODE_USE_ENV_PROXY = '1';
|
|
37
60
|
out.GC_RUNNER_SERVICE = kind;
|
|
38
61
|
return out;
|
|
@@ -83,7 +106,7 @@ function xml(value) {
|
|
|
83
106
|
return String(value).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
84
107
|
}
|
|
85
108
|
|
|
86
|
-
export function launchdPlist({ nodePath, entry, args = ['start'], environment, logFile }) {
|
|
109
|
+
export function launchdPlist({ nodePath, entry, args = ['start'], environment, logFile, label = LAUNCHD_LABEL }) {
|
|
87
110
|
const strings = (items) => items.map((item) => ` <string>${xml(item)}</string>`).join('\n');
|
|
88
111
|
const variables = Object.entries(environment)
|
|
89
112
|
.map(([name, value]) => ` <key>${xml(name)}</key>\n <string>${xml(value)}</string>`)
|
|
@@ -93,7 +116,7 @@ export function launchdPlist({ nodePath, entry, args = ['start'], environment, l
|
|
|
93
116
|
<plist version="1.0">
|
|
94
117
|
<dict>
|
|
95
118
|
<key>Label</key>
|
|
96
|
-
<string>${
|
|
119
|
+
<string>${xml(label)}</string>
|
|
97
120
|
<key>ProgramArguments</key>
|
|
98
121
|
<array>
|
|
99
122
|
${strings([nodePath, entry, ...args])}
|
|
@@ -119,22 +142,25 @@ ${variables}
|
|
|
119
142
|
}
|
|
120
143
|
|
|
121
144
|
export function servicePaths({ platform = process.platform, home = os.homedir(), env = process.env } = {}) {
|
|
145
|
+
const suffix = serviceSuffix({ env, home });
|
|
122
146
|
if (platform === 'darwin') {
|
|
123
147
|
const agents = path.join(home, 'Library', 'LaunchAgents');
|
|
148
|
+
const label = `${LAUNCHD_LABEL}${suffix}`;
|
|
124
149
|
return {
|
|
125
150
|
kind: 'launchd',
|
|
126
|
-
name:
|
|
127
|
-
file: path.join(agents, `${
|
|
151
|
+
name: label,
|
|
152
|
+
file: path.join(agents, `${label}.plist`),
|
|
128
153
|
legacyName: LEGACY_LAUNCHD_LABEL,
|
|
129
154
|
legacyFile: path.join(agents, `${LEGACY_LAUNCHD_LABEL}.plist`),
|
|
130
|
-
logFile: path.join(home, 'Library', 'Logs', `${SERVICE_NAME}.log`),
|
|
155
|
+
logFile: path.join(home, 'Library', 'Logs', `${SERVICE_NAME}${suffix}.log`),
|
|
131
156
|
};
|
|
132
157
|
}
|
|
133
158
|
const units = path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'systemd', 'user');
|
|
159
|
+
const name = `${SERVICE_NAME}${suffix}`;
|
|
134
160
|
return {
|
|
135
161
|
kind: 'systemd',
|
|
136
|
-
name
|
|
137
|
-
file: path.join(units, `${
|
|
162
|
+
name,
|
|
163
|
+
file: path.join(units, `${name}.service`),
|
|
138
164
|
legacyName: LEGACY_SERVICE_NAME,
|
|
139
165
|
legacyFile: path.join(units, `${LEGACY_SERVICE_NAME}.service`),
|
|
140
166
|
logFile: '',
|
|
@@ -146,6 +172,11 @@ function run(command, args, { quiet = false } = {}) {
|
|
|
146
172
|
return { ok: result.status === 0, status: result.status, stdout: result.stdout || '', stderr: result.stderr || '', error: result.error };
|
|
147
173
|
}
|
|
148
174
|
|
|
175
|
+
/** How to read the service's own output. */
|
|
176
|
+
function logHintFor(paths) {
|
|
177
|
+
return paths.kind === 'launchd' ? `日志:${paths.logFile}` : `日志:journalctl --user -u ${paths.name} -f`;
|
|
178
|
+
}
|
|
179
|
+
|
|
149
180
|
/** Writes the definition (0600), loads it and (re)starts the service. */
|
|
150
181
|
export function installService({ platform = process.platform, nodePath, entry, args, env = process.env, say }) {
|
|
151
182
|
const paths = servicePaths({ platform, env });
|
|
@@ -155,24 +186,52 @@ export function installService({ platform = process.platform, nodePath, entry, a
|
|
|
155
186
|
fs.mkdirSync(path.dirname(paths.file), { recursive: true, mode: 0o700 });
|
|
156
187
|
if (paths.kind === 'launchd') {
|
|
157
188
|
fs.mkdirSync(path.dirname(paths.logFile), { recursive: true });
|
|
158
|
-
fs.writeFileSync(paths.file, launchdPlist({ nodePath, entry, args, environment, logFile: paths.logFile }), { mode: 0o600 });
|
|
189
|
+
fs.writeFileSync(paths.file, launchdPlist({ nodePath, entry, args, environment, logFile: paths.logFile, label: paths.name }), { mode: 0o600 });
|
|
159
190
|
fs.chmodSync(paths.file, 0o600);
|
|
160
191
|
const domain = `gui/${process.getuid()}`;
|
|
161
|
-
run('launchctl', ['bootout', `${domain}/${
|
|
192
|
+
run('launchctl', ['bootout', `${domain}/${paths.name}`], { quiet: true }); // an older definition, if loaded
|
|
162
193
|
const loaded = run('launchctl', ['bootstrap', domain, paths.file]);
|
|
163
194
|
if (!loaded.ok) throw new Error('launchctl bootstrap 失败');
|
|
164
|
-
say(`已安装并启动后台服务(launchd
|
|
195
|
+
say(`已安装并启动后台服务(launchd,${paths.name})。${logHintFor(paths)}`);
|
|
165
196
|
return paths;
|
|
166
197
|
}
|
|
167
198
|
fs.writeFileSync(paths.file, systemdUnit({ nodePath, entry, args, environment }), { mode: 0o600 });
|
|
168
199
|
fs.chmodSync(paths.file, 0o600);
|
|
169
|
-
for (const command of [['daemon-reload'], ['enable',
|
|
200
|
+
for (const command of [['daemon-reload'], ['enable', paths.name], ['restart', paths.name]]) {
|
|
170
201
|
const result = run('systemctl', ['--user', ...command]);
|
|
171
202
|
if (!result.ok) throw new Error(`systemctl --user ${command.join(' ')} 失败`);
|
|
172
203
|
}
|
|
173
|
-
say(
|
|
204
|
+
say(`已安装并启动后台服务(systemd 用户服务 ${paths.name})。`);
|
|
174
205
|
say('退出登录后服务会停止;要让它一直运行,请让管理员执行一次:loginctl enable-linger $USER');
|
|
175
|
-
say(`查看日志:journalctl --user -u ${
|
|
206
|
+
say(`查看日志:journalctl --user -u ${paths.name} -f`);
|
|
207
|
+
return paths;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* start | stop | restart an installed service. Throws when it is not
|
|
212
|
+
* installed or the service manager refuses.
|
|
213
|
+
*/
|
|
214
|
+
export function controlService(action, { platform = process.platform, env = process.env, say }) {
|
|
215
|
+
const paths = servicePaths({ platform, env });
|
|
216
|
+
if (!fs.existsSync(paths.file)) throw new Error('后台服务还没有安装:先运行 work-agent-runner service install');
|
|
217
|
+
const labels = { start: '启动', stop: '停止', restart: '重启' };
|
|
218
|
+
if (paths.kind === 'launchd') {
|
|
219
|
+
const domain = `gui/${process.getuid()}`;
|
|
220
|
+
const target = `${domain}/${paths.name}`;
|
|
221
|
+
let result;
|
|
222
|
+
if (action === 'stop') result = run('launchctl', ['bootout', target]);
|
|
223
|
+
else if (action === 'start') result = run('launchctl', ['bootstrap', domain, paths.file]);
|
|
224
|
+
else {
|
|
225
|
+
// kickstart -k restarts a loaded job; a stopped one is loaded first.
|
|
226
|
+
result = run('launchctl', ['kickstart', '-k', target], { quiet: true });
|
|
227
|
+
if (!result.ok) result = run('launchctl', ['bootstrap', domain, paths.file]);
|
|
228
|
+
}
|
|
229
|
+
if (!result.ok) throw new Error(`launchctl 未能${labels[action]}后台服务(${paths.name})`);
|
|
230
|
+
} else {
|
|
231
|
+
const result = run('systemctl', ['--user', action, paths.name]);
|
|
232
|
+
if (!result.ok) throw new Error(`systemctl --user ${action} ${paths.name} 失败`);
|
|
233
|
+
}
|
|
234
|
+
say(`已${labels[action]}后台服务(${paths.name})。${action === 'stop' ? '' : logHintFor(paths)}`);
|
|
176
235
|
return paths;
|
|
177
236
|
}
|
|
178
237
|
|
|
@@ -211,16 +270,16 @@ export function uninstallService({ platform = process.platform, env = process.en
|
|
|
211
270
|
else if (!legacy) say('没有安装后台服务');
|
|
212
271
|
}
|
|
213
272
|
|
|
214
|
-
/** { installed, state, logHint } */
|
|
273
|
+
/** { installed, state, logHint, name } */
|
|
215
274
|
export function serviceStatus({ platform = process.platform, env = process.env } = {}) {
|
|
216
275
|
const paths = servicePaths({ platform, env });
|
|
217
276
|
const installed = fs.existsSync(paths.file);
|
|
218
277
|
if (paths.kind === 'launchd') {
|
|
219
|
-
const result = run('launchctl', ['print', `gui/${process.getuid()}/${
|
|
278
|
+
const result = run('launchctl', ['print', `gui/${process.getuid()}/${paths.name}`], { quiet: true });
|
|
220
279
|
const state = result.ok ? /state = (\w+)/.exec(result.stdout)?.[1] || '已加载' : '未加载';
|
|
221
|
-
return { installed, state, logHint:
|
|
280
|
+
return { installed, state, logHint: logHintFor(paths), name: paths.name };
|
|
222
281
|
}
|
|
223
|
-
const active = run('systemctl', ['--user', 'is-active',
|
|
282
|
+
const active = run('systemctl', ['--user', 'is-active', paths.name], { quiet: true });
|
|
224
283
|
const state = active.error ? '无法读取(systemctl 不可用)' : active.stdout.trim() || 'unknown';
|
|
225
|
-
return { installed, state, logHint:
|
|
284
|
+
return { installed, state, logHint: logHintFor(paths), name: paths.name };
|
|
226
285
|
}
|
package/lib/skill-tree.mjs
CHANGED
|
@@ -25,10 +25,14 @@ export const MAX_TOTAL_BYTES = 512 * 1024 * 1024;
|
|
|
25
25
|
* - a directory reached again through a symlink loop is not entered twice
|
|
26
26
|
* `onFile(relPath, absPath, stats)` gets every regular file; `onDir(relPath,
|
|
27
27
|
* absPath)` every directory ('' is the root) before its contents. Relative
|
|
28
|
-
* paths use '/'.
|
|
28
|
+
* paths use '/'. With `boundary` (a real path), a symlink whose target lies
|
|
29
|
+
* outside it is skipped and reported to `onSkip(relPath, target)`: a link in
|
|
30
|
+
* the work-agent clone to ../config.json must not carry the machine token into
|
|
31
|
+
* a job's directory.
|
|
29
32
|
*/
|
|
30
|
-
export function walkSkillTree(sourceDir, onFile, onDir = () => {}) {
|
|
33
|
+
export function walkSkillTree(sourceDir, onFile, onDir = () => {}, { boundary = '', onSkip = () => {} } = {}) {
|
|
31
34
|
const seen = new Set();
|
|
35
|
+
const inside = (target) => target === boundary || target.startsWith(boundary.endsWith(path.sep) ? boundary : `${boundary}${path.sep}`);
|
|
32
36
|
const walk = (dir, rel) => {
|
|
33
37
|
const real = fs.realpathSync(dir);
|
|
34
38
|
if (seen.has(real)) return; // symlink loop
|
|
@@ -38,6 +42,18 @@ export function walkSkillTree(sourceDir, onFile, onDir = () => {}) {
|
|
|
38
42
|
if (entry.name === '.git') continue;
|
|
39
43
|
const from = path.join(dir, entry.name);
|
|
40
44
|
const childRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
45
|
+
if (boundary && entry.isSymbolicLink()) {
|
|
46
|
+
let target;
|
|
47
|
+
try {
|
|
48
|
+
target = fs.realpathSync(from);
|
|
49
|
+
} catch {
|
|
50
|
+
continue; // dangling symlink
|
|
51
|
+
}
|
|
52
|
+
if (!inside(target)) {
|
|
53
|
+
onSkip(childRel, target);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
41
57
|
let stats;
|
|
42
58
|
try {
|
|
43
59
|
stats = fs.statSync(from); // follows symlinks
|
|
@@ -58,11 +74,12 @@ export function walkSkillTree(sourceDir, onFile, onDir = () => {}) {
|
|
|
58
74
|
* walkSkillTree for what is followed and skipped). The directory layout is
|
|
59
75
|
* preserved, so relative references between Skills (`../gitcode-toolkit/...`)
|
|
60
76
|
* keep working. Throws when the tree is larger than the limits above.
|
|
77
|
+
* `options.boundary` / `options.onSkip`: see walkSkillTree.
|
|
61
78
|
*/
|
|
62
|
-
export function copyTreeDetached(source, target,
|
|
63
|
-
const maxFiles =
|
|
64
|
-
const maxFileBytes =
|
|
65
|
-
const maxTotalBytes =
|
|
79
|
+
export function copyTreeDetached(source, target, options = {}) {
|
|
80
|
+
const maxFiles = options.maxFiles ?? MAX_FILES;
|
|
81
|
+
const maxFileBytes = options.maxFileBytes ?? MAX_FILE_BYTES;
|
|
82
|
+
const maxTotalBytes = options.maxTotalBytes ?? MAX_TOTAL_BYTES;
|
|
66
83
|
let files = 0;
|
|
67
84
|
let bytes = 0;
|
|
68
85
|
walkSkillTree(
|
|
@@ -78,6 +95,7 @@ export function copyTreeDetached(source, target, limits = {}) {
|
|
|
78
95
|
fs.chmodSync(to, (stats.mode & 0o777) | 0o600);
|
|
79
96
|
},
|
|
80
97
|
(rel) => fs.mkdirSync(path.join(target, rel), { recursive: true, mode: 0o700 }),
|
|
98
|
+
{ boundary: options.boundary || '', onSkip: options.onSkip },
|
|
81
99
|
);
|
|
82
100
|
return { files, bytes };
|
|
83
101
|
}
|