@floydous/pi-agent-kernel 0.5.0 → 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 (36) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +15 -6
  2. package/CHANGELOG.md +51 -0
  3. package/README.md +2 -3
  4. package/config.example.toml +1 -0
  5. package/docs/configuration.md +1 -1
  6. package/docs/editing-and-verification.md +20 -5
  7. package/docs/podman-linux-checks.md +24 -0
  8. package/docs/release-discipline.md +10 -0
  9. package/docs/retrieval.md +14 -11
  10. package/grammars/tree-sitter-html.wasm +0 -0
  11. package/package.json +2 -2
  12. package/src/config/agent_kernel_command.ts +59 -593
  13. package/src/config/kernel_config.ts +24 -2
  14. package/src/editing/patch.ts +48 -21
  15. package/src/editing/post_edit_verification.ts +8 -4
  16. package/src/editing/smart_anchor.ts +2 -1
  17. package/src/editing/syntax-verify.ts +73 -220
  18. package/src/index.ts +21 -196
  19. package/src/retrieval/html_chunker.ts +526 -0
  20. package/src/retrieval/search_bm25.ts +36 -27
  21. package/src/retrieval/search_chunker.ts +68 -6
  22. package/src/retrieval/search_config.ts +17 -34
  23. package/src/retrieval/search_embedder.ts +11 -29
  24. package/src/retrieval/search_index.ts +307 -145
  25. package/src/retrieval/search_modal.ts +1209 -222
  26. package/src/retrieval/tag_extractor.ts +1 -1
  27. package/src/retrieval/tree_sitter_engine.ts +103 -4
  28. package/src/retrieval/workspace_walker.ts +72 -0
  29. package/src/safety/host_environment.ts +180 -0
  30. package/src/safety/output_clamper.ts +83 -19
  31. package/src/tools/code_search_output.ts +9 -1
  32. package/src/tools/code_search_tool.ts +25 -10
  33. package/src/tools/context.ts +15 -0
  34. package/src/tools/edit_tool.ts +182 -60
  35. package/src/tools/read_tool.ts +245 -38
  36. package/src/tools/stream_reader.ts +206 -0
package/src/index.ts CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  globalEpistemicGuard,
10
10
  resolveUserPath,
11
11
  } from "./safety/epistemic_guard";
12
- import { loadKernelConfig, registerAgentKernelCommand } from "./config";
12
+ import { loadKernelConfig, registerAgentKernelCommand, saveProjectKernelConfig } from "./config";
13
13
  import { kernelDebug } from "./safety/kernel_debug";
14
14
  import { registerCodeSearchTool } from "./tools/code_search_tool";
15
15
  import { registerReadTool } from "./tools/read_tool";
@@ -118,6 +118,7 @@ function appendKernelGuidance(systemPrompt: string, guidance: string): string {
118
118
  import { clampCommandOutput, getSpilloverRoot } from "./safety/output_clamper";
119
119
  import { sanitizeSessionFiles } from "./context/session_repair";
120
120
  import { formatSearchEngineTag, renderFooter } from "./ui/footer";
121
+ import { renderHostEnvironment } from "./safety/host_environment";
121
122
 
122
123
  export default async function unifiedHybridExtension(pi: ExtensionAPI) {
123
124
  // Initialize TreeSitter WASM engine eagerly in background
@@ -316,6 +317,8 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
316
317
  invalidateConfig: (cwd, ctx) => {
317
318
  applyConfigChanges(cwd, ctx);
318
319
  },
320
+ getSearchIndex: (cwd) => getSearchIndex(cwd),
321
+ triggerBackgroundIndexing: (idx, ctx, isFull) => triggerBackgroundIndexing(idx, ctx, isFull),
319
322
  });
320
323
 
321
324
  pi.registerCommand("repair-sessions", {
@@ -378,200 +381,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
378
381
  },
379
382
  });
380
383
 
