@criogaid/pi-hashline-edit 0.7.0 → 0.9.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/README.md +76 -220
- package/README.zh-CN.md +166 -0
- package/package.json +2 -1
- package/src/core/AGENTS.md +1 -1
- package/src/core/apply.test.ts +171 -133
- package/src/core/apply.ts +34 -31
- package/src/core/case-fold.test.ts +11 -7
- package/src/core/case-fold.ts +2 -6
- package/src/core/character-set.ts +14 -0
- package/src/core/hash.test.ts +1 -25
- package/src/core/hash.ts +0 -5
- package/src/core/lines.ts +25 -7
- package/src/core/ranges.test.ts +49 -9
- package/src/core/ranges.ts +15 -4
- package/src/core/regex.ts +36 -6
- package/src/core/replace-schema.ts +18 -11
- package/src/core/replace.test.ts +90 -0
- package/src/core/replace.ts +6 -5
- package/src/core/search-analysis.test.ts +9 -0
- package/src/core/search-analysis.ts +35 -31
- package/src/core/search.ts +1 -1
- package/src/core/types.ts +6 -8
- package/src/index.ts +2 -4
- package/src/integration/config-registration.test.ts +18 -10
- package/src/integration/fusion-dispatch.test.ts +41 -22
- package/src/integration/grep-flags.test.ts +6 -13
- package/src/integration/grep-js-completeness.test.ts +41 -31
- package/src/integration/grep-order.test.ts +78 -0
- package/src/integration/grep-path-matrix.test.ts +4 -3
- package/src/integration/grep-regex.test.ts +13 -16
- package/src/integration/grep-rg.test.ts +132 -92
- package/src/integration/grep-scan-budget.test.ts +27 -5
- package/src/integration/large-text.test.ts +4 -5
- package/src/integration/model-budget-lifecycle.test.ts +26 -8
- package/src/integration/mutation-file-types.test.ts +0 -1
- package/src/integration/mutation-file-types.testing.ts +2 -2
- package/src/integration/npm-package.testing.ts +7 -33
- package/src/integration/publication-read-changes.test.ts +60 -28
- package/src/integration/replace-package.testing.ts +4 -1
- package/src/integration/replace-worker-boundary.test.ts +34 -24
- package/src/integration/report-replay.test.ts +3 -3
- package/src/integration/utf8-errors.test.ts +3 -3
- package/src/pi/AGENTS.md +13 -14
- package/src/pi/action-fusion.test.ts +75 -220
- package/src/pi/action-fusion.ts +37 -74
- package/src/pi/anchor-format.test.ts +16 -0
- package/src/pi/anchor-format.ts +7 -3
- package/src/pi/argument-diagnostics.ts +35 -186
- package/src/pi/argument-error.testing.ts +7 -4
- package/src/pi/argument-error.ts +5 -7
- package/src/pi/argument-format.test.ts +25 -38
- package/src/pi/argument-validation.test.ts +446 -420
- package/src/pi/argument-validation.ts +4 -5
- package/src/pi/budgets.ts +5 -7
- package/src/pi/config.test.ts +15 -5
- package/src/pi/config.ts +6 -6
- package/src/pi/diagnostic-buffer.test.ts +2 -3
- package/src/pi/diagnostic-buffer.ts +2 -2
- package/src/pi/edit-tool.ts +175 -121
- package/src/pi/execute.test.ts +170 -227
- package/src/pi/failure-context.test.ts +61 -16
- package/src/pi/failure-context.ts +13 -10
- package/src/pi/failure-path.test.ts +115 -50
- package/src/pi/file-commit.test.ts +30 -46
- package/src/pi/file-commit.ts +11 -40
- package/src/pi/file-revision.ts +25 -0
- package/src/pi/fusion-card-interaction.test.ts +143 -0
- package/src/pi/fusion-card.test.ts +193 -37
- package/src/pi/fusion-card.ts +186 -116
- package/src/pi/grep-candidates.ts +25 -27
- package/src/pi/grep-matrix.test.ts +1 -1
- package/src/pi/grep-order.test.ts +323 -0
- package/src/pi/grep-output.testing.ts +24 -0
- package/src/pi/grep-output.ts +62 -69
- package/src/pi/grep-render.ts +4 -1
- package/src/pi/grep-scope.ts +1 -1
- package/src/pi/grep-search.ts +85 -56
- package/src/pi/grep-tool.ts +17 -48
- package/src/pi/grep.test.ts +271 -170
- package/src/pi/mutation-outcome.testing.ts +2 -3
- package/src/pi/mutation-result.test.ts +26 -19
- package/src/pi/mutation-result.ts +25 -40
- package/src/pi/mutation-runner.ts +9 -17
- package/src/pi/output-budgets.test.ts +27 -18
- package/src/pi/path.ts +3 -1
- package/src/pi/pi.test.ts +7 -6
- package/src/pi/read-tool.ts +32 -80
- package/src/pi/read.test.ts +145 -92
- package/src/pi/regex-worker-contract.ts +5 -23
- package/src/pi/regex-worker.ts +4 -10
- package/src/pi/registration.test.ts +106 -67
- package/src/pi/render.test.ts +239 -109
- package/src/pi/render.ts +42 -22
- package/src/pi/replace-regex.ts +3 -5
- package/src/pi/replace-tool.ts +29 -27
- package/src/pi/replace-worker-contract.ts +3 -12
- package/src/pi/replace.test.ts +144 -226
- package/src/pi/report-cause.ts +23 -19
- package/src/pi/report-failure.testing.ts +2 -2
- package/src/pi/report-schema.ts +60 -45
- package/src/pi/report.test.ts +138 -71
- package/src/pi/report.ts +40 -43
- package/src/pi/result-safety.test.ts +186 -131
- package/src/pi/rg-process.test.ts +36 -10
- package/src/pi/rg-process.ts +9 -3
- package/src/pi/rg-regex.test.ts +17 -0
- package/src/pi/rg-regex.ts +28 -22
- package/src/pi/text-stream.test.ts +35 -36
- package/src/pi/text-stream.ts +14 -14
- package/src/pi/tool-call.testing.ts +17 -7
- package/src/pi/write-tool.ts +9 -11
- package/src/pi/write.test.ts +43 -75
- package/src/testing/regex-translation-corpus.ts +16 -0
- package/src/testing/rg-line-listing.fixture.mjs +1 -1
- package/src/integration/forget-grep.test.ts +0 -148
- package/src/pi/forget-tool.ts +0 -367
- package/src/pi/forget.test.ts +0 -630
- package/src/pi/forget.testing.ts +0 -201
package/src/pi/grep-search.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Native RegExp matching in a bounded worker pool. grep-candidates supplies absolute paths
|
|
3
|
-
* and optional candidate lines; this module owns queue backpressure,
|
|
4
|
-
*
|
|
3
|
+
* and optional candidate lines; this module owns queue backpressure, worker cleanup, and
|
|
4
|
+
* each matched file's revision.
|
|
5
5
|
*
|
|
6
6
|
* @module pi-hashline-edit/pi
|
|
7
7
|
*/
|
|
8
|
-
import { createHash } from "node:crypto";
|
|
9
8
|
import { stat } from "node:fs/promises";
|
|
10
9
|
import { availableParallelism } from "node:os";
|
|
11
10
|
import { countLines } from "../core/lines.ts";
|
|
@@ -18,6 +17,7 @@ import { listCandidates, type Candidate } from "./grep-candidates.ts";
|
|
|
18
17
|
import { withRegexWorker } from "./regex-worker.ts";
|
|
19
18
|
import { invalidWorkerResult, workerReplyDecoder } from "./regex-worker-contract.ts";
|
|
20
19
|
import { fileReadWarning, throwIfCancelled } from "./error-text.ts";
|
|
20
|
+
import { formatByteSize } from "./budgets.ts";
|
|
21
21
|
|
|
22
22
|
/** Matching physical lines in ascending order, with the revision they were searched against. */
|
|
23
23
|
export interface GrepFileMatch {
|
|
@@ -30,31 +30,31 @@ export interface GrepFileMatch {
|
|
|
30
30
|
interface SearchFileSnapshot {
|
|
31
31
|
readonly revision: string;
|
|
32
32
|
readonly validUtf8: boolean;
|
|
33
|
-
readonly totalLines: number;
|
|
34
33
|
}
|
|
35
34
|
|
|
36
35
|
/** Whole-file input of a multiline query; README's search limits link here. */
|
|
37
36
|
export const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
|
|
38
37
|
/** Line-mode requests end after a line feed once they reach this many UTF-16 units. */
|
|
39
38
|
const SEARCH_CHUNK_UNITS = 1024 * 1024;
|
|
40
|
-
/**
|
|
39
|
+
/** Maximum UTF-16 code units in one physical line; independent of its encoded byte length. */
|
|
41
40
|
const MAX_SEARCH_LINE_UNITS = MAX_MULTILINE_SEARCH_BYTES;
|
|
42
41
|
const MAX_SEARCH_HEAP_MB = 512;
|
|
43
42
|
const MAX_SEARCH_WORKERS = 4;
|
|
44
43
|
const SEARCH_WORKERS = Math.max(1, Math.min(MAX_SEARCH_WORKERS, availableParallelism() - 1));
|
|
44
|
+
/** Listed files that may wait, searched or not, for an earlier file's result to commit. */
|
|
45
|
+
const MAX_UNCOMMITTED_FILES = 16 * SEARCH_WORKERS;
|
|
45
46
|
class SearchFileLimitError extends Error {
|
|
46
47
|
constructor(multiline: boolean) {
|
|
47
|
-
const limit = `${MAX_MULTILINE_SEARCH_BYTES / 1024 ** 2} MiB`;
|
|
48
48
|
super(
|
|
49
49
|
multiline
|
|
50
|
-
? `Multiline search requires a file of at most ${
|
|
51
|
-
: `Search requires lines of at most ${
|
|
50
|
+
? `Multiline search requires a file of at most ${formatByteSize(MAX_MULTILINE_SEARCH_BYTES)}.`
|
|
51
|
+
: `Search requires lines of at most ${MAX_SEARCH_LINE_UNITS} UTF-16 code units.`,
|
|
52
52
|
);
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
/** A worker failure inside a file scan;
|
|
57
|
-
class
|
|
56
|
+
/** A worker failure inside a file scan; never classify it as a file-read warning. */
|
|
57
|
+
class ScanWorkerFailure {
|
|
58
58
|
readonly error: unknown;
|
|
59
59
|
constructor(error: unknown) {
|
|
60
60
|
this.error = error;
|
|
@@ -64,6 +64,15 @@ class WorkerFailure {
|
|
|
64
64
|
const decodeReply = workerReplyDecoder(SEARCH_RESULT_SCHEMA);
|
|
65
65
|
type Rows = SearchResult["lines"];
|
|
66
66
|
type Run = (input: SearchInput | LineSearchInput) => Promise<SearchResult>;
|
|
67
|
+
/** A listed candidate and its position in the listing. */
|
|
68
|
+
interface Queued {
|
|
69
|
+
readonly candidate: Candidate;
|
|
70
|
+
readonly position: number;
|
|
71
|
+
}
|
|
72
|
+
/** A searched candidate, including fatal failures that only matter before the ordered cutoff. */
|
|
73
|
+
type Settled =
|
|
74
|
+
| { readonly file?: GrepFileMatch; readonly warning?: string }
|
|
75
|
+
| { readonly error: unknown };
|
|
67
76
|
|
|
68
77
|
/**
|
|
69
78
|
* The candidate lines among the next lines of a request source, as the LF view shows them.
|
|
@@ -106,7 +115,6 @@ async function searchFile(
|
|
|
106
115
|
): Promise<{ rows: Rows; snapshot: SearchFileSnapshot } | undefined> {
|
|
107
116
|
if (query.multiline && (await stat(filePath)).size > MAX_MULTILINE_SEARCH_BYTES)
|
|
108
117
|
throw new SearchFileLimitError(true);
|
|
109
|
-
const hash = createHash("sha256");
|
|
110
118
|
const rows: Rows = [];
|
|
111
119
|
let lineOffset = 0;
|
|
112
120
|
let nextWanted = 0;
|
|
@@ -115,7 +123,7 @@ async function searchFile(
|
|
|
115
123
|
try {
|
|
116
124
|
result = await run(input);
|
|
117
125
|
} catch (error) {
|
|
118
|
-
throw new
|
|
126
|
+
throw new ScanWorkerFailure(error);
|
|
119
127
|
}
|
|
120
128
|
if (result.totalLines !== lines || result.lines.length > input.limit)
|
|
121
129
|
throw invalidWorkerResult();
|
|
@@ -158,17 +166,24 @@ async function searchFile(
|
|
|
158
166
|
let pending = "";
|
|
159
167
|
/** Length of pending through its last line feed. */
|
|
160
168
|
let complete = 0;
|
|
161
|
-
let
|
|
169
|
+
let lineUnits = 0;
|
|
162
170
|
const stats = await scanTextFile(filePath, {
|
|
163
|
-
onChunk: async (text) => {
|
|
171
|
+
onChunk: async (text, bytesRead) => {
|
|
164
172
|
if (query.multiline) {
|
|
165
|
-
if (
|
|
173
|
+
if (bytesRead <= MAX_MULTILINE_SEARCH_BYTES) pending += text;
|
|
166
174
|
return;
|
|
167
175
|
}
|
|
168
|
-
|
|
169
|
-
|
|
176
|
+
let start = 0;
|
|
177
|
+
for (;;) {
|
|
178
|
+
const lf = text.indexOf("\n", start);
|
|
179
|
+
lineUnits += (lf === -1 ? text.length : lf) - start;
|
|
180
|
+
if (lineUnits > MAX_SEARCH_LINE_UNITS) throw new SearchFileLimitError(false);
|
|
181
|
+
if (lf === -1) break;
|
|
182
|
+
lineUnits = 0;
|
|
183
|
+
complete = pending.length + lf + 1;
|
|
184
|
+
start = lf + 1;
|
|
185
|
+
}
|
|
170
186
|
pending += text;
|
|
171
|
-
if (pending.length - complete > MAX_SEARCH_LINE_UNITS) throw new SearchFileLimitError(false);
|
|
172
187
|
if (complete >= SEARCH_CHUNK_UNITS) {
|
|
173
188
|
const source = pending.slice(0, complete);
|
|
174
189
|
pending = pending.slice(complete);
|
|
@@ -177,28 +192,23 @@ async function searchFile(
|
|
|
177
192
|
}
|
|
178
193
|
},
|
|
179
194
|
signal,
|
|
180
|
-
onBytes: (chunk) => {
|
|
181
|
-
bytes += chunk.length;
|
|
182
|
-
hash.update(chunk);
|
|
183
|
-
},
|
|
184
195
|
decoding: "lossy",
|
|
185
196
|
});
|
|
186
197
|
if (stats.hasNul) return undefined;
|
|
187
|
-
if (
|
|
198
|
+
if (stats.byteLength > MAX_MULTILINE_SEARCH_BYTES && query.multiline)
|
|
199
|
+
throw new SearchFileLimitError(true);
|
|
188
200
|
await send(pending);
|
|
189
201
|
return {
|
|
190
202
|
rows,
|
|
191
|
-
snapshot: {
|
|
192
|
-
revision: hash.digest("hex"),
|
|
193
|
-
validUtf8: stats.validUtf8,
|
|
194
|
-
totalLines: stats.totalLines,
|
|
195
|
-
},
|
|
203
|
+
snapshot: { revision: stats.revision, validUtf8: stats.validUtf8 },
|
|
196
204
|
};
|
|
197
205
|
}
|
|
198
206
|
|
|
199
207
|
/**
|
|
200
|
-
* Search every candidate file in scope. Paths stream from rg into a queue that
|
|
201
|
-
* SEARCH_WORKERS workers drain; a worker starts only when no idle one can take a path.
|
|
208
|
+
* Search every candidate file in scope. Paths stream from rg in listing order into a queue that
|
|
209
|
+
* at most SEARCH_WORKERS workers drain; a worker starts only when no idle one can take a path.
|
|
210
|
+
* Workers finish in any order, so results commit in listing order: every run returns the same
|
|
211
|
+
* files, rows, and warnings, and a limit keeps the first matches in that order.
|
|
202
212
|
*/
|
|
203
213
|
export async function searchFiles(options: {
|
|
204
214
|
readonly backend: GrepBackend;
|
|
@@ -212,6 +222,7 @@ export async function searchFiles(options: {
|
|
|
212
222
|
}) {
|
|
213
223
|
const { backend, rgPath, scope, query, limit, timeoutMs, signal, warnings } = options;
|
|
214
224
|
const files: GrepFileMatch[] = [];
|
|
225
|
+
/** Committed matches; a file still searching gets at most the remaining room. */
|
|
215
226
|
let matches = 0;
|
|
216
227
|
let matchLimitReached = false;
|
|
217
228
|
let failure: { error: unknown } | undefined;
|
|
@@ -222,7 +233,7 @@ export async function searchFiles(options: {
|
|
|
222
233
|
failed.abort();
|
|
223
234
|
};
|
|
224
235
|
|
|
225
|
-
const queue:
|
|
236
|
+
const queue: Queued[] = [];
|
|
226
237
|
let listed = false;
|
|
227
238
|
const idle: (() => void)[] = [];
|
|
228
239
|
const space: (() => void)[] = [];
|
|
@@ -231,37 +242,53 @@ export async function searchFiles(options: {
|
|
|
231
242
|
for (const wake of idle.splice(0)) wake();
|
|
232
243
|
for (const wake of space.splice(0)) wake();
|
|
233
244
|
};
|
|
234
|
-
const next = async (): Promise<
|
|
245
|
+
const next = async (): Promise<Queued | undefined> => {
|
|
235
246
|
while (!queue.length && !listed && !stopped())
|
|
236
247
|
await new Promise<void>((wake) => idle.push(wake));
|
|
237
248
|
space.shift()?.();
|
|
238
249
|
return stopped() ? undefined : queue.shift();
|
|
239
250
|
};
|
|
240
251
|
|
|
241
|
-
|
|
252
|
+
/** Searched candidates by listing position, until every earlier one has committed. */
|
|
253
|
+
const settled = new Map<number, Settled>();
|
|
254
|
+
let enqueued = 0;
|
|
255
|
+
let committed = 0;
|
|
256
|
+
const commit = () => {
|
|
257
|
+
for (let result = settled.get(committed); result && !stopped(); ) {
|
|
258
|
+
settled.delete(committed++);
|
|
259
|
+
if ("error" in result) fail(result.error);
|
|
260
|
+
else if (result.warning) warnings.push(result.warning);
|
|
261
|
+
else if (result.file) {
|
|
262
|
+
const rows = result.file.rows.slice(0, limit - matches);
|
|
263
|
+
files.push({ ...result.file, rows });
|
|
264
|
+
matches += rows.length;
|
|
265
|
+
if (matches >= limit) matchLimitReached = true;
|
|
266
|
+
}
|
|
267
|
+
result = settled.get(committed);
|
|
268
|
+
}
|
|
269
|
+
releaseAll();
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const searchPath = async ({ candidate, position }: Queued, run: Run) => {
|
|
242
273
|
const { filePath } = candidate;
|
|
243
|
-
let
|
|
274
|
+
let result: Settled;
|
|
244
275
|
try {
|
|
245
|
-
found = await searchFile(candidate, query, () => limit - matches, run, poolSignal);
|
|
276
|
+
const found = await searchFile(candidate, query, () => limit - matches, run, poolSignal);
|
|
277
|
+
result = found?.rows.length ? { file: { filePath, ...found } } : {};
|
|
246
278
|
} catch (error) {
|
|
247
|
-
|
|
279
|
+
throwIfCancelled(poolSignal);
|
|
248
280
|
const warning =
|
|
249
281
|
error instanceof SearchFileLimitError
|
|
250
282
|
? `${filePath}: ${error.message}`
|
|
251
283
|
: fileReadWarning(filePath, error, poolSignal);
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
}
|
|
256
|
-
const room = limit - matches;
|
|
257
|
-
if (!found?.rows.length || room <= 0) return;
|
|
258
|
-
const rows = found.rows.slice(0, room);
|
|
259
|
-
files.push({ filePath, rows, snapshot: found.snapshot });
|
|
260
|
-
matches += rows.length;
|
|
261
|
-
if (matches >= limit) {
|
|
262
|
-
matchLimitReached = true;
|
|
263
|
-
releaseAll();
|
|
284
|
+
result = warning
|
|
285
|
+
? { warning }
|
|
286
|
+
: { error: error instanceof ScanWorkerFailure ? error.error : error };
|
|
264
287
|
}
|
|
288
|
+
settled.set(position, result);
|
|
289
|
+
commit();
|
|
290
|
+
// Nothing after a fatal candidate can be needed; retire its worker without reusing a failure.
|
|
291
|
+
return !("error" in result);
|
|
265
292
|
};
|
|
266
293
|
|
|
267
294
|
const workers: Promise<void>[] = [];
|
|
@@ -273,7 +300,7 @@ export async function searchFiles(options: {
|
|
|
273
300
|
poolSignal,
|
|
274
301
|
async (run) => {
|
|
275
302
|
for (let file = await next(); file !== undefined; file = await next())
|
|
276
|
-
await searchPath(file, run);
|
|
303
|
+
if (!(await searchPath(file, run))) break;
|
|
277
304
|
},
|
|
278
305
|
{ maxOldGenerationSizeMb: MAX_SEARCH_HEAP_MB },
|
|
279
306
|
).catch((error) => {
|
|
@@ -281,16 +308,16 @@ export async function searchFiles(options: {
|
|
|
281
308
|
releaseAll();
|
|
282
309
|
});
|
|
283
310
|
|
|
284
|
-
const seen = new Set<string>();
|
|
285
311
|
const enqueue = async (candidate: Candidate) => {
|
|
286
|
-
const { filePath } = candidate;
|
|
287
312
|
if (stopped()) return false;
|
|
288
|
-
|
|
289
|
-
seen.add(filePath);
|
|
290
|
-
queue.push(candidate);
|
|
313
|
+
queue.push({ candidate, position: enqueued++ });
|
|
291
314
|
if (idle.length) idle.shift()!();
|
|
292
315
|
else if (workers.length < SEARCH_WORKERS) workers.push(startWorker());
|
|
293
|
-
|
|
316
|
+
// A slow early file holds back every later result; bound what waits behind it.
|
|
317
|
+
while (
|
|
318
|
+
(queue.length >= SEARCH_WORKERS || enqueued - committed >= MAX_UNCOMMITTED_FILES) &&
|
|
319
|
+
!stopped()
|
|
320
|
+
)
|
|
294
321
|
await new Promise<void>((wake) => space.push(wake));
|
|
295
322
|
return !stopped();
|
|
296
323
|
};
|
|
@@ -302,9 +329,9 @@ export async function searchFiles(options: {
|
|
|
302
329
|
scope,
|
|
303
330
|
query,
|
|
304
331
|
signal: poolSignal,
|
|
332
|
+
stopped,
|
|
305
333
|
onCandidate: enqueue,
|
|
306
334
|
});
|
|
307
|
-
if (selection.listing) recordSearchDiagnostics(selection.listing, warnings);
|
|
308
335
|
} catch (error) {
|
|
309
336
|
fail(error);
|
|
310
337
|
throw error;
|
|
@@ -315,6 +342,8 @@ export async function searchFiles(options: {
|
|
|
315
342
|
throwIfCancelled(signal);
|
|
316
343
|
if (failure) throw failure.error;
|
|
317
344
|
}
|
|
345
|
+
// After every file's warning, so their order does not depend on when the listing ends.
|
|
346
|
+
if (selection.listing) recordSearchDiagnostics(selection.listing, warnings);
|
|
318
347
|
return {
|
|
319
348
|
files,
|
|
320
349
|
matchLimitReached,
|
package/src/pi/grep-tool.ts
CHANGED
|
@@ -11,8 +11,7 @@ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
|
11
11
|
import { rgPath as bundledRgPath } from "@vscode/ripgrep";
|
|
12
12
|
import { Type, type Static } from "typebox";
|
|
13
13
|
import { Text } from "@earendil-works/pi-tui";
|
|
14
|
-
import { renderOutputPreview, renderToolError, reportLines,
|
|
15
|
-
import { type ForgetReceiptDetails, grepReceipt, withResultTag } from "./forget-tool.ts";
|
|
14
|
+
import { renderOutputPreview, renderToolError, reportLines, splitReport } from "./render.ts";
|
|
16
15
|
import { createAnchorFormatter } from "./anchor-format.ts";
|
|
17
16
|
import { grepOutput } from "./grep-output.ts";
|
|
18
17
|
import {
|
|
@@ -25,9 +24,8 @@ import { searchFiles } from "./grep-search.ts";
|
|
|
25
24
|
import { toDisplayLines } from "./grep-render.ts";
|
|
26
25
|
import { runRgLines, runRgPaths, type GrepBackend } from "./rg-process.ts";
|
|
27
26
|
import { smartIgnoreCase } from "../core/search-analysis.ts";
|
|
28
|
-
import {
|
|
27
|
+
import { checkRegexArguments } from "../core/regex.ts";
|
|
29
28
|
import { DEFAULT_GREP_FLAGS } from "../core/search.ts";
|
|
30
|
-
import { errorMessage } from "../core/errors.ts";
|
|
31
29
|
import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER } from "./schema.ts";
|
|
32
30
|
import { throwIfCancelled } from "./error-text.ts";
|
|
33
31
|
import { reportResult, runTool, type ReportDetails } from "./report.ts";
|
|
@@ -76,13 +74,13 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
|
|
|
76
74
|
}),
|
|
77
75
|
flags: Type.Optional(
|
|
78
76
|
Type.String({
|
|
79
|
-
description: `JavaScript regex flags (default ${DEFAULT_GREP_FLAGS});
|
|
77
|
+
description: `JavaScript regex flags (default ${DEFAULT_GREP_FLAGS}); given flags replace the default, so in a multiline search without m, ^ and $ anchor to the file's start and end. g is always enabled and repeated flags are ignored. Use u or v for Unicode mode, s for dotAll, and y for sticky matching.`,
|
|
80
78
|
}),
|
|
81
79
|
),
|
|
82
80
|
ignoreCase: Type.Optional(
|
|
83
81
|
Type.Boolean({
|
|
84
82
|
description:
|
|
85
|
-
"true ignores case, false matches case; overrides the i flag. When omitted, the i flag ignores case;
|
|
83
|
+
"true ignores case, false matches case; overrides the i flag. When omitted, the i flag ignores case; without it, case is ignored only when no pattern contains an uppercase letter (a pattern that cannot be analyzed counts as uppercase).",
|
|
86
84
|
}),
|
|
87
85
|
),
|
|
88
86
|
multiline: Type.Optional(
|
|
@@ -106,7 +104,7 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
|
|
|
106
104
|
outputMode: Type.Optional(
|
|
107
105
|
Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
|
|
108
106
|
description:
|
|
109
|
-
'"content" (default): matches/context with anchors for valid UTF-8 or plain previews otherwise; "files": paths; "count": matching lines per file and total. Use files or count when only paths or counts are needed.
|
|
107
|
+
'"content" (default): matches/context with anchors for valid UTF-8 or plain previews otherwise; "files": paths; "count": matching lines per file and total. Use files or count when only paths or counts are needed. limit counts matching lines in every mode, so files and count stop at the same cutoff as content.',
|
|
110
108
|
}),
|
|
111
109
|
),
|
|
112
110
|
},
|
|
@@ -116,37 +114,17 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
|
|
|
116
114
|
type GrepSchema = ReturnType<typeof createGrepSchema>;
|
|
117
115
|
/** How grep presents matches; grep-output formats each mode. */
|
|
118
116
|
export type GrepOutputMode = NonNullable<Static<GrepSchema>["outputMode"]>;
|
|
119
|
-
type GrepTool = ToolDefinition<
|
|
120
|
-
GrepSchema,
|
|
121
|
-
({ incomplete?: true } & ForgetReceiptDetails & Partial<ReportDetails>) | undefined
|
|
122
|
-
>;
|
|
117
|
+
type GrepTool = ToolDefinition<GrepSchema, Partial<ReportDetails> | undefined>;
|
|
123
118
|
/** Validate JavaScript syntax once; the search never rejects a pattern V8 accepts. */
|
|
124
119
|
function checkGrepArguments(args: unknown, report: ReportArgumentIssue): void {
|
|
125
120
|
const { pattern, literal, flags } = (args ?? {}) as Record<string, unknown>;
|
|
126
121
|
if (typeof literal !== "boolean" || (flags !== undefined && typeof flags !== "string")) return;
|
|
127
|
-
try {
|
|
128
|
-
buildRegex("", false, flags ?? DEFAULT_GREP_FLAGS);
|
|
129
|
-
} catch (error) {
|
|
130
|
-
report("flags", errorMessage(error));
|
|
131
|
-
return;
|
|
132
|
-
}
|
|
133
|
-
if (literal) return;
|
|
134
122
|
const fields = Array.isArray(pattern)
|
|
135
123
|
? pattern.map((value, index) => [`pattern[${index}]`, value] as const)
|
|
136
124
|
: [["pattern", pattern] as const];
|
|
137
|
-
|
|
138
|
-
if (typeof value !== "string" || value === "") continue;
|
|
139
|
-
try {
|
|
140
|
-
buildRegex(value, true, flags ?? DEFAULT_GREP_FLAGS);
|
|
141
|
-
} catch (error) {
|
|
142
|
-
report(field, errorMessage(error));
|
|
143
|
-
}
|
|
144
|
-
}
|
|
125
|
+
checkRegexArguments("flags", flags ?? DEFAULT_GREP_FLAGS, literal, fields, report);
|
|
145
126
|
}
|
|
146
127
|
|
|
147
|
-
/** The grep card shows the forget id only on the forget card. */
|
|
148
|
-
const GREP_CARD_SHOWN = new Set(["resultId"]);
|
|
149
|
-
|
|
150
128
|
/** Build the production grep override (a ToolDefinition fragment for registerTool). */
|
|
151
129
|
export function makeGrepOverride(
|
|
152
130
|
cwd: string,
|
|
@@ -210,13 +188,13 @@ export function makeGrepOverrideWithBackend(
|
|
|
210
188
|
context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
|
|
211
189
|
) {
|
|
212
190
|
if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
|
|
213
|
-
if (context?.isError) return renderToolError(result, theme, expanded);
|
|
214
|
-
const
|
|
215
|
-
const
|
|
191
|
+
if (context?.isError) return renderToolError(result, "grep", theme, expanded);
|
|
192
|
+
const { content, report } = splitReport(result);
|
|
193
|
+
const payload = content[0];
|
|
216
194
|
return renderOutputPreview(
|
|
217
195
|
[
|
|
218
196
|
...(payload?.type === "text" ? toDisplayLines(payload.text, theme) : []),
|
|
219
|
-
...(report ? reportLines(report, theme
|
|
197
|
+
...(report ? reportLines(report, theme) : []),
|
|
220
198
|
],
|
|
221
199
|
expanded,
|
|
222
200
|
theme,
|
|
@@ -224,7 +202,7 @@ export function makeGrepOverrideWithBackend(
|
|
|
224
202
|
},
|
|
225
203
|
|
|
226
204
|
async execute(
|
|
227
|
-
|
|
205
|
+
_toolCallId: string,
|
|
228
206
|
params: Static<GrepSchema>,
|
|
229
207
|
signal: AbortSignal | undefined,
|
|
230
208
|
_onUpdate: Parameters<GrepTool["execute"]>[3],
|
|
@@ -277,7 +255,7 @@ export function makeGrepOverrideWithBackend(
|
|
|
277
255
|
signal,
|
|
278
256
|
warnings,
|
|
279
257
|
});
|
|
280
|
-
const { payload, facts
|
|
258
|
+
const { payload, facts } = await grepOutput({
|
|
281
259
|
cwd,
|
|
282
260
|
search,
|
|
283
261
|
outputMode,
|
|
@@ -286,21 +264,12 @@ export function makeGrepOverrideWithBackend(
|
|
|
286
264
|
signal,
|
|
287
265
|
warnings,
|
|
288
266
|
effectiveLimit,
|
|
267
|
+
literalPipe: literal && patterns.some((pattern) => pattern.includes("|")),
|
|
289
268
|
budget,
|
|
290
269
|
});
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
payload
|
|
294
|
-
details: incomplete ? { incomplete: true as const } : undefined,
|
|
295
|
-
};
|
|
296
|
-
// Only matched content-mode rows are file text; paths and counts have nothing to forget.
|
|
297
|
-
if (outputMode !== "content" || payload === undefined)
|
|
298
|
-
return reportResult(parts.report, parts.payload, parts.details);
|
|
299
|
-
return withResultTag(toolCallId, parts, config.forget, () =>
|
|
300
|
-
grepReceipt(patterns, facts.matches, facts.files, {
|
|
301
|
-
limitReached: search.matchLimitReached,
|
|
302
|
-
incomplete,
|
|
303
|
-
}),
|
|
270
|
+
return reportResult(
|
|
271
|
+
{ tool: "grep" as const, path: params.path, ...facts },
|
|
272
|
+
payload === undefined ? [] : [{ type: "text" as const, text: payload }],
|
|
304
273
|
);
|
|
305
274
|
});
|
|
306
275
|
},
|