opencode-fs-plugin 3.4.0 → 3.6.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.
@@ -24,8 +24,8 @@ With `execute` allowed, call it as `tools.fs.<command>`; agents without
24
24
  | Metadata/predicate search | `fs.find` |
25
25
  | Regex substitution or in-place edit | `fs.sed` |
26
26
  | Recoverable deletion | `fs.trash` |
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) |
27
+ | `curl` fetch, API call, or file download | `fs.curl` |
28
+ | Allowlisted package CLI | `fs.command` (no shell; default npm/npx/uv/uvx/pip/pip3) |
29
29
  | Many independent fs calls | one multi-path call, else `Promise.all` in `execute` |
30
30
  | Sequential byte pipeline | `fs.pipe` |
31
31
 
@@ -53,8 +53,8 @@ what `fs.stat`, `fs.ls`, `fs.hash`, `fs.diff`, or `fs.cat` can confirm.
53
53
  | Temp and trash | `fs.mktemp`, `fs.trash` |
54
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` |
55
55
  | Compose filters | `fs.pipe` |
56
- | HTTP(S) | `fs.http_request` (`output`, `checksum`, `maxBytes`, `json`) |
57
- | Allowlisted package CLI | `fs.exec` (`command`, `args`, `cwd`, `stdin`, `timeoutMs`) |
56
+ | curl | `fs.curl` (`output`, `checksum`, `maxBytes`, `json`) |
57
+ | Allowlisted package CLI | `fs.command` (`command`, `args`, `cwd`, `stdin`, `timeoutMs`) |
58
58
  | Processes | `fs.ps`, `fs.pgrep`, `fs.kill` (`dryRun` available) |
59
59
  | System info | `fs.id`, `fs.uname`, `fs.uptime`, `fs.date`, `fs.findmnt`, `fs.mountpoint` |
60
60
  | Binary inspection | `fs.file`, `fs.base64`, `fs.od`, `fs.strings` |
@@ -98,9 +98,9 @@ host drops unknown fields, so a name typo runs with defaults.
98
98
  | `input` + `output` | `fs.dd` (`blockSize`, `count`, `skip`, `seek`) |
99
99
  | `content` | `fs.tee` when there is no stdin |
100
100
  | `paths` + optional `keep`/`force`/`stdout`/`level`/`suffix` | `fs.gzip`, `fs.gunzip` |
101
- | `url` + optional `output` | `fs.http_request` |
101
+ | `url` + optional `output` | `fs.curl` |
102
102
  | `stages` + optional `input`/`output` | `fs.pipe` |
103
- | `command` + `args` + optional `cwd`/`stdin`/`timeoutMs` | `fs.exec` |
103
+ | `command` + `args` + optional `cwd`/`stdin`/`timeoutMs` | `fs.command` |
104
104
 
105
105
  `fs.head` takes `skip` for line ranges: `sed -n '20,40p'` is
106
106
  `fs.head({ paths, skip: 19, lines: 21 })`. `fs.find` takes
@@ -139,54 +139,92 @@ removed, and deletion asserts `fs_rm`/`fs_trash`.
139
139
  | `cat > f <<EOF` | built-in `write` or `fs.tee({ paths: [f], content })` |
140
140
  | `rg pattern path` | `fs.grep({ pattern, paths })` or the built-in `grep` |
141
141
  | `ls -l f` | `fs.ls({ paths: [f], long: true })` |
142
- | `npm ...` / `uv run ...` | `fs.exec({ command, args })` (allowlisted only) |
142
+ | `npm ...` / `uv run ...` | `fs.command({ command, args })` (`fs_command` permission) |
143
143
 
144
144
  `sed -n` applied to another command's stdout has no fs equivalent; keep that in
145
145
  the command pipeline. `fs.find` has no arbitrary `-exec` by design; use
146
146
  `action: "delete"` or `"trash"` for the common cleanup case, or list the paths and
147
147
  remove them explicitly.
148
148
 
149
- ## Exec
149
+ ## Command
150
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`:
151
+ `fs.command` runs an executable in a **procage sandbox** without a shell. It is
152
+ closest to the shell's `command <prog>`: one program with literal argv, not
153
+ `exec` (which replaces the shell) or `sh -c` (which parses shell syntax). The
154
+ executable allowlist is the `fs_command` permission: the tool asserts that action
155
+ with the bare executable name as its resource. Deny `*`, then allow the names
156
+ you need:
154
157
 
