pi-agent-flow 1.0.8 → 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/batch.ts ADDED
@@ -0,0 +1,1221 @@
1
+ /**
2
+ * batch — Unified batch file operations tool.
3
+ *
4
+ * Combines read, write, edit, and delete into a single tool call.
5
+ * Executes operations sequentially with skip-on-failure semantics.
6
+ */
7
+
8
+ import * as fs from "node:fs/promises";
9
+ import * as os from "node:os";
10
+ import * as path from "node:path";
11
+ import { Type } from "@sinclair/typebox";
12
+ import { Text, TruncatedText } from "@mariozechner/pi-tui";
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // Schema
16
+ // ---------------------------------------------------------------------------
17
+
18
+ const EditOp = Type.Object({
19
+ f: Type.String({
20
+ description:
21
+ "Exact text to find (oldText). Must be unique in the file. All edits matched against original file, not incrementally.",
22
+ }),
23
+ r: Type.String({ description: "Replacement text (newText)." }),
24
+ });
25
+
26
+ const FileOp = Type.Object({
27
+ o: Type.Union([
28
+ Type.Literal("read"),
29
+ Type.Literal("write"),
30
+ Type.Literal("edit"),
31
+ Type.Literal("delete"),
32
+ ]),
33
+ p: Type.String({ description: "Path to the file (relative or absolute)" }),
34
+ c: Type.Optional(
35
+ Type.String({
36
+ description:
37
+ "Full file content. Creates if new, overwrites if exists. Auto-creates parent dirs. Used with o: 'write'.",
38
+ }),
39
+ ),
40
+ e: Type.Optional(
41
+ Type.Array(EditOp, {
42
+ description:
43
+ "One or more targeted replacements matched against the original file, not incrementally.",
44
+ }),
45
+ ),
46
+ s: Type.Optional(
47
+ Type.Number({
48
+ minimum: 1,
49
+ description:
50
+ "1-indexed line number to start reading from (offset). Used with o: 'read'.",
51
+ }),
52
+ ),
53
+ l: Type.Optional(
54
+ Type.Number({
55
+ minimum: 1,
56
+ description:
57
+ "Maximum number of lines to read (limit). Used with o: 'read'.",
58
+ }),
59
+ ),
60
+ });
61
+
62
+ export const WeavePatchParams = Type.Object({
63
+ o: Type.Array(FileOp, {
64
+ description:
65
+ "Ordered list of file operations. Executed sequentially. On failure, remaining operations are skipped.",
66
+ }),
67
+ });
68
+
69
+ // ---------------------------------------------------------------------------
70
+ // Types
71
+ // ---------------------------------------------------------------------------
72
+
73
+ interface EditReplacement {
74
+ f: string;
75
+ r: string;
76
+ }
77
+
78
+ interface FileOpInput {
79
+ o: "read" | "write" | "edit" | "delete";
80
+ p: string;
81
+ c?: string;
82
+ e?: EditReplacement[];
83
+ s?: number;
84
+ l?: number;
85
+ }
86
+
87
+ interface OpResult {
88
+ op: "read" | "write" | "edit" | "delete";
89
+ path: string;
90
+ status: "ok" | "error" | "skipped";
91
+ content?: string;
92
+ bytes?: number;
93
+ blocksChanged?: number;
94
+ totalLines?: number;
95
+ truncated?: boolean;
96
+ nextOffset?: number;
97
+ error?: string;
98
+ hint?: string;
99
+ }
100
+
101
+ interface ReadTruncationResult {
102
+ content: string;
103
+ truncated: boolean;
104
+ nextOffset?: number;
105
+ linesRead: number;
106
+ }
107
+
108
+ interface ReadOptions {
109
+ /**
110
+ * When false, read operations ignore MAX_LINES and total MAX_BYTES caps.
111
+ * A single selected line that exceeds MAX_BYTES still fails with a targeted error.
112
+ */
113
+ truncate?: boolean;
114
+ toolName?: "batch" | "batch_read";
115
+ }
116
+
117
+ interface ExecuteOptions {
118
+ readOptions?: ReadOptions;
119
+ includeLimitWarnings?: boolean;
120
+ }
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // Helpers
124
+ // ---------------------------------------------------------------------------
125
+
126
+ const MAX_LINES = 2000;
127
+ const MAX_BYTES = 50 * 1024; // 50KB
128
+
129
+ function normalizeToLF(text: string): string {
130
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
131
+ }
132
+
133
+ function restoreLineEndings(text: string, ending: string): string {
134
+ return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text;
135
+ }
136
+
137
+ function detectLineEnding(content: string): string {
138
+ const crlfIdx = content.indexOf("\r\n");
139
+ const lfIdx = content.indexOf("\n");
140
+ if (lfIdx === -1) return "\n";
141
+ if (crlfIdx === -1) return "\n";
142
+ return crlfIdx < lfIdx ? "\r\n" : "\n";
143
+ }
144
+
145
+ function stripBom(content: string): { bom: string; text: string } {
146
+ return content.startsWith("\uFEFF")
147
+ ? { bom: "\uFEFF", text: content.slice(1) }
148
+ : { bom: "", text: content };
149
+ }
150
+
151
+ function readWithOffsetLimit(
152
+ content: string,
153
+ offset?: number,
154
+ limit?: number,
155
+ filePath?: string,
156
+ options: ReadOptions = {},
157
+ ): ReadTruncationResult {
158
+ const allLines = content.split("\n");
159
+ const totalFileLines = allLines.length;
160
+ const shouldTruncate = options.truncate !== false;
161
+ const toolName = options.toolName ?? "batch";
162
+
163
+ // Validate offset
164
+ if (offset !== undefined && offset > totalFileLines) {
165
+ throw new Error(
166
+ `Offset ${offset} is beyond end of file (${totalFileLines} lines total)`,
167
+ );
168
+ }
169
+
170
+ // Determine the start line (convert 1-indexed to 0-indexed)
171
+ const startLine = offset !== undefined ? Math.max(0, offset - 1) : 0;
172
+
173
+ // Determine end line
174
+ let endLine = totalFileLines;
175
+ if (limit !== undefined) {
176
+ endLine = Math.min(startLine + limit, totalFileLines);
177
+ }
178
+
179
+ let selectedLines = allLines.slice(startLine, endLine);
180
+ let truncated = false;
181
+ let nextOffset: number | undefined;
182
+
183
+ // Apply max-lines cap for regular batch reads. batch_read intentionally
184
+ // bypasses this cap so each read operation can return the full requested file
185
+ // or range.
186
+ if (shouldTruncate && selectedLines.length > MAX_LINES) {
187
+ selectedLines = selectedLines.slice(0, MAX_LINES);
188
+ truncated = true;
189
+ }
190
+
191
+ // A single selected line that exceeds the byte cap is not safely splittable by
192
+ // line-oriented offsets, so keep the existing hard error in both modes.
193
+ for (let i = 0; i < selectedLines.length; i++) {
194
+ if (Buffer.byteLength(selectedLines[i], "utf-8") > MAX_BYTES) {
195
+ const lineDisplay = startLine + i + 1;
196
+ throw new Error(
197
+ `Line ${lineDisplay} exceeds limit. Try: ${toolName} with o:"read", s:${lineDisplay}, l:10, or use bash: head -c ... ${filePath ?? "<file>"}`,
198
+ );
199
+ }
200
+ }
201
+
202
+ // Join and check byte size
203
+ let result = selectedLines.join("\n");
204
+
205
+ // Truncate by total bytes for regular batch reads only. batch_read keeps the
206
+ // complete selected multi-line content unless an individual line is too long.
207
+ if (shouldTruncate && Buffer.byteLength(result, "utf-8") > MAX_BYTES) {
208
+ let byteAccum = 0;
209
+ let keepLines = 0;
210
+ for (let i = 0; i < selectedLines.length; i++) {
211
+ byteAccum += Buffer.byteLength(selectedLines[i], "utf-8") + (i > 0 ? 1 : 0); // newline separator between lines
212
+ if (byteAccum > MAX_BYTES) break;
213
+ keepLines = i + 1;
214
+ }
215
+ selectedLines = selectedLines.slice(0, keepLines);
216
+ result = selectedLines.join("\n");
217
+ truncated = true;
218
+ }
219
+
220
+ // Calculate nextOffset for continuation
221
+ const lastLineRead = startLine + selectedLines.length;
222
+ if (truncated || (limit !== undefined && lastLineRead < totalFileLines)) {
223
+ nextOffset = lastLineRead + 1; // 1-indexed
224
+ }
225
+
226
+ // Append truncation/continuation hints
227
+ if (truncated) {
228
+ const endDisplay = startLine + selectedLines.length;
229
+ const startDisplay = startLine + 1;
230
+ result += `\n\n[Showing lines ${startDisplay}-${endDisplay} of ${totalFileLines}. Use s=${nextOffset} to continue.]`;
231
+ } else if (limit !== undefined && lastLineRead < totalFileLines) {
232
+ const remaining = totalFileLines - lastLineRead;
233
+ result += `\n\n[${remaining} more lines in file. Use s=${nextOffset} to continue.]`;
234
+ }
235
+
236
+ return { content: result, truncated, nextOffset, linesRead: selectedLines.length };
237
+ }
238
+
239
+ function levenshtein(a: string, b: string): number {
240
+ const m = a.length;
241
+ const n = b.length;
242
+ const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
243
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
244
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
245
+ for (let i = 1; i <= m; i++) {
246
+ for (let j = 1; j <= n; j++) {
247
+ dp[i][j] =
248
+ a[i - 1] === b[j - 1]
249
+ ? dp[i - 1][j - 1]
250
+ : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
251
+ }
252
+ }
253
+ return dp[m][n];
254
+ }
255
+
256
+ /**
257
+ * Scan the parent directory (or cwd) for files with similar names.
258
+ * Returns up to 3 suggestions sorted by similarity.
259
+ */
260
+ export async function suggestSimilarFiles(
261
+ inputPath: string,
262
+ cwd: string,
263
+ ): Promise<string[]> {
264
+ const resolved = path.resolve(cwd, inputPath);
265
+ const dir = path.dirname(resolved);
266
+ const target = path.basename(resolved);
267
+
268
+ try {
269
+ const entries = await fs.readdir(dir, { withFileTypes: true });
270
+ const candidates: { name: string; dist: number }[] = [];
271
+
272
+ for (const entry of entries) {
273
+ const name = entry.name;
274
+ // Skip hidden files and node_modules
275
+ if (name.startsWith(".") || name === "node_modules") continue;
276
+
277
+ const dist = levenshtein(target.toLowerCase(), name.toLowerCase());
278
+ const maxLen = Math.max(target.length, name.length);
279
+ // Only suggest if reasonably similar (within 40% edit distance, or shares prefix)
280
+ if (dist <= Math.ceil(maxLen * 0.4) || name.startsWith(target.slice(0, 3))) {
281
+ candidates.push({ name: entry.isDirectory() ? name + "/" : name, dist });
282
+ }
283
+ }
284
+
285
+ return candidates
286
+ .sort((a, b) => a.dist - b.dist)
287
+ .slice(0, 3)
288
+ .map((c) => path.join(path.relative(cwd, dir), c.name));
289
+ } catch {
290
+ return [];
291
+ }
292
+ }
293
+
294
+ function getErrorHint(error: string): string {
295
+ if (error.includes("File not found") || error.includes("file not found"))
296
+ return "Verify the path exists.";
297
+ if (error.includes("Could not find"))
298
+ return "Re-read the file first, then retry with exact f (oldText).";
299
+ if (error.includes("occurrences"))
300
+ return "Add more surrounding context to make oldText unique.";
301
+ if (error.includes("overlap"))
302
+ return "Merge overlapping edits into one.";
303
+ if (error.includes("No changes"))
304
+ return "File already has this content. No edit needed.";
305
+ if (error.includes("is not readable") || error.includes("not readable"))
306
+ return "Check file permissions.";
307
+ if (error.includes("ENOENT") || error.includes("no such file"))
308
+ return "Verify the path exists.";
309
+ if (error.includes("is beyond end of file"))
310
+ return "Use a smaller offset within the file length.";
311
+ return "";
312
+ }
313
+
314
+ // ---------------------------------------------------------------------------
315
+ // Fuzzy matching (simplified)
316
+ // ---------------------------------------------------------------------------
317
+
318
+ function normalizeForMatch(text: string): string {
319
+ return text
320
+ .split("\n")
321
+ .map((line) => line.trimEnd())
322
+ .join("\n");
323
+ }
324
+
325
+ function buildPositionMap(original: string): number[] {
326
+ const normalized = normalizeForMatch(original);
327
+ const map: number[] = new Array(normalized.length + 1);
328
+ let oi = 0;
329
+ let ni = 0;
330
+
331
+ while (oi < original.length && ni < normalized.length) {
332
+ map[ni] = oi;
333
+ if (original[oi] === normalized[ni]) {
334
+ oi++;
335
+ ni++;
336
+ } else {
337
+ oi++;
338
+ }
339
+ }
340
+
341
+ while (ni < normalized.length) {
342
+ map[ni] = oi;
343
+ ni++;
344
+ }
345
+
346
+ map[normalized.length] = original.length;
347
+ return map;
348
+ }
349
+
350
+ function fuzzyFindText(
351
+ content: string,
352
+ oldText: string,
353
+ ): { found: boolean; index: number; matchLength: number; isExact: boolean } {
354
+ // Try exact match first
355
+ const exactIndex = content.indexOf(oldText);
356
+ if (exactIndex !== -1) {
357
+ return { found: true, index: exactIndex, matchLength: oldText.length, isExact: true };
358
+ }
359
+
360
+ // Try trimmed match, returning original indices
361
+ const normalizedContent = normalizeForMatch(content);
362
+ const normalizedOld = normalizeForMatch(oldText);
363
+ const fuzzyIndex = normalizedContent.indexOf(normalizedOld);
364
+ if (fuzzyIndex !== -1) {
365
+ const map = buildPositionMap(content);
366
+ const originalStart = map[fuzzyIndex];
367
+ const originalEnd = map[fuzzyIndex + normalizedOld.length];
368
+ return { found: true, index: originalStart, matchLength: originalEnd - originalStart, isExact: false };
369
+ }
370
+
371
+ return { found: false, index: -1, matchLength: 0, isExact: false };
372
+ }
373
+
374
+ function countOccurrences(content: string, oldText: string): number {
375
+ const normalizedContent = normalizeForMatch(content);
376
+ const normalizedOld = normalizeForMatch(oldText);
377
+ let count = 0;
378
+ let pos = 0;
379
+ while (true) {
380
+ const idx = normalizedContent.indexOf(normalizedOld, pos);
381
+ if (idx === -1) break;
382
+ count++;
383
+ pos = idx + normalizedOld.length;
384
+ }
385
+ return count;
386
+ }
387
+
388
+ function countExactOccurrences(content: string, oldText: string): number {
389
+ let count = 0;
390
+ let pos = 0;
391
+ while (true) {
392
+ const idx = content.indexOf(oldText, pos);
393
+ if (idx === -1) break;
394
+ count++;
395
+ pos = idx + oldText.length;
396
+ }
397
+ return count;
398
+ }
399
+
400
+ // ---------------------------------------------------------------------------
401
+ // Edit logic
402
+ // ---------------------------------------------------------------------------
403
+
404
+ /**
405
+ * Apply a fuzzy edit, preserving trailing whitespace from the original matched
406
+ * text that wasn't explicitly present in the oldText.
407
+ *
408
+ * This prevents normalizeForMatch from stripping trailing whitespace on lines
409
+ * that are being edited when fuzzy matching is used.
410
+ */
411
+ function applyFuzzyEdit(
412
+ content: string,
413
+ matchIndex: number,
414
+ matchLength: number,
415
+ oldText: string,
416
+ newText: string,
417
+ ): string {
418
+ const before = content.substring(0, matchIndex);
419
+ const after = content.substring(matchIndex + matchLength);
420
+ const matched = content.substring(matchIndex, matchIndex + matchLength);
421
+
422
+ const matchedLines = matched.split("\n");
423
+ const oldLines = oldText.split("\n");
424
+ const newLines = newText.split("\n");
425
+
426
+ const resultLines: string[] = [];
427
+ for (let i = 0; i < newLines.length; i++) {
428
+ const newLine = newLines[i];
429
+ const oldLine = oldLines[i] ?? "";
430
+ const matchedLine = matchedLines[i] ?? "";
431
+
432
+ const oldTrailing = oldLine.length - oldLine.trimEnd().length;
433
+ const matchedTrailing = matchedLine.length - matchedLine.trimEnd().length;
434
+
435
+ if (matchedTrailing > oldTrailing) {
436
+ const extraStart = matchedLine.trimEnd().length + oldTrailing;
437
+ resultLines.push(newLine + matchedLine.slice(extraStart));
438
+ } else {
439
+ resultLines.push(newLine);
440
+ }
441
+ }
442
+
443
+ return before + resultLines.join("\n") + after;
444
+ }
445
+
446
+ function applyEdits(
447
+ content: string,
448
+ edits: EditReplacement[],
449
+ filePath: string,
450
+ ): { newContent: string; blocksChanged: number } {
451
+ const normalizedEdits = edits.map((e) => ({
452
+ oldText: normalizeToLF(e.f),
453
+ newText: normalizeToLF(e.r),
454
+ }));
455
+
456
+ // Validate non-empty
457
+ for (let i = 0; i < normalizedEdits.length; i++) {
458
+ if (normalizedEdits[i].oldText.length === 0) {
459
+ throw new Error(`edits[${i}].f (oldText) must not be empty in ${filePath}.`);
460
+ }
461
+ }
462
+
463
+ const baseContent = content;
464
+
465
+ // Match all edits
466
+ interface MatchResult {
467
+ editIndex: number;
468
+ matchIndex: number;
469
+ matchLength: number;
470
+ newText: string;
471
+ oldText: string;
472
+ isExact: boolean;
473
+ }
474
+
475
+ const matchedEdits: MatchResult[] = [];
476
+ for (let i = 0; i < normalizedEdits.length; i++) {
477
+ const edit = normalizedEdits[i];
478
+ const matchResult = fuzzyFindText(baseContent, edit.oldText);
479
+
480
+ if (!matchResult.found) {
481
+ throw new Error(
482
+ edits.length === 1
483
+ ? `Could not find the exact text in ${filePath}. The old text must match exactly including all whitespace and newlines.`
484
+ : `Could not find edits[${i}] in ${filePath}. The f (oldText) must match exactly including all whitespace and newlines.`,
485
+ );
486
+ }
487
+
488
+ const occurrences = matchResult.isExact
489
+ ? countExactOccurrences(baseContent, edit.oldText)
490
+ : countOccurrences(baseContent, edit.oldText);
491
+ if (occurrences > 1) {
492
+ throw new Error(
493
+ edits.length === 1
494
+ ? `Found ${occurrences} occurrences of the text in ${filePath}. The text must be unique. Please provide more context to make it unique.`
495
+ : `Found ${occurrences} occurrences of edits[${i}] in ${filePath}. Each f (oldText) must be unique. Please provide more context to make it unique.`,
496
+ );
497
+ }
498
+
499
+ matchedEdits.push({
500
+ editIndex: i,
501
+ matchIndex: matchResult.index,
502
+ matchLength: matchResult.matchLength,
503
+ newText: edit.newText,
504
+ oldText: edit.oldText,
505
+ isExact: matchResult.isExact,
506
+ });
507
+ }
508
+
509
+ // Sort by position (ascending)
510
+ matchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);
511
+
512
+ // Check for overlaps
513
+ for (let i = 1; i < matchedEdits.length; i++) {
514
+ const previous = matchedEdits[i - 1];
515
+ const current = matchedEdits[i];
516
+ if (previous.matchIndex + previous.matchLength > current.matchIndex) {
517
+ throw new Error(
518
+ `edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${filePath}. Merge them into one edit or target disjoint regions.`,
519
+ );
520
+ }
521
+ }
522
+
523
+ // Apply edits in reverse order to preserve offsets
524
+ let newContent = baseContent;
525
+ for (let i = matchedEdits.length - 1; i >= 0; i--) {
526
+ const edit = matchedEdits[i];
527
+ if (edit.isExact) {
528
+ newContent =
529
+ newContent.substring(0, edit.matchIndex) +
530
+ edit.newText +
531
+ newContent.substring(edit.matchIndex + edit.matchLength);
532
+ } else {
533
+ newContent = applyFuzzyEdit(
534
+ newContent,
535
+ edit.matchIndex,
536
+ edit.matchLength,
537
+ edit.oldText,
538
+ edit.newText,
539
+ );
540
+ }
541
+ }
542
+
543
+ if (baseContent === newContent) {
544
+ throw new Error(
545
+ edits.length === 1
546
+ ? `No changes made to ${filePath}. The replacement produced identical content.`
547
+ : `No changes made to ${filePath}. The replacements produced identical content.`,
548
+ );
549
+ }
550
+
551
+ return {
552
+ newContent,
553
+ blocksChanged: matchedEdits.length,
554
+ };
555
+ }
556
+
557
+ // ---------------------------------------------------------------------------
558
+ // Path validation
559
+ // ---------------------------------------------------------------------------
560
+
561
+ function expandTilde(inputPath: string): string {
562
+ if (inputPath === "~") return os.homedir();
563
+ if (inputPath.startsWith("~/")) return path.join(os.homedir(), inputPath.slice(2));
564
+ return inputPath;
565
+ }
566
+
567
+ export function isWithinDirectory(child: string, parent: string): boolean {
568
+ if (process.platform === "win32") {
569
+ const childLower = child.toLowerCase();
570
+ const parentLower = parent.toLowerCase();
571
+ if (childLower === parentLower) return true;
572
+ const sep = path.win32.sep;
573
+ const prefix = parentLower.endsWith(sep) ? parentLower : parentLower + sep;
574
+ return childLower.startsWith(prefix);
575
+ }
576
+ if (child === parent) return true;
577
+ if (parent === "/") return child.startsWith("/");
578
+ return child.startsWith(parent + path.sep);
579
+ }
580
+
581
+ async function validatePath(inputPath: string, cwd: string): Promise<string> {
582
+ const expandedPath = expandTilde(inputPath);
583
+ return path.resolve(cwd, expandedPath);
584
+ }
585
+
586
+ // ---------------------------------------------------------------------------
587
+ // prepareArguments shim
588
+ // ---------------------------------------------------------------------------
589
+
590
+ /**
591
+ * Normalize a single operation object from any legacy format to the new
592
+ * single-letter canonical form: { o, p, c, e, s, l }.
593
+ */
594
+ function normalizeOp(raw: Record<string, unknown>): Record<string, unknown> {
595
+ const op: Record<string, unknown> = {};
596
+
597
+ // Map operation type
598
+ op.o = raw.o ?? raw.op ?? (raw.c != null || raw.content != null ? "write" : (raw.e != null || raw.edits != null ? "edit" : "read"));
599
+
600
+ // Map path
601
+ op.p = raw.p ?? raw.path;
602
+
603
+ // Map content
604
+ if (raw.c !== undefined) op.c = raw.c;
605
+ else if (raw.content !== undefined) op.c = raw.content;
606
+
607
+ // Map edits
608
+ let editsRaw = raw.e ?? raw.edits;
609
+ if (typeof editsRaw === "string") {
610
+ try { editsRaw = JSON.parse(editsRaw); } catch { /* ignore */ }
611
+ }
612
+ if (Array.isArray(editsRaw)) {
613
+ op.e = editsRaw.map((e: unknown) => {
614
+ if (!e || typeof e !== "object") return e;
615
+ const edit = e as Record<string, unknown>;
616
+ return { f: edit.f ?? edit.oldText, r: edit.r ?? edit.newText };
617
+ });
618
+ }
619
+
620
+ // Map offset / limit
621
+ if (raw.s !== undefined) op.s = raw.s;
622
+ else if (raw.offset !== undefined) op.s = raw.offset;
623
+ if (raw.l !== undefined) op.l = raw.l;
624
+ else if (raw.limit !== undefined) op.l = raw.limit;
625
+
626
+ return op;
627
+ }
628
+
629
+ /**
630
+ * Normalize input arguments to the canonical { o: [...] } shape.
631
+ * Handles legacy formats, bare arrays, and single-operation shorthands.
632
+ * Always returns { o: FileOpInput[] } to match WeavePatchParams schema.
633
+ */
634
+ function prepareArguments(input: unknown): { o: unknown[] } | unknown {
635
+ if (!input || typeof input !== "object") return { o: [] };
636
+
637
+ const args = input as Record<string, unknown>;
638
+
639
+ // Handle legacy top-level format: { path, oldText, newText }
640
+ if (
641
+ typeof args.oldText === "string" &&
642
+ typeof args.newText === "string" &&
643
+ typeof args.path === "string"
644
+ ) {
645
+ return {
646
+ o: [
647
+ normalizeOp({
648
+ o: "edit",
649
+ p: args.path,
650
+ e: [{ oldText: args.oldText, newText: args.newText }],
651
+ }),
652
+ ],
653
+ };
654
+ }
655
+
656
+ // Extract ops array — canonical { o: [...] }, legacy { op: [...] }, legacy { operations: [...] }, or bare array
657
+ let opsArray: unknown[];
658
+ if (Array.isArray(args.o)) {
659
+ opsArray = args.o;
660
+ } else if (Array.isArray(args.op)) {
661
+ opsArray = args.op;
662
+ } else if (Array.isArray(args.operations)) {
663
+ opsArray = args.operations;
664
+ } else if (Array.isArray(args)) {
665
+ opsArray = args;
666
+ } else if (typeof args.p === "string" || typeof args.path === "string") {
667
+ // Single-operation shorthand: { p: "...", o: "read" }
668
+ opsArray = [args];
669
+ } else {
670
+ return { o: [] };
671
+ }
672
+
673
+ // Normalize each operation to single-letter form
674
+ return {
675
+ o: opsArray.map((op: unknown) => {
676
+ if (!op || typeof op !== "object") return op;
677
+ return normalizeOp(op as Record<string, unknown>);
678
+ }),
679
+ };
680
+ }
681
+
682
+ // ---------------------------------------------------------------------------
683
+ // Main execute function
684
+ // ---------------------------------------------------------------------------
685
+
686
+ async function executeOperations(
687
+ operations: FileOpInput[],
688
+ cwd: string,
689
+ signal?: AbortSignal,
690
+ options: ExecuteOptions = {},
691
+ ): Promise<{ summary: string; contentText: string; results: OpResult[] }> {
692
+ const results: OpResult[] = [];
693
+ let failed = false;
694
+
695
+ const counts = { read: 0, write: 0, edit: 0, delete: 0, error: 0, skipped: 0 };
696
+ const errors: { path: string; op: string; message: string; hint?: string }[] = [];
697
+ const truncatedFiles: { path: string; shown: number; total: number; nextOffset?: number }[] = [];
698
+ const includeLimitWarnings = options.includeLimitWarnings ?? true;
699
+
700
+ for (const op of operations) {
701
+ if (signal?.aborted) {
702
+ results.push({ op: op.o, path: op.p, status: "skipped", error: "Operation aborted." });
703
+ counts.skipped++;
704
+ continue;
705
+ }
706
+
707
+ if (failed) {
708
+ results.push({ op: op.o, path: op.p, status: "skipped" });
709
+ counts.skipped++;
710
+ continue;
711
+ }
712
+
713
+ try {
714
+ const resolvedPath = await validatePath(op.p, cwd);
715
+
716
+ switch (op.o) {
717
+ case "read": {
718
+ // Access check before reading
719
+ try {
720
+ await fs.access(resolvedPath);
721
+ } catch {
722
+ throw new Error(`File not found: ${op.p}`);
723
+ }
724
+ try {
725
+ await fs.access(resolvedPath, fs.constants.R_OK);
726
+ } catch {
727
+ throw new Error(`File not readable: ${op.p}`);
728
+ }
729
+
730
+ const rawContent = await fs.readFile(resolvedPath, "utf-8");
731
+ const { text } = stripBom(rawContent);
732
+ const allLines = text.split("\n");
733
+ const totalFileLines = allLines.length;
734
+
735
+ const { content: readContent, truncated, nextOffset, linesRead } =
736
+ readWithOffsetLimit(text, op.s, op.l, op.p, options.readOptions);
737
+
738
+ if (truncated || (includeLimitWarnings && op.l !== undefined && (op.s ?? 1) - 1 + op.l < totalFileLines)) {
739
+ const shownLines = truncated ? linesRead : op.l!;
740
+ truncatedFiles.push({
741
+ path: op.p,
742
+ shown: shownLines,
743
+ total: totalFileLines,
744
+ nextOffset,
745
+ });
746
+ }
747
+
748
+ results.push({
749
+ op: "read",
750
+ path: op.p,
751
+ status: "ok",
752
+ content: readContent,
753
+ totalLines: totalFileLines,
754
+ truncated: truncated || undefined,
755
+ nextOffset,
756
+ });
757
+ counts.read++;
758
+ break;
759
+ }
760
+
761
+ case "write": {
762
+ if (!op.c && op.c !== "") {
763
+ throw new Error("c (content) is required for write operations.");
764
+ }
765
+ await fs.mkdir(path.dirname(resolvedPath), { recursive: true });
766
+ await fs.writeFile(resolvedPath, op.c!, "utf-8");
767
+ results.push({
768
+ op: "write",
769
+ path: op.p,
770
+ status: "ok",
771
+ bytes: Buffer.byteLength(op.c!, "utf-8"),
772
+ });
773
+ counts.write++;
774
+ break;
775
+ }
776
+
777
+ case "edit": {
778
+ if (!op.e || op.e.length === 0) {
779
+ throw new Error("e (edits) array is required for edit operations.");
780
+ }
781
+
782
+ const rawContent = await fs.readFile(resolvedPath, "utf-8");
783
+ const { bom, text: contentWithoutBom } = stripBom(rawContent);
784
+ const originalEnding = detectLineEnding(contentWithoutBom);
785
+ const normalizedContent = normalizeToLF(contentWithoutBom);
786
+
787
+ const { newContent, blocksChanged } = applyEdits(
788
+ normalizedContent,
789
+ op.e,
790
+ op.p,
791
+ );
792
+
793
+ const finalContent = bom + restoreLineEndings(newContent, originalEnding);
794
+ await fs.writeFile(resolvedPath, finalContent, "utf-8");
795
+
796
+ results.push({
797
+ op: "edit",
798
+ path: op.p,
799
+ status: "ok",
800
+ blocksChanged,
801
+ });
802
+ counts.edit++;
803
+ break;
804
+ }
805
+
806
+ case "delete": {
807
+ let stat;
808
+ try {
809
+ stat = await fs.lstat(resolvedPath);
810
+ } catch (err: any) {
811
+ if (err.code === "ENOENT") {
812
+ throw new Error(`File not found: ${op.p}`);
813
+ }
814
+ throw err;
815
+ }
816
+ if (stat.isDirectory()) {
817
+ throw new Error(`Cannot delete directory: ${op.p}. Use a recursive removal tool or delete files individually.`);
818
+ }
819
+ await fs.unlink(resolvedPath);
820
+ results.push({ op: "delete", path: op.p, status: "ok" });
821
+ counts.delete++;
822
+ break;
823
+ }
824
+
825
+ default:
826
+ throw new Error(`Unknown operation type: ${op.o}`);
827
+ }
828
+ } catch (err) {
829
+ failed = true;
830
+ counts.error++;
831
+ const message = err instanceof Error ? err.message : String(err);
832
+
833
+ // Enrich file-not-found errors with fuzzy filename suggestions
834
+ let hint = getErrorHint(message);
835
+ if (
836
+ message.includes("File not found") ||
837
+ message.includes("file not found") ||
838
+ message.includes("ENOENT") ||
839
+ message.includes("no such file")
840
+ ) {
841
+ const suggestions = await suggestSimilarFiles(op.p, cwd);
842
+ if (suggestions.length > 0) {
843
+ hint += ` Did you mean: ${suggestions.join(", ")}?`;
844
+ }
845
+ }
846
+
847
+ errors.push({ path: op.p, op: op.o, message, hint });
848
+ results.push({
849
+ op: op.o,
850
+ path: op.p,
851
+ status: "error",
852
+ error: message,
853
+ hint,
854
+ });
855
+ }
856
+
857
+ }
858
+ // Build the enhanced summary and content text
859
+ const summary = buildSummary(counts, errors, truncatedFiles);
860
+ const contentText = buildContentText(summary, results);
861
+
862
+ return { summary, contentText, results };
863
+ }
864
+
865
+ function buildSummary(
866
+ counts: { read: number; write: number; edit: number; delete: number; error: number; skipped: number },
867
+ errors: { path: string; op: string; message: string; hint?: string }[],
868
+ truncatedFiles: { path: string; shown: number; total: number; nextOffset?: number }[],
869
+ ): string {
870
+ const totalSuccess =
871
+ counts.read + counts.write + counts.edit + counts.delete;
872
+ const totalOps = totalSuccess + counts.error + counts.skipped;
873
+
874
+ const parts: string[] = [];
875
+
876
+ // Build the success breakdown
877
+ const successParts: string[] = [];
878
+ if (counts.read > 0)
879
+ successParts.push(
880
+ `${counts.read} read${counts.read > 1 ? "s" : ""}`,
881
+ );
882
+ if (counts.write > 0)
883
+ successParts.push(
884
+ `${counts.write} write${counts.write > 1 ? "s" : ""}`,
885
+ );
886
+ if (counts.edit > 0)
887
+ successParts.push(
888
+ `${counts.edit} edit${counts.edit > 1 ? "s" : ""}`,
889
+ );
890
+ if (counts.delete > 0)
891
+ successParts.push(
892
+ `${counts.delete} delete${counts.delete > 1 ? "s" : ""}`,
893
+ );
894
+
895
+ if (counts.error === 0) {
896
+ // All success
897
+ parts.push(`✓ ${totalOps} operations: ${successParts.join(", ")}`);
898
+ } else {
899
+ // Mixed success/failure
900
+ parts.push(
901
+ `✗ ${counts.error} failed${counts.skipped > 0 ? `, ${counts.skipped} skipped` : ""}`,
902
+ );
903
+ if (totalSuccess > 0) {
904
+ parts.push(` ✓ ${successParts.join(", ")} ok`);
905
+ }
906
+ for (const err of errors) {
907
+ const hint = err.hint ?? "";
908
+ const hintSuffix = hint ? ` — ${hint}` : "";
909
+ parts.push(` ✗ ${err.op} ${err.path}: ${err.message}${hintSuffix}`);
910
+ }
911
+ }
912
+
913
+ // Truncation warnings
914
+ for (const tf of truncatedFiles) {
915
+ if (tf.nextOffset) {
916
+ parts.push(
917
+ ` ⚠ ${tf.path} truncated (${tf.shown}/${tf.total} lines) — use s=${tf.nextOffset}`,
918
+ );
919
+ }
920
+ }
921
+
922
+ return parts.join("\n");
923
+ }
924
+
925
+ function shortenPath(p: string): string {
926
+ const home = os.homedir();
927
+ return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
928
+ }
929
+
930
+ type BatchTheme = {
931
+ fg: (color: string, text: string) => string;
932
+ bold: (s: string) => string;
933
+ bg: (color: string, text: string) => string;
934
+ };
935
+
936
+ function extractBatchOps(args: Record<string, unknown>): Array<{ o: string; p: string; e?: unknown[] }> {
937
+ let rawOps: unknown[];
938
+ if (Array.isArray(args.o)) rawOps = args.o;
939
+ else if (Array.isArray(args.op)) rawOps = args.op;
940
+ else if (Array.isArray(args.operations)) rawOps = args.operations;
941
+ else if (Array.isArray(args)) rawOps = args;
942
+ else rawOps = [];
943
+
944
+ return rawOps
945
+ .filter((op): op is Record<string, unknown> => !!op && typeof op === "object")
946
+ .map((op) => {
947
+ const opName = String(op.o ?? op.op ?? "?");
948
+ const opPath = String(op.p ?? op.path ?? "?");
949
+ const edits = Array.isArray(op.e) ? op.e : Array.isArray(op.edits) ? op.edits : undefined;
950
+ return { o: opName, p: opPath, e: edits };
951
+ });
952
+ }
953
+
954
+ function formatBatchCall(args: Record<string, unknown>): string {
955
+ const ops = extractBatchOps(args);
956
+ if (ops.length === 0) return "batch (empty)";
957
+
958
+ const parts: string[] = [];
959
+ for (const op of ops) {
960
+ const shortPath = shortenPath(op.p);
961
+ if (op.o === "edit" && op.e && op.e.length > 1) {
962
+ parts.push(`edit ${shortPath} (${op.e.length} blocks)`);
963
+ } else {
964
+ parts.push(`${op.o} ${shortPath}`);
965
+ }
966
+ }
967
+
968
+ if (parts.length <= 3) {
969
+ return parts.join(", ");
970
+ }
971
+ return `${parts.slice(0, 2).join(", ")} +${parts.length - 2} more`;
972
+ }
973
+
974
+ function renderBatchCall(args: Record<string, unknown>, theme: BatchTheme): Text {
975
+ const summary = formatBatchCall(args);
976
+ return new Text(theme.fg("muted", "batch ") + theme.fg("accent", summary), 0, 0);
977
+ }
978
+
979
+ function renderBatchResult(
980
+ result: { content?: Array<{ type: string; text?: string }> },
981
+ expanded: boolean,
982
+ _theme: BatchTheme,
983
+ _args?: Record<string, unknown>,
984
+ ): Text | TruncatedText {
985
+ const fullText = result.content?.find((c) => c.type === "text")?.text ?? "";
986
+ if (!expanded) {
987
+ const summary = fullText.split("\n")[0] ?? "";
988
+ return new TruncatedText(summary, 0, 0);
989
+ }
990
+ return new Text(fullText, 0, 0);
991
+ }
992
+
993
+ function buildContentText(summary: string, results: OpResult[]): string {
994
+ const sections: string[] = [summary];
995
+
996
+ for (const r of results) {
997
+ if (r.op === "read" && r.status === "ok" && r.content) {
998
+ const lineInfo = r.totalLines !== undefined ? ` (${r.totalLines} lines)` : "";
999
+ sections.push(`\n--- ${r.path}${lineInfo} ---\n${r.content}`);
1000
+ } else if (r.op === "edit" && r.status === "ok") {
1001
+ const blockInfo = r.blocksChanged !== undefined ? `${r.blocksChanged} block${r.blocksChanged > 1 ? "s" : ""}` : "";
1002
+ sections.push(`\n--- edit: ${r.path} (${blockInfo}) ---`);
1003
+ } else if (r.op === "write" && r.status === "ok") {
1004
+ sections.push(`\n--- write: ${r.path} (${r.bytes ?? 0} bytes) ---`);
1005
+ } else if (r.op === "delete" && r.status === "ok") {
1006
+ sections.push(`\n--- delete: ${r.path} ---`);
1007
+ } else if (r.status === "error") {
1008
+ sections.push(`\n--- ${r.op}: ${r.path} ---\nError: ${r.error}`);
1009
+ }
1010
+ }
1011
+
1012
+ return sections.join("");
1013
+ }
1014
+
1015
+ // ---------------------------------------------------------------------------
1016
+ // Tool definition factory
1017
+ // ---------------------------------------------------------------------------
1018
+
1019
+ export const BatchReadParams = Type.Object({
1020
+ o: Type.Array(
1021
+ Type.Object({
1022
+ o: Type.Literal("read"),
1023
+ p: Type.String({ description: "Path to the file (relative or absolute)" }),
1024
+ s: Type.Optional(
1025
+ Type.Number({
1026
+ minimum: 1,
1027
+ description:
1028
+ "1-indexed line number to start reading from (offset). Used with o: 'read'.",
1029
+ }),
1030
+ ),
1031
+ l: Type.Optional(
1032
+ Type.Number({
1033
+ minimum: 1,
1034
+ description:
1035
+ "Maximum number of lines to read (limit). Used with o: 'read'.",
1036
+ }),
1037
+ ),
1038
+ }),
1039
+ {
1040
+ description:
1041
+ "Ordered list of read operations. Executed sequentially. On failure, remaining operations are skipped.",
1042
+ },
1043
+ ),
1044
+ });
1045
+
1046
+ function prepareBatchReadArguments(input: unknown): { o: FileOpInput[] } | unknown {
1047
+ const prepared = prepareArguments(input);
1048
+ const ops = Array.isArray(prepared) ? prepared : (prepared as { o: unknown[] }).o;
1049
+ if (!Array.isArray(ops)) return { o: [] };
1050
+
1051
+ for (const op of ops) {
1052
+ if (!op || typeof op !== "object") continue;
1053
+ const obj = op as Record<string, unknown>;
1054
+ const opType = String(obj.o ?? obj.op ?? "").toLowerCase();
1055
+ if (opType && opType !== "read") {
1056
+ throw new Error(`batch_read only supports read operations. Received: ${opType}`);
1057
+ }
1058
+ }
1059
+ return prepared;
1060
+ }
1061
+
1062
+ function renderBatchReadCall(args: Record<string, unknown>, theme: BatchTheme): Text {
1063
+ const summary = formatBatchCall(args);
1064
+ return new Text(theme.fg("muted", "batch_read ") + theme.fg("accent", summary), 0, 0);
1065
+ }
1066
+
1067
+ export function createBatchReadTool() {
1068
+ return {
1069
+ name: "batch_read",
1070
+ label: "batch_read",
1071
+ description: [
1072
+ "Batch read-only file operations — run multiple read ops in a single call.",
1073
+ "Each operation is independent and executes sequentially in array order; on failure, remaining operations are skipped.",
1074
+ "Reads are not truncated by the batch MAX_LINES or total MAX_BYTES caps; a single line over the byte limit still errors.",
1075
+ "Use `o: \"read\"` with `s` (offset) and `l` (limit) for targeted reading. Prefer this over bash sed/head/tail.",
1076
+ "Best for reading multiple files or sections in one call.",
1077
+ ].join("\n"),
1078
+ promptSnippet: "Batch read-only file operations — run multiple read ops in one call",
1079
+ promptGuidelines: [
1080
+ "Use batch_read to perform multiple file reads in a single call rather than separate tool calls.",
1081
+ "Prefer batch_read when reading 2+ files or multiple sections of the same file.",
1082
+ "batch_read returns the full requested content except when an individual line exceeds the byte limit.",
1083
+ "For single-file reads, the read tool is fine; batch_read shines for multi-file reading.",
1084
+ ],
1085
+ parameters: BatchReadParams,
1086
+ prepareArguments: prepareBatchReadArguments,
1087
+
1088
+ async execute(
1089
+ _toolCallId: string,
1090
+ input: unknown,
1091
+ signal: AbortSignal | undefined,
1092
+ _onUpdate: unknown,
1093
+ ctx: { cwd: string },
1094
+ ) {
1095
+ let prepared: unknown;
1096
+ try {
1097
+ prepared = prepareBatchReadArguments(input);
1098
+ } catch (err) {
1099
+ const message = err instanceof Error ? err.message : String(err);
1100
+ return {
1101
+ content: [{ type: "text", text: `Error: ${message}` }],
1102
+ isError: true,
1103
+ };
1104
+ }
1105
+
1106
+ const ops = Array.isArray(prepared)
1107
+ ? (prepared as FileOpInput[])
1108
+ : (prepared as { o: FileOpInput[] }).o;
1109
+
1110
+ if (!Array.isArray(ops) || ops.length === 0) {
1111
+ return {
1112
+ content: [
1113
+ { type: "text", text: "Error: o array is required and must not be empty." },
1114
+ ],
1115
+ isError: true,
1116
+ };
1117
+ }
1118
+
1119
+ // Defensive validation: reject any non-read operations
1120
+ for (const op of ops) {
1121
+ if (op.o !== "read") {
1122
+ return {
1123
+ content: [
1124
+ {
1125
+ type: "text",
1126
+ text: `Error: batch_read only supports read operations. Received ${op.o} for ${op.p}.`,
1127
+ },
1128
+ ],
1129
+ isError: true,
1130
+ };
1131
+ }
1132
+ }
1133
+
1134
+ if (signal?.aborted) {
1135
+ return {
1136
+ content: [{ type: "text", text: "Operation aborted." }],
1137
+ isError: true,
1138
+ };
1139
+ }
1140
+
1141
+ const { contentText, results } = await executeOperations(ops, ctx.cwd, signal, {
1142
+ readOptions: { truncate: false, toolName: "batch_read" },
1143
+ includeLimitWarnings: false,
1144
+ });
1145
+
1146
+ return {
1147
+ content: [{ type: "text", text: contentText }],
1148
+ details: { results },
1149
+ };
1150
+ },
1151
+
1152
+ renderCall: (args: Record<string, unknown>, theme: BatchTheme) => renderBatchReadCall(args, theme),
1153
+ renderResult: (result: any, { expanded }: { expanded: boolean }, theme: BatchTheme, args?: Record<string, unknown>) =>
1154
+ renderBatchResult(result, expanded, theme, args),
1155
+ };
1156
+ }
1157
+
1158
+ export function createBatchTool() {
1159
+ return {
1160
+ name: "batch",
1161
+ label: "batch",
1162
+ description: [
1163
+ "Batch file operations — run multiple read, write, edit, or delete ops in a single call.",
1164
+ "Each operation is independent: edits are matched against the current on-disk file, not against prior operations in the same call.",
1165
+ "Operations execute sequentially in array order; on failure, remaining operations are skipped.",
1166
+ "Use `o: \"read\"` with `s` (offset) and `l` (limit) for targeted reading. Prefer this over bash sed/head/tail.",
1167
+ "Best for cross-cutting changes, multi-file refactors, or mixing reads with writes across several files.",
1168
+ ].join("\n"),
1169
+ promptSnippet: "Batch file operations — run multiple read/write/edit/delete ops in one call",
1170
+ promptGuidelines: [
1171
+ "Use batch to perform multiple file operations in a single call rather than separate tool calls.",
1172
+ "Prefer batch when touching 2+ files or mixing creates, edits, reads, and deletes.",
1173
+ "Each operation is independent — edits match the on-disk file, not prior ops in the same call.",
1174
+ "For single-file edits, the edit tool is fine; batch shines for cross-cutting and multi-file work.",
1175
+ ],
1176
+ parameters: WeavePatchParams,
1177
+ prepareArguments: prepareArguments,
1178
+
1179
+ async execute(
1180
+ _toolCallId: string,
1181
+ input: unknown,
1182
+ signal: AbortSignal | undefined,
1183
+ _onUpdate: unknown,
1184
+ ctx: { cwd: string },
1185
+ ) {
1186
+ const prepared = prepareArguments(input);
1187
+ // prepareArguments always returns { o: [...] }, but handle
1188
+ // legacy bare arrays for backward compatibility
1189
+ const ops = Array.isArray(prepared)
1190
+ ? prepared as FileOpInput[]
1191
+ : (prepared as { o: FileOpInput[] }).o;
1192
+
1193
+ if (!Array.isArray(ops) || ops.length === 0) {
1194
+ return {
1195
+ content: [
1196
+ { type: "text", text: "Error: o array is required and must not be empty." },
1197
+ ],
1198
+ isError: true,
1199
+ };
1200
+ }
1201
+
1202
+ if (signal?.aborted) {
1203
+ return {
1204
+ content: [{ type: "text", text: "Operation aborted." }],
1205
+ isError: true,
1206
+ };
1207
+ }
1208
+
1209
+ const { contentText, results } = await executeOperations(ops, ctx.cwd, signal);
1210
+
1211
+ return {
1212
+ content: [{ type: "text", text: contentText }],
1213
+ details: { results },
1214
+ };
1215
+ },
1216
+
1217
+ renderCall: (args: Record<string, unknown>, theme: BatchTheme) => renderBatchCall(args, theme),
1218
+ renderResult: (result: any, { expanded }: { expanded: boolean }, theme: BatchTheme, args?: Record<string, unknown>) =>
1219
+ renderBatchResult(result, expanded, theme, args),
1220
+ };
1221
+ }