opencode-fs-plugin 0.0.0-stage → 1.0.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.
Files changed (51) hide show
  1. package/INSTALL.md +186 -0
  2. package/LICENSE +225 -0
  3. package/README.md +265 -2
  4. package/SPEC.md +45 -0
  5. package/package.json +63 -4
  6. package/skills/filesystem/SKILL.md +153 -0
  7. package/src/core/errors.ts +81 -0
  8. package/src/core/format.ts +100 -0
  9. package/src/core/fsutil.ts +228 -0
  10. package/src/core/mode.ts +107 -0
  11. package/src/core/parallel.ts +76 -0
  12. package/src/core/permissions.ts +134 -0
  13. package/src/core/sandbox.ts +270 -0
  14. package/src/core/schema.ts +16 -0
  15. package/src/core/stream.ts +84 -0
  16. package/src/core/types.ts +51 -0
  17. package/src/index.ts +172 -0
  18. package/src/tools/cat.ts +90 -0
  19. package/src/tools/chmod.ts +93 -0
  20. package/src/tools/cp.ts +136 -0
  21. package/src/tools/cut.ts +93 -0
  22. package/src/tools/df.ts +78 -0
  23. package/src/tools/diff.ts +136 -0
  24. package/src/tools/du.ts +102 -0
  25. package/src/tools/find.ts +181 -0
  26. package/src/tools/grep.ts +205 -0
  27. package/src/tools/gzip.ts +164 -0
  28. package/src/tools/hash.ts +84 -0
  29. package/src/tools/head.ts +78 -0
  30. package/src/tools/ln.ts +98 -0
  31. package/src/tools/ls.ts +178 -0
  32. package/src/tools/mkdir.ts +70 -0
  33. package/src/tools/mktemp.ts +83 -0
  34. package/src/tools/mv.ts +135 -0
  35. package/src/tools/pipe.ts +107 -0
  36. package/src/tools/readlink.ts +90 -0
  37. package/src/tools/rm.ts +91 -0
  38. package/src/tools/rmdir.ts +117 -0
  39. package/src/tools/sed.ts +151 -0
  40. package/src/tools/sort.ts +73 -0
  41. package/src/tools/stat.ts +157 -0
  42. package/src/tools/tail.ts +74 -0
  43. package/src/tools/tar.ts +195 -0
  44. package/src/tools/tee.ts +51 -0
  45. package/src/tools/touch.ts +130 -0
  46. package/src/tools/tr.ts +123 -0
  47. package/src/tools/trash.ts +86 -0
  48. package/src/tools/truncate.ts +96 -0
  49. package/src/tools/uniq.ts +76 -0
  50. package/src/tools/wc.ts +97 -0
  51. package/src/tools/zip.ts +231 -0
