@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.
- package/AGENT_KERNEL_SYS_PROMPT.md +6 -4
- package/CHANGELOG.md +35 -4
- package/README.md +39 -74
- package/config.example.toml +36 -0
- package/docs/configuration.md +11 -3
- package/docs/retrieval.md +17 -1
- package/docs/testing.md +5 -3
- package/package.json +9 -7
- package/src/config/agent_kernel_command.ts +91 -91
- package/src/config/kernel_config.ts +179 -43
- package/src/config/toml.ts +15 -4
- package/src/context/session_repair.ts +179 -80
- package/src/editing/patch.ts +28 -16
- package/src/editing/smart_anchor.ts +29 -36
- package/src/editing/syntax-verify.ts +52 -18
- package/src/index.ts +257 -219
- package/src/lsp/lsp_client.ts +138 -23
- package/src/lsp/lsp_formatter.ts +61 -24
- package/src/lsp/lsp_installer.ts +277 -561
- package/src/lsp/lsp_manager.ts +1 -1
- package/src/lsp/lsp_registry.ts +110 -73
- package/src/retrieval/ast_search.ts +136 -172
- package/src/retrieval/repomap.ts +8 -47
- package/src/retrieval/search_bm25.ts +5 -2
- package/src/retrieval/search_cache.ts +69 -0
- package/src/retrieval/search_chunker.ts +21 -43
- package/src/retrieval/search_config.ts +75 -18
- package/src/retrieval/search_embedder.ts +8 -16
- package/src/retrieval/search_index.ts +923 -123
- package/src/retrieval/workspace_walker.ts +262 -0
- package/src/safety/atomic_write.ts +59 -20
- package/src/safety/epistemic_guard.ts +163 -43
- package/src/safety/output_clamper.ts +316 -74
- package/src/tools/code_search_output.ts +59 -23
- package/src/tools/code_search_tool.ts +42 -46
- package/src/tools/context.ts +15 -1
- package/src/tools/edit_tool.ts +124 -43
- package/src/tools/lsp_tool.ts +17 -4
- package/src/tools/read_tool.ts +48 -7
- package/config.toml +0 -31
package/src/index.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import * as path from "path";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
|
-
import * as child_process from "node:child_process";
|
|
4
3
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import { computeRepoMap
|
|
4
|
+
import { computeRepoMap } from "./retrieval/repomap";
|
|
6
5
|
import { HybridSearchIndex } from "./retrieval/search_index";
|
|
7
|
-
import type
|
|
6
|
+
import { type SearchProfile, savePersistedProfile } from "./retrieval/search_config";
|
|
8
7
|
import { SearchControlModal } from "./retrieval/search_modal";
|
|
9
8
|
import { checkSyntax } from "./editing/syntax-verify";
|
|
10
9
|
import {
|
|
@@ -15,6 +14,7 @@ import { loadKernelConfig, registerAgentKernelCommand } from "./config";
|
|
|
15
14
|
import { kernelDebug } from "./safety/kernel_debug";
|
|
16
15
|
import { registerRepoMapTool } from "./tools/repo_map_tool";
|
|
17
16
|
import { registerAstSearchTool } from "./tools/ast_search_tool";
|
|
17
|
+
import { speculativeToolsEnabled } from "./tools/context";
|
|
18
18
|
import { registerCodeSearchTool } from "./tools/code_search_tool";
|
|
19
19
|
import { registerReadTool } from "./tools/read_tool";
|
|
20
20
|
import { registerEditTool } from "./tools/edit_tool";
|
|
@@ -48,10 +48,10 @@ function getSessionId(ctx: any): string {
|
|
|
48
48
|
const PI_DOCS_START =
|
|
49
49
|
"Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):";
|
|
50
50
|
const PI_DOCS_END = /\n- Always read pi \.md files completely[^\n]*/;
|
|
51
|
-
const KERNEL_GUIDANCE_MARKER = "
|
|
51
|
+
export const KERNEL_GUIDANCE_MARKER = "<agent_kernel_guidance>";
|
|
52
|
+
const KERNEL_TOOL_BLOCKS = ["CODE_SEARCH"] as const;
|
|
52
53
|
let kernelGuidance: string | null | undefined;
|
|
53
54
|
const piDocsEnabledBySession = new Map<string, boolean>();
|
|
54
|
-
const codebaseProfileBySession = new Map<string, "auto" | "light" | "heavy">();
|
|
55
55
|
|
|
56
56
|
function withoutPiDocumentation(systemPrompt: string): string {
|
|
57
57
|
const start = systemPrompt.indexOf(PI_DOCS_START);
|
|
@@ -72,27 +72,55 @@ function piDocsEnabled(ctx: any): boolean {
|
|
|
72
72
|
return loadKernelConfig(cwd).instructions.pi_docs ?? true;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
-
function
|
|
76
|
-
|
|
75
|
+
export function renderKernelGuidance(guidance: string, availableTools: ReadonlySet<string>): string {
|
|
76
|
+
return KERNEL_TOOL_BLOCKS.reduce((rendered, block) => {
|
|
77
|
+
const toolName = block.toLowerCase();
|
|
78
|
+
// Tolerate CRLF: a git checkout with core.autocrlf produces CRLF line endings, and a
|
|
79
|
+
// pattern requiring a bare LF never matches. That failure is silent: it disables gating
|
|
80
|
+
// entirely, shipping the raw <!-- KERNEL:... --> comments and advertising tools that
|
|
81
|
+
// are not registered.
|
|
82
|
+
const pattern = new RegExp(`<!-- KERNEL:${block} -->\\r?\n([\\s\\S]*?)\\r?\n<!-- /KERNEL:${block} -->\\r?\n?`, "g");
|
|
83
|
+
return rendered.replace(pattern, (_match, body: string) => availableTools.has(toolName) ? `${body}\n` : "");
|
|
84
|
+
}, guidance);
|
|
85
|
+
}
|
|
77
86
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
87
|
+
function loadKernelGuidance(
|
|
88
|
+
toolCollisions: ReadonlySet<string>,
|
|
89
|
+
availableTools: ReadonlySet<string>,
|
|
90
|
+
): string {
|
|
91
|
+
if (kernelGuidance === undefined) {
|
|
92
|
+
try {
|
|
93
|
+
const instructionPath = path.join(__dirname, "..", "AGENT_KERNEL_SYS_PROMPT.md");
|
|
94
|
+
const contents = fs.readFileSync(instructionPath, "utf8").trim();
|
|
95
|
+
kernelGuidance = contents || null;
|
|
96
|
+
} catch (error) {
|
|
97
|
+
kernelGuidance = null;
|
|
98
|
+
kernelDebug(error);
|
|
99
|
+
}
|
|
85
100
|
}
|
|
86
101
|
|
|
87
|
-
|
|
102
|
+
const base = kernelGuidance ?? "";
|
|
103
|
+
const rendered = renderKernelGuidance(base, availableTools);
|
|
104
|
+
if (toolCollisions.size === 0) return rendered;
|
|
105
|
+
return [
|
|
106
|
+
rendered,
|
|
107
|
+
"",
|
|
108
|
+
"## Tool Integration Notice",
|
|
109
|
+
`Pi reports that another extension already owns: ${[...toolCollisions].sort().join(", ")}. Agent Kernel did not replace those tools. Kernel-specific output limits, read-before-write checks, or edit verification may not apply to them.`,
|
|
110
|
+
].filter(Boolean).join("\n");
|
|
88
111
|
}
|
|
89
112
|
|
|
90
113
|
function appendKernelGuidance(systemPrompt: string, guidance: string): string {
|
|
91
|
-
if (!guidance
|
|
114
|
+
if (!guidance) return systemPrompt;
|
|
115
|
+
const trimmed = guidance.trim();
|
|
116
|
+
const wrapped = `${KERNEL_GUIDANCE_MARKER}\n${trimmed}\n</agent_kernel_guidance>`;
|
|
117
|
+
if (systemPrompt.includes(wrapped) || systemPrompt.includes(guidance) || systemPrompt.includes(trimmed)) {
|
|
118
|
+
return systemPrompt;
|
|
119
|
+
}
|
|
92
120
|
const base = systemPrompt.trimEnd();
|
|
93
|
-
return `${base ? `${base}\n\n` : ""}${
|
|
121
|
+
return `${base ? `${base}\n\n` : ""}${wrapped}`;
|
|
94
122
|
}
|
|
95
|
-
import { clampCommandOutput } from "./safety/output_clamper";
|
|
123
|
+
import { clampCommandOutput, getSpilloverRoot } from "./safety/output_clamper";
|
|
96
124
|
import { sanitizeSessionFiles } from "./context/session_repair";
|
|
97
125
|
import { formatSearchEngineTag, renderFooter } from "./ui/footer";
|
|
98
126
|
import {
|
|
@@ -111,25 +139,20 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
111
139
|
kernelDebug(`TreeSitter background init error: ${err}`);
|
|
112
140
|
});
|
|
113
141
|
|
|
114
|
-
// 0. Auto-Sanitize Session Files (Repairs pre-existing incomplete usage metadata)
|
|
115
|
-
try {
|
|
116
|
-
sanitizeSessionFiles();
|
|
117
|
-
} catch (e) {
|
|
118
|
-
kernelDebug(e);
|
|
119
|
-
}
|
|
120
|
-
|
|
121
142
|
// 3. Slash Commands: /repomap, /engine, /lsp, /pi-docs
|
|
122
143
|
let activeTui: any = null;
|
|
144
|
+
let projectTrusted = false;
|
|
123
145
|
const configByWorkspace = new Map<
|
|
124
146
|
string,
|
|
125
147
|
ReturnType<typeof loadKernelConfig>
|
|
126
148
|
>();
|
|
127
149
|
const getConfig = (cwd: string) => {
|
|
128
150
|
const workspace = path.resolve(cwd);
|
|
129
|
-
|
|
151
|
+
const cacheKey = `${workspace}\0${projectTrusted}`;
|
|
152
|
+
let config = configByWorkspace.get(cacheKey);
|
|
130
153
|
if (!config) {
|
|
131
|
-
config = loadKernelConfig(workspace);
|
|
132
|
-
configByWorkspace.set(
|
|
154
|
+
config = loadKernelConfig(workspace, { projectTrusted });
|
|
155
|
+
configByWorkspace.set(cacheKey, config);
|
|
133
156
|
}
|
|
134
157
|
return config;
|
|
135
158
|
};
|
|
@@ -138,7 +161,8 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
138
161
|
const workspace = path.resolve(cwd);
|
|
139
162
|
let index = searchIndexes.get(workspace);
|
|
140
163
|
if (!index) {
|
|
141
|
-
|
|
164
|
+
const profile = getConfig(workspace).retrieval.default_profile;
|
|
165
|
+
index = new HybridSearchIndex(workspace, profile, { projectTrusted });
|
|
142
166
|
searchIndexes.set(workspace, index);
|
|
143
167
|
}
|
|
144
168
|
return index;
|
|
@@ -148,6 +172,13 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
148
172
|
const syncRetrievalStatus = (ctx: any, customText?: string) => {
|
|
149
173
|
if (!ctx?.ui?.setStatus) return;
|
|
150
174
|
const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
175
|
+
const config = getConfig(cwd);
|
|
176
|
+
if (!config.ui.enable_pastel_footer) {
|
|
177
|
+
ctx.ui.setStatus("retrieval", "");
|
|
178
|
+
activeTui?.requestRender?.();
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
|
|
151
182
|
const index = getSearchIndex(cwd);
|
|
152
183
|
const eff = index.getEffectiveProfile();
|
|
153
184
|
if (eff === "off") {
|
|
@@ -165,28 +196,32 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
165
196
|
activeTui?.requestRender?.();
|
|
166
197
|
};
|
|
167
198
|
|
|
199
|
+
let activeIndexingGeneration = 0;
|
|
200
|
+
|
|
168
201
|
const triggerBackgroundIndexing = (
|
|
169
202
|
index: HybridSearchIndex,
|
|
170
203
|
ctx: any,
|
|
171
204
|
isFullSync = false,
|
|
172
205
|
) => {
|
|
206
|
+
const currentGeneration = ++activeIndexingGeneration;
|
|
173
207
|
const eff = index.getEffectiveProfile();
|
|
174
208
|
if (eff === "off") {
|
|
175
209
|
syncRetrievalStatus(ctx);
|
|
176
210
|
return;
|
|
177
211
|
}
|
|
178
212
|
|
|
179
|
-
const engineTag = formatSearchEngineTag(index, true);
|
|
180
213
|
const streamArrow = "\x1b[38;2;155;210;170m⇢\x1b[0m";
|
|
181
214
|
syncRetrievalStatus(
|
|
182
215
|
ctx,
|
|
183
|
-
`${
|
|
216
|
+
`${formatSearchEngineTag(index, true)} ${streamArrow} \x1b[38;2;165;175;190m(indexing...)\x1b[0m`,
|
|
184
217
|
);
|
|
185
218
|
|
|
186
219
|
const runSync = async () => {
|
|
187
220
|
return await index.syncWorkspace(
|
|
188
221
|
isFullSync,
|
|
189
222
|
(msg: string) => {
|
|
223
|
+
if (currentGeneration !== activeIndexingGeneration) return;
|
|
224
|
+
const engineTag = formatSearchEngineTag(index, true);
|
|
190
225
|
const pctMatch = msg.match(/(\d+)%/);
|
|
191
226
|
const speedMatch = msg.match(/([\d.]+\s*chunk\/s)/);
|
|
192
227
|
const countMatch = msg.match(/\((\d+)\/(\d+)/);
|
|
@@ -220,6 +255,12 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
220
255
|
// while progress stays cleanly reported on the statusline.
|
|
221
256
|
void runSync()
|
|
222
257
|
.then((result) => {
|
|
258
|
+
if (currentGeneration !== activeIndexingGeneration) return;
|
|
259
|
+
if (index.getEffectiveProfile() === "off") {
|
|
260
|
+
ctx?.ui?.setStatus?.("retrieval", "");
|
|
261
|
+
activeTui?.requestRender?.();
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
223
264
|
syncRetrievalStatus(ctx); // Reset to clean idle tag on status line
|
|
224
265
|
if (
|
|
225
266
|
(result.indexedCount !== undefined ? result.indexedCount > 0 : false) ||
|
|
@@ -232,6 +273,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
232
273
|
}
|
|
233
274
|
})
|
|
234
275
|
.catch((err: any) => {
|
|
276
|
+
if (currentGeneration !== activeIndexingGeneration) return;
|
|
235
277
|
syncRetrievalStatus(ctx);
|
|
236
278
|
ctx.ui?.notify?.(`Indexing error: ${err.message}`, "error");
|
|
237
279
|
});
|
|
@@ -258,16 +300,69 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
258
300
|
}
|
|
259
301
|
};
|
|
260
302
|
|
|
303
|
+
const applyConfigChanges = (cwd: string, ctx?: any) => {
|
|
304
|
+
const workspace = path.resolve(cwd);
|
|
305
|
+
configByWorkspace.delete(`${workspace}\0true`);
|
|
306
|
+
configByWorkspace.delete(`${workspace}\0false`);
|
|
307
|
+
const newConfig = getConfig(workspace);
|
|
308
|
+
const newProfile = newConfig.retrieval.default_profile;
|
|
309
|
+
|
|
310
|
+
// 1. Live update of running in-memory search index if profile changed
|
|
311
|
+
const index = searchIndexes.get(workspace);
|
|
312
|
+
if (index) {
|
|
313
|
+
if (index.getProfile() !== newProfile) {
|
|
314
|
+
index.setProfile(newProfile);
|
|
315
|
+
if (ctx) {
|
|
316
|
+
triggerBackgroundIndexing(index, ctx, false);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// 2. Refresh statusline and footer immediately
|
|
322
|
+
if (ctx) {
|
|
323
|
+
syncRetrievalStatus(ctx);
|
|
324
|
+
activeTui?.requestRender?.();
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
|
|
261
328
|
registerAgentKernelCommand(pi, {
|
|
262
329
|
getConfig,
|
|
263
|
-
invalidateConfig: (cwd) => {
|
|
264
|
-
|
|
330
|
+
invalidateConfig: (cwd, ctx) => {
|
|
331
|
+
applyConfigChanges(cwd, ctx);
|
|
265
332
|
},
|
|
266
333
|
clearCaches: () => {
|
|
267
334
|
cachedRepoMap = "";
|
|
268
335
|
},
|
|
269
336
|
});
|
|
270
337
|
|
|
338
|
+
pi.registerCommand("repair-sessions", {
|
|
339
|
+
description: "Preview or explicitly apply repairs for malformed historical session usage metadata",
|
|
340
|
+
getArgumentCompletions: (prefix: string) => {
|
|
341
|
+
const options = [
|
|
342
|
+
{ value: "", label: "preview - report repair candidates without writing" },
|
|
343
|
+
{ value: "--apply", label: "--apply - back up and repair eligible inactive sessions" },
|
|
344
|
+
];
|
|
345
|
+
return options.filter((option) => option.value.startsWith(prefix.toLowerCase()));
|
|
346
|
+
},
|
|
347
|
+
handler: async (args: string, ctx: any) => {
|
|
348
|
+
const mode = (args || "").trim().toLowerCase();
|
|
349
|
+
if (mode && mode !== "--apply") {
|
|
350
|
+
ctx.ui?.notify?.("Usage: /repair-sessions [--apply]", "error");
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
const activeSession = ctx?.sessionManager?.getSessionFile?.();
|
|
354
|
+
const stats = sanitizeSessionFiles({
|
|
355
|
+
skipFile: activeSession,
|
|
356
|
+
apply: mode === "--apply",
|
|
357
|
+
});
|
|
358
|
+
const summary = stats.dryRun
|
|
359
|
+
? `Session repair preview: ${stats.candidateFiles} candidate file(s), ${stats.repairedEntries} entr(ies); no files written.`
|
|
360
|
+
: `Session repair complete: ${stats.repairedFiles} repaired, ${stats.skippedFiles} skipped, ${stats.failedFiles} failed.`;
|
|
361
|
+
ctx.ui?.notify?.(summary, stats.failedFiles > 0 ? "error" : "info");
|
|
362
|
+
console.log(`[repair-sessions] ${summary} ${JSON.stringify(stats)}`);
|
|
363
|
+
},
|
|
364
|
+
});
|
|
365
|
+
|
|
271
366
|
pi.registerCommand("pi-docs", {
|
|
272
367
|
description: "Toggle Pi documentation guidance in the system prompt",
|
|
273
368
|
getArgumentCompletions: (prefix: string) => {
|
|
@@ -320,44 +415,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
320
415
|
},
|
|
321
416
|
});
|
|
322
417
|
|
|
323
|
-
// Slash Command: /profile [auto|smart|light|heavy|status]
|
|
324
|
-
pi.registerCommand("profile", {
|
|
325
|
-
description: "Configure codebase scale profile (auto/smart | light | heavy | status)",
|
|
326
|
-
getArgumentCompletions: (prefix: string) => {
|
|
327
|
-
const options = [
|
|
328
|
-
{ value: "auto", label: "auto (smart) - Auto-detect scale from codebase metrics" },
|
|
329
|
-
{ value: "light", label: "light - Force light profile (suppress auto repo-map)" },
|
|
330
|
-
{ value: "heavy", label: "heavy - Force heavy profile (always inject repo-map)" },
|
|
331
|
-
{ value: "status", label: "status - Display current profile & codebase metrics" },
|
|
332
|
-
];
|
|
333
|
-
const filtered = options.filter((o) => o.value.startsWith(prefix.toLowerCase()));
|
|
334
|
-
return filtered.length > 0 ? filtered : null;
|
|
335
|
-
},
|
|
336
|
-
handler: async (args: string, ctx: any) => {
|
|
337
|
-
const sessionId = getSessionId(ctx);
|
|
338
|
-
const raw = (args || "").trim().toLowerCase();
|
|
339
|
-
const val = raw === "smart" ? "auto" : raw;
|
|
340
|
-
|
|
341
|
-
if (val === "auto" || val === "light" || val === "heavy") {
|
|
342
|
-
codebaseProfileBySession.set(sessionId, val);
|
|
343
|
-
cachedRepoMap = "";
|
|
344
|
-
const msg = `Codebase profile set to '${val}' for this session.`;
|
|
345
|
-
ctx.ui?.notify?.(msg, "info");
|
|
346
|
-
if (!ctx.hasUI) console.log(msg);
|
|
347
|
-
return;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
351
|
-
const current = codebaseProfileBySession.get(sessionId) ?? getConfig(currentCwd).retrieval.codebase_profile;
|
|
352
|
-
const metrics = evaluateCodebaseMetrics(currentCwd);
|
|
353
|
-
const detected = metrics.isLight ? "light" : "heavy";
|
|
354
|
-
const effective = current === "auto" ? detected : current;
|
|
355
|
-
const statusMsg = `Profile: ${current} (effective: ${effective})\nMetrics: ${metrics.implFiles} impl files (${Math.round(metrics.implBytes / 1024)} KB), ${metrics.testFiles} test files (${Math.round(metrics.testBytes / 1024)} KB)`;
|
|
356
|
-
ctx.ui?.notify?.(statusMsg, "info");
|
|
357
|
-
if (!ctx.hasUI) console.log("\n" + statusMsg + "\n");
|
|
358
|
-
},
|
|
359
|
-
});
|
|
360
|
-
|
|
361
418
|
// Slash Command: /engine [auto|lean|hybrid|full|off|status|reindex]
|
|
362
419
|
pi.registerCommand("engine", {
|
|
363
420
|
description:
|
|
@@ -412,8 +469,9 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
412
469
|
sub === "full" ||
|
|
413
470
|
sub === "off"
|
|
414
471
|
) {
|
|
415
|
-
|
|
416
|
-
|
|
472
|
+
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
473
|
+
savePersistedProfile(sub as SearchProfile, currentCwd);
|
|
474
|
+
applyConfigChanges(currentCwd, ctx);
|
|
417
475
|
const status = index.getStatus();
|
|
418
476
|
const msg = `Default search profile saved: ${sub.toUpperCase()} (Effective: ${status.effectiveProfile.toUpperCase()})`;
|
|
419
477
|
ctx.ui?.notify?.(msg, "info");
|
|
@@ -472,6 +530,11 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
472
530
|
const effName = eff.toUpperCase();
|
|
473
531
|
|
|
474
532
|
if (res.action === "select") {
|
|
533
|
+
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
534
|
+
if (res.profile) {
|
|
535
|
+
savePersistedProfile(res.profile, currentCwd);
|
|
536
|
+
applyConfigChanges(currentCwd, ctx);
|
|
537
|
+
}
|
|
475
538
|
ctx.ui?.notify?.(
|
|
476
539
|
`Engine set to ${profileName} (Effective: ${effName})`,
|
|
477
540
|
"info",
|
|
@@ -509,42 +572,34 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
509
572
|
);
|
|
510
573
|
if (!choice || choice.startsWith("──")) return;
|
|
511
574
|
|
|
512
|
-
|
|
513
|
-
let
|
|
514
|
-
|
|
515
|
-
if (choice.includes("
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
index
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
ctx.ui.notify("Default search profile saved: OFF", "info");
|
|
534
|
-
} else if (choice.includes("Re-index")) {
|
|
535
|
-
isReindex = true;
|
|
536
|
-
} else if (choice.includes("View Status")) {
|
|
575
|
+
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
576
|
+
let newProfile: SearchProfile | null = null;
|
|
577
|
+
if (choice.includes("Auto Detect")) newProfile = "auto";
|
|
578
|
+
else if (choice.includes("Lean Mode")) newProfile = "lean";
|
|
579
|
+
else if (choice.includes("Hybrid Mode")) newProfile = "hybrid";
|
|
580
|
+
else if (choice.includes("Full Mode")) newProfile = "full";
|
|
581
|
+
else if (choice.includes("Disable Engine")) newProfile = "off";
|
|
582
|
+
|
|
583
|
+
if (newProfile) {
|
|
584
|
+
savePersistedProfile(newProfile, currentCwd);
|
|
585
|
+
applyConfigChanges(currentCwd, ctx);
|
|
586
|
+
ctx.ui?.notify?.(`Default search profile saved: ${newProfile.toUpperCase()}`, "info");
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
if (choice.includes("Re-index")) {
|
|
591
|
+
triggerBackgroundIndexing(index, ctx, true);
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
if (choice.includes("View Status")) {
|
|
537
596
|
const s = index.getStatus();
|
|
538
597
|
ctx.ui.notify(
|
|
539
598
|
`Engine: ${s.engineState} | Profile: ${s.profile.toUpperCase()} (Effective: ${s.effectiveProfile.toUpperCase()}) | Files: ${s.fileCount} | Chunks: ${s.chunkCount} | Model: ${s.modelStatus} | RSS: ${s.rssMemoryMB}MB`,
|
|
540
599
|
"info",
|
|
541
600
|
);
|
|
601
|
+
return;
|
|
542
602
|
}
|
|
543
|
-
|
|
544
|
-
if (profileChanged || isReindex) {
|
|
545
|
-
triggerBackgroundIndexing(index, ctx, isReindex);
|
|
546
|
-
}
|
|
547
|
-
return;
|
|
548
603
|
}
|
|
549
604
|
|
|
550
605
|
// CLI fallback if not in UI mode
|
|
@@ -679,9 +734,12 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
679
734
|
|
|
680
735
|
// Background workspace auto-indexer on session startup + setup integrated footer
|
|
681
736
|
pi.on("session_start", async (_event: any, ctx: any) => {
|
|
737
|
+
projectTrusted = ctx.isProjectTrusted?.() === true;
|
|
738
|
+
configByWorkspace.clear();
|
|
739
|
+
const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
740
|
+
registerKernelTools(cwd);
|
|
682
741
|
setupUnifiedFooter(ctx);
|
|
683
742
|
try {
|
|
684
|
-
const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
685
743
|
const index = getSearchIndex(cwd);
|
|
686
744
|
if (index.getEffectiveProfile() !== "off") {
|
|
687
745
|
triggerBackgroundIndexing(index, ctx, false);
|
|
@@ -704,27 +762,74 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
704
762
|
} catch (e) {
|
|
705
763
|
kernelDebug(e);
|
|
706
764
|
}
|
|
765
|
+
// Flush any debounced search index writes to disk on shutdown and halt further admissions
|
|
766
|
+
for (const index of searchIndexes.values()) {
|
|
767
|
+
try {
|
|
768
|
+
await index.flushPendingSave(true);
|
|
769
|
+
} catch (e) {
|
|
770
|
+
kernelDebug(e);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
707
773
|
});
|
|
708
774
|
|
|
709
|
-
//
|
|
710
|
-
//
|
|
711
|
-
//
|
|
712
|
-
const
|
|
713
|
-
|
|
775
|
+
// Tools are registered at session start, after every extension factory has
|
|
776
|
+
// registered its tools. This makes collision handling independent of package
|
|
777
|
+
// load order and lets project trust affect optional-tool registration.
|
|
778
|
+
const toolCollisions = new Set<string>();
|
|
779
|
+
const kernelRegisteredTools = new Set<string>();
|
|
780
|
+
let kernelToolsRegistered = false;
|
|
781
|
+
const invalidateSearchFile = async (cwd: string, filePath: string) => {
|
|
782
|
+
const index = getSearchIndex(cwd);
|
|
783
|
+
await index.updateFile(filePath).catch((err) => {
|
|
784
|
+
kernelDebug(`Incremental updateFile error for ${filePath}: ${err}`);
|
|
785
|
+
});
|
|
786
|
+
};
|
|
787
|
+
const registerKernelTools = (cwd: string): void => {
|
|
788
|
+
if (kernelToolsRegistered) return;
|
|
789
|
+
kernelToolsRegistered = true;
|
|
790
|
+
// pi marks its own built-in tools with sourceInfo.source === "builtin" and a
|
|
791
|
+
// "builtin:<name>" path (BUILTIN_PATH_PREFIX in pi's core/source-info). Only tools owned
|
|
792
|
+
// by another extension are collisions: extension tools override built-ins in pi's tool
|
|
793
|
+
// registry, so built-ins must be excluded here or we would never register our own read/edit.
|
|
794
|
+
const extensionTools = (pi.getAllTools?.() || []).filter(
|
|
795
|
+
(tool: any) =>
|
|
796
|
+
tool?.sourceInfo?.source !== "builtin" &&
|
|
797
|
+
!String(tool?.sourceInfo?.path || "").startsWith("builtin:"),
|
|
798
|
+
);
|
|
799
|
+
const owned = new Set(extensionTools.map((tool: any) => tool.name));
|
|
800
|
+
if (owned.has("bash")) toolCollisions.add("bash");
|
|
801
|
+
const canRegister = (name: string): boolean => {
|
|
802
|
+
if (owned.has(name)) {
|
|
803
|
+
toolCollisions.add(name);
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
return true;
|
|
807
|
+
};
|
|
808
|
+
|
|
809
|
+
if (canRegister("read")) {
|
|
810
|
+
registerReadTool(pi, { getSessionId, getConfig });
|
|
811
|
+
kernelRegisteredTools.add("read");
|
|
812
|
+
}
|
|
813
|
+
if (canRegister("edit")) {
|
|
814
|
+
registerEditTool(pi, { getSessionId, getConfig, invalidateSearchFile });
|
|
815
|
+
kernelRegisteredTools.add("edit");
|
|
816
|
+
}
|
|
817
|
+
// Register independently of the first session's profile: one extension instance may
|
|
818
|
+
// serve multiple workspaces. Availability is gated per workspace in execution and prompts.
|
|
819
|
+
if (canRegister("code_search")) {
|
|
820
|
+
registerCodeSearchTool(pi, { getSessionId, getSearchIndex, getConfig });
|
|
821
|
+
kernelRegisteredTools.add("code_search");
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
const enableSpeculativeTools = speculativeToolsEnabled(getConfig, cwd);
|
|
825
|
+
if (enableSpeculativeTools) {
|
|
826
|
+
if (canRegister("get_repo_map")) registerRepoMapTool(pi);
|
|
827
|
+
if (canRegister("ast_search")) {
|
|
828
|
+
registerAstSearchTool(pi, { getSessionId, getConfig });
|
|
829
|
+
}
|
|
830
|
+
if (canRegister("lsp")) registerLspTool(pi, { getSessionId, getConfig });
|
|
831
|
+
}
|
|
714
832
|
};
|
|
715
|
-
registerReadTool(pi, { getSessionId, getConfig });
|
|
716
|
-
registerEditTool(pi, { getSessionId, getConfig, invalidateSearchFile });
|
|
717
|
-
registerCodeSearchTool(pi, { getSessionId, getSearchIndex, getConfig });
|
|
718
|
-
|
|
719
|
-
const enableSpeculativeTools = process.env.PI_ENABLE_ALL_RETRIEVAL_TOOLS === "1" ||
|
|
720
|
-
process.env.PI_ENABLE_ALL_RETRIEVAL_TOOLS === "true" ||
|
|
721
|
-
getConfig(process.cwd()).retrieval.enable_tools === true;
|
|
722
|
-
|
|
723
|
-
if (enableSpeculativeTools) {
|
|
724
|
-
registerRepoMapTool(pi);
|
|
725
|
-
registerAstSearchTool(pi, { getSessionId, getConfig });
|
|
726
|
-
registerLspTool(pi, { getSessionId, getConfig });
|
|
727
|
-
}
|
|
728
833
|
|
|
729
834
|
// 9a. Block host writes before the host tool can create parent directories
|
|
730
835
|
// or overwrite the target. Bash read evidence is recorded after a successful
|
|
@@ -771,16 +876,16 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
771
876
|
|
|
772
877
|
// 9. Tool Result Interceptor: Syntax Validation & Output Clamping (ACI)
|
|
773
878
|
pi.on("tool_result", async (event: any, ctx: any) => {
|
|
774
|
-
const
|
|
775
|
-
if (event.isError && !
|
|
879
|
+
const isShell = event.toolName === "bash" || event.toolName === "powershell";
|
|
880
|
+
if (event.isError && !isShell) return;
|
|
776
881
|
|
|
777
882
|
// resultContent === undefined means "no transformation, return event.content as-is".
|
|
778
883
|
const toolName = event.toolName;
|
|
779
884
|
let resultContent: any = undefined;
|
|
780
885
|
let didBail = false;
|
|
781
886
|
|
|
782
|
-
// 9a. Intercept bash &
|
|
783
|
-
if (toolName === "bash") {
|
|
887
|
+
// 9a. Intercept bash & powershell output to clamp minified lines & massive match floods
|
|
888
|
+
if (toolName === "bash" || toolName === "powershell") {
|
|
784
889
|
const command = (event.input as any)?.command || "";
|
|
785
890
|
const outputConfig = getConfig(
|
|
786
891
|
ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
|
|
@@ -788,11 +893,16 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
788
893
|
let bashOutputComplete = true;
|
|
789
894
|
resultContent = (event.content || []).map((c: any) => {
|
|
790
895
|
if (c.type === "text" && typeof c.text === "string") {
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
896
|
+
const spilloverDir = getSpilloverRoot(
|
|
897
|
+
ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
|
|
898
|
+
);
|
|
899
|
+
const clamped = clampCommandOutput(c.text, command, {
|
|
900
|
+
maxLineLength: outputConfig.safety.max_line_length,
|
|
901
|
+
maxLines: outputConfig.safety.max_lines,
|
|
902
|
+
maxTotalBytes: outputConfig.safety.max_total_bytes,
|
|
903
|
+
spilloverDir,
|
|
904
|
+
isError: event.isError,
|
|
905
|
+
});
|
|
796
906
|
if (clamped.truncated) {
|
|
797
907
|
bashOutputComplete = false;
|
|
798
908
|
return { ...c, text: clamped.text };
|
|
@@ -843,7 +953,9 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
843
953
|
const resultCwd =
|
|
844
954
|
ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
845
955
|
const resolvedPath = resolveUserPath(targetPath, resultCwd);
|
|
846
|
-
getSearchIndex(resultCwd).
|
|
956
|
+
void getSearchIndex(resultCwd).updateFile(resolvedPath).catch((err) => {
|
|
957
|
+
kernelDebug(`Incremental updateFile error for ${resolvedPath}: ${err}`);
|
|
958
|
+
});
|
|
847
959
|
|
|
848
960
|
// Update epistemic guard ledger with the newly written file
|
|
849
961
|
try {
|
|
@@ -911,98 +1023,18 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
911
1023
|
}
|
|
912
1024
|
});
|
|
913
1025
|
|
|
914
|
-
// 10. Dynamic Runtime Context Injection (
|
|
915
|
-
//
|
|
916
|
-
//
|
|
1026
|
+
// 10. Dynamic Runtime Context Injection (optional repository map only)
|
|
1027
|
+
// Custom user instructions remain the primary authority. Repository-controlled
|
|
1028
|
+
// diffs, source text, filenames, and command output are never promoted into the
|
|
1029
|
+
// system prompt by this extension.
|
|
917
1030
|
let cachedRepoMap = "";
|
|
918
1031
|
let cachedRepoMapCwd = "";
|
|
919
1032
|
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
|
-
}
|
|
999
1033
|
|
|
1000
1034
|
pi.on("before_agent_start", async (event: any, ctx: any) => {
|
|
1001
1035
|
const now = Date.now();
|
|
1002
1036
|
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
1003
1037
|
const kernelConfig = getConfig(currentCwd);
|
|
1004
|
-
const sessionId = getSessionId(ctx);
|
|
1005
|
-
const profile = codebaseProfileBySession.get(sessionId) ?? kernelConfig.retrieval.codebase_profile ?? "auto";
|
|
1006
1038
|
|
|
1007
1039
|
let shouldInjectMap = false;
|
|
1008
1040
|
// Disabled automatic AST repo map injection to evaluate prompt token footprint and latency
|
|
@@ -1023,10 +1055,8 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
1023
1055
|
lastRepoMapCheck = now;
|
|
1024
1056
|
}
|
|
1025
1057
|
|
|
1026
|
-
const preFlightDiff = getPreFlightGrounding(currentCwd, sessionId);
|
|
1027
1058
|
const runtimeParts = [
|
|
1028
1059
|
cachedRepoMap ? `## Available Repository Context:\n${cachedRepoMap}` : "",
|
|
1029
|
-
preFlightDiff,
|
|
1030
1060
|
].filter(Boolean);
|
|
1031
1061
|
const runtimeContext = runtimeParts.length > 0 ? `\n${runtimeParts.join("\n\n")}\n` : "";
|
|
1032
1062
|
|
|
@@ -1034,8 +1064,16 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
1034
1064
|
const systemPrompt = piDocsEnabled(ctx)
|
|
1035
1065
|
? basePrompt
|
|
1036
1066
|
: withoutPiDocumentation(basePrompt);
|
|
1067
|
+
const activeToolNames = new Set(pi.getActiveTools?.() || []);
|
|
1068
|
+
const promptToolNames = new Set<string>();
|
|
1069
|
+
for (const name of ["read", "edit", "code_search", "bash"]) {
|
|
1070
|
+
const enabledForWorkspace = name !== "code_search" || kernelConfig.retrieval.default_profile !== "off";
|
|
1071
|
+
if (enabledForWorkspace && activeToolNames.has(name) && !toolCollisions.has(name) && (name === "bash" || kernelRegisteredTools.has(name))) {
|
|
1072
|
+
promptToolNames.add(name);
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1037
1075
|
const guidance = kernelConfig.instructions.enabled
|
|
1038
|
-
? loadKernelGuidance()
|
|
1076
|
+
? loadKernelGuidance(toolCollisions, promptToolNames)
|
|
1039
1077
|
: "";
|
|
1040
1078
|
const guidedPrompt = appendKernelGuidance(systemPrompt, guidance);
|
|
1041
1079
|
const shouldAppendRuntime = runtimeContext && !guidedPrompt.includes(runtimeContext.trim());
|