opencode-fs-plugin 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -72,6 +72,7 @@ unit, end-to-end and coverage tests.
72
72
  | `cpio` | `fs.cpio` | `create`/`list`/`extract` (newc), `directory`, `members`, `input`, `member`, `verbose` |
73
73
  | `ar` | `fs.ar` | `create`/`list`/`extract`, `directory`, `members` |
74
74
  | HTTP(S) | `fs.http_request` | `url`, `method`, `headers`, `body`, `json`, `output`, `checksum`, `maxBytes`, `timeoutMs`, `failOnError`, `followRedirects`, `maxRedirects` |
75
+ | process | `fs.exec` | `command`, `args`, `cwd`, `stdin`, `timeoutMs`; exact allowlist, no shell |
75
76
  | shell pipe | `fs.pipe` | `stages`, `input`, `output`, `append` |
76
77
 
77
78
  `fs.head.skip` selects line ranges (`sed -n '20,40p'`). `fs.find` can
@@ -102,7 +103,7 @@ await tools.fs.pipe({
102
103
  })
103
104
  ```
104
105
 
105
- New filter stages: `tac`, `rev`, `nl`, `paste`, `shuf`, `fold`, `base64`, `od`,
106
+ New filter stages: `exec`, `tac`, `rev`, `nl`, `paste`, `shuf`, `fold`, `base64`, `od`,
106
107
  and `strings`; `dd` and `cpio` are source/sink stages like `tar`.
107
108
 
108
109
  `fs.http_request` is a pipe source, so network data can feed the same stages:
@@ -119,12 +120,41 @@ await tools.fs.pipe({
119
120
  Pipe stages exchange whole buffers, so use `maxBytes` for large responses. For
120
121
  large downloads prefer `fs.http_request({ output })`, which streams to disk.
121
122
 
122
- There is no shell, redirection operator, nested pipe, or `find -exec`.
123
+ There is no shell, redirection operator, nested pipe, or arbitrary `find -exec`.
123
124
 
124
125
  `fs.pipe` is sequential by design and is not a batch primitive. For independent
125
126
  work, fan out with `Promise.all` over `tools.fs.*` (or one multi-path call).
126
- `fs` domain errors resolve as `ERROR:`/`BLOCKED:` text, so check each result;
127
- permission denials throw.
127
+ `fs` domain errors resolve as `ERROR:`/`BLOCKED:` text; permission denials throw.
128
+
129
+ ## Exec
130
+
131
+ `fs.exec` runs one allowlisted executable with `shell: false`. The default
132
+ allowlist is `npm`, `npx`, `uv`, `uvx`, `pip`, `pip3`; override it in the plugin
133
+ options:
134
+
135
+ ```jsonc
136
+ {
137
+ "package": "./repos/opencode-fs-plugin",
138
+ "options": { "execAllowlist": ["npm", "uv"] }
139
+ }
140
+ ```
141
+
142
+ `command` is a bare name, `args` are literal, and `cwd` is sandboxed. Direct
143
+ calls return JSON with `exitCode`, `stdout`, and `stderr`; a pipe stage returns
144
+ raw stdout so it composes with `grep`, `sort`, `tee`, and the rest.
145
+
146
+ ```js
147
+ await tools.fs.exec({ command: "npm", args: ["run", "build"], timeoutMs: 300000 })
148
+ await tools.fs.pipe({
149
+ stages: [
150
+ { tool: "exec", args: { command: "npm", args: ["test"] } },
151
+ { tool: "grep", args: { pattern: "FAIL" } },
152
+ ],
153
+ })
154
+ ```
155
+
156
+ The command asserts `fs_exec`, uses a process group for timeout kills, caps
157
+ stdout/stderr, and treats a non-zero exit as a normal result.
128
158
 
129
159
  ## Performance and concurrency
130
160
 
package/SPEC.md CHANGED
@@ -78,6 +78,22 @@ Aliases are accepted only where noted: `path` for one `paths` element (`stat`,
78
78
  - `maxBytes` is enforced while reading, for buffered and downloaded bodies.
79
79
  - Pipe use is a buffered source; whole bodies pass between stages.
80
80
 
81
+ ## Process execution
82
+
83
+ - `fs.exec` is the only `child_process` use. It spawns with `shell: false`; there
84
+ is no shell parsing, redirection, or command substitution.
85
+ - `command` must be a bare executable name and must match the allowlist exactly.
86
+ Default: `npm`, `npx`, `uv`, `uvx`, `pip`, `pip3`. Override with the plugin
87
+ option `execAllowlist`; an empty list disables execution.
88
+ - `args` are passed verbatim. `cwd` resolves inside the sandbox and asserts
89
+ `external_directory` when it leaves the project; the action is `fs_exec`.
90
+ - Timeout defaults to 120000 ms, capped at 600000. A timeout kills the process
91
+ group (SIGTERM, then SIGKILL) and reports `timedOut: true`, exit code 124.
92
+ - Captured stdout/stderr are capped at `maxOutputBytes`; truncation is reported.
93
+ - Direct calls return JSON with `exitCode`, `stdout`, and `stderr`. In `fs.pipe`,
94
+ the stage returns raw stdout and composes as a source or filter.
95
+ - A non-zero exit is a normal result, not a tool error.
96
+
81
97
  ## Deliberate gaps
82
98
 
83
99
  These are not implemented:
@@ -97,8 +113,8 @@ These are not implemented:
97
113
  - true streaming through pipe stages; `http_request` buffers unless `output` is set
98
114
  - worker threads for CPU-bound stages (`sort`, `sed`, text diffing)
99
115
  - parallel member reads inside a single `tar`/`zip` archive; member order is fixed
100
- - process start, `nohup`, `setsid`, and `timeout` wrappers; the plugin never
101
- uses `child_process`
116
+ - process start beyond the allowlisted `exec` tool; `nohup`, `setsid`, and
117
+ `timeout` wrappers are unavailable
102
118
  - ICMP `ping` (raw sockets) and `ip`/netlink configuration
103
119
  - `rsync`, `scp`, and other transfer protocols; use the SSH MCP for remote work
104
120
  - ACLs, xattrs, and `chattr`/`lsattr`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-fs-plugin",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "type": "module",
5
5
  "description": "OpenCode 2 plugin: Linux-style filesystem, text, and HTTP(S) tools under the fs namespace.",
6
6
  "repository": {
@@ -25,6 +25,7 @@ With `execute` allowed, call it as `tools.fs.<command>`; agents without
25
25
  | Regex substitution or in-place edit | `fs.sed` |
26
26
  | Recoverable deletion | `fs.trash` |
27
27
  | HTTP(S) fetch, API call, or file download | `fs.http_request` |
28
+ | Allowlisted package CLI | `fs.exec` (no shell; default npm/npx/uv/uvx/pip/pip3) |
28
29
  | Many independent fs calls | one multi-path call, else `Promise.all` in `execute` |
29
30
  | Sequential byte pipeline | `fs.pipe` |
30
31
 
@@ -53,6 +54,7 @@ what `fs.stat`, `fs.ls`, `fs.hash`, `fs.diff`, or `fs.cat` can confirm.
53
54
  | Text filters | `fs.cat`, `fs.head`, `fs.tail`, `fs.grep`, `fs.sed`, `fs.sort`, `fs.uniq`, `fs.cut`, `fs.tr`, `fs.wc`, `fs.tee`, `fs.tac`, `fs.rev`, `fs.nl`, `fs.paste`, `fs.comm`, `fs.split`, `fs.shuf`, `fs.fold` |
54
55
  | Compose filters | `fs.pipe` |
55
56
  | HTTP(S) | `fs.http_request` (`output`, `checksum`, `maxBytes`, `json`) |
57
+ | Allowlisted package CLI | `fs.exec` (`command`, `args`, `cwd`, `stdin`, `timeoutMs`) |
56
58
  | Processes | `fs.ps`, `fs.pgrep`, `fs.kill` (`dryRun` available) |
57
59
  | System info | `fs.id`, `fs.uname`, `fs.uptime`, `fs.date`, `fs.findmnt`, `fs.mountpoint` |
58
60
  | Binary inspection | `fs.file`, `fs.base64`, `fs.od`, `fs.strings` |
@@ -98,6 +100,7 @@ host drops unknown fields, so a name typo runs with defaults.
98
100
  | `paths` + optional `keep`/`force`/`stdout`/`level`/`suffix` | `fs.gzip`, `fs.gunzip` |
99
101
  | `url` + optional `output` | `fs.http_request` |
100
102
  | `stages` + optional `input`/`output` | `fs.pipe` |
103
+ | `command` + `args` + optional `cwd`/`stdin`/`timeoutMs` | `fs.exec` |
101
104
 
102
105
  `fs.head` takes `skip` for line ranges: `sed -n '20,40p'` is
103
106
  `fs.head({ paths, skip: 19, lines: 21 })`. `fs.find` takes
@@ -136,12 +139,43 @@ removed, and deletion asserts `fs_rm`/`fs_trash`.
136
139
  | `cat > f <<EOF` | built-in `write` or `fs.tee({ paths: [f], content })` |
137
140
  | `rg pattern path` | `fs.grep({ pattern, paths })` or the built-in `grep` |
138
141
  | `ls -l f` | `fs.ls({ paths: [f], long: true })` |
142
+ | `npm ...` / `uv run ...` | `fs.exec({ command, args })` (allowlisted only) |
139
143
 
140
144
  `sed -n` applied to another command's stdout has no fs equivalent; keep that in
141
145
  the command pipeline. `fs.find` has no arbitrary `-exec` by design; use
142
146
  `action: "delete"` or `"trash"` for the common cleanup case, or list the paths and
143
147
  remove them explicitly.
144
148
 
149
+ ## Exec
150
+
151
+ `fs.exec` runs an allowlisted executable without a shell. The default allowlist
152
+ is `npm`, `npx`, `uv`, `uvx`, `pip`, `pip3`; override it with the fs plugin
153
+ option `execAllowlist` in `opencode.jsonc`:
154
+
155
+ ```jsonc
156
+ { "package": "./repos/opencode-fs-plugin", "options": { "execAllowlist": ["npm", "uv"] } }
157
+ ```
158
+
159
+ `command` is a bare executable name; `args` are passed verbatim, so `;`, `|`,
160
+ and `$()` have no shell meaning. `cwd` must resolve inside the project unless
161
+ `external_directory` allows it. Direct calls return JSON with
162
+ `exitCode`/`stdout`/`stderr`; in `fs.pipe` the stage passes raw stdout.
163
+
164
+ ```js
165
+ await tools.fs.exec({ command: "npm", args: ["run", "build"], timeoutMs: 300000 })
166
+ await tools.fs.exec({ command: "uv", args: ["run", "pytest"] })
167
+ await tools.fs.pipe({
168
+ stages: [
169
+ { tool: "exec", args: { command: "npm", args: ["test"] } },
170
+ { tool: "grep", args: { pattern: "FAIL" } },
171
+ ],
172
+ })
173
+ ```
174
+
175
+ A non-zero exit is a normal result; allowlist rejection, timeout, and abort are
176
+ errors. The tool asserts `fs_exec`, uses a process group for timeout kills, and
177
+ caps captured stdout/stderr.
178
+
145
179
  ## Batch independent calls
146
180
 
147
181
  `execute` is a JS runtime. Do not `await` independent fs calls one at a time.
@@ -254,9 +288,9 @@ Common pipe mistakes:
254
288
  - There is no shell, redirection operator, nested pipe, `find -exec`, or
255
289
  `xargs`.
256
290
 
257
- Pipeable filters include `head`, `tail`, `grep`, `sed`, `sort`, `uniq`, `cut`,
258
- `tr`, `tee`, `gzip`, `gunzip`, `tac`, `rev`, `nl`, `paste`, `shuf`, `fold`,
259
- `base64`, `od`, and `strings`. Unknown stage names fail with `unsupported`.
291
+ Pipeable filters include `exec`, `head`, `tail`, `grep`, `sed`, `sort`, `uniq`,
292
+ `cut`, `tr`, `tee`, `gzip`, `gunzip`, `tac`, `rev`, `nl`, `paste`, `shuf`,
293
+ `fold`, `base64`, `od`, and `strings`. Unknown stage names fail with `unsupported`.
260
294
 
261
295
  ## Background jobs
262
296
 
@@ -382,8 +416,9 @@ await tools.fs.http_request({
382
416
  - `fs.tar`/`fs.zip` create from `input` or stdin; extraction is file-backed.
383
417
  - `fs.http_request` is HTTP(S) only: no FTP/SFTP, cookie jars, client
384
418
  certificates, proxies, multipart uploads, or resumable downloads.
385
- - No process can be started or wrapped: `nohup`, `setsid`, and `timeout` are
386
- unavailable, and `fs.kill` rejects pid 0, pid 1, and process groups.
419
+ - Only `fs.exec` starts processes, and only exact allowlisted names; `nohup`,
420
+ `setsid`, and `timeout` wrappers are unavailable. `fs.kill` rejects pid 0,
421
+ pid 1, and process groups.
387
422
  - No ICMP ping; use `fs.http_request` or a TCP port check. No ACL, xattr, or
388
423
  `chattr` support. `rsync`/`scp` are out of scope; use the SSH MCP.
389
424
  - `fs.comm` expects sorted input. `fs.ar` uses GNU short names (16 bytes max);
@@ -425,6 +460,9 @@ Command actions are `fs_<command>` (for example `fs_cp`). `fs_*` wildcards work
425
460
  in agent rules. `fs.pipe` asserts each stage's action; a denied stage cannot be
426
461
  hidden inside a pipeline. Do not work around a denied tool with shell.
427
462
 
463
+ `fs_exec` runs only exact allowlisted names and asserts `fs_exec` plus
464
+ `external_directory` when `cwd` leaves the project. There is no shell.
465
+
428
466
  `fs_http_request` is allowed by default, like `fetch`. Its resource is the
429
467
  request host; rules can allow one host and ask or deny the rest. Each redirect
430
468
  hop is checked against the new host. Nothing blocks localhost or private
package/src/core/types.ts CHANGED
@@ -12,6 +12,8 @@ export type PipeMode = "source" | "filter" | "sink" | false;
12
12
  export interface IO {
13
13
  /** Piped input when the tool is used as a pipe stage. */
14
14
  readonly stdin?: AsyncIterable<Buffer>;
15
+ /** True when the tool is running inside `fs.pipe`. */
16
+ readonly piped?: boolean;
15
17
  }
16
18
 
17
19
  export interface ToolResult {
@@ -29,6 +31,7 @@ export interface RunContext {
29
31
  readonly signal: AbortSignal;
30
32
  readonly tmpdir: string;
31
33
  readonly maxOutputBytes: number;
34
+ readonly execAllowlist: readonly string[];
32
35
  }
33
36
 
34
37
  export interface ToolSpec<I> {
package/src/index.ts CHANGED
@@ -30,6 +30,7 @@ import { diffTool } from "./tools/diff.js";
30
30
  import { duTool } from "./tools/du.js";
31
31
  import { fileTool } from "./tools/file.js";
32
32
  import { findTool } from "./tools/find.js";
33
+ import { execTool, normalizeExecAllowlist } from "./tools/exec.js";
33
34
  import { findmntTool } from "./tools/findmnt.js";
34
35
  import { foldTool } from "./tools/fold.js";
35
36
  import { grepTool } from "./tools/grep.js";
@@ -141,6 +142,7 @@ const TOOLS: readonly AnyTool[] = [
141
142
  trTool,
142
143
  sedTool,
143
144
  grepTool,
145
+ execTool,
144
146
  pipeTool,
145
147
  ];
146
148
 
@@ -196,6 +198,7 @@ export default Plugin.define({
196
198
  const concurrency = clampConcurrency(
197
199
  typeof ctx.options?.concurrency === "number" ? ctx.options.concurrency : undefined,
198
200
  );
201
+ const execAllowlist = normalizeExecAllowlist(ctx.options?.execAllowlist);
199
202
  const maxOutputBytes =
200
203
  typeof ctx.options?.maxOutputBytes === "number" && ctx.options.maxOutputBytes > 0
201
204
  ? Math.trunc(ctx.options.maxOutputBytes)
@@ -248,6 +251,7 @@ export default Plugin.define({
248
251
  signal,
249
252
  tmpdir: os.tmpdir(),
250
253
  maxOutputBytes,
254
+ execAllowlist,
251
255
  },
252
256
  parsed,
253
257
  {},
@@ -0,0 +1,255 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ import { spawn, type ChildProcess } from "node:child_process";
7
+ import { once } from "node:events";
8
+ import { Type, type Static } from "@sinclair/typebox";
9
+ import { FsError, fromErrno } from "../core/errors.js";
10
+ import { textResult, type RunContext, type ToolSpec } from "../core/types.js";
11
+
12
+ export const DEFAULT_EXEC_ALLOWLIST = ["npm", "npx", "uv", "uvx", "pip", "pip3"] as const;
13
+
14
+ const EXEC_NAME = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;
15
+
16
+ export function isSafeExecName(value: string): boolean {
17
+ return EXEC_NAME.test(value);
18
+ }
19
+
20
+ export function normalizeExecAllowlist(value: unknown): readonly string[] {
21
+ if (value === undefined) return DEFAULT_EXEC_ALLOWLIST;
22
+ if (!Array.isArray(value)) throw new FsError("execAllowlist must be an array of executable names.", "invalid");
23
+ const names: string[] = [];
24
+ for (const entry of value) {
25
+ if (typeof entry !== "string") throw new FsError("execAllowlist entries must be strings.", "invalid");
26
+ const name = entry.trim();
27
+ if (!isSafeExecName(name)) throw new FsError(`Invalid exec allowlist entry: ${entry}`, "invalid");
28
+ names.push(name);
29
+ }
30
+ return [...new Set(names)];
31
+ }
32
+
33
+ const Schema = Type.Object(
34
+ {
35
+ command: Type.String({ minLength: 1, description: "Allowlisted executable name, without a path or shell syntax." }),
36
+ args: Type.Optional(Type.Array(Type.String(), { description: "Arguments passed verbatim to the executable." })),
37
+ cwd: Type.Optional(Type.String({ minLength: 1, description: "Working directory inside the project. Default: project root." })),
38
+ stdin: Type.Optional(Type.String({ description: "Text for stdin when the tool is not used in a pipe." })),
39
+ timeoutMs: Type.Optional(
40
+ Type.Integer({ minimum: 100, maximum: 600_000, description: "Timeout in milliseconds. Default: 120000." }),
41
+ ),
42
+ },
43
+ { additionalProperties: false },
44
+ );
45
+
46
+ type Input = Static<typeof Schema>;
47
+
48
+ interface ExecOutcome {
49
+ stdout: Buffer;
50
+ stderr: Buffer;
51
+ exitCode: number;
52
+ signal: NodeJS.Signals | null;
53
+ timedOut: boolean;
54
+ aborted: boolean;
55
+ stdoutTruncated: boolean;
56
+ stderrTruncated: boolean;
57
+ }
58
+
59
+ export const execTool: ToolSpec<Input> = {
60
+ name: "exec",
61
+ description:
62
+ "Run an allowlisted executable without a shell and return its exit code, stdout, and stderr. " +
63
+ "Direct calls return JSON; pipe stages pass raw stdout. Default allowlist: npm, npx, uv, uvx, pip, pip3.",
64
+ schema: Schema,
65
+ pipeable: "filter",
66
+ mutates: true,
67
+ async run(ctx, input, io) {
68
+ const command = input.command.trim();
69
+ if (!isSafeExecName(command)) {
70
+ throw new FsError(`exec command must be a bare executable name: "${input.command}"`, "invalid");
71
+ }
72
+ if (!ctx.execAllowlist.includes(command)) {
73
+ throw new FsError(`exec command is not allowlisted: "${command}"`, "unsupported");
74
+ }
75
+ const args = input.args ?? [];
76
+ if (args.some((arg) => arg.includes("\0"))) {
77
+ throw new FsError("exec arguments must not contain NUL bytes.", "invalid");
78
+ }
79
+
80
+ const requested = input.cwd ?? ".";
81
+ const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
82
+ const stats = await ctx.sandbox.stat(target.full, requested);
83
+ if (!stats.isDirectory()) throw new FsError(`exec cwd is not a directory: "${requested}"`, "not-directory");
84
+ await ctx.permission.assert([{ target, boundary: target.full }]);
85
+ if (ctx.signal.aborted) throw new FsError("exec interrupted.", "interrupted");
86
+
87
+ const outcome = await runProcess(
88
+ ctx,
89
+ command,
90
+ args,
91
+ target.full,
92
+ input.timeoutMs ?? 120_000,
93
+ input.stdin,
94
+ io.stdin,
95
+ );
96
+ const metadata = {
97
+ command,
98
+ args,
99
+ exitCode: outcome.exitCode,
100
+ signal: outcome.signal,
101
+ timedOut: outcome.timedOut,
102
+ aborted: outcome.aborted,
103
+ stdoutTruncated: outcome.stdoutTruncated,
104
+ stderrTruncated: outcome.stderrTruncated,
105
+ };
106
+ if (io.piped === true) {
107
+ return {
108
+ stdout: outcome.stdout,
109
+ stderr: outcome.stderr.toString("utf8"),
110
+ exitCode: outcome.exitCode === 0 ? 0 : 1,
111
+ metadata,
112
+ };
113
+ }
114
+ const body = {
115
+ ...metadata,
116
+ stdout: outcome.stdout.toString("utf8"),
117
+ stderr: outcome.stderr.toString("utf8"),
118
+ };
119
+ return textResult(JSON.stringify(body, null, 2), metadata, outcome.exitCode === 0 ? 0 : 1);
120
+ },
121
+ };
122
+
123
+ function runProcess(
124
+ ctx: RunContext,
125
+ command: string,
126
+ args: string[],
127
+ cwd: string,
128
+ timeoutMs: number,
129
+ input: string | undefined,
130
+ pipe: AsyncIterable<Buffer> | undefined,
131
+ ): Promise<ExecOutcome> {
132
+ return new Promise((resolve, reject) => {
133
+ const feed = input !== undefined || pipe !== undefined;
134
+ const child = spawn(command, args, {
135
+ cwd,
136
+ env: process.env,
137
+ shell: false,
138
+ detached: process.platform !== "win32",
139
+ stdio: [feed ? "pipe" : "ignore", "pipe", "pipe"],
140
+ windowsHide: true,
141
+ });
142
+ const cap = ctx.maxOutputBytes;
143
+ let stdout: Buffer<ArrayBufferLike> = Buffer.alloc(0);
144
+ let stderr: Buffer<ArrayBufferLike> = Buffer.alloc(0);
145
+ let stdoutTruncated = false;
146
+ let stderrTruncated = false;
147
+ let timedOut = false;
148
+ let aborted = false;
149
+ let settled = false;
150
+ let forceTimer: NodeJS.Timeout | undefined;
151
+
152
+ child.stdout?.on("data", (chunk: Buffer) => {
153
+ const next = appendCapped(stdout, chunk, cap);
154
+ stdout = next.data;
155
+ stdoutTruncated ||= next.truncated;
156
+ });
157
+ child.stderr?.on("data", (chunk: Buffer) => {
158
+ const next = appendCapped(stderr, chunk, cap);
159
+ stderr = next.data;
160
+ stderrTruncated ||= next.truncated;
161
+ });
162
+
163
+ const timer = setTimeout(() => {
164
+ timedOut = true;
165
+ killTree(child, "SIGTERM");
166
+ forceTimer = setTimeout(() => killTree(child, "SIGKILL"), 2_000);
167
+ forceTimer.unref();
168
+ }, timeoutMs);
169
+ const onAbort = () => {
170
+ aborted = true;
171
+ killTree(child, "SIGTERM");
172
+ };
173
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
174
+
175
+ const cleanup = () => {
176
+ clearTimeout(timer);
177
+ if (forceTimer) clearTimeout(forceTimer);
178
+ ctx.signal.removeEventListener("abort", onAbort);
179
+ };
180
+ child.on("error", (error) => {
181
+ /* v8 ignore next */
182
+ if (settled) return;
183
+ settled = true;
184
+ cleanup();
185
+ reject(fromErrno(error));
186
+ });
187
+ child.on("close", (code, signal) => {
188
+ if (settled) return;
189
+ settled = true;
190
+ cleanup();
191
+ resolve({
192
+ stdout,
193
+ stderr,
194
+ exitCode: timedOut ? 124 : aborted ? 130 : (code ?? 1),
195
+ signal,
196
+ timedOut,
197
+ aborted,
198
+ stdoutTruncated,
199
+ stderrTruncated,
200
+ });
201
+ });
202
+
203
+ if (feed) void feedStdin(child, input, pipe);
204
+ });
205
+ }
206
+
207
+ async function feedStdin(
208
+ child: ChildProcess,
209
+ input: string | undefined,
210
+ pipe: AsyncIterable<Buffer> | undefined,
211
+ ): Promise<void> {
212
+ const stdin = child.stdin;
213
+ /* v8 ignore next */
214
+ if (!stdin) return;
215
+ try {
216
+ stdin.on("error", () => undefined);
217
+ if (pipe !== undefined) {
218
+ for await (const chunk of pipe) {
219
+ if (!stdin.write(chunk)) await once(stdin, "drain");
220
+ }
221
+ } else {
222
+ stdin.write(input as string);
223
+ }
224
+ stdin.end();
225
+ } catch {
226
+ /* child closed before the write completed */
227
+ }
228
+ }
229
+
230
+ function appendCapped(current: Buffer, chunk: Buffer, cap: number): { data: Buffer; truncated: boolean } {
231
+ if (current.length >= cap) return { data: current, truncated: true };
232
+ const remaining = cap - current.length;
233
+ if (chunk.length <= remaining) return { data: Buffer.concat([current, chunk]), truncated: false };
234
+ return { data: Buffer.concat([current, chunk.subarray(0, remaining)]), truncated: true };
235
+ }
236
+
237
+ function killTree(child: ChildProcess, signal: NodeJS.Signals): void {
238
+ /* v8 ignore next */
239
+ if (!child.pid) return;
240
+ /* v8 ignore next */
241
+ if (process.platform !== "win32") {
242
+ try {
243
+ process.kill(-child.pid, signal);
244
+ return;
245
+ } catch {
246
+ /* fall through to child.kill */
247
+ }
248
+ }
249
+ /* v8 ignore next 5 */
250
+ try {
251
+ child.kill(signal);
252
+ } catch {
253
+ /* already gone */
254
+ }
255
+ }
package/src/tools/pipe.ts CHANGED
@@ -13,6 +13,7 @@ import { catTool } from "./cat.js";
13
13
  import { cpioTool } from "./cpio.js";
14
14
  import { cutTool } from "./cut.js";
15
15
  import { ddTool } from "./dd.js";
16
+ import { execTool } from "./exec.js";
16
17
  import { foldTool } from "./fold.js";
17
18
  import { grepTool } from "./grep.js";
18
19
  import { gunzipTool, gzipTool } from "./gzip.js";
@@ -62,7 +63,7 @@ const REGISTRY: ReadonlyMap<string, AnyTool> = new Map(
62
63
  catTool, headTool, tailTool, grepTool, sedTool, sortTool, uniqTool, cutTool,
63
64
  trTool, wcTool, teeTool, hashTool, gzipTool, gunzipTool, tarTool, zipTool,
64
65
  httpRequestTool, base64Tool, odTool, stringsTool, tacTool, revTool, nlTool,
65
- pasteTool, shufTool, foldTool, ddTool, cpioTool,
66
+ pasteTool, shufTool, foldTool, ddTool, cpioTool, execTool,
66
67
  ].map((tool) => [tool.name, tool]),
67
68
  );
68
69
 
@@ -93,7 +94,7 @@ export const pipeTool: ToolSpec<Input> = {
93
94
  const result = await tool.run(
94
95
  { ...ctx, permission: gate },
95
96
  parsed,
96
- { ...(data === undefined ? {} : { stdin: fromBuffer(data) }) },
97
+ { ...(data === undefined ? {} : { stdin: fromBuffer(data) }), piped: true },
97
98
  ) as ToolResult;
98
99
  stages.push({
99
100
  tool: stage.tool,