@floydous/pi-agent-kernel 0.5.0 → 0.6.1

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 (37) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +20 -6
  2. package/CHANGELOG.md +69 -0
  3. package/README.md +23 -20
  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 +60 -593
  13. package/src/config/kernel_config.ts +46 -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 +105 -203
  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 +1247 -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 +190 -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 +51 -14
  33. package/src/tools/context.ts +15 -0
  34. package/src/tools/edit_tool.ts +306 -79
  35. package/src/tools/read_tool.ts +248 -39
  36. package/src/tools/stream_reader.ts +206 -0
  37. package/src/ui/tui_utils.ts +70 -12
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";
@@ -40,17 +40,53 @@ function getSessionId(ctx: any): string {
40
40
  return `__default__${process.pid}`;
41
41
  }
42
42
 
43
+ const PI_DOCS_TAGGED = /\n?<docs>\s*\nPi documentation \(read only when the user asks about [^)]+\):[\s\S]*?<\/docs>\r?\n?/;
43
44
  const PI_DOCS_START =
44
- "Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):";
45
- const PI_DOCS_END = /\n- Always read pi \.md files completely[^\n]*/;
45
+ /Pi documentation \(read only when the user asks about (?:pi|the harness) itself, its SDK, extensions, themes, skills, or TUI\):/;
46
+ const PI_DOCS_END =
47
+ /\n- (?:Always read pi \.md files completely|Before implementing harness changes, read the relevant docs)[^\n]*/;
46
48
  export const KERNEL_GUIDANCE_MARKER = "<agent_kernel_guidance>";
47
49
  const KERNEL_TOOL_BLOCKS = ["CODE_SEARCH"] as const;
48
50
  let kernelGuidance: string | null | undefined;
49
51
  const piDocsEnabledBySession = new Map<string, boolean>();
52
+ const lastNotifiedProfileBySession = new Map<string, "lean" | "full" | "off">();
53
+ const pendingEngineNotificationBySession = new Map<string, string | null>();
54
+
55
+ export function formatEngineNotification(effectiveProfile: "lean" | "full" | "off"): string {
56
+ if (effectiveProfile === "lean") {
57
+ return `<system_notification>\nRetrieval engine updated: Lean Mode (lexical BM25 over code AST chunks).\nFormulate \`code_search\` queries using 3–5 mechanism keywords, domain nouns, or code identifier patterns likely to appear in source code or docstrings (e.g., "connection idle timeout", "token expiration").\n</system_notification>`;
58
+ }
59
+ if (effectiveProfile === "full") {
60
+ return `<system_notification>\nRetrieval engine updated: Full Mode (hybrid BM25 + 768-dim ModernBERT neural embeddings via RRF).\nFormulate \`code_search\` queries using both technical keywords and conceptual intent phrases (e.g., "dropping dead upstream sockets", "session lifecycle").\n</system_notification>`;
61
+ }
62
+ return `<system_notification>\nRetrieval engine updated: Off profile (retrieval disabled).\n\`code_search\` is disabled and returns an error. Direct discovery to \`rg -n\` and file reading tools.\n</system_notification>`;
63
+ }
64
+
65
+ export function getPendingEngineNotification(sessionId: string): string | null {
66
+ return pendingEngineNotificationBySession.get(sessionId) ?? null;
67
+ }
68
+
69
+ export function getLastNotifiedProfile(sessionId: string): ("lean" | "full" | "off") | undefined {
70
+ return lastNotifiedProfileBySession.get(sessionId);
71
+ }
72
+
73
+ export function clearEngineNotificationState(): void {
74
+ lastNotifiedProfileBySession.clear();
75
+ pendingEngineNotificationBySession.clear();
76
+ }
50
77
 