155
158
  ```jsonc
156
- { "package": "./repos/opencode-fs-plugin", "options": { "execAllowlist": ["npm", "uv"] } }
159
+ { "permissions": [
160
+ { "action": "fs_command", "resource": "*", "effect": "deny" },
161
+ { "action": "fs_command", "resource": "npm", "effect": "allow" },
162
+ { "action": "fs_command", "resource": "uv", "effect": "allow" }
163
+ ] }
157
164
  ```
158
165
 
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; every host must be approved through `fs_exec_network`, which asks with
162
- the host as the resource and retries with it added. The permission rules are
163
- the allowlist: a `*` deny plus host allows fails closed for everything else.
164
- `execNetworkMode: "ip"` opts into all-IP after approval instead. On Linux T2
165
- (no network namespace) the run falls back to `ip`.
166
+ With no rule the base allow applies to every executable.
167
+
168
+ The project is read/write/exec. **Network egress needs Linux tier T1** and uses
169
+ procage's transparent relay. There are no per-call grants. Every TCP/UDP flow is
170
+ named as a DNS QNAME, TLS SNI, HTTP `Host`, QUIC SNI, or IP literal, and that
171
+ exact resource is approved through `fs_exec_network`; ports, URLs, and payloads
172
+ are never part of the permission. Bare IPv6 literals and bracketed IPv6 `Host`
173
+ forms with an optional port are valid resources. The permission rules are the
174
+ network allowlist: a `*` deny plus name/address allows fails closed for anything
175
+ else.
176
+
177
+ DNS is authorized by QNAME. Allowed answers feed a per-run address-to-name
178
+ cache: a nameless flow is allowed by a fresh allowed name bound to its address,
179
+ else by the address. A named flow needs the exact `(name, address)` from an
180
+ allowed answer plus the allowed name, or both name and address allowed; a denied
181
+ named identity is never rescued by an allowed address. Allow an address in
182
+ addition to the name when a program connects to an IP literal, or when a named
183
+ flow's exact `(name, address)` was not returned by an allowed DNS answer.
184
+
185
+ DoH blocking is best-effort: TCP/853 and known DoH names are refused, but custom
186
+ or unknown DoH endpoints on other names or ports may not be recognized. ECH
187
+ detected in TLS or QUIC is visibly refused.
166
188
 
167
189
  ```js
168
- await tools.fs.exec({ command: "npm", args: ["install"], timeoutMs: 300000 })
190
+ await tools.fs.command({ command: "npm", args: ["install"], timeoutMs: 300000 })
169
191
  ```
170
192
 
