opencode-fs-plugin 1.5.2 → 1.6.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/README.md CHANGED
@@ -74,6 +74,13 @@ unit, end-to-end and coverage tests.
74
74
  | HTTP(S) | `fs.http_request` | `url`, `method`, `headers`, `body`, `json`, `output`, `checksum`, `maxBytes`, `timeoutMs`, `failOnError`, `followRedirects`, `maxRedirects` |
75
75
  | shell pipe | `fs.pipe` | `stages`, `input`, `output`, `append` |
76
76
 
77
+ Canonical field names are listed above. Aliases are accepted only where noted:
78
+ `path` for one `paths` element (`stat`, `ls`, `cat`, `find`, `tee`, `grep`,
79
+ `sed`), `source` for `sources` (`cp`, `mv`, `ln`), `expression` for
80
+ `expressions` (`sed`), and `limit` for `maxCount` (`grep`). `fs.mkdir` accepts
81
+ `paths` beside `path`, and `fs.hash` accepts `paths`/`path` beside `files`.
82
+ Prefer the canonical names.
83
+
77
84
  ## Pipe
78
85
 
79
86
  `fs.pipe` joins registered tools through byte buffers. Stages run in order;
@@ -110,6 +117,11 @@ large downloads prefer `fs.http_request({ output })`, which streams to disk.
110
117
 
111
118
  There is no shell, redirection operator, nested pipe, or `find -exec`.
112
119
 
120
+ `fs.pipe` is sequential by design and is not a batch primitive. For independent
121
+ work, fan out with `Promise.all` over `tools.fs.*` (or one multi-path call).
122
+ `fs` domain errors resolve as `ERROR:`/`BLOCKED:` text, so check each result;
123
+ permission denials throw.
124
+
113
125
  ## Performance and concurrency
114
126
 
115
127
  All I/O is asynchronous; the plugin never calls a synchronous `fs` API.
package/SPEC.md CHANGED
@@ -4,6 +4,12 @@ This fork targets Linux and Node 22+. Tool names follow native commands; option
4
4
  fields follow the native long options. The model-facing tools are grouped under
5
5
  the `fs` namespace (`tools.fs.cp`, direct `fs_cp`).
6
6
 
7
+ Aliases are accepted only where noted: `path` for one `paths` element (`stat`,
8
+ `ls`, `cat`, `find`, `tee`, `grep`, `sed`), `source` for `sources` (`cp`, `mv`,
9
+ `ln`), `expression` for `expressions` (`sed`), and `limit` for `maxCount`
10
+ (`grep`). `mkdir` accepts `paths` beside `path`, and `hash` accepts
11
+ `paths`/`path` beside `files`; the canonical names remain preferred.
12
+
7
13
  ## Principles
8
14
 
9
15
  - Every tool is async and uses `fs/promises`; no synchronous filesystem calls.
@@ -111,7 +117,8 @@ These are not implemented:
111
117
  - `sort -k` accepts field/character ranges with modifiers `bdfghiMnrV`.
112
118
  - `tar`/`zip` extraction rejects path traversal and escaping links.
113
119
  - `pipe` passes raw bytes and only accepts registered pipeable stages; `tar` and
114
- `zip` are sink stages.
120
+ `zip` are sink stages. It is sequential and not a batch primitive: independent
121
+ calls fan out with `Promise.all` in `execute`.
115
122
 
116
123
  ## Coverage policy
117
124
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-fs-plugin",
3
- "version": "1.5.2",
3
+ "version": "1.6.1",
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,7 +25,8 @@ 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
- | Batching or loops | `execute` JS loops over `tools.fs.*` |
28
+ | Many independent fs calls | one multi-path call, else `Promise.all` in `execute` |
29
+ | Sequential byte pipeline | `fs.pipe` |
29
30
 
30
31
  Do not duplicate a built-in when it already covers the job. `fs` exists for the
31
32
  operations the built-ins do not cover, and for composable text/archive work.
@@ -73,13 +74,17 @@ Recent parity additions:
73
74
 
74
75
  ## Argument shapes
75
76
 
76
- Use the exact field names; scalar `path` is only valid for `fs.mkdir`. The host
77
- silently drops unknown arguments, so a typo like `path` instead of `paths` makes
78
- the tool run with defaults (often `.`), not fail.
77
+ Use the canonical field names below. Aliases are accepted only where noted:
78
+ `path` for one `paths` element (`fs.stat`, `fs.ls`, `fs.cat`, `fs.find`,
79
+ `fs.tee`, `fs.grep`, `fs.sed`), `source` for `sources` (`fs.cp`, `fs.mv`,
80
+ `fs.ln`), `expression` for `expressions` (`fs.sed`), and `limit` for `maxCount`
81
+ (`fs.grep`). `fs.mkdir` accepts `paths` beside `path`, and `fs.hash` accepts
82
+ `paths`/`path` beside `files`. Other tools take only the canonical name; the
83
+ host drops unknown fields, so a name typo runs with defaults.
79
84
 
80
85
  | Field | Commands |
81
86
  |---|---|
82
- | `path` | `fs.mkdir` |
87
+ | `path` | `fs.mkdir` (canonical; `paths` accepted); alias for one path in `fs.stat`, `fs.ls`, `fs.cat`, `fs.find`, `fs.tee`, `fs.grep`, `fs.sed` |
83
88
  | `sources` + `destination` | `fs.cp`, `fs.mv`, `fs.ln` |
