@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/config.mjs
CHANGED
|
@@ -3,17 +3,26 @@
|
|
|
3
3
|
//
|
|
4
4
|
// config.json { server, token, clientId, setupDone, workRoot?,
|
|
5
5
|
// claudePath?, machineName?, workAgentRepo?,
|
|
6
|
-
// workAgentRepoDir, ascendReposDir } (0600)
|
|
7
|
-
//
|
|
6
|
+
// workAgentHome, workAgentRepoDir, ascendReposDir } (0600)
|
|
7
|
+
// config.lock held while config.json is read, changed and written
|
|
8
|
+
// run.lock one running instance per program home
|
|
8
9
|
// work-agent/ the work-agent clone: the Skill source (lib/work-agent.mjs)
|
|
9
10
|
// work-agent.lock the clone's lock (a terminal `update` vs the service)
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
11
|
+
// state/ pool-busy (a terminal's knowledge-pool operation) and
|
|
12
|
+
// requests/ (work for the running service)
|
|
13
|
+
// .work-agent symlink to work-agent's own home ($WORK_AGENT_HOME,
|
|
14
|
+
// ~/.work-agent by default): the WORK_AGENT_HOME of every
|
|
15
|
+
// job (logs/ tmp/ docs/ ascend-repos/ essential-repos.txt
|
|
16
|
+
// live there, shared with the user's own use of work-agent)
|
|
14
17
|
// node/ a downloaded Node, when the system one is too old
|
|
15
|
-
// runs/<7 chars>/ one directory per job, deleted when it ends
|
|
16
|
-
//
|
|
18
|
+
// runs/<7 chars>/ one directory per job, deleted when it ends; trash/ holds
|
|
19
|
+
// what could not be deleted (--work-dir moves both
|
|
20
|
+
// elsewhere, e.g. a bigger disk)
|
|
21
|
+
//
|
|
22
|
+
// The program only deletes or chmods what it can show is its own
|
|
23
|
+
// (docs/design.md 3.1): the program home must be new, empty or the program's
|
|
24
|
+
// already; a --work-dir must be new, empty or marked with WORK_ROOT_MARKER,
|
|
25
|
+
// else runs go into a work-agent-runner/ subdirectory of it.
|
|
17
26
|
//
|
|
18
27
|
// Earlier versions kept these under XDG directories and ran jobs in /var/tmp;
|
|
19
28
|
// adoptLegacyState() moves what matters and drops the rest.
|
|
@@ -24,6 +33,9 @@ import fs from 'node:fs';
|
|
|
24
33
|
import os from 'node:os';
|
|
25
34
|
import path from 'node:path';
|
|
26
35
|
|
|
36
|
+
import { isRunEntry, readJsonFile, writeJsonAtomic } from './fs-safe.mjs';
|
|
37
|
+
import { withFileLockSync } from './lock.mjs';
|
|
38
|
+
|
|
27
39
|
export const DEFAULT_SERVER = 'https://online-tools.closerouter.site';
|
|
28
40
|
/** The work-agent clone is fast-forwarded every day at this hour (local time). */
|
|
29
41
|
export const REPO_UPDATE_HOUR = 8;
|
|
@@ -34,6 +46,10 @@ export const PROGRAM_DIR = '.work-agent-runner';
|
|
|
34
46
|
export const WORK_AGENT_DIR = '.work-agent';
|
|
35
47
|
/** Its repository pool, which the program may be pointed at another disk. */
|
|
36
48
|
export const POOL_DIR = path.join(WORK_AGENT_DIR, 'ascend-repos');
|
|
49
|
+
/** Marks a directory given with --work-dir as this program's work root. */
|
|
50
|
+
export const WORK_ROOT_MARKER = '.work-agent-runner.json';
|
|
51
|
+
/** Where runs go when the directory given with --work-dir already holds other things. */
|
|
52
|
+
export const WORK_ROOT_SUBDIR = 'work-agent-runner';
|
|
37
53
|
|
|
38
54
|
const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
39
55
|
|
|
@@ -45,28 +61,39 @@ export class ConfigError extends Error {}
|
|
|
45
61
|
/**
|
|
46
62
|
* Every path the program owns. `home` is the user's home directory; the
|
|
47
63
|
* program's own home is WORK_AGENT_RUNNER_HOME or <home>/.work-agent-runner.
|
|
64
|
+
* workAgentHome / poolDir / repoDir are first defaults: once config.json names
|
|
65
|
+
* them, withRepoPaths() takes the file's values.
|
|
48
66
|
*/
|
|
49
67
|
export function configPaths(env = process.env, home = os.homedir()) {
|
|
50
68
|
const base = env.WORK_AGENT_RUNNER_HOME ? path.resolve(env.WORK_AGENT_RUNNER_HOME) : path.join(home, PROGRAM_DIR);
|
|
51
69
|
const configRoot = env.XDG_CONFIG_HOME || path.join(home, '.config');
|
|
70
|
+
// work-agent's own home as work-agent.py finds it: WORK_AGENT_HOME, else ~/.work-agent.
|
|
71
|
+
const workAgentHome = env.WORK_AGENT_HOME ? path.resolve(env.WORK_AGENT_HOME) : path.join(home, WORK_AGENT_DIR);
|
|
52
72
|
return {
|
|
53
73
|
baseDir: base,
|
|
54
74
|
// saveConfig() creates this; it is the program's home, not a subdirectory.
|
|
55
75
|
configDir: base,
|
|
56
76
|
configFile: path.join(base, 'config.json'),
|
|
77
|
+
configLockFile: path.join(base, 'config.lock'),
|
|
57
78
|
lockFile: path.join(base, 'run.lock'),
|
|
58
79
|
repoDir: path.join(base, 'work-agent'),
|
|
80
|
+
// Where the clone is when config.json does not move it: a clone found here
|
|
81
|
+
// without an ownership marker was made by 0.0.2–0.0.4 (lib/work-agent.mjs).
|
|
82
|
+
defaultRepoDir: path.join(base, 'work-agent'),
|
|
59
83
|
repoLockFile: path.join(base, 'work-agent.lock'),
|
|
84
|
+
stateDir: path.join(base, 'state'),
|
|
85
|
+
requestsDir: path.join(base, 'state', 'requests'),
|
|
86
|
+
poolBusyFile: path.join(base, 'state', 'pool-busy'),
|
|
60
87
|
// WORK_AGENT_HOME handed to every job: work-agent's own home, a real
|
|
61
88
|
// directory outside the program's, so the user's own work-agent use sees
|
|
62
89
|
// the same logs, scratch and repository pool.
|
|
63
|
-
workAgentHome
|
|
90
|
+
workAgentHome,
|
|
64
91
|
// A symlink to it inside the program's home, so everything the program
|
|
65
92
|
// touches is reachable from one place.
|
|
66
93
|
workAgentLink: path.join(base, WORK_AGENT_DIR),
|
|
67
94
|
nodeDir: path.join(base, 'node'),
|
|
68
95
|
runsRoot: base,
|
|
69
|
-
poolDir: path.join(
|
|
96
|
+
poolDir: path.join(workAgentHome, 'ascend-repos'),
|
|
70
97
|
// Where earlier versions kept things (newest first: adopt the newest).
|
|
71
98
|
legacyConfigFiles: [
|
|
72
99
|
path.join(configRoot, 'work-agent-runner', 'config.json'),
|
|
@@ -91,20 +118,21 @@ export function configPaths(env = process.env, home = os.homedir()) {
|
|
|
91
118
|
}
|
|
92
119
|
|
|
93
120
|
/**
|
|
94
|
-
*
|
|
95
|
-
* is where the updater looks) and otherwise the
|
|
96
|
-
*
|
|
97
|
-
* the file always shows
|
|
121
|
+
* work-agent's home and the two repository locations, from the config file
|
|
122
|
+
* when it names them (that is where the updater looks) and otherwise the
|
|
123
|
+
* defaults. Returns `paths` with them resolved, and whether the config should
|
|
124
|
+
* be written back so the file always shows all three.
|
|
98
125
|
*/
|
|
99
126
|
export function withRepoPaths(paths, config) {
|
|
127
|
+
const workAgentHome = config.workAgentHome || paths.workAgentHome;
|
|
100
128
|
const repoDir = config.workAgentRepoDir || paths.repoDir;
|
|
101
|
-
const poolDir = config.ascendReposDir ||
|
|
129
|
+
const poolDir = config.ascendReposDir || path.join(workAgentHome, 'ascend-repos');
|
|
102
130
|
if (repoDir === poolDir) {
|
|
103
131
|
throw new ConfigError(`work-agent 仓库和知识仓不能是同一个目录(${repoDir})`);
|
|
104
132
|
}
|
|
105
133
|
return {
|
|
106
|
-
paths: { ...paths, repoDir, poolDir },
|
|
107
|
-
missing: !config.workAgentRepoDir || !config.ascendReposDir,
|
|
134
|
+
paths: { ...paths, workAgentHome, repoDir, poolDir },
|
|
135
|
+
missing: !config.workAgentRepoDir || !config.ascendReposDir || !config.workAgentHome,
|
|
108
136
|
};
|
|
109
137
|
}
|
|
110
138
|
|
|
@@ -130,9 +158,10 @@ function normalize(raw) {
|
|
|
130
158
|
};
|
|
131
159
|
if (typeof raw.workRoot === 'string' && raw.workRoot) config.workRoot = raw.workRoot;
|
|
132
160
|
if (typeof raw.claudePath === 'string' && raw.claudePath) config.claudePath = raw.claudePath;
|
|
133
|
-
// Where the two repositories are. Written on first
|
|
134
|
-
// them; edit it (absolute paths) to put
|
|
135
|
-
|
|
161
|
+
// Where work-agent's home and the two repositories are. Written on first
|
|
162
|
+
// run, so the file shows them; edit it (absolute paths) to put any of them
|
|
163
|
+
// somewhere else.
|
|
164
|
+
for (const key of ['workAgentHome', 'workAgentRepoDir', 'ascendReposDir']) {
|
|
136
165
|
if (typeof raw[key] === 'string' && path.isAbsolute(raw[key])) config[key] = path.resolve(raw[key]);
|
|
137
166
|
}
|
|
138
167
|
// A mirror of the work-agent repository, for this machine only. http(s) only:
|
|
@@ -178,6 +207,23 @@ export function saveConfig(paths, config) {
|
|
|
178
207
|
fs.chmodSync(paths.configFile, 0o600);
|
|
179
208
|
}
|
|
180
209
|
|
|
210
|
+
/**
|
|
211
|
+
* Changes config.json field by field: under config.lock it is read again,
|
|
212
|
+
* `mutate(config)` changes what it means to, and the result is written. Two
|
|
213
|
+
* processes (the background service and a terminal `login`) never write back
|
|
214
|
+
* each other's stale copy. Returns the config as written.
|
|
215
|
+
*/
|
|
216
|
+
export function updateConfig(paths, mutate) {
|
|
217
|
+
fs.mkdirSync(paths.configDir, { recursive: true, mode: 0o700 });
|
|
218
|
+
const lockFile = paths.configLockFile || path.join(paths.configDir, 'config.lock');
|
|
219
|
+
return withFileLockSync(lockFile, () => {
|
|
220
|
+
const config = loadConfig(paths);
|
|
221
|
+
mutate(config);
|
|
222
|
+
saveConfig(paths, config);
|
|
223
|
+
return normalize(config);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
181
227
|
/** The newest legacy config to adopt ('' when there is none, or one is already here). */
|
|
182
228
|
export function legacyConfigPending(paths) {
|
|
183
229
|
if (fs.existsSync(paths.configFile)) return '';
|
|
@@ -222,25 +268,154 @@ function realpathOr(value) {
|
|
|
222
268
|
}
|
|
223
269
|
}
|
|
224
270
|
|
|
225
|
-
|
|
271
|
+
function samePath(a, b) {
|
|
272
|
+
return realpathOr(a) === realpathOr(b);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// What a program home may hold before config.json exists (the entry point
|
|
276
|
+
// downloads Node into node/ first) or after an interrupted write.
|
|
277
|
+
const PROGRAM_ENTRIES = new Set([
|
|
278
|
+
'config.json', 'config.lock', 'run.lock', 'work-agent.lock', 'work-agent', WORK_AGENT_DIR,
|
|
279
|
+
'node', 'claude', 'runs', 'state', 'logs', 'control', 'archive', 'trash', WORK_ROOT_MARKER,
|
|
280
|
+
]);
|
|
281
|
+
const PROGRAM_ENTRY_PATTERNS = [/^config\.json\..+\.tmp$/, /^config\.json\.bak-/, /\.lock\..+\.tmp$/, /\.lock\.takeover$/, /^\.work-agent\.(new|old)-/];
|
|
282
|
+
|
|
283
|
+
/** Whether `name` is something this program keeps in its home. */
|
|
284
|
+
export function isProgramEntry(name) {
|
|
285
|
+
return PROGRAM_ENTRIES.has(name) || PROGRAM_ENTRY_PATTERNS.some((pattern) => pattern.test(name));
|
|
286
|
+
}
|
|
226
287
|
|
|
227
288
|
/**
|
|
228
|
-
*
|
|
229
|
-
*
|
|
230
|
-
*
|
|
231
|
-
*
|
|
232
|
-
*
|
|
289
|
+
* Checks (creating it when missing) the program's home before anything is
|
|
290
|
+
* written into it. It must be new, empty, or this program's already
|
|
291
|
+
* (config.json, or only names this program uses): pointed at a directory of
|
|
292
|
+
* the user's, a start would delete its runs/ and change its mode. Makes it
|
|
293
|
+
* 0700 and returns its real path; throws ConfigError.
|
|
233
294
|
*/
|
|
234
|
-
export function
|
|
235
|
-
const resolved = path.resolve(
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
if (stat.
|
|
295
|
+
export function prepareProgramHome(base, { uid = process.getuid?.() ?? 0 } = {}) {
|
|
296
|
+
const resolved = path.resolve(base);
|
|
297
|
+
let stat;
|
|
298
|
+
try {
|
|
299
|
+
fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
|
|
300
|
+
stat = fs.statSync(resolved);
|
|
301
|
+
} catch (error) {
|
|
302
|
+
throw new ConfigError(`无法使用程序目录 ${resolved}:${error.message}`);
|
|
303
|
+
}
|
|
304
|
+
if (!stat.isDirectory()) throw new ConfigError(`程序目录 ${resolved} 不是目录`);
|
|
305
|
+
if (stat.uid !== uid) throw new ConfigError(`程序目录 ${resolved} 的属主不是当前用户`);
|
|
306
|
+
if (!fs.existsSync(path.join(resolved, 'config.json'))) {
|
|
307
|
+
const foreign = fs.readdirSync(resolved).filter((name) => !isProgramEntry(name));
|
|
308
|
+
if (foreign.length) {
|
|
309
|
+
throw new ConfigError(
|
|
310
|
+
`${resolved} 里已有不属于本程序的内容(${foreign.slice(0, 3).join('、')}${foreign.length > 3 ? ' 等' : ''}),` +
|
|
311
|
+
'不能用作程序目录:请把 WORK_AGENT_RUNNER_HOME 设为一个新的或空的目录',
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
244
315
|
if ((stat.mode & 0o777) !== 0o700) fs.chmodSync(resolved, 0o700);
|
|
245
316
|
return fs.realpathSync(resolved);
|
|
246
317
|
}
|
|
318
|
+
|
|
319
|
+
export class WorkRootError extends Error {}
|
|
320
|
+
|
|
321
|
+
// Never a work root themselves (a subdirectory is fine).
|
|
322
|
+
const SYSTEM_DIRS = new Set([
|
|
323
|
+
'/', '/bin', '/boot', '/dev', '/etc', '/home', '/lib', '/lib32', '/lib64', '/libx32', '/media', '/mnt', '/opt',
|
|
324
|
+
'/proc', '/root', '/run', '/sbin', '/srv', '/sys', '/tmp', '/usr', '/var', '/var/tmp',
|
|
325
|
+
'/Applications', '/Library', '/private', '/System', '/Users', '/Volumes',
|
|
326
|
+
]);
|
|
327
|
+
|
|
328
|
+
function workRootProblem(resolved, home) {
|
|
329
|
+
const real = realpathOr(resolved);
|
|
330
|
+
const realHome = realpathOr(home);
|
|
331
|
+
if (resolved === path.resolve(home) || real === realHome) {
|
|
332
|
+
return `工作目录不能是主目录本身(${resolved}),请用 --work-dir 指定一个子目录`;
|
|
333
|
+
}
|
|
334
|
+
if (SYSTEM_DIRS.has(resolved) || SYSTEM_DIRS.has(real)) {
|
|
335
|
+
return `工作目录不能是 ${resolved},请用 --work-dir 指定其下的一个子目录`;
|
|
336
|
+
}
|
|
337
|
+
if (isInside(realHome, real)) return `工作目录不能是主目录的上级目录(${resolved}),请用 --work-dir 指定一个子目录`;
|
|
338
|
+
return '';
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Only runs/ (with run and probe directories in it), trash/ and archive/: what 0.0.4 and later leave. */
|
|
342
|
+
function isLegacyWorkRoot(dir, names, uid) {
|
|
343
|
+
if (!names.includes('runs') || !names.every((name) => ['runs', 'trash', 'archive'].includes(name))) return false;
|
|
344
|
+
try {
|
|
345
|
+
for (const name of names) if (!fs.lstatSync(path.join(dir, name)).isDirectory()) return false;
|
|
346
|
+
const runs = path.join(dir, 'runs');
|
|
347
|
+
return fs.readdirSync(runs).every((name) => isRunEntry(runs, name, { uid }));
|
|
348
|
+
} catch {
|
|
349
|
+
return false;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function writeWorkRootMarker(dir, { programHome, createdByProgram }) {
|
|
354
|
+
writeJsonAtomic(path.join(dir, WORK_ROOT_MARKER), {
|
|
355
|
+
kind: 'work-root',
|
|
356
|
+
programHome: programHome ? realpathOr(programHome) : '',
|
|
357
|
+
createdByProgram,
|
|
358
|
+
createdAt: new Date().toISOString(),
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function chooseWorkRoot(candidate, { programHome, uid, allowSubdir }) {
|
|
363
|
+
let stat = null;
|
|
364
|
+
try {
|
|
365
|
+
stat = fs.lstatSync(candidate);
|
|
366
|
+
} catch (error) {
|
|
367
|
+
if (error.code !== 'ENOENT') throw new WorkRootError(`无法使用工作目录 ${candidate}:${error.message}`);
|
|
368
|
+
}
|
|
369
|
+
if (!stat) {
|
|
370
|
+
fs.mkdirSync(candidate, { recursive: true, mode: 0o700 });
|
|
371
|
+
writeWorkRootMarker(candidate, { programHome, createdByProgram: true });
|
|
372
|
+
return candidate;
|
|
373
|
+
}
|
|
374
|
+
if (stat.isSymbolicLink()) throw new WorkRootError(`工作目录 ${candidate} 不能是符号链接`);
|
|
375
|
+
if (!stat.isDirectory()) throw new WorkRootError(`${candidate} 不是目录`);
|
|
376
|
+
if (stat.uid !== uid) throw new WorkRootError(`工作目录 ${candidate} 的属主不是当前用户,请删除它或用 --work-dir 换一个目录`);
|
|
377
|
+
const marker = readJsonFile(path.join(candidate, WORK_ROOT_MARKER));
|
|
378
|
+
if (marker) {
|
|
379
|
+
if (marker.programHome && programHome && !samePath(marker.programHome, programHome)) {
|
|
380
|
+
throw new WorkRootError(
|
|
381
|
+
`工作目录 ${candidate} 已属于另一个程序目录(${marker.programHome}):两者共用会互相清理对方的任务目录,请用 --work-dir 换一个目录`,
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
return candidate;
|
|
385
|
+
}
|
|
386
|
+
const names = fs.readdirSync(candidate);
|
|
387
|
+
if (names.length === 0 || isLegacyWorkRoot(candidate, names, uid)) {
|
|
388
|
+
writeWorkRootMarker(candidate, { programHome, createdByProgram: false });
|
|
389
|
+
return candidate;
|
|
390
|
+
}
|
|
391
|
+
// Other things live here (/data, a project…): never touch them, use a subdirectory.
|
|
392
|
+
if (allowSubdir) return chooseWorkRoot(path.join(candidate, WORK_ROOT_SUBDIR), { programHome, uid, allowSubdir: false });
|
|
393
|
+
throw new WorkRootError(
|
|
394
|
+
`${candidate} 不是空目录,也不是本程序的工作目录(没有 ${WORK_ROOT_MARKER}):请用 --work-dir 指定一个新目录或空目录`,
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* The directory that holds runs/ and trash/. The program's home by default
|
|
400
|
+
* (`programHome`); a directory given with --work-dir must be new, empty, or
|
|
401
|
+
* marked as this program's (WORK_ROOT_MARKER) — one that already holds other
|
|
402
|
+
* things gets a work-agent-runner/ subdirectory instead, so nothing of the
|
|
403
|
+
* user's is ever deleted or chmod-ed (docs/design.md 3.4.2). Never the home
|
|
404
|
+
* itself, one of its parents or a system directory; not a symlink; owned by
|
|
405
|
+
* this user. Returns its real path, which everything else uses.
|
|
406
|
+
*/
|
|
407
|
+
export function prepareWorkRoot(dir, { home = os.homedir(), uid = process.getuid?.() ?? 0, programHome = '' } = {}) {
|
|
408
|
+
const resolved = path.resolve(dir);
|
|
409
|
+
if (programHome && samePath(resolved, programHome)) {
|
|
410
|
+
fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
|
|
411
|
+
return fs.realpathSync(resolved);
|
|
412
|
+
}
|
|
413
|
+
const problem = workRootProblem(resolved, home);
|
|
414
|
+
if (problem) throw new WorkRootError(problem);
|
|
415
|
+
const chosen = chooseWorkRoot(resolved, { programHome, uid, allowSubdir: true });
|
|
416
|
+
const stat = fs.lstatSync(chosen);
|
|
417
|
+
if (stat.isSymbolicLink()) throw new WorkRootError(`工作目录 ${chosen} 不能是符号链接`);
|
|
418
|
+
if (!stat.isDirectory()) throw new WorkRootError(`${chosen} 不是目录`);
|
|
419
|
+
if (stat.uid !== uid) throw new WorkRootError(`工作目录 ${chosen} 的属主不是当前用户,请删除它或用 --work-dir 换一个目录`);
|
|
420
|
+
return fs.realpathSync(chosen);
|
|
421
|
+
}
|
package/lib/doctor.mjs
CHANGED
|
@@ -9,6 +9,7 @@ import path from 'node:path';
|
|
|
9
9
|
import readline from 'node:readline';
|
|
10
10
|
|
|
11
11
|
import { claudeArgs, claudeEnv } from './claude-cli.mjs';
|
|
12
|
+
import { removeTree } from './fs-safe.mjs';
|
|
12
13
|
import { SANDBOX_TOOLS, SKILL_TOOLS, detectPackageManager } from './packages.mjs';
|
|
13
14
|
import { PROBE_MARKER, PROBE_TOOL_ID, startProbeModel } from './probe-model.mjs';
|
|
14
15
|
import {
|
|
@@ -247,7 +248,8 @@ export async function probeSandbox({
|
|
|
247
248
|
return result;
|
|
248
249
|
} finally {
|
|
249
250
|
await model?.close();
|
|
250
|
-
|
|
251
|
+
// Never throws: whatever is left goes to trash/ next to runs/.
|
|
252
|
+
removeTree(layout.runDir, { trashDir: path.join(workRoot, 'trash') });
|
|
251
253
|
}
|
|
252
254
|
}
|
|
253
255
|
|
package/lib/fs-safe.mjs
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Deleting only what this program made, without ever throwing out of a
|
|
2
|
+
// cleanup (docs/design.md 3.1, 3.4.3, 7.5).
|
|
3
|
+
//
|
|
4
|
+
// A job may leave a directory it made read-only (chmod 555, a Go module
|
|
5
|
+
// cache…): fs.rmSync gives up on those with EACCES, and one such directory
|
|
6
|
+
// used to stop the service for good (every start removed runs/ and crashed).
|
|
7
|
+
// removeTree() makes the job's own directories writable again; what still
|
|
8
|
+
// cannot go is moved into trash/ and retried later. Cleanups only touch run
|
|
9
|
+
// and probe directories by name, never a directory the user named.
|
|
10
|
+
//
|
|
11
|
+
// Only node: built-ins.
|
|
12
|
+
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
|
|
16
|
+
/** A run (r) or probe (p) directory: one letter and mkdtemp's six characters. */
|
|
17
|
+
export const RUN_ENTRY = /^[rp][A-Za-z0-9]{6}$/;
|
|
18
|
+
|
|
19
|
+
const RETRY_CODES = new Set(['EACCES', 'EPERM']);
|
|
20
|
+
|
|
21
|
+
function stamp(date = new Date()) {
|
|
22
|
+
return date.toISOString().replace(/[:.]/g, '-');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Gives the owner rwx on `dir` again (never through a symlink, never someone else's). */
|
|
26
|
+
function makeWritable(dir, ops, uid) {
|
|
27
|
+
const stat = ops.lstatSync(dir);
|
|
28
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) return false;
|
|
29
|
+
if (Number.isInteger(uid) && stat.uid !== uid) return false;
|
|
30
|
+
ops.chmodSync(dir, (stat.mode & 0o7777) | 0o700);
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Runs `operation`; on EACCES / EPERM makes `dir` writable and tries once more. */
|
|
35
|
+
function withRetry(operation, dir, ops, uid) {
|
|
36
|
+
try {
|
|
37
|
+
return operation();
|
|
38
|
+
} catch (error) {
|
|
39
|
+
if (!RETRY_CODES.has(error.code) || !makeWritable(dir, ops, uid)) throw error;
|
|
40
|
+
return operation();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function removeEntry(target, ops, uid) {
|
|
45
|
+
let stat;
|
|
46
|
+
try {
|
|
47
|
+
stat = ops.lstatSync(target);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error.code === 'ENOENT') return;
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
const parent = path.dirname(target);
|
|
53
|
+
if (!stat.isDirectory()) {
|
|
54
|
+
withRetry(() => ops.unlinkSync(target), parent, ops, uid);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
// A directory without r/x cannot even be listed; one without w keeps its
|
|
58
|
+
// entries (each unlink / rmdir below retries after fixing its parent).
|
|
59
|
+
const names = withRetry(() => ops.readdirSync(target), target, ops, uid);
|
|
60
|
+
for (const name of names) removeEntry(path.join(target, name), ops, uid);
|
|
61
|
+
withRetry(() => ops.rmdirSync(target), parent, ops, uid);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Removes `target` (file or directory tree) without following symlinks.
|
|
66
|
+
* Never throws. Returns { removed: true } or { removed: false, error } — with
|
|
67
|
+
* `trashDir`, what cannot be removed is renamed into it ({ trashed }), which
|
|
68
|
+
* must be on the same filesystem. `ops` replaces node:fs in tests.
|
|
69
|
+
*/
|
|
70
|
+
export function removeTree(target, { trashDir = '', ops = fs, uid = process.getuid?.() } = {}) {
|
|
71
|
+
try {
|
|
72
|
+
removeEntry(target, ops, uid);
|
|
73
|
+
return { removed: true };
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (trashDir) {
|
|
76
|
+
try {
|
|
77
|
+
ops.mkdirSync(trashDir, { recursive: true, mode: 0o700 });
|
|
78
|
+
const trashed = path.join(trashDir, `${stamp()}-${path.basename(target)}`);
|
|
79
|
+
ops.renameSync(target, trashed);
|
|
80
|
+
return { removed: false, trashed, error };
|
|
81
|
+
} catch {
|
|
82
|
+
// Not even that: leave it where it is for the next cleanup.
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { removed: false, error };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Whether `name` in `dir` is a run or probe directory of this user (never a symlink). */
|
|
90
|
+
export function isRunEntry(dir, name, { uid = process.getuid?.() } = {}) {
|
|
91
|
+
if (!RUN_ENTRY.test(name)) return false;
|
|
92
|
+
try {
|
|
93
|
+
const stat = fs.lstatSync(path.join(dir, name));
|
|
94
|
+
return stat.isDirectory() && (!Number.isInteger(uid) || stat.uid === uid);
|
|
95
|
+
} catch {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Removes the run and probe directories left in `runsDir` (and retries what
|
|
102
|
+
* is in `trashDir`). Anything else in runsDir is left alone and reported.
|
|
103
|
+
* Never throws: { removed, trashed: [paths], failed: [paths], unknown: [names] }.
|
|
104
|
+
*/
|
|
105
|
+
export function cleanRunsDir(runsDir, { trashDir = '', uid = process.getuid?.() } = {}) {
|
|
106
|
+
const summary = { removed: 0, trashed: [], failed: [], unknown: [] };
|
|
107
|
+
let names = [];
|
|
108
|
+
try {
|
|
109
|
+
names = fs.readdirSync(runsDir);
|
|
110
|
+
} catch {
|
|
111
|
+
return summary;
|
|
112
|
+
}
|
|
113
|
+
for (const name of names) {
|
|
114
|
+
if (!isRunEntry(runsDir, name, { uid })) {
|
|
115
|
+
summary.unknown.push(name);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
const outcome = removeTree(path.join(runsDir, name), { trashDir, uid });
|
|
119
|
+
if (outcome.removed) summary.removed += 1;
|
|
120
|
+
else if (outcome.trashed) summary.trashed.push(outcome.trashed);
|
|
121
|
+
else summary.failed.push(path.join(runsDir, name));
|
|
122
|
+
}
|
|
123
|
+
if (trashDir) summary.failed.push(...retryTrash(trashDir, { uid }));
|
|
124
|
+
return summary;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Tries again to remove everything in `trashDir`; returns what is still there. */
|
|
128
|
+
export function retryTrash(trashDir, { uid = process.getuid?.() } = {}) {
|
|
129
|
+
let names = [];
|
|
130
|
+
try {
|
|
131
|
+
names = fs.readdirSync(trashDir);
|
|
132
|
+
} catch {
|
|
133
|
+
return [];
|
|
134
|
+
}
|
|
135
|
+
const left = [];
|
|
136
|
+
for (const name of names) {
|
|
137
|
+
const entry = path.join(trashDir, name);
|
|
138
|
+
if (!removeTree(entry, { uid }).removed) left.push(entry);
|
|
139
|
+
}
|
|
140
|
+
return left;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** JSON written atomically (temporary file, then rename), mode 0600. */
|
|
144
|
+
export function writeJsonAtomic(file, value) {
|
|
145
|
+
const temp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
146
|
+
try {
|
|
147
|
+
fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
148
|
+
fs.renameSync(temp, file);
|
|
149
|
+
} catch (error) {
|
|
150
|
+
fs.rmSync(temp, { force: true });
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Parsed JSON object from `file`, or null when it is missing or not an object. */
|
|
156
|
+
export function readJsonFile(file) {
|
|
157
|
+
try {
|
|
158
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
159
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
|
|
160
|
+
} catch {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
}
|
package/lib/jobs.mjs
CHANGED
|
@@ -19,6 +19,7 @@ import path from 'node:path';
|
|
|
19
19
|
import { StringDecoder } from 'node:string_decoder';
|
|
20
20
|
|
|
21
21
|
import { claudeArgs, claudeEnv } from './claude-cli.mjs';
|
|
22
|
+
import { removeTree } from './fs-safe.mjs';
|
|
22
23
|
import { ApiError } from './http.mjs';
|
|
23
24
|
import { createClaudeInteraction } from './interaction.mjs';
|
|
24
25
|
import {
|
|
@@ -42,6 +43,9 @@ const RUN_ID = /^(skill|review)_\d+_[0-9a-f]{8}$/;
|
|
|
42
43
|
const TASK_MAX_BYTES = 64 * 1024;
|
|
43
44
|
const KILL_GRACE_MS = 5000;
|
|
44
45
|
const CLOSE_WAIT_MS = 2000;
|
|
46
|
+
// How long an accepted job waits for a knowledge-pool update to finish before
|
|
47
|
+
// it starts (its own timeout only starts with claude).
|
|
48
|
+
export const JOB_WAIT_MS = 15 * 60_000;
|
|
45
49
|
|
|
46
50
|
const BATCH_DELAY_MS = 200;
|
|
47
51
|
const BATCH_BYTES = 64 * 1024;
|
|
@@ -259,11 +263,25 @@ function killGroup(pid, signal) {
|
|
|
259
263
|
* everything).
|
|
260
264
|
*/
|
|
261
265
|
export class JobManager {
|
|
262
|
-
constructor({
|
|
266
|
+
constructor({
|
|
267
|
+
client,
|
|
268
|
+
workAgent,
|
|
269
|
+
workRoot,
|
|
270
|
+
claudePath,
|
|
271
|
+
realHome,
|
|
272
|
+
env = process.env,
|
|
273
|
+
platform = process.platform,
|
|
274
|
+
log,
|
|
275
|
+
onFatal = () => {},
|
|
276
|
+
jobWaitMs = JOB_WAIT_MS,
|
|
277
|
+
}) {
|
|
263
278
|
this.client = client;
|
|
264
279
|
this.workAgent = workAgent;
|
|
265
280
|
this.paths = workAgent?.paths || null;
|
|
266
281
|
this.runsDir = path.join(workRoot, 'runs');
|
|
282
|
+
// Same filesystem as runs/: a run directory that cannot be deleted is renamed here.
|
|
283
|
+
this.trashDir = path.join(workRoot, 'trash');
|
|
284
|
+
this.jobWaitMs = jobWaitMs;
|
|
267
285
|
this.claudePath = claudePath;
|
|
268
286
|
this.realHome = realHome;
|
|
269
287
|
this.env = env;
|
|
@@ -393,6 +411,21 @@ export class JobManager {
|
|
|
393
411
|
const label = FEATURE_LABELS[job.feature];
|
|
394
412
|
this.log.info(`开始任务 ${runId}(${label})`);
|
|
395
413
|
|
|
414
|
+
// A `git pull` in the knowledge pool must not replace files under a running
|
|
415
|
+
// job: wait for it (bounded) before anything starts.
|
|
416
|
+
if (typeof this.workAgent?.waitForPoolIdle === 'function') {
|
|
417
|
+
const idle = await this.workAgent.waitForPoolIdle({
|
|
418
|
+
timeoutMs: this.jobWaitMs,
|
|
419
|
+
isCancelled: () => entry.cancelled,
|
|
420
|
+
onWait: () => this.log.info(`任务 ${runId} 等待知识仓更新完成后开始`),
|
|
421
|
+
});
|
|
422
|
+
if (!idle && !entry.cancelled) {
|
|
423
|
+
this.log.warn(`任务 ${runId} 等待知识仓更新超时,未执行`);
|
|
424
|
+
await this.reportExit(entry, { error: `执行机器正在更新知识仓,等待超过 ${Math.round(this.jobWaitMs / 60_000)} 分钟,任务未执行,请稍后重试` });
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
396
429
|
if (entry.cancelled) {
|
|
397
430
|
await this.reportExit(entry, { signal: 'SIGTERM' });
|
|
398
431
|
return;
|
|
@@ -407,7 +440,7 @@ export class JobManager {
|
|
|
407
440
|
const tooLong = socketPathProblem(layout.tmpDir, this.platform);
|
|
408
441
|
if (tooLong) throw new Error(tooLong);
|
|
409
442
|
} catch (error) {
|
|
410
|
-
if (runDir)
|
|
443
|
+
if (runDir) this.removeRunDir(runDir);
|
|
411
444
|
await this.reportExit(entry, { error: `准备运行目录失败:${error?.message || error}` });
|
|
412
445
|
return;
|
|
413
446
|
}
|
|
@@ -435,7 +468,7 @@ export class JobManager {
|
|
|
435
468
|
});
|
|
436
469
|
this.log.info(`任务 ${runId} 使用 work-agent ${commit.slice(0, 7)}${pool ? ',已挂载知识仓' : ''}`);
|
|
437
470
|
} catch (error) {
|
|
438
|
-
|
|
471
|
+
this.removeRunDir(runDir);
|
|
439
472
|
await this.reportExit(entry, { error: `准备 Skill 失败:${error?.message || error}` });
|
|
440
473
|
return;
|
|
441
474
|
}
|
|
@@ -455,10 +488,23 @@ export class JobManager {
|
|
|
455
488
|
const outcome = entry.timedOut ? '超时' : entry.cancelled ? '已取消' : result.error ? result.error : `退出码 ${result.code ?? result.signal}`;
|
|
456
489
|
this.log.info(`任务 ${runId} 结束(${label}):${outcome},用时 ${seconds} 秒`);
|
|
457
490
|
} finally {
|
|
458
|
-
|
|
491
|
+
this.removeRunDir(runDir);
|
|
459
492
|
}
|
|
460
493
|
}
|
|
461
494
|
|
|
495
|
+
/**
|
|
496
|
+
* Deletes a run directory; never throws. What a job made undeletable (a
|
|
497
|
+
* read-only directory) goes to trash/, retried at the next start and every
|
|
498
|
+
* hour — it must never stop the program.
|
|
499
|
+
*/
|
|
500
|
+
removeRunDir(runDir) {
|
|
501
|
+
const outcome = removeTree(runDir, { trashDir: this.trashDir });
|
|
502
|
+
if (outcome.removed) return;
|
|
503
|
+
const why = outcome.error?.code || outcome.error?.message || String(outcome.error);
|
|
504
|
+
if (outcome.trashed) this.log.warn(`运行目录 ${runDir} 删不掉(${why}),已移到 ${outcome.trashed},稍后再试`);
|
|
505
|
+
else this.log.warn(`运行目录 ${runDir} 删不掉(${why}),下次启动时再试`);
|
|
506
|
+
}
|
|
507
|
+
|
|
462
508
|
spawnClaude(entry, layout) {
|
|
463
509
|
const { job } = entry;
|
|
464
510
|
return new Promise((resolve) => {
|