opencode-fs-plugin 1.6.3 → 1.8.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 +40 -6
- package/SPEC.md +25 -5
- package/package.json +1 -1
- package/skills/filesystem/SKILL.md +62 -13
- package/src/core/types.ts +3 -0
- package/src/index.ts +4 -0
- package/src/tools/exec.ts +255 -0
- package/src/tools/find.ts +64 -6
- package/src/tools/head.ts +15 -6
- package/src/tools/pipe.ts +3 -2
package/README.md
CHANGED
|
@@ -25,9 +25,9 @@ unit, end-to-end and coverage tests.
|
|
|
25
25
|
| `sha256sum`/`md5sum` | `fs.hash` | `algorithm`, `tag`; hashes files or stdin |
|
|
26
26
|
| `du` | `fs.du` | `summarize`, `all`, `human`, `total`, `maxDepth`, `follow`, `oneFileSystem` |
|
|
27
27
|
| `df` | `fs.df` | `human`, `inodes`, `printType`, `all` |
|
|
28
|
-
| `find` | `fs.find` | `name`, `iname`, `pathPattern`, `lname`, `ilname`, `regex`, `iregex`, `type`, `size`, `mtime`, `mmin`, `maxDepth`, `minDepth`, `empty`, `perm`, `uid`, `gid`, `user`, `group`, `links`, `inum`, `samefile`, `fstype`, `newer`, `newerXY`, `printf`, `follow`, `print0`, `sort` |
|
|
28
|
+
| `find` | `fs.find` | `name`, `iname`, `pathPattern`, `lname`, `ilname`, `regex`, `iregex`, `type`, `size`, `mtime`, `mmin`, `maxDepth`, `minDepth`, `empty`, `perm`, `uid`, `gid`, `user`, `group`, `links`, `inum`, `samefile`, `fstype`, `newer`, `newerXY`, `printf`, `follow`, `print0`, `sort`, `action` (`print`/`delete`/`trash`), `recursive` |
|
|
29
29
|
| `cat` | `fs.cat` | `number`, `numberNonBlank`, `squeezeBlank`, `showEnds`, `showTabs`, `showNonPrinting` |
|
|
30
|
-
| `head` | `fs.head` | `lines`, `bytes`, `quiet`, `verbose` |
|
|
30
|
+
| `head` | `fs.head` | `lines`, `skip`, `bytes`, `quiet`, `verbose` |
|
|
31
31
|
| `tail` | `fs.tail` | `lines`, `bytes`, `fromStart`, `quiet`, `verbose`, `follow`, `timeoutMs`, `intervalMs`, `maxBytes` |
|
|
32
32
|
| `tee` | `fs.tee` | `append`, `content` |
|
|
33
33
|
| `wc` | `fs.wc` | `lines`, `words`, `bytes`, `chars`, `maxLineLength` |
|
|
@@ -72,8 +72,13 @@ 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
76
|
| shell pipe | `fs.pipe` | `stages`, `input`, `output`, `append` |
|
|
76
77
|
|
|
78
|
+
`fs.head.skip` selects line ranges (`sed -n '20,40p'`). `fs.find` can
|
|
79
|
+
`action: "delete"` or `"trash"` its matches; the starting directory itself is
|
|
80
|
+
never removed, and the `fs_rm`/`fs_trash` permissions are asserted.
|
|
81
|
+
|
|
77
82
|
Canonical field names are listed above. Aliases are accepted only where noted:
|
|
78
83
|
`path` for one `paths` element (`stat`, `ls`, `cat`, `find`, `tee`, `grep`,
|
|
79
84
|
`sed`), `source` for `sources` (`cp`, `mv`, `ln`), `expression` for
|
|
@@ -98,7 +103,7 @@ await tools.fs.pipe({
|
|
|
98
103
|
})
|
|
99
104
|
```
|
|
100
105
|
|
|
101
|
-
New filter stages: `tac`, `rev`, `nl`, `paste`, `shuf`, `fold`, `base64`, `od`,
|
|
106
|
+
New filter stages: `exec`, `tac`, `rev`, `nl`, `paste`, `shuf`, `fold`, `base64`, `od`,
|
|
102
107
|
and `strings`; `dd` and `cpio` are source/sink stages like `tar`.
|
|
103
108
|
|
|
104
109
|
`fs.http_request` is a pipe source, so network data can feed the same stages:
|
|
@@ -115,12 +120,41 @@ await tools.fs.pipe({
|
|
|
115
120
|
Pipe stages exchange whole buffers, so use `maxBytes` for large responses. For
|
|
116
121
|
large downloads prefer `fs.http_request({ output })`, which streams to disk.
|
|
117
122
|
|
|
118
|
-
There is no shell, redirection operator, nested pipe, or `find -exec`.
|
|
123
|
+
There is no shell, redirection operator, nested pipe, or arbitrary `find -exec`.
|
|
119
124
|
|
|
120
125
|
`fs.pipe` is sequential by design and is not a batch primitive. For independent
|
|
121
126
|
work, fan out with `Promise.all` over `tools.fs.*` (or one multi-path call).
|
|
122
|
-
`fs` domain errors resolve as `ERROR:`/`BLOCKED:` text
|
|
123
|
-
|
|
127
|
+
`fs` domain errors resolve as `ERROR:`/`BLOCKED:` text; permission denials throw.
|
|
128
|
+
|
|
129
|
+
## Exec
|
|
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:
|
|
134
|
+
|
|
135
|
+
```jsonc
|
|
136
|
+
{
|
|
137
|
+
"package": "./repos/opencode-fs-plugin",
|
|
138
|
+
"options": { "execAllowlist": ["npm", "uv"] }
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`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.
|
|
145
|
+
|
|
146
|
+
```js
|
|
147
|
+
await tools.fs.exec({ command: "npm", args: ["run", "build"], timeoutMs: 300000 })
|
|
148
|
+
await tools.fs.pipe({
|
|
149
|
+
stages: [
|
|
150
|
+
{ tool: "exec", args: { command: "npm", args: ["test"] } },
|
|
151
|
+
{ tool: "grep", args: { pattern: "FAIL" } },
|
|
152
|
+
],
|
|
153
|
+
})
|
|
154
|
+
```
|
|
155
|
+
|
|
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.
|
|
124
158
|
|
|
125
159
|
## Performance and concurrency
|
|
126
160
|
|
package/SPEC.md
CHANGED
|
@@ -78,13 +78,30 @@ 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 `child_process` use. It spawns with `shell: false`; there
|
|
84
|
+
is no shell parsing, redirection, or command substitution.
|
|
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
|
+
- `args` are passed verbatim. `cwd` resolves inside the sandbox and asserts
|
|
89
|
+
`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.
|
|
92
|
+
- 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.
|
|
95
|
+
- A non-zero exit is a normal result, not a tool error.
|
|
96
|
+
|
|
81
97
|
## Deliberate gaps
|
|
82
98
|
|
|
83
99
|
These are not implemented:
|
|
84
100
|
|
|
85
101
|
- `xz`, `zstd`, `7z`, `rar`
|
|
86
|
-
- `awk`, full `sed` command language, `find -exec`
|
|
87
|
-
|
|
102
|
+
- `awk`, full `sed` command language, arbitrary `find -exec`; `find action` covers
|
|
103
|
+
delete/trash only
|
|
104
|
+
- `chgrp`, `chattr`, `rsync`
|
|
88
105
|
- ACL and xattr preservation in `cp -a`
|
|
89
106
|
- remaining GNU edge-flag parity for `ls`, `stat`, `sort`, `find`
|
|
90
107
|
- symlink-race-proof sandboxing
|
|
@@ -96,12 +113,12 @@ These are not implemented:
|
|
|
96
113
|
- true streaming through pipe stages; `http_request` buffers unless `output` is set
|
|
97
114
|
- worker threads for CPU-bound stages (`sort`, `sed`, text diffing)
|
|
98
115
|
- parallel member reads inside a single `tar`/`zip` archive; member order is fixed
|
|
99
|
-
- process start
|
|
100
|
-
|
|
116
|
+
- process start beyond the allowlisted `exec` tool; `nohup`, `setsid`, and
|
|
117
|
+
`timeout` wrappers are unavailable
|
|
101
118
|
- ICMP `ping` (raw sockets) and `ip`/netlink configuration
|
|
102
119
|
- `rsync`, `scp`, and other transfer protocols; use the SSH MCP for remote work
|
|
103
120
|
- ACLs, xattrs, and `chattr`/`lsattr`
|
|
104
|
-
- `
|
|
121
|
+
- `jq`/`yq`
|
|
105
122
|
- `7z`, `rar`, `xz`, `zstd`, and `bzip2`; batch 2 may add pure-JS or native deps
|
|
106
123
|
- `fallocate`, `mkfifo`, `mknod`, `flock`, and mount operations
|
|
107
124
|
|
|
@@ -114,6 +131,9 @@ These are not implemented:
|
|
|
114
131
|
- `find -size` accepts `c` (bytes), `w` (2-byte words), `b` (512-byte blocks),
|
|
115
132
|
and binary `K`/`M`/`G`/... suffixes; `-mtime`/`-mmin` accept `+N` (older),
|
|
116
133
|
`-N` (newer), and exact `N`. `newerXY` uses `XY:path`.
|
|
134
|
+
- `head skip` selects a line range: `skip: 19, lines: 21` is `sed -n '20,40p'`.
|
|
135
|
+
- `find action: "delete"|"trash"` reuses the `fs_rm`/`fs_trash` gates, removes
|
|
136
|
+
deepest matches first, and never removes the starting directory itself.
|
|
117
137
|
- `sort -k` accepts field/character ranges with modifiers `bdfghiMnrV`.
|
|
118
138
|
- `tar`/`zip` extraction rejects path traversal and escaping links.
|
|
119
139
|
- `pipe` passes raw bytes and only accepts registered pipeable stages; `tar` and
|
package/package.json
CHANGED
|
@@ -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
|
|
|
@@ -46,13 +47,14 @@ what `fs.stat`, `fs.ls`, `fs.hash`, `fs.diff`, or `fs.cat` can confirm.
|
|
|
46
47
|
| Times and sizes | `fs.touch`, `fs.truncate` |
|
|
47
48
|
| Links and modes | `fs.ln`, `fs.readlink`, `fs.chmod` |
|
|
48
49
|
| Hash, usage | `fs.hash`, `fs.du`, `fs.df` |
|
|
49
|
-
| Predicate search | `fs.find` (`name`, `type`, `size`, `mtime`, `maxDepth`) |
|
|
50
|
+
| Predicate search | `fs.find` (`name`, `type`, `size`, `mtime`, `maxDepth`, `action`) |
|
|
50
51
|
| Archives | `fs.tar` (`create`/`extract`/`list`), `fs.zip`, `fs.unzip` (`extract`/`list`), `fs.cpio`, `fs.ar`, `fs.gzip`, `fs.gunzip` |
|
|
51
52
|
| Compare | `fs.diff` |
|
|
52
53
|
| Temp and trash | `fs.mktemp`, `fs.trash` |
|
|
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` |
|
|
@@ -67,7 +69,7 @@ Recent parity additions:
|
|
|
67
69
|
|---|---|
|
|
68
70
|
| `fs.sort` | `generalNumeric`, `humanNumeric`, `version`, `dictionary`, `ignoreNonPrinting`, `stable`, `check`, `checkQuiet`, `zeroTerminated`, GNU `keys` ranges |
|
|
69
71
|
| `fs.ls` | `size`, `numericIds`, `noGroup`, `noOwner`, `slash`, `quote`, `versionSort`, `extensionSort`, `fullTime`, `timeStyle`, `hide`, `ignore`, `groupDirectoriesFirst` |
|
|
70
|
-
| `fs.find` | `lname`/`ilname`, `regex`/`iregex`, `uid`/`gid`/`user`/`group`, `links`, `inum`, `samefile`, `fstype`, `newerXY`, `printf
|
|
72
|
+
| `fs.find` | `lname`/`ilname`, `regex`/`iregex`, `uid`/`gid`/`user`/`group`, `links`, `inum`, `samefile`, `fstype`, `newerXY`, `printf`, `action` (`print`/`delete`/`trash`); `c`/`w`/`b` size suffixes |
|
|
71
73
|
| `fs.stat` | `terse`, extended tokens `%f`, `%m`, `%r`, `%w`, `%W`, `%C` |
|
|
72
74
|
| `fs.tail` | bounded `follow`, `timeoutMs`, `intervalMs`, `maxBytes` |
|
|
73
75
|
| `fs.tar`/`fs.zip` | `input`/`member` stream input and pipe sink support |
|
|
@@ -98,15 +100,25 @@ 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` | `fs.exec` |
|
|
104
|
+
|
|
105
|
+
`fs.head` takes `skip` for line ranges: `sed -n '20,40p'` is
|
|
106
|
+
`fs.head({ paths, skip: 19, lines: 21 })`. `fs.find` takes
|
|
107
|
+
`action: "print" | "delete" | "trash"`; the starting directory itself is never
|
|
108
|
+
removed, and deletion asserts `fs_rm`/`fs_trash`.
|
|
101
109
|
|
|
102
110
|
### Common mistakes
|
|
103
111
|
|
|
104
112
|
- `fs.hash` canonical is `files`; `paths` and `path` are accepted aliases.
|
|
105
113
|
- `fs.mkdir` canonical is `path`; `paths` is accepted but cannot be combined.
|
|
106
114
|
- `fs.sed` canonical is `script`/`expressions`; `expression` is accepted. Only
|
|
107
|
-
`s/.../.../flags` is supported; line ranges
|
|
115
|
+
`s/.../.../flags` is supported; line ranges use `fs.head({ skip, lines })` or
|
|
116
|
+
`fs.tail`.
|
|
108
117
|
- `fs.grep` canonical is `maxCount`; `limit` is accepted. Add `recursive: true`
|
|
109
118
|
for a directory.
|
|
119
|
+
- `fs.find` `action: "delete"`/`"trash"` never removes the starting directory
|
|
120
|
+
itself; use `fs.rm` if you mean the root. Deletion asserts `fs_rm`/`fs_trash`,
|
|
121
|
+
and directory matches need `recursive: true` for delete.
|
|
110
122
|
- `fs.cat` and text filters read `paths`; Code Mode has no stdin, so `fs.cat({})`
|
|
111
123
|
fails. Use `fs.pipe` for stdin.
|
|
112
124
|
- There is no `fs.write`; use the built-in `write` or `fs.tee({ paths, content })`.
|
|
@@ -118,19 +130,51 @@ host drops unknown fields, so a name typo runs with defaults.
|
|
|
118
130
|
| Shell pattern | Use |
|
|
119
131
|
|---|---|
|
|
120
132
|
| `sed -n '1,80p' f` | `fs.head({ paths: [f], lines: 80 })` |
|
|
121
|
-
| `sed -n '20,40p' f` | `fs.
|
|
133
|
+
| `sed -n '20,40p' f` | `fs.head({ paths: [f], skip: 19, lines: 21 })` |
|
|
122
134
|
| `sed 's/a/b/'` / `sed -i` | `fs.sed({ script, paths, inPlace })` |
|
|
123
135
|
| `head -n N f` / `tail -n N f` | `fs.head` / `fs.tail` |
|
|
124
136
|
| `wc -l f` | `fs.wc({ paths: [f], lines: true })` |
|
|
125
137
|
| `sha256sum f` | `fs.hash({ files: [f] })` |
|
|
126
|
-
| `find ... -exec rm -rf {} +` | `fs.find(
|
|
138
|
+
| `find ... -exec rm -rf {} +` | `fs.find({ ..., action: "delete", recursive: true })` or `action: "trash"` |
|
|
127
139
|
| `cat > f <<EOF` | built-in `write` or `fs.tee({ paths: [f], content })` |
|
|
128
140
|
| `rg pattern path` | `fs.grep({ pattern, paths })` or the built-in `grep` |
|
|
129
141
|
| `ls -l f` | `fs.ls({ paths: [f], long: true })` |
|
|
142
|
+
| `npm ...` / `uv run ...` | `fs.exec({ command, args })` (allowlisted only) |
|
|
130
143
|
|
|
131
144
|
`sed -n` applied to another command's stdout has no fs equivalent; keep that in
|
|
132
|
-
the command pipeline. `fs.find` has no `-exec` by design;
|
|
133
|
-
delete or trash
|
|
145
|
+
the command pipeline. `fs.find` has no arbitrary `-exec` by design; use
|
|
146
|
+
`action: "delete"` or `"trash"` for the common cleanup case, or list the paths and
|
|
147
|
+
remove them explicitly.
|
|
148
|
+
|
|
149
|
+
## Exec
|
|
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`:
|
|
154
|
+
|
|
155
|
+
```jsonc
|
|
156
|
+
{ "package": "./repos/opencode-fs-plugin", "options": { "execAllowlist": ["npm", "uv"] } }
|
|
157
|
+
```
|
|
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.
|
|
163
|
+
|
|
164
|
+
```js
|
|
165
|
+
await tools.fs.exec({ command: "npm", args: ["run", "build"], timeoutMs: 300000 })
|
|
166
|
+
await tools.fs.exec({ command: "uv", args: ["run", "pytest"] })
|
|
167
|
+
await tools.fs.pipe({
|
|
168
|
+
stages: [
|
|
169
|
+
{ tool: "exec", args: { command: "npm", args: ["test"] } },
|
|
170
|
+
{ tool: "grep", args: { pattern: "FAIL" } },
|
|
171
|
+
],
|
|
172
|
+
})
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
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.
|
|
134
178
|
|
|
135
179
|
## Batch independent calls
|
|
136
180
|
|
|
@@ -244,9 +288,9 @@ Common pipe mistakes:
|
|
|
244
288
|
- There is no shell, redirection operator, nested pipe, `find -exec`, or
|
|
245
289
|
`xargs`.
|
|
246
290
|
|
|
247
|
-
Pipeable filters include `head`, `tail`, `grep`, `sed`, `sort`, `uniq`,
|
|
248
|
-
`tr`, `tee`, `gzip`, `gunzip`, `tac`, `rev`, `nl`, `paste`, `shuf`,
|
|
249
|
-
`base64`, `od`, and `strings`. Unknown stage names fail with `unsupported`.
|
|
291
|
+
Pipeable filters include `exec`, `head`, `tail`, `grep`, `sed`, `sort`, `uniq`,
|
|
292
|
+
`cut`, `tr`, `tee`, `gzip`, `gunzip`, `tac`, `rev`, `nl`, `paste`, `shuf`,
|
|
293
|
+
`fold`, `base64`, `od`, and `strings`. Unknown stage names fail with `unsupported`.
|
|
250
294
|
|
|
251
295
|
## Background jobs
|
|
252
296
|
|
|
@@ -363,7 +407,8 @@ await tools.fs.http_request({
|
|
|
363
407
|
- Linux only; there is no Windows branch.
|
|
364
408
|
- `fs.sed` supports `s<delim>pattern<delim>replacement<delim>flags` with `g`,
|
|
365
409
|
`i` and `p`. It is not a full sed interpreter.
|
|
366
|
-
- `fs.find` has no `-exec`; use `
|
|
410
|
+
- `fs.find` has no arbitrary `-exec`; use `action: "delete"`/`"trash"` for the
|
|
411
|
+
common cleanup case, or `fs.rm`/`fs.trash` separately.
|
|
367
412
|
- No `xz`, `zstd`, `7z`, `rar`, `chattr`, ACLs, xattrs, or `rsync`.
|
|
368
413
|
`chown` and `dd` are available; the SSH MCP covers transfers.
|
|
369
414
|
- `fs.tail` has bounded `follow` only; unbounded `tail -f` is not supported.
|
|
@@ -371,8 +416,9 @@ await tools.fs.http_request({
|
|
|
371
416
|
- `fs.tar`/`fs.zip` create from `input` or stdin; extraction is file-backed.
|
|
372
417
|
- `fs.http_request` is HTTP(S) only: no FTP/SFTP, cookie jars, client
|
|
373
418
|
certificates, proxies, multipart uploads, or resumable downloads.
|
|
374
|
-
-
|
|
375
|
-
|
|
419
|
+
- Only `fs.exec` starts processes, and only exact allowlisted names; `nohup`,
|
|
420
|
+
`setsid`, and `timeout` wrappers are unavailable. `fs.kill` rejects pid 0,
|
|
421
|
+
pid 1, and process groups.
|
|
376
422
|
- No ICMP ping; use `fs.http_request` or a TCP port check. No ACL, xattr, or
|
|
377
423
|
`chattr` support. `rsync`/`scp` are out of scope; use the SSH MCP.
|
|
378
424
|
- `fs.comm` expects sorted input. `fs.ar` uses GNU short names (16 bytes max);
|
|
@@ -414,6 +460,9 @@ Command actions are `fs_<command>` (for example `fs_cp`). `fs_*` wildcards work
|
|
|
414
460
|
in agent rules. `fs.pipe` asserts each stage's action; a denied stage cannot be
|
|
415
461
|
hidden inside a pipeline. Do not work around a denied tool with shell.
|
|
416
462
|
|
|
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.
|
|
465
|
+
|
|
417
466
|
`fs_http_request` is allowed by default, like `fetch`. Its resource is the
|
|
418
467
|
request host; rules can allow one host and ask or deny the rest. Each redirect
|
|
419
468
|
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,255 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
7
|
+
import { once } from "node:events";
|
|
8
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
9
|
+
import { FsError, fromErrno } from "../core/errors.js";
|
|
10
|
+
import { textResult, type RunContext, type ToolSpec } from "../core/types.js";
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_EXEC_ALLOWLIST = ["npm", "npx", "uv", "uvx", "pip", "pip3"] as const;
|
|
13
|
+
|
|
14
|
+
const EXEC_NAME = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;
|
|
15
|
+
|
|
16
|
+
export function isSafeExecName(value: string): boolean {
|
|
17
|
+
return EXEC_NAME.test(value);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function normalizeExecAllowlist(value: unknown): readonly string[] {
|
|
21
|
+
if (value === undefined) return DEFAULT_EXEC_ALLOWLIST;
|
|
22
|
+
if (!Array.isArray(value)) throw new FsError("execAllowlist must be an array of executable names.", "invalid");
|
|
23
|
+
const names: string[] = [];
|
|
24
|
+
for (const entry of value) {
|
|
25
|
+
if (typeof entry !== "string") throw new FsError("execAllowlist entries must be strings.", "invalid");
|
|
26
|
+
const name = entry.trim();
|
|
27
|
+
if (!isSafeExecName(name)) throw new FsError(`Invalid exec allowlist entry: ${entry}`, "invalid");
|
|
28
|
+
names.push(name);
|
|
29
|
+
}
|
|
30
|
+
return [...new Set(names)];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const Schema = Type.Object(
|
|
34
|
+
{
|
|
35
|
+
command: Type.String({ minLength: 1, description: "Allowlisted executable name, without a path or shell syntax." }),
|
|
36
|
+
args: Type.Optional(Type.Array(Type.String(), { description: "Arguments passed verbatim to the executable." })),
|
|
37
|
+
cwd: Type.Optional(Type.String({ minLength: 1, description: "Working directory inside the project. Default: project root." })),
|
|
38
|
+
stdin: Type.Optional(Type.String({ description: "Text for stdin when the tool is not used in a pipe." })),
|
|
39
|
+
timeoutMs: Type.Optional(
|
|
40
|
+
Type.Integer({ minimum: 100, maximum: 600_000, description: "Timeout in milliseconds. Default: 120000." }),
|
|
41
|
+
),
|
|
42
|
+
},
|
|
43
|
+
{ additionalProperties: false },
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
type Input = Static<typeof Schema>;
|
|
47
|
+
|
|
48
|
+
interface ExecOutcome {
|
|
49
|
+
stdout: Buffer;
|
|
50
|
+
stderr: Buffer;
|
|
51
|
+
exitCode: number;
|
|
52
|
+
signal: NodeJS.Signals | null;
|
|
53
|
+
timedOut: boolean;
|
|
54
|
+
aborted: boolean;
|
|
55
|
+
stdoutTruncated: boolean;
|
|
56
|
+
stderrTruncated: boolean;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export const execTool: ToolSpec<Input> = {
|
|
60
|
+
name: "exec",
|
|
61
|
+
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.",
|
|
64
|
+
schema: Schema,
|
|
65
|
+
pipeable: "filter",
|
|
66
|
+
mutates: true,
|
|
67
|
+
async run(ctx, input, io) {
|
|
68
|
+
const command = input.command.trim();
|
|
69
|
+
if (!isSafeExecName(command)) {
|
|
70
|
+
throw new FsError(`exec command must be a bare executable name: "${input.command}"`, "invalid");
|
|
71
|
+
}
|
|
72
|
+
if (!ctx.execAllowlist.includes(command)) {
|
|
73
|
+
throw new FsError(`exec command is not allowlisted: "${command}"`, "unsupported");
|
|
74
|
+
}
|
|
75
|
+
const args = input.args ?? [];
|
|
76
|
+
if (args.some((arg) => arg.includes("\0"))) {
|
|
77
|
+
throw new FsError("exec arguments must not contain NUL bytes.", "invalid");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
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 }]);
|
|
85
|
+
if (ctx.signal.aborted) throw new FsError("exec interrupted.", "interrupted");
|
|
86
|
+
|
|
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,
|
|
109
|
+
stderr: outcome.stderr.toString("utf8"),
|
|
110
|
+
exitCode: outcome.exitCode === 0 ? 0 : 1,
|
|
111
|
+
metadata,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
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
|
+
},
|
|
121
|
+
};
|
|
122
|
+
|
|
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;
|
|
156
|
+
});
|
|
157
|
+
child.stderr?.on("data", (chunk: Buffer) => {
|
|
158
|
+
const next = appendCapped(stderr, chunk, cap);
|
|
159
|
+
stderr = next.data;
|
|
160
|
+
stderrTruncated ||= next.truncated;
|
|
161
|
+
});
|
|
162
|
+
|
|
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");
|
|
172
|
+
};
|
|
173
|
+
ctx.signal.addEventListener("abort", onAbort, { once: true });
|
|
174
|
+
|
|
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
|
+
});
|
|
202
|
+
|
|
203
|
+
if (feed) void feedStdin(child, input, pipe);
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
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);
|
|
223
|
+
}
|
|
224
|
+
stdin.end();
|
|
225
|
+
} catch {
|
|
226
|
+
/* child closed before the write completed */
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
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 };
|
|
235
|
+
}
|
|
236
|
+
|
|
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") {
|
|
242
|
+
try {
|
|
243
|
+
process.kill(-child.pid, signal);
|
|
244
|
+
return;
|
|
245
|
+
} catch {
|
|
246
|
+
/* fall through to child.kill */
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/* v8 ignore next 5 */
|
|
250
|
+
try {
|
|
251
|
+
child.kill(signal);
|
|
252
|
+
} catch {
|
|
253
|
+
/* already gone */
|
|
254
|
+
}
|
|
255
|
+
}
|
package/src/tools/find.ts
CHANGED
|
@@ -11,6 +11,8 @@ import { pathsFrom } from "../core/aliases.js";
|
|
|
11
11
|
import { FsError } from "../core/errors.js";
|
|
12
12
|
import { lookupGroup, lookupUser, modeString, num, typeName, walkAll } from "../core/fsutil.js";
|
|
13
13
|
import { textResult, type ToolSpec } from "../core/types.js";
|
|
14
|
+
import { rmTool } from "./rm.js";
|
|
15
|
+
import { trashTool } from "./trash.js";
|
|
14
16
|
|
|
15
17
|
const Schema = Type.Object(
|
|
16
18
|
{
|
|
@@ -49,6 +51,15 @@ const Schema = Type.Object(
|
|
|
49
51
|
follow: Type.Optional(Type.Boolean({ description: "Follow symlinks (`-L`)." })),
|
|
50
52
|
print0: Type.Optional(Type.Boolean({ description: "NUL-separated output (`-print0`)." })),
|
|
51
53
|
sort: Type.Optional(Type.Boolean({ description: "Sort results lexically. Default: true." })),
|
|
54
|
+
action: Type.Optional(
|
|
55
|
+
Type.Union([Type.Literal("print"), Type.Literal("delete"), Type.Literal("trash")], {
|
|
56
|
+
description:
|
|
57
|
+
"What to do with matches. Default `print`. `delete`/`trash` are destructive and assert `fs_rm`/`fs_trash`; the starting directory itself is never removed.",
|
|
58
|
+
}),
|
|
59
|
+
),
|
|
60
|
+
recursive: Type.Optional(
|
|
61
|
+
Type.Boolean({ description: "Delete matched directories recursively (`action: delete` only)." }),
|
|
62
|
+
),
|
|
52
63
|
},
|
|
53
64
|
{ additionalProperties: false },
|
|
54
65
|
);
|
|
@@ -78,6 +89,15 @@ interface Patterns {
|
|
|
78
89
|
fstypeCache: Map<string, string>;
|
|
79
90
|
}
|
|
80
91
|
|
|
92
|
+
interface Match {
|
|
93
|
+
requested: string;
|
|
94
|
+
full: string;
|
|
95
|
+
stats: Awaited<ReturnType<typeof fs.lstat>>;
|
|
96
|
+
root: string;
|
|
97
|
+
depth: number;
|
|
98
|
+
isRoot: boolean;
|
|
99
|
+
}
|
|
100
|
+
|
|
81
101
|
const FS_TYPES = new Map<number, string>([
|
|
82
102
|
[0xef53, "ext4"],
|
|
83
103
|
[0x01021994, "tmpfs"],
|
|
@@ -108,13 +128,21 @@ export const findTool: ToolSpec<Input> = {
|
|
|
108
128
|
"Find entries with Linux-like predicates: `-name`, `-iname`, `-path`, `-lname`, `-ilname`, " +
|
|
109
129
|
"`-regex`, `-iregex`, `-type`, `-size`, `-mtime`, `-mmin`, `-maxdepth`, `-mindepth`, `-empty`, `-perm`, " +
|
|
110
130
|
"`-uid`, `-gid`, `-user`, `-group`, `-links`, `-inum`, `-samefile`, `-fstype`, `-newer`, " +
|
|
111
|
-
"`-newerXY`, `-printf`, `-L`, `-print0`."
|
|
131
|
+
"`-newerXY`, `-printf`, `-L`, `-print0`. `action` can print, delete, or trash matches; " +
|
|
132
|
+
"the starting directory itself is never removed.",
|
|
112
133
|
schema: Schema,
|
|
113
134
|
pipeable: false,
|
|
114
|
-
mutates:
|
|
135
|
+
mutates: true,
|
|
115
136
|
async run(ctx, input) {
|
|
116
137
|
/* v8 ignore next */
|
|
117
138
|
const paths = pathsFrom(input) ?? ["."];
|
|
139
|
+
const action = input.action ?? "print";
|
|
140
|
+
if (action !== "print" && (input.printf !== undefined || input.print0 === true)) {
|
|
141
|
+
throw new FsError("find action delete/trash cannot be combined with printf or print0.", "invalid");
|
|
142
|
+
}
|
|
143
|
+
if (input.recursive === true && action !== "delete") {
|
|
144
|
+
throw new FsError("find recursive requires action: delete.", "invalid");
|
|
145
|
+
}
|
|
118
146
|
const patterns: Patterns = {
|
|
119
147
|
nameMatch: input.name === undefined ? undefined : picomatch(input.name, { dot: true }),
|
|
120
148
|
inameMatch: input.iname === undefined ? undefined : picomatch(input.iname, { dot: true, nocase: true }),
|
|
@@ -141,7 +169,7 @@ export const findTool: ToolSpec<Input> = {
|
|
|
141
169
|
patterns.uid = input.uid ?? await resolveId(input.user, "user");
|
|
142
170
|
patterns.gid = input.gid ?? await resolveId(input.group, "group");
|
|
143
171
|
|
|
144
|
-
const
|
|
172
|
+
const found: Match[] = [];
|
|
145
173
|
for (const requested of paths) {
|
|
146
174
|
const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
|
|
147
175
|
await ctx.permission.assert([{ target, boundary: target.full }]);
|
|
@@ -152,14 +180,14 @@ export const findTool: ToolSpec<Input> = {
|
|
|
152
180
|
/* v8 ignore next */
|
|
153
181
|
if (!rootStats.isDirectory()) {
|
|
154
182
|
if (await matches(target.full, rootStats, input, patterns, 0)) {
|
|
155
|
-
|
|
183
|
+
found.push({ requested, full: target.full, stats: rootStats, root: target.full, depth: 0, isRoot: true });
|
|
156
184
|
}
|
|
157
185
|
continue;
|
|
158
186
|
}
|
|
159
187
|
/* v8 ignore next */
|
|
160
188
|
if (input.maxDepth === 0) {
|
|
161
189
|
if (await matches(target.full, rootStats, input, patterns, 0)) {
|
|
162
|
-
|
|
190
|
+
found.push({ requested, full: target.full, stats: rootStats, root: target.full, depth: 0, isRoot: true });
|
|
163
191
|
}
|
|
164
192
|
continue;
|
|
165
193
|
}
|
|
@@ -175,10 +203,40 @@ export const findTool: ToolSpec<Input> = {
|
|
|
175
203
|
const depth = relative.split(path.sep).length;
|
|
176
204
|
if (input.minDepth !== undefined && depth < input.minDepth) continue;
|
|
177
205
|
if (await matches(entry.path, entry.stats, input, patterns, depth)) {
|
|
178
|
-
|
|
206
|
+
found.push({ requested: entry.path, full: entry.path, stats: entry.stats, root: target.full, depth, isRoot: false });
|
|
179
207
|
}
|
|
180
208
|
}
|
|
181
209
|
}
|
|
210
|
+
|
|
211
|
+
if (action !== "print") {
|
|
212
|
+
const targets = found
|
|
213
|
+
.filter((match) => !(match.isRoot && match.stats.isDirectory()))
|
|
214
|
+
.sort((a, b) => b.depth - a.depth || a.full.localeCompare(b.full));
|
|
215
|
+
const unique = [...new Map(targets.map((match) => [match.full, match])).values()];
|
|
216
|
+
if (unique.length === 0) {
|
|
217
|
+
return textResult("", { found: found.length, action, ...(action === "delete" ? { removed: [] } : { trashed: [] }) });
|
|
218
|
+
}
|
|
219
|
+
const pathsToChange = unique.map((match) => match.full);
|
|
220
|
+
if (action === "delete") {
|
|
221
|
+
const result = await rmTool.run(
|
|
222
|
+
{ ...ctx, permission: ctx.permissionFor("fs_rm") },
|
|
223
|
+
{ paths: pathsToChange, recursive: input.recursive === true, force: true },
|
|
224
|
+
{},
|
|
225
|
+
);
|
|
226
|
+
return textResult("", { found: found.length, action, ...result.metadata });
|
|
227
|
+
}
|
|
228
|
+
const result = await trashTool.run(
|
|
229
|
+
{ ...ctx, permission: ctx.permissionFor("fs_trash") },
|
|
230
|
+
{ paths: pathsToChange },
|
|
231
|
+
{},
|
|
232
|
+
);
|
|
233
|
+
return textResult("", { found: found.length, action, ...result.metadata });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const results: string[] = [];
|
|
237
|
+
for (const match of found) {
|
|
238
|
+
results.push(await render(match.requested, match.full, match.stats, input, patterns, match.root, match.depth));
|
|
239
|
+
}
|
|
182
240
|
if (input.sort !== false) results.sort((a, b) => a.localeCompare(b));
|
|
183
241
|
if (input.printf !== undefined) {
|
|
184
242
|
return textResult(results.join(""), { found: results.length });
|
package/src/tools/head.ts
CHANGED
|
@@ -12,6 +12,9 @@ const Schema = Type.Object(
|
|
|
12
12
|
{
|
|
13
13
|
paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to read. Omit to read stdin." })),
|
|
14
14
|
lines: Type.Optional(Type.Integer({ minimum: 1, description: "Number of lines. Default: 10 (`-n`)." })),
|
|
15
|
+
skip: Type.Optional(
|
|
16
|
+
Type.Integer({ minimum: 0, description: "Skip this many leading lines before output (`sed -n 'a,bp'` ranges)." }),
|
|
17
|
+
),
|
|
15
18
|
bytes: Type.Optional(Type.Integer({ minimum: 1, description: "Number of bytes (`-c`)." })),
|
|
16
19
|
quiet: Type.Optional(Type.Boolean({ description: "Never print file headers (`-q`)." })),
|
|
17
20
|
verbose: Type.Optional(Type.Boolean({ description: "Always print file headers (`-v`)." })),
|
|
@@ -23,7 +26,9 @@ type Input = Static<typeof Schema>;
|
|
|
23
26
|
|
|
24
27
|
export const headTool: ToolSpec<Input> = {
|
|
25
28
|
name: "head",
|
|
26
|
-
description:
|
|
29
|
+
description:
|
|
30
|
+
"Output the first part of files or stdin with Linux `head` semantics (`-n`, `-c`, `-q`, `-v`). " +
|
|
31
|
+
"`skip` selects a line range such as `sed -n '20,40p'`.",
|
|
27
32
|
schema: Schema,
|
|
28
33
|
pipeable: "filter",
|
|
29
34
|
mutates: false,
|
|
@@ -31,7 +36,11 @@ export const headTool: ToolSpec<Input> = {
|
|
|
31
36
|
if (input.lines !== undefined && input.bytes !== undefined) {
|
|
32
37
|
throw new FsError("head accepts either lines or bytes, not both.", "invalid");
|
|
33
38
|
}
|
|
39
|
+
if (input.skip !== undefined && input.bytes !== undefined) {
|
|
40
|
+
throw new FsError("head skip applies to lines, not bytes.", "invalid");
|
|
41
|
+
}
|
|
34
42
|
const count = input.bytes ?? input.lines ?? 10;
|
|
43
|
+
const skip = input.skip ?? 0;
|
|
35
44
|
const paths = input.paths ?? [];
|
|
36
45
|
const targets = [];
|
|
37
46
|
for (const requested of paths) {
|
|
@@ -46,7 +55,7 @@ export const headTool: ToolSpec<Input> = {
|
|
|
46
55
|
if (targets.length === 0) {
|
|
47
56
|
const data = input.bytes !== undefined
|
|
48
57
|
? await collect(await inputStream([], io.stdin), input.bytes)
|
|
49
|
-
: await takeLines(inputStream([], io.stdin), count);
|
|
58
|
+
: await takeLines(inputStream([], io.stdin), count, skip);
|
|
50
59
|
output.push(data);
|
|
51
60
|
} else {
|
|
52
61
|
for (const target of targets) {
|
|
@@ -56,7 +65,7 @@ export const headTool: ToolSpec<Input> = {
|
|
|
56
65
|
output.push(
|
|
57
66
|
input.bytes !== undefined
|
|
58
67
|
? await collect(readFiles([target.full]), input.bytes)
|
|
59
|
-
: await takeLines(readFiles([target.full]), count),
|
|
68
|
+
: await takeLines(readFiles([target.full]), count, skip),
|
|
60
69
|
);
|
|
61
70
|
}
|
|
62
71
|
}
|
|
@@ -64,14 +73,14 @@ export const headTool: ToolSpec<Input> = {
|
|
|
64
73
|
},
|
|
65
74
|
};
|
|
66
75
|
|
|
67
|
-
async function takeLines(stream: AsyncIterable<Buffer>, count: number): Promise<Buffer> {
|
|
76
|
+
async function takeLines(stream: AsyncIterable<Buffer>, count: number, skip = 0): Promise<Buffer> {
|
|
68
77
|
const output: string[] = [];
|
|
78
|
+
let seen = 0;
|
|
69
79
|
let taken = 0;
|
|
70
80
|
for await (const line of lines(stream)) {
|
|
71
|
-
|
|
81
|
+
if (seen++ < skip) continue;
|
|
72
82
|
output.push(line.text + (line.newline ? "\n" : ""));
|
|
73
83
|
taken++;
|
|
74
|
-
/* v8 ignore next */
|
|
75
84
|
if (taken >= count) break;
|
|
76
85
|
}
|
|
77
86
|
return Buffer.from(output.join(""), "utf8");
|
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,
|