opencode-fs-plugin 1.2.2 → 1.3.1
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/INSTALL.md +9 -9
- package/README.md +43 -10
- package/SPEC.md +18 -0
- package/package.json +2 -2
- package/skills/filesystem/SKILL.md +35 -3
- package/src/index.ts +2 -0
- package/src/tools/http_request.ts +392 -0
- package/src/tools/pipe.ts +2 -0
package/INSTALL.md
CHANGED
|
@@ -17,14 +17,14 @@ Add the registry package to the plugin list:
|
|
|
17
17
|
|
|
18
18
|
```jsonc
|
|
19
19
|
{
|
|
20
|
-
"plugins": ["opencode-fs-plugin@1.
|
|
20
|
+
"plugins": ["opencode-fs-plugin@1.3.1"]
|
|
21
21
|
}
|
|
22
22
|
```
|
|
23
23
|
|
|
24
24
|
Or let the CLI install and configure it:
|
|
25
25
|
|
|
26
26
|
```bash
|
|
27
|
-
opencode plugin add opencode-fs-plugin@1.
|
|
27
|
+
opencode plugin add opencode-fs-plugin@1.3.1
|
|
28
28
|
```
|
|
29
29
|
|
|
30
30
|
A bare `opencode-fs-plugin` follows `latest`. OpenCode installs it into its
|
|
@@ -36,7 +36,7 @@ Option A if you also want the skill.
|
|
|
36
36
|
Download the release artifact and install it as a normal npm package:
|
|
37
37
|
|
|
38
38
|
```bash
|
|
39
|
-
VERSION=1.
|
|
39
|
+
VERSION=1.3.1
|
|
40
40
|
curl -L -o "opencode-fs-plugin-${VERSION}.tgz" \
|
|
41
41
|
"https://github.com/masterjg/opencode-fs-plugin/releases/download/v${VERSION}/opencode-fs-plugin-${VERSION}.tgz"
|
|
42
42
|
npm install "./opencode-fs-plugin-${VERSION}.tgz"
|
|
@@ -64,20 +64,20 @@ OpenCode installs it from Git:
|
|
|
64
64
|
|
|
65
65
|
```jsonc
|
|
66
66
|
{
|
|
67
|
-
"plugins": ["github:masterjg/opencode-fs-plugin#v1.
|
|
67
|
+
"plugins": ["github:masterjg/opencode-fs-plugin#v1.3.1"]
|
|
68
68
|
}
|
|
69
69
|
```
|
|
70
70
|
|
|
71
|
-
`opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.
|
|
71
|
+
`opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.3.1'` installs the
|
|
72
72
|
same spec and writes the entry for you. The equivalent full URL is
|
|
73
|
-
`git+https://github.com/masterjg/opencode-fs-plugin.git#v1.
|
|
73
|
+
`git+https://github.com/masterjg/opencode-fs-plugin.git#v1.3.1`. A tag is
|
|
74
74
|
checked for updates; use a full commit hash to pin it.
|
|
75
75
|
|
|
76
76
|
Git plugins are installed under OpenCode's cache, so their package path is not
|
|
77
77
|
stable. For a stable skill path, install the tag with npm instead:
|
|
78
78
|
|
|
79
79
|
```bash
|
|
80
|
-
npm install "github:masterjg/opencode-fs-plugin#v1.
|
|
80
|
+
npm install "github:masterjg/opencode-fs-plugin#v1.3.1"
|
|
81
81
|
```
|
|
82
82
|
|
|
83
83
|
Then configure `./node_modules/opencode-fs-plugin` in `plugins` as in the
|
|
@@ -174,9 +174,9 @@ and description until the model loads it.
|
|
|
174
174
|
To let a coding agent install the plugin, use:
|
|
175
175
|
|
|
176
176
|
```text
|
|
177
|
-
Install opencode-fs-plugin 1.
|
|
177
|
+
Install opencode-fs-plugin 1.3.1 with "npm install opencode-fs-plugin@1.3.1",
|
|
178
178
|
or from its release tarball or the Git tag
|
|
179
|
-
"github:masterjg/opencode-fs-plugin#v1.
|
|
179
|
+
"github:masterjg/opencode-fs-plugin#v1.3.1". Add
|
|
180
180
|
"./node_modules/opencode-fs-plugin" to the plugins array in opencode.jsonc, add
|
|
181
181
|
"./node_modules/opencode-fs-plugin/skills" to the skills array, then verify that
|
|
182
182
|
the filesystem skill loads with the skill tool using id "filesystem".
|
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# opencode-fs-plugin
|
|
2
2
|
|
|
3
|
-
An OpenCode 2 plugin that adds a Linux-style filesystem
|
|
4
|
-
the `fs` namespace. It is a maintained fork of
|
|
3
|
+
An OpenCode 2 plugin that adds a Linux-style filesystem, text, and HTTP(S)
|
|
4
|
+
toolkit under the `fs` namespace. It is a maintained fork of
|
|
5
5
|
[`kiu345/opencode-fs-plugin`](https://github.com/kiu345/opencode-fs-plugin),
|
|
6
6
|
rewritten with async I/O, permission integration, a symlink-aware sandbox, and
|
|
7
7
|
unit, end-to-end and coverage tests.
|
|
@@ -45,6 +45,7 @@ unit, end-to-end and coverage tests.
|
|
|
45
45
|
| `mktemp` | `fs.mktemp` | `template`, `directory`, `tmpdir`, `suffix` |
|
|
46
46
|
| `trash` | `fs.trash` | XDG home trash |
|
|
47
47
|
| `diff` | `fs.diff` | `unified`, `brief`, `recursive`, `ignoreWhitespace`, `ignoreCase`, `exclude` |
|
|
48
|
+
| HTTP(S) | `fs.http_request` | `url`, `method`, `headers`, `body`, `json`, `output`, `checksum`, `maxBytes`, `timeoutMs`, `failOnError`, `followRedirects`, `maxRedirects` |
|
|
48
49
|
| shell pipe | `fs.pipe` | `stages`, `input`, `output`, `append` |
|
|
49
50
|
|
|
50
51
|
## Pipe
|
|
@@ -64,6 +65,20 @@ await tools.fs.pipe({
|
|
|
64
65
|
})
|
|
65
66
|
```
|
|
66
67
|
|
|
68
|
+
`fs.http_request` is a pipe source, so network data can feed the same stages:
|
|
69
|
+
|
|
70
|
+
```js
|
|
71
|
+
await tools.fs.pipe({
|
|
72
|
+
stages: [
|
|
73
|
+
{ tool: "http_request", args: { url: "https://example.com/app.log" } },
|
|
74
|
+
{ tool: "grep", args: { pattern: "ERROR" } },
|
|
75
|
+
],
|
|
76
|
+
})
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Pipe stages exchange whole buffers, so use `maxBytes` for large responses. For
|
|
80
|
+
large downloads prefer `fs.http_request({ output })`, which streams to disk.
|
|
81
|
+
|
|
67
82
|
There is no shell, redirection operator, nested pipe, or `find -exec`.
|
|
68
83
|
|
|
69
84
|
## Background jobs
|
|
@@ -127,18 +142,18 @@ Add the registry package directly to the plugin list:
|
|
|
127
142
|
|
|
128
143
|
```jsonc
|
|
129
144
|
{
|
|
130
|
-
"plugins": ["opencode-fs-plugin@1.
|
|
145
|
+
"plugins": ["opencode-fs-plugin@1.3.1"]
|
|
131
146
|
}
|
|
132
147
|
```
|
|
133
148
|
|
|
134
|
-
`opencode plugin add opencode-fs-plugin@1.
|
|
149
|
+
`opencode plugin add opencode-fs-plugin@1.3.1` installs it and writes the config
|
|
135
150
|
entry. A bare `opencode-fs-plugin` follows the `latest` tag.
|
|
136
151
|
|
|
137
152
|
OpenCode manages the package under its cache, so the path is not stable. If you
|
|
138
153
|
also want the packaged skill, install it into a project instead:
|
|
139
154
|
|
|
140
155
|
```bash
|
|
141
|
-
npm install opencode-fs-plugin@1.
|
|
156
|
+
npm install opencode-fs-plugin@1.3.1
|
|
142
157
|
```
|
|
143
158
|
|
|
144
159
|
```jsonc
|
|
@@ -153,7 +168,7 @@ npm install opencode-fs-plugin@1.2.2
|
|
|
153
168
|
Download the release tarball, then install it as a normal npm package:
|
|
154
169
|
|
|
155
170
|
```bash
|
|
156
|
-
VERSION=1.
|
|
171
|
+
VERSION=1.3.1
|
|
157
172
|
curl -L -o "opencode-fs-plugin-${VERSION}.tgz" \
|
|
158
173
|
"https://github.com/masterjg/opencode-fs-plugin/releases/download/v${VERSION}/opencode-fs-plugin-${VERSION}.tgz"
|
|
159
174
|
npm install "./opencode-fs-plugin-${VERSION}.tgz"
|
|
@@ -182,20 +197,20 @@ OpenCode installs it from Git:
|
|
|
182
197
|
|
|
183
198
|
```jsonc
|
|
184
199
|
{
|
|
185
|
-
"plugins": ["github:masterjg/opencode-fs-plugin#v1.
|
|
200
|
+
"plugins": ["github:masterjg/opencode-fs-plugin#v1.3.1"]
|
|
186
201
|
}
|
|
187
202
|
```
|
|
188
203
|
|
|
189
|
-
`opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.
|
|
204
|
+
`opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.3.1'` installs the
|
|
190
205
|
same spec and writes the config entry. The equivalent full URL is
|
|
191
|
-
`git+https://github.com/masterjg/opencode-fs-plugin.git#v1.
|
|
206
|
+
`git+https://github.com/masterjg/opencode-fs-plugin.git#v1.3.1`. A tag is
|
|
192
207
|
checked for updates; use a full commit hash to pin it.
|
|
193
208
|
|
|
194
209
|
Git plugins are installed under OpenCode's cache, so their package path is not
|
|
195
210
|
stable. If you also want the packaged skill, install with npm instead:
|
|
196
211
|
|
|
197
212
|
```bash
|
|
198
|
-
npm install "github:masterjg/opencode-fs-plugin#v1.
|
|
213
|
+
npm install "github:masterjg/opencode-fs-plugin#v1.3.1"
|
|
199
214
|
```
|
|
200
215
|
|
|
201
216
|
Then use `./node_modules/opencode-fs-plugin` in `plugins` and
|
|
@@ -253,6 +268,20 @@ Every tool asserts an action named after the tool (`fs_cp`, `fs_rm`,
|
|
|
253
268
|
external targets first require `external_directory` on the absolute boundary.
|
|
254
269
|
`allow always` persists the same patterns as the built-in tools.
|
|
255
270
|
|
|
271
|
+
`fs.http_request` is allowed by default, like `fetch`. Its resource is the
|
|
272
|
+
request host (`example.com:8443`), so requests can be restricted per host:
|
|
273
|
+
|
|
274
|
+
```jsonc
|
|
275
|
+
{
|
|
276
|
+
"permissions": [
|
|
277
|
+
{ "action": "fs_http_request", "resource": "api.github.com", "effect": "allow" },
|
|
278
|
+
{ "action": "fs_http_request", "resource": "*", "effect": "ask" }
|
|
279
|
+
]
|
|
280
|
+
}
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
Redirects re-assert the rule against each new host.
|
|
284
|
+
|
|
256
285
|
Agent rules can use wildcards:
|
|
257
286
|
|
|
258
287
|
```jsonc
|
|
@@ -285,6 +314,10 @@ when only some agents should be shell-free.
|
|
|
285
314
|
project requires `external_directory`; removing or renaming the link itself is
|
|
286
315
|
internal.
|
|
287
316
|
- Archive extraction rejects absolute paths, `..`, and escaping symlinks.
|
|
317
|
+
- `http_request` accepts only `http:` and `https:`, keeps TLS verification on,
|
|
318
|
+
re-checks permissions on redirect hops, and writes downloads to a temporary
|
|
319
|
+
file before renaming. Localhost and private addresses are not blocked by
|
|
320
|
+
default.
|
|
288
321
|
- `rm` is permanent. `trash` uses the XDG home trash and refuses cross-device
|
|
289
322
|
moves instead of silently copying.
|
|
290
323
|
- The sandbox is a guardrail, not a kernel security boundary. Symlink races
|
package/SPEC.md
CHANGED
|
@@ -25,6 +25,21 @@ the `fs` namespace (`tools.fs.cp`, direct `fs_cp`).
|
|
|
25
25
|
- Results stay in memory and are returned by `fs.job`; status files contain only
|
|
26
26
|
state and metadata. Permission checks still apply to background work.
|
|
27
27
|
|
|
28
|
+
## HTTP requests
|
|
29
|
+
|
|
30
|
+
- `fs.http_request` supports `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, and `HEAD`
|
|
31
|
+
over `http:`/`https:` only; other schemes fail with `unsupported`.
|
|
32
|
+
- Requests are allowed by default. The permission resource is the request host,
|
|
33
|
+
and every redirect hop re-asserts `fs_http_request` for the new host.
|
|
34
|
+
- Redirects are followed manually: 301/302 rewrite `POST` to `GET`, 303 always
|
|
35
|
+
does, and the hop count is bounded by `maxRedirects`.
|
|
36
|
+
- `output` streams the response to a temporary file in the target directory and
|
|
37
|
+
renames it only after the body and checksum are complete.
|
|
38
|
+
- `checksum` accepts `<md5|sha1|sha256|sha512>:<hex>`; a bare digest means
|
|
39
|
+
SHA-256. Mismatches fail with `checksum` and leave no partial file.
|
|
40
|
+
- `maxBytes` is enforced while reading, for buffered and downloaded bodies.
|
|
41
|
+
- Pipe use is a buffered source; whole bodies pass between stages.
|
|
42
|
+
|
|
28
43
|
## Deliberate gaps
|
|
29
44
|
|
|
30
45
|
These are not implemented:
|
|
@@ -38,6 +53,9 @@ These are not implemented:
|
|
|
38
53
|
- unbounded `tail -f`; use bounded `follow` or the wait plugin
|
|
39
54
|
- archive extraction from arbitrary streams; create accepts text/stdin stream input
|
|
40
55
|
- cross-filesystem `trash`; use `rm` or a mount-trash helper
|
|
56
|
+
- curl protocols beyond HTTP(S), cookie jars, client certificates, proxies,
|
|
57
|
+
multipart uploads, and resumable/range downloads
|
|
58
|
+
- true streaming through pipe stages; `http_request` buffers unless `output` is set
|
|
41
59
|
|
|
42
60
|
## Format details
|
|
43
61
|
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-fs-plugin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.1",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "OpenCode 2 plugin: Linux-style filesystem and
|
|
5
|
+
"description": "OpenCode 2 plugin: Linux-style filesystem, text, and HTTP(S) tools under the fs namespace.",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
8
8
|
"url": "git+https://github.com/masterjg/opencode-fs-plugin.git"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: Filesystem
|
|
3
|
-
description: Use when a task needs Linux-style filesystem or
|
|
3
|
+
description: Use when a task needs Linux-style filesystem, text, or network operations beyond OpenCode's built-ins - copy, move, metadata, touch, truncate, symlinks, chmod, hashes, disk usage, find, archives, diff, HTTP(S) requests, API calls, or file downloads (curl replacement), trash, background jobs, or composing filters through a pipe. Covers the fs namespace, argument shapes, native options, permissions, limits, and verification.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Filesystem
|
|
@@ -24,6 +24,7 @@ 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` |
|
|
27
28
|
| Batching or loops | `execute` JS loops over `tools.fs.*` |
|
|
28
29
|
|
|
29
30
|
Do not duplicate a built-in when it already covers the job. `fs` exists for the
|
|
@@ -50,6 +51,7 @@ what `fs.stat`, `fs.ls`, `fs.hash`, `fs.diff`, or `fs.cat` can confirm.
|
|
|
50
51
|
| Temp and trash | `fs.mktemp`, `fs.trash` |
|
|
51
52
|
| Text filters | `fs.cat`, `fs.head`, `fs.tail`, `fs.grep`, `fs.sed`, `fs.sort`, `fs.uniq`, `fs.cut`, `fs.tr`, `fs.wc`, `fs.tee` |
|
|
52
53
|
| Compose filters | `fs.pipe` |
|
|
54
|
+
| HTTP(S) | `fs.http_request` (`output`, `checksum`, `maxBytes`, `json`) |
|
|
53
55
|
| Background jobs | `background: true`, then `fs.job` |
|
|
54
56
|
|
|
55
57
|
Recent parity additions:
|
|
@@ -77,6 +79,7 @@ Use the exact field names; scalar `path` is only valid for `fs.mkdir`.
|
|
|
77
79
|
| `archive` + `paths` | `fs.tar` create, `fs.zip` create |
|
|
78
80
|
| `archive` + `mode` | `fs.tar` (`create`/`extract`/`list`), `fs.unzip` (`extract`/`list`) |
|
|
79
81
|
| `content` | `fs.tee` when there is no stdin |
|
|
82
|
+
| `url` + optional `output` | `fs.http_request` |
|
|
80
83
|
| `stages` + optional `input`/`output` | `fs.pipe` |
|
|
81
84
|
|
|
82
85
|
## Pipe
|
|
@@ -100,6 +103,18 @@ native names (`cat`, `grep`, `sort`), not `fs.cat`. There is no shell,
|
|
|
100
103
|
redirection operator, nested pipe, or `find -exec`. A filter stage needs
|
|
101
104
|
`input` or a preceding source stage.
|
|
102
105
|
|
|
106
|
+
`http_request` is a source stage. Pipe stages exchange whole buffers, so set
|
|
107
|
+
`maxBytes` for large responses; use `output` for real streaming to disk.
|
|
108
|
+
|
|
109
|
+
```js
|
|
110
|
+
await tools.fs.pipe({
|
|
111
|
+
stages: [
|
|
112
|
+
{ tool: "http_request", args: { url: "https://example.com/app.log", maxBytes: 8_000_000 } },
|
|
113
|
+
{ tool: "grep", args: { pattern: "ERROR" } },
|
|
114
|
+
],
|
|
115
|
+
})
|
|
116
|
+
```
|
|
117
|
+
|
|
103
118
|
## Background jobs
|
|
104
119
|
|
|
105
120
|
Every tool accepts `background: true`. It returns immediately with a job id and
|
|
@@ -216,6 +231,16 @@ await tools.fs.unzip({ archive: "bundle.zip", mode: "list" })
|
|
|
216
231
|
|
|
217
232
|
// compare two files
|
|
218
233
|
await tools.fs.diff({ left: "old.txt", right: "new.txt", unified: 3 })
|
|
234
|
+
|
|
235
|
+
// API call, then a verified download
|
|
236
|
+
await tools.fs.http_request({ url: "https://api.github.com/repos/owner/repo/releases/latest" })
|
|
237
|
+
await tools.fs.http_request({
|
|
238
|
+
url: "https://example.com/tool-1.0.0.tgz",
|
|
239
|
+
output: "tool-1.0.0.tgz",
|
|
240
|
+
checksum: "sha256:<hex>",
|
|
241
|
+
maxBytes: 50_000_000,
|
|
242
|
+
background: true,
|
|
243
|
+
})
|
|
219
244
|
```
|
|
220
245
|
|
|
221
246
|
## Limits
|
|
@@ -225,9 +250,11 @@ await tools.fs.diff({ left: "old.txt", right: "new.txt", unified: 3 })
|
|
|
225
250
|
`i` and `p`. It is not a full sed interpreter.
|
|
226
251
|
- `fs.find` has no `-exec`; use `fs.rm`/`fs.trash` separately.
|
|
227
252
|
- No `xz`, `zstd`, `7z`, `chown`, `chattr`, `dd`, or `rsync`.
|
|
228
|
-
- `fs.tail` has
|
|
253
|
+
- `fs.tail` has bounded `follow` only; unbounded `tail -f` is not supported.
|
|
229
254
|
- `cp -a` preserves mode and timestamps but not ACLs or xattrs.
|
|
230
|
-
- `fs.tar`/`fs.zip`
|
|
255
|
+
- `fs.tar`/`fs.zip` create from `input` or stdin; extraction is file-backed.
|
|
256
|
+
- `fs.http_request` is HTTP(S) only: no FTP/SFTP, cookie jars, client
|
|
257
|
+
certificates, proxies, multipart uploads, or resumable downloads.
|
|
231
258
|
- `fs.tar` resolves `paths` even when `directory` is set; pass absolute sources
|
|
232
259
|
with `directory` or the member path may not be found.
|
|
233
260
|
- `fs.du` reports allocated blocks like `du`; use `fs.stat` with `%s` for
|
|
@@ -256,6 +283,11 @@ Command actions are `fs_<command>` (for example `fs_cp`). `fs_*` wildcards work
|
|
|
256
283
|
in agent rules. `fs.pipe` asserts each stage's action; a denied stage cannot be
|
|
257
284
|
hidden inside a pipeline. Do not work around a denied tool with shell.
|
|
258
285
|
|
|
286
|
+
`fs_http_request` is allowed by default, like `fetch`. Its resource is the
|
|
287
|
+
request host; rules can allow one host and ask or deny the rest. Each redirect
|
|
288
|
+
hop is checked against the new host. Nothing blocks localhost or private
|
|
289
|
+
addresses by default.
|
|
290
|
+
|
|
259
291
|
## Errors and output
|
|
260
292
|
|
|
261
293
|
- `ERROR: ...` is a recoverable tool failure; `BLOCKED: ...` is a sandbox hard
|
package/src/index.ts
CHANGED
|
@@ -26,6 +26,7 @@ import { grepTool } from "./tools/grep.js";
|
|
|
26
26
|
import { gunzipTool, gzipTool } from "./tools/gzip.js";
|
|
27
27
|
import { hashTool } from "./tools/hash.js";
|
|
28
28
|
import { headTool } from "./tools/head.js";
|
|
29
|
+
import { httpRequestTool } from "./tools/http_request.js";
|
|
29
30
|
import { lnTool } from "./tools/ln.js";
|
|
30
31
|
import { lsTool } from "./tools/ls.js";
|
|
31
32
|
import { mkdirTool } from "./tools/mkdir.js";
|
|
@@ -80,6 +81,7 @@ const TOOLS: readonly AnyTool[] = [
|
|
|
80
81
|
headTool,
|
|
81
82
|
tailTool,
|
|
82
83
|
teeTool,
|
|
84
|
+
httpRequestTool,
|
|
83
85
|
wcTool,
|
|
84
86
|
sortTool,
|
|
85
87
|
uniqTool,
|
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as crypto from "node:crypto";
|
|
7
|
+
import * as fs from "node:fs/promises";
|
|
8
|
+
import * as path from "node:path";
|
|
9
|
+
import { Readable } from "node:stream";
|
|
10
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
11
|
+
import { errorMessage, FsError, fromErrno } from "../core/errors.js";
|
|
12
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
13
|
+
|
|
14
|
+
const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"] as const;
|
|
15
|
+
|
|
16
|
+
const Schema = Type.Object(
|
|
17
|
+
{
|
|
18
|
+
url: Type.String({ minLength: 1, description: "Absolute http:// or https:// URL." }),
|
|
19
|
+
method: Type.Optional(
|
|
20
|
+
Type.Union(
|
|
21
|
+
METHODS.map((method) => Type.Literal(method)),
|
|
22
|
+
{ description: "HTTP method. Default: GET." },
|
|
23
|
+
),
|
|
24
|
+
),
|
|
25
|
+
headers: Type.Optional(
|
|
26
|
+
Type.Record(Type.String(), Type.String(), { description: "Request headers." }),
|
|
27
|
+
),
|
|
28
|
+
body: Type.Optional(Type.String({ description: "Raw request body text." })),
|
|
29
|
+
json: Type.Optional(
|
|
30
|
+
Type.Unknown({ description: "JSON request body; sets content-type: application/json." }),
|
|
31
|
+
),
|
|
32
|
+
output: Type.Optional(
|
|
33
|
+
Type.String({ description: "Download the response body here, streamed to a temp file then renamed." }),
|
|
34
|
+
),
|
|
35
|
+
checksum: Type.Optional(
|
|
36
|
+
Type.String({
|
|
37
|
+
description: "Expected checksum as `<md5|sha1|sha256|sha512>:<hex>`; bare hex means sha256.",
|
|
38
|
+
}),
|
|
39
|
+
),
|
|
40
|
+
maxBytes: Type.Optional(
|
|
41
|
+
Type.Integer({ minimum: 1, description: "Maximum response body bytes. Default: unlimited." }),
|
|
42
|
+
),
|
|
43
|
+
timeoutMs: Type.Optional(
|
|
44
|
+
Type.Integer({ minimum: 100, maximum: 600_000, description: "Total request timeout. Default: 30000." }),
|
|
45
|
+
),
|
|
46
|
+
failOnError: Type.Optional(
|
|
47
|
+
Type.Boolean({ description: "Treat HTTP 4xx/5xx as an error. Default: true." }),
|
|
48
|
+
),
|
|
49
|
+
followRedirects: Type.Optional(
|
|
50
|
+
Type.Boolean({ description: "Follow 3xx redirects. Default: true." }),
|
|
51
|
+
),
|
|
52
|
+
maxRedirects: Type.Optional(
|
|
53
|
+
Type.Integer({ minimum: 0, maximum: 20, description: "Maximum redirects. Default: 10." }),
|
|
54
|
+
),
|
|
55
|
+
},
|
|
56
|
+
{ additionalProperties: false },
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
type Input = Static<typeof Schema>;
|
|
60
|
+
|
|
61
|
+
type Algorithm = "md5" | "sha1" | "sha256" | "sha512";
|
|
62
|
+
|
|
63
|
+
interface Checksum {
|
|
64
|
+
algorithm: Algorithm;
|
|
65
|
+
digest: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const httpRequestTool: ToolSpec<Input> = {
|
|
69
|
+
name: "http_request",
|
|
70
|
+
description:
|
|
71
|
+
"Make an HTTP(S) request and either return the body or stream it to a file (`output`). " +
|
|
72
|
+
"Supports methods, headers, a text or JSON body, redirects, timeouts, `maxBytes`, and " +
|
|
73
|
+
"`checksum` verification. Usable as a `pipe` source.",
|
|
74
|
+
schema: Schema,
|
|
75
|
+
pipeable: "source",
|
|
76
|
+
mutates: true,
|
|
77
|
+
async run(ctx, input) {
|
|
78
|
+
const url = parseUrl(input.url);
|
|
79
|
+
if (input.body !== undefined && input.json !== undefined) {
|
|
80
|
+
throw new FsError("body and json are mutually exclusive.", "invalid");
|
|
81
|
+
}
|
|
82
|
+
const method = input.method ?? "GET";
|
|
83
|
+
if ((input.body !== undefined || input.json !== undefined) && (method === "GET" || method === "HEAD")) {
|
|
84
|
+
throw new FsError(`${method} does not accept a request body.`, "invalid");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const headers: Record<string, string> = { ...(input.headers ?? {}) };
|
|
88
|
+
let body: string | undefined = input.body;
|
|
89
|
+
if (input.json !== undefined) {
|
|
90
|
+
body = JSON.stringify(input.json);
|
|
91
|
+
const hasContentType = Object.keys(headers).some((key) => key.toLowerCase() === "content-type");
|
|
92
|
+
if (!hasContentType) headers["content-type"] = "application/json";
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const timeoutMs = input.timeoutMs ?? 30_000;
|
|
96
|
+
const controller = new AbortController();
|
|
97
|
+
let timedOut = false;
|
|
98
|
+
const timer = setTimeout(() => {
|
|
99
|
+
timedOut = true;
|
|
100
|
+
controller.abort();
|
|
101
|
+
}, timeoutMs);
|
|
102
|
+
const forwardAbort = () => controller.abort();
|
|
103
|
+
ctx.signal.addEventListener("abort", forwardAbort, { once: true });
|
|
104
|
+
const mapError = (error: unknown): FsError => {
|
|
105
|
+
if (error instanceof FsError) return error;
|
|
106
|
+
if (controller.signal.aborted) {
|
|
107
|
+
return new FsError(
|
|
108
|
+
timedOut ? `HTTP request timed out after ${timeoutMs} ms.` : "HTTP request aborted.",
|
|
109
|
+
"interrupted",
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
return new FsError(`HTTP request failed: ${errorMessage(error)}`, "io");
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
try {
|
|
116
|
+
if (ctx.signal.aborted) throw new FsError("HTTP request aborted.", "interrupted");
|
|
117
|
+
|
|
118
|
+
const { response, finalUrl } = await request(ctx, url, {
|
|
119
|
+
method,
|
|
120
|
+
headers,
|
|
121
|
+
...(body === undefined ? {} : { body }),
|
|
122
|
+
followRedirects: input.followRedirects !== false,
|
|
123
|
+
maxRedirects: input.maxRedirects ?? 10,
|
|
124
|
+
signal: controller.signal,
|
|
125
|
+
mapError,
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const status = response.status;
|
|
129
|
+
const manualRedirect =
|
|
130
|
+
input.followRedirects === false && status >= 300 && status < 400;
|
|
131
|
+
if (!response.ok && !manualRedirect && input.failOnError !== false) {
|
|
132
|
+
const snippet = await readSnippet(response, 4096, mapError);
|
|
133
|
+
const base = [`HTTP ${status}`, response.statusText, `for ${finalUrl}`].join(" ");
|
|
134
|
+
throw new FsError(snippet.length > 0 ? `${base}: ${snippet}` : base, "io");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const checksum = input.checksum === undefined ? undefined : parseChecksum(input.checksum);
|
|
138
|
+
const metadata = {
|
|
139
|
+
url: finalUrl,
|
|
140
|
+
status,
|
|
141
|
+
statusText: response.statusText,
|
|
142
|
+
headers: Object.fromEntries(response.headers.entries()),
|
|
143
|
+
method,
|
|
144
|
+
output: input.output ?? null,
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
if (input.output !== undefined) {
|
|
148
|
+
const target = await ctx.sandbox.resolveForCreate(input.output);
|
|
149
|
+
await ctx.permission.assert([{ target, boundary: target.full }]);
|
|
150
|
+
const downloaded = await download(target.full, response, input.maxBytes, checksum, mapError);
|
|
151
|
+
return textResult(
|
|
152
|
+
`Downloaded ${downloaded.bytes} bytes to ${input.output}\n`,
|
|
153
|
+
{
|
|
154
|
+
...metadata,
|
|
155
|
+
bytes: downloaded.bytes,
|
|
156
|
+
sha256: downloaded.sha256,
|
|
157
|
+
checksum: downloaded.checksum,
|
|
158
|
+
},
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const collected = await collectBody(response, input.maxBytes, checksum, mapError);
|
|
163
|
+
return {
|
|
164
|
+
stdout: collected.body,
|
|
165
|
+
exitCode: 0,
|
|
166
|
+
metadata: {
|
|
167
|
+
...metadata,
|
|
168
|
+
bytes: collected.body.length,
|
|
169
|
+
sha256: collected.sha256,
|
|
170
|
+
checksum: collected.checksum,
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
} catch (error) {
|
|
174
|
+
throw mapError(error);
|
|
175
|
+
} finally {
|
|
176
|
+
clearTimeout(timer);
|
|
177
|
+
ctx.signal.removeEventListener("abort", forwardAbort);
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
interface RequestOptions {
|
|
183
|
+
method: string;
|
|
184
|
+
headers: Record<string, string>;
|
|
185
|
+
body?: string;
|
|
186
|
+
followRedirects: boolean;
|
|
187
|
+
maxRedirects: number;
|
|
188
|
+
signal: AbortSignal;
|
|
189
|
+
mapError: (error: unknown) => FsError;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function request(
|
|
193
|
+
ctx: Parameters<ToolSpec<Input>["run"]>[0],
|
|
194
|
+
url: URL,
|
|
195
|
+
options: RequestOptions,
|
|
196
|
+
): Promise<{ response: Response; finalUrl: string }> {
|
|
197
|
+
const gate = ctx.permissionFor("fs_http_request");
|
|
198
|
+
let current = url;
|
|
199
|
+
let method = options.method;
|
|
200
|
+
let body = options.body;
|
|
201
|
+
|
|
202
|
+
for (let redirects = 0; ; redirects++) {
|
|
203
|
+
await gate.assertTrusted([current.host]);
|
|
204
|
+
const response = await fetch(current, {
|
|
205
|
+
method,
|
|
206
|
+
headers: options.headers,
|
|
207
|
+
redirect: "manual",
|
|
208
|
+
signal: options.signal,
|
|
209
|
+
...(body === undefined ? {} : { body }),
|
|
210
|
+
}).catch((error: unknown) => {
|
|
211
|
+
throw options.mapError(error);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
if (!options.followRedirects) return { response, finalUrl: current.toString() };
|
|
215
|
+
const location = response.headers.get("location");
|
|
216
|
+
if (response.status < 300 || response.status >= 400 || location === null) {
|
|
217
|
+
return { response, finalUrl: current.toString() };
|
|
218
|
+
}
|
|
219
|
+
if (redirects >= options.maxRedirects) {
|
|
220
|
+
/* v8 ignore next -- a 3xx response always carries a body stream */
|
|
221
|
+
await response.body?.cancel().catch(() => undefined);
|
|
222
|
+
throw new FsError(`Too many redirects (max ${options.maxRedirects}).`, "io");
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/* v8 ignore next -- a 3xx response always carries a body stream */
|
|
226
|
+
await response.body?.cancel().catch(() => undefined);
|
|
227
|
+
let next: URL;
|
|
228
|
+
try {
|
|
229
|
+
next = parseUrl(new URL(location, current).toString());
|
|
230
|
+
} catch (error) {
|
|
231
|
+
throw options.mapError(error);
|
|
232
|
+
}
|
|
233
|
+
current = next;
|
|
234
|
+
if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === "POST")) {
|
|
235
|
+
method = "GET";
|
|
236
|
+
body = undefined;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
interface Collected {
|
|
242
|
+
body: Buffer;
|
|
243
|
+
sha256: string;
|
|
244
|
+
checksum: string | undefined;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
interface Downloaded extends Collected {
|
|
248
|
+
bytes: number;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function collectBody(
|
|
252
|
+
response: Response,
|
|
253
|
+
maxBytes: number | undefined,
|
|
254
|
+
checksum: Checksum | undefined,
|
|
255
|
+
mapError: (error: unknown) => FsError,
|
|
256
|
+
): Promise<Collected> {
|
|
257
|
+
const chunks: Buffer[] = [];
|
|
258
|
+
let total = 0;
|
|
259
|
+
const hashers = makeHashers(checksum);
|
|
260
|
+
for await (const chunk of bodyChunks(response, mapError)) {
|
|
261
|
+
total += chunk.length;
|
|
262
|
+
if (maxBytes !== undefined && total > maxBytes) {
|
|
263
|
+
throw new FsError(`Response exceeded maxBytes (${maxBytes}).`, "invalid");
|
|
264
|
+
}
|
|
265
|
+
hashers.update(chunk);
|
|
266
|
+
chunks.push(chunk);
|
|
267
|
+
}
|
|
268
|
+
return { body: Buffer.concat(chunks), ...hashers.digests() };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async function download(
|
|
272
|
+
full: string,
|
|
273
|
+
response: Response,
|
|
274
|
+
maxBytes: number | undefined,
|
|
275
|
+
checksum: Checksum | undefined,
|
|
276
|
+
mapError: (error: unknown) => FsError,
|
|
277
|
+
): Promise<Downloaded> {
|
|
278
|
+
const directory = path.dirname(full);
|
|
279
|
+
const temp = path.join(
|
|
280
|
+
directory,
|
|
281
|
+
`.${path.basename(full)}.${crypto.randomBytes(6).toString("hex")}.part`,
|
|
282
|
+
);
|
|
283
|
+
let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
|
|
284
|
+
let bytes = 0;
|
|
285
|
+
const hashers = makeHashers(checksum);
|
|
286
|
+
try {
|
|
287
|
+
handle = await fs.open(temp, "wx");
|
|
288
|
+
for await (const chunk of bodyChunks(response, mapError)) {
|
|
289
|
+
bytes += chunk.length;
|
|
290
|
+
if (maxBytes !== undefined && bytes > maxBytes) {
|
|
291
|
+
throw new FsError(`Response exceeded maxBytes (${maxBytes}).`, "invalid");
|
|
292
|
+
}
|
|
293
|
+
hashers.update(chunk);
|
|
294
|
+
await handle.write(chunk);
|
|
295
|
+
}
|
|
296
|
+
await handle.close();
|
|
297
|
+
handle = undefined;
|
|
298
|
+
const digests = hashers.digests();
|
|
299
|
+
await fs.rename(temp, full);
|
|
300
|
+
return { body: Buffer.alloc(0), bytes, ...digests };
|
|
301
|
+
} catch (error) {
|
|
302
|
+
/* v8 ignore next -- cleanup failures must not mask the original error */
|
|
303
|
+
await handle?.close().catch(() => undefined);
|
|
304
|
+
/* v8 ignore next -- cleanup failures must not mask the original error */
|
|
305
|
+
await fs.rm(temp, { force: true }).catch(() => undefined);
|
|
306
|
+
if (error instanceof FsError) throw error;
|
|
307
|
+
throw fromErrno(error);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function makeHashers(checksum: Checksum | undefined): {
|
|
312
|
+
update: (chunk: Buffer) => void;
|
|
313
|
+
digests: () => { sha256: string; checksum: string | undefined };
|
|
314
|
+
} {
|
|
315
|
+
const sha256 = crypto.createHash("sha256");
|
|
316
|
+
const other =
|
|
317
|
+
checksum === undefined || checksum.algorithm === "sha256"
|
|
318
|
+
? undefined
|
|
319
|
+
: crypto.createHash(checksum.algorithm);
|
|
320
|
+
return {
|
|
321
|
+
update(chunk) {
|
|
322
|
+
sha256.update(chunk);
|
|
323
|
+
other?.update(chunk);
|
|
324
|
+
},
|
|
325
|
+
digests() {
|
|
326
|
+
const sha256Hex = sha256.digest("hex");
|
|
327
|
+
const actual = checksum === undefined ? undefined : other === undefined ? sha256Hex : other.digest("hex");
|
|
328
|
+
if (checksum !== undefined && actual !== checksum.digest) {
|
|
329
|
+
throw new FsError(
|
|
330
|
+
`Checksum mismatch: expected ${checksum.algorithm}:${checksum.digest}, got ${checksum.algorithm}:${actual}.`,
|
|
331
|
+
"checksum",
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
return { sha256: sha256Hex, checksum: actual };
|
|
335
|
+
},
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async function* bodyChunks(
|
|
340
|
+
response: Response,
|
|
341
|
+
mapError: (error: unknown) => FsError,
|
|
342
|
+
): AsyncGenerator<Buffer> {
|
|
343
|
+
if (response.body === null) return;
|
|
344
|
+
const stream = Readable.fromWeb(response.body as never);
|
|
345
|
+
try {
|
|
346
|
+
for await (const chunk of stream) {
|
|
347
|
+
/* v8 ignore next -- Readable.fromWeb yields Buffers */
|
|
348
|
+
yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
|
|
349
|
+
}
|
|
350
|
+
} catch (error) {
|
|
351
|
+
throw mapError(error);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function readSnippet(
|
|
356
|
+
response: Response,
|
|
357
|
+
limit: number,
|
|
358
|
+
mapError: (error: unknown) => FsError,
|
|
359
|
+
): Promise<string> {
|
|
360
|
+
const chunks: Buffer[] = [];
|
|
361
|
+
let total = 0;
|
|
362
|
+
for await (const chunk of bodyChunks(response, mapError)) {
|
|
363
|
+
chunks.push(chunk);
|
|
364
|
+
total += chunk.length;
|
|
365
|
+
if (total >= limit) break;
|
|
366
|
+
}
|
|
367
|
+
return Buffer.concat(chunks).subarray(0, limit).toString("utf8").trim();
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function parseUrl(value: string): URL {
|
|
371
|
+
let url: URL;
|
|
372
|
+
try {
|
|
373
|
+
url = new URL(value);
|
|
374
|
+
} catch {
|
|
375
|
+
throw new FsError(`Invalid URL: "${value}".`, "invalid");
|
|
376
|
+
}
|
|
377
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
378
|
+
throw new FsError(`Unsupported URL scheme "${url.protocol}" (only http and https).`, "unsupported");
|
|
379
|
+
}
|
|
380
|
+
return url;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function parseChecksum(value: string): Checksum {
|
|
384
|
+
const match = /^(?:(md5|sha1|sha256|sha512):)?([0-9a-fA-F]+)$/.exec(value.trim());
|
|
385
|
+
if (match === null) {
|
|
386
|
+
throw new FsError(`Invalid checksum: "${value}" (use <algorithm>:<hex>).`, "invalid");
|
|
387
|
+
}
|
|
388
|
+
return {
|
|
389
|
+
algorithm: (match[1] ?? "sha256") as Algorithm,
|
|
390
|
+
digest: (match[2] as string).toLowerCase(),
|
|
391
|
+
};
|
|
392
|
+
}
|
package/src/tools/pipe.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { grepTool } from "./grep.js";
|
|
|
14
14
|
import { gunzipTool, gzipTool } from "./gzip.js";
|
|
15
15
|
import { hashTool } from "./hash.js";
|
|
16
16
|
import { headTool } from "./head.js";
|
|
17
|
+
import { httpRequestTool } from "./http_request.js";
|
|
17
18
|
import { sedTool } from "./sed.js";
|
|
18
19
|
import { sortTool } from "./sort.js";
|
|
19
20
|
import { tailTool } from "./tail.js";
|
|
@@ -49,6 +50,7 @@ const REGISTRY: ReadonlyMap<string, AnyTool> = new Map(
|
|
|
49
50
|
[
|
|
50
51
|
catTool, headTool, tailTool, grepTool, sedTool, sortTool, uniqTool, cutTool,
|
|
51
52
|
trTool, wcTool, teeTool, hashTool, gzipTool, gunzipTool, tarTool, zipTool,
|
|
53
|
+
httpRequestTool,
|
|
52
54
|
].map((tool) => [tool.name, tool]),
|
|
53
55
|
);
|
|
54
56
|
|