opencode-fs-plugin 3.2.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -88,6 +88,13 @@ Prefer the canonical names.
88
88
 
89
89
  ## Pipe
90
90
 
91
+ Direct results larger than the spill threshold are written to
92
+ `/tmp/opencode/fs-spill` and returned as a 64 KiB preview plus `outputPath`,
93
+ `bytes`, and `spilled` metadata; the rendered result points at the file. The
94
+ threshold defaults to a quarter of free memory, clamped between 16 MiB and
95
+ 512 MiB; set `spillThresholdBytes` in the plugin options to fix it. Pipe stages
96
+ keep whole buffers so bytes pass unchanged.
97
+
91
98
  `fs.pipe` joins registered tools through byte buffers. Stages run in order;
92
99
  only pipeable tools can be used. Each stage asserts its own `fs_<tool>` action
93
100
  before it runs, so a disabled stage cannot be hidden inside a pipe. `output` and
package/SPEC.md CHANGED
@@ -126,6 +126,15 @@ Aliases are accepted only where noted: `path` for one `paths` element (`stat`,
126
126
  The trust-handoff class is waived so package tools can update workspace files
127
127
  such as `.git/hooks`; the executable allowlist remains the trust boundary.
128
128
 
129
+ ## Large output
130
+
131
+ A direct tool result larger than the spill threshold is written to
132
+ `/tmp/opencode/fs-spill/<tool>-<uuid>.out`. The threshold is a quarter of free
133
+ memory, clamped to 16 MiB..512 MiB, or the `spillThresholdBytes` plugin option.
134
+ The tool returns a 64 KiB preview, `outputPath`, `bytes`, and `spilled: true`,
135
+ and `renderResult` appends a note with the path. `fs.cat` streams into the sink;
136
+ other tools spill their finished result. Pipe stages stay in memory.
137
+
129
138
  ## Deliberate gaps
130
139
 
131
140
  These are not implemented:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-fs-plugin",
3
- "version": "3.2.0",
3
+ "version": "3.4.0",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22.12"
@@ -34,16 +34,22 @@ export function renderResult(result: ToolResult): RenderedResult {
34
34
  return { content: "", metadata };
35
35
  }
36
36
 
37
- metadata.bytes = result.stdout.length;
37
+ if (metadata.bytes === undefined) metadata.bytes = result.stdout.length;
38
38
 
39
39
  if (isBinary(result.stdout)) {
40
40
  metadata.encoding = "base64";
41
- return { content: result.stdout.toString("base64"), metadata };
41
+ return { content: spillNote(metadata, result.stdout.toString("base64")), metadata };
42
42
  }
43
43
 
44
44
  let content = result.stdout.toString("utf8");
45
45
  if (result.stderr) content += `${content.endsWith("\n") ? "" : "\n"}[stderr]\n${result.stderr}`;
46
- return { content, metadata };
46
+ return { content: spillNote(metadata, content), metadata };
47
+ }
48
+
49
+ function spillNote(metadata: Record<string, unknown>, content: string): string {
50
+ const outputPath = metadata.outputPath;
51
+ if (typeof outputPath !== "string") return content;
52
+ return `${content}${content.endsWith("\n") ? "" : "\n"}[output spilled to ${outputPath}; ${String(metadata.bytes)} bytes]`;
47
53
  }
48
54
 
