@floydous/pi-agent-kernel 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +108 -0
  3. package/config.toml +24 -0
  4. package/docs/README.md +22 -0
  5. package/docs/architecture.md +40 -0
  6. package/docs/configuration.md +43 -0
  7. package/docs/editing-and-verification.md +41 -0
  8. package/docs/lsp.md +31 -0
  9. package/docs/retrieval.md +42 -0
  10. package/docs/testing.md +32 -0
  11. package/package.json +48 -0
  12. package/src/config/index.ts +2 -0
  13. package/src/config/kernel_config.ts +218 -0
  14. package/src/config/toml.ts +237 -0
  15. package/src/context/session_repair.ts +99 -0
  16. package/src/dedup/content_store.ts +365 -0
  17. package/src/dedup/recall_tool.ts +157 -0
  18. package/src/editing/patch.ts +482 -0
  19. package/src/editing/post_edit_verification.ts +200 -0
  20. package/src/editing/syntax-verify.ts +353 -0
  21. package/src/index.ts +852 -0
  22. package/src/lsp/adapters/base.ts +42 -0
  23. package/src/lsp/adapters/index.ts +21 -0
  24. package/src/lsp/adapters/python.ts +37 -0
  25. package/src/lsp/adapters/rust.ts +35 -0
  26. package/src/lsp/adapters/typescript.ts +40 -0
  27. package/src/lsp/index.ts +13 -0
  28. package/src/lsp/lsp_client.ts +650 -0
  29. package/src/lsp/lsp_detector.ts +52 -0
  30. package/src/lsp/lsp_formatter.ts +284 -0
  31. package/src/lsp/lsp_installer.ts +604 -0
  32. package/src/lsp/lsp_manager.ts +202 -0
  33. package/src/lsp/lsp_modal.ts +675 -0
  34. package/src/lsp/lsp_registry.ts +539 -0
  35. package/src/lsp/lsp_types.ts +143 -0
  36. package/src/retrieval/ast_search.ts +926 -0
  37. package/src/retrieval/repomap.ts +779 -0
  38. package/src/retrieval/search_bm25.ts +190 -0
  39. package/src/retrieval/search_chunker.ts +251 -0
  40. package/src/retrieval/search_config.ts +162 -0
  41. package/src/retrieval/search_embedder.ts +362 -0
  42. package/src/retrieval/search_index.ts +753 -0
  43. package/src/retrieval/search_modal.ts +358 -0
  44. package/src/retrieval/symbol_reader.ts +200 -0
  45. package/src/safety/atomic_write.ts +26 -0
  46. package/src/safety/epistemic_guard.ts +733 -0
  47. package/src/safety/kernel_debug.ts +15 -0
  48. package/src/safety/output_clamper.ts +213 -0
  49. package/src/tools/ast_search_tool.ts +131 -0
  50. package/src/tools/code_search_tool.ts +147 -0
  51. package/src/tools/context.ts +20 -0
  52. package/src/tools/edit_tool.ts +288 -0
  53. package/src/tools/lsp_tool.ts +813 -0
  54. package/src/tools/read_tool.ts +348 -0
  55. package/src/tools/repo_map_tool.ts +57 -0
  56. package/src/ui/footer.ts +287 -0
  57. package/src/ui/tui_utils.ts +278 -0
