@online-tools/work-agent-runner 0.0.4-alpha-1 → 0.1.0-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 +127 -25
- package/bin/main.mjs +1124 -246
- package/lib/config.mjs +250 -40
- package/lib/connection.mjs +38 -1
- package/lib/control.mjs +330 -0
- package/lib/doctor.mjs +3 -1
- package/lib/errors.mjs +34 -0
- package/lib/fs-safe.mjs +163 -0
- package/lib/jobs.mjs +402 -60
- package/lib/lock.mjs +114 -15
- package/lib/log.mjs +95 -7
- package/lib/maintenance.mjs +394 -0
- package/lib/sandbox.mjs +61 -9
- package/lib/service.mjs +85 -26
- package/lib/skill-tree.mjs +24 -6
- package/lib/state.mjs +145 -0
- package/lib/views.mjs +234 -0
- package/lib/work-agent.mjs +397 -77
- package/package.json +1 -1
package/lib/sandbox.mjs
CHANGED
|
@@ -125,10 +125,21 @@ export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow
|
|
|
125
125
|
* $WORK_AGENT_HOME and the pool. Not claude-home:
|
|
126
126
|
* claude's own state is none of the model's business.
|
|
127
127
|
* deny the program's own files and pool writes.
|
|
128
|
+
* A per-run layout (docs/design.md 2.6) has its own WORK_AGENT_HOME (wah/):
|
|
129
|
+
* its logs/tmp/docs are the writable ones, and the shared home stays
|
|
130
|
+
* readable for what wah/ links to (essential-repos.txt…). `denySharedWork`
|
|
131
|
+
* (server execution machines, where other users' jobs ran before) closes the
|
|
132
|
+
* shared logs/tmp/docs to both kinds of tool. `controlDirs`: the local control
|
|
133
|
+
* interface (lib/control.mjs); `privateDirs`: the program's own records
|
|
134
|
+
* (archive/, trash/, state/, logs/) — never a job's business (design 3.15).
|
|
128
135
|
*/
|
|
129
|
-
export function runAllowances(
|
|
136
|
+
export function runAllowances(
|
|
137
|
+
layout,
|
|
138
|
+
{ realHome, pathEnv = '', caPaths = [], pool = '', paths = null, denySharedWork = false, controlDirs = [], privateDirs = [] },
|
|
139
|
+
) {
|
|
130
140
|
const runDirs = [layout.workDir, layout.homeDir, layout.tmpDir, layout.configDir].map((dir) => realpathOr(dir));
|
|
131
141
|
const workAgentHome = layout.workAgentHome ? realpathOr(layout.workAgentHome) : '';
|
|
142
|
+
const sharedHome = layout.sharedWorkAgentHome && layout.sharedWorkAgentHome !== layout.workAgentHome ? realpathOr(layout.sharedWorkAgentHome) : '';
|
|
132
143
|
// Writable: this run, and the three directories the Skills write into. Not
|
|
133
144
|
// the work-agent home itself and not the pool — a job must not be able to
|
|
134
145
|
// delete the repositories it shares with the user's own work-agent.
|
|
@@ -139,6 +150,7 @@ export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], po
|
|
|
139
150
|
const readAllow = [
|
|
140
151
|
...writeAllow,
|
|
141
152
|
...(workAgentHome ? [workAgentHome] : []),
|
|
153
|
+
...(sharedHome ? [sharedHome] : []),
|
|
142
154
|
...(pool ? [realpathOr(pool)] : []),
|
|
143
155
|
...homeReadAllow({ realHome, pathEnv, caPaths }),
|
|
144
156
|
];
|
|
@@ -149,14 +161,26 @@ export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], po
|
|
|
149
161
|
const toolRead = [
|
|
150
162
|
...toolWrite,
|
|
151
163
|
...(workAgentHome ? [workAgentHome] : []),
|
|
164
|
+
...(sharedHome ? [sharedHome] : []),
|
|
152
165
|
...(pool ? [realpathOr(pool)] : []),
|
|
153
166
|
];
|
|
154
167
|
const deny = [];
|
|
168
|
+
const denyBoth = (dir) => {
|
|
169
|
+
for (const at of new Set([path.resolve(dir), realpathOr(dir)])) {
|
|
170
|
+
deny.push(`Read(//${fromRoot(at)}/**)`, `Read(//${fromRoot(at)})`, `Edit(//${fromRoot(at)}/**)`, `Edit(//${fromRoot(at)})`);
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
// Other users' Skill logs, scratch and deliverables (server execution machines).
|
|
174
|
+
if (denySharedWork && sharedHome) for (const name of ['logs', 'tmp', 'docs']) denyBoth(path.join(sharedHome, name));
|
|
175
|
+
for (const dir of [...controlDirs, ...privateDirs]) if (dir) denyBoth(dir);
|
|
155
176
|
if (paths) {
|
|
156
|
-
// The access token, and the clone every job copies from
|
|
177
|
+
// The access token, and the clone every job copies from: by the path the
|
|
178
|
+
// program uses and by the real one, so a home behind a symlink (/home ->
|
|
179
|
+
// /data/home) cannot open them by the other name.
|
|
157
180
|
for (const file of [paths.configFile, paths.repoDir]) {
|
|
158
|
-
|
|
159
|
-
|
|
181
|
+
for (const at of new Set([path.resolve(file), realpathOr(file)])) {
|
|
182
|
+
deny.push(`Read(//${fromRoot(at)}/**)`, `Read(//${fromRoot(at)})`, `Edit(//${fromRoot(at)}/**)`, `Edit(//${fromRoot(at)})`);
|
|
183
|
+
}
|
|
160
184
|
}
|
|
161
185
|
}
|
|
162
186
|
// The pool is shared with the user's own work-agent: read it, never write it.
|
|
@@ -233,11 +257,19 @@ export function newRunDir(runsDir, prefix) {
|
|
|
233
257
|
|
|
234
258
|
/**
|
|
235
259
|
* Creates the run directory tree (0700) and returns its paths. `workAgentHome`
|
|
236
|
-
* is the program's persistent WORK_AGENT_HOME
|
|
237
|
-
*
|
|
238
|
-
*
|
|
260
|
+
* is the program's persistent WORK_AGENT_HOME (shared with the user's own
|
|
261
|
+
* work-agent). `isolation`:
|
|
262
|
+
* 'shared' the job's HOME gets a `.work-agent` symlink to it, so a Skill's
|
|
263
|
+
* `~/.work-agent/...` and `$WORK_AGENT_HOME` are one directory
|
|
264
|
+
* 'per-run' the job gets a WORK_AGENT_HOME of its own, <run>/wah/ (docs/design.md
|
|
265
|
+
* 2.6): logs/ tmp/ docs/ are its own; everything else of the shared
|
|
266
|
+
* home (essential-repos.txt…) is linked read-only, ascend-repos to
|
|
267
|
+
* `pool`, work-agent.py to the run's copy of the script; HOME's
|
|
268
|
+
* `.work-agent` points at wah/. What it leaves is merged or archived
|
|
269
|
+
* by the job manager when it ends.
|
|
270
|
+
* `layout.workAgentHome` is what the job gets; `layout.sharedWorkAgentHome` the shared one.
|
|
239
271
|
*/
|
|
240
|
-
export function createRunLayout(runDir, { workAgentHome = '' } = {}) {
|
|
272
|
+
export function createRunLayout(runDir, { workAgentHome = '', isolation = 'shared', pool = '' } = {}) {
|
|
241
273
|
fs.mkdirSync(runDir, { recursive: true, mode: 0o700 });
|
|
242
274
|
const layout = {
|
|
243
275
|
runDir,
|
|
@@ -248,6 +280,8 @@ export function createRunLayout(runDir, { workAgentHome = '' } = {}) {
|
|
|
248
280
|
homeDir: path.join(runDir, '.home'),
|
|
249
281
|
tmpDir: path.join(runDir, '.tmp'),
|
|
250
282
|
workAgentHome,
|
|
283
|
+
sharedWorkAgentHome: workAgentHome,
|
|
284
|
+
isolation: workAgentHome && isolation === 'per-run' ? 'per-run' : 'shared',
|
|
251
285
|
};
|
|
252
286
|
layout.skillsDir = path.join(layout.workDir, '.claude', 'skills');
|
|
253
287
|
// The Skills' `/tmp/work-agent` (clones, intermediate files): deleted with the run.
|
|
@@ -255,7 +289,25 @@ export function createRunLayout(runDir, { workAgentHome = '' } = {}) {
|
|
|
255
289
|
for (const dir of [layout.configDir, layout.workDir, layout.homeDir, layout.tmpDir, layout.scratchDir]) {
|
|
256
290
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
257
291
|
}
|
|
258
|
-
if (
|
|
292
|
+
if (layout.isolation === 'per-run') {
|
|
293
|
+
const wah = path.join(runDir, 'wah');
|
|
294
|
+
for (const name of ['logs', 'tmp', 'docs']) fs.mkdirSync(path.join(wah, name), { recursive: true, mode: 0o700 });
|
|
295
|
+
let shared = [];
|
|
296
|
+
try {
|
|
297
|
+
shared = fs.readdirSync(workAgentHome);
|
|
298
|
+
} catch {
|
|
299
|
+
// No shared home yet: nothing to link.
|
|
300
|
+
}
|
|
301
|
+
for (const name of shared) {
|
|
302
|
+
if (['logs', 'tmp', 'docs', 'ascend-repos', 'work-agent.py'].includes(name)) continue;
|
|
303
|
+
fs.symlinkSync(path.join(path.resolve(workAgentHome), name), path.join(wah, name));
|
|
304
|
+
}
|
|
305
|
+
if (pool) fs.symlinkSync(realpathOr(pool), path.join(wah, 'ascend-repos'));
|
|
306
|
+
// The run's own copy of the script (inside the run, readable by the job).
|
|
307
|
+
fs.symlinkSync(path.join('..', 'work-agent', 'scripts', 'work-agent.py'), path.join(wah, 'work-agent.py'));
|
|
308
|
+
fs.symlinkSync(path.join('..', 'wah'), path.join(layout.homeDir, '.work-agent'));
|
|
309
|
+
layout.workAgentHome = wah;
|
|
310
|
+
} else if (workAgentHome) {
|
|
259
311
|
fs.symlinkSync(path.resolve(workAgentHome), path.join(layout.homeDir, '.work-agent'));
|
|
260
312
|
}
|
|
261
313
|
return layout;
|
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
|
}
|
package/lib/state.mjs
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// What the running instance knows about itself, kept where a terminal can
|
|
2
|
+
// read it even when the instance does not answer (docs/design.md 9.1, 9.2):
|
|
3
|
+
//
|
|
4
|
+
// state/status.json a snapshot: instance, connection, jobs and their
|
|
5
|
+
// phases, maintenance, resources — rewritten (atomically)
|
|
6
|
+
// at most every 2 s while something changes
|
|
7
|
+
// state/history.jsonl one line per finished job: run id, feature, phase
|
|
8
|
+
// times, result, exit, error code — the last 1000
|
|
9
|
+
// jobs or 30 days
|
|
10
|
+
//
|
|
11
|
+
// Neither ever holds a task's text, a model, an API key, GITCODE_CRED or an
|
|
12
|
+
// answer of 交互执行; the website's 操作记录 has who ran what.
|
|
13
|
+
//
|
|
14
|
+
// Only node: built-ins and files in this directory.
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
|
|
19
|
+
import { readJsonFile, writeJsonAtomic } from './fs-safe.mjs';
|
|
20
|
+
|
|
21
|
+
export const STATUS_SCHEMA = 1;
|
|
22
|
+
export const HISTORY_MAX = 1000;
|
|
23
|
+
export const HISTORY_DAYS = 30;
|
|
24
|
+
const WRITE_DELAY_MS = 2000;
|
|
25
|
+
const TRIM_EVERY = 50;
|
|
26
|
+
|
|
27
|
+
export class StateStore {
|
|
28
|
+
constructor({ statusFile, historyFile, writeDelayMs = WRITE_DELAY_MS, now = () => Date.now() }) {
|
|
29
|
+
this.statusFile = statusFile;
|
|
30
|
+
this.historyFile = historyFile;
|
|
31
|
+
this.writeDelayMs = writeDelayMs;
|
|
32
|
+
this.now = now;
|
|
33
|
+
this.status = { schema: STATUS_SCHEMA };
|
|
34
|
+
this.timer = null;
|
|
35
|
+
this.appends = 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Merges `patch` into the snapshot; written within writeDelayMs. */
|
|
39
|
+
set(patch) {
|
|
40
|
+
Object.assign(this.status, patch);
|
|
41
|
+
if (this.timer) return;
|
|
42
|
+
this.timer = setTimeout(() => {
|
|
43
|
+
this.timer = null;
|
|
44
|
+
this.flush();
|
|
45
|
+
}, this.writeDelayMs);
|
|
46
|
+
this.timer.unref?.();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The snapshot as written, with its time. */
|
|
50
|
+
snapshot() {
|
|
51
|
+
return { ...this.status, updatedAt: new Date(this.now()).toISOString() };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
flush() {
|
|
55
|
+
clearTimeout(this.timer);
|
|
56
|
+
this.timer = null;
|
|
57
|
+
try {
|
|
58
|
+
fs.mkdirSync(path.dirname(this.statusFile), { recursive: true, mode: 0o700 });
|
|
59
|
+
writeJsonAtomic(this.statusFile, this.snapshot());
|
|
60
|
+
} catch {
|
|
61
|
+
// Status is for display: never a reason to stop.
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** One finished job. Trimmed to the last HISTORY_MAX within HISTORY_DAYS now and then. */
|
|
66
|
+
appendHistory(record) {
|
|
67
|
+
try {
|
|
68
|
+
fs.mkdirSync(path.dirname(this.historyFile), { recursive: true, mode: 0o700 });
|
|
69
|
+
fs.appendFileSync(this.historyFile, `${JSON.stringify(record)}\n`, { mode: 0o600 });
|
|
70
|
+
this.appends += 1;
|
|
71
|
+
if (this.appends % TRIM_EVERY === 0) this.trimHistory();
|
|
72
|
+
} catch {
|
|
73
|
+
// Same as above.
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
trimHistory() {
|
|
78
|
+
try {
|
|
79
|
+
const cutoff = this.now() - HISTORY_DAYS * 86_400_000;
|
|
80
|
+
const kept = readLines(this.historyFile)
|
|
81
|
+
.filter((record) => Date.parse(record?.at?.done || '') >= cutoff)
|
|
82
|
+
.slice(-HISTORY_MAX);
|
|
83
|
+
const temp = `${this.historyFile}.${process.pid}.tmp`;
|
|
84
|
+
fs.writeFileSync(temp, kept.map((record) => `${JSON.stringify(record)}\n`).join(''), { mode: 0o600 });
|
|
85
|
+
fs.renameSync(temp, this.historyFile);
|
|
86
|
+
} catch {
|
|
87
|
+
// Next time.
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function readLines(file) {
|
|
93
|
+
let text = '';
|
|
94
|
+
try {
|
|
95
|
+
text = fs.readFileSync(file, 'utf8');
|
|
96
|
+
} catch {
|
|
97
|
+
return [];
|
|
98
|
+
}
|
|
99
|
+
const records = [];
|
|
100
|
+
for (const line of text.split('\n')) {
|
|
101
|
+
if (!line.trim()) continue;
|
|
102
|
+
try {
|
|
103
|
+
const record = JSON.parse(line);
|
|
104
|
+
if (record && typeof record === 'object' && typeof record.runId === 'string') records.push(record);
|
|
105
|
+
} catch {
|
|
106
|
+
// A line cut by a crash: skipped.
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return records;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The last snapshot an instance wrote, or null. */
|
|
113
|
+
export function readStatus(statusFile) {
|
|
114
|
+
return readJsonFile(statusFile);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Whether `wanted` names the run `runId`: the whole id, or any part of it of at least 6 characters. */
|
|
118
|
+
export function matchesRunId(runId, wanted) {
|
|
119
|
+
const id = String(runId || '');
|
|
120
|
+
const part = String(wanted || '');
|
|
121
|
+
return Boolean(part) && (id === part || (part.length >= 6 && id.includes(part)));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Finished jobs, newest first: `since` (ms) by finish time, `failedOnly`
|
|
126
|
+
* (anything but ok), `runId` (see matchesRunId()), at most `limit`.
|
|
127
|
+
*/
|
|
128
|
+
export function readHistory(historyFile, { since = 0, limit = 20, failedOnly = false, runId = '' } = {}) {
|
|
129
|
+
return readLines(historyFile)
|
|
130
|
+
.filter((record) => !since || Date.parse(record?.at?.done || '') >= since)
|
|
131
|
+
.filter((record) => !failedOnly || record.result !== 'ok')
|
|
132
|
+
.filter((record) => !runId || matchesRunId(record.runId, runId))
|
|
133
|
+
.reverse()
|
|
134
|
+
.slice(0, limit);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** { ok, failed, cancelled, timeout } over the records given (e.g. the last 24 hours). */
|
|
138
|
+
export function countResults(records) {
|
|
139
|
+
const counts = { ok: 0, failed: 0, cancelled: 0, timeout: 0 };
|
|
140
|
+
for (const record of records) {
|
|
141
|
+
if (record.result in counts) counts[record.result] += 1;
|
|
142
|
+
else if (record.result !== 'not_accepted') counts.failed += 1;
|
|
143
|
+
}
|
|
144
|
+
return counts;
|
|
145
|
+
}
|