@online-tools/work-agent-runner 0.0.5-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/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,16 @@ 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
+ historyFile: path.join(base, 'state', 'history.jsonl'),
86
+ logsDir: path.join(base, 'logs'),
87
+ logFile: path.join(base, 'logs', 'runner.log'),
88
+ // The local control interface (lib/control.mjs): socket, token, and where
89
+ // the socket really is when this path is too long for one.
90
+ controlDir: path.join(base, 'control'),
91
+ controlTokenFile: path.join(base, 'control', 'token'),
92
+ controlEndpointFile: path.join(base, 'control', 'endpoint'),
87
93
  // WORK_AGENT_HOME handed to every job: work-agent's own home, a real
88
94
  // directory outside the program's, so the user's own work-agent use sees
89
95
  // the same logs, scratch and repository pool.
@@ -171,9 +177,38 @@ function normalize(raw) {
171
177
  }
172
178
  // The name sent with /connect: it names this machine when the website registers it.
173
179
  if (typeof raw.machineName === 'string' && raw.machineName) config.machineName = raw.machineName.slice(0, 100);
180
+ // How a job sees work-agent's home (docs/design.md 2.6): 'shared' (the user's
181
+ // own, as before) or 'per-run'. A server execution machine always runs per-run.
182
+ if (raw.isolation === 'shared' || raw.isolation === 'per-run') config.isolation = raw.isolation;
183
+ const maintenance = {};
184
+ if (CLOCK.test(raw.maintenance?.repoRefreshAt)) maintenance.repoRefreshAt = raw.maintenance.repoRefreshAt;
185
+ if (CLOCK.test(raw.maintenance?.poolUpdateAt) || raw.maintenance?.poolUpdateAt === 'hourly') maintenance.poolUpdateAt = raw.maintenance.poolUpdateAt;
186
+ if (Object.keys(maintenance).length) config.maintenance = maintenance;
187
+ const limits = {};
188
+ const whole = (value, min, max) => Number.isInteger(value) && value >= min && value <= max;
189
+ if (whole(raw.limits?.minFreeBytes, 0, 2 ** 40)) limits.minFreeBytes = raw.limits.minFreeBytes;
190
+ if (whole(raw.limits?.jobWaitMaxMinutes, 1, 60)) limits.jobWaitMaxMinutes = raw.limits.jobWaitMaxMinutes;
191
+ if (whole(raw.limits?.archiveDays, 0, 30)) limits.archiveDays = raw.limits.archiveDays;
192
+ if (Object.keys(limits).length) config.limits = limits;
174
193
  return config;
175
194
  }
176
195
 
196
+ const CLOCK = /^([01]\d|2[0-3]):[0-5]\d$/;
197
+
198
+ /** When maintenance runs, unless config.json says otherwise (local time). */
199
+ export const DEFAULT_MAINTENANCE = { repoRefreshAt: '08:00', poolUpdateAt: '03:00' };
200
+ /** Limits, unless config.json says otherwise. */
201
+ export const DEFAULT_LIMITS = { minFreeBytes: 1024 ** 3, jobWaitMaxMinutes: 15, archiveDays: 0 };
202
+
203
+ /** The settings in effect: config.json's, else the defaults. */
204
+ export function effectiveSettings(config) {
205
+ return {
206
+ isolation: config.isolation || 'shared',
207
+ maintenance: { ...DEFAULT_MAINTENANCE, ...(config.maintenance || {}) },
208
+ limits: { ...DEFAULT_LIMITS, ...(config.limits || {}) },
209
+ };
210
+ }
211
+
177
212
  /** The saved config (defaults when there is none); throws ConfigError when it is unreadable. */
