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,58 @@
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 } 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 dump. Omit to read stdin." })),
13
+ offset: Type.Optional(Type.Integer({ minimum: 0, description: "Start byte offset. Default: 0." })),
14
+ length: Type.Optional(Type.Integer({ minimum: 1, description: "Maximum bytes to dump." })),
15
+ width: Type.Optional(
16
+ Type.Integer({ minimum: 1, maximum: 64, description: "Bytes per line. Default: 16." }),
17
+ ),
18
+ },
19
+ { additionalProperties: false },
20
+ );
21
+
22
+ type Input = Static<typeof Schema>;
23
+
24
+ export const odTool: ToolSpec<Input> = {
25
+ name: "od",
26
+ description:
27
+ "Hex dump files or stdin with offsets and an ASCII column (`-j`, `-N`, `-w`).",
28
+ schema: Schema,
29
+ pipeable: "source",
30
+ mutates: false,
31
+ async run(ctx, input, io) {
32
+ const targets = [];
33
+ for (const requested of input.paths ?? []) {
34
+ const target = await ctx.sandbox.resolveFollow(requested);
35
+ targets.push({ requested, full: target.full, target });
36
+ }
37
+ if (targets.length > 0) {
38
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
39
+ }
40
+ const data = await collect(inputStream(targets.map((target) => target.full), io.stdin));
41
+ const offset = input.offset ?? 0;
42
+ const end = input.length === undefined ? data.length : Math.min(data.length, offset + input.length);
43
+ const slice = data.subarray(offset, end);
44
+ const width = input.width ?? 16;
45
+ const lines: string[] = [];
46
+ for (let position = 0; position < slice.length; position += width) {
47
+ const row = slice.subarray(position, position + width);
48
+ const groups: string[] = [];
49
+ for (let index = 0; index < row.length; index += 2) {
50
+ groups.push(row.subarray(index, index + 2).toString("hex").padEnd(4, " "));
51
+ }
52
+ const hex = groups.join(" ").padEnd(width * 3 - 1, " ");
53
+ const ascii = [...row].map((byte) => (byte >= 0x20 && byte <= 0x7e ? String.fromCharCode(byte) : ".")).join("");
54
+ lines.push(`${(offset + position).toString(16).padStart(8, "0")}: ${hex} ${ascii}`);
55
+ }
56
+ return textResult(lines.length > 0 ? `${lines.join("\n")}\n` : "", { bytes: slice.length });
57
+ },
58
+ };
@@ -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 { mapLimit } from "../core/parallel.js";
8
+ import { collect, inputStream } 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: "Input files. Omit to read stdin." })),
14
+ delimiters: Type.Optional(Type.String({ description: "Delimiter cycle. Default: tab." })),
15
+ serial: Type.Optional(Type.Boolean({ description: "Paste one file at a time (`-s`)." })),
16
+ },
17
+ { additionalProperties: false },
18
+ );
19
+
20
+ type Input = Static<typeof Schema>;
21
+
22
+ export const pasteTool: ToolSpec<Input> = {
23
+ name: "paste",
24
+ description: "Merge input files line by line with a delimiter cycle (`-d`, `-s`).",
25
+ schema: Schema,
26
+ pipeable: "source",
27
+ mutates: false,
28
+ async run(ctx, input, io) {
29
+ const targets = [];
30
+ for (const requested of input.paths ?? []) {
31
+ const target = await ctx.sandbox.resolveFollow(requested);
32
+ targets.push({ requested, full: target.full, target });
33
+ }
34
+ if (targets.length > 0) {
35
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
36
+ }
37
+ const sources = targets.length > 0
38
+ ? targets.map((target) => target.full)
39
+ : undefined;
40
+ const tables = sources === undefined
41
+ ? [splitLines(await collect(inputStream([], io.stdin)))]
42
+ : await mapLimit(sources, ctx.concurrency, async (full) => splitLines(await collect(inputStream([full], undefined))), ctx.signal);
43
+
44
+ const delimiters = input.delimiters === undefined || input.delimiters.length === 0 ? "\t" : input.delimiters;
45
+ const rows: string[] = [];
46
+ if (input.serial === true) {
47
+ for (const table of tables) {
48
+ if (table.length === 0) continue;
49
+ rows.push(
50
+ table
51
+ .map((line, index) => line + (index === table.length - 1 ? "" : delimiterAt(delimiters, index)))
52
+ .join(""),
53
+ );
54
+ }
55
+ } else {
56
+ const height = Math.max(0, ...tables.map((table) => table.length));
57
+ for (let index = 0; index < height; index++) {
58
+ const fields: string[] = [];
59
+ for (let column = 0; column < tables.length; column++) {
60
+ fields.push((tables[column] as string[])[index] ?? "");
61
+ }
62
+ rows.push(fields.map((field, column) => `${field}${column === fields.length - 1 ? "" : delimiterAt(delimiters, column)}`).join(""));
63
+ }
64
+ }
65
+ return textResult(rows.length > 0 ? `${rows.join("\n")}\n` : "", { rows: rows.length });
66
+ },
67
+ };
68
+
69
+ function splitLines(data: Buffer): string[] {
70
+ const rows = data.toString("utf8").split("\n");
71
+ /* v8 ignore next */
72
+ if (rows[rows.length - 1] === "") rows.pop();
73
+ return rows;
74
+ }
75
+
76
+ function delimiterAt(delimiters: string, index: number): string {
77
+ return delimiters[index % delimiters.length] as string;
78
+ }
@@ -0,0 +1,59 @@
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 { listProcesses } from "../core/procfs.js";
8
+ import { resolveUid } from "../core/fsutil.js";
9
+ import { FsError } from "../core/errors.js";
10
+ import { textResult, type ToolSpec } from "../core/types.js";
11
+
12
+ const Schema = Type.Object(
13
+ {
14
+ pattern: Type.String({ minLength: 1, description: "Process name or command-line regex." }),
15
+ full: Type.Optional(Type.Boolean({ description: "Match the full command line instead of the name." })),
16
+ ignoreCase: Type.Optional(Type.Boolean({ description: "Case-insensitive match." })),
17
+ user: Type.Optional(Type.String({ description: "Only processes owned by this user name or uid." })),
18
+ newest: Type.Optional(Type.Boolean({ description: "Return only the newest match." })),
19
+ oldest: Type.Optional(Type.Boolean({ description: "Return only the oldest match." })),
20
+ count: Type.Optional(Type.Boolean({ description: "Print only the match count." })),
21
+ delimiter: Type.Optional(Type.String({ description: "Separator between pids. Default: newline." })),
22
+ },
23
+ { additionalProperties: false },
24
+ );
25
+
26
+ type Input = Static<typeof Schema>;
27
+
28
+ export const pgrepTool: ToolSpec<Input> = {
29
+ name: "pgrep",
30
+ description:
31
+ "Find processes by name or command-line regex using /proc (`-f`, `-i`, `-u`, `-n`, `-o`, `-c`).",
32
+ schema: Schema,
33
+ pipeable: false,
34
+ mutates: false,
35
+ async run(ctx, input) {
36
+ await ctx.permission.assertTrusted([input.pattern]);
37
+ if (input.newest === true && input.oldest === true) {
38
+ throw new FsError("newest and oldest are mutually exclusive.", "invalid");
39
+ }
40
+ let regex: RegExp;
41
+ try {
42
+ regex = new RegExp(input.pattern, input.ignoreCase === true ? "i" : "");
43
+ } catch (error) {
44
+ throw new FsError(`Invalid pattern: ${(error as Error).message}`, "invalid");
45
+ }
46
+ const uid = input.user === undefined ? undefined : await resolveUid(input.user);
47
+ let matches = (await listProcesses(ctx.concurrency, ctx.signal))
48
+ .filter((row) => uid === undefined || row.uid === uid)
49
+ .filter((row) => regex.test(input.full === true ? row.command : row.comm));
50
+
51
+ if (input.newest === true) matches = matches.sort((a, b) => b.startTime - a.startTime).slice(0, 1);
52
+ if (input.oldest === true) matches = matches.sort((a, b) => a.startTime - b.startTime).slice(0, 1);
53
+ if (input.count === true) return textResult(`${matches.length}\n`, { matched: matches.length });
54
+
55
+ const delimiter = input.delimiter ?? "\n";
56
+ const text = matches.length === 0 ? "" : `${matches.map((row) => row.pid).join(delimiter)}${delimiter}`;
57
+ return textResult(text, { matched: matches.length }, matches.length > 0 ? 0 : 1);
58
+ },
59
+ };
package/src/tools/pipe.ts CHANGED
@@ -8,15 +8,26 @@ import { FsError } from "../core/errors.js";
8
8
  import { parseSchema } from "../core/schema.js";