84
89
  | `paths` | `fs.stat`, `fs.ls`, `fs.find`, `fs.rm`, `fs.rmdir`, `fs.touch`, `fs.truncate`, `fs.chmod`, `fs.chown`, `fs.readlink`, `fs.du`, `fs.df`, `fs.cat`, `fs.head`, `fs.tail`, `fs.tee`, `fs.wc`, `fs.sort`, `fs.uniq`, `fs.cut`, `fs.tr`, `fs.grep`, `fs.sed`, `fs.gzip`, `fs.gunzip`, `fs.trash`, `fs.file`, `fs.base64`, `fs.od`, `fs.strings`, `fs.sync`, `fs.mountpoint`, `fs.tac`, `fs.rev`, `fs.nl`, `fs.fold`, `fs.shuf` |
85
90
  | `pids` | `fs.ps`, `fs.kill` |
@@ -96,21 +101,71 @@ the tool run with defaults (often `.`), not fail.
96
101
 
97
102
  ### Common mistakes
98
103
 
99
- - `fs.hash` takes `files`, not `paths`; with neither files nor stdin it fails.
100
- - `fs.mkdir` takes `path`; every other path tool takes `paths`.
101
- - `fs.sed` takes `expressions` (plural) and only `s/.../.../flags`; line ranges
102
- need `head`/`tail` or `pipe`.
103
- - `fs.grep` takes `maxCount`, not `limit`; add `recursive: true` for a directory.
104
+ - `fs.hash` canonical is `files`; `paths` and `path` are accepted aliases.
105
+ - `fs.mkdir` canonical is `path`; `paths` is accepted but cannot be combined.
106
+ - `fs.sed` canonical is `script`/`expressions`; `expression` is accepted. Only
107
+ `s/.../.../flags` is supported; line ranges need `head`/`tail` or `pipe`.
108
+ - `fs.grep` canonical is `maxCount`; `limit` is accepted. Add `recursive: true`
109
+ for a directory.
104
110
  - `fs.cat` and text filters read `paths`; Code Mode has no stdin, so `fs.cat({})`
105
111
  fails. Use `fs.pipe` for stdin.
106
112
  - There is no `fs.write`; use the built-in `write` or `fs.tee({ paths, content })`.
107
113
  - `fs.mktemp` needs a template ending in at least three `X`; use `suffix` for an
108
114
  extension.
109
115
 
116
+ ## Batch independent calls
117
+
118
+ `execute` is a JS runtime. Do not `await` independent fs calls one at a time.
119
+
120
+ 1. **Use the widest native call first.** `cat`, `stat`, `hash`, `ls`, `grep`,
121
+ `tee`, `wc`, `chmod`, `touch`, `rm`, and `trash` take `paths` arrays. Use one
122
+ call when combined output is enough:
123
+
124
+ ```js
125
+ const stats = await tools.fs.stat({ paths: files, format: "%n %s" })
126
+ const sums = await tools.fs.hash({ files })
127
+ ```
128
+
129
+ 2. **Fan out when you need per-item results.** `Promise.all` preserves input
130
+ order:
131
+
132
+ ```js
133
+ const rows = await Promise.all(files.map(async (f) => {
134
+ const text = String(await tools.fs.cat({ paths: [f] }))
135
+ return { f, text, ok: !/^(ERROR|BLOCKED):/.test(text) }
136
+ }))
137
+ ```
138
+
139
+ `fs` domain errors resolve as `ERROR:`/`BLOCKED:` text; they do not reject.
140
+ Permission denials and host validation throw, so use `Promise.allSettled`
141
+ only when those should not cancel the batch.
142
+
143
+ 3. **Bound very large fan-outs.** One tool call per item is expensive; use a
144
+ small worker pool (for example 8) instead of `Promise.all` over thousands:
145
+
146
+ ```js
147
+ async function mapLimit(items, limit, fn) {
148
+ const out = new Array(items.length)
149
+ let next = 0
150
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
151
+ while (next < items.length) {
152
+ const i = next++
153
+ out[i] = await fn(items[i], i)
154
+ }
155
+ }))
156
+ return out
157
+ }
158
+ ```
159
+
160
+ Keep `for (const x of items) { await ... }` only when each step depends on the
161
+ previous result, such as read → transform → write the same file. Use `fs.pipe`
162
+ for a sequential byte chain; use this section for independent work.
163
+
110
164
  ## Pipe
111
165
 
112
- Stages run sequentially and pass bytes. Only pipeable tools are allowed. The
113
- first stage may be a source or a filter; later stages consume stdin.
166
+ `fs.pipe` runs fs tools as a **sequential byte pipeline**: each stage's stdout
167
+ is the next stage's stdin. Use it for filter chains; use the batching pattern
168
+ above for parallel fan-out.
114
169
 
115
170
  ```js
116
171
  await tools.fs.pipe({
@@ -123,17 +178,30 @@ await tools.fs.pipe({
123
178
  })
124
179
  ```
125
180
 
126
- `output` writes the final stream and `append` appends. Stage names are the short
127
- native names (`cat`, `grep`, `sort`), not `fs.cat`. There is no shell,
128
- redirection operator, nested pipe, or `find -exec`. A filter stage needs
129
- `input` or a preceding source stage. Set `grep.noFilename: true` in a pipe when
130
- later stages need bare lines instead of `path:line`.
131
-
132
- New filter stages: `tac`, `rev`, `nl`, `paste`, `shuf`, `fold`, `base64`, `od`,
133
- and `strings`. `dd` and `cpio` are source/sink stages.
181
+ | Field | Meaning |
182
+ |---|---|
183
+ | `stages` | 1–50 `{ tool, args }` entries; names are short (`cat`, not `fs.cat`) |
184
+ | `input` | Initial stdin text when the first stage is a filter |
185
+ | `output` | Write final stdout to a file (final `tee`) |
186
+ | `append` | Append to `output` instead of overwriting |
187
+
188
+ The first stage must be a source (`cat`, `http_request`, `dd`, or a path-reading
189
+ text tool such as `tac`, `rev`, `nl`, `base64`, `od`, `strings`) or receive
190
+ `input`. A filter first (`grep`, `sort`, `head`, `wc`) emits
191
+ `ERROR: no input files and no stdin` as pipeline data. Archive writers (`tar`,
192
+ `zip`, `cpio`) emit nothing downstream, so put them last. `wc` and `hash` also
193
+ emit their result text, so they can end a chain or feed a later stage.
194
+
195
+ Stages exchange whole buffers. Set `maxBytes` on `http_request`; for large
196
+ downloads prefer `fs.http_request({ output })`, which streams to disk. In-memory
197
+ text is allowed:
134
198
 