178
213
  export function loadConfig(paths) {
179
214
  let text;
@@ -8,6 +8,8 @@
8
8
  // (token deleted, machine blocked, the same config running twice), 0 when
9
9
  // stopped through `signal`.
10
10
 
11
+ import crypto from 'node:crypto';
12
+
11
13
  import { ApiError, IdleError } from './http.mjs';
12
14
 
13
15
  export const UPDATE_COMMAND = 'npm i -g @online-tools/work-agent-runner@latest';
@@ -73,6 +75,14 @@ function jitter(ms) {
73
75
  * confirmed whether the owner has confirmed this machine (from the connect reply);
74
76
  * the program says so once when that changes
75
77
  * heartbeatMs from the connect reply
78
+ * onStatus (optional) { connected, since, lastHeartbeatAt, lastError, confirmed }
79
+ * as they change, for the instance's status
80
+ * onReply (optional) the reply of a /connect made here (re-registration)
81
+ *
82
+ * A heartbeat reply may carry capabilitiesDigest (the SHA-256 of the
83
+ * capabilities the website last received, as JSON): when it is not this
84
+ * program's, the next heartbeat sends them again (a terminal's /connect may
85
+ * have reported another environment's).
76
86
  */
77
87
  export async function runConnection({
78
88
  client,
@@ -85,14 +95,24 @@ export async function runConnection({
85
95
  confirmed = true,
86
96
  heartbeatMs = 20_000,
87
97
  signal,
98
+ onStatus = () => {},
99
+ onReply = () => {},
88
100
  }) {
89
101
  const stopper = new AbortController();
90
102
  const stop = AbortSignal.any([signal || new AbortController().signal, stopper.signal]);
91
103
  const state = { result: null, heartbeatMs, replaced: [], sentCapabilities: '', warnedOutdated: false, toldLatest: '', confirmed };
92
104
 
105
+ const report = (patch) => {
106
+ try {
107
+ onStatus(patch);
108
+ } catch {
109
+ // Status is for display only.
110
+ }
111
+ };
93
112
  const noteConfirmed = (value, name = '') => {
94
113
  if (typeof value !== 'boolean' || value === state.confirmed) return;
95
114
  state.confirmed = value;
115
+ report({ confirmed: value });
96
116
  if (value) log.info(`✓ 网页上已确认这台机器${name ? `「${name}」` : ''},可以接收任务了`);
97
117
  else log.warn('这台机器需要在网页上(重新)确认后才会收到任务:在线 Agent → 模型配置 → 执行机器');
98
118
  };
@@ -115,6 +135,11 @@ export async function runConnection({
115
135
  const reply = await connect();
116
136
  if (reply?.heartbeatMs) state.heartbeatMs = reply.heartbeatMs;
117
137
  state.sentCapabilities = '';
138
+ try {
139
+ onReply(reply);
140
+ } catch {
141
+ // The caller's business.
142
+ }
118
143
  noteConfirmed(reply?.confirmed, reply?.name);
119
144
  } catch (failure) {
120
145
  const again = fatalFor(failure);
@@ -178,6 +203,13 @@ export async function runConnection({
178
203
  try {
179
204
  const reply = await client.request('POST', '/heartbeat', body, { signal: stop });
180
205
  if (body.capabilities) state.sentCapabilities = current;
206
+ report({ lastHeartbeatAt: new Date().toISOString() });
207
+ // The website holds capabilities this program did not send (a terminal's
208
+ // /connect from another environment): send them again next time.
209
+ if (typeof reply?.capabilitiesDigest === 'string' && reply.capabilitiesDigest) {
210
+ const mine = crypto.createHash('sha256').update(state.sentCapabilities || current).digest('hex');
211
+ if (reply.capabilitiesDigest !== mine) state.sentCapabilities = '';
212
+ }
181
213
  for (const runId of Array.isArray(reply?.cancel) ? reply.cancel : []) jobs.cancel(runId);
182
214
  // Answers the website has not seen arrive yet (the control channel may
183
215
  // have been down); repeats of one already given are dropped.
@@ -208,12 +240,17 @@ export async function runConnection({
208
240
  onOpen: () => {
209
241
  openedAt = Date.now();
210
242
  log.info('控制通道已连接,等待任务');
243
+ report({ connected: true, since: new Date(openedAt).toISOString(), lastError: '' });
211
244
  },
212
245
  onEvent,
213
246
  });
214
- if (!stop.aborted) log.warn('控制通道已断开,稍后重连');
247
+ if (!stop.aborted) {
248
+ log.warn('控制通道已断开,稍后重连');
249
+ report({ connected: false, lastError: '控制通道已断开' });
250
+ }
215
251
  } catch (error) {
216
252
  if (stop.aborted) break;
253
+ report({ connected: false, lastError: error instanceof ApiError ? error.message : error?.cause?.code || error.message });
217
254
  if (error instanceof IdleError) log.warn(`${error.message},重新连接`);
218
255
  else if (error instanceof ApiError) {
219
256
  await handleError(error);
@@ -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/errors.mjs ADDED
@@ -0,0 +1,34 @@
1
+ // Error codes (docs/design.md 附录 B) the program writes into its job history,
2
+ // its status and the messages it sends: one code per kind of failure, so a
3
+ // report can be matched to its explanation. Only what the program reports so
4
+ // far; the catalog grows with it.
5
+
6
+ export const ERROR_CODES = {
7
+ E1112: '本机管理接口无法启动(socket 路径太长或目录不安全)',
8
+ E1301: 'Claude Code 未安装或无法运行',
9
+ E3101: '任务参数不合法',
10
+ E3201: '等待执行条件超时',
11
+ E3301: '工作目录磁盘空间不足',
12
+ E3401: '准备任务失败',
13
+ E3501: '输出无法送达网站',
14
+ E4101: '沙箱不可用',
15
+ E5101: 'work-agent 仓库刷新失败',
16
+ E5201: '知识仓更新失败',
17
+ E5202: '知识仓长时间未能更新',
18
+ E5301: '清理失败(已移入回收站)',
19
+ E9000: '本机管理接口:操作失败',
20
+ E9001: '本机管理接口:令牌不正确',
21
+ E9002: '本机管理接口:已被另一个进程占用',
22
+ E9003: '本机管理接口:请求格式不正确',
23
+ E9004: '本机管理接口:两端版本不一致',
24
+ E9005: '本机管理接口:不支持的操作',
25
+ E9006: '本机管理接口:程序没有响应',
26
+ E9007: '仓名不正确',
27
+ E9008: '知识仓正被另一个进程下载或更新',
28
+ E9009: '任务 ID 对应多个任务',
29
+ };
30
+
31
+ /** "message(E3201)": the code goes last, so the sentence still reads first. */
32
+ export function withCode(code, message) {
33
+ return code ? `${message}(${code})` : message;
34
+ }