opencode-fs-plugin 1.7.0 → 1.9.2

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,6 +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`, `network`, `allowPaths`; exact allowlist, procage sandbox, no shell |
75
76
  | shell pipe | `fs.pipe` | `stages`, `input`, `output`, `append` |
76
77
 
77
78
  `fs.head.skip` selects line ranges (`sed -n '20,40p'`). `fs.find` can
@@ -102,7 +103,7 @@ await tools.fs.pipe({
102
103
  })
103
104
  ```
104
105
 
105
- New filter stages: `tac`, `rev`, `nl`, `paste`, `shuf`, `fold`, `base64`, `od`,
106
+ New filter stages: `exec`, `tac`, `rev`, `nl`, `paste`, `shuf`, `fold`, `base64`, `od`,
106
107
  and `strings`; `dd` and `cpio` are source/sink stages like `tar`.
107
108
 
108
109
  `fs.http_request` is a pipe source, so network data can feed the same stages:
@@ -119,12 +120,62 @@ await tools.fs.pipe({
119
120
  Pipe stages exchange whole buffers, so use `maxBytes` for large responses. For
120
121
  large downloads prefer `fs.http_request({ output })`, which streams to disk.
121
122
 
122
- There is no shell, redirection operator, nested pipe, or `find -exec`.
123
+ There is no shell, redirection operator, nested pipe, or arbitrary `find -exec`.
123
124
 
124
125
  `fs.pipe` is sequential by design and is not a batch primitive. For independent
125
126
  work, fan out with `Promise.all` over `tools.fs.*` (or one multi-path call).
126
- `fs` domain errors resolve as `ERROR:`/`BLOCKED:` text, so check each result;
127
- permission denials throw.
127
+ `fs` domain errors resolve as `ERROR:`/`BLOCKED:` text; permission denials throw.
128
+
129
+ ## Exec
130
+
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
+
135
+ ```jsonc
136
+ {
137
+ "package": "./repos/opencode-fs-plugin",
138
+ "options": { "execAllowlist": ["npm", "uv"] }
139
+ }
140
+ ```
141
+
142
+ The workspace (project) is read/write/exec, but **network and external paths are
143
+ denied by default**. Approve them per call:
144
+
145
+ ```js
146
+ await tools.fs.exec({
147
+ command: "npm",
148
+ args: ["install"],
149
+ network: true,
150
+ allowPaths: [{ path: "/home/you/.npm", mode: "rw" }],
151
+ timeoutMs: 300000,
152
+ })
153
+ ```
154
+
155
+ `network: true` asserts `fs_exec_network`; every `allowPaths` entry asserts
156
+ `external_directory`. Use `mode: "ro"` for read-only paths. Denied operations
157
+ come back as `violations` and a `hint`; ask the user, then retry with the approved
158
+ paths or network. `fs.exec` also kills every process it started when the run
159
+ ends, including detached descendants.
160
+
161
+ `command` is a bare name, `args` are literal, and `cwd` is sandboxed. Direct
162
+ calls return JSON with `exitCode`, `stdout`, `stderr`, and violations; a pipe
163
+ stage returns raw stdout so it composes with `grep`, `sort`, `tee`, and the rest.
164
+
165
+ ```js
166
+ await tools.fs.pipe({
167
+ stages: [
168
+ { tool: "exec", args: { command: "npm", args: ["test"] } },
169
+ { tool: "grep", args: { pattern: "FAIL" } },
170
+ ],
171
+ })
172
+ ```
173
+
174
+ The command asserts `fs_exec`, caps stdout/stderr, and treats a non-zero exit as
175
+ a normal result. Procage requires Linux x64/arm64, glibc 2.28+, and Node 22.12+.
176
+ On kernels before Landlock ABI 6, signal isolation relaxes to same-user. The
177
+ trust-handoff class is waived so package tools can update workspace files such as
178
+ `.git/hooks`; the executable allowlist remains the trust boundary.
128
179
 
129
180
  ## Performance and concurrency
130
181
 
@@ -211,18 +262,18 @@ Add the registry package directly to the plugin list:
211
262
 
212
263
  ```jsonc
213
264
  {
214
- "plugins": ["opencode-fs-plugin@1.5.1"]
265
+ "plugins": ["opencode-fs-plugin@1.9.0"]
215
266
  }
216
267
  ```
217
268
 
218
- `opencode plugin add opencode-fs-plugin@1.5.1` installs it and writes the config
269
+ `opencode plugin add opencode-fs-plugin@1.9.0` installs it and writes the config
219
270
  entry. A bare `opencode-fs-plugin` follows the `latest` tag.
220
271
 
221
272
  OpenCode manages the package under its cache, so the path is not stable. If you
222
273
  also want the packaged skill, install it into a project instead:
223
274
 
224
275
  ```bash
225
- npm install opencode-fs-plugin@1.5.1
276
+ npm install opencode-fs-plugin@1.9.0
226
277
  ```
227
278
 
228
279
  ```jsonc
@@ -237,7 +288,7 @@ npm install opencode-fs-plugin@1.5.1
237
288
  Download the release tarball, then install it as a normal npm package:
238
289
 
239
290
  ```bash
240
- VERSION=1.5.1
291
+ VERSION=1.9.0
241
292
  curl -L -o "opencode-fs-plugin-${VERSION}.tgz" \
242
293
  "https://github.com/masterjg/opencode-fs-plugin/releases/download/v${VERSION}/opencode-fs-plugin-${VERSION}.tgz"
243
294
  npm install "./opencode-fs-plugin-${VERSION}.tgz"
@@ -266,20 +317,20 @@ OpenCode installs it from Git:
266
317
 
267
318
  ```jsonc
268
319
  {
269
- "plugins": ["github:masterjg/opencode-fs-plugin#v1.5.1"]
320
+ "plugins": ["github:masterjg/opencode-fs-plugin#v1.9.0"]
270
321
  }
271
322
  ```
272
323
 
273
- `opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.5.1'` installs the
324
+ `opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.9.0'` installs the
274
325
  same spec and writes the config entry. The equivalent full URL is
275
- `git+https://github.com/masterjg/opencode-fs-plugin.git#v1.5.1`. A tag is
326
+ `git+https://github.com/masterjg/opencode-fs-plugin.git#v1.9.0`. A tag is
276
327
  checked for updates; use a full commit hash to pin it.
277
328
 
278
329
  Git plugins are installed under OpenCode's cache, so their package path is not
279
330
  stable. If you also want the packaged skill, install with npm instead:
280
331
 
281
332
  ```bash
282
- npm install "github:masterjg/opencode-fs-plugin#v1.5.1"
333
+ npm install "github:masterjg/opencode-fs-plugin#v1.9.0"
283
334
  ```
284
335
 
285
336
  Then use `./node_modules/opencode-fs-plugin` in `plugins` and
@@ -337,6 +388,17 @@ Every tool asserts an action named after the tool (`fs_cp`, `fs_rm`,
337
388
  external targets first require `external_directory` on the absolute boundary.
338
389
  `allow always` persists the same patterns as the built-in tools.
339
390
 
391
+ `fs.exec` asserts `fs_exec`; `network: true` also asserts `fs_exec_network`, and
392
+ each `allowPaths` entry asserts `external_directory`:
393
+
394
+ ```jsonc
395
+ {
396
+ "permissions": [
397
+ { "action": "fs_exec_network", "resource": "*", "effect": "ask" }
398
+ ]
399
+ }
400
+ ```
401
+
340
402
  `fs.http_request` is allowed by default, like `fetch`. Its resource is the
341
403
  request host (`example.com:8443`), so requests can be restricted per host:
342
404
 
package/SPEC.md CHANGED
@@ -78,6 +78,38 @@ Aliases are accepted only where noted: `path` for one `paths` element (`stat`,
78
78
  - `maxBytes` is enforced while reading, for buffered and downloaded bodies.
79
79
  - Pipe use is a buffered source; whole bodies pass between stages.
80
80
 
81
+ ## Process execution
82
+
83
+ - `fs.exec` is the only tool that starts processes, through `procage`; it never
84
+ uses `child_process`, `spawn`, or a shell.
85
+ - `command` must be a bare executable name and must match the allowlist exactly.
86
+ Default: `npm`, `npx`, `uv`, `uvx`, `pip`, `pip3`. Override with the plugin
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.
90
+ - `network: true` asserts `fs_exec_network` and sets the policy network to IP.
91
+ `allowPaths` entries assert `external_directory`; `mode: "ro"` adds a read
92
+ rule, `mode: "rw"` adds a write rule.
93
+ - Denied file or network access is reported as `violations` plus a `hint`, and
94
+ stderr containing EACCES/EPERM/EROFS marks `sandboxBlocked`. Ask the user, then
95
+ retry with the approved paths or network.
96
+ - `args` are passed verbatim. `cwd` resolves inside the sandbox and asserts
97
+ `external_directory` when it leaves the project; the action is `fs_exec`.
98
+ - Timeout defaults to 120000 ms, capped at 600000. Procage ends the run and kills
99
+ every process it started, including detached descendants; `timedOut: true`
100
+ and exit code 124 are returned.
101
+ - Captured stdout/stderr are capped at `maxOutputBytes`; truncation is reported.
102
+ - Direct calls return JSON with `exitCode`, `stdout`, `stderr`, `violations`, and
103
+ the sandbox decision. In `fs.pipe`, the stage returns raw stdout and composes as
104
+ a source or filter.
105
+ - A non-zero exit is a normal result, not a tool error.
106
+ - `procage` is lazy-loaded; if the host cannot load it, `fs.exec` fails with
107
+ `unsupported` while the other fs tools continue to work. Requires Linux
108
+ x64/arm64, glibc 2.28+, and Node 22.12+. On kernels before Landlock ABI 6,
109
+ signals are relaxed from self-and-children to same-user, as procage requires.
110
+ The trust-handoff class is waived so package tools can update workspace files
111
+ such as `.git/hooks`; the executable allowlist remains the trust boundary.
112
+
81
113
  ## Deliberate gaps
82
114
 
83
115
  These are not implemented:
@@ -97,8 +129,8 @@ These are not implemented:
97
129
  - true streaming through pipe stages; `http_request` buffers unless `output` is set
98
130
  - worker threads for CPU-bound stages (`sort`, `sed`, text diffing)
99
131
  - parallel member reads inside a single `tar`/`zip` archive; member order is fixed
100
- - process start, `nohup`, `setsid`, and `timeout` wrappers; the plugin never
101
- uses `child_process`
132
+ - process start beyond the allowlisted `exec` tool; `nohup`, `setsid`, and
133
+ `timeout` wrappers are unavailable
102
134
  - ICMP `ping` (raw sockets) and `ip`/netlink configuration
103
135
  - `rsync`, `scp`, and other transfer protocols; use the SSH MCP for remote work
104
136
  - ACLs, xattrs, and `chattr`/`lsattr`
package/package.json CHANGED
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "name": "opencode-fs-plugin",
3
- "version": "1.7.0",
3
+ "version": "1.9.2",
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"
@@ -25,6 +25,7 @@ With `execute` allowed, call it as `tools.fs.<command>`; agents without
25
25
  | Regex substitution or in-place edit | `fs.sed` |
26
26
  | Recoverable deletion | `fs.trash` |
27
27
  | HTTP(S) fetch, API call, or file download | `fs.http_request` |
28
+ | Allowlisted package CLI | `fs.exec` (no shell; default npm/npx/uv/uvx/pip/pip3) |
28
29
  | Many independent fs calls | one multi-path call, else `Promise.all` in `execute` |
29
30
  | Sequential byte pipeline | `fs.pipe` |
30
31
 
@@ -53,6 +54,7 @@ what `fs.stat`, `fs.ls`, `fs.hash`, `fs.diff`, or `fs.cat` can confirm.
53
54
  | Text filters | `fs.cat`, `fs.head`, `fs.tail`, `fs.grep`, `fs.sed`, `fs.sort`, `fs.uniq`, `fs.cut`, `fs.tr`, `fs.wc`, `fs.tee`, `fs.tac`, `fs.rev`, `fs.nl`, `fs.paste`, `fs.comm`, `fs.split`, `fs.shuf`, `fs.fold` |
54
55
  | Compose filters | `fs.pipe` |
55
56
  | HTTP(S) | `fs.http_request` (`output`, `checksum`, `maxBytes`, `json`) |
57
+ | Allowlisted package CLI | `fs.exec` (`command`, `args`, `cwd`, `stdin`, `timeoutMs`) |
56
58
  | Processes | `fs.ps`, `fs.pgrep`, `fs.kill` (`dryRun` available) |
57
59
  | System info | `fs.id`, `fs.uname`, `fs.uptime`, `fs.date`, `fs.findmnt`, `fs.mountpoint` |
58
60
  | Binary inspection | `fs.file`, `fs.base64`, `fs.od`, `fs.strings` |
@@ -98,6 +100,7 @@ host drops unknown fields, so a name typo runs with defaults.
98
100
  | `paths` + optional `keep`/`force`/`stdout`/`level`/`suffix` | `fs.gzip`, `fs.gunzip` |
99
101
  | `url` + optional `output` | `fs.http_request` |
100
102
  | `stages` + optional `input`/`output` | `fs.pipe` |
103
+ | `command` + `args` + optional `cwd`/`stdin`/`timeoutMs`/`network`/`allowPaths` | `fs.exec` |
101
104
 
102
105
  `fs.head` takes `skip` for line ranges: `sed -n '20,40p'` is
103
106
  `fs.head({ paths, skip: 19, lines: 21 })`. `fs.find` takes
@@ -136,12 +139,56 @@ removed, and deletion asserts `fs_rm`/`fs_trash`.
136
139
  | `cat > f <<EOF` | built-in `write` or `fs.tee({ paths: [f], content })` |
137
140
  | `rg pattern path` | `fs.grep({ pattern, paths })` or the built-in `grep` |
138
141
  | `ls -l f` | `fs.ls({ paths: [f], long: true })` |
142
+ | `npm ...` / `uv run ...` | `fs.exec({ command, args })` (allowlisted only) |
139
143
 
140
144
  `sed -n` applied to another command's stdout has no fs equivalent; keep that in
141
145
  the command pipeline. `fs.find` has no arbitrary `-exec` by design; use
142
146
  `action: "delete"` or `"trash"` for the common cleanup case, or list the paths and
143
147
  remove them explicitly.
144
148
 
149
+ ## Exec
150
+
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
+
155
+ ```jsonc
156
+ { "package": "./repos/opencode-fs-plugin", "options": { "execAllowlist": ["npm", "uv"] } }
157
+ ```
158
+
159
+ The project is read/write/exec. **Network and external paths are denied by
160
+ default.** `network: true` asserts `fs_exec_network`; every `allowPaths` entry
161
+ asserts `external_directory`, and `mode: "ro"` keeps it read-only:
162
+
163
+ ```js
164
+ await tools.fs.exec({
165
+ command: "npm",
166
+ args: ["install"],
167
+ network: true,
168
+ allowPaths: [{ path: "/home/you/.npm", mode: "rw" }],
169
+ timeoutMs: 300000,
170
+ })
171
+ ```
172
+
173
+ Denied access returns `violations` and a `hint`; ask the user, then retry with
174
+ the approved path or network. `command` is a bare name, `args` are literal, and
175
+ `cwd` is sandboxed. Direct calls return JSON with `exitCode`/`stdout`/`stderr`
176
+ and violations; in `fs.pipe` the stage passes raw stdout.
177
+
178
+ ```js
179
+ await tools.fs.pipe({
180
+ stages: [
181
+ { tool: "exec", args: { command: "npm", args: ["test"] } },
182
+ { tool: "grep", args: { pattern: "FAIL" } },
183
+ ],
184
+ })
185
+ ```
186
+
187
+ A non-zero exit is a normal result; allowlist rejection, timeout, and abort are
188
+ handled explicitly. Procage kills every process the run started, including
189
+ detached descendants, and caps captured stdout/stderr. It requires Linux
190
+ x64/arm64, glibc 2.28+, and Node 22.12+.
191
+
145
192
  ## Batch independent calls
146
193
 
147
194
  `execute` is a JS runtime. Do not `await` independent fs calls one at a time.
@@ -254,9 +301,9 @@ Common pipe mistakes:
254
301
  - There is no shell, redirection operator, nested pipe, `find -exec`, or
255
302
  `xargs`.
256
303
 
257
- Pipeable filters include `head`, `tail`, `grep`, `sed`, `sort`, `uniq`, `cut`,
258
- `tr`, `tee`, `gzip`, `gunzip`, `tac`, `rev`, `nl`, `paste`, `shuf`, `fold`,
259
- `base64`, `od`, and `strings`. Unknown stage names fail with `unsupported`.
304
+ Pipeable filters include `exec`, `head`, `tail`, `grep`, `sed`, `sort`, `uniq`,
305
+ `cut`, `tr`, `tee`, `gzip`, `gunzip`, `tac`, `rev`, `nl`, `paste`, `shuf`,
306
+ `fold`, `base64`, `od`, and `strings`. Unknown stage names fail with `unsupported`.
260
307
 
261
308
  ## Background jobs
262
309
 
@@ -373,6 +420,8 @@ await tools.fs.http_request({
373
420
  - Linux only; there is no Windows branch.
374
421
  - `fs.sed` supports `s<delim>pattern<delim>replacement<delim>flags` with `g`,
375
422
  `i` and `p`. It is not a full sed interpreter.
423
+ - `fs.exec` requires procage: Linux x64/arm64, glibc 2.28+, Node 22.12+. Network
424
+ and external paths are denied until approved.
376
425
  - `fs.find` has no arbitrary `-exec`; use `action: "delete"`/`"trash"` for the
377
426
  common cleanup case, or `fs.rm`/`fs.trash` separately.
378
427
  - No `xz`, `zstd`, `7z`, `rar`, `chattr`, ACLs, xattrs, or `rsync`.
@@ -382,8 +431,9 @@ await tools.fs.http_request({
382
431
  - `fs.tar`/`fs.zip` create from `input` or stdin; extraction is file-backed.
383
432
  - `fs.http_request` is HTTP(S) only: no FTP/SFTP, cookie jars, client
384
433
  certificates, proxies, multipart uploads, or resumable downloads.
385
- - No process can be started or wrapped: `nohup`, `setsid`, and `timeout` are
386
- unavailable, and `fs.kill` rejects pid 0, pid 1, and process groups.
434
+ - Only `fs.exec` starts processes, and only exact allowlisted names; `nohup`,
435
+ `setsid`, and `timeout` wrappers are unavailable. `fs.kill` rejects pid 0,
436
+ pid 1, and process groups.
387
437
  - No ICMP ping; use `fs.http_request` or a TCP port check. No ACL, xattr, or
388
438
  `chattr` support. `rsync`/`scp` are out of scope; use the SSH MCP.
389
439
  - `fs.comm` expects sorted input. `fs.ar` uses GNU short names (16 bytes max);
@@ -425,6 +475,10 @@ Command actions are `fs_<command>` (for example `fs_cp`). `fs_*` wildcards work
425
475
  in agent rules. `fs.pipe` asserts each stage's action; a denied stage cannot be
426
476
  hidden inside a pipeline. Do not work around a denied tool with shell.
427
477
 
478
+ `fs_exec` runs only exact allowlisted names in a procage sandbox. It asserts
479
+ `fs_exec`, plus `fs_exec_network` for `network: true` and `external_directory`
480
+ for each `allowPaths` entry or an external `cwd`. There is no shell.
481
+
428
482
  `fs_http_request` is allowed by default, like `fetch`. Its resource is the
429
483
  request host; rules can allow one host and ask or deny the rest. Each redirect
430
484
  hop is checked against the new host. Nothing blocks localhost or private
package/src/core/types.ts CHANGED
@@ -12,6 +12,8 @@ export type PipeMode = "source" | "filter" | "sink" | false;
12
12
  export interface IO {
13
13
  /** Piped input when the tool is used as a pipe stage. */
14
14
  readonly stdin?: AsyncIterable<Buffer>;
15
+ /** True when the tool is running inside `fs.pipe`. */
16
+ readonly piped?: boolean;
15
17
  }
16
18
 
17
19
  export interface ToolResult {
@@ -29,6 +31,7 @@ export interface RunContext {
29
31
  readonly signal: AbortSignal;
30
32
  readonly tmpdir: string;
31
33
  readonly maxOutputBytes: number;
34
+ readonly execAllowlist: readonly string[];
32
35
  }
33
36
 
34
37
  export interface ToolSpec<I> {
package/src/index.ts CHANGED
@@ -30,6 +30,7 @@ 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
34
  import { findmntTool } from "./tools/findmnt.js";
34
35
  import { foldTool } from "./tools/fold.js";
35
36
  import { grepTool } from "./tools/grep.js";
@@ -141,6 +142,7 @@ const TOOLS: readonly AnyTool[] = [
141
142
  trTool,
142
143
  sedTool,
143
144
  grepTool,
145
+ execTool,
144
146
  pipeTool,
145
147
  ];
146
148
 
@@ -196,6 +198,7 @@ export default Plugin.define({
196
198
  const concurrency = clampConcurrency(
197
199
  typeof ctx.options?.concurrency === "number" ? ctx.options.concurrency : undefined,
198
200
  );
201
+ const execAllowlist = normalizeExecAllowlist(ctx.options?.execAllowlist);
199
202
  const maxOutputBytes =
200
203
  typeof ctx.options?.maxOutputBytes === "number" && ctx.options.maxOutputBytes > 0
201
204
  ? Math.trunc(ctx.options.maxOutputBytes)
@@ -248,6 +251,7 @@ export default Plugin.define({
248
251
  signal,
249
252
  tmpdir: os.tmpdir(),
250
253
  maxOutputBytes,
254
+ execAllowlist,
251
255
  },
252
256
  parsed,
253
257
  {},
@@ -0,0 +1,352 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ import * as fs from "node:fs/promises";
7
+ import { constants as fsConstants } from "node:fs";
8
+ import * as path from "node:path";
9
+ import { Type, type Static } from "@sinclair/typebox";
10
+ import type { Violation } from "procage";
11
+ import { FsError } from "../core/errors.js";
12
+ import { collect } from "../core/stream.js";
13
+ import { textResult, type RunContext, type ToolSpec } from "../core/types.js";
14
+
15
+ export const DEFAULT_EXEC_ALLOWLIST = ["npm", "npx", "uv", "uvx", "pip", "pip3"] as const;
16
+
17
+ const EXEC_NAME = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;
18
+
19
+ export function isSafeExecName(value: string): boolean {
20
+ return EXEC_NAME.test(value);
21
+ }
22
+
23
+ export function normalizeExecAllowlist(value: unknown): readonly string[] {
24
+ if (value === undefined) return DEFAULT_EXEC_ALLOWLIST;
25
+ if (!Array.isArray(value)) throw new FsError("execAllowlist must be an array of executable names.", "invalid");
26
+ const names: string[] = [];
27
+ for (const entry of value) {
28
+ if (typeof entry !== "string") throw new FsError("execAllowlist entries must be strings.", "invalid");
29
+ const name = entry.trim();
30
+ if (!isSafeExecName(name)) throw new FsError(`Invalid exec allowlist entry: ${entry}`, "invalid");
31
+ names.push(name);
32
+ }
33
+ return [...new Set(names)];
34
+ }
35
+
36
+ const Schema = Type.Object(
37
+ {
38
+ command: Type.String({ minLength: 1, description: "Allowlisted executable name, without a path or shell syntax." }),
39
+ args: Type.Optional(Type.Array(Type.String(), { description: "Arguments passed verbatim to the executable." })),
40
+ cwd: Type.Optional(Type.String({ minLength: 1, description: "Working directory inside the project. Default: project root." })),
41
+ stdin: Type.Optional(Type.String({ description: "Text for stdin when the tool is not used in a pipe." })),
42
+ timeoutMs: Type.Optional(
43
+ Type.Integer({ minimum: 100, maximum: 600_000, description: "Timeout in milliseconds. Default: 120000." }),
44
+ ),
45
+ network: Type.Optional(
46
+ Type.Boolean({
47
+ description: "Allow IP network after `fs_exec_network` approval. Default: false.",
48
+ }),
49
+ ),
50
+ allowPaths: Type.Optional(
51
+ Type.Array(
52
+ Type.Object(
53
+ {
54
+ path: Type.String({ minLength: 1, description: "External path to expose after approval." }),
55
+ mode: Type.Optional(
56
+ Type.Union([Type.Literal("ro"), Type.Literal("rw")], { description: "Read-only or read-write. Default: rw." }),
57
+ ),
58
+ },
59
+ { additionalProperties: false },
60
+ ),
61
+ ),
62
+ ),
63
+ },
64
+ { additionalProperties: false },
65
+ );
66
+
67
+ type Input = Static<typeof Schema>;
68
+
69
+ interface PolicyDocument {
70
+ fs: Array<{ access: string; target: { subpath: string } }>;
71
+ net: string;
72
+ [key: string]: unknown;
73
+ }
74
+
75
+ interface ExecOutcome {
76
+ stdout: Buffer;
77
+ stderr: Buffer;
78
+ exitCode: number;
79
+ signal: string | null;
80
+ timedOut: boolean;
81
+ aborted: boolean;
82
+ stdoutTruncated: boolean;
83
+ stderrTruncated: boolean;
84
+ violations: Violation[];
85
+ }
86
+
87
+ let procage: Promise<typeof import("procage")> | undefined;
88
+
89
+ function loadProcage(): Promise<typeof import("procage")> {
90
+ procage ??= import("procage");
91
+ return procage;
92
+ }
93
+
94
+ export const execTool: ToolSpec<Input> = {
95
+ name: "exec",
96
+ description:
97
+ "Run an allowlisted executable in a procage sandbox without a shell. Direct calls return JSON; " +
98
+ "pipe stages pass raw stdout. Default allowlist: npm, npx, uv, uvx, pip, pip3. Network and external " +
99
+ "paths are denied until approved.",
100
+ schema: Schema,
101
+ pipeable: "filter",
102
+ mutates: true,
103
+ async run(ctx, input, io) {
104
+ const command = input.command.trim();
105
+ if (!isSafeExecName(command)) {
106
+ throw new FsError(`exec command must be a bare executable name: "${input.command}"`, "invalid");
107
+ }
108
+ if (!ctx.execAllowlist.includes(command)) {
109
+ throw new FsError(`exec command is not allowlisted: "${command}"`, "unsupported");
110
+ }
111
+ const args = input.args ?? [];
112
+ if (args.some((arg) => arg.includes("\0"))) {
113
+ throw new FsError("exec arguments must not contain NUL bytes.", "invalid");
114
+ }
115
+
116
+ const requested = input.cwd ?? ".";
117
+ const cwdTarget = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
118
+ const cwdStats = await ctx.sandbox.stat(cwdTarget.full, requested);
119
+ if (!cwdStats.isDirectory()) throw new FsError(`exec cwd is not a directory: "${requested}"`, "not-directory");
120
+ await ctx.permission.assert([{ target: cwdTarget, boundary: cwdTarget.full }]);
121
+ if (ctx.signal.aborted) throw new FsError("exec interrupted.", "interrupted");
122
+
123
+ if (input.network === true) await ctx.permissionFor("fs_exec_network").assert([]);
124
+
125
+ const allowed: Array<{ full: string; mode: "ro" | "rw" }> = [];
126
+ for (const entry of input.allowPaths ?? []) {
127
+ const target = await ctx.sandbox.resolveExisting(entry.path, { allowRoot: true });
128
+ await ctx.permission.assert([{ target, boundary: target.full }]);
129
+ const mode = entry.mode ?? "rw";
130
+ if (!allowed.some((item) => item.full === target.full && item.mode === mode)) {
131
+ allowed.push({ full: target.full, mode });
132
+ }
133
+ }
134
+
135
+ const executable = await resolveExecutable(command);
136
+ const tempDir = await fs.mkdtemp(path.join(ctx.tmpdir, "fs-exec-"));
137
+ try {
138
+ const outcome = await runCaged(ctx, {
139
+ command,
140
+ executable,
141
+ args,
142
+ cwd: cwdTarget.full,
143
+ timeoutMs: input.timeoutMs ?? 120_000,
144
+ network: input.network === true,
145
+ allowed,
146
+ tempDir,
147
+ input: io.stdin === undefined
148
+ ? input.stdin === undefined ? undefined : Buffer.from(input.stdin)
149
+ : await collect(io.stdin),
150
+ });
151
+ const metadata = {
152
+ command,
153
+ args,
154
+ exitCode: outcome.exitCode,
155
+ signal: outcome.signal,
156
+ timedOut: outcome.timedOut,
157
+ aborted: outcome.aborted,
158
+ stdoutTruncated: outcome.stdoutTruncated,
159
+ stderrTruncated: outcome.stderrTruncated,
160
+ sandboxBlocked: isSandboxBlocked(outcome),
161
+ violations: outcome.violations.length,
162
+ network: input.network === true,
163
+ allowPaths: allowed,
164
+ };
165
+ if (io.piped === true) {
166
+ return {
167
+ stdout: outcome.stdout,
168
+ stderr: outcome.stderr.toString("utf8"),
169
+ exitCode: outcome.exitCode === 0 ? 0 : 1,
170
+ metadata,
171
+ };
172
+ }
173
+ const sandboxBlocked = isSandboxBlocked(outcome);
174
+ const body = {
175
+ ...metadata,
176
+ stdout: outcome.stdout.toString("utf8"),
177
+ stderr: outcome.stderr.toString("utf8"),
178
+ violations: outcome.violations,
179
+ ...(sandboxBlocked
180
+ ? {
181
+ hint:
182
+ "The sandbox denied an external path or network access. Ask the user, then retry with allowPaths or network: true.",
183
+ }
184
+ : {}),
185
+ };
186
+ return textResult(JSON.stringify(body, null, 2), metadata, outcome.exitCode === 0 ? 0 : 1);
187
+ } finally {
188
+ /* v8 ignore next 5 */
189
+ try {
190
+ await fs.rm(tempDir, { recursive: true, force: true });
191
+ } catch {
192
+ /* already gone */
193
+ }
194
+ }
195
+ },
196
+ };
197
+
198
+ interface CagedInput {
199
+ command: string;
200
+ executable: { path: string; real: string };
201
+ args: string[];
202
+ cwd: string;
203
+ timeoutMs: number;
204
+ network: boolean;
205
+ allowed: Array<{ full: string; mode: "ro" | "rw" }>;
206
+ tempDir: string;
207
+ input: Buffer | undefined;
208
+ }
209
+
210
+ async function runCaged(ctx: RunContext, input: CagedInput): Promise<ExecOutcome> {
211
+ let api: typeof import("procage");
212
+ try {
213
+ api = await loadProcage();
214
+ } catch (error) {
215
+ /* v8 ignore next */
216
+ throw new FsError(`exec sandbox is unavailable: ${String(error)}`, "unsupported");
217
+ }
218
+
219
+ const doc = api.Policy.preset("agent_workspace", 3, { workspace: ctx.sandbox.root }).toJSON() as PolicyDocument;
220
+ doc.net = input.network ? "ip" : "none";
221
+ addRule(doc, "exec", path.dirname(input.executable.path));
222
+ addRule(doc, "exec", path.dirname(input.executable.real));
223
+ addRule(doc, "exec", path.dirname(process.execPath));
224
+ addRule(doc, "exec", path.resolve(path.dirname(process.execPath), ".."));
225
+ addRule(doc, "exec", path.dirname(input.executable.real));
226
+ addRule(doc, "exec", path.resolve(path.dirname(input.executable.real), ".."));
227
+ for (const root of ["/home/linuxbrew", "/var/home/linuxbrew"]) {
228
+ try {
229
+ await fs.access(root);
230
+ addRule(doc, "read", root);
231
+ addRule(doc, "exec", root);
232
+ } catch {
233
+ // Homebrew is optional.
234
+ }
235
+ }
236
+ addRule(doc, "write", input.tempDir);
237
+ addRule(doc, "write", input.cwd);
238
+ for (const allowed of input.allowed) addRule(doc, allowed.mode === "ro" ? "read" : "write", allowed.full);
239
+
240
+ let cage: InstanceType<typeof api.Cage>;
241
+ let policy: ReturnType<typeof api.Policy.fromJSON>;
242
+ try {
243
+ policy = api.Policy.fromJSON(doc);
244
+ cage = new api.Cage(policy, {
245
+ violations: true,
246
+ acceptSpawnSnapshot: true,
247
+ relax: ["waive:trust-handoff", "signals-same-user"],
248
+ });
249
+ } catch (error) {
250
+ /* v8 ignore next */
251
+ throw new FsError(`exec policy rejected: ${String(error)}`, "unsupported");
252
+ }
253
+
254
+ const env = Object.fromEntries(
255
+ Object.entries(process.env).filter((entry): entry is [string, string] => entry[1] !== undefined),
256
+ );
257
+ env.TMPDIR = input.tempDir;
258
+
259
+ let child;
260
+ try {
261
+ child = await cage.spawn([input.executable.path, ...input.args], {
262
+ cwd: input.cwd,
263
+ env,
264
+ stdin: input.input !== undefined,
265
+ });
266
+ } catch (error) {
267
+ /* v8 ignore next */
268
+ throw new FsError(`exec spawn failed: ${String(error)}`, "unsupported");
269
+ }
270
+
271
+ let aborted = false;
272
+ const onAbort = () => {
273
+ aborted = true;
274
+ child?.kill();
275
+ };
276
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
277
+ try {
278
+ const out = await child.output({ timeout: input.timeoutMs, ...(input.input === undefined ? {} : { input: input.input }) });
279
+ const violations = filterViolations(await child.violations());
280
+ const stdout = cap(out.stdout, ctx.maxOutputBytes);
281
+ const stderr = cap(out.stderr, ctx.maxOutputBytes);
282
+ return {
283
+ stdout: stdout.data,
284
+ stderr: stderr.data,
285
+ exitCode: out.timedOut ? 124 : aborted ? 130 : (out.exitCode ?? 1),
286
+ signal: out.signal,
287
+ timedOut: out.timedOut,
288
+ aborted,
289
+ stdoutTruncated: stdout.truncated,
290
+ stderrTruncated: stderr.truncated,
291
+ violations,
292
+ };
293
+ } catch (error) {
294
+ /* v8 ignore next 14 */
295
+ if (aborted || ctx.signal.aborted) {
296
+ return {
297
+ stdout: Buffer.alloc(0),
298
+ stderr: Buffer.alloc(0),
299
+ exitCode: 130,
300
+ signal: null,
301
+ timedOut: false,
302
+ aborted: true,
303
+ stdoutTruncated: false,
304
+ stderrTruncated: false,
305
+ violations: [],
306
+ };
307
+ }
308
+ /* v8 ignore next */
309
+ throw new FsError(`exec failed: ${String(error)}`, "unsupported");
310
+ } finally {
311
+ ctx.signal.removeEventListener("abort", onAbort);
312
+ child.close();
313
+ }
314
+ }
315
+
316
+ function addRule(doc: PolicyDocument, access: string, target: string): void {
317
+ const subpath = path.resolve(target);
318
+ if (doc.fs.some((rule) => rule.access === access && rule.target.subpath === subpath)) return;
319
+ doc.fs.push({ access, target: { subpath } });
320
+ }
321
+
322
+ export function filterViolations(violations: readonly Violation[]): Violation[] {
323
+ return violations.filter((violation) => {
324
+ if (violation.target?.startsWith("/")) return true;
325
+ return /AF_INET|AF_INET6/.test(violation.target ?? "");
326
+ });
327
+ }
328
+
329
+ function isSandboxBlocked(outcome: ExecOutcome): boolean {
330
+ if (outcome.violations.length > 0) return true;
331
+ if (outcome.exitCode === 0) return false;
332
+ return /EACCES|EPERM|EROFS|Permission denied|Read-only file system/i.test(outcome.stderr.toString("utf8"));
333
+ }
334
+
335
+ async function resolveExecutable(command: string): Promise<{ path: string; real: string }> {
336
+ const directories = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
337
+ for (const directory of directories) {
338
+ const candidate = path.join(directory, command);
339
+ try {
340
+ await fs.access(candidate, fsConstants.X_OK);
341
+ return { path: candidate, real: await fs.realpath(candidate) };
342
+ } catch {
343
+ // keep searching PATH
344
+ }
345
+ }
346
+ throw new FsError(`exec command not found: "${command}"`, "not-found");
347
+ }
348
+
349
+ function cap(data: Buffer, limit: number): { data: Buffer; truncated: boolean } {
350
+ if (data.length <= limit) return { data, truncated: false };
351
+ return { data: data.subarray(0, limit), truncated: true };
352
+ }
package/src/tools/pipe.ts CHANGED
@@ -13,6 +13,7 @@ import { catTool } from "./cat.js";
13
13
  import { cpioTool } from "./cpio.js";
14
14
  import { cutTool } from "./cut.js";
15
15
  import { ddTool } from "./dd.js";
16
+ import { execTool } from "./exec.js";
16
17
  import { foldTool } from "./fold.js";
17
18
  import { grepTool } from "./grep.js";
18
19
  import { gunzipTool, gzipTool } from "./gzip.js";
@@ -62,7 +63,7 @@ const REGISTRY: ReadonlyMap<string, AnyTool> = new Map(
62
63
  catTool, headTool, tailTool, grepTool, sedTool, sortTool, uniqTool, cutTool,
63
64
  trTool, wcTool, teeTool, hashTool, gzipTool, gunzipTool, tarTool, zipTool,
64
65
  httpRequestTool, base64Tool, odTool, stringsTool, tacTool, revTool, nlTool,
65
- pasteTool, shufTool, foldTool, ddTool, cpioTool,
66
+ pasteTool, shufTool, foldTool, ddTool, cpioTool, execTool,
66
67
  ].map((tool) => [tool.name, tool]),
67
68
  );
68
69
 
@@ -93,7 +94,7 @@ export const pipeTool: ToolSpec<Input> = {
93
94
  const result = await tool.run(
94
95
  { ...ctx, permission: gate },
95
96
  parsed,
96
- { ...(data === undefined ? {} : { stdin: fromBuffer(data) }) },
97
+ { ...(data === undefined ? {} : { stdin: fromBuffer(data) }), piped: true },
97
98
  ) as ToolResult;
98
99
  stages.push({
99
100
  tool: stage.tool,