@online-tools/work-agent-runner 0.0.1-alpha-5 → 0.0.2-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/lib/config.mjs CHANGED
@@ -1,12 +1,22 @@
1
- // Where the program keeps things, and its config file:
2
- // config ${XDG_CONFIG_HOME:-~/.config}/work-agent-runner/config.json (dir 0700, file 0600)
3
- // { server, token, clientId, setupDone, workRoot?, claudePath?, machineName? }
4
- // lock same directory, run.lock
5
- // cache ${XDG_CACHE_HOME:-~/.cache}/work-agent-runner/skills/
6
- // work /var/tmp/work-agent-runner-<uid>/ (Linux) or <tmpdir>/work-agent-runner/
7
- // (macOS): never inside HOME, which the sandbox may not read.
8
- // Until 0.0.1-alpha-4 the program was npm @online-tools/agent-runner and every
9
- // name above was gitcode-agent-runner; adoptLegacyConfig() moves that config.
1
+ // Everything the program keeps lives under one directory, its "home"
2
+ // (WORK_AGENT_RUNNER_HOME, default ~/.work-agent-runner, 0700):
3
+ //
4
+ // config.json { server, token, clientId, setupDone, workRoot?,
5
+ // claudePath?, machineName?, workAgentRepo?,
6
+ // workAgentRepoDir, ascendReposDir } (0600)
7
+ // run.lock one running instance per user
8
+ // work-agent/ the work-agent clone: the Skill source (lib/work-agent.mjs)
9
+ // work-agent.lock the clone's lock (a terminal `update` vs the service)
10
+ // .work-agent symlink to ~/.work-agent, work-agent's own home and the
11
+ // WORK_AGENT_HOME of every job (logs/ tmp/ docs/
12
+ // ascend-repos/ essential-repos.txt live there, shared
13
+ // with the user's own use of work-agent)
14
+ // node/ a downloaded Node, when the system one is too old
15
+ // runs/<7 chars>/ one directory per job, deleted when it ends (--work-dir
16
+ // moves just this one elsewhere, e.g. a bigger disk)
17
+ //
18
+ // Earlier versions kept these under XDG directories and ran jobs in /var/tmp;
19
+ // adoptLegacyState() moves what matters and drops the rest.
10
20
  // Functions only; bin/ decides when to read or write.
11
21
 
12
22
  import crypto from 'node:crypto';
@@ -15,6 +25,15 @@ import os from 'node:os';
15
25
  import path from 'node:path';
16
26
 
17
27
  export const DEFAULT_SERVER = 'https://online-tools.closerouter.site';
28
+ /** The work-agent clone is fast-forwarded every day at this hour (local time). */
29
+ export const REPO_UPDATE_HOUR = 8;
30
+ /** The knowledge pool is updated this often (every repository it holds). */
31
+ export const POOL_UPDATE_MS = 60 * 60_000;
32
+ export const PROGRAM_DIR = '.work-agent-runner';
33
+ /** work-agent's own home, shared with the user's own use of it. */
34
+ export const WORK_AGENT_DIR = '.work-agent';
35
+ /** Its repository pool, which the program may be pointed at another disk. */
36
+ export const POOL_DIR = path.join(WORK_AGENT_DIR, 'ascend-repos');
18
37
 
19
38
  const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
20
39
 
@@ -23,25 +42,77 @@ export const LEGACY_NAME = 'gitcode-agent-runner';
23
42
 
24
43
  export class ConfigError extends Error {}
25
44
 
