@criogaid/pi-hashline-edit 0.6.1 → 0.8.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.
Files changed (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -1,41 +1,37 @@
1
1
  /**
2
2
  * Override grep: valid UTF-8 results feed edit; malformed UTF-8 uses non-editable previews.
3
- * Scope and paths live in grep-scope; search requests and ripgrep events in
4
- * grep-search; the rg process layer in rg-process; result formatting in
5
- * grep-output; TUI presentation in grep-render. This module owns the tool
6
- * schema, the production backend, render wiring, and execution order.
3
+ * grep-scope admits paths, grep-candidates selects candidates with rg, grep-search matches
4
+ * them with native JavaScript (core/search), grep-output states the payload and every report
5
+ * fact, and grep-render draws the card. This module owns the schema, backend wiring, and
6
+ * execution order.
7
7
  * @module pi-hashline-edit/pi
8
8
  */
9
9
 
10
- import { type ToolDefinition } from "@earendil-works/pi-coding-agent";
10
+ 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 } from "./render.ts";
15
- import { type ForgetReceiptDetails, grepReceipt, withResultTag } from "./forget-tool.ts";
16
- import { normalizeLineEndings } from "../core/lines.ts";
14
+ import { renderOutputPreview, renderToolError, reportLines, splitReport } from "./render.ts";
17
15
  import { createAnchorFormatter } from "./anchor-format.ts";
18
- import { assembleGrepOutput, formatMatches, formatSearchWarnings } from "./grep-output.ts";
16
+ import { grepOutput } from "./grep-output.ts";
19
17
  import {
20
- assertValidRegex,
21
18
  filterExplicitFilesByGlob,
22
19
  toArray,
23
20
  resolveSearchPaths,
24
- } from "./grep-scope.ts";
25
- import {
26
- searchMatches,
27
- type GrepBackend,
28
21
  type SearchScope,
29
- type SearchFileSnapshot,
30
- } from "./grep-search.ts";
31
- export type { GrepBackend } from "./grep-search.ts";
22
+ } from "./grep-scope.ts";
23
+ import { searchFiles } from "./grep-search.ts";
32
24
  import { toDisplayLines } from "./grep-render.ts";
33
- import { probeRegex, resolveIgnoreCase, runRgPaths, type SearchModes } from "./rg-process.ts";
34
- import { runRgTextView } from "./rg-text-view.ts";
25
+ import { runRgLines, runRgPaths, type GrepBackend } from "./rg-process.ts";
26
+ import { smartIgnoreCase } from "../core/search-analysis.ts";
27
+ import { checkRegexArguments } from "../core/regex.ts";
28
+ import { DEFAULT_GREP_FLAGS } from "../core/search.ts";
35
29
  import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER } from "./schema.ts";
36
30
  import { throwIfCancelled } from "./error-text.ts";
31
+ import { reportResult, runTool, type ReportDetails } from "./report.ts";
37
32
  import type { HashlineEditConfig } from "./config.ts";
38
- import { createArgumentPreparer } from "./argument-validation.ts";
33
+ import { createArgumentPreparer, type ReportArgumentIssue } from "./argument-validation.ts";
34
+ import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
39
35
 
40
36
  /** Grep parameters; descriptions state the configured defaults. */
41
37
  function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["grep"]) {
@@ -45,7 +41,7 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
45
41
  [Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
46
42
  {
47
43
  description:
48
- "String or array of strings (an array matches any of them). Regex syntax is ripgrep's Rust regex, not JavaScript: no lookaround or backreferences; ^ and $ match at line boundaries.",
44
+ "String or array of strings; an array matches any of them, so use it for alternatives instead of joining them with |. Regex syntax is JavaScript, as in replace.",
49
45
  },
50
46
  ),
51
47
  path: Type.Optional(
@@ -68,30 +64,35 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
68
64
  ],
69
65
  {
70
66
  description:
71
- "Filename glob, or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
67
+ "Filename wildcards go here, not in path: a glob or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
72
68
  },
73
69
  ),
74
70
  ),
75
71
  literal: Type.Boolean({
76
72
  description:
77
- "true: match the text exactly, including regex punctuation. false: ripgrep Rust regex, where foo(0) matches foo0.",
73
+ "true: match the text exactly, including regex punctuation; use it for names, paths, and code snippets. false: JavaScript regex, where foo(0) matches foo0; use it only for an intentional regex.",
78
74
  }),
