@koalaauto/agentchannel 3.27.1 → 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 () => {
@@ -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
  }
@@ -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) {
@@ -98,6 +98,11 @@ export declare function probeSandbox(tool: SandboxTool, o?: ProbeOptions): Promi
98
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
99
  */
100
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;
101
106
  /** Lets the system bubblewrap (only that path) create user namespaces under Ubuntu's AppArmor rule; never machine-wide. */
102
107
  export declare const BWRAP_APPARMOR: string;
103
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 = {}) {
@@ -127,7 +140,13 @@ 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;
133
152
  let codex;
@@ -145,17 +164,31 @@ async function probe(tool, o) {
145
164
  if (!codex)
146
165
  return { tool, ok: true, unverified: true, detail: 'Codex was not found' };
147
166
  const cmd = platform === 'win32' ? ['cmd', '/c', `type nul > "${join(dir, 'ok')}" && (type nul > "${outside}" && exit 4 || exit 0)`] : sh;
148
- // the work directory is the cwd (`-C` would also need a named permission profile)
149
- 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 });
150
173
  if (r.code !== 0 && /unrecognized subcommand|unexpected argument|Usage: codex \[OPTIONS\]/i.test(r.stderr)) {
151
174
  return { tool, ok: true, unverified: true, detail: 'this Codex has no `codex sandbox` command' };
152
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 };
153
187
  }
154
188
  if (existsSync(outside) || r.code === 4)
155
189
  return { tool, ok: false, problem: 'not-enforced', detail: `a sandboxed command could write ${outside}` };
156
- // await: the finally below removes `dir`, the network check's cwd
157
190
  if (r.code === 0 && existsSync(join(dir, 'ok')))
158
- return codex && o.hub ? await probeNetwork(tool, codex, o.hub, dir, run, env) : { tool, ok: true };
191
+ return { tool, ok: true };
159
192
  const err = `${r.stderr}\n${r.stdout}`;
160
193
  if (r.code === 127 && platform === 'linux' && tool === 'claude')
161
194
  return { tool, ok: false, problem: 'missing', missing: ['bubblewrap'] };
@@ -164,23 +197,38 @@ async function probe(tool, o) {
164
197
  finally {
165
198
  rmSync(dir, { recursive: true, force: true });
166
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 });
167
204
  }
168
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
+ }
169
210
  /**
170
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
171
212
  * connection fails or takes over 8 s. No HTTP: what matters is whether the sandbox lets the agent's `ach` out at all.
172
213
  */
173
214
  export const NET_SCRIPT = "const[h,p]=process.argv.slice(1);require('dns').lookup(h,(e)=>{if(e)process.exit(5);" +
174
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)";
175
223
  const PROXY_VARS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy'];
176
224
  /**
177
- * Work runs keep Codex's network on (codexThreadOptions) because the agent reports through `ach`. Codex settings on the machine
178
- * can still turn it off (live: TASK-20, every `ach complete` failed with EAI_AGAIN and the task failed without its result).
179
- * Connect to the hub from inside `codex sandbox` with the runner's network setting; compare with the same check outside, so a
180
- * hub that is down or a machine that is offline is not blamed on the sandbox. Behind a proxy a direct connection proves
181
- * nothing, so it is not checked.
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.
182
230
  */
183
- async function probeNetwork(tool, codex, hub, dir, run, env) {
231
+ async function probeNetwork(tool, codex, hub, dir, run, env, home) {
184
232
  let host;
185
233
  let port;
186
234
  try {
@@ -197,10 +245,11 @@ async function probeNetwork(tool, codex, hub, dir, run, env) {
197
245
  const outside = await run(check[0], check.slice(1), { env });
198
246
  if (outside.code !== 0)
199
247
  return { tool, ok: true, unverified: true, detail: `${host} is not reachable from this machine either: the sandbox network was not checked` };
200
- const inside = await run(codex[0], [...codex.slice(1), 'sandbox', '-c', 'sandbox_mode="workspace-write"', '-c', 'sandbox_workspace_write.network_access=true', '--', ...check], { env, cwd: dir });
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 });
201
250
  if (inside.code === 0)
202
251
  return { tool, ok: true };
203
- if (inside.code === 5 || inside.code === 6)
252
+ if (inside.code === 5 || inside.code === 6 || inside.code === 7)
204
253
  return { tool, ok: false, problem: 'no-network', detail: host };
205
254
  return { tool, ok: true, unverified: true, detail: `the sandbox network check did not run: ${firstLine(`${inside.stderr}\n${inside.stdout}`) || `exit ${inside.code}`}` };
206
255
  }
@@ -240,16 +289,20 @@ export function sandboxFix(st, host) {
240
289
  const h = st.detail ?? 'the hub';
241
290
  return {
242
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. ` +
243
- `The runner asks Codex for network; a Codex setting here turns it off: check ~/.codex/config.toml and requirements.toml ` +
244
- `(default_permissions, [permissions.*.network], sandbox_workspace_write.network_access), then run \`ach doctor\`.`,
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\`.`,
245
294
  zh: `${name} 的沙箱在这台机器上没有网络,智能体的 \`ach\` 连不上 ${h},每个任务都会失败且交不回结果。` +
246
- `runner 已经要求 Codex 打开网络,是本机的 Codex 设置把它关了:检查 ~/.codex/config.toml 和 requirements.toml` +
247
- `(default_permissions、[permissions.*.network]、sandbox_workspace_write.network_access),改完再运行 \`ach doctor\`。`,
295
+ `runner 让 Codex 通过它自带的网络代理连 hub,是本机管理员级的 Codex 设置挡住了:检查 requirements.toml` +
296
+ `(features.network_proxy、[experimental_network]、allowed_permission_profiles),改完再运行 \`ach doctor\`。`,
248
297
  commands: [],
249
298
  };
250
299
  }
251
300
  case 'not-enforced':
252
- 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
+ };
253
306
  case 'missing':
254
307
  case 'userns-blocked': {
255
308
  if (host.platform !== 'linux')
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.27.1";
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.1';
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.1",
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",