9
9
  import { writeAll } from "../core/stream.js";
10
10
  import { textResult, type ToolSpec, type ToolResult } from "../core/types.js";
11
+ import { base64Tool } from "./base64.js";
11
12
  import { catTool } from "./cat.js";
13
+ import { cpioTool } from "./cpio.js";
12
14
  import { cutTool } from "./cut.js";
15
+ import { ddTool } from "./dd.js";
16
+ import { foldTool } from "./fold.js";
13
17
  import { grepTool } from "./grep.js";
14
18
  import { gunzipTool, gzipTool } from "./gzip.js";
15
19
  import { hashTool } from "./hash.js";
16
20
  import { headTool } from "./head.js";
17
21
  import { httpRequestTool } from "./http_request.js";
22
+ import { nlTool } from "./nl.js";
23
+ import { odTool } from "./od.js";
24
+ import { pasteTool } from "./paste.js";
25
+ import { revTool } from "./rev.js";
18
26
  import { sedTool } from "./sed.js";
27
+ import { shufTool } from "./shuf.js";
19
28
  import { sortTool } from "./sort.js";
29
+ import { stringsTool } from "./strings.js";
30
+ import { tacTool } from "./tac.js";
20
31
  import { tailTool } from "./tail.js";
21
32
  import { tarTool } from "./tar.js";
