@online-tools/work-agent-runner 0.0.1-alpha-5 → 0.0.2-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/sandbox.mjs CHANGED
@@ -1,12 +1,26 @@
1
1
  // Claude Code sandbox settings for every job on this machine (passed with
2
2
  // --settings, so project settings cannot weaken them) and the run directory
3
3
  // layout they assume:
4
- // <runDir>/settings.json --settings (outside the sandbox's writable area)
5
- // <runDir>/claude-home/ CLAUDE_CONFIG_DIR (written by claude itself, unsandboxed)
6
- // <runDir>/work/ cwd: the only place sandboxed commands may write
7
- // .claude/skills/ the Skill copy (Edit denied)
8
- // workagent/ what /tmp/work-agent in the Skills points to
9
- // .home/ .tmp/ HOME and TMPDIR of the job
4
+ // <runDir>/settings.json --settings (never writable: not in allowWrite)
5
+ // <runDir>/claude-home/ CLAUDE_CONFIG_DIR (claude's own state)
6
+ // <runDir>/work-agent/ cwd: a full copy of this machine's work-agent
7
+ // clone, so a job works inside a work-agent
8
+ // repository without being able to touch the real
9
+ // one. .claude/** stays Edit-denied.
10
+ // <runDir>/.home/ HOME of the job, with .work-agent -> the program's
11
+ // persistent WORK_AGENT_HOME, so the Skills' own
12
+ // `~/.work-agent/...` and $WORK_AGENT_HOME are the
13
+ // same directory (linkWorkAgentHome)
14
+ // <runDir>/.tmp/ TMPDIR (the sandbox's bridge sockets live here)
15
+ //
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.
23
+ //
10
24
  // Paths are real paths: claude's HOME is the run's, so `~` cannot be used,
11
25
  // and on macOS /var is a symlink to /private/var.
12
26
 
@@ -21,8 +35,35 @@ function fromRoot(absolute) {
21
35
  return absolute.replace(/^\/+/, '');
22
36
  }
23
37
 
