opencode-fs-plugin 1.10.0 → 1.11.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.
package/README.md CHANGED
@@ -139,18 +139,39 @@ work, fan out with `Promise.all` over `tools.fs.*` (or one multi-path call).
139
139
  }
140
140
  ```
141
141
 
142
- The workspace (project) is read/write/exec, but **network and external paths are
143
- denied by default**. There are no per-call grants: when the sandbox blocks a
144
- path or a socket, `fs.exec` asks the matching permission and retries the run.
142
+ The workspace (project) is read/write/exec. **Network is proxy-only by
143
+ default**: every run gets its own egress proxy, no direct route, and only
144
+ allowlisted hosts are reachable. Pre-approve hosts in the plugin options:
145
145
 
146
- - blocked path → `external_directory` for the absolute path
147
- - blocked socket → `fs_exec_network`
146
+ ```jsonc
147
+ {
148
+ "options": {
149
+ "execNetworkAllowlist": ["registry.npmjs.org", "*.npmjs.org"]
150
+ }
151
+ }
152
+ ```
153
+
154
+ A host the proxy refuses asks `fs_exec_network` with that host, and the run
155
+ retries with it added. `execNetworkMode: "ip"` opts into all-IP networking after
156
+ the same approval instead. External paths are separate: a blocked path asks
157
+ `external_directory` for its containing directory (or the nearest existing
158
+ ancestor), and the sandbox grants read/write there.
148
159
 
149
160
  The decision comes from your `opencode.jsonc` rules (`ask`, `allow`, `deny`), the
150
- same as every other tool. If a path is still blocked after approval, the result
161
+ same as every other tool. If a path stays blocked after approval, the result
151
162
  reports `violations` and a `hint`. `fs.exec` also kills every process it started
152
163
  when the run ends, including detached descendants.
153
164
 
165
+ Proxy mode needs Linux T1 (user namespaces) or macOS. On Linux T2 there is no
166
+ network namespace, so `fs.exec` falls back to all-IP: a socket denial asks
167
+ `fs_exec_network` and retries with `ip`. In `ip` mode the policy also opens the
168
+ resolver sockets used by systemd-resolved, nscd, and SSSD
169
+ (`/run/systemd/resolve`, `/run/nscd`, `/var/lib/sss/pipes`), so DNS works across
170
+ common Linux distributions. Plain UDP DNS needs none of them; other Unix sockets
171
+ stay blocked. On kernels where procage cannot scope Unix sockets (T2 below
172
+ Landlock ABI 9), the policy drops them via `no-unix-sockets`; DNS then works only
173
+ through a plain UDP resolver.
174
+
154
175
  ```js
155
176
  await tools.fs.exec({ command: "npm", args: ["install"], timeoutMs: 300000 })
156
177
  ```
@@ -259,18 +280,18 @@ Add the registry package directly to the plugin list:
259
280
 
260
281
  ```jsonc
261
282
  {
262
- "plugins": ["opencode-fs-plugin@1.10.0"]
283
+ "plugins": ["opencode-fs-plugin@1.11.0"]
263
284
  }
264
285
  ```
265
286
 
266
- `opencode plugin add opencode-fs-plugin@1.10.0` installs it and writes the config
287
+ `opencode plugin add opencode-fs-plugin@1.11.0` installs it and writes the config
267
288
  entry. A bare `opencode-fs-plugin` follows the `latest` tag.
268
289
 
269
290
  OpenCode manages the package under its cache, so the path is not stable. If you
270
291
  also want the packaged skill, install it into a project instead:
271
292
 
272
293
  ```bash
273
- npm install opencode-fs-plugin@1.10.0
294
+ npm install opencode-fs-plugin@1.11.0
274
295
  ```
275
296
 
276
297
  ```jsonc
@@ -285,7 +306,7 @@ npm install opencode-fs-plugin@1.10.0
285
306
  Download the release tarball, then install it as a normal npm package:
286
307
 
287
308
  ```bash
288
- VERSION=1.10.0
309
+ VERSION=1.11.0
289
310
  curl -L -o "opencode-fs-plugin-${VERSION}.tgz" \
290
311
  "https://github.com/masterjg/opencode-fs-plugin/releases/download/v${VERSION}/opencode-fs-plugin-${VERSION}.tgz"
291
312
  npm install "./opencode-fs-plugin-${VERSION}.tgz"
@@ -314,20 +335,20 @@ OpenCode installs it from Git:
314
335
 
315
336
  ```jsonc