45
+ /**
46
+ * Every path the program owns. `home` is the user's home directory; the
47
+ * program's own home is WORK_AGENT_RUNNER_HOME or <home>/.work-agent-runner.
48
+ */
26
49
  export function configPaths(env = process.env, home = os.homedir()) {
50
+ const base = env.WORK_AGENT_RUNNER_HOME ? path.resolve(env.WORK_AGENT_RUNNER_HOME) : path.join(home, PROGRAM_DIR);
27
51
  const configRoot = env.XDG_CONFIG_HOME || path.join(home, '.config');
28
- const cacheRoot = env.XDG_CACHE_HOME || path.join(home, '.cache');
29
- const configDir = path.join(configRoot, 'work-agent-runner');
30
- const cacheDir = path.join(cacheRoot, 'work-agent-runner');
31
- const legacyConfigDir = path.join(configRoot, LEGACY_NAME);
32
52
  return {
33
- configDir,
34
- configFile: path.join(configDir, 'config.json'),
35
- lockFile: path.join(configDir, 'run.lock'),
36
- cacheDir,
37
- skillsDir: path.join(cacheDir, 'skills'),
38
- legacyConfigDir,
39
- legacyConfigFile: path.join(legacyConfigDir, 'config.json'),
40
- legacyLockFile: path.join(legacyConfigDir, 'run.lock'),
41
- legacyCacheDir: path.join(cacheRoot, LEGACY_NAME),
53
+ baseDir: base,
54
+ // saveConfig() creates this; it is the program's home, not a subdirectory.
55
+ configDir: base,
56
+ configFile: path.join(base, 'config.json'),
57
+ lockFile: path.join(base, 'run.lock'),
58
+ repoDir: path.join(base, 'work-agent'),
59
+ repoLockFile: path.join(base, 'work-agent.lock'),
60
+ // WORK_AGENT_HOME handed to every job: work-agent's own home, a real
61
+ // directory outside the program's, so the user's own work-agent use sees
62
+ // the same logs, scratch and repository pool.
63
+ workAgentHome: path.join(home, WORK_AGENT_DIR),
64
+ // A symlink to it inside the program's home, so everything the program
65
+ // touches is reachable from one place.
66
+ workAgentLink: path.join(base, WORK_AGENT_DIR),
67
+ nodeDir: path.join(base, 'node'),
68
+ runsRoot: base,
69
+ poolDir: path.join(home, POOL_DIR),
70
+ // Where earlier versions kept things (newest first: adopt the newest).
71
+ legacyConfigFiles: [
72
+ path.join(configRoot, 'work-agent-runner', 'config.json'),
73
+ path.join(configRoot, LEGACY_NAME, 'config.json'),
74
+ ],
75
+ legacyDirs: [
76
+ path.join(configRoot, 'work-agent-runner'),
77
+ path.join(configRoot, LEGACY_NAME),
78
+ path.join(env.XDG_CACHE_HOME || path.join(home, '.cache'), 'work-agent-runner'),
79
+ path.join(env.XDG_CACHE_HOME || path.join(home, '.cache'), LEGACY_NAME),
80
+ ],
81
+ legacyNodeDirs: [
82
+ path.join(env.XDG_DATA_HOME || path.join(home, '.local', 'share'), 'work-agent-runner', 'node'),
83
+ path.join(env.XDG_DATA_HOME || path.join(home, '.local', 'share'), LEGACY_NAME, 'node'),
84
+ ],
85
+ legacyRepoDir: path.join(env.XDG_DATA_HOME || path.join(home, '.local', 'share'), 'work-agent-runner', 'work-agent'),
86
+ legacyWorkRoots: [
87
+ `/var/tmp/work-agent-runner-${process.getuid?.() ?? 0}`,
88
+ `/var/tmp/gitcode-agent-runner-${process.getuid?.() ?? 0}`,
89
+ ],
90
+ };
91
+ }
92
+
93
+ /**
94
+ * The two repository locations, from the config file when it names them (that
95
+ * is where the updater looks) and otherwise the defaults. Returns `paths` with
96
+ * repoDir / poolDir resolved, and whether the config should be written back so
97
+ * the file always shows both.
98
+ */
99
+ export function withRepoPaths(paths, config) {
100
+ const repoDir = config.workAgentRepoDir || paths.repoDir;
101
+ const poolDir = config.ascendReposDir || paths.poolDir;
102
+ if (repoDir === poolDir) {
103
+ throw new ConfigError(`work-agent 仓库和知识仓不能是同一个目录(${repoDir})`);
104
+ }
105
+ return {
106
+ paths: { ...paths, repoDir, poolDir },
107
+ missing: !config.workAgentRepoDir || !config.ascendReposDir,
42
108
  };
43
109
  }
44
110
 
