@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/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,16 +33,19 @@ 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
|
-
/** The work-agent clone is fast-forwarded every day at this hour (local time). */
|
|
29
|
-
export const REPO_UPDATE_HOUR = 8;
|
|
30
|
-
/** The knowledge pool is updated this often (every repository it holds). */
|
|
31
|
-
export const POOL_UPDATE_MS = 60 * 60_000;
|
|
32
40
|
export const PROGRAM_DIR = '.work-agent-runner';
|
|
33
41
|
/** work-agent's own home, shared with the user's own use of it. */
|
|
34
42
|
export const WORK_AGENT_DIR = '.work-agent';
|
|
35
43
|
/** Its repository pool, which the program may be pointed at another disk. */
|
|
36
44
|
export const POOL_DIR = path.join(WORK_AGENT_DIR, 'ascend-repos');
|
|
45
|
+
/** Marks a directory given with --work-dir as this program's work root. */
|
|
46
|
+
export const WORK_ROOT_MARKER = '.work-agent-runner.json';
|
|
47
|
+
/** Where runs go when the directory given with --work-dir already holds other things. */
|
|
48
|
+
export const WORK_ROOT_SUBDIR = 'work-agent-runner';
|
|
37
49
|
|
|
38
50
|
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
51
|
|
|
@@ -45,28 +57,49 @@ export class ConfigError extends Error {}
|
|
|
45
57
|
/**
|
|
46
58
|
* Every path the program owns. `home` is the user's home directory; the
|
|
47
59
|
* program's own home is WORK_AGENT_RUNNER_HOME or <home>/.work-agent-runner.
|
|
60
|
+
* workAgentHome / poolDir / repoDir are first defaults: once config.json names
|
|
61
|
+
* them, withRepoPaths() takes the file's values.
|
|
48
62
|
*/
|
|
49
63
|
export function configPaths(env = process.env, home = os.homedir()) {
|
|
50
64
|
const base = env.WORK_AGENT_RUNNER_HOME ? path.resolve(env.WORK_AGENT_RUNNER_HOME) : path.join(home, PROGRAM_DIR);
|
|
51
65
|
const configRoot = env.XDG_CONFIG_HOME || path.join(home, '.config');
|
|
66
|
+
// work-agent's own home as work-agent.py finds it: WORK_AGENT_HOME, else ~/.work-agent.
|
|
67
|
+
const workAgentHome = env.WORK_AGENT_HOME ? path.resolve(env.WORK_AGENT_HOME) : path.join(home, WORK_AGENT_DIR);
|
|
52
68
|
return {
|
|
53
69
|
baseDir: base,
|
|
54
70
|
// saveConfig() creates this; it is the program's home, not a subdirectory.
|
|
55
71
|
configDir: base,
|
|
56
72
|
configFile: path.join(base, 'config.json'),
|
|
73
|
+
configLockFile: path.join(base, 'config.lock'),
|
|
57
74
|
lockFile: path.join(base, 'run.lock'),
|
|
58
75
|
repoDir: path.join(base, 'work-agent'),
|
|
76
|
+
// Where the clone is when config.json does not move it: a clone found here
|
|
77
|
+
// without an ownership marker was made by 0.0.2–0.0.4 (lib/work-agent.mjs).
|
|
78
|
+
defaultRepoDir: path.join(base, 'work-agent'),
|
|
59
79
|
repoLockFile: path.join(base, 'work-agent.lock'),
|
|
80
|
+
stateDir: path.join(base, 'state'),
|
|
81
|
+
requestsDir: path.join(base, 'state', 'requests'),
|
|
82
|
+
poolBusyFile: path.join(base, 'state', 'pool-busy'),
|
|
83
|
+
// What the instance knows about itself, readable when it does not answer (lib/state.mjs).
|
|
84
|
+
statusFile: path.join(base, 'state', 'status.json'),
|
|
85
|
+
historyFile: path.join(base, 'state', 'history.jsonl'),
|
|
86
|
+
logsDir: path.join(base, 'logs'),
|
|
87
|
+
logFile: path.join(base, 'logs', 'runner.log'),
|
|
88
|
+
// The local control interface (lib/control.mjs): socket, token, and where
|
|
89
|
+
// the socket really is when this path is too long for one.
|
|
90
|
+
controlDir: path.join(base, 'control'),
|
|
91
|
+
controlTokenFile: path.join(base, 'control', 'token'),
|
|
92
|
+
controlEndpointFile: path.join(base, 'control', 'endpoint'),
|
|
60
93
|
// WORK_AGENT_HOME handed to every job: work-agent's own home, a real
|
|
61
94
|
// directory outside the program's, so the user's own work-agent use sees
|
|
62
95
|
// the same logs, scratch and repository pool.
|
|
63
|
-
workAgentHome
|
|
96
|
+
workAgentHome,
|
|
64
97
|
// A symlink to it inside the program's home, so everything the program
|
|
65
98
|
// touches is reachable from one place.
|
|
66
99
|
workAgentLink: path.join(base, WORK_AGENT_DIR),
|
|
67
100
|
nodeDir: path.join(base, 'node'),
|
|
68
101
|
runsRoot: base,
|
|
69
|
-
poolDir: path.join(
|
|
102
|
+
poolDir: path.join(workAgentHome, 'ascend-repos'),
|
|
70
103
|
// Where earlier versions kept things (newest first: adopt the newest).
|
|
71
104
|
legacyConfigFiles: [
|
|
72
105
|
path.join(configRoot, 'work-agent-runner', 'config.json'),
|
|
@@ -91,20 +124,21 @@ export function configPaths(env = process.env, home = os.homedir()) {
|
|
|
91
124
|
}
|
|
92
125
|
|
|
93
126
|
/**
|
|
94
|
-
*
|
|
95
|
-
* is where the updater looks) and otherwise the
|
|
96
|
-
*
|
|
97
|
-
* the file always shows
|
|
127
|
+
* work-agent's home and the two repository locations, from the config file
|
|
128
|
+
* when it names them (that is where the updater looks) and otherwise the
|
|
129
|
+
* defaults. Returns `paths` with them resolved, and whether the config should
|
|
130
|
+
* be written back so the file always shows all three.
|
|
98
131
|
*/
|
|
99
132
|
export function withRepoPaths(paths, config) {
|
|
133
|
+
const workAgentHome = config.workAgentHome || paths.workAgentHome;
|
|
100
134
|
const repoDir = config.workAgentRepoDir || paths.repoDir;
|
|
101
|
-
const poolDir = config.ascendReposDir ||
|
|
135
|
+
const poolDir = config.ascendReposDir || path.join(workAgentHome, 'ascend-repos');
|
|
102
136
|
if (repoDir === poolDir) {
|
|
103
137
|
throw new ConfigError(`work-agent 仓库和知识仓不能是同一个目录(${repoDir})`);
|
|
104
138
|
}
|
|
105
139
|
return {
|
|
106
|
-
paths: { ...paths, repoDir, poolDir },
|
|
107
|
-
missing: !config.workAgentRepoDir || !config.ascendReposDir,
|
|
140
|
+
paths: { ...paths, workAgentHome, repoDir, poolDir },
|
|
141
|
+
missing: !config.workAgentRepoDir || !config.ascendReposDir || !config.workAgentHome,
|
|
108
142
|
};
|
|
109
143
|
}
|
|
110
144
|
|
|
@@ -130,9 +164,10 @@ function normalize(raw) {
|
|
|
130
164
|
};
|
|
131
165
|
if (typeof raw.workRoot === 'string' && raw.workRoot) config.workRoot = raw.workRoot;
|
|
132
166
|
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
|
-
|
|
167
|
+
// Where work-agent's home and the two repositories are. Written on first
|
|
168
|
+
// run, so the file shows them; edit it (absolute paths) to put any of them
|
|
169
|
+
// somewhere else.
|
|
170
|
+
for (const key of ['workAgentHome', 'workAgentRepoDir', 'ascendReposDir']) {
|
|
136
171
|
if (typeof raw[key] === 'string' && path.isAbsolute(raw[key])) config[key] = path.resolve(raw[key]);
|
|
137
172
|
}
|
|
138
173
|
// A mirror of the work-agent repository, for this machine only. http(s) only:
|
|
@@ -142,9 +177,38 @@ function normalize(raw) {
|
|
|
142
177
|
}
|
|
143
178
|
// The name sent with /connect: it names this machine when the website registers it.
|
|
144
179
|
if (typeof raw.machineName === 'string' && raw.machineName) config.machineName = raw.machineName.slice(0, 100);
|
|
180
|
+
// How a job sees work-agent's home (docs/design.md 2.6): 'shared' (the user's
|
|
181
|
+
// own, as before) or 'per-run'. A server execution machine always runs per-run.
|
|
182
|
+
if (raw.isolation === 'shared' || raw.isolation === 'per-run') config.isolation = raw.isolation;
|
|
183
|
+
const maintenance = {};
|
|
184
|
+
if (CLOCK.test(raw.maintenance?.repoRefreshAt)) maintenance.repoRefreshAt = raw.maintenance.repoRefreshAt;
|
|
185
|
+
if (CLOCK.test(raw.maintenance?.poolUpdateAt) || raw.maintenance?.poolUpdateAt === 'hourly') maintenance.poolUpdateAt = raw.maintenance.poolUpdateAt;
|
|
186
|
+
if (Object.keys(maintenance).length) config.maintenance = maintenance;
|
|
187
|
+
const limits = {};
|
|
188
|
+
const whole = (value, min, max) => Number.isInteger(value) && value >= min && value <= max;
|
|
189
|
+
if (whole(raw.limits?.minFreeBytes, 0, 2 ** 40)) limits.minFreeBytes = raw.limits.minFreeBytes;
|
|
190
|
+
if (whole(raw.limits?.jobWaitMaxMinutes, 1, 60)) limits.jobWaitMaxMinutes = raw.limits.jobWaitMaxMinutes;
|
|
191
|
+
if (whole(raw.limits?.archiveDays, 0, 30)) limits.archiveDays = raw.limits.archiveDays;
|
|
192
|
+
if (Object.keys(limits).length) config.limits = limits;
|
|
145
193
|
return config;
|
|
146
194
|
}
|
|
147
195
|
|
|
196
|
+
const CLOCK = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
197
|
+
|
|
198
|
+
/** When maintenance runs, unless config.json says otherwise (local time). */
|
|
199
|
+
export const DEFAULT_MAINTENANCE = { repoRefreshAt: '08:00', poolUpdateAt: '03:00' };
|
|
200
|
+
/** Limits, unless config.json says otherwise. */
|
|
201
|
+
export const DEFAULT_LIMITS = { minFreeBytes: 1024 ** 3, jobWaitMaxMinutes: 15, archiveDays: 0 };
|
|
202
|
+
|
|
203
|
+
/** The settings in effect: config.json's, else the defaults. */
|
|
204
|
+
export function effectiveSettings(config) {
|
|
205
|
+
return {
|
|
206
|
+
isolation: config.isolation || 'shared',
|
|
207
|
+
maintenance: { ...DEFAULT_MAINTENANCE, ...(config.maintenance || {}) },
|
|
208
|
+
limits: { ...DEFAULT_LIMITS, ...(config.limits || {}) },
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
148
212
|
/** The saved config (defaults when there is none); throws ConfigError when it is unreadable. */
|
|
149
213
|
export function loadConfig(paths) {
|
|
150
214
|
let text;
|
|
@@ -178,6 +242,23 @@ export function saveConfig(paths, config) {
|
|
|
178
242
|
fs.chmodSync(paths.configFile, 0o600);
|
|
179
243
|
}
|
|
180
244
|
|
|
245
|
+
/**
|
|
246
|
+
* Changes config.json field by field: under config.lock it is read again,
|
|
247
|
+
* `mutate(config)` changes what it means to, and the result is written. Two
|
|
248
|
+
* processes (the background service and a terminal `login`) never write back
|
|
249
|
+
* each other's stale copy. Returns the config as written.
|
|
250
|
+
*/
|
|
251
|
+
export function updateConfig(paths, mutate) {
|
|
252
|
+
fs.mkdirSync(paths.configDir, { recursive: true, mode: 0o700 });
|
|
253
|
+
const lockFile = paths.configLockFile || path.join(paths.configDir, 'config.lock');
|
|
254
|
+
return withFileLockSync(lockFile, () => {
|
|
255
|
+
const config = loadConfig(paths);
|
|
256
|
+
mutate(config);
|
|
257
|
+
saveConfig(paths, config);
|
|
258
|
+
return normalize(config);
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
181
262
|
/** The newest legacy config to adopt ('' when there is none, or one is already here). */
|
|
182
263
|
export function legacyConfigPending(paths) {
|
|
183
264
|
if (fs.existsSync(paths.configFile)) return '';
|
|
@@ -222,25 +303,154 @@ function realpathOr(value) {
|
|
|
222
303
|
}
|
|
223
304
|
}
|
|
224
305
|
|
|
225
|
-
|
|
306
|
+
function samePath(a, b) {
|
|
307
|
+
return realpathOr(a) === realpathOr(b);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// What a program home may hold before config.json exists (the entry point
|
|
311
|
+
// downloads Node into node/ first) or after an interrupted write.
|
|
312
|
+
const PROGRAM_ENTRIES = new Set([
|
|
313
|
+
'config.json', 'config.lock', 'run.lock', 'work-agent.lock', 'work-agent', WORK_AGENT_DIR,
|
|
314
|
+
'node', 'claude', 'runs', 'state', 'logs', 'control', 'archive', 'trash', WORK_ROOT_MARKER,
|
|
315
|
+
]);
|
|
316
|
+
const PROGRAM_ENTRY_PATTERNS = [/^config\.json\..+\.tmp$/, /^config\.json\.bak-/, /\.lock\..+\.tmp$/, /\.lock\.takeover$/, /^\.work-agent\.(new|old)-/];
|
|
317
|
+
|
|
318
|
+
/** Whether `name` is something this program keeps in its home. */
|
|
319
|
+
export function isProgramEntry(name) {
|
|
320
|
+
return PROGRAM_ENTRIES.has(name) || PROGRAM_ENTRY_PATTERNS.some((pattern) => pattern.test(name));
|
|
321
|
+
}
|
|
226
322
|
|
|
227
323
|
/**
|
|
228
|
-
*
|
|
229
|
-
*
|
|
230
|
-
*
|
|
231
|
-
*
|
|
232
|
-
*
|
|
324
|
+
* Checks (creating it when missing) the program's home before anything is
|
|
325
|
+
* written into it. It must be new, empty, or this program's already
|
|
326
|
+
* (config.json, or only names this program uses): pointed at a directory of
|
|
327
|
+
* the user's, a start would delete its runs/ and change its mode. Makes it
|
|
328
|
+
* 0700 and returns its real path; throws ConfigError.
|
|
233
329
|
*/
|
|
234
|
-
export function
|
|
235
|
-
const resolved = path.resolve(
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
if (stat.
|
|
330
|
+
export function prepareProgramHome(base, { uid = process.getuid?.() ?? 0 } = {}) {
|
|
331
|
+
const resolved = path.resolve(base);
|
|
332
|
+
let stat;
|
|
333
|
+
try {
|
|
334
|
+
fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
|
|
335
|
+
stat = fs.statSync(resolved);
|
|
336
|
+
} catch (error) {
|
|
337
|
+
throw new ConfigError(`无法使用程序目录 ${resolved}:${error.message}`);
|
|
338
|
+
}
|
|
339
|
+
if (!stat.isDirectory()) throw new ConfigError(`程序目录 ${resolved} 不是目录`);
|
|
340
|
+
if (stat.uid !== uid) throw new ConfigError(`程序目录 ${resolved} 的属主不是当前用户`);
|
|
341
|
+
if (!fs.existsSync(path.join(resolved, 'config.json'))) {
|
|
342
|
+
const foreign = fs.readdirSync(resolved).filter((name) => !isProgramEntry(name));
|
|
343
|
+
if (foreign.length) {
|
|
344
|
+
throw new ConfigError(
|
|
345
|
+
`${resolved} 里已有不属于本程序的内容(${foreign.slice(0, 3).join('、')}${foreign.length > 3 ? ' 等' : ''}),` +
|
|
346
|
+
'不能用作程序目录:请把 WORK_AGENT_RUNNER_HOME 设为一个新的或空的目录',
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
244
350
|
if ((stat.mode & 0o777) !== 0o700) fs.chmodSync(resolved, 0o700);
|
|
245
351
|
return fs.realpathSync(resolved);
|
|
246
352
|
}
|
|
353
|
+
|
|
354
|
+
export class WorkRootError extends Error {}
|
|
355
|
+
|
|
356
|
+
// Never a work root themselves (a subdirectory is fine).
|
|
357
|
+
const SYSTEM_DIRS = new Set([
|
|
358
|
+
'/', '/bin', '/boot', '/dev', '/etc', '/home', '/lib', '/lib32', '/lib64', '/libx32', '/media', '/mnt', '/opt',
|
|
359
|
+
'/proc', '/root', '/run', '/sbin', '/srv', '/sys', '/tmp', '/usr', '/var', '/var/tmp',
|
|
360
|
+
'/Applications', '/Library', '/private', '/System', '/Users', '/Volumes',
|
|
361
|
+
]);
|
|
362
|
+
|
|
363
|
+
function workRootProblem(resolved, home) {
|
|
364
|
+
const real = realpathOr(resolved);
|
|
365
|
+
const realHome = realpathOr(home);
|
|
366
|
+
if (resolved === path.resolve(home) || real === realHome) {
|
|
367
|
+
return `工作目录不能是主目录本身(${resolved}),请用 --work-dir 指定一个子目录`;
|
|
368
|
+
}
|
|
369
|
+
if (SYSTEM_DIRS.has(resolved) || SYSTEM_DIRS.has(real)) {
|
|
370
|
+
return `工作目录不能是 ${resolved},请用 --work-dir 指定其下的一个子目录`;
|
|
371
|
+
}
|
|
372
|
+
if (isInside(realHome, real)) return `工作目录不能是主目录的上级目录(${resolved}),请用 --work-dir 指定一个子目录`;
|
|
373
|
+
return '';
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** Only runs/ (with run and probe directories in it), trash/ and archive/: what 0.0.4 and later leave. */
|
|
377
|
+
function isLegacyWorkRoot(dir, names, uid) {
|
|
378
|
+
if (!names.includes('runs') || !names.every((name) => ['runs', 'trash', 'archive'].includes(name))) return false;
|
|
379
|
+
try {
|
|
380
|
+
for (const name of names) if (!fs.lstatSync(path.join(dir, name)).isDirectory()) return false;
|
|
381
|
+
const runs = path.join(dir, 'runs');
|
|
382
|
+
return fs.readdirSync(runs).every((name) => isRunEntry(runs, name, { uid }));
|
|
383
|
+
} catch {
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function writeWorkRootMarker(dir, { programHome, createdByProgram }) {
|
|
389
|
+
writeJsonAtomic(path.join(dir, WORK_ROOT_MARKER), {
|
|
390
|
+
kind: 'work-root',
|
|
391
|
+
programHome: programHome ? realpathOr(programHome) : '',
|
|
392
|
+
createdByProgram,
|
|
393
|
+
createdAt: new Date().toISOString(),
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function chooseWorkRoot(candidate, { programHome, uid, allowSubdir }) {
|
|
398
|
+
let stat = null;
|
|
399
|
+
try {
|
|
400
|
+
stat = fs.lstatSync(candidate);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
if (error.code !== 'ENOENT') throw new WorkRootError(`无法使用工作目录 ${candidate}:${error.message}`);
|
|
403
|
+
}
|
|
404
|
+
if (!stat) {
|
|
405
|
+
fs.mkdirSync(candidate, { recursive: true, mode: 0o700 });
|
|
406
|
+
writeWorkRootMarker(candidate, { programHome, createdByProgram: true });
|
|
407
|
+
return candidate;
|
|
408
|
+
}
|
|
409
|
+
if (stat.isSymbolicLink()) throw new WorkRootError(`工作目录 ${candidate} 不能是符号链接`);
|
|
410
|
+
if (!stat.isDirectory()) throw new WorkRootError(`${candidate} 不是目录`);
|
|
411
|
+
if (stat.uid !== uid) throw new WorkRootError(`工作目录 ${candidate} 的属主不是当前用户,请删除它或用 --work-dir 换一个目录`);
|
|
412
|
+
const marker = readJsonFile(path.join(candidate, WORK_ROOT_MARKER));
|
|
413
|
+
if (marker) {
|
|
414
|
+
if (marker.programHome && programHome && !samePath(marker.programHome, programHome)) {
|
|
415
|
+
throw new WorkRootError(
|
|
416
|
+
`工作目录 ${candidate} 已属于另一个程序目录(${marker.programHome}):两者共用会互相清理对方的任务目录,请用 --work-dir 换一个目录`,
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
return candidate;
|
|
420
|
+
}
|
|
421
|
+
const names = fs.readdirSync(candidate);
|
|
422
|
+
if (names.length === 0 || isLegacyWorkRoot(candidate, names, uid)) {
|
|
423
|
+
writeWorkRootMarker(candidate, { programHome, createdByProgram: false });
|
|
424
|
+
return candidate;
|
|
425
|
+
}
|
|
426
|
+
// Other things live here (/data, a project…): never touch them, use a subdirectory.
|
|
427
|
+
if (allowSubdir) return chooseWorkRoot(path.join(candidate, WORK_ROOT_SUBDIR), { programHome, uid, allowSubdir: false });
|
|
428
|
+
throw new WorkRootError(
|
|
429
|
+
`${candidate} 不是空目录,也不是本程序的工作目录(没有 ${WORK_ROOT_MARKER}):请用 --work-dir 指定一个新目录或空目录`,
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* The directory that holds runs/ and trash/. The program's home by default
|
|
435
|
+
* (`programHome`); a directory given with --work-dir must be new, empty, or
|
|
436
|
+
* marked as this program's (WORK_ROOT_MARKER) — one that already holds other
|
|
437
|
+
* things gets a work-agent-runner/ subdirectory instead, so nothing of the
|
|
438
|
+
* user's is ever deleted or chmod-ed (docs/design.md 3.4.2). Never the home
|
|
439
|
+
* itself, one of its parents or a system directory; not a symlink; owned by
|
|
440
|
+
* this user. Returns its real path, which everything else uses.
|
|
441
|
+
*/
|
|
442
|
+
export function prepareWorkRoot(dir, { home = os.homedir(), uid = process.getuid?.() ?? 0, programHome = '' } = {}) {
|
|
443
|
+
const resolved = path.resolve(dir);
|
|
444
|
+
if (programHome && samePath(resolved, programHome)) {
|
|
445
|
+
fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
|
|
446
|
+
return fs.realpathSync(resolved);
|
|
447
|
+
}
|
|
448
|
+
const problem = workRootProblem(resolved, home);
|
|
449
|
+
if (problem) throw new WorkRootError(problem);
|
|
450
|
+
const chosen = chooseWorkRoot(resolved, { programHome, uid, allowSubdir: true });
|
|
451
|
+
const stat = fs.lstatSync(chosen);
|
|
452
|
+
if (stat.isSymbolicLink()) throw new WorkRootError(`工作目录 ${chosen} 不能是符号链接`);
|
|
453
|
+
if (!stat.isDirectory()) throw new WorkRootError(`${chosen} 不是目录`);
|
|
454
|
+
if (stat.uid !== uid) throw new WorkRootError(`工作目录 ${chosen} 的属主不是当前用户,请删除它或用 --work-dir 换一个目录`);
|
|
455
|
+
return fs.realpathSync(chosen);
|
|
456
|
+
}
|
package/lib/connection.mjs
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
// (token deleted, machine blocked, the same config running twice), 0 when
|
|
9
9
|
// stopped through `signal`.
|
|
10
10
|
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
|
|
11
13
|
import { ApiError, IdleError } from './http.mjs';
|
|
12
14
|
|
|
13
15
|
export const UPDATE_COMMAND = 'npm i -g @online-tools/work-agent-runner@latest';
|
|
@@ -73,6 +75,14 @@ function jitter(ms) {
|
|
|
73
75
|
* confirmed whether the owner has confirmed this machine (from the connect reply);
|
|
74
76
|
* the program says so once when that changes
|
|
75
77
|
* heartbeatMs from the connect reply
|
|
78
|
+
* onStatus (optional) { connected, since, lastHeartbeatAt, lastError, confirmed }
|
|
79
|
+
* as they change, for the instance's status
|
|
80
|
+
* onReply (optional) the reply of a /connect made here (re-registration)
|
|
81
|
+
*
|
|
82
|
+
* A heartbeat reply may carry capabilitiesDigest (the SHA-256 of the
|
|
83
|
+
* capabilities the website last received, as JSON): when it is not this
|
|
84
|
+
* program's, the next heartbeat sends them again (a terminal's /connect may
|
|
85
|
+
* have reported another environment's).
|
|
76
86
|
*/
|
|
77
87
|
export async function runConnection({
|
|
78
88
|
client,
|
|
@@ -85,14 +95,24 @@ export async function runConnection({
|
|
|
85
95
|
confirmed = true,
|
|
86
96
|
heartbeatMs = 20_000,
|
|
87
97
|
signal,
|
|
98
|
+
onStatus = () => {},
|
|
99
|
+
onReply = () => {},
|
|
88
100
|
}) {
|
|
89
101
|
const stopper = new AbortController();
|
|
90
102
|
const stop = AbortSignal.any([signal || new AbortController().signal, stopper.signal]);
|
|
91
103
|
const state = { result: null, heartbeatMs, replaced: [], sentCapabilities: '', warnedOutdated: false, toldLatest: '', confirmed };
|
|
92
104
|
|
|
105
|
+
const report = (patch) => {
|
|
106
|
+
try {
|
|
107
|
+
onStatus(patch);
|
|
108
|
+
} catch {
|
|
109
|
+
// Status is for display only.
|
|
110
|
+
}
|
|
111
|
+
};
|
|
93
112
|
const noteConfirmed = (value, name = '') => {
|
|
94
113
|
if (typeof value !== 'boolean' || value === state.confirmed) return;
|
|
95
114
|
state.confirmed = value;
|
|
115
|
+
report({ confirmed: value });
|
|
96
116
|
if (value) log.info(`✓ 网页上已确认这台机器${name ? `「${name}」` : ''},可以接收任务了`);
|
|
97
117
|
else log.warn('这台机器需要在网页上(重新)确认后才会收到任务:在线 Agent → 模型配置 → 执行机器');
|
|
98
118
|
};
|
|
@@ -115,6 +135,11 @@ export async function runConnection({
|
|
|
115
135
|
const reply = await connect();
|
|
116
136
|
if (reply?.heartbeatMs) state.heartbeatMs = reply.heartbeatMs;
|
|
117
137
|
state.sentCapabilities = '';
|
|
138
|
+
try {
|
|
139
|
+
onReply(reply);
|
|
140
|
+
} catch {
|
|
141
|
+
// The caller's business.
|
|
142
|
+
}
|
|
118
143
|
noteConfirmed(reply?.confirmed, reply?.name);
|
|
119
144
|
} catch (failure) {
|
|
120
145
|
const again = fatalFor(failure);
|
|
@@ -178,6 +203,13 @@ export async function runConnection({
|
|
|
178
203
|
try {
|
|
179
204
|
const reply = await client.request('POST', '/heartbeat', body, { signal: stop });
|
|
180
205
|
if (body.capabilities) state.sentCapabilities = current;
|
|
206
|
+
report({ lastHeartbeatAt: new Date().toISOString() });
|
|
207
|
+
// The website holds capabilities this program did not send (a terminal's
|
|
208
|
+
// /connect from another environment): send them again next time.
|
|
209
|
+
if (typeof reply?.capabilitiesDigest === 'string' && reply.capabilitiesDigest) {
|
|
210
|
+
const mine = crypto.createHash('sha256').update(state.sentCapabilities || current).digest('hex');
|
|
211
|
+
if (reply.capabilitiesDigest !== mine) state.sentCapabilities = '';
|
|
212
|
+
}
|
|
181
213
|
for (const runId of Array.isArray(reply?.cancel) ? reply.cancel : []) jobs.cancel(runId);
|
|
182
214
|
// Answers the website has not seen arrive yet (the control channel may
|
|
183
215
|
// have been down); repeats of one already given are dropped.
|
|
@@ -208,12 +240,17 @@ export async function runConnection({
|
|
|
208
240
|
onOpen: () => {
|
|
209
241
|
openedAt = Date.now();
|
|
210
242
|
log.info('控制通道已连接,等待任务');
|
|
243
|
+
report({ connected: true, since: new Date(openedAt).toISOString(), lastError: '' });
|
|
211
244
|
},
|
|
212
245
|
onEvent,
|
|
213
246
|
});
|
|
214
|
-
if (!stop.aborted)
|
|
247
|
+
if (!stop.aborted) {
|
|
248
|
+
log.warn('控制通道已断开,稍后重连');
|
|
249
|
+
report({ connected: false, lastError: '控制通道已断开' });
|
|
250
|
+
}
|
|
215
251
|
} catch (error) {
|
|
216
252
|
if (stop.aborted) break;
|
|
253
|
+
report({ connected: false, lastError: error instanceof ApiError ? error.message : error?.cause?.code || error.message });
|
|
217
254
|
if (error instanceof IdleError) log.warn(`${error.message},重新连接`);
|
|
218
255
|
else if (error instanceof ApiError) {
|
|
219
256
|
await handleError(error);
|