75
+ flags: Type.Optional(
76
+ Type.String({
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.`,
78
+ }),
79
+ ),
79
80
  ignoreCase: Type.Optional(
80
81
  Type.Boolean({
81
82
  description:
82
- "true ignores case, false matches case; omitted uses smart-case for the whole query. Inline regex flags still apply.",
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).",
83
84
  }),
84
85
  ),
85
86
  multiline: Type.Optional(
86
87
  Type.Boolean({
87
88
  description:
88
- "Match across lines (default false); content mode returns every line a match touches. The . wildcard does not match newlines; use \\n or (?s).",
89
+ "Match across lines (default false); content mode returns every line a match touches. \\n matches LF and CRLF.",
89
90
  }),
90
91
  ),
91
92
  context: Type.Optional(
92
93
  Type.Number({
93
94
  ...GREP_CONTEXT_RANGE,
94
- description: `Lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched.`,
95
+ description: `Lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched. Use 3-5 when searching code to edit.`,
95
96
  }),
96
97
  ),
97
98
  limit: Type.Optional(
@@ -103,7 +104,7 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
103
104
  outputMode: Type.Optional(
104
105
  Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
105
106
  description:
106
- '"content" (default): matches/context with anchors for valid UTF-8 or plain previews otherwise; "files": paths; "count": matching lines per file and total. All modes share limit.',
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.',
107
108
  }),
108
109
  ),
109
110
  },
@@ -111,14 +112,26 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
111
112
  );
112
113
  }
113
114
  type GrepSchema = ReturnType<typeof createGrepSchema>;
114
- type GrepTool = ToolDefinition<
115
- GrepSchema,
116
- ({ incomplete?: true } & ForgetReceiptDetails) | undefined
117
- >;
115
+ /** How grep presents matches; grep-output formats each mode. */
116
+ export type GrepOutputMode = NonNullable<Static<GrepSchema>["outputMode"]>;
117
+ type GrepTool = ToolDefinition<GrepSchema, Partial<ReportDetails> | undefined>;
118
+ /** Validate JavaScript syntax once; the search never rejects a pattern V8 accepts. */
119
+ function checkGrepArguments(args: unknown, report: ReportArgumentIssue): void {
120
+ const { pattern, literal, flags } = (args ?? {}) as Record<string, unknown>;
121
+ if (typeof literal !== "boolean" || (flags !== undefined && typeof flags !== "string")) return;
122
+ const fields = Array.isArray(pattern)
123
+ ? pattern.map((value, index) => [`pattern[${index}]`, value] as const)
124
+ : [["pattern", pattern] as const];
125
+ checkRegexArguments("flags", flags ?? DEFAULT_GREP_FLAGS, literal, fields, report);
126
+ }
118
127
 
119
128
  /** Build the production grep override (a ToolDefinition fragment for registerTool). */
120
- export function makeGrepOverride(cwd: string, config: HashlineEditConfig) {
121
- return makeGrepOverrideWithBackend(cwd, config, {});
129
+ export function makeGrepOverride(
130
+ cwd: string,
131
+ config: HashlineEditConfig,
132
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
133
+ ) {
134
+ return makeGrepOverrideWithBackend(cwd, config, {}, budgets);
122
135
  }
123
136
 
124
137
  /** @internal — build a grep override with deterministic process backends for tests. */
@@ -126,33 +139,24 @@ export function makeGrepOverrideWithBackend(
126
139
  cwd: string,
127
140
  config: HashlineEditConfig,
128
141
  overrides: Partial<GrepBackend>,
142
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
129
143
  ) {
130
144
  const { hashLen } = config;
131
145
  const grepSchema = createGrepSchema(config.grep);
132
- const backend: GrepBackend = {
133
- search: runRgTextView,
134
- runRgPaths,
135
- resolveIgnoreCase,
136
- probeRegex,
137
- ...overrides,
138
- };
146
+ const backend: GrepBackend = { runRgPaths, runRgLines, ...overrides };
139
147
 
140
148
  return {
141
149
  name: "grep" as const,
142
150
  label: "grep",
143
151
  description:
144
- "Search file contents with ripgrep. Content mode returns LINE#HASH edit anchors for valid UTF-8 and plain line numbers without anchors otherwise; files/count modes return paths or matching-line counts. Valid UTF-8 CRLF is searched as LF; invalid UTF-8 is searched as raw bytes. NUL-containing files are skipped. Directory searches respect ignore rules and skip linked directories.",
145
- promptSnippet: "Search file contents with ripgrep",
152
+ "Search file contents. Content mode returns LINE#HASH edit anchors for valid UTF-8 and plain line numbers without anchors otherwise; files/count modes return paths or matching-line counts. NUL-containing files are skipped. Directory searches respect ignore rules and skip .git and linked directories. Use grep instead of rg or grep in a shell to search files; use the shell only for ignored, .git, or linked directories, or to filter another command's output.",
153
+ promptSnippet: "Search file contents",
146
154
  promptGuidelines: [
147
- "Prefer grep for file-content searches; use another tool for ignored or linked directories.",
148
- "In grep, use glob for filename wildcards.",
149
- "In grep, use literal:true for exact text, including names, paths, and code snippets; use literal:false only for intentional regex.",
150
- "In grep, use a pattern array for alternatives instead of joining them with |, and context:3-5 when searching code to edit.",
151
- "In grep, use multiline:true for cross-line matches and outputMode files or count when only paths or counts are needed.",
152
- "Copy grep anchors directly into edit; read the full line before rewriting from a partial preview.",
155
+ "When you need several independent searches, send them as separate grep calls in one response; they run in parallel.",
156
+ "Copy grep anchors directly into edit.",
153
157
  ],
154
158
  parameters: grepSchema,
155
- prepareArguments: createArgumentPreparer("grep", grepSchema),
159
+ prepareArguments: createArgumentPreparer("grep", grepSchema, checkGrepArguments, budgets),
156
160
 
157
161
  renderShell: "default" as const,
158
162
 
@@ -168,7 +172,7 @@ export function makeGrepOverrideWithBackend(
168
172
  const pathText = Array.isArray(rawPath) ? rawPath.join(" ") : String(rawPath ?? ".");
169
173
  let text =
170
174
  theme.fg("toolTitle", theme.bold("grep ")) +
171
- theme.fg("accent", `/${patternText}/`) +
175
+ theme.fg("accent", `/${patternText}/${args?.flags ?? ""}`) +
172
176
  theme.fg("toolOutput", ` in ${pathText}`);
173
177
  if (args?.glob) text += theme.fg("toolOutput", ` (${toArray(args.glob).join(", ")})`);
174
178
  if (args?.outputMode && args.outputMode !== "content")
@@ -184,115 +188,90 @@ export function makeGrepOverrideWithBackend(
184
188
  context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
185
189
  ) {
186
190
  if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
187
- if (context?.isError) return renderToolError(result, theme, expanded);
188
- const out = result.content?.[0]?.type === "text" ? result.content[0].text : "";
189
- return renderOutputPreview(toDisplayLines(out, theme), expanded, theme);
191
+ if (context?.isError) return renderToolError(result, "grep", theme, expanded);
192
+ const { content, report } = splitReport(result);
193
+ const payload = content[0];
194
+ return renderOutputPreview(
195
+ [
196
+ ...(payload?.type === "text" ? toDisplayLines(payload.text, theme) : []),
197
+ ...(report ? reportLines(report, theme) : []),
198
+ ],
199
+ expanded,
200
+ theme,
201
+ );
190
202
  },
191
203
 
192
204
  async execute(
193
- toolCallId: string,
205
+ _toolCallId: string,
194
206
  params: Static<GrepSchema>,
195
207
  signal: AbortSignal | undefined,
196
208
  _onUpdate: Parameters<GrepTool["execute"]>[3],
197
209
  ) {
198
- throwIfCancelled(signal);
199
- const anchors = createAnchorFormatter(hashLen);
200
- const warnings: string[] = [];
201
-
202
- const patterns = toArray(params.pattern);
203
- const effectiveLimit = params.limit ?? config.grep.defaultLimit;
204
- const context = params.context ?? config.grep.defaultContext;
205
- const rgPath = bundledRgPath;
206
- const outputMode: "content" | "files" | "count" = params.outputMode ?? "content";
207
- const multiline = params.multiline ?? false;
208
- const globs = toArray(params.glob);
209
- const { literal } = params;
210
- if (!literal) {
211
- await assertValidRegex(patterns, multiline, rgPath, backend, signal);
212
- const normalized = patterns.map(normalizeLineEndings);
213
- if (patterns.some((pattern, index) => pattern !== normalized[index]))
214
- await assertValidRegex(normalized, multiline, rgPath, backend, signal);
215
- }
216
- const matcherIgnoreCase = await backend.resolveIgnoreCase(
217
- rgPath,
218
- patterns,
219
- { literal, multiline },
220
- params.ignoreCase,
221
- signal,
222
- );
223
- const modes: SearchModes = { literal, ignoreCase: matcherIgnoreCase, multiline };
224
- const ctx = context;
225
- const { searchPaths, pathInfo } = await resolveSearchPaths(cwd, params.path);
226
- let scope: SearchScope = {
227
- globs,
228
- noIgnore: false,
229
- follow: false,
230
- searchPaths,
231
- };
232
-
233
- scope = {
234
- ...scope,
235
- searchPaths: await filterExplicitFilesByGlob(
210
+ const budget = budgets();
211
+ return runTool("grep", { path: params.path, signal, budget }, async () => {
212
+ throwIfCancelled(signal);
213
+ const warnings: string[] = [];
214
+ const patterns = toArray(params.pattern);
215
+ const effectiveLimit = params.limit ?? config.grep.defaultLimit;
216
+ const outputMode = params.outputMode ?? "content";
217
+ const { literal } = params;
218
+ const flags = new Set(params.flags ?? DEFAULT_GREP_FLAGS);
219
+ const ignoreCase =
220
+ params.ignoreCase ??
221
+ (flags.has("i") || smartIgnoreCase(patterns, literal, [...flags].join("")));
222
+ if (ignoreCase) flags.add("i");
223
+ else flags.delete("i");
224
+ const query = {
225
+ patterns,
226
+ literal,
227
+ flags: [...flags].join(""),
228
+ multiline: params.multiline ?? false,
229
+ };
230
+ const { searchPaths, pathInfo } = await resolveSearchPaths(cwd, params.path);
231
+ const unfiltered: SearchScope = {
232
+ globs: toArray(params.glob),
233
+ noIgnore: false,
234
+ follow: false,
235
+ searchPaths,
236
+ };
237
+ const scope: SearchScope = {
238
+ ...unfiltered,
239
+ searchPaths: await filterExplicitFilesByGlob(
240
+ backend,
241
+ bundledRgPath,
242
+ unfiltered,
243
+ pathInfo,
244
+ signal,
245
+ warnings,
246
+ ),
247
+ };
248
+ const search = await searchFiles({
236
249
  backend,
237
- rgPath,
250
+ rgPath: bundledRgPath,
238
251
  scope,
239
- pathInfo,
252
+ query,
253
+ limit: effectiveLimit,
254
+ timeoutMs: config.grep.regexTimeoutMs,
240
255
  signal,
241
256
  warnings,
242
- ),
243
- };
244
-
245
- const result =
246
- scope.searchPaths.length === 0
247
- ? { raw: [], matchLimitReached: false, snapshots: new Map<string, SearchFileSnapshot>() }
248
- : await searchMatches({
249
- backend,
250
- rgPath,
251
- scope,
252
- patterns,
253
- modes,
254
- limit: effectiveLimit,
255
- outputMode,
256
- signal,
257
- warnings,
258
- });
259
- const { raw, matchLimitReached } = result;
260
-
261
- if (raw.length === 0) {
262
- if (warnings.length)
263
- throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
264
- return {
265
- content: [{ type: "text" as const, text: "No matches found" }],
266
- details: undefined,
267
- };
268
- }
269
-
270
- const { blocks, linesTruncated } = await formatMatches({
271
- cwd,
272
- raw,
273
- outputMode,
274
- context: ctx,
275
- anchors,
276
- signal,
277
- warnings,
278
- searchSnapshots: result.snapshots,
279
- });
280
- const output = assembleGrepOutput({
281
- blocks,
282
- warnings,
283
- outputMode,
284
- matchLimitReached,
285
- effectiveLimit,
286
- linesTruncated,
257
+ });
258
+ const { payload, facts } = await grepOutput({
259
+ cwd,
260
+ search,
261
+ outputMode,
262
+ context: params.context ?? config.grep.defaultContext,
263
+ anchors: createAnchorFormatter(hashLen),
264
+ signal,
265
+ warnings,
266
+ effectiveLimit,
267
+ literalPipe: literal && patterns.some((pattern) => pattern.includes("|")),
268
+ budget,
269
+ });
270
+ return reportResult(
271
+ { tool: "grep" as const, path: params.path, ...facts },
272
+ payload === undefined ? [] : [{ type: "text" as const, text: payload }],
273
+ );
287
274
  });
288
- // Only content mode returns file text; paths and counts have nothing to forget.
289
- if (outputMode !== "content") return output;
290
- return withResultTag(toolCallId, output, config.forget, () =>
291
- grepReceipt(patterns, raw.length, new Set(raw.map((match) => match.filePath)).size, {
292
- limitReached: matchLimitReached,
293
- incomplete: warnings.length > 0,
294
- }),
295
- );
296
275
  },
297
276
  } satisfies GrepTool;
298
277
  }
@@ -0,0 +1,4 @@
1
+ import { createJiti } from "jiti";
2
+
3
+ // Installed packages need an explicit TypeScript loader in worker threads.
4
+ await createJiti(import.meta.url).import("./grep-worker.ts");
@@ -0,0 +1,14 @@
1
+ /** grep's regex worker: runs core/search on the requests of grep-search's pool. */
2
+ import { parentPort } from "node:worker_threads";
3
+ import { searchLines, searchText, type LineSearchInput, type SearchInput } from "../core/search.ts";
4
+ import { workerFailure } from "./report-cause.ts";
5
+
6
+ // Query syntax and options have already passed the tool entry point.
7
+ parentPort!.on("message", (input: SearchInput | LineSearchInput) => {
8
+ try {
9
+ const result = "lines" in input ? searchLines(input) : searchText(input);
10
+ parentPort!.postMessage({ result });
11
+ } catch (error) {
12
+ parentPort!.postMessage(workerFailure(error));
13
+ }
14
+ });