@floydous/pi-agent-kernel 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -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
 
@@ -60,11 +96,14 @@ function withoutPiDocumentation(systemPrompt: string): string {
60
96
  return before + after;
61
97
  }
62
98
 
63
- function piDocsEnabled(ctx: any): boolean {
99
+ function piDocsEnabled(
100
+ ctx: any,
101
+ resolveConfig: (cwd: string) => ReturnType<typeof loadKernelConfig> = (cwd) => loadKernelConfig(cwd),
102
+ ): boolean {
64
103
  const sessionVal = piDocsEnabledBySession.get(getSessionId(ctx));
65
104
  if (sessionVal !== undefined) return sessionVal;
66
105
  const cwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
67
- return loadKernelConfig(cwd).instructions.pi_docs ?? true;
106
+ return resolveConfig(cwd).instructions.pi_docs ?? true;
68
107
  }
69
108
 
70
109
  export function renderKernelGuidance(guidance: string, availableTools: ReadonlySet<string>): string {
@@ -126,7 +165,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
126
165
  kernelDebug(`TreeSitter background init error: ${err}`);
127
166
  });
128
167
 
129
- // 3. Slash Commands: /engine, /pi-docs
168
+ // 3. Slash Commands: /agent-kernel, /pi-docs
130
169
  let activeTui: any = null;
131
170
  let projectTrusted = false;
132
171
  const configByWorkspace = new Map<
@@ -280,8 +319,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
280
319
  return {
281
320
  dispose: () => unsubBranch?.(),
282
321
  invalidate: () => {},
283
- render: (width: number) =>
284
- renderFooter(ctx, theme, footerData, width, currentIndex),
322
+ render: (width: number) => {
323
+ const renderCwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
324
+ return renderFooter(ctx, theme, footerData, width, currentIndex, getConfig(renderCwd));
325
+ },
285
326
  };
286
327
  });
287
328
  }
@@ -305,7 +346,20 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
305
346
  }
306
347
  }
307
348
 
308
- // 2. Refresh statusline and footer immediately
349
+ // 2. Track engine notification with intra-turn net-state collapsing (zero-stack)
350
+ if (ctx && index) {
351
+ const sessionId = getSessionId(ctx);
352
+ const eff = index.getEffectiveProfile();
353
+ const lastNotified = lastNotifiedProfileBySession.get(sessionId);
354
+ if (eff !== lastNotified) {
355
+ pendingEngineNotificationBySession.set(sessionId, formatEngineNotification(eff));
356
+ } else {
357
+ // User switched back and forth resulting in zero net change: cancel pending
358
+ pendingEngineNotificationBySession.delete(sessionId);
359
+ }
360
+ }
361
+
362
+ // 3. Refresh statusline and footer immediately
309
363
  if (ctx) {
310
364
  syncRetrievalStatus(ctx);
311
365
  activeTui?.requestRender?.();
@@ -374,7 +428,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
374
428
  return;
375
429
  }
376
430
 
377
- const enabled = piDocsEnabled(ctx);
431
+ const enabled = piDocsEnabled(ctx, getConfig);
378
432
  const message = `Pi documentation guidance: ${enabled ? "on" : "off"}`;
379
433
  ctx.ui?.notify?.(message, "info");
380
434
  if (!ctx.hasUI) console.log(message);
