@leolastforce/chalice-hashline-edit 0.0.0-stage → 4.4.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/LICENSE +21 -0
- package/README.md +153 -2
- package/index.ts +282 -0
- package/package.json +79 -4
- package/prompts/find-guidelines.md +2 -0
- package/prompts/find-snippet.md +1 -0
- package/prompts/find.md +1 -0
- package/prompts/grep-guidelines.md +2 -0
- package/prompts/grep-snippet.md +1 -0
- package/prompts/grep.md +1 -0
- package/prompts/insert-guidelines.md +1 -0
- package/prompts/insert-snippet.md +1 -0
- package/prompts/insert.md +1 -0
- package/prompts/read-guidelines.md +2 -0
- package/prompts/read-snippet.md +1 -0
- package/prompts/read.md +1 -0
- package/prompts/replace-guidelines.md +4 -0
- package/prompts/replace-snippet.md +1 -0
- package/prompts/replace.md +1 -0
- package/prompts/undo-last-change-guidelines.md +1 -0
- package/prompts/undo-last-change-snippet.md +1 -0
- package/prompts/undo-last-change.md +1 -0
- package/src/anchor-registry.ts +977 -0
- package/src/auto-read-all-state.ts +27 -0
- package/src/auto-read-all.ts +477 -0
- package/src/batch.ts +767 -0
- package/src/commit.ts +137 -0
- package/src/config-ui.ts +212 -0
- package/src/config.ts +235 -0
- package/src/constants.ts +26 -0
- package/src/edit-common.ts +206 -0
- package/src/file-kind.ts +191 -0
- package/src/file-reader.ts +135 -0
- package/src/find.ts +244 -0
- package/src/fs-write.ts +231 -0
- package/src/glob.ts +186 -0
- package/src/grep.ts +690 -0
- package/src/hash-store/cache.ts +18 -0
- package/src/hash-store/retry.ts +44 -0
- package/src/hash-store/validation.ts +62 -0
- package/src/hash-store.ts +609 -0
- package/src/hashline/alphabet.ts +21 -0
- package/src/hashline/anchor-table.json +1 -0
- package/src/hashline/apply.ts +297 -0
- package/src/hashline/hash.ts +119 -0
- package/src/hashline/hasher.ts +47 -0
- package/src/hashline/index.ts +50 -0
- package/src/hashline/parse.ts +84 -0
- package/src/hashline/resolve.ts +373 -0
- package/src/insert.ts +258 -0
- package/src/normalize.ts +27 -0
- package/src/paths.ts +56 -0
- package/src/payload-contract.ts +133 -0
- package/src/prompts.ts +13 -0
- package/src/read.ts +286 -0
- package/src/replace-diff.ts +610 -0
- package/src/replace-render.ts +390 -0
- package/src/replace-response.ts +166 -0
- package/src/replace-undo.ts +270 -0
- package/src/replace.ts +318 -0
- package/src/served.ts +36 -0
- package/src/utils.ts +387 -0
- package/src/validation.ts +45 -0
- package/src/write-hook.ts +53 -0
package/src/grep.ts
ADDED
|
@@ -0,0 +1,690 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { formatSize, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type TruncationResult } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import { stat } from "node:fs/promises";
|
|
5
|
+
import { dirname, isAbsolute, join, win32 } from "node:path";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
8
|
+
import { createInterface } from "node:readline";
|
|
9
|
+
import { tryReadNormFile } from "./file-reader";
|
|
10
|
+
import { globToRegex } from "./glob";
|
|
11
|
+
import { MAX_HASH_LINES, fmtRow, HASH_LEN, HASH_SEP, HASH_CLASS } from "./hashline";
|
|
12
|
+
import { ANCHOR_POOL_EXHAUSTED_PREFIX, MAX_GREP_LINE_BYTES } from "./constants";
|
|
13
|
+
import { toCwd, toDisplayPath } from "./paths";
|
|
14
|
+
import { loadP, loadGuide } from "./prompts";
|
|
15
|
+
import { normReq } from "./payload-contract";
|
|
16
|
+
import { abortIf, errCode, gutterWidth, isRec, makePrepareArguments, rejectUnknownFields, truncateToBytes, visLines } from "./utils";
|
|
17
|
+
import { withAnchorSession } from "./anchor-registry";
|
|
18
|
+
import { serveRows } from "./served";
|
|
19
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
20
|
+
import { expandHint, getResultText, reuseText, type CallT, type FgT } from "./replace-render";
|
|
21
|
+
const GREP_KS = new Set(["pattern", "path", "glob", "context", "ignoreCase", "literal", "limit"]);
|
|
22
|
+
|
|
23
|
+
function cmp(a: string, b: string): number {
|
|
24
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function isPoolExhaustedError(error: unknown): boolean {
|
|
28
|
+
return error instanceof Error && error.message.startsWith(ANCHOR_POOL_EXHAUSTED_PREFIX);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface GrepReq {
|
|
32
|
+
pattern: string;
|
|
33
|
+
path?: string;
|
|
34
|
+
glob?: string;
|
|
35
|
+
context?: number;
|
|
36
|
+
ignoreCase?: boolean;
|
|
37
|
+
literal?: boolean;
|
|
38
|
+
limit?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function assertGrepReq(request: unknown): asserts request is GrepReq {
|
|
42
|
+
if (!isRec(request)) {
|
|
43
|
+
throw new Error("[E_BAD_SHAPE] Grep request must be an object.");
|
|
44
|
+
}
|
|
45
|
+
rejectUnknownFields(request, GREP_KS, "Grep request");
|
|
46
|
+
if (typeof request.pattern !== "string" || request.pattern.length === 0) {
|
|
47
|
+
throw new Error('[E_BAD_SHAPE] Grep request requires a non-empty "pattern" string.');
|
|
48
|
+
}
|
|
49
|
+
if (request.context !== undefined && (typeof request.context !== "number" || !Number.isInteger(request.context) || request.context < 0)) {
|
|
50
|
+
throw new Error('[E_BAD_SHAPE] Grep request field "context" must be a non-negative integer.');
|
|
51
|
+
}
|
|
52
|
+
if (request.limit !== undefined && (typeof request.limit !== "number" || !Number.isInteger(request.limit) || request.limit < 1)) {
|
|
53
|
+
throw new Error('[E_BAD_SHAPE] Grep request field "limit" must be a positive integer.');
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function buildRegex(pattern: string, literal: boolean, ignoreCase: boolean): RegExp {
|
|
58
|
+
if (!literal) assertSafeRegex(pattern);
|
|
59
|
+
const source = literal ? pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : pattern;
|
|
60
|
+
try {
|
|
61
|
+
return new RegExp(source, ignoreCase ? "ui" : "u");
|
|
62
|
+
} catch {
|
|
63
|
+
throw new Error(`[E_BAD_SHAPE] Invalid pattern: ${pattern}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface RegexGroupRisk {
|
|
68
|
+
hasQuantifier: boolean;
|
|
69
|
+
hasAlternation: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function unsafeRegex(pattern: string): never {
|
|
73
|
+
throw new Error(
|
|
74
|
+
`[E_UNSAFE_REGEX] Refusing potentially exponential regex: ${pattern}. Use literal: true or simplify the expression.`,
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function assertSafeRegex(pattern: string): void {
|
|
79
|
+
if (pattern.length > 4096) unsafeRegex(pattern);
|
|
80
|
+
const groups: RegexGroupRisk[] = [];
|
|
81
|
+
let inClass = false;
|
|
82
|
+
let escaped = false;
|
|
83
|
+
let variableQuantifiers = 0;
|
|
84
|
+
let lastAtom: { groupRisky: boolean; quantified: boolean } | undefined;
|
|
85
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
86
|
+
const ch = pattern[i]!;
|
|
87
|
+
if (escaped) {
|
|
88
|
+
if (!inClass && (/[1-9]/.test(ch) || (ch === "k" && pattern[i + 1] === "<"))) {
|
|
89
|
+
unsafeRegex(pattern);
|
|
90
|
+
}
|
|
91
|
+
escaped = false;
|
|
92
|
+
lastAtom = { groupRisky: false, quantified: false };
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (ch === "\\") {
|
|
96
|
+
escaped = true;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (inClass) {
|
|
100
|
+
if (ch === "]") {
|
|
101
|
+
inClass = false;
|
|
102
|
+
lastAtom = { groupRisky: false, quantified: false };
|
|
103
|
+
}
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (ch === "[") {
|
|
107
|
+
inClass = true;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (ch === "(") {
|
|
111
|
+
groups.push({ hasQuantifier: false, hasAlternation: false });
|
|
112
|
+
lastAtom = undefined;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (ch === ")") {
|
|
116
|
+
const group = groups.pop();
|
|
117
|
+
if (group) {
|
|
118
|
+
lastAtom = {
|
|
119
|
+
groupRisky: group.hasQuantifier || group.hasAlternation,
|
|
120
|
+
quantified: false,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (ch === "|") {
|
|
126
|
+
const group = groups.at(-1);
|
|
127
|
+
if (group) group.hasAlternation = true;
|
|
128
|
+
lastAtom = undefined;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
let quantifierLength = 0;
|
|
132
|
+
if (ch === "*" || ch === "+" || ch === "?") {
|
|
133
|
+
quantifierLength = 1;
|
|
134
|
+
} else if (ch === "{") {
|
|
135
|
+
quantifierLength = /^\{\d+(?:,\d*)?\}/.exec(pattern.slice(i))?.[0].length ?? 0;
|
|
136
|
+
}
|
|
137
|
+
if (ch === "{" && quantifierLength > 0) {
|
|
138
|
+
const quant = pattern.slice(i, i + quantifierLength);
|
|
139
|
+
const m = /^\{(\d+)/.exec(quant);
|
|
140
|
+
if (m && Number(m[1]) > 1000) unsafeRegex(pattern);
|
|
141
|
+
}
|
|
142
|
+
if (quantifierLength > 0 && lastAtom) {
|
|
143
|
+
if (ch === "?" && lastAtom.quantified) continue;
|
|
144
|
+
const variable = ch !== "{" || pattern.slice(i, i + quantifierLength).includes(",");
|
|
145
|
+
if (variable && ++variableQuantifiers > 1) unsafeRegex(pattern);
|
|
146
|
+
if (lastAtom.groupRisky) unsafeRegex(pattern);
|
|
147
|
+
const group = groups.at(-1);
|
|
148
|
+
if (group) group.hasQuantifier = true;
|
|
149
|
+
lastAtom.quantified = true;
|
|
150
|
+
i += quantifierLength - 1;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
lastAtom = { groupRisky: false, quantified: false };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
interface FileHit {
|
|
158
|
+
path: string;
|
|
159
|
+
displayPath: string;
|
|
160
|
+
fileHashes: string[];
|
|
161
|
+
fileLines: string[];
|
|
162
|
+
rows: string[];
|
|
163
|
+
hashes: string[];
|
|
164
|
+
lineNumbers: number[];
|
|
165
|
+
matchCount: number;
|
|
166
|
+
totalMatchCount: number;
|
|
167
|
+
fragmented: boolean[];
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const GREP_ROW_OVERHEAD_BYTES = HASH_LEN + Buffer.byteLength(HASH_SEP, "utf-8");
|
|
171
|
+
const GREP_ROW_CONTENT_BYTES = MAX_GREP_LINE_BYTES - GREP_ROW_OVERHEAD_BYTES;
|
|
172
|
+
|
|
173
|
+
function snapCharBoundaries(line: string, start: number, end: number): [number, number] {
|
|
174
|
+
let s = start;
|
|
175
|
+
let e = end;
|
|
176
|
+
if (s > 0 && s < line.length) {
|
|
177
|
+
const c = line.charCodeAt(s);
|
|
178
|
+
if (c >= 0xdc00 && c <= 0xdfff && line.charCodeAt(s - 1) >= 0xd800 && line.charCodeAt(s - 1) <= 0xdbff) s -= 1;
|
|
179
|
+
}
|
|
180
|
+
if (e > 0 && e < line.length) {
|
|
181
|
+
const c = line.charCodeAt(e - 1);
|
|
182
|
+
if (c >= 0xd800 && c <= 0xdbff && line.charCodeAt(e) >= 0xdc00 && line.charCodeAt(e) <= 0xdfff) e += 1;
|
|
183
|
+
}
|
|
184
|
+
return [s, e];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function grepMatchFragment(line: string, regex: RegExp): string {
|
|
188
|
+
const m = regex.exec(line);
|
|
189
|
+
const matchStart = m?.index ?? 0;
|
|
190
|
+
const matchLen = m?.[0].length ?? 0;
|
|
191
|
+
const budget = GREP_ROW_CONTENT_BYTES - 6;
|
|
192
|
+
const half = Math.floor((budget - Math.min(matchLen, budget)) / 2);
|
|
193
|
+
const [start, end] = snapCharBoundaries(line, Math.max(0, matchStart - half), Math.min(line.length, matchStart + matchLen + half));
|
|
194
|
+
const content = truncateToBytes(line.slice(start, end), budget);
|
|
195
|
+
const lead = start > 0 ? "..." : "";
|
|
196
|
+
const tail = end < line.length ? "..." : "";
|
|
197
|
+
return truncateToBytes(`${lead}${content}${tail}`, GREP_ROW_CONTENT_BYTES);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function grepHeadFragment(line: string): string {
|
|
201
|
+
const head = truncateToBytes(line, GREP_ROW_CONTENT_BYTES - 3);
|
|
202
|
+
return head.length < line.length ? `${head}...` : head;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function makeHitFromIndices(
|
|
206
|
+
norm: { normalized: string; fileHashes: string[]; absolutePath: string },
|
|
207
|
+
displayPath: string,
|
|
208
|
+
matchIndices: number[],
|
|
209
|
+
context: number,
|
|
210
|
+
regex: RegExp | undefined,
|
|
211
|
+
totalMatchCount: number,
|
|
212
|
+
keptMatchCount: number,
|
|
213
|
+
): FileHit {
|
|
214
|
+
const lines = visLines(norm.normalized);
|
|
215
|
+
const shown = new Set<number>();
|
|
216
|
+
const kept = matchIndices.slice(0, keptMatchCount);
|
|
217
|
+
for (const i of kept) {
|
|
218
|
+
for (let j = Math.max(0, i - context); j <= Math.min(lines.length - 1, i + context); j++) shown.add(j);
|
|
219
|
+
}
|
|
220
|
+
const sorted = [...shown].sort((a, b) => a - b);
|
|
221
|
+
const matchSet = new Set(matchIndices);
|
|
222
|
+
const rows: string[] = [];
|
|
223
|
+
const hashes: string[] = [];
|
|
224
|
+
const lineNumbers: number[] = [];
|
|
225
|
+
const fragmented: boolean[] = [];
|
|
226
|
+
for (const idx of sorted) {
|
|
227
|
+
const hash = norm.fileHashes[idx]!;
|
|
228
|
+
const line = lines[idx]!;
|
|
229
|
+
const row = fmtRow(hash, line);
|
|
230
|
+
if (Buffer.byteLength(row, "utf-8") > MAX_GREP_LINE_BYTES) {
|
|
231
|
+
const content = matchSet.has(idx) && regex ? grepMatchFragment(line, regex) : grepHeadFragment(line);
|
|
232
|
+
rows.push(fmtRow(hash, content));
|
|
233
|
+
hashes.push(hash);
|
|
234
|
+
lineNumbers.push(idx + 1);
|
|
235
|
+
fragmented.push(true);
|
|
236
|
+
} else {
|
|
237
|
+
rows.push(row);
|
|
238
|
+
hashes.push(hash);
|
|
239
|
+
lineNumbers.push(idx + 1);
|
|
240
|
+
fragmented.push(false);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return {
|
|
244
|
+
path: norm.absolutePath,
|
|
245
|
+
displayPath,
|
|
246
|
+
fileHashes: norm.fileHashes,
|
|
247
|
+
fileLines: lines,
|
|
248
|
+
rows,
|
|
249
|
+
hashes,
|
|
250
|
+
lineNumbers,
|
|
251
|
+
matchCount: kept.length,
|
|
252
|
+
totalMatchCount,
|
|
253
|
+
fragmented,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
let cachedRgPath: string | undefined;
|
|
258
|
+
|
|
259
|
+
export async function resolveRgPath(): Promise<string> {
|
|
260
|
+
if (cachedRgPath !== undefined) return cachedRgPath;
|
|
261
|
+
try {
|
|
262
|
+
const r = spawnSync("rg", ["--version"], { stdio: "pipe" });
|
|
263
|
+
if (!r.error && r.status === 0) { cachedRgPath = "rg"; return "rg"; }
|
|
264
|
+
} catch {}
|
|
265
|
+
try {
|
|
266
|
+
const { homedir } = await import("node:os");
|
|
267
|
+
const { existsSync } = await import("node:fs");
|
|
268
|
+
const home = process.env.HOME ?? homedir();
|
|
269
|
+
const base = process.env.PI_CODING_AGENT_DIR ?? join(home, ".pi", "agent");
|
|
270
|
+
const bin = join(base, "bin", process.platform === "win32" ? "rg.exe" : "rg");
|
|
271
|
+
if (existsSync(bin)) {
|
|
272
|
+
const r = spawnSync(bin, ["--version"], { stdio: "pipe" });
|
|
273
|
+
if (!r.error && r.status === 0) { cachedRgPath = bin; return bin; }
|
|
274
|
+
}
|
|
275
|
+
} catch {}
|
|
276
|
+
try {
|
|
277
|
+
const { createRequire } = await import("node:module");
|
|
278
|
+
const require = createRequire(import.meta.url);
|
|
279
|
+
const pkgPath = require.resolve("@earendil-works/pi-coding-agent/package.json");
|
|
280
|
+
const piDir = dirname(pkgPath);
|
|
281
|
+
const toolsManagerPath = join(piDir, "dist/utils/tools-manager.js");
|
|
282
|
+
const mod = await import(pathToFileURL(toolsManagerPath).href);
|
|
283
|
+
if (mod.ensureTool) {
|
|
284
|
+
const p = await mod.ensureTool("rg", true);
|
|
285
|
+
if (p) { cachedRgPath = p; return p; }
|
|
286
|
+
}
|
|
287
|
+
} catch {}
|
|
288
|
+
throw new Error("[E_ACCESS] ripgrep (rg) is required for grep but was not found. Install ripgrep or ensure pi can download it to ~/.pi/agent/bin.");
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function collectRgMatches(
|
|
292
|
+
rgPath: string,
|
|
293
|
+
pattern: string,
|
|
294
|
+
searchPath: string,
|
|
295
|
+
req: GrepReq,
|
|
296
|
+
signal?: AbortSignal,
|
|
297
|
+
): Promise<Map<string, number[]>> {
|
|
298
|
+
const args = ["--json", "--line-number", "--color=never", "--hidden", "--glob", "!.git"];
|
|
299
|
+
const wanted = req.limit ?? 100;
|
|
300
|
+
args.push("--max-count", String(wanted + 1));
|
|
301
|
+
if (typeof req.glob === "string" && req.glob.length > 0) {
|
|
302
|
+
const stripped = req.glob.startsWith("/") ? req.glob.slice(1) : req.glob;
|
|
303
|
+
if (!stripped.includes("/")) args.push("--glob", stripped);
|
|
304
|
+
}
|
|
305
|
+
if (req.ignoreCase) args.push("--ignore-case");
|
|
306
|
+
if (req.literal) args.push("--fixed-strings");
|
|
307
|
+
args.push("--", pattern, searchPath);
|
|
308
|
+
const result = new Map<string, number[]>();
|
|
309
|
+
return await new Promise<Map<string, number[]>>((resolve, reject) => {
|
|
310
|
+
const child = spawn(rgPath, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
311
|
+
const rl = createInterface({ input: child.stdout });
|
|
312
|
+
let stderr = "";
|
|
313
|
+
let timedOut = false;
|
|
314
|
+
const rgTimeout = setTimeout(() => {
|
|
315
|
+
timedOut = true;
|
|
316
|
+
if (!child.killed) child.kill("SIGKILL");
|
|
317
|
+
reject(new Error("rg timeout"));
|
|
318
|
+
}, 10000);
|
|
319
|
+
child.stderr?.on("data", (chunk) => {
|
|
320
|
+
stderr += chunk.toString();
|
|
321
|
+
});
|
|
322
|
+
const onAbort = () => {
|
|
323
|
+
if (!child.killed) child.kill("SIGKILL");
|
|
324
|
+
};
|
|
325
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
326
|
+
const cleanup = () => {
|
|
327
|
+
clearTimeout(rgTimeout);
|
|
328
|
+
rl.close();
|
|
329
|
+
signal?.removeEventListener("abort", onAbort);
|
|
330
|
+
};
|
|
331
|
+
rl.on("line", (line) => {
|
|
332
|
+
if (!line.trim()) return;
|
|
333
|
+
let event: { type?: string; data?: { path?: { text?: string }; line_number?: number } };
|
|
334
|
+
try {
|
|
335
|
+
event = JSON.parse(line);
|
|
336
|
+
} catch {
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (event.type === "match") {
|
|
340
|
+
const filePath = event.data?.path?.text;
|
|
341
|
+
const lineNumber = event.data?.line_number;
|
|
342
|
+
if (typeof filePath === "string" && typeof lineNumber === "number") {
|
|
343
|
+
let abs: string;
|
|
344
|
+
try {
|
|
345
|
+
abs = isAbsolute(filePath) || win32.isAbsolute(filePath) ? filePath : join(searchPath, filePath);
|
|
346
|
+
} catch {
|
|
347
|
+
abs = filePath;
|
|
348
|
+
}
|
|
349
|
+
const list = result.get(abs) ?? [];
|
|
350
|
+
list.push(lineNumber);
|
|
351
|
+
result.set(abs, list);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
child.on("error", (error) => {
|
|
356
|
+
cleanup();
|
|
357
|
+
if (rgPath === cachedRgPath) cachedRgPath = undefined;
|
|
358
|
+
reject(error);
|
|
359
|
+
});
|
|
360
|
+
child.on("close", (code) => {
|
|
361
|
+
cleanup();
|
|
362
|
+
if (timedOut) return;
|
|
363
|
+
if (signal?.aborted) {
|
|
364
|
+
reject(new Error("Operation aborted"));
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
if (code !== 0 && code !== 1) {
|
|
368
|
+
const msg = stderr.trim() || `ripgrep exited with code ${code}`;
|
|
369
|
+
reject(new Error(msg));
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
resolve(result);
|
|
373
|
+
});
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
function displayRowsForHit(hit: FileHit): string[] {
|
|
379
|
+
let max = 0;
|
|
380
|
+
for (const n of hit.lineNumbers) if (n > max) max = n;
|
|
381
|
+
const width = gutterWidth(max, 1);
|
|
382
|
+
return hit.rows.map((row, i) => {
|
|
383
|
+
const n = hit.lineNumbers[i]!;
|
|
384
|
+
const padded = String(n).padStart(width, " ");
|
|
385
|
+
return `${padded} │ ${row}`;
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const grepToolSchema = Type.Object(
|
|
390
|
+
{
|
|
391
|
+
pattern: Type.String({
|
|
392
|
+
description: "Search pattern (regex or literal string)",
|
|
393
|
+
}),
|
|
394
|
+
path: Type.Optional(
|
|
395
|
+
Type.String({
|
|
396
|
+
description: "Directory or file to search (default: current directory)",
|
|
397
|
+
}),
|
|
398
|
+
),
|
|
399
|
+
glob: Type.Optional(
|
|
400
|
+
Type.String({
|
|
401
|
+
description: "Filter files by glob; `*` crosses directories, e.g. `*.ts`. A leading `/` is ignored; relative to the search root or cwd.",
|
|
402
|
+
}),
|
|
403
|
+
),
|
|
404
|
+
ignoreCase: Type.Optional(
|
|
405
|
+
Type.Boolean({
|
|
406
|
+
description: "Case-insensitive search",
|
|
407
|
+
}),
|
|
408
|
+
),
|
|
409
|
+
literal: Type.Optional(
|
|
410
|
+
Type.Boolean({
|
|
411
|
+
description: "Treat pattern as literal text instead of regex",
|
|
412
|
+
}),
|
|
413
|
+
),
|
|
414
|
+
context: Type.Optional(
|
|
415
|
+
Type.Integer({
|
|
416
|
+
minimum: 0,
|
|
417
|
+
description: "Lines of context before and after each match",
|
|
418
|
+
}),
|
|
419
|
+
),
|
|
420
|
+
limit: Type.Optional(
|
|
421
|
+
Type.Integer({
|
|
422
|
+
minimum: 1,
|
|
423
|
+
description: "Maximum number of matched lines to return",
|
|
424
|
+
}),
|
|
425
|
+
),
|
|
426
|
+
},
|
|
427
|
+
{ additionalProperties: true },
|
|
428
|
+
);
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
const GREP_PREVIEW_LINES = 16;
|
|
432
|
+
const GREP_PREVIEW_LINES_EXPANDED = 40;
|
|
433
|
+
|
|
434
|
+
export function fmtGrepCall(args: { pattern?: unknown; path?: unknown; glob?: unknown; literal?: unknown; ignoreCase?: unknown; context?: unknown; limit?: unknown } | undefined, theme: CallT): string {
|
|
435
|
+
const pattern = typeof args?.pattern === "string" && args.pattern.length > 0 ? theme.fg("accent", args.pattern) : theme.fg("toolOutput", "...");
|
|
436
|
+
const qualifiers: string[] = [];
|
|
437
|
+
if (typeof args?.path === "string" && args.path.length > 0) qualifiers.push(args.path);
|
|
438
|
+
if (typeof args?.glob === "string" && args.glob.length > 0) qualifiers.push(args.glob);
|
|
439
|
+
if (args?.literal === true) qualifiers.push("literal");
|
|
440
|
+
if (args?.ignoreCase === true) qualifiers.push("case-insensitive");
|
|
441
|
+
if (typeof args?.context === "number") qualifiers.push(`context ${args.context}`);
|
|
442
|
+
if (typeof args?.limit === "number") qualifiers.push(`limit ${args.limit}`);
|
|
443
|
+
let text = `${theme.fg("toolTitle", theme.bold("anchor_grep"))} ${pattern}`;
|
|
444
|
+
if (qualifiers.length > 0) text += ` ${theme.fg("dim", qualifiers.join(" "))}`;
|
|
445
|
+
return text;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function highlightRegex(args: unknown): RegExp | undefined {
|
|
449
|
+
if (!isRec(args) || typeof args.pattern !== "string" || args.pattern.length === 0) return undefined;
|
|
450
|
+
try {
|
|
451
|
+
const validated = buildRegex(args.pattern, args.literal === true, args.ignoreCase === true);
|
|
452
|
+
return new RegExp(validated.source, validated.flags.includes("i") ? "giu" : "gu");
|
|
453
|
+
} catch {
|
|
454
|
+
return undefined;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function highlightMatches(text: string, regex: RegExp, theme: FgT): string {
|
|
459
|
+
let out = "";
|
|
460
|
+
let last = 0;
|
|
461
|
+
regex.lastIndex = 0;
|
|
462
|
+
for (;;) {
|
|
463
|
+
const match = regex.exec(text);
|
|
464
|
+
if (!match || match[0].length === 0) break;
|
|
465
|
+
out += text.slice(last, match.index) + theme.fg("accent", match[0]);
|
|
466
|
+
last = match.index + match[0].length;
|
|
467
|
+
}
|
|
468
|
+
return out + text.slice(last);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
const ANCHORED_ROW_RE = new RegExp(`^${HASH_CLASS}${HASH_SEP}`);
|
|
472
|
+
|
|
473
|
+
function highlightHitRow(row: string, highlight: RegExp, theme: FgT): string {
|
|
474
|
+
const anchored = row.match(ANCHORED_ROW_RE);
|
|
475
|
+
if (!anchored) return highlightMatches(row, highlight, theme);
|
|
476
|
+
return anchored[0] + highlightMatches(row.slice(anchored[0].length), highlight, theme);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function styleGrepLine(line: string, highlight: RegExp | undefined, theme: FgT): string {
|
|
480
|
+
if (line.startsWith("=== ")) return theme.fg("accent", line);
|
|
481
|
+
if (line.startsWith("[grep:") || line.startsWith("... ")) return theme.fg("dim", line);
|
|
482
|
+
if (!highlight) return line;
|
|
483
|
+
const gutter = line.indexOf(" │ ");
|
|
484
|
+
if (gutter < 0) return highlightHitRow(line, highlight, theme);
|
|
485
|
+
const cut = gutter + " │ ".length;
|
|
486
|
+
return line.slice(0, cut) + highlightHitRow(line.slice(cut), highlight, theme);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
export function renderGrepResult(result: { content?: Array<{ type: string; text?: string }> }, options: { isPartial: boolean; expanded?: boolean } | boolean, theme: FgT, context: any): Text {
|
|
490
|
+
const isPartial = typeof options === "boolean" ? options : options.isPartial;
|
|
491
|
+
const expanded = typeof options === "boolean" ? context.expanded === true : options.expanded === true || context.expanded === true;
|
|
492
|
+
if (isPartial) return reuseText(context, theme.fg("warning", "Searching..."));
|
|
493
|
+
const raw = getResultText(result);
|
|
494
|
+
if (context.isError) return raw ? reuseText(context, `\n${theme.fg("error", raw)}`) : new Text("", 0, 0);
|
|
495
|
+
if (!raw) return new Text("", 0, 0);
|
|
496
|
+
const maxLines = expanded ? GREP_PREVIEW_LINES_EXPANDED : GREP_PREVIEW_LINES;
|
|
497
|
+
const lines = raw.split("\n");
|
|
498
|
+
const highlight = highlightRegex((context as { args?: unknown }).args);
|
|
499
|
+
const shown = lines.slice(0, maxLines).map((line) => styleGrepLine(line, highlight, theme));
|
|
500
|
+
if (lines.length > maxLines) shown.push(theme.fg("muted", `... ${lines.length - maxLines} more grep lines (${expandHint()})`));
|
|
501
|
+
return reuseText(context, shown.join("\n"));
|
|
502
|
+
}
|
|
503
|
+
export function regGrep(pi: ExtensionAPI): void {
|
|
504
|
+
pi.registerTool({
|
|
505
|
+
name: "anchor_grep",
|
|
506
|
+
label: "Anchor Grep",
|
|
507
|
+
description: loadP("../prompts/grep.md"),
|
|
508
|
+
promptSnippet: loadP("../prompts/grep-snippet.md"),
|
|
509
|
+
promptGuidelines: loadGuide("../prompts/grep-guidelines.md"),
|
|
510
|
+
prepareArguments: makePrepareArguments(),
|
|
511
|
+
parameters: grepToolSchema,
|
|
512
|
+
executionMode: "sequential",
|
|
513
|
+
renderCall(args: any, theme: CallT, context: any) {
|
|
514
|
+
const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
|
|
515
|
+
text.setText(fmtGrepCall(args as { pattern?: unknown; path?: unknown } | undefined, theme));
|
|
516
|
+
return text;
|
|
517
|
+
},
|
|
518
|
+
renderResult(result, opts, theme, context) {
|
|
519
|
+
return renderGrepResult(result as never, opts as { isPartial: boolean; expanded?: boolean }, theme as never, context as never);
|
|
520
|
+
},
|
|
521
|
+
|
|
522
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
523
|
+
return withAnchorSession(ctx, async () => {
|
|
524
|
+
const canonical = normReq(params);
|
|
525
|
+
assertGrepReq(canonical);
|
|
526
|
+
const req = canonical;
|
|
527
|
+
const context = req.context ?? 0;
|
|
528
|
+
const limit = req.limit ?? 100;
|
|
529
|
+
const base = req.path ? toCwd(req.path, ctx.cwd) : ctx.cwd;
|
|
530
|
+
abortIf(signal);
|
|
531
|
+
let baseStat;
|
|
532
|
+
try {
|
|
533
|
+
baseStat = await stat(base);
|
|
534
|
+
} catch (error) {
|
|
535
|
+
if (errCode(error) === "ENOENT") {
|
|
536
|
+
throw new Error(`[E_NOT_FOUND] File not found: ${req.path ?? ctx.cwd}`);
|
|
537
|
+
}
|
|
538
|
+
throw new Error(`[E_ACCESS] Cannot access path: ${req.path ?? ctx.cwd}`);
|
|
539
|
+
}
|
|
540
|
+
const globRoot = baseStat.isFile() ? dirname(base) : base;
|
|
541
|
+
const globRegex = req.glob === undefined ? undefined : globToRegex(req.glob);
|
|
542
|
+
const matchesGlob = (absPath: string): boolean => {
|
|
543
|
+
if (globRegex === undefined) return true;
|
|
544
|
+
const displayPath = toDisplayPath(ctx.cwd, absPath);
|
|
545
|
+
const globPath = toDisplayPath(globRoot, absPath);
|
|
546
|
+
return globRegex.test(globPath) || globRegex.test(displayPath);
|
|
547
|
+
};
|
|
548
|
+
const validatedRegex = buildRegex(req.pattern, req.literal === true, req.ignoreCase === true);
|
|
549
|
+
const rgPath = await resolveRgPath();
|
|
550
|
+
const hits: FileHit[] = [];
|
|
551
|
+
let matches = 0;
|
|
552
|
+
let limitTruncated = false;
|
|
553
|
+
let rowTruncated = false;
|
|
554
|
+
let rowCount = 0;
|
|
555
|
+
let byteCount = 0;
|
|
556
|
+
let totalRows = 0;
|
|
557
|
+
let totalBytes = 0;
|
|
558
|
+
let truncatedBy: "lines" | "bytes" | null = null;
|
|
559
|
+
let linesReplaced = 0;
|
|
560
|
+
let countOnly = false;
|
|
561
|
+
let poolSkipped = 0;
|
|
562
|
+
const makeGrepReader = (allocation: "real" | "shadow") => async (absPath: string) => {
|
|
563
|
+
try {
|
|
564
|
+
return await tryReadNormFile(absPath, ctx.cwd, { maxLines: MAX_HASH_LINES, noPersist: true, allocation, signal });
|
|
565
|
+
} catch (error) {
|
|
566
|
+
if (!isPoolExhaustedError(error)) throw error;
|
|
567
|
+
poolSkipped += 1;
|
|
568
|
+
return undefined;
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
const readGrepFile = makeGrepReader("real");
|
|
572
|
+
const readGrepFileShadow = makeGrepReader("shadow");
|
|
573
|
+
const rgMatches = await collectRgMatches(rgPath, req.pattern, base, req, signal);
|
|
574
|
+
const sortedFiles = [...rgMatches.keys()].sort(cmp);
|
|
575
|
+
for (let f = 0; f < sortedFiles.length; f++) {
|
|
576
|
+
abortIf(signal);
|
|
577
|
+
const absPath = sortedFiles[f]!;
|
|
578
|
+
const allNums = rgMatches.get(absPath) ?? [];
|
|
579
|
+
const totalForFile = allNums.length;
|
|
580
|
+
const sortedNums = [...allNums].sort((a, b) => a - b);
|
|
581
|
+
const indices = sortedNums.map((n) => n - 1).filter((n) => n >= 0);
|
|
582
|
+
if (countOnly) {
|
|
583
|
+
if (!matchesGlob(absPath)) continue;
|
|
584
|
+
const norm = await readGrepFileShadow(absPath);
|
|
585
|
+
if (!norm) continue;
|
|
586
|
+
const hit = makeHitFromIndices(norm, toDisplayPath(ctx.cwd, absPath), indices, context, validatedRegex, totalForFile, indices.length);
|
|
587
|
+
const display = displayRowsForHit(hit);
|
|
588
|
+
totalRows += display.length;
|
|
589
|
+
for (const r of display) totalBytes += Buffer.byteLength(r, "utf-8") + 1;
|
|
590
|
+
const remainingCountOnly = limit - matches;
|
|
591
|
+
if (remainingCountOnly > 0) {
|
|
592
|
+
const add = Math.min(hit.matchCount, remainingCountOnly);
|
|
593
|
+
matches += add;
|
|
594
|
+
if (hit.matchCount > remainingCountOnly) limitTruncated = true;
|
|
595
|
+
} else {
|
|
596
|
+
limitTruncated = true;
|
|
597
|
+
}
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
const remaining = limit - matches;
|
|
601
|
+
if (remaining <= 0) {
|
|
602
|
+
limitTruncated = true;
|
|
603
|
+
break;
|
|
604
|
+
}
|
|
605
|
+
if (!matchesGlob(absPath)) continue;
|
|
606
|
+
const norm = await readGrepFile(absPath);
|
|
607
|
+
if (!norm) continue;
|
|
608
|
+
const hit = makeHitFromIndices(norm, toDisplayPath(ctx.cwd, absPath), indices, context, validatedRegex, totalForFile, Math.min(totalForFile, remaining));
|
|
609
|
+
const display = displayRowsForHit(hit);
|
|
610
|
+
const keptRows: string[] = [];
|
|
611
|
+
const keptHashes: string[] = [];
|
|
612
|
+
const keptLineNumbers: number[] = [];
|
|
613
|
+
const keptFragmented: boolean[] = [];
|
|
614
|
+
for (let i = 0; i < display.length; i++) {
|
|
615
|
+
const row = display[i]!;
|
|
616
|
+
const rowBytes = Buffer.byteLength(row, "utf-8") + 1;
|
|
617
|
+
if (rowCount >= DEFAULT_MAX_LINES || byteCount + rowBytes > DEFAULT_MAX_BYTES) {
|
|
618
|
+
rowTruncated = true;
|
|
619
|
+
if (truncatedBy === null) truncatedBy = byteCount + rowBytes > DEFAULT_MAX_BYTES ? "bytes" : "lines";
|
|
620
|
+
for (let j = i; j < display.length; j++) {
|
|
621
|
+
totalRows += 1;
|
|
622
|
+
totalBytes += Buffer.byteLength(display[j]!, "utf-8") + 1;
|
|
623
|
+
}
|
|
624
|
+
break;
|
|
625
|
+
}
|
|
626
|
+
keptRows.push(row);
|
|
627
|
+
keptHashes.push(hit.hashes[i]!);
|
|
628
|
+
keptLineNumbers.push(hit.lineNumbers[i]!);
|
|
629
|
+
keptFragmented.push(hit.fragmented[i]!);
|
|
630
|
+
if (hit.fragmented[i]) linesReplaced += 1;
|
|
631
|
+
rowCount += 1;
|
|
632
|
+
byteCount += rowBytes;
|
|
633
|
+
totalRows += 1;
|
|
634
|
+
totalBytes += rowBytes;
|
|
635
|
+
}
|
|
636
|
+
if (hit.totalMatchCount > hit.matchCount) limitTruncated = true;
|
|
637
|
+
matches += hit.matchCount;
|
|
638
|
+
const displayHit: FileHit = { ...hit, rows: keptRows, hashes: keptHashes, lineNumbers: keptLineNumbers, fragmented: keptFragmented };
|
|
639
|
+
hits.push(displayHit);
|
|
640
|
+
if (rowTruncated) countOnly = true;
|
|
641
|
+
}
|
|
642
|
+
hits.sort((a, b) => cmp(a.displayPath, b.displayPath));
|
|
643
|
+
for (const hit of hits) {
|
|
644
|
+
serveRows(hit.path, hit.fileHashes, hit.fileLines, hit.hashes);
|
|
645
|
+
}
|
|
646
|
+
const blocks = hits
|
|
647
|
+
.map((hit) => `=== ${hit.displayPath} ===\n${hit.rows.join("\n")}`)
|
|
648
|
+
.join("\n");
|
|
649
|
+
const notes: string[] = [];
|
|
650
|
+
if (rowTruncated) notes.push(`[grep: output truncated at ${DEFAULT_MAX_LINES} rows or ${formatSize(DEFAULT_MAX_BYTES)}; refine the pattern to see more.]`);
|
|
651
|
+
if (limitTruncated) notes.push(`[grep: showing first ${limit} matches; increase limit to see more.]`);
|
|
652
|
+
if (linesReplaced > 0) notes.push(`[grep: ${linesReplaced} line(s) exceed ${formatSize(MAX_GREP_LINE_BYTES)} and are shown as truncated fragments; use read to see the full lines.]`);
|
|
653
|
+
if (poolSkipped > 0) notes.push(`[grep: ${poolSkipped} file(s) skipped because the session's anchor pool is exhausted; narrow the search.]`);
|
|
654
|
+
const truncated = limitTruncated || rowTruncated;
|
|
655
|
+
const truncation: TruncationResult | undefined = rowTruncated
|
|
656
|
+
? {
|
|
657
|
+
content: blocks,
|
|
658
|
+
truncated: true,
|
|
659
|
+
truncatedBy,
|
|
660
|
+
totalLines: totalRows,
|
|
661
|
+
totalBytes,
|
|
662
|
+
outputLines: rowCount,
|
|
663
|
+
outputBytes: byteCount,
|
|
664
|
+
lastLinePartial: false,
|
|
665
|
+
firstLineExceedsLimit: false,
|
|
666
|
+
maxLines: DEFAULT_MAX_LINES,
|
|
667
|
+
maxBytes: DEFAULT_MAX_BYTES,
|
|
668
|
+
}
|
|
669
|
+
: undefined;
|
|
670
|
+
const text = blocks.length > 0
|
|
671
|
+
? `${blocks}${notes.length > 0 ? `\n${notes.join("\n")}` : ""}`
|
|
672
|
+
: notes.length > 0
|
|
673
|
+
? `No matches found.\n${notes.join("\n")}`
|
|
674
|
+
: "No matches found.";
|
|
675
|
+
return {
|
|
676
|
+
content: [{ type: "text", text }],
|
|
677
|
+
details: {
|
|
678
|
+
...(truncation ? { truncation } : {}),
|
|
679
|
+
...(linesReplaced > 0 ? { linesTruncated: true as const } : {}),
|
|
680
|
+
metrics: {
|
|
681
|
+
matches,
|
|
682
|
+
files: hits.length,
|
|
683
|
+
truncated,
|
|
684
|
+
},
|
|
685
|
+
},
|
|
686
|
+
};
|
|
687
|
+
});
|
|
688
|
+
},
|
|
689
|
+
});
|
|
690
|
+
}
|