@floydous/pi-agent-kernel 0.1.0 → 0.2.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,32 @@
1
+ # Changelog
2
+
3
+ ## [0.2.0] - 2026-09-05
4
+
5
+ This release replaces the old line-based symbol extraction path with a Tree-sitter WASM parser where a bundled grammar is available, while keeping the scanner fallback for unsupported or unavailable languages.
6
+
7
+ ### Added
8
+
9
+ - Tree-sitter WASM parsing for TypeScript, JavaScript, Python, Rust, Go, C, C++, Java, C#, Bash, Ruby, and PHP.
10
+ - AST-based symbol lookup and reference extraction that handles class methods and ignores identifiers inside comments and strings.
11
+ - Support for exact AST end lines when reading symbols and building search chunks.
12
+ - Parsing for additional constructs including abstract and ambient TypeScript declarations, Go interfaces, Rust traits, and C++ member methods.
13
+ - Regression coverage for the parser, cache, repository map, LSP lookup, and polyglot extraction paths.
14
+
15
+ ### Changed
16
+
17
+ - Grammars load on demand for languages found in the workspace instead of loading every grammar at startup.
18
+ - Search caches now record the extractor generation and reject caches produced by an older extractor.
19
+ - Repository-map startup waits for Tree-sitter initialization, including the `/repomap` command path.
20
+ - LSP executable lookup checks both the extension-local directory and the legacy user directory.
21
+ - Hover output removes transient `(loading...)` markers returned by language servers.
22
+ - `typebox` is now packaged as a runtime dependency.
23
+
24
+ ### Fixed
25
+
26
+ - Native Tree-sitter parse trees are released after extraction.
27
+ - Local variables no longer appear as top-level repository-map symbols.
28
+ - Braces in strings and comments no longer truncate symbol content.
29
+ - Syntax errors are reported on extracted file tags.
30
+ - LSP reference filtering preserves the intended fallback behavior.
31
+
32
+ [0.2.0]: https://github.com/floydous/pi-agent-kernel/releases/tag/v0.2.0
package/README.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  A Pi extension for code retrieval, surgical editing, safety checks, and language-server support.
4
4
 
5
+ ## Pi with and without agent-kernel
6
+
7
+ The screenshots compare a Pi session with agent-kernel to one without it. The agent-kernel run uses fewer tool calls and fits in one screenshot. The run without agent-kernel takes three screenshots, shown in order from top to bottom.
8
+
9
+ ### With agent-kernel
10
+
11
+ ![Pi session with agent-kernel](static/with-agent-kernel.png)
12
+
13
+ ### Without agent-kernel
14
+
15
+ ![Pi session without agent-kernel, top](static/without-agent-kernel-1.png)
16
+
17
+ ![Pi session without agent-kernel, middle](static/without-agent-kernel-2.png)
18
+
19
+ ![Pi session without agent-kernel, bottom](static/without-agent-kernel-3.png)
20
+
5
21
  ## Design priorities
6
22
 
7
23
  The extension keeps agent interactions small while improving reliability. It uses focused retrieval, bounded output, deterministic checks, and grounded edits. It avoids loading unnecessary context, doing background work without a reason, or making speculative changes.
