@koalaauto/agentchannel 3.27.0 → 3.28.0

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.
@@ -29,6 +29,18 @@ export interface ClaudePermInput {
29
29
  achHome?: string;
30
30
  /** P2: hub `net_allow` of the agent; see sandboxNetwork(). */
31
31
  netAllow?: string[];
32
+ /** program paths (default: systemPaths() of this machine) */
33
+ systemRoots?: string[];
34
+ /** data inside the program paths, denied (default: systemPaths().deny) */
35
+ systemDeny?: string[];
36
+ /** what is not readable unless granted (default: systemPaths().hide: Linux `/`, macOS the places people's data is) */
37
+ hide?: string[];
38
+ /** macOS: patterns programs must write in the user's temp folder (default: macTempPatterns()) */
39
+ tempPatterns?: string[];
40
+ /** the run's private TMPDIR: writable (Claude Code keeps its sandbox's network bridge there) */
41
+ tmpDir?: string;
42
+ /** tests: take the roots as given (no real-path lookup on this machine) */
43
+ exists?: boolean;
32
44
  }
33
45
  /**
34
46
  * P2: sandbox network policy. The hub host is always reachable (the agent's
@@ -1,5 +1,6 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { toolDenied } from './paths.js';
3
+ import { macTempPatterns, readable, systemPaths } from './scope.js';
3
4
  import { spawnGroup } from './procgroup.js';
4
5
  /** Best-effort Bash deny list for `workdir` (the SDK sandbox is the real boundary). */
