@floydous/pi-agent-kernel 0.4.0 → 0.4.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.
- package/AGENT_KERNEL_SYS_PROMPT.md +8 -4
- package/CHANGELOG.md +40 -87
- package/README.md +39 -74
- package/config.example.toml +1 -1
- package/docs/retrieval.md +2 -0
- package/package.json +7 -6
- package/src/config/agent_kernel_command.ts +29 -14
- package/src/config/kernel_config.ts +175 -30
- package/src/context/session_repair.ts +166 -85
- package/src/editing/patch.ts +28 -16
- package/src/editing/smart_anchor.ts +13 -29
- package/src/editing/syntax-verify.ts +35 -11
- package/src/index.ts +161 -141
- package/src/lsp/lsp_client.ts +101 -20
- package/src/lsp/lsp_formatter.ts +57 -22
- package/src/lsp/lsp_installer.ts +272 -487
- package/src/lsp/lsp_manager.ts +1 -1
- package/src/lsp/lsp_registry.ts +75 -46
- package/src/retrieval/search_bm25.ts +5 -2
- package/src/retrieval/search_cache.ts +69 -0
- package/src/retrieval/search_chunker.ts +12 -9
- package/src/retrieval/search_config.ts +20 -8
- package/src/retrieval/search_embedder.ts +8 -16
- package/src/retrieval/search_index.ts +552 -121
- package/src/safety/atomic_write.ts +59 -20
- package/src/safety/epistemic_guard.ts +440 -67
- package/src/safety/output_clamper.ts +316 -76
- package/src/tools/code_search_output.ts +59 -23
- package/src/tools/code_search_tool.ts +42 -46
- package/src/tools/context.ts +15 -1
- package/src/tools/edit_tool.ts +114 -36
- package/src/tools/lsp_tool.ts +5 -2
- package/src/tools/read_tool.ts +44 -3
|
@@ -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
|
|
6
|
+
import { speculativeToolsEnabled, type SearchDeps } from "./context";
|
|
7
7
|
|
|
8
8
|
/** Extracted from index.ts — registers the `code_search` tool. */
|
|
9
9
|
export function registerCodeSearchTool(
|
|
@@ -48,25 +48,20 @@ export function registerCodeSearchTool(
|
|
|
48
48
|
isError: true,
|
|
49
49
|
};
|
|
50
50
|
}
|
|
51
|
-
|
|
52
|
-
const requestedMode = params.mode ?? "auto";
|
|
53
|
-
if (!(CODE_SEARCH_MODES as readonly string[]).includes(requestedMode)) {
|
|
51
|
+
if (deps.getConfig?.(ctx.cwd).retrieval.default_profile === "off") {
|
|
54
52
|
return {
|
|
55
|
-
content: [{
|
|
56
|
-
type: "text",
|
|
57
|
-
text: `[ERROR] Invalid mode "${String(requestedMode)}". Use auto, full, preview, or summary.`,
|
|
58
|
-
}],
|
|
53
|
+
content: [{ type: "text", text: "[ERROR] Code search is disabled for this workspace." }],
|
|
59
54
|
details: { count: 0 },
|
|
60
55
|
isError: true,
|
|
61
56
|
};
|
|
62
57
|
}
|
|
63
58
|
|
|
64
|
-
const
|
|
65
|
-
if (!
|
|
59
|
+
const requestedMode = params.mode ?? "auto";
|
|
60
|
+
if (!(CODE_SEARCH_MODES as readonly string[]).includes(requestedMode)) {
|
|
66
61
|
return {
|
|
67
62
|
content: [{
|
|
68
63
|
type: "text",
|
|
69
|
-
text: `[ERROR] Invalid
|
|
64
|
+
text: `[ERROR] Invalid mode "${String(requestedMode)}". Use auto, full, preview, or summary.`,
|
|
70
65
|
}],
|
|
71
66
|
details: { count: 0 },
|
|
72
67
|
isError: true,
|
|
@@ -87,41 +82,8 @@ export function registerCodeSearchTool(
|
|
|
87
82
|
limit,
|
|
88
83
|
filePattern: params.file_pattern,
|
|
89
84
|
rrfK: params.rrf_k,
|
|
90
|
-
scope,
|
|
91
85
|
});
|
|
92
86
|
|
|
93
|
-
const sessionId = deps.getSessionId(ctx);
|
|
94
|
-
for (const hit of hits) {
|
|
95
|
-
const chunkRange =
|
|
96
|
-
Number.isFinite(hit.chunk.startLine) && Number.isFinite(hit.chunk.endLine)
|
|
97
|
-
? [{ startLine: hit.chunk.startLine, endLine: hit.chunk.endLine }]
|
|
98
|
-
: [];
|
|
99
|
-
if (chunkRange.length > 0) {
|
|
100
|
-
globalEpistemicGuard.recordFileRead(
|
|
101
|
-
hit.chunk.absolutePath,
|
|
102
|
-
sessionId,
|
|
103
|
-
ctx.cwd,
|
|
104
|
-
undefined,
|
|
105
|
-
{
|
|
106
|
-
coverage: { complete: false, ranges: chunkRange },
|
|
107
|
-
provenance: "code_search",
|
|
108
|
-
query,
|
|
109
|
-
},
|
|
110
|
-
);
|
|
111
|
-
} else {
|
|
112
|
-
globalEpistemicGuard.recordFileSearched(
|
|
113
|
-
hit.chunk.absolutePath,
|
|
114
|
-
sessionId,
|
|
115
|
-
ctx.cwd,
|
|
116
|
-
{
|
|
117
|
-
coverage: { complete: false, ranges: [] },
|
|
118
|
-
provenance: "code_search",
|
|
119
|
-
query,
|
|
120
|
-
},
|
|
121
|
-
);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
87
|
const indexStatus = typeof index.getStatus === "function" ? index.getStatus() : undefined;
|
|
126
88
|
const wantsVectors =
|
|
127
89
|
indexStatus?.effectiveProfile === "hybrid" ||
|
|
@@ -138,7 +100,10 @@ export function registerCodeSearchTool(
|
|
|
138
100
|
content: [
|
|
139
101
|
{
|
|
140
102
|
type: "text",
|
|
141
|
-
text: `${vectorNotice}No code chunks found matching "${query}". (
|
|
103
|
+
text: `${vectorNotice}No code chunks found matching "${query}". (` +
|
|
104
|
+
(speculativeToolsEnabled(deps.getConfig, ctx.cwd)
|
|
105
|
+
? `Tips: Try 'ast_search' for exact symbol names or 'rg' for exact text literals.`
|
|
106
|
+
: `Tips: Try broader or different terms, or 'rg' for exact text literals.`),
|
|
142
107
|
},
|
|
143
108
|
],
|
|
144
109
|
details: { count: 0 },
|
|
@@ -150,6 +115,37 @@ export function registerCodeSearchTool(
|
|
|
150
115
|
query,
|
|
151
116
|
requestedMode as CodeSearchMode,
|
|
152
117
|
);
|
|
118
|
+
const sessionId = deps.getSessionId(ctx);
|
|
119
|
+
const hitById = new Map(hits.map((hit) => [hit.chunk.id, hit]));
|
|
120
|
+
const visibleIds = new Set<string>();
|
|
121
|
+
for (const range of formatted.visibleRanges) {
|
|
122
|
+
const hit = hitById.get(range.chunkId);
|
|
123
|
+
if (!hit) continue;
|
|
124
|
+
visibleIds.add(range.chunkId);
|
|
125
|
+
globalEpistemicGuard.recordFileRead(
|
|
126
|
+
hit.chunk.absolutePath,
|
|
127
|
+
sessionId,
|
|
128
|
+
ctx.cwd,
|
|
129
|
+
undefined,
|
|
130
|
+
{
|
|
131
|
+
coverage: {
|
|
132
|
+
complete: false,
|
|
133
|
+
ranges: [{ startLine: range.startLine, endLine: range.endLine }],
|
|
134
|
+
},
|
|
135
|
+
provenance: "code_search",
|
|
136
|
+
query,
|
|
137
|
+
},
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
for (const hit of hits) {
|
|
141
|
+
if (visibleIds.has(hit.chunk.id)) continue;
|
|
142
|
+
globalEpistemicGuard.recordFileSearched(
|
|
143
|
+
hit.chunk.absolutePath,
|
|
144
|
+
sessionId,
|
|
145
|
+
ctx.cwd,
|
|
146
|
+
{ coverage: { complete: false, ranges: [] }, provenance: "code_search", query },
|
|
147
|
+
);
|
|
148
|
+
}
|
|
153
149
|
|
|
154
150
|
return {
|
|
155
151
|
content: [
|
|
@@ -162,8 +158,8 @@ export function registerCodeSearchTool(
|
|
|
162
158
|
count: hits.length,
|
|
163
159
|
mode: formatted.mode,
|
|
164
160
|
requestedMode,
|
|
165
|
-
scope,
|
|
166
161
|
truncated: formatted.truncated,
|
|
162
|
+
visibleRanges: formatted.visibleRanges,
|
|
167
163
|
hits: hits.map((h) => ({
|
|
168
164
|
id: h.chunk.id,
|
|
169
165
|
score: h.rrfScore,
|
package/src/tools/context.ts
CHANGED
|
@@ -9,7 +9,21 @@ export interface SessionDeps {
|
|
|
9
9
|
/** Load runtime settings for the active workspace. */
|
|
10
10
|
getConfig?: (cwd: string) => import("../config").KernelConfig;
|
|
11
11
|
/** Mark a successfully mutated file stale in the workspace index. */
|
|
12
|
-
invalidateSearchFile?: (cwd: string, filePath: string) => void
|
|
12
|
+
invalidateSearchFile?: (cwd: string, filePath: string) => void | Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Whether the opt-in tools (`get_repo_map`, `ast_search`, `lsp`) are registered for this
|
|
17
|
+
* workspace. Single source of truth: `src/index.ts` gates registration on this, and user-facing
|
|
18
|
+
* tool hints consult it so they never recommend a tool the model cannot actually call.
|
|
19
|
+
*/
|
|
20
|
+
export function speculativeToolsEnabled(
|
|
21
|
+
getConfig: ((cwd: string) => import("../config").KernelConfig) | undefined,
|
|
22
|
+
cwd: string,
|
|
23
|
+
): boolean {
|
|
24
|
+
const flag = process.env.PI_ENABLE_ALL_RETRIEVAL_TOOLS;
|
|
25
|
+
if (flag === "1" || flag === "true") return true;
|
|
26
|
+
return getConfig?.(cwd)?.retrieval?.enable_tools === true;
|
|
13
27
|
}
|
|
14
28
|
|
|
15
29
|
export interface SearchDeps extends SessionDeps {
|
package/src/tools/edit_tool.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { Text, makeOutputText } from "../ui/tui_utils";
|
|
|
4
4
|
import * as path from "node:path";
|
|
5
5
|
import * as fs from "node:fs";
|
|
6
6
|
import { kernelDebug } from "../safety/kernel_debug";
|
|
7
|
+
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
7
8
|
import {
|
|
8
9
|
applySurgicalPatch,
|
|
9
10
|
applyMultiBlockPatch,
|
|
@@ -29,6 +30,24 @@ import {
|
|
|
29
30
|
import { loadKernelConfig } from "../config";
|
|
30
31
|
import type { SessionDeps } from "./context";
|
|
31
32
|
|
|
33
|
+
function mutationLockKey(filePath: string): string {
|
|
34
|
+
const resolved = path.resolve(filePath);
|
|
35
|
+
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function withFileMutationLocks<T>(
|
|
39
|
+
filePaths: string[],
|
|
40
|
+
operation: () => Promise<T>,
|
|
41
|
+
): Promise<T> {
|
|
42
|
+
const { withFileMutationQueue } = await import("@earendil-works/pi-coding-agent");
|
|
43
|
+
const keys = [...new Set(filePaths.map(mutationLockKey))].sort();
|
|
44
|
+
const run = (index: number): Promise<T> =>
|
|
45
|
+
index >= keys.length
|
|
46
|
+
? operation()
|
|
47
|
+
: withFileMutationQueue(keys[index]!, () => run(index + 1));
|
|
48
|
+
return run(0);
|
|
49
|
+
}
|
|
50
|
+
|
|
32
51
|
interface PreparedFileEdit {
|
|
33
52
|
resolvedPath: string;
|
|
34
53
|
relPath: string;
|
|
@@ -207,26 +226,35 @@ async function applyPreparedEdit(
|
|
|
207
226
|
prepared: PreparedFileEdit,
|
|
208
227
|
ctx: any,
|
|
209
228
|
deps: SessionDeps,
|
|
210
|
-
|
|
229
|
+
options: { syntaxGate?: "warn" | "block" } = {},
|
|
230
|
+
): Promise<{ success: boolean; mutated: boolean; error?: string; verification?: any; strategy?: string; statusText?: string }> {
|
|
211
231
|
const { resolvedPath, relPath, item, isAnchorMode, hasSingleBlock, hasMultiBlock, anchorBlocks, anchorPreflight, targetRanges } = prepared;
|
|
232
|
+
const config = deps.getConfig?.(ctx.cwd);
|
|
233
|
+
const editingMode = config?.editing?.mode ?? "smart_anchor";
|
|
234
|
+
const autoHeal = editingMode !== "standard";
|
|
235
|
+
const syntaxGate = options.syntaxGate ?? config?.editing?.syntax_gate ?? (editingMode === "standard" ? "block" : "warn");
|
|
212
236
|
let patchRes: ReturnType<typeof applySurgicalPatch>;
|
|
213
237
|
if (isAnchorMode) {
|
|
214
|
-
patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks);
|
|
238
|
+
patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks, { syntaxGate });
|
|
215
239
|
} else if (hasMultiBlock) {
|
|
216
|
-
patchRes = applyMultiBlockPatch(resolvedPath, item.edits);
|
|
240
|
+
patchRes = applyMultiBlockPatch(resolvedPath, item.edits, { autoHeal, syntaxGate });
|
|
217
241
|
} else if (hasSingleBlock) {
|
|
218
242
|
const singleOpt = {
|
|
219
243
|
startLine: item.start_line,
|
|
220
244
|
endLine: item.end_line,
|
|
221
245
|
lineHint: item.line_hint,
|
|
222
246
|
};
|
|
223
|
-
patchRes = applySurgicalPatch(resolvedPath, item.search, item.replace,
|
|
247
|
+
patchRes = applySurgicalPatch(resolvedPath, item.search, item.replace, {
|
|
248
|
+
...singleOpt,
|
|
249
|
+
autoHeal,
|
|
250
|
+
syntaxGate,
|
|
251
|
+
});
|
|
224
252
|
} else {
|
|
225
|
-
return { success: false, error: `[EDIT ERROR] Must provide either smart anchors or 'search' and 'replace' strings.` };
|
|
253
|
+
return { success: false, mutated: false, error: `[EDIT ERROR] Must provide either smart anchors or 'search' and 'replace' strings.` };
|
|
226
254
|
}
|
|
227
255
|
|
|
228
256
|
if (!patchRes.success) {
|
|
229
|
-
return { success: false, error: renderEditFailure(patchRes.error || "patch failed") };
|
|
257
|
+
return { success: false, mutated: false, error: renderEditFailure(patchRes.error || "patch failed") };
|
|
230
258
|
}
|
|
231
259
|
|
|
232
260
|
let diskContent: string;
|
|
@@ -267,7 +295,7 @@ async function applyPreparedEdit(
|
|
|
267
295
|
},
|
|
268
296
|
);
|
|
269
297
|
|
|
270
|
-
deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
|
|
298
|
+
await deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
|
|
271
299
|
|
|
272
300
|
const readyLsp = LspManager.getInstance().getReadyClientForFile(resolvedPath, ctx.cwd);
|
|
273
301
|
if (readyLsp && readyLsp.getState() === "ready") {
|
|
@@ -304,7 +332,8 @@ async function applyPreparedEdit(
|
|
|
304
332
|
|
|
305
333
|
const statusText = renderPostEditVerification(verification, undefined, relPath);
|
|
306
334
|
return {
|
|
307
|
-
success:
|
|
335
|
+
success: true,
|
|
336
|
+
mutated: true,
|
|
308
337
|
verification,
|
|
309
338
|
strategy: patchRes.strategy,
|
|
310
339
|
statusText,
|
|
@@ -392,7 +421,7 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
392
421
|
? "Edit code with a unique exact search block and replacement block only."
|
|
393
422
|
: benchmarkMethod === "adaptive"
|
|
394
423
|
? "Edit code with search/replace or line range; use search first."
|
|
395
|
-
: "Edit code with
|
|
424
|
+
: "Edit code with search/replace, multi-block 'edits', or multi-file 'files'. Valid after read or exact rg search.",
|
|
396
425
|
promptSnippet: "Edit code using search/replace (optional line_hint), multi-block 'edits', or multi-file 'files'",
|
|
397
426
|
renderShell: "default",
|
|
398
427
|
parameters: editToolParameters,
|
|
@@ -427,6 +456,7 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
427
456
|
const effectiveCtx = ctx || { cwd: effectiveCwd };
|
|
428
457
|
// Check for duplicate canonical paths
|
|
429
458
|
const seenPaths = new Set<string>();
|
|
459
|
+
const lockPaths: string[] = [];
|
|
430
460
|
for (const item of fileEdits) {
|
|
431
461
|
if (!item || typeof item !== "object" || !item.path) {
|
|
432
462
|
return { content: [{ type: "text", text: "[EDIT ERROR] Malformed file edit entry." }], isError: true };
|
|
@@ -440,8 +470,10 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
440
470
|
};
|
|
441
471
|
}
|
|
442
472
|
seenPaths.add(lookupKey);
|
|
473
|
+
lockPaths.push(canonical);
|
|
443
474
|
}
|
|
444
475
|
|
|
476
|
+
return withFileMutationLocks(lockPaths, async () => {
|
|
445
477
|
onUpdate?.({
|
|
446
478
|
content: [{ type: "text", text: `Preflighting ${fileEdits.length} file edits...` }],
|
|
447
479
|
});
|
|
@@ -472,8 +504,14 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
472
504
|
}
|
|
473
505
|
}
|
|
474
506
|
|
|
475
|
-
|
|
476
|
-
|
|
507
|
+
const sessionId = deps.getSessionId(ctx);
|
|
508
|
+
const originalEvidence = new Map(preparedList.map((prep) => [
|
|
509
|
+
prep.resolvedPath,
|
|
510
|
+
globalEpistemicGuard.getEvidence(prep.resolvedPath, sessionId, ctx.cwd),
|
|
511
|
+
]));
|
|
512
|
+
|
|
513
|
+
// Step 3: Apply mutations with rollback guard
|
|
514
|
+
onUpdate?.({
|
|
477
515
|
content: [{ type: "text", text: `Applying edits to ${preparedList.length} files...` }],
|
|
478
516
|
});
|
|
479
517
|
|
|
@@ -484,9 +522,9 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
484
522
|
|
|
485
523
|
for (const prepared of preparedList) {
|
|
486
524
|
try {
|
|
487
|
-
const outcome = await applyPreparedEdit(prepared, ctx, deps);
|
|
525
|
+
const outcome = await applyPreparedEdit(prepared, ctx, deps, { syntaxGate: "block" });
|
|
488
526
|
outcomes.push(outcome);
|
|
489
|
-
mutatedPaths.push(prepared.resolvedPath);
|
|
527
|
+
if (outcome.mutated) mutatedPaths.push(prepared.resolvedPath);
|
|
490
528
|
if (!outcome.success) {
|
|
491
529
|
failureEncountered = true;
|
|
492
530
|
failureReason = outcome.error || outcome.statusText || "Verification failed";
|
|
@@ -500,32 +538,71 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
500
538
|
}
|
|
501
539
|
|
|
502
540
|
// Rollback if any write or verification failed
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
541
|
+
if (failureEncountered) {
|
|
542
|
+
const rollbackFailures: string[] = [];
|
|
543
|
+
for (const mutated of mutatedPaths) {
|
|
544
|
+
const backup = originalSnapshots.get(mutated);
|
|
545
|
+
if (backup === undefined) continue;
|
|
546
|
+
try {
|
|
547
|
+
writeFileSyncAtomic(mutated, backup);
|
|
548
|
+
if (fs.readFileSync(mutated, "utf8") !== backup) {
|
|
549
|
+
throw new Error("restored content verification failed");
|
|
512
550
|
}
|
|
551
|
+
} catch (rbErr) {
|
|
552
|
+
rollbackFailures.push(`${path.basename(mutated)}: ${rbErr instanceof Error ? rbErr.message : String(rbErr)}`);
|
|
553
|
+
continue;
|
|
513
554
|
}
|
|
555
|
+
|
|
556
|
+
globalEpistemicGuard.restoreEvidence(
|
|
557
|
+
mutated,
|
|
558
|
+
sessionId,
|
|
559
|
+
originalEvidence.get(mutated) || null,
|
|
560
|
+
ctx.cwd,
|
|
561
|
+
);
|
|
562
|
+
try {
|
|
563
|
+
await deps.invalidateSearchFile?.(ctx.cwd, mutated);
|
|
564
|
+
} catch (indexErr) {
|
|
565
|
+
rollbackFailures.push(`${path.basename(mutated)} index: ${indexErr instanceof Error ? indexErr.message : String(indexErr)}`);
|
|
566
|
+
}
|
|
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
|
+
}
|
|
577
|
+
if (rollbackFailures.length > 0) {
|
|
514
578
|
return {
|
|
515
|
-
content: [{ type: "text", text: `[EDIT FAILED -
|
|
579
|
+
content: [{ type: "text", text: `[EDIT FAILED - PARTIAL ROLLBACK] Multi-file edit aborted; recovery errors: ${rollbackFailures.join("; ")}` }],
|
|
580
|
+
details: { rolledBack: false, recoveryErrors: rollbackFailures },
|
|
516
581
|
isError: true,
|
|
517
582
|
};
|
|
518
583
|
}
|
|
519
|
-
|
|
520
|
-
const affectedPaths = preparedList.map((p) => p.relPath);
|
|
521
584
|
return {
|
|
522
|
-
content: [{ type: "text", text: `
|
|
523
|
-
details: {
|
|
585
|
+
content: [{ type: "text", text: `[EDIT FAILED - ROLLED BACK] Multi-file edit aborted and all file/index/LSP/guard state restored: ${failureReason}` }],
|
|
586
|
+
details: { rolledBack: true },
|
|
587
|
+
isError: true,
|
|
524
588
|
};
|
|
525
589
|
}
|
|
526
590
|
|
|
527
|
-
|
|
528
|
-
|
|
591
|
+
const affectedPaths = preparedList.map((p) => p.relPath);
|
|
592
|
+
return {
|
|
593
|
+
content: [{ type: "text", text: `Successfully applied edits to ${affectedPaths.length} files: ${affectedPaths.join(", ")}.` }],
|
|
594
|
+
details: { multiFile: true, count: affectedPaths.length, files: affectedPaths },
|
|
595
|
+
};
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// Single-file execution. Queue the complete preflight through
|
|
600
|
+
// post-verification sequence against host write/edit operations.
|
|
601
|
+
const singleLockPath = typeof params?.path === "string"
|
|
602
|
+
? mutationLockKey(resolveUserPath(params.path, ctx.cwd))
|
|
603
|
+
: mutationLockKey(path.resolve(ctx.cwd, "__invalid_edit_target__"));
|
|
604
|
+
return withFileMutationLocks([singleLockPath], async () => {
|
|
605
|
+
const preflight = preflightFileEdit(params, ctx, deps, benchmarkMethod);
|
|
529
606
|
if (preflight.error || !preflight.prepared) {
|
|
530
607
|
return {
|
|
531
608
|
content: [{ type: "text", text: preflight.error || "[EDIT FAILED] Preflight check failed." }],
|
|
@@ -537,7 +614,10 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
537
614
|
content: [{ type: "text", text: `Editing ${preflight.prepared.relPath}...` }],
|
|
538
615
|
});
|
|
539
616
|
|
|
540
|
-
const
|
|
617
|
+
const config = deps.getConfig?.(ctx.cwd);
|
|
618
|
+
const editingMode = config?.editing?.mode ?? "smart_anchor";
|
|
619
|
+
const syntaxGate = config?.editing?.syntax_gate ?? (editingMode === "standard" ? "block" : "warn");
|
|
620
|
+
const outcome = await applyPreparedEdit(preflight.prepared, ctx, deps, { syntaxGate });
|
|
541
621
|
if (!outcome.success && outcome.error) {
|
|
542
622
|
return {
|
|
543
623
|
content: [{ type: "text", text: outcome.error }],
|
|
@@ -545,7 +625,8 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
545
625
|
isError: true,
|
|
546
626
|
};
|
|
547
627
|
}
|
|
548
|
-
|
|
628
|
+
const hasSyntaxFailure = outcome.verification?.syntax?.state === "failed";
|
|
629
|
+
const shouldFlagError = !outcome.mutated || (editingMode === "standard" && hasSyntaxFailure);
|
|
549
630
|
return {
|
|
550
631
|
content: outcome.statusText ? [{ type: "text", text: outcome.statusText }] : [],
|
|
551
632
|
details: {
|
|
@@ -553,12 +634,9 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
553
634
|
verification: outcome.verification,
|
|
554
635
|
success: outcome.verification?.syntax?.state === "clean",
|
|
555
636
|
},
|
|
556
|
-
isError:
|
|
557
|
-
outcome.verification?.syntax?.state === "failed" ||
|
|
558
|
-
outcome.verification?.diagnostic?.findings?.some(
|
|
559
|
-
(finding: any) => finding.severity === "error" || !finding.severity,
|
|
560
|
-
),
|
|
637
|
+
isError: shouldFlagError,
|
|
561
638
|
};
|
|
639
|
+
});
|
|
562
640
|
},
|
|
563
641
|
renderCall(args: any, theme: any, context: any) {
|
|
564
642
|
const fileEdits: string[] = [];
|
package/src/tools/lsp_tool.ts
CHANGED
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
} from "../retrieval/ast_search";
|
|
22
22
|
import { checkSyntax } from "../editing/syntax-verify";
|
|
23
23
|
import { kernelDebug } from "../safety/kernel_debug";
|
|
24
|
-
import type
|
|
24
|
+
import { speculativeToolsEnabled, type SessionDeps } from "./context";
|
|
25
25
|
|
|
26
26
|
/** Extracted from index.ts — registers the `lsp` tool. */
|
|
27
27
|
export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
|
|
@@ -447,7 +447,10 @@ export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
|
|
|
447
447
|
}
|
|
448
448
|
|
|
449
449
|
return result(
|
|
450
|
-
`[LSP Notice] No installed LSP server found for ${path.basename(absPath)}.
|
|
450
|
+
`[LSP Notice] No installed LSP server found for ${path.basename(absPath)}. ` +
|
|
451
|
+
(speculativeToolsEnabled(deps.getConfig, ctx.cwd)
|
|
452
|
+
? `Use 'ast_search' or run '/lsp install' to configure an LSP server.`
|
|
453
|
+
: `Run '/lsp install' to configure an LSP server.`),
|
|
451
454
|
"tree-sitter",
|
|
452
455
|
{ status: "unavailable" },
|
|
453
456
|
);
|
package/src/tools/read_tool.ts
CHANGED
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
globalEpistemicGuard,
|
|
11
11
|
resolveUserPath,
|
|
12
12
|
} from "../safety/epistemic_guard";
|
|
13
|
-
import type
|
|
13
|
+
import { speculativeToolsEnabled, type SessionDeps } from "./context";
|
|
14
14
|
|
|
15
15
|
function countFileLines(filePath: string): number {
|
|
16
16
|
return fs.readFileSync(filePath, "utf8").split("\n").length;
|
|
@@ -18,6 +18,21 @@ function countFileLines(filePath: string): number {
|
|
|
18
18
|
|
|
19
19
|
const MAX_READ_LINES = 2_000;
|
|
20
20
|
const MAX_READ_BYTES = 50 * 1024;
|
|
21
|
+
const MAX_READ_FILE_BYTES = 5 * 1024 * 1024;
|
|
22
|
+
const DEFAULT_UNCONSTRAINED_LINES = 250;
|
|
23
|
+
|
|
24
|
+
function validateReadableFile(filePath: string): string | null {
|
|
25
|
+
try {
|
|
26
|
+
const stat = fs.statSync(filePath);
|
|
27
|
+
if (!stat.isFile()) return "Path is not a regular file";
|
|
28
|
+
if (stat.size > MAX_READ_FILE_BYTES) {
|
|
29
|
+
return `File is ${stat.size} bytes; maximum in-memory source size is ${MAX_READ_FILE_BYTES} bytes`;
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
} catch (error: any) {
|
|
33
|
+
return error?.code === "ENOENT" ? "File not found" : error?.message || String(error);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
21
36
|
|
|
22
37
|
function shouldUseAnchors(
|
|
23
38
|
params: any,
|
|
@@ -196,6 +211,11 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
196
211
|
continue;
|
|
197
212
|
}
|
|
198
213
|
try {
|
|
214
|
+
const readLimitError = validateReadableFile(resolvedPath);
|
|
215
|
+
if (readLimitError) {
|
|
216
|
+
results.push(`=== file: ${relPath} ===\nRead rejected: ${readLimitError}`);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
199
219
|
const content = fs.readFileSync(resolvedPath, "utf-8");
|
|
200
220
|
const lines = content.split("\n");
|
|
201
221
|
const totalLines = lines.length;
|
|
@@ -265,6 +285,15 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
265
285
|
};
|
|
266
286
|
}
|
|
267
287
|
|
|
288
|
+
const readLimitError = validateReadableFile(resolvedPath);
|
|
289
|
+
if (readLimitError) {
|
|
290
|
+
return {
|
|
291
|
+
content: [{ type: "text", text: `[READ ERROR] ${readLimitError}: ${params.path}` }],
|
|
292
|
+
details: { error: "read_limit", maxBytes: MAX_READ_FILE_BYTES },
|
|
293
|
+
isError: true,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
268
297
|
// Mode 1: Targeted AST symbol extraction
|
|
269
298
|
if (params.symbol && params.symbol.trim()) {
|
|
270
299
|
const sym = params.symbol.trim();
|
|
@@ -312,7 +341,10 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
312
341
|
.join("\n");
|
|
313
342
|
errorText = `Symbol '${sym}' not found in ${params.path}.\nDid you mean:\n${formattedSuggestions}`;
|
|
314
343
|
} else {
|
|
315
|
-
errorText = `Symbol '${sym}' not found in ${params.path}.
|
|
344
|
+
errorText = `Symbol '${sym}' not found in ${params.path}. ` +
|
|
345
|
+
(speculativeToolsEnabled(deps.getConfig, ctx.cwd)
|
|
346
|
+
? `Use 'ast_search' to locate symbols or 'rg' in bash to search text.`
|
|
347
|
+
: `Use 'code_search' to locate code or 'rg' in bash to search text.`);
|
|
316
348
|
}
|
|
317
349
|
return {
|
|
318
350
|
content: [{ type: "text", text: errorText }],
|
|
@@ -384,6 +416,14 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
384
416
|
|
|
385
417
|
// Mode 2: Standard file reading
|
|
386
418
|
try {
|
|
419
|
+
const readLimitError = validateReadableFile(resolvedPath);
|
|
420
|
+
if (readLimitError) {
|
|
421
|
+
return {
|
|
422
|
+
content: [{ type: "text", text: `[READ ERROR] ${readLimitError}: ${params.path}` }],
|
|
423
|
+
details: { error: "read_limit", maxBytes: MAX_READ_FILE_BYTES },
|
|
424
|
+
isError: true,
|
|
425
|
+
};
|
|
426
|
+
}
|
|
387
427
|
const ext = path.extname(resolvedPath).toLowerCase();
|
|
388
428
|
const isImage = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"].includes(
|
|
389
429
|
ext,
|
|
@@ -477,7 +517,8 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
477
517
|
}
|
|
478
518
|
|
|
479
519
|
const offset = params.offset ?? 1;
|
|
480
|
-
const
|
|
520
|
+
const hasExplicitLimit = typeof params.limit === "number";
|
|
521
|
+
const limit = hasExplicitLimit ? params.limit : Math.min(totalLines, DEFAULT_UNCONSTRAINED_LINES);
|
|
481
522
|
const startIdx = offset - 1;
|
|
482
523
|
|
|
483
524
|
// Offset past the end of file: return a clean error instead of an
|