@floydous/pi-agent-kernel 0.4.3 → 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 (65) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +15 -12
  2. package/CHANGELOG.md +87 -0
  3. package/README.md +6 -54
  4. package/config.example.toml +1 -8
  5. package/docs/README.md +1 -2
  6. package/docs/architecture.md +2 -3
  7. package/docs/configuration.md +11 -10
  8. package/docs/editing-and-verification.md +21 -8
  9. package/docs/podman-linux-checks.md +24 -0
  10. package/docs/release-discipline.md +10 -0
  11. package/docs/retrieval.md +21 -23
  12. package/docs/testing.md +3 -3
  13. package/grammars/tree-sitter-html.wasm +0 -0
  14. package/package.json +5 -3
  15. package/src/config/agent_kernel_command.ts +60 -625
  16. package/src/config/kernel_config.ts +53 -69
  17. package/src/config/toml.ts +6 -1
  18. package/src/editing/auto_heal.ts +1 -1
  19. package/src/editing/patch.ts +75 -37
  20. package/src/editing/post_edit_verification.ts +20 -14
  21. package/src/editing/smart_anchor.ts +9 -6
  22. package/src/editing/syntax-verify.ts +79 -222
  23. package/src/index.ts +36 -453
  24. package/src/retrieval/html_chunker.ts +526 -0
  25. package/src/retrieval/search_bm25.ts +39 -28
  26. package/src/retrieval/search_chunker.ts +69 -7
  27. package/src/retrieval/search_config.ts +21 -40
  28. package/src/retrieval/search_embedder.ts +14 -31
  29. package/src/retrieval/search_index.ts +338 -129
  30. package/src/retrieval/search_modal.ts +1208 -222
  31. package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
  32. package/src/retrieval/tree_sitter_engine.ts +171 -36
  33. package/src/retrieval/workspace_walker.ts +78 -2
  34. package/src/safety/atomic_write.ts +1 -1
  35. package/src/safety/epistemic_guard.ts +105 -31
  36. package/src/safety/host_environment.ts +180 -0
  37. package/src/safety/output_clamper.ts +97 -27
  38. package/src/tools/code_search_output.ts +11 -2
  39. package/src/tools/code_search_tool.ts +25 -13
  40. package/src/tools/context.ts +11 -10
  41. package/src/tools/edit_tool.ts +243 -154
  42. package/src/tools/read_tool.ts +285 -214
  43. package/src/tools/stream_reader.ts +206 -0
  44. package/src/ui/footer.ts +7 -7
  45. package/docs/lsp.md +0 -31
  46. package/src/lsp/adapters/base.ts +0 -42
  47. package/src/lsp/adapters/index.ts +0 -21
  48. package/src/lsp/adapters/python.ts +0 -37
  49. package/src/lsp/adapters/rust.ts +0 -35
  50. package/src/lsp/adapters/typescript.ts +0 -40
  51. package/src/lsp/index.ts +0 -13
  52. package/src/lsp/lsp_client.ts +0 -765
  53. package/src/lsp/lsp_detector.ts +0 -52
  54. package/src/lsp/lsp_formatter.ts +0 -323
  55. package/src/lsp/lsp_installer.ts +0 -320
  56. package/src/lsp/lsp_manager.ts +0 -202
  57. package/src/lsp/lsp_modal.ts +0 -675
  58. package/src/lsp/lsp_registry.ts +0 -600
  59. package/src/lsp/lsp_types.ts +0 -143
  60. package/src/retrieval/ast_search.ts +0 -999
  61. package/src/retrieval/symbol_reader.ts +0 -228
  62. package/src/tools/ast_search_formatter.ts +0 -161
  63. package/src/tools/ast_search_tool.ts +0 -146
  64. package/src/tools/lsp_tool.ts +0 -794
  65. package/src/tools/repo_map_tool.ts +0 -56
