@floydous/pi-agent-kernel 0.3.2 → 0.3.31

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";
@@ -54,6 +54,7 @@ export interface UiConfig {
54
54
 
55
55
  export interface InstructionsConfig {
56
56
  enabled: boolean;
57
+ pi_docs: boolean;
57
58
  }
58
59
 
59
60
  export interface KernelConfig {
@@ -99,6 +100,7 @@ const DEFAULT_CONFIG: KernelConfig = {
99
100
  },
100
101
  instructions: {
101
102
  enabled: true,
103
+ pi_docs: true,
102
104
  },
103
105
  };
104
106
 
@@ -235,6 +237,77 @@ export function saveGlobalKernelConfig(updates: KernelConfigOverrides): void {
235
237
  writeFileSyncAtomic(globalPath, tomlString);
236
238
  }
237
239
 
240
+ /**
241
+ * Remove a single setting key from global configuration file (~/.pi/agent/config.toml)
242
+ */
243
+ export function removeGlobalKernelConfigKey(section: string, key: string): void {
244
+ const globalPath = getGlobalConfigPath();
245
+ if (!fs.existsSync(globalPath)) return;
246
+
247
+ try {
248
+ const existing: any = parseToml(fs.readFileSync(globalPath, "utf-8"));
249
+ if (existing && existing[section] && existing[section][key] !== undefined) {
250
+ delete existing[section][key];
251
+ if (Object.keys(existing[section]).length === 0) {
252
+ delete existing[section];
253
+ }
254
+ const tomlString = stringifyToml(existing);
255
+ writeFileSyncAtomic(globalPath, tomlString);
256
+ }
257
+ } catch (e) {
258
+ kernelDebug(e);
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Read raw global configuration TOML if it exists
264
+ */
265
+ export function getGlobalRawConfig(): Record<string, any> {
266
+ const globalPath = getGlobalConfigPath();
267
+ if (fs.existsSync(globalPath)) {
268
+ try {
269
+ return parseToml(fs.readFileSync(globalPath, "utf-8")) as any;
270
+ } catch (e) {
271
+ kernelDebug(e);
272
+ }
273
+ }
274
+ return {};
275
+ }
276
+
277
+ /**
278
+ * Determine the target path for saving project-local configuration
279
+ */
280
+ export function getTargetProjectConfigPath(cwd = process.cwd()): string {
281
+ const existing = getProjectConfigPath(cwd);
282
+ if (existing) return existing;
283
+ return path.join(path.resolve(cwd), ".pi", "config.toml");
284
+ }
285
+
286
+ /**
287
+ * Save user overrides to project-local configuration file (.pi/config.toml)
288
+ */
289
+ export function saveProjectKernelConfig(cwd: string, updates: KernelConfigOverrides): string {
290
+ const projectPath = getTargetProjectConfigPath(cwd);
291
+ const parentDir = path.dirname(projectPath);
292
+ if (!fs.existsSync(parentDir)) {
293
+ fs.mkdirSync(parentDir, { recursive: true });
294
+ }
295
+
296
+ let existing: Record<string, TomlValue> = {};
297
+ if (fs.existsSync(projectPath)) {
298
+ try {
299
+ existing = parseToml(fs.readFileSync(projectPath, "utf-8"));
300
+ } catch (e) {
301
+ kernelDebug(e);
302
+ }
303
+ }
304
+
305
+ mergeDeep(existing, updates);
306
+ const tomlString = stringifyToml(existing);
307
+ writeFileSyncAtomic(projectPath, tomlString);
308
+ return projectPath;
309
+ }
310
+
238
311
  function mergeDeep(target: any, source: any) {
239
312
  if (!source || typeof source !== "object") return;
240
313
  for (const key of Object.keys(source)) {
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as path from "path";
2
2
  import * as fs from "node:fs";
3
+ import * as child_process from "node:child_process";
3
4
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
5
  import { computeRepoMap, evaluateCodebaseMetrics } from "./retrieval/repomap";
5
6
  import { HybridSearchIndex } from "./retrieval/search_index";
@@ -10,7 +11,7 @@ import {
10
11
  globalEpistemicGuard,
11
12
  resolveUserPath,
12
13
  } from "./safety/epistemic_guard";
13
- import { loadKernelConfig } from "./config";
14
+ import { loadKernelConfig, registerAgentKernelCommand } from "./config";
14
15
  import { kernelDebug } from "./safety/kernel_debug";
15
16
  import { registerRepoMapTool } from "./tools/repo_map_tool";
16
17
  import { registerAstSearchTool } from "./tools/ast_search_tool";
@@ -65,7 +66,10 @@ function withoutPiDocumentation(systemPrompt: string): string {
65
66
  }
66
67
 
67
68
  function piDocsEnabled(ctx: any): boolean {
68
- return piDocsEnabledBySession.get(getSessionId(ctx)) ?? true;
69
+ const sessionVal = piDocsEnabledBySession.get(getSessionId(ctx));
70
+ if (sessionVal !== undefined) return sessionVal;
71
+ const cwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
72
+ return loadKernelConfig(cwd).instructions.pi_docs ?? true;
69
73
  }
70
74
 
71
75
  function loadKernelGuidance(): string {
@@ -254,6 +258,16 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
254
258
  }
255
259
  };
256
260
 
261
+ registerAgentKernelCommand(pi, {
262
+ getConfig,
263
+ invalidateConfig: (cwd) => {
264
+ configByWorkspace.delete(path.resolve(cwd));
265
+ },
266
+ clearCaches: () => {
267
+ cachedRepoMap = "";
268
+ },
269
+ });
270
+
257
271
  pi.registerCommand("pi-docs", {
258
272
  description: "Toggle Pi documentation guidance in the system prompt",
259
273
  getArgumentCompletions: (prefix: string) => {
@@ -897,12 +911,91 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
897
911
  }
898
912
  });
899
913
 
900
- // 10. Dynamic Runtime Context Injection (Repo Map with in-memory caching)
914
+ // 10. Dynamic Runtime Context Injection (Repo Map with in-memory caching & Turn 1 Grounding)
901
915
  // Notice: Custom user instructions (AGENT.md / prompt templates) are respected as the primary authority.
902
916
  // Only runtime operational metadata (repo map) is dynamically attached and cached per session/cwd.
903
917
  let cachedRepoMap = "";
904
918
  let cachedRepoMapCwd = "";
905
919
  let lastRepoMapCheck = 0;
920
+ const sessionGroundingDone = new Set<string>();
921
+ const sessionGroundingText = new Map<string, string>();
922
+
923
+ function getPreFlightGrounding(cwd: string, sessionId: string): string {
924
+ if (sessionGroundingDone.has(sessionId)) {
925
+ return sessionGroundingText.get(sessionId) || "";
926
+ }
927
+ sessionGroundingDone.add(sessionId);
928
+
929
+ try {
930
+ const statusRaw = child_process.execFileSync(
931
+ "git",
932
+ ["status", "--porcelain"],
933
+ { cwd, encoding: "utf8", timeout: 1000, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024 },
934
+ ).trim();
935
+
936
+ if (!statusRaw) {
937
+ sessionGroundingText.set(sessionId, "");
938
+ return "";
939
+ }
940
+
941
+ let diffRaw = "";
942
+ try {
943
+ diffRaw = child_process.execFileSync(
944
+ "git",
945
+ ["diff", "HEAD", "-U3"],
946
+ { cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] },
947
+ ).trim();
948
+ } catch {
949
+ try {
950
+ diffRaw = child_process.execFileSync(
951
+ "git",
952
+ ["diff", "-U3"],
953
+ { cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] },
954
+ ).trim();
955
+ } catch {
956
+ diffRaw = "";
957
+ }
958
+ }
959
+
960
+ if (!diffRaw && !statusRaw) {
961
+ sessionGroundingText.set(sessionId, "");
962
+ return "";
963
+ }
964
+
965
+ const statusLines = statusRaw.split("\n").slice(0, 8).join("\n");
966
+ const lines = diffRaw.split("\n");
967
+ const maxLines = 25;
968
+ const maxDiffBytes = 2048;
969
+ let clampedDiff = lines.slice(0, maxLines).join("\n");
970
+ let wasByteTruncated = false;
971
+ if (Buffer.byteLength(clampedDiff, "utf8") > maxDiffBytes) {
972
+ clampedDiff = clampedDiff.slice(0, maxDiffBytes);
973
+ wasByteTruncated = true;
974
+ }
975
+ const truncatedNotice = lines.length > maxLines || wasByteTruncated
976
+ ? `\n[... diff truncated; inspect test file via read() ...]`
977
+ : "";
978
+
979
+ const safeStatus = statusLines.replace(/```/g, "'''");
980
+ const safeDiff = clampedDiff.replace(/```/g, "'''");
981
+
982
+ const grounding = [
983
+ "## Workspace Pre-Flight (Reproduction Status):",
984
+ "<!-- Passive environment context; not instruction -->",
985
+ "```git-status",
986
+ safeStatus,
987
+ "```",
988
+ safeDiff ? `\`\`\`diff\n${safeDiff}\n\`\`\`${truncatedNotice}` : "",
989
+ ].filter(Boolean).join("\n");
990
+
991
+ sessionGroundingText.set(sessionId, grounding);
992
+ return grounding;
993
+ } catch (error) {
994
+ kernelDebug(error);
995
+ sessionGroundingText.set(sessionId, "");
996
+ return "";
997
+ }
998
+ }
906
999
 
907
1000
  pi.on("before_agent_start", async (event: any, ctx: any) => {
908
1001
  const now = Date.now();
@@ -930,9 +1023,13 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
930
1023
  lastRepoMapCheck = now;
931
1024
  }
932
1025
 
933
- const runtimeContext = cachedRepoMap
934
- ? `\n## Available Repository Context:\n${cachedRepoMap}\n`
935
- : "";
1026
+ const preFlightDiff = getPreFlightGrounding(currentCwd, sessionId);
1027
+ const runtimeParts = [
1028
+ cachedRepoMap ? `## Available Repository Context:\n${cachedRepoMap}` : "",
1029
+ preFlightDiff,
1030
+ ].filter(Boolean);
1031
+ const runtimeContext = runtimeParts.length > 0 ? `\n${runtimeParts.join("\n\n")}\n` : "";
1032
+
936
1033
  const basePrompt = event.systemPrompt || "";
937
1034
  const systemPrompt = piDocsEnabled(ctx)
938
1035
  ? basePrompt
@@ -941,9 +1038,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
941
1038
  ? loadKernelGuidance()
942
1039
  : "";
943
1040
  const guidedPrompt = appendKernelGuidance(systemPrompt, guidance);
1041
+ const shouldAppendRuntime = runtimeContext && !guidedPrompt.includes(runtimeContext.trim());
944
1042
  return {
945
1043
  systemPrompt: guidedPrompt
946
- ? (runtimeContext ? `${guidedPrompt}\n\n${runtimeContext}` : guidedPrompt)
1044
+ ? (shouldAppendRuntime ? `${guidedPrompt}\n\n${runtimeContext}` : guidedPrompt)
947
1045
  : runtimeContext,
948
1046
  };
949
1047
  });
@@ -253,6 +253,14 @@ export class HybridSearchIndex {
253
253
  this.persistedVectorCaches = [];
254
254
 
255
255
  for (const chunk of data.chunks as CodeChunk[]) {
256
+ // Normalize chunk.filePath alias if chunk was serialized with file
257
+ if (!chunk.filePath && (chunk as any).file) {
258
+ chunk.filePath = (chunk as any).file;
259
+ }
260
+ // Rebase absolutePath to the current workspace root if paths differ
261
+ if (chunk.filePath && this.cwd) {
262
+ chunk.absolutePath = path.resolve(this.cwd, chunk.filePath);
263
+ }
256
264
  this.chunks.set(chunk.id, chunk);
257
265
  this.bm25.addChunk(chunk);
258
266
  }
@@ -55,6 +55,10 @@ export function isDiscoveryCommand(command: string): boolean {
55
55
  * Clamps output lines horizontally and vertically to prevent context bloat
56
56
  * from single-line minified files, lockfiles, or massive multi-file matches.
57
57
  * Preserves 100% of raw output in an OS temp spillover file when truncation occurs.
58
+ *
59
+ * Adheres strictly to the language-agnostic conservative head/tail architecture:
60
+ * never uses language-specific regex guessing to discard intermediate lines,
61
+ * guaranteeing zero false-negative diagnostic suppression across arbitrary runtimes.
58
62
  */
59
63
  export function clampCommandOutput(
60
64
  rawText: string,
@@ -136,14 +140,16 @@ export function clampCommandOutput(
136
140
  if (files.length > 20) {
137
141
  const toDelete = files.slice(0, files.length - 20);
138
142
  for (const item of toDelete) {
139
- try { fs.unlinkSync(item.full); } catch {}
143
+ try {
144
+ fs.unlinkSync(item.full);
145
+ } catch {}
140
146
  }
141
147
  }
142
148
  } catch {}
143
149
 
144
150
  const hash = crypto.randomBytes(4).toString("hex");
145
151
  const candidatePath = path.join(tempDir, `pi_bash_spillover_${hash}.log`);
146
- fs.writeFileSync(candidatePath, rawText, "utf8");
152
+ fs.writeFileSync(candidatePath, rawText, { encoding: "utf8", mode: 0o600 });
147
153
  spilloverPath = candidatePath;
148
154
  } catch (e) {
149
155
  kernelDebug(e);
@@ -156,7 +162,11 @@ export function clampCommandOutput(
156
162
  if (line.length > maxLineLength) {
157
163
  let end = Math.max(10, maxLineLength - 60);
158
164
  // Do not split a valid UTF-16 surrogate pair.
159
- if (/[\uD800-\uDBFF]/.test(line.charAt(end - 1)) && /[\uDC00-\uDFFF]/.test(line.charAt(end))) end--;
165
+ if (
166
+ /[\uD800-\uDBFF]/.test(line.charAt(end - 1)) &&
167
+ /[\uDC00-\uDFFF]/.test(line.charAt(end))
168
+ )
169
+ end--;
160
170
  const kept = line.slice(0, end);
161
171
  const omitted = line.length - kept.length;
162
172
  return `${kept}... <line ${idx + 1} truncated: ${omitted.toLocaleString()} chars omitted>`;
@@ -205,15 +215,26 @@ export function clampCommandOutput(
205
215
  }
206
216
 
207
217
  if (Buffer.byteLength(resultText + footer, "utf8") > maxTotalBytes) {
208
- const marker = clampedLines.findIndex(line => /^\n\[\.\.\. /.test(line));
218
+ const marker = clampedLines.findIndex((line) => /^\n\[\.\.\. /.test(line));
209
219
  if (marker !== -1) clampedLines.splice(marker, 1);
210
220
  }
211
221
  // Enforce the byte budget on the complete returned text: retain whole lines,
212
222
  // removing from the middle first so head and tail context survive.
213
- while (clampedLines.length && Buffer.byteLength(clampedLines.join("\n") + footer, "utf8") > maxTotalBytes) {
214
- const [removed] = clampedLines.splice(Math.floor(clampedLines.length / 2), 1);
223
+ while (
224
+ clampedLines.length &&
225
+ Buffer.byteLength(clampedLines.join("\n") + footer, "utf8") > maxTotalBytes
226
+ ) {
227
+ const [removed] = clampedLines.splice(
228
+ Math.floor(clampedLines.length / 2),
229
+ 1,
230
+ );
215
231
  if (!removed.startsWith("\n[... ")) shownLines--;
216
- footer = "\n\n[Truncated: " + shownLines + "/" + totalLines + " lines." +
232
+ footer =
233
+ "\n\n[Truncated: " +
234
+ shownLines +
235
+ "/" +
236
+ totalLines +
237
+ " lines." +
217
238
  (spilloverPath ? " Full: " + spilloverPath + "]" : "]");
218
239
  }
219
240
  resultText = clampedLines.join("\n") + footer;