@online-tools/work-agent-runner 0.0.5-alpha-1 → 0.1.0-alpha-2
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/CHANGELOG.md +65 -0
- package/README.md +289 -116
- package/bin/main.mjs +1948 -436
- package/lib/check.mjs +391 -0
- package/lib/claude-cli.mjs +8 -0
- package/lib/claude-install.mjs +221 -0
- package/lib/config.mjs +48 -4
- package/lib/connection.mjs +87 -4
- package/lib/control.mjs +330 -0
- package/lib/diagnose.mjs +82 -0
- package/lib/doctor.mjs +19 -3
- package/lib/errors.mjs +43 -0
- package/lib/jobs.mjs +428 -91
- package/lib/log.mjs +100 -7
- package/lib/maintenance.mjs +394 -0
- package/lib/sandbox.mjs +55 -6
- package/lib/service.mjs +42 -6
- package/lib/setup-state.mjs +119 -0
- package/lib/setup.mjs +4 -1
- package/lib/state.mjs +145 -0
- package/lib/uninstall.mjs +122 -0
- package/lib/views.mjs +260 -0
- package/lib/work-agent.mjs +27 -6
- package/package.json +2 -2
package/lib/config.mjs
CHANGED
|
@@ -37,10 +37,6 @@ import { isRunEntry, readJsonFile, writeJsonAtomic } from './fs-safe.mjs';
|
|
|
37
37
|
import { withFileLockSync } from './lock.mjs';
|
|
38
38
|
|
|
39
39
|
export const DEFAULT_SERVER = 'https://online-tools.closerouter.site';
|
|
40
|
-
/** The work-agent clone is fast-forwarded every day at this hour (local time). */
|
|
41
|
-
export const REPO_UPDATE_HOUR = 8;
|
|
42
|
-
/** The knowledge pool is updated this often (every repository it holds). */
|
|
43
|
-
export const POOL_UPDATE_MS = 60 * 60_000;
|
|
44
40
|
export const PROGRAM_DIR = '.work-agent-runner';
|
|
45
41
|
/** work-agent's own home, shared with the user's own use of it. */
|
|
46
42
|
export const WORK_AGENT_DIR = '.work-agent';
|
|
@@ -84,6 +80,18 @@ export function configPaths(env = process.env, home = os.homedir()) {
|
|
|
84
80
|
stateDir: path.join(base, 'state'),
|
|
85
81
|
requestsDir: path.join(base, 'state', 'requests'),
|
|
86
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
|
+
// What each `setup` step came to (lib/setup-state.mjs).
|
|
86
|
+
setupFile: path.join(base, 'state', 'setup.json'),
|
|
87
|
+
historyFile: path.join(base, 'state', 'history.jsonl'),
|
|
88
|
+
logsDir: path.join(base, 'logs'),
|
|
89
|
+
logFile: path.join(base, 'logs', 'runner.log'),
|
|
90
|
+
// The local control interface (lib/control.mjs): socket, token, and where
|
|
91
|
+
// the socket really is when this path is too long for one.
|
|
92
|
+
controlDir: path.join(base, 'control'),
|
|
93
|
+
controlTokenFile: path.join(base, 'control', 'token'),
|
|
94
|
+
controlEndpointFile: path.join(base, 'control', 'endpoint'),
|
|
87
95
|
// WORK_AGENT_HOME handed to every job: work-agent's own home, a real
|
|
88
96
|
// directory outside the program's, so the user's own work-agent use sees
|
|
89
97
|
// the same logs, scratch and repository pool.
|
|
@@ -92,6 +100,8 @@ export function configPaths(env = process.env, home = os.homedir()) {
|
|
|
92
100
|
// touches is reachable from one place.
|
|
93
101
|
workAgentLink: path.join(base, WORK_AGENT_DIR),
|
|
94
102
|
nodeDir: path.join(base, 'node'),
|
|
103
|
+
// Claude Code installed by this program (lib/claude-install.mjs): claude/<version>/claude.
|
|
104
|
+
claudeDir: path.join(base, 'claude'),
|
|
95
105
|
runsRoot: base,
|
|
96
106
|
poolDir: path.join(workAgentHome, 'ascend-repos'),
|
|
97
107
|
// Where earlier versions kept things (newest first: adopt the newest).
|
|
@@ -169,11 +179,45 @@ function normalize(raw) {
|
|
|
169
179
|
if (typeof raw.workAgentRepo === 'string' && /^https?:\/\/[^\s]{1,480}$/.test(raw.workAgentRepo)) {
|
|
170
180
|
config.workAgentRepo = raw.workAgentRepo;
|
|
171
181
|
}
|
|
182
|
+
// Where Claude Code is downloaded from (lib/claude-install.mjs): an npm
|
|
183
|
+
// registry mirror, https only; its checksums are compared with npmjs.org's.
|
|
184
|
+
if (typeof raw.mirrors?.npmRegistry === 'string' && /^https:\/\/[^\s]{1,200}$/.test(raw.mirrors.npmRegistry)) {
|
|
185
|
+
config.mirrors = { npmRegistry: raw.mirrors.npmRegistry.replace(/\/+$/, '') };
|
|
186
|
+
}
|
|
172
187
|
// The name sent with /connect: it names this machine when the website registers it.
|
|
173
188
|
if (typeof raw.machineName === 'string' && raw.machineName) config.machineName = raw.machineName.slice(0, 100);
|
|
189
|
+
// How a job sees work-agent's home (docs/design.md 2.6): 'shared' (the user's
|
|
190
|
+
// own, as before) or 'per-run'. A server execution machine always runs per-run.
|
|
191
|
+
if (raw.isolation === 'shared' || raw.isolation === 'per-run') config.isolation = raw.isolation;
|
|
192
|
+
const maintenance = {};
|
|
193
|
+
if (CLOCK.test(raw.maintenance?.repoRefreshAt)) maintenance.repoRefreshAt = raw.maintenance.repoRefreshAt;
|
|
194
|
+
if (CLOCK.test(raw.maintenance?.poolUpdateAt) || raw.maintenance?.poolUpdateAt === 'hourly') maintenance.poolUpdateAt = raw.maintenance.poolUpdateAt;
|
|
195
|
+
if (Object.keys(maintenance).length) config.maintenance = maintenance;
|
|
196
|
+
const limits = {};
|
|
197
|
+
const whole = (value, min, max) => Number.isInteger(value) && value >= min && value <= max;
|
|
198
|
+
if (whole(raw.limits?.minFreeBytes, 0, 2 ** 40)) limits.minFreeBytes = raw.limits.minFreeBytes;
|
|
199
|
+
if (whole(raw.limits?.jobWaitMaxMinutes, 1, 60)) limits.jobWaitMaxMinutes = raw.limits.jobWaitMaxMinutes;
|
|
200
|
+
if (whole(raw.limits?.archiveDays, 0, 30)) limits.archiveDays = raw.limits.archiveDays;
|
|
201
|
+
if (Object.keys(limits).length) config.limits = limits;
|
|
174
202
|
return config;
|
|
175
203
|
}
|
|
176
204
|
|
|
205
|
+
const CLOCK = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
206
|
+
|
|
207
|
+
/** When maintenance runs, unless config.json says otherwise (local time). */
|
|
208
|
+
export const DEFAULT_MAINTENANCE = { repoRefreshAt: '08:00', poolUpdateAt: '03:00' };
|
|
209
|
+
/** Limits, unless config.json says otherwise. */
|
|
210
|
+
export const DEFAULT_LIMITS = { minFreeBytes: 1024 ** 3, jobWaitMaxMinutes: 15, archiveDays: 0 };
|
|
211
|
+
|
|
212
|
+
/** The settings in effect: config.json's, else the defaults. */
|
|
213
|
+
export function effectiveSettings(config) {
|
|
214
|
+
return {
|
|
215
|
+
isolation: config.isolation || 'shared',
|
|
216
|
+
maintenance: { ...DEFAULT_MAINTENANCE, ...(config.maintenance || {}) },
|
|
217
|
+
limits: { ...DEFAULT_LIMITS, ...(config.limits || {}) },
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
177
221
|
/** The saved config (defaults when there is none); throws ConfigError when it is unreadable. */
|
|
178
222
|
export function loadConfig(paths) {
|
|
179
223
|
let text;
|
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';
|
|
@@ -17,6 +19,7 @@ const BACKOFF_MAX_MS = 60_000;
|
|
|
17
19
|
const STABLE_MS = 60_000;
|
|
18
20
|
const REPLACED_WINDOW_MS = 10 * 60_000;
|
|
19
21
|
const REPLACED_LIMIT = 3;
|
|
22
|
+
const MIN_BEAT_GAP_MS = 2000;
|
|
20
23
|
|
|
21
24
|
export const FATAL = {
|
|
22
25
|
tokenDeleted: {
|
|
@@ -73,6 +76,18 @@ function jitter(ms) {
|
|
|
73
76
|
* confirmed whether the owner has confirmed this machine (from the connect reply);
|
|
74
77
|
* the program says so once when that changes
|
|
75
78
|
* heartbeatMs from the connect reply
|
|
79
|
+
* onStatus (optional) { connected, since, lastHeartbeatAt, lastError, confirmed }
|
|
80
|
+
* as they change, for the instance's status
|
|
81
|
+
* onReply (optional) the reply of a /connect made here (re-registration)
|
|
82
|
+
* selfReport (optional) { current(): { state, jobs } } — whether this machine takes
|
|
83
|
+
* jobs and why not, and its jobs' phases, with every heartbeat (0.1.0-alpha-2+)
|
|
84
|
+
* bindBeat (optional) receives beat(): send a heartbeat now (the machine stopped
|
|
85
|
+
* or resumed taking jobs), at most every MIN_BEAT_GAP_MS
|
|
86
|
+
*
|
|
87
|
+
* A heartbeat reply may carry capabilitiesDigest (the SHA-256 of the
|
|
88
|
+
* capabilities the website last received, as JSON): when it is not this
|
|
89
|
+
* program's, the next heartbeat sends them again (a terminal's /connect may
|
|
90
|
+
* have reported another environment's).
|
|
76
91
|
*/
|
|
77
92
|
export async function runConnection({
|
|
78
93
|
client,
|
|
@@ -85,14 +100,27 @@ export async function runConnection({
|
|
|
85
100
|
confirmed = true,
|
|
86
101
|
heartbeatMs = 20_000,
|
|
87
102
|
signal,
|
|
103
|
+
onStatus = () => {},
|
|
104
|
+
onReply = () => {},
|
|
105
|
+
selfReport = null,
|
|
106
|
+
bindBeat = () => {},
|
|
88
107
|
}) {
|
|
89
108
|
const stopper = new AbortController();
|
|
90
109
|
const stop = AbortSignal.any([signal || new AbortController().signal, stopper.signal]);
|
|
91
|
-
|
|
110
|
+
// confirmedAt: when a `confirmed` event arrived — a heartbeat reply computed before it is stale.
|
|
111
|
+
const state = { result: null, heartbeatMs, replaced: [], sentCapabilities: '', warnedOutdated: false, toldLatest: '', confirmed, confirmedAt: 0 };
|
|
92
112
|
|
|
113
|
+
const report = (patch) => {
|
|
114
|
+
try {
|
|
115
|
+
onStatus(patch);
|
|
116
|
+
} catch {
|
|
117
|
+
// Status is for display only.
|
|
118
|
+
}
|
|
119
|
+
};
|
|
93
120
|
const noteConfirmed = (value, name = '') => {
|
|
94
121
|
if (typeof value !== 'boolean' || value === state.confirmed) return;
|
|
95
122
|
state.confirmed = value;
|
|
123
|
+
report({ confirmed: value });
|
|
96
124
|
if (value) log.info(`✓ 网页上已确认这台机器${name ? `「${name}」` : ''},可以接收任务了`);
|
|
97
125
|
else log.warn('这台机器需要在网页上(重新)确认后才会收到任务:在线 Agent → 模型配置 → 执行机器');
|
|
98
126
|
};
|
|
@@ -115,6 +143,11 @@ export async function runConnection({
|
|
|
115
143
|
const reply = await connect();
|
|
116
144
|
if (reply?.heartbeatMs) state.heartbeatMs = reply.heartbeatMs;
|
|
117
145
|
state.sentCapabilities = '';
|
|
146
|
+
try {
|
|
147
|
+
onReply(reply);
|
|
148
|
+
} catch {
|
|
149
|
+
// The caller's business.
|
|
150
|
+
}
|
|
118
151
|
noteConfirmed(reply?.confirmed, reply?.name);
|
|
119
152
|
} catch (failure) {
|
|
120
153
|
const again = fatalFor(failure);
|
|
@@ -136,6 +169,7 @@ export async function runConnection({
|
|
|
136
169
|
jobs.handle(event.job);
|
|
137
170
|
break;
|
|
138
171
|
case 'confirmed':
|
|
172
|
+
state.confirmedAt = Date.now();
|
|
139
173
|
noteConfirmed(true, typeof event.name === 'string' ? event.name.slice(0, 40) : '');
|
|
140
174
|
break;
|
|
141
175
|
case 'cancel':
|
|
@@ -161,11 +195,47 @@ export async function runConnection({
|
|
|
161
195
|
}
|
|
162
196
|
};
|
|
163
197
|
|
|
198
|
+
// The wait between heartbeats, cut short by beat(). A beat asked for while a
|
|
199
|
+
// heartbeat is on its way is sent right after it (pending).
|
|
200
|
+
let wake = null;
|
|
201
|
+
let pending = false;
|
|
202
|
+
let lastBeatAt = 0;
|
|
203
|
+
const untilAllowed = () => Math.max(0, MIN_BEAT_GAP_MS - (Date.now() - lastBeatAt));
|
|
204
|
+
const nap = (ms) =>
|
|
205
|
+
new Promise((resolve) => {
|
|
206
|
+
const done = () => {
|
|
207
|
+
clearTimeout(timer);
|
|
208
|
+
stop.removeEventListener('abort', done);
|
|
209
|
+
wake = null;
|
|
210
|
+
resolve();
|
|
211
|
+
};
|
|
212
|
+
// A pending beat goes as soon as allowed — never later than the regular one.
|
|
213
|
+
const timer = setTimeout(done, pending ? Math.min(ms, untilAllowed()) : ms);
|
|
214
|
+
stop.addEventListener('abort', done, { once: true });
|
|
215
|
+
wake = done;
|
|
216
|
+
});
|
|
217
|
+
bindBeat(() => {
|
|
218
|
+
pending = true;
|
|
219
|
+
if (!wake) return;
|
|
220
|
+
const wait = untilAllowed();
|
|
221
|
+
if (!wait) wake();
|
|
222
|
+
else setTimeout(() => (pending ? wake?.() : null), wait).unref?.();
|
|
223
|
+
});
|
|
224
|
+
|
|
164
225
|
const heartbeats = (async () => {
|
|
165
226
|
while (!stop.aborted) {
|
|
166
|
-
await
|
|
227
|
+
await nap(state.heartbeatMs);
|
|
167
228
|
if (stop.aborted) break;
|
|
229
|
+
pending = false;
|
|
230
|
+
lastBeatAt = Date.now();
|
|
168
231
|
const body = { version, running: jobs.runningIds().slice(0, 200) };
|
|
232
|
+
if (selfReport) {
|
|
233
|
+
try {
|
|
234
|
+
Object.assign(body, selfReport.current());
|
|
235
|
+
} catch (error) {
|
|
236
|
+
log.warn(`读取本机状态失败:${error.message}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
169
239
|
const current = JSON.stringify(capabilities.current());
|
|
170
240
|
if (current !== state.sentCapabilities) body.capabilities = capabilities.current();
|
|
171
241
|
if (system) {
|
|
@@ -178,11 +248,19 @@ export async function runConnection({
|
|
|
178
248
|
try {
|
|
179
249
|
const reply = await client.request('POST', '/heartbeat', body, { signal: stop });
|
|
180
250
|
if (body.capabilities) state.sentCapabilities = current;
|
|
251
|
+
report({ lastHeartbeatAt: new Date().toISOString() });
|
|
252
|
+
// The website holds capabilities this program did not send (a terminal's
|
|
253
|
+
// /connect from another environment): send them again next time.
|
|
254
|
+
if (typeof reply?.capabilitiesDigest === 'string' && reply.capabilitiesDigest) {
|
|
255
|
+
const mine = crypto.createHash('sha256').update(state.sentCapabilities || current).digest('hex');
|
|
256
|
+
if (reply.capabilitiesDigest !== mine) state.sentCapabilities = '';
|
|
257
|
+
}
|
|
181
258
|
for (const runId of Array.isArray(reply?.cancel) ? reply.cancel : []) jobs.cancel(runId);
|
|
182
259
|
// Answers the website has not seen arrive yet (the control channel may
|
|
183
260
|
// have been down); repeats of one already given are dropped.
|
|
184
261
|
for (const item of Array.isArray(reply?.answers) ? reply.answers : []) jobs.answer?.(item?.runId, item?.requestId, item?.answers);
|
|
185
|
-
|
|
262
|
+
// A reply computed before the `confirmed` event that overtook it says nothing new.
|
|
263
|
+
if (!(reply?.confirmed === false && state.confirmedAt >= lastBeatAt)) noteConfirmed(reply?.confirmed);
|
|
186
264
|
if (reply?.outdated && !state.warnedOutdated) {
|
|
187
265
|
state.warnedOutdated = true;
|
|
188
266
|
log.warn(`程序版本 ${version} 已低于网站要求的 ${reply.minVersion},请运行 ${UPDATE_COMMAND} 后重启`);
|
|
@@ -208,12 +286,17 @@ export async function runConnection({
|
|
|
208
286
|
onOpen: () => {
|
|
209
287
|
openedAt = Date.now();
|
|
210
288
|
log.info('控制通道已连接,等待任务');
|
|
289
|
+
report({ connected: true, since: new Date(openedAt).toISOString(), lastError: '' });
|
|
211
290
|
},
|
|
212
291
|
onEvent,
|
|
213
292
|
});
|
|
214
|
-
if (!stop.aborted)
|
|
293
|
+
if (!stop.aborted) {
|
|
294
|
+
log.warn('控制通道已断开,稍后重连');
|
|
295
|
+
report({ connected: false, lastError: '控制通道已断开' });
|
|
296
|
+
}
|
|
215
297
|
} catch (error) {
|
|
216
298
|
if (stop.aborted) break;
|
|
299
|
+
report({ connected: false, lastError: error instanceof ApiError ? error.message : error?.cause?.code || error.message });
|
|
217
300
|
if (error instanceof IdleError) log.warn(`${error.message},重新连接`);
|
|
218
301
|
else if (error instanceof ApiError) {
|
|
219
302
|
await handleError(error);
|
package/lib/control.mjs
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
// The local control interface (docs/design.md 2.1, 3.10, 第 8 章): how a
|
|
2
|
+
// terminal command talks to the running instance of the same program home —
|
|
3
|
+
// `status`, `jobs`, `update`, `setup`'s knowledge pool, `doctor` — instead of
|
|
4
|
+
// writing the same files and repositories from a second process.
|
|
5
|
+
//
|
|
6
|
+
// <program home>/control/runner.sock Unix socket (0600; directory 0700)
|
|
7
|
+
// <program home>/control/token 32 random bytes (hex), new at every start
|
|
8
|
+
// <program home>/control/endpoint where the socket really is, when that
|
|
9
|
+
// path is too long for one (Linux 107,
|
|
10
|
+
// macOS 103 bytes): $XDG_RUNTIME_DIR, a
|
|
11
|
+
// private /tmp directory, or macOS $TMPDIR
|
|
12
|
+
//
|
|
13
|
+
// One JSON message per line:
|
|
14
|
+
// → { v: 1, id, token, method, params }
|
|
15
|
+
// ← { v: 1, id, ok: true, result } | { v: 1, id, ok: false, error: { code, message } }
|
|
16
|
+
// ← { v: 1, id, event, data } progress before the result (long methods)
|
|
17
|
+
//
|
|
18
|
+
// Jobs cannot use it: the sandbox gives their commands no Unix sockets (this
|
|
19
|
+
// program never sets allowUnixSockets), the control directories are on the
|
|
20
|
+
// jobs' deny list, and every request carries the token. Other accounts on the
|
|
21
|
+
// host cannot even reach the directory.
|
|
22
|
+
//
|
|
23
|
+
// Only node: built-ins and files in this directory.
|
|
24
|
+
|
|
25
|
+
import crypto from 'node:crypto';
|
|
26
|
+
import fs from 'node:fs';
|
|
27
|
+
import net from 'node:net';
|
|
28
|
+
import os from 'node:os';
|
|
29
|
+
import path from 'node:path';
|
|
30
|
+
|
|
31
|
+
export const CONTROL_VERSION = 1;
|
|
32
|
+
const MAX_LINE_BYTES = 64 * 1024;
|
|
33
|
+
const MAX_CONNECTIONS = 16;
|
|
34
|
+
const IDLE_MS = 60_000;
|
|
35
|
+
|
|
36
|
+
export class ControlError extends Error {
|
|
37
|
+
constructor(code, message) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.code = code;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** No instance answers for this program home (no socket, nobody listening, no token). */
|
|
44
|
+
export class NotRunningError extends Error {
|
|
45
|
+
constructor() {
|
|
46
|
+
super('程序没有在运行');
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function socketPathMax(platform) {
|
|
51
|
+
return platform === 'darwin' ? 103 : 107;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function realpathOr(value) {
|
|
55
|
+
try {
|
|
56
|
+
return fs.realpathSync(value);
|
|
57
|
+
} catch {
|
|
58
|
+
return path.resolve(value);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A directory only this user can enter (not a symlink). */
|
|
63
|
+
function privateDir(dir, uid) {
|
|
64
|
+
try {
|
|
65
|
+
const stat = fs.lstatSync(dir);
|
|
66
|
+
return stat.isDirectory() && (!Number.isInteger(uid) || stat.uid === uid) && (stat.mode & 0o077) === 0;
|
|
67
|
+
} catch {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Where the socket goes: { dir, socket, fallback }. The program home's
|
|
74
|
+
* control/ when the path fits, else a directory named with a hash of the
|
|
75
|
+
* program home, in $XDG_RUNTIME_DIR, /tmp (Linux) or $TMPDIR (macOS).
|
|
76
|
+
* Throws ControlError E1112 when even that is too long.
|
|
77
|
+
*/
|
|
78
|
+
export function socketLocation(paths, { env = process.env, platform = process.platform, uid = process.getuid?.() } = {}) {
|
|
79
|
+
const max = socketPathMax(platform);
|
|
80
|
+
const primary = path.join(paths.controlDir, 'runner.sock');
|
|
81
|
+
if (Buffer.byteLength(primary) <= max) return { dir: paths.controlDir, socket: primary, fallback: false };
|
|
82
|
+
const hash = crypto.createHash('sha256').update(realpathOr(paths.baseDir)).digest('hex').slice(0, 8);
|
|
83
|
+
let dir;
|
|
84
|
+
if (platform === 'darwin') dir = path.join(env.TMPDIR || os.tmpdir(), `work-agent-runner-${hash}`);
|
|
85
|
+
else if (env.XDG_RUNTIME_DIR && privateDir(env.XDG_RUNTIME_DIR, uid)) dir = path.join(env.XDG_RUNTIME_DIR, `work-agent-runner-${hash}`);
|
|
86
|
+
else dir = path.join('/tmp', `work-agent-runner-${uid ?? 0}-${hash}`);
|
|
87
|
+
const socket = path.join(dir, 'runner.sock');
|
|
88
|
+
if (Buffer.byteLength(socket) > max) {
|
|
89
|
+
throw new ControlError('E1112', `管理接口的 socket 路径太长(${socket}):请把 WORK_AGENT_RUNNER_HOME 设为更短的路径`);
|
|
90
|
+
}
|
|
91
|
+
return { dir, socket, fallback: true };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The directories a job must never reach: control/ and the fallback, if any. */
|
|
95
|
+
export function controlDirectories(paths, options) {
|
|
96
|
+
const dirs = [paths.controlDir];
|
|
97
|
+
try {
|
|
98
|
+
const where = socketLocation(paths, options);
|
|
99
|
+
if (where.fallback) dirs.push(where.dir);
|
|
100
|
+
} catch {
|
|
101
|
+
// No socket possible: nothing more to hide.
|
|
102
|
+
}
|
|
103
|
+
return dirs;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Creates `dir` 0700, or checks that it is this user's, private and not a symlink. */
|
|
107
|
+
function ensurePrivateDir(dir, uid) {
|
|
108
|
+
try {
|
|
109
|
+
fs.mkdirSync(dir, { mode: 0o700 });
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (error.code !== 'EEXIST') throw error;
|
|
112
|
+
}
|
|
113
|
+
if (!privateDir(dir, uid)) {
|
|
114
|
+
throw new ControlError('E1112', `${dir} 不是只属于当前用户的目录,不能放管理接口的 socket`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function writePrivate(file, text) {
|
|
119
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
120
|
+
fs.writeFileSync(temp, text, { mode: 0o600 });
|
|
121
|
+
fs.renameSync(temp, file);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function canConnect(socket) {
|
|
125
|
+
return new Promise((resolve) => {
|
|
126
|
+
const probe = net.connect(socket);
|
|
127
|
+
probe.once('connect', () => {
|
|
128
|
+
probe.destroy();
|
|
129
|
+
resolve(true);
|
|
130
|
+
});
|
|
131
|
+
probe.once('error', () => resolve(false));
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function sameToken(given, token) {
|
|
136
|
+
if (typeof given !== 'string' || given.length !== token.length) return false;
|
|
137
|
+
return crypto.timingSafeEqual(Buffer.from(given), Buffer.from(token));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Starts serving `handlers` ({ [method](params, { send(event, data), signal }) → result }).
|
|
142
|
+
* Resolves { socket, close() }. Throws when another process already answers there.
|
|
143
|
+
* `idleMs`: a connection with no request in progress is closed after this long.
|
|
144
|
+
*/
|
|
145
|
+
export async function startControlServer({
|
|
146
|
+
paths,
|
|
147
|
+
handlers,
|
|
148
|
+
log = null,
|
|
149
|
+
env = process.env,
|
|
150
|
+
platform = process.platform,
|
|
151
|
+
uid = process.getuid?.(),
|
|
152
|
+
idleMs = IDLE_MS,
|
|
153
|
+
}) {
|
|
154
|
+
fs.mkdirSync(paths.controlDir, { recursive: true, mode: 0o700 });
|
|
155
|
+
fs.chmodSync(paths.controlDir, 0o700);
|
|
156
|
+
const where = socketLocation(paths, { env, platform, uid });
|
|
157
|
+
if (where.fallback) ensurePrivateDir(where.dir, uid);
|
|
158
|
+
if (fs.existsSync(where.socket)) {
|
|
159
|
+
if (await canConnect(where.socket)) throw new ControlError('E9002', '另一个进程正在使用这个管理接口');
|
|
160
|
+
fs.rmSync(where.socket, { force: true });
|
|
161
|
+
}
|
|
162
|
+
const token = crypto.randomBytes(32).toString('hex');
|
|
163
|
+
writePrivate(paths.controlTokenFile, `${token}\n`);
|
|
164
|
+
if (where.fallback) writePrivate(paths.controlEndpointFile, `${where.socket}\n`);
|
|
165
|
+
else fs.rmSync(paths.controlEndpointFile, { force: true });
|
|
166
|
+
|
|
167
|
+
const connections = new Set();
|
|
168
|
+
const server = net.createServer((socket) => {
|
|
169
|
+
connections.add(socket);
|
|
170
|
+
socket.on('close', () => connections.delete(socket));
|
|
171
|
+
serveConnection(socket, { token, handlers, log, idleMs });
|
|
172
|
+
});
|
|
173
|
+
server.maxConnections = MAX_CONNECTIONS;
|
|
174
|
+
await new Promise((resolve, reject) => {
|
|
175
|
+
server.once('error', reject);
|
|
176
|
+
server.listen(where.socket, () => {
|
|
177
|
+
server.off('error', reject);
|
|
178
|
+
resolve();
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
fs.chmodSync(where.socket, 0o600);
|
|
182
|
+
server.on('error', (error) => log?.warn(`管理接口出错:${error.message}`));
|
|
183
|
+
return {
|
|
184
|
+
socket: where.socket,
|
|
185
|
+
close: () =>
|
|
186
|
+
new Promise((resolve) => {
|
|
187
|
+
for (const socket of connections) socket.destroy();
|
|
188
|
+
server.close(() => resolve());
|
|
189
|
+
for (const file of [where.socket, paths.controlTokenFile, paths.controlEndpointFile]) fs.rmSync(file, { force: true });
|
|
190
|
+
}),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function serveConnection(socket, { token, handlers, log, idleMs }) {
|
|
195
|
+
let buffer = '';
|
|
196
|
+
let inFlight = 0;
|
|
197
|
+
const controller = new AbortController();
|
|
198
|
+
socket.setEncoding('utf8');
|
|
199
|
+
// Idle between requests only: a download of the pool may be silent for minutes.
|
|
200
|
+
socket.setTimeout(idleMs, () => {
|
|
201
|
+
if (!inFlight) socket.destroy();
|
|
202
|
+
});
|
|
203
|
+
socket.on('close', () => controller.abort());
|
|
204
|
+
socket.on('error', () => {});
|
|
205
|
+
const write = (message) => {
|
|
206
|
+
if (!socket.destroyed) socket.write(`${JSON.stringify({ v: CONTROL_VERSION, ...message })}\n`);
|
|
207
|
+
};
|
|
208
|
+
socket.on('data', (text) => {
|
|
209
|
+
buffer += text;
|
|
210
|
+
if (Buffer.byteLength(buffer) > MAX_LINE_BYTES && !buffer.includes('\n')) {
|
|
211
|
+
write({ id: null, ok: false, error: { code: 'E9003', message: '请求过大' } });
|
|
212
|
+
socket.destroy();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
let index;
|
|
216
|
+
while ((index = buffer.indexOf('\n')) >= 0) {
|
|
217
|
+
const line = buffer.slice(0, index);
|
|
218
|
+
buffer = buffer.slice(index + 1);
|
|
219
|
+
if (line.trim()) handleLine(line);
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
const handleLine = async (line) => {
|
|
223
|
+
let request;
|
|
224
|
+
try {
|
|
225
|
+
request = JSON.parse(line);
|
|
226
|
+
} catch {
|
|
227
|
+
write({ id: null, ok: false, error: { code: 'E9003', message: '请求不是 JSON' } });
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
const id = typeof request?.id === 'string' ? request.id.slice(0, 100) : null;
|
|
231
|
+
if (request?.v !== CONTROL_VERSION) {
|
|
232
|
+
write({ id, ok: false, error: { code: 'E9004', message: '管理接口的版本不一致:请用同一版本的程序' } });
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (!sameToken(request.token, token)) {
|
|
236
|
+
write({ id, ok: false, error: { code: 'E9001', message: '管理接口的令牌不正确' } });
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
const handler = typeof request.method === 'string' && Object.hasOwn(handlers, request.method) ? handlers[request.method] : null;
|
|
240
|
+
if (!handler) {
|
|
241
|
+
write({ id, ok: false, error: { code: 'E9005', message: `不支持的操作:${String(request.method).slice(0, 40)}` } });
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
inFlight += 1;
|
|
245
|
+
try {
|
|
246
|
+
const result = await handler(request.params && typeof request.params === 'object' ? request.params : {}, {
|
|
247
|
+
send: (event, data) => write({ id, event, data }),
|
|
248
|
+
signal: controller.signal,
|
|
249
|
+
});
|
|
250
|
+
write({ id, ok: true, result: result ?? null });
|
|
251
|
+
} catch (error) {
|
|
252
|
+
log?.warn(`管理接口的「${request.method}」失败:${error?.message || error}`);
|
|
253
|
+
const code = typeof error?.code === 'string' && /^E\d{4}$/.test(error.code) ? error.code : 'E9000';
|
|
254
|
+
write({ id, ok: false, error: { code, message: String(error?.message || error) } });
|
|
255
|
+
} finally {
|
|
256
|
+
inFlight -= 1;
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function readText(file) {
|
|
262
|
+
try {
|
|
263
|
+
return fs.readFileSync(file, 'utf8').trim();
|
|
264
|
+
} catch {
|
|
265
|
+
return '';
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Asks the running instance: resolves `result`, calls `onEvent(event, data)`
|
|
271
|
+
* for progress on the way. Rejects NotRunningError when no instance answers,
|
|
272
|
+
* ControlError when it refuses. `timeoutMs`: silence allowed (0 = none, for
|
|
273
|
+
* long methods).
|
|
274
|
+
*/
|
|
275
|
+
export function controlRequest(paths, method, params = {}, { onEvent = () => {}, timeoutMs = 30_000 } = {}) {
|
|
276
|
+
const token = readText(paths.controlTokenFile);
|
|
277
|
+
const socketPath = readText(paths.controlEndpointFile) || path.join(paths.controlDir, 'runner.sock');
|
|
278
|
+
if (!token) return Promise.reject(new NotRunningError());
|
|
279
|
+
return new Promise((resolve, reject) => {
|
|
280
|
+
const id = crypto.randomUUID();
|
|
281
|
+
const socket = net.connect(socketPath);
|
|
282
|
+
let buffer = '';
|
|
283
|
+
let settled = false;
|
|
284
|
+
const settle = (fn, value) => {
|
|
285
|
+
if (settled) return;
|
|
286
|
+
settled = true;
|
|
287
|
+
socket.destroy();
|
|
288
|
+
fn(value);
|
|
289
|
+
};
|
|
290
|
+
socket.setEncoding('utf8');
|
|
291
|
+
if (timeoutMs) socket.setTimeout(timeoutMs, () => settle(reject, new ControlError('E9006', '程序没有响应')));
|
|
292
|
+
socket.once('connect', () => socket.write(`${JSON.stringify({ v: CONTROL_VERSION, id, token, method, params })}\n`));
|
|
293
|
+
socket.on('error', (error) => {
|
|
294
|
+
settle(reject, ['ENOENT', 'ECONNREFUSED', 'ENOTSOCK'].includes(error.code) ? new NotRunningError() : error);
|
|
295
|
+
});
|
|
296
|
+
socket.on('close', () => settle(reject, new ControlError('E9006', '程序中断了连接')));
|
|
297
|
+
socket.on('data', (text) => {
|
|
298
|
+
buffer += text;
|
|
299
|
+
let index;
|
|
300
|
+
while ((index = buffer.indexOf('\n')) >= 0) {
|
|
301
|
+
const line = buffer.slice(0, index);
|
|
302
|
+
buffer = buffer.slice(index + 1);
|
|
303
|
+
let message;
|
|
304
|
+
try {
|
|
305
|
+
message = JSON.parse(line);
|
|
306
|
+
} catch {
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (message.id !== id && message.id !== null) continue;
|
|
310
|
+
if (message.event) {
|
|
311
|
+
try {
|
|
312
|
+
onEvent(message.event, message.data);
|
|
313
|
+
} catch {
|
|
314
|
+
// The caller's display problem, not the request's.
|
|
315
|
+
}
|
|
316
|
+
} else if (message.ok) settle(resolve, message.result);
|
|
317
|
+
else settle(reject, new ControlError(message.error?.code || 'E9000', message.error?.message || '失败'));
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Whether an instance answers for this program home (its pid and version), or null. */
|
|
324
|
+
export async function pingInstance(paths) {
|
|
325
|
+
try {
|
|
326
|
+
return await controlRequest(paths, 'ping', {}, { timeoutMs: 5000 });
|
|
327
|
+
} catch {
|
|
328
|
+
return null;
|
|
329
|
+
}
|
|
330
|
+
}
|
package/lib/diagnose.mjs
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// `work-agent-runner diagnose` (design 9.5): a .tar.gz a person can look
|
|
2
|
+
// through and send to whoever helps them — version, check, status, paths,
|
|
3
|
+
// recent job history, the end of the program log, the latest setup log, the
|
|
4
|
+
// config without its token, the service definition, system details. Every
|
|
5
|
+
// text goes through redact() on the way in; the config's token is removed
|
|
6
|
+
// outright. The archive holds regular files only (a tar writer of its own,
|
|
7
|
+
// gzip from node:zlib).
|
|
8
|
+
//
|
|
9
|
+
// Only node: built-ins and files in this directory.
|
|
10
|
+
|
|
11
|
+
import zlib from 'node:zlib';
|
|
12
|
+
|
|
13
|
+
import { redact } from './log.mjs';
|
|
14
|
+
|
|
15
|
+
const BLOCK = 512;
|
|
16
|
+
|
|
17
|
+
function octal(value, length) {
|
|
18
|
+
return `${value.toString(8).padStart(length - 1, '0')}\0`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** One ustar header for a regular file `name` (≤ 100 bytes) of `size` bytes. */
|
|
22
|
+
function header(name, size, mtime) {
|
|
23
|
+
const block = Buffer.alloc(BLOCK, 0);
|
|
24
|
+
const write = (text, offset, length) => block.write(text, offset, length, 'utf8');
|
|
25
|
+
if (Buffer.byteLength(name) > 100) throw new Error(`文件名过长:${name}`);
|
|
26
|
+
write(name, 0, 100);
|
|
27
|
+
write(octal(0o644, 8), 100, 8); // mode
|
|
28
|
+
write(octal(0, 8), 108, 8); // uid
|
|
29
|
+
write(octal(0, 8), 116, 8); // gid
|
|
30
|
+
write(octal(size, 12), 124, 12);
|
|
31
|
+
write(octal(Math.floor(mtime / 1000), 12), 136, 12);
|
|
32
|
+
write(' ', 148, 8); // checksum: spaces while it is computed
|
|
33
|
+
write('0', 156, 1); // regular file
|
|
34
|
+
write('ustar\0', 257, 6);
|
|
35
|
+
write('00', 263, 2);
|
|
36
|
+
let sum = 0;
|
|
37
|
+
for (const byte of block) sum += byte;
|
|
38
|
+
write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8);
|
|
39
|
+
return block;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A gzip'ed tar of `files` ([{ name, content }], regular files under one directory). */
|
|
43
|
+
export function tarGz(files, { mtime = Date.now() } = {}) {
|
|
44
|
+
const parts = [];
|
|
45
|
+
for (const { name, content } of files) {
|
|
46
|
+
const data = Buffer.isBuffer(content) ? content : Buffer.from(String(content), 'utf8');
|
|
47
|
+
parts.push(header(name, data.length, mtime), data);
|
|
48
|
+
const pad = (BLOCK - (data.length % BLOCK)) % BLOCK;
|
|
49
|
+
if (pad) parts.push(Buffer.alloc(pad, 0));
|
|
50
|
+
}
|
|
51
|
+
parts.push(Buffer.alloc(BLOCK * 2, 0));
|
|
52
|
+
return zlib.gzipSync(Buffer.concat(parts));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The config as it goes into a bundle: no token, every other value kept (and redacted like any text). */
|
|
56
|
+
export function configForBundle(config) {
|
|
57
|
+
const copy = { ...config };
|
|
58
|
+
if (copy.token) copy.token = '(已去掉)';
|
|
59
|
+
return copy;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The last `count` lines of `text`. */
|
|
63
|
+
export function lastLines(text, count) {
|
|
64
|
+
const lines = String(text || '').split('\n');
|
|
65
|
+
if (lines.at(-1) === '') lines.pop();
|
|
66
|
+
return lines.slice(-count).join('\n') + (lines.length ? '\n' : '');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The bundle's files, in order, every text redacted: `entries` is
|
|
71
|
+
* [{ name, content }] (strings or objects, written as JSON). Returns
|
|
72
|
+
* { files, listing } — what the archive holds, for the person to look at.
|
|
73
|
+
*/
|
|
74
|
+
export function bundleFiles(entries, { folder = 'work-agent-runner-diag' } = {}) {
|
|
75
|
+
const files = [];
|
|
76
|
+
for (const { name, content } of entries) {
|
|
77
|
+
if (content === null || content === undefined) continue;
|
|
78
|
+
const text = typeof content === 'string' ? content : `${JSON.stringify(content, null, 2)}\n`;
|
|
79
|
+
files.push({ name: `${folder}/${name}`, content: redact(text) });
|
|
80
|
+
}
|
|
81
|
+
return { files, listing: files.map((file) => `${file.name}(${Buffer.byteLength(file.content)} 字节)`) };
|
|
82
|
+
}
|