@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/lock.mjs
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// Lock files holding their owner's pid: run.lock (one running instance per
|
|
2
|
+
// program home), work-agent.lock (the clone), config.lock (read-modify-write
|
|
3
|
+
// of config.json). A lock whose pid is gone (or now belongs to some other
|
|
4
|
+
// program) is taken over.
|
|
5
|
+
//
|
|
6
|
+
// A lock is created with its content in one step (a temporary file
|
|
7
|
+
// hard-linked into place), so nobody ever reads an empty lock and takes it
|
|
8
|
+
// for a dead one; taking over a dead lock happens under <lock>.takeover, so
|
|
9
|
+
// two processes cannot both take it over.
|
|
3
10
|
|
|
4
11
|
import { spawnSync } from 'node:child_process';
|
|
12
|
+
import crypto from 'node:crypto';
|
|
5
13
|
import fs from 'node:fs';
|
|
6
14
|
|
|
15
|
+
// A takeover directory older than this was left by a process that died taking over.
|
|
16
|
+
const TAKEOVER_STALE_MS = 30_000;
|
|
17
|
+
const NO_HARD_LINKS = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS']);
|
|
18
|
+
|
|
7
19
|
export class LockedError extends Error {
|
|
8
|
-
constructor(pid) {
|
|
9
|
-
super(`已有实例在运行(pid ${pid},可能是后台服务,见 work-agent-runner service status)`);
|
|
20
|
+
constructor(pid, message = '') {
|
|
21
|
+
super(message || `已有实例在运行(pid ${pid},可能是后台服务,见 work-agent-runner service status)`);
|
|
10
22
|
this.pid = pid;
|
|
11
23
|
}
|
|
12
24
|
}
|
|
@@ -47,24 +59,111 @@ export function lockHolder(file) {
|
|
|
47
59
|
}
|
|
48
60
|
}
|
|
49
61
|
|
|
62
|
+
function sleepSync(ms) {
|
|
63
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Creates `file` holding `pid` in one step; false when it already exists. */
|
|
67
|
+
function createLockFile(file, pid) {
|
|
68
|
+
const temp = `${file}.${pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
69
|
+
fs.writeFileSync(temp, String(pid), { mode: 0o600 });
|
|
70
|
+
try {
|
|
71
|
+
fs.linkSync(temp, file);
|
|
72
|
+
return true;
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (error.code === 'EEXIST') return false;
|
|
75
|
+
if (!NO_HARD_LINKS.has(error.code)) throw error;
|
|
76
|
+
// No hard links on this filesystem: exclusive create, then the pid.
|
|
77
|
+
try {
|
|
78
|
+
const fd = fs.openSync(file, 'wx', 0o600);
|
|
79
|
+
try {
|
|
80
|
+
fs.writeSync(fd, String(pid));
|
|
81
|
+
} finally {
|
|
82
|
+
fs.closeSync(fd);
|
|
83
|
+
}
|
|
84
|
+
return true;
|
|
85
|
+
} catch (fallback) {
|
|
86
|
+
if (fallback.code === 'EEXIST') return false;
|
|
87
|
+
throw fallback;
|
|
88
|
+
}
|
|
89
|
+
} finally {
|
|
90
|
+
fs.rmSync(temp, { force: true });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Removes a dead holder's lock; one taker at a time, and only if it is still that holder's. */
|
|
95
|
+
function takeOver(file, deadHolder) {
|
|
96
|
+
const guard = `${file}.takeover`;
|
|
97
|
+
try {
|
|
98
|
+
fs.mkdirSync(guard);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (error.code !== 'EEXIST') throw error;
|
|
101
|
+
try {
|
|
102
|
+
if (Date.now() - fs.statSync(guard).mtimeMs > TAKEOVER_STALE_MS) fs.rmdirSync(guard);
|
|
103
|
+
} catch {
|
|
104
|
+
// Gone already.
|
|
105
|
+
}
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
const holder = lockHolder(file);
|
|
110
|
+
const stillDead = holder === deadHolder || !Number.isInteger(holder) || holder <= 0;
|
|
111
|
+
if (stillDead) fs.rmSync(file, { force: true });
|
|
112
|
+
} finally {
|
|
113
|
+
fs.rmSync(guard, { recursive: true, force: true });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
50
117
|
/** Takes the lock or throws LockedError. Returns { release() }. */
|
|
51
118
|
export function acquireLock(file, { pid = process.pid, isAlive = isRunnerAlive } = {}) {
|
|
52
119
|
const release = () => {
|
|
53
120
|
if (lockHolder(file) === pid) fs.rmSync(file, { force: true });
|
|
54
121
|
};
|
|
55
|
-
for (let attempt = 0; attempt <
|
|
56
|
-
|
|
57
|
-
const fd = fs.openSync(file, 'wx', 0o600);
|
|
58
|
-
fs.writeSync(fd, String(pid));
|
|
59
|
-
fs.closeSync(fd);
|
|
60
|
-
return { release };
|
|
61
|
-
} catch (error) {
|
|
62
|
-
if (error.code !== 'EEXIST') throw error;
|
|
63
|
-
}
|
|
122
|
+
for (let attempt = 0; attempt < 10; attempt += 1) {
|
|
123
|
+
if (createLockFile(file, pid)) return { release };
|
|
64
124
|
const holder = lockHolder(file);
|
|
65
125
|
if (holder === pid) return { release };
|
|
66
126
|
if (Number.isInteger(holder) && holder > 0 && isAlive(holder)) throw new LockedError(holder);
|
|
67
|
-
|
|
127
|
+
takeOver(file, holder); // left behind by a dead process
|
|
128
|
+
if (attempt > 0) sleepSync(20);
|
|
129
|
+
}
|
|
130
|
+
throw new Error(`无法获取锁 ${file}`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** acquireLock, retried for up to `timeoutMs` while someone else holds it. */
|
|
134
|
+
export async function acquireLockWaiting(file, { timeoutMs = 0, pollMs = 1000, onWait = () => {}, ...options } = {}) {
|
|
135
|
+
const deadline = Date.now() + timeoutMs;
|
|
136
|
+
let told = false;
|
|
137
|
+
for (;;) {
|
|
138
|
+
try {
|
|
139
|
+
return acquireLock(file, options);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (!(error instanceof LockedError) || Date.now() >= deadline) throw error;
|
|
142
|
+
if (!told) {
|
|
143
|
+
told = true;
|
|
144
|
+
onWait(error.pid);
|
|
145
|
+
}
|
|
146
|
+
await new Promise((resolve) => setTimeout(resolve, Math.max(1, Math.min(pollMs, deadline - Date.now()))));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Runs `fn` under the lock, waiting (synchronously, briefly) for it; for short critical sections. */
|
|
152
|
+
export function withFileLockSync(file, fn, { timeoutMs = 10_000, ...options } = {}) {
|
|
153
|
+
const deadline = Date.now() + timeoutMs;
|
|
154
|
+
let lock;
|
|
155
|
+
for (;;) {
|
|
156
|
+
try {
|
|
157
|
+
lock = acquireLock(file, options);
|
|
158
|
+
break;
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (!(error instanceof LockedError) || Date.now() >= deadline) throw error;
|
|
161
|
+
sleepSync(50);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
return fn();
|
|
166
|
+
} finally {
|
|
167
|
+
lock.release();
|
|
68
168
|
}
|
|
69
|
-
throw new Error(`无法获取运行锁 ${file}`);
|
|
70
169
|
}
|
package/lib/log.mjs
CHANGED
|
@@ -1,18 +1,106 @@
|
|
|
1
1
|
// Timestamped Chinese log lines on stdout / stderr (systemd puts them in the
|
|
2
|
-
// journal, launchd in ~/Library/Logs)
|
|
3
|
-
//
|
|
2
|
+
// journal, launchd in ~/Library/Logs) and, for the running instance, in
|
|
3
|
+
// <program home>/logs/runner.log (10 MiB × 5, rotated), which `work-agent-runner
|
|
4
|
+
// logs` reads. Never log a token, an API key, GITCODE_CRED or a proxy password:
|
|
5
|
+
// every line goes through redact(), which masks the known shapes and the
|
|
6
|
+
// secrets of the jobs that are running (addSecret / removeSecret).
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
|
|
11
|
+
export const LOG_MAX_BYTES = 10 * 1024 * 1024;
|
|
12
|
+
export const LOG_KEEP = 5; // runner.log and runner.log.1 … .4
|
|
4
13
|
|
|
5
14
|
function stamp(date = new Date()) {
|
|
6
15
|
const pad = (value) => String(value).padStart(2, '0');
|
|
7
16
|
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
8
17
|
}
|
|
9
18
|
|
|
10
|
-
|
|
11
|
-
|
|
19
|
+
const SECRET_SHAPES = [
|
|
20
|
+
[/gcm_[A-Za-z0-9_-]{43}/g, 'gcm_***'],
|
|
21
|
+
[/(\/\/)[^/@\s]*@/g, '$1***@'],
|
|
22
|
+
[/(access_token=)[^&\s"']+/gi, '$1***'],
|
|
23
|
+
[/(authorization:\s*bearer\s+)\S+/gi, '$1***'],
|
|
24
|
+
[/\bsk-[A-Za-z0-9_-]{16,}/g, 'sk-***'],
|
|
25
|
+
];
|
|
26
|
+
const secrets = new Set();
|
|
27
|
+
|
|
28
|
+
/** A value (a job's API key, its GITCODE_CRED) that must never appear in a log line. */
|
|
29
|
+
export function addSecret(value) {
|
|
30
|
+
if (typeof value === 'string' && value.length >= 8) secrets.add(value);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function removeSecret(value) {
|
|
34
|
+
secrets.delete(value);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The text with tokens, keys and credentials masked. */
|
|
38
|
+
export function redact(text) {
|
|
39
|
+
let out = String(text ?? '');
|
|
40
|
+
for (const secret of secrets) out = out.split(secret).join('***');
|
|
41
|
+
for (const [pattern, replacement] of SECRET_SHAPES) out = out.replace(pattern, replacement);
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** runner.log → runner.log.1 → … → runner.log.<keep-1>; the oldest goes. */
|
|
46
|
+
function rotate(file, keep) {
|
|
47
|
+
for (let index = keep - 1; index >= 1; index -= 1) {
|
|
48
|
+
const from = index === 1 ? file : `${file}.${index - 1}`;
|
|
49
|
+
try {
|
|
50
|
+
fs.renameSync(from, `${file}.${index}`);
|
|
51
|
+
} catch {
|
|
52
|
+
// Not there yet.
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function sizeOf(file) {
|
|
58
|
+
try {
|
|
59
|
+
return fs.statSync(file).size;
|
|
60
|
+
} catch {
|
|
61
|
+
return 0;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function createLogger({ out = process.stdout, err = process.stderr, file = '', maxBytes = LOG_MAX_BYTES, keep = LOG_KEEP } = {}) {
|
|
66
|
+
let target = file;
|
|
67
|
+
let size = target ? sizeOf(target) : 0;
|
|
68
|
+
const listeners = new Set();
|
|
69
|
+
const toFile = (line) => {
|
|
70
|
+
if (!target) return;
|
|
71
|
+
try {
|
|
72
|
+
if (size + Buffer.byteLength(line) > maxBytes) {
|
|
73
|
+
rotate(target, keep);
|
|
74
|
+
size = 0;
|
|
75
|
+
}
|
|
76
|
+
fs.appendFileSync(target, line, { mode: 0o600 });
|
|
77
|
+
size += Buffer.byteLength(line);
|
|
78
|
+
} catch {
|
|
79
|
+
// The log file must never stop the program.
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
const write = (stream, level, prefix, message) => {
|
|
83
|
+
const text = redact(message);
|
|
84
|
+
const time = stamp();
|
|
85
|
+
stream.write(`${time} ${prefix}${text}\n`);
|
|
86
|
+
toFile(`${time} ${level.padEnd(5)} ${text}\n`);
|
|
87
|
+
for (const listener of listeners) listener({ time, level, text });
|
|
88
|
+
};
|
|
12
89
|
return {
|
|
13
|
-
info: (message) => write(out, '', message),
|
|
14
|
-
warn: (message) => write(err, '警告:', message),
|
|
15
|
-
error: (message) => write(err, '错误:', message),
|
|
90
|
+
info: (message) => write(out, 'INFO', '', message),
|
|
91
|
+
warn: (message) => write(err, 'WARN', '警告:', message),
|
|
92
|
+
error: (message) => write(err, 'ERROR', '错误:', message),
|
|
93
|
+
/** From now on also into `next` (0600, its directory 0700); '' stops it. */
|
|
94
|
+
setFile(next) {
|
|
95
|
+
target = next || '';
|
|
96
|
+
if (target) fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
97
|
+
size = target ? sizeOf(target) : 0;
|
|
98
|
+
},
|
|
99
|
+
/** Every line as it is written: { time, level, text }. Returns the function that stops it. */
|
|
100
|
+
subscribe(listener) {
|
|
101
|
+
listeners.add(listener);
|
|
102
|
+
return () => listeners.delete(listener);
|
|
103
|
+
},
|
|
16
104
|
};
|
|
17
105
|
}
|
|
18
106
|
|
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
// When the running instance maintains things (docs/design.md 2.3, 7.1):
|
|
2
|
+
//
|
|
3
|
+
// work-agent clone every day at maintenance.repoRefreshAt (08:00) plus up to
|
|
4
|
+
// 10 minutes; a missing or broken clone again after 1, 2,
|
|
5
|
+
// 4 … 30 minutes
|
|
6
|
+
// knowledge pool every day at maintenance.poolUpdateAt (03:00, or 'hourly')
|
|
7
|
+
// plus up to 10 minutes, only while no job runs (then every
|
|
8
|
+
// 15 minutes until it can); a terminal's `update` asks for
|
|
9
|
+
// one (control interface, or state/requests/pool-update)
|
|
10
|
+
// checks every hour: dependencies and the sandbox (recheck())
|
|
11
|
+
// housekeeping every hour: trash/, archive/, what has gone wrong for long
|
|
12
|
+
//
|
|
13
|
+
// One maintenance step at a time (a download of the pool is the exception: it
|
|
14
|
+
// only adds repositories, so it runs beside the rest). Timers are re-armed with
|
|
15
|
+
// setTimeout each time, so a schedule stays on its clock across a change of
|
|
16
|
+
// day length or a sleep. The random offset keeps machines in one time zone
|
|
17
|
+
// from all reaching gitcode.com at the same minute.
|
|
18
|
+
//
|
|
19
|
+
// Only node: built-ins and files in this directory.
|
|
20
|
+
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
|
|
24
|
+
import { retryTrash, removeTree } from './fs-safe.mjs';
|
|
25
|
+
import { clearPoolUpdateRequest, poolBusyInfo, poolUpdateRequested } from './work-agent.mjs';
|
|
26
|
+
|
|
27
|
+
export const CLONE_RETRY_START_MS = 60_000;
|
|
28
|
+
export const CLONE_RETRY_MAX_MS = 30 * 60_000;
|
|
29
|
+
export const POOL_RETRY_MS = 15 * 60_000;
|
|
30
|
+
export const POOL_STALE_DAYS = 3;
|
|
31
|
+
const HOUR_MS = 60 * 60_000;
|
|
32
|
+
const REQUEST_POLL_MS = 30_000;
|
|
33
|
+
const JITTER_MS = 10 * 60_000;
|
|
34
|
+
// archive/ as a whole (docs/design.md 3.16): the oldest go first beyond this.
|
|
35
|
+
export const ARCHIVE_MAX_BYTES = 2 * 1024 ** 3;
|
|
36
|
+
// workAgent.state() runs git; the status is published at every heartbeat and job phase.
|
|
37
|
+
const STATE_CACHE_MS = 60_000;
|
|
38
|
+
|
|
39
|
+
/** The first time after `now` that the clock shows `clock` ('HH:MM', local), plus `jitterMs`. */
|
|
40
|
+
export function nextDailyRun(clock, now = new Date(), jitterMs = 0) {
|
|
41
|
+
const [hours, minutes] = String(clock).split(':').map(Number);
|
|
42
|
+
const next = new Date(now.getTime());
|
|
43
|
+
next.setHours(hours, minutes, 0, 0);
|
|
44
|
+
if (next.getTime() <= now.getTime()) next.setDate(next.getDate() + 1);
|
|
45
|
+
return new Date(next.getTime() + jitterMs);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const iso = (ms) => (ms ? new Date(ms).toISOString() : '');
|
|
49
|
+
|
|
50
|
+
/** Bytes of the regular files under `dir` (symlinks not followed). */
|
|
51
|
+
function treeBytes(dir) {
|
|
52
|
+
let total = 0;
|
|
53
|
+
let entries = [];
|
|
54
|
+
try {
|
|
55
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
56
|
+
} catch {
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
59
|
+
for (const entry of entries) {
|
|
60
|
+
const full = path.join(dir, entry.name);
|
|
61
|
+
if (entry.isDirectory()) total += treeBytes(full);
|
|
62
|
+
else if (entry.isFile()) {
|
|
63
|
+
try {
|
|
64
|
+
total += fs.statSync(full).size;
|
|
65
|
+
} catch {
|
|
66
|
+
// Gone meanwhile.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return total;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export class Maintenance {
|
|
74
|
+
/**
|
|
75
|
+
* `recheck()`: the dependency / sandbox check (updates capabilities);
|
|
76
|
+
* `settings()`: { maintenance: { repoRefreshAt, poolUpdateAt }, limits: { archiveDays } };
|
|
77
|
+
* `onChange()`: the status changed.
|
|
78
|
+
*/
|
|
79
|
+
constructor({
|
|
80
|
+
workAgent,
|
|
81
|
+
jobs,
|
|
82
|
+
log,
|
|
83
|
+
paths,
|
|
84
|
+
workRoot,
|
|
85
|
+
settings,
|
|
86
|
+
recheck,
|
|
87
|
+
onChange = () => {},
|
|
88
|
+
random = Math.random,
|
|
89
|
+
now = () => Date.now(),
|
|
90
|
+
}) {
|
|
91
|
+
this.workAgent = workAgent;
|
|
92
|
+
this.jobs = jobs;
|
|
93
|
+
this.log = log;
|
|
94
|
+
this.paths = paths;
|
|
95
|
+
this.trashDir = path.join(workRoot, 'trash');
|
|
96
|
+
this.archiveDir = path.join(workRoot, 'archive');
|
|
97
|
+
this.settings = settings;
|
|
98
|
+
this.recheck = recheck;
|
|
99
|
+
this.onChange = onChange;
|
|
100
|
+
this.random = random;
|
|
101
|
+
this.now = now;
|
|
102
|
+
this.queue = Promise.resolve();
|
|
103
|
+
this.timers = {};
|
|
104
|
+
this.cloneDelay = CLONE_RETRY_START_MS;
|
|
105
|
+
this.poolRequested = false;
|
|
106
|
+
this.stopped = false;
|
|
107
|
+
this.repo = { result: '', error: '', lastRunAt: '', nextAt: '' };
|
|
108
|
+
this.pool = { result: '', error: '', lastRunAt: '', lastOkAt: 0, nextAt: '', running: false };
|
|
109
|
+
this.checks = { lastRunAt: '' };
|
|
110
|
+
this.trashLeft = 0;
|
|
111
|
+
this.stateCache = null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
start() {
|
|
115
|
+
this.scheduleRepo();
|
|
116
|
+
this.schedulePool();
|
|
117
|
+
this.scheduleCloneRetry();
|
|
118
|
+
this.timers.hourly = setInterval(() => this.hourly(), HOUR_MS);
|
|
119
|
+
this.timers.hourly.unref?.();
|
|
120
|
+
this.timers.requests = setInterval(() => this.takeRequest(), REQUEST_POLL_MS);
|
|
121
|
+
this.timers.requests.unref?.();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
stop() {
|
|
125
|
+
this.stopped = true;
|
|
126
|
+
clearInterval(this.timers.hourly);
|
|
127
|
+
clearInterval(this.timers.requests);
|
|
128
|
+
for (const name of ['repo', 'pool', 'clone', 'poolRetry']) clearTimeout(this.timers[name]);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
changed() {
|
|
132
|
+
try {
|
|
133
|
+
this.onChange();
|
|
134
|
+
} catch {
|
|
135
|
+
// Display only.
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** One maintenance step at a time; failures are reported, never thrown at timers. */
|
|
140
|
+
exclusive(work) {
|
|
141
|
+
const next = this.queue.then(work);
|
|
142
|
+
this.queue = next.then(
|
|
143
|
+
() => {},
|
|
144
|
+
() => {},
|
|
145
|
+
);
|
|
146
|
+
return next;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
jitter() {
|
|
150
|
+
return Math.floor(this.random() * JITTER_MS);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The clone and the pool (workAgent.state()), read at most once a minute unless something changed them. */
|
|
154
|
+
repoState() {
|
|
155
|
+
if (!this.stateCache || this.now() - this.stateCache.at >= STATE_CACHE_MS) {
|
|
156
|
+
this.stateCache = { at: this.now(), value: this.workAgent.state() };
|
|
157
|
+
}
|
|
158
|
+
return this.stateCache.value;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ---- work-agent clone -----------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
scheduleRepo() {
|
|
164
|
+
clearTimeout(this.timers.repo);
|
|
165
|
+
if (this.stopped) return;
|
|
166
|
+
const at = nextDailyRun(this.settings().maintenance.repoRefreshAt, new Date(this.now()), this.jitter());
|
|
167
|
+
this.repo.nextAt = at.toISOString();
|
|
168
|
+
this.timers.repo = setTimeout(() => {
|
|
169
|
+
this.refreshClone({ say: (line) => this.log.info(line) })
|
|
170
|
+
.catch(() => {})
|
|
171
|
+
.finally(() => this.scheduleRepo());
|
|
172
|
+
}, Math.max(0, at.getTime() - this.now()));
|
|
173
|
+
this.timers.repo.unref?.();
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Brings the clone up to date now; a clone that stays unusable is tried again soon. */
|
|
177
|
+
refreshClone({ say = () => {} } = {}) {
|
|
178
|
+
return this.exclusive(async () => {
|
|
179
|
+
const state = await this.workAgent.refresh().catch((error) => ({ ...this.workAgent.state(), ok: false, reason: error.message }));
|
|
180
|
+
this.stateCache = null;
|
|
181
|
+
this.repo.lastRunAt = iso(this.now());
|
|
182
|
+
this.repo.result = state.ok ? 'ok' : 'failed';
|
|
183
|
+
this.repo.error = state.ok ? state.fetchReason || '' : state.reason;
|
|
184
|
+
if (state.ok) say(`✓ work-agent ${state.commit.slice(0, 7)}`);
|
|
185
|
+
else say(`work-agent 仓库不可用:${state.reason}`);
|
|
186
|
+
this.changed();
|
|
187
|
+
this.scheduleCloneRetry(state);
|
|
188
|
+
return state;
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
scheduleCloneRetry(state = this.workAgent.state()) {
|
|
193
|
+
clearTimeout(this.timers.clone);
|
|
194
|
+
if (this.stopped || state.ok || state.foreign) {
|
|
195
|
+
this.cloneDelay = CLONE_RETRY_START_MS;
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const delay = this.cloneDelay;
|
|
199
|
+
this.cloneDelay = Math.min(CLONE_RETRY_MAX_MS, this.cloneDelay * 2);
|
|
200
|
+
this.timers.clone = setTimeout(async () => {
|
|
201
|
+
const fresh = await this.refreshClone({ say: (line) => this.log.info(line) }).catch(() => null);
|
|
202
|
+
if (fresh?.ok) await this.runChecks().catch(() => {});
|
|
203
|
+
else this.log.warn(`work-agent 仓库仍不可用,${Math.round(this.cloneDelay / 60_000)} 分钟后再试`);
|
|
204
|
+
}, delay);
|
|
205
|
+
this.timers.clone.unref?.();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// ---- knowledge pool -------------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
schedulePool() {
|
|
211
|
+
clearTimeout(this.timers.pool);
|
|
212
|
+
if (this.stopped) return;
|
|
213
|
+
const clock = this.settings().maintenance.poolUpdateAt;
|
|
214
|
+
if (clock === 'hourly') {
|
|
215
|
+
this.pool.nextAt = '';
|
|
216
|
+
return; // the hourly tick does it
|
|
217
|
+
}
|
|
218
|
+
const at = nextDailyRun(clock, new Date(this.now()), this.jitter());
|
|
219
|
+
this.pool.nextAt = at.toISOString();
|
|
220
|
+
this.timers.pool = setTimeout(() => {
|
|
221
|
+
this.tryPoolUpdate(at.getTime() + 24 * HOUR_MS);
|
|
222
|
+
this.schedulePool();
|
|
223
|
+
}, Math.max(0, at.getTime() - this.now()));
|
|
224
|
+
this.timers.pool.unref?.();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Updates the pool now if nothing runs; else again every 15 minutes until `until`. */
|
|
228
|
+
tryPoolUpdate(until) {
|
|
229
|
+
clearTimeout(this.timers.poolRetry);
|
|
230
|
+
if (this.stopped || !this.workAgent.mountablePool()) return;
|
|
231
|
+
if (this.busyReason()) {
|
|
232
|
+
if (this.now() + POOL_RETRY_MS < until) {
|
|
233
|
+
this.timers.poolRetry = setTimeout(() => this.tryPoolUpdate(until), POOL_RETRY_MS);
|
|
234
|
+
this.timers.poolRetry.unref?.();
|
|
235
|
+
}
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
this.updatePool({ say: (line) => this.log.info(line) }).catch(() => {});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Why a pull cannot start now ('' = it can): jobs running, or another process at the pool. */
|
|
242
|
+
busyReason() {
|
|
243
|
+
const running = this.jobs.runningIds().length;
|
|
244
|
+
if (running) return `${running} 个任务正在运行`;
|
|
245
|
+
const other = poolBusyInfo(this.paths);
|
|
246
|
+
if (other) return `进程 ${other.pid} 正在${other.kind === 'init' ? '下载' : '更新'}知识仓`;
|
|
247
|
+
return '';
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** A terminal asked: as soon as nothing runs. */
|
|
251
|
+
requestPoolUpdate() {
|
|
252
|
+
this.poolRequested = true;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
takeRequest() {
|
|
256
|
+
if (!this.poolRequested && !poolUpdateRequested(this.paths)) return;
|
|
257
|
+
if (this.busyReason()) return;
|
|
258
|
+
this.poolRequested = false;
|
|
259
|
+
clearPoolUpdateRequest(this.paths);
|
|
260
|
+
this.log.info('按终端里 work-agent-runner update 的请求更新知识仓');
|
|
261
|
+
this.updatePool({ say: (line) => this.log.info(line) }).catch(() => {});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* `git pull` in every repository of the pool, if no job runs (checked here,
|
|
266
|
+
* in the same tick as workAgent.updatePool() makes new jobs wait); else it is
|
|
267
|
+
* queued for when nothing runs: { queued: true, reason }.
|
|
268
|
+
*/
|
|
269
|
+
updatePool({ say = () => {} } = {}) {
|
|
270
|
+
return this.exclusive(async () => {
|
|
271
|
+
if (!this.workAgent.mountablePool()) return { skipped: '没有知识仓' };
|
|
272
|
+
const busy = this.busyReason();
|
|
273
|
+
if (busy) {
|
|
274
|
+
this.poolRequested = true;
|
|
275
|
+
this.changed();
|
|
276
|
+
return { queued: true, reason: busy };
|
|
277
|
+
}
|
|
278
|
+
this.pool.running = true;
|
|
279
|
+
this.changed();
|
|
280
|
+
try {
|
|
281
|
+
await this.workAgent.updatePool({ say });
|
|
282
|
+
this.pool.result = 'ok';
|
|
283
|
+
this.pool.error = '';
|
|
284
|
+
this.pool.lastOkAt = this.now();
|
|
285
|
+
} catch (error) {
|
|
286
|
+
this.pool.result = 'failed';
|
|
287
|
+
this.pool.error = error.message;
|
|
288
|
+
this.log.warn(`知识仓更新失败:${error.message}`);
|
|
289
|
+
} finally {
|
|
290
|
+
this.stateCache = null;
|
|
291
|
+
this.pool.running = false;
|
|
292
|
+
this.pool.lastRunAt = iso(this.now());
|
|
293
|
+
this.changed();
|
|
294
|
+
}
|
|
295
|
+
await this.recheck().catch(() => {});
|
|
296
|
+
return { result: this.pool.result, error: this.pool.error };
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ---- checks and housekeeping -----------------------------------------------------
|
|
301
|
+
|
|
302
|
+
/** The dependency and sandbox check (recheck()); resolves what it returned. */
|
|
303
|
+
runChecks() {
|
|
304
|
+
return this.exclusive(async () => {
|
|
305
|
+
this.stateCache = null;
|
|
306
|
+
const result = await this.recheck();
|
|
307
|
+
this.checks.lastRunAt = iso(this.now());
|
|
308
|
+
this.changed();
|
|
309
|
+
return result;
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async hourly() {
|
|
314
|
+
if (this.stopped) return;
|
|
315
|
+
await this.runChecks().catch((error) => this.log.warn(`定期检查失败:${error.message}`));
|
|
316
|
+
if (this.settings().maintenance.poolUpdateAt === 'hourly') this.tryPoolUpdate(this.now() + HOUR_MS);
|
|
317
|
+
this.housekeeping();
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
housekeeping() {
|
|
321
|
+
this.trashLeft = retryTrash(this.trashDir).length;
|
|
322
|
+
this.pruneArchive();
|
|
323
|
+
this.changed();
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* archive/<runId>/ older than limits.archiveDays (all of it when archiving
|
|
328
|
+
* is off); then the oldest until the rest fits ARCHIVE_MAX_BYTES.
|
|
329
|
+
*/
|
|
330
|
+
pruneArchive({ maxBytes = ARCHIVE_MAX_BYTES } = {}) {
|
|
331
|
+
const days = this.settings().limits.archiveDays;
|
|
332
|
+
let names = [];
|
|
333
|
+
try {
|
|
334
|
+
names = fs.readdirSync(this.archiveDir);
|
|
335
|
+
} catch {
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
const cutoff = this.now() - days * 86_400_000;
|
|
339
|
+
const kept = [];
|
|
340
|
+
for (const name of names) {
|
|
341
|
+
const dir = path.join(this.archiveDir, name);
|
|
342
|
+
let finished = 0;
|
|
343
|
+
try {
|
|
344
|
+
finished = Date.parse(JSON.parse(fs.readFileSync(path.join(dir, 'meta.json'), 'utf8')).finishedAt) || fs.statSync(dir).mtimeMs;
|
|
345
|
+
} catch {
|
|
346
|
+
try {
|
|
347
|
+
finished = fs.statSync(dir).mtimeMs;
|
|
348
|
+
} catch {
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
if (!days || finished < cutoff) removeTree(dir);
|
|
353
|
+
else kept.push({ dir, finished, bytes: treeBytes(dir) });
|
|
354
|
+
}
|
|
355
|
+
let total = kept.reduce((sum, item) => sum + item.bytes, 0);
|
|
356
|
+
for (const item of kept.sort((a, b) => a.finished - b.finished)) {
|
|
357
|
+
if (total <= maxBytes) break;
|
|
358
|
+
removeTree(item.dir);
|
|
359
|
+
total -= item.bytes;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** What has gone wrong and is still wrong: [{ code, message }]. */
|
|
364
|
+
degraded() {
|
|
365
|
+
const problems = [];
|
|
366
|
+
const repo = this.repoState();
|
|
367
|
+
if (!repo.ok) problems.push({ code: 'E5101', message: `work-agent 仓库不可用:${repo.reason}` });
|
|
368
|
+
if (repo.repos > 0) {
|
|
369
|
+
const last = Math.max(this.pool.lastOkAt || 0, repo.poolFetchedAt || 0);
|
|
370
|
+
if (last && this.now() - last > POOL_STALE_DAYS * 86_400_000) {
|
|
371
|
+
problems.push({ code: 'E5202', message: `知识仓已 ${Math.floor((this.now() - last) / 86_400_000)} 天没有更新${this.pool.error ? `(${this.pool.error})` : ''}` });
|
|
372
|
+
} else if (this.pool.result === 'failed') {
|
|
373
|
+
problems.push({ code: 'E5201', message: `知识仓上次更新失败:${this.pool.error}` });
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
if (this.trashLeft) problems.push({ code: 'E5301', message: `${this.trashDir} 里有 ${this.trashLeft} 个目录删不掉` });
|
|
377
|
+
return problems;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
snapshot() {
|
|
381
|
+
const repo = this.repoState();
|
|
382
|
+
return {
|
|
383
|
+
repo: { commit: repo.commit || '', committedAt: repo.committedAt || '', ...this.repo },
|
|
384
|
+
pool: {
|
|
385
|
+
repos: repo.repos || 0,
|
|
386
|
+
updatedAt: iso(repo.poolFetchedAt),
|
|
387
|
+
requested: this.poolRequested || Boolean(poolUpdateRequested(this.paths)),
|
|
388
|
+
...this.pool,
|
|
389
|
+
lastOkAt: iso(this.pool.lastOkAt),
|
|
390
|
+
},
|
|
391
|
+
checks: { ...this.checks },
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
}
|