381
- // Slash Command: /engine [auto|lean|hybrid|full|off|status|reindex]
382
- pi.registerCommand("engine", {
383
- description:
384
- "Configure codebase retrieval engine (auto | lean | hybrid | full | off | status | reindex)",
385
- getArgumentCompletions: (prefix: string) => {
386
- const options = [
387
- {
388
- value: "status",
389
- label: "status - Display current engine profile, memory & diagnostics",
390
- },
391
- {
392
- value: "auto",
393
- label:
394
- "auto - Auto-detect: Lean (VPS), Hybrid (Laptop), Full (Workstation)",
395
- },
396
- {
397
- value: "lean",
398
- label:
399
- "lean - Fast AST-aware BM25 (0% CPU, 0 MB extra RAM) [Persisted Default]",
400
- },
401
- {
402
- value: "hybrid",
403
- label:
404
- "hybrid - Throttled 256-dim Matryoshka embeddings",
405
- },
406
- {
407
- value: "full",
408
- label: "full - Multi-core 768-dim embeddings",
409
- },
410
- {
411
- value: "off",
412
- label: "off - Disable search & unload memory",
413
- },
414
- { value: "reindex", label: "reindex - Force full workspace re-indexing" },
415
- ];
416
- const filtered = options.filter((o) =>
417
- o.value.startsWith(prefix.toLowerCase()),
418
- );
419
- return filtered.length > 0 ? filtered : null;
420
- },
421
- handler: async (args: string, ctx: any) => {
422
- let sub = (args || "").trim().toLowerCase();
423
- if (sub.startsWith("default ")) {
424
- sub = sub.replace("default ", "").trim();
425
- }
426
- const index = getSearchIndex(ctx.cwd);
427
-
428
- if (
429
- sub === "auto" ||
430
- sub === "lean" ||
431
- sub === "hybrid" ||
432
- sub === "full" ||
433
- sub === "off"
434
- ) {
435
- const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
436
- savePersistedProfile(sub as SearchProfile, currentCwd);
437
- applyConfigChanges(currentCwd, ctx);
438
- const status = index.getStatus();
439
- const msg = `Default search profile saved: ${sub.toUpperCase()} (Effective: ${status.effectiveProfile.toUpperCase()})`;
440
- ctx.ui?.notify?.(msg, "info");
441
- if (!ctx.hasUI) console.log(`[Codebase Engine] ${msg}`);
442
- return;
443
- }
444
-
445
- if (sub === "reindex") {
446
- ctx.ui?.notify?.("Re-indexing workspace...", "info");
447
- const res = await index.syncWorkspace(true, (msg) => {
448
- if (ctx.hasUI) ctx.ui?.notify?.(msg, "info");
449
- });
450
- ctx.ui?.notify?.(
451
- `Indexed ${res.fileCount} files (${res.chunkCount} chunks)`,
452
- "info",
453
- );
454
- if (!ctx.hasUI)
455
- console.log(
456
- `[Codebase Engine] Re-indexed ${res.fileCount} files, ${res.chunkCount} chunks.`,
457
- );
458
- return;
459
- }
460
-
461
- if (sub === "status") {
462
- const status = index.getStatus();
463
- ctx.ui?.notify?.(
464
- `Engine: ${status.engineState} | Profile: ${status.profile.toUpperCase()} (${status.effectiveProfile.toUpperCase()}) | Chunks: ${status.chunkCount} | Model: ${status.modelStatus} | RSS: ${status.rssMemoryMB}MB`,
465
- "info",
466
- );
467
- if (!ctx.hasUI) {
468
- console.log(
469
- `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`,
470
- );
471
- }
472
- return;
473
- }
474
-
475
- // Interactive centered modal dialog with full-viewport backdrop scrim
476
- if (ctx.hasUI && ctx.ui?.custom) {
477
- const res: any = await ctx.ui.custom(
478
- (tui: any, theme: any, _keybindings: any, done: any) =>
479
- new SearchControlModal(tui, index, theme, done),
480
- {
481
- overlay: true,
482
- overlayOptions: {
483
- anchor: "center",
484
- width: "100%",
485
- },
486
- },
487
- );
488
-
489
- if (res) {
490
- activeTui?.requestRender?.();
491
- const eff = index.getEffectiveProfile();
492
- const profileName = (res.profile || index.getProfile()).toUpperCase();
493
- const effName = eff.toUpperCase();
494
-
495
- if (res.action === "select") {
496
- const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
497
- if (res.profile) {
498
- savePersistedProfile(res.profile, currentCwd);
499
- applyConfigChanges(currentCwd, ctx);
500
- }
501
- ctx.ui?.notify?.(
502
- `Engine set to ${profileName} (Effective: ${effName})`,
503
- "info",
504
- );
505
- }
506
-
507
- if (res.reindexed || eff !== "off") {
508
- triggerBackgroundIndexing(index, ctx, res.action === "reindex");
509
- } else {
510
- ctx.ui?.setWidget?.("engine-progress", undefined);
511
- }
512
- }
513
- return;
514
- }
515
-
516
- // Fallback select menu if custom overlays are unavailable
517
- if (ctx.hasUI && ctx.ui?.select) {
518
- const status = index.getStatus();
519
- const currentProfile = index.getProfile();
520
- const options = [
521
- `View Status (${status.engineState} - ${status.chunkCount} chunks, RSS ${status.rssMemoryMB}MB)`,
522
- `── Profiles ───────────────────────`,
523
- `Set Default: Auto Detect (Lean -> Hybrid -> Full based on specs)${currentProfile === "auto" ? " [Current]" : ""}`,
524
- `Set Default: Lean Mode (Fast BM25, 0% CPU, 0 MB extra RAM)${currentProfile === "lean" ? " [Current]" : ""}`,
525
- `Set Default: Hybrid Mode (Throttled 256-dim Matryoshka)${currentProfile === "hybrid" ? " [Current]" : ""}`,
526
- `Set Default: Full Mode (768-dim embeddings)${currentProfile === "full" ? " [Current]" : ""}`,
527
- `Set Default: Disable Engine (Turn off search)${currentProfile === "off" ? " [Current]" : ""}`,
528
- `── Actions ────────────────────────`,
529
- `Re-index Workspace`,
530
- ];
531
-
532
- const choice = await ctx.ui.select(
533
- "Codebase Retrieval Engine Settings",
534
- options,
535
- );
536
- if (!choice || choice.startsWith("──")) return;
537
-
538
- const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
539
- let newProfile: SearchProfile | null = null;
540
- if (choice.includes("Auto Detect")) newProfile = "auto";
541
- else if (choice.includes("Lean Mode")) newProfile = "lean";
542
- else if (choice.includes("Hybrid Mode")) newProfile = "hybrid";
543
- else if (choice.includes("Full Mode")) newProfile = "full";
544
- else if (choice.includes("Disable Engine")) newProfile = "off";
545
-
546
- if (newProfile) {
547
- savePersistedProfile(newProfile, currentCwd);
548
- applyConfigChanges(currentCwd, ctx);
549
- ctx.ui?.notify?.(`Default search profile saved: ${newProfile.toUpperCase()}`, "info");
550
- return;
551
- }
552
-
553
- if (choice.includes("Re-index")) {
554
- triggerBackgroundIndexing(index, ctx, true);
555
- return;
556
- }
557
-
558
- if (choice.includes("View Status")) {
559
- const s = index.getStatus();
560
- ctx.ui.notify(
561
- `Engine: ${s.engineState} | Profile: ${s.profile.toUpperCase()} (Effective: ${s.effectiveProfile.toUpperCase()}) | Files: ${s.fileCount} | Chunks: ${s.chunkCount} | Model: ${s.modelStatus} | RSS: ${s.rssMemoryMB}MB`,
562
- "info",
563
- );
564
- return;
565
- }
566
- }
567
-
568
- // CLI fallback if not in UI mode
569
- const status = index.getStatus();
570
- 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`;
571
- console.log("\n" + msg + "\n");
572
- },
573
- });
574
-
575
384
  // Background workspace auto-indexer on session startup + setup integrated footer
576
385
  pi.on("session_start", async (_event: any, ctx: any) => {
577
386
  projectTrusted = ctx.isProjectTrusted?.() === true;
@@ -702,6 +511,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
702
511
 
703
512
  // 9. Tool Result Interceptor: Syntax Validation & Output Clamping (ACI)
704
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
+ }
705
518
  const isShell = event.toolName === "bash" || event.toolName === "powershell";
706
519
  if (event.isError && !isShell) return;
707
520
 
@@ -798,6 +611,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
798
611
  kernelDebug(e);
799
612
  }
800
613
 
614
+ await TreeSitterEngine.getInstance().loadLanguages([path.extname(resolvedPath).toLowerCase()]);
801
615
  const syntaxRes = checkSyntax(resolvedPath);
802
616
 
803
617
  if (!syntaxRes.valid && syntaxRes.status === "failed") {
@@ -838,7 +652,18 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
838
652
  const guidance = kernelConfig.instructions.enabled
839
653
  ? loadKernelGuidance(toolCollisions, promptToolNames)
840
654
  : "";
841
- const guidedPrompt = appendKernelGuidance(systemPrompt, guidance);
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
+ }
842
667
  return { systemPrompt: guidedPrompt };
843
668
  });
844
669
  }