@floydous/pi-agent-kernel 0.4.3 → 0.6.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/AGENT_KERNEL_SYS_PROMPT.md +15 -12
- package/CHANGELOG.md +87 -0
- package/README.md +6 -54
- package/config.example.toml +1 -8
- package/docs/README.md +1 -2
- package/docs/architecture.md +2 -3
- package/docs/configuration.md +11 -10
- package/docs/editing-and-verification.md +21 -8
- package/docs/podman-linux-checks.md +24 -0
- package/docs/release-discipline.md +10 -0
- package/docs/retrieval.md +21 -23
- package/docs/testing.md +3 -3
- package/grammars/tree-sitter-html.wasm +0 -0
- package/package.json +5 -3
- package/src/config/agent_kernel_command.ts +60 -625
- package/src/config/kernel_config.ts +53 -69
- package/src/config/toml.ts +6 -1
- package/src/editing/auto_heal.ts +1 -1
- package/src/editing/patch.ts +75 -37
- package/src/editing/post_edit_verification.ts +20 -14
- package/src/editing/smart_anchor.ts +9 -6
- package/src/editing/syntax-verify.ts +79 -222
- package/src/index.ts +36 -453
- package/src/retrieval/html_chunker.ts +526 -0
- package/src/retrieval/search_bm25.ts +39 -28
- package/src/retrieval/search_chunker.ts +69 -7
- package/src/retrieval/search_config.ts +21 -40
- package/src/retrieval/search_embedder.ts +14 -31
- package/src/retrieval/search_index.ts +338 -129
- package/src/retrieval/search_modal.ts +1208 -222
- package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
- package/src/retrieval/tree_sitter_engine.ts +171 -36
- package/src/retrieval/workspace_walker.ts +78 -2
- package/src/safety/atomic_write.ts +1 -1
- package/src/safety/epistemic_guard.ts +105 -31
- package/src/safety/host_environment.ts +180 -0
- package/src/safety/output_clamper.ts +97 -27
- package/src/tools/code_search_output.ts +11 -2
- package/src/tools/code_search_tool.ts +25 -13
- package/src/tools/context.ts +11 -10
- package/src/tools/edit_tool.ts +243 -154
- package/src/tools/read_tool.ts +285 -214
- package/src/tools/stream_reader.ts +206 -0
- package/src/ui/footer.ts +7 -7
- package/docs/lsp.md +0 -31
- package/src/lsp/adapters/base.ts +0 -42
- package/src/lsp/adapters/index.ts +0 -21
- package/src/lsp/adapters/python.ts +0 -37
- package/src/lsp/adapters/rust.ts +0 -35
- package/src/lsp/adapters/typescript.ts +0 -40
- package/src/lsp/index.ts +0 -13
- package/src/lsp/lsp_client.ts +0 -765
- package/src/lsp/lsp_detector.ts +0 -52
- package/src/lsp/lsp_formatter.ts +0 -323
- package/src/lsp/lsp_installer.ts +0 -320
- package/src/lsp/lsp_manager.ts +0 -202
- package/src/lsp/lsp_modal.ts +0 -675
- package/src/lsp/lsp_registry.ts +0 -600
- package/src/lsp/lsp_types.ts +0 -143
- package/src/retrieval/ast_search.ts +0 -999
- package/src/retrieval/symbol_reader.ts +0 -228
- package/src/tools/ast_search_formatter.ts +0 -161
- package/src/tools/ast_search_tool.ts +0 -146
- package/src/tools/lsp_tool.ts +0 -794
- package/src/tools/repo_map_tool.ts +0 -56
package/src/tools/edit_tool.ts
CHANGED
|
@@ -3,12 +3,10 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { Text, makeOutputText } from "../ui/tui_utils";
|
|
4
4
|
import * as path from "node:path";
|
|
5
5
|
import * as fs from "node:fs";
|
|
6
|
-
import { kernelDebug } from "../safety/kernel_debug";
|
|
7
6
|
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
8
7
|
import {
|
|
9
8
|
applySurgicalPatch,
|
|
10
9
|
applyMultiBlockPatch,
|
|
11
|
-
findSurgicalPatchTargetRange,
|
|
12
10
|
preflightSurgicalPatchBlock,
|
|
13
11
|
} from "../editing/patch";
|
|
14
12
|
import {
|
|
@@ -22,13 +20,13 @@ import {
|
|
|
22
20
|
renderPostEditVerification,
|
|
23
21
|
verifyEditedFile,
|
|
24
22
|
} from "../editing/post_edit_verification";
|
|
25
|
-
import { LspManager } from "../lsp";
|
|
26
23
|
import {
|
|
27
24
|
globalEpistemicGuard,
|
|
28
25
|
resolveUserPath,
|
|
29
26
|
} from "../safety/epistemic_guard";
|
|
30
27
|
import { loadKernelConfig } from "../config";
|
|
31
|
-
import type
|
|
28
|
+
import { markReturnedErrors, type SessionDeps } from "./context";
|
|
29
|
+
import { TreeSitterEngine } from "../retrieval/tree_sitter_engine";
|
|
32
30
|
|
|
33
31
|
function mutationLockKey(filePath: string): string {
|
|
34
32
|
const resolved = path.resolve(filePath);
|
|
@@ -40,7 +38,7 @@ export async function withFileMutationLocks<T>(
|
|
|
40
38
|
operation: () => Promise<T>,
|
|
41
39
|
): Promise<T> {
|
|
42
40
|
const { withFileMutationQueue } = await import("@earendil-works/pi-coding-agent");
|
|
43
|
-
const keys = [...new Set(filePaths.map(mutationLockKey))].sort();
|
|
41
|
+
const keys = [...new Set(filePaths.map(mutationLockKey))].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
44
42
|
const run = (index: number): Promise<T> =>
|
|
45
43
|
index >= keys.length
|
|
46
44
|
? operation()
|
|
@@ -78,21 +76,44 @@ function preflightFileEdit(
|
|
|
78
76
|
return { error: `[EDIT FAILED] File not found: '${item.path}'.` };
|
|
79
77
|
}
|
|
80
78
|
|
|
79
|
+
const config = deps.getConfig?.(ctx.cwd) ?? loadKernelConfig(ctx.cwd);
|
|
80
|
+
const shouldNormalizeDots = config?.editing?.normalize_fullwidth_dots !== false;
|
|
81
|
+
|
|
81
82
|
let edits = item.edits;
|
|
82
83
|
if (Array.isArray(edits)) {
|
|
83
84
|
edits = edits.map((e: any) => {
|
|
84
85
|
if (!e || typeof e !== "object") return e;
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
86
|
+
let search = e.search ?? e.oldText ?? e.old_text ?? e.old;
|
|
87
|
+
let rawReplace = e.replace === null ? "" : (e.replace ?? e.replacement ?? e.newText ?? e.new_text ?? e.new);
|
|
88
|
+
if (rawReplace === null) {
|
|
89
|
+
rawReplace = "";
|
|
90
|
+
}
|
|
91
|
+
let replace = rawReplace;
|
|
92
|
+
let lines = e.lines;
|
|
93
|
+
if (shouldNormalizeDots) {
|
|
94
|
+
if (typeof search === "string" && search.includes("\uff0e")) search = search.replace(/\uff0e/g, ".");
|
|
95
|
+
if (typeof replace === "string" && replace.includes("\uff0e")) replace = replace.replace(/\uff0e/g, ".");
|
|
96
|
+
if (Array.isArray(lines)) lines = lines.map((l: any) => typeof l === "string" ? l.replace(/\uff0e/g, ".") : l);
|
|
97
|
+
}
|
|
98
|
+
return { ...e, search, replace, ...(lines !== undefined ? { lines } : {}) };
|
|
88
99
|
});
|
|
89
100
|
}
|
|
90
|
-
|
|
91
|
-
|
|
101
|
+
let singleSearch = item.search ?? item.oldText ?? item.old_text ?? item.old;
|
|
102
|
+
let rawSingleReplace = item.replace === null ? "" : (item.replace ?? item.replacement ?? item.newText ?? item.new_text ?? item.new);
|
|
103
|
+
if (rawSingleReplace === null) {
|
|
104
|
+
rawSingleReplace = "";
|
|
105
|
+
}
|
|
106
|
+
let singleReplace = rawSingleReplace;
|
|
107
|
+
let singleLines = Array.isArray(item.lines) ? [...item.lines] : item.lines;
|
|
108
|
+
if (shouldNormalizeDots) {
|
|
109
|
+
if (typeof singleSearch === "string" && singleSearch.includes("\uff0e")) singleSearch = singleSearch.replace(/\uff0e/g, ".");
|
|
110
|
+
if (typeof singleReplace === "string" && singleReplace.includes("\uff0e")) singleReplace = singleReplace.replace(/\uff0e/g, ".");
|
|
111
|
+
if (Array.isArray(singleLines)) singleLines = singleLines.map((l: any) => typeof l === "string" ? l.replace(/\uff0e/g, ".") : l);
|
|
112
|
+
}
|
|
92
113
|
|
|
93
114
|
const hasSingleAnchor =
|
|
94
115
|
(item.pos !== undefined || item.start_line !== undefined) &&
|
|
95
|
-
Array.isArray(
|
|
116
|
+
Array.isArray(singleLines);
|
|
96
117
|
const hasAnchorEdits =
|
|
97
118
|
Array.isArray(edits) &&
|
|
98
119
|
edits.length > 0 &&
|
|
@@ -112,6 +133,12 @@ function preflightFileEdit(
|
|
|
112
133
|
}
|
|
113
134
|
|
|
114
135
|
if (!isAnchorMode && !hasSingleBlock && !hasMultiBlock) {
|
|
136
|
+
if (typeof singleSearch === "string") {
|
|
137
|
+
return { error: `[EDIT ERROR] Missing 'replace' for the 'search' block in '${relPath}'. To delete the matched block, pass replace: "" (or edits: [{ search: "<block>", replace: "" }]).` };
|
|
138
|
+
}
|
|
139
|
+
if (item.offset !== undefined || item.limit !== undefined) {
|
|
140
|
+
return { error: `[EDIT ERROR] 'offset'/'limit' are 'read' arguments. To inspect lines, call read({ path: "${relPath}", offset, limit }). To edit, pass 'search' and 'replace'.` };
|
|
141
|
+
}
|
|
115
142
|
return { error: `[EDIT ERROR] Must provide either smart anchors ('pos' and 'lines', or 'edits' with anchors) or 'search' and 'replace' blocks for '${relPath}'.` };
|
|
116
143
|
}
|
|
117
144
|
|
|
@@ -126,7 +153,7 @@ function preflightFileEdit(
|
|
|
126
153
|
{
|
|
127
154
|
pos: item.pos ?? item.start_line,
|
|
128
155
|
end: item.end ?? item.end_line,
|
|
129
|
-
lines:
|
|
156
|
+
lines: singleLines,
|
|
130
157
|
},
|
|
131
158
|
];
|
|
132
159
|
} else {
|
|
@@ -191,7 +218,6 @@ function preflightFileEdit(
|
|
|
191
218
|
}
|
|
192
219
|
}
|
|
193
220
|
|
|
194
|
-
const config = deps.getConfig?.(ctx.cwd) ?? loadKernelConfig(ctx.cwd);
|
|
195
221
|
const epistemicCheck = globalEpistemicGuard.checkReadPrecondition(
|
|
196
222
|
resolvedPath,
|
|
197
223
|
"edit",
|
|
@@ -209,7 +235,7 @@ function preflightFileEdit(
|
|
|
209
235
|
prepared: {
|
|
210
236
|
resolvedPath,
|
|
211
237
|
relPath,
|
|
212
|
-
item: { ...item, search: singleSearch, replace: singleReplace, edits },
|
|
238
|
+
item: { ...item, search: singleSearch, replace: singleReplace, lines: singleLines, edits },
|
|
213
239
|
isAnchorMode,
|
|
214
240
|
hasSingleAnchor,
|
|
215
241
|
hasSingleBlock,
|
|
@@ -227,12 +253,20 @@ async function applyPreparedEdit(
|
|
|
227
253
|
ctx: any,
|
|
228
254
|
deps: SessionDeps,
|
|
229
255
|
options: { syntaxGate?: "warn" | "block" } = {},
|
|
230
|
-
): Promise<{ success: boolean; mutated: boolean; error?: string; verification?: any; strategy?: string; statusText?: string }> {
|
|
231
|
-
const { resolvedPath, relPath, item, isAnchorMode, hasSingleBlock, hasMultiBlock, anchorBlocks,
|
|
256
|
+
): Promise<{ success: boolean; mutated: boolean; error?: string; verification?: any; strategy?: string; statusText?: string; lineSpanSummary?: string }> {
|
|
257
|
+
const { resolvedPath, relPath, item, isAnchorMode, hasSingleBlock, hasMultiBlock, anchorBlocks, targetRanges } = prepared;
|
|
232
258
|
const config = deps.getConfig?.(ctx.cwd);
|
|
233
259
|
const editingMode = config?.editing?.mode ?? "smart_anchor";
|
|
234
260
|
const autoHeal = editingMode !== "standard";
|
|
235
261
|
const syntaxGate = options.syntaxGate ?? config?.editing?.syntax_gate ?? (editingMode === "standard" ? "block" : "warn");
|
|
262
|
+
// The syntax check uses tree-sitter when the grammar is loaded (see checkSyntaxContent).
|
|
263
|
+
await TreeSitterEngine.getInstance().loadLanguages([path.extname(resolvedPath).toLowerCase()]);
|
|
264
|
+
|
|
265
|
+
let originalLines = 0;
|
|
266
|
+
try {
|
|
267
|
+
originalLines = fs.readFileSync(resolvedPath, "utf8").split("\n").length;
|
|
268
|
+
} catch {}
|
|
269
|
+
|
|
236
270
|
let patchRes: ReturnType<typeof applySurgicalPatch>;
|
|
237
271
|
if (isAnchorMode) {
|
|
238
272
|
patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks, { syntaxGate });
|
|
@@ -264,25 +298,7 @@ async function applyPreparedEdit(
|
|
|
264
298
|
diskContent = "";
|
|
265
299
|
}
|
|
266
300
|
|
|
267
|
-
|
|
268
|
-
if (isAnchorMode && anchorPreflight?.resolvedSpans) {
|
|
269
|
-
for (const span of anchorPreflight.resolvedSpans) {
|
|
270
|
-
const deletedCount = span.endLine - span.startLine + 1;
|
|
271
|
-
deltaLines += span.replacementLines.length - deletedCount;
|
|
272
|
-
}
|
|
273
|
-
} else if (hasSingleBlock) {
|
|
274
|
-
const searchLines = item.search.replace(/\r\n/g, "\n").split("\n").length;
|
|
275
|
-
const replaceLines = item.replace.replace(/\r\n/g, "\n").split("\n").length;
|
|
276
|
-
deltaLines = replaceLines - searchLines;
|
|
277
|
-
} else if (hasMultiBlock) {
|
|
278
|
-
for (const block of item.edits) {
|
|
279
|
-
if (block && typeof block.search === "string" && typeof block.replace === "string") {
|
|
280
|
-
const sLines = block.search.replace(/\r\n/g, "\n").split("\n").length;
|
|
281
|
-
const rLines = block.replace.replace(/\r\n/g, "\n").split("\n").length;
|
|
282
|
-
deltaLines += (rLines - sLines);
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
}
|
|
301
|
+
const deltaLines = originalLines > 0 ? diskContent.split("\n").length - originalLines : 0;
|
|
286
302
|
|
|
287
303
|
globalEpistemicGuard.recordFileMutation(
|
|
288
304
|
resolvedPath,
|
|
@@ -297,132 +313,182 @@ async function applyPreparedEdit(
|
|
|
297
313
|
|
|
298
314
|
await deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
|
|
299
315
|
|
|
300
|
-
const
|
|
301
|
-
if (readyLsp && readyLsp.getState() === "ready") {
|
|
302
|
-
try {
|
|
303
|
-
await readyLsp.changeDocument(resolvedPath, diskContent);
|
|
304
|
-
await readyLsp.saveDocument(resolvedPath, diskContent);
|
|
305
|
-
} catch (err) {
|
|
306
|
-
kernelDebug(err);
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
const verification = await verifyEditedFile(
|
|
311
|
-
resolvedPath,
|
|
312
|
-
readyLsp
|
|
313
|
-
? async () => {
|
|
314
|
-
const result = await readyLsp.getDiagnosticsResult(resolvedPath);
|
|
315
|
-
return {
|
|
316
|
-
state: result.status,
|
|
317
|
-
findings: result.diagnostics.map((finding) => ({
|
|
318
|
-
line: finding.range.start.line + 1,
|
|
319
|
-
column: finding.range.start.character + 1,
|
|
320
|
-
message: finding.message,
|
|
321
|
-
severity:
|
|
322
|
-
finding.severity === 1
|
|
323
|
-
? ("error" as const)
|
|
324
|
-
: finding.severity === 2
|
|
325
|
-
? ("warning" as const)
|
|
326
|
-
: ("info" as const),
|
|
327
|
-
})),
|
|
328
|
-
};
|
|
329
|
-
}
|
|
330
|
-
: undefined,
|
|
331
|
-
);
|
|
316
|
+
const verification = await verifyEditedFile(resolvedPath, undefined, patchRes.syntax);
|
|
332
317
|
|
|
333
|
-
const
|
|
318
|
+
const lineSpanSummary = computeLineSpanSummary(prepared, patchRes);
|
|
319
|
+
const statusText = renderPostEditVerification(verification, undefined, relPath, lineSpanSummary);
|
|
334
320
|
return {
|
|
335
321
|
success: true,
|
|
336
322
|
mutated: true,
|
|
337
323
|
verification,
|
|
338
324
|
strategy: patchRes.strategy,
|
|
339
325
|
statusText,
|
|
326
|
+
lineSpanSummary,
|
|
340
327
|
};
|
|
341
328
|
}
|
|
342
329
|
|
|
330
|
+
function computeLineSpanSummary(
|
|
331
|
+
prepared: PreparedFileEdit,
|
|
332
|
+
patchRes: ReturnType<typeof applySurgicalPatch>,
|
|
333
|
+
): string | undefined {
|
|
334
|
+
const { item, isAnchorMode, hasSingleBlock, hasMultiBlock, anchorPreflight } = prepared;
|
|
335
|
+
const ranges = patchRes.targetRanges || prepared.targetRanges;
|
|
336
|
+
if (!ranges || ranges.length === 0) return undefined;
|
|
337
|
+
|
|
338
|
+
if (isAnchorMode && anchorPreflight?.resolvedSpans) {
|
|
339
|
+
const spanParts = anchorPreflight.resolvedSpans.slice(0, 3).map((span) => {
|
|
340
|
+
const oldSpan = span.startLine === span.endLine ? `line ${span.startLine}` : `lines ${span.startLine}–${span.endLine}`;
|
|
341
|
+
if (span.replacementLines.length === 0) {
|
|
342
|
+
return `${oldSpan} deleted`;
|
|
343
|
+
}
|
|
344
|
+
const newEnd = span.startLine + span.replacementLines.length - 1;
|
|
345
|
+
const newSpan = span.startLine === newEnd ? `line ${span.startLine}` : `${span.startLine}–${newEnd}`;
|
|
346
|
+
return `${oldSpan} -> ${newSpan}`;
|
|
347
|
+
});
|
|
348
|
+
if (anchorPreflight.resolvedSpans.length > 3) {
|
|
349
|
+
spanParts.push(`+${anchorPreflight.resolvedSpans.length - 3} more`);
|
|
350
|
+
}
|
|
351
|
+
return spanParts.join(", ");
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
if (hasSingleBlock && ranges[0]) {
|
|
355
|
+
const range = ranges[0];
|
|
356
|
+
const oldSpan = range.startLine === range.endLine ? `line ${range.startLine}` : `lines ${range.startLine}–${range.endLine}`;
|
|
357
|
+
const replaceStr = typeof item.replace === "string" ? item.replace : "";
|
|
358
|
+
if (replaceStr === "") {
|
|
359
|
+
return `${oldSpan} deleted`;
|
|
360
|
+
}
|
|
361
|
+
const rLines = replaceStr.replace(/\r\n/g, "\n").split("\n").length;
|
|
362
|
+
const newEnd = range.startLine + rLines - 1;
|
|
363
|
+
const newSpan = range.startLine === newEnd ? `line ${range.startLine}` : `${range.startLine}–${newEnd}`;
|
|
364
|
+
return `${oldSpan} -> ${newSpan}`;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (hasMultiBlock && Array.isArray(item.edits)) {
|
|
368
|
+
let currentLineDelta = 0;
|
|
369
|
+
const summaries: string[] = [];
|
|
370
|
+
for (let i = 0; i < item.edits.length; i++) {
|
|
371
|
+
const block = item.edits[i];
|
|
372
|
+
const range = ranges[i];
|
|
373
|
+
if (!range) continue;
|
|
374
|
+
const oldSpan = range.startLine === range.endLine ? `line ${range.startLine}` : `lines ${range.startLine}–${range.endLine}`;
|
|
375
|
+
const replaceStr = typeof block.replace === "string" ? block.replace : "";
|
|
376
|
+
if (replaceStr === "") {
|
|
377
|
+
summaries.push(`${oldSpan} deleted`);
|
|
378
|
+
currentLineDelta += 0 - (range.endLine - range.startLine + 1);
|
|
379
|
+
} else {
|
|
380
|
+
const rLines = replaceStr.replace(/\r\n/g, "\n").split("\n").length;
|
|
381
|
+
const newStart = range.startLine + currentLineDelta;
|
|
382
|
+
const newEnd = newStart + rLines - 1;
|
|
383
|
+
const newSpan = newStart === newEnd ? `line ${newStart}` : `${newStart}–${newEnd}`;
|
|
384
|
+
summaries.push(`${oldSpan} -> ${newSpan}`);
|
|
385
|
+
currentLineDelta += rLines - (range.endLine - range.startLine + 1);
|
|
386
|
+
}
|
|
387
|
+
if (summaries.length >= 3 && i < item.edits.length - 1) {
|
|
388
|
+
summaries.push(`+${item.edits.length - 1 - i} more`);
|
|
389
|
+
break;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return summaries.join(", ");
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
return undefined;
|
|
396
|
+
}
|
|
397
|
+
|
|
343
398
|
/** Extracted from index.ts — registers the `edit` tool. */
|
|
344
399
|
export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
345
400
|
// 7. Tool: `edit` (Unified Surgical Diff, Smart Anchor, & Multi-Block Editor - Replaces stock edit tool)
|
|
346
401
|
const benchmarkMethod = process.env.PI_EDIT_METHOD?.toLowerCase();
|
|
347
|
-
|
|
348
|
-
|
|
402
|
+
let editToolParameters: any;
|
|
403
|
+
let editToolDescription =
|
|
404
|
+
"Edit code with search/replace, multi-block 'edits', or multi-file 'files'. Auto-preserves existing line endings (CRLF/LF). Use when modifying existing code with unique search blocks, targeted multi-block edits, or atomic multi-file changes. Do NOT use edit for shell commands (use bash) or creating new files (use write).";
|
|
405
|
+
|
|
406
|
+
switch (benchmarkMethod) {
|
|
407
|
+
case "line-range":
|
|
408
|
+
editToolParameters = Type.Object({
|
|
349
409
|
path: Type.String({ description: "File path to edit" }),
|
|
350
410
|
start_line: Type.Number({ description: "First 1-based line to replace" }),
|
|
351
411
|
end_line: Type.Optional(Type.Number({ description: "Last 1-based line to replace, inclusive" })),
|
|
352
412
|
lines: Type.Array(Type.String(), { description: "Replacement lines (empty to delete)" }),
|
|
353
|
-
})
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
})
|
|
361
|
-
:
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
:
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
413
|
+
});
|
|
414
|
+
editToolDescription = "Edit code with numeric line ranges only: start_line, optional end_line, and replacement lines.";
|
|
415
|
+
break;
|
|
416
|
+
case "hash-anchor":
|
|
417
|
+
editToolParameters = Type.Object({
|
|
418
|
+
path: Type.String({ description: "File path to edit" }),
|
|
419
|
+
pos: Type.String({ description: "Start anchor copied from read output, e.g. '288#ZH'" }),
|
|
420
|
+
end: Type.Optional(Type.String({ description: "End anchor copied from read output, e.g. '294#VN'" })),
|
|
421
|
+
lines: Type.Array(Type.String(), { description: "Replacement lines (empty to delete)" }),
|
|
422
|
+
});
|
|
423
|
+
editToolDescription = "Edit code with LINE#HASH anchors only, copied from read output.";
|
|
424
|
+
break;
|
|
425
|
+
case "search-replace":
|
|
426
|
+
editToolParameters = Type.Object({
|
|
427
|
+
path: Type.String({ description: "File path to edit" }),
|
|
428
|
+
search: Type.String({ description: "Unique exact source block to replace" }),
|
|
429
|
+
replace: Type.String({ description: "Replacement source block (empty string to delete)" }),
|
|
430
|
+
});
|
|
431
|
+
editToolDescription = "Edit code with a unique exact search block and replacement block only.";
|
|
432
|
+
break;
|
|
433
|
+
case "adaptive":
|
|
434
|
+
editToolParameters = Type.Object({
|
|
435
|
+
path: Type.String({ description: "File path to edit" }),
|
|
436
|
+
search: Type.Optional(Type.String({ description: "Unique exact source block to replace" })),
|
|
437
|
+
replace: Type.Optional(Type.String({ description: "Replacement source block (empty string to delete)" })),
|
|
438
|
+
start_line: Type.Optional(Type.Number({ description: "First 1-based line to replace" })),
|
|
439
|
+
end_line: Type.Optional(Type.Number({ description: "Last 1-based line to replace, inclusive" })),
|
|
440
|
+
pos: Type.Optional(Type.String({ description: "LINE#HASH anchor copied from read output" })),
|
|
441
|
+
end: Type.Optional(Type.String({ description: "Ending LINE#HASH anchor" })),
|
|
442
|
+
lines: Type.Optional(Type.Array(Type.String(), { description: "Replacement lines (empty to delete)" })),
|
|
443
|
+
});
|
|
444
|
+
editToolDescription = "Edit code with search/replace or line range; use search first.";
|
|
445
|
+
break;
|
|
446
|
+
default:
|
|
447
|
+
const blockEditSchema = Type.Object(
|
|
448
|
+
{
|
|
449
|
+
search: Type.Optional(Type.String({ description: "Exact block to replace" })),
|
|
450
|
+
replace: Type.Optional(Type.String({ description: "Replacement text (empty string to delete)" })),
|
|
451
|
+
line_hint: Type.Optional(Type.Number({ description: "Line hint for disambiguating matching blocks" })),
|
|
452
|
+
},
|
|
453
|
+
{ additionalProperties: true },
|
|
454
|
+
);
|
|
455
|
+
|
|
456
|
+
editToolParameters = Type.Object(
|
|
457
|
+
{
|
|
458
|
+
path: Type.Optional(Type.String({ description: "Path to file to edit" })),
|
|
459
|
+
search: Type.Optional(Type.String({ description: "Exact block to replace" })),
|
|
460
|
+
replace: Type.Optional(Type.String({ description: "Replacement text (empty string to delete)" })),
|
|
461
|
+
line_hint: Type.Optional(Type.Number({ description: "Line hint for disambiguation" })),
|
|
462
|
+
edits: Type.Optional(
|
|
463
|
+
Type.Array(blockEditSchema, { description: "Targeted replacements" }),
|
|
464
|
+
),
|
|
465
|
+
files: Type.Optional(
|
|
466
|
+
Type.Array(
|
|
467
|
+
Type.Object(
|
|
468
|
+
{
|
|
469
|
+
path: Type.String({ description: "Workspace-relative or absolute file path to edit" }),
|
|
470
|
+
search: Type.Optional(Type.String({ description: "Exact block to replace" })),
|
|
471
|
+
replace: Type.Optional(Type.String({ description: "Replacement text (empty string to delete)" })),
|
|
472
|
+
line_hint: Type.Optional(Type.Number({ description: "Line hint for disambiguating matching blocks" })),
|
|
473
|
+
edits: Type.Optional(
|
|
474
|
+
Type.Array(blockEditSchema, { description: "Array of targeted replacements for this file" }),
|
|
407
475
|
),
|
|
408
|
-
|
|
409
|
-
|
|
476
|
+
},
|
|
477
|
+
{ additionalProperties: true },
|
|
410
478
|
),
|
|
411
|
-
|
|
479
|
+
{ description: "Multi-file edits" },
|
|
480
|
+
),
|
|
481
|
+
),
|
|
482
|
+
},
|
|
483
|
+
{ additionalProperties: true },
|
|
484
|
+
);
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
412
487
|
const editToolDefinition: any = {
|
|
413
488
|
name: "edit",
|
|
414
489
|
label: "Code Editor",
|
|
415
|
-
description:
|
|
416
|
-
|
|
417
|
-
? "Edit code with numeric line ranges only: start_line, optional end_line, and replacement lines."
|
|
418
|
-
: benchmarkMethod === "hash-anchor"
|
|
419
|
-
? "Edit code with LINE#HASH anchors only, copied from read output."
|
|
420
|
-
: benchmarkMethod === "search-replace"
|
|
421
|
-
? "Edit code with a unique exact search block and replacement block only."
|
|
422
|
-
: benchmarkMethod === "adaptive"
|
|
423
|
-
? "Edit code with search/replace or line range; use search first."
|
|
424
|
-
: "Edit code with search/replace, multi-block 'edits', or multi-file 'files'. Valid after read or exact rg search.",
|
|
425
|
-
promptSnippet: "Edit code using search/replace (optional line_hint), multi-block 'edits', or multi-file 'files'",
|
|
490
|
+
description: editToolDescription,
|
|
491
|
+
promptSnippet: "Edit code using search/replace (optional line_hint), multi-block 'edits', or multi-file 'files' (preserves CRLF/LF)",
|
|
426
492
|
renderShell: "default",
|
|
427
493
|
parameters: editToolParameters,
|
|
428
494
|
async execute(
|
|
@@ -432,6 +498,34 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
432
498
|
onUpdate: any,
|
|
433
499
|
ctx: any,
|
|
434
500
|
): Promise<any> {
|
|
501
|
+
// Detect tool confusion (caller passed shell command to edit tool)
|
|
502
|
+
if (params && typeof params === "object" && typeof params.command === "string" && params.command.trim().length > 0) {
|
|
503
|
+
const hasPath = typeof params.path === "string" && params.path.trim().length > 0;
|
|
504
|
+
const hasFiles = Array.isArray(params.files) && params.files.length > 0;
|
|
505
|
+
if (hasPath || hasFiles) {
|
|
506
|
+
return {
|
|
507
|
+
content: [
|
|
508
|
+
{
|
|
509
|
+
type: "text",
|
|
510
|
+
text: `[EDIT ERROR] Ambiguous parameters: received both shell 'command' and file edit parameters ('path'/'files'). To execute shell commands, invoke the 'bash' tool. To modify code, invoke the 'edit' tool without 'command'.`,
|
|
511
|
+
},
|
|
512
|
+
],
|
|
513
|
+
details: { error: "ambiguous_parameters", command: params.command.trim() },
|
|
514
|
+
isError: true,
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
return {
|
|
518
|
+
content: [
|
|
519
|
+
{
|
|
520
|
+
type: "text",
|
|
521
|
+
text: `[EDIT ERROR] Received shell command in 'edit' tool. To execute shell commands, invoke the 'bash' tool instead with { command: ${JSON.stringify(params.command.trim())} }. The 'edit' tool is for modifying file contents and requires { path: "path/to/file", search: "...", replace: "..." }.`,
|
|
522
|
+
},
|
|
523
|
+
],
|
|
524
|
+
details: { error: "tool_confusion_command", command: params.command.trim() },
|
|
525
|
+
isError: true,
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
435
529
|
// Check for multi-file payload
|
|
436
530
|
const fileEdits: any[] = [];
|
|
437
531
|
if (params && typeof params === "object") {
|
|
@@ -564,15 +658,6 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
564
658
|
} catch (indexErr) {
|
|
565
659
|
rollbackFailures.push(`${path.basename(mutated)} index: ${indexErr instanceof Error ? indexErr.message : String(indexErr)}`);
|
|
566
660
|
}
|
|
567
|
-
try {
|
|
568
|
-
const client = LspManager.getInstance().getReadyClientForFile(mutated, ctx.cwd);
|
|
569
|
-
if (client?.getState() === "ready") {
|
|
570
|
-
await client.changeDocument(mutated, backup);
|
|
571
|
-
await client.saveDocument(mutated, backup);
|
|
572
|
-
}
|
|
573
|
-
} catch (lspErr) {
|
|
574
|
-
rollbackFailures.push(`${path.basename(mutated)} LSP: ${lspErr instanceof Error ? lspErr.message : String(lspErr)}`);
|
|
575
|
-
}
|
|
576
661
|
}
|
|
577
662
|
if (rollbackFailures.length > 0) {
|
|
578
663
|
return {
|
|
@@ -582,17 +667,21 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
582
667
|
};
|
|
583
668
|
}
|
|
584
669
|
return {
|
|
585
|
-
content: [{ type: "text", text: `[EDIT FAILED - ROLLED BACK] Multi-file edit aborted and all file/index/
|
|
670
|
+
content: [{ type: "text", text: `[EDIT FAILED - ROLLED BACK] Multi-file edit aborted and all file/index/guard state restored: ${failureReason}` }],
|
|
586
671
|
details: { rolledBack: true },
|
|
587
672
|
isError: true,
|
|
588
673
|
};
|
|
589
674
|
}
|
|
590
675
|
|
|
591
|
-
const
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
676
|
+
const summaries = preparedList.map((p, idx) => {
|
|
677
|
+
const outcome = outcomes[idx];
|
|
678
|
+
const span = outcome?.lineSpanSummary ? ` (${outcome.lineSpanSummary})` : "";
|
|
679
|
+
return `${p.relPath}${span}`;
|
|
680
|
+
});
|
|
681
|
+
return {
|
|
682
|
+
content: [{ type: "text", text: `Successfully applied edits to ${preparedList.length} files: ${summaries.join(", ")}.` }],
|
|
683
|
+
details: { multiFile: true, count: preparedList.length, files: preparedList.map((p) => p.relPath) },
|
|
684
|
+
};
|
|
596
685
|
});
|
|
597
686
|
}
|
|
598
687
|
|
|
@@ -677,5 +766,5 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
677
766
|
},
|
|
678
767
|
};
|
|
679
768
|
|
|
680
|
-
pi.registerTool(editToolDefinition);
|
|
769
|
+
pi.registerTool(markReturnedErrors(editToolDefinition));
|
|
681
770
|
}
|