@floydous/pi-agent-kernel 0.4.3 → 0.6.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 (65) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +15 -12
  2. package/CHANGELOG.md +87 -0
  3. package/README.md +6 -54
  4. package/config.example.toml +1 -8
  5. package/docs/README.md +1 -2
  6. package/docs/architecture.md +2 -3
  7. package/docs/configuration.md +11 -10
  8. package/docs/editing-and-verification.md +21 -8
  9. package/docs/podman-linux-checks.md +24 -0
  10. package/docs/release-discipline.md +10 -0
  11. package/docs/retrieval.md +21 -23
  12. package/docs/testing.md +3 -3
  13. package/grammars/tree-sitter-html.wasm +0 -0
  14. package/package.json +5 -3
  15. package/src/config/agent_kernel_command.ts +60 -625
  16. package/src/config/kernel_config.ts +53 -69
  17. package/src/config/toml.ts +6 -1
  18. package/src/editing/auto_heal.ts +1 -1
  19. package/src/editing/patch.ts +75 -37
  20. package/src/editing/post_edit_verification.ts +20 -14
  21. package/src/editing/smart_anchor.ts +9 -6
  22. package/src/editing/syntax-verify.ts +79 -222
  23. package/src/index.ts +36 -453
  24. package/src/retrieval/html_chunker.ts +526 -0
  25. package/src/retrieval/search_bm25.ts +39 -28
  26. package/src/retrieval/search_chunker.ts +69 -7
  27. package/src/retrieval/search_config.ts +21 -40
  28. package/src/retrieval/search_embedder.ts +14 -31
  29. package/src/retrieval/search_index.ts +338 -129
  30. package/src/retrieval/search_modal.ts +1208 -222
  31. package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
  32. package/src/retrieval/tree_sitter_engine.ts +171 -36
  33. package/src/retrieval/workspace_walker.ts +78 -2
  34. package/src/safety/atomic_write.ts +1 -1
  35. package/src/safety/epistemic_guard.ts +105 -31
  36. package/src/safety/host_environment.ts +180 -0
  37. package/src/safety/output_clamper.ts +97 -27
  38. package/src/tools/code_search_output.ts +11 -2
  39. package/src/tools/code_search_tool.ts +25 -13
  40. package/src/tools/context.ts +11 -10
  41. package/src/tools/edit_tool.ts +243 -154
  42. package/src/tools/read_tool.ts +285 -214
  43. package/src/tools/stream_reader.ts +206 -0
  44. package/src/ui/footer.ts +7 -7
  45. package/docs/lsp.md +0 -31
  46. package/src/lsp/adapters/base.ts +0 -42
  47. package/src/lsp/adapters/index.ts +0 -21
  48. package/src/lsp/adapters/python.ts +0 -37
  49. package/src/lsp/adapters/rust.ts +0 -35
  50. package/src/lsp/adapters/typescript.ts +0 -40
  51. package/src/lsp/index.ts +0 -13
  52. package/src/lsp/lsp_client.ts +0 -765
  53. package/src/lsp/lsp_detector.ts +0 -52
  54. package/src/lsp/lsp_formatter.ts +0 -323
  55. package/src/lsp/lsp_installer.ts +0 -320
  56. package/src/lsp/lsp_manager.ts +0 -202
  57. package/src/lsp/lsp_modal.ts +0 -675
  58. package/src/lsp/lsp_registry.ts +0 -600
  59. package/src/lsp/lsp_types.ts +0 -143
  60. package/src/retrieval/ast_search.ts +0 -999
  61. package/src/retrieval/symbol_reader.ts +0 -228
  62. package/src/tools/ast_search_formatter.ts +0 -161
  63. package/src/tools/ast_search_tool.ts +0 -146
  64. package/src/tools/lsp_tool.ts +0 -794
  65. package/src/tools/repo_map_tool.ts +0 -56
package/src/index.ts CHANGED
@@ -1,7 +1,6 @@
1
- import * as path from "path";
1
+ import * as path from "node:path";
2
2
  import * as fs from "node:fs";
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
- import { computeRepoMap } from "./retrieval/repomap";
5
4
  import { HybridSearchIndex } from "./retrieval/search_index";