135
- `http_request` is a source stage. Pipe stages exchange whole buffers, so set
136
- `maxBytes` for large responses; use `output` for real streaming to disk.
199
+ ```js
200
+ await tools.fs.pipe({
201
+ input: "b\na\nb\n",
202
+ stages: [{ tool: "sort", args: { unique: true } }],
203
+ })
204
+ ```
137
205
 
138
206
  ```js
139
207
  await tools.fs.pipe({
@@ -144,6 +212,23 @@ await tools.fs.pipe({
144
212
  })
145
213
  ```
146
214
 
215
+ `output` and `append` assert `fs_tee` on the destination. The result metadata
216
+ lists each stage's `bytesIn`, `bytesOut`, and `exitCode`; use it as the
217
+ verification trail.
218
+
219
+ Common pipe mistakes:
220
+
221
+ - `commands` is not a field; the field is `stages`.
222
+ - A bare `{ tool: "sort", args: {} }` first stage returns
223
+ `ERROR: no input files and no stdin`; add a source stage or `input`.
224
+ - Stage names are `cat`, not `fs.cat`.
225
+ - There is no shell, redirection operator, nested pipe, `find -exec`, or
226
+ `xargs`.
227
+
228
+ Pipeable filters include `head`, `tail`, `grep`, `sed`, `sort`, `uniq`, `cut`,
229
+ `tr`, `tee`, `gzip`, `gunzip`, `tac`, `rev`, `nl`, `paste`, `shuf`, `fold`,
230
+ `base64`, `od`, and `strings`. Unknown stage names fail with `unsupported`.
231
+
147
232
  ## Background jobs
148
233
 
149
234
  Every tool accepts `background: true`. It returns immediately with a job id and
@@ -0,0 +1,46 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ import { FsError } from "./errors.js";
7
+
8
+ /** Accept a singular `path` wherever a tool normally takes `paths`. */
9
+ export function pathsFrom(input: { path?: string; paths?: string[] }): string[] | undefined {
10
+ return input.paths ?? (input.path === undefined ? undefined : [input.path]);
11
+ }
12
+
13
+ export function requiredPaths(input: { path?: string; paths?: string[] }, tool: string): string[] {
14
+ const paths = pathsFrom(input);
15
+ if (paths === undefined || paths.length === 0) {
16
+ throw new FsError(`${tool} needs paths: [...]`, "invalid");
17
+ }
18
+ return paths;
19
+ }
20
+
21
+ /** Accept a singular `source` wherever a tool normally takes `sources`. */
22
+ export function sourcesFrom(input: { source?: string; sources?: string[] }): string[] {
23
+ return input.sources ?? (input.source === undefined ? [] : [input.source]);
24
+ }
25
+
26
+ /** Accept a singular `expression` beside the canonical `expressions` array. */
27
+ export function expressionsFrom(input: { expression?: string; expressions?: string[] }): string[] {
28
+ return input.expressions ?? (input.expression === undefined ? [] : [input.expression]);
29
+ }
30
+
31
+ /** Accept `paths` as an alias for `files`; canonical `files` wins. */
32
+ export function filesFrom(input: { files?: string[]; path?: string; paths?: string[] }): string[] | undefined {
33
+ return input.files ?? pathsFrom(input);
34
+ }
35
+
36
+ /** `mkdir` accepts one `path` or a `paths` array, but not both. */
37
+ export function directoryPaths(input: { path?: string; paths?: string[] }): string[] {
38
+ if (input.path !== undefined && input.paths !== undefined) {
39
+ throw new FsError("mkdir accepts path or paths, not both", "invalid");
40
+ }
41
+ const paths = pathsFrom(input);
42
+ if (paths === undefined || paths.length === 0) {
43
+ throw new FsError("mkdir needs path or paths", "invalid");
44
+ }
45
+ return paths;
46
+ }
package/src/tools/cat.ts CHANGED
@@ -4,12 +4,14 @@
4
4
  */
5
5
 
6
6
  import { Type, type Static } from "@sinclair/typebox";
7
+ import { pathsFrom } from "../core/aliases.js";
7
8
  import { collect, inputStream, lines } from "../core/stream.js";
8
9
  import { textResult, type ToolSpec } from "../core/types.js";
9
10
 