@@ -0,0 +1,206 @@
1
+ import * as fs from "node:fs";
2
+ import { StringDecoder } from "node:string_decoder";
3
+
4
+ export interface StreamedReadResult {
5
+ lines: string[];
6
+ startLine: number;
7
+ endLine: number;
8
+ totalLinesRead: number;
9
+ hasMore: boolean;
10
+ totalBytes: number;
11
+ truncatedByBytes: boolean;
12
+ singleLineTruncated: boolean;
13
+ isBinary: boolean;
14
+ }
15
+
16
+ const CHUNK_SIZE = 64 * 1024;
17
+ const MAX_READ_BYTES = 50 * 1024; // 50 KB output budget
18
+ const MAX_SINGLE_LINE_BYTES = 50 * 1024;
19
+
20
+ /**
21
+ * Hardened bounded streaming line reader.
22
+ * Operates directly on an open file descriptor to eliminate TOCTOU races.
23
+ * Uses StringDecoder to prevent multi-byte UTF-8 character corruption across 64 KB chunk boundaries.
24
+ * Strictly caps single-line accumulation at 50 KB with early I/O exit to prevent O(N) heap blowup on newline-free files.
25
+ * Memory is strictly O(1) (< 200 KB) regardless of file size.
26
+ */
27
+ export function readStreamLineRangeFromFd(
28
+ fd: number,
29
+ options: {
30
+ offset?: number;
31
+ limit?: number;
32
+ maxBytes?: number;
33
+ } = {},
34
+ ): StreamedReadResult {
35
+ const offset = Math.max(1, options.offset ?? 1);
36
+ const limit = Math.max(1, Math.min(options.limit ?? 250, 2000));
37
+ const maxBytes = options.maxBytes ?? MAX_READ_BYTES;
38
+
39
+ const buf = Buffer.allocUnsafe(CHUNK_SIZE);
40
+ let currentLine = 1;
41
+ const targetEndLine = offset + limit - 1;
42
+ const collectedLines: string[] = [];
43
+ let accumulatedBytes = 0;
44
+ let truncatedByBytes = false;
45
+ let singleLineTruncated = false;
46
+ let hasMore = false;
47
+ let isBinary = false;
48
+ let checkedBinary = false;
49
+
50
+ const lineDecoder = new StringDecoder("utf8");
51
+ let currentLineDecoded = "";
52
+ let currentLineAccumulatedBytes = 0;
53
+ let skippingExcessInLine = false;
54
+
55
+ try {
56
+ let bytesRead = 0;
57
+ while ((bytesRead = fs.readSync(fd, buf, 0, CHUNK_SIZE, null)) > 0) {
58
+ // Binary guard: check for 0x00 null byte in the initial 8 KB
59
+ if (!checkedBinary) {
60
+ checkedBinary = true;
61
+ const probeLength = Math.min(bytesRead, 8192);
62
+ if (buf.subarray(0, probeLength).includes(0)) {
63
+ isBinary = true;
64
+ break;
65
+ }
66
+ }
67
+
68
+ let lineStart = 0;
69
+ for (let i = 0; i < bytesRead; i++) {
70
+ if (buf[i] === 0x0a) { // '\n'
71
+ const lineSlice = buf.subarray(lineStart, i);
72
+
73
+ if (currentLine >= offset && currentLine <= targetEndLine) {
74
+ if (!skippingExcessInLine) {
75
+ currentLineDecoded += lineDecoder.write(lineSlice);
76
+ currentLineAccumulatedBytes += lineSlice.length;
77
+ }
78
+ // Flush any remaining characters in decoder for this line
79
+ currentLineDecoded += lineDecoder.end();
80
+ // Strip trailing '\r' safely across buffer boundaries
81
+ if (currentLineDecoded.endsWith("\r")) {
82
+ currentLineDecoded = currentLineDecoded.slice(0, -1);
83
+ }
84
+
85
+ const lineBytes = Buffer.byteLength(currentLineDecoded, "utf8");
86
+ if (accumulatedBytes + lineBytes + (collectedLines.length > 0 ? 1 : 0) > maxBytes) {
87
+ if (collectedLines.length === 0) {
88
+ const clipped = currentLineDecoded.slice(0, Math.max(10, maxBytes - 50)) + "... <line truncated>";
89
+ collectedLines.push(clipped);
90
+ accumulatedBytes = Buffer.byteLength(clipped, "utf8");
91
+ }
92
+ truncatedByBytes = true;
93
+ hasMore = true;
94
+ break;
95
+ }
96
+
97
+ collectedLines.push(currentLineDecoded);
98
+ accumulatedBytes += lineBytes + (collectedLines.length > 1 ? 1 : 0);
99
+ }
100
+
101
+ // Reset state for next line
102
+ currentLineDecoded = "";
103
+ currentLineAccumulatedBytes = 0;
104
+ skippingExcessInLine = false;
105
+ currentLine++;
106
+ lineStart = i + 1;
107
+
108
+ if (currentLine > targetEndLine) {
109
+ hasMore = true;
110
+ break;
111
+ }
112
+ } else {
113
+ // Byte within a line
114
+ if (currentLine >= offset && currentLine <= targetEndLine) {
115
+ if (!skippingExcessInLine) {
116
+ // Hard cap per line to prevent O(N) memory on newline-free files
117
+ if (currentLineAccumulatedBytes + (i - lineStart + 1) > MAX_SINGLE_LINE_BYTES) {
118
+ const safeSlice = buf.subarray(lineStart, i + 1);
119
+ currentLineDecoded += lineDecoder.write(safeSlice);
120
+ currentLineDecoded += lineDecoder.end();
121
+ currentLineDecoded += "... <line truncated: exceeds 50 KB>";
122
+ singleLineTruncated = true;
123
+ skippingExcessInLine = true;
124
+ // Early I/O exit: when line 1 hits the 50 KB budget, stop reading immediately
125
+ if (collectedLines.length === 0) {
126
+ collectedLines.push(currentLineDecoded);
127
+ accumulatedBytes = Buffer.byteLength(currentLineDecoded, "utf8");
128
+ truncatedByBytes = true;
129
+ hasMore = true;
130
+ break;
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+ }
137
+
138
+ if (truncatedByBytes || currentLine > targetEndLine) {
139
+ break;
140
+ }
141
+
142
+ // Incomplete line remaining at end of chunk
143
+ if (lineStart < bytesRead && currentLine >= offset && currentLine <= targetEndLine) {
144
+ if (!skippingExcessInLine) {
145
+ const leftover = buf.subarray(lineStart, bytesRead);
146
+ currentLineDecoded += lineDecoder.write(leftover);
147
+ currentLineAccumulatedBytes += leftover.length;
148
+ if (currentLineAccumulatedBytes > MAX_SINGLE_LINE_BYTES) {
149
+ currentLineDecoded += lineDecoder.end();
150
+ currentLineDecoded += "... <line truncated: exceeds 50 KB>";
151
+ singleLineTruncated = true;
152
+ skippingExcessInLine = true;
153
+ if (collectedLines.length === 0) {
154
+ collectedLines.push(currentLineDecoded);
155
+ accumulatedBytes = Buffer.byteLength(currentLineDecoded, "utf8");
156
+ truncatedByBytes = true;
157
+ hasMore = true;
158
+ break;
159
+ }
160
+ }
161
+ }
162
+ }
163
+ }
164
+
165
+ // Trailing line without trailing newline
166
+ if (!isBinary && !truncatedByBytes && currentLine >= offset && currentLine <= targetEndLine) {
167
+ if (!skippingExcessInLine) {
168
+ currentLineDecoded += lineDecoder.end();
169
+ }
170
+ if (currentLineDecoded.length > 0) {
171
+ if (currentLineDecoded.endsWith("\r")) {
172
+ currentLineDecoded = currentLineDecoded.slice(0, -1);
173
+ }
174
+ const lineBytes = Buffer.byteLength(currentLineDecoded, "utf8");
175
+ if (accumulatedBytes + lineBytes <= maxBytes) {
176
+ collectedLines.push(currentLineDecoded);
177
+ accumulatedBytes += lineBytes;
178
+ } else if (collectedLines.length === 0) {
179
+ const clipped = currentLineDecoded.slice(0, Math.max(10, maxBytes - 50)) + "... <line truncated>";
180
+ collectedLines.push(clipped);
181
+ accumulatedBytes = Buffer.byteLength(clipped, "utf8");
182
+ truncatedByBytes = true;
183
+ hasMore = true;
184
+ } else {
185
+ truncatedByBytes = true;
186
+ hasMore = true;
187
+ }
188
+ }
189
+ }
190
+ } finally {
191
+ lineDecoder.end();
192
+ }
193
+
194
+ const endLine = offset + collectedLines.length - 1;
195
+ return {
196
+ lines: collectedLines,
197
+ startLine: collectedLines.length > 0 ? offset : 0,
198
+ endLine: collectedLines.length > 0 ? endLine : 0,
199
+ totalLinesRead: collectedLines.length,
200
+ hasMore,
201
+ totalBytes: accumulatedBytes,
202
+ truncatedByBytes,
203
+ singleLineTruncated,
204
+ isBinary,
205
+ };
206
+ }
package/src/ui/footer.ts CHANGED
@@ -63,7 +63,7 @@ export const Pastel = {
63
63
  * Format numbers into compact token strings (e.g. 1.2k, 45k, 1.2M)
64
64
  */
65
65
  export function formatTokens(count: number): string {
66
- if (isNaN(count) || count < 0) return "0";
66
+ if (!Number.isFinite(count) || count < 0) return "0";
67
67
  if (count < 1000) return count.toString();
68
68
  if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
69
69
  if (count < 1000000) return `${Math.round(count / 1000)}k`;
@@ -280,12 +280,12 @@ export function renderFooter(
280
280
 
281
281
  // If retrieval is not yet recorded in extension statuses but searchIndex is provided, include it
282
282
  if (searchIndex && !extEntries.some(([key]) => key === "retrieval")) {
283
- const eff =
284
- typeof searchIndex.getEffectiveProfile === "function"
285
- ? searchIndex.getEffectiveProfile()
286
- : typeof searchIndex === "string"
287
- ? searchIndex
288
- : "lean";
283
+ let eff = "lean";
284
+ if (typeof searchIndex.getEffectiveProfile === "function") {
285
+ eff = searchIndex.getEffectiveProfile();
286
+ } else if (typeof searchIndex === "string") {
287
+ eff = searchIndex;
288
+ }
289
289
  if (eff !== "off") {
290
290
  const tag = formatSearchEngineTag(searchIndex, true);
291
291
  extEntries.push(["retrieval", tag]);
package/docs/lsp.md DELETED
@@ -1,31 +0,0 @@
1
- # Language Server Protocol
2
-
3
- LSP support lives under `src/lsp/`. It provides language-server discovery,
4
- client lifecycle management, formatting, diagnostics, and interactive controls.
5
-
6
- ## Components
7
-
8
- - `lsp_registry.ts` describes supported language servers.
9
- - `lsp_detector.ts` detects a file language and workspace root.
10
- - `lsp_client.ts` manages JSON-RPC communication with a server process.
11
- - `lsp_manager.ts` owns client reuse, lifecycle, and status reporting.
12
- - `lsp_formatter.ts` renders diagnostics and navigation results for agents.
13
- - `lsp_installer.ts` handles optional server installation.
14
- - `lsp_modal.ts` provides the interactive server-control UI.
15
-
16
- ## Edit verification
17
-
18
- Post-edit verification only reuses a client that is already ready for the
19
- edited file. It does not start a new server solely to verify an edit. If a
20
- client is unavailable, the result remains explicitly `not run`, `unavailable`,
21
- or otherwise uncertain; it is never presented as `clean`.
22
-
23
- The LSP tool can request diagnostics, definitions, references, hover details,
24
- and document symbols. AST-based fallback behavior is kept in
25
- `src/retrieval/ast_search.ts` for cases where no ready language server can
26
- answer the request.
27
-
28
- ## Output formatting
29
-
30
- - Diagnostics render in token-minimal format (`- [line:col] [SEV] [code] message (source)`) with no redundant `<path>` preamble. Clean files return strictly `<path> clean`.
31
- - References support `exclude_tests` and `exclude_declaration` filters with bounded code window snippets (`windowAround`).
@@ -1,42 +0,0 @@
1
- import type { LspDiagnostic } from "../lsp_types";
2
-
3
- export interface LspAdapter {
4
- readonly languageKey: string;
5
- getInitializationOptions?(rootDir: string): Record<string, any>;
6
- getClientCapabilities?(): Record<string, any>;
7
- handleServerRequest?(method: string, params: any, rootDir: string): any;
8
- transformDiagnostics?(uri: string, diagnostics: LspDiagnostic[]): LspDiagnostic[];
9
- }
10
-
11
- export class BaseLspAdapter implements LspAdapter {
12
- public readonly languageKey: string;
13
-
14
- constructor(languageKey = "generic") {
15
- this.languageKey = languageKey;
16
- }
17
-
18
- public getInitializationOptions(_rootDir: string): Record<string, any> {
19
- return {};
20
- }
21
-
22
- public getClientCapabilities(): Record<string, any> {
23
- return {};
24
- }
25
-
26
- public handleServerRequest(method: string, params: any, rootDir: string): any {
27
- switch (method) {
28
- case "workspace/configuration":
29
- return Array.isArray(params?.items) ? params.items.map(() => null) : [];
30
- case "workspace/workspaceFolders":
31
- return [{ uri: rootDir, name: "workspace" }];
32
- case "workspace/applyEdit":
33
- return { applied: false };
34
- default:
35
- return null;
36
- }
37
- }
38
-
39
- public transformDiagnostics(_uri: string, diagnostics: LspDiagnostic[]): LspDiagnostic[] {
40
- return diagnostics;
41
- }
42
- }
@@ -1,21 +0,0 @@
1
- import type { LspAdapter } from "./base";
2
- import { BaseLspAdapter } from "./base";
3
- import { TypeScriptLspAdapter } from "./typescript";
4
- import { PythonLspAdapter } from "./python";
5
- import { RustLspAdapter } from "./rust";
6
-
7
- export * from "./base";
8
- export * from "./typescript";
9
- export * from "./python";
10
- export * from "./rust";
11
-
12
- const adapters = new Map<string, LspAdapter>([
13
- ["typescript", new TypeScriptLspAdapter()],
14
- ["python", new PythonLspAdapter()],
15
- ["rust", new RustLspAdapter()],
16
- ]);
17
-
18
- export function getLspAdapter(languageKey: string): LspAdapter {
19
- const norm = languageKey.toLowerCase();
20
- return adapters.get(norm) || new BaseLspAdapter(norm);
21
- }
@@ -1,37 +0,0 @@
1
- import { BaseLspAdapter } from "./base";
2
-
3
- export class PythonLspAdapter extends BaseLspAdapter {
4
- constructor() {
5
- super("python");
6
- }
7
-
8
- public override getInitializationOptions(_rootDir: string): Record<string, any> {
9
- return {
10
- analysis: {
11
- autoSearchPaths: true,
12
- useLibraryCodeForTypes: true,
13
- diagnosticMode: "openFilesOnly",
14
- typeCheckingMode: "basic",
15
- },
16
- };
17
- }
18
-
19
- public override handleServerRequest(method: string, params: any, rootDir: string): any {
20
- if (method === "workspace/configuration") {
21
- const items = params?.items || [];
22
- return items.map((item: any) => {
23
- const section = item?.section || "";
24
- if (section.startsWith("python") || section.startsWith("pyright") || section.startsWith("basedpyright")) {
25
- return {
26
- analysis: {
27
- diagnosticMode: "openFilesOnly",
28
- typeCheckingMode: "basic",
29
- },
30
- };
31
- }
32
- return null;
33
- });
34
- }
35
- return super.handleServerRequest(method, params, rootDir);
36
- }
37
- }
@@ -1,35 +0,0 @@
1
- import { BaseLspAdapter } from "./base";
2
-
3
- export class RustLspAdapter extends BaseLspAdapter {
4
- constructor() {
5
- super("rust");
6
- }
7
-
8
- public override getInitializationOptions(_rootDir: string): Record<string, any> {
9
- return {
10
- checkOnSave: true,
11
- diagnostics: {
12
- enable: true,
13
- },
14
- };
15
- }
16
-
17
- public override handleServerRequest(method: string, params: any, rootDir: string): any {
18
- if (method === "workspace/configuration") {
19
- const items = params?.items || [];
20
- return items.map((item: any) => {
21
- const section = item?.section || "";
22
- if (section.startsWith("rust-analyzer") || section === "") {
23
- return {
24
- check: { command: "check" },
25
- checkOnSave: true,
26
- cargo: { buildScripts: { enable: true } },
27
- diagnostics: { enable: true, experimental: { enable: true } },
28
- };
29
- }
30
- return {};
31
- });
32
- }
33
- return super.handleServerRequest(method, params, rootDir);
34
- }
35
- }
@@ -1,40 +0,0 @@
1
- import { BaseLspAdapter } from "./base";
2
- import type { LspDiagnostic } from "../lsp_types";
3
-
4
- export class TypeScriptLspAdapter extends BaseLspAdapter {
5
- constructor() {
6
- super("typescript");
7
- }
8
-
9
- public override getInitializationOptions(_rootDir: string): Record<string, any> {
10
- return {
11
- preferences: {
12
- includeInlayParameterNameHints: "none",
13
- includeInlayVariableTypeHints: false,
14
- includeInlayFunctionParameterTypeHints: false,
15
- },
16
- tsserver: {
17
- log: "off",
18
- maxTsServerMemory: 4096,
19
- },
20
- };
21
- }
22
-
23
- public override handleServerRequest(method: string, params: any, rootDir: string): any {
24
- if (method === "workspace/configuration") {
25
- const items = params?.items || [];
26
- return items.map((item: any) => {
27
- const section = item?.section || "";
28
- if (section.startsWith("typescript") || section.startsWith("javascript") || section.startsWith("vtsls")) {
29
- return {};
30
- }
31
- return null;
32
- });
33
- }
34
- return super.handleServerRequest(method, params, rootDir);
35
- }
36
-
37
- public override transformDiagnostics(_uri: string, diagnostics: LspDiagnostic[]): LspDiagnostic[] {
38
- return diagnostics;
39
- }
40
- }
package/src/lsp/index.ts DELETED
@@ -1,13 +0,0 @@
1
- /**
2
- * Public LSP Module Exports
3
- */
4
-
5
- export * from "./lsp_types";
6
- export * from "./adapters";
7
- export * from "./lsp_registry";
8
- export * from "./lsp_detector";
9
- export * from "./lsp_formatter";
10
- export * from "./lsp_client";
11
- export * from "./lsp_manager";
12
- export * from "./lsp_installer";
13
- export * from "./lsp_modal";