@floydous/pi-agent-kernel 0.5.0 → 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.
Files changed (36) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +15 -6
  2. package/CHANGELOG.md +51 -0
  3. package/README.md +2 -3
  4. package/config.example.toml +1 -0
  5. package/docs/configuration.md +1 -1
  6. package/docs/editing-and-verification.md +20 -5
  7. package/docs/podman-linux-checks.md +24 -0
  8. package/docs/release-discipline.md +10 -0
  9. package/docs/retrieval.md +14 -11
  10. package/grammars/tree-sitter-html.wasm +0 -0
  11. package/package.json +2 -2
  12. package/src/config/agent_kernel_command.ts +59 -593
  13. package/src/config/kernel_config.ts +24 -2
  14. package/src/editing/patch.ts +48 -21
  15. package/src/editing/post_edit_verification.ts +8 -4
  16. package/src/editing/smart_anchor.ts +2 -1
  17. package/src/editing/syntax-verify.ts +73 -220
  18. package/src/index.ts +21 -196
  19. package/src/retrieval/html_chunker.ts +526 -0
  20. package/src/retrieval/search_bm25.ts +36 -27
  21. package/src/retrieval/search_chunker.ts +68 -6
  22. package/src/retrieval/search_config.ts +17 -34
  23. package/src/retrieval/search_embedder.ts +11 -29
  24. package/src/retrieval/search_index.ts +307 -145
  25. package/src/retrieval/search_modal.ts +1209 -222
  26. package/src/retrieval/tag_extractor.ts +1 -1
  27. package/src/retrieval/tree_sitter_engine.ts +103 -4
  28. package/src/retrieval/workspace_walker.ts +72 -0
  29. package/src/safety/host_environment.ts +180 -0
  30. package/src/safety/output_clamper.ts +83 -19
  31. package/src/tools/code_search_output.ts +9 -1
  32. package/src/tools/code_search_tool.ts +25 -10
  33. package/src/tools/context.ts +15 -0
  34. package/src/tools/edit_tool.ts +182 -60
  35. package/src/tools/read_tool.ts +245 -38
  36. package/src/tools/stream_reader.ts +206 -0
@@ -3,7 +3,7 @@ import { Type } from "typebox";
3
3
  import { Text, makeOutputText } from "../ui/tui_utils";
4
4
  import { globalEpistemicGuard } from "../safety/epistemic_guard";
5
5
  import { formatCodeSearchResults, CODE_SEARCH_MODES, type CodeSearchMode } from "./code_search_output";
6
- import type { SearchDeps } from "./context";
6
+ import { markReturnedErrors, type SearchDeps } from "./context";
7
7
 
8
8
  /** Extracted from index.ts — registers the `code_search` tool. */
