@floydous/pi-agent-kernel 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/README.md +108 -0
- package/config.toml +24 -0
- package/docs/README.md +22 -0
- package/docs/architecture.md +40 -0
- package/docs/configuration.md +43 -0
- package/docs/editing-and-verification.md +41 -0
- package/docs/lsp.md +31 -0
- package/docs/retrieval.md +42 -0
- package/docs/testing.md +32 -0
- package/package.json +48 -0
- package/src/config/index.ts +2 -0
- package/src/config/kernel_config.ts +218 -0
- package/src/config/toml.ts +237 -0
- package/src/context/session_repair.ts +99 -0
- package/src/dedup/content_store.ts +365 -0
- package/src/dedup/recall_tool.ts +157 -0
- package/src/editing/patch.ts +482 -0
- package/src/editing/post_edit_verification.ts +200 -0
- package/src/editing/syntax-verify.ts +353 -0
- package/src/index.ts +852 -0
- package/src/lsp/adapters/base.ts +42 -0
- package/src/lsp/adapters/index.ts +21 -0
- package/src/lsp/adapters/python.ts +37 -0
- package/src/lsp/adapters/rust.ts +35 -0
- package/src/lsp/adapters/typescript.ts +40 -0
- package/src/lsp/index.ts +13 -0
- package/src/lsp/lsp_client.ts +650 -0
- package/src/lsp/lsp_detector.ts +52 -0
- package/src/lsp/lsp_formatter.ts +284 -0
- package/src/lsp/lsp_installer.ts +604 -0
- package/src/lsp/lsp_manager.ts +202 -0
- package/src/lsp/lsp_modal.ts +675 -0
- package/src/lsp/lsp_registry.ts +539 -0
- package/src/lsp/lsp_types.ts +143 -0
- package/src/retrieval/ast_search.ts +926 -0
- package/src/retrieval/repomap.ts +779 -0
- package/src/retrieval/search_bm25.ts +190 -0
- package/src/retrieval/search_chunker.ts +251 -0
- package/src/retrieval/search_config.ts +162 -0
- package/src/retrieval/search_embedder.ts +362 -0
- package/src/retrieval/search_index.ts +753 -0
- package/src/retrieval/search_modal.ts +358 -0
- package/src/retrieval/symbol_reader.ts +200 -0
- package/src/safety/atomic_write.ts +26 -0
- package/src/safety/epistemic_guard.ts +733 -0
- package/src/safety/kernel_debug.ts +15 -0
- package/src/safety/output_clamper.ts +213 -0
- package/src/tools/ast_search_tool.ts +131 -0
- package/src/tools/code_search_tool.ts +147 -0
- package/src/tools/context.ts +20 -0
- package/src/tools/edit_tool.ts +288 -0
- package/src/tools/lsp_tool.ts +813 -0
- package/src/tools/read_tool.ts +348 -0
- package/src/tools/repo_map_tool.ts +57 -0
- package/src/ui/footer.ts +287 -0
- package/src/ui/tui_utils.ts +278 -0
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import * as os from "node:os";
|
|
4
|
+
import { getSearchConfig, type SearchConfig } from "./search_config";
|
|
5
|
+
import { kernelDebug } from "../safety/kernel_debug";
|
|
6
|
+
|
|
7
|
+
export interface EmbeddingResult {
|
|
8
|
+
vector: Float32Array;
|
|
9
|
+
dim: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class LocalEmbedder {
|
|
13
|
+
private extractor: any = null;
|
|
14
|
+
private layerNormFn: any = null;
|
|
15
|
+
private config: SearchConfig;
|
|
16
|
+
private isInitializing = false;
|
|
17
|
+
private initPromise: Promise<void> | null = null;
|
|
18
|
+
private queryLruCache = new Map<string, Float32Array>();
|
|
19
|
+
private static readonly MAX_QUERY_CACHE_ENTRIES = 128;
|
|
20
|
+
|
|
21
|
+
constructor(config?: SearchConfig) {
|
|
22
|
+
this.config = config || getSearchConfig();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
public updateConfig(config: SearchConfig): void {
|
|
26
|
+
this.config = config;
|
|
27
|
+
this.queryLruCache.clear();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
public isLoaded(): boolean {
|
|
31
|
+
return this.extractor !== null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Check if model weights are already downloaded and cached locally on disk.
|
|
36
|
+
*/
|
|
37
|
+
public isCachedOnDisk(): boolean {
|
|
38
|
+
try {
|
|
39
|
+
const modelParts = this.config.modelId.split("/");
|
|
40
|
+
const candidateDirs = [
|
|
41
|
+
path.join(
|
|
42
|
+
__dirname,
|
|
43
|
+
"../../node_modules",
|
|
44
|
+
"@huggingface",
|
|
45
|
+
"transformers",
|
|
46
|
+
".cache",
|
|
47
|
+
...modelParts,
|
|
48
|
+
),
|
|
49
|
+
path.join(
|
|
50
|
+
__dirname,
|
|
51
|
+
"../..",
|
|
52
|
+
"node_modules",
|
|
53
|
+
"@huggingface",
|
|
54
|
+
"transformers",
|
|
55
|
+
".cache",
|
|
56
|
+
...modelParts,
|
|
57
|
+
),
|
|
58
|
+
path.join(
|
|
59
|
+
process.cwd(),
|
|
60
|
+
"node_modules",
|
|
61
|
+
"@huggingface",
|
|
62
|
+
"transformers",
|
|
63
|
+
".cache",
|
|
64
|
+
...modelParts,
|
|
65
|
+
),
|
|
66
|
+
path.join(
|
|
67
|
+
os.homedir(),
|
|
68
|
+
".pi",
|
|
69
|
+
"agent",
|
|
70
|
+
"extensions",
|
|
71
|
+
"agent-kernel",
|
|
72
|
+
"node_modules",
|
|
73
|
+
"@huggingface",
|
|
74
|
+
"transformers",
|
|
75
|
+
".cache",
|
|
76
|
+
...modelParts,
|
|
77
|
+
),
|
|
78
|
+
path.join(
|
|
79
|
+
os.homedir(),
|
|
80
|
+
".pi",
|
|
81
|
+
"agent",
|
|
82
|
+
"extensions",
|
|
83
|
+
"features",
|
|
84
|
+
"node_modules",
|
|
85
|
+
"@huggingface",
|
|
86
|
+
"transformers",
|
|
87
|
+
".cache",
|
|
88
|
+
...modelParts,
|
|
89
|
+
),
|
|
90
|
+
path.join(
|
|
91
|
+
os.homedir(),
|
|
92
|
+
".cache",
|
|
93
|
+
"huggingface",
|
|
94
|
+
"hub",
|
|
95
|
+
`models--${this.config.modelId.replace("/", "--")}`,
|
|
96
|
+
),
|
|
97
|
+
path.join(
|
|
98
|
+
os.homedir(),
|
|
99
|
+
".cache",
|
|
100
|
+
"huggingface",
|
|
101
|
+
"transformers",
|
|
102
|
+
...modelParts,
|
|
103
|
+
),
|
|
104
|
+
path.join(os.homedir(), ".cache", ...modelParts),
|
|
105
|
+
path.join(os.homedir(), ".pi", "cache", "models", ...modelParts),
|
|
106
|
+
];
|
|
107
|
+
|
|
108
|
+
for (const dir of candidateDirs) {
|
|
109
|
+
if (!fs.existsSync(dir)) continue;
|
|
110
|
+
|
|
111
|
+
// Check for ONNX files or snapshot folders
|
|
112
|
+
const onnxPath = path.join(dir, "onnx");
|
|
113
|
+
if (fs.existsSync(onnxPath)) {
|
|
114
|
+
const files = fs.readdirSync(onnxPath);
|
|
115
|
+
if (files.some((f) => f.endsWith(".onnx"))) return true;
|
|
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;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
} catch (e) {
|
|
130
|
+
kernelDebug(e);
|
|
131
|
+
}
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Lazy-initializes the Hugging Face Transformers pipeline with strict thread limits.
|
|
137
|
+
*/
|
|
138
|
+
public async initialize(onProgress?: (msg: string) => void): Promise<boolean> {
|
|
139
|
+
if (this.extractor) return true;
|
|
140
|
+
if (
|
|
141
|
+
this.config.effectiveProfile === "off" ||
|
|
142
|
+
this.config.effectiveProfile === "lean"
|
|
143
|
+
) {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (this.initPromise) {
|
|
148
|
+
await this.initPromise;
|
|
149
|
+
return this.extractor !== null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
this.isInitializing = true;
|
|
153
|
+
this.initPromise = (async () => {
|
|
154
|
+
try {
|
|
155
|
+
const cached = this.isCachedOnDisk();
|
|
156
|
+
if (cached) {
|
|
157
|
+
onProgress?.("Loading embedding weights into RAM...");
|
|
158
|
+
} else {
|
|
159
|
+
onProgress?.("Downloading embedding weights: 0% (~135 MB)...");
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Enforce single-thread CPU constraints to avoid starving system processes
|
|
163
|
+
process.env.OMP_NUM_THREADS = String(this.config.numThreads || 1);
|
|
164
|
+
process.env.ORT_INTRA_OP_NUM_THREADS = String(this.config.numThreads || 1);
|
|
165
|
+
process.env.ORT_INTER_OP_NUM_THREADS = String(this.config.numThreads || 1);
|
|
166
|
+
|
|
167
|
+
const { env, pipeline, layer_norm } = await import(
|
|
168
|
+
"@huggingface/transformers"
|
|
169
|
+
);
|
|
170
|
+
if (env && env.backends && env.backends.onnx) {
|
|
171
|
+
env.backends.onnx.numThreads = this.config.numThreads || 1;
|
|
172
|
+
env.backends.onnx.logLevel = "warning";
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
this.layerNormFn = layer_norm;
|
|
176
|
+
|
|
177
|
+
this.extractor = await pipeline("feature-extraction", this.config.modelId, {
|
|
178
|
+
dtype: this.config.dtype,
|
|
179
|
+
progress_callback: (p: any) => {
|
|
180
|
+
if (p.status === "progress" && p.total && p.loaded) {
|
|
181
|
+
const pct = Math.round((p.loaded / p.total) * 100);
|
|
182
|
+
onProgress?.(`Downloading embedding weights: ${pct}%`);
|
|
183
|
+
}
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
// Strictly clamp tokenizer max sequence length to 512 tokens to prevent ONNX activation RAM explosions
|
|
188
|
+
if (this.extractor?.tokenizer?.config) {
|
|
189
|
+
this.extractor.tokenizer.config.model_max_length = 512;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
onProgress?.("Embedding model loaded.");
|
|
193
|
+
} catch (err: any) {
|
|
194
|
+
console.error("[Search Embedder] Error loading pipeline:", err);
|
|
195
|
+
this.extractor = null;
|
|
196
|
+
} finally {
|
|
197
|
+
this.isInitializing = false;
|
|
198
|
+
}
|
|
199
|
+
})();
|
|
200
|
+
|
|
201
|
+
await this.initPromise;
|
|
202
|
+
return this.extractor !== null;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Embed a single text string (document or query).
|
|
207
|
+
*/
|
|
208
|
+
public async embed(
|
|
209
|
+
text: string,
|
|
210
|
+
isQuery = false,
|
|
211
|
+
onProgress?: (msg: string) => void,
|
|
212
|
+
): Promise<Float32Array | null> {
|
|
213
|
+
if (isQuery) {
|
|
214
|
+
const cached = this.queryLruCache.get(text);
|
|
215
|
+
if (cached) {
|
|
216
|
+
// Refresh MRU order
|
|
217
|
+
this.queryLruCache.delete(text);
|
|
218
|
+
this.queryLruCache.set(text, cached);
|
|
219
|
+
return cached;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const results = await this.embedBatch([text], isQuery, onProgress);
|
|
224
|
+
if (results.length > 0) {
|
|
225
|
+
if (isQuery) {
|
|
226
|
+
if (this.queryLruCache.size >= LocalEmbedder.MAX_QUERY_CACHE_ENTRIES) {
|
|
227
|
+
const firstKey = this.queryLruCache.keys().next().value;
|
|
228
|
+
if (firstKey !== undefined) {
|
|
229
|
+
this.queryLruCache.delete(firstKey);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
this.queryLruCache.set(text, results[0]);
|
|
233
|
+
}
|
|
234
|
+
return results[0];
|
|
235
|
+
}
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Embed a batch of texts with Matryoshka dimension truncation and L2 normalization.
|
|
241
|
+
*/
|
|
242
|
+
public async embedBatch(
|
|
243
|
+
texts: string[],
|
|
244
|
+
isQuery = false,
|
|
245
|
+
onProgress?: (msg: string) => void,
|
|
246
|
+
): Promise<Float32Array[]> {
|
|
247
|
+
if (
|
|
248
|
+
this.config.effectiveProfile === "off" ||
|
|
249
|
+
this.config.effectiveProfile === "lean"
|
|
250
|
+
) {
|
|
251
|
+
return [];
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (!this.extractor) {
|
|
255
|
+
const ok = await this.initialize(onProgress);
|
|
256
|
+
if (!ok || !this.extractor) return [];
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (texts.length === 0) return [];
|
|
260
|
+
|
|
261
|
+
// Apply mandatory Nomic task prefix and clamp character length to 1,800 chars (~400 tokens)
|
|
262
|
+
const prefix = isQuery ? "search_query: " : "search_document: ";
|
|
263
|
+
const prefixedTexts = texts.map((t) => `${prefix}${t.slice(0, 1800)}`);
|
|
264
|
+
|
|
265
|
+
try {
|
|
266
|
+
let tensorOutput = await this.extractor(prefixedTexts, {
|
|
267
|
+
pooling: "mean",
|
|
268
|
+
normalize: false,
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
const targetDim =
|
|
272
|
+
this.config.matryoshkaDim > 0 ? this.config.matryoshkaDim : 768;
|
|
273
|
+
|
|
274
|
+
// Apply LayerNorm -> Slice to Matryoshka Dim -> L2 Normalize
|
|
275
|
+
if (this.layerNormFn && targetDim < 768) {
|
|
276
|
+
tensorOutput = this.layerNormFn(tensorOutput, [tensorOutput.dims[1]])
|
|
277
|
+
.slice(null, [0, targetDim])
|
|
278
|
+
.normalize(2, -1);
|
|
279
|
+
} else {
|
|
280
|
+
tensorOutput = tensorOutput.normalize(2, -1);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const data: Float32Array = tensorOutput.data;
|
|
284
|
+
const batchCount = tensorOutput.dims[0];
|
|
285
|
+
const actualDim = tensorOutput.dims[1];
|
|
286
|
+
|
|
287
|
+
const results: Float32Array[] = [];
|
|
288
|
+
for (let b = 0; b < batchCount; b++) {
|
|
289
|
+
const start = b * actualDim;
|
|
290
|
+
const end = start + actualDim;
|
|
291
|
+
const slice = new Float32Array(actualDim);
|
|
292
|
+
slice.set(data.subarray(start, end));
|
|
293
|
+
results.push(slice);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return results;
|
|
297
|
+
} catch (err: any) {
|
|
298
|
+
console.error("[Search Embedder] Error during batch embedding:", err);
|
|
299
|
+
return [];
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Compute fast cosine similarity between two normalized vectors.
|
|
305
|
+
*/
|
|
306
|
+
public static cosineSimilarity(a: Float32Array, b: Float32Array): number {
|
|
307
|
+
if (a.length !== b.length) return 0;
|
|
308
|
+
let dot = 0;
|
|
309
|
+
const len = a.length;
|
|
310
|
+
for (let i = 0; i < len; i++) {
|
|
311
|
+
dot += a[i] * b[i];
|
|
312
|
+
}
|
|
313
|
+
return dot;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Unload model from RAM and aggressively release native ONNX sessions and C++ heap buffers.
|
|
318
|
+
*/
|
|
319
|
+
public async dispose(): Promise<void> {
|
|
320
|
+
if (this.extractor) {
|
|
321
|
+
try {
|
|
322
|
+
if (typeof this.extractor.dispose === "function") {
|
|
323
|
+
await this.extractor.dispose();
|
|
324
|
+
}
|
|
325
|
+
if (this.extractor.model) {
|
|
326
|
+
if (typeof this.extractor.model.dispose === "function") {
|
|
327
|
+
await this.extractor.model.dispose();
|
|
328
|
+
}
|
|
329
|
+
if (this.extractor.model.session) {
|
|
330
|
+
if (typeof this.extractor.model.session.release === "function") {
|
|
331
|
+
await this.extractor.model.session.release();
|
|
332
|
+
}
|
|
333
|
+
if (typeof this.extractor.model.session.dispose === "function") {
|
|
334
|
+
await this.extractor.model.session.dispose();
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (
|
|
339
|
+
this.extractor.tokenizer &&
|
|
340
|
+
typeof this.extractor.tokenizer.dispose === "function"
|
|
341
|
+
) {
|
|
342
|
+
await this.extractor.tokenizer.dispose();
|
|
343
|
+
}
|
|
344
|
+
} catch (e) {
|
|
345
|
+
kernelDebug(e);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
this.extractor = null;
|
|
350
|
+
this.layerNormFn = null;
|
|
351
|
+
this.initPromise = null;
|
|
352
|
+
this.queryLruCache.clear();
|
|
353
|
+
|
|
354
|
+
try {
|
|
355
|
+
if (typeof (global as any).gc === "function") {
|
|
356
|
+
(global as any).gc();
|
|
357
|
+
}
|
|
358
|
+
} catch (e) {
|
|
359
|
+
kernelDebug(e);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|