22
33
  import { teeTool } from "./tee.js";
@@ -50,7 +61,8 @@ const REGISTRY: ReadonlyMap<string, AnyTool> = new Map(
50
61
  [
51
62
  catTool, headTool, tailTool, grepTool, sedTool, sortTool, uniqTool, cutTool,
52
63
  trTool, wcTool, teeTool, hashTool, gzipTool, gunzipTool, tarTool, zipTool,
53
- httpRequestTool,
64
+ httpRequestTool, base64Tool, odTool, stringsTool, tacTool, revTool, nlTool,
65
+ pasteTool, shufTool, foldTool, ddTool, cpioTool,
54
66
  ].map((tool) => [tool.name, tool]),
55
67
  );
56
68
 
@@ -0,0 +1,88 @@
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 { listProcesses } from "../core/procfs.js";
8
+ import { lookupUser, resolveUid } from "../core/fsutil.js";
9
+ import { FsError } from "../core/errors.js";
10
+ import { textResult, type ToolSpec } from "../core/types.js";
11
+
12
+ const Schema = Type.Object(
13
+ {
14
+ pids: Type.Optional(Type.Array(Type.Integer({ minimum: 1 }), { description: "Only these process ids." })),
15
+ user: Type.Optional(Type.String({ description: "Only processes owned by this user name or uid." })),
16
+ command: Type.Optional(Type.String({ description: "Only processes whose command line matches this regex." })),
17
+ sortBy: Type.Optional(
18
+ Type.Union([Type.Literal("pid"), Type.Literal("rss"), Type.Literal("start")], {
19
+ description: "Sort key. Default: pid.",
20
+ }),
21
+ ),
22
+ limit: Type.Optional(Type.Integer({ minimum: 1, description: "Maximum rows." })),
23
+ noHeader: Type.Optional(Type.Boolean({ description: "Omit the header row." })),
24
+ format: Type.Optional(
25
+ Type.Union([Type.Literal("table"), Type.Literal("json")], { description: "Output format. Default: table." }),
26
+ ),
27
+ },
28
+ { additionalProperties: false },
29
+ );
30
+
31
+ type Input = Static<typeof Schema>;
32
+
33
+ export const psTool: ToolSpec<Input> = {
34
+ name: "ps",
35
+ description:
36
+ "List processes from /proc with pid, ppid, owner, state, rss and command. " +
37
+ "Filters by pid, user, or command regex; sorts and formats the result.",
38
+ schema: Schema,
39
+ pipeable: false,
40
+ mutates: false,
41
+ async run(ctx, input) {
42
+ await ctx.permission.assertTrusted(["*"]);
43
+ const uid = input.user === undefined ? undefined : await resolveUid(input.user);
44
+ const regex = input.command === undefined ? undefined : compile(input.command);
45
+
46
+ const wanted = input.pids === undefined ? undefined : new Set(input.pids);
47
+ let rows = (await listProcesses(ctx.concurrency, ctx.signal))
48
+ .filter((row) => wanted === undefined || wanted.has(row.pid))
49
+ .filter((row) => uid === undefined || row.uid === uid)
50
+ .filter((row) => regex === undefined || regex.test(row.command));
51
+
52
+ const sortBy = input.sortBy ?? "pid";
53
+ rows = rows.sort((a, b) =>
54
+ sortBy === "rss"
55
+ ? b.rssBytes - a.rssBytes
56
+ : sortBy === "start"
57
+ ? a.startTime - b.startTime
58
+ : a.pid - b.pid);
59
+ if (input.limit !== undefined) rows = rows.slice(0, input.limit);
60
+
61
+ const withUser = await Promise.all(
62
+ rows.map(async (row) => ({ ...row, user: await lookupUser(row.uid) })),
63
+ );
64
+ if (input.format === "json") {
65
+ return textResult(`${JSON.stringify(withUser, null, 2)}\n`, { processes: withUser.length });
66
+ }
67
+
68
+ const table = withUser.map((row) => [
69
+ String(row.pid).padStart(6),
70
+ String(row.ppid).padStart(6),
71
+ row.user.padEnd(10),
72
+ row.state.padEnd(4),
73
+ String(row.rssBytes).padStart(10),
74
+ row.command,
75
+ ].join(" "));
76
+ const header = ["PID".padStart(6), "PPID".padStart(6), "USER".padEnd(10), "STAT".padEnd(4), "RSS".padStart(10), "COMMAND"].join(" ");
77
+ const lines = input.noHeader === true ? table : [header, ...table];
78
+ return textResult(lines.length > 0 ? `${lines.join("\n")}\n` : "", { processes: rows.length });
79
+ },
80
+ };
81
+
82
+ function compile(pattern: string): RegExp {
83
+ try {
84
+ return new RegExp(pattern);
85
+ } catch (error) {
86
+ throw new FsError(`Invalid command regex: ${(error as Error).message}`, "invalid");
87
+ }
88
+ }
@@ -0,0 +1,41 @@
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
+ },
14
+ { additionalProperties: false },
15
+ );
16
+
17
+ type Input = Static<typeof Schema>;
18
+
19
+ export const revTool: ToolSpec<Input> = {
20
+ name: "rev",
21
+ description: "Reverse the characters of every line from files or stdin.",
22
+ schema: Schema,
23
+ pipeable: "source",
24
+ mutates: false,
25
+ async run(ctx, input, io) {
26
+ const targets = [];
27
+ for (const requested of input.paths ?? []) {
28
+ const target = await ctx.sandbox.resolveFollow(requested);
29
+ targets.push({ requested, full: target.full, target });
30
+ }
31
+ if (targets.length > 0) {
32
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
33
+ }
34
+ const data = await collect(inputStream(targets.map((target) => target.full), io.stdin));
35
+ const output: string[] = [];
36
+ for await (const line of lines({ async *[Symbol.asyncIterator]() { yield data; } })) {
37
+ output.push([...line.text].reverse().join("") + (line.newline ? "\n" : ""));
38
+ }
39
+ return textResult(output.join(""), { lines: output.length });
40
+ },
41
+ };
@@ -0,0 +1,49 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ import * as crypto from "node:crypto";
7
+ import { Type, type Static } from "@sinclair/typebox";
8
+ import { collect, inputStream } 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 shuffle. Omit to read stdin." })),
14
+ headCount: Type.Optional(Type.Integer({ minimum: 1, description: "Print only this many lines (`-n`)." })),
15
+ zeroTerminated: Type.Optional(Type.Boolean({ description: "NUL-separated records (`-z`)." })),
16
+ },
17
+ { additionalProperties: false },
18
+ );
19
+
20
+ type Input = Static<typeof Schema>;
21
+
22
+ export const shufTool: ToolSpec<Input> = {
23
+ name: "shuf",
24
+ description: "Shuffle lines or NUL-separated records from files or stdin (`-n`, `-z`).",
25
+ schema: Schema,
26
+ pipeable: "source",
27
+ mutates: false,
28
+ async run(ctx, input, io) {
29
+ const targets = [];
30
+ for (const requested of input.paths ?? []) {
31
+ const target = await ctx.sandbox.resolveFollow(requested);
32
+ targets.push({ requested, full: target.full, target });
33
+ }
34
+ if (targets.length > 0) {
35
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
36
+ }
37
+ const data = await collect(inputStream(targets.map((target) => target.full), io.stdin));
38
+ const delimiter = input.zeroTerminated === true ? "\0" : "\n";
39
+ const rows = data.toString("utf8").split(delimiter);
40
+ /* v8 ignore next */
41
+ if (rows[rows.length - 1] === "") rows.pop();
42
+ for (let index = rows.length - 1; index > 0; index--) {
43
+ const swap = crypto.randomInt(index + 1);
44
+ [rows[index], rows[swap]] = [rows[swap] as string, rows[index] as string];
45
+ }
46
+ const result = input.headCount === undefined ? rows : rows.slice(0, input.headCount);
47
+ return textResult(result.length > 0 ? `${result.join(delimiter)}${delimiter}` : "", { lines: result.length });
48
+ },
49
+ };
@@ -0,0 +1,103 @@
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 { mapLimit } from "../core/parallel.js";
10
+ import { collect, inputStream, lines } from "../core/stream.js";
11
+ import type { ResolvedTarget } from "../core/sandbox.js";
12
+ import { textResult, type ToolSpec } from "../core/types.js";
13
+
14
+ const Schema = Type.Object(
15
+ {
16
+ input: Type.Optional(Type.String({ description: "File to split. Omit to read stdin." })),
17
+ prefix: Type.Optional(Type.String({ description: "Output name prefix. Default: x." })),
18
+ lines: Type.Optional(Type.Integer({ minimum: 1, description: "Lines per chunk (`-l`)." })),
19
+ bytes: Type.Optional(Type.Integer({ minimum: 1, description: "Bytes per chunk (`-b`)." })),
20
+ suffixLength: Type.Optional(Type.Integer({ minimum: 1, maximum: 16, description: "Suffix length (`-a`). Default: 2." })),
21
+ numeric: Type.Optional(Type.Boolean({ description: "Numeric suffixes (`-d`)." })),
22
+ additionalSuffix: Type.Optional(Type.String({ description: "Extra suffix appended to every name (`--additional-suffix`)." })),
23
+ },
24
+ { additionalProperties: false },
25
+ );
26
+
27
+ type Input = Static<typeof Schema>;
28
+
29
+ export const splitTool: ToolSpec<Input> = {
30
+ name: "split",
31
+ description:
32
+ "Split a file into line or byte chunks with alphabetic or numeric suffixes (`-l`, `-b`, `-a`, `-d`).",
33
+ schema: Schema,
34
+ pipeable: false,
35
+ mutates: true,
36
+ async run(ctx, input, io) {
37
+ if ((input.lines === undefined) === (input.bytes === undefined)) {
38
+ throw new FsError("exactly one of lines or bytes is required.", "invalid");
39
+ }
40
+ const prefix = input.prefix ?? "x";
41
+ const suffixLength = input.suffixLength ?? 2;
42
+ const additional = input.additionalSuffix ?? "";
43
+ let inputPath: string | undefined;
44
+ if (input.input !== undefined) {
45
+ const target = await ctx.sandbox.resolveFollow(input.input);
46
+ await ctx.permission.assert([{ target, boundary: target.full }]);
47
+ inputPath = target.full;
48
+ }
49
+ const data = await collect(inputStream(inputPath === undefined ? [] : [inputPath], io.stdin));
50
+ const chunks = input.lines === undefined
51
+ ? byteChunks(data, input.bytes as number)
52
+ : await lineChunks(data, input.lines);
53
+
54
+ const names = chunks.map((_chunk, index) => `${prefix}${suffix(index, suffixLength, input.numeric === true)}${additional}`);
55
+ const targets: ResolvedTarget[] = [];
56
+ for (const name of names) {
57
+ const target = await ctx.sandbox.resolveForCreate(name);
58
+ targets.push(target);
59
+ }
60
+ await ctx.permission.assert(targets.map((target) => ({ target, boundary: target.full })));
61
+ await mapLimit(chunks, ctx.concurrency, async (chunk, index) => {
62
+ try {
63
+ await fs.writeFile((targets[index] as { full: string }).full, chunk);
64
+ } catch (error) {
65
+ /* v8 ignore next -- write errors are environment-dependent */
66
+ throw fromErrno(error);
67
+ }
68
+ }, ctx.signal);
69
+ return textResult("", { files: names, chunks: chunks.length });
70
+ },
71
+ };
72
+
73
+ function byteChunks(data: Buffer, size: number): Buffer[] {
74
+ const chunks: Buffer[] = [];
75
+ for (let offset = 0; offset < data.length; offset += size) chunks.push(data.subarray(offset, offset + size));
76
+ return chunks.length === 0 ? [Buffer.alloc(0)] : chunks;
77
+ }
78
+
79
+ async function lineChunks(data: Buffer, size: number): Promise<Buffer[]> {
80
+ const chunks: string[] = [];
81
+ let current: string[] = [];
82
+ for await (const line of lines({ async *[Symbol.asyncIterator]() { yield data; } })) {
83
+ current.push(line.text + (line.newline ? "\n" : ""));
84
+ if (current.length === size) {
85
+ chunks.push(current.join(""));
86
+ current = [];
87
+ }
88
+ }
89
+ if (current.length > 0) chunks.push(current.join(""));
90
+ if (chunks.length === 0) chunks.push("");
91
+ return chunks.map((chunk) => Buffer.from(chunk, "utf8"));
92
+ }
93
+
94
+ function suffix(index: number, length: number, numeric: boolean): string {
95
+ if (numeric) return String(index).padStart(length, "0");
96
+ let value = index;
97
+ let text = "";
98
+ for (let position = 0; position < length; position++) {
99
+ text = String.fromCharCode(97 + (value % 26)) + text;
100
+ value = Math.floor(value / 26);
101
+ }
102
+ return text;
103
+ }
package/src/tools/stat.ts CHANGED
@@ -51,7 +51,7 @@ export const statTool: ToolSpec<Input> = {
51
51
  input.format === undefined
52
52
  ? input.terse === true
53
53
  ? await terseFormat(requested, stats)
54
- : await defaultFormat(requested, target.full, stats, link)
54
+ : await defaultFormat(requested, stats, link)
55
55
  : await customFormat(input.format, requested, target.full, stats, link),
56
56
  );
