@floydous/pi-agent-kernel 0.1.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 (57) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +108 -0
  3. package/config.toml +24 -0
  4. package/docs/README.md +22 -0
  5. package/docs/architecture.md +40 -0
  6. package/docs/configuration.md +43 -0
  7. package/docs/editing-and-verification.md +41 -0
  8. package/docs/lsp.md +31 -0
  9. package/docs/retrieval.md +42 -0
  10. package/docs/testing.md +32 -0
  11. package/package.json +48 -0
  12. package/src/config/index.ts +2 -0
  13. package/src/config/kernel_config.ts +218 -0
  14. package/src/config/toml.ts +237 -0
  15. package/src/context/session_repair.ts +99 -0
  16. package/src/dedup/content_store.ts +365 -0
  17. package/src/dedup/recall_tool.ts +157 -0
  18. package/src/editing/patch.ts +482 -0
  19. package/src/editing/post_edit_verification.ts +200 -0
  20. package/src/editing/syntax-verify.ts +353 -0
  21. package/src/index.ts +852 -0
  22. package/src/lsp/adapters/base.ts +42 -0
  23. package/src/lsp/adapters/index.ts +21 -0
  24. package/src/lsp/adapters/python.ts +37 -0
  25. package/src/lsp/adapters/rust.ts +35 -0
  26. package/src/lsp/adapters/typescript.ts +40 -0
  27. package/src/lsp/index.ts +13 -0
  28. package/src/lsp/lsp_client.ts +650 -0
  29. package/src/lsp/lsp_detector.ts +52 -0
  30. package/src/lsp/lsp_formatter.ts +284 -0
  31. package/src/lsp/lsp_installer.ts +604 -0
  32. package/src/lsp/lsp_manager.ts +202 -0
  33. package/src/lsp/lsp_modal.ts +675 -0
  34. package/src/lsp/lsp_registry.ts +539 -0
  35. package/src/lsp/lsp_types.ts +143 -0
  36. package/src/retrieval/ast_search.ts +926 -0
  37. package/src/retrieval/repomap.ts +779 -0
  38. package/src/retrieval/search_bm25.ts +190 -0
  39. package/src/retrieval/search_chunker.ts +251 -0
  40. package/src/retrieval/search_config.ts +162 -0
  41. package/src/retrieval/search_embedder.ts +362 -0
  42. package/src/retrieval/search_index.ts +753 -0
  43. package/src/retrieval/search_modal.ts +358 -0
  44. package/src/retrieval/symbol_reader.ts +200 -0
  45. package/src/safety/atomic_write.ts +26 -0
  46. package/src/safety/epistemic_guard.ts +733 -0
  47. package/src/safety/kernel_debug.ts +15 -0
  48. package/src/safety/output_clamper.ts +213 -0
  49. package/src/tools/ast_search_tool.ts +131 -0
  50. package/src/tools/code_search_tool.ts +147 -0
  51. package/src/tools/context.ts +20 -0
  52. package/src/tools/edit_tool.ts +288 -0
  53. package/src/tools/lsp_tool.ts +813 -0
  54. package/src/tools/read_tool.ts +348 -0
  55. package/src/tools/repo_map_tool.ts +57 -0
  56. package/src/ui/footer.ts +287 -0
  57. package/src/ui/tui_utils.ts +278 -0
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Debug-gated sink for intentionally best-effort catch blocks.
3
+ *
4
+ * Many operations in this extension are advisory (cache cleanup, optional
5
+ * parsing, UI polish) and deliberately swallow failures. This helper keeps
6
+ * them silent by default while making them observable when debugging:
7
+ * set PI_KERNEL_DEBUG=1 to surface swallowed errors on stderr.
8
+ */
9
+ export function kernelDebug(err: unknown): void {
10
+ if (!process.env.PI_KERNEL_DEBUG) return;
11
+ console.error(
12
+ "[agent-kernel]",
13
+ err instanceof Error ? err.stack || err.message : err,
14
+ );
15
+ }
@@ -0,0 +1,213 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import * as os from "node:os";
4
+ import * as crypto from "node:crypto";
5
+ import { kernelDebug } from "./kernel_debug";
6
+
7
+ export interface ClampingOptions {
8
+ maxLineLength?: number; // Maximum width per line (default: 300)
9
+ maxLines?: number; // Maximum lines shown to model (default: 40)
10
+ maxTotalBytes?: number; // Maximum total bytes before spilling (default: 20 * 1024 = 20 KB)
11
+ }
12
+
13
+ export interface ClampingResult {
14
+ text: string;
15
+ truncated: boolean;
16
+ spilloverPath?: string;
17
+ originalBytes: number;
18
+ returnedBytes: number;
19
+ totalLines: number;
20
+ shownLines: number;
21
+ }
22
+
23
+ /**
24
+ * Identify if a command is primarily a discovery/search/listing command
25
+ * where aggressive line-width clamping and match capping should be enforced.
26
+ */
27
+ export function isDiscoveryCommand(command: string): boolean {
28
+ if (!command) return false;
29
+ const trimmed = command.trim().toLowerCase();
30
+ const firstWord = trimmed.split(/\s+/)[0];
31
+
32
+ const discoveryTools = [
33
+ "grep",
34
+ "find",
35
+ "rg",
36
+ "ripgrep",
37
+ "locate",
38
+ "where",
39
+ "which",
40
+ "tree",
41
+ "ls",
42
+ "dir",
43
+ ];
44
+ if (discoveryTools.includes(firstWord)) return true;
45
+
46
+ // Check for piped discovery tools (e.g. `cat file | grep foo`)
47
+ if (/\b(grep|find|rg|tree|ls)\b/.test(trimmed)) {
48
+ return true;
49
+ }
50
+
51
+ return false;
52
+ }
53
+
54
+ /**
55
+ * Clamps output lines horizontally and vertically to prevent context bloat
56
+ * from single-line minified files, lockfiles, or massive multi-file matches.
57
+ * Preserves 100% of raw output in an OS temp spillover file when truncation occurs.
58
+ */
59
+ export function clampCommandOutput(
60
+ rawText: string,
61
+ command: string,
62
+ options?: ClampingOptions,
63
+ ): ClampingResult {
64
+ const maxLineLength = options?.maxLineLength ?? 300;
65
+ const maxLines = options?.maxLines ?? 40;
66
+ const maxTotalBytes = options?.maxTotalBytes ?? 20 * 1024;
67
+
68
+ const originalBytes = Buffer.byteLength(rawText, "utf8");
69
+
70
+ // If the entire output is small and within bounds, return as-is
71
+ if (
72
+ originalBytes <= maxTotalBytes &&
73
+ !rawText.includes("\n") &&
74
+ rawText.length <= maxLineLength
75
+ ) {
76
+ return {
77
+ text: rawText,
78
+ truncated: false,
79
+ originalBytes,
80
+ returnedBytes: originalBytes,
81
+ totalLines: 1,
82
+ shownLines: 1,
83
+ };
84
+ }
85
+
86
+ const rawLines = rawText.split(/\r?\n/);
87
+ const totalLines = rawLines.length;
88
+ let needsTruncation = false;
89
+
90
+ // Check if any line violates maxLineLength or total lines violate maxLines
91
+ if (totalLines > maxLines || originalBytes > maxTotalBytes) {
92
+ needsTruncation = true;
93
+ }
94
+
95
+ for (const line of rawLines) {
96
+ if (line.length > maxLineLength) {
97
+ needsTruncation = true;
98
+ break;
99
+ }
100
+ }
101
+
102
+ // If no truncation is necessary, return clean output
103
+ if (!needsTruncation) {
104
+ return {
105
+ text: rawText,
106
+ truncated: false,
107
+ originalBytes,
108
+ returnedBytes: originalBytes,
109
+ totalLines,
110
+ shownLines: totalLines,
111
+ };
112
+ }
113
+
114
+ // Save complete raw output to temporary spillover file (with bounded rotation by mtime to prevent unbounded tmp growth)
115
+ let spilloverPath: string | undefined;
116
+ try {
117
+ const tempDir = os.tmpdir();
118
+ // Prune older spillover logs (> 20 files, oldest first by mtime)
119
+ try {
120
+ const files = fs
121
+ .readdirSync(tempDir)
122
+ .filter((f) => f.startsWith("pi_bash_spillover_"))
123
+ .map((name) => {
124
+ const full = path.join(tempDir, name);
125
+ try {
126
+ return { name, full, mtime: fs.statSync(full).mtimeMs };
127
+ } catch {
128
+ return { name, full, mtime: 0 };
129
+ }
130
+ })
131
+ .sort((a, b) => a.mtime - b.mtime);
132
+
133
+ if (files.length > 20) {
134
+ const toDelete = files.slice(0, files.length - 20);
135
+ for (const item of toDelete) {
136
+ try { fs.unlinkSync(item.full); } catch {}
137
+ }
138
+ }
139
+ } catch {}
140
+
141
+ const hash = crypto.randomBytes(4).toString("hex");
142
+ spilloverPath = path.join(tempDir, `pi_bash_spillover_${hash}.log`);
143
+ fs.writeFileSync(spilloverPath, rawText, "utf8");
144
+ } catch (e) {
145
+ kernelDebug(e);
146
+ }
147
+
148
+ // Horizontal Line-Width Clamping & Vertical Head+Tail Capping
149
+ const clampedLines: string[] = [];
150
+
151
+ const formatLine = (line: string, idx: number): string => {
152
+ if (line.length > maxLineLength) {
153
+ const kept = line.slice(0, Math.max(10, maxLineLength - 60));
154
+ const omitted = line.length - kept.length;
155
+ return `${kept}... <line ${idx + 1} truncated: ${omitted.toLocaleString()} chars omitted>`;
156
+ }
157
+ return line;
158
+ };
159
+
160
+ let shownLines = totalLines;
161
+
162
+ if (totalLines > maxLines) {
163
+ const effectiveMaxLines = Math.max(2, maxLines);
164
+ const headCount = Math.floor(effectiveMaxLines / 2);
165
+ const tailCount = effectiveMaxLines - headCount;
166
+ const omittedLines = totalLines - (headCount + tailCount);
167
+ shownLines = headCount + tailCount;
168
+
169
+ // Head lines
170
+ for (let i = 0; i < headCount; i++) {
171
+ clampedLines.push(formatLine(rawLines[i], i));
172
+ }
173
+
174
+ // Middle omission marker
175
+ clampedLines.push(
176
+ `\n[... ${omittedLines.toLocaleString()} lines omitted ...]\n`,
177
+ );
178
+
179
+ // Tail lines
180
+ const tailStart = totalLines - tailCount;
181
+ for (let i = tailStart; i < totalLines; i++) {
182
+ clampedLines.push(formatLine(rawLines[i], i));
183
+ }
184
+ } else {
185
+ for (let i = 0; i < totalLines; i++) {
186
+ clampedLines.push(formatLine(rawLines[i], i));
187
+ }
188
+ }
189
+
190
+ let resultText = clampedLines.join("\n");
191
+
192
+ // Append concise footer with spillover pointer
193
+ let footer = `\n\n[Truncated: ${shownLines}/${totalLines} lines.`;
194
+ if (spilloverPath) {
195
+ footer += ` Full: ${spilloverPath}]`;
196
+ } else {
197
+ footer += `]`;
198
+ }
199
+
200
+ resultText += footer;
201
+
202
+ const returnedBytes = Buffer.byteLength(resultText, "utf8");
203
+
204
+ return {
205
+ text: resultText,
206
+ truncated: true,
207
+ spilloverPath,
208
+ originalBytes,
209
+ returnedBytes,
210
+ totalLines,
211
+ shownLines,
212
+ };
213
+ }
@@ -0,0 +1,131 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { Text, makeOutputText } from "../ui/tui_utils";
4
+ import { searchAstSymbols } from "../retrieval/ast_search";
5
+ import { globalEpistemicGuard } from "../safety/epistemic_guard";
6
+ import type { SessionDeps } from "./context";
7
+
8
+ /** Extracted from index.ts — registers the `ast_search` tool. */
9
+ export function registerAstSearchTool(
10
+ pi: ExtensionAPI,
11
+ deps: SessionDeps,
12
+ ): void {
13
+ // 5. Tool: `ast_search` (Tree-sitter Structural Symbol Search)
14
+ pi.registerTool({
15
+ name: "ast_search",
16
+ label: "Tree-sitter AST Search",
17
+ description:
18
+ "Search symbol declarations (functions, classes, methods, types) by AST structure across the repository. Bypasses comments, strings, and documentation.",
19
+ promptSnippet:
20
+ "Search exact code declarations and signatures via Tree-sitter AST",
21
+ renderShell: "default",
22
+ parameters: Type.Object({
23
+ name: Type.Optional(
24
+ Type.String({ description: "Symbol name or substring to search" }),
25
+ ),
26
+ kind: Type.Optional(
27
+ Type.String({
28
+ description:
29
+ "Kind: function | class | method | interface | type | struct | trait | enum | impl | alias | variable | constant",
30
+ }),
31
+ ),
32
+ filePattern: Type.Optional(
33
+ Type.String({
34
+ description:
35
+ "Optional normalized relative path substring (e.g. 'src/safety', '.py', 'test')",
36
+ }),
37
+ ),
38
+ includeBody: Type.Optional(
39
+ Type.Boolean({
40
+ description:
41
+ "Include a bounded preview of up to 25 symbol lines (default: false); use read({ path, symbol }) for the complete body",
42
+ }),
43
+ ),
44
+ }),
45
+ async execute(
46
+ _toolCallId: string,
47
+ params: any,
48
+ _signal: any,
49
+ onUpdate: any,
50
+ ctx: any,
51
+ ): Promise<any> {
52
+ onUpdate?.({
53
+ content: [
54
+ { type: "text", text: `Searching AST for "${params.name || "*"}"...` },
55
+ ],
56
+ });
57
+ const results = searchAstSymbols(ctx.cwd, {
58
+ name: params.name,
59
+ kind: params.kind,
60
+ filePattern: params.filePattern,
61
+ includeBody: params.includeBody ?? false,
62
+ });
63
+
64
+ const sessionId = deps.getSessionId(ctx);
65
+ for (const r of results) {
66
+ const visibleRange = r.codeBlock && r.visibleEndLine
67
+ ? { startLine: r.line, endLine: r.visibleEndLine }
68
+ : null;
69
+ globalEpistemicGuard.recordFileSearched(r.filePath, sessionId, ctx.cwd, {
70
+ coverage: {
71
+ complete: false,
72
+ ranges: visibleRange ? [visibleRange] : [],
73
+ },
74
+ provenance: "ast_search",
75
+ query: params.name,
76
+ });
77
+ }
78
+
79
+ if (results.length === 0) {
80
+ return {
81
+ content: [
82
+ {
83
+ type: "text",
84
+ text: `No AST symbols found matching query. (Note: For string literals, error codes, or configs, use 'rg' in bash).`,
85
+ },
86
+ ],
87
+ details: { count: 0 },
88
+ };
89
+ }
90
+
91
+ const formatted = results.slice(0, 30).map((r) => {
92
+ const normPath = r.filePath.replace(/\\/g, "/");
93
+ const span = r.endLine && r.endLine !== r.line ? `${r.line}-${r.endLine}` : `${r.line}`;
94
+ let str = `${normPath}:${span} [${r.kind}] ${r.signature || r.name}`;
95
+ if (r.codeBlock) {
96
+ str += `\n${r.codeBlock}`;
97
+ }
98
+ return str;
99
+ });
100
+
101
+ return {
102
+ content: [
103
+ {
104
+ type: "text",
105
+ text: formatted.join("\n"),
106
+ },
107
+ ],
108
+ details: { count: results.length },
109
+ };
110
+ },
111
+ renderCall(args: any, theme: any, _context: any) {
112
+ return makeOutputText(
113
+ `${theme.fg("toolTitle", theme.bold("ast_search"))} ${theme.fg("accent", args?.name || "*")}${args?.kind ? ` [${args.kind}]` : ""}`,
114
+ );
115
+ },
116
+ renderResult(result: any, options: any, theme: any, context: any) {
117
+ if (context.isError) {
118
+ const errMsg =
119
+ result.content?.find((c: any) => c.type === "text")?.text ||
120
+ "Search failed";
121
+ return makeOutputText(`\n${theme.fg("error", errMsg)}`);
122
+ }
123
+ if (!options.expanded) {
124
+ return new Text("", 0, 0);
125
+ }
126
+ const output =
127
+ result.content?.find((c: any) => c.type === "text")?.text || "";
128
+ return makeOutputText(`\n${theme.fg("toolOutput", output)}`);
129
+ },
130
+ });
131
+ }
@@ -0,0 +1,147 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { Text, makeOutputText } from "../ui/tui_utils";
4
+ import * as path from "node:path";
5
+ import { globalEpistemicGuard } from "../safety/epistemic_guard";
6
+ import type { SearchDeps } from "./context";
7
+
8
+ /** Extracted from index.ts — registers the `code_search` tool. */
9
+ export function registerCodeSearchTool(
10
+ pi: ExtensionAPI,
11
+ deps: SearchDeps,
12
+ ): void {
13
+ // 5.5 Tool: `code_search` (Local Hybrid BM25 + Semantic AST Code Search)
14
+ pi.registerTool({
15
+ name: "code_search",
16
+ label: "Codebase Search",
17
+ description:
18
+ "Search the codebase using hybrid BM25 and semantic ranking across AST-bounded code chunks with hierarchical breadcrumbs. Ideal for conceptual queries, keywords, and finding relevant functions.",
19
+ promptSnippet:
20
+ "Search codebase conceptually or by keywords via hybrid AST index",
21
+ renderShell: "default",
22
+ parameters: Type.Object({
23
+ query: Type.String({
24
+ description:
25
+ "Search query: natural language concepts, variable names, error messages, or task descriptions",
26
+ }),
27
+ file_pattern: Type.Optional(
28
+ Type.String({
29
+ description:
30
+ "Optional normalized relative path substring (e.g. 'src/auth', '.py', 'test')",
31
+ }),
32
+ ),
33
+ limit: Type.Optional(
34
+ Type.Number({
35
+ description:
36
+ "Maximum number of code chunks to return (default: 5, max: 15)",
37
+ }),
38
+ ),
39
+ rrf_k: Type.Optional(
40
+ Type.Number({
41
+ description: "Optional RRF smoothing constant from 1 to 200 (default: 60)",
42
+ }),
43
+ ),
44
+ }),
45
+ async execute(
46
+ _toolCallId: string,
47
+ params: any,
48
+ _signal: any,
49
+ onUpdate: any,
50
+ ctx: any,
51
+ ): Promise<any> {
52
+ const query = (params.query || "").trim();
53
+ if (!query) {
54
+ return {
55
+ content: [{ type: "text", text: "[ERROR] Search query cannot be empty." }],
56
+ details: { count: 0 },
57
+ isError: true,
58
+ };
59
+ }
60
+
61
+ onUpdate?.({
62
+ content: [{ type: "text", text: `Searching code for "${query}"...` }],
63
+ });
64
+ const index = deps.getSearchIndex(ctx.cwd);
65
+ const configuredLimit = deps.getConfig?.(ctx.cwd).retrieval.max_search_results ?? 5;
66
+ const limit = Math.min(
67
+ Math.max(params.limit ?? configuredLimit, 1),
68
+ 15,
69
+ );
70
+
71
+ const hits = await index.search(query, {
72
+ limit,
73
+ filePattern: params.file_pattern,
74
+ rrfK: params.rrf_k,
75
+ });
76
+
77
+ const sessionId = deps.getSessionId(ctx);
78
+ for (const hit of hits) {
79
+ globalEpistemicGuard.recordFileSearched(
80
+ hit.chunk.absolutePath,
81
+ sessionId,
82
+ ctx.cwd,
83
+ {
84
+ coverage: { complete: false, ranges: [] },
85
+ provenance: "code_search",
86
+ query,
87
+ },
88
+ );
89
+ }
90
+
91
+ if (hits.length === 0) {
92
+ return {
93
+ content: [
94
+ {
95
+ type: "text",
96
+ text: `No code chunks found matching "${query}". (Tips: Try 'ast_search' for exact symbol names or 'rg' for exact text literals).`,
97
+ },
98
+ ],
99
+ details: { count: 0 },
100
+ };
101
+ }
102
+
103
+ const formatted = hits.map((hit) => {
104
+ const chunk = hit.chunk;
105
+ const normPath = chunk.filePath.replace(/\\/g, "/");
106
+ const lang = path.extname(chunk.filePath).slice(1) || "text";
107
+ return `${normPath}:${chunk.startLine}-${chunk.endLine} [${chunk.kind}] ${chunk.symbolName} (${chunk.breadcrumb}):\n\`\`\`${lang}\n${chunk.content}\n\`\`\``;
108
+ });
109
+
110
+ return {
111
+ content: [
112
+ {
113
+ type: "text",
114
+ text: formatted.join("\n\n"),
115
+ },
116
+ ],
117
+ details: {
118
+ count: hits.length,
119
+ hits: hits.map((h) => ({
120
+ id: h.chunk.id,
121
+ score: h.rrfScore,
122
+ signal: h.signal,
123
+ })),
124
+ },
125
+ };
126
+ },
127
+ renderCall(args: any, theme: any, _context: any) {
128
+ return makeOutputText(
129
+ `${theme.fg("toolTitle", theme.bold("code_search"))} ${theme.fg("accent", `"${args?.query || ""}"`)}${args?.file_pattern ? ` in ${args.file_pattern}` : ""}`,
130
+ );
131
+ },
132
+ renderResult(result: any, options: any, theme: any, context: any) {
133
+ if (context.isError) {
134
+ const errMsg =
135
+ result.content?.find((c: any) => c.type === "text")?.text ||
136
+ "Search failed";
137
+ return makeOutputText(`\n${theme.fg("error", errMsg)}`);
138
+ }
139
+ if (!options.expanded) {
140
+ return new Text("", 0, 0);
141
+ }
142
+ const output =
143
+ result.content?.find((c: any) => c.type === "text")?.text || "";
144
+ return makeOutputText(`\n${theme.fg("toolOutput", output)}`);
145
+ },
146
+ });
147
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Shared dependencies injected from the kernel entry point into tool modules.
3
+ * Keeps tool registration pure: no hidden singletons, everything flows through
4
+ * these explicit contracts.
5
+ */
6
+ export interface SessionDeps {
7
+ /** Resolve stable session id for epistemic-guard bookkeeping. */
8
+ getSessionId: (ctx: any) => string;
9
+ /** Load runtime settings for the active workspace. */
10
+ getConfig?: (cwd: string) => import("../config").KernelConfig;
11
+ /** Mark a successfully mutated file stale in the workspace index. */
12
+ invalidateSearchFile?: (cwd: string, filePath: string) => void;
13
+ }
14
+
15
+ export interface SearchDeps extends SessionDeps {
16
+ /** Lazily create/access the workspace hybrid search index singleton. */
17
+ getSearchIndex: (
18
+ cwd: string,
19
+ ) => import("../retrieval/search_index").HybridSearchIndex;
20
+ }