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,205 @@
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 picomatch from "picomatch";
8
+ import { Type, type Static } from "@sinclair/typebox";
9
+ import { FsError, fromErrno } from "../core/errors.js";
10
+ import { walk } from "../core/fsutil.js";
11
+ import { collect, inputStream, lines } from "../core/stream.js";
12
+ import { textResult, type ToolSpec } from "../core/types.js";
13
+
14
+ const Schema = Type.Object(
15
+ {
16
+ pattern: Type.String({ description: "Search pattern." }),
17
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files or directories. Omit to read stdin." })),
18
+ recursive: Type.Optional(Type.Boolean({ description: "Search directories recursively (`-r`)." })),
19
+ include: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Only search matching globs (`--include`)." })),
20
+ exclude: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Skip matching globs (`--exclude`)." })),
21
+ ignoreCase: Type.Optional(Type.Boolean({ description: "Case-insensitive search (`-i`)." })),
22
+ invert: Type.Optional(Type.Boolean({ description: "Select non-matching lines (`-v`)." })),
23
+ lineNumbers: Type.Optional(Type.Boolean({ description: "Print line numbers (`-n`)." })),
24
+ withFilename: Type.Optional(Type.Boolean({ description: "Prefix matches with filenames (`-H`)." })),
25
+ noFilename: Type.Optional(Type.Boolean({ description: "Never print filenames (`-h`)." })),
26
+ filesWithMatches: Type.Optional(Type.Boolean({ description: "Only print matching filenames (`-l`)." })),
27
+ filesWithoutMatch: Type.Optional(Type.Boolean({ description: "Only print non-matching filenames (`-L`)." })),
28
+ count: Type.Optional(Type.Boolean({ description: "Print match counts (`-c`)." })),
29
+ onlyMatching: Type.Optional(Type.Boolean({ description: "Print only the matching parts (`-o`)." })),
30
+ word: Type.Optional(Type.Boolean({ description: "Match whole words (`-w`)." })),
31
+ line: Type.Optional(Type.Boolean({ description: "Match whole lines (`-x`)." })),
32
+ fixed: Type.Optional(Type.Boolean({ description: "Treat the pattern as literal text (`-F`)." })),
33
+ extended: Type.Optional(Type.Boolean({ description: "Extended regular expressions (`-E`)." })),
34
+ context: Type.Optional(Type.Integer({ minimum: 0, description: "Lines of context (`-C`)." })),
35
+ before: Type.Optional(Type.Integer({ minimum: 0, description: "Lines before (`-B`)." })),
36
+ after: Type.Optional(Type.Integer({ minimum: 0, description: "Lines after (`-A`)." })),
37
+ maxCount: Type.Optional(Type.Integer({ minimum: 1, description: "Maximum matches per file (`-m`)." })),
38
+ noMessages: Type.Optional(Type.Boolean({ description: "Suppress error messages (`-s`)." })),
39
+ },
40
+ { additionalProperties: false },
41
+ );
42
+
43
+ type Input = Static<typeof Schema>;
44
+
45
+ interface Target {
46
+ requested: string;
47
+ full: string;
48
+ }
49
+
50
+ export const grepTool: ToolSpec<Input> = {
51
+ name: "grep",
52
+ description:
53
+ "Search file contents with Linux `grep` semantics (`-i`, `-v`, `-n`, `-H`, `-h`, `-l`, `-L`, " +
54
+ "`-c`, `-o`, `-w`, `-x`, `-F`, `-r`, `-A/-B/-C`, `--include`, `--exclude`).",
55
+ schema: Schema,
56
+ pipeable: "filter",
57
+ mutates: false,
58
+ async run(ctx, input, io) {
59
+ const regex = buildRegex(input);
60
+ const paths = input.paths ?? [];
61
+ const targets: Target[] = [];
62
+ if (paths.length > 0) {
63
+ for (const requested of paths) {
64
+ let target;
65
+ try {
66
+ target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
67
+ } catch (error) {
68
+ /* v8 ignore next 3 */
69
+ if (input.noMessages === true) continue;
70
+ /* v8 ignore next */
71
+ throw error;
72
+ }
73
+ await ctx.permission.assert([{ target, boundary: target.full }]);
74
+ const stats = await ctx.sandbox.lstat(target.full, requested);
75
+ if (stats.isDirectory()) {
76
+ if (input.recursive !== true) {
77
+ throw new FsError(`"${requested}" is a directory; recursive is required.`, "not-file");
78
+ }
79
+ for await (const entry of walk(target.full, {
80
+ recursive: true,
81
+ includeHidden: true,
82
+ signal: ctx.signal,
83
+ })) {
84
+ /* v8 ignore next */
85
+ if (!entry.stats.isFile()) continue;
86
+ const resource = entry.path;
87
+ if (!included(resource, input)) continue;
88
+ targets.push({ requested: resource, full: entry.path });
89
+ }
90
+ /* v8 ignore next */
91
+ } else if (included(target.full, input)) {
92
+ targets.push({ requested, full: target.full });
93
+ }
94
+ }
95
+ }
96
+
97
+ const output: string[] = [];
98
+ let matchedAny = false;
99
+ if (paths.length > 0 && targets.length === 0) {
100
+ return textResult("", { matched: false, files: 0 }, 1);
101
+ }
102
+ if (targets.length === 0) {
103
+ const data = await collect(await inputStream([], io.stdin));
104
+ const result = search("(standard input)", data, regex, input, false);
105
+ output.push(...result.lines);
106
+ matchedAny = result.matched;
107
+ } else {
108
+ for (const target of targets) {
109
+ let data: Buffer;
110
+ try {
111
+ data = await fs.readFile(target.full);
112
+ } catch (error) {
113
+ /* v8 ignore next 3 */
114
+ if (input.noMessages === true) continue;
115
+ /* v8 ignore next */
116
+ throw fromErrno(error);
117
+ }
118
+ const showName = input.noFilename !== true && (input.withFilename === true || targets.length > 1 || input.recursive === true);
119
+ const result = search(target.requested, data, regex, input, showName);
120
+ output.push(...result.lines);
121
+ matchedAny ||= result.matched;
122
+ }
123
+ }
124
+ return textResult(output.map((line) => `${line}\n`).join(""), { matched: matchedAny, files: targets.length }, matchedAny ? 0 : 1);
125
+ },
126
+ };
127
+
128
+ function buildRegex(input: Input): RegExp {
129
+ let pattern = input.fixed === true ? input.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : input.pattern;
130
+ if (input.word === true) pattern = `\\b(?:${pattern})\\b`;
131
+ if (input.line === true) pattern = `^(?:${pattern})$`;
132
+ try {
133
+ return new RegExp(pattern, `${input.ignoreCase === true ? "i" : ""}${input.onlyMatching === true ? "g" : ""}`);
134
+ } catch (error) {
135
+ throw new FsError(`Invalid pattern: ${(error as Error).message}`, "invalid");
136
+ }
137
+ }
138
+
139
+ function included(file: string, input: Input): boolean {
140
+ const include = input.include?.length ? picomatch(input.include, { dot: true, basename: true }) : undefined;
141
+ const exclude = input.exclude?.length ? picomatch(input.exclude, { dot: true, basename: true }) : undefined;
142
+ if (include !== undefined && !include(file)) return false;
143
+ if (exclude !== undefined && exclude(file)) return false;
144
+ return true;
145
+ }
146
+
147
+ function search(
148
+ name: string,
149
+ data: Buffer,
150
+ regex: RegExp,
151
+ input: Input,
152
+ showName: boolean,
153
+ ): { lines: string[]; matched: boolean } {
154
+ if (data.includes(0)) {
155
+ /* v8 ignore next */
156
+ return { lines: regex.test(data.toString("utf8")) ? [`Binary file ${name} matches`] : [], matched: regex.test(data.toString("utf8")) };
157
+ }
158
+ const rows = data.toString("utf8").split("\n");
159
+ /* v8 ignore next */
160
+ if (rows[rows.length - 1] === "") rows.pop();
161
+ const before = input.before ?? input.context ?? 0;
162
+ const after = input.after ?? input.context ?? 0;
163
+ const lines: string[] = [];
164
+ let matched = false;
165
+ let count = 0;
166
+ let lastPrinted = -1;
167
+ for (let index = 0; index < rows.length; index++) {
168
+ const row = rows[index] as string;
169
+ regex.lastIndex = 0;
170
+ const hit = input.invert === true ? !regex.test(row) : regex.test(row);
171
+ if (!hit) continue;
172
+ matched = true;
173
+ count++;
174
+ if (input.filesWithMatches === true && !lines.includes(name)) lines.push(name);
175
+ if (input.maxCount !== undefined && count >= input.maxCount) break;
176
+ if (input.filesWithMatches === true) continue;
177
+ /* v8 ignore next */
178
+ if (input.filesWithoutMatch === true) continue;
179
+ /* v8 ignore next */
180
+ if (input.count === true) continue;
181
+ if (input.onlyMatching === true) {
182
+ regex.lastIndex = 0;
183
+ for (const match of row.matchAll(regex)) {
184
+ /* v8 ignore next */
185
+ lines.push(`${showName ? `${name}:` : ""}${input.lineNumbers === true ? `${index + 1}:` : ""}${match[0]}`);
186
+ }
187
+ } else {
188
+ const start = Math.max(0, index - before);
189
+ const end = Math.min(rows.length - 1, index + after);
190
+ for (let context = start; context <= end; context++) {
191
+ /* v8 ignore next */
192
+ if (context <= lastPrinted) continue;
193
+ const separator = context === index ? ":" : "-";
194
+ const prefix = showName ? `${name}${separator}` : "";
195
+ const lineNumber = input.lineNumbers === true ? `${context + 1}${separator}` : "";
196
+ lines.push(`${prefix}${lineNumber}${rows[context]}`);
197
+ lastPrinted = context;
198
+ }
199
+ }
200
+ }
201
+ /* v8 ignore next */
202
+ if (input.count === true) lines.push(`${showName ? `${name}:` : ""}${Math.min(count, input.maxCount ?? count)}`);
203
+ if (input.filesWithoutMatch === true && !matched) lines.push(name);
204
+ return { lines, matched };
205
+ }
@@ -0,0 +1,164 @@
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 { gzip as gzipBuffer, gunzip as gunzipBuffer } from "node:zlib";
8
+ import { promisify } from "node:util";
9
+ import { Type, type Static } from "@sinclair/typebox";
10
+ import { FsError, fromErrno } from "../core/errors.js";
11
+ import { mapLimit } from "../core/parallel.js";
12
+ import { collect } from "../core/stream.js";
13
+ import { textResult, type ToolSpec } from "../core/types.js";
14
+
15
+ const gzipAsync = promisify(gzipBuffer);
16
+ const gunzipAsync = promisify(gunzipBuffer);
17
+
18
+ const GzipSchema = Type.Object(
19
+ {
20
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to compress. Omit to read stdin." })),
21
+ keep: Type.Optional(Type.Boolean({ description: "Keep the input file (`-k`)." })),
22
+ force: Type.Optional(Type.Boolean({ description: "Overwrite existing output (`-f`)." })),
23
+ stdout: Type.Optional(Type.Boolean({ description: "Write compressed data to stdout (`-c`)." })),
24
+ level: Type.Optional(Type.Integer({ minimum: 0, maximum: 9, description: "Compression level (`-1`..`-9`)." })),
25
+ },
26
+ { additionalProperties: false },
27
+ );
28
+
29
+ const GunzipSchema = Type.Object(
30
+ {
31
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to decompress. Omit to read stdin." })),
32
+ keep: Type.Optional(Type.Boolean({ description: "Keep the input file (`-k`)." })),
33
+ force: Type.Optional(Type.Boolean({ description: "Overwrite existing output (`-f`)." })),
34
+ stdout: Type.Optional(Type.Boolean({ description: "Write decompressed data to stdout (`-c`)." })),
35
+ suffix: Type.Optional(Type.String({ description: "Input suffix. Default: .gz." })),
36
+ },
37
+ { additionalProperties: false },
38
+ );
39
+
40
+ type GzipInput = Static<typeof GzipSchema>;
41
+ type GunzipInput = Static<typeof GunzipSchema>;
42
+
43
+ export const gzipTool: ToolSpec<GzipInput> = {
44
+ name: "gzip",
45
+ description:
46
+ "Compress files or stdin with gzip semantics (`-k`, `-f`, `-c`, `-1`..`-9`). " +
47
+ "File mode writes `<name>.gz` and removes the source unless keep is true.",
48
+ schema: GzipSchema,
49
+ pipeable: "filter",
50
+ mutates: true,
51
+ async run(ctx, input, io) {
52
+ if (input.paths === undefined || input.paths.length === 0) {
53
+ if (io.stdin === undefined) throw new FsError("no input files and no stdin.", "invalid");
54
+ const compressed = await gzipAsync(await collect(io.stdin), { level: input.level ?? 6 });
55
+ return { stdout: compressed, exitCode: 0, metadata: { stdin: true } };
56
+ }
57
+ const targets = [];
58
+ for (const requested of input.paths) {
59
+ const source = await ctx.sandbox.resolveFollow(requested);
60
+ const destination = await ctx.sandbox.resolveForCreate(input.stdout === true ? requested : `${requested}.gz`);
61
+ targets.push({ requested, source, destination });
62
+ }
63
+ await ctx.permission.assert(
64
+ targets.flatMap(({ source, destination }) => [
65
+ { target: source, boundary: source.full },
66
+ /* v8 ignore next */
67
+ ...(input.stdout === true ? [] : [{ target: destination, boundary: destination.full }]),
68
+ ]),
69
+ );
70
+ const results = await mapLimit(targets, ctx.concurrency, async ({ requested, source, destination }) => {
71
+ /* v8 ignore next */
72
+ const data = await fs.readFile(source.full).catch((error) => {
73
+ throw fromErrno(error);
74
+ });
75
+ const compressed = await gzipAsync(data, { level: input.level ?? 6 });
76
+ if (input.stdout === true) return compressed;
77
+ if (input.force !== true && (await exists(destination.full))) {
78
+ throw new FsError(`Output exists: "${destination.full}"`, "exists");
79
+ }
80
+ /* v8 ignore next */
81
+ await fs.writeFile(destination.full, compressed).catch((error) => {
82
+ throw fromErrno(error);
83
+ });
84
+ /* v8 ignore next */
85
+ if (input.keep !== true) await fs.unlink(source.full).catch(() => undefined);
86
+ return Buffer.alloc(0);
87
+ }, ctx.signal);
88
+ if (input.stdout === true) return { stdout: Buffer.concat(results), exitCode: 0, metadata: { files: input.paths } };
89
+ return textResult("", { files: input.paths });
90
+ },
91
+ };
92
+
93
+ export const gunzipTool: ToolSpec<GunzipInput> = {
94
+ name: "gunzip",
95
+ description:
96
+ "Decompress gzip files or stdin (`-k`, `-f`, `-c`, suffix). File mode strips the suffix and removes the source unless keep is true.",
97
+ schema: GunzipSchema,
98
+ pipeable: "filter",
99
+ mutates: true,
100
+ async run(ctx, input, io) {
101
+ if (input.paths === undefined || input.paths.length === 0) {
102
+ if (io.stdin === undefined) throw new FsError("no input files and no stdin.", "invalid");
103
+ /* v8 ignore next 3 */
104
+ const data = await gunzipAsync(await collect(io.stdin)).catch((error) => {
105
+ throw fromErrno(error);
106
+ });
107
+ return { stdout: data, exitCode: 0, metadata: { stdin: true } };
108
+ }
109
+ const suffix = input.suffix ?? ".gz";
110
+ const targets = [];
111
+ for (const requested of input.paths) {
112
+ if (!requested.endsWith(suffix)) throw new FsError(`"${requested}" does not end with ${suffix}.`, "invalid");
113
+ const source = await ctx.sandbox.resolveFollow(requested);
114
+ const output = requested.slice(0, -suffix.length);
115
+ /* v8 ignore next */
116
+ const destination = await ctx.sandbox.resolveForCreate(input.stdout === true ? requested : output);
117
+ targets.push({ requested, source, destination });
118
+ }
119
+ await ctx.permission.assert(
120
+ targets.flatMap(({ source, destination }) => [
121
+ { target: source, boundary: source.full },
122
+ /* v8 ignore next */
123
+ ...(input.stdout === true ? [] : [{ target: destination, boundary: destination.full }]),
124
+ ]),
125
+ );
126
+ const results = await mapLimit(targets, ctx.concurrency, async ({ requested, source, destination }) => {
127
+ /* v8 ignore next */
128
+ const data = await fs.readFile(source.full).catch((error) => {
129
+ throw fromErrno(error);
130
+ });
131
+ /* v8 ignore next */
132
+ const decompressed = await gunzipAsync(data).catch((error) => {
133
+ throw fromErrno(error);
134
+ });
135
+ /* v8 ignore next */
136
+ if (input.stdout === true) return decompressed;
137
+ /* v8 ignore next */
138
+ if (input.force !== true && (await exists(destination.full))) {
139
+ throw new FsError(`Output exists: "${destination.full}"`, "exists");
140
+ }
141
+ /* v8 ignore next */
142
+ await fs.writeFile(destination.full, decompressed).catch((error) => {
143
+ throw fromErrno(error);
144
+ });
145
+ /* v8 ignore next */
146
+ if (input.keep !== true) await fs.unlink(source.full).catch(() => undefined);
147
+ return Buffer.alloc(0);
148
+ }, ctx.signal);
149
+ /* v8 ignore next */
150
+ if (input.stdout === true) return { stdout: Buffer.concat(results), exitCode: 0, metadata: { files: input.paths } };
151
+ return textResult("", { files: input.paths });
152
+ },
153
+ };
154
+
155
+ async function exists(target: string): Promise<boolean> {
156
+ try {
157
+ await fs.lstat(target);
158
+ return true;
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+
164
+
@@ -0,0 +1,84 @@
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";
7
+ import { createHash } from "node:crypto";
8
+ import { Type, type Static } from "@sinclair/typebox";
9
+ import { FsError, fromErrno } from "../core/errors.js";
10
+ import { mapLimit } from "../core/parallel.js";
11
+ import { textResult, type ToolSpec } from "../core/types.js";
12
+
13
+ const Schema = Type.Object(
14
+ {
15
+ files: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to hash. Omit to hash stdin." })),
16
+ algorithm: Type.Optional(
17
+ Type.Union(
18
+ [Type.Literal("md5"), Type.Literal("sha1"), Type.Literal("sha256"), Type.Literal("sha512")],
19
+ { description: "Hash algorithm. Default: sha256." },
20
+ ),
21
+ ),
22
+ tag: Type.Optional(Type.Boolean({ description: "Use BSD-style tagged output (`--tag`)." })),
23
+ },
24
+ { additionalProperties: false },
25
+ );
26
+
27
+ type Input = Static<typeof Schema>;
28
+
29
+ export const hashTool: ToolSpec<Input> = {
30
+ name: "hash",
31
+ description:
32
+ "Compute file checksums like `sha256sum`/`md5sum` (`md5`, `sha1`, `sha256`, `sha512`). " +
33
+ "Hashes multiple files in parallel; omit files to hash stdin.",
34
+ schema: Schema,
35
+ pipeable: "sink",
36
+ mutates: false,
37
+ async run(ctx, input, io) {
38
+ 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");
41
+ const hash = await hashStream(algorithm, io.stdin);
42
+ return textResult(`${hash} -\n`, { algorithm, stdin: true });
43
+ }
44
+
45
+ const targets = [];
46
+ for (const requested of input.files) {
47
+ const target = await ctx.sandbox.resolveFollow(requested);
48
+ targets.push({ requested, target });
49
+ }
50
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
51
+
52
+ const results = await mapLimit(
53
+ targets,
54
+ ctx.concurrency,
55
+ async ({ requested, target }) => {
56
+ try {
57
+ const hash = await hashFile(algorithm, target.full);
58
+ return input.tag === true
59
+ ? `${algorithm.toUpperCase()} (${requested}) = ${hash}`
60
+ : `${hash} ${requested}`;
61
+ } catch (error) {
62
+ throw fromErrno(error);
63
+ }
64
+ },
65
+ ctx.signal,
66
+ );
67
+ return textResult(results.join("\n") + "\n", { algorithm, files: input.files });
68
+ },
69
+ };
70
+
71
+ async function hashFile(algorithm: string, file: string): Promise<string> {
72
+ const hash = createHash(algorithm);
73
+ const stream = fs.createReadStream(file);
74
+ for await (const chunk of stream) hash.update(chunk as Buffer);
75
+ return hash.digest("hex");
76
+ }
77
+
78
+ async function hashStream(algorithm: string, stream: AsyncIterable<Buffer>): Promise<string> {
79
+ const hash = createHash(algorithm);
80
+ for await (const chunk of stream) hash.update(chunk);
81
+ return hash.digest("hex");
82
+ }
83
+
84
+
@@ -0,0 +1,78 @@
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 { collect, inputStream, lines, readFiles } from "../core/stream.js";
8
+ import { FsError } from "../core/errors.js";
9
+ import { textResult, type ToolSpec } from "../core/types.js";
10
+
11
+ const Schema = Type.Object(
12
+ {
13
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to read. Omit to read stdin." })),
14
+ lines: Type.Optional(Type.Integer({ minimum: 1, description: "Number of lines. Default: 10 (`-n`)." })),
15
+ bytes: Type.Optional(Type.Integer({ minimum: 1, description: "Number of bytes (`-c`)." })),
16
+ quiet: Type.Optional(Type.Boolean({ description: "Never print file headers (`-q`)." })),
17
+ verbose: Type.Optional(Type.Boolean({ description: "Always print file headers (`-v`)." })),
18
+ },
19
+ { additionalProperties: false },
20
+ );
21
+
22
+ type Input = Static<typeof Schema>;
23
+
24
+ export const headTool: ToolSpec<Input> = {
25
+ name: "head",
26
+ description: "Output the first part of files or stdin with Linux `head` semantics (`-n`, `-c`, `-q`, `-v`).",
27
+ schema: Schema,
28
+ pipeable: "filter",
29
+ mutates: false,
30
+ async run(ctx, input, io) {
31
+ if (input.lines !== undefined && input.bytes !== undefined) {
32
+ throw new FsError("head accepts either lines or bytes, not both.", "invalid");
33
+ }
34
+ const count = input.bytes ?? input.lines ?? 10;
35
+ const paths = input.paths ?? [];
36
+ const targets = [];
37
+ for (const requested of paths) {
38
+ const target = await ctx.sandbox.resolveFollow(requested);
39
+ targets.push({ requested, full: target.full, target });
40
+ }
41
+ if (targets.length > 0) {
42
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
43
+ }
44
+
45
+ const output: Buffer[] = [];
46
+ if (targets.length === 0) {
47
+ const data = input.bytes !== undefined
48
+ ? await collect(await inputStream([], io.stdin), input.bytes)
49
+ : await takeLines(inputStream([], io.stdin), count);
50
+ output.push(data);
51
+ } else {
52
+ for (const target of targets) {
53
+ if (input.quiet !== true && (targets.length > 1 || input.verbose === true)) {
54
+ output.push(Buffer.from(`==> ${target.requested} <==\n`));
55
+ }
56
+ output.push(
57
+ input.bytes !== undefined
58
+ ? await collect(readFiles([target.full]), input.bytes)
59
+ : await takeLines(readFiles([target.full]), count),
60
+ );
61
+ }
62
+ }
63
+ return textResult(Buffer.concat(output).toString("utf8"), { paths });
64
+ },
65
+ };
66
+
67
+ async function takeLines(stream: AsyncIterable<Buffer>, count: number): Promise<Buffer> {
68
+ const output: string[] = [];
69
+ let taken = 0;
70
+ for await (const line of lines(stream)) {
71
+ /* v8 ignore next */
72
+ output.push(line.text + (line.newline ? "\n" : ""));
73
+ taken++;
74
+ /* v8 ignore next */
75
+ if (taken >= count) break;
76
+ }
77
+ return Buffer.from(output.join(""), "utf8");
78
+ }
@@ -0,0 +1,98 @@
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
+ sources: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
15
+ destination: Type.String({ minLength: 1, description: "Link path, or an existing directory for multiple sources." }),
16
+ symbolic: Type.Optional(Type.Boolean({ description: "Create symbolic links (`-s`)." })),
17
+ force: Type.Optional(Type.Boolean({ description: "Replace existing destinations (`-f`)." })),
18
+ noDereference: Type.Optional(Type.Boolean({ description: "Hard-link a symlink itself (`-P`)." })),
19
+ relative: Type.Optional(Type.Boolean({ description: "Create relative symbolic links (`-r`)." })),
20
+ verbose: Type.Optional(Type.Boolean({ description: "Report created links (`-v`)." })),
21
+ },
22
+ { additionalProperties: false },
23
+ );
24
+
25
+ type Input = Static<typeof Schema>;
26
+
27
+ export const lnTool: ToolSpec<Input> = {
28
+ name: "ln",
29
+ description:
30
+ "Create hard or symbolic links with Linux `ln` semantics (`-s`, `-f`, `-P`, `-r`, `-v`). " +
31
+ "Symbolic targets may be dangling; hard-link sources must exist.",
32
+ schema: Schema,
33
+ pipeable: false,
34
+ mutates: true,
35
+ async run(ctx, input) {
36
+ const destTarget = await ctx.sandbox.resolveForCreate(input.destination);
37
+ let destIsDirectory = false;
38
+ try {
39
+ destIsDirectory = (await fs.lstat(destTarget.full)).isDirectory();
40
+ } catch (error) {
41
+ /* v8 ignore next 2 */
42
+ if (!isMissing(error)) throw fromErrno(error, "access");
43
+ }
44
+ if (input.sources.length > 1 && !destIsDirectory) {
45
+ throw new FsError("Multiple sources require an existing directory destination.", "not-directory");
46
+ }
47
+
48
+ const created: string[] = [];
49
+ for (const requested of input.sources) {
50
+ const link = destIsDirectory || input.sources.length > 1
51
+ ? path.join(destTarget.full, path.basename(path.resolve(requested)))
52
+ : destTarget.full;
53
+ const linkTarget = await ctx.sandbox.resolveForCreate(link);
54
+ const entries = [{ target: linkTarget, boundary: path.dirname(linkTarget.full) }];
55
+
56
+ let sourceFull: string | undefined;
57
+ let targetText = requested;
58
+ if (input.symbolic === true) {
59
+ if (input.relative === true) {
60
+ const sourceAbs = path.resolve(ctx.sandbox.root, requested);
61
+ targetText = path.relative(path.dirname(linkTarget.full), sourceAbs);
62
+ }
63
+ } else {
64
+ const source = input.noDereference === true
65
+ ? await ctx.sandbox.resolveExisting(requested)
66
+ : await ctx.sandbox.resolveFollow(requested);
67
+ sourceFull = source.full;
68
+ targetText = source.full;
69
+ entries.push({ target: source, boundary: path.dirname(source.full) });
70
+ }
71
+ await ctx.permission.assert(entries);
72
+
73
+ if (input.force === true) {
74
+ try {
75
+ await fs.unlink(linkTarget.full);
76
+ } catch (error) {
77
+ /* v8 ignore next 2 */
78
+ if (!isMissing(error)) throw fromErrno(error);
79
+ }
80
+ }
81
+ try {
82
+ if (input.symbolic === true) {
83
+ await fs.symlink(targetText, linkTarget.full);
84
+ } else {
85
+ await fs.link(sourceFull as string, linkTarget.full);
86
+ }
87
+ } catch (error) {
88
+ throw fromErrno(error);
89
+ }
90
+ created.push(link);
91
+ }
92
+
93
+ return textResult(
94
+ input.verbose === true ? created.map((item) => `'${item}' created`).join("\n") : "",
95
+ { created },
96
+ );
97
+ },
98
+ };