193
+ Proxy variables (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`, lowercase
194
+ forms, npm proxy settings) pass through explicitly. The relay treats the proxy
195
+ as the destination, never its `CONNECT` target, so allow the proxy's address or
196
+ cached DNS name in `fs_exec_network`; approving it lets the proxy reach whatever
197
+ it forwards. No other caller environment variable is forwarded explicitly, but
198
+ the preset's own allowlist still applies, and a proxy variable may itself carry
199
+ proxy credentials.
200
+
171
201
  Denied paths ask `external_directory` and approval covers the denied path's
172
- containing directory (or nearest existing ancestor). Denied access returns
173
- `violations` and a `hint`. In `ip` mode DNS works through the
174
- systemd-resolved, nscd, or SSSD sockets where the kernel can scope them; other
175
- Unix sockets stay blocked and plain UDP DNS works everywhere.
176
- `command` is a bare name, `args` are literal, and `cwd` is sandboxed. Direct
177
- calls return JSON with `exitCode`/`stdout`/`stderr` and violations; in `fs.pipe`
178
- the stage passes raw stdout.
202
+ containing directory (or nearest existing ancestor) only when procage reports a
203
+ structured **write** violation (`file-write-*`). Read, exec, network, and
204
+ unknown operations never add a write rule; otherwise no path grant is inferred
205
+ and access stays denied — pre-grant the path or configure a rule. A path printed
206
+ on stdout or stderr is reported, never auto-approved. Denied access returns
207
+ `violations` and a `hint`. On Linux T2 or macOS the relay is unavailable, and a
208
+ relay control server that cannot start is treated the same way: the run
209
+ retries once with networking off (`net: "none"`, no resolver sockets, no macOS
210
+ resolver grant) and reports `networkMode: "disabled"` plus `networkReason`. A
211
+ denial, lost control link, malformed frame, or decision timeout refuses the
212
+ flow; there is no direct-IP fallback. `command` is a bare name, `args` are
213
+ literal, and `cwd` is sandboxed. Direct calls return JSON with
214
+ `exitCode`/`stdout`/`stderr`, violations, and the network fields `network`,
215
+ `networkMode`, `networkHosts`, and `networkReason`; `externalPaths` lists the
216
+ external roots the run could write to. In `fs.pipe` the stage passes raw stdout.
179
217
 
180
218
  ```js
181
219
  await tools.fs.pipe({
182
220
  stages: [
183
- { tool: "exec", args: { command: "npm", args: ["test"] } },
221
+ { tool: "command", args: { command: "npm", args: ["test"] } },
184
222
  { tool: "grep", args: { pattern: "FAIL" } },
185
223
  ],
186
224
  })
187
225
  ```
188
226
 
189
- A non-zero exit is a normal result; allowlist rejection, timeout, and abort are
227
+ A non-zero exit is a normal result; permission denial, timeout, and abort are
190
228
  handled explicitly. Procage kills every process the run started, including
191
229
  detached descendants, and returns captured stdout/stderr in full. It requires Linux
192
230
  x64/arm64, glibc 2.28+, and Node 22.12+.
@@ -263,15 +301,15 @@ await tools.fs.pipe({
263
301
  | `output` | Write final stdout to a file (final `tee`) |
264
302
  | `append` | Append to `output` instead of overwriting |
265
303
 
266
- The first stage must be a source (`cat`, `http_request`, `dd`, or a path-reading
304
+ The first stage must be a source (`cat`, `curl`, `dd`, or a path-reading
267
305
  text tool such as `tac`, `rev`, `nl`, `base64`, `od`, `strings`) or receive
268
306
  `input`. A filter first (`grep`, `sort`, `head`, `wc`) emits
269
307
  `ERROR: no input files and no stdin` as pipeline data. Archive writers (`tar`,
270
308
  `zip`, `cpio`) emit nothing downstream, so put them last. `wc` and `hash` also
271
309
  emit their result text, so they can end a chain or feed a later stage.
272
310
 
273
- Stages exchange whole buffers. Set `maxBytes` on `http_request`; for large
274
- downloads prefer `fs.http_request({ output })`, which streams to disk. In-memory
311
+ Stages exchange whole buffers. Set `maxBytes` on `curl`; for large
312
+ downloads prefer `fs.curl({ output })`, which streams to disk. In-memory
275
313
  text is allowed:
276
314
 
277
315
  ```js
@@ -284,7 +322,7 @@ await tools.fs.pipe({
284
322
  ```js
285
323
  await tools.fs.pipe({
286
324
  stages: [
287
- { tool: "http_request", args: { url: "https://example.com/app.log", maxBytes: 8_000_000 } },
325
+ { tool: "curl", args: { url: "https://example.com/app.log", maxBytes: 8_000_000 } },
288
326
  { tool: "grep", args: { pattern: "ERROR" } },
289
327
  ],
290
328
  })
@@ -292,7 +330,9 @@ await tools.fs.pipe({
292
330
 
293
331
  `output` and `append` assert `fs_tee` on the destination. The result metadata
294
332
  lists each stage's `bytesIn`, `bytesOut`, and `exitCode`; use it as the
295
- verification trail.
333
+ verification trail. A stage that yields no stdout becomes an empty buffer, so
334
+ `output` writes an empty file. The signal is checked before each stage and
335
+ before the final write, so an abort stops the chain before creating output.
296
336
 
297
337
  Common pipe mistakes:
298
338
 
@@ -303,15 +343,16 @@ Common pipe mistakes:
303
343
  - There is no shell, redirection operator, nested pipe, `find -exec`, or
304
344
  `xargs`.
305
345
 
306
- Pipeable filters include `exec`, `head`, `tail`, `grep`, `sed`, `sort`, `uniq`,
307
- `cut`, `tr`, `tee`, `gzip`, `gunzip`, `tac`, `rev`, `nl`, `paste`, `shuf`,
308
- `fold`, `base64`, `od`, and `strings`. Unknown stage names fail with `unsupported`.
346
+ Pipeable filters include `base64`, `command`, `cut`, `fold`, `grep`, `gunzip`,
347
+ `gzip`, `head`, `nl`, `od`, `paste`, `rev`, `sed`, `shuf`, `sort`, `strings`,
348
+ `tac`, `tail`, `tee`, `tr`, and `uniq`. Unknown stage names fail with
349
+ `unsupported`.
309
350
 
310
351
  ## Background jobs
311
352
 
312
- Every tool accepts `background: true`. It returns immediately with a job id and
313
- an atomic status-file path; use it for long copies, searches, archives, or
314
- hashes, then keep working and collect the result later.
353
+ Every tool except `fs.job` accepts `background: true`. It returns immediately
354
+ with a job id and an atomic status-file path; use it for long copies, searches,
355
+ archives, or hashes, then keep working and collect the result later.
315
356
 
316
357
  ```js
317
358
  const job = JSON.parse(
@@ -332,8 +373,23 @@ await tools.fs.job({ list: true }) // newest first
332
373
 
333
374
  `wait` returns the original tool result once the job completes; on timeout it
334
375
  returns the status with `timedOut: true`. Jobs are process-local and lost on
335
- server restart. Status files live under `/tmp/opencode/fs-jobs/<server-pid>/`;
336
- eight jobs may run at once and finished jobs are cleaned after one hour.
376
+ server restart. Status files live under `/tmp/opencode/fs-jobs/<server-pid>/`
377
+ by default; set the plugin option `jobDir` to move them. The caps are global to
378
+ one server, not per session: eight jobs may run at once and 64 are retained,
379
+ evicting the oldest finished job and deleting its status file; finished jobs are
380
+ cleaned after one hour. A background start or `fs.job` call without a non-empty
381
+ session id fails with `invalid`. Jobs are visible only to the session that
382
+ started them; the `jobDir` path is validated component by component (an existing
383
+ symlink, non-directory component, or `/` is refused; missing components and the
384
+ final directory become `0700`), and status files are `0600`. This is deliberately
385
+ fail-closed: a benign path through a host symlink such as `/home` is rejected,
386
+ while the default `/tmp/opencode/fs-jobs/<pid>` path is unaffected. A component
387
+ swapped after validation is a residual TOCTOU gap. Status files omit the result,
388
+ raw error, and absolute status path. Each
389
+ in-memory result is capped at 1 MiB: longer text is truncated with
390
+ `[truncated]`/`truncated`/`originalBytes`, and oversized base64/binary output
391
+ becomes empty. Retaining 64 results can hold roughly 64 MiB in the server
392
+ process until eviction.
337
393
 
338
394
  To wait without blocking the session, combine the status file with `wait_for`.
339
395
  Wait for any terminal state, then read the job for the result or error:
@@ -407,8 +463,8 @@ await tools.fs.cpio({ mode: "create", archive: "bundle.cpio", paths: ["dist"] })
407
463
  await tools.fs.ar({ mode: "list", archive: "lib.a" })
408
464
 
409
465
  // API call, then a verified download
410
- await tools.fs.http_request({ url: "https://api.github.com/repos/owner/repo/releases/latest" })
411
- await tools.fs.http_request({
466
+ await tools.fs.curl({ url: "https://api.github.com/repos/owner/repo/releases/latest" })
467
+ await tools.fs.curl({
412
468
  url: "https://example.com/tool-1.0.0.tgz",
413
469
  output: "tool-1.0.0.tgz",
414
470
  checksum: "sha256:<hex>",
@@ -422,8 +478,9 @@ await tools.fs.http_request({
422
478
  - Linux only; there is no Windows branch.
423
479
  - `fs.sed` supports `s<delim>pattern<delim>replacement<delim>flags` with `g`,
424
480
  `i` and `p`. It is not a full sed interpreter.
425
- - `fs.exec` requires procage: Linux x64/arm64, glibc 2.28+, Node 22.12+.
426
- Network is proxy-only by default; external paths are denied until approved.
481
+ - `fs.command` requires procage: Linux x64/arm64, glibc 2.28+, Node 22.12+.
482
+ Network egress needs Linux T1; elsewhere networking is disabled. External
483
+ paths are denied until approved.
427
484
  - `fs.find` has no arbitrary `-exec`; use `action: "delete"`/`"trash"` for the
428
485
  common cleanup case, or `fs.rm`/`fs.trash` separately.
429
486
  - No `xz`, `zstd`, `7z`, `rar`, `chattr`, ACLs, xattrs, or `rsync`.
@@ -431,17 +488,51 @@ await tools.fs.http_request({
431
488
  - `fs.tail` has bounded `follow` only; unbounded `tail -f` is not supported.
432
489
  - `cp -a` preserves mode and timestamps but not ACLs or xattrs.
433
490
  - `fs.tar`/`fs.zip` create from `input` or stdin; extraction is file-backed.
434
- - `fs.http_request` is HTTP(S) only: no FTP/SFTP, cookie jars, client
491
+ - `fs.curl` is HTTP(S) only: no FTP/SFTP, cookie jars, client
435
492
  certificates, proxies, multipart uploads, or resumable downloads.
436
- - Only `fs.exec` starts processes, and only exact allowlisted names; `nohup`,
493
+ - Only `fs.command` starts processes, and only names allowed by `fs_command`; `nohup`,
437
494
  `setsid`, and `timeout` wrappers are unavailable. `fs.kill` rejects pid 0,
438
495
  pid 1, and process groups.
439
- - No ICMP ping; use `fs.http_request` or a TCP port check. No ACL, xattr, or
496
+ - No ICMP ping; use `fs.curl` or a TCP port check. No ACL, xattr, or
440
497
  `chattr` support. `rsync`/`scp` are out of scope; use the SSH MCP.
441
498
  - `fs.comm` expects sorted input. `fs.ar` uses GNU short names (16 bytes max);
442
- `fs.cpio` reads and writes newc only. `fs.dd` has no conversion flags.
443
- - `fs.tar` resolves `paths` even when `directory` is set; pass absolute sources
444
- with `directory` or the member path may not be found.
499
+ `fs.cpio` writes newc with GNU 4-byte padding, reads both that and the prior
500
+ 3.x plugin padding, and rejects nonzero data after the trailer (concatenated
501
+ archives); its fields must fit `0..0xffffffff`. `fs.dd` has no conversion
502
+ flags.
503
+ Archives store files, directories, and symlinks only; hard links, device
504
+ nodes, and ACL/xattr metadata are dropped.
505
+ - `fs.tar` and `fs.cpio` create resolve relative `paths` under `directory`; an
506
+ absolute source is named relative to `directory` first, then the project, else
507
+ by basename (a traversing source also uses its basename).
508
+ - `fs.cp` fails closed on an existing symlink inside a recursive destination;
509
+ `fs.mv` refuses a directory destination under the source, and EXDEV falls back
510
+ to copy-then-remove that refuses a destination symlink. If nothing was copied
511
+ or an entry was skipped, the source is kept and a partial destination remains.
512
+ - `fs.chown` refuses the sandbox root, ancestors, `/`, `$HOME`, and core system
513
+ dirs before permission or mutation. `noDereference` canonicalizes the parent
514
+ chain but leaves the final link, so `lchown` changes a final symlink itself.
515
+ - `fs.split` takes 1-16 suffix characters and fails with `invalid` before
516
+ writing when the chunk count exceeds `26^n` (alphabetic) or `10^n`
517
+ (`numeric`).
518
+ - `fs.curl` refuses a cross-origin redirect unless it is a bodyless `GET`/`HEAD`
519
+ with only safe headers (`accept`, `accept-language`, `cache-control`,
520
+ `pragma`, `range`, `user-agent`), and refuses an HTTPS to HTTP hop. A 303
521
+ becomes a bodyless `GET` before that check; 301/302 rewrite `POST` after it;
522
+ 307/308 keep the method and body. `output` asks `external_directory` for the
523
+ file's containing directory.
524
+ - Archive extraction plans every member, refuses an existing final symlink,
525
+ applies the process umask to extracted file modes (strips setuid/setgid), and
526
+ preserves sticky on directories. ZIP entries without a Unix mode default to
527
+ `0644` files and `0755` directories before the umask. Directory modes are
528
+ deduplicated by canonical target (last entry wins) and applied deepest-first.
529
+ Ordinary mode changes use opened `O_NOFOLLOW` handles; an `EACCES` fallback for
530
+ an unreadable existing directory uses guarded pathname `chmod`, keeping a
531
+ final-component TOCTOU race. A bulk permission denial writes no members. A
532
+ swapped parent, an existing destination hardlink, an OS error, or an abort can
533
+ still redirect or partially write members.
534
+ Archive create and extraction buffer the whole archive and each extracted
535
+ member in memory, with no global archive-size cap.
445
536
  - `fs.du` reports allocated blocks like `du`; use `fs.stat` with `%s` for
446
537
  apparent file bytes.
447
538
  - `fs.trash` uses the XDG home trash only and refuses cross-device moves.
@@ -455,19 +546,32 @@ await tools.fs.http_request({
455
546
 
456
547
  ## Paths and safety
457
548
 
458
- - Paths resolve against the project directory. Paths outside it require
459
- `external_directory` approval, except tool-owned temp/trash paths.
460
- - The global config allows `/tmp/opencode/**` and the OpenCode cache, state, and
461
- config trees (`$HOME/.cache/opencode/**`, `$HOME/.local/share/opencode/**`,
462
- `$HOME/.local/state/opencode/**`, `$HOME/.config/opencode/**`). Prefer
463
- `fs.mktemp` for scratch files; a denied path is a blocker, not a reason to
464
- switch to shell.
549
+ - Paths resolve to their canonical target before permissions are asserted, so a
550
+ symlink out of the project asks `external_directory` for the real location.
551
+ Single-file output tools open the final component no-follow; `cp` rejects an
552
+ existing symlink at a nested entry but its copy call is not no-follow. A
553
+ parent directory swapped concurrently is still a TOCTOU gap, so treat the
554
+ sandbox as a guardrail.
555
+ - This installation's global config allows `/tmp/opencode/**` and the OpenCode
556
+ cache, state, and config trees; prefer `fs.mktemp` for scratch files, and treat
557
+ a denied path as a blocker rather than switching to shell.
465
558
  - Symlinks are handled per command: `rm`/`mv` never follow the final link, `cp`
466
- follows unless `archive`/`dereference: false`, and `stat`/`ls` use lstat
559
+ follows a top-level destination link and gates its target but refuses to write
560
+ through an existing symlink inside a recursive copy, and `stat`/`ls` use lstat
467
561
  unless asked to follow.
468
562
  - The project root, its ancestors, `/`, `$HOME`, and core system directories are
469
- hard stops for destructive operations.
470
- - Archive extraction rejects absolute paths, `..`, and escaping links.
563
+ hard stops for destructive operations; `fs.chown` enforces them before
564
+ permission or mutation.
565
+ - Archive extraction plans every member before writing and asserts one bulk
566
+ permission check for all targets: a denied member means nothing is written.
567
+ Existing final symlinks, absolute names, `..`, and escaping links are
568
+ rejected. File modes apply the umask and strip setuid/setgid; directory modes
569
+ preserve sticky. Directory modes are deduplicated by canonical target (last
570
+ entry wins) and applied deepest-first. Ordinary mode changes use `O_NOFOLLOW`
571
+ handles; an `EACCES` fallback uses guarded pathname `chmod` with a
572
+ final-component TOCTOU race. A swapped parent, an existing destination
573
+ hardlink, an OS error, or an abort can still redirect or partially write
574
+ members.
471
575
  - `rm` is permanent; prefer `trash` for recoverable deletes.
472
576
  - Pass `recursive: true` only when you intend to remove a whole tree.
473
577
 
@@ -477,12 +581,13 @@ Command actions are `fs_<command>` (for example `fs_cp`). `fs_*` wildcards work
477
581
  in agent rules. `fs.pipe` asserts each stage's action; a denied stage cannot be
478
582
  hidden inside a pipeline. Do not work around a denied tool with shell.
479
583
 
480
- `fs_exec` runs only exact allowlisted names in a procage sandbox. It asserts
481
- `fs_exec`, asks `external_directory` for a blocked path, and asks
482
- `fs_exec_network` with the refused host (or `*` in `ip` mode), then retries.
483
- There are no per-call grants and no shell.
584
+ `fs.command` asserts `fs_command` with the executable name as its resource;
585
+ deny `*` for a closed set. It asks `external_directory` for a blocked path and
586
+ `fs_exec_network` with the exact DNS name or IP address named by the relay.
587
+ There is no `*` fallback and no direct-IP mode; networking that cannot use the
588
+ relay is disabled. There are no per-call grants and no shell.
484
589
 
485
- `fs_http_request` reuses the built-in `webfetch` permission with the requested
590
+ `fs_curl` reuses the built-in `webfetch` permission with the requested
486
591
  URL as the resource, so one rule set covers both; each redirect hop is checked
487
592
  against its URL. Nothing blocks localhost or private addresses by default.
488
593
 
@@ -34,22 +34,16 @@ export function renderResult(result: ToolResult): RenderedResult {
34
34
  return { content: "", metadata };
35
35
  }
36
36
 
37
- if (metadata.bytes === undefined) metadata.bytes = result.stdout.length;
37
+ metadata.bytes = result.stdout.length;
38
38
 
39
39
  if (isBinary(result.stdout)) {
40
40
  metadata.encoding = "base64";
41
- return { content: spillNote(metadata, result.stdout.toString("base64")), metadata };
41
+ return { content: result.stdout.toString("base64"), metadata };
42
42
  }
43
43
 
44
44
  let content = result.stdout.toString("utf8");
45
45
  if (result.stderr) content += `${content.endsWith("\n") ? "" : "\n"}[stderr]\n${result.stderr}`;
46
- return { content: spillNote(metadata, content), metadata };
47
- }
48
-
49
- function spillNote(metadata: Record<string, unknown>, content: string): string {
50
- const outputPath = metadata.outputPath;
51
- if (typeof outputPath !== "string") return content;
52
- return `${content}${content.endsWith("\n") ? "" : "\n"}[output spilled to ${outputPath}; ${String(metadata.bytes)} bytes]`;
46
+ return { content, metadata };
53
47
  }
54
48
 
55
49
  export function renderError(error: FsError, blocked: boolean): RenderedResult {
@@ -133,6 +133,8 @@ async function walkDir(
133
133
  return output;
134
134
  }
135
135
 
136
+ export type CopyLimiter = <T>(fn: () => Promise<T>) => Promise<T>;
137
+
136
138
  export interface CopyOptions {
137
139
  readonly recursive?: boolean;
138
140
  readonly dereference?: boolean;
@@ -141,16 +143,24 @@ export interface CopyOptions {
141
143
  readonly update?: boolean;
142
144
  readonly signal?: AbortSignal;
143
145
  readonly concurrency: number;
146
+ /** Shared syscall limiter for nested trees; never held across recursion. */
147
+ readonly limiter?: CopyLimiter;
148
+ /** Called when noClobber or update leaves an existing destination in place. */
149
+ readonly onSkip?: () => void;
144
150
  }
145
151
 
146
152
  export async function copyTree(src: string, dest: string, options: CopyOptions): Promise<number> {
147
153
  if (options.signal?.aborted) throw new FsError("Operation interrupted.", "interrupted");
148
- const stats = options.dereference === false ? await fs.lstat(src) : await fs.stat(src);
154
+ const limit = options.limiter ?? immediate;
155
+ const stats = await limit(() => (options.dereference === false ? fs.lstat(src) : fs.stat(src)));
149
156
  if (options.update === true) {
150
157
  try {
151
- const destStats = await fs.lstat(dest);
158
+ const destStats = await limit(() => fs.lstat(dest));
152
159
  /* v8 ignore next */
153
- if (destStats.mtimeMs >= stats.mtimeMs) return 0;
160
+ if (destStats.mtimeMs >= stats.mtimeMs) {
161
+ options.onSkip?.();
162
+ return 0;
163
+ }
154
164
  } catch (error) {
155
165
  /* v8 ignore next 2 */
156
166
  if (!isMissing(error)) throw fromErrno(error, "access");
@@ -158,18 +168,19 @@ export async function copyTree(src: string, dest: string, options: CopyOptions):
158
168
  }
159
169
 
160
170
  if (stats.isSymbolicLink() && options.dereference === false) {
161
- const target = await fs.readlink(src);
162
- await ensureParent(dest);
171
+ const target = await limit(() => fs.readlink(src));
172
+ await limit(() => ensureParent(dest));
163
173
  try {
164
- await fs.symlink(target, dest);
174
+ await limit(() => fs.symlink(target, dest));
165
175
  } catch (error) {
166
176
  /* v8 ignore next */
167
- if (isExists(error) && options.noClobber !== true) {
168
- await fs.unlink(dest);
169
- await fs.symlink(target, dest);
170
- } else {
171
- throw fromErrno(error);
177
+ if (!isExists(error)) throw fromErrno(error);
178
+ if (options.noClobber === true) {
179
+ options.onSkip?.();
180
+ return 0;
172
181
  }
182
+ await limit(() => fs.unlink(dest));
183
+ await limit(() => fs.symlink(target, dest));
173
184
  }
174
185
  return 1;
175
186
  }
@@ -178,45 +189,85 @@ export async function copyTree(src: string, dest: string, options: CopyOptions):
178
189
  if (options.recursive !== true) {
179
190
  throw new FsError(`"${src}" is a directory; recursive is required.`, "not-file");
180
191
  }
192
+ const existing = await lstatOptional(dest, limit);
193
+ if (existing?.isSymbolicLink() === true) {
194
+ throw new FsError(`Refusing to write through symbolic link: "${dest}".`, "invalid");
195
+ }
181
196
  try {
182
- await fs.mkdir(dest, { recursive: true });
197
+ await limit(() => fs.mkdir(dest, { recursive: true }));
183
198
  } catch (error) {
184
199
  /* v8 ignore next */
185
200
  throw fromErrno(error);
186
201
  }
187
- const entries = await fs.readdir(src);
188
- let copied = 1;
189
- const limit = Math.max(1, options.concurrency);
202
+ const entries = await limit(() => fs.readdir(src));
203
+ const parallelism = Math.max(1, options.concurrency);
190
204
  let index = 0;
191
- const workers = Array.from({ length: Math.min(limit, entries.length) }, async () => {
205
+ const workers = Array.from({ length: Math.min(parallelism, entries.length) }, async () => {
206
+ let copied = 0;
192
207
  for (;;) {
193
208
  const current = index++;
194
- if (current >= entries.length) return;
209
+ if (current >= entries.length) break;
195
210
  const name = entries[current] as string;
196
211
  copied += await copyTree(path.join(src, name), path.join(dest, name), options);
197
212
  }
213
+ return copied;
198
214
  });
199
- await Promise.all(workers);
200
- if (options.preserve === true) await preserve(dest, stats);
215
+ const copied = 1 + (await Promise.all(workers)).reduce((sum, value) => sum + value, 0);
216
+ if (options.preserve === true) await limit(() => preserve(dest, stats));
201
217
  return copied;
202
218
  }
203
219
 
204
220
  if (!stats.isFile()) {
205
221
  throw new FsError(`"${src}" is not a regular file or directory.`, "unsupported");
206
222
  }
207
- await ensureParent(dest);
223
+ const existing = await lstatOptional(dest, limit);
224
+ if (options.noClobber === true && existing !== undefined) {
225
+ options.onSkip?.();
226
+ return 0;
227
+ }
228
+ if (existing?.isSymbolicLink() === true) {
229
+ throw new FsError(`Refusing to write through symbolic link: "${dest}".`, "invalid");
230
+ }
231
+ if (
232
+ existing !== undefined &&
233
+ num(existing.dev) === num(stats.dev) &&
234
+ num(existing.ino) === num(stats.ino)
235
+ ) {
236
+ throw new FsError(`"${src}" and destination are the same file.`, "invalid");
237
+ }
238
+ await limit(() => ensureParent(dest));
208
239
  try {
209
- await fs.copyFile(src, dest, options.noClobber === true ? constants.COPYFILE_EXCL : 0);
240
+ await limit(() => fs.copyFile(src, dest, options.noClobber === true ? constants.COPYFILE_EXCL : 0));
210
241
  } catch (error) {
211
242
  /* v8 ignore next */
212
- if (options.noClobber === true && isExists(error)) return 0;
243
+ if (options.noClobber === true && isExists(error)) {
244
+ options.onSkip?.();
245
+ return 0;
246
+ }
213
247
  /* v8 ignore next */
214
248
  throw fromErrno(error);
215
249
  }
216
- if (options.preserve === true) await preserve(dest, stats);
250
+ if (options.preserve === true) await limit(() => preserve(dest, stats));
217
251
  return 1;
218
252
  }
219
253
 
254
+ async function lstatOptional(
255
+ dest: string,
256
+ limit: CopyLimiter,
257
+ ): Promise<Awaited<ReturnType<typeof fs.lstat>> | undefined> {
258
+ try {
259
+ return await limit(() => fs.lstat(dest));
260
+ } catch (error) {
261
+ /* v8 ignore next */
262
+ if (!isMissing(error)) throw fromErrno(error, "access");
263
+ return undefined;
264
+ }
265
+ }
266
+
267
+ function immediate<T>(fn: () => Promise<T>): Promise<T> {
268
+ return fn();
269
+ }
270
+
220
271
  export async function ensureParent(dest: string): Promise<void> {
221
272
  try {
222
273
  await fs.mkdir(path.dirname(dest), { recursive: true });
@@ -230,10 +281,20 @@ export function num(value: number | bigint): number {
230
281
  }
231
282
 
232
283
  export async function preserve(dest: string, stats: Awaited<ReturnType<typeof fs.stat>>): Promise<void> {
284
+ let current: Awaited<ReturnType<typeof fs.lstat>>;
285
+ try {
286
+ current = await fs.lstat(dest);
287
+ } catch (error) {
288
+ throw fromErrno(error, "io");
289
+ }
290
+ if (current.isSymbolicLink()) {
291
+ throw new FsError(`Refusing to preserve metadata through symbolic link: "${dest}".`, "invalid");
292
+ }
233
293
  try {
234
294
  await fs.chmod(dest, num(stats.mode) & 0o7777);
235
295
  await fs.utimes(dest, stats.atime, stats.mtime);
236
296
  } catch (error) {
297
+ /* v8 ignore next */
237
298
  throw fromErrno(error, "io");
238
299
  }
239
300
  }