opencode-fs-plugin 1.0.2 → 1.1.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 +66 -9
- package/SPEC.md +11 -0
- package/package.json +1 -1
- package/skills/filesystem/SKILL.md +70 -6
- package/src/core/errors.ts +1 -0
- package/src/core/jobs.ts +217 -0
- package/src/index.ts +163 -17
- package/src/tools/du.ts +5 -7
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.1.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.1.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.1.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.1.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.1.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.1.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.1.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.1.1 with "npm install opencode-fs-plugin@1.1.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.1.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
|
@@ -66,24 +66,79 @@ await tools.fs.pipe({
|
|
|
66
66
|
|
|
67
67
|
There is no shell, redirection operator, nested pipe, or `find -exec`.
|
|
68
68
|
|
|
69
|
+
## Background jobs
|
|
70
|
+
|
|
71
|
+
Every `fs.*` tool accepts `background: true`. The call returns immediately with
|
|
72
|
+
a job id and a status-file path:
|
|
73
|
+
|
|
74
|
+
```js
|
|
75
|
+
const started = JSON.parse(
|
|
76
|
+
await tools.fs.cp({
|
|
77
|
+
sources: ["large-tree"],
|
|
78
|
+
destination: "backup",
|
|
79
|
+
recursive: true,
|
|
80
|
+
background: true,
|
|
81
|
+
}),
|
|
82
|
+
)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Wait for it with `fs.job`, or let the agent continue and check later:
|
|
86
|
+
|
|
87
|
+
```js
|
|
88
|
+
const result = await tools.fs.job({
|
|
89
|
+
id: started.jobId,
|
|
90
|
+
wait: true,
|
|
91
|
+
timeoutMs: 600000,
|
|
92
|
+
})
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`fs.job` also supports `status`, `cancel`, and `list`:
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
await tools.fs.job({ id: started.jobId }) // current status
|
|
99
|
+
await tools.fs.job({ id: started.jobId, cancel: true }) // abort
|
|
100
|
+
await tools.fs.job({ list: true }) // newest first
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The status file lets the `wait` plugin observe a job without coupling the two
|
|
104
|
+
plugins:
|
|
105
|
+
|
|
106
|
+
```js
|
|
107
|
+
await tools.wait.for({
|
|
108
|
+
condition: {
|
|
109
|
+
type: "file_contains",
|
|
110
|
+
path: started.statusPath,
|
|
111
|
+
pattern: '"state":"completed"',
|
|
112
|
+
},
|
|
113
|
+
timeoutMs: 600000,
|
|
114
|
+
})
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Jobs are process-local: they are lost on an OpenCode server restart, and their
|
|
118
|
+
status files may remain under `/tmp/opencode/fs-jobs/<server-pid>/`. The manager
|
|
119
|
+
allows 8 concurrent jobs and cleans up finished jobs after one hour. Results
|
|
120
|
+
stay in memory and are returned by `fs.job`; the status file contains only the
|
|
121
|
+
job state and metadata. Background permission prompts can appear after the
|
|
122
|
+
starting call returns, and a denied permission fails the job.
|
|
123
|
+
|
|
69
124
|
## Installing from npm
|
|
70
125
|
|
|
71
126
|
Add the registry package directly to the plugin list:
|
|
72
127
|
|
|
73
128
|
```jsonc
|
|
74
129
|
{
|
|
75
|
-
"plugins": ["opencode-fs-plugin@1.
|
|
130
|
+
"plugins": ["opencode-fs-plugin@1.1.1"]
|
|
76
131
|
}
|
|
77
132
|
```
|
|
78
133
|
|
|
79
|
-
`opencode plugin add opencode-fs-plugin@1.
|
|
134
|
+
`opencode plugin add opencode-fs-plugin@1.1.1` installs it and writes the config
|
|
80
135
|
entry. A bare `opencode-fs-plugin` follows the `latest` tag.
|
|
81
136
|
|
|
82
137
|
OpenCode manages the package under its cache, so the path is not stable. If you
|
|
83
138
|
also want the packaged skill, install it into a project instead:
|
|
84
139
|
|
|
85
140
|
```bash
|
|
86
|
-
npm install opencode-fs-plugin@1.
|
|
141
|
+
npm install opencode-fs-plugin@1.1.1
|
|
87
142
|
```
|
|
88
143
|
|
|
89
144
|
```jsonc
|
|
@@ -98,7 +153,7 @@ npm install opencode-fs-plugin@1.0.2
|
|
|
98
153
|
Download the release tarball, then install it as a normal npm package:
|
|
99
154
|
|
|
100
155
|
```bash
|
|
101
|
-
VERSION=1.
|
|
156
|
+
VERSION=1.1.1
|
|
102
157
|
curl -L -o "opencode-fs-plugin-${VERSION}.tgz" \
|
|
103
158
|
"https://github.com/masterjg/opencode-fs-plugin/releases/download/v${VERSION}/opencode-fs-plugin-${VERSION}.tgz"
|
|
104
159
|
npm install "./opencode-fs-plugin-${VERSION}.tgz"
|
|
@@ -127,20 +182,20 @@ OpenCode installs it from Git:
|
|
|
127
182
|
|
|
128
183
|
```jsonc
|
|
129
184
|
{
|
|
130
|
-
"plugins": ["github:masterjg/opencode-fs-plugin#v1.
|
|
185
|
+
"plugins": ["github:masterjg/opencode-fs-plugin#v1.1.1"]
|
|
131
186
|
}
|
|
132
187
|
```
|
|
133
188
|
|
|
134
|
-
`opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.
|
|
189
|
+
`opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.1.1'` installs the
|
|
135
190
|
same spec and writes the config entry. The equivalent full URL is
|
|
136
|
-
`git+https://github.com/masterjg/opencode-fs-plugin.git#v1.
|
|
191
|
+
`git+https://github.com/masterjg/opencode-fs-plugin.git#v1.1.1`. A tag is
|
|
137
192
|
checked for updates; use a full commit hash to pin it.
|
|
138
193
|
|
|
139
194
|
Git plugins are installed under OpenCode's cache, so their package path is not
|
|
140
195
|
stable. If you also want the packaged skill, install with npm instead:
|
|
141
196
|
|
|
142
197
|
```bash
|
|
143
|
-
npm install "github:masterjg/opencode-fs-plugin#v1.
|
|
198
|
+
npm install "github:masterjg/opencode-fs-plugin#v1.1.1"
|
|
144
199
|
```
|
|
145
200
|
|
|
146
201
|
Then use `./node_modules/opencode-fs-plugin` in `plugins` and
|
|
@@ -260,7 +315,9 @@ new release; an unchanged version is skipped with a notice.
|
|
|
260
315
|
|
|
261
316
|
The npm step uses trusted publishing (OIDC); no npm token is stored. The
|
|
262
317
|
package's trusted publisher must authorize workflow `release.yml` in
|
|
263
|
-
`masterjg/opencode-fs-plugin`.
|
|
318
|
+
`masterjg/opencode-fs-plugin`. Keep **Allow npm publish** enabled on that
|
|
319
|
+
connection: the workflow uses `npm publish`, not `npm stage publish`, so
|
|
320
|
+
releases publish directly without per-version approval.
|
|
264
321
|
|
|
265
322
|
## License
|
|
266
323
|
|
package/SPEC.md
CHANGED
|
@@ -14,6 +14,17 @@ the `fs` namespace (`tools.fs.cp`, direct `fs_cp`).
|
|
|
14
14
|
- Unsupported options fail with `unsupported` rather than being ignored.
|
|
15
15
|
- No tool invokes a shell or `child_process`.
|
|
16
16
|
|
|
17
|
+
## Background jobs
|
|
18
|
+
|
|
19
|
+
- Every tool accepts `background: true`; it returns a job id and an atomic
|
|
20
|
+
status-file path instead of waiting.
|
|
21
|
+
- `fs.job` exposes `status`, `wait`, `cancel`, and `list`.
|
|
22
|
+
- Jobs are process-local and are lost on server restart. Status files live under
|
|
23
|
+
`/tmp/opencode/fs-jobs/<server-pid>/`; finished jobs are cleaned after one hour.
|
|
24
|
+
- At most eight jobs run concurrently. Excess starts fail with `busy`.
|
|
25
|
+
- Results stay in memory and are returned by `fs.job`; status files contain only
|
|
26
|
+
state and metadata. Permission checks still apply to background work.
|
|
27
|
+
|
|
17
28
|
## Deliberate gaps
|
|
18
29
|
|
|
19
30
|
These are not implemented:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: Filesystem
|
|
3
|
-
description: Use when a task needs Linux-style filesystem or text operations beyond OpenCode's built-ins - copy, move, metadata, touch, truncate, symlinks, chmod, hashes, disk usage, find, archives, diff, trash, or composing filters through a pipe. Covers the fs namespace, argument shapes, native options, permissions, limits, and verification.
|
|
3
|
+
description: Use when a task needs Linux-style filesystem or text operations beyond OpenCode's built-ins - copy, move, metadata, touch, truncate, symlinks, chmod, hashes, disk usage, find, archives, diff, 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
|
|
@@ -28,6 +28,10 @@ With `execute` allowed, call it as `tools.fs.<command>`; agents without
|
|
|
28
28
|
Do not duplicate a built-in when it already covers the job. `fs` exists for the
|
|
29
29
|
operations the built-ins do not cover, and for composable text/archive work.
|
|
30
30
|
|
|
31
|
+
Use the `fs` tool for both the operation and its verification. Do not route an
|
|
32
|
+
`fs` operation through a shell or `toolbox.run`, and do not use shell to check
|
|
33
|
+
what `fs.stat`, `fs.ls`, `fs.hash`, `fs.diff`, or `fs.cat` can confirm.
|
|
34
|
+
|
|
31
35
|
## Command map
|
|
32
36
|
|
|
33
37
|
| Need | Command |
|
|
@@ -40,11 +44,12 @@ operations the built-ins do not cover, and for composable text/archive work.
|
|
|
40
44
|
| Links and modes | `fs.ln`, `fs.readlink`, `fs.chmod` |
|
|
41
45
|
| Hash, usage | `fs.hash`, `fs.du`, `fs.df` |
|
|
42
46
|
| Predicate search | `fs.find` (`name`, `type`, `size`, `mtime`, `maxDepth`) |
|
|
43
|
-
| Archives | `fs.tar
|
|
47
|
+
| Archives | `fs.tar` (`create`/`extract`/`list`), `fs.zip`, `fs.unzip` (`extract`/`list`), `fs.gzip`, `fs.gunzip` |
|
|
44
48
|
| Compare | `fs.diff` |
|
|
45
49
|
| Temp and trash | `fs.mktemp`, `fs.trash` |
|
|
46
50
|
| Text filters | `fs.cat`, `fs.head`, `fs.tail`, `fs.grep`, `fs.sed`, `fs.sort`, `fs.uniq`, `fs.cut`, `fs.tr`, `fs.wc`, `fs.tee` |
|
|
47
51
|
| Compose filters | `fs.pipe` |
|
|
52
|
+
| Background jobs | `background: true`, then `fs.job` |
|
|
48
53
|
|
|
49
54
|
## Argument shapes
|
|
50
55
|
|
|
@@ -58,7 +63,8 @@ Use the exact field names; scalar `path` is only valid for `fs.mkdir`.
|
|
|
58
63
|
| `files` | `fs.hash` |
|
|
59
64
|
| `left` + `right` | `fs.diff` |
|
|
60
65
|
| `archive` + `paths` | `fs.tar` create, `fs.zip` create |
|
|
61
|
-
| `archive` + `mode` | `fs.tar
|
|
66
|
+
| `archive` + `mode` | `fs.tar` (`create`/`extract`/`list`), `fs.unzip` (`extract`/`list`) |
|
|
67
|
+
| `content` | `fs.tee` when there is no stdin |
|
|
62
68
|
| `stages` + optional `input`/`output` | `fs.pipe` |
|
|
63
69
|
|
|
64
70
|
## Pipe
|
|
@@ -82,6 +88,54 @@ native names (`cat`, `grep`, `sort`), not `fs.cat`. There is no shell,
|
|
|
82
88
|
redirection operator, nested pipe, or `find -exec`. A filter stage needs
|
|
83
89
|
`input` or a preceding source stage.
|
|
84
90
|
|
|
91
|
+
## Background jobs
|
|
92
|
+
|
|
93
|
+
Every tool accepts `background: true`. It returns immediately with a job id and
|
|
94
|
+
an atomic status-file path; use it for long copies, searches, archives, or
|
|
95
|
+
hashes, then keep working and collect the result later.
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
const job = JSON.parse(
|
|
99
|
+
await tools.fs.cp({
|
|
100
|
+
sources: ["large-tree"],
|
|
101
|
+
destination: "backup",
|
|
102
|
+
recursive: true,
|
|
103
|
+
background: true,
|
|
104
|
+
}),
|
|
105
|
+
)
|
|
106
|
+
// { jobId, tool, state: "running", statusPath }
|
|
107
|
+
|
|
108
|
+
await tools.fs.job({ id: job.jobId, wait: true, timeoutMs: 600000 }) // blocks
|
|
109
|
+
await tools.fs.job({ id: job.jobId }) // current status
|
|
110
|
+
await tools.fs.job({ id: job.jobId, cancel: true }) // abort
|
|
111
|
+
await tools.fs.job({ list: true }) // newest first
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`wait` returns the original tool result once the job completes; on timeout it
|
|
115
|
+
returns the status with `timedOut: true`. Jobs are process-local and lost on
|
|
116
|
+
server restart. Status files live under `/tmp/opencode/fs-jobs/<server-pid>/`;
|
|
117
|
+
eight jobs may run at once and finished jobs are cleaned after one hour.
|
|
118
|
+
|
|
119
|
+
To wait without blocking the session, combine the status file with `wait_for`.
|
|
120
|
+
Wait for any terminal state, then read the job for the result or error:
|
|
121
|
+
|
|
122
|
+
```js
|
|
123
|
+
await tools.wait.for({
|
|
124
|
+
condition: {
|
|
125
|
+
type: "file_contains",
|
|
126
|
+
path: job.statusPath,
|
|
127
|
+
pattern: '"state":"(completed|failed|cancelled)"',
|
|
128
|
+
regex: true,
|
|
129
|
+
},
|
|
130
|
+
timeoutMs: 600000,
|
|
131
|
+
intervalMs: 500,
|
|
132
|
+
})
|
|
133
|
+
const status = JSON.parse(await tools.fs.job({ id: job.jobId }))
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
A job that produces no text returns empty content from `fs.job wait`; verify the
|
|
137
|
+
effect with `fs.stat`, `fs.ls`, or `fs.diff`, and use `fs.job({ id })` for state.
|
|
138
|
+
|
|
85
139
|
## Recipes
|
|
86
140
|
|
|
87
141
|
```js
|
|
@@ -96,9 +150,11 @@ await tools.fs.ls({ paths: ["dist"], long: true, human: true })
|
|
|
96
150
|
await tools.fs.find({ paths: ["."], name: "*.log", size: "+10M" })
|
|
97
151
|
await tools.fs.trash({ paths: ["old.log"] })
|
|
98
152
|
|
|
99
|
-
// create and extract an archive
|
|
153
|
+
// create, list, and extract an archive
|
|
100
154
|
await tools.fs.tar({ mode: "create", archive: "dist.tgz", paths: ["dist"], gzip: true })
|
|
155
|
+
await tools.fs.tar({ mode: "list", archive: "dist.tgz" })
|
|
101
156
|
await tools.fs.tar({ mode: "extract", archive: "dist.tgz", directory: "out" })
|
|
157
|
+
await tools.fs.unzip({ archive: "bundle.zip", mode: "list" })
|
|
102
158
|
|
|
103
159
|
// compare two files
|
|
104
160
|
await tools.fs.diff({ left: "old.txt", right: "new.txt", unified: 3 })
|
|
@@ -114,7 +170,13 @@ await tools.fs.diff({ left: "old.txt", right: "new.txt", unified: 3 })
|
|
|
114
170
|
- `fs.tail` has no follow mode; `fs.diff` compares files/directories only.
|
|
115
171
|
- `cp -a` preserves mode and timestamps but not ACLs or xattrs.
|
|
116
172
|
- `fs.tar`/`fs.zip` are file-backed; they are not pipe stages.
|
|
173
|
+
- `fs.tar` resolves `paths` even when `directory` is set; pass absolute sources
|
|
174
|
+
with `directory` or the member path may not be found.
|
|
175
|
+
- `fs.du` reports allocated blocks like `du`; use `fs.stat` with `%s` for
|
|
176
|
+
apparent file bytes.
|
|
117
177
|
- `fs.trash` uses the XDG home trash only and refuses cross-device moves.
|
|
178
|
+
Files under `/tmp` are usually on another filesystem; use a project path or a
|
|
179
|
+
same-filesystem holding directory instead.
|
|
118
180
|
- `fs.mktemp` uses the OS temp directory unless `tmpdir` is supplied.
|
|
119
181
|
|
|
120
182
|
## Paths and safety
|
|
@@ -143,11 +205,13 @@ hidden inside a pipeline. Do not work around a denied tool with shell.
|
|
|
143
205
|
- `fs.grep` with no matches and `fs.diff` with differences return exit code 1;
|
|
144
206
|
that is a result, not a tool failure.
|
|
145
207
|
- Binary output is returned as base64 when no `output` file is supplied.
|
|
208
|
+
- Tools that produce no text (`cp`, `mv`, `rm`, `touch`, `chmod`, `sed -i`) return
|
|
209
|
+
empty content; verify the effect with `fs.stat`, `fs.ls`, or `fs.diff`.
|
|
146
210
|
- Invalid arguments return `ERROR: Invalid ...`; fix the field names or option
|
|
147
211
|
values rather than retrying the same call.
|
|
148
212
|
|
|
149
213
|
## Verification
|
|
150
214
|
|
|
151
215
|
Use `fs.stat`, `fs.ls`, `fs.hash`, `fs.cat`, or `fs.diff` to confirm the result.
|
|
152
|
-
Report the tool result
|
|
153
|
-
`differences: true`.
|
|
216
|
+
Do not verify with a shell command. Report the tool result or the verified state,
|
|
217
|
+
such as `copied: 1`, `found: 2`, or `differences: true`.
|
package/src/core/errors.ts
CHANGED
package/src/core/jobs.ts
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import * as fs from "node:fs/promises";
|
|
8
|
+
import * as os from "node:os";
|
|
9
|
+
import * as path from "node:path";
|
|
10
|
+
import { FsError, errorMessage } from "./errors.js";
|
|
11
|
+
import type { RenderedResult } from "./format.js";
|
|
12
|
+
|
|
13
|
+
export type JobState = "running" | "completed" | "failed" | "cancelled";
|
|
14
|
+
|
|
15
|
+
export interface JobStatus {
|
|
16
|
+
readonly id: string;
|
|
17
|
+
readonly tool: string;
|
|
18
|
+
readonly state: JobState;
|
|
19
|
+
readonly startedAt: number;
|
|
20
|
+
readonly finishedAt?: number;
|
|
21
|
+
readonly error?: string;
|
|
22
|
+
readonly statusPath: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface JobWait {
|
|
26
|
+
readonly status: JobStatus;
|
|
27
|
+
readonly timedOut: boolean;
|
|
28
|
+
readonly result?: RenderedResult;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface JobManagerOptions {
|
|
32
|
+
readonly dir?: string;
|
|
33
|
+
readonly limit?: number;
|
|
34
|
+
readonly ttlMs?: number;
|
|
35
|
+
readonly now?: () => number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface JobRecord {
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly tool: string;
|
|
41
|
+
state: JobState;
|
|
42
|
+
readonly startedAt: number;
|
|
43
|
+
finishedAt?: number;
|
|
44
|
+
error?: string;
|
|
45
|
+
readonly statusPath: string;
|
|
46
|
+
readonly controller: AbortController;
|
|
47
|
+
result?: RenderedResult;
|
|
48
|
+
done: Promise<void>;
|
|
49
|
+
timer?: NodeJS.Timeout;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const DEFAULT_LIMIT = 8;
|
|
53
|
+
const DEFAULT_TTL_MS = 60 * 60 * 1000;
|
|
54
|
+
|
|
55
|
+
function snapshot(job: JobRecord): JobStatus {
|
|
56
|
+
return {
|
|
57
|
+
id: job.id,
|
|
58
|
+
tool: job.tool,
|
|
59
|
+
state: job.state,
|
|
60
|
+
startedAt: job.startedAt,
|
|
61
|
+
...(job.finishedAt === undefined ? {} : { finishedAt: job.finishedAt }),
|
|
62
|
+
...(job.error === undefined ? {} : { error: job.error }),
|
|
63
|
+
statusPath: job.statusPath,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
export class JobManager {
|
|
70
|
+
private readonly jobs = new Map<string, JobRecord>();
|
|
71
|
+
private readonly dir: string;
|
|
72
|
+
private readonly limit: number;
|
|
73
|
+
private readonly ttlMs: number;
|
|
74
|
+
private readonly now: () => number;
|
|
75
|
+
|
|
76
|
+
constructor(options: JobManagerOptions = {}) {
|
|
77
|
+
this.dir = options.dir ?? path.join(os.tmpdir(), "opencode", "fs-jobs", String(process.pid));
|
|
78
|
+
this.limit = options.limit ?? DEFAULT_LIMIT;
|
|
79
|
+
this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
80
|
+
this.now = options.now ?? Date.now;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async start(tool: string, run: (signal: AbortSignal) => Promise<RenderedResult>): Promise<JobStatus> {
|
|
84
|
+
if (this.runningCount() >= this.limit) {
|
|
85
|
+
throw new FsError(`background job limit reached (${this.limit} running).`, "busy");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const id = `job_${randomUUID()}`;
|
|
89
|
+
const job: JobRecord = {
|
|
90
|
+
id,
|
|
91
|
+
tool,
|
|
92
|
+
state: "running",
|
|
93
|
+
startedAt: this.now(),
|
|
94
|
+
statusPath: path.join(this.dir, `${id}.json`),
|
|
95
|
+
controller: new AbortController(),
|
|
96
|
+
done: Promise.resolve(),
|
|
97
|
+
};
|
|
98
|
+
this.jobs.set(id, job);
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
await this.write(job);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
this.jobs.delete(id);
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
job.done = this.execute(job, run);
|
|
108
|
+
this.armRunningDeadline(job);
|
|
109
|
+
return snapshot(job);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
status(id: string): JobStatus {
|
|
113
|
+
return snapshot(this.require(id));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
list(): JobStatus[] {
|
|
117
|
+
return [...this.jobs.values()]
|
|
118
|
+
.sort((a, b) => b.startedAt - a.startedAt)
|
|
119
|
+
.map((job) => snapshot(job));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async wait(id: string, timeoutMs: number): Promise<JobWait> {
|
|
123
|
+
const job = this.require(id);
|
|
124
|
+
if (job.state !== "running") {
|
|
125
|
+
return { status: snapshot(job), timedOut: false, ...(job.result ? { result: job.result } : {}) };
|
|
126
|
+
}
|
|
127
|
+
await new Promise<void>((resolve) => {
|
|
128
|
+
const timer = setTimeout(resolve, timeoutMs);
|
|
129
|
+
void job.done.then(() => {
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
resolve();
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
return {
|
|
135
|
+
status: snapshot(job),
|
|
136
|
+
timedOut: job.state === "running",
|
|
137
|
+
...(job.result ? { result: job.result } : {}),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
cancel(id: string): JobStatus {
|
|
142
|
+
const job = this.require(id);
|
|
143
|
+
if (job.state === "running") job.controller.abort();
|
|
144
|
+
return snapshot(job);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
dispose(): void {
|
|
148
|
+
for (const job of this.jobs.values()) {
|
|
149
|
+
clearTimeout(job.timer);
|
|
150
|
+
if (job.state === "running") job.controller.abort();
|
|
151
|
+
}
|
|
152
|
+
this.jobs.clear();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private async execute(
|
|
156
|
+
job: JobRecord,
|
|
157
|
+
run: (signal: AbortSignal) => Promise<RenderedResult>,
|
|
158
|
+
): Promise<void> {
|
|
159
|
+
try {
|
|
160
|
+
const result = await run(job.controller.signal);
|
|
161
|
+
if (job.controller.signal.aborted) {
|
|
162
|
+
job.state = "cancelled";
|
|
163
|
+
} else {
|
|
164
|
+
job.state = "completed";
|
|
165
|
+
job.result = result;
|
|
166
|
+
}
|
|
167
|
+
} catch (error) {
|
|
168
|
+
job.state = job.controller.signal.aborted ? "cancelled" : "failed";
|
|
169
|
+
job.error = errorMessage(error);
|
|
170
|
+
} finally {
|
|
171
|
+
job.finishedAt = this.now();
|
|
172
|
+
/* v8 ignore next 3 -- a status-file write failure must not lose the job result */
|
|
173
|
+
await this.write(job).catch(() => {});
|
|
174
|
+
this.armCleanup(job);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
private armRunningDeadline(job: JobRecord): void {
|
|
179
|
+
job.timer = setTimeout(() => {
|
|
180
|
+
job.controller.abort();
|
|
181
|
+
}, this.ttlMs);
|
|
182
|
+
job.timer.unref();
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
private armCleanup(job: JobRecord): void {
|
|
186
|
+
clearTimeout(job.timer);
|
|
187
|
+
job.timer = setTimeout(() => {
|
|
188
|
+
this.jobs.delete(job.id);
|
|
189
|
+
/* v8 ignore next -- status-file cleanup is best-effort */
|
|
190
|
+
void fs.rm(job.statusPath, { force: true }).catch(() => {});
|
|
191
|
+
}, this.ttlMs);
|
|
192
|
+
job.timer.unref();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private async write(job: JobRecord): Promise<void> {
|
|
196
|
+
await fs.mkdir(this.dir, { recursive: true });
|
|
197
|
+
const temp = `${job.statusPath}.${process.pid}.tmp`;
|
|
198
|
+
const payload = {
|
|
199
|
+
...snapshot(job),
|
|
200
|
+
...(job.result ? { hasResult: true } : {}),
|
|
201
|
+
};
|
|
202
|
+
await fs.writeFile(temp, `${JSON.stringify(payload)}\n`, "utf8");
|
|
203
|
+
await fs.rename(temp, job.statusPath);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private require(id: string): JobRecord {
|
|
207
|
+
const job = this.jobs.get(id);
|
|
208
|
+
if (!job) throw new FsError(`job not found: ${id}`, "not-found");
|
|
209
|
+
return job;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
private runningCount(): number {
|
|
213
|
+
let count = 0;
|
|
214
|
+
for (const job of this.jobs.values()) if (job.state === "running") count++;
|
|
215
|
+
return count;
|
|
216
|
+
}
|
|
217
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -4,9 +4,11 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import * as os from "node:os";
|
|
7
|
+
import { Type, type TSchema } from "@sinclair/typebox";
|
|
7
8
|
import { Plugin } from "@opencode/plugin";
|
|
8
9
|
import { FsError } from "./core/errors.js";
|
|
9
10
|
import { renderError, renderResult } from "./core/format.js";
|
|
11
|
+
import { JobManager } from "./core/jobs.js";
|
|
10
12
|
import { PermissionGate, type PermissionAssert } from "./core/permissions.js";
|
|
11
13
|
import { clampConcurrency } from "./core/parallel.js";
|
|
12
14
|
import { Sandbox } from "./core/sandbox.js";
|
|
@@ -90,6 +92,40 @@ const TOOLS: readonly AnyTool[] = [
|
|
|
90
92
|
|
|
91
93
|
const DEFAULT_MAX_OUTPUT = 1024 * 1024;
|
|
92
94
|
|
|
95
|
+
function withBackground(schema: TSchema): TSchema {
|
|
96
|
+
return Type.Composite(
|
|
97
|
+
[
|
|
98
|
+
schema,
|
|
99
|
+
Type.Object({
|
|
100
|
+
background: Type.Optional(
|
|
101
|
+
Type.Boolean({
|
|
102
|
+
description:
|
|
103
|
+
"Run this operation as a background job and return a job id immediately. Use fs.job to wait, inspect, cancel, or list jobs.",
|
|
104
|
+
}),
|
|
105
|
+
),
|
|
106
|
+
}),
|
|
107
|
+
],
|
|
108
|
+
{ additionalProperties: false },
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const JOB_SCHEMA = Type.Object(
|
|
113
|
+
{
|
|
114
|
+
id: Type.Optional(Type.String({ description: "Background job id." })),
|
|
115
|
+
wait: Type.Optional(Type.Boolean({ description: "Wait for the job to finish." })),
|
|
116
|
+
cancel: Type.Optional(Type.Boolean({ description: "Abort a running job." })),
|
|
117
|
+
list: Type.Optional(Type.Boolean({ description: "List all jobs, newest first." })),
|
|
118
|
+
timeoutMs: Type.Optional(
|
|
119
|
+
Type.Integer({
|
|
120
|
+
minimum: 1,
|
|
121
|
+
maximum: 600000,
|
|
122
|
+
description: "Maximum wait in milliseconds. Default 600000.",
|
|
123
|
+
}),
|
|
124
|
+
),
|
|
125
|
+
},
|
|
126
|
+
{ additionalProperties: false },
|
|
127
|
+
);
|
|
128
|
+
|
|
93
129
|
export default Plugin.define({
|
|
94
130
|
id: "opencode-fs-plugin",
|
|
95
131
|
async setup(ctx) {
|
|
@@ -110,22 +146,26 @@ export default Plugin.define({
|
|
|
110
146
|
typeof ctx.options?.maxOutputBytes === "number" && ctx.options.maxOutputBytes > 0
|
|
111
147
|
? Math.trunc(ctx.options.maxOutputBytes)
|
|
112
148
|
: DEFAULT_MAX_OUTPUT;
|
|
149
|
+
const jobs = new JobManager(
|
|
150
|
+
typeof ctx.options?.jobDir === "string" ? { dir: ctx.options.jobDir } : {},
|
|
151
|
+
);
|
|
113
152
|
|
|
114
|
-
await ctx.tool.transform((editor) => {
|
|
153
|
+
const registration = await ctx.tool.transform((editor) => {
|
|
115
154
|
editor.namespace({
|
|
116
155
|
name: "fs",
|
|
117
156
|
description: "Linux-style filesystem and text tools with native command semantics.",
|
|
118
157
|
});
|
|
119
158
|
|
|
120
159
|
for (const spec of TOOLS) {
|
|
160
|
+
const schema = withBackground(spec.schema);
|
|
121
161
|
editor.add({
|
|
122
162
|
name: spec.name,
|
|
123
163
|
description: spec.description,
|
|
124
|
-
input:
|
|
164
|
+
input: schema,
|
|
125
165
|
options: { namespace: "fs", permission: `fs_${spec.name}` },
|
|
126
166
|
execute: async (input, context) => {
|
|
127
167
|
try {
|
|
128
|
-
const parsed = parseSchema<unknown>(
|
|
168
|
+
const parsed = parseSchema<unknown>(schema, input, `${spec.name} input`);
|
|
129
169
|
const assertPermission: PermissionAssert = async (request) => {
|
|
130
170
|
await ctx.permission.assert(
|
|
131
171
|
request as unknown as Parameters<typeof ctx.permission.assert>[0],
|
|
@@ -144,20 +184,46 @@ export default Plugin.define({
|
|
|
144
184
|
(full) => sandbox.resource(full),
|
|
145
185
|
assertPermission,
|
|
146
186
|
);
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
187
|
+
const runSpec = async (signal: AbortSignal) => {
|
|
188
|
+
const result = await spec.run(
|
|
189
|
+
{
|
|
190
|
+
sandbox,
|
|
191
|
+
permission: permissionFor(`fs_${spec.name}`),
|
|
192
|
+
permissionFor,
|
|
193
|
+
concurrency,
|
|
194
|
+
signal,
|
|
195
|
+
tmpdir: os.tmpdir(),
|
|
196
|
+
maxOutputBytes,
|
|
197
|
+
},
|
|
198
|
+
parsed,
|
|
199
|
+
{},
|
|
200
|
+
);
|
|
201
|
+
return renderResult(result, maxOutputBytes);
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
if ((parsed as { background?: unknown }).background === true) {
|
|
205
|
+
const job = await jobs.start(spec.name, runSpec);
|
|
206
|
+
return {
|
|
207
|
+
content: JSON.stringify(
|
|
208
|
+
{
|
|
209
|
+
jobId: job.id,
|
|
210
|
+
tool: job.tool,
|
|
211
|
+
state: job.state,
|
|
212
|
+
statusPath: job.statusPath,
|
|
213
|
+
},
|
|
214
|
+
null,
|
|
215
|
+
2,
|
|
216
|
+
),
|
|
217
|
+
metadata: {
|
|
218
|
+
ok: true,
|
|
219
|
+
background: true,
|
|
220
|
+
jobId: job.id,
|
|
221
|
+
statusPath: job.statusPath,
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
return await runSpec(context.signal);
|
|
161
227
|
} catch (error) {
|
|
162
228
|
if (error instanceof FsError) {
|
|
163
229
|
return renderError(error, error.code === "outside");
|
|
@@ -167,6 +233,86 @@ export default Plugin.define({
|
|
|
167
233
|
},
|
|
168
234
|
});
|
|
169
235
|
}
|
|
236
|
+
|
|
237
|
+
editor.add({
|
|
238
|
+
name: "job",
|
|
239
|
+
description:
|
|
240
|
+
"Inspect, wait for, cancel, or list background fs jobs. Jobs are created by passing background: true to any fs tool. wait returns the original tool result when the job completes; a timeout returns the current status.",
|
|
241
|
+
input: JOB_SCHEMA,
|
|
242
|
+
options: { namespace: "fs", permission: "fs_job" },
|
|
243
|
+
execute: async (input, _context) => {
|
|
244
|
+
try {
|
|
245
|
+
const parsed = parseSchema<{
|
|
246
|
+
id?: string;
|
|
247
|
+
wait?: boolean;
|
|
248
|
+
cancel?: boolean;
|
|
249
|
+
list?: boolean;
|
|
250
|
+
timeoutMs?: number;
|
|
251
|
+
}>(JOB_SCHEMA, input, "job input");
|
|
252
|
+
|
|
253
|
+
if (parsed.list === true) {
|
|
254
|
+
if (parsed.id !== undefined || parsed.wait === true || parsed.cancel === true) {
|
|
255
|
+
throw new FsError("list cannot be combined with id, wait, or cancel.", "invalid");
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
content: JSON.stringify({ jobs: jobs.list() }, null, 2),
|
|
259
|
+
metadata: { ok: true },
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (!parsed.id) throw new FsError("job requires id or list.", "invalid");
|
|
264
|
+
|
|
265
|
+
if (parsed.cancel === true) {
|
|
266
|
+
if (parsed.wait === true) {
|
|
267
|
+
throw new FsError("cancel and wait are mutually exclusive.", "invalid");
|
|
268
|
+
}
|
|
269
|
+
const status = jobs.cancel(parsed.id);
|
|
270
|
+
return {
|
|
271
|
+
content: JSON.stringify(status, null, 2),
|
|
272
|
+
metadata: { ok: true, jobId: status.id, state: status.state },
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (parsed.wait === true) {
|
|
277
|
+
const waited = await jobs.wait(parsed.id, parsed.timeoutMs ?? 600000);
|
|
278
|
+
if (waited.result) {
|
|
279
|
+
return {
|
|
280
|
+
content: waited.result.content,
|
|
281
|
+
metadata: {
|
|
282
|
+
...waited.result.metadata,
|
|
283
|
+
jobId: waited.status.id,
|
|
284
|
+
state: waited.status.state,
|
|
285
|
+
timedOut: waited.timedOut,
|
|
286
|
+
},
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
return {
|
|
290
|
+
content: JSON.stringify({ ...waited.status, timedOut: waited.timedOut }, null, 2),
|
|
291
|
+
metadata: {
|
|
292
|
+
ok: false,
|
|
293
|
+
jobId: waited.status.id,
|
|
294
|
+
state: waited.status.state,
|
|
295
|
+
timedOut: waited.timedOut,
|
|
296
|
+
},
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const status = jobs.status(parsed.id);
|
|
301
|
+
return {
|
|
302
|
+
content: JSON.stringify(status, null, 2),
|
|
303
|
+
metadata: { ok: true, jobId: status.id, state: status.state },
|
|
304
|
+
};
|
|
305
|
+
} catch (error) {
|
|
306
|
+
if (error instanceof FsError) return renderError(error, error.code === "outside");
|
|
307
|
+
throw error;
|
|
308
|
+
}
|
|
309
|
+
},
|
|
310
|
+
});
|
|
170
311
|
});
|
|
312
|
+
|
|
313
|
+
return () => {
|
|
314
|
+
jobs.dispose();
|
|
315
|
+
void registration.dispose();
|
|
316
|
+
};
|
|
171
317
|
},
|
|
172
318
|
});
|
package/src/tools/du.ts
CHANGED
|
@@ -50,7 +50,7 @@ export const duTool: ToolSpec<Input> = {
|
|
|
50
50
|
: await ctx.sandbox.lstat(target.full, requested);
|
|
51
51
|
const rootDev = num(rootStats.dev);
|
|
52
52
|
const seen = new Set<string>();
|
|
53
|
-
let total = usage(
|
|
53
|
+
let total = usage(rootStats, seen);
|
|
54
54
|
const local: Row[] = [];
|
|
55
55
|
if (input.all === true && !rootStats.isDirectory()) {
|
|
56
56
|
local.push({ path: requested, bytes: total });
|
|
@@ -65,7 +65,7 @@ export const duTool: ToolSpec<Input> = {
|
|
|
65
65
|
})) {
|
|
66
66
|
/* v8 ignore next */
|
|
67
67
|
if (input.oneFileSystem === true && num(entry.stats.dev) !== rootDev) continue;
|
|
68
|
-
const bytes = usage(entry.
|
|
68
|
+
const bytes = usage(entry.stats, seen);
|
|
69
69
|
total += bytes;
|
|
70
70
|
if (input.all === true || entry.stats.isDirectory()) {
|
|
71
71
|
local.push({ path: entry.path, bytes });
|
|
@@ -89,14 +89,12 @@ export const duTool: ToolSpec<Input> = {
|
|
|
89
89
|
},
|
|
90
90
|
};
|
|
91
91
|
|
|
92
|
-
function usage(
|
|
93
|
-
|
|
94
|
-
if (!stats.isFile()) return stats.isDirectory() ? num(stats.blocks) * 512 : 0;
|
|
95
|
-
if (num(stats.nlink) > 1) {
|
|
92
|
+
function usage(stats: Awaited<ReturnType<typeof fs.lstat>>, seen: Set<string>): number {
|
|
93
|
+
if (!stats.isDirectory() && num(stats.nlink) > 1) {
|
|
96
94
|
const key = `${num(stats.dev)}:${num(stats.ino)}`;
|
|
97
95
|
/* v8 ignore next */
|
|
98
96
|
if (seen.has(key)) return 0;
|
|
99
97
|
seen.add(key);
|
|
100
98
|
}
|
|
101
|
-
return num(stats.
|
|
99
|
+
return num(stats.blocks) * 512;
|
|
102
100
|
}
|