opencode-fs-plugin 1.0.2 → 1.1.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/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.0.2"]
20
+ "plugins": ["opencode-fs-plugin@1.1.0"]
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.0.2
27
+ opencode plugin add opencode-fs-plugin@1.1.0
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.0.2
39
+ VERSION=1.1.0
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.0.2"]
67
+ "plugins": ["github:masterjg/opencode-fs-plugin#v1.1.0"]
68
68
  }
69
69
  ```
70
70
 
71
- `opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.0.2'` installs the
71
+ `opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.1.0'` 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.0.2`. A tag is
73
+ `git+https://github.com/masterjg/opencode-fs-plugin.git#v1.1.0`. 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.0.2"
80
+ npm install "github:masterjg/opencode-fs-plugin#v1.1.0"
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.0.2 with "npm install opencode-fs-plugin@1.0.2",
177
+ Install opencode-fs-plugin 1.1.0 with "npm install opencode-fs-plugin@1.1.0",
178
178
  or from its release tarball or the Git tag
179
- "github:masterjg/opencode-fs-plugin#v1.0.2". Add
179
+ "github:masterjg/opencode-fs-plugin#v1.1.0". 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.0.2"]
130
+ "plugins": ["opencode-fs-plugin@1.1.0"]
76
131
  }
77
132
  ```
78
133
 
79
- `opencode plugin add opencode-fs-plugin@1.0.2` installs it and writes the config
134
+ `opencode plugin add opencode-fs-plugin@1.1.0` 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.0.2
141
+ npm install opencode-fs-plugin@1.1.0
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.0.2
156
+ VERSION=1.1.0
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.0.2"]
185
+ "plugins": ["github:masterjg/opencode-fs-plugin#v1.1.0"]
131
186
  }
132
187
  ```
133
188
 
134
- `opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.0.2'` installs the
189
+ `opencode plugin add 'github:masterjg/opencode-fs-plugin#v1.1.0'` 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.0.2`. A tag is
191
+ `git+https://github.com/masterjg/opencode-fs-plugin.git#v1.1.0`. 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.0.2"
198
+ npm install "github:masterjg/opencode-fs-plugin#v1.1.0"
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": "opencode-fs-plugin",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "description": "OpenCode 2 plugin: Linux-style filesystem and text tools under the fs namespace.",
6
6
  "repository": {
@@ -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
@@ -45,6 +45,7 @@ operations the built-ins do not cover, and for composable text/archive work.
45
45
  | Temp and trash | `fs.mktemp`, `fs.trash` |
46
46
  | 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
47
  | Compose filters | `fs.pipe` |
48
+ | Background jobs | `background: true`, then `fs.job` |
48
49
 
49
50
  ## Argument shapes
50
51
 
@@ -82,6 +83,43 @@ native names (`cat`, `grep`, `sort`), not `fs.cat`. There is no shell,
82
83
  redirection operator, nested pipe, or `find -exec`. A filter stage needs
83
84
  `input` or a preceding source stage.
84
85
 
86
+ ## Background jobs
87
+
88
+ Every tool accepts `background: true`. It returns immediately with a job id and
89
+ an atomic status-file path; use it for long copies, searches, archives, or
90
+ hashes, then keep working and collect the result later.
91
+
92
+ ```js
93
+ const job = JSON.parse(
94
+ await tools.fs.cp({
95
+ sources: ["large-tree"],
96
+ destination: "backup",
97
+ recursive: true,
98
+ background: true,
99
+ }),
100
+ )
101
+ // { jobId, tool, state: "running", statusPath }
102
+
103
+ await tools.fs.job({ id: job.jobId, wait: true, timeoutMs: 600000 }) // blocks
104
+ await tools.fs.job({ id: job.jobId }) // current status
105
+ await tools.fs.job({ id: job.jobId, cancel: true }) // abort
106
+ await tools.fs.job({ list: true }) // newest first
107
+ ```
108
+
109
+ `wait` returns the original tool result once the job completes; on timeout it
110
+ returns the status with `timedOut: true`. Jobs are process-local and lost on
111
+ server restart. Status files live under `/tmp/opencode/fs-jobs/<server-pid>/`;
112
+ eight jobs may run at once and finished jobs are cleaned after one hour.
113
+
114
+ To wait without blocking the session, combine the status file with `wait_for`:
115
+
116
+ ```js
117
+ await tools.wait.for({
118
+ condition: { type: "file_contains", path: job.statusPath, pattern: '"state":"completed"' },
119
+ timeoutMs: 600000,
120
+ })
121
+ ```
122
+
85
123
  ## Recipes
86
124
 
87
125
  ```js
@@ -18,6 +18,7 @@ export type FsErrorCode =
18
18
  | "archive"
19
19
  | "checksum"
20
20
  | "interrupted"
21
+ | "busy"
21
22
  | "io";
22
23
 
23
24
  /**
@@ -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: spec.schema,
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>(spec.schema, input, `${spec.name} input`);
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 result = await spec.run(
148
- {
149
- sandbox,
150
- permission: permissionFor(`fs_${spec.name}`),
151
- permissionFor,
152
- concurrency,
153
- signal: context.signal,
154
- tmpdir: os.tmpdir(),
155
- maxOutputBytes,
156
- },
157
- parsed,
158
- {},
159
- );
160
- return renderResult(result, maxOutputBytes);
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
  });