@floydous/pi-agent-kernel 0.6.0 → 0.6.2

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.
@@ -1,12 +1,15 @@
1
1
  import * as path from "node:path";
2
2
  import type { SearchHit } from "../retrieval/search_index";
3
3
  import { tokenizeCode } from "../retrieval/search_bm25";
4
+ import { isTestPath } from "../retrieval/tag_extractor";
4
5
 
5
6
  export const CODE_SEARCH_MODES = ["auto", "full", "preview", "summary"] as const;
6
7
  export type CodeSearchMode = (typeof CODE_SEARCH_MODES)[number];
7
8
 
8
9
  /** Maximum automatic response size in characters (before the tool footer). */
9
10
  export const AUTO_OUTPUT_BUDGET = 8_000;
11
+ /** Hard safety cap in characters for explicit `mode: "full"` responses. */
12
+ export const FULL_OUTPUT_BUDGET = 12_000;
10
13
 
11
14
  const PREVIEW_LINE_LIMIT = 12;
12
15
  const PREVIEW_CHAR_LIMIT = 1_400;
@@ -139,6 +142,7 @@ interface BudgetEntry {
139
142
  function applyBudget(
140
143
  entries: BudgetEntry[],
141
144
  budget: number,
145
+ omissionHint: "full" | "read" = "full",
142
146
  ): { text: string; truncated: boolean; visibleRanges: VisibleCodeRange[] } {
143
147
  const selected: string[] = [];
144
148
  const visibleRanges: VisibleCodeRange[] = [];
@@ -174,7 +178,9 @@ function applyBudget(
174
178
  }
175
179
 
176
180
  if (omitted > 0) {
177
- const notice = `... ${omitted} additional match${omitted === 1 ? "" : "es"} omitted; use mode: "full" or a narrower query to inspect them ...`;
181
+ const notice = omissionHint === "read"
182
+ ? `... ${omitted} additional match${omitted === 1 ? "" : "es"} omitted (output cap); use read({ path, offset, limit }) or a narrower query to inspect them ...`
183
+ : `... ${omitted} additional match${omitted === 1 ? "" : "es"} omitted; use mode: "full" or a narrower query to inspect them ...`;
178
184
  const separator = selected.length > 0 ? "\n\n" : "";
179
185
  const remaining = Math.max(0, budget - used - separator.length);
180
186
  if (remaining > 0) {
@@ -200,6 +206,11 @@ function resolveAutoMode(hits: SearchHit[]): Exclude<CodeSearchMode, "auto"> | "
200
206
  * response. Automatic mode is context-preserving: it previews a small number
201
207
  * of top hits, summarizes the rest, and enforces a total response budget.
202
208
  */
209
+ function mixedPrefix(hitCount: number): string {
210
+ const previewCount = Math.min(AUTO_PREVIEW_HIT_LIMIT, hitCount);
211
+ return `${hitCount} matches returned; first ${previewCount} shown as previews, remaining ${hitCount - previewCount} summarized.\n\n`;
212
+ }
213
+
203
214
  function decorateResult(
204
215
  result: FormattedCodeSearchResults,
205
216
  requestedMode: CodeSearchMode,
@@ -209,10 +220,7 @@ function decorateResult(
209
220
  return result;
210
221
  }
211
222
 
212
- const notice = result.mode === "mixed"
213
- ? `${hitCount} matches returned; first ${Math.min(AUTO_PREVIEW_HIT_LIMIT, hitCount)} shown as previews, remaining ${hitCount - Math.min(AUTO_PREVIEW_HIT_LIMIT, hitCount)} summarized.`
214
- : "";
215
- const prefix = notice ? `${notice}\n\n` : "";
223
+ const prefix = result.mode === "mixed" ? mixedPrefix(hitCount) : "";
216
224
  const available = Math.max(0, AUTO_OUTPUT_BUDGET - prefix.length);
217
225
  const boundedText = clipToBudget(result.text, available);
218
226
  const finalClipped = boundedText.length < result.text.length;
@@ -224,19 +232,50 @@ function decorateResult(
224
232
  };
225
233
  }
226
234
 
235
+ export interface FormatCodeSearchOptions {
236
+ filePattern?: string;
237
+ separateTests?: boolean;
238
+ }
239
+
227
240
  /**
228
- * Format search hits for the model. Explicit full mode preserves the legacy
229
- * response. Automatic mode is context-preserving: it previews a small number
230
- * of top hits, summarizes the rest, and enforces a total response budget.
241
+ * Format search hits for the model. Explicit full mode renders complete bodies
242
+ * up to FULL_OUTPUT_BUDGET and summarizes appended bonus test hits when tests
243
+ * were not targeted. Automatic mode previews top hits and summarizes the rest
244
+ * within AUTO_OUTPUT_BUDGET.
231
245
  */
232
246
  export function formatCodeSearchResults(
233
247
  hits: SearchHit[],
234
248
  query: string,
235
249
  requestedMode: CodeSearchMode = "auto",
250
+ options: FormatCodeSearchOptions = {},
236
251
  ): FormattedCodeSearchResults {
237
252
  const autoMode = requestedMode === "auto" ? resolveAutoMode(hits) : requestedMode;
238
253
 
239
254
  if (autoMode === "full") {
255
+ if (requestedMode === "full") {
256
+ const targetsTests =
257
+ /\b(tests?|specs?)\b/i.test(query) ||
258
+ /test|spec/i.test(options.filePattern ?? "");
259
+ const summarizeBonusTests = Boolean(options.separateTests && !targetsTests);
260
+ const entries: BudgetEntry[] = hits.map((hit) => {
261
+ const isBonusTest =
262
+ summarizeBonusTests &&
263
+ (isTestPath(hit.chunk.filePath) || hit.chunk.kind === "test");
264
+ if (isBonusTest) {
265
+ return { text: summaryHit(hit) };
266
+ }
267
+ return {
268
+ text: fullHit(hit),
269
+ visibleRange: {
270
+ chunkId: hit.chunk.id,
271
+ startLine: hit.chunk.startLine,
272
+ endLine: hit.chunk.endLine,
273
+ },
274
+ };
275
+ });
276
+ const bounded = applyBudget(entries, FULL_OUTPUT_BUDGET, "read");
277
+ return { ...bounded, mode: "full" };
278
+ }
240
279
  return decorateResult(
241
280
  {
242
281
  text: hits.map(fullHit).join("\n\n"),
@@ -277,6 +316,7 @@ export function formatCodeSearchResults(
277
316
  const remainingSummary = hits
278
317
  .slice(AUTO_PREVIEW_HIT_LIMIT)
279
318
  .map((hit) => ({ text: summaryHit(hit) }));
280
- const bounded = applyBudget([...topPreview, ...remainingSummary], AUTO_OUTPUT_BUDGET);
319
+ const mixedBudget = Math.max(0, AUTO_OUTPUT_BUDGET - mixedPrefix(hits.length).length);
320
+ const bounded = applyBudget([...topPreview, ...remainingSummary], mixedBudget);
281
321
  return decorateResult({ ...bounded, mode: "mixed" }, requestedMode, hits.length);
282
322
  }
@@ -10,13 +10,13 @@ export function registerCodeSearchTool(
10
10
  pi: ExtensionAPI,
11
11
  deps: SearchDeps,
12
12
  ): void {
13
- // 5.5 Tool: `code_search` (Local Hybrid BM25 + Semantic AST Code Search)
13
+ // 5.5 Tool: `code_search` (Local AST-Chunk BM25 + Profile-Dependent Semantic Code Search)
14
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. 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
- promptSnippet: "Search codebase conceptually or by keywords via hybrid AST index",
18
+ "AST-chunk BM25 keyword search across source code (with neural semantic fusion when the active profile enables embeddings). Use when locating features, workflows, UI behaviors, or architecture without known symbol names or file paths. Do NOT use for exact string literals, call-sites, or non-code files; use bash (rg -n) instead.",
19
+ promptSnippet: "Search code chunks by mechanism keywords or concepts (BM25, plus vectors in full/auto profile)",
20
20
  renderShell: "default",
21
21
  parameters: Type.Object({
22
22
  query: Type.String({
@@ -29,7 +29,23 @@ export function registerCodeSearchTool(
29
29
  ),
30
30
  limit: Type.Optional(
31
31
  Type.Number({
32
- description: "Max results (default: 5, max: 15)",
32
+ minimum: 1,
33
+ maximum: 15,
34
+ description: "Max results (default: 5, range: 1-15)",
35
+ }),
36
+ ),
37
+ mode: Type.Optional(
38
+ Type.Unsafe<"auto" | "full" | "preview" | "summary">({
39
+ type: "string",
40
+ enum: ["auto", "full", "preview", "summary"],
41
+ description: "Output detail level: 'auto' (adaptive, recommended), 'full' (complete bodies for top source hits, capped at 12 KB), 'preview' (compact snippets), or 'summary' (headers only)",
42
+ }),
43
+ ),
44
+ rrf_k: Type.Optional(
45
+ Type.Number({
46
+ minimum: 1,
47
+ maximum: 200,
48
+ description: "Optional Reciprocal Rank Fusion smoothing constant (1-200, default: 60)",
33
49
  }),
34
50
  ),
35
51
  }),
@@ -108,9 +124,14 @@ export function registerCodeSearchTool(
108
124
  // Blame the filter, not the query, when it excludes every indexed file (e.g. "README": docs are not indexed).
109
125
  const filterExcludesIndex = params.file_pattern && indexStatus && indexStatus.chunkCount > 0 &&
110
126
  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.)`;
127
+ let message: string;
128
+ if (filterExcludesIndex) {
129
+ message = `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.`;
130
+ } else if (indexStatus?.effectiveProfile === "full") {
131
+ message = `No code chunks found matching "${query}". (Engine: Full [Neural RRF]. Tips: Try broader conceptual intent phrases if exact keywords failed; use 'rg' for exact text literals.)`;
132
+ } else {
133
+ message = `No code chunks found matching "${query}". (Engine: Lean [BM25 lexical]. Tips: Query with mechanism keywords or identifier patterns likely in source code; use 'rg' for exact text literals.)`;
134
+ }
114
135
  return {
115
136
  content: [
116
137
  {
@@ -118,7 +139,7 @@ export function registerCodeSearchTool(
118
139
  text: `${coverageNotice}${grammarNotice}${vectorNotice}${message}`,
119
140
  },
120
141
  ],
121
- details: { count: 0 },
142
+ details: { count: 0, effectiveProfile: indexStatus?.effectiveProfile || "lean" },
122
143
  };
123
144
  }
124
145
 
@@ -126,38 +147,41 @@ export function registerCodeSearchTool(
126
147
  hits,
127
148
  query,
128
149
  requestedMode as CodeSearchMode,
150
+ { filePattern: params.file_pattern, separateTests: true },
129
151
  );
130
152
  const sessionId = deps.getSessionId(ctx);
131
153
  const hitById = new Map(hits.map((hit) => [hit.chunk.id, hit]));
132
154
  const visibleIds = new Set<string>();
133
- for (const range of formatted.visibleRanges) {
134
- const hit = hitById.get(range.chunkId);
135
- if (!hit) continue;
136
- visibleIds.add(range.chunkId);
137
- globalEpistemicGuard.recordFileRead(
138
- hit.chunk.absolutePath,
139
- sessionId,
140
- ctx.cwd,
141
- undefined,
142
- {
143
- coverage: {
144
- complete: false,
145
- ranges: [{ startLine: range.startLine, endLine: range.endLine }],
155
+ globalEpistemicGuard.withBatchPersist(sessionId, ctx.cwd, () => {
156
+ for (const range of formatted.visibleRanges) {
157
+ const hit = hitById.get(range.chunkId);
158
+ if (!hit) continue;
159
+ visibleIds.add(range.chunkId);
160
+ globalEpistemicGuard.recordFileRead(
161
+ hit.chunk.absolutePath,
162
+ sessionId,
163
+ ctx.cwd,
164
+ undefined,
165
+ {
166
+ coverage: {
167
+ complete: false,
168
+ ranges: [{ startLine: range.startLine, endLine: range.endLine }],
169
+ },
170
+ provenance: "code_search",
171
+ query,
146
172
  },
147
- provenance: "code_search",
148
- query,
149
- },
150
- );
151
- }
152
- for (const hit of hits) {
153
- if (visibleIds.has(hit.chunk.id)) continue;
154
- globalEpistemicGuard.recordFileSearched(
155
- hit.chunk.absolutePath,
156
- sessionId,
157
- ctx.cwd,
158
- { coverage: { complete: false, ranges: [] }, provenance: "code_search", query },
159
- );
160
- }
173
+ );
174
+ }
175
+ for (const hit of hits) {
176
+ if (visibleIds.has(hit.chunk.id)) continue;
177
+ globalEpistemicGuard.recordFileSearched(
178
+ hit.chunk.absolutePath,
179
+ sessionId,
180
+ ctx.cwd,
181
+ { coverage: { complete: false, ranges: [] }, provenance: "code_search", query },
182
+ );
183
+ }
184
+ });
161
185
 
162
186
  return {
163
187
  content: [
@@ -168,6 +192,7 @@ export function registerCodeSearchTool(
168
192
  ],
169
193
  details: {
170
194
  count: hits.length,
195
+ effectiveProfile: indexStatus?.effectiveProfile || "lean",
171
196
  mode: formatted.mode,
172
197
  requestedMode,
173
198
  truncated: formatted.truncated,
@@ -185,7 +185,7 @@ function preflightFileEdit(
185
185
  if (!preflight.success) {
186
186
  if (preflight.isAmbiguous) {
187
187
  return {
188
- error: `[EDIT FAILED] Ambiguous Search Block in '${relPath}': ${preflight.error} Please provide more surrounding context lines to make the match unique.`,
188
+ error: `[EDIT FAILED] Ambiguous Search Block in '${relPath}': ${preflight.error}`,
189
189
  };
190
190
  }
191
191
  return {
@@ -207,7 +207,7 @@ function preflightFileEdit(
207
207
  if (!preflight.success) {
208
208
  if (preflight.isAmbiguous) {
209
209
  return {
210
- error: `[EDIT FAILED] Block ${i + 1}/${edits.length} is ambiguous in '${relPath}': ${preflight.error} Please provide more surrounding context lines.`,
210
+ error: `[EDIT FAILED] Block ${i + 1}/${edits.length} is ambiguous in '${relPath}': ${preflight.error}`,
211
211
  };
212
212
  }
213
213
  return {
@@ -259,6 +259,7 @@ async function applyPreparedEdit(
259
259
  const editingMode = config?.editing?.mode ?? "smart_anchor";
260
260
  const autoHeal = editingMode !== "standard";
261
261
  const syntaxGate = options.syntaxGate ?? config?.editing?.syntax_gate ?? (editingMode === "standard" ? "block" : "warn");
262
+ const execTimeoutMs = config?.safety?.exec_timeout_ms;
262
263
  // The syntax check uses tree-sitter when the grammar is loaded (see checkSyntaxContent).
263
264
  await TreeSitterEngine.getInstance().loadLanguages([path.extname(resolvedPath).toLowerCase()]);
264
265
 
@@ -269,9 +270,9 @@ async function applyPreparedEdit(
269
270
 
270
271
  let patchRes: ReturnType<typeof applySurgicalPatch>;
271
272
  if (isAnchorMode) {
272
- patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks, { syntaxGate });
273
+ patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks, { syntaxGate, execTimeoutMs });
273
274
  } else if (hasMultiBlock) {
274
- patchRes = applyMultiBlockPatch(resolvedPath, item.edits, { autoHeal, syntaxGate });
275
+ patchRes = applyMultiBlockPatch(resolvedPath, item.edits, { autoHeal, syntaxGate, execTimeoutMs });
275
276
  } else if (hasSingleBlock) {
276
277
  const singleOpt = {
277
278
  startLine: item.start_line,
@@ -282,6 +283,7 @@ async function applyPreparedEdit(
282
283
  ...singleOpt,
283
284
  autoHeal,
284
285
  syntaxGate,
286
+ execTimeoutMs,
285
287
  });
286
288
  } else {
287
289
  return { success: false, mutated: false, error: `[EDIT ERROR] Must provide either smart anchors or 'search' and 'replace' strings.` };
@@ -313,7 +315,7 @@ async function applyPreparedEdit(
313
315
 
314
316
  await deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
315
317
 
316
- const verification = await verifyEditedFile(resolvedPath, undefined, patchRes.syntax);
318
+ const verification = await verifyEditedFile(resolvedPath, undefined, patchRes.syntax, execTimeoutMs);
317
319
 
318
320
  const lineSpanSummary = computeLineSpanSummary(prepared, patchRes);
319
321
  const statusText = renderPostEditVerification(verification, undefined, relPath, lineSpanSummary);
@@ -401,7 +403,7 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
401
403
  const benchmarkMethod = process.env.PI_EDIT_METHOD?.toLowerCase();
402
404
  let editToolParameters: any;
403
405
  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).";
406
+ "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).";
405
407
 
406
408
  switch (benchmarkMethod) {
407
409
  case "line-range":
@@ -444,53 +446,158 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
444
446
  editToolDescription = "Edit code with search/replace or line range; use search first.";
445
447
  break;
446
448
  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
- );
449
+ const blockEditSchema = Type.Object({
450
+ search: Type.String({ description: "Exact block to replace" }),
451
+ replace: Type.String({ description: "Replacement text (empty string to delete)" }),
452
+ line_hint: Type.Optional(
453
+ Type.Number({
454
+ minimum: 1,
455
+ description: "1-based line number hint for disambiguating matching blocks",
456
+ }),
457
+ ),
458
+ });
455
459
 
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" }),
475
- ),
476
- },
477
- { additionalProperties: true },
478
- ),
479
- { description: "Multi-file edits" },
480
- ),
460
+ editToolParameters = Type.Object({
461
+ path: Type.Optional(Type.String({ description: "Workspace-relative or absolute file path to edit" })),
462
+ edits: Type.Optional(
463
+ Type.Array(blockEditSchema, {
464
+ description: "Ordered array of targeted search/replace blocks applied atomically to this file",
465
+ }),
466
+ ),
467
+ files: Type.Optional(
468
+ Type.Array(
469
+ Type.Object({
470
+ path: Type.String({ description: "Workspace-relative or absolute file path to edit" }),
471
+ edits: Type.Array(blockEditSchema, {
472
+ description: "Ordered array of targeted replacements for this file",
473
+ }),
474
+ }),
475
+ { description: "Atomic multi-file edits; each entry targets a distinct file path" },
481
476
  ),
482
- },
483
- { additionalProperties: true },
484
- );
477
+ ),
478
+ });
485
479
  break;
486
480
  }
487
481
  const editToolDefinition: any = {
488
482
  name: "edit",
489
483
  label: "Code Editor",
490
484
  description: editToolDescription,
491
- promptSnippet: "Edit code using search/replace (optional line_hint), multi-block 'edits', or multi-file 'files' (preserves CRLF/LF)",
485
+ promptSnippet: "Edit code using targeted 'edits' blocks (search/replace, optional line_hint) or atomic multi-file 'files' (preserves CRLF/LF)",
492
486
  renderShell: "default",
493
487
  parameters: editToolParameters,
488
+ prepareArguments(args: any) {
489
+ if (!args || typeof args !== "object" || Array.isArray(args)) return args;
490
+
491
+ if (benchmarkMethod) {
492
+ const normalizeBenchmarkItem = (item: any) => {
493
+ if (!item || typeof item !== "object" || Array.isArray(item)) return item;
494
+ let out = item;
495
+ if (out.replace === null) out = { ...out, replace: "" };
496
+ if (Array.isArray(out.edits)) {
497
+ out = {
498
+ ...out,
499
+ edits: out.edits.map((e: any) =>
500
+ e && typeof e === "object" && e.replace === null ? { ...e, replace: "" } : e,
501
+ ),
502
+ };
503
+ }
504
+ return out;
505
+ };
506
+ let prepared = normalizeBenchmarkItem(args);
507
+ if (Array.isArray(prepared.files)) {
508
+ prepared = { ...prepared, files: prepared.files.map(normalizeBenchmarkItem) };
509
+ }
510
+ return prepared;
511
+ }
512
+
513
+ const isPlainObject = (v: unknown): v is Record<string, any> =>
514
+ Boolean(v && typeof v === "object" && !Array.isArray(v));
515
+
516
+ const parseEditsField = (raw: unknown): unknown => {
517
+ if (typeof raw === "string") {
518
+ try {
519
+ const parsed = JSON.parse(raw);
520
+ if (Array.isArray(parsed)) return parsed;
521
+ if (isPlainObject(parsed)) return [parsed];
522
+ } catch {
523
+ return raw;
524
+ }
525
+ }
526
+ if (isPlainObject(raw)) return [raw];
527
+ return raw;
528
+ };
529
+
530
+ const normalizeBlock = (e: any): any => {
531
+ if (!isPlainObject(e)) return e;
532
+ const search = e.search ?? e.oldText ?? e.old_text ?? e.old;
533
+ const rawReplace =
534
+ e.replace === null ? "" : (e.replace ?? e.replacement ?? e.newText ?? e.new_text ?? e.new);
535
+ const replace = rawReplace === null ? "" : rawReplace;
536
+ const { oldText: _ot, old_text: _os, old: _o, newText: _nt, new_text: _ns, new: _n, replacement: _r, ...rest } = e;
537
+ const out: Record<string, any> = { ...rest };
538
+ if (search !== undefined) out.search = search;
539
+ if (replace !== undefined) out.replace = replace;
540
+ return out;
541
+ };
542
+
543
+ const normalizeFileEntry = (item: any): any => {
544
+ if (!isPlainObject(item)) return item;
545
+ const out: Record<string, any> = { ...item };
546
+ if (out.edits !== undefined) {
547
+ const unwrapped = parseEditsField(out.edits);
548
+ out.edits = Array.isArray(unwrapped) ? unwrapped.map(normalizeBlock) : unwrapped;
549
+ }
550
+ const singleSearch = out.search ?? out.oldText ?? out.old_text ?? out.old;
551
+ const rawSingleReplace =
552
+ out.replace === null ? "" : (out.replace ?? out.replacement ?? out.newText ?? out.new_text ?? out.new);
553
+ const singleReplace = rawSingleReplace === null ? "" : rawSingleReplace;
554
+
555
+ // Fold top-level search/replace only when both are strings; preserve missing-replace fail-closed errors.
556
+ if (typeof singleSearch === "string" && typeof singleReplace === "string") {
557
+ const foldedBlock: Record<string, any> = {
558
+ search: singleSearch,
559
+ replace: singleReplace,
560
+ ...(out.line_hint !== undefined ? { line_hint: out.line_hint } : {}),
561
+ };
562
+ out.edits = Array.isArray(out.edits) ? [...out.edits, foldedBlock] : [foldedBlock];
563
+ delete out.search;
564
+ delete out.replace;
565
+ delete out.line_hint;
566
+ delete out.oldText;
567
+ delete out.old_text;
568
+ delete out.old;
569
+ delete out.newText;
570
+ delete out.new_text;
571
+ delete out.new;
572
+ delete out.replacement;
573
+ } else if (out.replace === null) {
574
+ out.replace = "";
575
+ }
576
+ return out;
577
+ };
578
+
579
+ const unwrappedTopEdits = args.edits !== undefined ? parseEditsField(args.edits) : undefined;
580
+ if (
581
+ Array.isArray(unwrappedTopEdits) &&
582
+ unwrappedTopEdits.length > 0 &&
583
+ unwrappedTopEdits.some((e: any) => isPlainObject(e) && typeof e.path === "string")
584
+ ) {
585
+ const { edits: _ignoredEdits, ...rest } = args;
586
+ return {
587
+ ...rest,
588
+ files: unwrappedTopEdits.map(normalizeFileEntry),
589
+ };
590
+ }
591
+
592
+ let prepared = normalizeFileEntry(args);
593
+ if (Array.isArray(prepared.files)) {
594
+ prepared = {
595
+ ...prepared,
596
+ files: prepared.files.map(normalizeFileEntry),
597
+ };
598
+ }
599
+ return prepared;
600
+ },
494
601
  async execute(
495
602
  _toolCallId: string,
496
603
  params: any,
@@ -102,7 +102,7 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
102
102
  const benchmarkMethod = ["line-range", "search-replace", "hash-anchor", "adaptive"].includes(editMethod || "") ? editMethod : undefined;
103
103
  const readMode = process.env.PI_READ_MODE?.toLowerCase();
104
104
  let readToolDescription =
105
- "Read file contents with 50KB / 2,000-line caps. Use when inspecting code around known line coordinates, reviewing exact file contents, or reading multiple files via 'paths'. Defaults to 250 lines when limit is omitted. Do NOT use read for finding files or symbols; use code_search or bash (find, rg) instead.";
105
+ "Read file contents with 50KB / 2,000-line caps. Use when inspecting code around known line coordinates, reviewing exact file contents, or reading multiple files via 'paths'. Defaults to 250 lines when limit is omitted. Do NOT use read for finding files or symbols; use code_search (when enabled) or bash (rg, find) instead.";
106
106
  switch (benchmarkMethod) {
107
107
  case "line-range":
108
108
  readToolDescription = "Read source with line numbers for numeric line-range edits.";
@@ -135,17 +135,19 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
135
135
  ),
136
136
  offset: Type.Optional(
137
137
  Type.Number({
138
+ minimum: 1,
138
139
  description: "1-based starting line number for windowed reads (best when examining code around an exact line coordinate from grep or test failures)",
139
140
  }),
140
141
  ),
141
142
  limit: Type.Optional(
142
143
  Type.Number({
144
+ minimum: 1,
143
145
  description: "Maximum number of lines to read starting from 'offset' (default: 250 for unconstrained reads; keep <= 60 for narrow inspection)",
144
146
  }),
145
147
  ),
146
148
  anchors: Type.Optional(
147
149
  Type.Boolean({
148
- description: "Narrow ranges (<100 lines) with LINE#HASH│ anchors (default: false, plain text)",
150
+ description: "Emit LINE#HASH│ prefixes on narrow ranges (<100 lines) for positional line disambiguation (default: false, plain text)",
149
151
  }),
150
152
  ),
151
153
  raw: Type.Optional(
@@ -154,6 +156,24 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
154
156
  }),
155
157
  ),
156
158
  }),
159
+ prepareArguments(args: any) {
160
+ if (!args || typeof args !== "object" || Array.isArray(args)) return args;
161
+ let out: Record<string, any> | null = null;
162
+ if (typeof args.paths === "string") {
163
+ const trimmed = args.paths.trim();
164
+ out = { ...args, paths: trimmed ? [trimmed] : [] };
165
+ }
166
+ if (Array.isArray(args.path)) {
167
+ const coerced = args.path.filter((p: unknown): p is string => typeof p === "string" && p.trim().length > 0);
168
+ const base = out ?? { ...args };
169
+ delete base.path;
170
+ if (!Array.isArray(base.paths) || base.paths.length === 0) {
171
+ base.paths = coerced;
172
+ }
173
+ out = base;
174
+ }
175
+ return out ?? args;
176
+ },
157
177
  async execute(
158
178
  _toolCallId: string,
159
179
  params: any,
@@ -220,6 +240,7 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
220
240
  let hasAnySuccess = false;
221
241
  let cumulativeBytes = 0;
222
242
 
243
+ globalEpistemicGuard.withBatchPersist(deps.getSessionId(ctx), ctx.cwd, () => {
223
244
  for (let i = 0; i < pathsToRead.length; i++) {
224
245
  const filePath = pathsToRead[i];
225
246
  if (cumulativeBytes >= MAX_BATCH_BYTES) {
@@ -338,6 +359,7 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
338
359
  results.push(`=== file: ${relPath} ===\nError reading file: ${err.message}`);
339
360
  }
340
361
  }
362
+ });
341
363
 
342
364
  if (targetPaths.length > MAX_BATCH_PATHS) {
343
365
  results.push(`[...] Note: Truncated to first ${MAX_BATCH_PATHS} files (${targetPaths.length - MAX_BATCH_PATHS} omitted).`);
package/src/ui/footer.ts CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { isAbsolute, relative, resolve, sep } from "node:path";
9
9
  import { getSearchConfig } from "../retrieval/search_config";
10
- import { loadKernelConfig } from "../config";
10
+ import { loadKernelConfig, type KernelConfig } from "../config";
11
11
  import { truncateToWidth, visibleWidth } from "./tui_utils";
12
12
 
13
13
  export { stripAnsi, truncateToWidth, visibleWidth } from "./tui_utils";
@@ -147,11 +147,12 @@ export function renderFooter(
147
147
  footerData: FooterDataProvider,
148
148
  width: number,
149
149
  searchIndex?: any,
150
+ config?: KernelConfig,
150
151
  ): string[] {
151
152
  const parts: string[] = [];
152
153
  const rawCwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
153
- const config = loadKernelConfig(rawCwd);
154
- if (!config.ui.enable_pastel_footer) {
154
+ const resolvedConfig = config ?? loadKernelConfig(rawCwd);
155
+ if (!resolvedConfig.ui.enable_pastel_footer) {
155
156
  return [truncateToWidth(formatCwd(rawCwd), width, "...")];
156
157
  }
157
158