@floydous/pi-agent-kernel 0.3.31 → 0.4.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 (40) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +6 -4
  2. package/CHANGELOG.md +35 -4
  3. package/README.md +39 -74
  4. package/config.example.toml +36 -0
  5. package/docs/configuration.md +11 -3
  6. package/docs/retrieval.md +17 -1
  7. package/docs/testing.md +5 -3
  8. package/package.json +9 -7
  9. package/src/config/agent_kernel_command.ts +91 -91
  10. package/src/config/kernel_config.ts +179 -43
  11. package/src/config/toml.ts +15 -4
  12. package/src/context/session_repair.ts +179 -80
  13. package/src/editing/patch.ts +28 -16
  14. package/src/editing/smart_anchor.ts +29 -36
  15. package/src/editing/syntax-verify.ts +52 -18
  16. package/src/index.ts +257 -219
  17. package/src/lsp/lsp_client.ts +138 -23
  18. package/src/lsp/lsp_formatter.ts +61 -24
  19. package/src/lsp/lsp_installer.ts +277 -561
  20. package/src/lsp/lsp_manager.ts +1 -1
  21. package/src/lsp/lsp_registry.ts +110 -73
  22. package/src/retrieval/ast_search.ts +136 -172
  23. package/src/retrieval/repomap.ts +8 -47
  24. package/src/retrieval/search_bm25.ts +5 -2
  25. package/src/retrieval/search_cache.ts +69 -0
  26. package/src/retrieval/search_chunker.ts +21 -43
  27. package/src/retrieval/search_config.ts +75 -18
  28. package/src/retrieval/search_embedder.ts +8 -16
  29. package/src/retrieval/search_index.ts +923 -123
  30. package/src/retrieval/workspace_walker.ts +262 -0
  31. package/src/safety/atomic_write.ts +59 -20
  32. package/src/safety/epistemic_guard.ts +163 -43
  33. package/src/safety/output_clamper.ts +316 -74
  34. package/src/tools/code_search_output.ts +59 -23
  35. package/src/tools/code_search_tool.ts +42 -46
  36. package/src/tools/context.ts +15 -1
  37. package/src/tools/edit_tool.ts +124 -43
  38. package/src/tools/lsp_tool.ts +17 -4
  39. package/src/tools/read_tool.ts +48 -7
  40. package/config.toml +0 -31
@@ -1,4 +1,5 @@
1
- import { spawn, type ChildProcess } from "node:child_process";
1
+ import crossSpawn from "cross-spawn";
2
+ import { type ChildProcess } from "node:child_process";
2
3
  import * as fs from "node:fs";
3
4
  import * as path from "node:path";
