@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
package/src/lsp/lsp_manager.ts
CHANGED
|
@@ -117,7 +117,7 @@ export class LspManager {
|
|
|
117
117
|
if (inFlight) return inFlight;
|
|
118
118
|
|
|
119
119
|
// Resolve installed executable
|
|
120
|
-
const resolved = resolveLspServer(langKey);
|
|
120
|
+
const resolved = resolveLspServer(langKey, [], [rootDir]);
|
|
121
121
|
if (!resolved) return null;
|
|
122
122
|
|
|
123
123
|
const client = new StdioLspClient(clientId, {
|
package/src/lsp/lsp_registry.ts
CHANGED
|
@@ -7,28 +7,23 @@ import { getPiHomeDir, loadKernelConfig, saveGlobalKernelConfig } from "../confi
|
|
|
7
7
|
import { kernelDebug } from "../safety/kernel_debug";
|
|
8
8
|
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
// Confined to extensions/agent-kernel/bin/lsp by default
|
|
12
|
-
const candidate1 = path.join(__dirname, "..", "..", "bin", "lsp");
|
|
13
|
-
const candidate2 = path.join(process.cwd(), "bin", "lsp");
|
|
14
|
-
const candidate = fs.existsSync(candidate1) ? candidate1 : fs.existsSync(candidate2) ? candidate2 : candidate1;
|
|
15
|
-
|
|
16
|
-
// Test write permission; if read-only (e.g. system-wide npm global install), fall back to ~/.pi/lsp/bin
|
|
10
|
+
function usableDirectory(candidate: string): string | null {
|
|
17
11
|
try {
|
|
18
|
-
fs.
|
|
19
|
-
|
|
20
|
-
fs.
|
|
21
|
-
fs.
|
|
22
|
-
return candidate;
|
|
12
|
+
if (fs.lstatSync(candidate).isSymbolicLink()) return null;
|
|
13
|
+
if (!fs.statSync(candidate).isDirectory()) return null;
|
|
14
|
+
fs.accessSync(candidate, fs.constants.W_OK);
|
|
15
|
+
return fs.realpathSync(candidate);
|
|
23
16
|
} catch {
|
|
24
|
-
|
|
25
|
-
try {
|
|
26
|
-
fs.mkdirSync(userFallback, { recursive: true });
|
|
27
|
-
} catch {}
|
|
28
|
-
return userFallback;
|
|
17
|
+
return null;
|
|
29
18
|
}
|
|
30
19
|
}
|
|
31
20
|
|
|
21
|
+
export function getExtensionLspBinDir(): string {
|
|
22
|
+
const packageDir = path.join(__dirname, "..", "..", "bin", "lsp");
|
|
23
|
+
const userDir = path.join(getPiHomeDir(), "lsp", "bin");
|
|
24
|
+
return usableDirectory(packageDir) || usableDirectory(userDir) || path.resolve(userDir);
|
|
25
|
+
}
|
|
26
|
+
|
|
32
27
|
export const PI_LSP_BIN_DIR = getExtensionLspBinDir();
|
|
33
28
|
|
|
34
29
|
export const PI_LSP_CONFIG_FILE = path.join(
|
|
@@ -106,7 +101,7 @@ export const LSP_SERVERS: Record<string, LspServerConfig> = {
|
|
|
106
101
|
{ bin: "oxc_language_server", args: [] },
|
|
107
102
|
{ bin: "biome", args: ["lsp-proxy"] },
|
|
108
103
|
],
|
|
109
|
-
installHint: "
|
|
104
|
+
installHint: "Run /lsp install typescript (pins vtsls 0.3.0 and TypeScript 7.0.2)",
|
|
110
105
|
},
|
|
111
106
|
python: {
|
|
112
107
|
languageId: "python",
|
|
@@ -127,21 +122,21 @@ export const LSP_SERVERS: Record<string, LspServerConfig> = {
|
|
|
127
122
|
{ bin: "pylyzer", args: ["--server"] },
|
|
128
123
|
{ bin: "pylsp", args: [] },
|
|
129
124
|
],
|
|
130
|
-
installHint: "
|
|
125
|
+
installHint: "Run /lsp install python (pins ty 0.0.83 with Pyright 1.1.414 fallback)",
|
|
131
126
|
},
|
|
132
127
|
rust: {
|
|
133
128
|
languageId: "rust",
|
|
134
129
|
extensions: [".rs"],
|
|
135
130
|
markers: ["Cargo.toml", "Cargo.lock"],
|
|
136
131
|
commands: [{ bin: "rust-analyzer", args: [] }],
|
|
137
|
-
installHint: "rustup
|
|
132
|
+
installHint: "Install rust-analyzer through a reviewed rustup toolchain, then run /lsp install rust",
|
|
138
133
|
},
|
|
139
134
|
go: {
|
|
140
135
|
languageId: "go",
|
|
141
136
|
extensions: [".go"],
|
|
142
137
|
markers: ["go.mod", "go.work"],
|
|
143
138
|
commands: [{ bin: "gopls", args: [] }],
|
|
144
|
-
installHint: "
|
|
139
|
+
installHint: "Run /lsp install go (pins gopls v0.23.0)",
|
|
145
140
|
},
|
|
146
141
|
cpp: {
|
|
147
142
|
languageId: "cpp",
|
|
@@ -149,14 +144,14 @@ export const LSP_SERVERS: Record<string, LspServerConfig> = {
|
|
|
149
144
|
markers: ["compile_commands.json", "CMakeLists.txt", ".clangd"],
|
|
150
145
|
commands: [{ bin: "clangd", args: ["--background-index", "--clang-tidy"] }],
|
|
151
146
|
installHint:
|
|
152
|
-
"Install LLVM
|
|
147
|
+
"Install reviewed LLVM/clangd 23.1.2, then run /lsp install cpp",
|
|
153
148
|
},
|
|
154
149
|
zig: {
|
|
155
150
|
languageId: "zig",
|
|
156
151
|
extensions: [".zig"],
|
|
157
152
|
markers: ["build.zig"],
|
|
158
153
|
commands: [{ bin: "zls", args: [] }],
|
|
159
|
-
installHint: "
|
|
154
|
+
installHint: "Install reviewed ZLS 0.16.0, then run /lsp install zig",
|
|
160
155
|
},
|
|
161
156
|
elixir: {
|
|
162
157
|
languageId: "elixir",
|
|
@@ -178,7 +173,7 @@ export const LSP_SERVERS: Record<string, LspServerConfig> = {
|
|
|
178
173
|
{ bin: "csharp-ls", args: [] },
|
|
179
174
|
{ bin: "OmniSharp", args: ["-lsp"] },
|
|
180
175
|
],
|
|
181
|
-
installHint: "
|
|
176
|
+
installHint: "Run /lsp install csharp (pins csharp-ls 0.28.0)",
|
|
182
177
|
},
|
|
183
178
|
ruby: {
|
|
184
179
|
languageId: "ruby",
|
|
@@ -188,14 +183,14 @@ export const LSP_SERVERS: Record<string, LspServerConfig> = {
|
|
|
188
183
|
{ bin: "ruby-lsp", args: ["--stdio"] },
|
|
189
184
|
{ bin: "solargraph", args: ["stdio"] },
|
|
190
185
|
],
|
|
191
|
-
installHint: "
|
|
186
|
+
installHint: "Run /lsp install ruby (pins ruby-lsp 0.26.11)",
|
|
192
187
|
},
|
|
193
188
|
lua: {
|
|
194
189
|
languageId: "lua",
|
|
195
190
|
extensions: [".lua"],
|
|
196
191
|
markers: [".luarc.json", ".luacheckrc"],
|
|
197
192
|
commands: [{ bin: "lua-language-server", args: [] }],
|
|
198
|
-
installHint: "Install
|
|
193
|
+
installHint: "Install reviewed Lua Language Server 3.19.1, then run /lsp install lua",
|
|
199
194
|
},
|
|
200
195
|
java: {
|
|
201
196
|
languageId: "java",
|
|
@@ -232,28 +227,28 @@ export const LSP_SERVERS: Record<string, LspServerConfig> = {
|
|
|
232
227
|
{ bin: "intelephense", args: ["--stdio"] },
|
|
233
228
|
{ bin: "phpactor", args: ["language-server"] },
|
|
234
229
|
],
|
|
235
|
-
installHint: "
|
|
230
|
+
installHint: "Run /lsp install php (pins Intelephense 1.18.5)",
|
|
236
231
|
},
|
|
237
232
|
shell: {
|
|
238
233
|
languageId: "shellscript",
|
|
239
234
|
extensions: [".sh", ".bash", ".zsh"],
|
|
240
235
|
markers: [".shellcheckrc"],
|
|
241
236
|
commands: [{ bin: "bash-language-server", args: ["start"] }],
|
|
242
|
-
installHint: "
|
|
237
|
+
installHint: "Run /lsp install shell (pins bash-language-server 5.8.1)",
|
|
243
238
|
},
|
|
244
239
|
typst: {
|
|
245
240
|
languageId: "typst",
|
|
246
241
|
extensions: [".typ"],
|
|
247
242
|
markers: [],
|
|
248
243
|
commands: [{ bin: "tinymist", args: [] }],
|
|
249
|
-
installHint: "
|
|
244
|
+
installHint: "Run /lsp install typst (pins Tinymist 0.15.2)",
|
|
250
245
|
},
|
|
251
246
|
latex: {
|
|
252
247
|
languageId: "latex",
|
|
253
248
|
extensions: [".tex", ".latex", ".bib"],
|
|
254
249
|
markers: [".latexmkrc", "latexmkrc"],
|
|
255
250
|
commands: [{ bin: "texlab", args: [] }],
|
|
256
|
-
installHint: "
|
|
251
|
+
installHint: "Run /lsp install latex (pins Texlab 4.3.2)",
|
|
257
252
|
},
|
|
258
253
|
markdown: {
|
|
259
254
|
languageId: "markdown",
|
|
@@ -264,7 +259,7 @@ export const LSP_SERVERS: Record<string, LspServerConfig> = {
|
|
|
264
259
|
{ bin: "markdown-oxide", args: [] },
|
|
265
260
|
],
|
|
266
261
|
installHint:
|
|
267
|
-
"
|
|
262
|
+
"Install reviewed Marksman 2026-02-08, then run /lsp install markdown",
|
|
268
263
|
},
|
|
269
264
|
protobuf: {
|
|
270
265
|
languageId: "proto",
|
|
@@ -274,7 +269,7 @@ export const LSP_SERVERS: Record<string, LspServerConfig> = {
|
|
|
274
269
|
{ bin: "protols", args: [] },
|
|
275
270
|
{ bin: "buf", args: ["beta", "lsp"] },
|
|
276
271
|
],
|
|
277
|
-
installHint: "
|
|
272
|
+
installHint: "Run /lsp install protobuf (pins Protols 0.14.1)",
|
|
278
273
|
},
|
|
279
274
|
sql: {
|
|
280
275
|
languageId: "sql",
|
|
@@ -286,7 +281,7 @@ export const LSP_SERVERS: Record<string, LspServerConfig> = {
|
|
|
286
281
|
{ bin: "sql-language-server", args: ["up", "--method", "stdio"] },
|
|
287
282
|
],
|
|
288
283
|
installHint:
|
|
289
|
-
"
|
|
284
|
+
"Run /lsp install sql (pins sqls v0.2.48)",
|
|
290
285
|
},
|
|
291
286
|
nix: {
|
|
292
287
|
languageId: "nix",
|
|
@@ -307,7 +302,7 @@ export const LSP_SERVERS: Record<string, LspServerConfig> = {
|
|
|
307
302
|
{ bin: "vscode-html-language-server", args: ["--stdio"] },
|
|
308
303
|
],
|
|
309
304
|
installHint:
|
|
310
|
-
"
|
|
305
|
+
"Run /lsp install html (pins vscode-langservers-extracted 4.10.0)",
|
|
311
306
|
},
|
|
312
307
|
json: {
|
|
313
308
|
languageId: "json",
|
|
@@ -318,28 +313,28 @@ export const LSP_SERVERS: Record<string, LspServerConfig> = {
|
|
|
318
313
|
{ bin: "vscode-json-language-server", args: ["--stdio"] },
|
|
319
314
|
],
|
|
320
315
|
installHint:
|
|
321
|
-
"
|
|
316
|
+
"Run /lsp install json (pins Biome 2.5.14 with vscode fallback)",
|
|
322
317
|
},
|
|
323
318
|
yaml: {
|
|
324
319
|
languageId: "yaml",
|
|
325
320
|
extensions: [".yaml", ".yml"],
|
|
326
321
|
markers: [],
|
|
327
322
|
commands: [{ bin: "yaml-language-server", args: ["--stdio"] }],
|
|
328
|
-
installHint: "
|
|
323
|
+
installHint: "Run /lsp install yaml (pins yaml-language-server 1.24.0)",
|
|
329
324
|
},
|
|
330
325
|
toml: {
|
|
331
326
|
languageId: "toml",
|
|
332
327
|
extensions: [".toml"],
|
|
333
328
|
markers: ["Cargo.toml", "pyproject.toml"],
|
|
334
329
|
commands: [{ bin: "taplo", args: ["lsp", "stdio"] }],
|
|
335
|
-
installHint: "
|
|
330
|
+
installHint: "Run /lsp install toml (pins Taplo CLI 0.10.0)",
|
|
336
331
|
},
|
|
337
332
|
docker: {
|
|
338
333
|
languageId: "dockerfile",
|
|
339
334
|
extensions: ["Dockerfile", ".dockerfile"],
|
|
340
335
|
markers: ["Dockerfile", "compose.yaml", "docker-compose.yml"],
|
|
341
336
|
commands: [{ bin: "docker-langserver", args: ["--stdio"] }],
|
|
342
|
-
installHint: "
|
|
337
|
+
installHint: "Run /lsp install docker (pins dockerfile-language-server-nodejs 0.15.0)",
|
|
343
338
|
},
|
|
344
339
|
terraform: {
|
|
345
340
|
languageId: "terraform",
|
|
@@ -378,12 +373,45 @@ function isBinaryUsable(fullPath: string, binName: string): boolean {
|
|
|
378
373
|
/**
|
|
379
374
|
* Check if an executable exists in system PATH or ~/.pi/lsp/bin
|
|
380
375
|
*/
|
|
376
|
+
function canonicalDirectory(directory: string): string | null {
|
|
377
|
+
try {
|
|
378
|
+
return fs.realpathSync(path.resolve(directory));
|
|
379
|
+
} catch {
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function pathContains(root: string, target: string): boolean {
|
|
385
|
+
const relative = path.relative(root, target);
|
|
386
|
+
return relative === "" || (
|
|
387
|
+
relative !== ".." &&
|
|
388
|
+
!relative.startsWith(`..${path.sep}`) &&
|
|
389
|
+
!path.isAbsolute(relative)
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function isForbiddenDirectory(directory: string, forbiddenRoots: string[]): boolean {
|
|
394
|
+
const canonical = canonicalDirectory(directory);
|
|
395
|
+
if (!canonical) return true;
|
|
396
|
+
return forbiddenRoots.some((root) => {
|
|
397
|
+
const forbidden = canonicalDirectory(root);
|
|
398
|
+
return forbidden ? pathContains(forbidden, canonical) : false;
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
381
402
|
export function findExecutable(
|
|
382
403
|
binName: string,
|
|
383
404
|
extraDirs: string[] = [],
|
|
405
|
+
forbiddenRoots: string[] = [],
|
|
384
406
|
): string | null {
|
|
385
|
-
|
|
386
|
-
|
|
407
|
+
const cacheKey = JSON.stringify([
|
|
408
|
+
binName,
|
|
409
|
+
extraDirs.map((dir) => path.resolve(dir)),
|
|
410
|
+
forbiddenRoots.map((dir) => path.resolve(dir)),
|
|
411
|
+
process.platform,
|
|
412
|
+
]);
|
|
413
|
+
if (executableCache.has(cacheKey)) {
|
|
414
|
+
return executableCache.get(cacheKey) || null;
|
|
387
415
|
}
|
|
388
416
|
|
|
389
417
|
const isWindows = process.platform === "win32";
|
|
@@ -436,7 +464,7 @@ export function findExecutable(
|
|
|
436
464
|
|
|
437
465
|
// 1. Direct path check in extraDirs and ~/.pi/lsp/bin
|
|
438
466
|
for (const dir of searchDirs) {
|
|
439
|
-
if (!dir || !fs.existsSync(dir)) continue;
|
|
467
|
+
if (!dir || !fs.existsSync(dir) || isForbiddenDirectory(dir, forbiddenRoots)) continue;
|
|
440
468
|
const candidates = isWindows
|
|
441
469
|
? [`${binName}.cmd`, `${binName}.exe`, `${binName}.bat`, binName]
|
|
442
470
|
: [binName];
|
|
@@ -448,7 +476,7 @@ export function findExecutable(
|
|
|
448
476
|
if (!isBinaryUsable(fullPath, binName)) {
|
|
449
477
|
continue;
|
|
450
478
|
}
|
|
451
|
-
executableCache.set(
|
|
479
|
+
executableCache.set(cacheKey, fullPath);
|
|
452
480
|
return fullPath;
|
|
453
481
|
}
|
|
454
482
|
} catch (e) {
|
|
@@ -467,7 +495,7 @@ export function findExecutable(
|
|
|
467
495
|
.filter(Boolean);
|
|
468
496
|
|
|
469
497
|
for (const dir of pathDirs) {
|
|
470
|
-
if (!dir || !fs.existsSync(dir)) continue;
|
|
498
|
+
if (!dir || !fs.existsSync(dir) || isForbiddenDirectory(dir, forbiddenRoots)) continue;
|
|
471
499
|
const candidates = isWindows
|
|
472
500
|
? [
|
|
473
501
|
...pathext.map((ext) => `${binName}${ext}`),
|
|
@@ -487,7 +515,7 @@ export function findExecutable(
|
|
|
487
515
|
if (!isBinaryUsable(fullPath, binName)) {
|
|
488
516
|
continue;
|
|
489
517
|
}
|
|
490
|
-
executableCache.set(
|
|
518
|
+
executableCache.set(cacheKey, fullPath);
|
|
491
519
|
return fullPath;
|
|
492
520
|
}
|
|
493
521
|
}
|
|
@@ -497,7 +525,7 @@ export function findExecutable(
|
|
|
497
525
|
}
|
|
498
526
|
}
|
|
499
527
|
|
|
500
|
-
executableCache.set(
|
|
528
|
+
executableCache.set(cacheKey, null);
|
|
501
529
|
return null;
|
|
502
530
|
}
|
|
503
531
|
|
|
@@ -514,6 +542,7 @@ export function clearExecutableCache(): void {
|
|
|
514
542
|
export function resolveLspServer(
|
|
515
543
|
languageOrExt: string,
|
|
516
544
|
extraDirs: string[] = [],
|
|
545
|
+
forbiddenRoots: string[] = [],
|
|
517
546
|
): {
|
|
518
547
|
binPath: string;
|
|
519
548
|
command: string;
|
|
@@ -555,7 +584,7 @@ export function resolveLspServer(
|
|
|
555
584
|
|
|
556
585
|
// Try each configured command in priority order
|
|
557
586
|
for (const cmd of config.commands) {
|
|
558
|
-
const binPath = findExecutable(cmd.bin, extraDirs);
|
|
587
|
+
const binPath = findExecutable(cmd.bin, extraDirs, forbiddenRoots);
|
|
559
588
|
if (binPath) {
|
|
560
589
|
return {
|
|
561
590
|
binPath,
|
|
@@ -122,7 +122,7 @@ export class BM25Engine {
|
|
|
122
122
|
public removeFile(filePath: string): void {
|
|
123
123
|
const prefix = `${filePath}:`;
|
|
124
124
|
for (const chunkId of Array.from(this.docTermFreqs.keys())) {
|
|
125
|
-
if (chunkId.startsWith(prefix)
|
|
125
|
+
if (chunkId.startsWith(prefix)) {
|
|
126
126
|
const tfMap = this.docTermFreqs.get(chunkId);
|
|
127
127
|
if (tfMap) {
|
|
128
128
|
for (const term of tfMap.keys()) {
|
|
@@ -202,7 +202,10 @@ export class BM25Engine {
|
|
|
202
202
|
|
|
203
203
|
return Array.from(scores.entries())
|
|
204
204
|
.map(([chunkId, data]) => ({ chunkId, score: data.score, matches: data.matches }))
|
|
205
|
-
.sort((a, b) =>
|
|
205
|
+
.sort((a, b) => {
|
|
206
|
+
if (b.score !== a.score) return b.score - a.score;
|
|
207
|
+
return a.chunkId < b.chunkId ? -1 : a.chunkId > b.chunkId ? 1 : 0;
|
|
208
|
+
})
|
|
206
209
|
.slice(0, limit);
|
|
207
210
|
}
|
|
208
211
|
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import * as crypto from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { getPiHomeDir } from "../config/kernel_config";
|
|
5
|
+
|
|
6
|
+
function isWithin(root: string, target: string): boolean {
|
|
7
|
+
const relative = path.relative(root, target);
|
|
8
|
+
return relative === "" || (
|
|
9
|
+
relative !== ".." &&
|
|
10
|
+
!relative.startsWith(`..${path.sep}`) &&
|
|
11
|
+
!path.isAbsolute(relative)
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function ensureDirectoryNoLinks(trustedRoot: string, target: string): string {
|
|
16
|
+
const canonicalRoot = fs.realpathSync(trustedRoot);
|
|
17
|
+
const relative = path.relative(canonicalRoot, target);
|
|
18
|
+
if (!isWithin(canonicalRoot, target)) {
|
|
19
|
+
throw new Error(`Search cache path escapes trusted root: ${target}`);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let current = canonicalRoot;
|
|
23
|
+
for (const segment of relative.split(path.sep).filter(Boolean)) {
|
|
24
|
+
current = path.join(current, segment);
|
|
25
|
+
try {
|
|
26
|
+
const stat = fs.lstatSync(current);
|
|
27
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
28
|
+
throw new Error(`Search cache path contains a link or non-directory: ${current}`);
|
|
29
|
+
}
|
|
30
|
+
} catch (error: any) {
|
|
31
|
+
if (error?.code !== "ENOENT") throw error;
|
|
32
|
+
try {
|
|
33
|
+
fs.mkdirSync(current);
|
|
34
|
+
} catch (mkdirError: any) {
|
|
35
|
+
if (mkdirError?.code !== "EEXIST") throw mkdirError;
|
|
36
|
+
}
|
|
37
|
+
const stat = fs.lstatSync(current);
|
|
38
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
39
|
+
throw new Error(`Search cache path changed to a link or non-directory: ${current}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const canonicalTarget = fs.realpathSync(current);
|
|
45
|
+
if (!isWithin(canonicalRoot, canonicalTarget)) {
|
|
46
|
+
throw new Error(`Resolved search cache path escapes trusted root: ${canonicalTarget}`);
|
|
47
|
+
}
|
|
48
|
+
return canonicalTarget;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function getSearchCacheDir(cwd: string): string {
|
|
52
|
+
const workspace = fs.realpathSync(path.resolve(cwd));
|
|
53
|
+
const workspaceId = crypto
|
|
54
|
+
.createHash("sha256")
|
|
55
|
+
.update(process.platform === "win32" ? workspace.toLowerCase() : workspace)
|
|
56
|
+
.digest("hex")
|
|
57
|
+
.slice(0, 24);
|
|
58
|
+
const configuredPiRoot = path.resolve(getPiHomeDir());
|
|
59
|
+
fs.mkdirSync(configuredPiRoot, { recursive: true });
|
|
60
|
+
const trustedPiRoot = fs.realpathSync(configuredPiRoot);
|
|
61
|
+
const trustedRoot = ensureDirectoryNoLinks(
|
|
62
|
+
trustedPiRoot,
|
|
63
|
+
path.join(trustedPiRoot, "cache", "agent-kernel", "search"),
|
|
64
|
+
);
|
|
65
|
+
return ensureDirectoryNoLinks(
|
|
66
|
+
trustedRoot,
|
|
67
|
+
path.join(trustedRoot, workspaceId),
|
|
68
|
+
);
|
|
69
|
+
}
|
|
@@ -21,17 +21,13 @@ export interface CodeChunk {
|
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
export const SUPPORTED_EXTENSIONS = new Set([
|
|
24
|
-
".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".go", ".c", ".cpp", ".h", ".hpp", ".java", ".cs", ".rb", ".php", ".swift", ".sh", ".bash", ".sql"
|
|
24
|
+
".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".go", ".c", ".cpp", ".h", ".hpp", ".java", ".cs", ".rb", ".php", ".swift", ".sh", ".bash", ".sql"
|
|
25
25
|
]);
|
|
26
26
|
|
|
27
27
|
export const IGNORED_DIRS = DEFAULT_IGNORED_DIRS;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
export const
|
|
31
|
-
|
|
32
|
-
export function isProseFilePath(filePath: string): boolean {
|
|
33
|
-
return PROSE_EXTENSIONS.has(path.extname(filePath).toLowerCase());
|
|
34
|
-
}
|
|
28
|
+
export const MAX_INDEX_FILE_BYTES = 2 * 1024 * 1024;
|
|
29
|
+
export const MAX_INDEX_WORKSPACE_BYTES = 20 * 1024 * 1024;
|
|
30
|
+
export const MAX_INDEX_CHUNKS = 10_000;
|
|
35
31
|
|
|
36
32
|
/**
|
|
37
33
|
* Compute SHA-256 hash of a string.
|
|
@@ -45,6 +41,13 @@ export function computeHash(content: string): string {
|
|
|
45
41
|
*/
|
|
46
42
|
export function chunkFile(rootDir: string, filePath: string, content?: string): CodeChunk[] {
|
|
47
43
|
const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(rootDir, filePath);
|
|
44
|
+
const ext = path.extname(absPath).toLowerCase();
|
|
45
|
+
if (!SUPPORTED_EXTENSIONS.has(ext)) return [];
|
|
46
|
+
try {
|
|
47
|
+
if (fs.statSync(absPath).size > MAX_INDEX_FILE_BYTES) return [];
|
|
48
|
+
} catch {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
48
51
|
const relPath = path.relative(rootDir, absPath).replace(/\\/g, "/");
|
|
49
52
|
|
|
50
53
|
let fileContent = content;
|
|
@@ -55,11 +58,11 @@ export function chunkFile(rootDir: string, filePath: string, content?: string):
|
|
|
55
58
|
return [];
|
|
56
59
|
}
|
|
57
60
|
}
|
|
61
|
+
if (Buffer.byteLength(fileContent, "utf8") > MAX_INDEX_FILE_BYTES) return [];
|
|
58
62
|
|
|
59
63
|
const lines = fileContent.split("\n");
|
|
60
64
|
if (lines.length === 0) return [];
|
|
61
65
|
|
|
62
|
-
const ext = path.extname(absPath).toLowerCase();
|
|
63
66
|
const chunks: CodeChunk[] = [];
|
|
64
67
|
|
|
65
68
|
// 1. Extract AST symbols using extractFileTags
|
|
@@ -16,6 +16,9 @@ import { parseToml } from "../config/toml";
|
|
|
16
16
|
|
|
17
17
|
export type SearchProfile = "lean" | "hybrid" | "full" | "off" | "auto";
|
|
18
18
|
|
|
19
|
+
export const EMBEDDING_MODEL_ID = "nomic-ai/nomic-embed-text-v1.5";
|
|
20
|
+
export const EMBEDDING_MODEL_REVISION = "e9b6763023c676ca8431644204f50c2b100d9aab";
|
|
21
|
+
|
|
19
22
|
export interface SearchConfig {
|
|
20
23
|
profile: SearchProfile;
|
|
21
24
|
effectiveProfile: "lean" | "hybrid" | "full" | "off";
|
|
@@ -24,6 +27,7 @@ export interface SearchConfig {
|
|
|
24
27
|
vectorSimilarityThreshold: number;
|
|
25
28
|
numThreads: number;
|
|
26
29
|
modelId: string;
|
|
30
|
+
modelRevision: string;
|
|
27
31
|
dtype: "q8" | "fp32" | "fp16";
|
|
28
32
|
batchSize: number;
|
|
29
33
|
sleepBetweenBatchesMs: number;
|
|
@@ -51,9 +55,12 @@ export function detectBestProfile(): "lean" | "hybrid" | "full" {
|
|
|
51
55
|
/**
|
|
52
56
|
* Load persisted search settings or default to config.toml setting.
|
|
53
57
|
*/
|
|
54
|
-
export function loadPersistedProfile(
|
|
55
|
-
|
|
56
|
-
|
|
58
|
+
export function loadPersistedProfile(
|
|
59
|
+
cwd?: string,
|
|
60
|
+
projectTrusted = false,
|
|
61
|
+
): SearchProfile {
|
|
62
|
+
// 1. Explicit trusted project-local config (.pi/config.toml only)
|
|
63
|
+
const projectPath = cwd && projectTrusted ? getProjectConfigPath(cwd) : null;
|
|
57
64
|
if (projectPath && fs.existsSync(projectPath)) {
|
|
58
65
|
try {
|
|
59
66
|
const raw = parseToml(fs.readFileSync(projectPath, "utf-8"));
|
|
@@ -129,8 +136,9 @@ export function savePersistedProfile(profile: SearchProfile, cwd?: string): void
|
|
|
129
136
|
export function getSearchConfig(
|
|
130
137
|
requestedProfile?: SearchProfile,
|
|
131
138
|
cwd?: string,
|
|
139
|
+
projectTrusted = false,
|
|
132
140
|
): SearchConfig {
|
|
133
|
-
const profile = requestedProfile || loadPersistedProfile(cwd);
|
|
141
|
+
const profile = requestedProfile || loadPersistedProfile(cwd, projectTrusted);
|
|
134
142
|
const effectiveProfile: "lean" | "hybrid" | "full" | "off" =
|
|
135
143
|
profile === "auto" ? detectBestProfile() : profile || "lean";
|
|
136
144
|
|
|
@@ -143,7 +151,8 @@ export function getSearchConfig(
|
|
|
143
151
|
matryoshkaDim: 0,
|
|
144
152
|
vectorSimilarityThreshold: 0,
|
|
145
153
|
numThreads: 1,
|
|
146
|
-
modelId:
|
|
154
|
+
modelId: EMBEDDING_MODEL_ID,
|
|
155
|
+
modelRevision: EMBEDDING_MODEL_REVISION,
|
|
147
156
|
dtype: "q8",
|
|
148
157
|
batchSize: 1,
|
|
149
158
|
sleepBetweenBatchesMs: 0,
|
|
@@ -160,7 +169,8 @@ export function getSearchConfig(
|
|
|
160
169
|
matryoshkaDim: 0,
|
|
161
170
|
vectorSimilarityThreshold: 0,
|
|
162
171
|
numThreads: 1,
|
|
163
|
-
modelId:
|
|
172
|
+
modelId: EMBEDDING_MODEL_ID,
|
|
173
|
+
modelRevision: EMBEDDING_MODEL_REVISION,
|
|
164
174
|
dtype: "q8",
|
|
165
175
|
batchSize: 1,
|
|
166
176
|
sleepBetweenBatchesMs: 0,
|
|
@@ -179,7 +189,8 @@ export function getSearchConfig(
|
|
|
179
189
|
// while cleanly blocking off-topic noise (unrelated queries score ~0.48-0.52).
|
|
180
190
|
vectorSimilarityThreshold: 0.55,
|
|
181
191
|
numThreads: 1,
|
|
182
|
-
modelId:
|
|
192
|
+
modelId: EMBEDDING_MODEL_ID,
|
|
193
|
+
modelRevision: EMBEDDING_MODEL_REVISION,
|
|
183
194
|
dtype: "q8",
|
|
184
195
|
batchSize: 1,
|
|
185
196
|
sleepBetweenBatchesMs: 80, // 80ms sleep between chunk batches to prevent CPU starvation
|
|
@@ -196,7 +207,8 @@ export function getSearchConfig(
|
|
|
196
207
|
// Empirically calibrated floor for 768-dim embeddings.
|
|
197
208
|
vectorSimilarityThreshold: 0.55,
|
|
198
209
|
numThreads: Math.min(2, Math.max(1, Math.floor(os.cpus().length / 2))),
|
|
199
|
-
modelId:
|
|
210
|
+
modelId: EMBEDDING_MODEL_ID,
|
|
211
|
+
modelRevision: EMBEDDING_MODEL_REVISION,
|
|
200
212
|
dtype: "q8",
|
|
201
213
|
batchSize: 2,
|
|
202
214
|
sleepBetweenBatchesMs: 50,
|
|
@@ -108,22 +108,13 @@ export class LocalEmbedder {
|
|
|
108
108
|
for (const dir of candidateDirs) {
|
|
109
109
|
if (!fs.existsSync(dir)) continue;
|
|
110
110
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
if (
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const snapshots = path.join(dir, "snapshots");
|
|
119
|
-
if (fs.existsSync(snapshots)) {
|
|
120
|
-
const files = fs.readdirSync(snapshots);
|
|
121
|
-
if (files.length > 0) return true;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
const rootFiles = fs.readdirSync(dir);
|
|
125
|
-
if (rootFiles.some((f) => f.endsWith(".onnx") || f === "config.json")) {
|
|
126
|
-
return true;
|
|
111
|
+
for (const revisionDir of [
|
|
112
|
+
path.join(dir, this.config.modelRevision),
|
|
113
|
+
path.join(dir, "snapshots", this.config.modelRevision),
|
|
114
|
+
]) {
|
|
115
|
+
if (fs.existsSync(revisionDir) && fs.readdirSync(revisionDir).length > 0) {
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
127
118
|
}
|
|
128
119
|
}
|
|
129
120
|
} catch (e) {
|
|
@@ -175,6 +166,7 @@ export class LocalEmbedder {
|
|
|
175
166
|
this.layerNormFn = layer_norm;
|
|
176
167
|
|
|
177
168
|
this.extractor = await pipeline("feature-extraction", this.config.modelId, {
|
|
169
|
+
revision: this.config.modelRevision,
|
|
178
170
|
dtype: this.config.dtype,
|
|
179
171
|
progress_callback: (p: any) => {
|
|
180
172
|
if (p.status === "progress" && p.total && p.loaded) {
|