316
337
  {
317
- "plugins": ["github:masterjg/opencode-fs-plugin#v1.10.0"]
338
+ "plugins": ["github:masterjg/opencode-fs-plugin#v1.11.0"]
318
339
  }
319
340
  ```
320
341
 
321
- `opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.10.0'` installs the
342
+ `opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.11.0'` installs the
322
343
  same spec and writes the config entry. The equivalent full URL is
323
- `git+https://github.com/masterjg/opencode-fs-plugin.git#v1.10.0`. A tag is
344
+ `git+https://github.com/masterjg/opencode-fs-plugin.git#v1.11.0`. A tag is
324
345
  checked for updates; use a full commit hash to pin it.
325
346
 
326
347
  Git plugins are installed under OpenCode's cache, so their package path is not
327
348
  stable. If you also want the packaged skill, install with npm instead:
328
349
 
329
350
  ```bash
330
- npm install "github:masterjg/opencode-fs-plugin#v1.10.0"
351
+ npm install "github:masterjg/opencode-fs-plugin#v1.11.0"
331
352
  ```
332
353
 
333
354
  Then use `./node_modules/opencode-fs-plugin` in `plugins` and
@@ -386,7 +407,8 @@ external targets first require `external_directory` on the absolute boundary.
386
407
  `allow always` persists the same patterns as the built-in tools.
387
408
 
388
409
  `fs.exec` asserts `fs_exec` for the run, then asks `external_directory` for any
389
- blocked path and `fs_exec_network` for blocked sockets before retrying:
410
+ blocked path and `fs_exec_network` for a refused host (the resource is the host,
411
+ or `*` in ip mode) before retrying:
390
412
 
391
413
  ```jsonc
392
414
  {
@@ -397,6 +419,11 @@ blocked path and `fs_exec_network` for blocked sockets before retrying:
397
419
  }
398
420
  ```
399
421
 
422
+ Keep both rules explicit. Plugin actions match OpenCode's base
423
+ `{ "action": "*", "resource": "*", "effect": "allow" }` rule, so an unlisted
424
+ `fs_exec_network` or `external_directory` resource is allowed without a prompt,
425
+ not asked.
426
+
400
427
  `fs.http_request` is allowed by default, like `fetch`. Its resource is the
401
428
  request host (`example.com:8443`), so requests can be restricted per host:
402
429
 