package/src/index.ts ADDED
@@ -0,0 +1,852 @@
1
+ import * as path from "path";
2
+ import * as fs from "node:fs";
3
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+ import { computeRepoMap } from "./retrieval/repomap";
5
+ import { HybridSearchIndex } from "./retrieval/search_index";
6
+ import type { SearchProfile } from "./retrieval/search_config";
7
+ import { SearchControlModal } from "./retrieval/search_modal";
8
+ import { checkSyntax } from "./editing/syntax-verify";
9
+ import {
10
+ globalEpistemicGuard,
11
+ resolveUserPath,
12
+ } from "./safety/epistemic_guard";
13
+ import { loadKernelConfig } from "./config";
14
+ import { kernelDebug } from "./safety/kernel_debug";
15
+ import { registerRepoMapTool } from "./tools/repo_map_tool";
16
+ import { registerAstSearchTool } from "./tools/ast_search_tool";
17
+ import { registerCodeSearchTool } from "./tools/code_search_tool";
18
+ import { registerReadTool } from "./tools/read_tool";
19
+ import { registerEditTool } from "./tools/edit_tool";
20
+ import { registerLspTool } from "./tools/lsp_tool";
21
+
22
+ /**
23
+ * Resolve the current session id from a handler context, or fall back to a
24
+ * shared default for single-session CLI use and in-memory sessions that
25
+ * have no UUID assigned.
26
+ */
27
+ let fallbackSessionCounter = 0;
28
+ const fallbackSessionIds = new WeakMap<object, string>();
29
+
30
+ function getSessionId(ctx: any): string {
31
+ const provided = ctx?.sessionManager?.getSessionId?.();
32
+ if (typeof provided === "string" && provided.length > 0) return provided;
33
+
34
+ if (ctx && (typeof ctx === "object" || typeof ctx === "function")) {
35
+ let fallback = fallbackSessionIds.get(ctx);
36
+ if (!fallback) {
37
+ fallback = `__default__${process.pid}_${++fallbackSessionCounter}__`;
38
+ fallbackSessionIds.set(ctx, fallback);
39
+ }
40
+ return fallback;
41
+ }
42
+
43
+ return `__default__${process.pid}`;
44
+ }
45
+ import { clampCommandOutput } from "./safety/output_clamper";
46
+ import { sanitizeSessionFiles } from "./context/session_repair";
47
+ import { renderFooter } from "./ui/footer";
48
+ import { DedupStore } from "./dedup/content_store";
49
+ import { registerRecallTool } from "./dedup/recall_tool";
50
+ import {
51
+ LspManager,
52
+ LspControlModal,
53
+ LspDownloadModal,
54
+ formatDiagnostics,
55
+ installLanguageServer,
56
+ LSP_SERVERS,
57
+ findExecutable,
58
+ } from "./lsp";
59
+
60
+ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
61
+ // 0. Auto-Sanitize Session Files (Repairs pre-existing incomplete usage metadata)
62
+ try {
63
+ sanitizeSessionFiles();
64
+ } catch (e) {
65
+ kernelDebug(e);
66
+ }
67
+
68
+ // 0b. Dedup store: shared across all sessions in this process. Per-session
69
+ // state is keyed by sessionId. A single instance lets the dedup store
70
+ // benefit from cross-session LRU and lets the recall tool look up refs
71
+ // from any active session.
72
+ const dedupStore = new DedupStore();
73
+ const getDedupStore = () => dedupStore;
74
+
75
+ // 3. Slash Commands: /repomap, /engine, /lsp
76
+ let activeTui: any = null;
77
+ const configByWorkspace = new Map<
78
+ string,
79
+ ReturnType<typeof loadKernelConfig>
80
+ >();
81
+ const getConfig = (cwd: string) => {
82
+ const workspace = path.resolve(cwd);
83
+ let config = configByWorkspace.get(workspace);
84
+ if (!config) {
85
+ config = loadKernelConfig(workspace);
86
+ configByWorkspace.set(workspace, config);
87
+ }
88
+ return config;
89
+ };
90
+ const searchIndexes = new Map<string, HybridSearchIndex>();
91
+ const getSearchIndex = (cwd: string) => {
92
+ const workspace = path.resolve(cwd);
93
+ let index = searchIndexes.get(workspace);
94
+ if (!index) {
95
+ index = new HybridSearchIndex(workspace);
96
+ searchIndexes.set(workspace, index);
97
+ }
98
+ return index;
99
+ };
100
+
101
+ // Helper: Background index synchronization with TUI progress bar widget
102
+ const triggerBackgroundIndexing = (
103
+ index: HybridSearchIndex,
104
+ ctx: any,
105
+ isFullSync = false,
106
+ ) => {
107
+ const eff = index.getEffectiveProfile();
108
+ if (eff === "off") {
109
+ ctx.ui?.setWidget?.("engine-progress", undefined);
110
+ return;
111
+ }
112
+
113
+ if (eff === "lean") {
114
+ ctx.ui?.setWidget?.("engine-progress", undefined);
115
+ ctx.ui?.notify?.(
116
+ `Lean mode active (${index.getStatus().chunkCount} chunks ready in RAM)`,
117
+ "info",
118
+ );
119
+ return;
120
+ }
121
+
122
+ const isVectorProfile = eff === "hybrid" || eff === "full";
123
+ const updateWidget = (line: string) => {
124
+ ctx.ui?.setWidget?.("engine-progress", [line], { placement: "belowEditor" });
125
+ };
126
+ const clearWidget = () => {
127
+ ctx.ui?.setWidget?.("engine-progress", undefined);
128
+ };
129
+
130
+ const runSync = async () => {
131
+ if (isVectorProfile) {
132
+ updateWidget("\x1b[38;5;244mEngine: Loading embedding model...\x1b[0m");
133
+ await index.preloadModel((msg: string) => {
134
+ updateWidget(`\x1b[38;5;244mEngine: ${msg.slice(0, 40)}\x1b[0m`);
135
+ });
136
+ }
137
+ return await index.syncWorkspace(
138
+ isFullSync,
139
+ (msg: string) => {
140
+ const pctMatch = msg.match(/(\d+)%/);
141
+ if (pctMatch) {
142
+ const pct = parseInt(pctMatch[1], 10);
143
+ const barLen = 16;
144
+ const filled = Math.round((pct / 100) * barLen);
145
+ const empty = barLen - filled;
146
+ const bar =
147
+ "\x1b[38;5;248m" +
148
+ "█".repeat(filled) +
149
+ "\x1b[38;5;238m" +
150
+ "░".repeat(empty) +
151
+ "\x1b[0m";
152
+ updateWidget(
153
+ `\x1b[38;5;244mEngine:\x1b[0m [${bar}] \x1b[38;5;250m${pct}%\x1b[0m \x1b[38;5;242mIndexing workspace\x1b[0m`,
154
+ );
155
+ } else {
156
+ updateWidget(`\x1b[38;5;244mEngine: ${msg.slice(0, 40)}\x1b[0m`);
157
+ }
158
+ },
159
+ );
160
+ };
161
+
162
+ // Keep profile changes responsive: model warm-up and indexing run in the
163
+ // existing background lifecycle, while progress remains visible in the UI.
164
+ void runSync()
165
+ .then((result) => {
166
+ clearWidget();
167
+ ctx.ui?.notify?.(
168
+ `Search index ready (${result.chunkCount} chunks in ${result.fileCount} files)`,
169
+ "info",
170
+ );
171
+ })
172
+ .catch((err: any) => {
173
+ clearWidget();
174
+ ctx.ui?.notify?.(`Indexing error: ${err.message}`, "error");
175
+ });
176
+ };
177
+
178
+ const setupUnifiedFooter = (ctx: any) => {
179
+ if (ctx.hasUI && ctx.ui?.setFooter) {
180
+ ctx.ui.setFooter((tui: any, theme: any, footerData: any) => {
181
+ activeTui = tui;
182
+ const unsubBranch = footerData?.onBranchChange?.(() =>
183
+ tui.requestRender?.(),
184
+ );
185
+ const currentIndex = getSearchIndex(
186
+ ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
187
+ );
188
+ return {
189
+ dispose: () => unsubBranch?.(),
190
+ invalidate: () => {},
191
+ render: (width: number) =>
192
+ renderFooter(ctx, theme, footerData, width, currentIndex),
193
+ };
194
+ });
195
+ }
196
+ };
197
+
198
+ pi.registerCommand("repomap", {
199
+ description: "Display the Tree-Sitter AST & PageRank ranked repository map",
200
+ handler: async (args: string, ctx: any) => {
201
+ const budget = args ? parseInt(args, 10) : 1024;
202
+ const map = computeRepoMap(
203
+ ctx.cwd,
204
+ Number.isNaN(budget)
205
+ ? getConfig(ctx.cwd).retrieval.repo_map_budget
206
+ : budget,
207
+ );
208
+ ctx.ui?.notify?.("Repository Map Generated", "info");
209
+ if (ctx.hasUI && ctx.ui?.setWidget) {
210
+ ctx.ui.setWidget("repomap-widget", map.split("\n").slice(0, 25));
211
+ } else if (!ctx.hasUI) {
212
+ console.log("\n" + map + "\n");
213
+ }
214
+ },
215
+ });
216
+
217
+ // Slash Command: /engine [auto|lean|hybrid|full|off|status|reindex]
218
+ pi.registerCommand("engine", {
219
+ description:
220
+ "Configure codebase retrieval engine (auto | lean | hybrid | full | off | status | reindex)",
221
+ getArgumentCompletions: (prefix: string) => {
222
+ const options = [
223
+ {
224
+ value: "status",
225
+ label: "status - Display current engine profile, memory & diagnostics",
226
+ },
227
+ {
228
+ value: "auto",
229
+ label:
230
+ "auto - Auto-detect: Lean (VPS), Hybrid (Laptop), Full (Workstation)",
231
+ },
232
+ {
233
+ value: "lean",
234
+ label:
235
+ "lean - Fast AST-aware BM25 (0% CPU, 0 MB extra RAM) [Persisted Default]",
236
+ },
237
+ {
238
+ value: "hybrid",
239
+ label:
240
+ "hybrid - Throttled 256-dim Matryoshka embeddings",
241
+ },
242
+ {
243
+ value: "full",
244
+ label: "full - Multi-core 768-dim embeddings",
245
+ },
246
+ {
247
+ value: "off",
248
+ label: "off - Disable search & unload memory",
249
+ },
250
+ { value: "reindex", label: "reindex - Force full workspace re-indexing" },
251
+ ];
252
+ const filtered = options.filter((o) =>
253
+ o.value.startsWith(prefix.toLowerCase()),
254
+ );
255
+ return filtered.length > 0 ? filtered : null;
256
+ },
257
+ handler: async (args: string, ctx: any) => {
258
+ let sub = (args || "").trim().toLowerCase();
259
+ if (sub.startsWith("default ")) {
260
+ sub = sub.replace("default ", "").trim();
261
+ }
262
+ const index = getSearchIndex(ctx.cwd);
263
+
264
+ if (
265
+ sub === "auto" ||
266
+ sub === "lean" ||
267
+ sub === "hybrid" ||
268
+ sub === "full" ||
269
+ sub === "off"
270
+ ) {
271
+ index.setProfile(sub as SearchProfile);
272
+ activeTui?.requestRender?.();
273
+ const status = index.getStatus();
274
+ const msg = `Default search profile saved: ${sub.toUpperCase()} (Effective: ${status.effectiveProfile.toUpperCase()})`;
275
+ ctx.ui?.notify?.(msg, "info");
276
+ if (!ctx.hasUI) console.log(`[Codebase Engine] ${msg}`);
277
+ return;
278
+ }
279
+
280
+ if (sub === "reindex") {
281
+ ctx.ui?.notify?.("Re-indexing workspace...", "info");
282
+ const res = await index.syncWorkspace(true, (msg) => {
283
+ if (ctx.hasUI) ctx.ui?.notify?.(msg, "info");
284
+ });
285
+ ctx.ui?.notify?.(
286
+ `Indexed ${res.fileCount} files (${res.chunkCount} chunks)`,
287
+ "info",
288
+ );
289
+ if (!ctx.hasUI)
290
+ console.log(
291
+ `[Codebase Engine] Re-indexed ${res.fileCount} files, ${res.chunkCount} chunks.`,
292
+ );
293
+ return;
294
+ }
295
+
296
+ if (sub === "status") {
297
+ const status = index.getStatus();
298
+ ctx.ui?.notify?.(
299
+ `Engine: ${status.engineState} | Profile: ${status.profile.toUpperCase()} (${status.effectiveProfile.toUpperCase()}) | Chunks: ${status.chunkCount} | Model: ${status.modelStatus} | RSS: ${status.rssMemoryMB}MB`,
300
+ "info",
301
+ );
302
+ if (!ctx.hasUI) {
303
+ console.log(
304
+ `Codebase Retrieval Engine Status:\n- Engine State: ${status.engineState}\n- Pipeline: ${status.pipelineDesc}\n- Default Profile: ${status.profile.toUpperCase()} (persisted in ~/.pi/agent/search_settings.json)\n- Active Mode: ${status.effectiveProfile.toUpperCase()} (${status.hardwareInfo})\n- Indexed Files: ${status.fileCount}\n- Code Chunks: ${status.chunkCount}\n- Vector Embeddings: ${status.vectorCount}\n- Model Status: ${status.modelStatus}\n- Process RSS: ${status.rssMemoryMB} MB`,
305
+ );
306
+ }
307
+ return;
308
+ }
309
+
310
+ // Interactive centered modal dialog with full-viewport backdrop scrim
311
+ if (ctx.hasUI && ctx.ui?.custom) {
312
+ const res: any = await ctx.ui.custom(
313
+ (tui: any, theme: any, _keybindings: any, done: any) =>
314
+ new SearchControlModal(tui, index, theme, done),
315
+ {
316
+ overlay: true,
317
+ overlayOptions: {
318
+ anchor: "center",
319
+ width: "100%",
320
+ },
321
+ },
322
+ );
323
+
324
+ if (res) {
325
+ activeTui?.requestRender?.();
326
+ const eff = index.getEffectiveProfile();
327
+ const profileName = (res.profile || index.getProfile()).toUpperCase();
328
+ const effName = eff.toUpperCase();
329
+
330
+ if (res.action === "select") {
331
+ ctx.ui?.notify?.(
332
+ `Engine set to ${profileName} (Effective: ${effName})`,
333
+ "info",
334
+ );
335
+ }
336
+
337
+ if (res.reindexed || eff !== "off") {
338
+ triggerBackgroundIndexing(index, ctx, res.action === "reindex");
339
+ } else {
340
+ ctx.ui?.setWidget?.("engine-progress", undefined);
341
+ }
342
+ }
343
+ return;
344
+ }
345
+
346
+ // Fallback select menu if custom overlays are unavailable
347
+ if (ctx.hasUI && ctx.ui?.select) {
348
+ const status = index.getStatus();
349
+ const currentProfile = index.getProfile();
350
+ const options = [
351
+ `View Status (${status.engineState} - ${status.chunkCount} chunks, RSS ${status.rssMemoryMB}MB)`,
352
+ `── Profiles ───────────────────────`,
353
+ `Set Default: Auto Detect (Lean -> Hybrid -> Full based on specs)${currentProfile === "auto" ? " [Current]" : ""}`,
354
+ `Set Default: Lean Mode (Fast BM25, 0% CPU, 0 MB extra RAM)${currentProfile === "lean" ? " [Current]" : ""}`,
355
+ `Set Default: Hybrid Mode (Throttled 256-dim Matryoshka)${currentProfile === "hybrid" ? " [Current]" : ""}`,
356
+ `Set Default: Full Mode (768-dim embeddings)${currentProfile === "full" ? " [Current]" : ""}`,
357
+ `Set Default: Disable Engine (Turn off search)${currentProfile === "off" ? " [Current]" : ""}`,
358
+ `── Actions ────────────────────────`,
359
+ `Re-index Workspace`,
360
+ ];
361
+
362
+ const choice = await ctx.ui.select(
363
+ "Codebase Retrieval Engine Settings",
364
+ options,
365
+ );
366
+ if (!choice || choice.startsWith("──")) return;
367
+
368
+ let profileChanged = false;
369
+ let isReindex = false;
370
+
371
+ if (choice.includes("Auto Detect")) {
372
+ index.setProfile("auto");
373
+ ctx.ui.notify("Default search profile saved: AUTO", "info");
374
+ profileChanged = true;
375
+ } else if (choice.includes("Lean Mode")) {
376
+ index.setProfile("lean");
377
+ ctx.ui.notify("Default search profile saved: LEAN", "info");
378
+ profileChanged = true;
379
+ } else if (choice.includes("Hybrid Mode")) {
380
+ index.setProfile("hybrid");
381
+ ctx.ui.notify("Default search profile saved: HYBRID", "info");
382
+ profileChanged = true;
383
+ } else if (choice.includes("Full Mode")) {
384
+ index.setProfile("full");
385
+ ctx.ui.notify("Default search profile saved: FULL", "info");
386
+ profileChanged = true;
387
+ } else if (choice.includes("Disable Engine")) {
388
+ index.setProfile("off");
389
+ ctx.ui.notify("Default search profile saved: OFF", "info");
390
+ } else if (choice.includes("Re-index")) {
391
+ isReindex = true;
392
+ } else if (choice.includes("View Status")) {
393
+ const s = index.getStatus();
394
+ ctx.ui.notify(
395
+ `Engine: ${s.engineState} | Profile: ${s.profile.toUpperCase()} (Effective: ${s.effectiveProfile.toUpperCase()}) | Files: ${s.fileCount} | Chunks: ${s.chunkCount} | Model: ${s.modelStatus} | RSS: ${s.rssMemoryMB}MB`,
396
+ "info",
397
+ );
398
+ }
399
+
400
+ if (profileChanged || isReindex) {
401
+ triggerBackgroundIndexing(index, ctx, isReindex);
402
+ }
403
+ return;
404
+ }
405
+
406
+ // CLI fallback if not in UI mode
407
+ const status = index.getStatus();
408
+ const msg = `Search Status:\n- Engine: ${status.engineState}\n- Profile: ${status.profile} (effective: ${status.effectiveProfile})\n- Indexed Files: ${status.fileCount}\n- Code Chunks: ${status.chunkCount}\n- Vector Embeddings: ${status.vectorCount}\n- Model: ${status.modelStatus}\n- Process RSS: ${status.rssMemoryMB} MB`;
409
+ console.log("\n" + msg + "\n");
410
+ },
411
+ });
412
+
413
+ // Slash Command: /lsp (Inspect language servers, active daemons, or install language servers)
414
+ pi.registerCommand("lsp", {
415
+ description:
416
+ "Inspect language servers, active daemons, or install servers (/lsp, /lsp install <lang>)",
417
+ getArgumentCompletions: (prefix: string) => {
418
+ const options = [
419
+ {
420
+ value: "status",
421
+ label: "status - View LSP status and active daemon processes",
422
+ },
423
+ { value: "stop", label: "stop - Stop all active LSP daemon processes" },
424
+ {
425
+ value: "install",
426
+ label:
427
+ "install - Install an LSP server (e.g. pyright, typescript-language-server, gopls, rust-analyzer, clangd)",
428
+ },
429
+ ];
430
+ const filtered = options.filter((o) =>
431
+ o.value.startsWith(prefix.toLowerCase()),
432
+ );
433
+ return filtered.length > 0 ? filtered : null;
434
+ },
435
+ async handler(args: string, ctx: any) {
436
+ const sub = args.trim().split(/\s+/);
437
+ const lspMgr = LspManager.getInstance();
438
+
439
+ if (sub[0] === "install" && sub[1]) {
440
+ const target = sub[1];
441
+ if (ctx.hasUI && ctx.ui?.notify) {
442
+ ctx.ui.notify(`Installing LSP server for ${target}...`, "info");
443
+ }
444
+ const res = await installLanguageServer(target, (msg) => {
445
+ if (ctx.hasUI && ctx.ui?.notify) {
446
+ ctx.ui.notify(msg, "info");
447
+ }
448
+ });
449
+ if (res.success) {
450
+ ctx.ui?.notify?.(res.message, "info");
451
+ } else {
452
+ ctx.ui?.notify?.(res.message, "error");
453
+ }
454
+ return;
455
+ }
456
+
457
+ if (sub[0] === "stop" || sub[0] === "kill") {
458
+ await lspMgr.stopAll();
459
+ ctx.ui?.notify?.("All active LSP servers stopped.", "info");
460
+ return;
461
+ }
462
+
463
+ // Interactive centered modal dialog with full-viewport backdrop scrim
464
+ if (ctx.hasUI && ctx.ui?.custom) {
465
+ const res: any = await ctx.ui.custom(
466
+ (tui: any, theme: any, _keybindings: any, done: any) =>
467
+ new LspControlModal(tui, lspMgr, theme, done),
468
+ {
469
+ overlay: true,
470
+ overlayOptions: {
471
+ anchor: "center",
472
+ width: "100%",
473
+ },
474
+ },
475
+ );
476
+
477
+ if (res) {
478
+ if (res.action === "stop") {
479
+ await lspMgr.stopAll();
480
+ ctx.ui?.notify?.("All active LSP servers stopped.", "info");
481
+ } else if (res.installTargets && res.installTargets.length > 0) {
482
+ // Spawn animated ASCII loading spinner modal
483
+ await ctx.ui.custom(
484
+ (tui: any, theme: any, _keybindings: any, done: any) =>
485
+ new LspDownloadModal(tui, res.installTargets, theme, done),
486
+ {
487
+ overlay: true,
488
+ overlayOptions: {
489
+ anchor: "center",
490
+ width: "100%",
491
+ },
492
+ },
493
+ );
494
+ }
495
+ }
496
+ return;
497
+ }
498
+
499
+ const activeClients = lspMgr.getStatus();
500
+ if (ctx.hasUI && ctx.ui?.select) {
501
+ const lines = [
502
+ `── Active LSP Daemons (${activeClients.length}) ────────────────`,
503
+ ...activeClients.map(
504
+ (c) =>
505
+ `[Active] ${c.languageId.toUpperCase()} (State: ${c.state}, Idle: ${c.idleSeconds}s)`,
506
+ ),
507
+ `── Installed / Available Servers ─────────────────────────────`,
508
+ ...Object.entries(LSP_SERVERS)
509
+ .slice(0, 10)
510
+ .map(([k, cfg]) => {
511
+ const primaryBin = cfg.commands[0]?.bin;
512
+ const found = findExecutable(primaryBin);
513
+ return `[${found ? "✓" : "✗"}] ${k.padEnd(12)} → ${primaryBin} ${found ? `(${found})` : "(not installed)"}`;
514
+ }),
515
+ `── Actions ───────────────────────────────────────────────────`,
516
+ `Stop all active LSP daemons`,
517
+ ];
518
+
519
+ const choice = await ctx.ui.select("LSP Server Status & Management", lines);
520
+ if (choice?.includes("Stop all active")) {
521
+ await lspMgr.stopAll();
522
+ ctx.ui.notify("All active LSP servers stopped.", "info");
523
+ }
524
+ return;
525
+ }
526
+
527
+ // Console fallback
528
+ let out = `=== LSP Status ===\nActive Daemons: ${activeClients.length}\n`;
529
+ for (const c of activeClients) {
530
+ out += ` • ${c.languageId}: ${c.state} (idle: ${c.idleSeconds}s, root: ${c.rootDir})\n`;
531
+ }
532
+ console.log(out);
533
+ },
534
+ });
535
+
536
+ // Background workspace auto-indexer on session startup + setup integrated footer
537
+ pi.on("session_start", async (_event: any, ctx: any) => {
538
+ setupUnifiedFooter(ctx);
539
+ try {
540
+ const index = getSearchIndex(ctx.cwd);
541
+ if (index.getEffectiveProfile() !== "off") {
542
+ index.syncWorkspace(false).catch(() => {});
543
+ }
544
+ } catch (e) {
545
+ kernelDebug(e);
546
+ }
547
+ });
548
+
549
+ // 2. Per-session cleanup of the epistemic guard's inspection state and LSP processes.
550
+ // Without this, Map<sessionId, Set<filePath>> grows unbounded over a
551
+ // long-lived process hosting many sessions (e.g. RPC mode). On session
552
+ // shutdown we drop only this session's entry and stop running LSP daemons.
553
+ pi.on("session_shutdown", async (_event: any, ctx: any) => {
554
+ const sessionId = getSessionId(ctx);
555
+ globalEpistemicGuard.resetSession(sessionId);
556
+ dedupStore.clearSession(sessionId);
557
+ try {
558
+ await LspManager.getInstance().stopAll();
559
+ } catch (e) {
560
+ kernelDebug(e);
561
+ }
562
+ });
563
+
564
+ // 2b. Compaction hooks: bump the dedup store's per-session counter so
565
+ // the next duplicate of any prior content is treated as a new first
566
+ // occurrence. This applies to both auto-triggered and manual compactions.
567
+ pi.on("session_before_compact", async (_event: any, ctx: any) => {
568
+ const sessionId = getSessionId(ctx);
569
+ dedupStore.onCompaction(sessionId);
570
+ });
571
+ pi.on("session_compact", async (_event: any, ctx: any) => {
572
+ const sessionId = getSessionId(ctx);
573
+ dedupStore.onCompaction(sessionId);
574
+ });
575
+
576
+ // 4-8. Tools: repo map, AST search, code search, read, edit, LSP
577
+ registerRepoMapTool(pi);
578
+ const invalidateSearchFile = (cwd: string, filePath: string) => {
579
+ getSearchIndex(cwd).invalidateFile(filePath);
580
+ };
581
+ registerAstSearchTool(pi, { getSessionId, getConfig });
582
+ registerCodeSearchTool(pi, { getSessionId, getSearchIndex, getConfig });
583
+ registerReadTool(pi, { getSessionId, getConfig });
584
+ registerEditTool(pi, { getSessionId, getConfig, invalidateSearchFile });
585
+ registerLspTool(pi, { getSessionId, getConfig });
586
+ registerRecallTool(pi, { getSessionId, getDedupStore });
587
+
588
+ // 9a. Block host writes before the host tool can create parent directories
589
+ // or overwrite the target. Bash read evidence is recorded after a successful
590
+ // command result below; preflight classification alone is not a read.
591
+ pi.on("tool_call", async (event: any, ctx: any) => {
592
+ try {
593
+ const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
594
+ const sessionId = getSessionId(ctx);
595
+ if (event.toolName !== "write") return;
596
+ const targetPath = (event.input as any)?.path;
597
+ if (typeof targetPath !== "string" || !targetPath.trim()) {
598
+ return {
599
+ block: true,
600
+ reason: "[WRITE ERROR] Missing target path.",
601
+ };
602
+ }
603
+ const config = getConfig(cwd);
604
+ const resolvedPath = resolveUserPath(targetPath, cwd);
605
+ const check = globalEpistemicGuard.checkReadPrecondition(
606
+ resolvedPath,
607
+ "write",
608
+ sessionId,
609
+ cwd,
610
+ config.safety.enable_epistemic_guard,
611
+ );
612
+ if (!check.allowed) {
613
+ // Block only this write. The model must remain able to inspect the
614
+ // rejection and choose a safe workaround or ask for clarification.
615
+ return {
616
+ block: true,
617
+ reason: check.reason,
618
+ };
619
+ }
620
+ } catch (e) {
621
+ kernelDebug(e);
622
+ if (event.toolName === "write") {
623
+ return {
624
+ block: true,
625
+ reason: `[WRITE BLOCKED] Safety preflight failed closed: ${e instanceof Error ? e.message : String(e)}`,
626
+ };
627
+ }
628
+ }
629
+ });
630
+
631
+ // 9. Tool Result Interceptor: Syntax Validation & Output Clamping (ACI)
632
+ pi.on("tool_result", async (event: any, ctx: any) => {
633
+ if (event.isError) return;
634
+
635
+ const toolName = event.toolName;
636
+ // resultContent === undefined means "no transformation, return event.content as-is".
637
+ // A non-undefined value is the content the LLM will see; the dedup check
638
+ // at the end runs on whichever form is set.
639
+ let resultContent: any = undefined;
640
+ let didBail = false;
641
+
642
+ // 9a. Intercept bash & terminal output to clamp minified lines & massive match floods
643
+ if (toolName === "bash") {
644
+ const command = (event.input as any)?.command || "";
645
+ const outputConfig = getConfig(
646
+ ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
647
+ );
648
+ let bashOutputComplete = true;
649
+ resultContent = (event.content || []).map((c: any) => {
650
+ if (c.type === "text" && typeof c.text === "string") {
651
+ const clamped = clampCommandOutput(c.text, command, {
652
+ maxLineLength: outputConfig.safety.max_line_length,
653
+ maxLines: outputConfig.safety.max_lines,
654
+ maxTotalBytes: outputConfig.safety.max_total_bytes,
655
+ });
656
+ if (clamped.truncated) {
657
+ bashOutputComplete = false;
658
+ return { ...c, text: clamped.text };
659
+ }
660
+ }
661
+ return c;
662
+ });
663
+ globalEpistemicGuard.recordCommandExecution(
664
+ command,
665
+ ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
666
+ getSessionId(ctx),
667
+ bashOutputComplete,
668
+ (resultContent || [])
669
+ .filter((c: any) => c.type === "text" && typeof c.text === "string")
670
+ .map((c: any) => c.text)
671
+ .join(""),
672
+ );
673
+ }
674
+
675
+ // 9b. Preserve the host write-tool compatibility path. The custom edit
676
+ // tool owns its complete verification lifecycle; intercepting edit results
677
+ // here would duplicate syntax/LSP work.
678
+ if (toolName === "write") {
679
+ const input = event.input as any;
680
+ const targetPath = input?.path;
681
+
682
+ // The harness does not reliably propagate result-level isError to this
683
+ // hook, so a failed edit can still reach here. Detect the edit tool's
684
+ // failure markers and bail out before post-write checks.
685
+ const resultText = (event.content || [])
686
+ .map((c: any) =>
687
+ c.type === "text" && typeof c.text === "string" ? c.text : "",
688
+ )
689
+ .join("\n");
690
+ if (
691
+ resultText.includes("[EDIT FAILED]") ||
692
+ resultText.includes("[EDIT ERROR]") ||
693
+ resultText.includes("[EPISTEMIC GUARD REJECTION]") ||
694
+ resultText.includes("[READ ERROR]")
695
+ ) {
696
+ didBail = true;
697
+ } else if (targetPath) {
698
+ const resultCwd =
699
+ ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
700
+ const resolvedPath = resolveUserPath(targetPath, resultCwd);
701
+ getSearchIndex(resultCwd).invalidateFile(resolvedPath);
702
+
703
+ // Update epistemic guard ledger with the newly written file
704
+ try {
705
+ if (fs.existsSync(resolvedPath)) {
706
+ const writtenContent = fs.readFileSync(resolvedPath, "utf8");
707
+ globalEpistemicGuard.recordFileMutation(
708
+ resolvedPath,
709
+ getSessionId(ctx),
710
+ resultCwd,
711
+ writtenContent,
712
+ { complete: true },
713
+ );
714
+ }
715
+ } catch (e) {
716
+ kernelDebug(e);
717
+ }
718
+
719
+ const syntaxRes = checkSyntax(resolvedPath);
720
+
721
+ if (!syntaxRes.valid && syntaxRes.status === "failed") {
722
+ const warning = `\n\n[SYNTAX WARNING] ${syntaxRes.error}\nPlease fix this syntax error.`;
723
+ resultContent = event.content.map((c: any) =>
724
+ c.type === "text" ? { ...c, text: c.text + warning } : c,
725
+ );
726
+ } else {
727
+ // Synchronize with active LSP daemon and fetch post-edit diagnostics if available
728
+ let lspNotice = "";
729
+ try {
730
+ const lspMgr = LspManager.getInstance();
731
+ const client = lspMgr.getReadyClientForFile(resolvedPath, resultCwd);
732
+ if (client && client.getState() === "ready") {
733
+ const fileContent = fs.readFileSync(resolvedPath, "utf8");
734
+ await client.changeDocument(resolvedPath, fileContent);
735
+ await client.saveDocument(resolvedPath, fileContent);
736
+
737
+ // Allow LSP server brief window to compute diagnostics
738
+ const diagnostics = await client.getDiagnosticsResult(resolvedPath);
739
+ if (diagnostics.diagnostics.length > 0) {
740
+ const formattedDiags = formatDiagnostics(
741
+ diagnostics.diagnostics,
742
+ resolvedPath,
743
+ resultCwd,
744
+ );
745
+ lspNotice = `\n\n[LSP Diagnostics]\n${formattedDiags}`;
746
+ } else if (diagnostics.status !== "clean") {
747
+ lspNotice = `\n\n[LSP ${diagnostics.status.toUpperCase()}] No definitive diagnostics result.`;
748
+ }
749
+ }
750
+ } catch (e) {
751
+ kernelDebug(e);
752
+ }
753
+
754
+ if (lspNotice) {
755
+ resultContent = event.content.map((c: any) =>
756
+ c.type === "text" ? { ...c, text: c.text + lspNotice } : c,
757
+ );
758
+ }
759
+ }
760
+ }
761
+ }
762
+
763
+ // 9c. Dedup pass: hash the rendered text + tool name + input params;
764
+ // if it's a byte-equal duplicate (same tool, same params, same text)
765
+ // of one already in this session's current (uncompacted) context,
766
+ // replace with a [=rN,sizeB,tool,paramsKey] reference. Bail
767
+ // branches (didBail) skip dedup; errors are filtered at the top.
768
+ // The `recall` tool is exempt: its entire purpose is to break the
769
+ // dedup chain by emitting the original bytes; if we dedup'd its
770
+ // output, the LLM would get a reference instead of the bytes it
771
+ // asked for.
772
+ if (!didBail && toolName !== "recall") {
773
+ const contentForLLM = resultContent !== undefined ? resultContent : (event.content || []);
774
+ const hasOnlyTextContent = (contentForLLM as any[]).every(
775
+ (c: any) => c.type === "text" && typeof c.text === "string",
776
+ );
777
+ const finalText = hasOnlyTextContent
778
+ ? (contentForLLM as any[]).map((c: any) => c.text).join("")
779
+ : "";
780
+ if (hasOnlyTextContent && Buffer.byteLength(finalText, "utf8") > 0) {
781
+ const sessionId = getSessionId(ctx);
782
+ const compactionCounter = dedupStore.getCompactionCounter(sessionId);
783
+ const inputParams = event.input || {};
784
+ const decision = dedupStore.record(
785
+ sessionId,
786
+ event.toolCallId || "",
787
+ toolName,
788
+ inputParams,
789
+ finalText,
790
+ false,
791
+ compactionCounter,
792
+ );
793
+ if (decision.isDuplicate) {
794
+ // Recall the prior entry's metadata so the notice names
795
+ // the tool and paramsKey. The LLM can use this to
796
+ // decide whether to recall or run a fresh tool call.
797
+ const prior = dedupStore.get(sessionId, decision.shortRef);
798
+ const priorTool = prior?.toolName ?? toolName;
799
+ const priorParamsKey = prior?.paramsKey ?? "";
800
+ resultContent = [
801
+ {
802
+ type: "text",
803
+ text: `[=${decision.shortRef},${Buffer.byteLength(finalText, "utf8")}B,${priorTool},${priorParamsKey}]`,
804
+ },
805
+ ];
806
+ }
807
+ // For first occurrence, the dedup store has the entry, but we
808
+ // don't need to return anything; Pi will use event.content as-is.
809
+ }
810
+ }
811
+
812
+ if (didBail) return;
813
+ if (resultContent !== undefined) {
814
+ return { content: resultContent };
815
+ }
816
+ });
817
+
818
+ // 10. Dynamic Runtime Context Injection (Repo Map with in-memory caching)
819
+ // Notice: Custom user instructions (AGENT.md / prompt templates) are respected as the primary authority.
820
+ // Only runtime operational metadata (repo map) is dynamically attached and cached per session/cwd.
821
+ let cachedRepoMap = "";
822
+ let cachedRepoMapCwd = "";
823
+ let lastRepoMapCheck = 0;
824
+
825
+ pi.on("before_agent_start", async (event: any, ctx: any) => {
826
+ const now = Date.now();
827
+ const currentCwd = ctx.cwd || process.cwd();
828
+
829
+ // Cache repo-map across turns with a 15-second TTL to avoid scanning/PageRanking entire repo on every turn
830
+ if (!cachedRepoMap || cachedRepoMapCwd !== currentCwd || now - lastRepoMapCheck > 15000) {
831
+ cachedRepoMap = computeRepoMap(
832
+ currentCwd,
833
+ getConfig(currentCwd).retrieval.repo_map_budget,
834
+ );
835
+ cachedRepoMapCwd = currentCwd;
836
+ lastRepoMapCheck = now;
837
+ }
838
+
839
+ const dedupNote = `\nA [=rN,sizeB,tool,paramsKey] reference means the identical result was already provided earlier in this session. It is informational, not an instruction to call recall. Use recall only when the exact content is needed and is no longer visible. For a different range, symbol, or query, run a fresh tool call.\n`;
840
+
841
+ const runtimeContext = `
842
+ ## Available Repository Context:
843
+ ${cachedRepoMap}
844
+ ${dedupNote}
845
+ `;
846
+ return {
847
+ systemPrompt: event.systemPrompt
848
+ ? `${event.systemPrompt}\n\n${runtimeContext}`
849
+ : runtimeContext,
850
+ };
851
+ });
852
+ }