@@ -87,6 +103,7 @@ The entry point is declared in `package.json` under `pi.extensions` (`./src/inde
87
103
  | `/repomap` | `[budget]` | Render the AST and PageRank-ranked repository map. The default budget is 1024 tokens. |
88
104
  | `/engine` | `auto\|lean\|hybrid\|full\|off\|status\|reindex` | Change the retrieval profile or inspect engine state. `lean` is the default and uses AST-aware BM25; `hybrid` adds local embeddings. |
89
105
  | `/lsp` | `[install <lang>]` | Inspect active language servers or install one, for example `/lsp install python`. |
106
+ | `/pi-docs` | `on\|off\|status` | Toggle Pi documentation guidance in the system prompt for the current session. |
90
107
 
91
108
  ## Configuration
92
109
 
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floydous/pi-agent-kernel",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Focused code retrieval, editing, safety checks, and language-server support for Pi.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -14,15 +14,13 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "@huggingface/transformers": "^4.2.0",
17
- "diff": "^9.0.0"
18
- },
19
- "peerDependencies": {
20
- "typebox": "^1.3.16"
17
+ "diff": "^9.0.0",
18
+ "typebox": "^1.3.16",
19
+ "web-tree-sitter": "^0.26.12"
21
20
  },
22
21
  "devDependencies": {
23
22
  "@earendil-works/pi-coding-agent": "0.84.3",
24
23
  "tsx": "^4.23.13",
25
- "typebox": "^1.3.16",
26
24
  "typescript": "^7.0.2"
27
25
  },
28
26
  "overrides": {
@@ -40,9 +38,12 @@
40
38
  },
41
39
  "files": [
42
40
  "src",
41
+ "grammars",
43
42
  "README.md",
43
+ "static",
44
44
  "docs",
45
45
  "LICENSE",
46
- "config.toml"
46
+ "config.toml",
47
+ "CHANGELOG.md"
47
48
  ]
48
49
  }
package/src/index.ts CHANGED
@@ -18,6 +18,7 @@ import { registerCodeSearchTool } from "./tools/code_search_tool";
18
18
  import { registerReadTool } from "./tools/read_tool";
19
19
  import { registerEditTool } from "./tools/edit_tool";
20
20
  import { registerLspTool } from "./tools/lsp_tool";
21
+ import { TreeSitterEngine } from "./retrieval/tree_sitter_engine";
21
22
 
22
23
  /**
23
24
  * Resolve the current session id from a handler context, or fall back to a
@@ -42,6 +43,27 @@ function getSessionId(ctx: any): string {
42
43
 
43
44
  return `__default__${process.pid}`;
44
45
  }
46
+
47
+ const PI_DOCS_START =
48
+ "Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):";
49
+ const PI_DOCS_END = /\n- Always read pi \.md files completely[^\n]*/;
50
+ const piDocsEnabledBySession = new Map<string, boolean>();
51
+
52
+ function withoutPiDocumentation(systemPrompt: string): string {
53
+ const start = systemPrompt.indexOf(PI_DOCS_START);
54
+ if (start < 0) return systemPrompt;
55
+ const endMatch = systemPrompt.slice(start).match(PI_DOCS_END);
56
+ if (!endMatch || endMatch.index === undefined) return systemPrompt;
57
+
58
+ const end = start + endMatch.index + endMatch[0].length;
59
+ const before = systemPrompt.slice(0, start).replace(/\n{2,}$/, "\n");
60
+ const after = systemPrompt.slice(end).replace(/^\n{2,}/, "\n");
61
+ return before + after;
62
+ }
63
+
64
+ function piDocsEnabled(ctx: any): boolean {
65
+ return piDocsEnabledBySession.get(getSessionId(ctx)) ?? true;
66
+ }
45
67
  import { clampCommandOutput } from "./safety/output_clamper";
46
68
  import { sanitizeSessionFiles } from "./context/session_repair";
47
69
  import { renderFooter } from "./ui/footer";
@@ -58,6 +80,11 @@ import {
58
80
  } from "./lsp";
59
81
 
60
82
  export default async function unifiedHybridExtension(pi: ExtensionAPI) {
83
+ // Initialize TreeSitter WASM engine eagerly in background
84
+ TreeSitterEngine.getInstance().init().catch((err) => {
85
+ kernelDebug(`TreeSitter background init error: ${err}`);
86
+ });
87
+
61
88
  // 0. Auto-Sanitize Session Files (Repairs pre-existing incomplete usage metadata)
62
89
  try {
63
90
  sanitizeSessionFiles();
@@ -72,7 +99,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
72
99
  const dedupStore = new DedupStore();
73
100
  const getDedupStore = () => dedupStore;
74
101
 
75
- // 3. Slash Commands: /repomap, /engine, /lsp
102
+ // 3. Slash Commands: /repomap, /engine, /lsp, /pi-docs
76
103
  let activeTui: any = null;
77
104
  const configByWorkspace = new Map<
78
105
  string,
@@ -195,9 +222,42 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
195
222
  }
196
223
  };
197
224
 
225
+ pi.registerCommand("pi-docs", {
226
+ description: "Toggle Pi documentation guidance in the system prompt",
227
+ getArgumentCompletions: (prefix: string) => {
228
+ const options = [
229
+ { value: "on", label: "on - Include Pi documentation guidance" },
230
+ { value: "off", label: "off - Omit Pi documentation guidance" },
231
+ { value: "status", label: "status - Show the current setting" },
232
+ ];
233
+ const filtered = options.filter((option) =>
234
+ option.value.startsWith(prefix.toLowerCase()),
235
+ );
236
+ return filtered.length > 0 ? filtered : null;
237
+ },
238
+ handler: async (args: string, ctx: any) => {
239
+ const sessionId = getSessionId(ctx);
240
+ const value = (args || "").trim().toLowerCase();
241
+ if (value === "on" || value === "off") {
242
+ piDocsEnabledBySession.set(sessionId, value === "on");
243
+ ctx.ui?.notify?.(
244
+ `Pi documentation guidance ${value === "on" ? "enabled" : "disabled"} for this session.`,
245
+ "info",
246
+ );
247
+ return;
248
+ }
249
+
250
+ const enabled = piDocsEnabled(ctx);
251
+ const message = `Pi documentation guidance: ${enabled ? "on" : "off"}`;
252
+ ctx.ui?.notify?.(message, "info");
253
+ if (!ctx.hasUI) console.log(message);
254
+ },
255
+ });
256
+
198
257
  pi.registerCommand("repomap", {
199
258
  description: "Display the Tree-Sitter AST & PageRank ranked repository map",
200
259
  handler: async (args: string, ctx: any) => {
260
+ await TreeSitterEngine.getInstance().init();
201
261
  const budget = args ? parseInt(args, 10) : 1024;
202
262
  const map = computeRepoMap(
203
263
  ctx.cwd,
@@ -552,6 +612,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
552
612
  // shutdown we drop only this session's entry and stop running LSP daemons.
553
613
  pi.on("session_shutdown", async (_event: any, ctx: any) => {
554
614
  const sessionId = getSessionId(ctx);
615
+ piDocsEnabledBySession.delete(sessionId);
555
616
  globalEpistemicGuard.resetSession(sessionId);
556
617
  dedupStore.clearSession(sessionId);
557
618
  try {
@@ -828,6 +889,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
828
889
 
829
890
  // Cache repo-map across turns with a 15-second TTL to avoid scanning/PageRanking entire repo on every turn
830
891
  if (!cachedRepoMap || cachedRepoMapCwd !== currentCwd || now - lastRepoMapCheck > 15000) {
892
+ await TreeSitterEngine.getInstance().init();
831
893
  cachedRepoMap = computeRepoMap(
832
894
  currentCwd,
833
895
  getConfig(currentCwd).retrieval.repo_map_budget,
@@ -843,9 +905,13 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
843
905
  ${cachedRepoMap}
844
906
  ${dedupNote}
845
907
  `;
908
+ const basePrompt = event.systemPrompt || "";
909
+ const systemPrompt = piDocsEnabled(ctx)
910
+ ? basePrompt
911
+ : withoutPiDocumentation(basePrompt);
846
912
  return {
847
- systemPrompt: event.systemPrompt
848
- ? `${event.systemPrompt}\n\n${runtimeContext}`
913
+ systemPrompt: systemPrompt
914
+ ? `${systemPrompt}\n\n${runtimeContext}`
849
915
  : runtimeContext,
850
916
  };
851
917
  });