4
5
  import {
@@ -16,6 +17,60 @@ import { getLspAdapter, type LspAdapter } from "./adapters";
16
17
  import { kernelDebug } from "../safety/kernel_debug";
17
18
  import { loadKernelConfig } from "../config";
18
19
 
20
+ const LSP_ENV_ALLOWLIST = new Set([
21
+ "path",
22
+ "pathext",
23
+ "home",
24
+ "userprofile",
25
+ "homedrive",
26
+ "homepath",
27
+ "temp",
28
+ "tmp",
29
+ "tmpdir",
30
+ "systemroot",
31
+ "windir",
32
+ "comspec",
33
+ "appdata",
34
+ "localappdata",
35
+ "programdata",
36
+ "programfiles",
37
+ "programfiles(x86)",
38
+ "lang",
39
+ "lc_all",
40
+ "java_home",
41
+ "jdk_home",
42
+ "goroot",
43
+ "gopath",
44
+ "cargo_home",
45
+ "rustup_home",
46
+ "pythonhome",
47
+ "pythonpath",
48
+ "virtual_env",
49
+ "node_path",
50
+ "ld_library_path",
51
+ ]);
52
+
53
+ export function buildLspEnvironment(
54
+ overrides: Record<string, string> = {},
55
+ ): Record<string, string> {
56
+ const source = new Map<string, { key: string; value: string }>();
57
+ for (const [key, value] of Object.entries(process.env)) {
58
+ if (typeof value === "string") source.set(key.toLowerCase(), { key, value });
59
+ }
60
+ const result: Record<string, string> = {};
61
+ for (const [lowerKey, entry] of source) {
62
+ if (LSP_ENV_ALLOWLIST.has(lowerKey)) result[entry.key] = entry.value;
63
+ }
64
+ for (const [key, value] of Object.entries(overrides)) {
65
+ if (LSP_ENV_ALLOWLIST.has(key.toLowerCase())) result[key] = value;
66
+ }
67
+ return result;
68
+ }
69
+
70
+ export const MAX_LSP_STDERR_BYTES = 64 * 1024;
71
+ export const MAX_LSP_DOCUMENT_BYTES = 5 * 1024 * 1024;
72
+ export const MAX_LSP_DIAGNOSTICS = 200;
73
+
19
74
  export interface StdioLspClientOptions {
20
75
  command: string;
21
76
  args: string[];
@@ -50,6 +105,9 @@ export class StdioLspClient {
50
105
  private openDocuments = new Map<string, { version: number; text: string }>();
51
106
  private lastActivityTime = Date.now();
52
107
  private serverCapabilities: any = {};
108
+ private static readonly MAX_HEADER_SIZE = 8192;
109
+ private static readonly MAX_BUFFER_SIZE = 50 * 1024 * 1024;
110
+ private static readonly MAX_CONTENT_LENGTH = 25 * 1024 * 1024;
53
111
 
54
112
  constructor(id: string, options: StdioLspClientOptions) {
55
113
  this.id = id;
@@ -81,11 +139,12 @@ export class StdioLspClient {
81
139
  this.touch();
82
140
 
83
141
  try {
84
- this.process = spawn(this.options.command, this.options.args, {
142
+ this.process = crossSpawn(this.options.command, this.options.args, {
85
143
  cwd: this.rootDir,
86
- env: { ...process.env, ...this.options.env },
144
+ env: buildLspEnvironment(this.options.env),
87
145
  stdio: ["pipe", "pipe", "pipe"],
88
- shell: process.platform === "win32",
146
+ shell: false,
147
+ windowsHide: true,
89
148
  });
90
149
 
91
150
  this.process.stdout?.on("data", (chunk: Buffer) => {
@@ -94,7 +153,9 @@ export class StdioLspClient {
94
153
 
95
154
  let serverStderr = "";
96
155
  this.process.stderr?.on("data", (chunk: Buffer) => {
97
- serverStderr += chunk.toString("utf8");
156
+ if (serverStderr.length < MAX_LSP_STDERR_BYTES) {
157
+ serverStderr = `${serverStderr}${chunk.toString("utf8")}`.slice(0, MAX_LSP_STDERR_BYTES);
158
+ }
98
159
  });
99
160
 
100
161
  this.process.on("error", (err) => {
@@ -181,21 +242,52 @@ export class StdioLspClient {
181
242
  this.touch();
182
243
  this.buffer = Buffer.concat([this.buffer, chunk]);
183
244
 
245
+ if (this.buffer.length > StdioLspClient.MAX_BUFFER_SIZE) {
246
+ kernelDebug(new Error("LSP client buffer exceeded maximum allowed size. Clearing buffer."));
247
+ this.buffer = Buffer.alloc(0);
248
+ return;
249
+ }
250
+
184
251
  while (true) {
252
+ // Resynchronize if buffer has leading garbage before Content-Length
253
+ const clIndex = this.buffer.indexOf("Content-Length:");
254
+ const lowerClIndex = clIndex === -1 ? this.buffer.indexOf("content-length:") : clIndex;
255
+ if (lowerClIndex > 0) {
256
+ this.buffer = this.buffer.subarray(lowerClIndex);
257
+ }
258
+
185
259
  const headerEndIndex = this.buffer.indexOf("\r\n\r\n");
186
- if (headerEndIndex === -1) break;
260
+ if (headerEndIndex === -1) {
261
+ if (this.buffer.length > StdioLspClient.MAX_HEADER_SIZE) {
262
+ kernelDebug(new Error("LSP header exceeds max allowable size without delimiter. Discarding corrupt stream."));
263
+ this.buffer = Buffer.alloc(0);
264
+ }
265
+ break;
266
+ }
187
267
 
188
268
  const headerText = this.buffer
189
269
  .subarray(0, headerEndIndex)
190
270
  .toString("utf8");
191
- const match = /Content-Length:\s*(\d+)/i.exec(headerText);
271
+ const match = /(?:^|\r?\n)Content-Length:\s*(\d+)\s*(?:\r?\n|$)/i.exec(headerText);
192
272
  if (!match) {
193
273
  // Corrupted header, skip past \r\n\r\n
194
274
  this.buffer = this.buffer.subarray(headerEndIndex + 4);
195
275
  continue;
196
276
  }
197
277
 
198
- const contentLength = parseInt(match[1], 10);
278
+ const contentLengthStr = match[1];
279
+ const contentLength = Number(contentLengthStr);
280
+
281
+ if (
282
+ !Number.isSafeInteger(contentLength) ||
283
+ contentLength < 0 ||
284
+ contentLength > StdioLspClient.MAX_CONTENT_LENGTH
285
+ ) {
286
+ kernelDebug(new Error(`Invalid or oversized LSP Content-Length: ${contentLengthStr}`));
287
+ this.buffer = Buffer.alloc(0);
288
+ break;
289
+ }
290
+
199
291
  const bodyStartIndex = headerEndIndex + 4;
200
292
  const totalMessageLength = bodyStartIndex + contentLength;
201
293
 
@@ -287,6 +379,9 @@ export class StdioLspClient {
287
379
  if (notif.method === "textDocument/publishDiagnostics") {
288
380
  const rawUri = notif.params?.uri;
289
381
  let diagnostics = notif.params?.diagnostics || [];
382
+ if (diagnostics.length > MAX_LSP_DIAGNOSTICS) {
383
+ diagnostics = diagnostics.slice(0, MAX_LSP_DIAGNOSTICS);
384
+ }
290
385
  if (rawUri) {
291
386
  const uri = normalizeUri(rawUri);
292
387
  if (this.adapter.transformDiagnostics) {
@@ -372,12 +467,14 @@ export class StdioLspClient {
372
467
  */
373
468
  public async openDocument(filePath: string, content?: string): Promise<void> {
374
469
  const uri = pathToUri(filePath);
375
- const text =
376
- content === undefined
377
- ? fs.existsSync(filePath)
378
- ? fs.readFileSync(filePath, "utf8")
379
- : ""
380
- : content;
470
+ const fileStat = fs.statSync(filePath);
471
+ if (!fileStat.isFile() || fileStat.size > MAX_LSP_DOCUMENT_BYTES) {
472
+ throw new Error(`LSP document exceeds the ${MAX_LSP_DOCUMENT_BYTES}-byte limit`);
473
+ }
474
+ const text = content === undefined ? fs.readFileSync(filePath, "utf8") : content;
475
+ if (Buffer.byteLength(text, "utf8") > MAX_LSP_DOCUMENT_BYTES) {
476
+ throw new Error(`LSP document exceeds the ${MAX_LSP_DOCUMENT_BYTES}-byte limit`);
477
+ }
381
478
 
382
479
  if (this.openDocuments.has(uri)) {
383
480
  const existing = this.openDocuments.get(uri);
@@ -618,18 +715,36 @@ export class StdioLspClient {
618
715
  * Graceful shutdown and termination
619
716
  */
620
717
  public async stop(): Promise<void> {
621
- if (this.state === "stopped") return;
718
+ if (this.state === "stopped" && !this.process) return;
622
719
  this.state = "shutting_down";
720
+ const child = this.process;
623
721
 
624
722
  try {
625
- if (this.process && !this.process.killed) {
626
- await Promise.race([
627
- this.sendRequest("shutdown", undefined, 1000).then(() => {
628
- this.sendNotification("exit");
629
- }),
630
- new Promise((r) => setTimeout(r, 1000)),
631
- ]);
632
- this.process.kill();
723
+ if (child) {
724
+ const exited = new Promise<void>((resolve) => {
725
+ child.once("exit", () => resolve());
726
+ child.once("error", () => resolve());
727
+ });
728
+ try {
729
+ await Promise.race([
730
+ this.sendRequest("shutdown", undefined, 1000).then(() => {
731
+ this.sendNotification("exit");
732
+ }),
733
+ new Promise((resolve) => setTimeout(resolve, 1000)),
734
+ ]);
735
+ } catch (error) {
736
+ kernelDebug(error);
737
+ }
738
+
739
+ await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 250))]);
740
+ if (child.exitCode === null && child.signalCode === null && !child.killed) {
741
+ child.kill();
742
+ }
743
+ await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 2000))]);
744
+ if (child.exitCode === null && child.signalCode === null) {
745
+ child.kill("SIGKILL");
746
+ await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 1000))]);
747
+ }
633
748
  }
634
749
  } catch (e) {
635
750
  kernelDebug(e);
@@ -66,6 +66,19 @@ function severityLabel(severity?: LspDiagnosticSeverity): string {
66
66
  }
67
67
  }
68
68
 
69
+ const MAX_DEFINITIONS = 200;
70
+ const MAX_REFERENCES = 200;
71
+ const MAX_REFERENCE_FILE_BYTES = 1024 * 1024;
72
+ const MAX_SYMBOLS = 100;
73
+ const MAX_SYMBOL_DEPTH = 10;
74
+ const MAX_HOVER_CHARS = 32 * 1024;
75
+ const MAX_DIAGNOSTIC_MESSAGE_CHARS = 2 * 1024;
76
+
77
+ function clipText(value: unknown, limit: number): string {
78
+ const text = String(value ?? "");
79
+ return text.length > limit ? `${text.slice(0, limit)}…` : text;
80
+ }
81
+
69
82
  /**
70
83
  * Symbol kind name lookup
71
84
  */
@@ -85,15 +98,17 @@ export function formatDiagnostics(
85
98
  return "";
86
99
  }
87
100
 
88
- const lines: string[] = [];
89
-
90
- for (const d of diagnostics) {
101
+ const visible = diagnostics.slice(0, 200);
102
+ const lines = visible.map((d) => {
91
103
  const sev = severityLabel(d.severity);
92
104
  const line = d.range.start.line + 1; // Convert 0-indexed to 1-indexed
93
105
  const col = d.range.start.character + 1;
94
106
  const codeStr = d.code !== undefined ? ` [${d.code}]` : "";
95
107
  const srcStr = d.source ? ` (${d.source})` : "";
96
- lines.push(`- [${line}:${col}] [${sev}]${codeStr} ${d.message}${srcStr}`);
108
+ return `- [${line}:${col}] [${sev}]${codeStr} ${clipText(d.message, MAX_DIAGNOSTIC_MESSAGE_CHARS)}${srcStr}`;
109
+ });
110
+ if (diagnostics.length > visible.length) {
111
+ lines.push(`[Truncated: ${visible.length}/${diagnostics.length} diagnostics]`);
97
112
  }
98
113
 
99
114
  return lines.join("\n");
@@ -131,13 +146,18 @@ export function formatDefinitions(
131
146
  return "Definition not found.";
132
147
  }
133
148
 
134
- const lines = locations.map((loc) => {
149
+ const visible = locations.slice(0, MAX_DEFINITIONS);
150
+ const lines = visible.map((loc) => {
135
151
  const filePath = uriToPath(loc.uri);
136
- const displayPath = cwd ? path.relative(cwd, filePath) || filePath : filePath;
152
+ const rawDisplay = cwd ? path.relative(cwd, filePath) || filePath : filePath;
153
+ const displayPath = rawDisplay.replace(/\\/g, "/");
137
154
  const line = loc.range.start.line + 1;
138
155
  const col = loc.range.start.character + 1;
139
156
  return `${displayPath}:${line}:${col}`;
140
157
  });
158
+ if (locations.length > visible.length) {
159
+ lines.push(`[Truncated: ${visible.length}/${locations.length} definitions]`);
160
+ }
141
161
 
142
162
  return lines.join("\n");
143
163
  }
@@ -155,11 +175,11 @@ export function windowAround(
155
175
  const s = Math.max(0, Math.min(startCol0, normLine.length));
156
176
  const e = Math.max(s, Math.min(endCol0, normLine.length));
157
177
  const symLen = Math.max(1, e - s);
158
- const effectiveBudget = Math.max(budget, symLen);
178
+ const effectiveBudget = Math.min(4096, Math.max(budget, symLen));
159
179
  const pad = Math.max(0, effectiveBudget - symLen);
160
180
  const left = Math.max(0, s - Math.floor(pad / 2));
161
181
  const right = Math.min(normLine.length, e + Math.ceil(pad / 2));
162
- const snippet = normLine.slice(left, right).trim();
182
+ const snippet = normLine.slice(left, right).trim().slice(0, 4096);
163
183
  const prefix = left > 0 ? "... " : "";
164
184
  const suffix = right < normLine.length ? " ..." : "";
165
185
  return `${prefix}${snippet}${suffix}`.trim();
@@ -186,9 +206,12 @@ export function formatReferences(
186
206
  }
187
207
  try {
188
208
  if (fs.existsSync(filePath)) {
189
- const lines = fs.readFileSync(filePath, "utf8").split("\n");
190
- fileLinesCache.set(filePath, lines);
191
- return lines;
209
+ const stat = fs.statSync(filePath);
210
+ if (stat.isFile() && stat.size <= MAX_REFERENCE_FILE_BYTES) {
211
+ const lines = fs.readFileSync(filePath, "utf8").split("\n");
212
+ fileLinesCache.set(filePath, lines);
213
+ return lines;
214
+ }
192
215
  }
193
216
  } catch {
194
217
  // Fall through to null for inaccessible/virtual files
@@ -197,9 +220,11 @@ export function formatReferences(
197
220
  return null;
198
221
  };
199
222
 
200
- const lines = references.map((loc) => {
223
+ const visible = references.slice(0, MAX_REFERENCES);
224
+ const lines = visible.map((loc) => {
201
225
  const filePath = uriToPath(loc.uri);
202
- const displayPath = cwd ? path.relative(cwd, filePath) || filePath : filePath;
226
+ const rawDisplay = cwd ? path.relative(cwd, filePath) || filePath : filePath;
227
+ const displayPath = rawDisplay.replace(/\\/g, "/");
203
228
  const line1 = loc.range.start.line + 1;
204
229
  const col1 = loc.range.start.character + 1;
205
230
  const baseLoc = `${displayPath}:${line1}:${col1}`;
@@ -219,7 +244,9 @@ export function formatReferences(
219
244
  const snippet = windowAround(rawLine, startCol0, endCol0, 50);
220
245
  return snippet ? `${baseLoc}: ${snippet}` : baseLoc;
221
246
  });
222
-
247
+ if (references.length > visible.length) {
248
+ lines.push(`[Truncated: ${visible.length}/${references.length} references]`);
249
+ }
223
250
  return lines.join("\n");
224
251
  }
225
252
 
@@ -243,7 +270,10 @@ export function formatHover(hover: LspHover | null | undefined): string {
243
270
  const rawText = extractText(hover.contents).trim();
244
271
  // Strip transient LSP loading state markers (e.g. tsserver / vtsls prefixing "(loading...) ")
245
272
  const cleanText = rawText.replace(/\(loading\.\.\.\)\s*/g, "").trim();
246
- return cleanText || "No hover information available.";
273
+ if (!cleanText) return "No hover information available at this position.";
274
+ return cleanText.length > MAX_HOVER_CHARS
275
+ ? `${cleanText.slice(0, MAX_HOVER_CHARS)}\n[Hover truncated]`
276
+ : cleanText;
247
277
  }
248
278
 
249
279
  /**
@@ -257,30 +287,37 @@ export function formatDocumentSymbols(
257
287
  }
258
288
 
259
289
  const lines: string[] = [];
290
+ let emitted = 0;
291
+ let truncated = false;
260
292
 
261
293
  const renderSymbol = (s: any, depth = 0) => {
294
+ if (emitted >= MAX_SYMBOLS || depth > MAX_SYMBOL_DEPTH) {
295
+ truncated = true;
296
+ return;
297
+ }
262
298
  const indent = " ".repeat(depth);
263
299
  const kind = symbolKindLabel(s.kind);
264
300
  const range = s.range || s.location?.range;
265
301
  const line = range ? range.start.line + 1 : 1;
266
- const detail = s.detail ? ` (${s.detail})` : "";
267
- lines.push(`${indent}${line}: [${kind}] ${s.name}${detail}`);
302
+ const detail = s.detail ? ` (${clipText(s.detail, 500)})` : "";
303
+ lines.push(`${indent}${line}: [${kind}] ${clipText(s.name, 200)}${detail}`);
304
+ emitted++;
268
305
 
269
306
  if (s.children && Array.isArray(s.children)) {
270
- for (const child of s.children) {
271
- renderSymbol(child, depth + 1);
272
- }
307
+ for (const child of s.children) renderSymbol(child, depth + 1);
273
308
  }
274
309
  };
275
310
 
276
311
  for (const s of symbols) {
312
+ if (emitted >= MAX_SYMBOLS) {
313
+ truncated = true;
314
+ break;
315
+ }
277
316
  renderSymbol(s, 0);
278
317
  }
279
318
 
280
- // Bounded output to prevent blowing context window on monolithic files
281
- if (lines.length > 100) {
282
- return lines.slice(0, 100).join("\n") + `\n\n[Truncated: 100/${lines.length} symbols shown]`;
319
+ if (truncated) {
320
+ lines.push(`[Truncated: ${emitted}/${symbols.length} symbols shown]`);
283
321
  }
284
-
285
322
  return lines.join("\n");
286
323
  }