@floydous/pi-agent-kernel 0.5.0 → 0.6.1
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 +20 -6
- package/CHANGELOG.md +69 -0
- package/README.md +23 -20
- package/config.example.toml +1 -0
- package/docs/configuration.md +1 -1
- package/docs/editing-and-verification.md +20 -5
- package/docs/podman-linux-checks.md +24 -0
- package/docs/release-discipline.md +10 -0
- package/docs/retrieval.md +14 -11
- package/grammars/tree-sitter-html.wasm +0 -0
- package/package.json +2 -2
- package/src/config/agent_kernel_command.ts +60 -593
- package/src/config/kernel_config.ts +46 -2
- package/src/editing/patch.ts +48 -21
- package/src/editing/post_edit_verification.ts +8 -4
- package/src/editing/smart_anchor.ts +2 -1
- package/src/editing/syntax-verify.ts +73 -220
- package/src/index.ts +105 -203
- package/src/retrieval/html_chunker.ts +526 -0
- package/src/retrieval/search_bm25.ts +36 -27
- package/src/retrieval/search_chunker.ts +68 -6
- package/src/retrieval/search_config.ts +17 -34
- package/src/retrieval/search_embedder.ts +11 -29
- package/src/retrieval/search_index.ts +307 -145
- package/src/retrieval/search_modal.ts +1247 -222
- package/src/retrieval/tag_extractor.ts +1 -1
- package/src/retrieval/tree_sitter_engine.ts +103 -4
- package/src/retrieval/workspace_walker.ts +72 -0
- package/src/safety/host_environment.ts +190 -0
- package/src/safety/output_clamper.ts +83 -19
- package/src/tools/code_search_output.ts +9 -1
- package/src/tools/code_search_tool.ts +51 -14
- package/src/tools/context.ts +15 -0
- package/src/tools/edit_tool.ts +306 -79
- package/src/tools/read_tool.ts +248 -39
- package/src/tools/stream_reader.ts +206 -0
- package/src/ui/tui_utils.ts +70 -12
package/src/tools/edit_tool.ts
CHANGED
|
@@ -25,7 +25,8 @@ import {
|
|
|
25
25
|
resolveUserPath,
|
|
26
26
|
} from "../safety/epistemic_guard";
|
|
27
27
|
import { loadKernelConfig } from "../config";
|
|
28
|
-
import type
|
|
28
|
+
import { markReturnedErrors, type SessionDeps } from "./context";
|
|
29
|
+
import { TreeSitterEngine } from "../retrieval/tree_sitter_engine";
|
|
29
30
|
|
|
30
31
|
function mutationLockKey(filePath: string): string {
|
|
31
32
|
const resolved = path.resolve(filePath);
|
|
@@ -75,21 +76,44 @@ function preflightFileEdit(
|
|
|
75
76
|
return { error: `[EDIT FAILED] File not found: '${item.path}'.` };
|
|
76
77
|
}
|
|
77
78
|
|
|
79
|
+
const config = deps.getConfig?.(ctx.cwd) ?? loadKernelConfig(ctx.cwd);
|
|
80
|
+
const shouldNormalizeDots = config?.editing?.normalize_fullwidth_dots !== false;
|
|
81
|
+
|
|
78
82
|
let edits = item.edits;
|
|
79
83
|
if (Array.isArray(edits)) {
|
|
80
84
|
edits = edits.map((e: any) => {
|
|
81
85
|
if (!e || typeof e !== "object") return e;
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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 } : {}) };
|
|
85
99
|
});
|
|
86
100
|
}
|
|
87
|
-
|
|
88
|
-
|
|
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
|
+
}
|
|
89
113
|
|
|
90
114
|
const hasSingleAnchor =
|
|
91
115
|
(item.pos !== undefined || item.start_line !== undefined) &&
|
|
92
|
-
Array.isArray(
|
|
116
|
+
Array.isArray(singleLines);
|
|
93
117
|
const hasAnchorEdits =
|
|
94
118
|
Array.isArray(edits) &&
|
|
95
119
|
edits.length > 0 &&
|
|
@@ -109,6 +133,12 @@ function preflightFileEdit(
|
|
|
109
133
|
}
|
|
110
134
|
|
|
111
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
|
+
}
|
|
112
142
|
return { error: `[EDIT ERROR] Must provide either smart anchors ('pos' and 'lines', or 'edits' with anchors) or 'search' and 'replace' blocks for '${relPath}'.` };
|
|
113
143
|
}
|
|
114
144
|
|
|
@@ -123,7 +153,7 @@ function preflightFileEdit(
|
|
|
123
153
|
{
|
|
124
154
|
pos: item.pos ?? item.start_line,
|
|
125
155
|
end: item.end ?? item.end_line,
|
|
126
|
-
lines:
|
|
156
|
+
lines: singleLines,
|
|
127
157
|
},
|
|
128
158
|
];
|
|
129
159
|
} else {
|
|
@@ -188,7 +218,6 @@ function preflightFileEdit(
|
|
|
188
218
|
}
|
|
189
219
|
}
|
|
190
220
|
|
|
191
|
-
const config = deps.getConfig?.(ctx.cwd) ?? loadKernelConfig(ctx.cwd);
|
|
192
221
|
const epistemicCheck = globalEpistemicGuard.checkReadPrecondition(
|
|
193
222
|
resolvedPath,
|
|
194
223
|
"edit",
|
|
@@ -206,7 +235,7 @@ function preflightFileEdit(
|
|
|
206
235
|
prepared: {
|
|
207
236
|
resolvedPath,
|
|
208
237
|
relPath,
|
|
209
|
-
item: { ...item, search: singleSearch, replace: singleReplace, edits },
|
|
238
|
+
item: { ...item, search: singleSearch, replace: singleReplace, lines: singleLines, edits },
|
|
210
239
|
isAnchorMode,
|
|
211
240
|
hasSingleAnchor,
|
|
212
241
|
hasSingleBlock,
|
|
@@ -224,12 +253,20 @@ async function applyPreparedEdit(
|
|
|
224
253
|
ctx: any,
|
|
225
254
|
deps: SessionDeps,
|
|
226
255
|
options: { syntaxGate?: "warn" | "block" } = {},
|
|
227
|
-
): Promise<{ success: boolean; mutated: boolean; error?: string; verification?: any; strategy?: string; statusText?: string }> {
|
|
228
|
-
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;
|
|
229
258
|
const config = deps.getConfig?.(ctx.cwd);
|
|
230
259
|
const editingMode = config?.editing?.mode ?? "smart_anchor";
|
|
231
260
|
const autoHeal = editingMode !== "standard";
|
|
232
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
|
+
|
|
233
270
|
let patchRes: ReturnType<typeof applySurgicalPatch>;
|
|
234
271
|
if (isAnchorMode) {
|
|
235
272
|
patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks, { syntaxGate });
|
|
@@ -261,25 +298,7 @@ async function applyPreparedEdit(
|
|
|
261
298
|
diskContent = "";
|
|
262
299
|
}
|
|
263
300
|
|
|
264
|
-
|
|
265
|
-
if (isAnchorMode && anchorPreflight?.resolvedSpans) {
|
|
266
|
-
for (const span of anchorPreflight.resolvedSpans) {
|
|
267
|
-
const deletedCount = span.endLine - span.startLine + 1;
|
|
268
|
-
deltaLines += span.replacementLines.length - deletedCount;
|
|
269
|
-
}
|
|
270
|
-
} else if (hasSingleBlock) {
|
|
271
|
-
const searchLines = item.search.replace(/\r\n/g, "\n").split("\n").length;
|
|
272
|
-
const replaceLines = item.replace.replace(/\r\n/g, "\n").split("\n").length;
|
|
273
|
-
deltaLines = replaceLines - searchLines;
|
|
274
|
-
} else if (hasMultiBlock) {
|
|
275
|
-
for (const block of item.edits) {
|
|
276
|
-
if (block && typeof block.search === "string" && typeof block.replace === "string") {
|
|
277
|
-
const sLines = block.search.replace(/\r\n/g, "\n").split("\n").length;
|
|
278
|
-
const rLines = block.replace.replace(/\r\n/g, "\n").split("\n").length;
|
|
279
|
-
deltaLines += (rLines - sLines);
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
}
|
|
301
|
+
const deltaLines = originalLines > 0 ? diskContent.split("\n").length - originalLines : 0;
|
|
283
302
|
|
|
284
303
|
globalEpistemicGuard.recordFileMutation(
|
|
285
304
|
resolvedPath,
|
|
@@ -294,25 +313,95 @@ async function applyPreparedEdit(
|
|
|
294
313
|
|
|
295
314
|
await deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
|
|
296
315
|
|
|
297
|
-
const verification = await verifyEditedFile(resolvedPath);
|
|
316
|
+
const verification = await verifyEditedFile(resolvedPath, undefined, patchRes.syntax);
|
|
298
317
|
|
|
299
|
-
const
|
|
318
|
+
const lineSpanSummary = computeLineSpanSummary(prepared, patchRes);
|
|
319
|
+
const statusText = renderPostEditVerification(verification, undefined, relPath, lineSpanSummary);
|
|
300
320
|
return {
|
|
301
321
|
success: true,
|
|
302
322
|
mutated: true,
|
|
303
323
|
verification,
|
|
304
324
|
strategy: patchRes.strategy,
|
|
305
325
|
statusText,
|
|
326
|
+
lineSpanSummary,
|
|
306
327
|
};
|
|
307
328
|
}
|
|
308
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
|
+
|
|
309
398
|
/** Extracted from index.ts — registers the `edit` tool. */
|
|
310
399
|
export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
311
400
|
// 7. Tool: `edit` (Unified Surgical Diff, Smart Anchor, & Multi-Block Editor - Replaces stock edit tool)
|
|
312
401
|
const benchmarkMethod = process.env.PI_EDIT_METHOD?.toLowerCase();
|
|
313
402
|
let editToolParameters: any;
|
|
314
403
|
let editToolDescription =
|
|
315
|
-
"Edit code
|
|
404
|
+
"Edit code using targeted 'edits' blocks (search/replace with optional line_hint) or atomic multi-file 'files'. Auto-preserves existing line endings (CRLF/LF). Use when modifying existing code with unique search blocks or atomic multi-file changes. Do NOT use edit for shell commands (use bash) or creating new files (use write).";
|
|
316
405
|
|
|
317
406
|
switch (benchmarkMethod) {
|
|
318
407
|
case "line-range":
|
|
@@ -337,7 +426,7 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
337
426
|
editToolParameters = Type.Object({
|
|
338
427
|
path: Type.String({ description: "File path to edit" }),
|
|
339
428
|
search: Type.String({ description: "Unique exact source block to replace" }),
|
|
340
|
-
replace: Type.String({ description: "Replacement source block" }),
|
|
429
|
+
replace: Type.String({ description: "Replacement source block (empty string to delete)" }),
|
|
341
430
|
});
|
|
342
431
|
editToolDescription = "Edit code with a unique exact search block and replacement block only.";
|
|
343
432
|
break;
|
|
@@ -345,7 +434,7 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
345
434
|
editToolParameters = Type.Object({
|
|
346
435
|
path: Type.String({ description: "File path to edit" }),
|
|
347
436
|
search: Type.Optional(Type.String({ description: "Unique exact source block to replace" })),
|
|
348
|
-
replace: Type.Optional(Type.String({ description: "Replacement source block" })),
|
|
437
|
+
replace: Type.Optional(Type.String({ description: "Replacement source block (empty string to delete)" })),
|
|
349
438
|
start_line: Type.Optional(Type.Number({ description: "First 1-based line to replace" })),
|
|
350
439
|
end_line: Type.Optional(Type.Number({ description: "Last 1-based line to replace, inclusive" })),
|
|
351
440
|
pos: Type.Optional(Type.String({ description: "LINE#HASH anchor copied from read output" })),
|
|
@@ -355,52 +444,158 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
355
444
|
editToolDescription = "Edit code with search/replace or line range; use search first.";
|
|
356
445
|
break;
|
|
357
446
|
default:
|
|
358
|
-
|
|
359
|
-
{
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
Type.
|
|
379
|
-
Type.
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
edits: Type.Optional(Type.Array(Type.Any())),
|
|
386
|
-
},
|
|
387
|
-
{ additionalProperties: true },
|
|
388
|
-
),
|
|
389
|
-
{ description: "Multi-file edits" },
|
|
390
|
-
),
|
|
447
|
+
const blockEditSchema = Type.Object({
|
|
448
|
+
search: Type.String({ description: "Exact block to replace" }),
|
|
449
|
+
replace: Type.String({ description: "Replacement text (empty string to delete)" }),
|
|
450
|
+
line_hint: Type.Optional(
|
|
451
|
+
Type.Number({
|
|
452
|
+
minimum: 1,
|
|
453
|
+
description: "1-based line number hint for disambiguating matching blocks",
|
|
454
|
+
}),
|
|
455
|
+
),
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
editToolParameters = Type.Object({
|
|
459
|
+
path: Type.Optional(Type.String({ description: "Workspace-relative or absolute file path to edit" })),
|
|
460
|
+
edits: Type.Optional(
|
|
461
|
+
Type.Array(blockEditSchema, {
|
|
462
|
+
description: "Ordered array of targeted search/replace blocks applied atomically to this file",
|
|
463
|
+
}),
|
|
464
|
+
),
|
|
465
|
+
files: Type.Optional(
|
|
466
|
+
Type.Array(
|
|
467
|
+
Type.Object({
|
|
468
|
+
path: Type.String({ description: "Workspace-relative or absolute file path to edit" }),
|
|
469
|
+
edits: Type.Array(blockEditSchema, {
|
|
470
|
+
description: "Ordered array of targeted replacements for this file",
|
|
471
|
+
}),
|
|
472
|
+
}),
|
|
473
|
+
{ description: "Atomic multi-file edits; each entry targets a distinct file path" },
|
|
391
474
|
),
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
);
|
|
475
|
+
),
|
|
476
|
+
});
|
|
395
477
|
break;
|
|
396
478
|
}
|
|
397
479
|
const editToolDefinition: any = {
|
|
398
480
|
name: "edit",
|
|
399
481
|
label: "Code Editor",
|
|
400
482
|
description: editToolDescription,
|
|
401
|
-
promptSnippet: "Edit code using search/replace
|
|
483
|
+
promptSnippet: "Edit code using targeted 'edits' blocks (search/replace, optional line_hint) or atomic multi-file 'files' (preserves CRLF/LF)",
|
|
402
484
|
renderShell: "default",
|
|
403
485
|
parameters: editToolParameters,
|
|
486
|
+
prepareArguments(args: any) {
|
|
487
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) return args;
|
|
488
|
+
|
|
489
|
+
if (benchmarkMethod) {
|
|
490
|
+
const normalizeBenchmarkItem = (item: any) => {
|
|
491
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) return item;
|
|
492
|
+
let out = item;
|
|
493
|
+
if (out.replace === null) out = { ...out, replace: "" };
|
|
494
|
+
if (Array.isArray(out.edits)) {
|
|
495
|
+
out = {
|
|
496
|
+
...out,
|
|
497
|
+
edits: out.edits.map((e: any) =>
|
|
498
|
+
e && typeof e === "object" && e.replace === null ? { ...e, replace: "" } : e,
|
|
499
|
+
),
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
return out;
|
|
503
|
+
};
|
|
504
|
+
let prepared = normalizeBenchmarkItem(args);
|
|
505
|
+
if (Array.isArray(prepared.files)) {
|
|
506
|
+
prepared = { ...prepared, files: prepared.files.map(normalizeBenchmarkItem) };
|
|
507
|
+
}
|
|
508
|
+
return prepared;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const isPlainObject = (v: unknown): v is Record<string, any> =>
|
|
512
|
+
Boolean(v && typeof v === "object" && !Array.isArray(v));
|
|
513
|
+
|
|
514
|
+
const parseEditsField = (raw: unknown): unknown => {
|
|
515
|
+
if (typeof raw === "string") {
|
|
516
|
+
try {
|
|
517
|
+
const parsed = JSON.parse(raw);
|
|
518
|
+
if (Array.isArray(parsed)) return parsed;
|
|
519
|
+
if (isPlainObject(parsed)) return [parsed];
|
|
520
|
+
} catch {
|
|
521
|
+
return raw;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
if (isPlainObject(raw)) return [raw];
|
|
525
|
+
return raw;
|
|
526
|
+
};
|
|
527
|
+
|
|
528
|
+
const normalizeBlock = (e: any): any => {
|
|
529
|
+
if (!isPlainObject(e)) return e;
|
|
530
|
+
const search = e.search ?? e.oldText ?? e.old_text ?? e.old;
|
|
531
|
+
const rawReplace =
|
|
532
|
+
e.replace === null ? "" : (e.replace ?? e.replacement ?? e.newText ?? e.new_text ?? e.new);
|
|
533
|
+
const replace = rawReplace === null ? "" : rawReplace;
|
|
534
|
+
const { oldText: _ot, old_text: _os, old: _o, newText: _nt, new_text: _ns, new: _n, replacement: _r, ...rest } = e;
|
|
535
|
+
const out: Record<string, any> = { ...rest };
|
|
536
|
+
if (search !== undefined) out.search = search;
|
|
537
|
+
if (replace !== undefined) out.replace = replace;
|
|
538
|
+
return out;
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
const normalizeFileEntry = (item: any): any => {
|
|
542
|
+
if (!isPlainObject(item)) return item;
|
|
543
|
+
const out: Record<string, any> = { ...item };
|
|
544
|
+
if (out.edits !== undefined) {
|
|
545
|
+
const unwrapped = parseEditsField(out.edits);
|
|
546
|
+
out.edits = Array.isArray(unwrapped) ? unwrapped.map(normalizeBlock) : unwrapped;
|
|
547
|
+
}
|
|
548
|
+
const singleSearch = out.search ?? out.oldText ?? out.old_text ?? out.old;
|
|
549
|
+
const rawSingleReplace =
|
|
550
|
+
out.replace === null ? "" : (out.replace ?? out.replacement ?? out.newText ?? out.new_text ?? out.new);
|
|
551
|
+
const singleReplace = rawSingleReplace === null ? "" : rawSingleReplace;
|
|
552
|
+
|
|
553
|
+
// Fold top-level search/replace only when both are strings; preserve missing-replace fail-closed errors.
|
|
554
|
+
if (typeof singleSearch === "string" && typeof singleReplace === "string") {
|
|
555
|
+
const foldedBlock: Record<string, any> = {
|
|
556
|
+
search: singleSearch,
|
|
557
|
+
replace: singleReplace,
|
|
558
|
+
...(out.line_hint !== undefined ? { line_hint: out.line_hint } : {}),
|
|
559
|
+
};
|
|
560
|
+
out.edits = Array.isArray(out.edits) ? [...out.edits, foldedBlock] : [foldedBlock];
|
|
561
|
+
delete out.search;
|
|
562
|
+
delete out.replace;
|
|
563
|
+
delete out.line_hint;
|
|
564
|
+
delete out.oldText;
|
|
565
|
+
delete out.old_text;
|
|
566
|
+
delete out.old;
|
|
567
|
+
delete out.newText;
|
|
568
|
+
delete out.new_text;
|
|
569
|
+
delete out.new;
|
|
570
|
+
delete out.replacement;
|
|
571
|
+
} else if (out.replace === null) {
|
|
572
|
+
out.replace = "";
|
|
573
|
+
}
|
|
574
|
+
return out;
|
|
575
|
+
};
|
|
576
|
+
|
|
577
|
+
const unwrappedTopEdits = args.edits !== undefined ? parseEditsField(args.edits) : undefined;
|
|
578
|
+
if (
|
|
579
|
+
Array.isArray(unwrappedTopEdits) &&
|
|
580
|
+
unwrappedTopEdits.length > 0 &&
|
|
581
|
+
unwrappedTopEdits.some((e: any) => isPlainObject(e) && typeof e.path === "string")
|
|
582
|
+
) {
|
|
583
|
+
const { edits: _ignoredEdits, ...rest } = args;
|
|
584
|
+
return {
|
|
585
|
+
...rest,
|
|
586
|
+
files: unwrappedTopEdits.map(normalizeFileEntry),
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
let prepared = normalizeFileEntry(args);
|
|
591
|
+
if (Array.isArray(prepared.files)) {
|
|
592
|
+
prepared = {
|
|
593
|
+
...prepared,
|
|
594
|
+
files: prepared.files.map(normalizeFileEntry),
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
return prepared;
|
|
598
|
+
},
|
|
404
599
|
async execute(
|
|
405
600
|
_toolCallId: string,
|
|
406
601
|
params: any,
|
|
@@ -408,6 +603,34 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
408
603
|
onUpdate: any,
|
|
409
604
|
ctx: any,
|
|
410
605
|
): Promise<any> {
|
|
606
|
+
// Detect tool confusion (caller passed shell command to edit tool)
|
|
607
|
+
if (params && typeof params === "object" && typeof params.command === "string" && params.command.trim().length > 0) {
|
|
608
|
+
const hasPath = typeof params.path === "string" && params.path.trim().length > 0;
|
|
609
|
+
const hasFiles = Array.isArray(params.files) && params.files.length > 0;
|
|
610
|
+
if (hasPath || hasFiles) {
|
|
611
|
+
return {
|
|
612
|
+
content: [
|
|
613
|
+
{
|
|
614
|
+
type: "text",
|
|
615
|
+
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'.`,
|
|
616
|
+
},
|
|
617
|
+
],
|
|
618
|
+
details: { error: "ambiguous_parameters", command: params.command.trim() },
|
|
619
|
+
isError: true,
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
return {
|
|
623
|
+
content: [
|
|
624
|
+
{
|
|
625
|
+
type: "text",
|
|
626
|
+
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: "..." }.`,
|
|
627
|
+
},
|
|
628
|
+
],
|
|
629
|
+
details: { error: "tool_confusion_command", command: params.command.trim() },
|
|
630
|
+
isError: true,
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
411
634
|
// Check for multi-file payload
|
|
412
635
|
const fileEdits: any[] = [];
|
|
413
636
|
if (params && typeof params === "object") {
|
|
@@ -555,11 +778,15 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
555
778
|
};
|
|
556
779
|
}
|
|
557
780
|
|
|
558
|
-
const
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
781
|
+
const summaries = preparedList.map((p, idx) => {
|
|
782
|
+
const outcome = outcomes[idx];
|
|
783
|
+
const span = outcome?.lineSpanSummary ? ` (${outcome.lineSpanSummary})` : "";
|
|
784
|
+
return `${p.relPath}${span}`;
|
|
785
|
+
});
|
|
786
|
+
return {
|
|
787
|
+
content: [{ type: "text", text: `Successfully applied edits to ${preparedList.length} files: ${summaries.join(", ")}.` }],
|
|
788
|
+
details: { multiFile: true, count: preparedList.length, files: preparedList.map((p) => p.relPath) },
|
|
789
|
+
};
|
|
563
790
|
});
|
|
564
791
|
}
|
|
565
792
|
|
|
@@ -644,5 +871,5 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
644
871
|
},
|
|
645
872
|
};
|
|
646
873
|
|
|
647
|
-
pi.registerTool(editToolDefinition);
|
|
874
|
+
pi.registerTool(markReturnedErrors(editToolDefinition));
|
|
648
875
|
}
|