opencode-fs-plugin 1.8.0 → 1.10.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
@@ -72,7 +72,7 @@ unit, end-to-end and coverage tests.
72
72
  | `cpio` | `fs.cpio` | `create`/`list`/`extract` (newc), `directory`, `members`, `input`, `member`, `verbose` |
73
73
  | `ar` | `fs.ar` | `create`/`list`/`extract`, `directory`, `members` |
74
74
  | HTTP(S) | `fs.http_request` | `url`, `method`, `headers`, `body`, `json`, `output`, `checksum`, `maxBytes`, `timeoutMs`, `failOnError`, `followRedirects`, `maxRedirects` |
75
- | process | `fs.exec` | `command`, `args`, `cwd`, `stdin`, `timeoutMs`; exact allowlist, no shell |
75
+ | process | `fs.exec` | `command`, `args`, `cwd`, `stdin`, `timeoutMs`; exact allowlist, procage sandbox, no shell |
76
76
  | shell pipe | `fs.pipe` | `stages`, `input`, `output`, `append` |
77
77
 
78
78
  `fs.head.skip` selects line ranges (`sed -n '20,40p'`). `fs.find` can
@@ -128,9 +128,9 @@ work, fan out with `Promise.all` over `tools.fs.*` (or one multi-path call).
128
128
 
129
129
  ## Exec
130
130
 
131
- `fs.exec` runs one allowlisted executable with `shell: false`. The default
132
- allowlist is `npm`, `npx`, `uv`, `uvx`, `pip`, `pip3`; override it in the plugin
133
- options:
131
+ `fs.exec` runs one allowlisted executable inside a procage sandbox with
132
+ `shell: false`. The default allowlist is `npm`, `npx`, `uv`, `uvx`, `pip`,
133
+ `pip3`; override it in the plugin options:
134
134
 
135
135
  ```jsonc
136
136
  {
@@ -139,12 +139,27 @@ options:
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.
145
+
146
+ - blocked path → `external_directory` for the absolute path
147
+ - blocked socket → `fs_exec_network`
148
+
149
+ 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
151
+ reports `violations` and a `hint`. `fs.exec` also kills every process it started
152
+ when the run ends, including detached descendants.
153
+
154
+ ```js
155
+ await tools.fs.exec({ command: "npm", args: ["install"], timeoutMs: 300000 })
156
+ ```
157
+
142
158
  `command` is a bare name, `args` are literal, and `cwd` is sandboxed. Direct
143
- calls return JSON with `exitCode`, `stdout`, and `stderr`; a pipe stage returns
144
- raw stdout so it composes with `grep`, `sort`, `tee`, and the rest.
159
+ calls return JSON with `exitCode`, `stdout`, `stderr`, and violations; a pipe
160
+ stage returns raw stdout so it composes with `grep`, `sort`, `tee`, and the rest.
145
161
 
146
162
  ```js
