@criogaid/pi-hashline-edit 0.9.0 → 0.10.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 +9 -10
- package/README.zh-CN.md +8 -9
- package/THIRD_PARTY_NOTICES.md +0 -6
- package/package.json +1 -1
- package/src/core/AGENTS.md +4 -5
- package/src/core/apply.test.ts +96 -271
- package/src/core/apply.ts +62 -169
- package/src/core/case-fold.ts +8 -67
- package/src/core/character-set.ts +4 -4
- package/src/core/errors.test.ts +23 -7
- package/src/core/errors.ts +32 -5
- package/src/core/hash.test.ts +8 -16
- package/src/core/hash.ts +3 -23
- package/src/core/lines.ts +2 -4
- package/src/core/regex.ts +3 -4
- package/src/core/replace.test.ts +47 -1
- package/src/core/replace.ts +19 -13
- package/src/core/search-analysis.test.ts +24 -27
- package/src/core/search-analysis.ts +34 -65
- package/src/core/search-matrix.testing.ts +0 -2
- package/src/core/search.ts +1 -1
- package/src/core/text.test.ts +5 -5
- package/src/core/text.ts +5 -12
- package/src/core/types.ts +7 -43
- package/src/integration/fusion-dispatch.test.ts +2 -5
- package/src/integration/grep-flags.test.ts +0 -14
- package/src/integration/grep-js-completeness.test.ts +34 -8
- package/src/integration/grep-line-candidates.test.ts +4 -8
- package/src/integration/grep-matrix.test.ts +3 -7
- package/src/integration/grep-path-matrix.test.ts +5 -5
- package/src/integration/grep-prefilter-coverage.test.ts +3 -7
- package/src/integration/grep-process-limits.test.ts +78 -0
- package/src/integration/grep-rg.test.ts +118 -20
- package/src/integration/grep-scan-budget.test.ts +2 -2
- package/src/integration/grep-translation.test.ts +12 -27
- package/src/integration/large-text.test.ts +1 -47
- package/src/integration/model-budget-lifecycle.test.ts +2 -1
- package/src/integration/publication-read-changes.test.ts +123 -45
- package/src/integration/replace-worker-boundary.test.ts +21 -11
- package/src/integration/report-replay.test.ts +20 -22
- package/src/pi/AGENTS.md +15 -15
- package/src/pi/action-fusion.test.ts +164 -296
- package/src/pi/action-fusion.ts +148 -111
- package/src/pi/anchor-format.test.ts +9 -9
- package/src/pi/anchor-format.ts +6 -8
- package/src/pi/argument-diagnostics.ts +21 -25
- package/src/pi/argument-error.ts +2 -1
- package/src/pi/argument-validation.test.ts +129 -157
- package/src/pi/argument-validation.ts +5 -8
- package/src/pi/budgets.ts +5 -4
- package/src/pi/config.test.ts +5 -2
- package/src/pi/config.ts +4 -6
- package/src/pi/diagnostic-buffer.test.ts +12 -1
- package/src/pi/diagnostic-buffer.ts +1 -2
- package/src/pi/directory-sync.test.ts +0 -1
- package/src/pi/edit-tool.ts +46 -156
- package/src/pi/error-text.ts +4 -8
- package/src/pi/execute.test.ts +83 -196
- package/src/pi/failure-context.test.ts +144 -126
- package/src/pi/failure-context.ts +44 -93
- package/src/pi/failure-path.test.ts +168 -141
- package/src/pi/file-commit.test.ts +110 -53
- package/src/pi/file-commit.ts +90 -137
- package/src/pi/file-snapshot.test.ts +3 -5
- package/src/pi/fusion-card.test.ts +4 -1
- package/src/pi/fusion-card.ts +16 -24
- package/src/pi/grep-candidates.test.ts +2 -101
- package/src/pi/grep-candidates.ts +23 -69
- package/src/pi/grep-matrix.test.ts +2 -2
- package/src/pi/grep-order.test.ts +4 -4
- package/src/pi/grep-output.ts +62 -96
- package/src/pi/grep-render.ts +1 -1
- package/src/pi/grep-reread.ts +92 -0
- package/src/pi/grep-scope.ts +40 -42
- package/src/pi/grep-search.ts +22 -31
- package/src/pi/grep-tool.ts +55 -82
- package/src/pi/grep.test.ts +80 -45
- package/src/pi/model-budgets.test.ts +25 -23
- package/src/pi/model-budgets.ts +6 -38
- package/src/pi/mutation-result.test.ts +44 -35
- package/src/pi/mutation-result.ts +51 -20
- package/src/pi/mutation-runner.ts +126 -70
- package/src/pi/output-budgets.test.ts +36 -14
- package/src/pi/path.ts +1 -1
- package/src/pi/read-tool.ts +5 -5
- package/src/pi/regex-worker-contract.ts +3 -13
- package/src/pi/regex-worker.ts +1 -10
- package/src/pi/registration.test.ts +64 -36
- package/src/pi/render.test.ts +38 -28
- package/src/pi/render.ts +59 -63
- package/src/pi/replace-regex.ts +14 -2
- package/src/pi/replace-tool.ts +20 -82
- package/src/pi/replace-worker.ts +1 -1
- package/src/pi/replace.test.ts +9 -5
- package/src/pi/report-cause.ts +3 -8
- package/src/pi/report-failure.testing.ts +1 -2
- package/src/pi/report-schema.ts +62 -81
- package/src/pi/report.test.ts +171 -25
- package/src/pi/report.ts +33 -87
- package/src/pi/result-safety.test.ts +149 -176
- package/src/pi/rg-process.test.ts +77 -63
- package/src/pi/rg-process.ts +48 -64
- package/src/pi/rg-regex.ts +40 -400
- package/src/pi/schema.ts +12 -0
- package/src/pi/text-stream.test.ts +0 -21
- package/src/pi/text-stream.ts +14 -21
- package/src/pi/write-tool.ts +33 -62
- package/src/pi/write.test.ts +1 -3
- package/src/testing/regex-translation-corpus.ts +12 -12
- package/src/pi/replace-worker-contract.ts +0 -10
package/src/pi/grep-tool.ts
CHANGED
|
@@ -8,64 +8,44 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
11
|
-
import {
|
|
12
|
-
import { Type, type Static } from "typebox";
|
|
11
|
+
import { Type, type Static, type TLiteral } from "typebox";
|
|
13
12
|
import { Text } from "@earendil-works/pi-tui";
|
|
14
13
|
import { renderOutputPreview, renderToolError, reportLines, splitReport } from "./render.ts";
|
|
15
14
|
import { createAnchorFormatter } from "./anchor-format.ts";
|
|
16
|
-
import { grepOutput } from "./grep-output.ts";
|
|
17
|
-
import {
|
|
18
|
-
filterExplicitFilesByGlob,
|
|
19
|
-
toArray,
|
|
20
|
-
resolveSearchPaths,
|
|
21
|
-
type SearchScope,
|
|
22
|
-
} from "./grep-scope.ts";
|
|
15
|
+
import { GREP_OUTPUT_MODES, grepOutput, type GrepOutputMode } from "./grep-output.ts";
|
|
16
|
+
import { filterExplicitFilesByGlob, resolveSearchPaths } from "./grep-scope.ts";
|
|
23
17
|
import { searchFiles } from "./grep-search.ts";
|
|
24
18
|
import { toDisplayLines } from "./grep-render.ts";
|
|
25
19
|
import { runRgLines, runRgPaths, type GrepBackend } from "./rg-process.ts";
|
|
26
20
|
import { smartIgnoreCase } from "../core/search-analysis.ts";
|
|
27
21
|
import { checkRegexArguments } from "../core/regex.ts";
|
|
28
22
|
import { DEFAULT_GREP_FLAGS } from "../core/search.ts";
|
|
29
|
-
import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER } from "./schema.ts";
|
|
23
|
+
import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER, STRICT_SAMPLING } from "./schema.ts";
|
|
30
24
|
import { throwIfCancelled } from "./error-text.ts";
|
|
31
25
|
import { reportResult, runTool, type ReportDetails } from "./report.ts";
|
|
32
26
|
import type { HashlineEditConfig } from "./config.ts";
|
|
33
27
|
import { createArgumentPreparer, type ReportArgumentIssue } from "./argument-validation.ts";
|
|
34
28
|
import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
|
|
35
29
|
|
|
30
|
+
/** A list field: arrays only, because strict sampling cannot take a string-or-array union. */
|
|
31
|
+
const nonEmptyStrings = (description: string) =>
|
|
32
|
+
Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description });
|
|
33
|
+
|
|
36
34
|
/** Grep parameters; descriptions state the configured defaults. */
|
|
37
35
|
function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["grep"]) {
|
|
38
36
|
return Type.Object(
|
|
39
37
|
{
|
|
40
|
-
pattern:
|
|
41
|
-
|
|
42
|
-
{
|
|
43
|
-
description:
|
|
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.",
|
|
45
|
-
},
|
|
38
|
+
pattern: nonEmptyStrings(
|
|
39
|
+
"Patterns; a line matches if any of them matches. With literal true, | is an ordinary character, so give alternatives as separate items. Regex syntax is JavaScript, as in replace.",
|
|
46
40
|
),
|
|
47
41
|
path: Type.Optional(
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
Type.String({ minLength: 1 }),
|
|
51
|
-
Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
|
|
52
|
-
],
|
|
53
|
-
{
|
|
54
|
-
description:
|
|
55
|
-
"Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded.",
|
|
56
|
-
},
|
|
42
|
+
nonEmptyStrings(
|
|
43
|
+
"Existing files or directories; omit to search the working directory. Wildcards are not expanded.",
|
|
57
44
|
),
|
|
58
45
|
),
|
|
59
46
|
glob: Type.Optional(
|
|
60
|
-
|
|
61
|
-
[
|
|
62
|
-
Type.String({ minLength: 1 }),
|
|
63
|
-
Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
|
|
64
|
-
],
|
|
65
|
-
{
|
|
66
|
-
description:
|
|
67
|
-
"Filename wildcards go here, not in path: a glob or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
|
|
68
|
-
},
|
|
47
|
+
nonEmptyStrings(
|
|
48
|
+
"Filename wildcards go here, not in path: ordered globs; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
|
|
69
49
|
),
|
|
70
50
|
),
|
|
71
51
|
literal: Type.Boolean({
|
|
@@ -102,26 +82,39 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
|
|
|
102
82
|
}),
|
|
103
83
|
),
|
|
104
84
|
outputMode: Type.Optional(
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
85
|
+
// TypeBox infers a union's static type only from a tuple.
|
|
86
|
+
Type.Union(
|
|
87
|
+
GREP_OUTPUT_MODES.map((mode) => Type.Literal(mode)) as [
|
|
88
|
+
TLiteral<GrepOutputMode>,
|
|
89
|
+
...TLiteral<GrepOutputMode>[],
|
|
90
|
+
],
|
|
91
|
+
{
|
|
92
|
+
description:
|
|
93
|
+
'"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.',
|
|
94
|
+
},
|
|
95
|
+
),
|
|
109
96
|
),
|
|
110
97
|
},
|
|
111
98
|
{ additionalProperties: false },
|
|
112
99
|
);
|
|
113
100
|
}
|
|
114
101
|
type GrepSchema = ReturnType<typeof createGrepSchema>;
|
|
115
|
-
/** How grep presents matches; grep-output formats each mode. */
|
|
116
|
-
export type GrepOutputMode = NonNullable<Static<GrepSchema>["outputMode"]>;
|
|
117
102
|
type GrepTool = ToolDefinition<GrepSchema, Partial<ReportDetails> | undefined>;
|
|
103
|
+
/** A list field as the call header sees it: streamed before Pi wraps a lone string. */
|
|
104
|
+
function streamedList(value: string | readonly string[] | null | undefined): readonly string[] {
|
|
105
|
+
return value == null ? [] : typeof value === "string" ? [value] : value;
|
|
106
|
+
}
|
|
107
|
+
|
|
118
108
|
/** Validate JavaScript syntax once; the search never rejects a pattern V8 accepts. */
|
|
119
109
|
function checkGrepArguments(args: unknown, report: ReportArgumentIssue): void {
|
|
120
110
|
const { pattern, literal, flags } = (args ?? {}) as Record<string, unknown>;
|
|
121
|
-
if (
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
111
|
+
if (
|
|
112
|
+
!Array.isArray(pattern) ||
|
|
113
|
+
typeof literal !== "boolean" ||
|
|
114
|
+
(flags !== undefined && typeof flags !== "string")
|
|
115
|
+
)
|
|
116
|
+
return;
|
|
117
|
+
const fields = pattern.map((value, index) => [`pattern[${index}]`, value] as const);
|
|
125
118
|
checkRegexArguments("flags", flags ?? DEFAULT_GREP_FLAGS, literal, fields, report);
|
|
126
119
|
}
|
|
127
120
|
|
|
@@ -149,7 +142,7 @@ export function makeGrepOverrideWithBackend(
|
|
|
149
142
|
name: "grep" as const,
|
|
150
143
|
label: "grep",
|
|
151
144
|
description:
|
|
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
|
|
145
|
+
"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, even beneath a directory named in path; to search an ignored file or one of those directories, name it itself in path. Use grep instead of rg or grep in a shell to search files; use the shell only to filter another command's output.",
|
|
153
146
|
promptSnippet: "Search file contents",
|
|
154
147
|
promptGuidelines: [
|
|
155
148
|
"When you need several independent searches, send them as separate grep calls in one response; they run in parallel.",
|
|
@@ -157,6 +150,7 @@ export function makeGrepOverrideWithBackend(
|
|
|
157
150
|
],
|
|
158
151
|
parameters: grepSchema,
|
|
159
152
|
prepareArguments: createArgumentPreparer("grep", grepSchema, checkGrepArguments, budgets),
|
|
153
|
+
constrainedSampling: STRICT_SAMPLING,
|
|
160
154
|
|
|
161
155
|
renderShell: "default" as const,
|
|
162
156
|
|
|
@@ -164,20 +158,17 @@ export function makeGrepOverrideWithBackend(
|
|
|
164
158
|
args: Static<GrepSchema>,
|
|
165
159
|
theme: Parameters<NonNullable<GrepTool["renderCall"]>>[1],
|
|
166
160
|
) {
|
|
167
|
-
const
|
|
168
|
-
const
|
|
169
|
-
? rawPattern.join(" | ")
|
|
170
|
-
: String(rawPattern ?? "");
|
|
171
|
-
const rawPath = args?.path;
|
|
172
|
-
const pathText = Array.isArray(rawPath) ? rawPath.join(" ") : String(rawPath ?? ".");
|
|
161
|
+
const paths = streamedList(args?.path);
|
|
162
|
+
const globs = streamedList(args?.glob);
|
|
173
163
|
let text =
|
|
174
164
|
theme.fg("toolTitle", theme.bold("grep ")) +
|
|
175
|
-
theme.fg("accent", `/${
|
|
176
|
-
theme.fg("toolOutput", ` in ${
|
|
177
|
-
if (
|
|
165
|
+
theme.fg("accent", `/${streamedList(args?.pattern).join(" | ")}/${args?.flags ?? ""}`) +
|
|
166
|
+
theme.fg("toolOutput", ` in ${paths.length ? paths.join(" ") : "."}`);
|
|
167
|
+
if (globs.length) text += theme.fg("toolOutput", ` (${globs.join(", ")})`);
|
|
178
168
|
if (args?.outputMode && args.outputMode !== "content")
|
|
179
169
|
text += theme.fg("success", ` → ${args.outputMode}`);
|
|
180
|
-
|
|
170
|
+
// Strict sampling streams unused optional fields as null.
|
|
171
|
+
if (args?.limit != null) text += theme.fg("toolOutput", ` limit ${args.limit}`);
|
|
181
172
|
return new Text(text, 0, 0);
|
|
182
173
|
},
|
|
183
174
|
|
|
@@ -188,7 +179,7 @@ export function makeGrepOverrideWithBackend(
|
|
|
188
179
|
context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
|
|
189
180
|
) {
|
|
190
181
|
if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
|
|
191
|
-
if (context
|
|
182
|
+
if (context.isError) return renderToolError(result, "grep", theme, expanded);
|
|
192
183
|
const { content, report } = splitReport(result);
|
|
193
184
|
const payload = content[0];
|
|
194
185
|
return renderOutputPreview(
|
|
@@ -205,13 +196,11 @@ export function makeGrepOverrideWithBackend(
|
|
|
205
196
|
_toolCallId: string,
|
|
206
197
|
params: Static<GrepSchema>,
|
|
207
198
|
signal: AbortSignal | undefined,
|
|
208
|
-
_onUpdate: Parameters<GrepTool["execute"]>[3],
|
|
209
199
|
) {
|
|
210
200
|
const budget = budgets();
|
|
211
201
|
return runTool("grep", { path: params.path, signal, budget }, async () => {
|
|
212
202
|
throwIfCancelled(signal);
|
|
213
|
-
const
|
|
214
|
-
const patterns = toArray(params.pattern);
|
|
203
|
+
const patterns = params.pattern;
|
|
215
204
|
const effectiveLimit = params.limit ?? config.grep.defaultLimit;
|
|
216
205
|
const outputMode = params.outputMode ?? "content";
|
|
217
206
|
const { literal } = params;
|
|
@@ -227,33 +216,16 @@ export function makeGrepOverrideWithBackend(
|
|
|
227
216
|
flags: [...flags].join(""),
|
|
228
217
|
multiline: params.multiline ?? false,
|
|
229
218
|
};
|
|
230
|
-
const
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
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({
|
|
219
|
+
const globs = params.glob ?? [];
|
|
220
|
+
const paths = await resolveSearchPaths(cwd, params.path);
|
|
221
|
+
const admitted = await filterExplicitFilesByGlob(backend, globs, paths, signal);
|
|
222
|
+
const { warnings: searchWarnings, ...search } = await searchFiles({
|
|
249
223
|
backend,
|
|
250
|
-
|
|
251
|
-
scope,
|
|
224
|
+
scope: { globs, searchPaths: admitted.searchPaths },
|
|
252
225
|
query,
|
|
253
226
|
limit: effectiveLimit,
|
|
254
227
|
timeoutMs: config.grep.regexTimeoutMs,
|
|
255
228
|
signal,
|
|
256
|
-
warnings,
|
|
257
229
|
});
|
|
258
230
|
const { payload, facts } = await grepOutput({
|
|
259
231
|
cwd,
|
|
@@ -262,7 +234,8 @@ export function makeGrepOverrideWithBackend(
|
|
|
262
234
|
context: params.context ?? config.grep.defaultContext,
|
|
263
235
|
anchors: createAnchorFormatter(hashLen),
|
|
264
236
|
signal,
|
|
265
|
-
warnings
|
|
237
|
+
// Each stage returns its warnings in order; the report states them in stage order.
|
|
238
|
+
warnings: [...admitted.warnings, ...searchWarnings],
|
|
266
239
|
effectiveLimit,
|
|
267
240
|
literalPipe: literal && patterns.some((pattern) => pattern.includes("|")),
|
|
268
241
|
budget,
|
package/src/pi/grep.test.ts
CHANGED
|
@@ -11,7 +11,6 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
|
11
11
|
import fsPromises from "node:fs/promises";
|
|
12
12
|
import { tmpdir } from "node:os";
|
|
13
13
|
import { join } from "node:path";
|
|
14
|
-
import { rgPath } from "@vscode/ripgrep";
|
|
15
14
|
import { initTheme } from "@earendil-works/pi-coding-agent";
|
|
16
15
|
import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
|
|
17
16
|
import { computeLineHash } from "../core/hash.ts";
|
|
@@ -51,14 +50,13 @@ async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
|
|
|
51
50
|
}
|
|
52
51
|
|
|
53
52
|
function fakeBackend(options: FakeOptions = {}) {
|
|
54
|
-
const calls: { kind: "paths" | "lines";
|
|
53
|
+
const calls: { kind: "paths" | "lines"; args: readonly string[] }[] = [];
|
|
55
54
|
const run = async (
|
|
56
55
|
kind: "paths" | "lines",
|
|
57
|
-
path: string,
|
|
58
56
|
args: readonly string[],
|
|
59
57
|
onPath: (file: string) => boolean | Promise<boolean>,
|
|
60
58
|
) => {
|
|
61
|
-
calls.push({ kind,
|
|
59
|
+
calls.push({ kind, args });
|
|
62
60
|
await options.onRun?.();
|
|
63
61
|
if (options.error) throw options.error;
|
|
64
62
|
for (const file of options.paths ?? []) {
|
|
@@ -71,9 +69,9 @@ function fakeBackend(options: FakeOptions = {}) {
|
|
|
71
69
|
};
|
|
72
70
|
};
|
|
73
71
|
const backend: GrepBackend = {
|
|
74
|
-
runRgPaths: (
|
|
75
|
-
runRgLines: (
|
|
76
|
-
run("lines",
|
|
72
|
+
runRgPaths: (args, _signal, onPath) => run("paths", args, onPath),
|
|
73
|
+
runRgLines: (args, _signal, _maxLines, onFile) =>
|
|
74
|
+
run("lines", args, (file) => onFile(file, options.lines)),
|
|
77
75
|
};
|
|
78
76
|
return { backend, calls };
|
|
79
77
|
}
|
|
@@ -86,13 +84,33 @@ test("explicit JavaScript flags → call rendering shows them", () => {
|
|
|
86
84
|
initTheme("dark");
|
|
87
85
|
const { backend } = fakeBackend();
|
|
88
86
|
const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, backend);
|
|
89
|
-
const rendered = tool.renderCall!(
|
|
87
|
+
const rendered = tool.renderCall!(
|
|
88
|
+
{ pattern: ["\\p{Letter}+"], literal: false, flags: "u" },
|
|
89
|
+
theme,
|
|
90
|
+
)
|
|
90
91
|
.render(120)
|
|
91
92
|
.join("\n");
|
|
92
93
|
assert.ok(rendered.includes("/\\p{Letter}+/u"));
|
|
93
94
|
});
|
|
94
95
|
|
|
95
|
-
test("
|
|
96
|
+
test("streamed grep strings and null fields → render the pattern and default path without a limit", () => {
|
|
97
|
+
initTheme("dark");
|
|
98
|
+
const { backend } = fakeBackend();
|
|
99
|
+
const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, backend);
|
|
100
|
+
for (const pattern of ["needle", null]) {
|
|
101
|
+
const args: unknown = { pattern, literal: true, path: null, limit: null };
|
|
102
|
+
const rendered = tool
|
|
103
|
+
// Streaming arguments reach the renderer before Pi validates and coerces them.
|
|
104
|
+
.renderCall(args as Parameters<typeof tool.renderCall>[0], theme)
|
|
105
|
+
.render(120)
|
|
106
|
+
.join("\n");
|
|
107
|
+
assert.ok(rendered.includes(`/${pattern ?? ""}/`));
|
|
108
|
+
assert.ok(rendered.includes("in ."));
|
|
109
|
+
assert.doesNotMatch(rendered, /limit/);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("configured defaults → descriptions, limits, and context use registered values", async () =>
|
|
96
114
|
withDir(async (dir) => {
|
|
97
115
|
const file = join(dir, "configured.txt");
|
|
98
116
|
const lines = [
|
|
@@ -192,7 +210,7 @@ test("grep points wildcard paths to glob without changing ordinary missing-path
|
|
|
192
210
|
call(tool, { literal: true, pattern: "value", path: "src/fusion-card*" }),
|
|
193
211
|
"PATH_NOT_FOUND",
|
|
194
212
|
(report) => {
|
|
195
|
-
assert.
|
|
213
|
+
assert.deepEqual(report.path, ["src/fusion-card*"]);
|
|
196
214
|
assert.match(report.next ?? "", /directory.*path.*wildcard.*glob/);
|
|
197
215
|
},
|
|
198
216
|
);
|
|
@@ -200,33 +218,43 @@ test("grep points wildcard paths to glob without changing ordinary missing-path
|
|
|
200
218
|
call(tool, { literal: true, pattern: "value", path: "src/missing" }),
|
|
201
219
|
"PATH_NOT_FOUND",
|
|
202
220
|
(report) => {
|
|
203
|
-
assert.
|
|
221
|
+
assert.deepEqual(report.path, ["src/missing"]);
|
|
204
222
|
assert.equal(report.next, "Check the path.");
|
|
205
223
|
},
|
|
206
224
|
);
|
|
207
225
|
});
|
|
208
226
|
});
|
|
209
227
|
|
|
210
|
-
test("
|
|
228
|
+
test("multiple grep paths are missing → reports all resolved paths and selects wildcard recovery", async () =>
|
|
211
229
|
withDir(async (dir) => {
|
|
212
230
|
await writeFile(join(dir, "present.txt"), "value\n");
|
|
213
|
-
const path
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
231
|
+
for (const [path, missing, wildcard] of [
|
|
232
|
+
[["missing.txt", "present.txt", "other.txt"], ["missing.txt", "other.txt"], false],
|
|
233
|
+
[["missing.txt", "present.txt", "other*.txt"], ["missing.txt", "other*.txt"], true],
|
|
234
|
+
[["missing?.txt", "present.txt", "other.txt"], ["missing?.txt", "other.txt"], true],
|
|
235
|
+
] as const) {
|
|
236
|
+
const fake = fakeBackend();
|
|
237
|
+
const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
|
|
238
|
+
const result = await call(tool, { literal: true, pattern: "value", path });
|
|
239
|
+
assert.equal(result.isError, true);
|
|
240
|
+
const block = result.content[0];
|
|
241
|
+
assert.ok(block.type === "text");
|
|
242
|
+
const facts = JSON.parse(block.text);
|
|
243
|
+
assert.equal(facts.error, "PATH_NOT_FOUND");
|
|
244
|
+
assert.deepEqual(
|
|
245
|
+
facts.missing,
|
|
246
|
+
missing.map((item) => join(dir, item)),
|
|
247
|
+
);
|
|
248
|
+
if (wildcard) assert.match(facts.next, /directory.*path.*wildcard.*glob/);
|
|
249
|
+
else assert.equal(facts.next, "Check the path.");
|
|
250
|
+
assert.equal(Object.hasOwn(facts, "tool"), false);
|
|
251
|
+
assert.equal(Object.hasOwn(facts, "path"), false);
|
|
252
|
+
const report = reportOf(result, "grep");
|
|
253
|
+
assert.equal(report?.tool, "grep");
|
|
254
|
+
assert.deepEqual(report?.path, path);
|
|
255
|
+
assert.deepEqual(report?.missing, facts.missing);
|
|
256
|
+
assert.equal(fake.calls.length, 0);
|
|
257
|
+
}
|
|
230
258
|
}));
|
|
231
259
|
|
|
232
260
|
test("matched files → full-line hash anchors", async () => {
|
|
@@ -245,7 +273,6 @@ test("matched files → full-line hash anchors", async () => {
|
|
|
245
273
|
assert.match(output, /b\.ts · 1 match/);
|
|
246
274
|
assert.match(output, new RegExp(`1#${computeLineHash(1, "alpha beta", 4)}│alpha beta`));
|
|
247
275
|
assert.match(output, /3#[0-9A-Z]+│alpha only/);
|
|
248
|
-
assert.equal(fake.calls[0].path, rgPath);
|
|
249
276
|
});
|
|
250
277
|
});
|
|
251
278
|
|
|
@@ -494,7 +521,7 @@ test("candidate selection → reports only whole-file candidate facts", async ()
|
|
|
494
521
|
withDir(async (dir) => {
|
|
495
522
|
const file = join(dir, "input.txt");
|
|
496
523
|
await writeFile(file, "abc \nneedle");
|
|
497
|
-
for (const [pattern, multiline,
|
|
524
|
+
for (const [pattern, multiline, scanned] of [
|
|
498
525
|
["needle", false, undefined],
|
|
499
526
|
["needle", true, "files"],
|
|
500
527
|
["[^x\\s]{3}\\s", true, "all"],
|
|
@@ -511,7 +538,7 @@ test("candidate selection → reports only whole-file candidate facts", async ()
|
|
|
511
538
|
);
|
|
512
539
|
assert.equal(result.isError, undefined);
|
|
513
540
|
assert.equal(grepCounts(result).matches, 1);
|
|
514
|
-
assert.equal(reportOf(result, "grep")?.
|
|
541
|
+
assert.equal(reportOf(result, "grep")?.scanned, scanned);
|
|
515
542
|
assert.equal(reportOf(result, "grep")?.scanLimit, undefined);
|
|
516
543
|
assert.equal(fake.calls[0].kind, multiline ? "paths" : "lines");
|
|
517
544
|
}
|
|
@@ -625,7 +652,7 @@ for (const diagnosticLineCount of [0, 80]) {
|
|
|
625
652
|
].join("\n");
|
|
626
653
|
const fake = fakeBackend({ code: 2, stderr: diagnostic });
|
|
627
654
|
const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, fake.backend);
|
|
628
|
-
const args = { pattern: "(?<=a+)b", literal: false };
|
|
655
|
+
const args = { pattern: ["(?<=a+)b"], literal: false };
|
|
629
656
|
const failure: Awaited<ReturnType<typeof tool.execute>> = await callTool(tool, args);
|
|
630
657
|
assert.equal(failure.isError, true);
|
|
631
658
|
const errorText = failure.content
|
|
@@ -766,7 +793,7 @@ test("literal pipe patterns find no match → alternatives recovery preserves li
|
|
|
766
793
|
if (literalPipe) {
|
|
767
794
|
assert.match(
|
|
768
795
|
report.next ?? "",
|
|
769
|
-
/if you meant alternatives.*pattern
|
|
796
|
+
/if you meant alternatives.*each as its own pattern item.*otherwise.*literal matching/i,
|
|
770
797
|
context,
|
|
771
798
|
);
|
|
772
799
|
} else {
|
|
@@ -777,17 +804,25 @@ test("literal pipe patterns find no match → alternatives recovery preserves li
|
|
|
777
804
|
|
|
778
805
|
test("invalid JavaScript → its field rejects before file discovery", async () =>
|
|
779
806
|
withDir(async (dir) => {
|
|
780
|
-
for (const
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
807
|
+
for (const [pattern, flags, field] of [
|
|
808
|
+
["(", undefined, "pattern[0]"],
|
|
809
|
+
[["plain", "("], undefined, "pattern[1]"],
|
|
810
|
+
["(?m)^foo", undefined, "pattern[0]"],
|
|
811
|
+
[["plain", "(?m)^foo"], undefined, "pattern[1]"],
|
|
812
|
+
["(?i)abc", undefined, "pattern[0]"],
|
|
813
|
+
[["plain", "(?i)abc"], undefined, "pattern[1]"],
|
|
814
|
+
["\\p{NotAProperty}", "u", "pattern[0]"],
|
|
815
|
+
["queueTool(", undefined, "pattern[0]"],
|
|
816
|
+
[["queueTool(", "\\bfoo\\b"], undefined, "pattern[0]"],
|
|
817
|
+
["*", undefined, "pattern[0]"],
|
|
818
|
+
] as const) {
|
|
819
|
+
const fake = fakeBackend();
|
|
820
|
+
const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
|
|
821
|
+
await assert.rejects(
|
|
822
|
+
call(tool, { path: "missing.txt", pattern, literal: false, flags }),
|
|
823
|
+
rejectsArgument(field, /Invalid regular expression/),
|
|
824
|
+
);
|
|
825
|
+
assert.equal(fake.calls.length, 0);
|
|
791
826
|
}
|
|
792
827
|
}));
|
|
793
828
|
|
|
@@ -1,32 +1,34 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { test } from "node:test";
|
|
3
3
|
import { DEFAULT_OUTPUT_BUDGETS, MAX_CONTENT_KIB, outputBudgetsFor } from "./budgets.ts";
|
|
4
|
-
import {
|
|
4
|
+
import { openTestSession } from "../testing/session.testing.ts";
|
|
5
|
+
import { registerModelBudgets } from "./model-budgets.ts";
|
|
5
6
|
|
|
6
|
-
test("
|
|
7
|
-
let
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
7
|
+
test("session start and model selection → budgets follow the live model", async (t) => {
|
|
8
|
+
let get: ReturnType<typeof registerModelBudgets> | undefined;
|
|
9
|
+
const { session, model } = await openTestSession(t, {
|
|
10
|
+
tools: [],
|
|
11
|
+
configure(pi) {
|
|
12
|
+
get = registerModelBudgets(pi);
|
|
13
|
+
assert.deepEqual(get(), DEFAULT_OUTPUT_BUDGETS);
|
|
14
|
+
},
|
|
12
15
|
});
|
|
13
|
-
assert.
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
assert.
|
|
19
|
-
|
|
16
|
+
assert.ok(get);
|
|
17
|
+
assert.deepEqual(get(), outputBudgetsFor(model.contextWindow));
|
|
18
|
+
const selected = { ...model, id: "small", contextWindow: 65_536 };
|
|
19
|
+
await session.setModel(selected);
|
|
20
|
+
const small = get();
|
|
21
|
+
assert.ok(Object.isFrozen(small));
|
|
22
|
+
assert.deepEqual(small, outputBudgetsFor(selected.contextWindow));
|
|
23
|
+
selected.contextWindow = 1_048_576;
|
|
20
24
|
const large = get();
|
|
21
|
-
assert.
|
|
22
|
-
assert.ok(large.readBytes >
|
|
23
|
-
assert.ok(large.blockBytes >
|
|
24
|
-
assert.ok(large.fieldBytes >
|
|
25
|
-
assert.ok(large.grepPreviewUnits >
|
|
26
|
-
|
|
27
|
-
assert.
|
|
28
|
-
model = { ...model, contextWindow: 65_536 };
|
|
29
|
-
assert.equal(get().readBytes, first.readBytes);
|
|
25
|
+
assert.deepEqual(large, outputBudgetsFor(selected.contextWindow));
|
|
26
|
+
assert.ok(large.readBytes > small.readBytes);
|
|
27
|
+
assert.ok(large.blockBytes > small.blockBytes);
|
|
28
|
+
assert.ok(large.fieldBytes > small.fieldBytes);
|
|
29
|
+
assert.ok(large.grepPreviewUnits > small.grepPreviewUnits);
|
|
30
|
+
await session.setModel({ ...model, id: "small-again", contextWindow: 65_536 });
|
|
31
|
+
assert.deepEqual(get(), small);
|
|
30
32
|
});
|
|
31
33
|
|
|
32
34
|
test("unknown or invalid model capacity → bounded defaults are used", () => {
|
package/src/pi/model-budgets.ts
CHANGED
|
@@ -1,44 +1,12 @@
|
|
|
1
|
-
/** Per-extension
|
|
1
|
+
/** Per-extension budgets. Tool preparation and execution share the same provider. */
|
|
2
2
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import { outputBudgetsFor, type OutputBudgetProvider
|
|
3
|
+
import { outputBudgetsFor, type OutputBudgetProvider } from "./budgets.ts";
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
NonNullable<ExtensionContext["model"]>,
|
|
7
|
-
"provider" | "id" | "contextWindow"
|
|
8
|
-
>;
|
|
9
|
-
|
|
10
|
-
/** Reuse the snapshot until selection or its declared capacity changes. No provider request is made. */
|
|
11
|
-
export function createOutputBudgetProvider(
|
|
12
|
-
readModel: () => BudgetModel | undefined,
|
|
13
|
-
): OutputBudgetProvider {
|
|
14
|
-
let provider: string | undefined;
|
|
15
|
-
let id: string | undefined;
|
|
16
|
-
let contextWindow: number | undefined;
|
|
17
|
-
let cached: OutputBudgets | undefined;
|
|
18
|
-
return () => {
|
|
19
|
-
const model = readModel();
|
|
20
|
-
if (
|
|
21
|
-
cached === undefined ||
|
|
22
|
-
provider !== model?.provider ||
|
|
23
|
-
id !== model?.id ||
|
|
24
|
-
!Object.is(contextWindow, model?.contextWindow)
|
|
25
|
-
) {
|
|
26
|
-
provider = model?.provider;
|
|
27
|
-
id = model?.id;
|
|
28
|
-
contextWindow = model?.contextWindow;
|
|
29
|
-
cached = outputBudgetsFor(contextWindow);
|
|
30
|
-
}
|
|
31
|
-
return cached;
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** Retain Pi's live context getter, including after session restore, without calculating on events. */
|
|
5
|
+
/** Retain Pi's context once per session: its model getter stays live, so no event recalculates. */
|
|
36
6
|
export function registerModelBudgets(pi: ExtensionAPI): OutputBudgetProvider {
|
|
37
7
|
let context: ExtensionContext | undefined;
|
|
38
|
-
|
|
8
|
+
pi.on("session_start", (_event, ctx) => {
|
|
39
9
|
context = ctx;
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
pi.on("model_select", bind);
|
|
43
|
-
return createOutputBudgetProvider(() => context?.model);
|
|
10
|
+
});
|
|
11
|
+
return () => outputBudgetsFor(context?.model?.contextWindow);
|
|
44
12
|
}
|