@floydous/pi-agent-kernel 0.3.3 → 0.4.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.
@@ -1,2 +1,3 @@
1
1
  export * from "./toml";
2
2
  export * from "./kernel_config";
3
+ export * from "./agent_kernel_command";
@@ -5,11 +5,8 @@ import { parseToml, stringifyToml, type TomlValue } from "./toml";
5
5
  import { kernelDebug } from "../safety/kernel_debug";
6
6
  import { writeFileSyncAtomic } from "../safety/atomic_write";
7
7
 
8
- export type CodebaseProfile = "auto" | "light" | "heavy";
9
-
10
8
  export interface RetrievalConfig {
11
- default_profile: "lean" | "hybrid" | "full";
12
- codebase_profile: CodebaseProfile;
9
+ default_profile: "auto" | "lean" | "hybrid" | "full" | "off";
13
10
  repo_map_budget: number;
14
11
  repo_map_min_files: number;
15
12
  repo_map_min_bytes: number;
@@ -54,6 +51,7 @@ export interface UiConfig {
54
51
 
55
52
  export interface InstructionsConfig {
56
53
  enabled: boolean;
54
+ pi_docs: boolean;
57
55
  }
58
56
 
59
57
  export interface KernelConfig {
@@ -68,7 +66,6 @@ export interface KernelConfig {
68
66
  const DEFAULT_CONFIG: KernelConfig = {
69
67
  retrieval: {
70
68
  default_profile: "lean",
71
- codebase_profile: "auto",
72
69
  repo_map_budget: 1024,
73
70
  repo_map_min_files: 10,
74
71
  repo_map_min_bytes: 50 * 1024,
@@ -99,6 +96,7 @@ const DEFAULT_CONFIG: KernelConfig = {
99
96
  },
100
97
  instructions: {
101
98
  enabled: true,
99
+ pi_docs: true,
102
100
  },
103
101
  };
104
102
 
@@ -139,9 +137,9 @@ export function getProjectConfigPath(cwd = process.cwd()): string | null {
139
137
 
140
138
  while (current && current !== root) {
141
139
  const candidates = [
140
+ path.join(current, ".pi", "config.toml"),
142
141
  path.join(current, "config.toml"),
143
142
  path.join(current, "agent-kernel", "config.toml"),
144
- path.join(current, ".pi", "config.toml"),
145
143
  ];
146
144
  for (const candidate of candidates) {
147
145
  if (fs.existsSync(candidate)) {
@@ -201,13 +199,6 @@ export function loadKernelConfig(cwd = process.cwd()): KernelConfig {
201
199
  }
202
200
  }
203
201
 
204
- if (process.env.PI_CODEBASE_PROFILE) {
205
- const cp = process.env.PI_CODEBASE_PROFILE.toLowerCase();
206
- if (cp === "auto" || cp === "smart" || cp === "light" || cp === "heavy") {
207
- config.retrieval.codebase_profile = (cp === "smart" ? "auto" : cp) as CodebaseProfile;
208
- }
209
- }
210
-
211
202
  return config;
212
203
  }
213
204
 
@@ -235,9 +226,82 @@ export function saveGlobalKernelConfig(updates: KernelConfigOverrides): void {
235
226
  writeFileSyncAtomic(globalPath, tomlString);
236
227
  }
237
228
 
238
- function mergeDeep(target: any, source: any) {
229
+ /**
230
+ * Remove a single setting key from global configuration file (~/.pi/agent/config.toml)
231
+ */
232
+ export function removeGlobalKernelConfigKey(section: string, key: string): void {
233
+ const globalPath = getGlobalConfigPath();
234
+ if (!fs.existsSync(globalPath)) return;
235
+
236
+ try {
237
+ const existing: any = parseToml(fs.readFileSync(globalPath, "utf-8"));
238
+ if (existing && existing[section] && existing[section][key] !== undefined) {
239
+ delete existing[section][key];
240
+ if (Object.keys(existing[section]).length === 0) {
241
+ delete existing[section];
242
+ }
243
+ const tomlString = stringifyToml(existing);
244
+ writeFileSyncAtomic(globalPath, tomlString);
245
+ }
246
+ } catch (e) {
247
+ kernelDebug(e);
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Read raw global configuration TOML if it exists
253
+ */
254
+ export function getGlobalRawConfig(): Record<string, any> {
255
+ const globalPath = getGlobalConfigPath();
256
+ if (fs.existsSync(globalPath)) {
257
+ try {
258
+ return parseToml(fs.readFileSync(globalPath, "utf-8")) as any;
259
+ } catch (e) {
260
+ kernelDebug(e);
261
+ }
262
+ }
263
+ return {};
264
+ }
265
+
266
+ /**
267
+ * Determine the target path for saving project-local configuration
268
+ */
269
+ export function getTargetProjectConfigPath(cwd = process.cwd()): string {
270
+ const existing = getProjectConfigPath(cwd);
271
+ if (existing) return existing;
272
+ return path.join(path.resolve(cwd), ".pi", "config.toml");
273
+ }
274
+
275
+ /**
276
+ * Save user overrides to project-local configuration file (.pi/config.toml)
277
+ */
278
+ export function saveProjectKernelConfig(cwd: string, updates: KernelConfigOverrides): string {
279
+ const projectPath = getTargetProjectConfigPath(cwd);
280
+ const parentDir = path.dirname(projectPath);
281
+ if (!fs.existsSync(parentDir)) {
282
+ fs.mkdirSync(parentDir, { recursive: true });
283
+ }
284
+
285
+ let existing: Record<string, TomlValue> = {};
286
+ if (fs.existsSync(projectPath)) {
287
+ try {
288
+ existing = parseToml(fs.readFileSync(projectPath, "utf-8"));
289
+ } catch (e) {
290
+ kernelDebug(e);
291
+ }
292
+ }
293
+
294
+ mergeDeep(existing, updates);
295
+ const tomlString = stringifyToml(existing);
296
+ writeFileSyncAtomic(projectPath, tomlString);
297
+ return projectPath;
298
+ }
299
+
300
+ export function mergeDeep(target: any, source: any) {
239
301
  if (!source || typeof source !== "object") return;
240
302
  for (const key of Object.keys(source)) {
303
+ if (key === "__proto__" || key === "prototype" || key === "constructor") continue;
304
+ if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
241
305
  const sVal = source[key];
242
306
  if (sVal && typeof sVal === "object" && !Array.isArray(sVal)) {
243
307
  if (!target[key] || typeof target[key] !== "object") {
@@ -16,8 +16,12 @@ export type TomlValue =
16
16
  | TomlValue[]
17
17
  | { [key: string]: TomlValue };
18
18
 
19
+ function isDangerousKey(key: string): boolean {
20
+ return key === "__proto__" || key === "prototype" || key === "constructor";
21
+ }
22
+
19
23
  export function parseToml(tomlStr: string): Record<string, TomlValue> {
20
- const root: Record<string, TomlValue> = {};
24
+ const root: Record<string, TomlValue> = Object.create(null);
21
25
  let currentTable: Record<string, TomlValue> = root;
22
26
 
23
27
  const lines = tomlStr.split(/\r?\n/);
@@ -33,12 +37,15 @@ export function parseToml(tomlStr: string): Record<string, TomlValue> {
33
37
  // Table header: [table] or [table.sub]
34
38
  if (line.startsWith("[") && line.endsWith("]") && !line.startsWith("[[")) {
35
39
  const tableName = line.slice(1, -1).trim();
36
- const parts = tableName.split(".").map((p) => p.trim());
40
+ const parts = tableName.split(".").map((p) => p.trim().replace(/^["']|["']$/g, ""));
41
+ if (parts.some(isDangerousKey)) {
42
+ continue;
43
+ }
37
44
  let cursor = root;
38
45
  for (const part of parts) {
39
- const existing = cursor[part];
46
+ const existing = Object.prototype.hasOwnProperty.call(cursor, part) ? cursor[part] : undefined;
40
47
  if (!existing || typeof existing !== "object" || Array.isArray(existing)) {
41
- cursor[part] = {};
48
+ cursor[part] = Object.create(null);
42
49
  }
43
50
  cursor = cursor[part] as Record<string, TomlValue>;
44
51
  }
@@ -51,6 +58,10 @@ export function parseToml(tomlStr: string): Record<string, TomlValue> {
51
58
  if (eqIndex === -1) continue;
52
59
 
53
60
  const key = line.slice(0, eqIndex).trim();
61
+ const cleanKey = key.replace(/^["']|["']$/g, "").trim();
62
+ if (isDangerousKey(cleanKey) || cleanKey.split(".").some(isDangerousKey)) {
63
+ continue;
64
+ }
54
65
  let rawValue = line.slice(eqIndex + 1).trim();
55
66
 
56
67
  // Handle multi-line arrays if open bracket without close bracket
@@ -2,6 +2,10 @@ import * as fs from "fs";
2
2
  import * as path from "path";
3
3
  import * as os from "os";
4
4
  import { getPiHomeDir } from "../config";
5
+ import { writeFileSyncAtomic } from "../safety/atomic_write";
6
+
7
+ const MAX_SESSION_FILE_SIZE = 10 * 1024 * 1024; // 10MB
8
+ const MAX_SESSIONS_SCANNED = 20;
5
9
 
6
10
  /**
7
11
  * Sanitizes and repairs session JSONL files in ~/.pi/agent/sessions/
@@ -21,18 +25,32 @@ export function sanitizeSessionFiles(agentDir?: string): { repairedFiles: number
21
25
  return { repairedFiles: 0, repairedEntries: 0 };
22
26
  }
23
27
 
24
- const sessionFolders = fs.readdirSync(sessionsDir);
25
-
26
- for (const folder of sessionFolders) {
27
- const folderPath = path.join(sessionsDir, folder);
28
- if (!fs.statSync(folderPath).isDirectory()) continue;
28
+ const sessionFolders = fs.readdirSync(sessionsDir)
29
+ .map((folder) => {
30
+ const folderPath = path.join(sessionsDir, folder);
31
+ try {
32
+ const stat = fs.lstatSync(folderPath);
33
+ return { folder, folderPath, isDir: stat.isDirectory() && !stat.isSymbolicLink(), mtime: stat.mtimeMs };
34
+ } catch {
35
+ return { folder, folderPath, isDir: false, mtime: 0 };
36
+ }
37
+ })
38
+ .filter((f) => f.isDir)
39
+ .sort((a, b) => b.mtime - a.mtime)
40
+ .slice(0, MAX_SESSIONS_SCANNED);
29
41
 
42
+ for (const { folderPath } of sessionFolders) {
30
43
  const files = fs.readdirSync(folderPath);
31
44
  for (const file of files) {
32
45
  if (!file.endsWith(".jsonl")) continue;
33
46
 
34
47
  const filePath = path.join(folderPath, file);
35
48
  try {
49
+ const stat = fs.lstatSync(filePath);
50
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_SESSION_FILE_SIZE) {
51
+ continue;
52
+ }
53
+
36
54
  const content = fs.readFileSync(filePath, "utf8");
37
55
  const lines = content.split("\n");
38
56
  let fileModified = false;
@@ -83,7 +101,7 @@ export function sanitizeSessionFiles(agentDir?: string): { repairedFiles: number
83
101
  });
84
102
 
85
103
  if (fileModified) {
86
- fs.writeFileSync(filePath, repairedLines.join("\n"), "utf8");
104
+ writeFileSyncAtomic(filePath, repairedLines.join("\n"));
87
105
  repairedFiles++;
88
106
  }
89
107
  } catch (err) {
@@ -346,7 +346,10 @@ export function applySmartAnchorEdits(
346
346
  };
347
347
  }
348
348
 
349
- const preflight = preflightSmartAnchorEdits(originalContent, edits);
349
+ const hadCrlf = originalContent.includes("\r\n");
350
+ const contentNorm = originalContent.replace(/\r\n/g, "\n");
351
+
352
+ const preflight = preflightSmartAnchorEdits(contentNorm, edits);
350
353
  if (!preflight.success || !preflight.resolvedSpans) {
351
354
  return {
352
355
  success: false,
@@ -356,7 +359,7 @@ export function applySmartAnchorEdits(
356
359
  };
357
360
  }
358
361
 
359
- const fileLines = originalContent.split("\n");
362
+ const fileLines = contentNorm.split("\n");
360
363
  const currentLines = [...fileLines];
361
364
 
362
365
  // Sort spans strictly bottom-to-top (descending line number) so edits do not shift earlier lines
@@ -364,10 +367,16 @@ export function applySmartAnchorEdits(
364
367
 
365
368
  for (const span of sortedSpans) {
366
369
  const deleteCount = span.endLine - span.startLine + 1;
367
- currentLines.splice(span.startLine - 1, deleteCount, ...span.replacementLines);
370
+ const cleanReplacementLines = span.replacementLines.flatMap((line) =>
371
+ line.replace(/\r\n/g, "\n").split("\n"),
372
+ );
373
+ currentLines.splice(span.startLine - 1, deleteCount, ...cleanReplacementLines);
368
374
  }
369
375
 
370
- const candidateContent = currentLines.join("\n");
376
+ const candidateContentNorm = currentLines.join("\n");
377
+ const candidateContent = hadCrlf
378
+ ? candidateContentNorm.replace(/\n/g, "\r\n")
379
+ : candidateContentNorm;
371
380
 
372
381
  // Syntax validation gate
373
382
  const syntax = checkSyntaxContent(resolvedPath, candidateContent);
@@ -404,10 +413,10 @@ export function applySmartAnchorEdits(
404
413
  // Unified diff output
405
414
  const diffOutput = diff.createPatch(
406
415
  resolvedPath,
407
- originalContent,
408
- candidateContent,
416
+ contentNorm,
417
+ candidateContentNorm,
409
418
  "original",
410
- "modified",
419
+ "updated",
411
420
  );
412
421
 
413
422
  return {
@@ -52,7 +52,7 @@ function regexCanStart(prevSig: string, lastWord: string): boolean {
52
52
  }
53
53
 
54
54
  function checkTsStructure(content: string): string | null {
55
- const stack: { ch: string; line: number }[] = [];
55
+ const stack: { ch: string; line: number; isTemplateInterp?: boolean }[] = [];
56
56
  let line = 1;
57
57
  let i = 0;
58
58
  // State machine over raw source: code | 'str' | "str" | `tpl` | //line | /*block */ | /regex/
@@ -106,11 +106,15 @@ function checkTsStructure(content: string): string | null {
106
106
  else if (ch === '"') state = "code";
107
107
  break;
108
108
  case "template":
109
- if (ch === "\\") i++;
110
- else if (ch === "`") state = "code";
111
- // NOTE: ${...} interpolations are tracked as part of the template
112
- // body; braces inside them are balanced by JS itself, and any
113
- // imbalance surfaces as an unbalanced delimiter anyway.
109
+ if (ch === "\\") {
110
+ i++;
111
+ } else if (ch === "$" && next === "{") {
112
+ stack.push({ ch: "{", line, isTemplateInterp: true });
113
+ state = "code";
114
+ i++;
115
+ } else if (ch === "`") {
116
+ state = "code";
117
+ }
114
118
  break;
115
119
  case "code":
116
120
  if (ch === "/" && next === "/") {
@@ -144,6 +148,9 @@ function checkTsStructure(content: string): string | null {
144
148
  if (!top || top.ch !== closers[ch]) {
145
149
  return `Unbalanced '${ch}' on line ${line}${top ? ` (unclosed '${top.ch}' from line ${top.line})` : " (no matching opener)"}`;
146
150
  }
151
+ if (top.isTemplateInterp) {
152
+ state = "template";
153
+ }
147
154
  }
148
155
  if (!/\s/.test(ch)) prevSig = ch;
149
156
  // Accumulate identifier/number tokens; whitespace preserves the
@@ -167,9 +174,12 @@ function checkTsStructure(content: string): string | null {
167
174
  i++;
168
175
  }
169
176
 
170
- if (state === "squote" || state === "dquote" || state === "template") {
177
+ if (state === "squote" || state === "dquote") {
171
178
  return `Unterminated string literal (reached end of file, last line ${line})`;
172
179
  }
180
+ if (state === "template") {
181
+ return `Unterminated template literal (reached end of file, last line ${line})`;
182
+ }
173
183
  if (state === "blockComment") {
174
184
  return `Unterminated block comment (last line ${line})`;
175
185
  }