9
9
  export function registerCodeSearchTool(
@@ -11,11 +11,11 @@ export function registerCodeSearchTool(
11
11
  deps: SearchDeps,
12
12
  ): void {
13
13
  // 5.5 Tool: `code_search` (Local Hybrid BM25 + Semantic AST Code Search)
14
- pi.registerTool({
14
+ pi.registerTool(markReturnedErrors({
15
15
  name: "code_search",
16
16
  label: "Codebase Search",
17
17
  description:
18
- "Fast BM25 & AST semantic search across code chunks. Best for conceptual questions, finding unfamiliar features, and searching when exact symbol names or file paths are unknown (prefer rg for exact text literals).",
18
+ "Fast BM25 & AST semantic search across code chunks. Use when locating features, workflows, UI behaviors, or architecture without known symbol names or file paths (prefer rg for exact text literals and non-code files). Do NOT use for finding exact string literals or call-sites; use rg -n instead.",
19
19
  promptSnippet: "Search codebase conceptually or by keywords via hybrid AST index",
20
20
  renderShell: "default",
21
21
  parameters: Type.Object({
@@ -24,7 +24,7 @@ export function registerCodeSearchTool(
24
24
  }),
25
25
  file_pattern: Type.Optional(
26
26
  Type.String({
27
- description: "Optional relative path substring filter",
27
+ description: "Optional relative path substring filter (e.g., 'src/auth', 'tests'). Omit for whole-workspace search. Do NOT guess paths.",
28
28
  }),
29
29
  ),
30
30
  limit: Type.Optional(
@@ -82,25 +82,40 @@ export function registerCodeSearchTool(
82
82
  limit,
83
83
  filePattern: params.file_pattern,
84
84
  rrfK: params.rrf_k,
85
+ separateTests: true,
85
86
  });
86
87
 
87
88
  const indexStatus = typeof index.getStatus === "function" ? index.getStatus() : undefined;
88
- const wantsVectors =
89
- indexStatus?.effectiveProfile === "hybrid" ||
90
- indexStatus?.effectiveProfile === "full";
89
+ const wantsVectors = indexStatus?.effectiveProfile === "full";
91
90
  const vectorNotice =
92
91
  wantsVectors &&
93
92
  indexStatus &&
94
93
  indexStatus.vectorCount < indexStatus.chunkCount
95
94
  ? `[Notice: Vector embeddings are incomplete (${indexStatus.vectorCount}/${indexStatus.chunkCount} chunks); searched via BM25]\n\n`
96
95
  : "";
96
+ const grammarIssues = indexStatus?.grammarIssues ?? [];
97
+ const grammarNotice = grammarIssues.length > 0
98
+ ? `[Notice: tree-sitter grammar unavailable for ${grammarIssues.map((issue) => `${issue.extensions.join(", ")} (${issue.reason})`).join("; ")}; code structure for those files is approximate]\n\n`
99
+ : "";
100
+ const notIndexed = indexStatus?.notIndexed;
101
+ const missingFiles = notIndexed ? notIndexed.source + notIndexed.test + notIndexed.vendored : 0;
102
+ const count = (n: number) => n.toLocaleString("en-US");
103
+ const coverageNotice = indexStatus && notIndexed && missingFiles > 0
104
+ ? `[Notice: index covers ${count(indexStatus.indexableFiles - missingFiles)} of ${indexStatus.walkTruncated ? "≥ " : ""}${count(indexStatus.indexableFiles)} indexable files (index limits); not indexed: ${(["source", "test", "vendored"] as const).filter((tier) => notIndexed[tier] > 0).map((tier) => `${count(notIndexed[tier])} ${tier}`).join(", ")} (${indexStatus.notIndexedDirs.join(", ")}); use rg for those paths]\n\n`
105
+ : "";
97
106
 
98
107
  if (hits.length === 0) {
108
+ // Blame the filter, not the query, when it excludes every indexed file (e.g. "README": docs are not indexed).
109
+ const filterExcludesIndex = params.file_pattern && indexStatus && indexStatus.chunkCount > 0 &&
110
+ typeof index.hasIndexedFile === "function" && !index.hasIndexedFile(params.file_pattern);
111
+ const message = filterExcludesIndex
112
+ ? `No indexed file path contains "${params.file_pattern}". code_search indexes source code only (not Markdown, JSON, YAML, TOML or other text files); use rg to search other files.`
113
+ : `No code chunks found matching "${query}". (Tips: Try broader or different terms, or 'rg' for exact text literals.)`;
99
114
  return {
100
115
  content: [
101
116
  {
102
117
  type: "text",
103
- text: `${vectorNotice}No code chunks found matching "${query}". (Tips: Try broader or different terms, or 'rg' for exact text literals.)`,
118
+ text: `${coverageNotice}${grammarNotice}${vectorNotice}${message}`,
104
119
  },
105
120
  ],
106
121
  details: { count: 0 },
@@ -148,7 +163,7 @@ export function registerCodeSearchTool(
148
163
  content: [
149
164
  {
150
165
  type: "text",
151
- text: `${vectorNotice}${formatted.text}`,
166
+ text: `${coverageNotice}${grammarNotice}${vectorNotice}${formatted.text}`,
152
167
  },
153
168
  ],
154
169
  details: {
@@ -184,5 +199,5 @@ export function registerCodeSearchTool(
184
199
  result.content?.find((c: any) => c.type === "text")?.text || "";
185
200
  return makeOutputText(`\n${theme.fg("toolOutput", output)}`);
186
201
  },
187
- });
202
+ }));
188
203
  }
@@ -12,6 +12,21 @@ export interface SessionDeps {
12
12
  invalidateSearchFile?: (cwd: string, filePath: string) => void | Promise<void>;
13
13
  }
14
14
 
15
+ /**
16
+ * pi flags a tool result as an error only when `execute` throws; a returned `isError` is dropped. Kernel tools return
17
+ * their failures, so copy the flag into `details.isError`, where the kernel's tool_result hook restores it.
18
+ */
19
+ export function markReturnedErrors<T extends { execute: (...args: any[]) => Promise<any> }>(tool: T): T {
20
+ const execute = tool.execute;
21
+ return {
22
+ ...tool,
23
+ async execute(...args: any[]) {
24
+ const result = await execute.apply(tool, args);
25
+ return result?.isError === true ? { ...result, details: { ...(result.details ?? {}), isError: true } } : result;
26
+ },
27
+ };
28
+ }
29
+
15
30
  export interface SearchDeps extends SessionDeps {
16
31
  /** Lazily create/access the workspace hybrid search index singleton. */
17
32
  getSearchIndex: (
@@ -25,7 +25,8 @@ import {
25
25
  resolveUserPath,
26
26
  } from "../safety/epistemic_guard";
27
27
  import { loadKernelConfig } from "../config";
28
- import type { SessionDeps } from "./context";
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
- const search = e.search ?? e.oldText ?? e.old_text ?? e.old;
83
- const replace = e.replace ?? e.newText ?? e.new_text ?? e.new;
84
- return { ...e, search, replace };
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
- const singleSearch = item.search ?? item.oldText ?? item.old_text ?? item.old;
88
- const singleReplace = item.replace ?? item.newText ?? item.new_text ?? item.new;
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(item.lines);
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: item.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, anchorPreflight, targetRanges } = prepared;
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
- let deltaLines = 0;
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 statusText = renderPostEditVerification(verification, undefined, relPath);
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 with search/replace, multi-block 'edits', or multi-file 'files'. Valid after read or exact rg search.";
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).";
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,34 +444,35 @@ 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:
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
+
358
456
  editToolParameters = Type.Object(
359
457
  {
360
458
  path: Type.Optional(Type.String({ description: "Path to file to edit" })),
361
459
  search: Type.Optional(Type.String({ description: "Exact block to replace" })),
362
- replace: Type.Optional(Type.String({ description: "Replacement text" })),
460
+ replace: Type.Optional(Type.String({ description: "Replacement text (empty string to delete)" })),
363
461
  line_hint: Type.Optional(Type.Number({ description: "Line hint for disambiguation" })),
364
462
  edits: Type.Optional(
365
- Type.Array(
366
- Type.Object(
367
- {
368
- search: Type.Optional(Type.String()),
369
- replace: Type.Optional(Type.String()),
370
- line_hint: Type.Optional(Type.Number()),
371
- },
372
- { additionalProperties: true },
373
- ),
374
- { description: "Targeted replacements" },
375
- ),
463
+ Type.Array(blockEditSchema, { description: "Targeted replacements" }),
376
464
  ),
377
465
  files: Type.Optional(
378
466
  Type.Array(
379
467
  Type.Object(
380
468
  {
381
- path: Type.String(),
382
- search: Type.Optional(Type.String()),
383
- replace: Type.Optional(Type.String()),
384
- line_hint: Type.Optional(Type.Number()),
385
- edits: Type.Optional(Type.Array(Type.Any())),
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" }),
475
+ ),
386
476
  },
387
477
  { additionalProperties: true },
388
478
  ),
@@ -398,7 +488,7 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
398
488
  name: "edit",
399
489
  label: "Code Editor",
400
490
  description: editToolDescription,
401
- promptSnippet: "Edit code using search/replace (optional line_hint), multi-block 'edits', or multi-file 'files'",
491
+ promptSnippet: "Edit code using search/replace (optional line_hint), multi-block 'edits', or multi-file 'files' (preserves CRLF/LF)",
402
492
  renderShell: "default",
403
493
  parameters: editToolParameters,
404
494
  async execute(
@@ -408,6 +498,34 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
408
498
  onUpdate: any,
409
499
  ctx: any,
410
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
+
411
529
  // Check for multi-file payload
412
530
  const fileEdits: any[] = [];
413
531
  if (params && typeof params === "object") {
@@ -555,11 +673,15 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
555
673
  };
556
674
  }
557
675
 
558
- const affectedPaths = preparedList.map((p) => p.relPath);
559
- return {
560
- content: [{ type: "text", text: `Successfully applied edits to ${affectedPaths.length} files: ${affectedPaths.join(", ")}.` }],
561
- details: { multiFile: true, count: affectedPaths.length, files: affectedPaths },
562
- };
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
+ };
563
685
  });
564
686
  }
565
687
 
@@ -644,5 +766,5 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
644
766
  },
645
767
  };
646
768
 
647
- pi.registerTool(editToolDefinition);
769
+ pi.registerTool(markReturnedErrors(editToolDefinition));
648
770
  }