@floydous/pi-agent-kernel 0.4.0 → 0.4.2
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 +8 -4
- package/CHANGELOG.md +40 -87
- package/README.md +39 -74
- package/config.example.toml +1 -1
- package/docs/retrieval.md +2 -0
- package/package.json +7 -6
- package/src/config/agent_kernel_command.ts +29 -14
- package/src/config/kernel_config.ts +175 -30
- package/src/context/session_repair.ts +166 -85
- package/src/editing/patch.ts +28 -16
- package/src/editing/smart_anchor.ts +13 -29
- package/src/editing/syntax-verify.ts +35 -11
- package/src/index.ts +161 -141
- package/src/lsp/lsp_client.ts +101 -20
- package/src/lsp/lsp_formatter.ts +57 -22
- package/src/lsp/lsp_installer.ts +272 -487
- package/src/lsp/lsp_manager.ts +1 -1
- package/src/lsp/lsp_registry.ts +75 -46
- package/src/retrieval/search_bm25.ts +5 -2
- package/src/retrieval/search_cache.ts +69 -0
- package/src/retrieval/search_chunker.ts +12 -9
- package/src/retrieval/search_config.ts +20 -8
- package/src/retrieval/search_embedder.ts +8 -16
- package/src/retrieval/search_index.ts +552 -121
- package/src/safety/atomic_write.ts +59 -20
- package/src/safety/epistemic_guard.ts +440 -67
- package/src/safety/output_clamper.ts +316 -76
- 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 +114 -36
- package/src/tools/lsp_tool.ts +5 -2
- package/src/tools/read_tool.ts +44 -3
|
@@ -248,42 +248,25 @@ export function preflightSmartAnchorEdits(
|
|
|
248
248
|
};
|
|
249
249
|
}
|
|
250
250
|
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
// Verify Start Anchor Hash
|
|
251
|
+
// A supplied hash authenticates the exact requested line. Attention
|
|
252
|
+
// spillover must never redirect a write to a neighboring line.
|
|
254
253
|
if (startHash) {
|
|
255
254
|
const actualHash = computeLineHash(fileLines, startLine - 1);
|
|
256
255
|
if (actualHash !== startHash) {
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
if (startHash === prevHash || startHash === nextHash) {
|
|
262
|
-
recoveredNeighbor = true;
|
|
263
|
-
} else {
|
|
264
|
-
return {
|
|
265
|
-
success: false,
|
|
266
|
-
error: formatStaleAnchorError(fileLines, startLine, startHash, actualHash),
|
|
267
|
-
};
|
|
268
|
-
}
|
|
256
|
+
return {
|
|
257
|
+
success: false,
|
|
258
|
+
error: formatStaleAnchorError(fileLines, startLine, startHash, actualHash),
|
|
259
|
+
};
|
|
269
260
|
}
|
|
270
261
|
}
|
|
271
262
|
|
|
272
|
-
// Verify End Anchor Hash
|
|
273
263
|
if (endHash) {
|
|
274
264
|
const actualEndHash = computeLineHash(fileLines, endLine - 1);
|
|
275
265
|
if (actualEndHash !== endHash) {
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
recoveredNeighbor = true;
|
|
281
|
-
} else {
|
|
282
|
-
return {
|
|
283
|
-
success: false,
|
|
284
|
-
error: formatStaleAnchorError(fileLines, endLine, endHash, actualEndHash),
|
|
285
|
-
};
|
|
286
|
-
}
|
|
266
|
+
return {
|
|
267
|
+
success: false,
|
|
268
|
+
error: formatStaleAnchorError(fileLines, endLine, endHash, actualEndHash),
|
|
269
|
+
};
|
|
287
270
|
}
|
|
288
271
|
}
|
|
289
272
|
|
|
@@ -292,7 +275,7 @@ export function preflightSmartAnchorEdits(
|
|
|
292
275
|
startLine,
|
|
293
276
|
endLine,
|
|
294
277
|
replacementLines,
|
|
295
|
-
recoveredNeighbor,
|
|
278
|
+
recoveredNeighbor: false,
|
|
296
279
|
});
|
|
297
280
|
targetRanges.push({ startLine, endLine });
|
|
298
281
|
}
|
|
@@ -323,6 +306,7 @@ export function preflightSmartAnchorEdits(
|
|
|
323
306
|
export function applySmartAnchorEdits(
|
|
324
307
|
filePath: string,
|
|
325
308
|
edits: SmartAnchorEditBlock[],
|
|
309
|
+
options: { syntaxGate?: "warn" | "block" } = {},
|
|
326
310
|
): PatchResult {
|
|
327
311
|
const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(filePath);
|
|
328
312
|
if (!fs.existsSync(resolvedPath)) {
|
|
@@ -380,7 +364,7 @@ export function applySmartAnchorEdits(
|
|
|
380
364
|
|
|
381
365
|
// Syntax validation gate
|
|
382
366
|
const syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
383
|
-
if (!syntax.valid) {
|
|
367
|
+
if (!syntax.valid && options.syntaxGate !== "warn") {
|
|
384
368
|
return {
|
|
385
369
|
success: false,
|
|
386
370
|
filePath: resolvedPath,
|
|
@@ -83,7 +83,7 @@ function checkTsStructure(content: string): string | null {
|
|
|
83
83
|
const next = content[i + 1];
|
|
84
84
|
if (ch === "\n") {
|
|
85
85
|
line++;
|
|
86
|
-
if (state === "lineComment") state = "code";
|
|
86
|
+
if (state === "lineComment" || state === "regex") state = "code";
|
|
87
87
|
i++;
|
|
88
88
|
continue;
|
|
89
89
|
}
|
|
@@ -99,11 +99,19 @@ function checkTsStructure(content: string): string | null {
|
|
|
99
99
|
break;
|
|
100
100
|
case "squote":
|
|
101
101
|
if (ch === "\\") i++;
|
|
102
|
-
else if (ch === "'")
|
|
102
|
+
else if (ch === "'") {
|
|
103
|
+
state = "code";
|
|
104
|
+
prevSig = "'";
|
|
105
|
+
lastWord = "";
|
|
106
|
+
}
|
|
103
107
|
break;
|
|
104
108
|
case "dquote":
|
|
105
109
|
if (ch === "\\") i++;
|
|
106
|
-
else if (ch === '"')
|
|
110
|
+
else if (ch === '"') {
|
|
111
|
+
state = "code";
|
|
112
|
+
prevSig = '"';
|
|
113
|
+
lastWord = "";
|
|
114
|
+
}
|
|
107
115
|
break;
|
|
108
116
|
case "template":
|
|
109
117
|
if (ch === "\\") {
|
|
@@ -114,6 +122,8 @@ function checkTsStructure(content: string): string | null {
|
|
|
114
122
|
i++;
|
|
115
123
|
} else if (ch === "`") {
|
|
116
124
|
state = "code";
|
|
125
|
+
prevSig = "`";
|
|
126
|
+
lastWord = "";
|
|
117
127
|
}
|
|
118
128
|
break;
|
|
119
129
|
case "code":
|
|
@@ -123,7 +133,7 @@ function checkTsStructure(content: string): string | null {
|
|
|
123
133
|
} else if (ch === "/" && next === "*") {
|
|
124
134
|
state = "blockComment";
|
|
125
135
|
i++;
|
|
126
|
-
} else if (ch === "/" && regexCanStart(prevSig, lastWord)) {
|
|
136
|
+
} else if (ch === "/" && prevSig !== "<" && next !== ">" && regexCanStart(prevSig, lastWord)) {
|
|
127
137
|
// Regex literal (division makes no sense at this position).
|
|
128
138
|
// Delimiters inside it are pattern syntax, not code structure.
|
|
129
139
|
state = "regex";
|
|
@@ -150,6 +160,8 @@ function checkTsStructure(content: string): string | null {
|
|
|
150
160
|
}
|
|
151
161
|
if (top.isTemplateInterp) {
|
|
152
162
|
state = "template";
|
|
163
|
+
prevSig = "}";
|
|
164
|
+
lastWord = "";
|
|
153
165
|
}
|
|
154
166
|
}
|
|
155
167
|
if (!/\s/.test(ch)) prevSig = ch;
|
|
@@ -190,6 +202,15 @@ function checkTsStructure(content: string): string | null {
|
|
|
190
202
|
return null;
|
|
191
203
|
}
|
|
192
204
|
|
|
205
|
+
export function resolveTypeScriptCompiler(): string {
|
|
206
|
+
try {
|
|
207
|
+
return path.join(path.dirname(require.resolve("typescript/package.json")), "bin", "tsc");
|
|
208
|
+
} catch {
|
|
209
|
+
// Compatibility fallback for unusual loaders that do not expose require.resolve.
|
|
210
|
+
return path.resolve(__dirname, "../../node_modules/typescript/bin/tsc");
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
193
214
|
function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
|
|
194
215
|
if (!fs.existsSync(resolvedPath)) {
|
|
195
216
|
return { valid: true, status: "clean" };
|
|
@@ -238,14 +259,17 @@ function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
|
|
|
238
259
|
ext === ".mts" ||
|
|
239
260
|
ext === ".cts"
|
|
240
261
|
) {
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
|
|
262
|
+
const isJsx = ext === ".tsx" || ext === ".jsx";
|
|
263
|
+
// JSX/TSX text contains arbitrary unescaped delimiters (e.g. <p>step (1)</p>)
|
|
264
|
+
// that a naive bracket counter misidentifies. For JSX, tsc with --jsx preserve
|
|
265
|
+
// performs complete and authoritative syntax validation.
|
|
266
|
+
if (!isJsx) {
|
|
267
|
+
const tsContent = fs.readFileSync(resolvedPath, "utf8");
|
|
268
|
+
const structuralError = checkTsStructure(tsContent);
|
|
269
|
+
if (structuralError) throw new Error(structuralError);
|
|
270
|
+
}
|
|
244
271
|
|
|
245
|
-
const compiler =
|
|
246
|
-
__dirname,
|
|
247
|
-
"../../node_modules/typescript/bin/tsc",
|
|
248
|
-
);
|
|
272
|
+
const compiler = resolveTypeScriptCompiler();
|
|
249
273
|
const compilerArgs = [
|
|
250
274
|
"--noEmit",
|
|
251
275
|
"--noCheck",
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
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
4
|
import { computeRepoMap } from "./retrieval/repomap";
|
|
6
5
|
import { HybridSearchIndex } from "./retrieval/search_index";
|
|
@@ -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,7 +48,8 @@ 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
55
|
|
|
@@ -71,27 +72,55 @@ function piDocsEnabled(ctx: any): boolean {
|
|
|
71
72
|
return loadKernelConfig(cwd).instructions.pi_docs ?? true;
|
|
72
73
|
}
|
|
73
74
|
|
|
74
|
-
function
|
|
75
|
-
|
|
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
|
+
}
|
|
76
86
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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
|
+
}
|
|
84
100
|
}
|
|
85
101
|
|
|
86
|
-
|
|
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");
|
|
87
111
|
}
|
|
88
112
|
|
|
89
113
|
function appendKernelGuidance(systemPrompt: string, guidance: string): string {
|
|
90
|
-
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
|
+
}
|
|
91
120
|
const base = systemPrompt.trimEnd();
|
|
92
|
-
return `${base ? `${base}\n\n` : ""}${
|
|
121
|
+
return `${base ? `${base}\n\n` : ""}${wrapped}`;
|
|
93
122
|
}
|
|
94
|
-
import { clampCommandOutput } from "./safety/output_clamper";
|
|
123
|
+
import { clampCommandOutput, getSpilloverRoot } from "./safety/output_clamper";
|
|
95
124
|
import { sanitizeSessionFiles } from "./context/session_repair";
|
|
96
125
|
import { formatSearchEngineTag, renderFooter } from "./ui/footer";
|
|
97
126
|
import {
|
|
@@ -110,25 +139,20 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
110
139
|
kernelDebug(`TreeSitter background init error: ${err}`);
|
|
111
140
|
});
|
|
112
141
|
|
|
113
|
-
// 0. Auto-Sanitize Session Files (Repairs pre-existing incomplete usage metadata)
|
|
114
|
-
try {
|
|
115
|
-
sanitizeSessionFiles();
|
|
116
|
-
} catch (e) {
|
|
117
|
-
kernelDebug(e);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
142
|
// 3. Slash Commands: /repomap, /engine, /lsp, /pi-docs
|
|
121
143
|
let activeTui: any = null;
|
|
144
|
+
let projectTrusted = false;
|
|
122
145
|
const configByWorkspace = new Map<
|
|
123
146
|
string,
|
|
124
147
|
ReturnType<typeof loadKernelConfig>
|
|
125
148
|
>();
|
|
126
149
|
const getConfig = (cwd: string) => {
|
|
127
150
|
const workspace = path.resolve(cwd);
|
|
128
|
-
|
|
151
|
+
const cacheKey = `${workspace}\0${projectTrusted}`;
|
|
152
|
+
let config = configByWorkspace.get(cacheKey);
|
|
129
153
|
if (!config) {
|
|
130
|
-
config = loadKernelConfig(workspace);
|
|
131
|
-
configByWorkspace.set(
|
|
154
|
+
config = loadKernelConfig(workspace, { projectTrusted });
|
|
155
|
+
configByWorkspace.set(cacheKey, config);
|
|
132
156
|
}
|
|
133
157
|
return config;
|
|
134
158
|
};
|
|
@@ -138,7 +162,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
138
162
|
let index = searchIndexes.get(workspace);
|
|
139
163
|
if (!index) {
|
|
140
164
|
const profile = getConfig(workspace).retrieval.default_profile;
|
|
141
|
-
index = new HybridSearchIndex(workspace, profile);
|
|
165
|
+
index = new HybridSearchIndex(workspace, profile, { projectTrusted });
|
|
142
166
|
searchIndexes.set(workspace, index);
|
|
143
167
|
}
|
|
144
168
|
return index;
|
|
@@ -278,7 +302,8 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
278
302
|
|
|
279
303
|
const applyConfigChanges = (cwd: string, ctx?: any) => {
|
|
280
304
|
const workspace = path.resolve(cwd);
|
|
281
|
-
configByWorkspace.delete(workspace);
|
|
305
|
+
configByWorkspace.delete(`${workspace}\0true`);
|
|
306
|
+
configByWorkspace.delete(`${workspace}\0false`);
|
|
282
307
|
const newConfig = getConfig(workspace);
|
|
283
308
|
const newProfile = newConfig.retrieval.default_profile;
|
|
284
309
|
|
|
@@ -310,6 +335,34 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
310
335
|
},
|
|
311
336
|
});
|
|
312
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
|
+
|
|
313
366
|
pi.registerCommand("pi-docs", {
|
|
314
367
|
description: "Toggle Pi documentation guidance in the system prompt",
|
|
315
368
|
getArgumentCompletions: (prefix: string) => {
|
|
@@ -681,9 +734,12 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
681
734
|
|
|
682
735
|
// Background workspace auto-indexer on session startup + setup integrated footer
|
|
683
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);
|
|
684
741
|
setupUnifiedFooter(ctx);
|
|
685
742
|
try {
|
|
686
|
-
const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
687
743
|
const index = getSearchIndex(cwd);
|
|
688
744
|
if (index.getEffectiveProfile() !== "off") {
|
|
689
745
|
triggerBackgroundIndexing(index, ctx, false);
|
|
@@ -716,28 +772,64 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
716
772
|
}
|
|
717
773
|
});
|
|
718
774
|
|
|
719
|
-
//
|
|
720
|
-
//
|
|
721
|
-
//
|
|
722
|
-
const
|
|
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) => {
|
|
723
782
|
const index = getSearchIndex(cwd);
|
|
724
|
-
|
|
783
|
+
await index.updateFile(filePath).catch((err) => {
|
|
725
784
|
kernelDebug(`Incremental updateFile error for ${filePath}: ${err}`);
|
|
726
785
|
});
|
|
727
786
|
};
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
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
|
+
}
|
|
832
|
+
};
|
|
741
833
|
|
|
742
834
|
// 9a. Block host writes before the host tool can create parent directories
|
|
743
835
|
// or overwrite the target. Bash read evidence is recorded after a successful
|
|
@@ -801,11 +893,16 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
801
893
|
let bashOutputComplete = true;
|
|
802
894
|
resultContent = (event.content || []).map((c: any) => {
|
|
803
895
|
if (c.type === "text" && typeof c.text === "string") {
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
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
|
+
});
|
|
809
906
|
if (clamped.truncated) {
|
|
810
907
|
bashOutputComplete = false;
|
|
811
908
|
return { ...c, text: clamped.text };
|
|
@@ -926,101 +1023,18 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
926
1023
|
}
|
|
927
1024
|
});
|
|
928
1025
|
|
|
929
|
-
// 10. Dynamic Runtime Context Injection (
|
|
930
|
-
//
|
|
931
|
-
//
|
|
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.
|
|
932
1030
|
let cachedRepoMap = "";
|
|
933
1031
|
let cachedRepoMapCwd = "";
|
|
934
1032
|
let lastRepoMapCheck = 0;
|
|
935
|
-
const sessionGroundingDone = new Set<string>();
|
|
936
|
-
const sessionGroundingText = new Map<string, string>();
|
|
937
|
-
|
|
938
|
-
function getPreFlightGrounding(cwd: string, sessionId: string): string {
|
|
939
|
-
if (sessionGroundingDone.has(sessionId)) {
|
|
940
|
-
return sessionGroundingText.get(sessionId) || "";
|
|
941
|
-
}
|
|
942
|
-
sessionGroundingDone.add(sessionId);
|
|
943
|
-
|
|
944
|
-
try {
|
|
945
|
-
const statusRaw = child_process.execFileSync(
|
|
946
|
-
"git",
|
|
947
|
-
["status", "--porcelain"],
|
|
948
|
-
{ cwd, encoding: "utf8", timeout: 1000, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024 },
|
|
949
|
-
).trim();
|
|
950
|
-
|
|
951
|
-
if (!statusRaw) {
|
|
952
|
-
sessionGroundingText.set(sessionId, "");
|
|
953
|
-
return "";
|
|
954
|
-
}
|
|
955
|
-
|
|
956
|
-
let diffRaw = "";
|
|
957
|
-
try {
|
|
958
|
-
diffRaw = child_process.execFileSync(
|
|
959
|
-
"git",
|
|
960
|
-
["diff", "HEAD", "-U3"],
|
|
961
|
-
{ cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] },
|
|
962
|
-
).trim();
|
|
963
|
-
} catch {
|
|
964
|
-
try {
|
|
965
|
-
diffRaw = child_process.execFileSync(
|
|
966
|
-
"git",
|
|
967
|
-
["diff", "-U3"],
|
|
968
|
-
{ cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] },
|
|
969
|
-
).trim();
|
|
970
|
-
} catch {
|
|
971
|
-
diffRaw = "";
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
if (!diffRaw && !statusRaw) {
|
|
976
|
-
sessionGroundingText.set(sessionId, "");
|
|
977
|
-
return "";
|
|
978
|
-
}
|
|
979
|
-
|
|
980
|
-
const statusLines = statusRaw.split("\n").slice(0, 8).join("\n");
|
|
981
|
-
const lines = diffRaw.split("\n");
|
|
982
|
-
const maxLines = 25;
|
|
983
|
-
const maxDiffBytes = 2048;
|
|
984
|
-
let clampedDiff = lines.slice(0, maxLines).join("\n");
|
|
985
|
-
let wasByteTruncated = false;
|
|
986
|
-
if (Buffer.byteLength(clampedDiff, "utf8") > maxDiffBytes) {
|
|
987
|
-
const buf = Buffer.from(clampedDiff, "utf8").subarray(0, maxDiffBytes);
|
|
988
|
-
clampedDiff = new TextDecoder("utf-8", { fatal: false }).decode(buf);
|
|
989
|
-
if (/[\uD800-\uDBFF]$/.test(clampedDiff)) {
|
|
990
|
-
clampedDiff = clampedDiff.slice(0, -1);
|
|
991
|
-
}
|
|
992
|
-
wasByteTruncated = true;
|
|
993
|
-
}
|
|
994
|
-
const truncatedNotice = lines.length > maxLines || wasByteTruncated
|
|
995
|
-
? `\n[... diff truncated; inspect test file via read() ...]`
|
|
996
|
-
: "";
|
|
997
|
-
|
|
998
|
-
const safeStatus = statusLines.replace(/```/g, "'''");
|
|
999
|
-
const safeDiff = clampedDiff.replace(/```/g, "'''");
|
|
1000
|
-
|
|
1001
|
-
const grounding = [
|
|
1002
|
-
"## Workspace Pre-Flight (Reproduction Status):",
|
|
1003
|
-
"<!-- Passive environment context; not instruction -->",
|
|
1004
|
-
"```git-status",
|
|
1005
|
-
safeStatus,
|
|
1006
|
-
"```",
|
|
1007
|
-
safeDiff ? `\`\`\`diff\n${safeDiff}\n\`\`\`${truncatedNotice}` : "",
|
|
1008
|
-
].filter(Boolean).join("\n");
|
|
1009
|
-
|
|
1010
|
-
sessionGroundingText.set(sessionId, grounding);
|
|
1011
|
-
return grounding;
|
|
1012
|
-
} catch (error) {
|
|
1013
|
-
kernelDebug(error);
|
|
1014
|
-
sessionGroundingText.set(sessionId, "");
|
|
1015
|
-
return "";
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
1033
|
|
|
1019
1034
|
pi.on("before_agent_start", async (event: any, ctx: any) => {
|
|
1020
1035
|
const now = Date.now();
|
|
1021
1036
|
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
1022
1037
|
const kernelConfig = getConfig(currentCwd);
|
|
1023
|
-
const sessionId = getSessionId(ctx);
|
|
1024
1038
|
|
|
1025
1039
|
let shouldInjectMap = false;
|
|
1026
1040
|
// Disabled automatic AST repo map injection to evaluate prompt token footprint and latency
|
|
@@ -1041,10 +1055,8 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
1041
1055
|
lastRepoMapCheck = now;
|
|
1042
1056
|
}
|
|
1043
1057
|
|
|
1044
|
-
const preFlightDiff = getPreFlightGrounding(currentCwd, sessionId);
|
|
1045
1058
|
const runtimeParts = [
|
|
1046
1059
|
cachedRepoMap ? `## Available Repository Context:\n${cachedRepoMap}` : "",
|
|
1047
|
-
preFlightDiff,
|
|
1048
1060
|
].filter(Boolean);
|
|
1049
1061
|
const runtimeContext = runtimeParts.length > 0 ? `\n${runtimeParts.join("\n\n")}\n` : "";
|
|
1050
1062
|
|
|
@@ -1052,8 +1064,16 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
1052
1064
|
const systemPrompt = piDocsEnabled(ctx)
|
|
1053
1065
|
? basePrompt
|
|
1054
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
|
+
}
|
|
1055
1075
|
const guidance = kernelConfig.instructions.enabled
|
|
1056
|
-
? loadKernelGuidance()
|
|
1076
|
+
? loadKernelGuidance(toolCollisions, promptToolNames)
|
|
1057
1077
|
: "";
|
|
1058
1078
|
const guidedPrompt = appendKernelGuidance(systemPrompt, guidance);
|
|
1059
1079
|
const shouldAppendRuntime = runtimeContext && !guidedPrompt.includes(runtimeContext.trim());
|