5
6
  export const BASH_DENY = [
@@ -106,12 +107,19 @@ export function claudePermOptions(perm, o) {
106
107
  if (perm === 'full') {
107
108
  return { ...base, permissionMode: 'bypassPermissions', allowDangerouslySkipPermissions: true };
108
109
  }
110
+ const sys = o.systemRoots && o.systemDeny && o.hide ? undefined : systemPaths();
111
+ const hide = o.hide ?? sys.hide;
112
+ const tempPatterns = o.tempPatterns ?? macTempPatterns();
113
+ const systemRoots = o.systemRoots ?? sys.read;
114
+ const systemDeny = o.systemDeny ?? sys.deny;
109
115
  const pol = {
110
116
  home,
111
117
  cwd: o.cwd,
112
- readRoots: o.readRoots ?? [],
118
+ readRoots: [...(o.readRoots ?? []), ...(o.tmpDir ? [o.tmpDir] : [])],
119
+ systemRoots,
120
+ hide,
113
121
  writeRoots: perm === 'workdir' ? [o.cwd] : [],
114
- deny: denyRead,
122
+ deny: [...denyRead, ...systemDeny],
115
123
  secretFiles: o.mode === 'mention' || o.mode === 'answer',
116
124
  };
117
125
  const hubHost = hostOf(o.hub);
@@ -120,10 +128,15 @@ export function claudePermOptions(perm, o) {
120
128
  // read: only the pre-approved `ach` commands may run, sandboxed or not.
121
129
  autoAllowBashIfSandboxed: perm === 'workdir',
122
130
  allowUnsandboxedCommands: false,
131
+ // scope.ts: nothing is readable but the task directory, what the task brings, the toolchain and program paths
132
+ // (allowRead wins over denyRead; live-tested on Linux)
123
133
  filesystem: {
124
- allowWrite: perm === 'workdir' ? [o.cwd] : [],
125
- denyRead: [home, ...(o.achHome ? [o.achHome] : []), ...denyRead],
126
- allowRead: [o.cwd, ...(o.readRoots ?? [])],
134
+ // by real path: macOS checks where a path really is (/var/folders is /private/var/folders), and a write under the
135
+ // link's spelling was refused (live test)
136
+ allowWrite: [...(o.exists ? (x) => x : readable)([...(perm === 'workdir' ? [o.cwd] : []), ...(o.tmpDir ? [o.tmpDir] : [])]), ...tempPatterns],
137
+ // a deny more specific than an allow stays denied (Homebrew's var inside /opt/homebrew)
138
+ denyRead: [...hide, ...systemDeny, ...denyRead],
139
+ allowRead: [...(o.exists ? (x) => x : readable)([o.cwd, ...(o.readRoots ?? []), ...(o.tmpDir ? [o.tmpDir] : []), ...systemRoots]), ...tempPatterns],
127
140
  },
128
141
  network: sandboxNetwork(hubHost, o.netAllow),
129
142
  };
@@ -224,6 +237,7 @@ export class ClaudeAdapter {
224
237
  denyReadPaths: opts.denyReadPaths,
225
238
  home: opts.realHome ?? opts.env.HOME,
226
239
  achHome: opts.achHome,
240
+ tmpDir: opts.tmpDir,
227
241
  netAllow: opts.netAllow,
228
242
  }),
229
243
  spawnClaudeCodeProcess: (s) => spawnGroup(s.command, s.args, {
@@ -10,12 +10,13 @@ export interface PriceTable {
10
10
  export declare const DEFAULT_CODEX_PRICE: PriceTable;
11
11
  export declare function priceFromEnv(env?: Record<string, string | undefined>): PriceTable;
12
12
  export declare function estimateCost(u: Partial<Usage>, p: PriceTable): number;
13
- export declare function codexSandbox(perm: Perm): SandboxMode;
13
+ /** Only `perm=full` (hub and runner flag both say full) runs Codex without its sandbox. */
14
+ export declare function codexSandbox(perm: Perm): SandboxMode | undefined;
14
15
  /**
15
16
  * Thread options (§14.3 as amended by round 1). Pure, unit-tested.
16
- * - Answer runs: read-only sandbox, network off. The agent returns JSON
17
- * (outputSchema) and the runner posts it, so it never needs the hub (S4).
18
- * - Work runs keep network on for `ach`.
17
+ * - Sandboxed runs (every run but a `perm=full` work run) set no sandboxMode:
18
+ * `--sandbox` makes Codex ignore permission profiles, and the sandbox is the
19
+ * runner's profile (codexSandboxOverrides).
19
20
  * - No additionalDirectories: the main repo's .git is never writable (S10);
20
21
  * the runner commits after the run.
21
22
  */
@@ -23,25 +24,51 @@ export declare function codexThreadOptions(perm: Perm, cwd: string, model?: stri
23
24
  /** Codex `--config` overrides set by the runner (key names checked against the bundled codex 0.165 binary). */
24
25
  export type CodexRunnerConfig = {
25
26
  allow_login_shell: boolean;
26
- sandbox_workspace_write: {
27
- exclude_slash_tmp: boolean;
28
- exclude_tmpdir_env_var: boolean;
29
- };
30
27
  };
28
+ /** The permission profile the runner defines for its runs (a name the user's own config does not use). */
29
+ export declare const CODEX_PROFILE = "agentchannel";
30
+ export interface CodexSandboxInput {
31
+ perm: Perm;
32
+ mode?: 'work' | 'answer' | 'mention';
33
+ cwd: string;
34
+ /** readable besides cwd: the toolchain, the git common dir, the ach shim, the task's attachments and linked repos */
35
+ readRoots?: string[];
36
+ /** program paths (default: systemPaths() of this machine), on top of Codex's own `:minimal` */
37
+ systemRoots?: string[];
38
+ /** data inside the program paths, denied (default: systemPaths().deny); a more specific path wins in Codex */
39
+ systemDeny?: string[];
40
+ hub?: string;
41
+ /** the agent's hub `net_allow` ("*" = any host); the hub host is always allowed */
42
+ netAllow?: string[];
43
+ /** the run's private TMPDIR: writable */
44
+ tmpDir?: string;
45
+ /** tests: take the roots as given (no real-path or existence lookup on this machine) */
46
+ exists?: boolean;
47
+ }
48
+ /**
49
+ * The sandbox of every run but a `perm=full` work run, as Codex `--config` overrides: a permission profile (Codex >= 0.138)
50
+ * matching what Claude runs get (claudePermOptions; the levels are in scope.ts). Live-tested with codex 0.165 on Linux.
51
+ * - Files: nothing is readable but cwd, the read roots, the program paths and Codex's own `:minimal` set (only those are
52
+ * granted; a granted path's parents show as empty folders). Writes: cwd only (`workdir` work runs), else nothing.
53
+ * Roots are granted by real path and only when there: bubblewrap does not start over a missing path or a link.
54
+ * - Network: answer and mention runs have none. Work runs reach the hub and the agent's `net_allow` only, through Codex's
55
+ * own proxy (features.network_proxy): direct connections fail, and `ach` uses the proxy (netproxy.ts).
56
+ * The user's Codex config is not read (the run's CODEX_HOME is the runner's), so no `sandbox_mode` there switches this off.
57
+ */
58
+ export declare function codexSandboxOverrides(o: CodexSandboxInput): string[];
31
59
  /**
32
60
  * Codex client options.
33
61
  * - allow_login_shell=false: by default Codex runs tool commands in a login
34
62
  * shell, whose profile (path_helper, `brew shellenv`) reorders PATH, so a
35
63
  * globally installed `ach` (another program's) shadowed the runner's
36
64
  * <home>/bin/ach shim and every `ach complete` failed (live test).
37
- * - sandbox_workspace_write.exclude_slash_tmp / exclude_tmpdir_env_var = true:
38
- * in workspace-write, Codex by default also lets the agent write /tmp and
39
- * $TMPDIR, which other processes of the user read (live test). Writes are now
40
- * the working directory only.
65
+ * - configOverrides: the run's sandbox (codexSandboxOverrides), passed as raw
66
+ * `--config` lines because the SDK does not quote path keys.
41
67
  */
42
- export declare function codexClientOptions(env: Record<string, string | undefined>): {
68
+ export declare function codexClientOptions(env: Record<string, string | undefined>, sandbox?: string[]): {
43
69
  env: Record<string, string>;
44
70
  config: CodexRunnerConfig;
71
+ configOverrides: string[];
45
72
  };
46
73
  /** `root` and all its descendants, from `ps -axo pid=,ppid=,command=` output. Pure. */
47
74
  export declare function processTree(psOut: string, root: number): number[];
@@ -1,4 +1,5 @@
1
1
  import { execFileSync } from 'node:child_process';
2
+ import { readable, systemPaths } from './scope.js';
2
3
  import { KILL_GRACE_MS } from './procgroup.js';
3
4
  export const DEFAULT_CODEX_PRICE = { input: 1.25, cached_input: 0.125, output: 10 };
4
5
  export function priceFromEnv(env = process.env) {
@@ -17,52 +18,104 @@ export function estimateCost(u, p) {
17
18
  const output = (u.output_tokens ?? 0) + (u.reasoning_output_tokens ?? 0);
18
19
  return (input * p.input + cached * p.cached_input + output * p.output) / 1_000_000;
19
20
  }
21
+ /** Only `perm=full` (hub and runner flag both say full) runs Codex without its sandbox. */
20
22
  export function codexSandbox(perm) {
21
- return perm === 'read' ? 'read-only' : perm === 'workdir' ? 'workspace-write' : 'danger-full-access';
23
+ return perm === 'full' ? 'danger-full-access' : undefined;
22
24
  }
23
25
  /**
24
26
  * Thread options (§14.3 as amended by round 1). Pure, unit-tested.
25
- * - Answer runs: read-only sandbox, network off. The agent returns JSON
26
- * (outputSchema) and the runner posts it, so it never needs the hub (S4).
27
- * - Work runs keep network on for `ach`.
27
+ * - Sandboxed runs (every run but a `perm=full` work run) set no sandboxMode:
28
+ * `--sandbox` makes Codex ignore permission profiles, and the sandbox is the
29
+ * runner's profile (codexSandboxOverrides).
28
30
  * - No additionalDirectories: the main repo's .git is never writable (S10);
29
31
  * the runner commits after the run.
30
32
  */
31
33
  export function codexThreadOptions(perm, cwd, model, mode = 'work') {
32
- // answer and mention runs are read-only and offline; the runner posts their JSON
33
- const answer = mode === 'answer' || mode === 'mention';
34
+ const full = mode === 'work' ? codexSandbox(perm) : undefined;
34
35
  return {
35
36
  workingDirectory: cwd,
36
- sandboxMode: answer ? 'read-only' : codexSandbox(perm),
37
- networkAccessEnabled: !answer,
37
+ ...(full ? { sandboxMode: full, networkAccessEnabled: true } : {}),
38
38
  approvalPolicy: 'never',
39
39
  skipGitRepoCheck: true,
40
40
  ...(model ? { model } : {}),
41
41
  };
42
42
  }
43
+ /** The permission profile the runner defines for its runs (a name the user's own config does not use). */
44
+ export const CODEX_PROFILE = 'agentchannel';
45
+ function hostOf(url) {
46
+ try {
47
+ return url ? new URL(url).hostname.replace(/^\[|\]$/g, '').toLowerCase() : undefined;
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ }
53
+ /** A TOML inline table of string values; keys and values are quoted (paths hold `/`, `.`, `:`). */
54
+ function inlineTable(t) {
55
+ const v = (x) => (typeof x === 'string' ? JSON.stringify(x) : inlineTable(x));
56
+ return `{${Object.entries(t)
57
+ .map(([k, x]) => `${JSON.stringify(k)} = ${v(x)}`)
58
+ .join(', ')}}`;
59
+ }
60
+ /**
61
+ * The sandbox of every run but a `perm=full` work run, as Codex `--config` overrides: a permission profile (Codex >= 0.138)
62
+ * matching what Claude runs get (claudePermOptions; the levels are in scope.ts). Live-tested with codex 0.165 on Linux.
63
+ * - Files: nothing is readable but cwd, the read roots, the program paths and Codex's own `:minimal` set (only those are
64
+ * granted; a granted path's parents show as empty folders). Writes: cwd only (`workdir` work runs), else nothing.
65
+ * Roots are granted by real path and only when there: bubblewrap does not start over a missing path or a link.
66
+ * - Network: answer and mention runs have none. Work runs reach the hub and the agent's `net_allow` only, through Codex's
67
+ * own proxy (features.network_proxy): direct connections fail, and `ach` uses the proxy (netproxy.ts).
68
+ * The user's Codex config is not read (the run's CODEX_HOME is the runner's), so no `sandbox_mode` there switches this off.
69
+ */
70
+ export function codexSandboxOverrides(o) {
71
+ const work = (o.mode ?? 'work') === 'work';
72
+ const write = work && o.perm === 'workdir';
73
+ const sys = o.systemRoots && o.systemDeny ? undefined : systemPaths();
74
+ const roots = [...(o.readRoots ?? []), ...(o.systemRoots ?? sys.read)];
75
+ const fs = { ':minimal': 'read' };
76
+ for (const r of o.exists ? roots : readable(roots))
77
+ fs[r] = 'read';
78
+ for (const r of o.systemDeny ?? sys.deny)
79
+ fs[r] = 'deny';
80
+ for (const r of o.tmpDir ? (o.exists ? [o.tmpDir] : readable([o.tmpDir])) : [])
81
+ fs[r] = 'write';
82
+ fs[':workspace_roots'] = { '.': write ? 'write' : 'read' };
83
+ const p = `permissions.${CODEX_PROFILE}`;
84
+ const out = [`default_permissions=${JSON.stringify(CODEX_PROFILE)}`, `${p}.filesystem=${inlineTable(fs)}`];
85
+ if (!work)
86
+ return [...out, `${p}.network.enabled=false`];
87
+ const hub = hostOf(o.hub);
88
+ const list = (o.netAllow ?? []).map((d) => d.trim().toLowerCase()).filter(Boolean);
89
+ const domains = {};
90
+ if (list.includes('*'))
91
+ domains['*'] = 'allow';
92
+ else
93
+ for (const d of [...(hub ? [hub] : []), ...list])
94
+ domains[d] = 'allow';
95
+ return [
96
+ ...out,
97
+ `${p}.network.enabled=true`,
98
+ `${p}.network.domains=${inlineTable(domains)}`,
99
+ // a machine that reaches the internet through HTTP(S)_PROXY: Codex's proxy forwards to it
100
+ `${p}.network.allow_upstream_proxy=true`,
101
+ 'features.network_proxy=true',
102
+ ];
103
+ }
43
104
  /**
44
105
  * Codex client options.
45
106
  * - allow_login_shell=false: by default Codex runs tool commands in a login
46
107
  * shell, whose profile (path_helper, `brew shellenv`) reorders PATH, so a
47
108
  * globally installed `ach` (another program's) shadowed the runner's
48
109
  * <home>/bin/ach shim and every `ach complete` failed (live test).
49
- * - sandbox_workspace_write.exclude_slash_tmp / exclude_tmpdir_env_var = true:
50
- * in workspace-write, Codex by default also lets the agent write /tmp and
51
- * $TMPDIR, which other processes of the user read (live test). Writes are now
52
- * the working directory only.
110
+ * - configOverrides: the run's sandbox (codexSandboxOverrides), passed as raw
111
+ * `--config` lines because the SDK does not quote path keys.
53
112
  */
54
- export function codexClientOptions(env) {
113
+ export function codexClientOptions(env, sandbox = []) {
55
114
  const clean = {};
56
115
  for (const [k, v] of Object.entries(env))
57
116
  if (typeof v === 'string')
58
117
  clean[k] = v;
59
- return {
60
- env: clean,
61
- config: {
62
- allow_login_shell: false,
63
- sandbox_workspace_write: { exclude_slash_tmp: true, exclude_tmpdir_env_var: true },
64
- },
65
- };
118
+ return { env: clean, config: { allow_login_shell: false }, configOverrides: sandbox };
66
119
  }
67
120
  /** `root` and all its descendants, from `ps -axo pid=,ppid=,command=` output. Pure. */
68
121
  export function processTree(psOut, root) {
@@ -177,8 +230,19 @@ export class CodexAdapter {
177
230
  }
178
231
  async run(opts) {
179
232
  const { Codex } = await import('@openai/codex-sdk');
180
- const codex = new Codex(codexClientOptions(opts.env));
181
233
  const to = codexThreadOptions(opts.perm, opts.cwd, this.o.model, opts.mode);
234
+ const sandbox = to.sandboxMode
235
+ ? []
236
+ : codexSandboxOverrides({
237
+ perm: opts.perm,
238
+ mode: opts.mode,
239
+ cwd: opts.cwd,
240
+ readRoots: opts.readRoots,
241
+ tmpDir: opts.tmpDir,
242
+ hub: opts.hub,
243
+ netAllow: opts.netAllow,
244
+ });
245
+ const codex = new Codex(codexClientOptions(opts.env, sandbox));
182
246
  const thread = opts.resume ? codex.resumeThread(opts.resume, to) : codex.startThread(to);
183
247
  const price = this.o.price ?? priceFromEnv(opts.env);
184
248
  let sessionId = opts.resume;
@@ -16,16 +16,20 @@ export declare function packageRoot(): string;
16
16
  */
17
17
  export declare function dependencyRoots(from?: string): string[];
18
18
  /**
19
- * Paths under $HOME a spawned agent may read besides its cwd (S4): the node
20
- * install, npm and git config, and this package (the `ach` CLI). The git
21
- * common dir of the worktree is added by the caller.
19
+ * Toolchain paths a spawned agent may read besides its cwd and the system paths (S4): the node install, git config, the npm
20
+ * cache, and this package (the `ach` CLI, with the Codex binary among its dependencies). Not ~/.npmrc: it holds registry
21
+ * tokens. The git common dir of the worktree is added by the caller.
22
22
  */
23
23
  export declare function toolchainReadRoots(home?: string): string[];
24
24
  export interface PathPolicy {
25
25
  home: string;
26
26
  cwd: string;
27
- /** Readable roots under $HOME besides cwd. */
27
+ /** Readable besides cwd: the toolchain, the git common dir, the task's attachments and linked repos. */
28
28
  readRoots: string[];
29
+ /** Where programs live (systemPaths().read): readable too. */
30
+ systemRoots?: string[];
31
+ /** What is not readable unless granted (systemPaths().hide; default `/`: nothing but the granted paths). */
32
+ hide?: string[];
29
33
  /** Writable roots (empty = read-only). */
30
34
  writeRoots: string[];
31
35
  /** Never readable or writable, even inside an allowed root. */
@@ -66,21 +66,13 @@ export function dependencyRoots(from = packageRoot()) {
66
66
  return out;
67
67
  }
68
68
  /**
69
- * Paths under $HOME a spawned agent may read besides its cwd (S4): the node
70
- * install, npm and git config, and this package (the `ach` CLI). The git
71
- * common dir of the worktree is added by the caller.
69
+ * Toolchain paths a spawned agent may read besides its cwd and the system paths (S4): the node install, git config, the npm
70
+ * cache, and this package (the `ach` CLI, with the Codex binary among its dependencies). Not ~/.npmrc: it holds registry
71
+ * tokens. The git common dir of the worktree is added by the caller.
72
72
  */
73
73
  export function toolchainReadRoots(home = homedir()) {
74
74
  const nodePrefix = realish(resolve(dirname(process.execPath), '..'));
75
- return [
76
- nodePrefix,
77
- packageRoot(),
78
- ...dependencyRoots(),
79
- join(home, '.gitconfig'),
80
- join(home, '.config', 'git'),
81
- join(home, '.npmrc'),
82
- join(home, '.npm'),
83
- ];
75
+ return [nodePrefix, packageRoot(), ...dependencyRoots(), join(home, '.gitconfig'), join(home, '.config', 'git'), join(home, '.npm')];
84
76
  }
85
77
  /** Undefined = allowed, else the reason for denying a read of p. */
86
78
  export function readDenied(pol, p) {
@@ -89,11 +81,11 @@ export function readDenied(pol, p) {
89
81
  return `${p} is a protected AgentChannel file`;
90
82
  if (pol.secretFiles && isSecretFile(abs))
91
83
  return `${p} holds secrets by convention: a read-only reply does not read it`;
92
- if (!isInside(pol.home, abs))
84
+ if ([pol.cwd, ...pol.readRoots, ...(pol.systemRoots ?? [])].some((r) => isInside(r, abs)))
93
85
  return undefined;
94
- if ([pol.cwd, ...pol.readRoots].some((r) => isInside(r, abs)))
86
+ if (!(pol.hide ?? ['/']).some((h) => isInside(h, abs)))
95
87
  return undefined;
96
- return `reads under ${pol.home} are limited to the task directory and toolchain paths`;
88
+ return `reads are limited to the task directory, what the task brings (attachments, linked repos) and program paths`;
97
89
  }
98
90
  export function writeDenied(pol, p) {
99
91
  const abs = resolve(pol.cwd, p);
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The three permission levels, the same for Claude and Codex runs:
3
+ * - read: reads the task directory (and what the task brings: its attachments, the other repos it names) plus the system
4
+ * and toolchain paths programs need to run; writes nothing but its own TMPDIR; reaches the hub and the agent's
5
+ * `net_allow` only.
6
+ * - workdir: the same, and writes the task directory.
7
+ * - full: no sandbox at all (admin only, and the runner must be started with --perm full too).
8
+ * Answer and mention runs are always `read`, with no network.
9
+ * Nothing else is readable: not the home, not other projects on the machine, not the runner's own files.
10
+ */
11
+ export interface SystemPaths {
12
+ /**
13
+ * What a Claude run may not read unless granted (cwd, the read roots, `read`): Linux all of `/`; macOS the places that hold
14
+ * people's data. On macOS denying `/` also hides the links /var, /tmp and /etc, so xcode-select (git, python3) and curl's
15
+ * certificates (/etc/ssl) stop working (live test, macOS 26); the regions are what srt documents for macOS.
16
+ */
17
+ hide: string[];
18
+ /** where programs, their libraries and the system's configuration live */
19
+ read: string[];
20
+ /** inside `read`, but data, not programs (Homebrew's databases and logs): denied */
21
+ deny: string[];
22
+ }
23
+ /**
24
+ * Where programs live, readable in `read` and `workdir` so `git`, `node` or `sh` run at all: program files and system
25
+ * configuration (TLS certificates, users, git's system config), not a person's data. Only paths that are there (bubblewrap
26
+ * does not start over a missing one).
27
+ * - Linux: live-tested with Claude Code and Codex 0.165.
28
+ * - macOS: /System (the dyld cache, frameworks), the developer tools git runs through (xcode-select), Homebrew without its
29
+ * var (databases, logs), /dev. The whole /Library is not: it holds other programs' data.
30
+ */
31
+ export declare function systemPaths(platform?: NodeJS.Platform, exists?: (p: string) => boolean): SystemPaths;
32
+ /**
33
+ * macOS: what programs write in the user's temporary folder (getconf DARWIN_USER_TEMP_DIR) whatever TMPDIR says: xcrun, which
34
+ * runs git and python3, keeps its lookup cache there (`xcrun_db-*`; live test, macOS 26: "couldn't create cache file"). Only
35
+ * those names, as patterns (srt matches them on macOS); the folder itself, other programs' files, stays hidden. By real path.
36
+ */
37
+ export declare function macTempPatterns(platform?: NodeJS.Platform, userTemp?: () => string): string[];
38
+ /**
39
+ * macOS: the developer tools' own directory (`xcode-select -p`). /usr/bin/git and /usr/bin/python3 are shims that ask xcrun
40
+ * where the real tool is, and xcrun writes a cache and runs xcodebuild, which a sandbox refuses (notices on stderr in every
41
+ * command; live test, macOS 26). The real binaries in <dir>/usr/bin run clean, so agents get that directory on PATH.
42
+ * Undefined elsewhere, or when the tools are not installed.
43
+ */
44
+ export declare function developerDir(platform?: NodeJS.Platform, run?: () => string, exists?: (p: string) => boolean): string | undefined;
45
+ /** The readable program paths of this machine (systemPaths().read). */
46
+ export declare function systemReadRoots(platform?: NodeJS.Platform, exists?: (p: string) => boolean): string[];
47
+ /** Each root by its real path (a sandbox binds what a link points to; binding the link itself can stop it starting), only those that are there; no repeats. */
48
+ export declare function readable(roots: string[], exists?: (p: string) => boolean): string[];
@@ -0,0 +1,76 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { realish } from './paths.js';
4
+ /**
5
+ * Where programs live, readable in `read` and `workdir` so `git`, `node` or `sh` run at all: program files and system
6
+ * configuration (TLS certificates, users, git's system config), not a person's data. Only paths that are there (bubblewrap
7
+ * does not start over a missing one).
8
+ * - Linux: live-tested with Claude Code and Codex 0.165.
9
+ * - macOS: /System (the dyld cache, frameworks), the developer tools git runs through (xcode-select), Homebrew without its
10
+ * var (databases, logs), /dev. The whole /Library is not: it holds other programs' data.
11
+ */
12
+ export function systemPaths(platform = process.platform, exists = existsSync) {
13
+ const linux = { hide: ['/'], read: ['/usr', '/bin', '/sbin', '/lib', '/lib32', '/lib64', '/libx32', '/etc'], deny: ['/usr/local/var'] };
14
+ const darwin = {
15
+ // every person's home, other disks, other programs' temporary files and caches, shared temp, optional installs,
16
+ // system-wide program data and keychains
17
+ hide: ['/Users', '/Volumes', '/private/var/folders', '/private/tmp', '/opt', '/Library/Application Support', '/Library/Keychains'],
18
+ read: [
19
+ '/usr', '/bin', '/sbin', '/System', '/dev',
20
+ '/private/etc', '/private/var/db/timezone', '/private/var/select', '/private/var/db/xcode_select_link',
21
+ '/Library/Developer', '/Library/Apple', '/Library/Frameworks', '/Library/Preferences',
22
+ '/Applications/Xcode.app', '/opt/homebrew',
23
+ ],
24
+ deny: ['/usr/local/var', '/opt/homebrew/var'],
25
+ };
26
+ const p = platform === 'darwin' ? darwin : platform === 'linux' ? linux : { hide: [], read: [], deny: [] };
27
+ return { hide: p.hide.filter(exists), read: p.read.filter(exists), deny: p.deny.filter(exists) };
28
+ }
29
+ /**
30
+ * macOS: what programs write in the user's temporary folder (getconf DARWIN_USER_TEMP_DIR) whatever TMPDIR says: xcrun, which
31
+ * runs git and python3, keeps its lookup cache there (`xcrun_db-*`; live test, macOS 26: "couldn't create cache file"). Only
32
+ * those names, as patterns (srt matches them on macOS); the folder itself, other programs' files, stays hidden. By real path.
33
+ */
34
+ export function macTempPatterns(platform = process.platform, userTemp = darwinUserTemp) {
35
+ if (platform !== 'darwin')
36
+ return [];
37
+ const t = userTemp().replace(/\/+$/, '');
38
+ return t ? [`${realish(t)}/xcrun_db*`] : [];
39
+ }
40
+ let userTempCache;
41
+ function darwinUserTemp() {
42
+ if (userTempCache === undefined) {
43
+ try {
44
+ userTempCache = execFileSync('getconf', ['DARWIN_USER_TEMP_DIR'], { encoding: 'utf8', timeout: 5000 }).trim();
45
+ }
46
+ catch {
47
+ userTempCache = '';
48
+ }
49
+ }
50
+ return userTempCache;
51
+ }
52
+ /**
53
+ * macOS: the developer tools' own directory (`xcode-select -p`). /usr/bin/git and /usr/bin/python3 are shims that ask xcrun
54
+ * where the real tool is, and xcrun writes a cache and runs xcodebuild, which a sandbox refuses (notices on stderr in every
55
+ * command; live test, macOS 26). The real binaries in <dir>/usr/bin run clean, so agents get that directory on PATH.
56
+ * Undefined elsewhere, or when the tools are not installed.
57
+ */
58
+ export function developerDir(platform = process.platform, run = () => execFileSync('xcode-select', ['-p'], { encoding: 'utf8', timeout: 5000 }), exists = existsSync) {
59
+ if (platform !== 'darwin')
60
+ return undefined;
61
+ try {
62
+ const d = run().trim();
63
+ return d && exists(`${d}/usr/bin/git`) ? d : undefined;
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ }
69
+ /** The readable program paths of this machine (systemPaths().read). */
70
+ export function systemReadRoots(platform = process.platform, exists = existsSync) {
71
+ return systemPaths(platform, exists).read;
72
+ }
73
+ /** Each root by its real path (a sandbox binds what a link points to; binding the link itself can stop it starting), only those that are there; no repeats. */
74
+ export function readable(roots, exists = existsSync) {
75
+ return Array.from(new Set(roots.map((r) => realish(r)).filter(exists)));
76
+ }
@@ -31,8 +31,10 @@ export interface AdapterRunOptions {
31
31
  achHome?: string;
32
32
  /** Paths the agent must never read (runner config / state with secrets). */
33
33
  denyReadPaths?: string[];
34
- /** Extra paths readable under $HOME besides cwd (toolchain, git common dir). See readRoots(). */
34
+ /** Readable besides cwd and program paths: toolchain, git common dir, attachments, linked repos (see readRoots()). */
35
35
  readRoots?: string[];
36
+ /** The run's private temporary directory (its TMPDIR): readable and writable in the sandbox too. */
37
+ tmpDir?: string;
36
38
  /**
37
39
  * P2: the agent's hub `net_allow` (domains the sandbox may reach; "*" = any).
38
40
  * The hub host is always added. Undefined = hub host + api.anthropic.com only.
package/dist/src/cli.js CHANGED
@@ -4,6 +4,7 @@ import { randomBytes } from 'node:crypto';
4
4
  import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
5
5
  import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
+ import { developerDir } from './adapters/scope.js';
7
8
  import { acquireRunnerLock, RunnerLockedError } from './runner/lock.js';
8
9
  import { helpFor, HELP, parseCli, UsageError } from './args.js';
9
10
  import { channelRef, Client, clientFromConfig, HubError, isZh, NetworkError, parseLinkRepo } from './client.js';
@@ -1616,8 +1617,6 @@ async function runCommand(p, io) {
1616
1617
  // what the permission and the network list do not cover, said where the person starting the runner will read it
1617
1618
  if (perm === 'full')
1618
1619
  io.err('warning: --perm full runs commands with no sandbox (bypassPermissions): anything in a task that reaches the agent can run anything with your rights.');
1619
- if (runtime === 'codex')
1620
- io.err('warning: Codex work runs are not sandboxed like Claude runs: they can read the whole disk and reach any host, whatever --perm and net_allow say. On a shared machine run this under a dedicated OS user.');
1621
1620
  const { makeAdapter } = await import('./adapters/index.js');
1622
1621
  let adapter;
1623
1622
  try {
@@ -1647,7 +1646,10 @@ async function runCommand(p, io) {
1647
1646
  passEnv: (Array.isArray(v['pass-env']) ? v['pass-env'] : []).flatMap(splitList),
1648
1647
  baseEnv: (() => {
1649
1648
  const shim = writeAchShim(home);
1650
- return shim ? { ...env, PATH: `${shim}${delimiter}${env.PATH ?? ''}` } : env;
1649
+ // macOS: the real git and python3 of the developer tools before the /usr/bin shims (scope.ts developerDir)
1650
+ const dev = developerDir();
1651
+ const path = [shim, dev ? `${dev}/usr/bin` : undefined, env.PATH].filter(Boolean).join(delimiter);
1652
+ return shim || dev ? { ...env, PATH: path } : env;
1651
1653
  })(),
1652
1654
  log: io.err,
1653
1655
  sandboxCheck: async () => {
@@ -1655,7 +1657,7 @@ async function runCommand(p, io) {
1655
1657
  if (runtime === 'kiro')
1656
1658
  return (await import('./kirocheck.js')).probeKiro({ env });
1657
1659
  const { probeEnvironment } = await import('./envcheck.js');
1658
- return probeEnvironment(runtime === 'codex' ? 'codex' : 'claude', { env });
1660
+ return probeEnvironment(runtime === 'codex' ? 'codex' : 'claude', { env, hub: cfg.hub });
1659
1661
  },
1660
1662
  });
1661
1663
  io.err(`ach run: agent ${me.name}, runtime ${runtime}, perm min(${me.perm_level}, ${perm}), dir ${dir}` +
@@ -427,6 +427,12 @@ export declare class Client {
427
427
  release(taskId: string, reason: string, run_id?: string): Promise<any>;
428
428
  /** The repo names this runner can work in (never local paths): the directory shows them, and the hub refuses a task for another repo. */
429
429
  reportRepos(repos: string[]): Promise<any>;
430
+ /** How this runner runs tasks: its --perm, the tool, and the NAMES of the variables it hands its agents (never values). */
431
+ reportRunner(r: {
432
+ perm: string;
433
+ runtime: string;
434
+ pass_env: string[];
435
+ }): Promise<any>;
430
436
  reportSetup(sandbox: {
431
437
  tool: string;
432
438
  problem: string;
@@ -375,6 +375,10 @@ export class Client {
375
375
  async reportRepos(repos) {
376
376
  return this.ach('PUT', '/me/repos', { repos });
377
377
  }
378
+ /** How this runner runs tasks: its --perm, the tool, and the NAMES of the variables it hands its agents (never values). */
379
+ async reportRunner(r) {
380
+ return this.ach('PUT', '/me/runner', r);
381
+ }
378
382
  async reportSetup(sandbox) {
379
383
  return this.ach('PUT', '/me/setup', { sandbox });
380
384
  }
@@ -52,6 +52,7 @@ export declare function runDoctor(o: {
52
52
  /** the sandbox probe (tests) */
53
53
  sandbox?: (tool: 'claude' | 'codex', o: {
54
54
  env: NodeJS.ProcessEnv;
55
+ hub?: string;
55
56
  }) => Promise<import('./sandboxcheck.js').SandboxStatus>;
56
57
  /** Tests: the kiro runtime's machine check (kiro-cli and KIRO_API_KEY). */
57
58
  kiro?: (o: {
@@ -313,10 +313,10 @@ export async function runDoctor(o) {
313
313
  const { probeSandbox } = await import('./sandboxcheck.js');
314
314
  const tools = runtime === 'kiro' ? [] : runtime === 'codex' ? ['codex'] : runtime === 'claude' ? ['claude'] : [...(claude ? ['claude'] : []), ...(codexPath || bundled ? ['codex'] : [])];
315
315
  for (const t of tools) {
316
- const st = await (o.sandbox ?? probeSandbox)(t, { env });
316
+ const st = await (o.sandbox ?? probeSandbox)(t, { env, hub: cfg.hub });
317
317
  const name = `${t} sandbox`;
318
318
  if (st.ok)
319
- add(name, st.unverified ? 'info' : 'ok', st.unverified ? `not checked: ${st.detail ?? 'unknown'}` : 'starts, and stops writes outside the task directory');
319
+ add(name, st.unverified ? 'info' : 'ok', st.unverified ? `not checked: ${st.detail ?? 'unknown'}` : `starts, and stops writes outside the task directory${t === 'codex' && cfg.hub ? ', and reaches the hub' : ''}`);
320
320
  else
321
321
  add(name, runtime ? 'fail' : 'warn', `${st.fix?.en ?? st.detail ?? st.problem}${runtime ? ' The background runner takes no tasks until this is fixed.' : ''}`, 'machine', st.fix?.commands.length ? st.fix.commands.join('\n ') : st.fix?.en);
322
322
  }
@@ -54,6 +54,8 @@ export declare function userBin(name: string, env?: NodeJS.ProcessEnv): string |
54
54
  export declare function onPath(name: string, env?: NodeJS.ProcessEnv): boolean;
55
55
  /** This CLI's entry file (dist/src/cli.js). */
56
56
  export declare function thisCliPath(): string;
57
+ /** The CLI a runner shim (writeAchShim in cli.ts) runs, or undefined when `f` is not such a shim. */
58
+ export declare function shimTarget(f: string): string | undefined;
57
59
  /**
58
60
  * Which AgentChannel an `ach` executable is, without running it: follow the
59
61
  * symlink (npm global bins are symlinks) up to the nearest package.json.
@@ -1,4 +1,4 @@
1
- import { accessSync, constants, readFileSync, realpathSync } from 'node:fs';
1
+ import { accessSync, constants, readFileSync, realpathSync, statSync } from 'node:fs';
2
2
  import { delimiter, dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { PKG_NAME, VERSION } from './version.js';
@@ -125,6 +125,22 @@ export function onPath(name, env = process.env) {
125
125
  export function thisCliPath() {
126
126
  return fileURLToPath(new URL('./cli.js', import.meta.url));
127
127
  }
128
+ /** The CLI a runner shim (writeAchShim in cli.ts) runs, or undefined when `f` is not such a shim. */
129
+ export function shimTarget(f) {
130
+ let s;
131
+ try {
132
+ if (statSync(f).size > 4096)
133
+ return undefined; // a shim is one line; never read a large binary
134
+ s = readFileSync(f, 'utf8');
135
+ }
136
+ catch {
137
+ return undefined;
138
+ }
139
+ // `exec '<node>' '<cli.js>' "$@"`, both single-quoted by shq ('\'' for a quote inside)
140
+ const q = `'((?:[^']|'\\\\'')*)'`;
141
+ const m = new RegExp(`^#!/bin/sh\\nexec ${q} ${q} "\\$@"\\n?$`).exec(s);
142
+ return m ? m[2].replace(/'\\''/g, "'") : undefined;
143
+ }
128
144
  function real(p) {
129
145
  try {
130
146
  return realpathSync(p);
@@ -139,7 +155,10 @@ function real(p) {
139
155
  * `ours` = it is this very CLI.
140
156
  */
141
157
  export function identifyAch(path, self = thisCliPath()) {
142
- const r = real(path);
158
+ // the runner's PATH shim (writeAchShim: `exec <node> <cli.js>`) is that CLI: identify its target, not the script
159
+ const sh = real(path);
160
+ const target = sh ? shimTarget(sh) : undefined;
161
+ const r = target ? real(target) : sh;
143
162
  const ours = !!r && r === real(self);
144
163
  let d = r ? dirname(r) : undefined;
145
164
  for (let i = 0; d && i < 6; i++, d = dirname(d)) {
@@ -4,7 +4,7 @@ import { type Perm } from '../perm.js';
4
4
  import { RunnerState } from './state.js';
5
5
  import type { Workspace } from './workspace.js';
6
6
  import { type SandboxStatus } from '../sandboxcheck.js';
7
- export type RunnerClient = Pick<Client, 'me' | 'inbox' | 'claim' | 'getTask' | 'postMessage' | 'complete' | 'fail' | 'usage' | 'heartbeat' | 'answerRun' | 'endRun'> & Partial<Pick<Client, 'download' | 'channelPosts' | 'mentionRun' | 'mentionEnd' | 'mentionUsage' | 'promptSize' | 'reportSetup' | 'reportRepos' | 'release' | 'putTrace'>>;
7
+ export type RunnerClient = Pick<Client, 'me' | 'inbox' | 'claim' | 'getTask' | 'postMessage' | 'complete' | 'fail' | 'usage' | 'heartbeat' | 'answerRun' | 'endRun'> & Partial<Pick<Client, 'download' | 'channelPosts' | 'mentionRun' | 'mentionEnd' | 'mentionUsage' | 'promptSize' | 'reportSetup' | 'reportRepos' | 'reportRunner' | 'release' | 'putTrace'>>;
8
8
  export interface RunnerOptions {
9
9
  client: RunnerClient;
10
10
  adapter: RuntimeAdapter;
@@ -197,6 +197,10 @@ export declare class Runner {
197
197
  private reposReported;
198
198
  private reportRepos;
199
199
  private reposLogged;
200
+ /** Tell the hub how this runner runs tasks (its --perm, the tool, the names it passes with --pass-env), once, so the agent's
201
+ * owner sees on its page what a task sent to it can reach. Tried on every poll until the hub has it; an older hub (404) is left alone. */
202
+ private runnerReported;
203
+ private reportRunner;
200
204
  private notifyBudget;
201
205
  /**
202
206
  * Cancel running jobs whose task went terminal; forget parked runs of
@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { gitCommonDir } from '../adapters/index.js';
6
6
  import { toolchainReadRoots } from '../adapters/paths.js';
7
+ import { developerDir } from '../adapters/scope.js';
7
8
  import { Client as HubClient, HubError, isTerminal } from '../client.js';
8
9
  import { taskFiles } from '../attachments.js';
9
10
  import { buildAgentEnv } from '../env.js';
@@ -152,7 +153,11 @@ export function prepareAgentHome(root, agentName, key, realHome, realCodexHome)
152
153
  const safe = (x) => x.replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 80);
153
154
  const home = join(root, safe(agentName), safe(key));
154
155
  mkdirSync(home, { recursive: true, mode: 0o700 });
155
- const env = { HOME: home };
156
+ // the run's own temporary directory, the one place besides its task directory a sandboxed run writes: tools need one, and
157
+ // Claude Code keeps its sandbox's network bridge there (a sandbox that reads only its own paths cannot reach /tmp)
158
+ const tmp = join(home, 'tmp');
159
+ mkdirSync(tmp, { recursive: true, mode: 0o700 });
160
+ const env = { HOME: home, TMPDIR: tmp };
156
161
  if (!realHome) {
157
162
  env.CODEX_HOME = prepareCodexHome(home, realCodexHome);
158
163
  return { home, env };
@@ -437,6 +442,26 @@ export class Runner {
437
442
  }
438
443
  }
439
444
  reposLogged = false;
445
+ /** Tell the hub how this runner runs tasks (its --perm, the tool, the names it passes with --pass-env), once, so the agent's
446
+ * owner sees on its page what a task sent to it can reach. Tried on every poll until the hub has it; an older hub (404) is left alone. */
447
+ runnerReported = false;
448
+ async reportRunner() {
449
+ if (this.runnerReported || !this.o.client.reportRunner)
450
+ return;
451
+ const runtime = this.o.adapter.name;
452
+ if (runtime !== 'claude' && runtime !== 'codex' && runtime !== 'kiro') {
453
+ this.runnerReported = true;
454
+ return;
455
+ }
456
+ try {
457
+ await this.o.client.reportRunner({ perm: this.o.perm, runtime, pass_env: [...new Set(this.o.passEnv ?? [])] });
458
+ this.runnerReported = true;
459
+ }
460
+ catch (e) {
461
+ if (e instanceof HubError && e.status === 404)
462
+ this.runnerReported = true;
463
+ }
464
+ }
440
465
  async notifyBudget(t, me) {
441
466
  if (this.state.runs.budgetNotified[t.id])
442
467
  return;
@@ -1196,6 +1221,7 @@ export class Runner {
1196
1221
  const home = (this.o.baseEnv ?? process.env).HOME;
1197
1222
  return [
1198
1223
  ...toolchainReadRoots(home || undefined),
1224
+ ...(developerDir() ? [developerDir()] : []),
1199
1225
  ...gitCommonDir(cwd),
1200
1226
  join(this.o.home, 'bin'),
1201
1227
  ...readRepos.flatMap((r) => r.roots),
@@ -1300,7 +1326,10 @@ export class Runner {
1300
1326
  denyReadPaths: secretPaths(this.o.home),
1301
1327
  ...(realHome ? { realHome } : {}),
1302
1328
  achHome: this.o.home,
1303
- readRoots: this.readRoots(rec.workdir, rec.readRepos, rec.taskId),
1329
+ // from the run's scratch HOME only its git identity: the runtime's own config there is for the tool, which runs outside
1330
+ // the sandbox, and a read-only HOME would cover its writable TMPDIR inside it
1331
+ readRoots: [...this.readRoots(rec.workdir, rec.readRepos, rec.taskId), ...(env.HOME ? [join(env.HOME, '.gitconfig')] : [])],
1332
+ ...(env.TMPDIR ? { tmpDir: env.TMPDIR } : {}),
1304
1333
  ...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}),
1305
1334
  // the agent's budget is a cap on the run too, not only a gate on taking the next task (a run that loops stops at what is left)
1306
1335
  ...(Number(me.budget_usd ?? 0) > 0 ? { maxBudgetUsd: Math.max(0.01, Number(me.budget_usd) - Number(me.spent_usd ?? 0)) + ((mode === 'mention' ? undefined : this.state.session(taskId, mode))?.costTotal ?? 0) } : {}),
@@ -1448,6 +1477,7 @@ export class Runner {
1448
1477
  let wait = this.o.intervalMs;
1449
1478
  try {
1450
1479
  await this.reportRepos();
1480
+ await this.reportRunner();
1451
1481
  await this.tick();
1452
1482
  }
1453
1483
  catch (e) {
@@ -24,6 +24,8 @@ export type SandboxProblem =
24
24
  | 'unsupported'
25
25
  /** the tool is not logged in on this machine (envcheck.ts): not the sandbox, but the same "takes no tasks" state */
26
26
  | 'not-logged-in'
27
+ /** Codex's sandbox starts but has no network although the runner asks for it: the agent's `ach` cannot reach the hub (`detail`: the host) */
28
+ | 'no-network'
27
29
  /** anything else: `detail` has the first line of the error */
28
30
  | 'failed';
29
31
  export interface SandboxFix {
@@ -86,9 +88,21 @@ export interface ProbeOptions {
86
88
  home?: string;
87
89
  /** the Codex CLI (default: codexCommand()) */
88
90
  codex?: string[];
91
+ /** the hub URL: when set, a Codex probe also checks that a sandboxed command reaches it (work runs call `ach` from there) */
92
+ hub?: string;
89
93
  }
90
94
  /** Probe `tool`'s sandbox on this machine. Never throws. */
91
95
  export declare function probeSandbox(tool: SandboxTool, o?: ProbeOptions): Promise<SandboxStatus>;
96
+ /**
97
+ * A node one-liner: resolve `host` and open a TCP connection to `port`. Exit 0 connected, 5 the name does not resolve, 6 the
98
+ * connection fails or takes over 8 s. No HTTP: what matters is whether the sandbox lets the agent's `ach` out at all.
99
+ */
100
+ export declare const NET_SCRIPT: string;
101
+ /**
102
+ * NET_SCRIPT through the proxy Codex starts in its sandbox (the only way out there, as for `ach`): CONNECT to `host:port`.
103
+ * Exit 0 the proxy opened the tunnel, 6 it refused or failed, 7 no proxy in the sandbox (Codex's network proxy did not start).
104
+ */
105
+ export declare const NET_PROXY_SCRIPT: string;
92
106
  /** Lets the system bubblewrap (only that path) create user namespaces under Ubuntu's AppArmor rule; never machine-wide. */
93
107
  export declare const BWRAP_APPARMOR: string;
94
108
  /** The fix for a failed probe on this host. */
@@ -1,9 +1,11 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { randomBytes } from 'node:crypto';
3
- import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
4
  import { createRequire } from 'node:module';
5
5
  import { homedir, tmpdir } from 'node:os';
6
6
  import { delimiter, dirname, join } from 'node:path';
7
+ import { codexSandboxOverrides } from './adapters/codex.js';
8
+ import { toolchainReadRoots } from './adapters/paths.js';
7
9
  export const defaultRun = (file, args, opts) => new Promise((res) => {
8
10
  execFile(file, args, { env: opts.env, cwd: opts.cwd, timeout: 20_000, encoding: 'utf8', maxBuffer: 1 << 20 }, (err, stdout, stderr) => {
9
11
  const code = err ? (typeof err.code === 'number' ? err.code : err.code === 'ENOENT' ? 127 : 1) : 0;
@@ -87,9 +89,20 @@ export function classify(stderr, host) {
87
89
  function firstLine(s) {
88
90
  return (s.split('\n').map((l) => l.trim()).find(Boolean) ?? '').slice(0, 200);
89
91
  }
90
- /** The two writes: inside the sandbox's directory (must work) and in the home directory (must be refused). */
92
+ /**
93
+ * The two writes: inside the sandbox's directory (must work) and in the home directory (must be refused). With a third
94
+ * argument (Codex: its runs read only their own directory), reading that file elsewhere must be refused too. With a fourth
95
+ * and fifth (node, and git when installed), they must run inside the sandbox: the program paths it grants are enough.
96
+ */
91
97
  function probeScript() {
92
- return 'touch "$1/ok" || exit 3; if touch "$2" 2>/dev/null; then exit 4; fi; exit 0';
98
+ return ('touch "$1/ok" || exit 3; w=0; if touch "$2" 2>/dev/null; then w=4; fi; if [ -n "$3" ] && cat "$3" >/dev/null 2>&1; then exit 7; fi; ' +
99
+ 'if [ -n "$4" ] && ! "$4" -e 0 >/dev/null 2>&1; then exit 8; fi; if [ -n "$5" ] && ! "$5" --version >/dev/null 2>&1; then exit 9; fi; exit $w');
100
+ }
101
+ /** A Codex home like a worker run's (prepareCodexHome): the user's own config.toml is not read, so it cannot switch the profile off. */
102
+ function probeCodexHome() {
103
+ const d = mkdtempSync(join(tmpdir(), 'ach-sandbox-codex-'));
104
+ writeFileSync(join(d, 'config.toml'), '');
105
+ return d;
93
106
  }
94
107
  /** Probe `tool`'s sandbox on this machine. Never throws. */
95
108
  export async function probeSandbox(tool, o = {}) {
@@ -100,7 +113,7 @@ export async function probeSandbox(tool, o = {}) {
100
113
  const platform = o.platform ?? process.platform;
101
114
  const host = o.host ?? detectHost(env, platform);
102
115
  const run = o.run ?? defaultRun;
103
- const st = await probe(tool, { env, platform, host, run, home: o.home ?? homedir(), codex: o.codex });
116
+ const st = await probe(tool, { env, platform, host, run, home: o.home ?? homedir(), codex: o.codex, hub: o.hub });
104
117
  if (!st.ok)
105
118
  st.fix = sandboxFix(st, host);
106
119
  return st;
@@ -127,9 +140,16 @@ async function probe(tool, o) {
127
140
  return { tool, ok: false, problem: 'failed', detail: `cannot make a temporary directory: ${e?.message ?? e}` };
128
141
  }
129
142
  const outside = join(o.home, `.ach-sandbox-probe-${randomBytes(4).toString('hex')}`);
130
- const sh = ['/bin/sh', '-c', probeScript(), 'probe', dir, outside];
143
+ // Codex: a file outside the run's directory (not in the home: any other place) its runs must not read
144
+ const canaryDir = tool === 'codex' && platform !== 'win32' ? mkdtempSync(join(tmpdir(), 'ach-sandbox-other-')) : undefined;
145
+ const canary = canaryDir ? join(canaryDir, 'secret') : undefined;
146
+ // Codex: node (what `ach` runs on) and git must run with the program paths its runs get
147
+ const tools = canary ? [process.execPath, onPath('git', o.env) ?? ''] : [];
148
+ const sh = ['/bin/sh', '-c', probeScript(), 'probe', dir, outside, ...(canary ? [canary] : []), ...tools];
149
+ let codexHome;
131
150
  try {
132
151
  let r;
152
+ let codex;
133
153
  if (tool === 'claude' && platform === 'linux') {
134
154
  // what Claude Code's sandbox does: a new session, no network, the filesystem read-only except the work directory
135
155
  r = await run(host.bwrap, ['--new-session', '--die-with-parent', '--unshare-net', '--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--bind', dir, dir, '--', ...sh], { env });
@@ -140,15 +160,30 @@ async function probe(tool, o) {
140
160
  r = await run('/usr/bin/sandbox-exec', ['-p', profile, ...sh], { env });
141
161
  }
142
162
  else {
143
- const codex = o.codex ?? codexCommand(env);
163
+ codex = o.codex ?? codexCommand(env);
144
164
  if (!codex)
145
165
  return { tool, ok: true, unverified: true, detail: 'Codex was not found' };
146
166
  const cmd = platform === 'win32' ? ['cmd', '/c', `type nul > "${join(dir, 'ok')}" && (type nul > "${outside}" && exit 4 || exit 0)`] : sh;
147
- // the work directory is the cwd (`-C` would also need a named permission profile)
148
- r = await run(codex[0], [...codex.slice(1), 'sandbox', '-c', 'sandbox_mode="workspace-write"', '--', ...cmd], { env, cwd: dir });
167
+ if (canary)
168
+ writeFileSync(canary, 'probe\n', { mode: 0o600 });
169
+ codexHome = probeCodexHome();
170
+ const cenv = { ...env, CODEX_HOME: codexHome };
171
+ // the work directory is the cwd; the sandbox is the one a work run gets (codexSandboxOverrides)
172
+ r = await run(codex[0], [...codex.slice(1), 'sandbox', ...codexProbeConfig(dir, o.home, o.hub), '--', ...cmd], { env: cenv, cwd: dir });
149
173
  if (r.code !== 0 && /unrecognized subcommand|unexpected argument|Usage: codex \[OPTIONS\]/i.test(r.stderr)) {
150
174
  return { tool, ok: true, unverified: true, detail: 'this Codex has no `codex sandbox` command' };
151
175
  }
176
+ if (r.code === 7)
177
+ return { tool, ok: false, problem: 'not-enforced', detail: `a sandboxed command could read ${canary}` };
178
+ if (r.code === 8 || r.code === 9)
179
+ return { tool, ok: false, problem: 'failed', detail: `${r.code === 8 ? 'node' : 'git'} does not run in the sandbox: a path it needs is not readable (${firstLine(`${r.stderr}\n${r.stdout}`) || `exit ${r.code}`})` };
180
+ // only a file that reached this machine counts: on Linux the parents of a granted path (the home, for the toolchain) are
181
+ // empty in-memory folders inside the sandbox, so the write there "works" and is gone with the sandbox (live test)
182
+ if (existsSync(outside) || (platform === 'win32' && r.code === 4))
183
+ return { tool, ok: false, problem: 'not-enforced', detail: `a sandboxed command could write ${outside}` };
184
+ // await: the finally below removes `dir`, the network check's cwd
185
+ if ((r.code === 0 || r.code === 4) && existsSync(join(dir, 'ok')))
186
+ return o.hub ? await probeNetwork(tool, codex, o.hub, dir, run, cenv, o.home) : { tool, ok: true };
152
187
  }
153
188
  if (existsSync(outside) || r.code === 4)
154
189
  return { tool, ok: false, problem: 'not-enforced', detail: `a sandboxed command could write ${outside}` };
@@ -162,7 +197,61 @@ async function probe(tool, o) {
162
197
  finally {
163
198
  rmSync(dir, { recursive: true, force: true });
164
199
  rmSync(outside, { force: true });
200
+ if (canaryDir)
201
+ rmSync(canaryDir, { recursive: true, force: true });
202
+ if (codexHome)
203
+ rmSync(codexHome, { recursive: true, force: true });
204
+ }
205
+ }
206
+ /** `-c` arguments for `codex sandbox`: the profile of a `workdir` work run in `dir` (with the toolchain: the network check runs node). */
207
+ function codexProbeConfig(dir, home, hub) {
208
+ return codexSandboxOverrides({ perm: 'workdir', mode: 'work', cwd: dir, readRoots: toolchainReadRoots(home), hub }).flatMap((c) => ['-c', c]);
209
+ }
210
+ /**
211
+ * A node one-liner: resolve `host` and open a TCP connection to `port`. Exit 0 connected, 5 the name does not resolve, 6 the
212
+ * connection fails or takes over 8 s. No HTTP: what matters is whether the sandbox lets the agent's `ach` out at all.
213
+ */
214
+ export const NET_SCRIPT = "const[h,p]=process.argv.slice(1);require('dns').lookup(h,(e)=>{if(e)process.exit(5);" +
215
+ "const s=require('net').connect(+p,h,()=>process.exit(0));s.on('error',()=>process.exit(6));setTimeout(()=>process.exit(6),8000)})";
216
+ /**
217
+ * NET_SCRIPT through the proxy Codex starts in its sandbox (the only way out there, as for `ach`): CONNECT to `host:port`.
218
+ * Exit 0 the proxy opened the tunnel, 6 it refused or failed, 7 no proxy in the sandbox (Codex's network proxy did not start).
219
+ */
220
+ export const NET_PROXY_SCRIPT = "const[h,p]=process.argv.slice(1);const e=process.env;const v=e.HTTPS_PROXY||e.https_proxy||e.ALL_PROXY||e.all_proxy;if(!v)process.exit(7);" +
221
+ "let u;try{u=new URL(v)}catch{process.exit(7)}const s=require('net').connect(+u.port||80,u.hostname,()=>s.write('CONNECT '+h+':'+p+' HTTP/1.1\\r\\nHost: '+h+':'+p+'\\r\\n\\r\\n'));" +
222
+ "let b='';s.on('data',d=>{b+=d;if(b.includes('\\r\\n'))process.exit(/^HTTP\\/1\\.[01] 200/.test(b)?0:6)});s.on('error',()=>process.exit(6));setTimeout(()=>process.exit(6),8000)";
223
+ const PROXY_VARS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy'];
224
+ /**
225
+ * Work runs reach the hub through Codex's network proxy (codexSandboxOverrides) because the agent reports through `ach`.
226
+ * Codex settings on the machine (managed requirements) can still turn it off (live: TASK-20, every `ach complete` failed with
227
+ * EAI_AGAIN and the task failed without its result). Reach the hub from inside `codex sandbox` with the profile work runs
228
+ * use; compare with a direct connection outside, so a hub that is down or a machine that is offline is not blamed on the
229
+ * sandbox. Behind a proxy a direct connection proves nothing, so it is not checked.
230
+ */
231
+ async function probeNetwork(tool, codex, hub, dir, run, env, home) {
232
+ let host;
233
+ let port;
234
+ try {
235
+ const u = new URL(hub);
236
+ host = u.hostname.replace(/^\[|\]$/g, '');
237
+ port = u.port || (u.protocol === 'http:' ? '80' : '443');
238
+ }
239
+ catch {
240
+ return { tool, ok: true };
165
241
  }
242
+ if (PROXY_VARS.some((k) => env[k]))
243
+ return { tool, ok: true, unverified: true, detail: 'a proxy is set: the sandbox network was not checked' };
244
+ const check = [process.execPath, '-e', NET_SCRIPT, host, port];
245
+ const outside = await run(check[0], check.slice(1), { env });
246
+ if (outside.code !== 0)
247
+ return { tool, ok: true, unverified: true, detail: `${host} is not reachable from this machine either: the sandbox network was not checked` };
248
+ const insideCheck = [process.execPath, '-e', NET_PROXY_SCRIPT, host, port];
249
+ const inside = await run(codex[0], [...codex.slice(1), 'sandbox', ...codexProbeConfig(dir, home, hub), '--', ...insideCheck], { env, cwd: dir });
250
+ if (inside.code === 0)
251
+ return { tool, ok: true };
252
+ if (inside.code === 5 || inside.code === 6 || inside.code === 7)
253
+ return { tool, ok: false, problem: 'no-network', detail: host };
254
+ return { tool, ok: true, unverified: true, detail: `the sandbox network check did not run: ${firstLine(`${inside.stderr}\n${inside.stdout}`) || `exit ${inside.code}`}` };
166
255
  }
167
256
  const INSTALL = {
168
257
  apt: (p) => `sudo apt-get install -y ${p.join(' ')}`,
@@ -196,8 +285,24 @@ export function sandboxFix(st, host) {
196
285
  zh: '这台机器的内核不允许用户命名空间,沙箱需要它。请让管理这台机器的人开启(user.max_user_namespaces)。',
197
286
  commands: [],
198
287
  };
288
+ case 'no-network': {
289
+ const h = st.detail ?? 'the hub';
290
+ return {
291
+ en: `${name}'s sandbox has no network on this machine, so the agent's \`ach\` cannot reach ${h} and every task fails without its result. ` +
292
+ `The runner lets Codex reach the hub through Codex's network proxy; a managed Codex setting here stops it: check ` +
293
+ `requirements.toml (features.network_proxy, [experimental_network], allowed_permission_profiles), then run \`ach doctor\`.`,
294
+ zh: `${name} 的沙箱在这台机器上没有网络,智能体的 \`ach\` 连不上 ${h},每个任务都会失败且交不回结果。` +
295
+ `runner 让 Codex 通过它自带的网络代理连 hub,是本机管理员级的 Codex 设置挡住了:检查 requirements.toml` +
296
+ `(features.network_proxy、[experimental_network]、allowed_permission_profiles),改完再运行 \`ach doctor\`。`,
297
+ commands: [],
298
+ };
299
+ }
199
300
  case 'not-enforced':
200
- return { en: `${name}'s sandbox started but did not stop a write outside its directory: do not run this agent here.`, zh: `${name} 的沙箱能启动,但没有拦住目录外的写入:不要在这台机器上运行这个智能体。`, commands: [] };
301
+ return {
302
+ en: `${name}'s sandbox started but did not stop ${/could read/.test(st.detail ?? '') ? 'a read outside its directory' : 'a write outside its directory'}: do not run this agent here.`,
303
+ zh: `${name} 的沙箱能启动,但没有拦住${/could read/.test(st.detail ?? '') ? '对目录外文件的读取' : '目录外的写入'}:不要在这台机器上运行这个智能体。`,
304
+ commands: [],
305
+ };
201
306
  case 'missing':
202
307
  case 'userns-blocked': {
203
308
  if (host.platform !== 'linux')
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.27.0";
1
+ export declare const VERSION = "3.28.0";
2
2
  /** The npm package (scripts/release.mjs keeps it and VERSION in step with package.json). */
3
3
  export declare const PKG_NAME = "@koalaauto/agentchannel";
4
4
  /**
@@ -1,4 +1,4 @@
1
- export const VERSION = '3.27.0';
1
+ export const VERSION = '3.28.0';
2
2
  /** The npm package (scripts/release.mjs keeps it and VERSION in step with package.json). */
3
3
  export const PKG_NAME = '@koalaauto/agentchannel';
4
4
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koalaauto/agentchannel",
3
- "version": "3.27.0",
3
+ "version": "3.28.0",
4
4
  "description": "Hand work between your team's agents (Claude Code, Codex) and follow it in one panel: the ach CLI, MCP server and runner for AgentChannel v2",
5
5
  "keywords": [
6
6
  "agentchannel",