51
78
  function withoutPiDocumentation(systemPrompt: string): string {
52
- const start = systemPrompt.indexOf(PI_DOCS_START);
53
- if (start < 0) return systemPrompt;
79
+ const taggedMatch = PI_DOCS_TAGGED.exec(systemPrompt);
80
+ if (taggedMatch && taggedMatch.index !== undefined) {
81
+ const start = taggedMatch.index;
82
+ const end = start + taggedMatch[0].length;
83
+ const before = systemPrompt.slice(0, start).replace(/\n{2,}$/, "\n");
84
+ const after = systemPrompt.slice(end).replace(/^\n{2,}/, "\n");
85
+ return before + after;
86
+ }
87
+ const startMatch = PI_DOCS_START.exec(systemPrompt);
88
+ if (!startMatch || startMatch.index === undefined) return systemPrompt;
89
+ const start = startMatch.index;
54
90
  const endMatch = systemPrompt.slice(start).match(PI_DOCS_END);
55
91
  if (!endMatch || endMatch.index === undefined) return systemPrompt;
56
92
 
@@ -118,6 +154,7 @@ function appendKernelGuidance(systemPrompt: string, guidance: string): string {
118
154
  import { clampCommandOutput, getSpilloverRoot } from "./safety/output_clamper";
119
155
  import { sanitizeSessionFiles } from "./context/session_repair";
120
156
  import { formatSearchEngineTag, renderFooter } from "./ui/footer";
157
+ import { renderHostEnvironment } from "./safety/host_environment";
121
158
 
122
159
  export default async function unifiedHybridExtension(pi: ExtensionAPI) {
123
160
  // Initialize TreeSitter WASM engine eagerly in background
@@ -125,7 +162,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
125
162
  kernelDebug(`TreeSitter background init error: ${err}`);
126
163
  });
127
164
 
128
- // 3. Slash Commands: /engine, /pi-docs
165
+ // 3. Slash Commands: /agent-kernel, /pi-docs
129
166
  let activeTui: any = null;
130
167
  let projectTrusted = false;
131
168
  const configByWorkspace = new Map<
@@ -304,7 +341,20 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
304
341
  }
305
342
  }
306
343
 
307
- // 2. Refresh statusline and footer immediately
344
+ // 2. Track engine notification with intra-turn net-state collapsing (zero-stack)
345
+ if (ctx && index) {
346
+ const sessionId = getSessionId(ctx);
347
+ const eff = index.getEffectiveProfile();
348
+ const lastNotified = lastNotifiedProfileBySession.get(sessionId);
349
+ if (eff !== lastNotified) {
350
+ pendingEngineNotificationBySession.set(sessionId, formatEngineNotification(eff));
351
+ } else {
352
+ // User switched back and forth resulting in zero net change: cancel pending
353
+ pendingEngineNotificationBySession.delete(sessionId);
354
+ }
355
+ }
356
+
357
+ // 3. Refresh statusline and footer immediately
308
358
  if (ctx) {
309
359
  syncRetrievalStatus(ctx);
310
360
  activeTui?.requestRender?.();
@@ -316,6 +366,8 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
316
366
  invalidateConfig: (cwd, ctx) => {
317
367
  applyConfigChanges(cwd, ctx);
318
368
  },
369
+ getSearchIndex: (cwd) => getSearchIndex(cwd),
370
+ triggerBackgroundIndexing: (idx, ctx, isFull) => triggerBackgroundIndexing(idx, ctx, isFull),
319
371
  });
320
372
 
321
373
  pi.registerCommand("repair-sessions", {
@@ -378,209 +430,18 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
378
430
  },
379
431
  });
380
432
 
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
433
  // Background workspace auto-indexer on session startup + setup integrated footer
