@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/work-agent.mjs
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
// The work-agent repository on this machine: the Skill source for every job,
|
|
2
2
|
// and the optional AscendC knowledge pool (lib/config.mjs owns the paths):
|
|
3
3
|
//
|
|
4
|
-
// ~/.work-agent-runner/work-agent/ the clone, tracking origin/main
|
|
5
|
-
//
|
|
4
|
+
// ~/.work-agent-runner/work-agent/ the clone, tracking origin/main;
|
|
5
|
+
// .git/work-agent-runner.json marks it
|
|
6
|
+
// as this program's
|
|
7
|
+
// ~/.work-agent-runner/work-agent.lock the clone's lock (a terminal `update` vs the service)
|
|
6
8
|
// ~/.work-agent/ work-agent's own home = the
|
|
7
9
|
// WORK_AGENT_HOME of every job
|
|
8
10
|
// ├ ascend-repos/ the repository pool, built by
|
|
@@ -20,16 +22,28 @@
|
|
|
20
22
|
// development and tests) may point it at a mirror, and clone() logs the URL it
|
|
21
23
|
// used.
|
|
22
24
|
//
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
//
|
|
25
|
+
// Ownership (docs/design.md 3.8): only a clone this program made (marked, or
|
|
26
|
+
// found at its default place in the program's home) is ever replaced or
|
|
27
|
+
// deleted. A workAgentRepoDir pointed at anything else — a project of the
|
|
28
|
+
// user's, another repository, their own work-agent with local commits — is
|
|
29
|
+
// reported and left exactly as it is.
|
|
30
|
+
//
|
|
31
|
+
// Concurrency: clone operations (refresh, a job's copy) run one at a time in
|
|
32
|
+
// this process and under work-agent.lock across processes; a job waits for
|
|
33
|
+
// the lock instead of failing. Knowledge-pool operations run one at a time on
|
|
34
|
+
// their own queue and never hold the clone's lock (a download can take hours);
|
|
35
|
+
// work-agent.py's own lock covers other processes. While the pool is being
|
|
36
|
+
// updated (git pull) — here or by a terminal `update` (state/pool-busy) —
|
|
37
|
+
// jobs wait before they start (waitForPoolIdle).
|
|
26
38
|
|
|
27
39
|
import { spawn, spawnSync } from 'node:child_process';
|
|
40
|
+
import crypto from 'node:crypto';
|
|
28
41
|
import fs from 'node:fs';
|
|
29
42
|
import os from 'node:os';
|
|
30
43
|
import path from 'node:path';
|
|
31
44
|
|
|
32
|
-
import {
|
|
45
|
+
import { readJsonFile, removeTree, writeJsonAtomic } from './fs-safe.mjs';
|
|
46
|
+
import { LockedError, acquireLockWaiting, isRunnerAlive } from './lock.mjs';
|
|
33
47
|
import { CA_VARIABLES, PROXY_VARIABLES, prepareWorkAgentHome } from './sandbox.mjs';
|
|
34
48
|
import { copyTreeDetached, rewriteSkillPaths } from './skill-tree.mjs';
|
|
35
49
|
|
|
@@ -51,7 +65,11 @@ const ASCEND_ENTRY = {
|
|
|
51
65
|
// directory with something in it — not a particular Skill, which work-agent is
|
|
52
66
|
// free to rename.
|
|
53
67
|
const SKILLS_SUBDIR = path.join('.claude', 'skills');
|
|
54
|
-
|
|
68
|
+
// The repository is a few MB: these are generous, and run without blocking
|
|
69
|
+
// the program (heartbeats and job output keep flowing).
|
|
70
|
+
const FETCH_TIMEOUT_MS = 2 * 60_000;
|
|
71
|
+
const CLONE_TIMEOUT_MS = 5 * 60_000;
|
|
72
|
+
const LOCAL_GIT_TIMEOUT_MS = 30_000;
|
|
55
73
|
// The essential list is large and grows with upstream, cloned 8 at a time;
|
|
56
74
|
// work-agent.py gives each git operation 1800 s, so never be the one that kills
|
|
57
75
|
// it first. The free-space figure is a floor, not a claim about the list's size.
|
|
@@ -61,14 +79,10 @@ const ESSENTIAL_FILE = 'essential-repos.txt';
|
|
|
61
79
|
const KILL_GRACE_MS = 5000;
|
|
62
80
|
// work-agent.py cleanup: tmp/ is emptied and logs older than this are dropped.
|
|
63
81
|
const LOG_DAYS = 30;
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
} catch {
|
|
69
|
-
return path.resolve(value);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
82
|
+
/** How long a job waits for another process to be done with the clone. */
|
|
83
|
+
export const CLONE_LOCK_WAIT_MS = 10 * 60_000;
|
|
84
|
+
/** The ownership marker, inside .git: git ignores it and a job's copy skips .git. */
|
|
85
|
+
export const CLONE_MARKER = 'work-agent-runner.json';
|
|
72
86
|
|
|
73
87
|
function exists(file) {
|
|
74
88
|
try {
|
|
@@ -79,6 +93,8 @@ function exists(file) {
|
|
|
79
93
|
}
|
|
80
94
|
}
|
|
81
95
|
|
|
96
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
97
|
+
|
|
82
98
|
/**
|
|
83
99
|
* git's environment: PATH and HOME (for ~/.gitconfig), the proxy and CA
|
|
84
100
|
* variables this machine passes through (corporate machines need them, and the
|
|
@@ -100,7 +116,12 @@ function gitEnv(env) {
|
|
|
100
116
|
// repos into the Skill tree (work-agent has submodules inside .claude/skills).
|
|
101
117
|
const GIT_CONFIG = ['-c', 'credential.helper=', '-c', 'submodule.recurse=false'];
|
|
102
118
|
|
|
103
|
-
function
|
|
119
|
+
function lastLine(text) {
|
|
120
|
+
return String(text || '').trim().split('\n').filter(Boolean).pop() || '';
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Quick local queries (rev-parse, log, status): synchronous. */
|
|
124
|
+
function git(args, { cwd, env = process.env, timeout = LOCAL_GIT_TIMEOUT_MS } = {}) {
|
|
104
125
|
const result = spawnSync('git', [...GIT_CONFIG, ...args], {
|
|
105
126
|
cwd,
|
|
106
127
|
env: gitEnv(env),
|
|
@@ -108,15 +129,48 @@ function git(args, { cwd, env = process.env, timeout = GIT_TIMEOUT_MS } = {}) {
|
|
|
108
129
|
timeout,
|
|
109
130
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
110
131
|
});
|
|
111
|
-
const stderr = String(result.stderr || '').trim();
|
|
112
132
|
return {
|
|
113
133
|
ok: !result.error && result.status === 0,
|
|
114
134
|
stdout: String(result.stdout || '').trim(),
|
|
115
|
-
stderr
|
|
116
|
-
reason: result.error ? result.error.message : stderr.split('\n').filter(Boolean).pop() || `git ${args[0]} 退出码 ${result.status}`,
|
|
135
|
+
reason: result.error ? result.error.message : lastLine(result.stderr) || `git ${args[0]} 退出码 ${result.status}`,
|
|
117
136
|
};
|
|
118
137
|
}
|
|
119
138
|
|
|
139
|
+
/** Anything that may wait on the network (clone, fetch, merge): asynchronous. */
|
|
140
|
+
function gitAsync(args, { cwd, env = process.env, timeout }) {
|
|
141
|
+
return new Promise((resolve) => {
|
|
142
|
+
let child;
|
|
143
|
+
try {
|
|
144
|
+
child = spawn('git', [...GIT_CONFIG, ...args], { cwd, env: gitEnv(env), stdio: ['ignore', 'pipe', 'pipe'] });
|
|
145
|
+
} catch (error) {
|
|
146
|
+
resolve({ ok: false, stdout: '', reason: error.message });
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
let stdout = '';
|
|
150
|
+
let stderr = '';
|
|
151
|
+
let timedOut = false;
|
|
152
|
+
const timer = setTimeout(() => {
|
|
153
|
+
timedOut = true;
|
|
154
|
+
child.kill('SIGKILL');
|
|
155
|
+
}, timeout);
|
|
156
|
+
child.stdout.on('data', (chunk) => {
|
|
157
|
+
stdout += chunk;
|
|
158
|
+
});
|
|
159
|
+
child.stderr.on('data', (chunk) => {
|
|
160
|
+
stderr += chunk;
|
|
161
|
+
});
|
|
162
|
+
child.once('error', (error) => {
|
|
163
|
+
clearTimeout(timer);
|
|
164
|
+
resolve({ ok: false, stdout: '', reason: error.message });
|
|
165
|
+
});
|
|
166
|
+
child.once('close', (code) => {
|
|
167
|
+
clearTimeout(timer);
|
|
168
|
+
const reason = timedOut ? `git ${args[0]} 超过 ${Math.round(timeout / 1000)} 秒,已停止` : lastLine(stderr) || `git ${args[0]} 退出码 ${code}`;
|
|
169
|
+
resolve({ ok: code === 0 && !timedOut, stdout: stdout.trim(), reason });
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
120
174
|
/** Bytes free on the filesystem holding `dir` (its nearest existing parent); 0 when unknown. */
|
|
121
175
|
export function freeBytes(dir) {
|
|
122
176
|
let target = path.resolve(dir);
|
|
@@ -142,14 +196,73 @@ function killGroup(child, signal) {
|
|
|
142
196
|
}
|
|
143
197
|
}
|
|
144
198
|
|
|
199
|
+
function hasSkillTree(dir) {
|
|
200
|
+
try {
|
|
201
|
+
return fs.readdirSync(path.join(dir, SKILLS_SUBDIR)).some((name) => !name.startsWith('.'));
|
|
202
|
+
} catch {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// ---- The knowledge pool between processes ----------------------------------------
|
|
208
|
+
// A terminal's `update` / `setup` marks the pool busy (state/pool-busy) so the
|
|
209
|
+
// service holds new jobs while a `git pull` runs and postpones its own update;
|
|
210
|
+
// with the service running, a terminal `update` leaves the pull to it
|
|
211
|
+
// (state/requests/pool-update).
|
|
212
|
+
|
|
213
|
+
/** The knowledge-pool operation another process is running: { pid, kind: 'update' | 'init', startedAt }, or null. */
|
|
214
|
+
export function poolBusyInfo(paths) {
|
|
215
|
+
if (!paths?.poolBusyFile) return null;
|
|
216
|
+
const info = readJsonFile(paths.poolBusyFile);
|
|
217
|
+
const pid = Number(info?.pid);
|
|
218
|
+
if (!info || pid === process.pid || !isRunnerAlive(pid)) return null;
|
|
219
|
+
return { pid, kind: info.kind === 'init' ? 'init' : 'update', startedAt: String(info.startedAt || '') };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Marks this process's knowledge-pool operation; returns the function that clears the mark. */
|
|
223
|
+
export function markPoolBusy(paths, kind) {
|
|
224
|
+
fs.mkdirSync(path.dirname(paths.poolBusyFile), { recursive: true, mode: 0o700 });
|
|
225
|
+
writeJsonAtomic(paths.poolBusyFile, { pid: process.pid, kind, startedAt: new Date().toISOString() });
|
|
226
|
+
return () => {
|
|
227
|
+
if (Number(readJsonFile(paths.poolBusyFile)?.pid) === process.pid) fs.rmSync(paths.poolBusyFile, { force: true });
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function requestFile(paths) {
|
|
232
|
+
return path.join(paths.requestsDir, 'pool-update');
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Asks the running service to update the knowledge pool as soon as no job runs. */
|
|
236
|
+
export function requestPoolUpdate(paths) {
|
|
237
|
+
fs.mkdirSync(paths.requestsDir, { recursive: true, mode: 0o700 });
|
|
238
|
+
writeJsonAtomic(requestFile(paths), { requestedAt: new Date().toISOString(), pid: process.pid });
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** When a pool update was requested (ISO time), or ''. */
|
|
242
|
+
export function poolUpdateRequested(paths) {
|
|
243
|
+
const request = readJsonFile(requestFile(paths));
|
|
244
|
+
return request ? String(request.requestedAt || 'unknown') : '';
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function clearPoolUpdateRequest(paths) {
|
|
248
|
+
fs.rmSync(requestFile(paths), { force: true });
|
|
249
|
+
}
|
|
250
|
+
|
|
145
251
|
export class WorkAgent {
|
|
146
|
-
/**
|
|
147
|
-
|
|
252
|
+
/**
|
|
253
|
+
* `paths` from configPaths() / withRepoPaths(); `repoUrl` only from the
|
|
254
|
+
* machine's own config; `lockWaitMs`: how long clone operations wait for
|
|
255
|
+
* another process (jobs: 10 minutes; a terminal command: less).
|
|
256
|
+
*/
|
|
257
|
+
constructor({ paths, env = process.env, log = null, repoUrl = REPO_URL, lockWaitMs = CLONE_LOCK_WAIT_MS } = {}) {
|
|
148
258
|
this.paths = paths;
|
|
149
259
|
this.env = env;
|
|
150
260
|
this.log = log;
|
|
151
261
|
this.repoUrl = repoUrl || REPO_URL;
|
|
152
|
-
this.
|
|
262
|
+
this.lockWaitMs = lockWaitMs;
|
|
263
|
+
this.cloneQueue = Promise.resolve();
|
|
264
|
+
this.poolQueue = Promise.resolve();
|
|
265
|
+
this.poolUpdates = 0;
|
|
153
266
|
this.child = null;
|
|
154
267
|
this.stopped = false;
|
|
155
268
|
}
|
|
@@ -166,14 +279,24 @@ export class WorkAgent {
|
|
|
166
279
|
return path.join(this.paths.repoDir, SKILLS_SUBDIR);
|
|
167
280
|
}
|
|
168
281
|
|
|
169
|
-
/**
|
|
170
|
-
|
|
171
|
-
|
|
282
|
+
/** A `git pull` in the pool is running or about to (updatePool). */
|
|
283
|
+
get poolUpdating() {
|
|
284
|
+
return this.poolUpdates > 0;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Runs `fn` alone among clone operations: after anything queued here, and
|
|
289
|
+
* holding work-agent.lock, for which it waits up to `waitMs`.
|
|
290
|
+
*/
|
|
291
|
+
withClone(fn, { waitMs = this.lockWaitMs } = {}) {
|
|
292
|
+
const next = this.cloneQueue.then(async () => {
|
|
293
|
+
fs.mkdirSync(path.dirname(this.paths.repoLockFile), { recursive: true, mode: 0o700 });
|
|
172
294
|
let lock;
|
|
173
295
|
try {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
296
|
+
lock = await acquireLockWaiting(this.paths.repoLockFile, {
|
|
297
|
+
timeoutMs: waitMs,
|
|
298
|
+
onWait: (pid) => this.note('info', `work-agent 仓库正被另一个进程使用(pid ${pid}),等待它结束……`),
|
|
299
|
+
});
|
|
177
300
|
} catch (error) {
|
|
178
301
|
if (error instanceof LockedError) {
|
|
179
302
|
throw new Error(`work-agent 仓库正被另一个进程使用(pid ${error.pid}),请稍后再试`);
|
|
@@ -187,41 +310,119 @@ export class WorkAgent {
|
|
|
187
310
|
}
|
|
188
311
|
});
|
|
189
312
|
// Keep the chain alive whatever this call does.
|
|
190
|
-
this.
|
|
313
|
+
this.cloneQueue = next.then(
|
|
314
|
+
() => {},
|
|
315
|
+
() => {},
|
|
316
|
+
);
|
|
317
|
+
return next;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** The former name of withClone(), for callers that still use it. */
|
|
321
|
+
run(fn) {
|
|
322
|
+
return this.withClone(fn);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Runs `fn` alone among knowledge-pool operations in this process. */
|
|
326
|
+
withPool(fn) {
|
|
327
|
+
const next = this.poolQueue.then(fn);
|
|
328
|
+
this.poolQueue = next.then(
|
|
191
329
|
() => {},
|
|
192
330
|
() => {},
|
|
193
331
|
);
|
|
194
332
|
return next;
|
|
195
333
|
}
|
|
196
334
|
|
|
335
|
+
isDefaultLocation() {
|
|
336
|
+
return Boolean(this.paths.defaultRepoDir) && path.resolve(this.paths.repoDir) === path.resolve(this.paths.defaultRepoDir);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** A clean clone of work-agent's main from this URL, with nothing local to lose. */
|
|
340
|
+
isCleanClone() {
|
|
341
|
+
const { repoDir } = this.paths;
|
|
342
|
+
if (!exists(path.join(repoDir, '.git'))) return false;
|
|
343
|
+
const query = (args) => git(args, { cwd: repoDir, env: this.env });
|
|
344
|
+
const origin = query(['remote', 'get-url', 'origin']);
|
|
345
|
+
if (!origin.ok || origin.stdout !== this.repoUrl) return false;
|
|
346
|
+
const branch = query(['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
347
|
+
if (!branch.ok || branch.stdout !== REPO_BRANCH) return false;
|
|
348
|
+
const status = query(['status', '--porcelain']);
|
|
349
|
+
if (!status.ok || status.stdout !== '') return false;
|
|
350
|
+
const ahead = query(['rev-list', '--count', `origin/${REPO_BRANCH}..HEAD`]);
|
|
351
|
+
return ahead.ok && ahead.stdout === '0';
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Whose the clone directory is: { kind: 'absent' } (missing or empty: clone
|
|
356
|
+
* there), { kind: 'owned', adopt? } (marked; or a clone at the default place,
|
|
357
|
+
* or a clean work-agent clone, made by an earlier version: mark it), or
|
|
358
|
+
* { kind: 'foreign', reason } — never changed, never deleted.
|
|
359
|
+
*/
|
|
360
|
+
ownership() {
|
|
361
|
+
const { repoDir } = this.paths;
|
|
362
|
+
let stat;
|
|
363
|
+
try {
|
|
364
|
+
stat = fs.lstatSync(repoDir);
|
|
365
|
+
} catch {
|
|
366
|
+
return { kind: 'absent' };
|
|
367
|
+
}
|
|
368
|
+
const foreign = (what) => ({
|
|
369
|
+
kind: 'foreign',
|
|
370
|
+
reason:
|
|
371
|
+
`${repoDir} ${what},不是本程序创建的 work-agent 仓库,程序不会改动或删除它;` +
|
|
372
|
+
'请在 config.json 里把 workAgentRepoDir 改成一个不存在的或空的目录(或删掉这一项,使用默认位置)',
|
|
373
|
+
});
|
|
374
|
+
if (stat.isSymbolicLink()) return foreign('是符号链接');
|
|
375
|
+
if (!stat.isDirectory()) return foreign('不是目录');
|
|
376
|
+
if (exists(path.join(repoDir, '.git', CLONE_MARKER))) return { kind: 'owned' };
|
|
377
|
+
let names = [];
|
|
378
|
+
try {
|
|
379
|
+
names = fs.readdirSync(repoDir);
|
|
380
|
+
} catch {
|
|
381
|
+
return foreign('无法读取');
|
|
382
|
+
}
|
|
383
|
+
if (!names.length) return { kind: 'absent' };
|
|
384
|
+
if (this.isDefaultLocation() || this.isCleanClone()) return { kind: 'owned', adopt: true };
|
|
385
|
+
return foreign('已有内容');
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
markOwned(dir = this.paths.repoDir) {
|
|
389
|
+
writeJsonAtomic(path.join(dir, '.git', CLONE_MARKER), {
|
|
390
|
+
kind: 'work-agent-clone',
|
|
391
|
+
repoUrl: this.repoUrl,
|
|
392
|
+
programHome: this.paths.baseDir || '',
|
|
393
|
+
markedAt: new Date().toISOString(),
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
|
|
197
397
|
/**
|
|
198
398
|
* What this machine has, read without the lock (callers display it):
|
|
199
|
-
* { ok, reason, commit, committedAt, repos, ascend, incomplete, poolFetchedAt }
|
|
399
|
+
* { ok, reason, commit, committedAt, repos, ascend, incomplete, poolFetchedAt }
|
|
400
|
+
* (and foreign: true when the configured directory is not this program's).
|
|
200
401
|
*/
|
|
201
402
|
state() {
|
|
202
403
|
const { repoDir } = this.paths;
|
|
203
404
|
const pool = { ...this.poolState(), poolFetchedAt: this.poolFetchedAt() };
|
|
405
|
+
const own = this.ownership();
|
|
406
|
+
if (own.kind === 'foreign') {
|
|
407
|
+
return { ok: false, reason: own.reason, commit: '', committedAt: '', foreign: true, ...pool };
|
|
408
|
+
}
|
|
204
409
|
if (!exists(path.join(repoDir, '.git'))) {
|
|
205
410
|
return { ok: false, reason: '未下载 work-agent 仓库', commit: '', committedAt: '', ...pool };
|
|
206
411
|
}
|
|
207
412
|
if (!this.hasSkills()) {
|
|
208
413
|
return { ok: false, reason: 'work-agent 仓库不完整(没有 .claude/skills)', commit: '', committedAt: '', ...pool };
|
|
209
414
|
}
|
|
210
|
-
const head = git(['rev-parse', 'HEAD'], { cwd: repoDir, env: this.env
|
|
415
|
+
const head = git(['rev-parse', 'HEAD'], { cwd: repoDir, env: this.env });
|
|
211
416
|
if (!head.ok || !/^[0-9a-f]{40}$/.test(head.stdout)) {
|
|
212
417
|
return { ok: false, reason: 'work-agent 仓库损坏', commit: '', committedAt: '', ...pool };
|
|
213
418
|
}
|
|
214
|
-
const when = git(['log', '-1', '--format=%cI'], { cwd: repoDir, env: this.env
|
|
419
|
+
const when = git(['log', '-1', '--format=%cI'], { cwd: repoDir, env: this.env });
|
|
215
420
|
return { ok: true, reason: '', commit: head.stdout, committedAt: when.ok ? when.stdout : '', ...pool };
|
|
216
421
|
}
|
|
217
422
|
|
|
218
423
|
/** Whether the clone holds a Skill tree to copy. */
|
|
219
424
|
hasSkills() {
|
|
220
|
-
|
|
221
|
-
return fs.readdirSync(this.skillsDir).some((name) => !name.startsWith('.'));
|
|
222
|
-
} catch {
|
|
223
|
-
return false;
|
|
224
|
-
}
|
|
425
|
+
return hasSkillTree(this.paths.repoDir);
|
|
225
426
|
}
|
|
226
427
|
|
|
227
428
|
/** The repositories the pool holds, by name. */
|
|
@@ -300,31 +501,47 @@ export class WorkAgent {
|
|
|
300
501
|
* Makes the clone current: clone when missing or broken, otherwise fetch and
|
|
301
502
|
* fast-forward. A fetch that fails keeps the commit the machine already has.
|
|
302
503
|
* A fast-forward that fails (dirty tree, rewritten upstream) re-clones rather
|
|
303
|
-
* than `reset --hard`, which would silently adopt a force-push.
|
|
304
|
-
*
|
|
305
|
-
*
|
|
504
|
+
* than `reset --hard`, which would silently adopt a force-push. A new clone
|
|
505
|
+
* replaces the old one only once it is complete, so a failed one leaves the
|
|
506
|
+
* machine with what it had. A directory that is not this program's is never
|
|
507
|
+
* touched. Never throws — returns state() with a reason.
|
|
306
508
|
*/
|
|
307
|
-
refresh() {
|
|
308
|
-
return this.
|
|
509
|
+
refresh({ waitMs } = {}) {
|
|
510
|
+
return this.withClone(() => this.refreshNow(), { waitMs });
|
|
309
511
|
}
|
|
310
512
|
|
|
311
|
-
refreshNow() {
|
|
513
|
+
async refreshNow() {
|
|
312
514
|
const { repoDir } = this.paths;
|
|
515
|
+
this.removeLeftovers();
|
|
516
|
+
const own = this.ownership();
|
|
517
|
+
if (own.kind === 'foreign') {
|
|
518
|
+
this.note('warn', own.reason);
|
|
519
|
+
return this.state();
|
|
520
|
+
}
|
|
313
521
|
const before = this.state();
|
|
314
522
|
if (!before.ok) {
|
|
315
|
-
return this.
|
|
523
|
+
return this.reclone(before.reason === '未下载 work-agent 仓库' ? '' : before.reason);
|
|
316
524
|
}
|
|
317
|
-
|
|
525
|
+
if (own.adopt) this.markOwned();
|
|
526
|
+
const fetched = await gitAsync(['fetch', '--no-recurse-submodules', '--prune', 'origin', REPO_BRANCH], {
|
|
527
|
+
cwd: repoDir,
|
|
528
|
+
env: this.env,
|
|
529
|
+
timeout: FETCH_TIMEOUT_MS,
|
|
530
|
+
});
|
|
318
531
|
if (!fetched.ok) {
|
|
319
|
-
this.note('warn', `无法从 ${
|
|
532
|
+
this.note('warn', `无法从 ${this.repoUrl} 拉取更新(${fetched.reason}),继续使用本地的 ${before.commit.slice(0, 7)}`);
|
|
320
533
|
return { ...before, fetchReason: fetched.reason };
|
|
321
534
|
}
|
|
322
|
-
const merged =
|
|
535
|
+
const merged = await gitAsync(['merge', '--ff-only', '--no-recurse-submodules', 'FETCH_HEAD'], {
|
|
536
|
+
cwd: repoDir,
|
|
537
|
+
env: this.env,
|
|
538
|
+
timeout: LOCAL_GIT_TIMEOUT_MS,
|
|
539
|
+
});
|
|
323
540
|
if (!merged.ok) {
|
|
324
541
|
// Dirty tree or rewritten history: re-clone rather than reset --hard, which
|
|
325
542
|
// would silently accept a force-push.
|
|
326
543
|
this.note('warn', `work-agent 仓库无法快进(${merged.reason}),重新克隆`);
|
|
327
|
-
return this.
|
|
544
|
+
return this.reclone(merged.reason);
|
|
328
545
|
}
|
|
329
546
|
const after = this.state();
|
|
330
547
|
if (after.commit && after.commit !== before.commit) {
|
|
@@ -333,35 +550,94 @@ export class WorkAgent {
|
|
|
333
550
|
return after;
|
|
334
551
|
}
|
|
335
552
|
|
|
336
|
-
/**
|
|
337
|
-
|
|
553
|
+
/** Earlier versions of this method's work in progress, next to the clone: .<name>.new-* / .old-*. */
|
|
554
|
+
removeLeftovers() {
|
|
555
|
+
const parent = path.dirname(this.paths.repoDir);
|
|
556
|
+
const name = path.basename(this.paths.repoDir);
|
|
557
|
+
let entries = [];
|
|
558
|
+
try {
|
|
559
|
+
entries = fs.readdirSync(parent);
|
|
560
|
+
} catch {
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
const pattern = new RegExp(`^\\.${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.(new|old)-[A-Za-z0-9]{6}$`);
|
|
564
|
+
for (const entry of entries) if (pattern.test(entry)) removeTree(path.join(parent, entry));
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** The clone that is there stays: its state, with why the new one could not be made. */
|
|
568
|
+
failed(reason) {
|
|
569
|
+
const current = this.state();
|
|
570
|
+
if (current.ok) {
|
|
571
|
+
this.note('warn', `${reason};继续使用本地的 ${current.commit.slice(0, 7)}`);
|
|
572
|
+
return { ...current, fetchReason: reason };
|
|
573
|
+
}
|
|
574
|
+
return { ...current, ok: false, reason };
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* A fresh clone next to the current one (.<name>.new-*), checked, marked,
|
|
579
|
+
* then swapped in with two renames; the old one is deleted afterwards. `why`
|
|
580
|
+
* only appears in the log.
|
|
581
|
+
*/
|
|
582
|
+
async reclone(why = '') {
|
|
338
583
|
const { repoDir } = this.paths;
|
|
339
|
-
|
|
340
|
-
|
|
584
|
+
const parent = path.dirname(repoDir);
|
|
585
|
+
const name = path.basename(repoDir);
|
|
586
|
+
let temp;
|
|
587
|
+
try {
|
|
588
|
+
fs.mkdirSync(parent, { recursive: true, mode: 0o700 });
|
|
589
|
+
temp = fs.mkdtempSync(path.join(parent, `.${name}.new-`));
|
|
590
|
+
} catch (error) {
|
|
591
|
+
return this.failed(`无法在 ${parent} 下准备 work-agent 仓库:${error.message}`);
|
|
592
|
+
}
|
|
341
593
|
this.note('info', `正在下载 work-agent 仓库(${this.repoUrl})${why ? `:${why}` : ''}`);
|
|
342
|
-
const cloned =
|
|
343
|
-
['clone', '--quiet', '--single-branch', '--branch', REPO_BRANCH, '--no-recurse-submodules', this.repoUrl,
|
|
344
|
-
{ env: this.env },
|
|
594
|
+
const cloned = await gitAsync(
|
|
595
|
+
['clone', '--quiet', '--single-branch', '--branch', REPO_BRANCH, '--no-recurse-submodules', this.repoUrl, temp],
|
|
596
|
+
{ env: this.env, timeout: CLONE_TIMEOUT_MS },
|
|
345
597
|
);
|
|
346
598
|
if (!cloned.ok) {
|
|
347
|
-
|
|
348
|
-
return
|
|
599
|
+
removeTree(temp);
|
|
600
|
+
return this.failed(`下载 work-agent 仓库失败:${cloned.reason}`);
|
|
349
601
|
}
|
|
350
602
|
// A rewritten URL (url.<x>.insteadOf) means the code came from somewhere else.
|
|
351
|
-
const origin = git(['remote', 'get-url', 'origin'], { cwd:
|
|
603
|
+
const origin = git(['remote', 'get-url', 'origin'], { cwd: temp, env: this.env });
|
|
352
604
|
if (origin.ok && origin.stdout !== this.repoUrl) {
|
|
353
|
-
|
|
354
|
-
return {
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
605
|
+
removeTree(temp);
|
|
606
|
+
return this.failed(`git 把仓库地址改写成了 ${origin.stdout}(检查 ~/.gitconfig 的 url.*.insteadOf),已删除`);
|
|
607
|
+
}
|
|
608
|
+
if (!hasSkillTree(temp)) {
|
|
609
|
+
removeTree(temp);
|
|
610
|
+
return this.failed('下载的 work-agent 仓库不完整(没有 .claude/skills)');
|
|
611
|
+
}
|
|
612
|
+
this.markOwned(temp);
|
|
613
|
+
let old = '';
|
|
614
|
+
try {
|
|
615
|
+
let present = true;
|
|
616
|
+
try {
|
|
617
|
+
fs.lstatSync(repoDir);
|
|
618
|
+
} catch {
|
|
619
|
+
present = false;
|
|
620
|
+
}
|
|
621
|
+
if (present) {
|
|
622
|
+
old = path.join(parent, `.${name}.old-${crypto.randomBytes(3).toString('hex')}`);
|
|
623
|
+
fs.renameSync(repoDir, old);
|
|
624
|
+
}
|
|
625
|
+
fs.renameSync(temp, repoDir);
|
|
626
|
+
} catch (error) {
|
|
627
|
+
if (old && !exists(repoDir)) {
|
|
628
|
+
try {
|
|
629
|
+
fs.renameSync(old, repoDir);
|
|
630
|
+
old = '';
|
|
631
|
+
} catch {
|
|
632
|
+
// Left for removeLeftovers(); the state below says what is there.
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
removeTree(temp);
|
|
636
|
+
return this.failed(`无法替换 work-agent 仓库:${error.message}`);
|
|
361
637
|
}
|
|
638
|
+
if (old) removeTree(old);
|
|
362
639
|
const state = this.state();
|
|
363
640
|
if (state.ok) this.note('info', `work-agent 仓库就绪:${state.commit.slice(0, 7)}`);
|
|
364
|
-
else fs.rmSync(repoDir, { recursive: true, force: true });
|
|
365
641
|
return state;
|
|
366
642
|
}
|
|
367
643
|
|
|
@@ -371,13 +647,17 @@ export class WorkAgent {
|
|
|
371
647
|
* Skills' `/tmp/work-agent` at `targets`: { logs } (the persistent
|
|
372
648
|
* $WORK_AGENT_HOME/logs) and { scratch } (the job's own scratch directory)
|
|
373
649
|
* — lib/skill-text.mjs rewriteWorkAgentPath. `.git` is left out: the copy is
|
|
374
|
-
* for reading and running, not for pushing
|
|
650
|
+
* for reading and running, not for pushing; so is any symlink that leads out
|
|
651
|
+
* of the repository. Returns the commit that was copied.
|
|
375
652
|
*/
|
|
376
653
|
copyRepoInto(targetDir, targets) {
|
|
377
|
-
return this.
|
|
654
|
+
return this.withClone(() => {
|
|
378
655
|
const state = this.state();
|
|
379
656
|
if (!state.ok) throw new Error(state.reason);
|
|
380
|
-
copyTreeDetached(this.paths.repoDir, targetDir
|
|
657
|
+
copyTreeDetached(this.paths.repoDir, targetDir, {
|
|
658
|
+
boundary: fs.realpathSync(this.paths.repoDir),
|
|
659
|
+
onSkip: (rel, target) => this.note('warn', `work-agent 仓库里的 ${rel} 指向仓库之外(${target}),没有复制给任务`),
|
|
660
|
+
});
|
|
381
661
|
rewriteSkillPaths(path.join(targetDir, SKILLS_SUBDIR), targets);
|
|
382
662
|
return { commit: state.commit };
|
|
383
663
|
});
|
|
@@ -392,10 +672,12 @@ export class WorkAgent {
|
|
|
392
672
|
reject(new Error('程序正在退出'));
|
|
393
673
|
return;
|
|
394
674
|
}
|
|
675
|
+
// Line by line to `say`: the program's log, and the terminal that asked
|
|
676
|
+
// (directly, or through the control interface).
|
|
395
677
|
const child = spawn('python3', ['-I', script, ...args], {
|
|
396
678
|
cwd: this.paths.repoDir,
|
|
397
679
|
detached: true,
|
|
398
|
-
stdio: ['ignore', 'inherit', 'inherit'],
|
|
680
|
+
stdio: say ? ['ignore', 'pipe', 'pipe'] : ['ignore', 'inherit', 'inherit'],
|
|
399
681
|
env: {
|
|
400
682
|
...gitEnv(this.env),
|
|
401
683
|
WORK_AGENT_HOME: this.paths.workAgentHome,
|
|
@@ -406,6 +688,20 @@ export class WorkAgent {
|
|
|
406
688
|
},
|
|
407
689
|
});
|
|
408
690
|
this.child = child;
|
|
691
|
+
if (say) {
|
|
692
|
+
for (const stream of [child.stdout, child.stderr]) {
|
|
693
|
+
let rest = '';
|
|
694
|
+
stream.setEncoding('utf8');
|
|
695
|
+
stream.on('data', (text) => {
|
|
696
|
+
const parts = (rest + text).split(/\r?\n|\r/);
|
|
697
|
+
rest = parts.pop();
|
|
698
|
+
for (const line of parts) if (line.trim()) say(line);
|
|
699
|
+
});
|
|
700
|
+
stream.on('end', () => {
|
|
701
|
+
if (rest.trim()) say(rest);
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
}
|
|
409
705
|
const timer = setTimeout(() => {
|
|
410
706
|
say?.(`已超过 ${Math.round(timeoutMs / 60_000)} 分钟,正在停止`);
|
|
411
707
|
killGroup(child, 'SIGTERM');
|
|
@@ -449,10 +745,11 @@ export class WorkAgent {
|
|
|
449
745
|
* ($WORK_AGENT_HOME/essential-repos.txt, which init creates and the user may
|
|
450
746
|
* edit) into the pool, or the ones `repos` names. Only ever from a terminal:
|
|
451
747
|
* the list is large. `work-agent.py` skips repos that are already there, so
|
|
452
|
-
* this is safe to re-run
|
|
748
|
+
* this is safe to re-run — and it only adds repositories, so jobs keep
|
|
749
|
+
* running meanwhile.
|
|
453
750
|
*/
|
|
454
751
|
initPool({ repos = null, say = () => {}, requireFreeBytes = POOL_FREE_BYTES } = {}) {
|
|
455
|
-
return this.
|
|
752
|
+
return this.withPool(async () => {
|
|
456
753
|
const state = this.state();
|
|
457
754
|
if (!state.ok) throw new Error(state.reason);
|
|
458
755
|
const free = freeBytes(this.paths.poolDir);
|
|
@@ -483,11 +780,12 @@ export class WorkAgent {
|
|
|
483
780
|
* Updates every repository the pool holds — whatever they are, no names
|
|
484
781
|
* involved (`work-agent.py update` pulls each local repo's master and skips
|
|
485
782
|
* anything dirty or not from the CANN organisation). Never clones a new one.
|
|
486
|
-
* Callers
|
|
487
|
-
*
|
|
783
|
+
* Callers start it only when no job is running: from the call on, new jobs
|
|
784
|
+
* wait (waitForPoolIdle) until the pull is over.
|
|
488
785
|
*/
|
|
489
786
|
updatePool({ say = () => {} } = {}) {
|
|
490
|
-
|
|
787
|
+
this.poolUpdates += 1;
|
|
788
|
+
return this.withPool(async () => {
|
|
491
789
|
if (!this.poolState().repos) {
|
|
492
790
|
say('没有知识仓可更新(运行 work-agent-runner setup 可以下载)');
|
|
493
791
|
return this.poolState();
|
|
@@ -495,16 +793,38 @@ export class WorkAgent {
|
|
|
495
793
|
say(`正在更新知识仓:${this.paths.poolDir}`);
|
|
496
794
|
await this.python(['update'], { say });
|
|
497
795
|
return this.poolState();
|
|
796
|
+
}).finally(() => {
|
|
797
|
+
this.poolUpdates -= 1;
|
|
498
798
|
});
|
|
499
799
|
}
|
|
500
800
|
|
|
801
|
+
/**
|
|
802
|
+
* Resolves true once no `git pull` runs in the pool — this process's
|
|
803
|
+
* updatePool() or another process's (state/pool-busy) — so a job never reads
|
|
804
|
+
* files being replaced; false after `timeoutMs` or once `isCancelled()`.
|
|
805
|
+
*/
|
|
806
|
+
async waitForPoolIdle({ timeoutMs = 15 * 60_000, isCancelled = () => false, onWait = () => {}, pollMs = 1000 } = {}) {
|
|
807
|
+
const deadline = Date.now() + timeoutMs;
|
|
808
|
+
let told = false;
|
|
809
|
+
for (;;) {
|
|
810
|
+
if (isCancelled()) return false;
|
|
811
|
+
if (!this.poolUpdating && poolBusyInfo(this.paths)?.kind !== 'update') return true;
|
|
812
|
+
if (Date.now() >= deadline) return false;
|
|
813
|
+
if (!told) {
|
|
814
|
+
told = true;
|
|
815
|
+
onWait();
|
|
816
|
+
}
|
|
817
|
+
await sleep(Math.max(1, Math.min(pollMs, deadline - Date.now())));
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
501
821
|
/**
|
|
502
822
|
* work-agent's own housekeeping: empties `$WORK_AGENT_HOME/tmp` and drops logs
|
|
503
823
|
* older than 30 days. Only safe when no job is running (it deletes all of
|
|
504
824
|
* tmp/), so `start` calls it before it connects.
|
|
505
825
|
*/
|
|
506
826
|
cleanup({ say = () => {} } = {}) {
|
|
507
|
-
return this.
|
|
827
|
+
return this.withPool(async () => {
|
|
508
828
|
if (!this.state().ok) return false;
|
|
509
829
|
await this.python(['cleanup', '--log-days', String(LOG_DAYS)], { say, timeoutMs: 10 * 60_000 });
|
|
510
830
|
return true;
|