@floydous/pi-agent-kernel 0.3.3 → 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 +49 -2
- package/README.md +24 -1
- package/config.example.toml +36 -0
- 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 +834 -0
- package/src/config/index.ts +1 -0
- package/src/config/kernel_config.ts +78 -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 +117 -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 +32 -9
- package/src/tools/edit_tool.ts +11 -8
- package/src/tools/lsp_tool.ts +12 -2
- package/src/tools/read_tool.ts +4 -4
- package/config.toml +0 -30
package/src/index.ts
CHANGED
|
@@ -2,16 +2,16 @@ 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 {
|
|
11
11
|
globalEpistemicGuard,
|
|
12
12
|
resolveUserPath,
|
|
13
13
|
} from "./safety/epistemic_guard";
|
|
14
|
-
import { loadKernelConfig } from "./config";
|
|
14
|
+
import { loadKernelConfig, registerAgentKernelCommand } from "./config";
|
|
15
15
|
import { kernelDebug } from "./safety/kernel_debug";
|
|
16
16
|
import { registerRepoMapTool } from "./tools/repo_map_tool";
|
|
17
17
|
import { registerAstSearchTool } from "./tools/ast_search_tool";
|
|
@@ -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);
|
|
@@ -66,7 +65,10 @@ function withoutPiDocumentation(systemPrompt: string): string {
|
|
|
66
65
|
}
|
|
67
66
|
|
|
68
67
|
function piDocsEnabled(ctx: any): boolean {
|
|
69
|
-
|
|
68
|
+
const sessionVal = piDocsEnabledBySession.get(getSessionId(ctx));
|
|
69
|
+
if (sessionVal !== undefined) return sessionVal;
|
|
70
|
+
const cwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
71
|
+
return loadKernelConfig(cwd).instructions.pi_docs ?? true;
|
|
70
72
|
}
|
|
71
73
|
|
|
72
74
|
function loadKernelGuidance(): string {
|
|
@@ -135,7 +137,8 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
135
137
|
const workspace = path.resolve(cwd);
|
|
136
138
|
let index = searchIndexes.get(workspace);
|
|
137
139
|
if (!index) {
|
|
138
|
-
|
|
140
|
+
const profile = getConfig(workspace).retrieval.default_profile;
|
|
141
|
+
index = new HybridSearchIndex(workspace, profile);
|
|
139
142
|
searchIndexes.set(workspace, index);
|
|
140
143
|
}
|
|
141
144
|
return index;
|
|
@@ -145,6 +148,13 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
145
148
|
const syncRetrievalStatus = (ctx: any, customText?: string) => {
|
|
146
149
|
if (!ctx?.ui?.setStatus) return;
|
|
147
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
|
+
|
|
148
158
|
const index = getSearchIndex(cwd);
|
|
149
159
|
const eff = index.getEffectiveProfile();
|
|
150
160
|
if (eff === "off") {
|
|
@@ -162,28 +172,32 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
162
172
|
activeTui?.requestRender?.();
|
|
163
173
|
};
|
|
164
174
|
|
|
175
|
+
let activeIndexingGeneration = 0;
|
|
176
|
+
|
|
165
177
|
const triggerBackgroundIndexing = (
|
|
166
178
|
index: HybridSearchIndex,
|
|
167
179
|
ctx: any,
|
|
168
180
|
isFullSync = false,
|
|
169
181
|
) => {
|
|
182
|
+
const currentGeneration = ++activeIndexingGeneration;
|
|
170
183
|
const eff = index.getEffectiveProfile();
|
|
171
184
|
if (eff === "off") {
|
|
172
185
|
syncRetrievalStatus(ctx);
|
|
173
186
|
return;
|
|
174
187
|
}
|
|
175
188
|
|
|
176
|
-
const engineTag = formatSearchEngineTag(index, true);
|
|
177
189
|
const streamArrow = "\x1b[38;2;155;210;170m⇢\x1b[0m";
|
|
178
190
|
syncRetrievalStatus(
|
|
179
191
|
ctx,
|
|
180
|
-
`${
|
|
192
|
+
`${formatSearchEngineTag(index, true)} ${streamArrow} \x1b[38;2;165;175;190m(indexing...)\x1b[0m`,
|
|
181
193
|
);
|
|
182
194
|
|
|
183
195
|
const runSync = async () => {
|
|
184
196
|
return await index.syncWorkspace(
|
|
185
197
|
isFullSync,
|
|
186
198
|
(msg: string) => {
|
|
199
|
+
if (currentGeneration !== activeIndexingGeneration) return;
|
|
200
|
+
const engineTag = formatSearchEngineTag(index, true);
|
|
187
201
|
const pctMatch = msg.match(/(\d+)%/);
|
|
188
202
|
const speedMatch = msg.match(/([\d.]+\s*chunk\/s)/);
|
|
189
203
|
const countMatch = msg.match(/\((\d+)\/(\d+)/);
|
|
@@ -217,6 +231,12 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
217
231
|
// while progress stays cleanly reported on the statusline.
|
|
218
232
|
void runSync()
|
|
219
233
|
.then((result) => {
|
|
234
|
+
if (currentGeneration !== activeIndexingGeneration) return;
|
|
235
|
+
if (index.getEffectiveProfile() === "off") {
|
|
236
|
+
ctx?.ui?.setStatus?.("retrieval", "");
|
|
237
|
+
activeTui?.requestRender?.();
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
220
240
|
syncRetrievalStatus(ctx); // Reset to clean idle tag on status line
|
|
221
241
|
if (
|
|
222
242
|
(result.indexedCount !== undefined ? result.indexedCount > 0 : false) ||
|
|
@@ -229,6 +249,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
229
249
|
}
|
|
230
250
|
})
|
|
231
251
|
.catch((err: any) => {
|
|
252
|
+
if (currentGeneration !== activeIndexingGeneration) return;
|
|
232
253
|
syncRetrievalStatus(ctx);
|
|
233
254
|
ctx.ui?.notify?.(`Indexing error: ${err.message}`, "error");
|
|
234
255
|
});
|
|
@@ -255,6 +276,40 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
255
276
|
}
|
|
256
277
|
};
|
|
257
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
|
+
|
|
303
|
+
registerAgentKernelCommand(pi, {
|
|
304
|
+
getConfig,
|
|
305
|
+
invalidateConfig: (cwd, ctx) => {
|
|
306
|
+
applyConfigChanges(cwd, ctx);
|
|
307
|
+
},
|
|
308
|
+
clearCaches: () => {
|
|
309
|
+
cachedRepoMap = "";
|
|
310
|
+
},
|
|
311
|
+
});
|
|
312
|
+
|
|
258
313
|
pi.registerCommand("pi-docs", {
|
|
259
314
|
description: "Toggle Pi documentation guidance in the system prompt",
|
|
260
315
|
getArgumentCompletions: (prefix: string) => {
|
|
@@ -307,44 +362,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
307
362
|
},
|
|
308
363
|
});
|
|
309
364
|
|
|
310
|
-
// Slash Command: /profile [auto|smart|light|heavy|status]
|
|
311
|
-
pi.registerCommand("profile", {
|
|
312
|
-
description: "Configure codebase scale profile (auto/smart | light | heavy | status)",
|
|
313
|
-
getArgumentCompletions: (prefix: string) => {
|
|
314
|
-
const options = [
|
|
315
|
-
{ value: "auto", label: "auto (smart) - Auto-detect scale from codebase metrics" },
|
|
316
|
-
{ value: "light", label: "light - Force light profile (suppress auto repo-map)" },
|
|
317
|
-
{ value: "heavy", label: "heavy - Force heavy profile (always inject repo-map)" },
|
|
318
|
-
{ value: "status", label: "status - Display current profile & codebase metrics" },
|
|
319
|
-
];
|
|
320
|
-
const filtered = options.filter((o) => o.value.startsWith(prefix.toLowerCase()));
|
|
321
|
-
return filtered.length > 0 ? filtered : null;
|
|
322
|
-
},
|
|
323
|
-
handler: async (args: string, ctx: any) => {
|
|
324
|
-
const sessionId = getSessionId(ctx);
|
|
325
|
-
const raw = (args || "").trim().toLowerCase();
|
|
326
|
-
const val = raw === "smart" ? "auto" : raw;
|
|
327
|
-
|
|
328
|
-
if (val === "auto" || val === "light" || val === "heavy") {
|
|
329
|
-
codebaseProfileBySession.set(sessionId, val);
|
|
330
|
-
cachedRepoMap = "";
|
|
331
|
-
const msg = `Codebase profile set to '${val}' for this session.`;
|
|
332
|
-
ctx.ui?.notify?.(msg, "info");
|
|
333
|
-
if (!ctx.hasUI) console.log(msg);
|
|
334
|
-
return;
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
338
|
-
const current = codebaseProfileBySession.get(sessionId) ?? getConfig(currentCwd).retrieval.codebase_profile;
|
|
339
|
-
const metrics = evaluateCodebaseMetrics(currentCwd);
|
|
340
|
-
const detected = metrics.isLight ? "light" : "heavy";
|
|
341
|
-
const effective = current === "auto" ? detected : current;
|
|
342
|
-
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)`;
|
|
343
|
-
ctx.ui?.notify?.(statusMsg, "info");
|
|
344
|
-
if (!ctx.hasUI) console.log("\n" + statusMsg + "\n");
|
|
345
|
-
},
|
|
346
|
-
});
|
|
347
|
-
|
|
348
365
|
// Slash Command: /engine [auto|lean|hybrid|full|off|status|reindex]
|
|
349
366
|
pi.registerCommand("engine", {
|
|
350
367
|
description:
|
|
@@ -399,8 +416,9 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
399
416
|
sub === "full" ||
|
|
400
417
|
sub === "off"
|
|
401
418
|
) {
|
|
402
|
-
|
|
403
|
-
|
|
419
|
+
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
420
|
+
savePersistedProfile(sub as SearchProfile, currentCwd);
|
|
421
|
+
applyConfigChanges(currentCwd, ctx);
|
|
404
422
|
const status = index.getStatus();
|
|
405
423
|
const msg = `Default search profile saved: ${sub.toUpperCase()} (Effective: ${status.effectiveProfile.toUpperCase()})`;
|
|
406
424
|
ctx.ui?.notify?.(msg, "info");
|
|
@@ -459,6 +477,11 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
459
477
|
const effName = eff.toUpperCase();
|
|
460
478
|
|
|
461
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
|
+
}
|
|
462
485
|
ctx.ui?.notify?.(
|
|
463
486
|
`Engine set to ${profileName} (Effective: ${effName})`,
|
|
464
487
|
"info",
|
|
@@ -496,42 +519,34 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
496
519
|
);
|
|
497
520
|
if (!choice || choice.startsWith("──")) return;
|
|
498
521
|
|
|
499
|
-
|
|
500
|
-
let
|
|
501
|
-
|
|
502
|
-
if (choice.includes("
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
index
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
ctx.ui.notify("Default search profile saved: OFF", "info");
|
|
521
|
-
} else if (choice.includes("Re-index")) {
|
|
522
|
-
isReindex = true;
|
|
523
|
-
} 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")) {
|
|
524
543
|
const s = index.getStatus();
|
|
525
544
|
ctx.ui.notify(
|
|
526
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`,
|
|
527
546
|
"info",
|
|
528
547
|
);
|
|
548
|
+
return;
|
|
529
549
|
}
|
|
530
|
-
|
|
531
|
-
if (profileChanged || isReindex) {
|
|
532
|
-
triggerBackgroundIndexing(index, ctx, isReindex);
|
|
533
|
-
}
|
|
534
|
-
return;
|
|
535
550
|
}
|
|
536
551
|
|
|
537
552
|
// CLI fallback if not in UI mode
|
|
@@ -691,13 +706,24 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
691
706
|
} catch (e) {
|
|
692
707
|
kernelDebug(e);
|
|
693
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
|
+
}
|
|
694
717
|
});
|
|
695
718
|
|
|
696
719
|
// 4-8. Tools: Core tools (read, edit) and code_search are registered.
|
|
697
720
|
// Speculative AST dump and heavy daemon tools (ast_search, repo_map, lsp) remain optional
|
|
698
721
|
// to avoid prompt bloat on routine tasks.
|
|
699
722
|
const invalidateSearchFile = (cwd: string, filePath: string) => {
|
|
700
|
-
getSearchIndex(cwd)
|
|
723
|
+
const index = getSearchIndex(cwd);
|
|
724
|
+
void index.updateFile(filePath).catch((err) => {
|
|
725
|
+
kernelDebug(`Incremental updateFile error for ${filePath}: ${err}`);
|
|
726
|
+
});
|
|
701
727
|
};
|
|
702
728
|
registerReadTool(pi, { getSessionId, getConfig });
|
|
703
729
|
registerEditTool(pi, { getSessionId, getConfig, invalidateSearchFile });
|
|
@@ -758,16 +784,16 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
758
784
|
|
|
759
785
|
// 9. Tool Result Interceptor: Syntax Validation & Output Clamping (ACI)
|
|
760
786
|
pi.on("tool_result", async (event: any, ctx: any) => {
|
|
761
|
-
const
|
|
762
|
-
if (event.isError && !
|
|
787
|
+
const isShell = event.toolName === "bash" || event.toolName === "powershell";
|
|
788
|
+
if (event.isError && !isShell) return;
|
|
763
789
|
|
|
764
790
|
// resultContent === undefined means "no transformation, return event.content as-is".
|
|
765
791
|
const toolName = event.toolName;
|
|
766
792
|
let resultContent: any = undefined;
|
|
767
793
|
let didBail = false;
|
|
768
794
|
|
|
769
|
-
// 9a. Intercept bash &
|
|
770
|
-
if (toolName === "bash") {
|
|
795
|
+
// 9a. Intercept bash & powershell output to clamp minified lines & massive match floods
|
|
796
|
+
if (toolName === "bash" || toolName === "powershell") {
|
|
771
797
|
const command = (event.input as any)?.command || "";
|
|
772
798
|
const outputConfig = getConfig(
|
|
773
799
|
ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
|
|
@@ -830,7 +856,9 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
830
856
|
const resultCwd =
|
|
831
857
|
ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
832
858
|
const resolvedPath = resolveUserPath(targetPath, resultCwd);
|
|
833
|
-
getSearchIndex(resultCwd).
|
|
859
|
+
void getSearchIndex(resultCwd).updateFile(resolvedPath).catch((err) => {
|
|
860
|
+
kernelDebug(`Incremental updateFile error for ${resolvedPath}: ${err}`);
|
|
861
|
+
});
|
|
834
862
|
|
|
835
863
|
// Update epistemic guard ledger with the newly written file
|
|
836
864
|
try {
|
|
@@ -956,7 +984,11 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
956
984
|
let clampedDiff = lines.slice(0, maxLines).join("\n");
|
|
957
985
|
let wasByteTruncated = false;
|
|
958
986
|
if (Buffer.byteLength(clampedDiff, "utf8") > maxDiffBytes) {
|
|
959
|
-
|
|
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
|
+
}
|
|
960
992
|
wasByteTruncated = true;
|
|
961
993
|
}
|
|
962
994
|
const truncatedNotice = lines.length > maxLines || wasByteTruncated
|
|
@@ -989,7 +1021,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
989
1021
|
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
990
1022
|
const kernelConfig = getConfig(currentCwd);
|
|
991
1023
|
const sessionId = getSessionId(ctx);
|
|
992
|
-
const profile = codebaseProfileBySession.get(sessionId) ?? kernelConfig.retrieval.codebase_profile ?? "auto";
|
|
993
1024
|
|
|
994
1025
|
let shouldInjectMap = false;
|
|
995
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}`;
|