57
57
  }
@@ -61,7 +61,6 @@ export const statTool: ToolSpec<Input> = {
61
61
 
62
62
  async function defaultFormat(
63
63
  requested: string,
64
- full: string,
65
64
  stats: Awaited<ReturnType<typeof fs.lstat>>,
66
65
  link: string | undefined,
67
66
  ): Promise<string> {
@@ -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 { Type, type Static } from "@sinclair/typebox";
7
+ import { mapLimit } from "../core/parallel.js";
8
+ import { collect, inputStream } 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 scan. Omit to read stdin." })),
14
+ minLength: Type.Optional(
15
+ Type.Integer({ minimum: 1, maximum: 255, description: "Minimum printable run length. Default: 4." }),
16
+ ),
17
+ },
18
+ { additionalProperties: false },
19
+ );
20
+
21
+ type Input = Static<typeof Schema>;
22
+
23
+ export const stringsTool: ToolSpec<Input> = {
24
+ name: "strings",
25
+ description:
26
+ "Extract printable ASCII runs from binary files or stdin (`-n` minimum length).",
27
+ schema: Schema,
28
+ pipeable: "source",
29
+ mutates: false,
30
+ async run(ctx, input, io) {
31
+ const targets = [];
32
+ for (const requested of input.paths ?? []) {
33
+ const target = await ctx.sandbox.resolveFollow(requested);
34
+ targets.push({ requested, full: target.full, target });
35
+ }
36
+ if (targets.length > 0) {
37
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
38
+ }
39
+ const minLength = input.minLength ?? 4;
40
+
41
+ if (targets.length === 0) {
42
+ const data = await collect(inputStream([], io.stdin));
43
+ return textResult(extract(data, minLength), { files: 0 });
44
+ }
45
+
46
+ const chunks = await mapLimit(targets, ctx.concurrency, async ({ full }) => {
47
+ return extract(await collect(inputStream([full], undefined)), minLength);
48
+ }, ctx.signal);
49
+ return textResult(chunks.join(""), { files: targets.length });
50
+ },
51
+ };
52
+
53
+ function extract(data: Buffer, minLength: number): string {
54
+ const text = data.toString("latin1");
55
+ const matches = text.match(new RegExp(`[\\x20-\\x7e]{${minLength},}`, "g")) ?? [];
56
+ return matches.length === 0 ? "" : `${matches.join("\n")}\n`;
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 * as fs from "node:fs/promises";
7
+ import { Type, type Static } from "@sinclair/typebox";
8
+ import { fromErrno } from "../core/errors.js";
9
+ import { mapLimit } from "../core/parallel.js";
10
+ import { textResult, type ToolSpec } from "../core/types.js";
11
+
12
+ const Schema = Type.Object(
13
+ {
14
+ paths: Type.Optional(
15
+ Type.Array(Type.String({ minLength: 1 }), { description: "Files or directories to fsync. Default: ['.']." }),
16
+ ),
17
+ },
18
+ { additionalProperties: false },
19
+ );
20
+
21
+ type Input = Static<typeof Schema>;
22
+
23
+ export const syncTool: ToolSpec<Input> = {
24
+ name: "sync",
25
+ description:
26
+ "Flush file or directory data to disk with fsync. Defaults to the project root; Node has no global sync syscall.",
27
+ schema: Schema,
28
+ pipeable: false,
29
+ mutates: true,
30
+ async run(ctx, input) {
31
+ const targets = [];
32
+ for (const requested of input.paths ?? ["."]) {
33
+ const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
34
+ targets.push({ requested, full: target.full, target });
35
+ }
36
+ await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
37
+ await mapLimit(targets, ctx.concurrency, async ({ full }) => {
38
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
39
+ try {
40
+ handle = await fs.open(full, "r");
41
+ await handle.sync();
42
+ } catch (error) {
43
+ /* v8 ignore next -- fsync errors are environment-dependent */
44
+ throw fromErrno(error);
45
+ } finally {
46
+ await handle?.close();
47
+ }
48
+ }, ctx.signal);
49
+ return textResult("", { synced: targets.length });
50
+ },
51
+ };