@online-tools/work-agent-runner 0.0.3-alpha-1 → 0.0.5-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/jobs.mjs CHANGED
@@ -19,6 +19,7 @@ import path from 'node:path';
19
19
  import { StringDecoder } from 'node:string_decoder';
20
20
 
21
21
  import { claudeArgs, claudeEnv } from './claude-cli.mjs';
22
+ import { removeTree } from './fs-safe.mjs';
22
23
  import { ApiError } from './http.mjs';
23
24
  import { createClaudeInteraction } from './interaction.mjs';
24
25
  import {
@@ -42,6 +43,9 @@ const RUN_ID = /^(skill|review)_\d+_[0-9a-f]{8}$/;
42
43
  const TASK_MAX_BYTES = 64 * 1024;
43
44
  const KILL_GRACE_MS = 5000;
44
45
  const CLOSE_WAIT_MS = 2000;
46
+ // How long an accepted job waits for a knowledge-pool update to finish before
47
+ // it starts (its own timeout only starts with claude).
48
+ export const JOB_WAIT_MS = 15 * 60_000;
45
49
 
46
50
  const BATCH_DELAY_MS = 200;
47
51
  const BATCH_BYTES = 64 * 1024;
@@ -259,11 +263,25 @@ function killGroup(pid, signal) {
259
263
  * everything).
260
264
  */
261
265
  export class JobManager {
262
- constructor({ client, workAgent, workRoot, claudePath, realHome, env = process.env, platform = process.platform, log, onFatal = () => {} }) {
266
+ constructor({
267
+ client,
268
+ workAgent,
269
+ workRoot,
270
+ claudePath,
271
+ realHome,
272
+ env = process.env,
273
+ platform = process.platform,
274
+ log,
275
+ onFatal = () => {},
276
+ jobWaitMs = JOB_WAIT_MS,
277
+ }) {
263
278
  this.client = client;
264
279
  this.workAgent = workAgent;
265
280
  this.paths = workAgent?.paths || null;
266
281
  this.runsDir = path.join(workRoot, 'runs');
282
+ // Same filesystem as runs/: a run directory that cannot be deleted is renamed here.
283
+ this.trashDir = path.join(workRoot, 'trash');
284
+ this.jobWaitMs = jobWaitMs;
267
285
  this.claudePath = claudePath;
268
286
  this.realHome = realHome;
269
287
  this.env = env;
@@ -393,6 +411,21 @@ export class JobManager {
393
411
  const label = FEATURE_LABELS[job.feature];
394
412
  this.log.info(`开始任务 ${runId}(${label})`);
395
413
 
414
+ // A `git pull` in the knowledge pool must not replace files under a running
415
+ // job: wait for it (bounded) before anything starts.
416
+ if (typeof this.workAgent?.waitForPoolIdle === 'function') {
417
+ const idle = await this.workAgent.waitForPoolIdle({
418
+ timeoutMs: this.jobWaitMs,
419
+ isCancelled: () => entry.cancelled,
420
+ onWait: () => this.log.info(`任务 ${runId} 等待知识仓更新完成后开始`),
421
+ });
422
+ if (!idle && !entry.cancelled) {
423
+ this.log.warn(`任务 ${runId} 等待知识仓更新超时,未执行`);
424
+ await this.reportExit(entry, { error: `执行机器正在更新知识仓,等待超过 ${Math.round(this.jobWaitMs / 60_000)} 分钟,任务未执行,请稍后重试` });
425
+ return;
426
+ }
427
+ }
428
+
396
429
  if (entry.cancelled) {
397
430
  await this.reportExit(entry, { signal: 'SIGTERM' });
398
431
  return;
@@ -407,20 +440,21 @@ export class JobManager {
407
440
  const tooLong = socketPathProblem(layout.tmpDir, this.platform);
408
441
  if (tooLong) throw new Error(tooLong);
409
442
  } catch (error) {
410
- if (runDir) fs.rmSync(runDir, { recursive: true, force: true });
443
+ if (runDir) this.removeRunDir(runDir);
411
444
  await this.reportExit(entry, { error: `准备运行目录失败:${error?.message || error}` });
412
445
  return;
413
446
  }
414
447
 
415
- // A copy of this machine's work-agent clone as the working directory, and
416
- // the knowledge pool read-only if there is one.
448
+ // A copy of this machine's work-agent clone as the working directory (the
449
+ // Skills' logs pointed at $WORK_AGENT_HOME/logs, their scratch at the run's
450
+ // own), and the knowledge pool read-only if there is one: the settings name
451
+ // every path the job may reach (sandbox.mjs).
417
452
  try {
418
- const { commit } = await this.workAgent.copyRepoInto(layout.workDir, this.paths.workAgentHome);
453
+ const { commit } = await this.workAgent.copyRepoInto(layout.workDir, {
454
+ logs: path.join(this.paths.workAgentHome, 'logs'),
455
+ scratch: layout.scratchDir,
456
+ });
419
457
  const pool = this.workAgent.mountablePool();
420
- // Claude Code limits its file tools to the working directory and whatever
421
- // --add-dir names; the pool is outside it (the sandbox still decides what
422
- // may be written).
423
- entry.addDirs = pool ? [this.paths.workAgentHome] : [];
424
458
  writeSandboxSettings(layout.settingsFile, {
425
459
  workDir: fs.realpathSync(layout.workDir),
426
460
  realHome: this.realHome,
@@ -434,7 +468,7 @@ export class JobManager {
434
468
  });
435
469
  this.log.info(`任务 ${runId} 使用 work-agent ${commit.slice(0, 7)}${pool ? ',已挂载知识仓' : ''}`);
436
470
  } catch (error) {
437
- fs.rmSync(runDir, { recursive: true, force: true });
471
+ this.removeRunDir(runDir);
438
472
  await this.reportExit(entry, { error: `准备 Skill 失败:${error?.message || error}` });
439
473
  return;
440
474
  }
@@ -454,10 +488,23 @@ export class JobManager {
454
488
  const outcome = entry.timedOut ? '超时' : entry.cancelled ? '已取消' : result.error ? result.error : `退出码 ${result.code ?? result.signal}`;
455
489
  this.log.info(`任务 ${runId} 结束(${label}):${outcome},用时 ${seconds} 秒`);
456
490
  } finally {
457
- fs.rmSync(runDir, { recursive: true, force: true });
491
+ this.removeRunDir(runDir);
458
492
  }
459
493
  }
460
494
 
495
+ /**
496
+ * Deletes a run directory; never throws. What a job made undeletable (a
497
+ * read-only directory) goes to trash/, retried at the next start and every
498
+ * hour — it must never stop the program.
499
+ */
500
+ removeRunDir(runDir) {
501
+ const outcome = removeTree(runDir, { trashDir: this.trashDir });
502
+ if (outcome.removed) return;
503
+ const why = outcome.error?.code || outcome.error?.message || String(outcome.error);
504
+ if (outcome.trashed) this.log.warn(`运行目录 ${runDir} 删不掉(${why}),已移到 ${outcome.trashed},稍后再试`);
505
+ else this.log.warn(`运行目录 ${runDir} 删不掉(${why}),下次启动时再试`);
506
+ }
507
+
461
508
  spawnClaude(entry, layout) {
462
509
  const { job } = entry;
463
510
  return new Promise((resolve) => {
@@ -469,7 +516,7 @@ export class JobManager {
469
516
  const interactive = job.interactive === true;
470
517
  let child;
471
518
  try {
472
- child = spawn(this.claudePath, claudeArgs({ settingsFile: layout.settingsFile, addDirs: entry.addDirs || [], interactive }), {
519
+ child = spawn(this.claudePath, claudeArgs({ settingsFile: layout.settingsFile, interactive }), {
473
520
  cwd: layout.workDir,
474
521
  detached: true,
475
522
  stdio: ['pipe', 'pipe', 'pipe'],
package/lib/lock.mjs CHANGED
@@ -1,12 +1,24 @@
1
- // One running instance per user: run.lock holds the owner's pid. A lock
2
- // whose pid is gone (or now belongs to some other program) is taken over.
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 < 5; attempt += 1) {
56
- try {
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
- fs.rmSync(file, { force: true }); // left behind by a dead instance
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/sandbox.mjs CHANGED
@@ -12,14 +12,29 @@
12
12
  // `~/.work-agent/...` and $WORK_AGENT_HOME are the
13
13
  // same directory (linkWorkAgentHome)
14
14
  // <runDir>/.tmp/ TMPDIR (the sandbox's bridge sockets live here)
15
+ // <runDir>/.tmp/work-agent the Skills' `/tmp/work-agent` scratch (clones,
16
+ // intermediate files); their logs go to
17
+ // $WORK_AGENT_HOME/logs (skill-text.mjs)
15
18
  //
16
- // Jobs now run inside the program's home (~/.work-agent-runner), so the
17
- // sandbox is told exactly which subtrees to open instead of being kept out of
18
- // the home directory wholesale: the four writable directories above, the
19
- // persistent WORK_AGENT_HOME, and the knowledge pool read-only. Everything
20
- // else in the home directory stays closed, and the paths that must never be
21
- // read by a job (the real clone, config.json with the token) are named in
22
- // permissions.deny as well.
19
+ // Jobs run inside the program's home (~/.work-agent-runner). Two layers
20
+ // decide what a job reaches, one per kind of tool:
21
+ // - Bash commands run in the operating system sandbox: writable are exactly
22
+ // the four directories above and $WORK_AGENT_HOME/{logs,tmp,docs}
23
+ // (filesystem.allowWrite). Reading is NOT confined to them:
24
+ // filesystem.allowRead only re-opens paths inside a denyRead region, and
25
+ // none is set — closing the home for reads would also hide toolchains
26
+ // installed there (pyenv, nvm, conda) and has to be tried on real machines
27
+ // first. Bash reads are closed only for the deny list below.
28
+ // - claude's own file tools (Read, Glob, Grep, Edit, Write) run outside that
29
+ // sandbox. They are not pre-allowed (claude-cli.mjs), so they reach the
30
+ // working directory and exactly the paths in permissions.allow (toolRead /
31
+ // toolWrite from runAllowances); any other path is a permission prompt,
32
+ // which a silent job refuses and lib/interaction.mjs denies. claude checks
33
+ // a symlink's target as well as the link (verified with 2.1.322), so a
34
+ // link in a writable directory does not widen this.
35
+ // permissions.deny beats any allow, for both kinds (claude passes Read / Edit
36
+ // denies on to the sandbox): credentials in the home, the token, the real
37
+ // clone, writes to the pool and to this run's Skill copy.
23
38
  //
24
39
  // Paths are real paths: claude's HOME is the run's, so `~` cannot be used,
25
40
  // and on macOS /var is a symlink to /private/var.
@@ -36,9 +51,8 @@ function fromRoot(absolute) {
36
51
  }
37
52
 
38
53
  // Directories in the home that a job must never read, whatever else it may
39
- // reach: credentials, keys and shell history. The operating system sandbox is
40
- // the real boundary (nothing is readable unless it is in allowRead); this list
41
- // is the second one, at the tool layer, where deny beats any allow.
54
+ // reach: credentials, keys and shell history. A deny beats any allow, and
55
+ // claude passes these on to the sandbox, so Bash cannot read them either.
42
56
  export const SENSITIVE_HOME_PATHS = [
43
57
  '.ssh',
44
58
  '.gnupg',
@@ -58,12 +72,12 @@ export const SENSITIVE_HOME_PATHS = [
58
72
  ];
59
73
 
60
74
  /**
61
- * The settings object. `readAllow` / `writeAllow` are real paths (see
62
- * runAllowances); `deny` keeps the Read and Edit tools away from credentials,
63
- * from the program's own files (the token, the real clone) and from the Skill
64
- * copy of this run.
75
+ * The settings object. `readAllow` / `writeAllow` (the sandbox, for Bash) and
76
+ * `toolRead` / `toolWrite` (the file tools) are real paths, see
77
+ * runAllowances; `deny` keeps both away from credentials, from the program's
78
+ * own files (the token, the real clone) and from the Skill copy of this run.
65
79
  */
66
- export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow = [], deny = [] }) {
80
+ export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow = [], deny = [], toolRead = [], toolWrite = [] }) {
67
81
  return {
68
82
  sandbox: {
69
83
  enabled: true,
@@ -76,6 +90,11 @@ export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow
76
90
  credentials: { envVars: [{ name: 'ANTHROPIC_AUTH_TOKEN', mode: 'deny' }] },
77
91
  },
78
92
  permissions: {
93
+ // Where the file tools may go besides the working directory: nowhere else.
94
+ allow: [
95
+ ...toolRead.map((dir) => `Read(//${fromRoot(dir)}/**)`),
96
+ ...toolWrite.map((dir) => `Edit(//${fromRoot(dir)}/**)`),
97
+ ],
79
98
  deny: [
80
99
  ...SENSITIVE_HOME_PATHS.flatMap((name) => [
81
100
  `Read(//${fromRoot(realHome)}/${name})`,
@@ -93,11 +112,19 @@ export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow
93
112
  }
94
113
 
95
114
  /**
96
- * What one job may read and write: the four directories of its run, the
97
- * program's persistent WORK_AGENT_HOME (the Skills' logs, scratch and
98
- * deliverables), the knowledge pool read-only, and — inside the home directory
99
- * — the PATH entries and CA bundles a command needs to run at all. Also the
100
- * `deny` entries for the program's own files. All as real paths.
115
+ * What one job may read and write, all as real paths:
116
+ * writeAllow / readAllow the sandbox (Bash): the four directories of its
117
+ * run, $WORK_AGENT_HOME/{logs,tmp,docs}; read also
118
+ * all of $WORK_AGENT_HOME, the knowledge pool and —
119
+ * inside the home — the PATH entries and CA bundles
120
+ * a command needs (they only matter inside a
121
+ * denyRead region, see the top of this file)
122
+ * toolWrite / toolRead the file tools: the working directory, HOME and
123
+ * TMPDIR of the run (scratch included) and
124
+ * $WORK_AGENT_HOME/{logs,tmp,docs}; read also all of
125
+ * $WORK_AGENT_HOME and the pool. Not claude-home:
126
+ * claude's own state is none of the model's business.
127
+ * deny the program's own files and pool writes.
101
128
  */
102
129
  export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], pool = '', paths = null }) {
103
130
  const runDirs = [layout.workDir, layout.homeDir, layout.tmpDir, layout.configDir].map((dir) => realpathOr(dir));
@@ -115,17 +142,35 @@ export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], po
115
142
  ...(pool ? [realpathOr(pool)] : []),
116
143
  ...homeReadAllow({ realHome, pathEnv, caPaths }),
117
144
  ];
145
+ const toolWrite = [
146
+ ...[layout.workDir, layout.homeDir, layout.tmpDir].map((dir) => realpathOr(dir)),
147
+ ...(workAgentHome ? ['logs', 'tmp', 'docs'].map((name) => path.join(workAgentHome, name)) : []),
148
+ ];
149
+ const toolRead = [
150
+ ...toolWrite,
151
+ ...(workAgentHome ? [workAgentHome] : []),
152
+ ...(pool ? [realpathOr(pool)] : []),
153
+ ];
118
154
  const deny = [];
119
155
  if (paths) {
120
- // The access token, and the clone every job copies from.
156
+ // The access token, and the clone every job copies from: by the path the
157
+ // program uses and by the real one, so a home behind a symlink (/home ->
158
+ // /data/home) cannot open them by the other name.
121
159
  for (const file of [paths.configFile, paths.repoDir]) {
122
- deny.push(`Read(//${fromRoot(path.resolve(file))}/**)`, `Read(//${fromRoot(path.resolve(file))})`);
123
- deny.push(`Edit(//${fromRoot(path.resolve(file))}/**)`, `Edit(//${fromRoot(path.resolve(file))})`);
160
+ for (const at of new Set([path.resolve(file), realpathOr(file)])) {
161
+ deny.push(`Read(//${fromRoot(at)}/**)`, `Read(//${fromRoot(at)})`, `Edit(//${fromRoot(at)}/**)`, `Edit(//${fromRoot(at)})`);
162
+ }
124
163
  }
125
164
  }
126
165
  // The pool is shared with the user's own work-agent: read it, never write it.
127
166
  if (pool) deny.push(`Edit(//${fromRoot(realpathOr(pool))}/**)`);
128
- return { readAllow: [...new Set(readAllow)], writeAllow: [...new Set(writeAllow)], deny };
167
+ return {
168
+ readAllow: [...new Set(readAllow)],
169
+ writeAllow: [...new Set(writeAllow)],
170
+ toolRead: [...new Set(toolRead)],
171
+ toolWrite: [...new Set(toolWrite)],
172
+ deny,
173
+ };
129
174
  }
130
175
 
131
176
  function realpathOr(value) {
@@ -144,8 +189,9 @@ export function writeSandboxSettings(file, input) {
144
189
  * Directories / files inside HOME that sandboxed commands still need to read:
145
190
  * PATH entries (e.g. ~/.local/bin, nvm), CA bundles passed through, and
146
191
  * `extra` (the knowledge pool, which lives in ~/.work-agent by default).
147
- * Returns their real paths. Entries outside HOME are dropped — they need no
148
- * exception, since the sandbox only closes HOME.
192
+ * Returns their real paths, only those inside HOME: a denyRead on the home
193
+ * (not set yet, see the top of this file) would have to give exactly these
194
+ * back; everything outside it is readable anyway.
149
195
  */
150
196
  export function homeReadAllow({ realHome, pathEnv = '', caPaths = [], extra = [] }) {
151
197
  const allowed = new Set();
@@ -207,7 +253,9 @@ export function createRunLayout(runDir, { workAgentHome = '' } = {}) {
207
253
  workAgentHome,
208
254
  };
209
255
  layout.skillsDir = path.join(layout.workDir, '.claude', 'skills');
210
- for (const dir of [layout.configDir, layout.workDir, layout.homeDir, layout.tmpDir]) {
256
+ // The Skills' `/tmp/work-agent` (clones, intermediate files): deleted with the run.
257
+ layout.scratchDir = path.join(layout.tmpDir, 'work-agent');
258
+ for (const dir of [layout.configDir, layout.workDir, layout.homeDir, layout.tmpDir, layout.scratchDir]) {
211
259
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
212
260
  }
213
261
  if (workAgentHome) {
package/lib/service.mjs CHANGED
@@ -1,13 +1,17 @@
1
1
  // Background service: a systemd user unit (Linux) or a launchd agent (macOS).
2
- // Services do not inherit the shell environment, so PATH and the
3
- // pass-through variables (proxies, CA bundles, language) present now are
4
- // written into the definition (file mode 0600: proxy URLs may hold passwords).
2
+ // Services do not inherit the shell environment, so PATH, the pass-through
3
+ // variables (proxies, CA bundles, language) and WORK_AGENT_RUNNER_HOME present
4
+ // now are written into the definition (file mode 0600: proxy URLs may hold
5
+ // passwords). A program home other than the default gets a service of its
6
+ // own, named with a short hash of its path.
5
7
 
6
8
  import { spawnSync } from 'node:child_process';
9
+ import crypto from 'node:crypto';
7
10
  import fs from 'node:fs';
8
11
  import os from 'node:os';
9
12
  import path from 'node:path';
10
13
 
14
+ import { PROGRAM_DIR, configPaths } from './config.mjs';
11
15
  import { PASS_THROUGH_VARIABLES, PROXY_VARIABLES } from './sandbox.mjs';
12
16
  import { redactUrl } from './log.mjs';
13
17
 
@@ -23,16 +27,35 @@ export function serviceExitCode(code, env = process.env) {
23
27
  return code === EXIT_NEEDS_ATTENTION && env.GC_RUNNER_SERVICE === 'launchd' ? 0 : code;
24
28
  }
25
29
 
30
+ function realpathOr(value) {
31
+ try {
32
+ return fs.realpathSync(value);
33
+ } catch {
34
+ return path.resolve(value);
35
+ }
36
+ }
37
+
26
38
  /**
27
- * PATH, the pass-through variables that are set, WORK_AGENT_HOME when this
28
- * terminal has one (else the service would use a different knowledge pool than
29
- * the user's own work-agent), NODE_USE_ENV_PROXY with a proxy, and the service
30
- * marker.
39
+ * '' for the default program home (~/.work-agent-runner), else '-' and the
40
+ * first 8 hex digits of the SHA-256 of its real path: one service per program
41
+ * home, and two homes never share a definition.
42
+ */
43
+ export function serviceSuffix({ env = process.env, home = os.homedir() } = {}) {
44
+ const programHome = configPaths(env, home).baseDir;
45
+ if (realpathOr(programHome) === realpathOr(path.join(home, PROGRAM_DIR))) return '';
46
+ return `-${crypto.createHash('sha256').update(realpathOr(programHome)).digest('hex').slice(0, 8)}`;
47
+ }
48
+
49
+ /**
50
+ * PATH, the pass-through variables that are set, WORK_AGENT_RUNNER_HOME when
51
+ * the program's home is not the default one (else the service would read
52
+ * another home, without the token), NODE_USE_ENV_PROXY with a proxy, and the
53
+ * service marker. WORK_AGENT_HOME is not needed: config.json records it.
31
54
  */
32
55
  export function serviceEnvironment(env, kind) {
33
56
  const out = { PATH: env.PATH || '/usr/local/bin:/usr/bin:/bin' };
34
57
  for (const name of PASS_THROUGH_VARIABLES) if (env[name]) out[name] = env[name];
35
- if (env.WORK_AGENT_HOME) out.WORK_AGENT_HOME = env.WORK_AGENT_HOME;
58
+ if (env.WORK_AGENT_RUNNER_HOME) out.WORK_AGENT_RUNNER_HOME = path.resolve(env.WORK_AGENT_RUNNER_HOME);
36
59
  if (PROXY_VARIABLES.some((name) => env[name] && !/^no_proxy$/i.test(name))) out.NODE_USE_ENV_PROXY = '1';
37
60
  out.GC_RUNNER_SERVICE = kind;
38
61
  return out;
@@ -83,7 +106,7 @@ function xml(value) {
83
106
  return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
84
107
  }
85
108
 
86
- export function launchdPlist({ nodePath, entry, args = ['start'], environment, logFile }) {
109
+ export function launchdPlist({ nodePath, entry, args = ['start'], environment, logFile, label = LAUNCHD_LABEL }) {
87
110
  const strings = (items) => items.map((item) => ` <string>${xml(item)}</string>`).join('\n');
88
111
  const variables = Object.entries(environment)
89
112
  .map(([name, value]) => ` <key>${xml(name)}</key>\n <string>${xml(value)}</string>`)
@@ -93,7 +116,7 @@ export function launchdPlist({ nodePath, entry, args = ['start'], environment, l
93
116
  <plist version="1.0">
94
117
  <dict>
95
118
  <key>Label</key>
96
- <string>${LAUNCHD_LABEL}</string>
119
+ <string>${xml(label)}</string>
97
120
  <key>ProgramArguments</key>
98
121
  <array>
99
122
  ${strings([nodePath, entry, ...args])}
@@ -119,22 +142,25 @@ ${variables}
119
142
  }
120
143
 
121
144
  export function servicePaths({ platform = process.platform, home = os.homedir(), env = process.env } = {}) {
145
+ const suffix = serviceSuffix({ env, home });
122
146
  if (platform === 'darwin') {
123
147
  const agents = path.join(home, 'Library', 'LaunchAgents');
148
+ const label = `${LAUNCHD_LABEL}${suffix}`;
124
149
  return {
125
150
  kind: 'launchd',
126
- name: LAUNCHD_LABEL,
127
- file: path.join(agents, `${LAUNCHD_LABEL}.plist`),
151
+ name: label,
152
+ file: path.join(agents, `${label}.plist`),
128
153
  legacyName: LEGACY_LAUNCHD_LABEL,
129
154
  legacyFile: path.join(agents, `${LEGACY_LAUNCHD_LABEL}.plist`),
130
- logFile: path.join(home, 'Library', 'Logs', `${SERVICE_NAME}.log`),
155
+ logFile: path.join(home, 'Library', 'Logs', `${SERVICE_NAME}${suffix}.log`),
131
156
  };
132
157
  }
133
158
  const units = path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'systemd', 'user');
159
+ const name = `${SERVICE_NAME}${suffix}`;
134
160
  return {
135
161
  kind: 'systemd',
136
- name: SERVICE_NAME,
137
- file: path.join(units, `${SERVICE_NAME}.service`),
162
+ name,
163
+ file: path.join(units, `${name}.service`),
138
164
  legacyName: LEGACY_SERVICE_NAME,
139
165
  legacyFile: path.join(units, `${LEGACY_SERVICE_NAME}.service`),
140
166
  logFile: '',
@@ -146,6 +172,11 @@ function run(command, args, { quiet = false } = {}) {
146
172
  return { ok: result.status === 0, status: result.status, stdout: result.stdout || '', stderr: result.stderr || '', error: result.error };
147
173
  }
148
174
 
175
+ /** How to read the service's own output. */
176
+ function logHintFor(paths) {
177
+ return paths.kind === 'launchd' ? `日志:${paths.logFile}` : `日志:journalctl --user -u ${paths.name} -f`;
178
+ }
179
+
149
180
  /** Writes the definition (0600), loads it and (re)starts the service. */
150
181
  export function installService({ platform = process.platform, nodePath, entry, args, env = process.env, say }) {
151
182
  const paths = servicePaths({ platform, env });
@@ -155,24 +186,52 @@ export function installService({ platform = process.platform, nodePath, entry, a
155
186
  fs.mkdirSync(path.dirname(paths.file), { recursive: true, mode: 0o700 });
156
187
  if (paths.kind === 'launchd') {
157
188
  fs.mkdirSync(path.dirname(paths.logFile), { recursive: true });
158
- fs.writeFileSync(paths.file, launchdPlist({ nodePath, entry, args, environment, logFile: paths.logFile }), { mode: 0o600 });
189
+ fs.writeFileSync(paths.file, launchdPlist({ nodePath, entry, args, environment, logFile: paths.logFile, label: paths.name }), { mode: 0o600 });
159
190
  fs.chmodSync(paths.file, 0o600);
160
191
  const domain = `gui/${process.getuid()}`;
161
- run('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], { quiet: true }); // an older definition, if loaded
192
+ run('launchctl', ['bootout', `${domain}/${paths.name}`], { quiet: true }); // an older definition, if loaded
162
193
  const loaded = run('launchctl', ['bootstrap', domain, paths.file]);
163
194
  if (!loaded.ok) throw new Error('launchctl bootstrap 失败');
164
- say(`已安装并启动后台服务(launchd)。日志:${paths.logFile}`);
195
+ say(`已安装并启动后台服务(launchd,${paths.name})。${logHintFor(paths)}`);
165
196
  return paths;
166
197
  }
167
198
  fs.writeFileSync(paths.file, systemdUnit({ nodePath, entry, args, environment }), { mode: 0o600 });
168
199
  fs.chmodSync(paths.file, 0o600);
169
- for (const command of [['daemon-reload'], ['enable', SERVICE_NAME], ['restart', SERVICE_NAME]]) {
200
+ for (const command of [['daemon-reload'], ['enable', paths.name], ['restart', paths.name]]) {
170
201
  const result = run('systemctl', ['--user', ...command]);
171
202
  if (!result.ok) throw new Error(`systemctl --user ${command.join(' ')} 失败`);
172
203
  }
173
- say('已安装并启动后台服务(systemd 用户服务)。');
204
+ say(`已安装并启动后台服务(systemd 用户服务 ${paths.name})。`);
174
205
  say('退出登录后服务会停止;要让它一直运行,请让管理员执行一次:loginctl enable-linger $USER');
175
- say(`查看日志:journalctl --user -u ${SERVICE_NAME} -f`);
206
+ say(`查看日志:journalctl --user -u ${paths.name} -f`);
207
+ return paths;
208
+ }
209
+
210
+ /**
211
+ * start | stop | restart an installed service. Throws when it is not
212
+ * installed or the service manager refuses.
213
+ */
214
+ export function controlService(action, { platform = process.platform, env = process.env, say }) {
215
+ const paths = servicePaths({ platform, env });
216
+ if (!fs.existsSync(paths.file)) throw new Error('后台服务还没有安装:先运行 work-agent-runner service install');
217
+ const labels = { start: '启动', stop: '停止', restart: '重启' };
218
+ if (paths.kind === 'launchd') {
219
+ const domain = `gui/${process.getuid()}`;
220
+ const target = `${domain}/${paths.name}`;
221
+ let result;
222
+ if (action === 'stop') result = run('launchctl', ['bootout', target]);
223
+ else if (action === 'start') result = run('launchctl', ['bootstrap', domain, paths.file]);
224
+ else {
225
+ // kickstart -k restarts a loaded job; a stopped one is loaded first.
226
+ result = run('launchctl', ['kickstart', '-k', target], { quiet: true });
227
+ if (!result.ok) result = run('launchctl', ['bootstrap', domain, paths.file]);
228
+ }
229
+ if (!result.ok) throw new Error(`launchctl 未能${labels[action]}后台服务(${paths.name})`);
230
+ } else {
231
+ const result = run('systemctl', ['--user', action, paths.name]);
232
+ if (!result.ok) throw new Error(`systemctl --user ${action} ${paths.name} 失败`);
233
+ }
234
+ say(`已${labels[action]}后台服务(${paths.name})。${action === 'stop' ? '' : logHintFor(paths)}`);
176
235
  return paths;
177
236
  }
178
237
 
@@ -211,16 +270,16 @@ export function uninstallService({ platform = process.platform, env = process.en
211
270
  else if (!legacy) say('没有安装后台服务');
212
271
  }
213
272
 
214
- /** { installed, state, logHint } */
273
+ /** { installed, state, logHint, name } */
215
274
  export function serviceStatus({ platform = process.platform, env = process.env } = {}) {
216
275
  const paths = servicePaths({ platform, env });
217
276
  const installed = fs.existsSync(paths.file);
218
277
  if (paths.kind === 'launchd') {
219
- const result = run('launchctl', ['print', `gui/${process.getuid()}/${LAUNCHD_LABEL}`], { quiet: true });
278
+ const result = run('launchctl', ['print', `gui/${process.getuid()}/${paths.name}`], { quiet: true });
220
279
  const state = result.ok ? /state = (\w+)/.exec(result.stdout)?.[1] || '已加载' : '未加载';
221
- return { installed, state, logHint: `日志:${paths.logFile}` };
280
+ return { installed, state, logHint: logHintFor(paths), name: paths.name };
222
281
  }
223
- const active = run('systemctl', ['--user', 'is-active', SERVICE_NAME], { quiet: true });
282
+ const active = run('systemctl', ['--user', 'is-active', paths.name], { quiet: true });
224
283
  const state = active.error ? '无法读取(systemctl 不可用)' : active.stdout.trim() || 'unknown';
225
- return { installed, state, logHint: `日志:journalctl --user -u ${SERVICE_NAME} -f` };
284
+ return { installed, state, logHint: logHintFor(paths), name: paths.name };
226
285
  }