package/SPEC.md CHANGED
@@ -86,15 +86,28 @@ Aliases are accepted only where noted: `path` for one `paths` element (`stat`,
86
86
  Default: `npm`, `npx`, `uv`, `uvx`, `pip`, `pip3`. Override with the plugin
87
87
  option `execAllowlist`; an empty list disables execution.
88
88
  - The policy is procage `agent_workspace` v3: the project is read/write/exec.
89
- Network and external paths are denied by default; there are no per-call
90
- grants.
91
- - Denied access is handled by asserting the configured permission and retrying,
92
- bounded to six attempts: a blocked path asks `external_directory` on the
93
- absolute path, a blocked socket asks `fs_exec_network`. The `allow`/`ask`/`deny`
94
- decision comes from `opencode.jsonc`, not from the tool call.
89
+ Network is proxy-only and external paths are denied by default; there are no
90
+ per-call grants.
91
+ - Network is proxy-only by default: the cage gets a procage proxy whose
92
+ allowlist is the configured `execNetworkAllowlist` plus the hosts approved
93
+ in this run. A refused host asks `fs_exec_network` with the host as the
94
+ resource, then the run retries with it added. The decision comes from
95
+ `opencode.jsonc`.
96
+ - `execNetworkMode: "ip"` opts into all-IP networking after `fs_exec_network`
97
+ approval. In `ip` mode the policy also opens the resolver sockets used by
98
+ systemd-resolved, nscd, and SSSD. Plain UDP DNS needs none; other Unix
99
+ sockets stay blocked. Landlock ignores paths absent on the host. On T2 below
100
+ Landlock ABI 9 the sockets cannot be scoped, so `no-unix-sockets` drops them
101
+ and only UDP DNS remains.
102
+ - Proxy mode needs Linux T1 or macOS. On T2 the cage fails with the `net-proxy`
103
+ gap; `fs.exec` retries in `ip` mode and asks on a socket denial.
104
+ - Denied paths ask `external_directory` on their containing directory (or the
105
+ nearest existing ancestor for a missing or redacted path). Access handling is
106
+ bounded to twelve attempts.
95
107
  - If a path or socket stays blocked after approval, the result reports
96
108
  `violations` plus a `hint`; stderr containing EACCES/EPERM/EROFS marks
97
- `sandboxBlocked`.
109
+ `sandboxBlocked`. Results carry `network`, `networkMode`, `networkHosts`, and
110
+ `externalPaths`.
98
111
  - `args` are passed verbatim. `cwd` resolves inside the sandbox and asserts
99
112
  `external_directory` when it leaves the project; the action is `fs_exec`.
100
113
  - Timeout defaults to 120000 ms, capped at 600000. Procage ends the run and kills
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-fs-plugin",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22.12"
@@ -36,7 +36,7 @@
36
36
  "@sinclair/typebox": "^0.34.52",
37
37
  "diff": "^9.0.0",
38
38
  "picomatch": "^4.0.7",
39
- "procage": "^0.8.0",
39
+ "procage": "https://github.com/masterjg/procage/releases/download/node-proxy-v1/procage-0.8.0.tgz",
40
40
  "tar-stream": "^3.2.2",
41
41
  "yauzl": "^3.4.0",
42
42
  "yazl": "^3.3.1"
@@ -156,19 +156,25 @@ override it with the fs plugin option `execAllowlist` in `opencode.jsonc`:
156
156
  { "package": "./repos/opencode-fs-plugin", "options": { "execAllowlist": ["npm", "uv"] } }
157
157
  ```
158
158
 
159
- The project is read/write/exec. **Network and external paths are denied by
160
- default, and there are no per-call grants.** When the sandbox blocks something,
161
- `fs.exec` asks `external_directory` for the path or `fs_exec_network` for a
162
- socket, then retries; the decision comes from `opencode.jsonc`:
159
+ The project is read/write/exec. **Network is proxy-only by default, and there
160
+ are no per-call grants.** The run gets its own egress proxy with no direct
161
+ route; a refused host asks `fs_exec_network` with the host and the run retries
162
+ with it added. Pre-approve hosts with `execNetworkAllowlist`; set
163
+ `execNetworkMode: "ip"` to opt into all-IP after approval instead. On Linux T2
164
+ (no network namespace) the run falls back to `ip`.
163
165
 
164
166
  ```js
165
167
  await tools.fs.exec({ command: "npm", args: ["install"], timeoutMs: 300000 })
166
168
  ```
167
169
 
168
- Denied access returns `violations` and a `hint`; if a path stays blocked after
169
- approval, the result says so. `command` is a bare name, `args` are literal, and
170
- `cwd` is sandboxed. Direct calls return JSON with `exitCode`/`stdout`/`stderr`
171
- and violations; in `fs.pipe` the stage passes raw stdout.
170
+ Denied paths ask `external_directory` and approval covers the denied path's
171
+ containing directory (or nearest existing ancestor). Denied access returns
172
+ `violations` and a `hint`. In `ip` mode DNS works through the
173
+ systemd-resolved, nscd, or SSSD sockets where the kernel can scope them; other
174
+ Unix sockets stay blocked and plain UDP DNS works everywhere.
175
+ `command` is a bare name, `args` are literal, and `cwd` is sandboxed. Direct
176
+ calls return JSON with `exitCode`/`stdout`/`stderr` and violations; in `fs.pipe`
177
+ the stage passes raw stdout.
172
178
 
173
179
  ```js
174
180
  await tools.fs.pipe({
@@ -415,8 +421,8 @@ await tools.fs.http_request({
415
421
  - Linux only; there is no Windows branch.
416
422
  - `fs.sed` supports `s<delim>pattern<delim>replacement<delim>flags` with `g`,
417
423
  `i` and `p`. It is not a full sed interpreter.
418
- - `fs.exec` requires procage: Linux x64/arm64, glibc 2.28+, Node 22.12+. Network
419
- and external paths are denied until approved.
424
+ - `fs.exec` requires procage: Linux x64/arm64, glibc 2.28+, Node 22.12+.
425
+ Network is proxy-only by default; external paths are denied until approved.
420
426
  - `fs.find` has no arbitrary `-exec`; use `action: "delete"`/`"trash"` for the
421
427
  common cleanup case, or `fs.rm`/`fs.trash` separately.
422
428
  - No `xz`, `zstd`, `7z`, `rar`, `chattr`, ACLs, xattrs, or `rsync`.
@@ -471,9 +477,9 @@ in agent rules. `fs.pipe` asserts each stage's action; a denied stage cannot be
471
477
  hidden inside a pipeline. Do not work around a denied tool with shell.
472
478
 
473
479
  `fs_exec` runs only exact allowlisted names in a procage sandbox. It asserts
474
- `fs_exec`, then asks `external_directory` for a blocked path or `fs_exec_network`
475
- for a blocked socket and retries; there are no per-call grants. There is no
476
- shell.
480
+ `fs_exec`, asks `external_directory` for a blocked path, and asks
481
+ `fs_exec_network` with the refused host (or `*` in `ip` mode), then retries.
482
+ There are no per-call grants and no shell.
477
483
 
478
484
  `fs_http_request` is allowed by default, like `fetch`. Its resource is the
479
485
  request host; rules can allow one host and ask or deny the rest. Each redirect
package/src/core/types.ts CHANGED
@@ -32,6 +32,10 @@ export interface RunContext {
32
32
  readonly tmpdir: string;
33
33
  readonly maxOutputBytes: number;
34
34
  readonly execAllowlist: readonly string[];
35
+ /** `proxy` forces egress through the run's allowlist proxy; `ip` is all-IP. */
36
+ readonly execNetworkMode: "proxy" | "ip";
37
+ /** Hosts pre-approved for every `fs.exec` proxy run. */
38
+ readonly execNetworkAllowlist: readonly string[];
35
39
  }
36
40
 
37
41
  export interface ToolSpec<I> {
package/src/index.ts CHANGED
@@ -30,7 +30,12 @@ import { diffTool } from "./tools/diff.js";
30
30
  import { duTool } from "./tools/du.js";
31
31
  import { fileTool } from "./tools/file.js";
32
32
  import { findTool } from "./tools/find.js";
33
- import { execTool, normalizeExecAllowlist } from "./tools/exec.js";
33
+ import {
34
+ execTool,
35
+ normalizeExecAllowlist,
36
+ normalizeExecNetworkAllowlist,
37
+ normalizeExecNetworkMode,
38
+ } from "./tools/exec.js";
34
39
  import { findmntTool } from "./tools/findmnt.js";
35
40
  import { foldTool } from "./tools/fold.js";
36
41
  import { grepTool } from "./tools/grep.js";
@@ -199,6 +204,8 @@ export default Plugin.define({
199
204
  typeof ctx.options?.concurrency === "number" ? ctx.options.concurrency : undefined,
200
205
  );
201
206
  const execAllowlist = normalizeExecAllowlist(ctx.options?.execAllowlist);
207
+ const execNetworkMode = normalizeExecNetworkMode(ctx.options?.execNetworkMode);
208
+ const execNetworkAllowlist = normalizeExecNetworkAllowlist(ctx.options?.execNetworkAllowlist);
202
209
  const maxOutputBytes =
203
210
  typeof ctx.options?.maxOutputBytes === "number" && ctx.options.maxOutputBytes > 0
204
211
  ? Math.trunc(ctx.options.maxOutputBytes)
@@ -252,6 +259,8 @@ export default Plugin.define({
252
259
  tmpdir: os.tmpdir(),
253
260
  maxOutputBytes,
254
261
  execAllowlist,
262
+ execNetworkMode,
263
+ execNetworkAllowlist,
255
264
  },
256
265
  parsed,
257
266
  {},
package/src/tools/exec.ts CHANGED
@@ -7,7 +7,7 @@ import * as fs from "node:fs/promises";
7
7
  import { constants as fsConstants } from "node:fs";
8
8
  import * as path from "node:path";
9
9
  import { Type, type Static } from "@sinclair/typebox";
10
- import type { Violation } from "procage";
10
+ import type { Relaxation, Violation } from "procage";
11
11
  import { FsError } from "../core/errors.js";
12
12
  import { collect } from "../core/stream.js";
13
13
  import { textResult, type RunContext, type ToolSpec } from "../core/types.js";
@@ -48,12 +48,102 @@ const Schema = Type.Object(
48
48
 
49
49
  type Input = Static<typeof Schema>;
50
50
 
51
- interface PolicyDocument {
51
+ export interface PolicyDocument {
52
52
  fs: Array<{ access: string; target: { subpath: string } }>;
53
53
  net: string;
54
+ ipc: { unix_sockets: string[] };
54
55
  [key: string]: unknown;
55
56
  }
56
57
 
58
+ /**
59
+ * Sockets used by the name-service resolvers on common Linux systems:
60
+ * systemd-resolved, nscd, and SSSD. Plain glibc/musl DNS over UDP needs none.
61
+ * Landlock ignores paths that do not exist on the host.
62
+ */
63
+ export const RESOLVER_SOCKETS = ["/run/systemd/resolve", "/run/nscd", "/var/lib/sss/pipes"] as const;
64
+
65
+ /** The proxy allowlist must not be empty; this name never resolves. */
66
+ export const PROXY_SENTINEL = "procage.invalid";
67
+
68
+ export type ExecNetworkMode = "proxy" | "ip";
69
+
70
+ export function normalizeExecNetworkMode(value: unknown): ExecNetworkMode {
71
+ if (value === undefined) return "proxy";
72
+ if (value === "proxy" || value === "ip") return value;
73
+ throw new FsError('execNetworkMode must be "proxy" or "ip".', "invalid");
74
+ }
75
+
76
+ export function normalizeExecNetworkAllowlist(value: unknown): readonly string[] {
77
+ if (value === undefined) return [];
78
+ if (!Array.isArray(value)) {
79
+ throw new FsError("execNetworkAllowlist must be an array of hosts.", "invalid");
80
+ }
81
+ const hosts: string[] = [];
82
+ for (const entry of value) {
83
+ if (typeof entry !== "string" || entry.trim() === "") {
84
+ throw new FsError("execNetworkAllowlist entries must be non-empty strings.", "invalid");
85
+ }
86
+ hosts.push(entry.trim());
87
+ }
88
+ return [...new Set(hosts)];
89
+ }
90
+
91
+ /** `ip` adds all-IP networking; both modes get the local resolver sockets. */
92
+ export function applyNetworkPolicy(doc: PolicyDocument, mode: ExecNetworkMode): void {
93
+ doc.ipc.unix_sockets = [...RESOLVER_SOCKETS];
94
+ if (mode === "ip") doc.net = "ip";
95
+ }
96
+
97
+ /** A host the run's proxy refused. */
98
+ export interface ProxyHost {
99
+ /** Host without a port, for the permission resource. */
100
+ host: string;
101
+ /** `host:port`, for the allowlist entry. */
102
+ entry: string;
103
+ }
104
+
105
+ /** The refused host in a proxy violation, if this violation is one. */
106
+ export function proxyHostOf(violation: Violation): ProxyHost | undefined {
107
+ if (violation.operation !== "network-outbound") return undefined;
108
+ const match = /^(\[[^\]]+\]|[^\s:]+)(?::(\d+))? \(not on the allowlist\)$/.exec(violation.target ?? "");
109
+ if (match === null) return undefined;
110
+ const host = match[1]!;
111
+ return { host, entry: match[2] === undefined ? host : `${host}:${match[2]}` };
112
+ }
113
+
114
+ /**
115
+ * Ask `fs_exec_network` for every host the run's proxy refused, and add the
116
+ * approved ones to `hosts`. Returns whether the list grew.
117
+ */
118
+ export async function approveProxyHosts(
119
+ ctx: Pick<RunContext, "permissionFor">,
120
+ outcome: ExecOutcome,
121
+ hosts: string[],
122
+ ): Promise<boolean> {
123
+ if (outcome.networkMode !== "proxy") return false;
124
+ let added = false;
125
+ for (const violation of outcome.violations) {
126
+ const host = proxyHostOf(violation);
127
+ if (host === undefined || hosts.includes(host.entry)) continue;
128
+ await ctx.permissionFor("fs_exec_network").assertTrusted([host.host]);
129
+ hosts.push(host.entry);
130
+ added = true;
131
+ }
132
+ return added;
133
+ }
134
+
135
+ /** Whether the host cannot keep a run to a proxy-only route (Linux T2). */
136
+ export function isProxyGap(error: unknown, api: typeof import("procage")): boolean {
137
+ return error instanceof api.CapabilityGapError && error.gaps.some((gap) => gap.construct === "net-proxy");
138
+ }
139
+
140
+ /** Why a blocked run failed, and what to do about it. */
141
+ export function blockedHint(mode: ExecNetworkMode): string {
142
+ return mode === "proxy"
143
+ ? 'The run\'s network is proxy-only and a program tried to bypass it. Use a proxy-aware client, or set execNetworkMode to "ip".'
144
+ : "The sandbox denied an external path or network access. Approve the path or network in the permission prompt and retry.";
145
+ }
146
+
57
147
  export interface ExecOutcome {
58
148
  stdout: Buffer;
59
149
  stderr: Buffer;
@@ -63,6 +153,8 @@ export interface ExecOutcome {
63
153
  aborted: boolean;
64
154
  stdoutTruncated: boolean;
65
155
  stderrTruncated: boolean;
156
+ /** The mode the sandbox actually ran: proxy may fall back to ip. */
157
+ networkMode: ExecNetworkMode;
66
158
  violations: Violation[];
67
159
  }
68
160
 
@@ -77,8 +169,8 @@ export const execTool: ToolSpec<Input> = {
77
169
  name: "exec",
78
170
  description:
79
171
  "Run an allowlisted executable in a procage sandbox without a shell. Direct calls return JSON; " +
80
- "pipe stages pass raw stdout. Default allowlist: npm, npx, uv, uvx, pip, pip3. Network and external " +
81
- "paths are denied until approved.",
172
+ "pipe stages pass raw stdout. Default allowlist: npm, npx, uv, uvx, pip, pip3. Network is forced " +
173
+ "through the run's allowlist proxy by default; a refused host asks fs_exec_network.",
82
174
  schema: Schema,
83
175
  pipeable: "filter",
84
176
  mutates: true,
@@ -108,40 +200,49 @@ export const execTool: ToolSpec<Input> = {
108
200
  const inputData = io.stdin === undefined
109
201
  ? input.stdin === undefined ? undefined : Buffer.from(input.stdin)
110
202
  : await collect(io.stdin);
111
- let networkAllowed = false;
203
+ let networkMode = ctx.execNetworkMode;
204
+ const proxyHosts = [...ctx.execNetworkAllowlist];
205
+ let ipNetwork = false;
112
206
  const approved: Array<{ full: string }> = [];
113
207
  let outcome: ExecOutcome | undefined;
114
208
 
115
- for (let attempt = 0; attempt < 6; attempt++) {
209
+ for (let attempt = 0; attempt < 12; attempt++) {
116
210
  outcome = await runCaged(ctx, {
117
211
  command,
118
212
  executable,
119
213
  args,
120
214
  cwd: cwdTarget.full,
121
215
  timeoutMs: input.timeoutMs ?? 120_000,
122
- network: networkAllowed,
216
+ networkMode,
217
+ proxyHosts,
218
+ ipNetwork,
123
219
  allowed: approved,
124
220
  tempDir,
125
221
  input: inputData,
126
222
  });
223
+ networkMode = outcome.networkMode;
127
224
 
128
- const networkDenied = !networkAllowed && detectsNetworkDenial(outcome);
129
- const deniedPaths = discoverExternalPaths(ctx, outcome)
130
- .filter((candidate) => !approved.some((entry) => entry.full === candidate));
131
- if (!networkDenied && deniedPaths.length === 0) break;
132
-
133
- if (networkDenied) {
225
+ if (networkMode === "ip" && !ipNetwork && detectsNetworkDenial(outcome)) {
134
226
  await ctx.permissionFor("fs_exec_network").assert([]);
135
- networkAllowed = true;
227
+ ipNetwork = true;
136
228
  continue;
137
229
  }
138
230
 
139
- let added = false;
231
+ let added = await approveProxyHosts(ctx, outcome, proxyHosts);
232
+ const deniedPaths = discoverExternalPaths(ctx, outcome)
233
+ .filter((candidate) => !approved.some((entry) => entry.full === candidate));
140
234
  for (const candidate of deniedPaths) {
141
- const target = await ctx.sandbox.resolveExisting(candidate, { allowRoot: true }).catch(() => undefined);
235
+ const target = await existingBoundary(ctx, candidate);
142
236
  if (target === undefined) continue;
143
- await ctx.permission.assert([{ target, boundary: target.full }]);
144
- approved.push({ full: target.full });
237
+ /* v8 ignore next */
238
+ const stats = await ctx.sandbox.stat(target.full, candidate).catch(() => undefined);
239
+ /* v8 ignore next */
240
+ if (stats === undefined) continue;
241
+ const boundary = stats.isDirectory() ? target.full : path.dirname(target.full);
242
+ const dirTarget = await ctx.sandbox.resolveExisting(boundary, { allowRoot: true });
243
+ if (approved.some((entry) => entry.full === dirTarget.full)) continue;
244
+ await ctx.permission.assert([{ target: dirTarget, boundary: dirTarget.full }]);
245
+ approved.push({ full: dirTarget.full });
145
246
  added = true;
146
247
  }
147
248
  if (!added) break;
@@ -160,7 +261,9 @@ export const execTool: ToolSpec<Input> = {
160
261
  stderrTruncated: outcome.stderrTruncated,
161
262
  sandboxBlocked: isSandboxBlocked(outcome),
162
263
  violations: outcome.violations.length,
163
- network: networkAllowed,
264
+ network: networkMode === "proxy" || ipNetwork,
265
+ networkMode,
266
+ networkHosts: proxyHosts,
164
267
  externalPaths: approved.map((entry) => entry.full),
165
268
  };
166
269
  if (io.piped === true) {
@@ -177,12 +280,7 @@ export const execTool: ToolSpec<Input> = {
177
280
  stdout: outcome.stdout.toString("utf8"),
178
281
  stderr: outcome.stderr.toString("utf8"),
179
282
  violations: outcome.violations,
180
- ...(sandboxBlocked
181
- ? {
182
- hint:
183
- "The sandbox denied an external path or network access. Approve the path or network in the permission prompt and retry.",
184
- }
185
- : {}),
283
+ ...(sandboxBlocked ? { hint: blockedHint(networkMode) } : {}),
186
284
  };
187
285
  return textResult(JSON.stringify(body, null, 2), metadata, outcome.exitCode === 0 ? 0 : 1);
188
286
  } finally {
@@ -202,7 +300,9 @@ interface CagedInput {
202
300
  args: string[];
203
301
  cwd: string;
204
302
  timeoutMs: number;
205
- network: boolean;
303
+ networkMode: ExecNetworkMode;
304
+ proxyHosts: readonly string[];
305
+ ipNetwork: boolean;
206
306
  allowed: Array<{ full: string }>;
207
307
  tempDir: string;
208
308
  input: Buffer | undefined;
@@ -218,7 +318,7 @@ async function runCaged(ctx: RunContext, input: CagedInput): Promise<ExecOutcome
218
318
  }
219
319
 
220
320
  const doc = api.Policy.preset("agent_workspace", 3, { workspace: ctx.sandbox.root }).toJSON() as PolicyDocument;
221
- doc.net = input.network ? "ip" : "none";
321
+ applyNetworkPolicy(doc, input.networkMode === "ip" && !input.ipNetwork ? "proxy" : input.networkMode);
222
322
  addRule(doc, "exec", path.dirname(input.executable.path));
223
323
  addRule(doc, "exec", path.dirname(input.executable.real));
224
324
  addRule(doc, "exec", path.dirname(process.execPath));
@@ -238,16 +338,25 @@ async function runCaged(ctx: RunContext, input: CagedInput): Promise<ExecOutcome
238
338
  addRule(doc, "write", input.cwd);
239
339
  for (const allowed of input.allowed) addRule(doc, "write", allowed.full);
240
340
 
341
+ const cageOptions = {
342
+ violations: true,
343
+ acceptSpawnSnapshot: true,
344
+ relax: ["waive:trust-handoff", "signals-same-user", "no-unix-sockets"] as Relaxation[],
345
+ ...(input.networkMode === "proxy"
346
+ ? { proxy: { allowlist: input.proxyHosts.length === 0 ? [PROXY_SENTINEL] : [...input.proxyHosts] } }
347
+ : {}),
348
+ };
349
+
241
350
  let cage: InstanceType<typeof api.Cage>;
242
351
  let policy: ReturnType<typeof api.Policy.fromJSON>;
243
352
  try {
244
353
  policy = api.Policy.fromJSON(doc);
245
- cage = new api.Cage(policy, {
246
- violations: true,
247
- acceptSpawnSnapshot: true,
248
- relax: ["waive:trust-handoff", "signals-same-user"],
249
- });
354
+ cage = new api.Cage(policy, cageOptions);
250
355
  } catch (error) {
356
+ /* v8 ignore next 3 */
357
+ if (input.networkMode === "proxy" && isProxyGap(error, api)) {
358
+ return runCaged(ctx, { ...input, networkMode: "ip" });
359
+ }
251
360
  /* v8 ignore next */
252
361
  throw new FsError(`exec policy rejected: ${String(error)}`, "unsupported");
253
362
  }
@@ -289,10 +398,11 @@ async function runCaged(ctx: RunContext, input: CagedInput): Promise<ExecOutcome
289
398
  aborted,
290
399
  stdoutTruncated: stdout.truncated,
291
400
  stderrTruncated: stderr.truncated,
401
+ networkMode: input.networkMode,
292
402
  violations,
293
403
  };
294
404
  } catch (error) {
295
- /* v8 ignore next 14 */
405
+ /* v8 ignore next 15 */
296
406
  if (aborted || ctx.signal.aborted) {
297
407
  return {
298
408
  stdout: Buffer.alloc(0),
@@ -303,6 +413,7 @@ async function runCaged(ctx: RunContext, input: CagedInput): Promise<ExecOutcome
303
413
  aborted: true,
304
414
  stdoutTruncated: false,
305
415
  stderrTruncated: false,
416
+ networkMode: input.networkMode,
306
417
  violations: [],
307
418
  };
308
419
  }
@@ -314,6 +425,23 @@ async function runCaged(ctx: RunContext, input: CagedInput): Promise<ExecOutcome
314
425
  }
315
426
  }
316
427
 
428
+ /**
429
+ * Resolve a denied path to the nearest existing ancestor, so a missing
430
+ * directory or a redacted temp name still yields an approvable boundary.
431
+ * The filesystem root is never exposed.
432
+ */
433
+ async function existingBoundary(ctx: RunContext, candidate: string) {
434
+ let current = candidate;
435
+ for (;;) {
436
+ /* v8 ignore next */
437
+ const target = await ctx.sandbox.resolveExisting(current, { allowRoot: true }).catch(() => undefined);
438
+ if (target !== undefined) {
439
+ return target.full === path.parse(target.full).root ? undefined : target;
440
+ }
441
+ current = path.dirname(current);
442
+ }
443
+ }
444
+
317
445
  function addRule(doc: PolicyDocument, access: string, target: string): void {
318
446
  const subpath = path.resolve(target);
319
447
  if (doc.fs.some((rule) => rule.access === access && rule.target.subpath === subpath)) return;
@@ -322,6 +450,7 @@ function addRule(doc: PolicyDocument, access: string, target: string): void {
322
450
 
323
451
  export function filterViolations(violations: readonly Violation[]): Violation[] {
324
452
  return violations.filter((violation) => {
453
+ if (proxyHostOf(violation) !== undefined) return true;
325
454
  if (violation.target?.startsWith("/")) return true;
326
455
  return /AF_INET|AF_INET6/.test(violation.target ?? "");
327
456
  });
@@ -345,12 +474,11 @@ export function discoverExternalPaths(ctx: RunContext, outcome: ExecOutcome): st
345
474
  }
346
475
 
347
476
  const stderr = outcome.stderr.toString("utf8");
348
- for (const line of stderr.split("\n")) {
349
- if (!/EACCES|EPERM|EROFS|Permission denied|Read-only file system|error writing|not written|cannot open|failed to open/i.test(line)) {
350
- continue;
351
- }
352
- for (const match of line.matchAll(/(?:^|[\s'"`(])(\/[^\s'"`),]+)/g)) {
353
- found.add(match[1]!);
477
+ if (/EACCES|EPERM|EROFS|Permission denied|Read-only file system|error writing|not written|cannot open|failed to open/i.test(stderr)) {
478
+ for (const line of stderr.split("\n")) {
479
+ for (const match of line.matchAll(/(?:^|[\s'"`(])(\/[^\s'"`),]+)/g)) {
480
+ found.add(match[1]!);
481
+ }
354
482
  }
355
483
  }
356
484
  for (const match of stderr.matchAll(/path:\s*['"]([^'"]+)['"]/g)) {
@@ -360,6 +488,7 @@ export function discoverExternalPaths(ctx: RunContext, outcome: ExecOutcome): st
360
488
  const root = ctx.sandbox.root;
361
489
  return [...found]
362
490
  .map((candidate) => path.resolve(candidate))
491
+ .map((candidate) => candidate.replace(/\/\*+$/, ""))
363
492
  .filter((candidate) => candidate !== root && !candidate.startsWith(`${root}${path.sep}`))
364
493
  .filter((candidate, index, all) => all.indexOf(candidate) === index);
365
494
  }