147
- await tools.fs.exec({ command: "npm", args: ["run", "build"], timeoutMs: 300000 })
148
163
  await tools.fs.pipe({
149
164
  stages: [
150
165
  { tool: "exec", args: { command: "npm", args: ["test"] } },
@@ -153,8 +168,11 @@ await tools.fs.pipe({
153
168
  })
154
169
  ```
155
170
 
156
- The command asserts `fs_exec`, uses a process group for timeout kills, caps
157
- stdout/stderr, and treats a non-zero exit as a normal result.
171
+ The command asserts `fs_exec`, caps stdout/stderr, and treats a non-zero exit as
172
+ a normal result. Procage requires Linux x64/arm64, glibc 2.28+, and Node 22.12+.
173
+ On kernels before Landlock ABI 6, signal isolation relaxes to same-user. The
174
+ trust-handoff class is waived so package tools can update workspace files such as
175
+ `.git/hooks`; the executable allowlist remains the trust boundary.
158
176
 
159
177
  ## Performance and concurrency
160
178
 
@@ -241,18 +259,18 @@ Add the registry package directly to the plugin list:
241
259
 
242
260
  ```jsonc
243
261
  {
244
- "plugins": ["opencode-fs-plugin@1.5.1"]
262
+ "plugins": ["opencode-fs-plugin@1.10.0"]
245
263
  }
246
264
  ```
247
265
 
248
- `opencode plugin add opencode-fs-plugin@1.5.1` installs it and writes the config
266
+ `opencode plugin add opencode-fs-plugin@1.10.0` installs it and writes the config
249
267
  entry. A bare `opencode-fs-plugin` follows the `latest` tag.
250
268
 
251
269
  OpenCode manages the package under its cache, so the path is not stable. If you
252
270
  also want the packaged skill, install it into a project instead:
253
271
 
254
272
  ```bash
255
- npm install opencode-fs-plugin@1.5.1
273
+ npm install opencode-fs-plugin@1.10.0
256
274
  ```
257
275
 
258
276
  ```jsonc
@@ -267,7 +285,7 @@ npm install opencode-fs-plugin@1.5.1
267
285
  Download the release tarball, then install it as a normal npm package:
268
286
 
269
287
  ```bash
270
- VERSION=1.5.1
288
+ VERSION=1.10.0
271
289
  curl -L -o "opencode-fs-plugin-${VERSION}.tgz" \
272
290
  "https://github.com/masterjg/opencode-fs-plugin/releases/download/v${VERSION}/opencode-fs-plugin-${VERSION}.tgz"
273
291
  npm install "./opencode-fs-plugin-${VERSION}.tgz"
@@ -296,20 +314,20 @@ OpenCode installs it from Git:
296
314
 
297
315
  ```jsonc
298
316
  {
299
- "plugins": ["github:masterjg/opencode-fs-plugin#v1.5.1"]
317
+ "plugins": ["github:masterjg/opencode-fs-plugin#v1.10.0"]
300
318
  }
301
319
  ```
302
320
 
303
- `opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.5.1'` installs the
321
+ `opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.10.0'` installs the
304
322
  same spec and writes the config entry. The equivalent full URL is
305
- `git+https://github.com/masterjg/opencode-fs-plugin.git#v1.5.1`. A tag is
323
+ `git+https://github.com/masterjg/opencode-fs-plugin.git#v1.10.0`. A tag is
306
324
  checked for updates; use a full commit hash to pin it.
307
325
 
308
326
  Git plugins are installed under OpenCode's cache, so their package path is not
309
327
  stable. If you also want the packaged skill, install with npm instead:
310
328
 
311
329
  ```bash
312
- npm install "github:masterjg/opencode-fs-plugin#v1.5.1"
330
+ npm install "github:masterjg/opencode-fs-plugin#v1.10.0"
313
331
  ```
314
332
 
315
333
  Then use `./node_modules/opencode-fs-plugin` in `plugins` and
@@ -367,6 +385,18 @@ Every tool asserts an action named after the tool (`fs_cp`, `fs_rm`,
367
385
  external targets first require `external_directory` on the absolute boundary.
368
386
  `allow always` persists the same patterns as the built-in tools.
369
387
 
388
+ `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:
390
+
391
+ ```jsonc
392
+ {
393
+ "permissions": [
394
+ { "action": "external_directory", "resource": "$HOME/.npm/**", "effect": "ask" },
395
+ { "action": "fs_exec_network", "resource": "*", "effect": "ask" }
396
+ ]
397
+ }
398
+ ```
399
+
370
400
  `fs.http_request` is allowed by default, like `fetch`. Its resource is the
371
401
  request host (`example.com:8443`), so requests can be restricted per host:
372
402
 
package/SPEC.md CHANGED
@@ -80,19 +80,37 @@ Aliases are accepted only where noted: `path` for one `paths` element (`stat`,
80
80
 
81
81
  ## Process execution
82
82
 
83
- - `fs.exec` is the only `child_process` use. It spawns with `shell: false`; there
84
- is no shell parsing, redirection, or command substitution.
83
+ - `fs.exec` is the only tool that starts processes, through `procage`; it never
84
+ uses `child_process`, `spawn`, or a shell.
85
85
  - `command` must be a bare executable name and must match the allowlist exactly.
86
86
  Default: `npm`, `npx`, `uv`, `uvx`, `pip`, `pip3`. Override with the plugin
87
87
  option `execAllowlist`; an empty list disables execution.
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.
95
+ - If a path or socket stays blocked after approval, the result reports
96
+ `violations` plus a `hint`; stderr containing EACCES/EPERM/EROFS marks
97
+ `sandboxBlocked`.
88
98
  - `args` are passed verbatim. `cwd` resolves inside the sandbox and asserts
89
99
  `external_directory` when it leaves the project; the action is `fs_exec`.
90
- - Timeout defaults to 120000 ms, capped at 600000. A timeout kills the process
91
- group (SIGTERM, then SIGKILL) and reports `timedOut: true`, exit code 124.
100
+ - Timeout defaults to 120000 ms, capped at 600000. Procage ends the run and kills
101
+ every process it started, including detached descendants; `timedOut: true`
102
+ and exit code 124 are returned.
92
103
  - Captured stdout/stderr are capped at `maxOutputBytes`; truncation is reported.
93
- - Direct calls return JSON with `exitCode`, `stdout`, and `stderr`. In `fs.pipe`,
94
- the stage returns raw stdout and composes as a source or filter.
104
+ - Direct calls return JSON with `exitCode`, `stdout`, `stderr`, `violations`, and
105
+ the sandbox decision. In `fs.pipe`, the stage returns raw stdout and composes as
106
+ a source or filter.
95
107
  - A non-zero exit is a normal result, not a tool error.
108
+ - `procage` is lazy-loaded; if the host cannot load it, `fs.exec` fails with
109
+ `unsupported` while the other fs tools continue to work. Requires Linux
110
+ x64/arm64, glibc 2.28+, and Node 22.12+. On kernels before Landlock ABI 6,
111
+ signals are relaxed from self-and-children to same-user, as procage requires.
112
+ The trust-handoff class is waived so package tools can update workspace files
113
+ such as `.git/hooks`; the executable allowlist remains the trust boundary.
96
114
 
97
115
  ## Deliberate gaps
98
116
 
package/package.json CHANGED
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "name": "opencode-fs-plugin",
3
- "version": "1.8.0",
3
+ "version": "1.10.0",
4
4
  "type": "module",
5
+ "engines": {
6
+ "node": ">=22.12"
7
+ },
5
8
  "description": "OpenCode 2 plugin: Linux-style filesystem, text, and HTTP(S) tools under the fs namespace.",
6
9
  "repository": {
7
10
  "type": "git",
@@ -33,6 +36,7 @@
33
36
  "@sinclair/typebox": "^0.34.52",
34
37
  "diff": "^9.0.0",
35
38
  "picomatch": "^4.0.7",
39
+ "procage": "^0.8.0",
36
40
  "tar-stream": "^3.2.2",
37
41
  "yauzl": "^3.4.0",
38
42
  "yazl": "^3.3.1"
@@ -148,22 +148,29 @@ remove them explicitly.
148
148
 
149
149
  ## Exec
150
150
 
151
- `fs.exec` runs an allowlisted executable without a shell. The default allowlist
152
- is `npm`, `npx`, `uv`, `uvx`, `pip`, `pip3`; override it with the fs plugin
153
- option `execAllowlist` in `opencode.jsonc`:
151
+ `fs.exec` runs an allowlisted executable in a **procage sandbox** without a
152
+ shell. The default allowlist is `npm`, `npx`, `uv`, `uvx`, `pip`, `pip3`;
153
+ override it with the fs plugin option `execAllowlist` in `opencode.jsonc`:
154
154
 
155
155
  ```jsonc
156
156
  { "package": "./repos/opencode-fs-plugin", "options": { "execAllowlist": ["npm", "uv"] } }
157
157
  ```
158
158
 
159
- `command` is a bare executable name; `args` are passed verbatim, so `;`, `|`,
160
- and `$()` have no shell meaning. `cwd` must resolve inside the project unless
161
- `external_directory` allows it. Direct calls return JSON with
162
- `exitCode`/`stdout`/`stderr`; in `fs.pipe` the stage passes raw stdout.
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`:
163
+
164
+ ```js
165
+ await tools.fs.exec({ command: "npm", args: ["install"], timeoutMs: 300000 })
166
+ ```
167
+
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.
163
172
 
164
173
  ```js
165
- await tools.fs.exec({ command: "npm", args: ["run", "build"], timeoutMs: 300000 })
166
- await tools.fs.exec({ command: "uv", args: ["run", "pytest"] })
167
174
  await tools.fs.pipe({
168
175
  stages: [
169
176
  { tool: "exec", args: { command: "npm", args: ["test"] } },
@@ -173,8 +180,9 @@ await tools.fs.pipe({
173
180
  ```
174
181
 
175
182
  A non-zero exit is a normal result; allowlist rejection, timeout, and abort are
176
- errors. The tool asserts `fs_exec`, uses a process group for timeout kills, and
177
- caps captured stdout/stderr.
183
+ handled explicitly. Procage kills every process the run started, including
184
+ detached descendants, and caps captured stdout/stderr. It requires Linux
185
+ x64/arm64, glibc 2.28+, and Node 22.12+.
178
186
 
179
187
  ## Batch independent calls
180
188
 
@@ -407,6 +415,8 @@ await tools.fs.http_request({
407
415
  - Linux only; there is no Windows branch.
408
416
  - `fs.sed` supports `s<delim>pattern<delim>replacement<delim>flags` with `g`,
409
417
  `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.
410
420
  - `fs.find` has no arbitrary `-exec`; use `action: "delete"`/`"trash"` for the
411
421
  common cleanup case, or `fs.rm`/`fs.trash` separately.
412
422
  - No `xz`, `zstd`, `7z`, `rar`, `chattr`, ACLs, xattrs, or `rsync`.
@@ -460,8 +470,10 @@ Command actions are `fs_<command>` (for example `fs_cp`). `fs_*` wildcards work
460
470
  in agent rules. `fs.pipe` asserts each stage's action; a denied stage cannot be
461
471
  hidden inside a pipeline. Do not work around a denied tool with shell.
462
472
 
463
- `fs_exec` runs only exact allowlisted names and asserts `fs_exec` plus
464
- `external_directory` when `cwd` leaves the project. There is no shell.
473
+ `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.
465
477
 
466
478
  `fs_http_request` is allowed by default, like `fetch`. Its resource is the
467
479
  request host; rules can allow one host and ask or deny the rest. Each redirect
package/src/tools/exec.ts CHANGED
@@ -3,10 +3,13 @@
3
3
  * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
4
  */
5
5
 
6
- import { spawn, type ChildProcess } from "node:child_process";
7
- import { once } from "node:events";
6
+ import * as fs from "node:fs/promises";
7
+ import { constants as fsConstants } from "node:fs";
8
+ import * as path from "node:path";
8
9
  import { Type, type Static } from "@sinclair/typebox";
9
- import { FsError, fromErrno } from "../core/errors.js";
10
+ import type { Violation } from "procage";
11
+ import { FsError } from "../core/errors.js";
12
+ import { collect } from "../core/stream.js";
10
13
  import { textResult, type RunContext, type ToolSpec } from "../core/types.js";
11
14
 
12
15
  export const DEFAULT_EXEC_ALLOWLIST = ["npm", "npx", "uv", "uvx", "pip", "pip3"] as const;
@@ -45,22 +48,37 @@ const Schema = Type.Object(
45
48
 
46
49
  type Input = Static<typeof Schema>;
47
50
 
48
- interface ExecOutcome {
51
+ interface PolicyDocument {
52
+ fs: Array<{ access: string; target: { subpath: string } }>;
53
+ net: string;
54
+ [key: string]: unknown;
55
+ }
56
+
57
+ export interface ExecOutcome {
49
58
  stdout: Buffer;
50
59
  stderr: Buffer;
51
60
  exitCode: number;
52
- signal: NodeJS.Signals | null;
61
+ signal: string | null;
53
62
  timedOut: boolean;
54
63
  aborted: boolean;
55
64
  stdoutTruncated: boolean;
56
65
  stderrTruncated: boolean;
66
+ violations: Violation[];
67
+ }
68
+
69
+ let procage: Promise<typeof import("procage")> | undefined;
70
+
71
+ function loadProcage(): Promise<typeof import("procage")> {
72
+ procage ??= import("procage");
73
+ return procage;
57
74
  }
58
75
 
59
76
  export const execTool: ToolSpec<Input> = {
60
77
  name: "exec",
61
78
  description:
62
- "Run an allowlisted executable without a shell and return its exit code, stdout, and stderr. " +
63
- "Direct calls return JSON; pipe stages pass raw stdout. Default allowlist: npm, npx, uv, uvx, pip, pip3.",
79
+ "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.",
64
82
  schema: Schema,
65
83
  pipeable: "filter",
66
84
  mutates: true,
@@ -78,178 +96,289 @@ export const execTool: ToolSpec<Input> = {
78
96
  }
79
97
 
80
98
  const requested = input.cwd ?? ".";
81
- const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
82
- const stats = await ctx.sandbox.stat(target.full, requested);
83
- if (!stats.isDirectory()) throw new FsError(`exec cwd is not a directory: "${requested}"`, "not-directory");
84
- await ctx.permission.assert([{ target, boundary: target.full }]);
99
+ const cwdTarget = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
100
+ const cwdStats = await ctx.sandbox.stat(cwdTarget.full, requested);
101
+ if (!cwdStats.isDirectory()) throw new FsError(`exec cwd is not a directory: "${requested}"`, "not-directory");
102
+ await ctx.permission.assert([{ target: cwdTarget, boundary: cwdTarget.full }]);
85
103
  if (ctx.signal.aborted) throw new FsError("exec interrupted.", "interrupted");
86
104
 
87
- const outcome = await runProcess(
88
- ctx,
89
- command,
90
- args,
91
- target.full,
92
- input.timeoutMs ?? 120_000,
93
- input.stdin,
94
- io.stdin,
95
- );
96
- const metadata = {
97
- command,
98
- args,
99
- exitCode: outcome.exitCode,
100
- signal: outcome.signal,
101
- timedOut: outcome.timedOut,
102
- aborted: outcome.aborted,
103
- stdoutTruncated: outcome.stdoutTruncated,
104
- stderrTruncated: outcome.stderrTruncated,
105
- };
106
- if (io.piped === true) {
107
- return {
108
- stdout: outcome.stdout,
105
+ const executable = await resolveExecutable(command);
106
+ const tempDir = await fs.mkdtemp(path.join(ctx.tmpdir, "fs-exec-"));
107
+ try {
108
+ const inputData = io.stdin === undefined
109
+ ? input.stdin === undefined ? undefined : Buffer.from(input.stdin)
110
+ : await collect(io.stdin);
111
+ let networkAllowed = false;
112
+ const approved: Array<{ full: string }> = [];
113
+ let outcome: ExecOutcome | undefined;
114
+
115
+ for (let attempt = 0; attempt < 6; attempt++) {
116
+ outcome = await runCaged(ctx, {
117
+ command,
118
+ executable,
119
+ args,
120
+ cwd: cwdTarget.full,
121
+ timeoutMs: input.timeoutMs ?? 120_000,
122
+ network: networkAllowed,
123
+ allowed: approved,
124
+ tempDir,
125
+ input: inputData,
126
+ });
127
+
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) {
134
+ await ctx.permissionFor("fs_exec_network").assert([]);
135
+ networkAllowed = true;
136
+ continue;
137
+ }
138
+
139
+ let added = false;
140
+ for (const candidate of deniedPaths) {
141
+ const target = await ctx.sandbox.resolveExisting(candidate, { allowRoot: true }).catch(() => undefined);
142
+ if (target === undefined) continue;
143
+ await ctx.permission.assert([{ target, boundary: target.full }]);
144
+ approved.push({ full: target.full });
145
+ added = true;
146
+ }
147
+ if (!added) break;
148
+ }
149
+
150
+ /* v8 ignore next */
151
+ if (outcome === undefined) throw new FsError("exec produced no result.", "io");
152
+ const metadata = {
153
+ command,
154
+ args,
155
+ exitCode: outcome.exitCode,
156
+ signal: outcome.signal,
157
+ timedOut: outcome.timedOut,
158
+ aborted: outcome.aborted,
159
+ stdoutTruncated: outcome.stdoutTruncated,
160
+ stderrTruncated: outcome.stderrTruncated,
161
+ sandboxBlocked: isSandboxBlocked(outcome),
162
+ violations: outcome.violations.length,
163
+ network: networkAllowed,
164
+ externalPaths: approved.map((entry) => entry.full),
165
+ };
166
+ if (io.piped === true) {
167
+ return {
168
+ stdout: outcome.stdout,
169
+ stderr: outcome.stderr.toString("utf8"),
170
+ exitCode: outcome.exitCode === 0 ? 0 : 1,
171
+ metadata,
172
+ };
173
+ }
174
+ const sandboxBlocked = isSandboxBlocked(outcome);
175
+ const body = {
176
+ ...metadata,
177
+ stdout: outcome.stdout.toString("utf8"),
109
178
  stderr: outcome.stderr.toString("utf8"),
110
- exitCode: outcome.exitCode === 0 ? 0 : 1,
111
- metadata,
179
+ 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
+ : {}),
112
186
  };
187
+ return textResult(JSON.stringify(body, null, 2), metadata, outcome.exitCode === 0 ? 0 : 1);
188
+ } finally {
189
+ /* v8 ignore next 5 */
190
+ try {
191
+ await fs.rm(tempDir, { recursive: true, force: true });
192
+ } catch {
193
+ /* already gone */
194
+ }
113
195
  }
114
- const body = {
115
- ...metadata,
116
- stdout: outcome.stdout.toString("utf8"),
117
- stderr: outcome.stderr.toString("utf8"),
118
- };
119
- return textResult(JSON.stringify(body, null, 2), metadata, outcome.exitCode === 0 ? 0 : 1);
120
196
  },
121
197
  };
122
198
 
123
- function runProcess(
124
- ctx: RunContext,
125
- command: string,
126
- args: string[],
127
- cwd: string,
128
- timeoutMs: number,
129
- input: string | undefined,
130
- pipe: AsyncIterable<Buffer> | undefined,
131
- ): Promise<ExecOutcome> {
132
- return new Promise((resolve, reject) => {
133
- const feed = input !== undefined || pipe !== undefined;
134
- const child = spawn(command, args, {
135
- cwd,
136
- env: process.env,
137
- shell: false,
138
- detached: process.platform !== "win32",
139
- stdio: [feed ? "pipe" : "ignore", "pipe", "pipe"],
140
- windowsHide: true,
141
- });
142
- const cap = ctx.maxOutputBytes;
143
- let stdout: Buffer<ArrayBufferLike> = Buffer.alloc(0);
144
- let stderr: Buffer<ArrayBufferLike> = Buffer.alloc(0);
145
- let stdoutTruncated = false;
146
- let stderrTruncated = false;
147
- let timedOut = false;
148
- let aborted = false;
149
- let settled = false;
150
- let forceTimer: NodeJS.Timeout | undefined;
151
-
152
- child.stdout?.on("data", (chunk: Buffer) => {
153
- const next = appendCapped(stdout, chunk, cap);
154
- stdout = next.data;
155
- stdoutTruncated ||= next.truncated;
199
+ interface CagedInput {
200
+ command: string;
201
+ executable: { path: string; real: string };
202
+ args: string[];
203
+ cwd: string;
204
+ timeoutMs: number;
205
+ network: boolean;
206
+ allowed: Array<{ full: string }>;
207
+ tempDir: string;
208
+ input: Buffer | undefined;
209
+ }
210
+
211
+ async function runCaged(ctx: RunContext, input: CagedInput): Promise<ExecOutcome> {
212
+ let api: typeof import("procage");
213
+ try {
214
+ api = await loadProcage();
215
+ } catch (error) {
216
+ /* v8 ignore next */
217
+ throw new FsError(`exec sandbox is unavailable: ${String(error)}`, "unsupported");
218
+ }
219
+
220
+ const doc = api.Policy.preset("agent_workspace", 3, { workspace: ctx.sandbox.root }).toJSON() as PolicyDocument;
221
+ doc.net = input.network ? "ip" : "none";
222
+ addRule(doc, "exec", path.dirname(input.executable.path));
223
+ addRule(doc, "exec", path.dirname(input.executable.real));
224
+ addRule(doc, "exec", path.dirname(process.execPath));
225
+ addRule(doc, "exec", path.resolve(path.dirname(process.execPath), ".."));
226
+ addRule(doc, "exec", path.dirname(input.executable.real));
227
+ addRule(doc, "exec", path.resolve(path.dirname(input.executable.real), ".."));
228
+ for (const root of ["/home/linuxbrew", "/var/home/linuxbrew"]) {
229
+ try {
230
+ await fs.access(root);
231
+ addRule(doc, "read", root);
232
+ addRule(doc, "exec", root);
233
+ } catch {
234
+ // Homebrew is optional.
235
+ }
236
+ }
237
+ addRule(doc, "write", input.tempDir);
238
+ addRule(doc, "write", input.cwd);
239
+ for (const allowed of input.allowed) addRule(doc, "write", allowed.full);
240
+
241
+ let cage: InstanceType<typeof api.Cage>;
242
+ let policy: ReturnType<typeof api.Policy.fromJSON>;
243
+ try {
244
+ 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"],
156
249
  });
157
- child.stderr?.on("data", (chunk: Buffer) => {
158
- const next = appendCapped(stderr, chunk, cap);
159
- stderr = next.data;
160
- stderrTruncated ||= next.truncated;
250
+ } catch (error) {
251
+ /* v8 ignore next */
252
+ throw new FsError(`exec policy rejected: ${String(error)}`, "unsupported");
253
+ }
254
+
255
+ const env = Object.fromEntries(
256
+ Object.entries(process.env).filter((entry): entry is [string, string] => entry[1] !== undefined),
257
+ );
258
+ env.TMPDIR = input.tempDir;
259
+
260
+ let child;
261
+ try {
262
+ child = await cage.spawn([input.executable.path, ...input.args], {
263
+ cwd: input.cwd,
264
+ env,
265
+ stdin: input.input !== undefined,
161
266
  });
267
+ } catch (error) {
268
+ /* v8 ignore next */
269
+ throw new FsError(`exec spawn failed: ${String(error)}`, "unsupported");
270
+ }
162
271
 
163
- const timer = setTimeout(() => {
164
- timedOut = true;
165
- killTree(child, "SIGTERM");
166
- forceTimer = setTimeout(() => killTree(child, "SIGKILL"), 2_000);
167
- forceTimer.unref();
168
- }, timeoutMs);
169
- const onAbort = () => {
170
- aborted = true;
171
- killTree(child, "SIGTERM");
272
+ let aborted = false;
273
+ const onAbort = () => {
274
+ aborted = true;
275
+ child?.kill();
276
+ };
277
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
278
+ try {
279
+ const out = await child.output({ timeout: input.timeoutMs, ...(input.input === undefined ? {} : { input: input.input }) });
280
+ const violations = filterViolations(await child.violations());
281
+ const stdout = cap(out.stdout, ctx.maxOutputBytes);
282
+ const stderr = cap(out.stderr, ctx.maxOutputBytes);
283
+ return {
284
+ stdout: stdout.data,
285
+ stderr: stderr.data,
286
+ exitCode: out.timedOut ? 124 : aborted ? 130 : (out.exitCode ?? 1),
287
+ signal: out.signal,
288
+ timedOut: out.timedOut,
289
+ aborted,
290
+ stdoutTruncated: stdout.truncated,
291
+ stderrTruncated: stderr.truncated,
292
+ violations,
172
293
  };
173
- ctx.signal.addEventListener("abort", onAbort, { once: true });
294
+ } catch (error) {
295
+ /* v8 ignore next 14 */
296
+ if (aborted || ctx.signal.aborted) {
297
+ return {
298
+ stdout: Buffer.alloc(0),
299
+ stderr: Buffer.alloc(0),
300
+ exitCode: 130,
301
+ signal: null,
302
+ timedOut: false,
303
+ aborted: true,
304
+ stdoutTruncated: false,
305
+ stderrTruncated: false,
306
+ violations: [],
307
+ };
308
+ }
309
+ /* v8 ignore next */
310
+ throw new FsError(`exec failed: ${String(error)}`, "unsupported");
311
+ } finally {
312
+ ctx.signal.removeEventListener("abort", onAbort);
313
+ child.close();
314
+ }
315
+ }
174
316
 
175
- const cleanup = () => {
176
- clearTimeout(timer);
177
- if (forceTimer) clearTimeout(forceTimer);
178
- ctx.signal.removeEventListener("abort", onAbort);
179
- };
180
- child.on("error", (error) => {
181
- /* v8 ignore next */
182
- if (settled) return;
183
- settled = true;
184
- cleanup();
185
- reject(fromErrno(error));
186
- });
187
- child.on("close", (code, signal) => {
188
- if (settled) return;
189
- settled = true;
190
- cleanup();
191
- resolve({
192
- stdout,
193
- stderr,
194
- exitCode: timedOut ? 124 : aborted ? 130 : (code ?? 1),
195
- signal,
196
- timedOut,
197
- aborted,
198
- stdoutTruncated,
199
- stderrTruncated,
200
- });
201
- });
317
+ function addRule(doc: PolicyDocument, access: string, target: string): void {
318
+ const subpath = path.resolve(target);
319
+ if (doc.fs.some((rule) => rule.access === access && rule.target.subpath === subpath)) return;
320
+ doc.fs.push({ access, target: { subpath } });
321
+ }
202
322
 
203
- if (feed) void feedStdin(child, input, pipe);
323
+ export function filterViolations(violations: readonly Violation[]): Violation[] {
324
+ return violations.filter((violation) => {
325
+ if (violation.target?.startsWith("/")) return true;
326
+ return /AF_INET|AF_INET6/.test(violation.target ?? "");
204
327
  });
205
328
  }
206
329
 
207
- async function feedStdin(
208
- child: ChildProcess,
209
- input: string | undefined,
210
- pipe: AsyncIterable<Buffer> | undefined,
211
- ): Promise<void> {
212
- const stdin = child.stdin;
213
- /* v8 ignore next */
214
- if (!stdin) return;
215
- try {
216
- stdin.on("error", () => undefined);
217
- if (pipe !== undefined) {
218
- for await (const chunk of pipe) {
219
- if (!stdin.write(chunk)) await once(stdin, "drain");
220
- }
221
- } else {
222
- stdin.write(input as string);
330
+ export function isSandboxBlocked(outcome: ExecOutcome): boolean {
331
+ if (outcome.violations.length > 0) return true;
332
+ if (outcome.exitCode === 0) return false;
333
+ return /EACCES|EPERM|EROFS|Permission denied|Read-only file system/i.test(outcome.stderr.toString("utf8"));
334
+ }
335
+
336
+ export function detectsNetworkDenial(outcome: ExecOutcome): boolean {
337
+ if (outcome.violations.some((violation) => /AF_INET|AF_INET6/.test(violation.target ?? ""))) return true;
338
+ return /EAI_AGAIN|getaddrinfo|ENETUNREACH|ECONNREFUSED/i.test(outcome.stderr.toString("utf8"));
339
+ }
340
+
341
+ export function discoverExternalPaths(ctx: RunContext, outcome: ExecOutcome): string[] {
342
+ const found = new Set<string>();
343
+ for (const violation of outcome.violations) {
344
+ if (violation.target?.startsWith("/")) found.add(violation.target);
345
+ }
346
+
347
+ 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]!);
223
354
  }
224
- stdin.end();
225
- } catch {
226
- /* child closed before the write completed */
227
355
  }
228
- }
356
+ for (const match of stderr.matchAll(/path:\s*['"]([^'"]+)['"]/g)) {
357
+ found.add(match[1]!);
358
+ }
229
359
 
230
- function appendCapped(current: Buffer, chunk: Buffer, cap: number): { data: Buffer; truncated: boolean } {
231
- if (current.length >= cap) return { data: current, truncated: true };
232
- const remaining = cap - current.length;
233
- if (chunk.length <= remaining) return { data: Buffer.concat([current, chunk]), truncated: false };
234
- return { data: Buffer.concat([current, chunk.subarray(0, remaining)]), truncated: true };
360
+ const root = ctx.sandbox.root;
361
+ return [...found]
362
+ .map((candidate) => path.resolve(candidate))
363
+ .filter((candidate) => candidate !== root && !candidate.startsWith(`${root}${path.sep}`))
364
+ .filter((candidate, index, all) => all.indexOf(candidate) === index);
235
365
  }
236
366
 
237
- function killTree(child: ChildProcess, signal: NodeJS.Signals): void {
238
- /* v8 ignore next */
239
- if (!child.pid) return;
240
- /* v8 ignore next */
241
- if (process.platform !== "win32") {
367
+ async function resolveExecutable(command: string): Promise<{ path: string; real: string }> {
368
+ const directories = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
369
+ for (const directory of directories) {
370
+ const candidate = path.join(directory, command);
242
371
  try {
243
- process.kill(-child.pid, signal);
244
- return;
372
+ await fs.access(candidate, fsConstants.X_OK);
373
+ return { path: candidate, real: await fs.realpath(candidate) };
245
374
  } catch {
246
- /* fall through to child.kill */
375
+ // keep searching PATH
247
376
  }
248
377
  }
249
- /* v8 ignore next 5 */
250
- try {
251
- child.kill(signal);
252
- } catch {
253
- /* already gone */
254
- }
378
+ throw new FsError(`exec command not found: "${command}"`, "not-found");
379
+ }
380
+
381
+ function cap(data: Buffer, limit: number): { data: Buffer; truncated: boolean } {
382
+ if (data.length <= limit) return { data, truncated: false };
383
+ return { data: data.subarray(0, limit), truncated: true };
255
384
  }