6
5
  import { type SearchProfile, savePersistedProfile } from "./retrieval/search_config";
7
6
  import { SearchControlModal } from "./retrieval/search_modal";
@@ -10,15 +9,11 @@ import {
10
9
  globalEpistemicGuard,
11
10
  resolveUserPath,
12
11
  } from "./safety/epistemic_guard";
13
- import { loadKernelConfig, registerAgentKernelCommand } from "./config";
12
+ import { loadKernelConfig, registerAgentKernelCommand, saveProjectKernelConfig } from "./config";
14
13
  import { kernelDebug } from "./safety/kernel_debug";
15
- import { registerRepoMapTool } from "./tools/repo_map_tool";
16
- import { registerAstSearchTool } from "./tools/ast_search_tool";
17
- import { speculativeToolsEnabled } from "./tools/context";
18
14
  import { registerCodeSearchTool } from "./tools/code_search_tool";
19
15
  import { registerReadTool } from "./tools/read_tool";
20
16
  import { registerEditTool } from "./tools/edit_tool";
21
- import { registerLspTool } from "./tools/lsp_tool";
22
17
  import { TreeSitterEngine } from "./retrieval/tree_sitter_engine";
23
18
 
24
19
  /**
@@ -106,7 +101,7 @@ function loadKernelGuidance(
106
101
  rendered,
107
102
  "",
108
103
  "## Tool Integration Notice",
109
- `Pi reports that another extension already owns: ${[...toolCollisions].sort().join(", ")}. Agent Kernel did not replace those tools. Kernel-specific output limits, read-before-write checks, or edit verification may not apply to them.`,
104
+ `Pi reports that another extension already owns: ${[...toolCollisions].sort((a, b) => a.localeCompare(b)).join(", ")}. Agent Kernel did not replace those tools. Kernel-specific output limits, read-before-write checks, or edit verification may not apply to them.`,
110
105
  ].filter(Boolean).join("\n");
111
106
  }
112
107
 
@@ -123,15 +118,7 @@ function appendKernelGuidance(systemPrompt: string, guidance: string): string {
123
118
  import { clampCommandOutput, getSpilloverRoot } from "./safety/output_clamper";
124
119
  import { sanitizeSessionFiles } from "./context/session_repair";
125
120
  import { formatSearchEngineTag, renderFooter } from "./ui/footer";
126
- import {
127
- LspManager,
128
- LspControlModal,
129
- LspDownloadModal,
130
- formatDiagnostics,
131
- installLanguageServer,
132
- LSP_SERVERS,
133
- findExecutable,
134
- } from "./lsp";
121
+ import { renderHostEnvironment } from "./safety/host_environment";
135
122
 
136
123
  export default async function unifiedHybridExtension(pi: ExtensionAPI) {
137
124
  // Initialize TreeSitter WASM engine eagerly in background
@@ -139,7 +126,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
139
126
  kernelDebug(`TreeSitter background init error: ${err}`);
140
127
  });
141
128
 
142
- // 3. Slash Commands: /repomap, /engine, /lsp, /pi-docs
129
+ // 3. Slash Commands: /engine, /pi-docs
143
130
  let activeTui: any = null;
144
131
  let projectTrusted = false;
145
132
  const configByWorkspace = new Map<
@@ -217,7 +204,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
217
204
  );
218
205
 
219
206
  const runSync = async () => {
220
- return await index.syncWorkspace(
207
+ return index.syncWorkspace(
221
208
  isFullSync,
222
209
  (msg: string) => {
223
210
  if (currentGeneration !== activeIndexingGeneration) return;
@@ -330,9 +317,8 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
330
317
  invalidateConfig: (cwd, ctx) => {
331
318
  applyConfigChanges(cwd, ctx);
332
319
  },
333
- clearCaches: () => {
334
- cachedRepoMap = "";
335
- },
320
+ getSearchIndex: (cwd) => getSearchIndex(cwd),
321
+ triggerBackgroundIndexing: (idx, ctx, isFull) => triggerBackgroundIndexing(idx, ctx, isFull),
336
322
  });
337
323
 
338
324
  pi.registerCommand("repair-sessions", {
@@ -395,349 +381,12 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
395
381
  },
396
382
  });
397
383
 
398
- pi.registerCommand("repomap", {
399
- description: "Display the Tree-Sitter AST & PageRank ranked repository map",
400
- handler: async (args: string, ctx: any) => {
401
- await TreeSitterEngine.getInstance().init();
402
- const budget = args ? parseInt(args, 10) : 1024;
403
- const map = computeRepoMap(
404
- ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd(),
405
- Number.isNaN(budget)
406
- ? getConfig(ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd()).retrieval.repo_map_budget
407
- : budget,
408
- );
409
- ctx.ui?.notify?.("Repository Map Generated", "info");
410
- if (ctx.hasUI && ctx.ui?.setWidget) {
411
- ctx.ui.setWidget("repomap-widget", map.split("\n").slice(0, 25));
412
- } else if (!ctx.hasUI) {
413
- console.log("\n" + map + "\n");
414
- }
415
- },
416
- });
417
-
418
- // Slash Command: /engine [auto|lean|hybrid|full|off|status|reindex]
419
- pi.registerCommand("engine", {
420
- description:
421
- "Configure codebase retrieval engine (auto | lean | hybrid | full | off | status | reindex)",
422
- getArgumentCompletions: (prefix: string) => {
423
- const options = [
424
- {
425
- value: "status",
426
- label: "status - Display current engine profile, memory & diagnostics",
427
- },
428
- {
429
- value: "auto",
430
- label:
431
- "auto - Auto-detect: Lean (VPS), Hybrid (Laptop), Full (Workstation)",
432
- },
433
- {
434
- value: "lean",
435
- label:
436
- "lean - Fast AST-aware BM25 (0% CPU, 0 MB extra RAM) [Persisted Default]",
437
- },
438
- {
439
- value: "hybrid",
440
- label:
441
- "hybrid - Throttled 256-dim Matryoshka embeddings",
442
- },
443
- {
444
- value: "full",
445
- label: "full - Multi-core 768-dim embeddings",
446
- },
447
- {
448
- value: "off",
449
- label: "off - Disable search & unload memory",
450
- },
451
- { value: "reindex", label: "reindex - Force full workspace re-indexing" },
452
- ];
453
- const filtered = options.filter((o) =>
454
- o.value.startsWith(prefix.toLowerCase()),
455
- );
456
- return filtered.length > 0 ? filtered : null;
457
- },
458
- handler: async (args: string, ctx: any) => {
459
- let sub = (args || "").trim().toLowerCase();
460
- if (sub.startsWith("default ")) {
461
- sub = sub.replace("default ", "").trim();
462
- }
463
- const index = getSearchIndex(ctx.cwd);
464
-
465
- if (
466
- sub === "auto" ||
467
- sub === "lean" ||
468
- sub === "hybrid" ||
469
- sub === "full" ||
470
- sub === "off"
471
- ) {
472
- const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
473
- savePersistedProfile(sub as SearchProfile, currentCwd);
474
- applyConfigChanges(currentCwd, ctx);
475
- const status = index.getStatus();
476
- const msg = `Default search profile saved: ${sub.toUpperCase()} (Effective: ${status.effectiveProfile.toUpperCase()})`;
477
- ctx.ui?.notify?.(msg, "info");
478
- if (!ctx.hasUI) console.log(`[Codebase Engine] ${msg}`);
479
- return;
480
- }
481
-
482
- if (sub === "reindex") {
483
- ctx.ui?.notify?.("Re-indexing workspace...", "info");
484
- const res = await index.syncWorkspace(true, (msg) => {
485
- if (ctx.hasUI) ctx.ui?.notify?.(msg, "info");
486
- });
487
- ctx.ui?.notify?.(
488
- `Indexed ${res.fileCount} files (${res.chunkCount} chunks)`,
489
- "info",
490
- );
491
- if (!ctx.hasUI)
492
- console.log(
493
- `[Codebase Engine] Re-indexed ${res.fileCount} files, ${res.chunkCount} chunks.`,
494
- );
495
- return;
496
- }
497
-
498
- if (sub === "status") {
499
- const status = index.getStatus();
500
- ctx.ui?.notify?.(
501
- `Engine: ${status.engineState} | Profile: ${status.profile.toUpperCase()} (${status.effectiveProfile.toUpperCase()}) | Chunks: ${status.chunkCount} | Model: ${status.modelStatus} | RSS: ${status.rssMemoryMB}MB`,
502
- "info",
503
- );
504
- if (!ctx.hasUI) {
505
- console.log(
506
- `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`,
507
- );
508
- }
509
- return;
510
- }
511
-
512
- // Interactive centered modal dialog with full-viewport backdrop scrim
513
- if (ctx.hasUI && ctx.ui?.custom) {
514
- const res: any = await ctx.ui.custom(
515
- (tui: any, theme: any, _keybindings: any, done: any) =>
516
- new SearchControlModal(tui, index, theme, done),
517
- {
518
- overlay: true,
519
- overlayOptions: {
520
- anchor: "center",
521
- width: "100%",
522
- },
523
- },
524
- );
525
-
526
- if (res) {
527
- activeTui?.requestRender?.();
528
- const eff = index.getEffectiveProfile();
529
- const profileName = (res.profile || index.getProfile()).toUpperCase();
530
- const effName = eff.toUpperCase();
531
-
532
- if (res.action === "select") {
533
- const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
534
- if (res.profile) {
535
- savePersistedProfile(res.profile, currentCwd);
536
- applyConfigChanges(currentCwd, ctx);
537
- }
538
- ctx.ui?.notify?.(
539
- `Engine set to ${profileName} (Effective: ${effName})`,
540
- "info",
541
- );
542
- }
543
-
544
- if (res.reindexed || eff !== "off") {
545
- triggerBackgroundIndexing(index, ctx, res.action === "reindex");
546
- } else {
547
- ctx.ui?.setWidget?.("engine-progress", undefined);
548
- }
549
- }
550
- return;
551
- }
552
-
553
- // Fallback select menu if custom overlays are unavailable
554
- if (ctx.hasUI && ctx.ui?.select) {
555
- const status = index.getStatus();
556
- const currentProfile = index.getProfile();
557
- const options = [
558
- `View Status (${status.engineState} - ${status.chunkCount} chunks, RSS ${status.rssMemoryMB}MB)`,
559
- `── Profiles ───────────────────────`,
560
- `Set Default: Auto Detect (Lean -> Hybrid -> Full based on specs)${currentProfile === "auto" ? " [Current]" : ""}`,
561
- `Set Default: Lean Mode (Fast BM25, 0% CPU, 0 MB extra RAM)${currentProfile === "lean" ? " [Current]" : ""}`,
562
- `Set Default: Hybrid Mode (Throttled 256-dim Matryoshka)${currentProfile === "hybrid" ? " [Current]" : ""}`,
563
- `Set Default: Full Mode (768-dim embeddings)${currentProfile === "full" ? " [Current]" : ""}`,
564
- `Set Default: Disable Engine (Turn off search)${currentProfile === "off" ? " [Current]" : ""}`,
565
- `── Actions ────────────────────────`,
566
- `Re-index Workspace`,
567
- ];
568
-
569
- const choice = await ctx.ui.select(
570
- "Codebase Retrieval Engine Settings",
571
- options,
572
- );
573
- if (!choice || choice.startsWith("──")) return;
574
-
575
- const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
576
- let newProfile: SearchProfile | null = null;
577
- if (choice.includes("Auto Detect")) newProfile = "auto";
578
- else if (choice.includes("Lean Mode")) newProfile = "lean";
579
- else if (choice.includes("Hybrid Mode")) newProfile = "hybrid";
580
- else if (choice.includes("Full Mode")) newProfile = "full";
581
- else if (choice.includes("Disable Engine")) newProfile = "off";
582
-
583
- if (newProfile) {
584
- savePersistedProfile(newProfile, currentCwd);
585
- applyConfigChanges(currentCwd, ctx);
586
- ctx.ui?.notify?.(`Default search profile saved: ${newProfile.toUpperCase()}`, "info");
587
- return;
588
- }
589
-
590
- if (choice.includes("Re-index")) {
591
- triggerBackgroundIndexing(index, ctx, true);
592
- return;
593
- }
594
-
595
- if (choice.includes("View Status")) {
596
- const s = index.getStatus();
597
- ctx.ui.notify(
598
- `Engine: ${s.engineState} | Profile: ${s.profile.toUpperCase()} (Effective: ${s.effectiveProfile.toUpperCase()}) | Files: ${s.fileCount} | Chunks: ${s.chunkCount} | Model: ${s.modelStatus} | RSS: ${s.rssMemoryMB}MB`,
599
- "info",
600
- );
601
- return;
602
- }
603
- }
604
-
605
- // CLI fallback if not in UI mode
606
- const status = index.getStatus();
607
- 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`;
608
- console.log("\n" + msg + "\n");
609
- },
610
- });
611
-
612
- // Slash Command: /lsp (Inspect language servers, active daemons, or install language servers)
613
- pi.registerCommand("lsp", {
614
- description:
615
- "Inspect language servers, active daemons, or install servers (/lsp, /lsp install <lang>)",
616
- getArgumentCompletions: (prefix: string) => {
617
- const options = [
618
- {
619
- value: "status",
620
- label: "status - View LSP status and active daemon processes",
621
- },
622
- { value: "stop", label: "stop - Stop all active LSP daemon processes" },
623
- {
624
- value: "install",
625
- label:
626
- "install - Install an LSP server (e.g. pyright, typescript-language-server, gopls, rust-analyzer, clangd)",
627
- },
628
- ];
629
- const filtered = options.filter((o) =>
630
- o.value.startsWith(prefix.toLowerCase()),
631
- );
632
- return filtered.length > 0 ? filtered : null;
633
- },
634
- async handler(args: string, ctx: any) {
635
- const sub = args.trim().split(/\s+/);
636
- const lspMgr = LspManager.getInstance();
637
-
638
- if (sub[0] === "install" && sub[1]) {
639
- const target = sub[1];
640
- if (ctx.hasUI && ctx.ui?.notify) {
641
- ctx.ui.notify(`Installing LSP server for ${target}...`, "info");
642
- }
643
- const res = await installLanguageServer(target, (msg) => {
644
- if (ctx.hasUI && ctx.ui?.notify) {
645
- ctx.ui.notify(msg, "info");
646
- }
647
- });
648
- if (res.success) {
649
- ctx.ui?.notify?.(res.message, "info");
650
- } else {
651
- ctx.ui?.notify?.(res.message, "error");
652
- }
653
- return;
654
- }
655
-
656
- if (sub[0] === "stop" || sub[0] === "kill") {
657
- await lspMgr.stopAll();
658
- ctx.ui?.notify?.("All active LSP servers stopped.", "info");
659
- return;
660
- }
661
-
662
- // Interactive centered modal dialog with full-viewport backdrop scrim
663
- if (ctx.hasUI && ctx.ui?.custom) {
664
- const res: any = await ctx.ui.custom(
665
- (tui: any, theme: any, _keybindings: any, done: any) =>
666
- new LspControlModal(tui, lspMgr, theme, done),
667
- {
668
- overlay: true,
669
- overlayOptions: {
670
- anchor: "center",
671
- width: "100%",
672
- },
673
- },
674
- );
675
-
676
- if (res) {
677
- if (res.action === "stop") {
678
- await lspMgr.stopAll();
679
- ctx.ui?.notify?.("All active LSP servers stopped.", "info");
680
- } else if (res.installTargets && res.installTargets.length > 0) {
681
- // Spawn animated ASCII loading spinner modal
682
- await ctx.ui.custom(
683
- (tui: any, theme: any, _keybindings: any, done: any) =>
684
- new LspDownloadModal(tui, res.installTargets, theme, done),
685
- {
686
- overlay: true,
687
- overlayOptions: {
688
- anchor: "center",
689
- width: "100%",
690
- },
691
- },
692
- );
693
- }
694
- }
695
- return;
696
- }
697
-
698
- const activeClients = lspMgr.getStatus();
699
- if (ctx.hasUI && ctx.ui?.select) {
700
- const lines = [
701
- `── Active LSP Daemons (${activeClients.length}) ────────────────`,
702
- ...activeClients.map(
703
- (c) =>
704
- `[Active] ${c.languageId.toUpperCase()} (State: ${c.state}, Idle: ${c.idleSeconds}s)`,
705
- ),
706
- `── Installed / Available Servers ─────────────────────────────`,
707
- ...Object.entries(LSP_SERVERS)
708
- .slice(0, 10)
709
- .map(([k, cfg]) => {
710
- const primaryBin = cfg.commands[0]?.bin;
711
- const found = findExecutable(primaryBin);
712
- return `[${found ? "✓" : "✗"}] ${k.padEnd(12)} → ${primaryBin} ${found ? `(${found})` : "(not installed)"}`;
713
- }),
714
- `── Actions ───────────────────────────────────────────────────`,
715
- `Stop all active LSP daemons`,
716
- ];
717
-
718
- const choice = await ctx.ui.select("LSP Server Status & Management", lines);
719
- if (choice?.includes("Stop all active")) {
720
- await lspMgr.stopAll();
721
- ctx.ui.notify("All active LSP servers stopped.", "info");
722
- }
723
- return;
724
- }
725
-
726
- // Console fallback
727
- let out = `=== LSP Status ===\nActive Daemons: ${activeClients.length}\n`;
728
- for (const c of activeClients) {
729
- out += ` • ${c.languageId}: ${c.state} (idle: ${c.idleSeconds}s, root: ${c.rootDir})\n`;
730
- }
731
- console.log(out);
732
- },
733
- });
734
-
735
384
  // Background workspace auto-indexer on session startup + setup integrated footer
736
385
  pi.on("session_start", async (_event: any, ctx: any) => {
737
386
  projectTrusted = ctx.isProjectTrusted?.() === true;
738
387
  configByWorkspace.clear();
739
388
  const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
740
- registerKernelTools(cwd);
389
+ registerKernelTools();
741
390
  setupUnifiedFooter(ctx);
742
391
  try {
743
392
  const index = getSearchIndex(cwd);
@@ -749,19 +398,14 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
749
398
  }
750
399
  });
751
400
 
752
- // 2. Per-session cleanup of the epistemic guard's inspection state and LSP processes.
401
+ // 2. Per-session cleanup of the epistemic guard's inspection state.
753
402
  // Without this, Map<sessionId, Set<filePath>> grows unbounded over a
754
403
  // long-lived process hosting many sessions (e.g. RPC mode). On session
755
- // shutdown we drop only this session's entry and stop running LSP daemons.
404
+ // shutdown we drop only this session's entry.
756
405
  pi.on("session_shutdown", async (_event: any, ctx: any) => {
757
406
  const sessionId = getSessionId(ctx);
758
407
  piDocsEnabledBySession.delete(sessionId);
759
408
  globalEpistemicGuard.resetSession(sessionId);
760
- try {
761
- await LspManager.getInstance().stopAll();
762
- } catch (e) {
763
- kernelDebug(e);
764
- }
765
409
  // Flush any debounced search index writes to disk on shutdown and halt further admissions
766
410
  for (const index of searchIndexes.values()) {
767
411
  try {
@@ -784,7 +428,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
784
428
  kernelDebug(`Incremental updateFile error for ${filePath}: ${err}`);
785
429
  });
786
430
  };
787
- const registerKernelTools = (cwd: string): void => {
431
+ const registerKernelTools = (): void => {
788
432
  if (kernelToolsRegistered) return;
789
433
  kernelToolsRegistered = true;
790
434
  // pi marks its own built-in tools with sourceInfo.source === "builtin" and a
@@ -820,15 +464,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
820
464
  registerCodeSearchTool(pi, { getSessionId, getSearchIndex, getConfig });
821
465
  kernelRegisteredTools.add("code_search");
822
466
  }
823
-
824
- const enableSpeculativeTools = speculativeToolsEnabled(getConfig, cwd);
825
- if (enableSpeculativeTools) {
826
- if (canRegister("get_repo_map")) registerRepoMapTool(pi);
827
- if (canRegister("ast_search")) {
828
- registerAstSearchTool(pi, { getSessionId, getConfig });
829
- }
830
- if (canRegister("lsp")) registerLspTool(pi, { getSessionId, getConfig });
831
- }
832
467
  };
833
468
 
834
469
  // 9a. Block host writes before the host tool can create parent directories
@@ -839,7 +474,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
839
474
  const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
840
475
  const sessionId = getSessionId(ctx);
841
476
  if (event.toolName !== "write") return;
842
- const targetPath = (event.input as any)?.path;
477
+ const targetPath = (event.input as Record<string, unknown> | undefined)?.path;
843
478
  if (typeof targetPath !== "string" || !targetPath.trim()) {
844
479
  return {
845
480
  block: true,
@@ -876,6 +511,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
876
511
 
877
512
  // 9. Tool Result Interceptor: Syntax Validation & Output Clamping (ACI)
878
513
  pi.on("tool_result", async (event: any, ctx: any) => {
514
+ // Kernel tools return their failures, and pi drops a returned isError; markReturnedErrors kept it in details.
515
+ if (!event.isError && kernelRegisteredTools.has(event.toolName) && event.details?.isError === true) {
516
+ return { isError: true };
517
+ }
879
518
  const isShell = event.toolName === "bash" || event.toolName === "powershell";
880
519
  if (event.isError && !isShell) return;
881
520
 
@@ -886,7 +525,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
886
525
 
887
526
  // 9a. Intercept bash & powershell output to clamp minified lines & massive match floods
888
527
  if (toolName === "bash" || toolName === "powershell") {
889
- const command = (event.input as any)?.command || "";
528
+ const command = String((event.input as Record<string, unknown> | undefined)?.command || "");
890
529
  const outputConfig = getConfig(
891
530
  ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
892
531
  );
@@ -916,8 +555,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
916
555
  getSessionId(ctx),
917
556
  bashOutputComplete,
918
557
  (resultContent || [])
919
- .filter((c: any) => c.type === "text" && typeof c.text === "string")
920
- .map((c: any) => c.text)
558
+ .flatMap((c: any) => (c?.type === "text" && typeof c?.text === "string" ? [c.text] : []))
921
559
  .join(""),
922
560
  );
923
561
  if (event.isError) {
@@ -929,10 +567,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
929
567
 
930
568
  // 9b. Preserve the host write-tool compatibility path. The custom edit
931
569
  // tool owns its complete verification lifecycle; intercepting edit results
932
- // here would duplicate syntax/LSP work.
570
+ // here would duplicate syntax verification work.
933
571
  if (toolName === "write") {
934
- const input = event.input as any;
935
- const targetPath = input?.path;
572
+ const input = event.input as Record<string, unknown> | undefined;
573
+ const targetPath = typeof input?.path === "string" ? input.path : undefined;
936
574
 
937
575
  // The harness does not reliably propagate result-level isError to this
938
576
  // hook, so a failed edit can still reach here. Detect the edit tool's
@@ -973,6 +611,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
973
611
  kernelDebug(e);
974
612
  }
975
613
 
614
+ await TreeSitterEngine.getInstance().loadLanguages([path.extname(resolvedPath).toLowerCase()]);
976
615
  const syntaxRes = checkSyntax(resolvedPath);
977
616
 
978
617
  if (!syntaxRes.valid && syntaxRes.status === "failed") {
@@ -980,39 +619,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
980
619
  resultContent = event.content.map((c: any) =>
981
620
  c.type === "text" ? { ...c, text: c.text + warning } : c,
982
621
  );
983
- } else {
984
- // Synchronize with active LSP daemon and fetch post-edit diagnostics if available
985
- let lspNotice = "";
986
- try {
987
- const lspMgr = LspManager.getInstance();
988
- const client = lspMgr.getReadyClientForFile(resolvedPath, resultCwd);
989
- if (client && client.getState() === "ready") {
990
- const fileContent = fs.readFileSync(resolvedPath, "utf8");
991
- await client.changeDocument(resolvedPath, fileContent);
992
- await client.saveDocument(resolvedPath, fileContent);
993
-
994
- // Allow LSP server brief window to compute diagnostics
995
- const diagnostics = await client.getDiagnosticsResult(resolvedPath);
996
- if (diagnostics.diagnostics.length > 0) {
997
- const formattedDiags = formatDiagnostics(
998
- diagnostics.diagnostics,
999
- resolvedPath,
1000
- resultCwd,
1001
- );
1002
- lspNotice = `\n\n[LSP Diagnostics]\n${formattedDiags}`;
1003
- } else if (diagnostics.status !== "clean") {
1004
- lspNotice = `\n\n[LSP ${diagnostics.status.toUpperCase()}] No definitive diagnostics result.`;
1005
- }
1006
- }
1007
- } catch (e) {
1008
- kernelDebug(e);
1009
- }
1010
-
1011
- if (lspNotice) {
1012
- resultContent = event.content.map((c: any) =>
1013
- c.type === "text" ? { ...c, text: c.text + lspNotice } : c,
1014
- );
1015
- }
1016
622
  }
1017
623
  }
1018
624
  }
@@ -1027,39 +633,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
1027
633
  // Custom user instructions remain the primary authority. Repository-controlled
1028
634
  // diffs, source text, filenames, and command output are never promoted into the
1029
635
  // system prompt by this extension.
1030
- let cachedRepoMap = "";
1031
- let cachedRepoMapCwd = "";
1032
- let lastRepoMapCheck = 0;
1033
-
1034
636
  pi.on("before_agent_start", async (event: any, ctx: any) => {
1035
- const now = Date.now();
1036
637
  const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
1037
638
  const kernelConfig = getConfig(currentCwd);
1038
639
 
1039
- let shouldInjectMap = false;
1040
- // Disabled automatic AST repo map injection to evaluate prompt token footprint and latency
1041
- // The `get_repo_map` tool remains available on-demand.
1042
-
1043
- // Cache repo-map across turns with a 15-second TTL to avoid scanning/PageRanking entire repo on every turn
1044
- if (!cachedRepoMap || cachedRepoMapCwd !== currentCwd || now - lastRepoMapCheck > 15000) {
1045
- if (shouldInjectMap) {
1046
- await TreeSitterEngine.getInstance().init();
1047
- cachedRepoMap = computeRepoMap(
1048
- currentCwd,
1049
- kernelConfig.retrieval.repo_map_budget,
1050
- );
1051
- } else {
1052
- cachedRepoMap = "";
1053
- }
1054
- cachedRepoMapCwd = currentCwd;
1055
- lastRepoMapCheck = now;
1056
- }
1057
-
1058
- const runtimeParts = [
1059
- cachedRepoMap ? `## Available Repository Context:\n${cachedRepoMap}` : "",
1060
- ].filter(Boolean);
1061
- const runtimeContext = runtimeParts.length > 0 ? `\n${runtimeParts.join("\n\n")}\n` : "";
1062
-
1063
640
  const basePrompt = event.systemPrompt || "";
1064
641
  const systemPrompt = piDocsEnabled(ctx)
1065
642
  ? basePrompt
@@ -1075,12 +652,18 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
1075
652
  const guidance = kernelConfig.instructions.enabled
1076
653
  ? loadKernelGuidance(toolCollisions, promptToolNames)
1077
654
  : "";
1078
- const guidedPrompt = appendKernelGuidance(systemPrompt, guidance);
1079
- const shouldAppendRuntime = runtimeContext && !guidedPrompt.includes(runtimeContext.trim());
1080
- return {
1081
- systemPrompt: guidedPrompt
1082
- ? (shouldAppendRuntime ? `${guidedPrompt}\n\n${runtimeContext}` : guidedPrompt)
1083
- : runtimeContext,
1084
- };
655
+ const hostEnv = kernelConfig.instructions.enabled && kernelConfig.instructions.host_environment !== false
656
+ ? renderHostEnvironment()
657
+ : "";
658
+
659
+ let guidedPrompt = appendKernelGuidance(systemPrompt, guidance);
660
+ if (hostEnv && !guidedPrompt.includes("<host_environment>")) {
661
+ if (guidedPrompt.includes(KERNEL_GUIDANCE_MARKER)) {
662
+ guidedPrompt = guidedPrompt.replace(KERNEL_GUIDANCE_MARKER, `${hostEnv}\n\n${KERNEL_GUIDANCE_MARKER}`);
663
+ } else {
664
+ guidedPrompt = `${guidedPrompt.trimEnd()}\n\n${hostEnv}`;
665
+ }
666
+ }
667
+ return { systemPrompt: guidedPrompt };
1085
668
  });
1086
669
  }