opencode-fs-plugin 3.4.0 → 3.6.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.
package/src/tools/ar.ts CHANGED
@@ -8,6 +8,16 @@ import * as path from "node:path";
8
8
  import { Type, type Static } from "@sinclair/typebox";
9
9
  import { FsError, fromErrno } from "../core/errors.js";
10
10
  import { num } from "../core/fsutil.js";
11
+ import { mapLimit } from "../core/parallel.js";
12
+ import {
13
+ assertArchivePlan,
14
+ outputBoundary,
15
+ resolveArchiveTarget,
16
+ resolveOutputTarget,
17
+ safeMode,
18
+ throwIfAborted,
19
+ writeOutput,
20
+ } from "../core/safe-output.js";
11
21
  import { textResult, type ToolSpec } from "../core/types.js";
12
22
 
13
23
  const Schema = Type.Object(
@@ -45,9 +55,9 @@ export const arTool: ToolSpec<Input> = {
45
55
  mutates: true,
46
56
  async run(ctx, input) {
47
57
  const archive = input.mode === "create"
48
- ? await ctx.sandbox.resolveForCreate(input.archive)
58
+ ? await resolveOutputTarget(ctx.sandbox, input.archive)
49
59
  : await ctx.sandbox.resolveFollow(input.archive);
50
- await ctx.permission.assert([{ target: archive, boundary: archive.full }]);
60
+ await ctx.permission.assert([{ target: archive, boundary: outputBoundary(archive.full) }]);
51
61
 
52
62
  if (input.mode === "create") {
53
63
  if (input.paths === undefined || input.paths.length === 0) {
@@ -55,8 +65,9 @@ export const arTool: ToolSpec<Input> = {
55
65
  }
56
66
  const members: Member[] = [];
57
67
  for (const requested of input.paths) {
68
+ throwIfAborted(ctx.signal);
58
69
  const target = await ctx.sandbox.resolveFollow(requested);
59
- await ctx.permission.assert([{ target, boundary: target.full }]);
70
+ await ctx.permission.assert([{ target, boundary: outputBoundary(target.full) }]);
60
71
  const stats = await ctx.sandbox.stat(target.full, requested);
61
72
  if (!stats.isFile()) throw new FsError(`Not a regular file: "${requested}".`, "not-file");
62
73
  const name = path.basename(requested);
@@ -75,12 +86,8 @@ export const arTool: ToolSpec<Input> = {
75
86
  }),
76
87
  });
77
88
  }
78
- /* v8 ignore next 4 -- write errors are environment-dependent */
79
- try {
80
- await fs.writeFile(archive.full, encode(members));
81
- } catch (error) {
82
- throw fromErrno(error);
83
- }
89
+ throwIfAborted(ctx.signal);
90
+ await writeOutput(archive.full, encode(members), false, 0o666, ctx.signal);
84
91
  return textResult("", { archive: input.archive, members: members.map((member) => member.name) });
85
92
  }
86
93
 
@@ -99,23 +106,31 @@ export const arTool: ToolSpec<Input> = {
99
106
  return textResult(`${selected.map((member) => member.name).join("\n")}\n`, { members: selected.length });
100
107
  }
101
108
 
102
- const base = input.directory === undefined
103
- ? (await ctx.sandbox.resolveForCreate(".")).full
104
- : (await ctx.sandbox.resolveForCreate(input.directory)).full;
105
- for (const member of selected) {
106
- const target = path.join(base, safeName(member.name));
107
- await ctx.permission.assert([{
108
- target: { full: target, outside: false, requested: target, realAncestor: base },
109
- boundary: target,
110
- }]);
111
- /* v8 ignore next 5 -- write errors are environment-dependent */
109
+ const root = input.directory === undefined
110
+ ? await resolveOutputTarget(ctx.sandbox, ".")
111
+ : await resolveOutputTarget(ctx.sandbox, input.directory);
112
+ const planned = await mapLimit(selected, ctx.concurrency, async (member) => {
113
+ throwIfAborted(ctx.signal);
114
+ const target = await resolveArchiveTarget(
115
+ ctx.sandbox,
116
+ root.full,
117
+ path.join(root.full, safeName(member.name)),
118
+ "file",
119
+ );
120
+ return { member, target, kind: "file" as const };
121
+ }, ctx.signal);
122
+ throwIfAborted(ctx.signal);
123
+ await assertArchivePlan(ctx.permission, planned, { target: root, boundary: root.full });
124
+ for (const { member, target } of planned) {
125
+ throwIfAborted(ctx.signal);
126
+ /* v8 ignore next 4 -- write errors are environment-dependent */
112
127
  try {
113
- await fs.mkdir(path.dirname(target), { recursive: true });
114
- await fs.writeFile(target, member.data);
115
- await fs.chmod(target, member.mode);
128
+ await fs.mkdir(path.dirname(target.full), { recursive: true });
116
129
  } catch (error) {
117
130
  throw fromErrno(error);
118
131
  }
132
+ const mode = safeMode(member.mode);
133
+ await writeOutput(target.full, member.data, false, mode, ctx.signal, mode);
119
134
  }
120
135
  return textResult("", { extracted: selected.length });
121
136
  },
@@ -149,26 +164,44 @@ function decode(data: Buffer): Member[] {
149
164
  const header = data.subarray(offset, offset + 60).toString("ascii");
150
165
  if (header.slice(58, 60) !== "`\n") throw new FsError("Corrupt ar header.", "archive");
151
166
  const name = header.slice(0, 16).trim().replace(/\/$/, "");
152
- const size = Number.parseInt(header.slice(48, 58).trim(), 10);
167
+ const size = decimalField(header.slice(48, 58), "size");
153
168
  const dataStart = offset + 60;
154
- if (Number.isNaN(size) || dataStart + size > data.length) {
169
+ const next = dataStart + size + (size % 2);
170
+ if (dataStart + size > data.length || next <= offset) {
155
171
  throw new FsError("Truncated ar member.", "archive");
156
172
  }
157
173
  if (name !== "" && name !== "/" && !name.startsWith("/")) {
158
174
  members.push({
159
175
  name,
160
- mtime: Number.parseInt(header.slice(16, 28).trim(), 10) || 0,
161
- uid: Number.parseInt(header.slice(28, 34).trim(), 10) || 0,
162
- gid: Number.parseInt(header.slice(34, 40).trim(), 10) || 0,
163
- mode: Number.parseInt(header.slice(40, 48).trim(), 8) || 0o644,
176
+ mtime: decimalField(header.slice(16, 28), "mtime", true),
177
+ uid: decimalField(header.slice(28, 34), "uid", true),
178
+ gid: decimalField(header.slice(34, 40), "gid", true),
179
+ mode: octalField(header.slice(40, 48)),
164
180
  data: data.subarray(dataStart, dataStart + size),
165
181
  });
166
182
  }
167
- offset = dataStart + size + (size % 2);
183
+ offset = next;
168
184
  }
169
185
  return members;
170
186
  }
171
187
 
188
+ function decimalField(field: string, label: string, blankDefault = false): number {
189
+ const text = field.trim();
190
+ if (text === "") {
191
+ if (blankDefault) return 0;
192
+ throw new FsError(`Invalid ar ${label} field.`, "archive");
193
+ }
194
+ if (!/^\d+$/.test(text)) throw new FsError(`Invalid ar ${label} field.`, "archive");
195
+ return Number(text);
196
+ }
197
+
198
+ function octalField(field: string): number {
199
+ const text = field.trim();
200
+ if (text === "") return 0o644;
201
+ if (!/^[0-7]+$/.test(text)) throw new FsError("Invalid ar mode field.", "archive");
202
+ return Number.parseInt(text, 8);
203
+ }
204
+
172
205
  function safeName(name: string): string {
173
206
  const normalized = name.replaceAll("\\", "/").replace(/^\/+/, "");
174
207
  const parts = normalized.split("/").filter((part) => part !== "" && part !== ".");
package/src/tools/cat.ts CHANGED
@@ -5,9 +5,8 @@
5
5
 
6
6
  import { Type, type Static } from "@sinclair/typebox";
7
7
  import { pathsFrom } from "../core/aliases.js";
8
- import { SpillSink, dynamicSpillThreshold, spillDirectory } from "../core/spill.js";
9
- import { inputStream, lines } from "../core/stream.js";
10
- import type { ToolSpec } from "../core/types.js";
8
+ import { collect, inputStream, lines } from "../core/stream.js";
9
+ import { textResult, type ToolSpec } from "../core/types.js";
11
10
 
12
11
  const Schema = Type.Object(
13
12
  {
@@ -36,52 +35,38 @@ export const catTool: ToolSpec<Input> = {
36
35
  const paths = pathsFrom(input) ?? [];
37
36
  const targets = await resolvePaths(ctx, paths);
38
37
  const stream = inputStream(targets.map((entry) => entry.full), io.stdin);
39
- const sink = new SpillSink(spillDirectory(ctx.tmpdir), "cat", io.piped === true, ctx.spillThreshold ?? dynamicSpillThreshold());
40
- try {
41
- if (
42
- input.number !== true &&
43
- input.numberNonBlank !== true &&
44
- input.squeezeBlank !== true &&
45
- input.showEnds !== true &&
46
- input.showTabs !== true &&
47
- input.showNonPrinting !== true
48
- ) {
49
- for await (const chunk of stream) await sink.write(chunk);
38
+ if (
39
+ input.number !== true &&
40
+ input.numberNonBlank !== true &&
41
+ input.squeezeBlank !== true &&
42
+ input.showEnds !== true &&
43
+ input.showTabs !== true &&
44
+ input.showNonPrinting !== true
45
+ ) {
46
+ return { stdout: await collect(stream), exitCode: 0, metadata: { paths } };
47
+ }
48
+
49
+ const output: string[] = [];
50
+ let number = 0;
51
+ let blank = false;
52
+ for await (const line of lines(stream)) {
53
+ if (input.squeezeBlank === true && line.text === "") {
54
+ if (blank) continue;
55
+ blank = true;
50
56
  } else {
51
- let number = 0;
52
- let blank = false;
53
- for await (const line of lines(stream)) {
54
- if (input.squeezeBlank === true && line.text === "") {
55
- if (blank) continue;
56
- blank = true;
57
- } else {
58
- blank = false;
59
- }
60
- let text = line.text;
61
- if (input.showTabs === true || input.showNonPrinting === true) text = text.replaceAll("\t", "^I");
62
- if (input.showNonPrinting === true) text = visible(text);
63
- if (input.showEnds === true) text += "$";
64
- if ((input.number === true || input.numberNonBlank === true) && (input.numberNonBlank !== true || text.length > 0)) {
65
- number++;
66
- text = `${String(number).padStart(6)} ${text}`;
67
- }
68
- await sink.write(Buffer.from(text + (line.newline ? "\n" : "")));
69
- }
57
+ blank = false;
58
+ }
59
+ let text = line.text;
60
+ if (input.showTabs === true || input.showNonPrinting === true) text = text.replaceAll("\t", "^I");
61
+ if (input.showNonPrinting === true) text = visible(text);
62
+ if (input.showEnds === true) text += "$";
63
+ if ((input.number === true || input.numberNonBlank === true) && (input.numberNonBlank !== true || text.length > 0)) {
64
+ number++;
65
+ text = `${String(number).padStart(6)} ${text}`;
70
66
  }
71
- const out = await sink.finish();
72
- return {
73
- stdout: out.preview,
74
- exitCode: 0,
75
- metadata: {
76
- paths,
77
- bytes: out.bytes,
78
- ...(out.path === undefined ? {} : { outputPath: out.path, spilled: true }),
79
- },
80
- };
81
- } catch (error) {
82
- await sink.abort();
83
- throw error;
67
+ output.push(text + (line.newline ? "\n" : ""));
84
68
  }
69
+ return textResult(output.join(""), { paths });
85
70
  },
86
71
  };
87
72
 
@@ -38,36 +38,47 @@ export const chmodTool: ToolSpec<Input> = {
38
38
  if (input.mode === undefined && input.reference === undefined) {
39
39
  throw new FsError("mode or reference is required.", "invalid");
40
40
  }
41
- const referenceMode =
42
- input.reference === undefined
43
- ? undefined
44
- : num((await ctx.sandbox.lstat((await ctx.sandbox.resolveExisting(input.reference, { allowRoot: true })).full, input.reference)).mode) & 0o7777;
41
+ let referenceMode: number | undefined;
42
+ if (input.reference !== undefined) {
43
+ const reference = await ctx.sandbox.resolveFollow(input.reference);
44
+ await ctx.permission.assert([{ target: reference, boundary: ctx.sandbox.boundaryFor(reference.full, "file") }]);
45
+ const stats = await ctx.sandbox.lstat(reference.full, input.reference);
46
+ referenceMode = num(stats.mode) & 0o7777;
47
+ }
45
48
 
46
49
  const changed: string[] = [];
47
50
  for (const requested of input.paths) {
48
- const root = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
51
+ const root = input.noDereference === true
52
+ ? await ctx.sandbox.resolveForCreate(requested)
53
+ : await ctx.sandbox.resolveFollow(requested);
49
54
  ctx.sandbox.assertSafeToDelete(root.full);
50
- const targets = [root];
51
- if (input.recursive === true) {
52
- const rootStats = await ctx.sandbox.lstat(root.full, requested);
53
- if (rootStats.isDirectory()) {
54
- for (const entry of await walkAll(root.full, {
55
- recursive: true,
56
- signal: ctx.signal,
57
- concurrency: ctx.concurrency,
58
- })) {
59
- targets.push({
55
+ const rootStats = await ctx.sandbox.lstat(root.full, requested);
56
+ const targets = [{ target: root, directory: rootStats.isDirectory() }];
57
+ if (input.recursive === true && rootStats.isDirectory()) {
58
+ for (const entry of await walkAll(root.full, {
59
+ recursive: true,
60
+ signal: ctx.signal,
61
+ concurrency: ctx.concurrency,
62
+ })) {
63
+ // Traversal symlinks are skipped: their targets were never resolved or gated.
64
+ if (input.noDereference !== true && entry.stats.isSymbolicLink()) continue;
65
+ targets.push({
66
+ target: {
60
67
  full: entry.path,
61
68
  outside: root.outside,
62
69
  requested: entry.path,
63
70
  realAncestor: root.realAncestor,
64
- });
65
- }
71
+ },
72
+ directory: entry.stats.isDirectory(),
73
+ });
66
74
  }
67
75
  }
68
- await ctx.permission.assert(targets.map((target) => ({ target, boundary: target.full })));
76
+ await ctx.permission.assert(targets.map(({ target, directory }) => ({
77
+ target,
78
+ boundary: ctx.sandbox.boundaryFor(target.full, directory ? "directory" : "file"),
79
+ })));
69
80
 
70
- for (const target of targets) {
81
+ for (const { target } of targets) {
71
82
  const stats = input.noDereference === true
72
83
  ? await ctx.sandbox.lstat(target.full, target.requested)
73
84
  : await ctx.sandbox.stat(target.full, target.requested);
@@ -47,29 +47,37 @@ export const chownTool: ToolSpec<Input> = {
47
47
 
48
48
  const targets = [];
49
49
  for (const requested of input.paths) {
50
- const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
50
+ const target = input.noDereference === true
51
+ ? await ctx.sandbox.resolveForCreate(requested)
52
+ : await ctx.sandbox.resolveFollow(requested);
53
+ ctx.sandbox.assertSafeToDelete(target.full);
51
54
  targets.push({ requested, target });
52
55
  }
53
- const entries: Array<{ full: string; requested: string }> = [];
56
+ const entries: Array<{ full: string; requested: string; outside: boolean; directory: boolean }> = [];
54
57
  for (const { requested, target } of targets) {
55
- entries.push({ full: target.full, requested });
56
- if (input.recursive === true) {
57
- const stats = await ctx.sandbox.lstat(target.full, requested);
58
- if (stats.isDirectory()) {
59
- for (const entry of await walkAll(target.full, {
60
- recursive: true,
61
- includeHidden: true,
62
- concurrency: ctx.concurrency,
63
- signal: ctx.signal,
64
- })) {
65
- entries.push({ full: entry.path, requested: entry.path });
66
- }
58
+ const stats = await ctx.sandbox.lstat(target.full, requested);
59
+ entries.push({ full: target.full, requested, outside: target.outside, directory: stats.isDirectory() });
60
+ if (input.recursive === true && stats.isDirectory()) {
61
+ for (const entry of await walkAll(target.full, {
62
+ recursive: true,
63
+ includeHidden: true,
64
+ concurrency: ctx.concurrency,
65
+ signal: ctx.signal,
66
+ })) {
67
+ // Traversal symlinks are skipped: their targets were never resolved or gated.
68
+ if (input.noDereference !== true && entry.stats.isSymbolicLink()) continue;
69
+ entries.push({
70
+ full: entry.path,
71
+ requested: entry.path,
72
+ outside: target.outside,
73
+ directory: entry.stats.isDirectory(),
74
+ });
67
75
  }
68
76
  }
69
77
  }
70
78
  await ctx.permission.assert(entries.map((entry) => ({
71
- target: { full: entry.full, outside: false, requested: entry.requested, realAncestor: entry.full },
72
- boundary: entry.full,
79
+ target: { full: entry.full, outside: entry.outside, requested: entry.requested, realAncestor: entry.full },
80
+ boundary: ctx.sandbox.boundaryFor(entry.full, entry.directory ? "directory" : "file"),
73
81
  })));
74
82
 
75
83
  await mapLimit(entries, ctx.concurrency, async (entry) => {