@online-tools/work-agent-runner 0.0.3-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 +44 -16
- package/bin/main.mjs +346 -95
- package/lib/claude-cli.mjs +17 -6
- package/lib/config.mjs +211 -36
- package/lib/doctor.mjs +3 -1
- package/lib/fs-safe.mjs +163 -0
- package/lib/interaction.mjs +3 -1
- package/lib/jobs.mjs +59 -12
- package/lib/lock.mjs +114 -15
- package/lib/sandbox.mjs +75 -27
- package/lib/service.mjs +85 -26
- package/lib/skill-text.mjs +11 -3
- package/lib/skill-tree.mjs +31 -10
- package/lib/work-agent.mjs +385 -80
- package/package.json +1 -1
package/lib/claude-cli.mjs
CHANGED
|
@@ -5,7 +5,15 @@
|
|
|
5
5
|
// Only node: built-ins and files in this directory may be imported here, and
|
|
6
6
|
// importing must have no side effects.
|
|
7
7
|
|
|
8
|
+
// Every tool a job may use.
|
|
8
9
|
export const CLAUDE_TOOLS = 'Bash,Read,Glob,Grep,Edit,Write,Skill,Agent';
|
|
10
|
+
// Pre-allowed: Bash (confined by the operating system sandbox), Skill and
|
|
11
|
+
// Agent. The file tools are deliberately left out: pre-allowing them lets them
|
|
12
|
+
// read and write any path not on the deny list. Without it they reach the
|
|
13
|
+
// working directory and the paths the run's settings allow (sandbox.mjs
|
|
14
|
+
// runAllowances: toolRead / toolWrite); any other path asks, which a silent job
|
|
15
|
+
// refuses and lib/interaction.mjs denies.
|
|
16
|
+
export const CLAUDE_ALLOWED_TOOLS = 'Bash,Skill,Agent';
|
|
9
17
|
|
|
10
18
|
const DEFAULT_PATH = '/usr/local/bin:/usr/bin:/bin';
|
|
11
19
|
|
|
@@ -16,9 +24,12 @@ const DEFAULT_PATH = '/usr/local/bin:/usr/bin:/bin';
|
|
|
16
24
|
* deliberately not pre-allowed, so each call becomes a prompt.
|
|
17
25
|
*
|
|
18
26
|
* `settingsFile` (execution machines): appended as `--settings <file>`, which
|
|
19
|
-
* carries the sandbox settings.
|
|
27
|
+
* carries the sandbox settings and the file tools' path rules.
|
|
28
|
+
*
|
|
29
|
+
* There is no `--add-dir`: under acceptEdits it makes a whole directory tree
|
|
30
|
+
* writable for the file tools; the settings name exact paths instead.
|
|
20
31
|
*/
|
|
21
|
-
export function claudeArgs({
|
|
32
|
+
export function claudeArgs({ interactive = false, settingsFile = '' } = {}) {
|
|
22
33
|
const args = [
|
|
23
34
|
'-p',
|
|
24
35
|
'--output-format',
|
|
@@ -27,21 +38,21 @@ export function claudeArgs({ addDirs = [], interactive = false, settingsFile = '
|
|
|
27
38
|
...(interactive
|
|
28
39
|
? ['--input-format', 'stream-json', '--permission-prompt-tool', 'stdio']
|
|
29
40
|
: []),
|
|
30
|
-
//
|
|
31
|
-
// allowlist
|
|
41
|
+
// Never bypassPermissions (refused as root anyway): acceptEdits plus the
|
|
42
|
+
// allowlist and the settings' path rules run unattended, and anything else
|
|
43
|
+
// is refused.
|
|
32
44
|
'--permission-mode',
|
|
33
45
|
'acceptEdits',
|
|
34
46
|
'--tools',
|
|
35
47
|
interactive ? `${CLAUDE_TOOLS},AskUserQuestion` : CLAUDE_TOOLS,
|
|
36
48
|
'--allowedTools',
|
|
37
|
-
|
|
49
|
+
CLAUDE_ALLOWED_TOOLS,
|
|
38
50
|
// Only the per-run project (.claude/skills copy); never the host's user settings.
|
|
39
51
|
'--setting-sources',
|
|
40
52
|
'project',
|
|
41
53
|
'--strict-mcp-config',
|
|
42
54
|
'--no-session-persistence',
|
|
43
55
|
];
|
|
44
|
-
for (const dir of addDirs) args.push('--add-dir', dir);
|
|
45
56
|
if (settingsFile) args.push('--settings', settingsFile);
|
|
46
57
|
return args;
|
|
47
58
|
}
|
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/interaction.mjs
CHANGED
|
@@ -32,7 +32,9 @@ export const INPUT_TURN_IDLE_CLOSE_MS = 11 * 60 * 1000;
|
|
|
32
32
|
export const QUESTION_TIMEOUT_MESSAGE =
|
|
33
33
|
'用户未在 5 分钟内回答。如果这个问题是在确认写操作(提交 PR / Issue、发表评论等),视为不同意,不要执行该操作;'
|
|
34
34
|
+ '其他问题按推荐选项继续。不要再次询问同一问题。';
|
|
35
|
-
const DENY_TOOL_MESSAGE =
|
|
35
|
+
const DENY_TOOL_MESSAGE =
|
|
36
|
+
'在线执行环境不允许这个操作:文件工具只能读写本次任务的工作目录、$HOME、$TMPDIR 和 $WORK_AGENT_HOME 下的 logs / tmp / docs'
|
|
37
|
+
+ '($WORK_AGENT_HOME 的其余部分只读)。';
|
|
36
38
|
|
|
37
39
|
// Lines this program adds to an interactive job's stdout, where claude's own
|
|
38
40
|
// control lines were (claude never prints these types). The website turns
|