24
- /** The settings object (Appendix D of the design). */
25
- export function sandboxSettings({ workDir, realHome, readAllow = [] }) {
38
+ // 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.
42
+ export const SENSITIVE_HOME_PATHS = [
43
+ '.ssh',
44
+ '.gnupg',
45
+ '.aws',
46
+ '.azure',
47
+ '.gcloud',
48
+ '.kube',
49
+ '.docker',
50
+ '.config',
51
+ '.netrc',
52
+ '.npmrc',
53
+ '.pypirc',
54
+ '.git-credentials',
55
+ '.gitconfig',
56
+ '.bash_history',
57
+ '.zsh_history',
58
+ ];
59
+
60
+ /**
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.
65
+ */
66
+ export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow = [], deny = [] }) {
26
67
  return {
27
68
  sandbox: {
28
69
  enabled: true,
@@ -31,13 +72,18 @@ export function sandboxSettings({ workDir, realHome, readAllow = [] }) {
31
72
  // Ignore the model's dangerouslyDisableSandbox (project settings cannot override this).
32
73
  allowUnsandboxedCommands: false,
33
74
  network: { allowedDomains: [...ALLOWED_DOMAINS], strictAllowlist: true },
34
- filesystem: { allowRead: [...readAllow] },
75
+ filesystem: { allowRead: [...readAllow], allowWrite: [...writeAllow] },
35
76
  credentials: { envVars: [{ name: 'ANTHROPIC_AUTH_TOKEN', mode: 'deny' }] },
36
77
  },
37
78
  permissions: {
38
79
  deny: [
39
- `Read(//${fromRoot(realHome)}/**)`,
40
- `Edit(//${fromRoot(realHome)}/**)`,
80
+ ...SENSITIVE_HOME_PATHS.flatMap((name) => [
81
+ `Read(//${fromRoot(realHome)}/${name})`,
82
+ `Read(//${fromRoot(realHome)}/${name}/**)`,
83
+ `Edit(//${fromRoot(realHome)}/${name})`,
84
+ `Edit(//${fromRoot(realHome)}/${name}/**)`,
85
+ ]),
86
+ ...deny,
41
87
  `Edit(//${fromRoot(workDir)}/.claude/**)`,
42
88
  ],
43
89
  },
@@ -46,18 +92,57 @@ export function sandboxSettings({ workDir, realHome, readAllow = [] }) {
46
92
  };
47
93
  }
48
94
 
95
+ /**
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.
101
+ */
102
+ export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], pool = '', paths = null }) {
103
+ const runDirs = [layout.workDir, layout.homeDir, layout.tmpDir, layout.configDir].map((dir) => realpathOr(dir));
104
+ const workAgentHome = layout.workAgentHome ? realpathOr(layout.workAgentHome) : '';
105
+ const writeAllow = [...runDirs, ...(workAgentHome ? [workAgentHome] : [])];
106
+ const readAllow = [
107
+ ...writeAllow,
108
+ ...(pool ? [realpathOr(pool)] : []),
109
+ ...homeReadAllow({ realHome, pathEnv, caPaths }),
110
+ ];
111
+ const deny = [];
112
+ if (paths) {
113
+ // The access token, and the clone every job copies from.
114
+ for (const file of [paths.configFile, paths.repoDir]) {
115
+ deny.push(`Read(//${fromRoot(path.resolve(file))}/**)`, `Read(//${fromRoot(path.resolve(file))})`);
116
+ deny.push(`Edit(//${fromRoot(path.resolve(file))}/**)`, `Edit(//${fromRoot(path.resolve(file))})`);
117
+ }
118
+ }
119
+ // The pool is shared with the user's own work-agent: read it, never write it.
120
+ if (pool) deny.push(`Edit(//${fromRoot(realpathOr(pool))}/**)`);
121
+ return { readAllow: [...new Set(readAllow)], writeAllow: [...new Set(writeAllow)], deny };
122
+ }
123
+
124
+ function realpathOr(value) {
125
+ try {
126
+ return fs.realpathSync(value);
127
+ } catch {
128
+ return path.resolve(value);
129
+ }
130
+ }
131
+
49
132
  export function writeSandboxSettings(file, input) {
50
133
  fs.writeFileSync(file, `${JSON.stringify(sandboxSettings(input), null, 2)}\n`, { mode: 0o600 });
51
134
  }
52
135
 
53
136
  /**
54
137
  * Directories / files inside HOME that sandboxed commands still need to read:
55
- * PATH entries (e.g. ~/.local/bin, nvm) and CA bundles passed through.
56
- * Returns their real paths.
138
+ * PATH entries (e.g. ~/.local/bin, nvm), CA bundles passed through, and
139
+ * `extra` (the knowledge pool, which lives in ~/.work-agent by default).
140
+ * Returns their real paths. Entries outside HOME are dropped — they need no
141
+ * exception, since the sandbox only closes HOME.
57
142
  */
