@floydous/pi-agent-kernel 0.3.31 → 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.
@@ -0,0 +1,262 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import ignore, { type Ignore } from "ignore";
4
+
5
+ export const DEFAULT_IGNORED_DIRS = new Set([
6
+ ".git",
7
+ "node_modules",
8
+ ".venv",
9
+ "venv",
10
+ "__pycache__",
11
+ ".pytest_cache",
12
+ "dist",
13
+ "build",
14
+ "coverage",
15
+ ".pi",
16
+ ".hermes",
17
+ ".next",
18
+ ".turbo",
19
+ ".cache",
20
+ "target",
21
+ "vendor",
22
+ "agent-kernel-benchmark",
23
+ ]);
24
+
25
+ export interface IgnoreFrame {
26
+ dirRel: string; // relative to baseRoot with forward slashes (empty string for baseRoot)
27
+ ig: Ignore;
28
+ }
29
+
30
+ /**
31
+ * Finds the enclosing git root containing startDir, if any.
32
+ */
33
+ export function findGitRoot(startDir: string): string | null {
34
+ let curr = path.resolve(startDir);
35
+ while (true) {
36
+ if (fs.existsSync(path.join(curr, ".git"))) {
37
+ return curr;
38
+ }
39
+ const parent = path.dirname(curr);
40
+ if (parent === curr) break;
41
+ curr = parent;
42
+ }
43
+ return null;
44
+ }
45
+
46
+ /**
47
+ * Creates an ignore instance from a file path if the file exists.
48
+ */
49
+ export function loadIgnoreFile(filePath: string): Ignore | null {
50
+ if (!fs.existsSync(filePath)) return null;
51
+ try {
52
+ const content = fs.readFileSync(filePath, "utf-8");
53
+ const ig = typeof ignore === "function" ? ignore() : (ignore as any).default();
54
+ return ig.add(content);
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Checks whether a path (relative to baseRoot, with forward slashes) is ignored
62
+ * according to the stack of IgnoreFrames (evaluated from deepest child to root).
63
+ */
64
+ export function isPathIgnored(stack: IgnoreFrame[], relPath: string, isDirectory: boolean): boolean {
65
+ const targetPath = isDirectory && !relPath.endsWith("/") ? relPath + "/" : relPath;
66
+ for (let i = stack.length - 1; i >= 0; i--) {
67
+ const frame = stack[i];
68
+ let relToFrame = frame.dirRel ? targetPath.slice(frame.dirRel.length + 1) : targetPath;
69
+ if (relToFrame.startsWith("/")) relToFrame = relToFrame.slice(1);
70
+ if (!relToFrame) continue;
71
+
72
+ const res = (frame.ig as any).test(relToFrame);
73
+ if (res.unignored) return false;
74
+ if (res.ignored) return true;
75
+ }
76
+ return false;
77
+ }
78
+
79
+ export interface WalkWorkspaceOptions {
80
+ rootDir: string;
81
+ maxFiles?: number;
82
+ extensions?: Set<string>;
83
+ includeGithub?: boolean;
84
+ onFile?: (filePath: string) => boolean | void;
85
+ }
86
+
87
+ /**
88
+ * Walks workspace directories recursively respecting .gitignore, additive .piignore,
89
+ * and built-in hard exclusions (DEFAULT_IGNORED_DIRS).
90
+ *
91
+ * Safety boundaries:
92
+ * 1. Hard exclusions (DEFAULT_IGNORED_DIRS) cannot be overridden by user negations.
93
+ * 2. Gitignore hierarchy (nested .gitignore overrides parent .gitignore).
94
+ * 3. Additive .piignore (can only add exclusions; cannot un-ignore Git-ignored files).
95
+ * 4. Symlinks & containment: Symbolic links are skipped; traversed directories must remain
96
+ * strictly bounded inside the canonical workspace root.
97
+ * 5. Parent scope inheritance: When rootDir is a subdirectory of a Git repository, parent
98
+ * .gitignore files from gitRoot down to rootDir are discovered and applied in order.
99
+ *
100
+ * Returns absolute paths to matching files.
101
+ */
102
+ export function walkWorkspaceFiles(options: WalkWorkspaceOptions): string[] {
103
+ const rootDir = path.resolve(options.rootDir);
104
+ const maxFiles = options.maxFiles ?? 500;
105
+ const extensions = options.extensions;
106
+ const includeGithub = options.includeGithub ?? true;
107
+ const files: string[] = [];
108
+
109
+ let canonicalRoot: string;
110
+ try {
111
+ canonicalRoot = fs.realpathSync(rootDir);
112
+ } catch {
113
+ canonicalRoot = rootDir;
114
+ }
115
+
116
+ const visitedDirs = new Set<string>();
117
+ visitedDirs.add(canonicalRoot);
118
+
119
+ // Resolve Git base root (to support starting at subdirectories)
120
+ const gitRoot = findGitRoot(rootDir);
121
+ const baseRoot = gitRoot ? path.resolve(gitRoot) : rootDir;
122
+
123
+ // Build initial ignore stacks from baseRoot down to rootDir
124
+ const rootGitFrames: IgnoreFrame[] = [];
125
+ const rootPiFrames: IgnoreFrame[] = [];
126
+
127
+ // Collect directories in the path from baseRoot down to rootDir
128
+ const initialDirs: string[] = [];
129
+ let curr = rootDir;
130
+ while (curr.startsWith(baseRoot)) {
131
+ initialDirs.unshift(curr);
132
+ if (curr === baseRoot) break;
133
+ const parent = path.dirname(curr);
134
+ if (parent === curr) break;
135
+ curr = parent;
136
+ }
137
+
138
+ for (const dir of initialDirs) {
139
+ const dirRel = path.relative(baseRoot, dir).replace(/\\/g, "/");
140
+ const localGit = loadIgnoreFile(path.join(dir, ".gitignore"));
141
+ if (localGit) {
142
+ rootGitFrames.push({ dirRel, ig: localGit });
143
+ }
144
+ const localPi = loadIgnoreFile(path.join(dir, ".piignore"));
145
+ if (localPi) {
146
+ rootPiFrames.push({ dirRel, ig: localPi });
147
+ }
148
+ }
149
+
150
+ function scan(dir: string, gitStack: IgnoreFrame[], piStack: IgnoreFrame[]): boolean {
151
+ if (files.length >= maxFiles) return false;
152
+
153
+ let entries: fs.Dirent[];
154
+ try {
155
+ entries = fs.readdirSync(dir, { withFileTypes: true });
156
+ } catch {
157
+ return true;
158
+ }
159
+
160
+ // Check for local directory .gitignore / .piignore when below rootDir
161
+ const currentGitStack = [...gitStack];
162
+ const currentPiStack = [...piStack];
163
+ const dirRel = path.relative(baseRoot, dir).replace(/\\/g, "/");
164
+
165
+ // If dir is not one of the preloaded initialDirs, load local ignore files
166
+ if (!initialDirs.includes(dir)) {
167
+ const localGitIgnore = loadIgnoreFile(path.join(dir, ".gitignore"));
168
+ if (localGitIgnore) {
169
+ currentGitStack.push({ dirRel, ig: localGitIgnore });
170
+ }
171
+ const localPiIgnore = loadIgnoreFile(path.join(dir, ".piignore"));
172
+ if (localPiIgnore) {
173
+ currentPiStack.push({ dirRel, ig: localPiIgnore });
174
+ }
175
+ }
176
+
177
+ for (const entry of entries) {
178
+ if (files.length >= maxFiles) return false;
179
+
180
+ // Skip symbolic links to prevent circular loops or out-of-tree escapes
181
+ if (entry.isSymbolicLink()) {
182
+ continue;
183
+ }
184
+
185
+ // Handle hidden files/folders: ignore unless .github is explicitly permitted
186
+ if (entry.name.startsWith(".")) {
187
+ if (!includeGithub || entry.name !== ".github") {
188
+ continue;
189
+ }
190
+ }
191
+
192
+ // Built-in hard exclusions (cannot be negated)
193
+ if (DEFAULT_IGNORED_DIRS.has(entry.name)) {
194
+ continue;
195
+ }
196
+
197
+ const fullPath = path.join(dir, entry.name);
198
+ const entryRel = path.relative(baseRoot, fullPath).replace(/\\/g, "/");
199
+
200
+ if (entry.isDirectory()) {
201
+ let realDir: string;
202
+ try {
203
+ realDir = fs.realpathSync(fullPath);
204
+ } catch {
205
+ // Dangling link or permission error; safely skip
206
+ continue;
207
+ }
208
+
209
+ // Symlink & workspace containment guard
210
+ const relToRoot = path.relative(canonicalRoot, realDir);
211
+ if (relToRoot.startsWith("..") || path.isAbsolute(relToRoot)) {
212
+ continue;
213
+ }
214
+
215
+ if (visitedDirs.has(realDir)) {
216
+ continue;
217
+ }
218
+
219
+ // Test directory ignore against .gitignore then .piignore
220
+ if (
221
+ isPathIgnored(currentGitStack, entryRel, true) ||
222
+ isPathIgnored(currentPiStack, entryRel, true)
223
+ ) {
224
+ continue;
225
+ }
226
+
227
+ visitedDirs.add(realDir);
228
+ const shouldContinue = scan(fullPath, currentGitStack, currentPiStack);
229
+ if (!shouldContinue) return false;
230
+ } else if (entry.isFile()) {
231
+ // Extension filtering
232
+ if (extensions) {
233
+ const ext = path.extname(entry.name).toLowerCase();
234
+ if (!extensions.has(ext)) {
235
+ continue;
236
+ }
237
+ }
238
+
239
+ // Check .gitignore first
240
+ if (isPathIgnored(currentGitStack, entryRel, false)) {
241
+ continue;
242
+ }
243
+
244
+ // Check additive .piignore second
245
+ if (isPathIgnored(currentPiStack, entryRel, false)) {
246
+ continue;
247
+ }
248
+
249
+ files.push(fullPath);
250
+ if (options.onFile) {
251
+ const cont = options.onFile(fullPath);
252
+ if (cont === false) return false;
253
+ }
254
+ }
255
+ }
256
+
257
+ return true;
258
+ }
259
+
260
+ scan(rootDir, rootGitFrames, rootPiFrames);
261
+ return files;
262
+ }
@@ -34,7 +34,7 @@ function commandName(token: string): string {
34
34
  return path
35
35
  .basename(token)
36
36
  .toLowerCase()
37
- .replace(/\.exe$/, "");
37
+ .replace(/\.(exe|cmd|bat)$/i, "");
38
38
  }
39
39
 
40
40
  /** Resolve the path forms accepted by Pi's file tools, including ~ paths. */
@@ -130,11 +130,13 @@ export function clampCommandOutput(
130
130
  .map((name) => {
131
131
  const full = path.join(tempDir, name);
132
132
  try {
133
- return { name, full, mtime: fs.statSync(full).mtimeMs };
133
+ const stat = fs.lstatSync(full);
134
+ return { name, full, isFile: stat.isFile() && !stat.isSymbolicLink(), mtime: stat.mtimeMs };
134
135
  } catch {
135
- return { name, full, mtime: 0 };
136
+ return { name, full, isFile: false, mtime: 0 };
136
137
  }
137
138
  })
139
+ .filter((item) => item.isFile)
138
140
  .sort((a, b) => a.mtime - b.mtime);
139
141
 
140
142
  if (files.length > 20) {
@@ -53,7 +53,7 @@ function preflightFileEdit(
53
53
  return { error: `[EDIT ERROR] Missing required 'path' parameter or malformed argument payload.` };
54
54
  }
55
55
  const resolvedPath = resolveUserPath(item.path, ctx.cwd);
56
- const relPath = path.relative(ctx.cwd, resolvedPath) || item.path;
56
+ const relPath = (path.relative(ctx.cwd, resolvedPath) || item.path).replace(/\\/g, "/");
57
57
 
58
58
  if (!fs.existsSync(resolvedPath)) {
59
59
  return { error: `[EDIT FAILED] File not found: '${item.path}'.` };
@@ -423,20 +423,23 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
423
423
 
424
424
  // Multi-file atomic execution
425
425
  if (fileEdits.length > 0) {
426
+ const effectiveCwd = ctx?.cwd || process.cwd();
427
+ const effectiveCtx = ctx || { cwd: effectiveCwd };
426
428
  // Check for duplicate canonical paths
427
429
  const seenPaths = new Set<string>();
428
430
  for (const item of fileEdits) {
429
431
  if (!item || typeof item !== "object" || !item.path) {
430
432
  return { content: [{ type: "text", text: "[EDIT ERROR] Malformed file edit entry." }], isError: true };
431
433
  }
432
- const canonical = resolveUserPath(item.path, ctx.cwd);
433
- if (seenPaths.has(canonical)) {
434
+ const canonical = resolveUserPath(item.path, effectiveCwd);
435
+ const lookupKey = process.platform === "win32" ? canonical.toLowerCase() : canonical;
436
+ if (seenPaths.has(lookupKey)) {
434
437
  return {
435
438
  content: [{ type: "text", text: `[EDIT ERROR] Duplicate target path in multi-file edit: '${item.path}'.` }],
436
439
  isError: true,
437
440
  };
438
441
  }
439
- seenPaths.add(canonical);
442
+ seenPaths.add(lookupKey);
440
443
  }
441
444
 
442
445
  onUpdate?.({
@@ -446,7 +449,7 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
446
449
  // Step 1: Preflight ALL files atomically
447
450
  const preparedList: PreparedFileEdit[] = [];
448
451
  for (const item of fileEdits) {
449
- const preflight = preflightFileEdit(item, ctx, deps, benchmarkMethod);
452
+ const preflight = preflightFileEdit(item, effectiveCtx, deps, benchmarkMethod);
450
453
  if (preflight.error || !preflight.prepared) {
451
454
  return {
452
455
  content: [{ type: "text", text: preflight.error || "[EDIT FAILED] Preflight check failed." }],
@@ -561,11 +564,11 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
561
564
  const fileEdits: string[] = [];
562
565
  if (Array.isArray(args?.files)) {
563
566
  for (const f of args.files) {
564
- if (f?.path) fileEdits.push(path.relative(context.cwd, resolveUserPath(f.path, context.cwd)) || f.path);
567
+ if (f?.path) fileEdits.push((path.relative(context.cwd, resolveUserPath(f.path, context.cwd)) || f.path).replace(/\\/g, "/"));
565
568
  }
566
569
  } else if (Array.isArray(args?.edits) && args.edits.some((e: any) => e?.path)) {
567
570
  for (const e of args.edits) {
568
- if (e?.path) fileEdits.push(path.relative(context.cwd, resolveUserPath(e.path, context.cwd)) || e.path);
571
+ if (e?.path) fileEdits.push((path.relative(context.cwd, resolveUserPath(e.path, context.cwd)) || e.path).replace(/\\/g, "/"));
569
572
  }
570
573
  }
571
574
  if (fileEdits.length > 0) {
@@ -575,7 +578,7 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
575
578
  }
576
579
  const rawPath = args?.path || "";
577
580
  const relPath = rawPath
578
- ? path.relative(context.cwd, rawPath) || rawPath
581
+ ? (path.relative(context.cwd, rawPath) || rawPath).replace(/\\/g, "/")
579
582
  : "";
580
583
  return makeOutputText(
581
584
  `${theme.fg("toolTitle", theme.bold("edit"))} ${theme.fg("accent", relPath)}`,
@@ -519,7 +519,12 @@ export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
519
519
  if (params.exclude_declaration) {
520
520
  res = res.filter((loc) => {
521
521
  const locPath = uriToPath(loc.uri);
522
- const sameFile = locPath === absPath || path.resolve(locPath) === path.resolve(absPath);
522
+ const isWindows = process.platform === "win32";
523
+ const normLoc = path.resolve(locPath);
524
+ const normAbs = path.resolve(absPath);
525
+ const sameFile = isWindows
526
+ ? normLoc.toLowerCase() === normAbs.toLowerCase()
527
+ : normLoc === normAbs;
523
528
  const sameLine = loc.range?.start?.line === line0;
524
529
  return !(sameFile && sameLine);
525
530
  });
@@ -567,7 +572,12 @@ export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
567
572
  let astRefs = findSymbolReferences(ctx.cwd, targetSym);
568
573
  if (params.exclude_declaration) {
569
574
  astRefs = astRefs.filter((r) => {
570
- const sameFile = path.resolve(ctx.cwd, r.filePath) === path.resolve(absPath);
575
+ const isWindows = process.platform === "win32";
576
+ const normRef = path.resolve(ctx.cwd, r.filePath);
577
+ const normAbs = path.resolve(absPath);
578
+ const sameFile = isWindows
579
+ ? normRef.toLowerCase() === normAbs.toLowerCase()
580
+ : normRef === normAbs;
571
581
  return !(sameFile && r.line === (line0 + 1));
572
582
  });
573
583
  }
@@ -190,7 +190,7 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
190
190
  break;
191
191
  }
192
192
  const resolvedPath = resolveUserPath(filePath, ctx.cwd);
193
- const relPath = path.relative(ctx.cwd, resolvedPath) || filePath;
193
+ const relPath = (path.relative(ctx.cwd, resolvedPath) || filePath).replace(/\\/g, "/");
194
194
  if (!fs.existsSync(resolvedPath)) {
195
195
  results.push(`=== file: ${relPath} ===\nFile not found: ${filePath}`);
196
196
  continue;
@@ -359,7 +359,7 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
359
359
  const allFileLines = symbolSnapshot.split("\n");
360
360
  const formatted = res.symbols
361
361
  .map((s) => {
362
- const header = `// ${path.relative(ctx.cwd, s.filePath) || s.filePath}:${s.startLine}-${s.endLine} [${s.kind}] ${s.name}`;
362
+ const header = `// ${(path.relative(ctx.cwd, s.filePath) || s.filePath).replace(/\\/g, "/")}:${s.startLine}-${s.endLine} [${s.kind}] ${s.name}`;
363
363
  const body = useAnchors
364
364
  ? formatSmartAnchorLines(allFileLines, s.startLine, s.endLine)
365
365
  : benchmarkMethod === "line-range"
@@ -563,14 +563,14 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
563
563
  renderCall(args: any, theme: any, context: any) {
564
564
  const targetPaths = Array.isArray(args?.paths) ? args.paths : (Array.isArray(args?.path) ? args.path : []);
565
565
  if (targetPaths.length > 1) {
566
- const pathsSummary = targetPaths.map((p: string) => path.relative(context.cwd, p) || p).join(", ");
566
+ const pathsSummary = targetPaths.map((p: string) => (path.relative(context.cwd, p) || p).replace(/\\/g, "/")).join(", ");
567
567
  return makeOutputText(
568
568
  `${theme.fg("toolTitle", theme.bold("read"))} [${theme.fg("accent", pathsSummary)}]`,
569
569
  );
570
570
  }
571
571
  const rawPath = args?.path || (Array.isArray(args?.paths) ? args.paths[0] : "") || "";
572
572
  const relPath = rawPath
573
- ? path.relative(context.cwd, rawPath) || rawPath
573
+ ? (path.relative(context.cwd, rawPath) || rawPath).replace(/\\/g, "/")
574
574
  : "";
575
575
  if (args?.symbol) {
576
576
  return makeOutputText(