@@ -241,7 +241,9 @@ export function formatHover(hover: LspHover | null | undefined): string {
241
241
  };
242
242
 
243
243
  const rawText = extractText(hover.contents).trim();
244
- return rawText || "No hover information available.";
244
+ // Strip transient LSP loading state markers (e.g. tsserver / vtsls prefixing "(loading...) ")
245
+ const cleanText = rawText.replace(/\(loading\.\.\.\)\s*/g, "").trim();
246
+ return cleanText || "No hover information available.";
245
247
  }
246
248
 
247
249
  /**
@@ -7,7 +7,29 @@ import { getPiHomeDir, loadKernelConfig, saveGlobalKernelConfig } from "../confi
7
7
  import { kernelDebug } from "../safety/kernel_debug";
8
8
  import { writeFileSyncAtomic } from "../safety/atomic_write";
9
9
 
10
- export const PI_LSP_BIN_DIR = path.join(getPiHomeDir(), "lsp", "bin");
10
+ export function getExtensionLspBinDir(): string {
11
+ // Confined to extensions/agent-kernel/bin/lsp by default
12
+ const candidate1 = path.join(__dirname, "..", "..", "bin", "lsp");
13
+ const candidate2 = path.join(process.cwd(), "bin", "lsp");
14
+ const candidate = fs.existsSync(candidate1) ? candidate1 : fs.existsSync(candidate2) ? candidate2 : candidate1;
15
+
16
+ // Test write permission; if read-only (e.g. system-wide npm global install), fall back to ~/.pi/lsp/bin
17
+ try {
18
+ fs.mkdirSync(candidate, { recursive: true });
19
+ const probe = path.join(candidate, ".write_test");
20
+ fs.writeFileSync(probe, "");
21
+ fs.unlinkSync(probe);
22
+ return candidate;
23
+ } catch {
24
+ const userFallback = path.join(getPiHomeDir(), "lsp", "bin");
25
+ try {
26
+ fs.mkdirSync(userFallback, { recursive: true });
27
+ } catch {}
28
+ return userFallback;
29
+ }
30
+ }
31
+
32
+ export const PI_LSP_BIN_DIR = getExtensionLspBinDir();
11
33
 
12
34
  export const PI_LSP_CONFIG_FILE = path.join(
13
35
  getPiHomeDir(),
@@ -366,8 +388,10 @@ export function findExecutable(
366
388
 
367
389
  const isWindows = process.platform === "win32";
368
390
  const home = process.env.HOME || process.env.USERPROFILE || os.homedir();
391
+ const legacyUserLspBin = path.join(getPiHomeDir(), "lsp", "bin");
369
392
  const searchDirs = [
370
393
  PI_LSP_BIN_DIR,
394
+ legacyUserLspBin,
371
395
  path.join(home, ".local", "bin"),
372
396
  path.join(home, ".cargo", "bin"),
373
397
  path.join(home, "go", "bin"),
@@ -90,11 +90,15 @@ const SUPPORTED_EXTENSIONS = new Set([
90
90
  ".go",
91
91
  ".c",
92
92
  ".cpp",
93
+ ".cc",
93
94
  ".h",
94
95
  ".hpp",
95
96
  ".zig",
96
97
  ".rb",
97
98
  ".java",
99
+ ".cs",
100
+ ".sh",
101
+ ".bash",
98
102
  ".kt",
99
103
  ".php",
100
104
  ".lua",
@@ -796,7 +800,7 @@ export function searchAstSymbols(
796
800
  kind: def.kind,
797
801
  signature: def.signature,
798
802
  line: def.line,
799
- endLine: findSymbolEndLine(lines, def.line - 1, ext),
803
+ endLine: def.endLine && def.endLine >= def.line ? def.endLine : findSymbolEndLine(lines, def.line - 1, ext),
800
804
  codeBlock,
801
805
  visibleEndLine,
802
806
  bodyTruncated: includeBody ? bodyTruncated : undefined,
@@ -1,5 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
+ import { TreeSitterEngine } from "./tree_sitter_engine";
3
4
 
4
5
  export interface SymbolDef {
5
6
  name: string;
@@ -15,6 +16,7 @@ export interface SymbolDef {
15
16
  | "alias";
16
17
  signature: string;
17
18
  line: number;
19
+ endLine?: number;
18
20
  aliasedFrom?: {
19
21
  module?: string;
20
22
  originalName: string;
@@ -25,6 +27,7 @@ export interface FileTags {
25
27
  filePath: string;
26
28
  definitions: SymbolDef[];
27
29
  references: Set<string>;
30
+ hasSyntaxError?: boolean;
28
31
  }
29
32
 
30
33
  const IGNORED_DIRS = new Set([
@@ -182,10 +185,19 @@ function extractBalancedSig(
182
185
 
183
186
  // Fast AST & Signature tag extractor with multi-line support
184
187
  export function extractFileTags(filePath: string, content: string): FileTags {
188
+ const tsEngine = TreeSitterEngine.getInstance();
189
+ if (tsEngine.isSupported(filePath)) {
190
+ const treeTags = tsEngine.extractTags(filePath, content);
191
+ if (treeTags) {
192
+ return treeTags;
193
+ }
194
+ }
195
+
185
196
  const ext = path.extname(filePath).toLowerCase();
186
197
  const lines = content.split("\n");
187
198
  const definitions: SymbolDef[] = [];
188
199
  const references = new Set<string>();
200
+ let braceDepth = 0;
189
201
 
190
202
  // Extract identifier references (words matching [a-zA-Z_][a-zA-Z0-9_]*)
191
203
  const idRegex = /\b([a-zA-Z_][a-zA-Z0-9_]{2,})\b/g;
@@ -286,11 +298,11 @@ export function extractFileTags(filePath: string, content: string): FileTags {
286
298
  }
287
299
  }
288
300
 
289
- // const variable / constant declaration: const FOO = ... or const FOO: string = ...
301
+ // const variable / constant declaration: const FOO = ... or const FOO: string = ... (only top-level declarations)
290
302
  const constDecl = line.match(
291
303
  /^(?:export\s+)?const\s+([a-zA-Z0-9_]+)(?:\s*:\s*([^=]+))?\s*=/,
292
304
  );
293
- if (constDecl) {
305
+ if (constDecl && braceDepth === 0) {
294
306
  const isAllUpper = /^[A-Z0-9_]{2,}$/.test(constDecl[1]);
295
307
  definitions.push({
296
308
  name: constDecl[1],
@@ -572,6 +584,11 @@ export function extractFileTags(filePath: string, content: string): FileTags {
572
584
  continue;
573
585
  }
574
586
  }
587
+
588
+ for (const ch of line) {
589
+ if (ch === "{") braceDepth++;
590
+ else if (ch === "}") braceDepth = Math.max(0, braceDepth - 1);
591
+ }
575
592
  }
576
593
 
577
594
  return {
@@ -655,6 +672,16 @@ export function computeRepoMap(rootDir: string, tokenBudget = 1024): string {
655
672
  return "(No supported source files found in repository)";
656
673
  }
657
674
 
675
+ // Ensure languages present in sourceFiles are loaded in TreeSitterEngine
676
+ const detectedExts = new Set<string>();
677
+ for (const f of sourceFiles) {
678
+ const ext = path.extname(f).toLowerCase();
679
+ if (ext) detectedExts.add(ext);
680
+ }
681
+ // Note: loadLanguages is async, but if called from an async context it is pre-warmed.
682
+ // We also trigger loadLanguages asynchronously if not loaded.
683
+ void TreeSitterEngine.getInstance().loadLanguages(Array.from(detectedExts));
684
+
658
685
  const fileTagsMap = new Map<string, FileTags>();
659
686
  const defToFile = new Map<string, Set<string>>();
660
687
 
@@ -106,7 +106,10 @@ export function chunkFile(rootDir: string, filePath: string, content?: string):
106
106
  currentClass = def.name;
107
107
  }
108
108
 
109
- if (ext === ".py") {
109
+ if (def.endLine && def.endLine >= def.line) {
110
+ // Exact AST node boundaries from Tree-sitter
111
+ endIdx = Math.min(lines.length - 1, def.endLine - 1);
112
+ } else if (ext === ".py") {
110
113
  // Python scope
111
114
  const defLine = lines[startIdx];
112
115
  const matchIndent = defLine.match(/^(\s*)/);
@@ -123,7 +126,7 @@ export function chunkFile(rootDir: string, filePath: string, content?: string):
123
126
  endIdx = j;
124
127
  }
125
128
  } else {
126
- // Brace based scope
129
+ // Brace based scope (fallback)
127
130
  let braceCount = 0;
128
131
  let foundOpenBrace = false;
129
132
 
@@ -18,6 +18,10 @@ import {
18
18
  } from "./search_config";
19
19
  import { kernelDebug } from "../safety/kernel_debug";
20
20
  import { writeFileSyncAtomic } from "../safety/atomic_write";
21
+ import { TreeSitterEngine } from "./tree_sitter_engine";
22
+
23
+ const INDEX_VERSION = 3;
24
+ const EXTRACTOR_GENERATION = "tree-sitter-wasm-v2";
21
25
 
22
26
  export interface SearchHit {
23
27
  chunk: CodeChunk;
@@ -120,7 +124,12 @@ export class HybridSearchIndex {
120
124
  const raw = fs.readFileSync(indexPath, "utf-8");
121
125
  const data = JSON.parse(raw);
122
126
 
123
- if (data.version !== 1) return false;
127
+ if (
128
+ data.version !== INDEX_VERSION ||
129
+ data.extractorGeneration !== EXTRACTOR_GENERATION
130
+ ) {
131
+ return false;
132
+ }
124
133
 
125
134
  this.chunks.clear();
126
135
  this.bm25.clear();
@@ -242,7 +251,8 @@ export class HybridSearchIndex {
242
251
  .digest("hex");
243
252
 
244
253
  const indexData = {
245
- version: 1,
254
+ version: INDEX_VERSION,
255
+ extractorGeneration: EXTRACTOR_GENERATION,
246
256
  updatedAt: new Date().toISOString(),
247
257
  profile: this.config.profile,
248
258
  vectorDim,
@@ -389,6 +399,15 @@ export class HybridSearchIndex {
389
399
 
390
400
  onProgress?.("Scanning workspace files...");
391
401
 
402
+ // Ensure Tree-sitter parsers are warm for languages present in this workspace
403
+ const chunkableFiles = findChunkableFiles(this.cwd);
404
+ const workspaceExts = new Set<string>();
405
+ for (const f of chunkableFiles) {
406
+ const ext = path.extname(f).toLowerCase();
407
+ if (ext) workspaceExts.add(ext);
408
+ }
409
+ await TreeSitterEngine.getInstance().loadLanguages(Array.from(workspaceExts));
410
+
392
411
  // Read each file once and derive both its chunks and hash from that same
393
412
  // snapshot. A second read could pair old chunks with a new hash and make
394
413
  // the final freshness check falsely accept stale content.
@@ -396,7 +415,7 @@ export class HybridSearchIndex {
396
415
  string,
397
416
  { hash: string; chunks: CodeChunk[] }
398
417
  >();
399
- for (const absPath of findChunkableFiles(this.cwd)) {
418
+ for (const absPath of chunkableFiles) {
400
419
  const relPath = path.relative(this.cwd, absPath).replace(/\\/g, "/");
401
420
  try {
402
421
  const content = fs.readFileSync(absPath, "utf-8");
@@ -80,7 +80,10 @@ export function extractSymbolContent(
80
80
  }
81
81
  }
82
82
 
83
- if (ext === ".py") {
83
+ if (def.endLine && def.endLine >= def.line) {
84
+ // Ground-truth AST range provided directly by Tree-sitter
85
+ endIdx = Math.min(lines.length - 1, def.endLine - 1);
86
+ } else if (ext === ".py") {
84
87
  // Python indentation based boundary detection
85
88
  const defLine = lines[startIdx];
86
89
  const matchIndent = defLine.match(/^(\s*)/);
@@ -146,7 +149,7 @@ export function extractSymbolContent(
146
149
  endIdx = i;
147
150
  }
148
151
  } else {
149
- // Brace-based languages (TS, JS, Go, Rust, C++, Java, C#)
152
+ // Brace-based languages (fallback if AST endLine is unavailable)
150
153
  let braceCount = 0;
151
154
  let foundOpenBrace = false;
152
155