10
11
  const Schema = Type.Object(
11
12
  {
12
13
  paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to concatenate. Omit to read stdin." })),
14
+ path: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `paths`." })),
13
15
  number: Type.Optional(Type.Boolean({ description: "Number all output lines (`-n`)." })),
14
16
  numberNonBlank: Type.Optional(Type.Boolean({ description: "Number only non-blank lines (`-b`)." })),
15
17
  squeezeBlank: Type.Optional(Type.Boolean({ description: "Collapse repeated blank lines (`-s`)." })),
@@ -30,8 +32,9 @@ export const catTool: ToolSpec<Input> = {
30
32
  pipeable: "source",
31
33
  mutates: false,
32
34
  async run(ctx, input, io) {
33
- const paths = await resolvePaths(ctx, input.paths ?? []);
34
- const stream = inputStream(paths.map((entry) => entry.full), io.stdin);
35
+ const paths = pathsFrom(input) ?? [];
36
+ const targets = await resolvePaths(ctx, paths);
37
+ const stream = inputStream(targets.map((entry) => entry.full), io.stdin);
35
38
  if (
36
39
  input.number !== true &&
37
40
  input.numberNonBlank !== true &&
@@ -40,7 +43,7 @@ export const catTool: ToolSpec<Input> = {
40
43
  input.showTabs !== true &&
41
44
  input.showNonPrinting !== true
42
45
  ) {
43
- return { stdout: await collect(stream), exitCode: 0, metadata: { paths: input.paths ?? [] } };
46
+ return { stdout: await collect(stream), exitCode: 0, metadata: { paths } };
44
47
  }
45
48
 
46
49
  const output: string[] = [];
@@ -63,7 +66,7 @@ export const catTool: ToolSpec<Input> = {
63
66
  }
64
67
  output.push(text + (line.newline ? "\n" : ""));
65
68
  }
66
- return textResult(output.join(""), { paths: input.paths ?? [] });
69
+ return textResult(output.join(""), { paths });
67
70
  },
68
71
  };
69
72
 
package/src/tools/cp.ts CHANGED
@@ -6,13 +6,15 @@
6
6
  import * as fs from "node:fs/promises";
7
7
  import * as path from "node:path";
8
8
  import { Type, type Static } from "@sinclair/typebox";
9
+ import { sourcesFrom } from "../core/aliases.js";
9
10
  import { FsError, fromErrno, isMissing } from "../core/errors.js";
10
11
  import { copyTree, isSubpath } from "../core/fsutil.js";
11
12
  import { textResult, type ToolSpec } from "../core/types.js";
12
13
 
13
14
  const Schema = Type.Object(
14
15
  {
15
- sources: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
16
+ sources: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })),
17
+ source: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `sources`." })),
16
18
  destination: Type.String({ minLength: 1 }),
17
19
  recursive: Type.Optional(Type.Boolean({ description: "Copy directories recursively (`-r`, `-R`)." })),
18
20
  archive: Type.Optional(Type.Boolean({ description: "Archive mode (`-a`): recursive, preserve, keep symlinks." })),
@@ -49,8 +51,10 @@ export const cpTool: ToolSpec<Input> = {
49
51
  const dereference = archive ? false : input.dereference !== false;
50
52
  const preserve = archive || input.preserve === true;
51
53
 
54
+ const requestedSources = sourcesFrom(input);
55
+ if (requestedSources.length === 0) throw new FsError("cp needs sources: [...]", "invalid");
52
56
  const sources: Source[] = [];
53
- for (const requested of input.sources) {
57
+ for (const requested of requestedSources) {
54
58
  const target = dereference
55
59
  ? await ctx.sandbox.resolveFollow(requested)
56
60
  : await ctx.sandbox.resolveExisting(requested);
package/src/tools/find.ts CHANGED
@@ -7,6 +7,7 @@ import * as fs from "node:fs/promises";
7
7
  import * as path from "node:path";
8
8
  import picomatch from "picomatch";
9
9
  import { Type, type Static } from "@sinclair/typebox";
10
+ import { pathsFrom } from "../core/aliases.js";
10
11
  import { FsError } from "../core/errors.js";
11
12
  import { lookupGroup, lookupUser, modeString, num, typeName, walkAll } from "../core/fsutil.js";
12
13
  import { textResult, type ToolSpec } from "../core/types.js";
@@ -14,6 +15,7 @@ import { textResult, type ToolSpec } from "../core/types.js";
14
15
  const Schema = Type.Object(
15
16
  {
16
17
  paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Starting paths. Default: ['.']." })),
18
+ path: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `paths`." })),
17
19
  name: Type.Optional(Type.String({ description: "Filename glob (`-name`)." })),
18
20
  iname: Type.Optional(Type.String({ description: "Case-insensitive filename glob (`-iname`)." })),
19
21
  pathPattern: Type.Optional(Type.String({ description: "Path glob (`-path`)." })),
@@ -112,7 +114,7 @@ export const findTool: ToolSpec<Input> = {
112
114
  mutates: false,
113
115
  async run(ctx, input) {
114
116
  /* v8 ignore next */
115
- const paths = input.paths ?? ["."];
117
+ const paths = pathsFrom(input) ?? ["."];
116
118
  const patterns: Patterns = {
117
119
  nameMatch: input.name === undefined ? undefined : picomatch(input.name, { dot: true }),
118
120
  inameMatch: input.iname === undefined ? undefined : picomatch(input.iname, { dot: true, nocase: true }),
package/src/tools/grep.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  import * as fs from "node:fs/promises";
7
7
  import picomatch from "picomatch";
8
8
  import { Type, type Static } from "@sinclair/typebox";
9
+ import { pathsFrom } from "../core/aliases.js";
9
10
  import { FsError, fromErrno } from "../core/errors.js";
10
11
  import { walkAll } from "../core/fsutil.js";
11
12
  import { mapLimit } from "../core/parallel.js";
@@ -16,6 +17,7 @@ const Schema = Type.Object(
16
17
  {
17
18
  pattern: Type.String({ description: "Search pattern." }),
18
19
  paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files or directories. Omit to read stdin." })),
20
+ path: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `paths`." })),
19
21
  recursive: Type.Optional(Type.Boolean({ description: "Search directories recursively (`-r`)." })),
20
22
  include: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Only search matching globs (`--include`)." })),
21
23
  exclude: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Skip matching globs (`--exclude`)." })),
@@ -36,6 +38,7 @@ const Schema = Type.Object(
36
38
  before: Type.Optional(Type.Integer({ minimum: 0, description: "Lines before (`-B`)." })),
37
39
  after: Type.Optional(Type.Integer({ minimum: 0, description: "Lines after (`-A`)." })),
38
40
  maxCount: Type.Optional(Type.Integer({ minimum: 1, description: "Maximum matches per file (`-m`)." })),
41
+ limit: Type.Optional(Type.Integer({ minimum: 1, description: "Alias for `maxCount`." })),
39
42
  noMessages: Type.Optional(Type.Boolean({ description: "Suppress error messages (`-s`)." })),
40
43
  },
41
44
  { additionalProperties: false },
@@ -65,7 +68,7 @@ export const grepTool: ToolSpec<Input> = {
65
68
  if (exclude !== undefined && exclude(file)) return false;
66
69
  return true;
67
70
  };
68
- const paths = input.paths ?? [];
71
+ const paths = pathsFrom(input) ?? [];
69
72
  const targets: Target[] = [];
70
73
  if (paths.length > 0) {
71
74
  for (const requested of paths) {
@@ -168,6 +171,7 @@ function search(
168
171
  const rows = data.toString("utf8").split("\n");
169
172
  /* v8 ignore next */
170
173
  if (rows[rows.length - 1] === "") rows.pop();
174
+ const maxCount = input.maxCount ?? input.limit;
171
175
  const before = input.before ?? input.context ?? 0;
172
176
  const after = input.after ?? input.context ?? 0;
173
177
  const lines: string[] = [];
@@ -182,12 +186,20 @@ function search(
182
186
  matched = true;
183
187
  count++;
184
188
  if (input.filesWithMatches === true && !lines.includes(name)) lines.push(name);
185
- if (input.maxCount !== undefined && count >= input.maxCount) break;
186
- if (input.filesWithMatches === true) continue;
189
+ if (input.filesWithMatches === true) {
190
+ if (maxCount !== undefined && count >= maxCount) break;
191
+ continue;
192
+ }
187
193
  /* v8 ignore next */
188
- if (input.filesWithoutMatch === true) continue;
194
+ if (input.filesWithoutMatch === true) {
195
+ if (maxCount !== undefined && count >= maxCount) break;
196
+ continue;
197
+ }
189
198
  /* v8 ignore next */
190
- if (input.count === true) continue;
199
+ if (input.count === true) {
200
+ if (maxCount !== undefined && count >= maxCount) break;
201
+ continue;
202
+ }
191
203
  if (input.onlyMatching === true) {
192
204
  regex.lastIndex = 0;
193
205
  for (const match of row.matchAll(regex)) {
@@ -207,9 +219,10 @@ function search(
207
219
  lastPrinted = context;
208
220
  }
209
221
  }
222
+ if (maxCount !== undefined && count >= maxCount) break;
210
223
  }
211
224
  /* v8 ignore next */
212
- if (input.count === true) lines.push(`${showName ? `${name}:` : ""}${Math.min(count, input.maxCount ?? count)}`);
225
+ if (input.count === true) lines.push(`${showName ? `${name}:` : ""}${Math.min(count, maxCount ?? count)}`);
213
226
  if (input.filesWithoutMatch === true && !matched) lines.push(name);
214
227
  return { lines, matched };
215
228
  }
package/src/tools/hash.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  import * as fs from "node:fs";
7
7
  import { createHash } from "node:crypto";
8
8
  import { Type, type Static } from "@sinclair/typebox";
9
+ import { filesFrom } from "../core/aliases.js";
9
10
  import { FsError, fromErrno } from "../core/errors.js";
10
11
  import { mapLimit } from "../core/parallel.js";
11
12
  import { textResult, type ToolSpec } from "../core/types.js";
@@ -13,6 +14,8 @@ import { textResult, type ToolSpec } from "../core/types.js";
13
14
  const Schema = Type.Object(
14
15
  {
15
16
  files: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to hash. Omit to hash stdin." })),
17
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Alias for `files`." })),
18
+ path: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `files`." })),
16
19
  algorithm: Type.Optional(
17
20
  Type.Union(
18
21
  [Type.Literal("md5"), Type.Literal("sha1"), Type.Literal("sha256"), Type.Literal("sha512")],
@@ -36,14 +39,15 @@ export const hashTool: ToolSpec<Input> = {
36
39
  mutates: false,
37
40
  async run(ctx, input, io) {
38
41
  const algorithm = input.algorithm ?? "sha256";
39
- if (input.files === undefined || input.files.length === 0) {
40
- if (io.stdin === undefined) throw new FsError("no input files and no stdin.", "invalid");
42
+ const files = filesFrom(input);
43
+ if (files === undefined || files.length === 0) {
44
+ if (io.stdin === undefined) throw new FsError("hash needs files: [...] or stdin.", "invalid");
41
45
  const hash = await hashStream(algorithm, io.stdin);
42
46
  return textResult(`${hash} -\n`, { algorithm, stdin: true });
43
47
  }
44
48
 
45
49
  const targets = [];
46
- for (const requested of input.files) {
50
+ for (const requested of files) {
47
51
  const target = await ctx.sandbox.resolveFollow(requested);
48
52
  targets.push({ requested, target });
49
53
  }
@@ -64,7 +68,7 @@ export const hashTool: ToolSpec<Input> = {
64
68
  },
65
69
  ctx.signal,
66
70
  );
67
- return textResult(results.join("\n") + "\n", { algorithm, files: input.files });
71
+ return textResult(results.join("\n") + "\n", { algorithm, files });
68
72
  },
69
73
  };
70
74
 
package/src/tools/ln.ts CHANGED
@@ -6,12 +6,14 @@
6
6
  import * as fs from "node:fs/promises";
7
7
  import * as path from "node:path";
8
8
  import { Type, type Static } from "@sinclair/typebox";
9
+ import { sourcesFrom } from "../core/aliases.js";
9
10
  import { FsError, fromErrno, isMissing } from "../core/errors.js";
10
11
  import { textResult, type ToolSpec } from "../core/types.js";
11
12
 
12
13
  const Schema = Type.Object(
13
14
  {
14
- sources: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
15
+ sources: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })),
16
+ source: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `sources`." })),
15
17
  destination: Type.String({ minLength: 1, description: "Link path, or an existing directory for multiple sources." }),
16
18
  symbolic: Type.Optional(Type.Boolean({ description: "Create symbolic links (`-s`)." })),
17
19
  force: Type.Optional(Type.Boolean({ description: "Replace existing destinations (`-f`)." })),
@@ -33,6 +35,8 @@ export const lnTool: ToolSpec<Input> = {
33
35
  pipeable: false,
34
36
  mutates: true,
35
37
  async run(ctx, input) {
38
+ const sourcePaths = sourcesFrom(input);
39
+ if (sourcePaths.length === 0) throw new FsError("ln needs sources: [...]", "invalid");
36
40
  const destTarget = await ctx.sandbox.resolveForCreate(input.destination);
37
41
  let destIsDirectory = false;
38
42
  try {
@@ -41,13 +45,13 @@ export const lnTool: ToolSpec<Input> = {
41
45
  /* v8 ignore next 2 */
42
46
  if (!isMissing(error)) throw fromErrno(error, "access");
43
47
  }
44
- if (input.sources.length > 1 && !destIsDirectory) {
48
+ if (sourcePaths.length > 1 && !destIsDirectory) {
45
49
  throw new FsError("Multiple sources require an existing directory destination.", "not-directory");
46
50
  }
47
51
 
48
52
  const created: string[] = [];
49
- for (const requested of input.sources) {
50
- const link = destIsDirectory || input.sources.length > 1
53
+ for (const requested of sourcePaths) {
54
+ const link = destIsDirectory || sourcePaths.length > 1
51
55
  ? path.join(destTarget.full, path.basename(path.resolve(requested)))
52
56
  : destTarget.full;
53
57
  const linkTarget = await ctx.sandbox.resolveForCreate(link);
package/src/tools/ls.ts CHANGED
@@ -7,6 +7,7 @@ import * as fs from "node:fs/promises";
7
7
  import * as path from "node:path";
8
8
  import picomatch from "picomatch";
9
9
  import { Type, type Static } from "@sinclair/typebox";
10
+ import { pathsFrom } from "../core/aliases.js";
10
11
  import { fromErrno } from "../core/errors.js";
11
12
  import { formatDate, lookupGroup, lookupUser, modeString, num } from "../core/fsutil.js";
12
13
  import { humanSize } from "../core/format.js";
@@ -16,6 +17,7 @@ import { textResult, type ToolSpec } from "../core/types.js";
16
17
  const Schema = Type.Object(
17
18
  {
18
19
  paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Paths to list. Default: ['.']." })),
20
+ path: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `paths`." })),
19
21
  all: Type.Optional(Type.Boolean({ description: "Include hidden entries and `.`/`..` (`-a`)." })),
20
22
  almostAll: Type.Optional(Type.Boolean({ description: "Include hidden entries but not `.`/`..` (`-A`)." })),
21
23
  long: Type.Optional(Type.Boolean({ description: "Long listing (`-l`)." })),
@@ -72,7 +74,7 @@ export const lsTool: ToolSpec<Input> = {
72
74
  pipeable: false,
73
75
  mutates: false,
74
76
  async run(ctx, input) {
75
- const paths = input.paths ?? ["."];
77
+ const paths = pathsFrom(input) ?? ["."];
76
78
  const blocks: string[] = [];
77
79
  for (const requested of paths) {
78
80
  const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
@@ -5,13 +5,20 @@
5
5
 
6
6
  import * as fs from "node:fs/promises";
7
7
  import { Type, type Static } from "@sinclair/typebox";
8
+ import { directoryPaths } from "../core/aliases.js";
8
9
  import { FsError, fromErrno, isMissing } from "../core/errors.js";
9
10
  import { parseMode } from "../core/mode.js";
10
11
  import { textResult, type ToolSpec } from "../core/types.js";
11
12
 
12
13
  const Schema = Type.Object(
13
14
  {
14
- path: Type.String({ minLength: 1, description: "Directory path, relative to the project or absolute." }),
15
+ path: Type.Optional(Type.String({ minLength: 1, description: "Directory path, relative to the project or absolute." })),
16
+ paths: Type.Optional(
17
+ Type.Array(Type.String({ minLength: 1 }), {
18
+ minItems: 1,
19
+ description: "Alias for one or more `path` values; do not combine with `path`.",
20
+ }),
21
+ ),
15
22
  parents: Type.Optional(
16
23
  Type.Boolean({ description: "Create missing parents like `mkdir -p`. Default: false." }),
17
24
  ),
@@ -32,39 +39,49 @@ export const mkdirTool: ToolSpec<Input> = {
32
39
  pipeable: false,
33
40
  mutates: true,
34
41
  async run(ctx, input) {
35
- const target = await ctx.sandbox.resolveForCreate(input.path);
36
- await ctx.permission.assert([
37
- { target, boundary: target.full, resource: ctx.sandbox.resource(target.full) },
38
- ]);
42
+ const directories = directoryPaths(input);
43
+ const mode = input.mode === undefined ? undefined : parseMode(input.mode, 0o777, true);
44
+ const summaries: string[] = [];
45
+ let createdAny = false;
46
+ for (const requested of directories) {
47
+ const target = await ctx.sandbox.resolveForCreate(requested);
48
+ await ctx.permission.assert([
49
+ { target, boundary: target.full, resource: ctx.sandbox.resource(target.full) },
50
+ ]);
39
51
 
40
- let exists = false;
41
- let isDirectory = false;
42
- try {
43
- isDirectory = (await fs.lstat(target.full)).isDirectory();
44
- exists = true;
45
- } catch (error) {
46
- /* v8 ignore next */
47
- if (!isMissing(error)) throw fromErrno(error, "access");
48
- }
52
+ let exists = false;
53
+ let isDirectory = false;
54
+ try {
55
+ isDirectory = (await fs.lstat(target.full)).isDirectory();
56
+ exists = true;
57
+ } catch (error) {
58
+ /* v8 ignore next */
59
+ if (!isMissing(error)) throw fromErrno(error, "access");
60
+ }
49
61
 
50
- if (exists && isDirectory) {
51
- if (input.parents === true) {
52
- return textResult(`Directory already exists (no-op): ${input.path}`, {
53
- created: false,
54
- });
62
+ if (exists && isDirectory) {
63
+ if (input.parents === true) {
64
+ summaries.push(`Directory already exists (no-op): ${requested}\n`);
65
+ continue;
66
+ }
67
+ throw new FsError(`Already exists: "${requested}"`, "exists");
55
68
  }
56
- throw new FsError(`Already exists: "${input.path}"`, "exists");
57
- }
58
- if (exists) throw new FsError(`Already exists and is not a directory: "${input.path}"`, "exists");
69
+ if (exists) throw new FsError(`Already exists and is not a directory: "${requested}"`, "exists");
59
70
 
60
- const mode = input.mode === undefined ? undefined : parseMode(input.mode, 0o777, true);
61
- try {
62
- await fs.mkdir(target.full, { recursive: input.parents === true, ...(mode === undefined ? {} : { mode }) });
63
- } catch (error) {
64
- throw fromErrno(error);
71
+ try {
72
+ await fs.mkdir(target.full, { recursive: input.parents === true, ...(mode === undefined ? {} : { mode }) });
73
+ } catch (error) {
74
+ throw fromErrno(error);
75
+ }
76
+ createdAny = true;
77
+ if (input.verbose === true) summaries.push(`Directory created: ${requested}\n`);
65
78
  }
66
79
 
67
- const summary = input.verbose === true ? `Directory created: ${input.path}\n` : "";
68
- return textResult(summary, { created: true, path: input.path, mode: mode ?? null });
80
+ return textResult(summaries.join(""), {
81
+ created: createdAny,
82
+ ...(directories.length === 1 ? { path: directories[0] } : {}),
83
+ paths: directories,
84
+ mode: mode ?? null,
85
+ });
69
86
  },
70
87
  };
package/src/tools/mv.ts CHANGED
@@ -6,13 +6,15 @@
6
6
  import * as fs from "node:fs/promises";
7
7
  import * as path from "node:path";
8
8
  import { Type, type Static } from "@sinclair/typebox";
9
+ import { sourcesFrom } from "../core/aliases.js";
9
10
  import { FsError, fromErrno, isMissing } from "../core/errors.js";
10
11
  import { copyTree, ensureParent } from "../core/fsutil.js";
11
12
  import { textResult, type ToolSpec } from "../core/types.js";
12
13
 
13
14
  const Schema = Type.Object(
14
15
  {
15
- sources: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
16
+ sources: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })),
17
+ source: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `sources`." })),
16
18
  destination: Type.String({ minLength: 1 }),
17
19
  force: Type.Optional(Type.Boolean({ description: "Overwrite existing destinations (`-f`)." })),
18
20
  noClobber: Type.Optional(Type.Boolean({ description: "Never overwrite (`-n`)." })),
@@ -33,8 +35,10 @@ export const mvTool: ToolSpec<Input> = {
33
35
  pipeable: false,
34
36
  mutates: true,
35
37
  async run(ctx, input) {
38
+ const requestedSources = sourcesFrom(input);
39
+ if (requestedSources.length === 0) throw new FsError("mv needs sources: [...]", "invalid");
36
40
  const sources = [];
37
- for (const requested of input.sources) {
41
+ for (const requested of requestedSources) {
38
42
  const target = await ctx.sandbox.resolveExisting(requested);
39
43
  ctx.sandbox.assertSafeToDelete(target.full);
40
44
  const stats = await ctx.sandbox.lstat(target.full, requested);
package/src/tools/sed.ts CHANGED
@@ -7,15 +7,18 @@ import * as fs from "node:fs/promises";
7
7
  import * as path from "node:path";
8
8
  import { randomBytes } from "node:crypto";
9
9
  import { Type, type Static } from "@sinclair/typebox";
10
+ import { expressionsFrom, pathsFrom } from "../core/aliases.js";
10
11
  import { FsError, fromErrno } from "../core/errors.js";
11
12
  import { inputStream, writeAll } from "../core/stream.js";
12
13
  import { textResult, type ToolSpec } from "../core/types.js";
13
14
 
14
15
  const Schema = Type.Object(
15
16
  {
16
- script: Type.String({ description: "sed substitution, e.g. s/old/new/g." }),
17
+ script: Type.Optional(Type.String({ description: "sed substitution, e.g. s/old/new/g." })),
18
+ expression: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `expressions`." })),
17
19
  expressions: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Additional -e expressions." })),
18
20
  paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to process. Omit to read stdin." })),
21
+ path: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `paths`." })),
19
22
  inPlace: Type.Optional(Type.Boolean({ description: "Edit files in place (`-i`)." })),
20
23
  extendedRegexp: Type.Optional(Type.Boolean({ description: "Use extended regular expressions (`-E`)." })),
21
24
  quiet: Type.Optional(Type.Boolean({ description: "Suppress automatic output (`-n`)." })),
@@ -41,9 +44,12 @@ export const sedTool: ToolSpec<Input> = {
41
44
  pipeable: "filter",
42
45
  mutates: false,
43
46
  async run(ctx, input, io) {
44
- const scripts = [input.script, ...(input.expressions ?? [])];
47
+ const scripts = [input.script, ...expressionsFrom(input)].filter(
48
+ (value): value is string => value !== undefined,
49
+ );
50
+ if (scripts.length === 0) throw new FsError("sed needs script, expression, or expressions", "invalid");
45
51
  const substitutions = scripts.map((script) => parseSubstitution(script, input.extendedRegexp === true));
46
- const paths = input.paths ?? [];
52
+ const paths = pathsFrom(input) ?? [];
47
53
  if (input.inPlace === true && paths.length === 0) {
48
54
  throw new FsError("in-place editing requires paths.", "invalid");
49
55
  }
package/src/tools/stat.ts CHANGED
@@ -5,13 +5,15 @@
5
5
 
6
6
  import * as fs from "node:fs/promises";
7
7
  import { Type, type Static } from "@sinclair/typebox";
8
+ import { requiredPaths } from "../core/aliases.js";
8
9
  import { fromErrno } from "../core/errors.js";
9
10
  import { lookupGroup, lookupUser, modeString, num, typeName } from "../core/fsutil.js";
10
11
  import { textResult, type ToolSpec } from "../core/types.js";
11
12
 
12
13
  const Schema = Type.Object(
13
14
  {
14
- paths: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
15
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })),
16
+ path: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `paths`." })),
15
17
  follow: Type.Optional(Type.Boolean({ description: "Follow symlinks (`-L`)." })),
16
18
  format: Type.Optional(Type.String({ description: "printf-style format string (`-c`, `--printf`)." })),
17
19
  terse: Type.Optional(Type.Boolean({ description: "Terse single-line output (`-t`)." })),
@@ -33,7 +35,8 @@ export const statTool: ToolSpec<Input> = {
33
35
  mutates: false,
34
36
  async run(ctx, input) {
35
37
  const blocks: string[] = [];
36
- for (const requested of input.paths) {
38
+ const paths = requiredPaths(input, "stat");
39
+ for (const requested of paths) {
37
40
  const target = input.follow === true
38
41
  ? await ctx.sandbox.resolveFollow(requested)
39
42
  : await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
@@ -55,7 +58,7 @@ export const statTool: ToolSpec<Input> = {
55
58
  : await customFormat(input.format, requested, target.full, stats, link),
56
59
  );
57
60
  }
58
- return textResult(blocks.join("\n"), { paths: input.paths });
61
+ return textResult(blocks.join("\n"), { paths });
59
62
  },
60
63
  };
61
64
 
package/src/tools/tee.ts CHANGED
@@ -4,13 +4,15 @@
4
4
  */
5
5
 
6
6
  import { Type, type Static } from "@sinclair/typebox";
7
+ import { pathsFrom } from "../core/aliases.js";
7
8
  import { FsError } from "../core/errors.js";
8
9
  import { collect, writeAll } from "../core/stream.js";
9
10
  import type { ToolSpec } from "../core/types.js";
10
11
 
11
12
  const Schema = Type.Object(
12
13
  {
13
- paths: Type.Array(Type.String({ minLength: 1 }), { description: "Files to write. Empty means pass through only." }),
14
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to write. Empty means pass through only." })),
15
+ path: Type.Optional(Type.String({ minLength: 1, description: "Alias for a single element of `paths`." })),
14
16
  append: Type.Optional(Type.Boolean({ description: "Append instead of overwriting (`-a`)." })),
15
17
  content: Type.Optional(Type.String({ description: "Text to write when no stdin is available." })),
16
18
  },
@@ -28,7 +30,8 @@ export const teeTool: ToolSpec<Input> = {
28
30
  pipeable: "filter",
29
31
  mutates: true,
30
32
  async run(ctx, input, io) {
31
- if (input.paths.length === 0 && input.content === undefined && io.stdin === undefined) {
33
+ const paths = pathsFrom(input) ?? [];
34
+ if (paths.length === 0 && input.content === undefined && io.stdin === undefined) {
32
35
  throw new FsError("tee needs files, content, or stdin.", "invalid");
33
36
  }
34
37
  const data = input.content !== undefined
@@ -36,7 +39,7 @@ export const teeTool: ToolSpec<Input> = {
36
39
  : await collect(io.stdin as AsyncIterable<Buffer>);
37
40
 
38
41
  const targets = [];
39
- for (const requested of input.paths) {
42
+ for (const requested of paths) {
40
43
  const target = await ctx.sandbox.resolveForCreate(requested);
41
44
  targets.push({ requested, target });
42
45
  }
@@ -44,7 +47,7 @@ export const teeTool: ToolSpec<Input> = {
44
47
  for (const target of targets) {
45
48
  await writeAll(target.target.full, data, input.append === true);
46
49
  }
47
- return { stdout: data, exitCode: 0, metadata: { files: input.paths, append: input.append === true } };
50
+ return { stdout: data, exitCode: 0, metadata: { files: paths, append: input.append === true } };
48
51
  },
49
52
  };
50
53