opencode-fs-plugin 0.0.0-stage → 1.0.2

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 +266 -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,195 @@
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 { gzip as gzipBuffer, gunzip as gunzipBuffer } from "node:zlib";
9
+ import { promisify } from "node:util";
10
+ import * as tar from "tar-stream";
11
+ import picomatch from "picomatch";
12
+ import { Type, type Static } from "@sinclair/typebox";
13
+ import { FsError, fromErrno } from "../core/errors.js";
14
+ import { collect } from "../core/stream.js";
15
+ import { textResult, type ToolSpec } from "../core/types.js";
16
+
17
+ const gzipAsync = promisify(gzipBuffer);
18
+ const gunzipAsync = promisify(gunzipBuffer);
19
+
20
+ const Schema = Type.Object(
21
+ {
22
+ mode: Type.Union([Type.Literal("create"), Type.Literal("extract"), Type.Literal("list")], {
23
+ description: "Tar operation (`-c`, `-x`, `-t`).",
24
+ }),
25
+ archive: Type.String({ minLength: 1, description: "Archive path (`-f`)." }),
26
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Members to create, or paths to list/extract." })),
27
+ directory: Type.Optional(Type.String({ description: "Working directory (`-C`)." })),
28
+ gzip: Type.Optional(Type.Boolean({ description: "Use gzip compression (`-z`). Inferred from .gz/.tgz." })),
29
+ stripComponents: Type.Optional(Type.Integer({ minimum: 0, description: "Strip leading path components (`--strip-components`)." })),
30
+ exclude: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Exclude globs." })),
31
+ verbose: Type.Optional(Type.Boolean({ description: "List processed members (`-v`)." })),
32
+ },
33
+ { additionalProperties: false },
34
+ );
35
+
36
+ type Input = Static<typeof Schema>;
37
+
38
+ export const tarTool: ToolSpec<Input> = {
39
+ name: "tar",
40
+ description:
41
+ "Create, list or extract tar archives with common `tar` semantics (`-c`, `-x`, `-t`, `-f`, " +
42
+ "`-z`, `-C`, `--strip-components`, `--exclude`). Extraction rejects path escapes.",
43
+ schema: Schema,
44
+ pipeable: false,
45
+ mutates: true,
46
+ async run(ctx, input) {
47
+ const archive = await ctx.sandbox.resolveForCreate(input.archive);
48
+ const useGzip = input.gzip ?? /\.(?:tgz|tar\.gz)$/i.test(input.archive);
49
+ const excludes = input.exclude === undefined ? undefined : picomatch(input.exclude, { dot: true, basename: true });
50
+ const names: string[] = [];
51
+
52
+ if (input.mode === "create") {
53
+ if (input.paths === undefined || input.paths.length === 0) throw new FsError("create requires paths.", "invalid");
54
+ const members: Array<{ name: string; full: string; stats: Awaited<ReturnType<typeof fs.lstat>> }> = [];
55
+ for (const requested of input.paths) {
56
+ const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
57
+ const stats = await ctx.sandbox.lstat(target.full, requested);
58
+ const base = path.basename(path.resolve(requested));
59
+ members.push({ name: base, full: target.full, stats });
60
+ if (stats.isDirectory()) {
61
+ await collectMembers(target.full, base, members, excludes);
62
+ }
63
+ }
64
+ const entries = await Promise.all(
65
+ members.map(async (member) => ({
66
+ target: await ctx.sandbox.resolveExisting(member.full, { allowRoot: true }),
67
+ boundary: member.stats.isDirectory() ? member.full : path.dirname(member.full),
68
+ })),
69
+ );
70
+ await ctx.permission.assert([...entries, { target: archive, boundary: archive.full }]);
71
+ const pack = tar.pack();
72
+ for (const member of members) {
73
+ const header: tar.Header = {
74
+ name: member.name.split(path.sep).join("/"),
75
+ size: member.stats.isFile() ? Number(member.stats.size) : 0,
76
+ mode: Number(member.stats.mode) & 0o7777,
77
+ mtime: member.stats.mtime,
78
+ type: member.stats.isDirectory() ? "directory" : member.stats.isSymbolicLink() ? "symlink" : "file",
79
+ linkname: member.stats.isSymbolicLink() ? await fs.readlink(member.full) : "",
80
+ uid: Number(member.stats.uid),
81
+ gid: Number(member.stats.gid),
82
+ uname: "",
83
+ gname: "",
84
+ devmajor: 0,
85
+ devminor: 0,
86
+ };
87
+ if (member.stats.isFile()) {
88
+ pack.entry(header, await fs.readFile(member.full));
89
+ } else {
90
+ pack.entry(header);
91
+ }
92
+ names.push(header.name);
93
+ }
94
+ pack.finalize();
95
+ let buffer = await collect(pack as AsyncIterable<Buffer>);
96
+ if (useGzip) buffer = await gzipAsync(buffer);
97
+ /* v8 ignore next 3 */
98
+ await fs.writeFile(archive.full, buffer).catch((error) => {
99
+ throw fromErrno(error);
100
+ });
101
+ return textResult(input.verbose === true ? names.map((name) => `${name}\n`).join("") : "", {
102
+ archive: input.archive,
103
+ members: names,
104
+ });
105
+ }
106
+
107
+ /* v8 ignore next 3 */
108
+ const raw = await fs.readFile(archive.full).catch((error) => {
109
+ throw fromErrno(error);
110
+ });
111
+ /* v8 ignore next 3 */
112
+ const buffer = useGzip ? await gunzipAsync(raw).catch((error) => {
113
+ throw fromErrno(error);
114
+ }) : raw;
115
+ if (input.mode === "list") {
116
+ const extract = tar.extract();
117
+ extract.end(buffer);
118
+ for await (const entry of extract) {
119
+ names.push(entry.header.name);
120
+ await collect(entry as AsyncIterable<Buffer>);
121
+ }
122
+ return textResult(names.map((name) => `${name}\n`).join(""), { archive: input.archive, members: names });
123
+ }
124
+
125
+ const destTarget = input.directory === undefined
126
+ ? await ctx.sandbox.resolveForCreate(".")
127
+ : await ctx.sandbox.resolveForCreate(input.directory);
128
+ const destRoot = destTarget.full;
129
+ await ctx.permission.assert([{ target: destTarget, boundary: destRoot }]);
130
+ await ctx.sandbox.lstat(destRoot).catch(async () => {
131
+ await fs.mkdir(destRoot, { recursive: true });
132
+ });
133
+ const extract = tar.extract();
134
+ extract.end(buffer);
135
+ for await (const entry of extract) {
136
+ const name = safeMember(entry.header.name, input.stripComponents ?? 0);
137
+ if (name === undefined) {
138
+ await collect(entry as AsyncIterable<Buffer>);
139
+ continue;
140
+ }
141
+ const destination = path.join(destRoot, name);
142
+ /* v8 ignore next */
143
+ if (!isInside(destRoot, destination)) throw new FsError(`Blocked archive path: ${entry.header.name}`, "archive");
144
+ if (entry.header.type === "directory") {
145
+ await fs.mkdir(destination, { recursive: true });
146
+ await collect(entry as AsyncIterable<Buffer>);
147
+ } else if (entry.header.type === "symlink") {
148
+ if (path.isAbsolute(entry.header.linkname) || entry.header.linkname.split("/").includes("..")) {
149
+ throw new FsError(`Blocked symlink target: ${entry.header.linkname}`, "archive");
150
+ }
151
+ await fs.mkdir(path.dirname(destination), { recursive: true });
152
+ await fs.symlink(entry.header.linkname, destination);
153
+ await collect(entry as AsyncIterable<Buffer>);
154
+ } else {
155
+ await fs.mkdir(path.dirname(destination), { recursive: true });
156
+ const data = await collect(entry as AsyncIterable<Buffer>);
157
+ await fs.writeFile(destination, data, { mode: Number(entry.header.mode) & 0o7777 });
158
+ }
159
+ names.push(name);
160
+ }
161
+ return textResult("", { archive: input.archive, members: names });
162
+ },
163
+ };
164
+
165
+ async function collectMembers(
166
+ full: string,
167
+ name: string,
168
+ members: Array<{ name: string; full: string; stats: Awaited<ReturnType<typeof fs.lstat>> }>,
169
+ excludes: ((value: string) => boolean) | undefined,
170
+ ): Promise<void> {
171
+ const entries = await fs.readdir(full);
172
+ for (const entry of entries) {
173
+ const child = path.join(full, entry);
174
+ /* v8 ignore next */
175
+ const member = name === "" ? entry : `${name}/${entry}`;
176
+ if (excludes !== undefined && excludes(member)) continue;
177
+ const stats = await fs.lstat(child);
178
+ members.push({ name: member, full: child, stats });
179
+ if (stats.isDirectory()) await collectMembers(child, member, members, excludes);
180
+ }
181
+ }
182
+
183
+ function safeMember(name: string, strip: number): string | undefined {
184
+ /* v8 ignore next */
185
+ if (name.includes("\0") || path.isAbsolute(name)) throw new FsError(`Blocked archive path: ${name}`, "archive");
186
+ const parts = name.split("/").filter((part) => part.length > 0);
187
+ if (parts.some((part) => part === "..")) throw new FsError(`Blocked archive path: ${name}`, "archive");
188
+ const stripped = parts.slice(strip);
189
+ return stripped.length === 0 ? undefined : stripped.join(path.sep);
190
+ }
191
+
192
+ function isInside(root: string, target: string): boolean {
193
+ const rel = path.relative(root, target);
194
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
195
+ }
@@ -0,0 +1,51 @@
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 { collect, writeAll } from "../core/stream.js";
9
+ import type { ToolSpec } from "../core/types.js";
10
+
11
+ const Schema = Type.Object(
12
+ {
13
+ paths: Type.Array(Type.String({ minLength: 1 }), { description: "Files to write. Empty means pass through only." }),
14
+ append: Type.Optional(Type.Boolean({ description: "Append instead of overwriting (`-a`)." })),
15
+ content: Type.Optional(Type.String({ description: "Text to write when no stdin is available." })),
16
+ },
17
+ { additionalProperties: false },
18
+ );
19
+
20
+ type Input = Static<typeof Schema>;
21
+
22
+ export const teeTool: ToolSpec<Input> = {
23
+ name: "tee",
24
+ description:
25
+ "Copy stdin to one or more files and stdout with Linux `tee` semantics (`-a`). " +
26
+ "Use `content` when calling it outside a pipe.",
27
+ schema: Schema,
28
+ pipeable: "filter",
29
+ mutates: true,
30
+ async run(ctx, input, io) {
31
+ if (input.paths.length === 0 && input.content === undefined && io.stdin === undefined) {
32
+ throw new FsError("tee needs files, content, or stdin.", "invalid");
33
+ }
34
+ const data = input.content !== undefined
35
+ ? Buffer.from(input.content, "utf8")
36
+ : await collect(io.stdin as AsyncIterable<Buffer>);
37
+
38
+ const targets = [];
39
+ for (const requested of input.paths) {
40
+ const target = await ctx.sandbox.resolveForCreate(requested);
41
+ targets.push({ requested, target });
42
+ }
43
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
44
+ for (const target of targets) {
45
+ await writeAll(target.target.full, data, input.append === true);
46
+ }
47
+ return { stdout: data, exitCode: 0, metadata: { files: input.paths, append: input.append === true } };
48
+ },
49
+ };
50
+
51
+
@@ -0,0 +1,130 @@
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 { textResult, type ToolSpec } from "../core/types.js";
10
+
11
+ const Schema = Type.Object(
12
+ {
13
+ paths: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
14
+ accessOnly: Type.Optional(Type.Boolean({ description: "Change only access time (`-a`)." })),
15
+ modifyOnly: Type.Optional(Type.Boolean({ description: "Change only modification time (`-m`)." })),
16
+ noCreate: Type.Optional(Type.Boolean({ description: "Do not create missing files (`-c`)." })),
17
+ date: Type.Optional(Type.String({ description: "Date string accepted by Date.parse, or @epoch (`-d`)." })),
18
+ timestamp: Type.Optional(Type.String({ description: "GNU -t timestamp [[CC]YY]MMDDhhmm[.ss]." })),
19
+ reference: Type.Optional(Type.String({ description: "Use another file's times (`-r`)." })),
20
+ noDereference: Type.Optional(Type.Boolean({ description: "Affect a symlink itself (`-h`)." })),
21
+ },
22
+ { additionalProperties: false },
23
+ );
24
+
25
+ type Input = Static<typeof Schema>;
26
+
27
+ export const touchTool: ToolSpec<Input> = {
28
+ name: "touch",
29
+ description:
30
+ "Create empty files or update access/modification times with Linux `touch` semantics " +
31
+ "(`-a`, `-m`, `-c`, `-d`, `-t`, `-r`, `-h`).",
32
+ schema: Schema,
33
+ pipeable: false,
34
+ mutates: true,
35
+ async run(ctx, input) {
36
+ const base = await resolveTimes(ctx, input);
37
+ const changed: string[] = [];
38
+ for (const requested of input.paths) {
39
+ const target = await ctx.sandbox.resolveForCreate(requested);
40
+ await ctx.permission.assert([{ target, boundary: target.full }]);
41
+ let stats;
42
+ try {
43
+ stats = await ctx.sandbox.lstat(target.full, requested);
44
+ } catch (error) {
45
+ /* v8 ignore next */
46
+ if (!(error instanceof FsError) || error.code !== "not-found") throw error;
47
+ if (input.noCreate === true) continue;
48
+ try {
49
+ const handle = await fs.open(target.full, "a");
50
+ await handle.close();
51
+ stats = await ctx.sandbox.lstat(target.full, requested);
52
+ } catch (openError) {
53
+ /* v8 ignore next */
54
+ throw fromErrno(openError);
55
+ }
56
+ }
57
+
58
+ const atime = input.modifyOnly === true ? stats.atime : base.atime;
59
+ const mtime = input.accessOnly === true ? stats.mtime : base.mtime;
60
+ try {
61
+ if (input.noDereference === true) {
62
+ await fs.lutimes(target.full, atime, mtime);
63
+ } else {
64
+ await fs.utimes(target.full, atime, mtime);
65
+ }
66
+ } catch (error) {
67
+ /* v8 ignore next */
68
+ throw fromErrno(error);
69
+ }
70
+ changed.push(requested);
71
+ }
72
+ return textResult("", { changed });
73
+ },
74
+ };
75
+
76
+ async function resolveTimes(
77
+ ctx: Parameters<ToolSpec<Input>["run"]>[0],
78
+ input: Input,
79
+ ): Promise<{ atime: Date; mtime: Date }> {
80
+ if (input.reference !== undefined) {
81
+ const target = await ctx.sandbox.resolveExisting(input.reference, { allowRoot: true });
82
+ const stats = await ctx.sandbox.lstat(target.full, input.reference);
83
+ return { atime: stats.atime, mtime: stats.mtime };
84
+ }
85
+ if (input.date !== undefined) {
86
+ return { atime: parseDate(input.date), mtime: parseDate(input.date) };
87
+ }
88
+ if (input.timestamp !== undefined) {
89
+ const date = parseGnuTimestamp(input.timestamp);
90
+ return { atime: date, mtime: date };
91
+ }
92
+ const now = new Date();
93
+ return { atime: now, mtime: now };
94
+ }
95
+
96
+ export function parseDate(value: string): Date {
97
+ if (value.startsWith("@")) {
98
+ const seconds = Number(value.slice(1));
99
+ if (!Number.isFinite(seconds)) throw new FsError(`Invalid date: ${value}`, "invalid");
100
+ return new Date(seconds * 1000);
101
+ }
102
+ const parsed = Date.parse(value);
103
+ if (Number.isNaN(parsed)) throw new FsError(`Invalid date: ${value}`, "invalid");
104
+ return new Date(parsed);
105
+ }
106
+
107
+ export function parseGnuTimestamp(value: string): Date {
108
+ const match = /^(?:(\d{2})(\d{2})|(\d{2}))?(\d{2})(\d{2})(\d{2})(\d{2})(?:\.(\d{2}))?$/.exec(value);
109
+ if (!match) throw new FsError(`Invalid timestamp: ${value}`, "invalid");
110
+ const current = new Date();
111
+ const century = match[1];
112
+ const twoDigitYear = match[2] ?? match[3];
113
+ const year = century !== undefined && twoDigitYear !== undefined
114
+ ? Number(century) * 100 + Number(twoDigitYear)
115
+ : twoDigitYear === undefined
116
+ ? current.getFullYear()
117
+ /* v8 ignore next 3 */
118
+ : Number(twoDigitYear) >= 69
119
+ ? 1900 + Number(twoDigitYear)
120
+ : 2000 + Number(twoDigitYear);
121
+ const month = Number(match[4]) - 1;
122
+ const day = Number(match[5]);
123
+ const hour = Number(match[6]);
124
+ const minute = Number(match[7]);
125
+ const second = Number(match[8] ?? "0");
126
+ const date = new Date(year, month, day, hour, minute, second);
127
+ /* v8 ignore next */
128
+ if (Number.isNaN(date.getTime())) throw new FsError(`Invalid timestamp: ${value}`, "invalid");
129
+ return date;
130
+ }
@@ -0,0 +1,123 @@
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 { inputStream, lines } from "../core/stream.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
+ set1: Type.String({ description: "Source character set." }),
15
+ set2: Type.Optional(Type.String({ description: "Replacement character set." })),
16
+ delete: Type.Optional(Type.Boolean({ description: "Delete characters in set1 (`-d`)." })),
17
+ squeeze: Type.Optional(Type.Boolean({ description: "Squeeze repeated characters (`-s`)." })),
18
+ complement: Type.Optional(Type.Boolean({ description: "Use the complement of set1 (`-c`)." })),
19
+ },
20
+ { additionalProperties: false },
21
+ );
22
+
23
+ type Input = Static<typeof Schema>;
24
+
25
+ export const trTool: ToolSpec<Input> = {
26
+ name: "tr",
27
+ description:
28
+ "Translate or delete characters with Linux `tr` semantics (`-d`, `-s`, `-c`) and simple ranges/classes.",
29
+ schema: Schema,
30
+ pipeable: "filter",
31
+ mutates: false,
32
+ async run(ctx, input, io) {
33
+ const paths = input.paths ?? [];
34
+ const targets = [];
35
+ for (const requested of paths) {
36
+ const target = await ctx.sandbox.resolveFollow(requested);
37
+ targets.push({ requested, full: target.full, target });
38
+ }
39
+ if (targets.length > 0) {
40
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
41
+ }
42
+
43
+ const source = input.complement === true ? complement(expandSet(input.set1)) : expandSet(input.set1);
44
+ const replacement = input.set2 === undefined ? [] : expandSet(input.set2);
45
+ const output: string[] = [];
46
+ for await (const line of lines(inputStream(targets.map((target) => target.full), io.stdin))) {
47
+ let text = "";
48
+ let previous = "";
49
+ for (const char of Array.from(line.text)) {
50
+ if (input.delete === true) {
51
+ if (source.includes(char)) continue;
52
+ text += char;
53
+ } else {
54
+ const index = source.indexOf(char);
55
+ const mapped = index >= 0 && replacement.length > 0 ? replacement[Math.min(index, replacement.length - 1)] as string : char;
56
+ if (input.squeeze === true && mapped === previous && source.includes(char)) continue;
57
+ text += mapped;
58
+ previous = mapped;
59
+ }
60
+ }
61
+ output.push(text);
62
+ }
63
+ return textResult(output.map((line) => `${line}\n`).join(""), { lines: output.length });
64
+ },
65
+ };
66
+
67
+ export function expandSet(value: string): string[] {
68
+ const output: string[] = [];
69
+ for (let index = 0; index < value.length; index++) {
70
+ const char = value[index] as string;
71
+ if (char === "\\") {
72
+ const next = value[++index];
73
+ if (next === undefined) throw new FsError("trailing escape in set.", "invalid");
74
+ /* v8 ignore next */
75
+ output.push(next === "n" ? "\n" : next === "t" ? "\t" : next === "r" ? "\r" : next);
76
+ continue;
77
+ }
78
+ if (char === "[" && value[index + 1] === ":") {
79
+ const end = value.indexOf(":]", index + 2);
80
+ if (end < 0) throw new FsError("unterminated character class.", "invalid");
81
+ output.push(...characterClass(value.slice(index + 2, end)));
82
+ index = end + 1;
83
+ continue;
84
+ }
85
+ if (value[index + 1] === "-" && value[index + 2] !== undefined) {
86
+ const start = char.codePointAt(0) as number;
87
+ const end = value.codePointAt(index + 2) as number;
88
+ if (end < start) throw new FsError("invalid set range.", "invalid");
89
+ for (let code = start; code <= end; code++) output.push(String.fromCodePoint(code));
90
+ index += 2;
91
+ continue;
92
+ }
93
+ output.push(char);
94
+ }
95
+ return output;
96
+ }
97
+
98
+ function characterClass(name: string): string[] {
99
+ const ranges: Record<string, [number, number]> = {
100
+ alpha: [65, 122],
101
+ digit: [48, 57],
102
+ upper: [65, 90],
103
+ lower: [97, 122],
104
+ space: [9, 32],
105
+ };
106
+ const range = ranges[name];
107
+ if (range === undefined) throw new FsError(`Unknown character class: ${name}`, "invalid");
108
+ const output: string[] = [];
109
+ for (let code = range[0]; code <= range[1]; code++) {
110
+ if (name === "alpha" && code > 90 && code < 97) continue;
111
+ output.push(String.fromCharCode(code));
112
+ }
113
+ return output;
114
+ }
115
+
116
+ function complement(set: string[]): string[] {
117
+ const output: string[] = [];
118
+ for (let code = 0; code < 256; code++) {
119
+ const char = String.fromCharCode(code);
120
+ if (!set.includes(char)) output.push(char);
121
+ }
122
+ return output;
123
+ }
@@ -0,0 +1,86 @@
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 os from "node:os";
8
+ import * as path from "node:path";
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
+ paths: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
16
+ force: Type.Optional(Type.Boolean({ description: "Trash even when a target looks unusual." })),
17
+ },
18
+ { additionalProperties: false },
19
+ );
20
+
21
+ type Input = Static<typeof Schema>;
22
+
23
+ export const trashTool: ToolSpec<Input> = {
24
+ name: "trash",
25
+ description:
26
+ "Move files or directories to the XDG home trash instead of deleting them permanently. " +
27
+ "Cross-filesystem moves are refused; use `rm` or a mount trash helper for those.",
28
+ schema: Schema,
29
+ pipeable: false,
30
+ mutates: true,
31
+ async run(ctx, input) {
32
+ /* v8 ignore next */
33
+ const dataHome = process.env.XDG_DATA_HOME ?? path.join(os.homedir(), ".local", "share");
34
+ const trash = path.join(dataHome, "Trash");
35
+ const filesDir = path.join(trash, "files");
36
+ const infoDir = path.join(trash, "info");
37
+ await ctx.permission.assertTrusted([`${trash}/*`]);
38
+ try {
39
+ await fs.mkdir(filesDir, { recursive: true });
40
+ await fs.mkdir(infoDir, { recursive: true });
41
+ } catch (error) {
42
+ /* v8 ignore next */
43
+ throw fromErrno(error);
44
+ }
45
+
46
+ const trashed: string[] = [];
47
+ for (const requested of input.paths) {
48
+ const target = await ctx.sandbox.resolveExisting(requested);
49
+ ctx.sandbox.assertSafeToDelete(target.full);
50
+ await ctx.permission.assert([{ target, boundary: target.full }]);
51
+ const name = await uniqueName(filesDir, path.basename(target.full));
52
+ const info = path.join(infoDir, `${name}.trashinfo`);
53
+ const body = `[Trash Info]\nPath=${encodeURIComponent(target.full)}\nDeletionDate=${new Date().toISOString()}\n`;
54
+ /* v8 ignore next 3 */
55
+ await fs.writeFile(info, body, { mode: 0o600 }).catch((error) => {
56
+ throw fromErrno(error);
57
+ });
58
+ try {
59
+ await fs.rename(target.full, path.join(filesDir, name));
60
+ } catch (error) {
61
+ /* v8 ignore next */
62
+ if ((error as NodeJS.ErrnoException)?.code === "EXDEV") {
63
+ /* v8 ignore next */
64
+ await fs.unlink(info).catch(() => undefined);
65
+ throw new FsError(`Cannot trash across filesystems: "${requested}".`, "cross-device");
66
+ }
67
+ /* v8 ignore next */
68
+ throw fromErrno(error);
69
+ }
70
+ trashed.push(requested);
71
+ }
72
+ return textResult("", { trashed, trash });
73
+ },
74
+ };
75
+
76
+ async function uniqueName(dir: string, base: string): Promise<string> {
77
+ let candidate = base;
78
+ for (let index = 1; ; index++) {
79
+ try {
80
+ await fs.lstat(path.join(dir, candidate));
81
+ candidate = `${base}.${index}`;
82
+ } catch {
83
+ return candidate;
84
+ }
85
+ }
86
+ }
@@ -0,0 +1,96 @@
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 { constants } from "node:fs";
8
+ import { Type, type Static } from "@sinclair/typebox";
9
+ import { FsError, fromErrno } from "../core/errors.js";
10
+ import { parseSize } from "../core/format.js";
11
+ import { num } from "../core/fsutil.js";
12
+ import { textResult, type ToolSpec } from "../core/types.js";
13
+
14
+ const Schema = Type.Object(
15
+ {
16
+ paths: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
17
+ size: Type.Optional(Type.String({ description: "Target size, optionally relative with leading + or -, e.g. 10M." })),
18
+ reference: Type.Optional(Type.String({ description: "Use another file's size (`-r`)." })),
19
+ noCreate: Type.Optional(Type.Boolean({ description: "Do not create missing files (`-c`)." })),
20
+ noDereference: Type.Optional(Type.Boolean({ description: "Do not follow a final symlink (`-o`)." })),
21
+ },
22
+ { additionalProperties: false },
23
+ );
24
+
25
+ type Input = Static<typeof Schema>;
26
+
27
+ export const truncateTool: ToolSpec<Input> = {
28
+ name: "truncate",
29
+ description:
30
+ "Shrink or extend files to a size with Linux `truncate` semantics (`-s`, `-r`, `-c`, `-o`). " +
31
+ "Sizes accept K, M, G, T, P and E suffixes.",
32
+ schema: Schema,
33
+ pipeable: false,
34
+ mutates: true,
35
+ async run(ctx, input) {
36
+ if (input.size === undefined && input.reference === undefined) {
37
+ throw new FsError("size or reference is required.", "invalid");
38
+ }
39
+ const referenceSize =
40
+ input.reference === undefined
41
+ ? undefined
42
+ : num((await ctx.sandbox.lstat((await ctx.sandbox.resolveExisting(input.reference, { allowRoot: true })).full, input.reference)).size);
43
+
44
+ const changed: string[] = [];
45
+ for (const requested of input.paths) {
46
+ const target = await ctx.sandbox.resolveForCreate(requested);
47
+ await ctx.permission.assert([{ target, boundary: target.full }]);
48
+ let stats;
49
+ try {
50
+ stats = await ctx.sandbox.lstat(target.full, requested);
51
+ } catch (error) {
52
+ /* v8 ignore next 2 */
53
+ if (!(error instanceof FsError) || error.code !== "not-found") throw error;
54
+ /* v8 ignore next */
55
+ if (input.noCreate === true) continue;
56
+ /* v8 ignore next 10 */
57
+ try {
58
+ const handle = await fs.open(target.full, "a");
59
+ await handle.close();
60
+ stats = await ctx.sandbox.lstat(target.full, requested);
61
+ } catch (openError) {
62
+ /* v8 ignore next */
63
+ throw fromErrno(openError);
64
+ }
65
+ }
66
+
67
+ /* v8 ignore next 2 */
68
+ const desired = input.size === undefined ? (referenceSize ?? 0) : relativeSize(num(stats.size), input.size);
69
+ if (desired < 0) throw new FsError(`Size is negative: ${desired}`, "invalid");
70
+ try {
71
+ if (input.noDereference === true) {
72
+ const handle = await fs.open(target.full, constants.O_WRONLY | constants.O_NOFOLLOW);
73
+ try {
74
+ await handle.truncate(desired);
75
+ } finally {
76
+ await handle.close();
77
+ }
78
+ } else {
79
+ await fs.truncate(target.full, desired);
80
+ }
81
+ } catch (error) {
82
+ /* v8 ignore next */
83
+ throw fromErrno(error);
84
+ }
85
+ changed.push(requested);
86
+ }
87
+ return textResult("", { changed });
88
+ },
89
+ };
90
+
91
+ function relativeSize(current: number, value: string): number {
92
+ const sign = value.startsWith("+") ? 1 : value.startsWith("-") ? -1 : 0;
93
+ const body = sign === 0 ? value : value.slice(1);
94
+ const parsed = parseSize(body);
95
+ return sign === 0 ? parsed : current + sign * parsed;
96
+ }