opencode-fs-plugin 1.1.0 → 1.2.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/sort.ts CHANGED
@@ -4,17 +4,32 @@
4
4
  */
5
5
 
6
6
  import { Type, type Static } from "@sinclair/typebox";
7
- import { collect, inputStream, lines } from "../core/stream.js";
7
+ import { FsError } from "../core/errors.js";
8
+ import { inputStream } from "../core/stream.js";
8
9
  import { textResult, type ToolSpec } from "../core/types.js";
9
10
 
10
11
  const Schema = Type.Object(
11
12
  {
12
13
  paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to sort. Omit to read stdin." })),
13
14
  numeric: Type.Optional(Type.Boolean({ description: "Compare numerically (`-n`)." })),
15
+ generalNumeric: Type.Optional(Type.Boolean({ description: "Compare general numeric values, including exponents (`-g`)." })),
16
+ humanNumeric: Type.Optional(Type.Boolean({ description: "Compare human-readable sizes such as 1K, 2M (`-h`)." })),
17
+ version: Type.Optional(Type.Boolean({ description: "Natural version sort (`-V`)." })),
14
18
  reverse: Type.Optional(Type.Boolean({ description: "Reverse the result (`-r`)." })),
15
19
  unique: Type.Optional(Type.Boolean({ description: "Remove duplicate lines (`-u`)." })),
16
20
  ignoreCase: Type.Optional(Type.Boolean({ description: "Fold case (`-f`)." })),
21
+ dictionary: Type.Optional(Type.Boolean({ description: "Consider only blanks and alphanumerics (`-d`)." })),
22
+ ignoreNonPrinting: Type.Optional(Type.Boolean({ description: "Ignore non-printing characters (`-i`)." })),
17
23
  ignoreLeadingBlanks: Type.Optional(Type.Boolean({ description: "Ignore leading blanks (`-b`)." })),
24
+ stable: Type.Optional(Type.Boolean({ description: "Disable the last-resort whole-line comparison (`-s`)." })),
25
+ check: Type.Optional(Type.Boolean({ description: "Check whether input is sorted (`-c`)." })),
26
+ checkQuiet: Type.Optional(Type.Boolean({ description: "Check sortedness without output (`-C`)." })),
27
+ zeroTerminated: Type.Optional(Type.Boolean({ description: "NUL-separated records (`-z`)." })),
28
+ keys: Type.Optional(
29
+ Type.Array(Type.String({ minLength: 1 }), {
30
+ description: "Sort keys in GNU -k syntax, e.g. 2,2n or 1,1 2.2,2.4.",
31
+ }),
32
+ ),
18
33
  field: Type.Optional(Type.Integer({ minimum: 1, description: "Sort by this 1-based field (`-k`)." })),
19
34
  separator: Type.Optional(Type.String({ description: "Field separator (`-t`). Default: whitespace." })),
20
35
  },
@@ -26,11 +41,13 @@ type Input = Static<typeof Schema>;
26
41
  export const sortTool: ToolSpec<Input> = {
27
42
  name: "sort",
28
43
  description:
29
- "Sort lines with common Linux `sort` semantics (`-n`, `-r`, `-u`, `-f`, `-b`, `-k`, `-t`).",
44
+ "Sort records with Linux `sort` semantics (`-n`, `-g`, `-h`, `-V`, `-r`, `-u`, `-f`, " +
45
+ "`-d`, `-i`, `-b`, `-s`, `-c`, `-C`, `-z`, `-k`, `-t`).",
30
46
  schema: Schema,
31
47
  pipeable: "filter",
32
48
  mutates: false,
33
49
  async run(ctx, input, io) {
50
+ const keys = input.keys === undefined ? undefined : input.keys.map(parseKey);
34
51
  const paths = input.paths ?? [];
35
52
  const targets = [];
36
53
  for (const requested of paths) {
@@ -40,26 +57,126 @@ export const sortTool: ToolSpec<Input> = {
40
57
  if (targets.length > 0) {
41
58
  await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
42
59
  }
60
+
43
61
  const stream = inputStream(targets.map((target) => target.full), io.stdin);
62
+ const separator = input.zeroTerminated === true ? "\0" : "\n";
44
63
  const rows: string[] = [];
45
- for await (const line of lines(stream)) rows.push(line.text);
46
- rows.sort((a, b) => compare(a, b, input));
64
+ for await (const record of records(stream, separator)) rows.push(record);
65
+
66
+ if (input.check === true || input.checkQuiet === true) {
67
+ for (let index = 1; index < rows.length; index++) {
68
+ if (compare(rows[index - 1] as string, rows[index] as string, input, keys) > 0) {
69
+ return textResult(
70
+ input.checkQuiet === true ? "" : `sort: disorder at line ${index + 1}\n`,
71
+ { checked: false, line: index + 1 },
72
+ 1,
73
+ );
74
+ }
75
+ }
76
+ return textResult("", { checked: true });
77
+ }
78
+
79
+ rows.sort((a, b) => compare(a, b, input, keys));
47
80
  const result = input.unique === true ? [...new Set(rows)] : rows;
48
- return textResult(result.map((line) => `${line}\n`).join(""), { lines: result.length });
81
+ return textResult(
82
+ result.map((record) => `${record}${separator}`).join(""),
83
+ { lines: result.length },
84
+ );
49
85
  },
50
86
  };
51
87
 
52
- function compare(a: string, b: string, input: Input): number {
53
- const left = key(a, input);
54
- const right = key(b, input);
55
- let result: number;
56
- if (input.numeric === true) {
57
- result = Number.parseFloat(left) - Number.parseFloat(right);
58
- if (Number.isNaN(result)) result = left.localeCompare(right);
88
+ async function* records(
89
+ stream: AsyncIterable<Buffer>,
90
+ separator: string,
91
+ ): AsyncGenerator<string> {
92
+ let buffer = "";
93
+ for await (const chunk of stream) {
94
+ buffer += chunk.toString("utf8");
95
+ for (;;) {
96
+ const index = buffer.indexOf(separator);
97
+ if (index < 0) break;
98
+ yield buffer.slice(0, index);
99
+ buffer = buffer.slice(index + separator.length);
100
+ }
101
+ }
102
+ if (buffer.length > 0) yield buffer;
103
+ }
104
+
105
+ interface KeySpec {
106
+ startField: number;
107
+ startChar?: number;
108
+ endField?: number;
109
+ endChar?: number;
110
+ modifiers: Set<string>;
111
+ }
112
+
113
+ function parseKey(value: string): KeySpec {
114
+ const match = /^(\d+)(?:\.(\d+))?(?:,(\d+)(?:\.(\d+))?)?([bdfghiMnrV]*)$/.exec(value);
115
+ if (match === null) throw new FsError(`invalid sort key: ${value}`, "invalid");
116
+ return {
117
+ startField: Number(match[1]),
118
+ ...(match[2] === undefined ? {} : { startChar: Number(match[2]) }),
119
+ ...(match[3] === undefined ? {} : { endField: Number(match[3]) }),
120
+ ...(match[4] === undefined ? {} : { endChar: Number(match[4]) }),
121
+ modifiers: new Set((match[5] as string).split("")),
122
+ };
123
+ }
124
+
125
+ function compare(a: string, b: string, input: Input, keys?: KeySpec[]): number {
126
+ if (keys !== undefined && keys.length > 0) {
127
+ for (const spec of keys) {
128
+ const result = compareKey(a, b, spec, input);
129
+ if (result !== 0) return result;
130
+ }
59
131
  } else {
60
- result = input.ignoreCase === true ? left.toLowerCase().localeCompare(right.toLowerCase()) : left.localeCompare(right);
132
+ const result = compareValue(key(a, input), key(b, input), input);
133
+ if (result !== 0) return input.reverse === true ? -result : result;
134
+ }
135
+
136
+ if (input.stable !== true) {
137
+ const result = a.localeCompare(b);
138
+ return result === 0 ? 0 : input.reverse === true ? -result : result;
139
+ }
140
+ return 0;
141
+ }
142
+
143
+ function compareKey(a: string, b: string, spec: KeySpec, input: Input): number {
144
+ const left = keyText(a, spec, input);
145
+ const right = keyText(b, spec, input);
146
+ const result = compareValue(left, right, input, spec);
147
+ if (result === 0) return 0;
148
+ const reverse = spec.modifiers.has("r") ? !(input.reverse === true) : input.reverse === true;
149
+ return reverse ? -result : result;
150
+ }
151
+
152
+ function keyText(value: string, spec: KeySpec, input: Input): string {
153
+ const fields = input.separator === undefined ? value.split(/\s+/) : value.split(input.separator);
154
+ const joined = fields
155
+ .slice(spec.startField - 1, spec.endField ?? fields.length)
156
+ .join(input.separator ?? " ");
157
+ let text = joined;
158
+ if (spec.startChar !== undefined) text = text.slice(Math.max(0, spec.startChar - 1));
159
+ if (spec.endChar !== undefined) text = text.slice(0, Math.max(0, spec.endChar));
160
+ if (spec.modifiers.has("b") || input.ignoreLeadingBlanks === true) text = text.trimStart();
161
+ return text;
162
+ }
163
+
164
+ function compareValue(left: string, right: string, input: Input, spec?: KeySpec): number {
165
+ if (spec?.modifiers.has("V") === true || input.version === true) {
166
+ return versionCompare(left, right);
167
+ }
168
+ if (spec?.modifiers.has("g") === true || input.generalNumeric === true) {
169
+ return numeric(left) - numeric(right);
61
170
  }
62
- return input.reverse === true ? -result : result;
171
+ if (spec?.modifiers.has("h") === true || input.humanNumeric === true) {
172
+ return humanNumeric(left) - humanNumeric(right);
173
+ }
174
+ if (spec?.modifiers.has("n") === true || input.numeric === true) {
175
+ return numeric(left) - numeric(right);
176
+ }
177
+ const leftText = normalizeText(left, input, spec);
178
+ const rightText = normalizeText(right, input, spec);
179
+ return leftText.localeCompare(rightText);
63
180
  }
64
181
 
65
182
  function key(value: string, input: Input): string {
@@ -71,3 +188,53 @@ function key(value: string, input: Input): string {
71
188
  }
72
189
  return text;
73
190
  }
191
+
192
+ function normalizeText(value: string, input: Input, spec?: KeySpec): string {
193
+ let text = value;
194
+ if (spec?.modifiers.has("i") === true || input.ignoreNonPrinting === true) {
195
+ text = text.replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
196
+ }
197
+ if (spec?.modifiers.has("d") === true || input.dictionary === true) {
198
+ text = text.replace(/[^A-Za-z0-9\s]/g, "");
199
+ }
200
+ if (spec?.modifiers.has("f") === true || input.ignoreCase === true) {
201
+ text = text.toLowerCase();
202
+ }
203
+ return text;
204
+ }
205
+
206
+ function numeric(value: string): number {
207
+ const match = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(value);
208
+ return match === null ? 0 : Number(match[0]);
209
+ }
210
+
211
+ function humanNumeric(value: string): number {
212
+ const match = /^([+-]?(?:\d+\.?\d*|\.\d+))\s*([KMGTPEZY]?)/i.exec(value);
213
+ if (match === null) return 0;
214
+ const number = Number(match[1]);
215
+ const suffix = String(match[2]).toUpperCase();
216
+ const power = suffix === "" ? 0 : "KMGTPEZY".indexOf(suffix) + 1;
217
+ return number * 1024 ** power;
218
+ }
219
+
220
+ function versionCompare(left: string, right: string): number {
221
+ const leftParts = left.match(/\d+|\D+/g) ?? [];
222
+ const rightParts = right.match(/\d+|\D+/g) ?? [];
223
+ const length = Math.max(leftParts.length, rightParts.length);
224
+ for (let index = 0; index < length; index++) {
225
+ const a = leftParts[index];
226
+ const b = rightParts[index];
227
+ /* v8 ignore next */
228
+ if (a === undefined) return -1;
229
+ /* v8 ignore next */
230
+ if (b === undefined) return 1;
231
+ if (/^\d+$/.test(a) && /^\d+$/.test(b)) {
232
+ const difference = Number(a) - Number(b);
233
+ if (difference !== 0) return difference;
234
+ } else {
235
+ const result = a.localeCompare(b);
236
+ if (result !== 0) return result;
237
+ }
238
+ }
239
+ return 0;
240
+ }
package/src/tools/stat.ts CHANGED
@@ -14,6 +14,7 @@ const Schema = Type.Object(
14
14
  paths: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
15
15
  follow: Type.Optional(Type.Boolean({ description: "Follow symlinks (`-L`)." })),
16
16
  format: Type.Optional(Type.String({ description: "printf-style format string (`-c`, `--printf`)." })),
17
+ terse: Type.Optional(Type.Boolean({ description: "Terse single-line output (`-t`)." })),
17
18
  filesystem: Type.Optional(Type.Boolean({ description: "Show filesystem status (`-f`)." })),
18
19
  },
19
20
  { additionalProperties: false },
@@ -47,7 +48,9 @@ export const statTool: ToolSpec<Input> = {
47
48
  const link = stats.isSymbolicLink() ? await fs.readlink(target.full).catch(() => undefined) : undefined;
48
49
  blocks.push(
49
50
  input.format === undefined
50
- ? await defaultFormat(requested, target.full, stats, link)
51
+ ? input.terse === true
52
+ ? await terseFormat(requested, stats)
53
+ : await defaultFormat(requested, target.full, stats, link)
51
54
  : await customFormat(input.format, requested, target.full, stats, link),
52
55
  );
53
56
  }
@@ -95,6 +98,7 @@ async function customFormat(
95
98
  F: typeName(stats),
96
99
  a: (num(stats.mode) & 0o7777).toString(8),
97
100
  A: modeString(stats),
101
+ f: num(stats.mode).toString(16),
98
102
  u: String(num(stats.uid)),
99
103
  U: await lookupUser(num(stats.uid)),
100
104
  g: String(num(stats.gid)),
@@ -105,14 +109,20 @@ async function customFormat(
105
109
  b: String(num(stats.blocks)),
106
110
  B: String(num(stats.blksize)),
107
111
  o: String(num(stats.blksize)),
112
+ m: await mountPoint(full),
113
+ r: num(stats.rdev).toString(16),
108
114
  x: stats.atime.toISOString(),
109
115
  X: String(Math.floor(num(stats.atimeMs) / 1000)),
110
116
  y: stats.mtime.toISOString(),
111
117
  Y: String(Math.floor(num(stats.mtimeMs) / 1000)),
112
118
  z: stats.ctime.toISOString(),
113
119
  Z: String(Math.floor(num(stats.ctimeMs) / 1000)),
120
+ /* v8 ignore next -- some filesystems do not expose a birth time */
121
+ w: stats.birthtimeMs === 0 ? "-" : stats.birthtime.toISOString(),
122
+ W: String(Math.floor(num(stats.birthtimeMs) / 1000)),
114
123
  t: Math.floor(num(stats.rdev) / 256).toString(16),
115
124
  T: (num(stats.rdev) % 256).toString(16),
125
+ C: "?",
116
126
  L: full,
117
127
  };
118
128
  let output = "";
@@ -139,6 +149,57 @@ async function customFormat(
139
149
  return output;
140
150
  }
141
151
 
152
+ async function terseFormat(
153
+ requested: string,
154
+ stats: Awaited<ReturnType<typeof fs.lstat>>,
155
+ ): Promise<string> {
156
+ return [
157
+ requested,
158
+ num(stats.size),
159
+ num(stats.blocks),
160
+ num(stats.mode).toString(16),
161
+ num(stats.uid),
162
+ num(stats.gid),
163
+ num(stats.dev),
164
+ num(stats.ino),
165
+ num(stats.nlink),
166
+ num(stats.rdev).toString(16),
167
+ Math.floor(num(stats.atimeMs) / 1000),
168
+ Math.floor(num(stats.mtimeMs) / 1000),
169
+ Math.floor(num(stats.ctimeMs) / 1000),
170
+ Math.floor(num(stats.birthtimeMs) / 1000),
171
+ num(stats.blksize),
172
+ ].join(" ");
173
+ }
174
+
175
+ let mountPoints: string[] | undefined;
176
+
177
+ async function mountPoint(full: string): Promise<string> {
178
+ if (mountPoints === undefined) {
179
+ const points: string[] = [];
180
+ /* v8 ignore next -- /proc/self/mountinfo exists on Linux */
181
+ const text = await fs.readFile("/proc/self/mountinfo", "utf8").catch(() => "");
182
+ for (const line of text.split("\n")) {
183
+ const fields = line.split(" ");
184
+ const point = fields[4];
185
+ if (point !== undefined) {
186
+ /* v8 ignore next 2 -- escaped mount points are rare */
187
+ points.push(point.replace(/\\([0-7]{3})/g, (_match: string, octal: string) =>
188
+ String.fromCharCode(Number.parseInt(octal, 8))));
189
+ }
190
+ }
191
+ mountPoints = points;
192
+ }
193
+ let best = "/";
194
+ for (const point of mountPoints) {
195
+ if (full === point || full.startsWith(point === "/" ? "/" : `${point}/`)) {
196
+ /* v8 ignore next -- CI may only expose the root mount */
197
+ if (point.length > best.length) best = point;
198
+ }
199
+ }
200
+ return best;
201
+ }
202
+
142
203
  async function formatFilesystem(requested: string, full: string): Promise<string> {
143
204
  let stats;
144
205
  try {
package/src/tools/tail.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
4
  */
5
5
 
6
+ import * as fs from "node:fs/promises";
6
7
  import { Type, type Static } from "@sinclair/typebox";
7
8
  import { collect, inputStream, readFiles } from "../core/stream.js";
8
9
  import { textResult, type ToolSpec } from "../core/types.js";
@@ -16,6 +17,16 @@ const Schema = Type.Object(
16
17
  fromStart: Type.Optional(Type.Boolean({ description: "Treat lines as a 1-based starting line (`-n +N`)." })),
17
18
  quiet: Type.Optional(Type.Boolean({ description: "Never print file headers (`-q`)." })),
18
19
  verbose: Type.Optional(Type.Boolean({ description: "Always print file headers (`-v`)." })),
20
+ follow: Type.Optional(Type.Boolean({ description: "Follow appended data for a bounded interval (`-f`)." })),
21
+ timeoutMs: Type.Optional(
22
+ Type.Integer({ minimum: 100, maximum: 600_000, description: "Follow duration. Default: 10000." }),
23
+ ),
24
+ intervalMs: Type.Optional(
25
+ Type.Integer({ minimum: 50, maximum: 10_000, description: "Follow poll interval. Default: 250." }),
26
+ ),
27
+ maxBytes: Type.Optional(
28
+ Type.Integer({ minimum: 1, description: "Maximum appended bytes to return. Default: 1048576." }),
29
+ ),
19
30
  },
20
31
  { additionalProperties: false },
21
32
  );
@@ -26,7 +37,7 @@ export const tailTool: ToolSpec<Input> = {
26
37
  name: "tail",
27
38
  description:
28
39
  "Output the last part of files or stdin with Linux `tail` semantics (`-n`, `-n +N`, `-c`, `-q`, `-v`). " +
29
- "Follow mode (`-f`) is not supported.",
40
+ "Bounded follow mode (`-f`) requires one file and a timeout.",
30
41
  schema: Schema,
31
42
  pipeable: "filter",
32
43
  mutates: false,
@@ -38,15 +49,30 @@ export const tailTool: ToolSpec<Input> = {
38
49
  const paths = input.paths ?? [];
39
50
  const targets = [];
40
51
  for (const requested of paths) {
41
- const target = await ctx.sandbox.resolveFollow(requested);
52
+ const target = await ctx.sandbox.resolveFollow(requested).catch(async (error) => {
53
+ if (input.follow === true && error instanceof FsError && error.code === "not-found") {
54
+ return ctx.sandbox.resolveForCreate(requested);
55
+ }
56
+ throw error;
57
+ });
42
58
  targets.push({ requested, full: target.full, target });
43
59
  }
44
60
  if (targets.length > 0) {
45
61
  await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
46
62
  }
47
63
 
64
+ if (input.follow === true && targets.length !== 1) {
65
+ throw new FsError("follow requires exactly one file.", "invalid");
66
+ }
67
+
48
68
  const output: Buffer[] = [];
49
- if (targets.length === 0) {
69
+ if (input.follow === true) {
70
+ const target = targets[0] as (typeof targets)[number];
71
+ if (input.quiet !== true && input.verbose === true) {
72
+ output.push(Buffer.from(`==> ${target.requested} <==\n`));
73
+ }
74
+ output.push(await follow(target.full, count, input, ctx.signal));
75
+ } else if (targets.length === 0) {
50
76
  const data = await collect(await inputStream([], io.stdin));
51
77
  output.push(tailBuffer(data, count, input));
52
78
  } else {
@@ -62,6 +88,84 @@ export const tailTool: ToolSpec<Input> = {
62
88
  },
63
89
  };
64
90
 
91
+ async function follow(
92
+ full: string,
93
+ count: number,
94
+ input: Input,
95
+ signal: AbortSignal,
96
+ ): Promise<Buffer> {
97
+ const timeoutMs = Math.min(600_000, Math.max(100, input.timeoutMs ?? 10_000));
98
+ const intervalMs = Math.min(10_000, Math.max(50, input.intervalMs ?? 250));
99
+ const maxBytes = input.maxBytes ?? 1024 * 1024;
100
+ const deadline = Date.now() + timeoutMs;
101
+ const output: Buffer[] = [];
102
+ let offset = 0;
103
+ let appended = 0;
104
+ if (signal.aborted) return Buffer.alloc(0);
105
+
106
+ try {
107
+ const initial = await fs.readFile(full);
108
+ output.push(tailBuffer(initial, count, input));
109
+ offset = initial.length;
110
+ } catch {
111
+ // Follow starts when the file appears.
112
+ }
113
+
114
+ while (Date.now() < deadline && !signal.aborted && appended < maxBytes) {
115
+ let stats: Awaited<ReturnType<typeof fs.stat>> | undefined;
116
+ try {
117
+ stats = await fs.stat(full);
118
+ } catch {
119
+ offset = 0;
120
+ await delay(intervalMs, signal);
121
+ continue;
122
+ }
123
+ if (stats.size < offset) offset = 0;
124
+ if (stats.size > offset) {
125
+ const length = Math.min(stats.size - offset, maxBytes - appended);
126
+ const data = await readRange(full, offset, length);
127
+ /* v8 ignore next -- the file can shrink between stat and read */
128
+ if (data.length > 0) {
129
+ output.push(data);
130
+ offset += data.length;
131
+ appended += data.length;
132
+ }
133
+ }
134
+ await delay(intervalMs, signal);
135
+ }
136
+ return Buffer.concat(output);
137
+ }
138
+
139
+ async function readRange(full: string, start: number, length: number): Promise<Buffer> {
140
+ const handle = await fs.open(full, "r");
141
+ try {
142
+ const buffer = Buffer.alloc(Math.max(0, length));
143
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, start);
144
+ return buffer.subarray(0, bytesRead);
145
+ } finally {
146
+ await handle.close();
147
+ }
148
+ }
149
+
150
+ function delay(ms: number, signal: AbortSignal): Promise<void> {
151
+ return new Promise((resolve) => {
152
+ /* v8 ignore next 4 -- follow checks the signal before calling delay */
153
+ if (signal.aborted) {
154
+ resolve();
155
+ return;
156
+ }
157
+ const timer = setTimeout(() => {
158
+ signal.removeEventListener("abort", onAbort);
159
+ resolve();
160
+ }, ms);
161
+ const onAbort = () => {
162
+ clearTimeout(timer);
163
+ resolve();
164
+ };
165
+ signal.addEventListener("abort", onAbort, { once: true });
166
+ });
167
+ }
168
+
65
169
  function tailBuffer(data: Buffer, count: number, input: Input): Buffer {
66
170
  if (input.bytes !== undefined) return data.subarray(Math.max(0, data.length - count));
67
171
  const text = data.toString("utf8");
package/src/tools/tar.ts CHANGED
@@ -29,6 +29,8 @@ const Schema = Type.Object(
29
29
  stripComponents: Type.Optional(Type.Integer({ minimum: 0, description: "Strip leading path components (`--strip-components`)." })),
30
30
  exclude: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Exclude globs." })),
31
31
  verbose: Type.Optional(Type.Boolean({ description: "List processed members (`-v`)." })),
32
+ input: Type.Optional(Type.String({ description: "Text data to archive when paths are omitted." })),
33
+ member: Type.Optional(Type.String({ description: "Archive member name for stream input." })),
32
34
  },
33
35
  { additionalProperties: false },
34
36
  );
@@ -41,16 +43,53 @@ export const tarTool: ToolSpec<Input> = {
41
43
  "Create, list or extract tar archives with common `tar` semantics (`-c`, `-x`, `-t`, `-f`, " +
42
44
  "`-z`, `-C`, `--strip-components`, `--exclude`). Extraction rejects path escapes.",
43
45
  schema: Schema,
44
- pipeable: false,
46
+ pipeable: "sink",
45
47
  mutates: true,
46
- async run(ctx, input) {
48
+ async run(ctx, input, io) {
47
49
  const archive = await ctx.sandbox.resolveForCreate(input.archive);
48
50
  const useGzip = input.gzip ?? /\.(?:tgz|tar\.gz)$/i.test(input.archive);
49
51
  const excludes = input.exclude === undefined ? undefined : picomatch(input.exclude, { dot: true, basename: true });
50
52
  const names: string[] = [];
51
53
 
52
54
  if (input.mode === "create") {
53
- if (input.paths === undefined || input.paths.length === 0) throw new FsError("create requires paths.", "invalid");
55
+ if (input.paths === undefined || input.paths.length === 0) {
56
+ if (input.input === undefined && io.stdin === undefined) {
57
+ throw new FsError("create requires paths, input, or stdin.", "invalid");
58
+ }
59
+ const data = io.stdin === undefined
60
+ ? Buffer.from(input.input as string, "utf8")
61
+ : await collect(io.stdin);
62
+ const name = safeMember(input.member ?? "stdin", 0);
63
+ if (name === undefined) throw new FsError("member must not be empty.", "invalid");
64
+ await ctx.permission.assert([{ target: archive, boundary: archive.full }]);
65
+ const pack = tar.pack();
66
+ const header: tar.Header = {
67
+ name: name.split(path.sep).join("/"),
68
+ size: data.length,
69
+ mode: 0o644,
70
+ mtime: new Date(),
71
+ type: "file",
72
+ linkname: "",
73
+ uid: 0,
74
+ gid: 0,
75
+ uname: "",
76
+ gname: "",
77
+ devmajor: 0,
78
+ devminor: 0,
79
+ };
80
+ pack.entry(header, data);
81
+ pack.finalize();
82
+ let buffer = await collect(pack as AsyncIterable<Buffer>);
83
+ if (useGzip) buffer = await gzipAsync(buffer);
84
+ /* v8 ignore next 3 */
85
+ await fs.writeFile(archive.full, buffer).catch((error) => {
86
+ throw fromErrno(error);
87
+ });
88
+ return textResult(input.verbose === true ? `${header.name}\n` : "", {
89
+ archive: input.archive,
90
+ members: [header.name],
91
+ });
92
+ }
54
93
  const members: Array<{ name: string; full: string; stats: Awaited<ReturnType<typeof fs.lstat>> }> = [];
55
94
  for (const requested of input.paths) {
56
95
  const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
package/src/tools/zip.ts CHANGED
@@ -15,8 +15,10 @@ import { textResult, type ToolSpec } from "../core/types.js";
15
15
  const ZipSchema = Type.Object(
16
16
  {
17
17
  archive: Type.String({ minLength: 1, description: "ZIP archive to create." }),
18
- paths: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
18
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })),
19
19
  level: Type.Optional(Type.Integer({ minimum: 0, maximum: 9, description: "Compression level." })),
20
+ input: Type.Optional(Type.String({ description: "Text data to archive when paths are omitted." })),
21
+ member: Type.Optional(Type.String({ description: "Archive member name for stream input." })),
20
22
  },
21
23
  { additionalProperties: false },
22
24
  );
@@ -41,12 +43,39 @@ export const zipTool: ToolSpec<ZipInput> = {
41
43
  name: "zip",
42
44
  description: "Create ZIP archives with common `zip` semantics (`-r` is implicit, compression level 0-9).",
43
45
  schema: ZipSchema,
44
- pipeable: false,
46
+ pipeable: "sink",
45
47
  mutates: true,
46
- async run(ctx, input) {
48
+ async run(ctx, input, io) {
47
49
  const archive = await ctx.sandbox.resolveForCreate(input.archive);
50
+ const requestedPaths = input.paths ?? [];
51
+ if (requestedPaths.length === 0) {
52
+ if (input.input === undefined && io.stdin === undefined) {
53
+ throw new FsError("create requires paths, input, or stdin.", "invalid");
54
+ }
55
+ const data = io.stdin === undefined
56
+ ? Buffer.from(input.input as string, "utf8")
57
+ : await collect(io.stdin);
58
+ const name = safeName(input.member ?? "stdin");
59
+ if (name === undefined) throw new FsError("member must not be empty.", "invalid");
60
+ await ctx.permission.assert([{ target: archive, boundary: archive.full }]);
61
+ const writer = new ZipWriter();
62
+ writer.addBuffer(data, name.split(path.sep).join("/"), {
63
+ mtime: new Date(),
64
+ mode: 0o644,
65
+ compress: (input.level ?? 6) !== 0,
66
+ compressionLevel: input.level ?? 6,
67
+ });
68
+ writer.end();
69
+ const streamed = await collect(writer.outputStream as AsyncIterable<Buffer>);
70
+ /* v8 ignore next */
71
+ await fs.writeFile(archive.full, streamed).catch((error) => {
72
+ throw fromErrno(error);
73
+ });
74
+ return textResult("", { archive: input.archive, members: 1 });
75
+ }
76
+
48
77
  const members: Array<{ name: string; full: string; stats: Awaited<ReturnType<typeof fs.lstat>> }> = [];
49
- for (const requested of input.paths) {
78
+ for (const requested of requestedPaths) {
50
79
  const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
51
80
  const stats = await ctx.sandbox.lstat(target.full, requested);
52
81
  const base = path.basename(path.resolve(requested));