111
+ /** The lock file of a legacy config directory, for "is the old program running?". */
112
+ export function legacyLockFile(configFile) {
113
+ return path.join(path.dirname(configFile), 'run.lock');
114
+ }
115
+
45
116
  export function newClientId() {
46
117
  return crypto.randomUUID();
47
118
  }
@@ -59,6 +130,16 @@ function normalize(raw) {
59
130
  };
60
131
  if (typeof raw.workRoot === 'string' && raw.workRoot) config.workRoot = raw.workRoot;
61
132
  if (typeof raw.claudePath === 'string' && raw.claudePath) config.claudePath = raw.claudePath;
133
+ // Where the two repositories are. Written on first run, so the file shows
134
+ // them; edit it (absolute paths) to put either somewhere else.
135
+ for (const key of ['workAgentRepoDir', 'ascendReposDir']) {
136
+ if (typeof raw[key] === 'string' && path.isAbsolute(raw[key])) config[key] = path.resolve(raw[key]);
137
+ }
138
+ // A mirror of the work-agent repository, for this machine only. http(s) only:
139
+ // a value starting with '-' would reach git as an option.
140
+ if (typeof raw.workAgentRepo === 'string' && /^https?:\/\/[^\s]{1,480}$/.test(raw.workAgentRepo)) {
141
+ config.workAgentRepo = raw.workAgentRepo;
142
+ }
62
143
  // The name sent with /connect: it names this machine when the website registers it.
63
144
  if (typeof raw.machineName === 'string' && raw.machineName) config.machineName = raw.machineName.slice(0, 100);
64
145
  return config;
@@ -97,25 +178,36 @@ export function saveConfig(paths, config) {
97
178
  fs.chmodSync(paths.configFile, 0o600);
98
179
  }
99
180
 
100
- /** True when the old name's config should move here: none here yet, one there. */
181
+ /** The newest legacy config to adopt ('' when there is none, or one is already here). */
101
182
  export function legacyConfigPending(paths) {
102
- return !fs.existsSync(paths.configFile) && fs.existsSync(paths.legacyConfigFile);
183
+ if (fs.existsSync(paths.configFile)) return '';
184
+ return paths.legacyConfigFiles.find((file) => fs.existsSync(file)) || '';
103
185
  }
104
186
 
105
187
  /**
106
- * Moves the old name's config here, so the token, machine id and name stay
107
- * (the website keeps seeing the same machine), then deletes the old config
108
- * directory — one machine id must not be used by two programs — and the old
109
- * Skill cache. Throws ConfigError when the old config is unreadable.
188
+ * Moves an older layout's state into the program's home: the config (so the
189
+ * token, machine id and name stay — the website keeps seeing the same machine)
190
+ * and a Node this program downloaded before. Then removes the old directories,
191
+ * including the Skill cache of the versions whose Skills came from the website.
192
+ * Throws ConfigError when the old config is unreadable.
110
193
  */