49
55
  export function renderError(error: FsError, blocked: boolean): RenderedResult {
@@ -0,0 +1,145 @@
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 type { FileHandle } from "node:fs/promises";
10
+ import * as path from "node:path";
11
+ import { FsError } from "./errors.js";
12
+ import type { ToolResult } from "./types.js";
13
+
14
+ /** The dynamic threshold never goes below this. */
15
+ export const MIN_SPILL_THRESHOLD = 16 * 1024 * 1024;
16
+
17
+ /** The dynamic threshold never goes above this. */
18
+ export const MAX_SPILL_THRESHOLD = 512 * 1024 * 1024;
19
+
20
+ /** Bytes of a spilled result returned to the host as a preview. */
21
+ export const SPILL_PREVIEW = 64 * 1024;
22
+
23
+ /** A quarter of free memory, clamped to a safe range. */
24
+ export function dynamicSpillThreshold(free = os.freemem()): number {
25
+ return Math.max(MIN_SPILL_THRESHOLD, Math.min(MAX_SPILL_THRESHOLD, Math.floor(free / 4)));
26
+ }
27
+
28
+ /** An explicit byte count from the plugin options; undefined means dynamic. */
29
+ export function normalizeSpillThreshold(value: unknown): number | undefined {
30
+ if (value === undefined) return undefined;
31
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
32
+ throw new FsError("spillThresholdBytes must be a positive number.", "invalid");
33
+ }
34
+ return Math.trunc(value);
35
+ }
36
+
37
+ /** The shared directory for spilled outputs under the plugin's temp area. */
38
+ export function spillDirectory(tmpdir: string): string {
39
+ return path.join(tmpdir, "opencode", "fs-spill");
40
+ }
41
+
42
+ export interface SpillResult {
43
+ /** The full output when it stayed in memory, else its first bytes. */
44
+ readonly preview: Buffer;
45
+ /** Set when the full output was written to disk. */
46
+ readonly path: string | undefined;
47
+ /** Total bytes written. */
48
+ readonly bytes: number;
49
+ }
50
+
51
+ /**
52
+ * Collects chunks with a bounded in-memory prefix. Once a direct call passes
53
+ * `threshold`, the full stream goes to a temporary file and `finish` returns
54
+ * only the prefix; pipe stages pass `memoryOnly` and keep the whole buffer.
55
+ */
56
+ export class SpillSink {
57
+ private chunks: Buffer[] = [];
58
+ private head: Buffer[] = [];
59
+ private headBytes = 0;
60
+ private bytes = 0;
61
+ private handle: FileHandle | undefined;
62
+ private filePath: string | undefined;
63
+
64
+ constructor(
65
+ private readonly dir: string,
66
+ private readonly name: string,
67
+ private readonly memoryOnly = false,
68
+ private readonly threshold = dynamicSpillThreshold(),
69
+ private readonly previewBytes = SPILL_PREVIEW,
70
+ ) {}
71
+
72
+ async write(chunk: Buffer): Promise<void> {
73
+ if (chunk.length === 0) return;
74
+ this.bytes += chunk.length;
75
+ if (this.headBytes < this.previewBytes) {
76
+ const take = Math.min(chunk.length, this.previewBytes - this.headBytes);
77
+ this.head.push(chunk.subarray(0, take));
78
+ this.headBytes += take;
79
+ }
80
+ if (this.handle !== undefined) {
81
+ await this.handle.write(chunk);
82
+ return;
83
+ }
84
+ this.chunks.push(chunk);
85
+ if (!this.memoryOnly && this.bytes > this.threshold) await this.spill();
86
+ }
87
+
88
+ private async spill(): Promise<void> {
89
+ await fs.mkdir(this.dir, { recursive: true });
90
+ this.filePath = path.join(this.dir, `${this.name}-${randomUUID()}.out`);
91
+ this.handle = await fs.open(this.filePath, "w");
92
+ for (const chunk of this.chunks) await this.handle.write(chunk);
93
+ this.chunks = [];
94
+ }
95
+
96
+ async finish(): Promise<SpillResult> {
97
+ const preview = this.handle === undefined ? Buffer.concat(this.chunks) : Buffer.concat(this.head);
98
+ const filePath = this.filePath;
99
+ if (this.handle !== undefined) {
100
+ await this.handle.close();
101
+ this.handle = undefined;
102
+ }
103
+ return { preview, path: filePath, bytes: this.bytes };
104
+ }
105
+
106
+ /** Closes and removes a partial spill file. */
107
+ async abort(): Promise<void> {
108
+ if (this.handle !== undefined) {
109
+ /* v8 ignore next */
110
+ await this.handle.close().catch(() => undefined);
111
+ this.handle = undefined;
112
+ }
113
+ if (this.filePath !== undefined) {
114
+ /* v8 ignore next */
115
+ await fs.rm(this.filePath, { force: true }).catch(() => undefined);
116
+ this.filePath = undefined;
117
+ }
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Spill a finished tool result that is larger than the threshold. Tools that
123
+ * already streamed into a sink carry `outputPath` and pass through.
124
+ */
125
+ export async function spillResult(
126
+ result: ToolResult,
127
+ name: string,
128
+ tmpdir: string,
129
+ threshold = dynamicSpillThreshold(),
130
+ ): Promise<ToolResult> {
131
+ if (result.stdout.length <= threshold || result.metadata?.outputPath !== undefined) return result;
132
+ const sink = new SpillSink(spillDirectory(tmpdir), name, false, 0);
133
+ try {
134
+ await sink.write(result.stdout);
135
+ const out = await sink.finish();
136
+ return {
137
+ ...result,
138
+ stdout: out.preview,
139
+ metadata: { ...result.metadata, bytes: out.bytes, outputPath: out.path, spilled: true },
140
+ };
141
+ } catch (error) {
142
+ await sink.abort();
143
+ throw error;
144
+ }
145
+ }
package/src/core/types.ts CHANGED
@@ -31,6 +31,8 @@ export interface RunContext {
31
31
  readonly signal: AbortSignal;
32
32
  readonly tmpdir: string;
33
33
  readonly execAllowlist: readonly string[];
34
+ /** Explicit spill threshold in bytes; unset means the dynamic default. */
35
+ readonly spillThreshold?: number;
34
36
  /** `proxy` forces egress through the run's allowlist proxy; `ip` is all-IP. */
35
37
  readonly execNetworkMode: "proxy" | "ip";
36
38
  }
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ import { JobManager } from "./core/jobs.js";
12
12
  import { PermissionGate, type PermissionAssert } from "./core/permissions.js";
13
13
  import { clampConcurrency } from "./core/parallel.js";
14
14
  import { Sandbox } from "./core/sandbox.js";
15
+ import { normalizeSpillThreshold, spillResult } from "./core/spill.js";
15
16
  import { parseSchema } from "./core/schema.js";
16
17
  import type { ToolSpec } from "./core/types.js";
17
18
  import { arTool } from "./tools/ar.js";
@@ -200,6 +201,7 @@ export default Plugin.define({
200
201
  typeof ctx.options?.concurrency === "number" ? ctx.options.concurrency : undefined,
201
202
  );
202
203
  const execAllowlist = normalizeExecAllowlist(ctx.options?.execAllowlist);
204
+ const spillThreshold = normalizeSpillThreshold(ctx.options?.spillThresholdBytes);
203
205
  const execNetworkMode = normalizeExecNetworkMode(ctx.options?.execNetworkMode);
204
206
  const jobs = new JobManager(
205
207
  typeof ctx.options?.jobDir === "string" ? { dir: ctx.options.jobDir } : {},
@@ -250,11 +252,12 @@ export default Plugin.define({
250
252
  tmpdir: os.tmpdir(),
251
253
  execAllowlist,
252
254
  execNetworkMode,
255
+ ...(spillThreshold === undefined ? {} : { spillThreshold }),
253
256
  },
254
257
  parsed,
255
258
  {},
256
259
  );
257
- return renderResult(result);
260
+ return renderResult(await spillResult(result, spec.name, os.tmpdir(), spillThreshold));
258
261
  };
259
262
 
260
263
  if ((parsed as { background?: unknown }).background === true) {
package/src/tools/cat.ts CHANGED
@@ -5,8 +5,9 @@
5
5
 
6
6
  import { Type, type Static } from "@sinclair/typebox";
7
7
  import { pathsFrom } from "../core/aliases.js";
8
- import { collect, inputStream, lines } from "../core/stream.js";
9
- import { textResult, type ToolSpec } from "../core/types.js";
8
+ import { SpillSink, dynamicSpillThreshold, spillDirectory } from "../core/spill.js";
9
+ import { inputStream, lines } from "../core/stream.js";
10
+ import type { ToolSpec } from "../core/types.js";
10
11
 
11
12
  const Schema = Type.Object(
12
13
  {
@@ -35,38 +36,52 @@ export const catTool: ToolSpec<Input> = {
35
36
  const paths = pathsFrom(input) ?? [];
36
37
  const targets = await resolvePaths(ctx, paths);
37
38
  const stream = inputStream(targets.map((entry) => entry.full), io.stdin);
38
- if (
39
- input.number !== true &&
40
- input.numberNonBlank !== true &&
41
- input.squeezeBlank !== true &&
42
- input.showEnds !== true &&
43
- input.showTabs !== true &&
44
- input.showNonPrinting !== true
45
- ) {
46
- return { stdout: await collect(stream), exitCode: 0, metadata: { paths } };
47
- }
48
-
49
- const output: string[] = [];
50
- let number = 0;
51
- let blank = false;
52
- for await (const line of lines(stream)) {
53
- if (input.squeezeBlank === true && line.text === "") {
54
- if (blank) continue;
55
- blank = true;
39
+ const sink = new SpillSink(spillDirectory(ctx.tmpdir), "cat", io.piped === true, ctx.spillThreshold ?? dynamicSpillThreshold());
40
+ try {
41
+ if (
42
+ input.number !== true &&
43
+ input.numberNonBlank !== true &&
44
+ input.squeezeBlank !== true &&
45
+ input.showEnds !== true &&
46
+ input.showTabs !== true &&
47
+ input.showNonPrinting !== true
48
+ ) {
49
+ for await (const chunk of stream) await sink.write(chunk);
56
50
  } else {
57
- blank = false;
58
- }
59
- let text = line.text;
60
- if (input.showTabs === true || input.showNonPrinting === true) text = text.replaceAll("\t", "^I");
61
- if (input.showNonPrinting === true) text = visible(text);
62
- if (input.showEnds === true) text += "$";
63
- if ((input.number === true || input.numberNonBlank === true) && (input.numberNonBlank !== true || text.length > 0)) {
64
- number++;
65
- text = `${String(number).padStart(6)} ${text}`;
51
+ let number = 0;
52
+ let blank = false;
53
+ for await (const line of lines(stream)) {
54
+ if (input.squeezeBlank === true && line.text === "") {
55
+ if (blank) continue;
56
+ blank = true;
57
+ } else {
58
+ blank = false;
59
+ }
60
+ let text = line.text;
61
+ if (input.showTabs === true || input.showNonPrinting === true) text = text.replaceAll("\t", "^I");
62
+ if (input.showNonPrinting === true) text = visible(text);
63
+ if (input.showEnds === true) text += "$";
64
+ if ((input.number === true || input.numberNonBlank === true) && (input.numberNonBlank !== true || text.length > 0)) {
65
+ number++;
66
+ text = `${String(number).padStart(6)} ${text}`;
67
+ }
68
+ await sink.write(Buffer.from(text + (line.newline ? "\n" : "")));
69
+ }
66
70
  }
67
- output.push(text + (line.newline ? "\n" : ""));
71
+ const out = await sink.finish();
72
+ return {
73
+ stdout: out.preview,
74
+ exitCode: 0,
75
+ metadata: {
76
+ paths,
77
+ bytes: out.bytes,
78
+ ...(out.path === undefined ? {} : { outputPath: out.path, spilled: true }),
79
+ },
80
+ };
81
+ } catch (error) {
82
+ await sink.abort();
83
+ throw error;
68
84
  }
69
- return textResult(output.join(""), { paths });
70
85
  },
71
86
  };
72
87