58
- export function homeReadAllow({ realHome, pathEnv = '', caPaths = [] }) {
143
+ export function homeReadAllow({ realHome, pathEnv = '', caPaths = [], extra = [] }) {
59
144
  const allowed = new Set();
60
- for (const entry of [...String(pathEnv).split(path.delimiter), ...caPaths]) {
145
+ for (const entry of [...String(pathEnv).split(path.delimiter), ...caPaths, ...extra]) {
61
146
  if (!entry || !path.isAbsolute(entry)) continue;
62
147
  let real;
63
148
  try {
@@ -79,7 +164,7 @@ export function homeReadAllow({ realHome, pathEnv = '', caPaths = [] }) {
79
164
  // check sees the same path lengths a job does.
80
165
  const UNIX_SOCKET_PATH_MAX = 107;
81
166
  const BRIDGE_SOCKET_NAME = '/claude-socks-0123456789abcdef.sock';
82
- const RUN_TMP_SUFFIX = '/runs/r123456/work/.tmp';
167
+ const RUN_TMP_SUFFIX = '/runs/r123456/.tmp';
83
168
  export const WORK_ROOT_MAX_BYTES = UNIX_SOCKET_PATH_MAX - BRIDGE_SOCKET_NAME.length - RUN_TMP_SUFFIX.length;
84
169
 
85
170
  /** Why the sandbox cannot start with this TMPDIR ('' = it can). Linux only: macOS bridges over TCP. */
@@ -96,26 +181,70 @@ export function newRunDir(runsDir, prefix) {
96
181
  return fs.mkdtempSync(path.join(runsDir, prefix));
97
182
  }
98
183
 
99
- /** Creates the run directory tree (0700) and returns its paths. */
100
- export function createRunLayout(runDir) {
184
+ /**
185
+ * Creates the run directory tree (0700) and returns its paths. `workAgentHome`
186
+ * is the program's persistent WORK_AGENT_HOME; the job's HOME gets a
187
+ * `.work-agent` symlink to it, so a Skill's `~/.work-agent/...` and
188
+ * `$WORK_AGENT_HOME` are one directory.
189
+ */
190
+ export function createRunLayout(runDir, { workAgentHome = '' } = {}) {
101
191
  fs.mkdirSync(runDir, { recursive: true, mode: 0o700 });
102
- const workDir = path.join(runDir, 'work');
103
192
  const layout = {
104
193
  runDir,
105
194
  settingsFile: path.join(runDir, 'settings.json'),
106
195
  configDir: path.join(runDir, 'claude-home'),
107
- workDir,
108
- skillsDir: path.join(workDir, '.claude', 'skills'),
109
- workAgentDir: path.join(workDir, 'workagent'),
110
- homeDir: path.join(workDir, '.home'),
111
- tmpDir: path.join(workDir, '.tmp'),
196
+ // cwd: a copy of the work-agent repository, Skills included.
197
+ workDir: path.join(runDir, 'work-agent'),
198
+ homeDir: path.join(runDir, '.home'),
199
+ tmpDir: path.join(runDir, '.tmp'),
200
+ workAgentHome,
112
201
  };
113
- for (const dir of [layout.configDir, layout.skillsDir, layout.workAgentDir, layout.homeDir, layout.tmpDir]) {
202
+ layout.skillsDir = path.join(layout.workDir, '.claude', 'skills');
203
+ for (const dir of [layout.configDir, layout.workDir, layout.homeDir, layout.tmpDir]) {
114
204
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
115
205
  }
206
+ if (workAgentHome) {
207
+ fs.symlinkSync(path.resolve(workAgentHome), path.join(layout.homeDir, '.work-agent'));
208
+ }
116
209
  return layout;
117
210
  }
118
211
 
212
+ /**
213
+ * Creates the program's persistent WORK_AGENT_HOME: `logs/ tmp/ docs/` for the
214
+ * Skills to write, and `ascend-repos` pointing at the shared knowledge pool
215
+ * (work-agent's own documented way of putting the pool on another disk). The
216
+ * pool stays outside this directory, so a job cannot delete it.
217
+ */
218
+ export function prepareWorkAgentHome(workAgentHome, poolDir = '') {
219
+ for (const name of ['logs', 'tmp', 'docs']) {
220
+ fs.mkdirSync(path.join(workAgentHome, name), { recursive: true, mode: 0o700 });
221
+ }
222
+ const link = path.join(workAgentHome, 'ascend-repos');
223
+ if (!poolDir) return '';
224
+ let real;
225
+ try {
226
+ real = fs.realpathSync(poolDir);
227
+ } catch {
228
+ return '';
229
+ }
230
+ let current = '';
231
+ try {
232
+ current = fs.readlinkSync(link);
233
+ } catch {
234
+ // Not a symlink, or missing.
235
+ }
236
+ if (current !== real) {
237
+ if (current) fs.rmSync(link, { force: true });
238
+ try {
239
+ fs.symlinkSync(real, link);
240
+ } catch (error) {
241
+ // A real directory there (someone cloned into it): leave it alone.
242
+ if (error.code !== 'EEXIST') throw error;
243
+ }
244
+ }
245
+ return real;
246
+ }
247
+
119
248
  // Variables passed through to claude (and written into the background
120
249
  // service): proxies, CA bundles, language and time zone. Nothing else from
121
250
  // this machine's environment reaches a job.
package/lib/service.mjs CHANGED
@@ -23,10 +23,16 @@ export function serviceExitCode(code, env = process.env) {
23
23
  return code === EXIT_NEEDS_ATTENTION && env.GC_RUNNER_SERVICE === 'launchd' ? 0 : code;
24
24
  }
25
25
 
26
- /** PATH, the pass-through variables that are set, NODE_USE_ENV_PROXY with a proxy, and the service marker. */
26
+ /**
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.
31
+ */
27
32
  export function serviceEnvironment(env, kind) {
28
33
  const out = { PATH: env.PATH || '/usr/local/bin:/usr/bin:/bin' };
29
34
  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;
30
36
  if (PROXY_VARIABLES.some((name) => env[name] && !/^no_proxy$/i.test(name))) out.NODE_USE_ENV_PROXY = '1';
31
37
  out.GC_RUNNER_SERVICE = kind;
32
38
  return out;
package/lib/setup.mjs CHANGED
@@ -35,6 +35,8 @@ export function npmPrefixWritable(prefix) {
35
35
  /**
36
36
  * The install plan (pure; tested with fake inputs):
37
37
  * requiredTools from the website (or DEFAULT_REQUIRED_TOOLS without a token)
38
+ * extraTools what this machine wants regardless of the website (rg for
39
+ * the knowledge pool); must also be in SKILL_TOOLS
38
40
  * tools doctor's { [name]: { ok } }
39
41
  * claudeVersion '' when missing
40
42
  * manager 'apt' | … | 'brew' | ''
@@ -45,6 +47,7 @@ export function npmPrefixWritable(prefix) {
45
47
  export function planSetup({
46
48
  platform,
47
49
  requiredTools = DEFAULT_REQUIRED_TOOLS,
50
+ extraTools = [],
48
51
  tools,
49
52
  claudeVersion = '',
50
53
  minClaudeVersion = '',
@@ -55,7 +58,7 @@ export function planSetup({
55
58
  npmWritable = false,
56
59
  }) {
57
60
  const ignored = requiredTools.filter((name) => !SKILL_TOOLS.includes(name));
58
- const wanted = SKILL_TOOLS.filter((name) => requiredTools.includes(name));
61
+ const wanted = SKILL_TOOLS.filter((name) => requiredTools.includes(name) || extraTools.includes(name));
59
62
  if (platform === 'linux') wanted.push(...SANDBOX_TOOLS);
60
63
  const missing = wanted.filter((name) => !tools?.[name]?.ok);
61
64
  const notes = [];
@@ -1,6 +1,6 @@
1
1
  // How Skill text files are rewritten for a run, shared by the website
2
- // (lib/skill-bundle.js for server runs, lib/skill-manifest.js for the files
3
- // sent to execution machines) and the machine program (lib/skills.mjs).
2
+ // (lib/skill-bundle.js, server runs) and the machine program
3
+ // (lib/work-agent.mjs), through lib/skill-tree.mjs.
4
4
  //
5
5
  // Only node: built-ins and files in this directory may be imported here, and
6
6
  // importing must have no side effects.
@@ -0,0 +1,100 @@
1
+ // Reading a Skill tree and copying it into a run, shared by the website
2
+ // (lib/skill-bundle.js, for server runs) and the execution machine program
3
+ // (lib/work-agent.mjs, for jobs). One implementation, so a job's Skill copy is
4
+ // byte for byte what a server run gets from the same source.
5
+ //
6
+ // Only node: built-ins and files in this directory may be imported here, and
7
+ // importing must have no side effects.
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+
12
+ import { isSkillTextFile, renameTokenVariable, rewriteWorkAgentPath } from './skill-text.mjs';
13
+
14
+ // Far above the real tree (work-agent f0588e8: 102 files, 2.4 MB, largest 1 MB).
15
+ // They are here to stop a source that is not what we think it is — a clone
16
+ // made with submodule.recurse=true pulls ~1 GB into the Skill tree.
17
+ export const MAX_FILES = 10_000;
18
+ export const MAX_FILE_BYTES = 100 * 1024 * 1024;
19
+ export const MAX_TOTAL_BYTES = 512 * 1024 * 1024;
20
+
21
+ /**
22
+ * Visits a Skill tree the way every consumer (server run copies, a machine's
23
+ * run copies) must see it:
24
+ * - symlinks are followed and reported as what they point to (dangling ones are skipped)
25
+ * - `.git` entries (nested submodule pointers into the source .git) are skipped
26
+ * - sockets / fifos / devices are skipped
27
+ * - a directory reached again through a symlink loop is not entered twice
28
+ * `onFile(relPath, absPath, stats)` gets every regular file; `onDir(relPath,
29
+ * absPath)` every directory ('' is the root) before its contents. Relative
30
+ * paths use '/'.
31
+ */
32
+ export function walkSkillTree(sourceDir, onFile, onDir = () => {}) {
33
+ const seen = new Set();
34
+ const walk = (dir, rel) => {
35
+ const real = fs.realpathSync(dir);
36
+ if (seen.has(real)) return; // symlink loop
37
+ seen.add(real);
38
+ onDir(rel, dir);
39
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
40
+ if (entry.name === '.git') continue;
41
+ const from = path.join(dir, entry.name);
42
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
43
+ let stats;
44
+ try {
45
+ stats = fs.statSync(from); // follows symlinks
46
+ } catch {
47
+ continue; // dangling symlink
48
+ }
49
+ if (stats.isDirectory()) walk(from, childRel);
50
+ else if (stats.isFile()) onFile(childRel, from, stats);
51
+ }
52
+ seen.delete(real);
53
+ };
54
+ walk(sourceDir, '');
55
+ }
56
+
57
+ /**
58
+ * Copies `source` into `target` as plain files and directories only (0700 /
59
+ * 0600), so the run copy can never write back into the source repository (see
60
+ * walkSkillTree for what is followed and skipped). The directory layout is
61
+ * preserved, so relative references between Skills (`../gitcode-toolkit/...`)
62
+ * keep working. Throws when the tree is larger than the limits above.
63
+ */
64
+ export function copyTreeDetached(source, target, limits = {}) {
65
+ const maxFiles = limits.maxFiles ?? MAX_FILES;
66
+ const maxFileBytes = limits.maxFileBytes ?? MAX_FILE_BYTES;
67
+ const maxTotalBytes = limits.maxTotalBytes ?? MAX_TOTAL_BYTES;
68
+ let files = 0;
69
+ let bytes = 0;
70
+ walkSkillTree(
71
+ source,
72
+ (rel, from, stats) => {
73
+ files += 1;
74
+ bytes += stats.size;
75
+ if (files > maxFiles) throw new Error(`Skill 文件过多(超过 ${maxFiles} 个):${source} 可能不是 Skill 目录`);
76
+ if (stats.size > maxFileBytes) throw new Error(`Skill 文件过大:${rel}`);
77
+ if (bytes > maxTotalBytes) throw new Error(`Skill 目录过大(超过 ${Math.round(maxTotalBytes / 1048576)} MB):${source} 可能不是 Skill 目录`);
78
+ const to = path.join(target, rel);
79
+ fs.copyFileSync(from, to);
80
+ fs.chmodSync(to, (stats.mode & 0o777) | 0o600);
81
+ },
82
+ (rel) => fs.mkdirSync(path.join(target, rel), { recursive: true, mode: 0o700 }),
83
+ );
84
+ return { files, bytes };
85
+ }
86
+
87
+ /** Points `/tmp/work-agent` at the run's scratch dir and renames GITCODE_TOKEN (AGENTS.md 5.1). */
88
+ export function rewriteSkillPaths(directory, replacement) {
89
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
90
+ const target = path.join(directory, entry.name);
91
+ if (entry.isDirectory()) {
92
+ rewriteSkillPaths(target, replacement);
93
+ continue;
94
+ }
95
+ if (!entry.isFile() || !isSkillTextFile(entry.name)) continue;
96
+ const text = fs.readFileSync(target, 'utf8');
97
+ if (!text.includes('/tmp/work-agent') && !text.includes('GITCODE_TOKEN')) continue;
98
+ fs.writeFileSync(target, renameTokenVariable(rewriteWorkAgentPath(text, replacement)));
99
+ }
100
+ }