111
- export function adoptLegacyConfig(paths) {
112
- saveConfig(paths, loadConfig({ configFile: paths.legacyConfigFile }));
113
- fs.rmSync(paths.legacyConfigDir, { recursive: true, force: true });
114
- fs.rmSync(paths.legacyCacheDir, { recursive: true, force: true });
115
- }
116
-
117
- export function defaultWorkRoot({ platform = process.platform, uid = process.getuid?.() ?? 0, tmpdir = os.tmpdir() } = {}) {
118
- return platform === 'darwin' ? path.join(tmpdir, 'work-agent-runner') : `/var/tmp/work-agent-runner-${uid}`;
194
+ export function adoptLegacyState(paths, configFile) {
195
+ if (configFile) saveConfig(paths, loadConfig({ configFile }));
196
+ if (!fs.existsSync(paths.nodeDir)) {
197
+ const node = paths.legacyNodeDirs.find((dir) => fs.existsSync(dir));
198
+ if (node) {
199
+ try {
200
+ fs.mkdirSync(path.dirname(paths.nodeDir), { recursive: true, mode: 0o700 });
201
+ fs.renameSync(node, paths.nodeDir);
202
+ } catch {
203
+ // A different filesystem, or gone: it will be downloaded again when needed.
204
+ }
205
+ }
206
+ }
207
+ // One machine id must not be used by two programs, and nothing reads these now.
208
+ for (const dir of [...paths.legacyDirs, paths.legacyRepoDir, ...paths.legacyWorkRoots]) {
209
+ fs.rmSync(dir, { recursive: true, force: true });
210
+ }
119
211
  }
120
212
 
121
213
  export function isInside(child, parent) {
@@ -133,17 +225,16 @@ function realpathOr(value) {
133
225
  export class WorkRootError extends Error {}
134
226
 
135
227
  /**
136
- * Creates (0700) and checks the work root: not inside HOME (also after
137
- * resolving symlinks), not a symlink itself, owned by this user. Returns its
138
- * real path, which everything else uses.
228
+ * Creates (0700) and checks the directory that holds `runs/`: not a symlink,
229
+ * not the home directory itself, owned by this user. Returns its real path,
230
+ * which everything else uses. Jobs live inside the program's home now, so the
231
+ * sandbox is told about that one subtree (lib/sandbox.mjs) instead of being
232
+ * kept out of the home directory entirely.
139
233
  */
140
234
  export function prepareWorkRoot(dir, { home = os.homedir(), uid = process.getuid?.() ?? 0 } = {}) {
141
235
  const resolved = path.resolve(dir);
142
- const realHome = realpathOr(home);
143
- const inHome = (value) => isInside(value, path.resolve(home)) || isInside(value, realHome);
144
- const message = `工作目录 ${resolved} 在主目录(${home})之内;沙箱不允许读取主目录,请用 --work-dir 换到主目录之外`;
145
- if (inHome(resolved) || inHome(path.join(realpathOr(path.dirname(resolved)), path.basename(resolved)))) {
146
- throw new WorkRootError(message);
236
+ if (resolved === path.resolve(home) || resolved === realpathOr(home)) {
237
+ throw new WorkRootError(`工作目录不能是主目录本身(${resolved}),请用 --work-dir 指定一个子目录`);
147
238
  }
148
239
  fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
149
240
  const stat = fs.lstatSync(resolved);
@@ -151,7 +242,5 @@ export function prepareWorkRoot(dir, { home = os.homedir(), uid = process.getuid
151
242
  if (!stat.isDirectory()) throw new WorkRootError(`${resolved} 不是目录`);
152
243
  if (stat.uid !== uid) throw new WorkRootError(`工作目录 ${resolved} 的属主不是当前用户,请删除它或用 --work-dir 换一个目录`);
153
244
  if ((stat.mode & 0o777) !== 0o700) fs.chmodSync(resolved, 0o700);
154
- const real = fs.realpathSync(resolved);
155
- if (inHome(real)) throw new WorkRootError(message);
156
- return real;
245
+ return fs.realpathSync(resolved);
157
246
  }
package/lib/doctor.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // What this machine can do: tools on PATH, claude and its version, the
2
- // package manager, and whether a command really runs in the Claude Code
3
- // sandbox. The result is reported to the website as `capabilities` (it
4
- // decides which features run).
2
+ // package manager, the work-agent clone and knowledge pool, and whether a
3
+ // command really runs in the Claude Code sandbox. The result is reported to
4
+ // the website as `capabilities` (it decides which features run).
5
5
 
6
6
  import { spawn, spawnSync } from 'node:child_process';
7
7
  import fs from 'node:fs';
@@ -14,9 +14,9 @@ import { PROBE_MARKER, PROBE_TOOL_ID, startProbeModel } from './probe-model.mjs'
14
14
  import {
15
15
  caPaths,
16
16
  createRunLayout,
17
- homeReadAllow,
18
17
  newRunDir,
19
18
  passThroughEnv,
19
+ runAllowances,
20
20
  socketPathProblem,
21
21
  writeSandboxSettings,
22
22
  } from './sandbox.mjs';
@@ -161,13 +161,17 @@ export async function probeSandbox({
161
161
  claudePath,
162
162
  workRoot,
163
163
  realHome,
164
+ poolDir = '',
165
+ paths = null,
164
166
  env = process.env,
165
167
  platform = process.platform,
166
168
  timeoutMs = PROBE_TIMEOUT_MS,
167
169
  }) {
168
170
  if (!claudePath) return { ok: false, reason: '未安装 claude' };
169
171
  const pathEnv = env.PATH || '';
170
- const layout = createRunLayout(newRunDir(path.join(workRoot, 'runs'), 'p'));
172
+ const layout = createRunLayout(newRunDir(path.join(workRoot, 'runs'), 'p'), {
173
+ workAgentHome: paths?.workAgentHome || '',
174
+ });
171
175
  let model = null;
172
176
  try {
173
177
  const tooLong = socketPathProblem(layout.tmpDir, platform);
@@ -175,7 +179,7 @@ export async function probeSandbox({
175
179
  writeSandboxSettings(layout.settingsFile, {
176
180
  workDir: layout.workDir,
177
181
  realHome,
178
- readAllow: homeReadAllow({ realHome, pathEnv, caPaths: caPaths(env) }),
182
+ ...runAllowances(layout, { realHome, pathEnv, caPaths: caPaths(env), pool: poolDir, paths }),
179
183
  });
180
184
  model = await startProbeModel();
181
185
  const child = spawn(claudePath, claudeArgs({ settingsFile: layout.settingsFile }), {
@@ -191,7 +195,13 @@ export async function probeSandbox({
191
195
  baseUrl: model.baseUrl,
192
196
  apiKey: 'probe',
193
197
  model: 'probe',
194
- extra: { ...passThroughEnv(env, platform), ...localNoProxy(env) },
198
+ // Exactly a job's environment, so the probe exercises the same paths.
199
+ // Exactly a job's environment, so the probe exercises the same paths.
200
+ extra: {
201
+ ...passThroughEnv(env, platform),
202
+ ...(paths?.workAgentHome ? { WORK_AGENT_HOME: paths.workAgentHome } : {}),
203
+ ...localNoProxy(env),
204
+ },
195
205
  }),
196
206
  });
197
207
  const exited = new Promise((resolve) => child.once('close', resolve));
@@ -243,7 +253,9 @@ export async function probeSandbox({
243
253
 
244
254
  /**
245
255
  * Full check. `probe: false` skips the sandbox probe (it then reads as not
246
- * checked). Returns { capabilities, tools, claude, claudeVersion, packageManager }.
256
+ * checked). `workAgent`: a WorkAgent, whose clone and pool are reported as
257
+ * capabilities and mounted into the probe exactly as into a job. Returns
258
+ * { capabilities, tools, claude, claudeVersion, packageManager, workAgent }.
247
259
  */
248
260
  export async function runDoctor({
249
261
  env = process.env,
@@ -252,6 +264,7 @@ export async function runDoctor({
252
264
  configuredClaude = '',
253
265
  workRoot,
254
266
  realHome,
267
+ workAgent = null,
255
268
  probe = true,
256
269
  probeTimeoutMs = PROBE_TIMEOUT_MS,
257
270
  }) {
@@ -260,11 +273,21 @@ export async function runDoctor({
260
273
  const claude = resolveClaude({ env, configured: configuredClaude, pathEnv });
261
274
  const version = claudeVersion(claude.path, env);
262
275
  const packageManager = detectPackageManager({ platform, which: (name) => which(name, pathEnv) });
276
+ const repo = workAgent ? workAgent.state() : null;
263
277
  let sandbox;
264
278
  if (!claude.path) sandbox = { ok: false, reason: '未安装 claude' };
265
279
  else if (!probe) sandbox = { ok: false, reason: '尚未检测沙箱' };
266
280
  else {
267
- sandbox = await probeSandbox({ claudePath: claude.path, workRoot, realHome, env, platform, timeoutMs: probeTimeoutMs });
281
+ sandbox = await probeSandbox({
282
+ claudePath: claude.path,
283
+ workRoot,
284
+ realHome,
285
+ poolDir: workAgent?.mountablePool() || '',
286
+ paths: workAgent?.paths || null,
287
+ env,
288
+ platform,
289
+ timeoutMs: probeTimeoutMs,
290
+ });
268
291
  if (!sandbox.ok && platform === 'linux') {
269
292
  // The common case, in words the user can act on (setup installs them).
270
293
  const missing = SANDBOX_TOOLS.filter((name) => !tools[name]?.ok).map((name) => (name === 'bwrap' ? 'bubblewrap' : name));
@@ -280,10 +303,14 @@ export async function runDoctor({
280
303
  tools: Object.fromEntries(SKILL_TOOLS.map((name) => [name, Boolean(tools[name]?.ok)])),
281
304
  sandbox,
282
305
  packageManager,
306
+ workAgent: repo
307
+ ? { commit: repo.commit, committedAt: repo.committedAt, repos: repo.repos, ascend: repo.ascend }
308
+ : { commit: '', committedAt: '', repos: 0, ascend: false },
283
309
  },
284
310
  tools,
285
311
  claude,
286
312
  claudeVersion: version,
287
313
  packageManager,
314
+ workAgent: repo,
288
315
  };
289
316
  }
package/lib/jobs.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  // Running website jobs on this machine.
2
2
  //
3
- // A job carries data only (task text, model, credentials, timeout, Skill
4
- // version); the command line, environment, tool allowlist and sandbox
5
- // settings are built here. Per job:
6
- // validate → accept → sync Skills → run directory → claude (own process
3
+ // A job carries data only (task text, model, credentials, timeout); the
4
+ // command line, environment, tool allowlist and sandbox settings are built
5
+ // here, and the Skills come from this machine's own work-agent clone
6
+ // (lib/work-agent.mjs). Per job:
7
+ // validate → accept → run directory → copy Skills → claude (own process
7
8
  // group, sandboxed) → stream output (ordered batches, retried) → exit →
8
9
  // delete the run directory.
9
10
  // Logs name the run, feature, duration and exit code — never the API key,
@@ -19,9 +20,9 @@ import { ApiError } from './http.mjs';
19
20
  import {
20
21
  caPaths,
21
22
  createRunLayout,
22
- homeReadAllow,
23
23
  newRunDir,
24
24
  passThroughEnv,
25
+ runAllowances,
25
26
  socketPathProblem,
26
27
  writeSandboxSettings,
27
28
  } from './sandbox.mjs';
@@ -45,10 +46,15 @@ const RETRY_MAX_MS = 10_000;
45
46
  const UNDELIVERED_LIMIT_MS = 60_000;
46
47
  const BACKLOG_LIMIT_BYTES = 32 * 1024 * 1024;
47
48
 
48
- /** '' when the job is acceptable, else the name of the first bad field (design 5.4). */
49
+ /**
50
+ * '' when the job is acceptable, else the name of the first bad field (design
51
+ * 5.4). Protocol 2 dropped `skillsHash` (the machine owns its Skills now); 1 is
52
+ * still accepted and its `skillsHash` ignored, so this program works under a
53
+ * website that has not been deployed yet.
54
+ */
49
55
  export function invalidJobField(job) {
50
56
  if (!job || typeof job !== 'object') return 'job';
51
- if (job.protocol !== 1) return 'protocol';
57
+ if (job.protocol !== 1 && job.protocol !== 2) return 'protocol';
52
58
  if (typeof job.runId !== 'string' || !RUN_ID.test(job.runId)) return 'runId';
53
59
  if (!Object.hasOwn(FEATURE_LABELS, job.feature)) return 'feature';
54
60
  if (typeof job.task !== 'string' || !job.task || Buffer.byteLength(job.task) > TASK_MAX_BYTES) return 'task';
@@ -66,7 +72,6 @@ export function invalidJobField(job) {
66
72
  if (keys.length !== 1 || keys[0] !== 'GITCODE_CRED' || typeof env.GITCODE_CRED !== 'string' || env.GITCODE_CRED.length > 512) return 'env';
67
73
  if (!Number.isInteger(job.timeoutMs) || job.timeoutMs < 60_000 || job.timeoutMs > 14_400_000) return 'timeoutMs';
68
74
  if (job.interactive !== false) return 'interactive';
69
- if (typeof job.skillsHash !== 'string' || !/^[0-9a-f]{64}$/.test(job.skillsHash)) return 'skillsHash';
70
75
  return '';
71
76
  }
72
77
 
@@ -243,13 +248,15 @@ function killGroup(pid, signal) {
243
248
 
244
249
  /**
245
250
  * Holds the jobs running on this machine. `client`: http.mjs client;
246
- * `skills`: SkillCache; `onFatal(error)`: the token or machine is no longer
247
- * accepted (stop everything).
251
+ * `workAgent`: WorkAgent (the Skill source and the knowledge pool);
252
+ * `onFatal(error)`: the token or machine is no longer accepted (stop
253
+ * everything).
248
254
  */
249
255
  export class JobManager {
250
- constructor({ client, skills, workRoot, claudePath, realHome, env = process.env, platform = process.platform, log, onFatal = () => {} }) {
256
+ constructor({ client, workAgent, workRoot, claudePath, realHome, env = process.env, platform = process.platform, log, onFatal = () => {} }) {
251
257
  this.client = client;
252
- this.skills = skills;
258
+ this.workAgent = workAgent;
259
+ this.paths = workAgent?.paths || null;
253
260
  this.runsDir = path.join(workRoot, 'runs');
254
261
  this.claudePath = claudePath;
255
262
  this.realHome = realHome;
@@ -365,14 +372,6 @@ export class JobManager {
365
372
  const label = FEATURE_LABELS[job.feature];
366
373
  this.log.info(`开始任务 ${runId}(${label})`);
367
374
 
368
- let files;
369
- try {
370
- files = await this.skills.ensure(job.skillsHash);
371
- } catch (error) {
372
- if (error instanceof ApiError && (error.status === 401 || error.status === 403)) this.onFatal(error);
373
- await this.reportExit(entry, { error: `同步 Skill 失败:${error?.message || error}` });
374
- return;
375
- }
376
375
  if (entry.cancelled) {
377
376
  await this.reportExit(entry, { signal: 'SIGTERM' });
378
377
  return;
@@ -383,18 +382,35 @@ export class JobManager {
383
382
  let layout;
384
383
  try {
385
384
  runDir = newRunDir(this.runsDir, 'r');
386
- layout = createRunLayout(runDir);
385
+ layout = createRunLayout(runDir, { workAgentHome: this.paths?.workAgentHome || '' });
387
386
  const tooLong = socketPathProblem(layout.tmpDir, this.platform);
388
387
  if (tooLong) throw new Error(tooLong);
389
- this.skills.copyInto(job.skillsHash, files, layout.skillsDir, layout.workAgentDir);
388
+ } catch (error) {
389
+ if (runDir) fs.rmSync(runDir, { recursive: true, force: true });
390
+ await this.reportExit(entry, { error: `准备运行目录失败:${error?.message || error}` });
391
+ return;
392
+ }
393
+
394
+ // A copy of this machine's work-agent clone as the working directory, and
395
+ // the knowledge pool read-only if there is one.
396
+ try {
397
+ const { commit } = await this.workAgent.copyRepoInto(layout.workDir, this.paths.workAgentHome);
398
+ const pool = this.workAgent.mountablePool();
390
399
  writeSandboxSettings(layout.settingsFile, {
391
400
  workDir: fs.realpathSync(layout.workDir),
392
401
  realHome: this.realHome,
393
- readAllow: homeReadAllow({ realHome: this.realHome, pathEnv: this.env.PATH || '', caPaths: caPaths(this.env) }),
402
+ ...runAllowances(layout, {
403
+ realHome: this.realHome,
404
+ pathEnv: this.env.PATH || '',
405
+ caPaths: caPaths(this.env),
406
+ pool,
407
+ paths: this.paths,
408
+ }),
394
409
  });
410
+ this.log.info(`任务 ${runId} 使用 work-agent ${commit.slice(0, 7)}${pool ? ',已挂载知识仓' : ''}`);
395
411
  } catch (error) {
396
- if (runDir) fs.rmSync(runDir, { recursive: true, force: true });
397
- await this.reportExit(entry, { error: `准备运行目录失败:${error?.message || error}` });
412
+ fs.rmSync(runDir, { recursive: true, force: true });
413
+ await this.reportExit(entry, { error: `准备 Skill 失败:${error?.message || error}` });
398
414
  return;
399
415
  }
400
416
 
@@ -440,7 +456,13 @@ export class JobManager {
440
456
  baseUrl: job.baseUrl,
441
457
  apiKey: job.apiKey,
442
458
  model: job.model,
443
- extra: { ...passThroughEnv(this.env, this.platform), GITCODE_CRED: job.env.GITCODE_CRED },
459
+ extra: {
460
+ ...passThroughEnv(this.env, this.platform),
461
+ // The program's persistent workspace: the job's HOME links to it,
462
+ // so `~/.work-agent/...` in a Skill is the same directory.
463
+ WORK_AGENT_HOME: this.paths.workAgentHome,
464
+ GITCODE_CRED: job.env.GITCODE_CRED,
465
+ },
444
466
  }),
445
467
  });
446
468
  } catch (error) {
@@ -4,7 +4,7 @@
4
4
  // 18): download the latest official Node.js LTS build (nodejs.org, or the
5
5
  // npmmirror copy when nodejs.org is unreachable), check its SHA-256 against
6
6
  // SHASUMS256.txt, and keep only bin/node under
7
- // ${XDG_DATA_HOME:-~/.local/share}/work-agent-runner/node/. The system
7
+ // ${WORK_AGENT_RUNNER_HOME:-~/.work-agent-runner}/node/. The system
8
8
  // Node and PATH are never touched.
9
9
  //
10
10
  // This file runs on that old Node (from bin/work-agent-runner.cjs), so it
@@ -56,7 +56,8 @@ function compareVersionsDesc(a, b) {
56
56
 
57
57
  function nodeDataDir(env, home) {
58
58
  const vars = env || process.env;
59
- return path.join(vars.XDG_DATA_HOME || path.join(home || os.homedir(), '.local', 'share'), 'work-agent-runner', 'node');
59
+ const base = vars.WORK_AGENT_RUNNER_HOME || path.join(home || os.homedir(), '.work-agent-runner');
60
+ return path.join(base, 'node');
60
61
  }
61
62
 
62
63
  /** fs.rmSync(target, { recursive: true, force: true }), which Node < 14.14 lacks. */
package/lib/packages.mjs CHANGED
@@ -2,7 +2,10 @@
2
2
  // The website can only name tools from this list; anything else is ignored.
3
3
 
4
4
  // Tools the Skills need (the website's requiredTools draws from these).
5
- export const SKILL_TOOLS = ['git', 'curl', 'python3', 'jq', 'sed', 'base64'];
5
+ // `rg` is not in the website's list: it is what the AscendC knowledge pool is
6
+ // searched with (ascendc/references/retrieval.md is all `rg`), so `setup` asks
7
+ // for it alongside the pool (planSetup's extraTools).
8
+ export const SKILL_TOOLS = ['git', 'curl', 'python3', 'jq', 'sed', 'base64', 'rg'];
6
9
  // What the Linux sandbox needs.
7
10
  export const SANDBOX_TOOLS = ['bwrap', 'socat'];
8
11
 
@@ -13,6 +16,7 @@ const LINUX_PACKAGES = {
13
16
  jq: 'jq',
14
17
  sed: 'sed',
15
18
  base64: 'coreutils',
19
+ rg: 'ripgrep',
16
20
  bwrap: 'bubblewrap',
17
21
  socat: 'socat',
18
22
  };
@@ -25,7 +29,7 @@ export const PACKAGE_NAMES = {
25
29
  zypper: LINUX_PACKAGES,
26
30
  pacman: { ...LINUX_PACKAGES, python3: 'python' },
27
31
  apk: LINUX_PACKAGES,
28
- brew: { git: 'git', curl: null, python3: 'python', jq: 'jq', sed: null, base64: null, bwrap: null, socat: null },
32
+ brew: { git: 'git', curl: null, python3: 'python', jq: 'jq', sed: null, base64: null, rg: 'ripgrep', bwrap: null, socat: null },
29
33
  };
30
34
 
31
35
  export const LINUX_MANAGERS = ['apt', 'dnf', 'yum', 'zypper', 'pacman', 'apk'];