@@ -385,11 +439,14 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
385
439
  pi.on("session_start", async (_event: any, ctx: any) => {
386
440
  projectTrusted = ctx.isProjectTrusted?.() === true;
387
441
  configByWorkspace.clear();
442
+ const sessionId = getSessionId(ctx);
388
443
  const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
389
444
  registerKernelTools();
390
445
  setupUnifiedFooter(ctx);
391
446
  try {
392
447
  const index = getSearchIndex(cwd);
448
+ lastNotifiedProfileBySession.set(sessionId, index.getEffectiveProfile());
449
+ pendingEngineNotificationBySession.delete(sessionId);
393
450
  if (index.getEffectiveProfile() !== "off") {
394
451
  triggerBackgroundIndexing(index, ctx, false);
395
452
  }
@@ -405,6 +462,8 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
405
462
  pi.on("session_shutdown", async (_event: any, ctx: any) => {
406
463
  const sessionId = getSessionId(ctx);
407
464
  piDocsEnabledBySession.delete(sessionId);
465
+ lastNotifiedProfileBySession.delete(sessionId);
466
+ pendingEngineNotificationBySession.delete(sessionId);
408
467
  globalEpistemicGuard.resetSession(sessionId);
409
468
  // Flush any debounced search index writes to disk on shutdown and halt further admissions
410
469
  for (const index of searchIndexes.values()) {
@@ -612,7 +671,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
612
671
  }
613
672
 
614
673
  await TreeSitterEngine.getInstance().loadLanguages([path.extname(resolvedPath).toLowerCase()]);
615
- const syntaxRes = checkSyntax(resolvedPath);
674
+ const syntaxRes = checkSyntax(resolvedPath, getConfig(resultCwd).safety.exec_timeout_ms);
616
675
 
617
676
  if (!syntaxRes.valid && syntaxRes.status === "failed") {
618
677
  const warning = `\n\n[SYNTAX WARNING] ${syntaxRes.error}\nPlease fix this syntax error.`;
@@ -635,10 +694,15 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
635
694
  // system prompt by this extension.
636
695
  pi.on("before_agent_start", async (event: any, ctx: any) => {
637
696
  const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
697
+ const sessionId = getSessionId(ctx);
638
698
  const kernelConfig = getConfig(currentCwd);
639
699
 
640
700
  const basePrompt = event.systemPrompt || "";
641
- const systemPrompt = piDocsEnabled(ctx)
701
+ const includePiDocs = piDocsEnabled(ctx, getConfig);
702
+ if (!includePiDocs && event.systemPromptOptions?.sections?.docs !== undefined) {
703
+ delete event.systemPromptOptions.sections.docs;
704
+ }
705
+ const systemPrompt = includePiDocs
642
706
  ? basePrompt
643
707
  : withoutPiDocumentation(basePrompt);
644
708
  const activeToolNames = new Set(pi.getActiveTools?.() || []);
@@ -664,6 +728,24 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
664
728
  guidedPrompt = `${guidedPrompt.trimEnd()}\n\n${hostEnv}`;
665
729
  }
666
730
  }
731
+
732
+ const pendingNotification = pendingEngineNotificationBySession.get(sessionId);
733
+ if (pendingNotification) {
734
+ pendingEngineNotificationBySession.delete(sessionId);
735
+ try {
736
+ const index = getSearchIndex(currentCwd);
737
+ lastNotifiedProfileBySession.set(sessionId, index.getEffectiveProfile());
738
+ } catch {}
739
+ return {
740
+ systemPrompt: guidedPrompt,
741
+ message: {
742
+ customType: "agent-kernel-engine-notification",
743
+ content: pendingNotification,
744
+ display: true,
745
+ },
746
+ };
747
+ }
748
+
667
749
  return { systemPrompt: guidedPrompt };
668
750
  });
669
751
  }
@@ -3,7 +3,6 @@ import * as path from "node:path";
3
3
  import * as crypto from "node:crypto";
4
4
  import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS, type WorkspaceWalkCache } from "./workspace_walker";
5
5
  import { extractFileTags, isTestPath, SymbolDef } from "./tag_extractor";
6
- import { TreeSitterEngine } from "./tree_sitter_engine";
7
6
  import { chunkHtmlFile } from "./html_chunker";
8
7
 
9
8
  export interface CodeChunk {
@@ -93,72 +92,13 @@ export function chunkFile(rootDir: string, filePath: string, content?: string):
93
92
 
94
93
  const chunks: CodeChunk[] = [];
95
94
 
96
- // 1. Extract AST symbols using extractFileTags
97
- const tags = extractFileTags(absPath, fileContent);
95
+ // 1. Extract AST symbols (and top-level JS/TS test blocks for test files) in a single parse.
96
+ const tags = extractFileTags(absPath, fileContent, {
97
+ includeJsTestBlocks: isTestPath(relPath),
98
+ collectReferences: false,
99
+ });
98
100
  const defs = [...tags.definitions];
99
101
 
100
- // For test files (.test., .spec., /test/, /tests/), also extract top-level test blocks (describe/it/test/suite)
101
- // so test cases and assertions are indexed by code_search.
102
- if (isTestPath(relPath) && (ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx")) {
103
- const tsEngine = TreeSitterEngine.getInstance();
104
- const parser = tsEngine.getParser(ext);
105
- if (parser) {
106
- try {
107
- const tree = parser.parse(fileContent);
108
- const root = tree.rootNode;
109
- for (let i = 0; i < root.childCount; i++) {
110
- const child = root.child(i);
111
- if (child.type === "expression_statement") {
112
- let expr = child.firstNamedChild;
113
- let callee: any = null;
114
- let argsNode: any = null;
115
- while (expr && expr.type === "call_expression") {
116
- const fn = expr.childForFieldName("function");
117
- const args = expr.childForFieldName("arguments");
118
- if (args && !argsNode) argsNode = args;
119
- if (fn) {
120
- callee = fn;
121
- if (fn.type === "call_expression") {
122
- expr = fn;
123
- } else {
124
- break;
125
- }
126
- } else {
127
- break;
128
- }
129
- }
130
- if (callee) {
131
- const calleeText = callee.text;
132
- const match = calleeText.match(/^(?:(?:suite|describe|context|it|test)(?:\.(?:only|skip|each|todo|concurrent|serial))?)/);
133
- if (match) {
134
- let title = "";
135
- if (argsNode) {
136
- for (const arg of argsNode.namedChildren) {
137
- if (arg.type === "string" || arg.type === "template_string") {
138
- title = arg.text.replace(/^['"`]|['"`]$/g, "");
139
- break;
140
- }
141
- }
142
- }
143
- const testName = title ? `${match[0]}('${title}')` : match[0];
144
- const firstLine = fileContent.slice(child.startIndex, fileContent.indexOf("\n", child.startIndex)).trim();
145
- defs.push({
146
- name: testName,
147
- kind: "test",
148
- signature: firstLine.length < 120 ? firstLine : testName,
149
- line: child.startPosition.row + 1,
150
- endLine: child.endPosition.row + 1,
151
- });
152
- }
153
- }
154
- }
155
- }
156
- } catch {
157
- // Tree-sitter parsing is best-effort fallback
158
- }
159
- }
160
- }
161
-
162
102
  defs.sort((a, b) => a.line - b.line);
163
103
 
164
104
  // If file has no AST definitions or is small (< 40 lines), chunk as single whole file
@@ -14,18 +14,35 @@ export class LocalEmbedder {
14
14
  private config: SearchConfig;
15
15
  private isInitializing = false;
16
16
  private initPromise: Promise<void> | null = null;
17
+ private lastInitFailureAt = 0;
18
+ private retryCooldownMs: number;
19
+ private pipelineLoader?: (config: SearchConfig, onProgress?: (msg: string) => void) => Promise<any>;
17
20
  private queryLruCache = new Map<string, Float32Array>();
18
21
  private static readonly MAX_QUERY_CACHE_ENTRIES = 128;
22
+ private static readonly DEFAULT_INIT_RETRY_COOLDOWN_MS = 60_000;
19
23
 
20
- constructor(config?: SearchConfig) {
24
+ constructor(
25
+ config?: SearchConfig,
26
+ options?: {
27
+ retryCooldownMs?: number;
28
+ pipelineLoader?: (config: SearchConfig, onProgress?: (msg: string) => void) => Promise<any>;
29
+ },
30
+ ) {
21
31
  this.config = config || getSearchConfig();
32
+ this.retryCooldownMs = options?.retryCooldownMs ?? LocalEmbedder.DEFAULT_INIT_RETRY_COOLDOWN_MS;
33
+ this.pipelineLoader = options?.pipelineLoader;
22
34
  }
23
35
 
24
36
  public updateConfig(config: SearchConfig): void {
25
37
  this.config = config;
38
+ this.lastInitFailureAt = 0;
26
39
  this.queryLruCache.clear();
27
40
  }
28
41
 
42
+ public resetFailureBackoff(): void {
43
+ this.lastInitFailureAt = 0;
44
+ }
45
+
29
46
  public isLoaded(): boolean {
30
47
  return this.extractor !== null;
31
48
  }
@@ -138,6 +155,9 @@ export class LocalEmbedder {
138
155
  await this.initPromise;
139
156
  return this.extractor !== null;
140
157
  }
158
+ if (this.lastInitFailureAt > 0 && Date.now() - this.lastInitFailureAt < this.retryCooldownMs) {
159
+ return false;
160
+ }
141
161
 
142
162
  this.isInitializing = true;
143
163
  this.initPromise = (async () => {
@@ -149,42 +169,51 @@ export class LocalEmbedder {
149
169
  onProgress?.("Downloading embedding weights: 0% (~147 MB)...");
150
170
  }
151
171
 
152
- // Enforce single-thread CPU constraints to avoid starving system processes
153
- process.env.OMP_NUM_THREADS = String(this.config.numThreads || 1);
154
- process.env.ORT_INTRA_OP_NUM_THREADS = String(this.config.numThreads || 1);
155
- process.env.ORT_INTER_OP_NUM_THREADS = String(this.config.numThreads || 1);
172
+ if (this.pipelineLoader) {
173
+ this.extractor = await this.pipelineLoader(this.config, onProgress);
174
+ } else {
175
+ // Enforce single-thread CPU constraints to avoid starving system processes
176
+ process.env.OMP_NUM_THREADS = String(this.config.numThreads || 1);
177
+ process.env.ORT_INTRA_OP_NUM_THREADS = String(this.config.numThreads || 1);
178
+ process.env.ORT_INTER_OP_NUM_THREADS = String(this.config.numThreads || 1);
179
+
180
+ const { env, pipeline } = await import(
181
+ "@huggingface/transformers"
182
+ );
183
+ if (env && env.backends && env.backends.onnx) {
184
+ env.backends.onnx.numThreads = this.config.numThreads || 1;
185
+ env.backends.onnx.logLevel = "warning";
186
+ }
156
187
 
157
- const { env, pipeline } = await import(
158
- "@huggingface/transformers"
159
- );
160
- if (env && env.backends && env.backends.onnx) {
161
- env.backends.onnx.numThreads = this.config.numThreads || 1;
162
- env.backends.onnx.logLevel = "warning";
188
+ this.extractor = await pipeline("feature-extraction", this.config.modelId, {
189
+ revision: this.config.modelRevision,
190
+ dtype: this.config.dtype,
191
+ progress_callback: (p: any) => {
192
+ if (p.status === "progress" && p.total && p.loaded) {
193
+ const pct = Math.round((p.loaded / p.total) * 100);
194
+ onProgress?.(`Downloading embedding weights: ${pct}%`);
195
+ }
196
+ },
197
+ });
163
198
  }
164
199
 
165
- this.extractor = await pipeline("feature-extraction", this.config.modelId, {
166
- revision: this.config.modelRevision,
167
- dtype: this.config.dtype,
168
- progress_callback: (p: any) => {
169
- if (p.status === "progress" && p.total && p.loaded) {
170
- const pct = Math.round((p.loaded / p.total) * 100);
171
- onProgress?.(`Downloading embedding weights: ${pct}%`);
172
- }
173
- },
174
- });
175
-
176
200
  // Clamp the sequence length to bound ONNX activation RAM. Texts are cut to 1,800 chars first; with this
177
201
  // model those take ≤ 980 tokens in all but 3 of 23,000 measured chunks, so 1,024 rarely truncates.
178
202
  if (this.extractor?.tokenizer?.config) {
179
203
  this.extractor.tokenizer.config.model_max_length = 1024;
180
204
  }
181
205
 
206
+ this.lastInitFailureAt = 0;
182
207
  onProgress?.("Embedding model loaded.");
183
208
  } catch (err: any) {
184
209
  console.error("[Search Embedder] Error loading pipeline:", err);
185
210
  this.extractor = null;
211
+ this.lastInitFailureAt = Date.now();
186
212
  } finally {
187
213
  this.isInitializing = false;
214
+ if (!this.extractor) {
215
+ this.initPromise = null;
216
+ }
188
217
  }
189
218
  })();
190
219
 
@@ -323,6 +352,7 @@ export class LocalEmbedder {
323
352
 
324
353
  this.extractor = null;
325
354
  this.initPromise = null;
355
+ this.lastInitFailureAt = 0;
326
356
  this.queryLruCache.clear();
327
357
 
328
358
  try {