opencode-fs-plugin 1.4.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,61 @@
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 { textResult, type ToolSpec } from "../core/types.js";
9
+
10
+ const Schema = Type.Object(
11
+ {
12
+ value: Type.Optional(Type.String({ description: "Date string parsed by Date.parse, or @epoch seconds (`-d`)." })),
13
+ utc: Type.Optional(Type.Boolean({ description: "Use UTC (`-u`)." })),
14
+ format: Type.Optional(
15
+ Type.Union(
16
+ [Type.Literal("iso"), Type.Literal("unix"), Type.Literal("rfc"), Type.Literal("date")],
17
+ { description: "Output style. Default: iso." },
18
+ ),
19
+ ),
20
+ },
21
+ { additionalProperties: false },
22
+ );
23
+
24
+ type Input = Static<typeof Schema>;
25
+
26
+ export const dateTool: ToolSpec<Input> = {
27
+ name: "date",
28
+ description: "Print the current date or a parsed date as ISO, Unix seconds, RFC 2822, or JS date text (`-u`, `-d`, `-I`).",
29
+ schema: Schema,
30
+ pipeable: false,
31
+ mutates: false,
32
+ async run(ctx, input) {
33
+ await ctx.permission.assertTrusted(["*"]);
34
+ const date = parseDate(input.value);
35
+ const utc = input.utc === true;
36
+ const format = input.format ?? "iso";
37
+ if (format === "unix") return textResult(`${Math.floor(date.getTime() / 1000)}\n`, { epoch: date.getTime() });
38
+ if (format === "rfc") return textResult(`${date.toUTCString()}\n`, { epoch: date.getTime() });
39
+ if (format === "date") {
40
+ return textResult(`${utc ? date.toUTCString() : date.toString()}\n`, { epoch: date.getTime() });
41
+ }
42
+ return textResult(`${utc ? date.toISOString() : localIso(date)}\n`, { epoch: date.getTime() });
43
+ },
44
+ };
45
+
46
+ function parseDate(value: string | undefined): Date {
47
+ if (value === undefined) return new Date();
48
+ const date = value.startsWith("@")
49
+ ? new Date(Number(value.slice(1)) * 1000)
50
+ : new Date(value);
51
+ if (Number.isNaN(date.getTime())) throw new FsError(`Invalid date: "${value}".`, "invalid");
52
+ return date;
53
+ }
54
+
55
+ export function localIso(date: Date): string {
56
+ const offset = -date.getTimezoneOffset();
57
+ const sign = offset >= 0 ? "+" : "-";
58
+ const hours = String(Math.floor(Math.abs(offset) / 60)).padStart(2, "0");
59
+ const minutes = String(Math.abs(offset) % 60).padStart(2, "0");
60
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}T${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}:${String(date.getSeconds()).padStart(2, "0")}${sign}${hours}:${minutes}`;
61
+ }
@@ -0,0 +1,120 @@
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 } from "../core/errors.js";
9
+ import { textResult, type ToolSpec } from "../core/types.js";
10
+
11
+ const Schema = Type.Object(
12
+ {
13
+ input: Type.Optional(Type.String({ description: "Input file. Omit to read stdin (`if=`)." })),
14
+ output: Type.Optional(Type.String({ description: "Output file. Omit to write stdout (`of=`)." })),
15
+ blockSize: Type.Optional(Type.Integer({ minimum: 1, maximum: 16_777_216, description: "Block size in bytes (`bs=`). Default: 512." })),
16
+ count: Type.Optional(Type.Integer({ minimum: 1, description: "Copy at most this many blocks (`count=`)." })),
17
+ skip: Type.Optional(Type.Integer({ minimum: 0, description: "Skip this many input blocks (`skip=`)." })),
18
+ seek: Type.Optional(Type.Integer({ minimum: 0, description: "Seek this many output blocks (`seek=`)." })),
19
+ status: Type.Optional(Type.Boolean({ description: "Print a transfer summary (`status=progress`)." })),
20
+ },
21
+ { additionalProperties: false },
22
+ );
23
+
24
+ type Input = Static<typeof Schema>;
25
+
26
+ export const ddTool: ToolSpec<Input> = {
27
+ name: "dd",
28
+ description:
29
+ "Copy bytes with block size, count, skip and seek (`bs=`, `count=`, `skip=`, `seek=`, `status=`).",
30
+ schema: Schema,
31
+ pipeable: "source",
32
+ mutates: true,
33
+ async run(ctx, input, io) {
34
+ const block = input.blockSize ?? 512;
35
+ let inputPath: string | undefined;
36
+ if (input.input !== undefined) {
37
+ const target = await ctx.sandbox.resolveFollow(input.input);
38
+ await ctx.permission.assert([{ target, boundary: target.full }]);
39
+ inputPath = target.full;
40
+ }
41
+ let outputPath: string | undefined;
42
+ if (input.output !== undefined) {
43
+ const target = await ctx.sandbox.resolveForCreate(input.output);
44
+ await ctx.permission.assert([{ target, boundary: target.full }]);
45
+ outputPath = target.full;
46
+ }
47
+ const source = inputPath === undefined ? io.stdin : fileChunks(inputPath, block);
48
+ if (source === undefined) throw new FsError("no input file and no stdin.", "invalid");
49
+
50
+ const skipBytes = (input.skip ?? 0) * block;
51
+ const seekBytes = (input.seek ?? 0) * block;
52
+ const maxBytes = input.count === undefined ? Number.POSITIVE_INFINITY : input.count * block;
53
+ const chunks: Buffer[] = [];
54
+ let skipped = 0;
55
+ let copied = 0;
56
+ for await (const chunk of source) {
57
+ let data = chunk;
58
+ if (skipped < skipBytes) {
59
+ const drop = Math.min(skipBytes - skipped, data.length);
60
+ skipped += drop;
61
+ data = data.subarray(drop);
62
+ }
63
+ if (data.length === 0) continue;
64
+ const room = maxBytes - copied;
65
+ if (data.length > room) data = data.subarray(0, room);
66
+ chunks.push(data);
67
+ copied += data.length;
68
+ if (copied >= maxBytes) break;
69
+ }
70
+ const data = Buffer.concat(chunks);
71
+
72
+ if (outputPath !== undefined) {
73
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
74
+ try {
75
+ handle = await fs.open(outputPath, "w");
76
+ if (data.length > 0) await handle.write(data, 0, data.length, seekBytes);
77
+ } catch (error) {
78
+ /* v8 ignore next -- write errors are environment-dependent */
79
+ throw fromErrno(error);
80
+ } finally {
81
+ await handle?.close();
82
+ }
83
+ } else if (seekBytes > 0) {
84
+ chunks.unshift(Buffer.alloc(seekBytes));
85
+ }
86
+
87
+ const records = Math.ceil(copied / block);
88
+ if (input.status === true) {
89
+ return textResult(
90
+ `${records}+0 records in\n${records}+0 records out\n${copied} bytes copied\n`,
91
+ { bytes: copied, records, blockSize: block },
92
+ );
93
+ }
94
+ return {
95
+ stdout: outputPath === undefined ? Buffer.concat(chunks) : Buffer.alloc(0),
96
+ exitCode: 0,
97
+ metadata: { bytes: copied, records, blockSize: block },
98
+ };
99
+ },
100
+ };
101
+
102
+ async function* fileChunks(full: string, block: number): AsyncGenerator<Buffer> {
103
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
104
+ try {
105
+ handle = await fs.open(full, "r");
106
+ let position = 0;
107
+ for (;;) {
108
+ const buffer = Buffer.alloc(block);
109
+ const { bytesRead } = await handle.read(buffer, 0, block, position);
110
+ if (bytesRead === 0) break;
111
+ position += bytesRead;
112
+ yield buffer.subarray(0, bytesRead);
113
+ }
114
+ } catch (error) {
115
+ /* v8 ignore next -- read errors after a successful open are rare */
116
+ throw fromErrno(error);
117
+ } finally {
118
+ await handle?.close();
119
+ }
120
+ }
@@ -0,0 +1,62 @@
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 { fromErrno } from "../core/errors.js";
9
+ import { detectFileType } from "../core/magic.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
+ paths: Type.Array(Type.String({ minLength: 1 }), {
16
+ minItems: 1,
17
+ description: "Files to inspect.",
18
+ }),
19
+ mime: Type.Optional(Type.Boolean({ description: "Print MIME types instead of descriptions." })),
20
+ },
21
+ { additionalProperties: false },
22
+ );
23
+
24
+ type Input = Static<typeof Schema>;
25
+
26
+ export const fileTool: ToolSpec<Input> = {
27
+ name: "file",
28
+ description:
29
+ "Identify file types by content magic (ELF, images, archives, compression, SQLite, wasm, text, data).",
30
+ schema: Schema,
31
+ pipeable: false,
32
+ mutates: false,
33
+ async run(ctx, input) {
34
+ const targets = [];
35
+ for (const requested of input.paths) {
36
+ const target = await ctx.sandbox.resolveFollow(requested);
37
+ targets.push({ requested, full: target.full, target });
38
+ }
39
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
40
+
41
+ const lines = await mapLimit(targets, ctx.concurrency, async ({ requested, full }) => {
42
+ const sample = await readSample(full);
43
+ const type = detectFileType(sample);
44
+ return `${requested}: ${input.mime === true ? type.mime : type.description}`;
45
+ }, ctx.signal);
46
+ return textResult(`${lines.join("\n")}\n`, { files: lines.length });
47
+ },
48
+ };
49
+
50
+ async function readSample(full: string): Promise<Buffer> {
51
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
52
+ try {
53
+ handle = await fs.open(full, "r");
54
+ const buffer = Buffer.alloc(1024);
55
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
56
+ return buffer.subarray(0, bytesRead);
57
+ } catch (error) {
58
+ throw fromErrno(error);
59
+ } finally {
60
+ await handle?.close();
61
+ }
62
+ }
@@ -0,0 +1,74 @@
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 { fromErrno } 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: "Only mounts containing these paths." })),
14
+ fsType: Type.Optional(Type.String({ description: "Only this filesystem type." })),
15
+ noHeader: Type.Optional(Type.Boolean({ description: "Omit the header row." })),
16
+ },
17
+ { additionalProperties: false },
18
+ );
19
+
20
+ type Input = Static<typeof Schema>;
21
+
22
+ interface Mount {
23
+ target: string;
24
+ source: string;
25
+ fsType: string;
26
+ options: string;
27
+ }
28
+
29
+ export const findmntTool: ToolSpec<Input> = {
30
+ name: "findmnt",
31
+ description:
32
+ "List mounted filesystems from /proc/self/mountinfo with target, source, type, and options (`-T`, `-t`, `-n`).",
33
+ schema: Schema,
34
+ pipeable: false,
35
+ mutates: false,
36
+ async run(ctx, input) {
37
+ await ctx.permission.assertTrusted(["*"]);
38
+ let text: string;
39
+ try {
40
+ text = await fs.readFile("/proc/self/mountinfo", "utf8");
41
+ } catch (error) {
42
+ /* v8 ignore next -- /proc/self/mountinfo exists on Linux */
43
+ throw fromErrno(error);
44
+ }
45
+ const mounts = text.split("\n").filter(Boolean).map(parseMount);
46
+ const filters = (input.paths ?? []).map((value) => value.replace(/\/+$/, "") || "/");
47
+ const rows = mounts
48
+ .filter((mount) => input.fsType === undefined || mount.fsType === input.fsType)
49
+ .filter((mount) => filters.length === 0 || filters.some((path) =>
50
+ mount.target === path ||
51
+ mount.target === "/" ||
52
+ path.startsWith(`${mount.target}/`) ||
53
+ mount.target.startsWith(`${path}/`)))
54
+ .map((mount) => `${mount.target} ${mount.source} ${mount.fsType} ${mount.options}`);
55
+
56
+ const header = "TARGET SOURCE FSTYPE OPTIONS";
57
+ const lines = input.noHeader === true ? rows : [header, ...rows];
58
+ return textResult(lines.length > 0 ? `${lines.join("\n")}\n` : "", { mounts: rows.length });
59
+ },
60
+ };
61
+
62
+ export function parseMount(line: string): Mount {
63
+ const fields = line.split(" ");
64
+ const separator = fields.indexOf("-");
65
+ const decode = (value: string): string =>
66
+ value.replace(/\\([0-7]{3})/g, (_match, octal: string) =>
67
+ String.fromCharCode(Number.parseInt(octal, 8)));
68
+ return {
69
+ target: decode(fields[4] as string),
70
+ options: fields[5] as string,
71
+ fsType: fields[separator + 1] as string,
72
+ source: decode(fields[separator + 2] as string),
73
+ };
74
+ }
@@ -0,0 +1,64 @@
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 } from "../core/stream.js";
8
+ import { textResult, type ToolSpec } from "../core/types.js";
9
+
10
+ const Schema = Type.Object(
11
+ {
12
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to wrap. Omit to read stdin." })),
13
+ width: Type.Optional(
14
+ Type.Integer({ minimum: 1, maximum: 10_000, description: "Maximum line width. Default: 80 (`-w`)." }),
15
+ ),
16
+ spaces: Type.Optional(Type.Boolean({ description: "Break at spaces when possible (`-s`)." })),
17
+ },
18
+ { additionalProperties: false },
19
+ );
20
+
21
+ type Input = Static<typeof Schema>;
22
+
23
+ export const foldTool: ToolSpec<Input> = {
24
+ name: "fold",
25
+ description: "Wrap input lines at a fixed width, optionally at spaces (`-w`, `-s`).",
26
+ schema: Schema,
27
+ pipeable: "source",
28
+ mutates: false,
29
+ async run(ctx, input, io) {
30
+ const targets = [];
31
+ for (const requested of input.paths ?? []) {
32
+ const target = await ctx.sandbox.resolveFollow(requested);
33
+ targets.push({ requested, full: target.full, target });
34
+ }
35
+ if (targets.length > 0) {
36
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
37
+ }
38
+ const data = await collect(inputStream(targets.map((target) => target.full), io.stdin));
39
+ const width = input.width ?? 80;
40
+ const output: string[] = [];
41
+ for await (const line of lines({ async *[Symbol.asyncIterator]() { yield data; } })) {
42
+ for (const chunk of wrap(line.text, width, input.spaces === true)) output.push(`${chunk}\n`);
43
+ }
44
+ return textResult(output.join(""), { lines: output.length });
45
+ },
46
+ };
47
+
48
+ export function wrap(text: string, width: number, spaces: boolean): string[] {
49
+ if (text.length === 0) return [""];
50
+ const chunks: string[] = [];
51
+ let rest = text;
52
+ while (rest.length > width) {
53
+ let cut = width;
54
+ if (spaces) {
55
+ const space = rest.lastIndexOf(" ", width);
56
+ if (space > 0) cut = space + 1;
57
+ }
58
+ chunks.push(rest.slice(0, cut));
59
+ rest = rest.slice(cut);
60
+ if (spaces) rest = rest.replace(/^ +/, "");
61
+ }
62
+ chunks.push(rest);
63
+ return chunks;
64
+ }
package/src/tools/grep.ts CHANGED
@@ -9,7 +9,7 @@ import { Type, type Static } from "@sinclair/typebox";
9
9
  import { FsError, fromErrno } from "../core/errors.js";
10
10
  import { walkAll } from "../core/fsutil.js";
11
11
  import { mapLimit } from "../core/parallel.js";
12
- import { collect, inputStream, lines } from "../core/stream.js";
12
+ import { collect, inputStream } from "../core/stream.js";
13
13
  import { textResult, type ToolSpec } from "../core/types.js";
14
14
 
15
15
  const Schema = Type.Object(
package/src/tools/gzip.ts CHANGED
@@ -67,7 +67,7 @@ export const gzipTool: ToolSpec<GzipInput> = {
67
67
  ...(input.stdout === true ? [] : [{ target: destination, boundary: destination.full }]),
68
68
  ]),
69
69
  );
70
- const results = await mapLimit(targets, ctx.concurrency, async ({ requested, source, destination }) => {
70
+ const results = await mapLimit(targets, ctx.concurrency, async ({ source, destination }) => {
71
71
  /* v8 ignore next */
72
72
  const data = await fs.readFile(source.full).catch((error) => {
73
73
  throw fromErrno(error);
@@ -123,7 +123,7 @@ export const gunzipTool: ToolSpec<GunzipInput> = {
123
123
  ...(input.stdout === true ? [] : [{ target: destination, boundary: destination.full }]),
124
124
  ]),
125
125
  );
126
- const results = await mapLimit(targets, ctx.concurrency, async ({ requested, source, destination }) => {
126
+ const results = await mapLimit(targets, ctx.concurrency, async ({ source, destination }) => {
127
127
  /* v8 ignore next */
128
128
  const data = await fs.readFile(source.full).catch((error) => {
129
129
  throw fromErrno(error);
@@ -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 * as os from "node:os";
8
+ import { Type, type Static } from "@sinclair/typebox";
9
+ import { lookupGroup, lookupUser } from "../core/fsutil.js";
10
+ import { textResult, type ToolSpec } from "../core/types.js";
11
+
12
+ const Schema = Type.Object(
13
+ {
14
+ only: Type.Optional(
15
+ Type.Union([Type.Literal("user"), Type.Literal("group"), Type.Literal("groups")], {
16
+ description: "Print only uid, gid, or group list (`-u`, `-g`, `-G`).",
17
+ }),
18
+ ),
19
+ },
20
+ { additionalProperties: false },
21
+ );
22
+
23
+ type Input = Static<typeof Schema>;
24
+
25
+ export const idTool: ToolSpec<Input> = {
26
+ name: "id",
27
+ description: "Print the current uid, gid, and group memberships with names (`-u`, `-g`, `-G`).",
28
+ schema: Schema,
29
+ pipeable: false,
30
+ mutates: false,
31
+ async run(ctx, input) {
32
+ await ctx.permission.assertTrusted(["*"]);
33
+ /* v8 ignore next -- process.getuid exists on supported platforms */
34
+ const uid = process.getuid?.() ?? os.userInfo().uid;
35
+ /* v8 ignore next -- process.getgid exists on supported platforms */
36
+ const gid = process.getgid?.() ?? os.userInfo().gid;
37
+ const user = await lookupUser(uid);
38
+ const groups = await groupsFor(user, gid);
39
+
40
+ if (input.only === "user") return textResult(`${uid}\n`, { uid });
41
+ if (input.only === "group") return textResult(`${gid}\n`, { gid });
42
+ if (input.only === "groups") return textResult(`${groups.map((entry) => entry.gid).join(" ")}\n`, { groups });
43
+ return textResult(
44
+ `uid=${uid}(${user}) gid=${gid}(${await lookupGroup(gid)}) groups=${groups.map((entry) => `${entry.gid}(${entry.name})`).join(",")}\n`,
45
+ { uid, gid, groups },
46
+ );
47
+ },
48
+ };
49
+
50
+ async function groupsFor(
51
+ user: string,
52
+ primary: number,
53
+ ): Promise<Array<{ gid: number; name: string }>> {
54
+ const entries = new Map<number, string>();
55
+ /* v8 ignore next -- /etc/group exists on supported Linux systems */
56
+ const text = await fs.readFile("/etc/group", "utf8").catch(() => "");
57
+ for (const line of text.split("\n")) {
58
+ const fields = line.split(":");
59
+ if (fields.length < 4) continue;
60
+ const gid = Number(fields[2]);
61
+ if (gid === primary || (fields[3] as string).split(",").includes(user)) {
62
+ entries.set(gid, fields[0] as string);
63
+ }
64
+ }
65
+ /* v8 ignore next -- the primary group is normally present in /etc/group */
66
+ if (!entries.has(primary)) entries.set(primary, await lookupGroup(primary));
67
+ return [...entries.entries()]
68
+ .sort((a, b) => a[0] - b[0])
69
+ .map(([gid, name]) => ({ gid, name }));
70
+ }
@@ -0,0 +1,60 @@
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 { fromErrno } from "../core/errors.js";
8
+ import { SIGNALS } from "../core/procfs.js";
9
+ import { textResult, type ToolSpec } from "../core/types.js";
10
+
11
+ const Schema = Type.Object(
12
+ {
13
+ pids: Type.Array(Type.Integer({ minimum: 2 }), {
14
+ minItems: 1,
15
+ description: "Process ids to signal. Pid 0, 1, and negative groups are rejected.",
16
+ }),
17
+ signal: Type.Optional(
18
+ Type.Union(
19
+ Object.keys(SIGNALS).map((name) => Type.Literal(name)),
20
+ { description: "Signal name. Default: TERM." },
21
+ ),
22
+ ),
23
+ dryRun: Type.Optional(Type.Boolean({ description: "Report targets without signalling them." })),
24
+ },
25
+ { additionalProperties: false },
26
+ );
27
+
28
+ type Input = Static<typeof Schema>;
29
+
30
+ export const killTool: ToolSpec<Input> = {
31
+ name: "kill",
32
+ description:
33
+ "Send a signal to processes (`HUP`, `INT`, `QUIT`, `KILL`, `TERM`, `USR1`, `USR2`, `STOP`, `CONT`). " +
34
+ "Pid 1 and process groups are never targeted.",
35
+ schema: Schema,
36
+ pipeable: false,
37
+ mutates: true,
38
+ async run(ctx, input) {
39
+ await ctx.permission.assertTrusted(input.pids.map(String));
40
+ const name = input.signal ?? "TERM";
41
+ const signal = SIGNALS[name] as NodeJS.Signals;
42
+ const signalled: number[] = [];
43
+ for (const pid of input.pids) {
44
+ if (input.dryRun === true) {
45
+ signalled.push(pid);
46
+ continue;
47
+ }
48
+ try {
49
+ process.kill(pid, signal);
50
+ } catch (error) {
51
+ throw fromErrno(error);
52
+ }
53
+ signalled.push(pid);
54
+ }
55
+ return textResult(
56
+ input.dryRun === true ? signalled.map((pid) => `would signal ${pid} (${name})`).join("\n") + "\n" : "",
57
+ { signalled, signal: name, dryRun: input.dryRun === true },
58
+ );
59
+ },
60
+ };
package/src/tools/ls.ts CHANGED
@@ -7,8 +7,8 @@ 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 { FsError, fromErrno } from "../core/errors.js";
11
- import { formatDate, lookupGroup, lookupUser, modeString, num, typeName } from "../core/fsutil.js";
10
+ import { fromErrno } from "../core/errors.js";
11
+ import { formatDate, lookupGroup, lookupUser, modeString, num } from "../core/fsutil.js";
12
12
  import { humanSize } from "../core/format.js";
13
13
  import { mapLimit } from "../core/parallel.js";
14
14
  import { textResult, type ToolSpec } from "../core/types.js";
@@ -0,0 +1,57 @@
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 { fromErrno } 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, description: "Paths to test." }),
15
+ quiet: Type.Optional(Type.Boolean({ description: "Print nothing; use the exit code (`-q`)." })),
16
+ },
17
+ { additionalProperties: false },
18
+ );
19
+
20
+ type Input = Static<typeof Schema>;
21
+
22
+ export const mountpointTool: ToolSpec<Input> = {
23
+ name: "mountpoint",
24
+ description:
25
+ "Report whether paths are mount points by comparing device ids with their parent (`-q`).",
26
+ schema: Schema,
27
+ pipeable: false,
28
+ mutates: false,
29
+ async run(ctx, input) {
30
+ const targets = [];
31
+ for (const requested of input.paths) {
32
+ const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
33
+ targets.push({ requested, full: target.full, target });
34
+ }
35
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
36
+
37
+ const lines: string[] = [];
38
+ let allMounted = true;
39
+ for (const { requested, full } of targets) {
40
+ const mounted = await isMountPoint(full);
41
+ allMounted &&= mounted;
42
+ if (input.quiet !== true) lines.push(`${requested} is ${mounted ? "a" : "not a"} mountpoint`);
43
+ }
44
+ return textResult(lines.length > 0 ? `${lines.join("\n")}\n` : "", { mountpoints: allMounted }, allMounted ? 0 : 1);
45
+ },
46
+ };
47
+
48
+ async function isMountPoint(full: string): Promise<boolean> {
49
+ if (full === path.parse(full).root) return true;
50
+ try {
51
+ const [stats, parent] = await Promise.all([fs.stat(full), fs.stat(path.dirname(full))]);
52
+ return stats.dev !== parent.dev;
53
+ } catch (error) {
54
+ /* v8 ignore next -- stat errors after resolution are rare */
55
+ throw fromErrno(error);
56
+ }
57
+ }
@@ -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 { collect, inputStream, lines } from "../core/stream.js";
8
+ import { textResult, type ToolSpec } from "../core/types.js";
9
+
10
+ const Schema = Type.Object(
11
+ {
12
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to read. Omit to read stdin." })),
13
+ all: Type.Optional(Type.Boolean({ description: "Number blank lines too (`-ba`)." })),
14
+ start: Type.Optional(Type.Integer({ minimum: 1, description: "First line number (`-v`). Default: 1." })),
15
+ width: Type.Optional(Type.Integer({ minimum: 1, maximum: 20, description: "Number width (`-w`). Default: 6." })),
16
+ separator: Type.Optional(Type.String({ description: "Number separator (`-s`). Default: tab." })),
17
+ },
18
+ { additionalProperties: false },
19
+ );
20
+
21
+ type Input = Static<typeof Schema>;
22
+
23
+ export const nlTool: ToolSpec<Input> = {
24
+ name: "nl",
25
+ description: "Number lines of files or stdin (`-ba`, `-v`, `-w`, `-s`).",
26
+ schema: Schema,
27
+ pipeable: "source",
28
+ mutates: false,
29
+ async run(ctx, input, io) {
30
+ const targets = [];
31
+ for (const requested of input.paths ?? []) {
32
+ const target = await ctx.sandbox.resolveFollow(requested);
33
+ targets.push({ requested, full: target.full, target });
34
+ }
35
+ if (targets.length > 0) {
36
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
37
+ }
38
+ const data = await collect(inputStream(targets.map((target) => target.full), io.stdin));
39
+ const width = input.width ?? 6;
40
+ const separator = input.separator ?? "\t";
41
+ let number = (input.start ?? 1) - 1;
42
+ const output: string[] = [];
43
+ for await (const line of lines({ async *[Symbol.asyncIterator]() { yield data; } })) {
44
+ const numbered = input.all === true || line.text.length > 0;
45
+ if (numbered) number++;
46
+ const prefix = numbered ? `${String(number).padStart(width)}${separator}` : " ".repeat(width + separator.length);
47
+ output.push(prefix + line.text + (line.newline ? "\n" : ""));
48
+ }
49
+ return textResult(output.join(""), { lines: output.length });
50
+ },
51
+ };