@@ -0,0 +1,178 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ import * as fs from "node:fs/promises";
7
+ import * as path from "node:path";
8
+ import { Type, type Static } from "@sinclair/typebox";
9
+ import { FsError, fromErrno } from "../core/errors.js";
10
+ import { formatDate, lookupGroup, lookupUser, modeString, num, typeName } from "../core/fsutil.js";
11
+ import { humanSize } from "../core/format.js";
12
+ import { textResult, type ToolSpec } from "../core/types.js";
13
+
14
+ const Schema = Type.Object(
15
+ {
16
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Paths to list. Default: ['.']." })),
17
+ all: Type.Optional(Type.Boolean({ description: "Include hidden entries and `.`/`..` (`-a`)." })),
18
+ almostAll: Type.Optional(Type.Boolean({ description: "Include hidden entries but not `.`/`..` (`-A`)." })),
19
+ long: Type.Optional(Type.Boolean({ description: "Long listing (`-l`)." })),
20
+ human: Type.Optional(Type.Boolean({ description: "Human-readable sizes (`-h`)." })),
21
+ recursive: Type.Optional(Type.Boolean({ description: "List subdirectories recursively (`-R`)." })),
22
+ directory: Type.Optional(Type.Boolean({ description: "List directories themselves, not their contents (`-d`)." })),
23
+ inode: Type.Optional(Type.Boolean({ description: "Print inode numbers (`-i`)." })),
24
+ classify: Type.Optional(Type.Boolean({ description: "Append file type indicators (`-F`)." })),
25
+ sortBy: Type.Optional(
26
+ Type.Union([Type.Literal("name"), Type.Literal("size"), Type.Literal("time"), Type.Literal("none")], {
27
+ description: "Sort key. Default: name.",
28
+ }),
29
+ ),
30
+ reverse: Type.Optional(Type.Boolean({ description: "Reverse the sort order (`-r`)." })),
31
+ onePerLine: Type.Optional(Type.Boolean({ description: "One entry per line (`-1`)." })),
32
+ },
33
+ { additionalProperties: false },
34
+ );
35
+
36
+ type Input = Static<typeof Schema>;
37
+
38
+ interface Entry {
39
+ name: string;
40
+ full: string;
41
+ stats: Awaited<ReturnType<typeof fs.lstat>>;
42
+ link?: string;
43
+ }
44
+
45
+ export const lsTool: ToolSpec<Input> = {
46
+ name: "ls",
47
+ description:
48
+ "List files and directories with Linux `ls` semantics (`-a`, `-A`, `-l`, `-h`, `-R`, " +
49
+ "`-d`, `-i`, `-F`, `-t`, `-S`, `-r`, `-1`).",
50
+ schema: Schema,
51
+ pipeable: false,
52
+ mutates: false,
53
+ async run(ctx, input) {
54
+ const paths = input.paths ?? ["."];
55
+ const blocks: string[] = [];
56
+ for (const requested of paths) {
57
+ const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
58
+ await ctx.permission.assert([{ target, boundary: target.full }]);
59
+ const stats = await ctx.sandbox.lstat(target.full, requested);
60
+ const entries = await collect(ctx, requested, target.full, stats, input, 0);
61
+ blocks.push(entries.join("\n"));
62
+ }
63
+ return textResult(blocks.filter((block) => block.length > 0).join("\n\n"), { paths });
64
+ },
65
+ };
66
+
67
+ async function collect(
68
+ ctx: Parameters<ToolSpec<Input>["run"]>[0],
69
+ requested: string,
70
+ full: string,
71
+ stats: Awaited<ReturnType<typeof fs.lstat>>,
72
+ input: Input,
73
+ depth: number,
74
+ ): Promise<string[]> {
75
+ const lines: string[] = [];
76
+ const recursive = input.recursive === true;
77
+ if (stats.isDirectory() && input.directory !== true) {
78
+ if (recursive && depth > 0) {
79
+ /* v8 ignore next */
80
+ if (lines.length > 0) lines.push("");
81
+ lines.push(`${requested}:`);
82
+ }
83
+ const entries = await readEntries(full, input);
84
+ if (input.long === true) {
85
+ const total = entries.reduce((sum, entry) => sum + num(entry.stats.blocks), 0);
86
+ lines.push(`total ${total}`);
87
+ }
88
+ lines.push(...(await formatEntries(entries, input)));
89
+ if (recursive) {
90
+ for (const entry of entries) {
91
+ if (entry.name === "." || entry.name === ".." || !entry.stats.isDirectory()) continue;
92
+ lines.push("");
93
+ /* v8 ignore next */
94
+ lines.push(`${requested === "." ? entry.name : `${requested}/${entry.name}`}:`);
95
+ lines.push(...(await collect(ctx, path.join(requested, entry.name), entry.full, entry.stats, input, depth + 1)));
96
+ }
97
+ }
98
+ return lines;
99
+ }
100
+
101
+ /* v8 ignore next */
102
+ const link = stats.isSymbolicLink() ? await fs.readlink(full).catch(() => undefined) : undefined;
103
+ /* v8 ignore next */
104
+ lines.push(await formatEntry({ name: requested, full, stats, ...(link === undefined ? {} : { link }) }, input));
105
+ return lines;
106
+ }
107
+
108
+ async function readEntries(full: string, input: Input): Promise<Entry[]> {
109
+ let names: string[];
110
+ try {
111
+ names = await fs.readdir(full);
112
+ } catch (error) {
113
+ /* v8 ignore next */
114
+ throw fromErrno(error, "access");
115
+ }
116
+ if (input.all === true) names = [".", "..", ...names];
117
+ else if (input.almostAll !== true) names = names.filter((name) => !name.startsWith("."));
118
+ const entries: Entry[] = [];
119
+ for (const name of names) {
120
+ const target = path.join(full, name);
121
+ let stats: Awaited<ReturnType<typeof fs.lstat>>;
122
+ try {
123
+ stats = await fs.lstat(target);
124
+ } catch {
125
+ /* v8 ignore next */
126
+ continue;
127
+ }
128
+ /* v8 ignore next */
129
+ const link = stats.isSymbolicLink() ? await fs.readlink(target).catch(() => undefined) : undefined;
130
+ entries.push({ name, full: target, stats, ...(link === undefined ? {} : { link }) });
131
+ }
132
+ return sortEntries(entries, input);
133
+ }
134
+
135
+ function sortEntries(entries: Entry[], input: Input): Entry[] {
136
+ const sortBy = input.sortBy ?? "name";
137
+ if (sortBy !== "none") {
138
+ entries.sort((a, b) => {
139
+ if (sortBy === "size") return num(a.stats.size) - num(b.stats.size);
140
+ if (sortBy === "time") return num(a.stats.mtimeMs) - num(b.stats.mtimeMs);
141
+ return a.name.localeCompare(b.name);
142
+ });
143
+ }
144
+ if (input.reverse === true) entries.reverse();
145
+ return entries;
146
+ }
147
+
148
+ async function formatEntries(entries: Entry[], input: Input): Promise<string[]> {
149
+ if (input.long === true) {
150
+ return Promise.all(entries.map((entry) => formatEntry(entry, input)));
151
+ }
152
+ return entries.map((entry) => classify(entry.name, entry.stats, input));
153
+ }
154
+
155
+ async function formatEntry(entry: Entry, input: Input): Promise<string> {
156
+ const name = classify(entry.name, entry.stats, input);
157
+ /* v8 ignore next */
158
+ if (input.long !== true) return input.inode === true ? `${entry.stats.ino} ${name}` : name;
159
+ const user = await lookupUser(num(entry.stats.uid));
160
+ const group = await lookupGroup(num(entry.stats.gid));
161
+ const size = input.human === true ? humanSize(num(entry.stats.size)) : String(num(entry.stats.size));
162
+ const link = entry.link === undefined ? "" : ` -> ${entry.link}`;
163
+ /* v8 ignore next */
164
+ const inode = input.inode === true ? `${num(entry.stats.ino)} ` : "";
165
+ return `${inode}${modeString(entry.stats)} ${String(num(entry.stats.nlink)).padStart(2)} ${user} ${group} ${size.padStart(8)} ${formatDate(entry.stats.mtime)} ${name}${link}`;
166
+ }
167
+
168
+ function classify(name: string, stats: Awaited<ReturnType<typeof fs.lstat>>, input: Input): string {
169
+ if (input.classify !== true) return name;
170
+ if (stats.isDirectory()) return `${name}/`;
171
+ if (stats.isSymbolicLink()) return `${name}@`;
172
+ /* v8 ignore next */
173
+ if (stats.isFIFO()) return `${name}|`;
174
+ /* v8 ignore next */
175
+ if (stats.isSocket()) return `${name}=`;
176
+ if ((num(stats.mode) & 0o111) !== 0) return `${name}*`;
177
+ return name;
178
+ }
@@ -0,0 +1,70 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ import * as fs from "node:fs/promises";
7
+ import { Type, type Static } from "@sinclair/typebox";
8
+ import { FsError, fromErrno, isMissing } from "../core/errors.js";
9
+ import { parseMode } from "../core/mode.js";
10
+ import { textResult, type ToolSpec } from "../core/types.js";
11
+
12
+ const Schema = Type.Object(
13
+ {
14
+ path: Type.String({ minLength: 1, description: "Directory path, relative to the project or absolute." }),
15
+ parents: Type.Optional(
16
+ Type.Boolean({ description: "Create missing parents like `mkdir -p`. Default: false." }),
17
+ ),
18
+ mode: Type.Optional(Type.String({ description: "Permission mode, like `755` or `u=rwx,go=rx`." })),
19
+ verbose: Type.Optional(Type.Boolean({ description: "Report the created directory like `mkdir -v`." })),
20
+ },
21
+ { additionalProperties: false },
22
+ );
23
+
24
+ type Input = Static<typeof Schema>;
25
+
26
+ export const mkdirTool: ToolSpec<Input> = {
27
+ name: "mkdir",
28
+ description:
29
+ "Create a directory with Linux `mkdir` semantics (`-p`, `-m`, `-v`). " +
30
+ "Targets outside the project, including through symlinks, require external_directory approval.",
31
+ schema: Schema,
32
+ pipeable: false,
33
+ mutates: true,
34
+ 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
+ ]);
39
+
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
+ }
49
+
50
+ if (exists && isDirectory) {
51
+ if (input.parents === true) {
52
+ return textResult(`Directory already exists (no-op): ${input.path}`, {
53
+ created: false,
54
+ });
55
+ }
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");
59
+
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);
65
+ }
66
+
67
+ const summary = input.verbose === true ? `Directory created: ${input.path}\n` : "";
68
+ return textResult(summary, { created: true, path: input.path, mode: mode ?? null });
69
+ },
70
+ };
@@ -0,0 +1,83 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ import * as fs from "node:fs/promises";
7
+ import * as path from "node:path";
8
+ import { randomBytes } from "node:crypto";
9
+ import { Type, type Static } from "@sinclair/typebox";
10
+ import { FsError, fromErrno } from "../core/errors.js";
11
+ import { textResult, type ToolSpec } from "../core/types.js";
12
+
13
+ const Schema = Type.Object(
14
+ {
15
+ template: Type.Optional(Type.String({ description: "Template containing at least 3 X characters. Default: tmp.XXXXXXXXXX." })),
16
+ directory: Type.Optional(Type.Boolean({ description: "Create a directory instead of a file (`-d`)." })),
17
+ tmpdir: Type.Optional(Type.String({ description: "Directory for the temporary path (`-p`)." })),
18
+ suffix: Type.Optional(Type.String({ description: "Suffix to append." })),
19
+ },
20
+ { additionalProperties: false },
21
+ );
22
+
23
+ type Input = Static<typeof Schema>;
24
+
25
+ export const mktempTool: ToolSpec<Input> = {
26
+ name: "mktemp",
27
+ description:
28
+ "Create a unique temporary file or directory with Linux `mktemp` semantics (`-d`, `-p`, `-t`). " +
29
+ "The default directory is the OS temp directory.",
30
+ schema: Schema,
31
+ pipeable: false,
32
+ mutates: true,
33
+ async run(ctx, input) {
34
+ /* v8 ignore next 2 */
35
+ const dir = path.resolve(input.tmpdir ?? ctx.tmpdir);
36
+ /* v8 ignore next */
37
+ const template = input.template ?? "tmp.XXXXXXXXXX";
38
+ const tail = /X+$/.exec(template)?.[0] ?? "";
39
+ if (tail.length < 3) throw new FsError("template must end with at least three X characters.", "invalid");
40
+ await ctx.permission.assertTrusted([path.join(dir, "*")]);
41
+
42
+ if (input.directory === true) {
43
+ try {
44
+ await fs.mkdir(dir, { recursive: true });
45
+ const created = await fs.mkdtemp(path.join(dir, template.slice(0, -tail.length)));
46
+ const result = input.suffix === undefined ? created : `${created}${input.suffix}`;
47
+ if (input.suffix !== undefined) await fs.rename(created, result);
48
+ return textResult(`${result}\n`, { path: result, directory: true });
49
+ } catch (error) {
50
+ /* v8 ignore next */
51
+ throw fromErrno(error);
52
+ }
53
+ }
54
+
55
+ try {
56
+ await fs.mkdir(dir, { recursive: true });
57
+ } catch (error) {
58
+ /* v8 ignore next */
59
+ throw fromErrno(error);
60
+ }
61
+ for (let attempt = 0; attempt < 20; attempt++) {
62
+ const candidate = path.join(dir, template.slice(0, -tail.length) + randomToken(tail.length));
63
+ try {
64
+ const handle = await fs.open(candidate, "wx", 0o600);
65
+ await handle.close();
66
+ const result = input.suffix === undefined ? candidate : `${candidate}${input.suffix}`;
67
+ if (input.suffix !== undefined) await fs.rename(candidate, result);
68
+ return textResult(`${result}\n`, { path: result, directory: false });
69
+ } catch (error) {
70
+ /* v8 ignore next */
71
+ if ((error as NodeJS.ErrnoException)?.code === "EEXIST") continue;
72
+ /* v8 ignore next */
73
+ throw fromErrno(error);
74
+ }
75
+ }
76
+ /* v8 ignore next */
77
+ throw new FsError("could not create a unique temporary path.", "exists");
78
+ },
79
+ };
80
+
81
+ function randomToken(length: number): string {
82
+ return randomBytes(Math.ceil(length / 2)).toString("hex").slice(0, length);
83
+ }
@@ -0,0 +1,135 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ import * as fs from "node:fs/promises";
7
+ import * as path from "node:path";
8
+ import { Type, type Static } from "@sinclair/typebox";
9
+ import { FsError, fromErrno, isMissing } from "../core/errors.js";
10
+ import { copyTree, ensureParent } from "../core/fsutil.js";
11
+ import { textResult, type ToolSpec } from "../core/types.js";
12
+
13
+ const Schema = Type.Object(
14
+ {
15
+ sources: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
16
+ destination: Type.String({ minLength: 1 }),
17
+ force: Type.Optional(Type.Boolean({ description: "Overwrite existing destinations (`-f`)." })),
18
+ noClobber: Type.Optional(Type.Boolean({ description: "Never overwrite (`-n`)." })),
19
+ update: Type.Optional(Type.Boolean({ description: "Move only when the source is newer (`-u`)." })),
20
+ verbose: Type.Optional(Type.Boolean({ description: "Report moved paths (`-v`)." })),
21
+ },
22
+ { additionalProperties: false },
23
+ );
24
+
25
+ type Input = Static<typeof Schema>;
26
+
27
+ export const mvTool: ToolSpec<Input> = {
28
+ name: "mv",
29
+ description:
30
+ "Move or rename files and directories with Linux `mv` semantics (`-f`, `-n`, `-u`, `-v`). " +
31
+ "Cross-device moves fall back to copy-then-remove.",
32
+ schema: Schema,
33
+ pipeable: false,
34
+ mutates: true,
35
+ async run(ctx, input) {
36
+ const sources = [];
37
+ for (const requested of input.sources) {
38
+ const target = await ctx.sandbox.resolveExisting(requested);
39
+ ctx.sandbox.assertSafeToDelete(target.full);
40
+ const stats = await ctx.sandbox.lstat(target.full, requested);
41
+ sources.push({ requested, target, stats });
42
+ }
43
+
44
+ const destTarget = await ctx.sandbox.resolveForCreate(input.destination);
45
+ let destIsDirectory = false;
46
+ try {
47
+ destIsDirectory = (await fs.lstat(destTarget.full)).isDirectory();
48
+ } catch (error) {
49
+ /* v8 ignore next 2 */
50
+ if (!isMissing(error)) throw fromErrno(error, "access");
51
+ }
52
+ if (sources.length > 1 && !destIsDirectory) {
53
+ throw new FsError("Multiple sources require an existing directory destination.", "not-directory");
54
+ }
55
+
56
+ const jobs = sources.map((source) => ({
57
+ ...source,
58
+ destination:
59
+ destIsDirectory || sources.length > 1
60
+ ? path.join(destTarget.full, path.basename(path.resolve(source.requested)))
61
+ : destTarget.full,
62
+ }));
63
+
64
+ for (const job of jobs) {
65
+ if (job.target.full === job.destination) {
66
+ throw new FsError(`"${job.requested}" and destination are the same file.`, "invalid");
67
+ }
68
+ }
69
+
70
+ const entries = jobs.map((job) => ({
71
+ target: job.target,
72
+ boundary: job.stats.isDirectory() ? job.target.full : path.dirname(job.target.full),
73
+ }));
74
+ for (const job of jobs) {
75
+ const target = await ctx.sandbox.resolveForCreate(job.destination);
76
+ entries.push({ target, boundary: path.dirname(target.full) });
77
+ }
78
+ await ctx.permission.assert(entries);
79
+
80
+ const moved: string[] = [];
81
+ for (const job of jobs) {
82
+ if (input.noClobber === true && (await exists(job.destination))) continue;
83
+ if (input.update === true && (await exists(job.destination))) {
84
+ const destStats = await fs.lstat(job.destination);
85
+ /* v8 ignore next */
86
+ if (destStats.mtimeMs >= job.stats.mtimeMs) continue;
87
+ }
88
+ await ensureParent(job.destination);
89
+ try {
90
+ await fs.rename(job.target.full, job.destination);
91
+ } catch (error) {
92
+ /* v8 ignore next */
93
+ if ((error as NodeJS.ErrnoException)?.code !== "EXDEV") {
94
+ /* v8 ignore next 3 */
95
+ if (input.force === true && (await exists(job.destination))) {
96
+ await fs.rm(job.destination, { recursive: true, force: true });
97
+ await fs.rename(job.target.full, job.destination);
98
+ } else {
99
+ /* v8 ignore next */
100
+ throw fromErrno(error);
101
+ }
102
+ } else {
103
+ await copyTree(job.target.full, job.destination, {
104
+ recursive: true,
105
+ dereference: false,
106
+ preserve: true,
107
+ noClobber: input.noClobber === true,
108
+ update: input.update === true,
109
+ signal: ctx.signal,
110
+ concurrency: ctx.concurrency,
111
+ });
112
+ await fs.rm(job.target.full, { recursive: true, force: true });
113
+ }
114
+ }
115
+ moved.push(job.requested);
116
+ }
117
+
118
+ const output = input.verbose === true
119
+ ? jobs.filter((job) => moved.includes(job.requested)).map((job) => `'${job.requested}' -> '${job.destination}'`).join("\n")
120
+ : "";
121
+ return textResult(output, { moved: moved.length });
122
+ },
123
+ };
124
+
125
+ async function exists(target: string): Promise<boolean> {
126
+ try {
127
+ await fs.lstat(target);
128
+ return true;
129
+ } catch (error) {
130
+ /* v8 ignore next */
131
+ if (isMissing(error)) return false;
132
+ /* v8 ignore next */
133
+ throw fromErrno(error, "access");
134
+ }
135
+ }
@@ -0,0 +1,107 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ import { Type, type Static } from "@sinclair/typebox";
7
+ import { FsError } from "../core/errors.js";
8
+ import { parseSchema } from "../core/schema.js";
9
+ import { writeAll } from "../core/stream.js";
10
+ import { textResult, type ToolSpec, type ToolResult } from "../core/types.js";
11
+ import { catTool } from "./cat.js";
12
+ import { cutTool } from "./cut.js";
13
+ import { grepTool } from "./grep.js";
14
+ import { gunzipTool, gzipTool } from "./gzip.js";
15
+ import { hashTool } from "./hash.js";
16
+ import { headTool } from "./head.js";
17
+ import { sedTool } from "./sed.js";
18
+ import { sortTool } from "./sort.js";
19
+ import { tailTool } from "./tail.js";
20
+ import { teeTool } from "./tee.js";
21
+ import { trTool } from "./tr.js";
22
+ import { uniqTool } from "./uniq.js";
23
+ import { wcTool } from "./wc.js";
24
+
25
+ const Stage = Type.Object(
26
+ {
27
+ tool: Type.String({ minLength: 1, description: "Pipe stage tool name, e.g. cat, grep, sort." }),
28
+ args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
29
+ },
30
+ { additionalProperties: false },
31
+ );
32
+
33
+ const Schema = Type.Object(
34
+ {
35
+ stages: Type.Array(Stage, { minItems: 1, maxItems: 50 }),
36
+ input: Type.Optional(Type.String({ description: "Initial stdin text when the first stage reads from stdin." })),
37
+ output: Type.Optional(Type.String({ description: "Write final stdout to this file, like `> file`." })),
38
+ append: Type.Optional(Type.Boolean({ description: "Append to output instead of overwriting, like `>> file`." })),
39
+ },
40
+ { additionalProperties: false },
41
+ );
42
+
43
+ type Input = Static<typeof Schema>;
44
+ type AnyTool = ToolSpec<any>;
45
+
46
+ const REGISTRY: ReadonlyMap<string, AnyTool> = new Map(
47
+ [catTool, headTool, tailTool, grepTool, sedTool, sortTool, uniqTool, cutTool, trTool, wcTool, teeTool, hashTool, gzipTool, gunzipTool].map(
48
+ (tool) => [tool.name, tool],
49
+ ),
50
+ );
51
+
52
+ export const pipeTool: ToolSpec<Input> = {
53
+ name: "pipe",
54
+ description:
55
+ "Compose fs tools into a Linux-style pipeline. Stages run sequentially; stdin/stdout are buffers; " +
56
+ "only pipeable tools are allowed. `output` and `append` act as a final tee.",
57
+ schema: Schema,
58
+ pipeable: false,
59
+ mutates: true,
60
+ async run(ctx, input) {
61
+ let data: Buffer | undefined = input.input === undefined ? undefined : Buffer.from(input.input, "utf8");
62
+ const stages: Array<{ tool: string; bytesIn: number; bytesOut: number; exitCode: number }> = [];
63
+
64
+ for (let index = 0; index < input.stages.length; index++) {
65
+ const stage = input.stages[index] as Static<typeof Stage>;
66
+ const tool = REGISTRY.get(stage.tool);
67
+ if (tool === undefined) {
68
+ throw new FsError(`Unknown pipe stage: ${stage.tool}`, "unsupported");
69
+ }
70
+ /* v8 ignore next */
71
+ if (index > 0 && data === undefined && tool.pipeable !== "source") {
72
+ throw new FsError(`Pipe stage "${stage.tool}" has no input.`, "invalid");
73
+ }
74
+ const parsed = parseSchema(tool.schema, stage.args ?? {}, `${stage.tool} arguments`);
75
+ const gate = ctx.permissionFor(`fs_${tool.name}`);
76
+ const result = await tool.run(
77
+ { ...ctx, permission: gate },
78
+ parsed,
79
+ { ...(data === undefined ? {} : { stdin: fromBuffer(data) }) },
80
+ ) as ToolResult;
81
+ stages.push({
82
+ tool: stage.tool,
83
+ /* v8 ignore next */
84
+ bytesIn: data?.length ?? 0,
85
+ bytesOut: result.stdout.length,
86
+ /* v8 ignore next */
87
+ exitCode: result.exitCode ?? 0,
88
+ });
89
+ data = result.stdout;
90
+ }
91
+
92
+ if (input.output !== undefined) {
93
+ const target = await ctx.sandbox.resolveForCreate(input.output);
94
+ const gate = ctx.permissionFor("fs_tee");
95
+ await gate.assert([{ target, boundary: target.full }]);
96
+ /* v8 ignore next */
97
+ await writeAll(target.full, data ?? Buffer.alloc(0), input.append === true);
98
+ }
99
+
100
+ /* v8 ignore next */
101
+ return textResult(data?.toString("utf8") ?? "", { stages, output: input.output ?? null });
102
+ },
103
+ };
104
+
105
+ async function* fromBuffer(data: Buffer): AsyncGenerator<Buffer> {
106
+ yield data;
107
+ }
@@ -0,0 +1,90 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ import * as fs from "node:fs/promises";
7
+ import * as path from "node:path";
8
+ import { Type, type Static } from "@sinclair/typebox";
9
+ import { FsError, fromErrno, isMissing } from "../core/errors.js";
10
+ import { textResult, type ToolSpec } from "../core/types.js";
11
+
12
+ const Schema = Type.Object(
13
+ {
14
+ paths: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
15
+ mode: Type.Optional(
16
+ Type.Union(
17
+ [
18
+ Type.Literal("raw"),
19
+ Type.Literal("canonical"),
20
+ Type.Literal("existing"),
21
+ Type.Literal("missing"),
22
+ ],
23
+ { description: "raw, canonical (-f), existing (-e), or missing (-m). Default: raw." },
24
+ ),
25
+ ),
26
+ noNewline: Type.Optional(Type.Boolean({ description: "Do not append a newline (`-n`)." })),
27
+ },
28
+ { additionalProperties: false },
29
+ );
30
+
31
+ type Input = Static<typeof Schema>;
32
+
33
+ export const readlinkTool: ToolSpec<Input> = {
34
+ name: "readlink",
35
+ description:
36
+ "Print symbolic-link targets or canonical paths with Linux `readlink` semantics " +
37
+ "(`-f`, `-e`, `-m`, `-n`).",
38
+ schema: Schema,
39
+ pipeable: false,
40
+ mutates: false,
41
+ async run(ctx, input) {
42
+ const mode = input.mode ?? "raw";
43
+ const results: string[] = [];
44
+ for (const requested of input.paths) {
45
+ const target = mode === "missing"
46
+ ? await ctx.sandbox.resolveForCreate(requested)
47
+ : await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
48
+ await ctx.permission.assert([{ target, boundary: target.full }]);
49
+ results.push(await resolveLink(ctx, requested, target.full, mode));
50
+ }
51
+ const text = results.join(input.noNewline === true ? "" : "\n");
52
+ return textResult(input.noNewline === true ? text : `${text}\n`, { paths: input.paths, mode });
53
+ },
54
+ };
55
+
56
+ async function resolveLink(
57
+ ctx: Parameters<ToolSpec<Input>["run"]>[0],
58
+ requested: string,
59
+ full: string,
60
+ mode: string,
61
+ ): Promise<string> {
62
+ if (mode === "raw") {
63
+ try {
64
+ return await fs.readlink(full);
65
+ } catch (error) {
66
+ /* v8 ignore next */
67
+ if ((error as NodeJS.ErrnoException)?.code === "EINVAL") {
68
+ throw new FsError(`"${requested}" is not a symbolic link.`, "not-file");
69
+ }
70
+ /* v8 ignore next */
71
+ throw fromErrno(error);
72
+ }
73
+ }
74
+ if (mode === "existing") {
75
+ try {
76
+ return await fs.realpath(full);
77
+ } catch (error) {
78
+ /* v8 ignore next */
79
+ if (isMissing(error)) throw new FsError(`Not found: "${requested}"`, "not-found");
80
+ /* v8 ignore next */
81
+ throw fromErrno(error, "access");
82
+ }
83
+ }
84
+ if (mode === "canonical") {
85
+ const parent = await ctx.sandbox.resolveParent(requested);
86
+ return path.join(parent.full, path.basename(full));
87
+ }
88
+ const target = await ctx.sandbox.resolveForCreate(requested);
89
+ return target.full;
90
+ }