@floydous/pi-agent-kernel 0.3.31 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -0
- package/{config.toml → config.example.toml} +7 -2
- package/docs/configuration.md +11 -3
- package/docs/retrieval.md +15 -1
- package/docs/testing.md +5 -3
- package/package.json +3 -2
- package/src/config/agent_kernel_command.ts +73 -88
- package/src/config/kernel_config.ts +5 -14
- package/src/config/toml.ts +15 -4
- package/src/context/session_repair.ts +24 -6
- package/src/editing/smart_anchor.ts +16 -7
- package/src/editing/syntax-verify.ts +17 -7
- package/src/index.ts +104 -86
- package/src/lsp/lsp_client.ts +37 -3
- package/src/lsp/lsp_formatter.ts +4 -2
- package/src/lsp/lsp_installer.ts +46 -115
- package/src/lsp/lsp_registry.ts +36 -28
- package/src/retrieval/ast_search.ts +136 -172
- package/src/retrieval/repomap.ts +8 -47
- package/src/retrieval/search_chunker.ts +9 -34
- package/src/retrieval/search_config.ts +59 -14
- package/src/retrieval/search_index.ts +396 -27
- package/src/retrieval/workspace_walker.ts +262 -0
- package/src/safety/epistemic_guard.ts +1 -1
- package/src/safety/output_clamper.ts +4 -2
- package/src/tools/edit_tool.ts +11 -8
- package/src/tools/lsp_tool.ts +12 -2
- package/src/tools/read_tool.ts +4 -4
|
@@ -2,6 +2,10 @@ import * as fs from "fs";
|
|
|
2
2
|
import * as path from "path";
|
|
3
3
|
import * as os from "os";
|
|
4
4
|
import { getPiHomeDir } from "../config";
|
|
5
|
+
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
6
|
+
|
|
7
|
+
const MAX_SESSION_FILE_SIZE = 10 * 1024 * 1024; // 10MB
|
|
8
|
+
const MAX_SESSIONS_SCANNED = 20;
|
|
5
9
|
|
|
6
10
|
/**
|
|
7
11
|
* Sanitizes and repairs session JSONL files in ~/.pi/agent/sessions/
|
|
@@ -21,18 +25,32 @@ export function sanitizeSessionFiles(agentDir?: string): { repairedFiles: number
|
|
|
21
25
|
return { repairedFiles: 0, repairedEntries: 0 };
|
|
22
26
|
}
|
|
23
27
|
|
|
24
|
-
const sessionFolders = fs.readdirSync(sessionsDir)
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
28
|
+
const sessionFolders = fs.readdirSync(sessionsDir)
|
|
29
|
+
.map((folder) => {
|
|
30
|
+
const folderPath = path.join(sessionsDir, folder);
|
|
31
|
+
try {
|
|
32
|
+
const stat = fs.lstatSync(folderPath);
|
|
33
|
+
return { folder, folderPath, isDir: stat.isDirectory() && !stat.isSymbolicLink(), mtime: stat.mtimeMs };
|
|
34
|
+
} catch {
|
|
35
|
+
return { folder, folderPath, isDir: false, mtime: 0 };
|
|
36
|
+
}
|
|
37
|
+
})
|
|
38
|
+
.filter((f) => f.isDir)
|
|
39
|
+
.sort((a, b) => b.mtime - a.mtime)
|
|
40
|
+
.slice(0, MAX_SESSIONS_SCANNED);
|
|
29
41
|
|
|
42
|
+
for (const { folderPath } of sessionFolders) {
|
|
30
43
|
const files = fs.readdirSync(folderPath);
|
|
31
44
|
for (const file of files) {
|
|
32
45
|
if (!file.endsWith(".jsonl")) continue;
|
|
33
46
|
|
|
34
47
|
const filePath = path.join(folderPath, file);
|
|
35
48
|
try {
|
|
49
|
+
const stat = fs.lstatSync(filePath);
|
|
50
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_SESSION_FILE_SIZE) {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
|
|
36
54
|
const content = fs.readFileSync(filePath, "utf8");
|
|
37
55
|
const lines = content.split("\n");
|
|
38
56
|
let fileModified = false;
|
|
@@ -83,7 +101,7 @@ export function sanitizeSessionFiles(agentDir?: string): { repairedFiles: number
|
|
|
83
101
|
});
|
|
84
102
|
|
|
85
103
|
if (fileModified) {
|
|
86
|
-
|
|
104
|
+
writeFileSyncAtomic(filePath, repairedLines.join("\n"));
|
|
87
105
|
repairedFiles++;
|
|
88
106
|
}
|
|
89
107
|
} catch (err) {
|
|
@@ -346,7 +346,10 @@ export function applySmartAnchorEdits(
|
|
|
346
346
|
};
|
|
347
347
|
}
|
|
348
348
|
|
|
349
|
-
const
|
|
349
|
+
const hadCrlf = originalContent.includes("\r\n");
|
|
350
|
+
const contentNorm = originalContent.replace(/\r\n/g, "\n");
|
|
351
|
+
|
|
352
|
+
const preflight = preflightSmartAnchorEdits(contentNorm, edits);
|
|
350
353
|
if (!preflight.success || !preflight.resolvedSpans) {
|
|
351
354
|
return {
|
|
352
355
|
success: false,
|
|
@@ -356,7 +359,7 @@ export function applySmartAnchorEdits(
|
|
|
356
359
|
};
|
|
357
360
|
}
|
|
358
361
|
|
|
359
|
-
const fileLines =
|
|
362
|
+
const fileLines = contentNorm.split("\n");
|
|
360
363
|
const currentLines = [...fileLines];
|
|
361
364
|
|
|
362
365
|
// Sort spans strictly bottom-to-top (descending line number) so edits do not shift earlier lines
|
|
@@ -364,10 +367,16 @@ export function applySmartAnchorEdits(
|
|
|
364
367
|
|
|
365
368
|
for (const span of sortedSpans) {
|
|
366
369
|
const deleteCount = span.endLine - span.startLine + 1;
|
|
367
|
-
|
|
370
|
+
const cleanReplacementLines = span.replacementLines.flatMap((line) =>
|
|
371
|
+
line.replace(/\r\n/g, "\n").split("\n"),
|
|
372
|
+
);
|
|
373
|
+
currentLines.splice(span.startLine - 1, deleteCount, ...cleanReplacementLines);
|
|
368
374
|
}
|
|
369
375
|
|
|
370
|
-
const
|
|
376
|
+
const candidateContentNorm = currentLines.join("\n");
|
|
377
|
+
const candidateContent = hadCrlf
|
|
378
|
+
? candidateContentNorm.replace(/\n/g, "\r\n")
|
|
379
|
+
: candidateContentNorm;
|
|
371
380
|
|
|
372
381
|
// Syntax validation gate
|
|
373
382
|
const syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
@@ -404,10 +413,10 @@ export function applySmartAnchorEdits(
|
|
|
404
413
|
// Unified diff output
|
|
405
414
|
const diffOutput = diff.createPatch(
|
|
406
415
|
resolvedPath,
|
|
407
|
-
|
|
408
|
-
|
|
416
|
+
contentNorm,
|
|
417
|
+
candidateContentNorm,
|
|
409
418
|
"original",
|
|
410
|
-
"
|
|
419
|
+
"updated",
|
|
411
420
|
);
|
|
412
421
|
|
|
413
422
|
return {
|
|
@@ -52,7 +52,7 @@ function regexCanStart(prevSig: string, lastWord: string): boolean {
|
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
function checkTsStructure(content: string): string | null {
|
|
55
|
-
const stack: { ch: string; line: number }[] = [];
|
|
55
|
+
const stack: { ch: string; line: number; isTemplateInterp?: boolean }[] = [];
|
|
56
56
|
let line = 1;
|
|
57
57
|
let i = 0;
|
|
58
58
|
// State machine over raw source: code | 'str' | "str" | `tpl` | //line | /*block */ | /regex/
|
|
@@ -106,11 +106,15 @@ function checkTsStructure(content: string): string | null {
|
|
|
106
106
|
else if (ch === '"') state = "code";
|
|
107
107
|
break;
|
|
108
108
|
case "template":
|
|
109
|
-
if (ch === "\\")
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
109
|
+
if (ch === "\\") {
|
|
110
|
+
i++;
|
|
111
|
+
} else if (ch === "$" && next === "{") {
|
|
112
|
+
stack.push({ ch: "{", line, isTemplateInterp: true });
|
|
113
|
+
state = "code";
|
|
114
|
+
i++;
|
|
115
|
+
} else if (ch === "`") {
|
|
116
|
+
state = "code";
|
|
117
|
+
}
|
|
114
118
|
break;
|
|
115
119
|
case "code":
|
|
116
120
|
if (ch === "/" && next === "/") {
|
|
@@ -144,6 +148,9 @@ function checkTsStructure(content: string): string | null {
|
|
|
144
148
|
if (!top || top.ch !== closers[ch]) {
|
|
145
149
|
return `Unbalanced '${ch}' on line ${line}${top ? ` (unclosed '${top.ch}' from line ${top.line})` : " (no matching opener)"}`;
|
|
146
150
|
}
|
|
151
|
+
if (top.isTemplateInterp) {
|
|
152
|
+
state = "template";
|
|
153
|
+
}
|
|
147
154
|
}
|
|
148
155
|
if (!/\s/.test(ch)) prevSig = ch;
|
|
149
156
|
// Accumulate identifier/number tokens; whitespace preserves the
|
|
@@ -167,9 +174,12 @@ function checkTsStructure(content: string): string | null {
|
|
|
167
174
|
i++;
|
|
168
175
|
}
|
|
169
176
|
|
|
170
|
-
if (state === "squote" || state === "dquote"
|
|
177
|
+
if (state === "squote" || state === "dquote") {
|
|
171
178
|
return `Unterminated string literal (reached end of file, last line ${line})`;
|
|
172
179
|
}
|
|
180
|
+
if (state === "template") {
|
|
181
|
+
return `Unterminated template literal (reached end of file, last line ${line})`;
|
|
182
|
+
}
|
|
173
183
|
if (state === "blockComment") {
|
|
174
184
|
return `Unterminated block comment (last line ${line})`;
|
|
175
185
|
}
|
package/src/index.ts
CHANGED
|
@@ -2,9 +2,9 @@ import * as path from "path";
|
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as child_process from "node:child_process";
|
|
4
4
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import { computeRepoMap
|
|
5
|
+
import { computeRepoMap } from "./retrieval/repomap";
|
|
6
6
|
import { HybridSearchIndex } from "./retrieval/search_index";
|
|
7
|
-
import type
|
|
7
|
+
import { type SearchProfile, savePersistedProfile } from "./retrieval/search_config";
|
|
8
8
|
import { SearchControlModal } from "./retrieval/search_modal";
|
|
9
9
|
import { checkSyntax } from "./editing/syntax-verify";
|
|
10
10
|
import {
|
|
@@ -51,7 +51,6 @@ const PI_DOCS_END = /\n- Always read pi \.md files completely[^\n]*/;
|
|
|
51
51
|
const KERNEL_GUIDANCE_MARKER = "## Agent Kernel Guidance";
|
|
52
52
|
let kernelGuidance: string | null | undefined;
|
|
53
53
|
const piDocsEnabledBySession = new Map<string, boolean>();
|
|
54
|
-
const codebaseProfileBySession = new Map<string, "auto" | "light" | "heavy">();
|
|
55
54
|
|
|
56
55
|
function withoutPiDocumentation(systemPrompt: string): string {
|
|
57
56
|
const start = systemPrompt.indexOf(PI_DOCS_START);
|
|
@@ -138,7 +137,8 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
138
137
|
const workspace = path.resolve(cwd);
|
|
139
138
|
let index = searchIndexes.get(workspace);
|
|
140
139
|
if (!index) {
|
|
141
|
-
|
|
140
|
+
const profile = getConfig(workspace).retrieval.default_profile;
|
|
141
|
+
index = new HybridSearchIndex(workspace, profile);
|
|
142
142
|
searchIndexes.set(workspace, index);
|
|
143
143
|
}
|
|
144
144
|
return index;
|
|
@@ -148,6 +148,13 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
148
148
|
const syncRetrievalStatus = (ctx: any, customText?: string) => {
|
|
149
149
|
if (!ctx?.ui?.setStatus) return;
|
|
150
150
|
const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
151
|
+
const config = getConfig(cwd);
|
|
152
|
+
if (!config.ui.enable_pastel_footer) {
|
|
153
|
+
ctx.ui.setStatus("retrieval", "");
|
|
154
|
+
activeTui?.requestRender?.();
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
|
|
151
158
|
const index = getSearchIndex(cwd);
|
|
152
159
|
const eff = index.getEffectiveProfile();
|
|
153
160
|
if (eff === "off") {
|
|
@@ -165,28 +172,32 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
165
172
|
activeTui?.requestRender?.();
|
|
166
173
|
};
|
|
167
174
|
|
|
175
|
+
let activeIndexingGeneration = 0;
|
|
176
|
+
|
|
168
177
|
const triggerBackgroundIndexing = (
|
|
169
178
|
index: HybridSearchIndex,
|
|
170
179
|
ctx: any,
|
|
171
180
|
isFullSync = false,
|
|
172
181
|
) => {
|
|
182
|
+
const currentGeneration = ++activeIndexingGeneration;
|
|
173
183
|
const eff = index.getEffectiveProfile();
|
|
174
184
|
if (eff === "off") {
|
|
175
185
|
syncRetrievalStatus(ctx);
|
|
176
186
|
return;
|
|
177
187
|
}
|
|
178
188
|
|
|
179
|
-
const engineTag = formatSearchEngineTag(index, true);
|
|
180
189
|
const streamArrow = "\x1b[38;2;155;210;170m⇢\x1b[0m";
|
|
181
190
|
syncRetrievalStatus(
|
|
182
191
|
ctx,
|
|
183
|
-
`${
|
|
192
|
+
`${formatSearchEngineTag(index, true)} ${streamArrow} \x1b[38;2;165;175;190m(indexing...)\x1b[0m`,
|
|
184
193
|
);
|
|
185
194
|
|
|
186
195
|
const runSync = async () => {
|
|
187
196
|
return await index.syncWorkspace(
|
|
188
197
|
isFullSync,
|
|
189
198
|
(msg: string) => {
|
|
199
|
+
if (currentGeneration !== activeIndexingGeneration) return;
|
|
200
|
+
const engineTag = formatSearchEngineTag(index, true);
|
|
190
201
|
const pctMatch = msg.match(/(\d+)%/);
|
|
191
202
|
const speedMatch = msg.match(/([\d.]+\s*chunk\/s)/);
|
|
192
203
|
const countMatch = msg.match(/\((\d+)\/(\d+)/);
|
|
@@ -220,6 +231,12 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
220
231
|
// while progress stays cleanly reported on the statusline.
|
|
221
232
|
void runSync()
|
|
222
233
|
.then((result) => {
|
|
234
|
+
if (currentGeneration !== activeIndexingGeneration) return;
|
|
235
|
+
if (index.getEffectiveProfile() === "off") {
|
|
236
|
+
ctx?.ui?.setStatus?.("retrieval", "");
|
|
237
|
+
activeTui?.requestRender?.();
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
223
240
|
syncRetrievalStatus(ctx); // Reset to clean idle tag on status line
|
|
224
241
|
if (
|
|
225
242
|
(result.indexedCount !== undefined ? result.indexedCount > 0 : false) ||
|
|
@@ -232,6 +249,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
232
249
|
}
|
|
233
250
|
})
|
|
234
251
|
.catch((err: any) => {
|
|
252
|
+
if (currentGeneration !== activeIndexingGeneration) return;
|
|
235
253
|
syncRetrievalStatus(ctx);
|
|
236
254
|
ctx.ui?.notify?.(`Indexing error: ${err.message}`, "error");
|
|
237
255
|
});
|
|
@@ -258,10 +276,34 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
258
276
|
}
|
|
259
277
|
};
|
|
260
278
|
|
|
279
|
+
const applyConfigChanges = (cwd: string, ctx?: any) => {
|
|
280
|
+
const workspace = path.resolve(cwd);
|
|
281
|
+
configByWorkspace.delete(workspace);
|
|
282
|
+
const newConfig = getConfig(workspace);
|
|
283
|
+
const newProfile = newConfig.retrieval.default_profile;
|
|
284
|
+
|
|
285
|
+
// 1. Live update of running in-memory search index if profile changed
|
|
286
|
+
const index = searchIndexes.get(workspace);
|
|
287
|
+
if (index) {
|
|
288
|
+
if (index.getProfile() !== newProfile) {
|
|
289
|
+
index.setProfile(newProfile);
|
|
290
|
+
if (ctx) {
|
|
291
|
+
triggerBackgroundIndexing(index, ctx, false);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// 2. Refresh statusline and footer immediately
|
|
297
|
+
if (ctx) {
|
|
298
|
+
syncRetrievalStatus(ctx);
|
|
299
|
+
activeTui?.requestRender?.();
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
|
|
261
303
|
registerAgentKernelCommand(pi, {
|
|
262
304
|
getConfig,
|
|
263
|
-
invalidateConfig: (cwd) => {
|
|
264
|
-
|
|
305
|
+
invalidateConfig: (cwd, ctx) => {
|
|
306
|
+
applyConfigChanges(cwd, ctx);
|
|
265
307
|
},
|
|
266
308
|
clearCaches: () => {
|
|
267
309
|
cachedRepoMap = "";
|
|
@@ -320,44 +362,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
320
362
|
},
|
|
321
363
|
});
|
|
322
364
|
|
|
323
|
-
// Slash Command: /profile [auto|smart|light|heavy|status]
|
|
324
|
-
pi.registerCommand("profile", {
|
|
325
|
-
description: "Configure codebase scale profile (auto/smart | light | heavy | status)",
|
|
326
|
-
getArgumentCompletions: (prefix: string) => {
|
|
327
|
-
const options = [
|
|
328
|
-
{ value: "auto", label: "auto (smart) - Auto-detect scale from codebase metrics" },
|
|
329
|
-
{ value: "light", label: "light - Force light profile (suppress auto repo-map)" },
|
|
330
|
-
{ value: "heavy", label: "heavy - Force heavy profile (always inject repo-map)" },
|
|
331
|
-
{ value: "status", label: "status - Display current profile & codebase metrics" },
|
|
332
|
-
];
|
|
333
|
-
const filtered = options.filter((o) => o.value.startsWith(prefix.toLowerCase()));
|
|
334
|
-
return filtered.length > 0 ? filtered : null;
|
|
335
|
-
},
|
|
336
|
-
handler: async (args: string, ctx: any) => {
|
|
337
|
-
const sessionId = getSessionId(ctx);
|
|
338
|
-
const raw = (args || "").trim().toLowerCase();
|
|
339
|
-
const val = raw === "smart" ? "auto" : raw;
|
|
340
|
-
|
|
341
|
-
if (val === "auto" || val === "light" || val === "heavy") {
|
|
342
|
-
codebaseProfileBySession.set(sessionId, val);
|
|
343
|
-
cachedRepoMap = "";
|
|
344
|
-
const msg = `Codebase profile set to '${val}' for this session.`;
|
|
345
|
-
ctx.ui?.notify?.(msg, "info");
|
|
346
|
-
if (!ctx.hasUI) console.log(msg);
|
|
347
|
-
return;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
351
|
-
const current = codebaseProfileBySession.get(sessionId) ?? getConfig(currentCwd).retrieval.codebase_profile;
|
|
352
|
-
const metrics = evaluateCodebaseMetrics(currentCwd);
|
|
353
|
-
const detected = metrics.isLight ? "light" : "heavy";
|
|
354
|
-
const effective = current === "auto" ? detected : current;
|
|
355
|
-
const statusMsg = `Profile: ${current} (effective: ${effective})\nMetrics: ${metrics.implFiles} impl files (${Math.round(metrics.implBytes / 1024)} KB), ${metrics.testFiles} test files (${Math.round(metrics.testBytes / 1024)} KB)`;
|
|
356
|
-
ctx.ui?.notify?.(statusMsg, "info");
|
|
357
|
-
if (!ctx.hasUI) console.log("\n" + statusMsg + "\n");
|
|
358
|
-
},
|
|
359
|
-
});
|
|
360
|
-
|
|
361
365
|
// Slash Command: /engine [auto|lean|hybrid|full|off|status|reindex]
|
|
362
366
|
pi.registerCommand("engine", {
|
|
363
367
|
description:
|
|
@@ -412,8 +416,9 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
412
416
|
sub === "full" ||
|
|
413
417
|
sub === "off"
|
|
414
418
|
) {
|
|
415
|
-
|
|
416
|
-
|
|
419
|
+
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
420
|
+
savePersistedProfile(sub as SearchProfile, currentCwd);
|
|
421
|
+
applyConfigChanges(currentCwd, ctx);
|
|
417
422
|
const status = index.getStatus();
|
|
418
423
|
const msg = `Default search profile saved: ${sub.toUpperCase()} (Effective: ${status.effectiveProfile.toUpperCase()})`;
|
|
419
424
|
ctx.ui?.notify?.(msg, "info");
|
|
@@ -472,6 +477,11 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
472
477
|
const effName = eff.toUpperCase();
|
|
473
478
|
|
|
474
479
|
if (res.action === "select") {
|
|
480
|
+
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
481
|
+
if (res.profile) {
|
|
482
|
+
savePersistedProfile(res.profile, currentCwd);
|
|
483
|
+
applyConfigChanges(currentCwd, ctx);
|
|
484
|
+
}
|
|
475
485
|
ctx.ui?.notify?.(
|
|
476
486
|
`Engine set to ${profileName} (Effective: ${effName})`,
|
|
477
487
|
"info",
|
|
@@ -509,42 +519,34 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
509
519
|
);
|
|
510
520
|
if (!choice || choice.startsWith("──")) return;
|
|
511
521
|
|
|
512
|
-
|
|
513
|
-
let
|
|
514
|
-
|
|
515
|
-
if (choice.includes("
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
index
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
ctx.ui.notify("Default search profile saved: OFF", "info");
|
|
534
|
-
} else if (choice.includes("Re-index")) {
|
|
535
|
-
isReindex = true;
|
|
536
|
-
} else if (choice.includes("View Status")) {
|
|
522
|
+
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
523
|
+
let newProfile: SearchProfile | null = null;
|
|
524
|
+
if (choice.includes("Auto Detect")) newProfile = "auto";
|
|
525
|
+
else if (choice.includes("Lean Mode")) newProfile = "lean";
|
|
526
|
+
else if (choice.includes("Hybrid Mode")) newProfile = "hybrid";
|
|
527
|
+
else if (choice.includes("Full Mode")) newProfile = "full";
|
|
528
|
+
else if (choice.includes("Disable Engine")) newProfile = "off";
|
|
529
|
+
|
|
530
|
+
if (newProfile) {
|
|
531
|
+
savePersistedProfile(newProfile, currentCwd);
|
|
532
|
+
applyConfigChanges(currentCwd, ctx);
|
|
533
|
+
ctx.ui?.notify?.(`Default search profile saved: ${newProfile.toUpperCase()}`, "info");
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
if (choice.includes("Re-index")) {
|
|
538
|
+
triggerBackgroundIndexing(index, ctx, true);
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
if (choice.includes("View Status")) {
|
|
537
543
|
const s = index.getStatus();
|
|
538
544
|
ctx.ui.notify(
|
|
539
545
|
`Engine: ${s.engineState} | Profile: ${s.profile.toUpperCase()} (Effective: ${s.effectiveProfile.toUpperCase()}) | Files: ${s.fileCount} | Chunks: ${s.chunkCount} | Model: ${s.modelStatus} | RSS: ${s.rssMemoryMB}MB`,
|
|
540
546
|
"info",
|
|
541
547
|
);
|
|
548
|
+
return;
|
|
542
549
|
}
|
|
543
|
-
|
|
544
|
-
if (profileChanged || isReindex) {
|
|
545
|
-
triggerBackgroundIndexing(index, ctx, isReindex);
|
|
546
|
-
}
|
|
547
|
-
return;
|
|
548
550
|
}
|
|
549
551
|
|
|
550
552
|
// CLI fallback if not in UI mode
|
|
@@ -704,13 +706,24 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
704
706
|
} catch (e) {
|
|
705
707
|
kernelDebug(e);
|
|
706
708
|
}
|
|
709
|
+
// Flush any debounced search index writes to disk on shutdown and halt further admissions
|
|
710
|
+
for (const index of searchIndexes.values()) {
|
|
711
|
+
try {
|
|
712
|
+
await index.flushPendingSave(true);
|
|
713
|
+
} catch (e) {
|
|
714
|
+
kernelDebug(e);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
707
717
|
});
|
|
708
718
|
|
|
709
719
|
// 4-8. Tools: Core tools (read, edit) and code_search are registered.
|
|
710
720
|
// Speculative AST dump and heavy daemon tools (ast_search, repo_map, lsp) remain optional
|
|
711
721
|
// to avoid prompt bloat on routine tasks.
|
|
712
722
|
const invalidateSearchFile = (cwd: string, filePath: string) => {
|
|
713
|
-
getSearchIndex(cwd)
|
|
723
|
+
const index = getSearchIndex(cwd);
|
|
724
|
+
void index.updateFile(filePath).catch((err) => {
|
|
725
|
+
kernelDebug(`Incremental updateFile error for ${filePath}: ${err}`);
|
|
726
|
+
});
|
|
714
727
|
};
|
|
715
728
|
registerReadTool(pi, { getSessionId, getConfig });
|
|
716
729
|
registerEditTool(pi, { getSessionId, getConfig, invalidateSearchFile });
|
|
@@ -771,16 +784,16 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
771
784
|
|
|
772
785
|
// 9. Tool Result Interceptor: Syntax Validation & Output Clamping (ACI)
|
|
773
786
|
pi.on("tool_result", async (event: any, ctx: any) => {
|
|
774
|
-
const
|
|
775
|
-
if (event.isError && !
|
|
787
|
+
const isShell = event.toolName === "bash" || event.toolName === "powershell";
|
|
788
|
+
if (event.isError && !isShell) return;
|
|
776
789
|
|
|
777
790
|
// resultContent === undefined means "no transformation, return event.content as-is".
|
|
778
791
|
const toolName = event.toolName;
|
|
779
792
|
let resultContent: any = undefined;
|
|
780
793
|
let didBail = false;
|
|
781
794
|
|
|
782
|
-
// 9a. Intercept bash &
|
|
783
|
-
if (toolName === "bash") {
|
|
795
|
+
// 9a. Intercept bash & powershell output to clamp minified lines & massive match floods
|
|
796
|
+
if (toolName === "bash" || toolName === "powershell") {
|
|
784
797
|
const command = (event.input as any)?.command || "";
|
|
785
798
|
const outputConfig = getConfig(
|
|
786
799
|
ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
|
|
@@ -843,7 +856,9 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
843
856
|
const resultCwd =
|
|
844
857
|
ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
845
858
|
const resolvedPath = resolveUserPath(targetPath, resultCwd);
|
|
846
|
-
getSearchIndex(resultCwd).
|
|
859
|
+
void getSearchIndex(resultCwd).updateFile(resolvedPath).catch((err) => {
|
|
860
|
+
kernelDebug(`Incremental updateFile error for ${resolvedPath}: ${err}`);
|
|
861
|
+
});
|
|
847
862
|
|
|
848
863
|
// Update epistemic guard ledger with the newly written file
|
|
849
864
|
try {
|
|
@@ -969,7 +984,11 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
969
984
|
let clampedDiff = lines.slice(0, maxLines).join("\n");
|
|
970
985
|
let wasByteTruncated = false;
|
|
971
986
|
if (Buffer.byteLength(clampedDiff, "utf8") > maxDiffBytes) {
|
|
972
|
-
|
|
987
|
+
const buf = Buffer.from(clampedDiff, "utf8").subarray(0, maxDiffBytes);
|
|
988
|
+
clampedDiff = new TextDecoder("utf-8", { fatal: false }).decode(buf);
|
|
989
|
+
if (/[\uD800-\uDBFF]$/.test(clampedDiff)) {
|
|
990
|
+
clampedDiff = clampedDiff.slice(0, -1);
|
|
991
|
+
}
|
|
973
992
|
wasByteTruncated = true;
|
|
974
993
|
}
|
|
975
994
|
const truncatedNotice = lines.length > maxLines || wasByteTruncated
|
|
@@ -1002,7 +1021,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
1002
1021
|
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
1003
1022
|
const kernelConfig = getConfig(currentCwd);
|
|
1004
1023
|
const sessionId = getSessionId(ctx);
|
|
1005
|
-
const profile = codebaseProfileBySession.get(sessionId) ?? kernelConfig.retrieval.codebase_profile ?? "auto";
|
|
1006
1024
|
|
|
1007
1025
|
let shouldInjectMap = false;
|
|
1008
1026
|
// Disabled automatic AST repo map injection to evaluate prompt token footprint and latency
|
package/src/lsp/lsp_client.ts
CHANGED
|
@@ -50,6 +50,9 @@ export class StdioLspClient {
|
|
|
50
50
|
private openDocuments = new Map<string, { version: number; text: string }>();
|
|
51
51
|
private lastActivityTime = Date.now();
|
|
52
52
|
private serverCapabilities: any = {};
|
|
53
|
+
private static readonly MAX_HEADER_SIZE = 8192;
|
|
54
|
+
private static readonly MAX_BUFFER_SIZE = 50 * 1024 * 1024;
|
|
55
|
+
private static readonly MAX_CONTENT_LENGTH = 25 * 1024 * 1024;
|
|
53
56
|
|
|
54
57
|
constructor(id: string, options: StdioLspClientOptions) {
|
|
55
58
|
this.id = id;
|
|
@@ -181,21 +184,52 @@ export class StdioLspClient {
|
|
|
181
184
|
this.touch();
|
|
182
185
|
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
183
186
|
|
|
187
|
+
if (this.buffer.length > StdioLspClient.MAX_BUFFER_SIZE) {
|
|
188
|
+
kernelDebug(new Error("LSP client buffer exceeded maximum allowed size. Clearing buffer."));
|
|
189
|
+
this.buffer = Buffer.alloc(0);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
|
|
184
193
|
while (true) {
|
|
194
|
+
// Resynchronize if buffer has leading garbage before Content-Length
|
|
195
|
+
const clIndex = this.buffer.indexOf("Content-Length:");
|
|
196
|
+
const lowerClIndex = clIndex === -1 ? this.buffer.indexOf("content-length:") : clIndex;
|
|
197
|
+
if (lowerClIndex > 0) {
|
|
198
|
+
this.buffer = this.buffer.subarray(lowerClIndex);
|
|
199
|
+
}
|
|
200
|
+
|
|
185
201
|
const headerEndIndex = this.buffer.indexOf("\r\n\r\n");
|
|
186
|
-
if (headerEndIndex === -1)
|
|
202
|
+
if (headerEndIndex === -1) {
|
|
203
|
+
if (this.buffer.length > StdioLspClient.MAX_HEADER_SIZE) {
|
|
204
|
+
kernelDebug(new Error("LSP header exceeds max allowable size without delimiter. Discarding corrupt stream."));
|
|
205
|
+
this.buffer = Buffer.alloc(0);
|
|
206
|
+
}
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
187
209
|
|
|
188
210
|
const headerText = this.buffer
|
|
189
211
|
.subarray(0, headerEndIndex)
|
|
190
212
|
.toString("utf8");
|
|
191
|
-
const match = /Content-Length:\s*(\d+)/i.exec(headerText);
|
|
213
|
+
const match = /(?:^|\r?\n)Content-Length:\s*(\d+)\s*(?:\r?\n|$)/i.exec(headerText);
|
|
192
214
|
if (!match) {
|
|
193
215
|
// Corrupted header, skip past \r\n\r\n
|
|
194
216
|
this.buffer = this.buffer.subarray(headerEndIndex + 4);
|
|
195
217
|
continue;
|
|
196
218
|
}
|
|
197
219
|
|
|
198
|
-
const
|
|
220
|
+
const contentLengthStr = match[1];
|
|
221
|
+
const contentLength = Number(contentLengthStr);
|
|
222
|
+
|
|
223
|
+
if (
|
|
224
|
+
!Number.isSafeInteger(contentLength) ||
|
|
225
|
+
contentLength < 0 ||
|
|
226
|
+
contentLength > StdioLspClient.MAX_CONTENT_LENGTH
|
|
227
|
+
) {
|
|
228
|
+
kernelDebug(new Error(`Invalid or oversized LSP Content-Length: ${contentLengthStr}`));
|
|
229
|
+
this.buffer = Buffer.alloc(0);
|
|
230
|
+
break;
|
|
231
|
+
}
|
|
232
|
+
|
|
199
233
|
const bodyStartIndex = headerEndIndex + 4;
|
|
200
234
|
const totalMessageLength = bodyStartIndex + contentLength;
|
|
201
235
|
|
package/src/lsp/lsp_formatter.ts
CHANGED
|
@@ -133,7 +133,8 @@ export function formatDefinitions(
|
|
|
133
133
|
|
|
134
134
|
const lines = locations.map((loc) => {
|
|
135
135
|
const filePath = uriToPath(loc.uri);
|
|
136
|
-
const
|
|
136
|
+
const rawDisplay = cwd ? path.relative(cwd, filePath) || filePath : filePath;
|
|
137
|
+
const displayPath = rawDisplay.replace(/\\/g, "/");
|
|
137
138
|
const line = loc.range.start.line + 1;
|
|
138
139
|
const col = loc.range.start.character + 1;
|
|
139
140
|
return `${displayPath}:${line}:${col}`;
|
|
@@ -199,7 +200,8 @@ export function formatReferences(
|
|
|
199
200
|
|
|
200
201
|
const lines = references.map((loc) => {
|
|
201
202
|
const filePath = uriToPath(loc.uri);
|
|
202
|
-
const
|
|
203
|
+
const rawDisplay = cwd ? path.relative(cwd, filePath) || filePath : filePath;
|
|
204
|
+
const displayPath = rawDisplay.replace(/\\/g, "/");
|
|
203
205
|
const line1 = loc.range.start.line + 1;
|
|
204
206
|
const col1 = loc.range.start.character + 1;
|
|
205
207
|
const baseLoc = `${displayPath}:${line1}:${col1}`;
|