576
434
  pi.on("session_start", async (_event: any, ctx: any) => {
577
435
  projectTrusted = ctx.isProjectTrusted?.() === true;
578
436
  configByWorkspace.clear();
437
+ const sessionId = getSessionId(ctx);
579
438
  const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
580
439
  registerKernelTools();
581
440
  setupUnifiedFooter(ctx);
582
441
  try {
583
442
  const index = getSearchIndex(cwd);
443
+ lastNotifiedProfileBySession.set(sessionId, index.getEffectiveProfile());
444
+ pendingEngineNotificationBySession.delete(sessionId);
584
445
  if (index.getEffectiveProfile() !== "off") {
585
446
  triggerBackgroundIndexing(index, ctx, false);
586
447
  }
@@ -596,6 +457,8 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
596
457
  pi.on("session_shutdown", async (_event: any, ctx: any) => {
597
458
  const sessionId = getSessionId(ctx);
598
459
  piDocsEnabledBySession.delete(sessionId);
460
+ lastNotifiedProfileBySession.delete(sessionId);
461
+ pendingEngineNotificationBySession.delete(sessionId);
599
462
  globalEpistemicGuard.resetSession(sessionId);
600
463
  // Flush any debounced search index writes to disk on shutdown and halt further admissions
601
464
  for (const index of searchIndexes.values()) {
@@ -702,6 +565,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
702
565
 
703
566
  // 9. Tool Result Interceptor: Syntax Validation & Output Clamping (ACI)
704
567
  pi.on("tool_result", async (event: any, ctx: any) => {
568
+ // Kernel tools return their failures, and pi drops a returned isError; markReturnedErrors kept it in details.
569
+ if (!event.isError && kernelRegisteredTools.has(event.toolName) && event.details?.isError === true) {
570
+ return { isError: true };
571
+ }
705
572
  const isShell = event.toolName === "bash" || event.toolName === "powershell";
706
573
  if (event.isError && !isShell) return;
707
574
 
@@ -798,6 +665,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
798
665
  kernelDebug(e);
799
666
  }
800
667
 
668
+ await TreeSitterEngine.getInstance().loadLanguages([path.extname(resolvedPath).toLowerCase()]);
801
669
  const syntaxRes = checkSyntax(resolvedPath);
802
670
 
803
671
  if (!syntaxRes.valid && syntaxRes.status === "failed") {
@@ -821,10 +689,15 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
821
689
  // system prompt by this extension.
822
690
  pi.on("before_agent_start", async (event: any, ctx: any) => {
823
691
  const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
692
+ const sessionId = getSessionId(ctx);
824
693
  const kernelConfig = getConfig(currentCwd);
825
694
 
826
695
  const basePrompt = event.systemPrompt || "";
827
- const systemPrompt = piDocsEnabled(ctx)
696
+ const includePiDocs = piDocsEnabled(ctx);
697
+ if (!includePiDocs && event.systemPromptOptions?.sections?.docs !== undefined) {
698
+ delete event.systemPromptOptions.sections.docs;
699
+ }
700
+ const systemPrompt = includePiDocs
828
701
  ? basePrompt
829
702
  : withoutPiDocumentation(basePrompt);
830
703
  const activeToolNames = new Set(pi.getActiveTools?.() || []);
@@ -838,7 +711,36 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
838
711
  const guidance = kernelConfig.instructions.enabled
839
712
  ? loadKernelGuidance(toolCollisions, promptToolNames)
840
713
  : "";
841
- const guidedPrompt = appendKernelGuidance(systemPrompt, guidance);
714
+ const hostEnv = kernelConfig.instructions.enabled && kernelConfig.instructions.host_environment !== false
715
+ ? renderHostEnvironment()
716
+ : "";
717
+
718
+ let guidedPrompt = appendKernelGuidance(systemPrompt, guidance);
719
+ if (hostEnv && !guidedPrompt.includes("<host_environment>")) {
720
+ if (guidedPrompt.includes(KERNEL_GUIDANCE_MARKER)) {
721
+ guidedPrompt = guidedPrompt.replace(KERNEL_GUIDANCE_MARKER, `${hostEnv}\n\n${KERNEL_GUIDANCE_MARKER}`);
722
+ } else {
723
+ guidedPrompt = `${guidedPrompt.trimEnd()}\n\n${hostEnv}`;
724
+ }
725
+ }
726
+
727
+ const pendingNotification = pendingEngineNotificationBySession.get(sessionId);
728
+ if (pendingNotification) {
729
+ pendingEngineNotificationBySession.delete(sessionId);
730
+ try {
731
+ const index = getSearchIndex(currentCwd);
732
+ lastNotifiedProfileBySession.set(sessionId, index.getEffectiveProfile());
733
+ } catch {}
734
+ return {
735
+ systemPrompt: guidedPrompt,
736
+ message: {
737
+ customType: "agent-kernel-engine-notification",
738
+ content: pendingNotification,
739
+ display: true,
740
+ },
741
+ };
742
+ }
743
+
842
744
  return { systemPrompt: guidedPrompt };
843
745
  });
844
746
  }