@floydous/pi-agent-kernel 0.2.0 → 0.3.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/CHANGELOG.md +10 -23
- package/README.md +127 -82
- package/docs/testing.md +10 -9
- package/package.json +9 -5
- package/src/config/kernel_config.ts +15 -0
- package/src/dedup/content_store.ts +365 -365
- package/src/dedup/recall_tool.ts +3 -5
- package/src/index.ts +975 -918
- package/src/retrieval/ast_search.ts +1035 -930
- package/src/retrieval/repomap.ts +353 -37
- package/src/retrieval/search_bm25.ts +195 -190
- package/src/retrieval/search_chunker.ts +261 -254
- package/src/retrieval/search_index.ts +21 -10
- package/src/retrieval/symbol_reader.ts +198 -203
- package/src/retrieval/tree_sitter_engine.ts +1 -1
- package/src/safety/epistemic_guard.ts +8 -1
- package/src/tools/ast_search_formatter.ts +161 -0
- package/src/tools/ast_search_tool.ts +22 -18
- package/src/tools/code_search_output.ts +237 -0
- package/src/tools/code_search_tool.ts +52 -18
- package/src/tools/context.ts +20 -20
- package/src/tools/edit_tool.ts +6 -7
- package/src/tools/lsp_tool.ts +207 -241
- package/src/tools/read_tool.ts +38 -19
- package/src/tools/repo_map_tool.ts +1 -2
- package/src/ui/tui_utils.ts +278 -278
- package/static/with-agent-kernel.png +0 -0
- package/static/without-agent-kernel-1.png +0 -0
- package/static/without-agent-kernel-2.png +0 -0
- package/static/without-agent-kernel-3.png +0 -0
package/src/index.ts
CHANGED
|
@@ -1,918 +1,975 @@
|
|
|
1
|
-
import * as path from "path";
|
|
2
|
-
import * as fs from "node:fs";
|
|
3
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
4
|
-
import { computeRepoMap } from "./retrieval/repomap";
|
|
5
|
-
import { HybridSearchIndex } from "./retrieval/search_index";
|
|
6
|
-
import type { SearchProfile } from "./retrieval/search_config";
|
|
7
|
-
import { SearchControlModal } from "./retrieval/search_modal";
|
|
8
|
-
import { checkSyntax } from "./editing/syntax-verify";
|
|
9
|
-
import {
|
|
10
|
-
globalEpistemicGuard,
|
|
11
|
-
resolveUserPath,
|
|
12
|
-
} from "./safety/epistemic_guard";
|
|
13
|
-
import { loadKernelConfig } from "./config";
|
|
14
|
-
import { kernelDebug } from "./safety/kernel_debug";
|
|
15
|
-
import { registerRepoMapTool } from "./tools/repo_map_tool";
|
|
16
|
-
import { registerAstSearchTool } from "./tools/ast_search_tool";
|
|
17
|
-
import { registerCodeSearchTool } from "./tools/code_search_tool";
|
|
18
|
-
import { registerReadTool } from "./tools/read_tool";
|
|
19
|
-
import { registerEditTool } from "./tools/edit_tool";
|
|
20
|
-
import { registerLspTool } from "./tools/lsp_tool";
|
|
21
|
-
import { TreeSitterEngine } from "./retrieval/tree_sitter_engine";
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Resolve the current session id from a handler context, or fall back to a
|
|
25
|
-
* shared default for single-session CLI use and in-memory sessions that
|
|
26
|
-
* have no UUID assigned.
|
|
27
|
-
*/
|
|
28
|
-
let fallbackSessionCounter = 0;
|
|
29
|
-
const fallbackSessionIds = new WeakMap<object, string>();
|
|
30
|
-
|
|
31
|
-
function getSessionId(ctx: any): string {
|
|
32
|
-
const provided = ctx?.sessionManager?.getSessionId?.();
|
|
33
|
-
if (typeof provided === "string" && provided.length > 0) return provided;
|
|
34
|
-
|
|
35
|
-
if (ctx && (typeof ctx === "object" || typeof ctx === "function")) {
|
|
36
|
-
let fallback = fallbackSessionIds.get(ctx);
|
|
37
|
-
if (!fallback) {
|
|
38
|
-
fallback = `__default__${process.pid}_${++fallbackSessionCounter}__`;
|
|
39
|
-
fallbackSessionIds.set(ctx, fallback);
|
|
40
|
-
}
|
|
41
|
-
return fallback;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
return `__default__${process.pid}`;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
const PI_DOCS_START =
|
|
48
|
-
"Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):";
|
|
49
|
-
const PI_DOCS_END = /\n- Always read pi \.md files completely[^\n]*/;
|
|
50
|
-
const piDocsEnabledBySession = new Map<string, boolean>();
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
import {
|
|
69
|
-
import {
|
|
70
|
-
import {
|
|
71
|
-
import {
|
|
72
|
-
import {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
//
|
|
97
|
-
//
|
|
98
|
-
// from
|
|
99
|
-
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
ctx.ui?.
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
const
|
|
171
|
-
const
|
|
172
|
-
const
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
"
|
|
176
|
-
"
|
|
177
|
-
"
|
|
178
|
-
"
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
//
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
{ value: "
|
|
231
|
-
{ value: "
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
const
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
"
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
const
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
getArgumentCompletions: (prefix: string) => {
|
|
282
|
-
const options = [
|
|
283
|
-
{
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
},
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
const
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
);
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
const
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
//
|
|
650
|
-
//
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
return
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
//
|
|
737
|
-
//
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
)
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
1
|
+
import * as path from "path";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { computeRepoMap, evaluateCodebaseMetrics } from "./retrieval/repomap";
|
|
5
|
+
import { HybridSearchIndex } from "./retrieval/search_index";
|
|
6
|
+
import type { SearchProfile } from "./retrieval/search_config";
|
|
7
|
+
import { SearchControlModal } from "./retrieval/search_modal";
|
|
8
|
+
import { checkSyntax } from "./editing/syntax-verify";
|
|
9
|
+
import {
|
|
10
|
+
globalEpistemicGuard,
|
|
11
|
+
resolveUserPath,
|
|
12
|
+
} from "./safety/epistemic_guard";
|
|
13
|
+
import { loadKernelConfig } from "./config";
|
|
14
|
+
import { kernelDebug } from "./safety/kernel_debug";
|
|
15
|
+
import { registerRepoMapTool } from "./tools/repo_map_tool";
|
|
16
|
+
import { registerAstSearchTool } from "./tools/ast_search_tool";
|
|
17
|
+
import { registerCodeSearchTool } from "./tools/code_search_tool";
|
|
18
|
+
import { registerReadTool } from "./tools/read_tool";
|
|
19
|
+
import { registerEditTool } from "./tools/edit_tool";
|
|
20
|
+
import { registerLspTool } from "./tools/lsp_tool";
|
|
21
|
+
import { TreeSitterEngine } from "./retrieval/tree_sitter_engine";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Resolve the current session id from a handler context, or fall back to a
|
|
25
|
+
* shared default for single-session CLI use and in-memory sessions that
|
|
26
|
+
* have no UUID assigned.
|
|
27
|
+
*/
|
|
28
|
+
let fallbackSessionCounter = 0;
|
|
29
|
+
const fallbackSessionIds = new WeakMap<object, string>();
|
|
30
|
+
|
|
31
|
+
function getSessionId(ctx: any): string {
|
|
32
|
+
const provided = ctx?.sessionManager?.getSessionId?.();
|
|
33
|
+
if (typeof provided === "string" && provided.length > 0) return provided;
|
|
34
|
+
|
|
35
|
+
if (ctx && (typeof ctx === "object" || typeof ctx === "function")) {
|
|
36
|
+
let fallback = fallbackSessionIds.get(ctx);
|
|
37
|
+
if (!fallback) {
|
|
38
|
+
fallback = `__default__${process.pid}_${++fallbackSessionCounter}__`;
|
|
39
|
+
fallbackSessionIds.set(ctx, fallback);
|
|
40
|
+
}
|
|
41
|
+
return fallback;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return `__default__${process.pid}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const PI_DOCS_START =
|
|
48
|
+
"Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):";
|
|
49
|
+
const PI_DOCS_END = /\n- Always read pi \.md files completely[^\n]*/;
|
|
50
|
+
const piDocsEnabledBySession = new Map<string, boolean>();
|
|
51
|
+
const codebaseProfileBySession = new Map<string, "auto" | "light" | "heavy">();
|
|
52
|
+
|
|
53
|
+
function withoutPiDocumentation(systemPrompt: string): string {
|
|
54
|
+
const start = systemPrompt.indexOf(PI_DOCS_START);
|
|
55
|
+
if (start < 0) return systemPrompt;
|
|
56
|
+
const endMatch = systemPrompt.slice(start).match(PI_DOCS_END);
|
|
57
|
+
if (!endMatch || endMatch.index === undefined) return systemPrompt;
|
|
58
|
+
|
|
59
|
+
const end = start + endMatch.index + endMatch[0].length;
|
|
60
|
+
const before = systemPrompt.slice(0, start).replace(/\n{2,}$/, "\n");
|
|
61
|
+
const after = systemPrompt.slice(end).replace(/^\n{2,}/, "\n");
|
|
62
|
+
return before + after;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function piDocsEnabled(ctx: any): boolean {
|
|
66
|
+
return piDocsEnabledBySession.get(getSessionId(ctx)) ?? true;
|
|
67
|
+
}
|
|
68
|
+
import { clampCommandOutput } from "./safety/output_clamper";
|
|
69
|
+
import { sanitizeSessionFiles } from "./context/session_repair";
|
|
70
|
+
import { renderFooter } from "./ui/footer";
|
|
71
|
+
import { DedupStore } from "./dedup/content_store";
|
|
72
|
+
import { registerRecallTool } from "./dedup/recall_tool";
|
|
73
|
+
import {
|
|
74
|
+
LspManager,
|
|
75
|
+
LspControlModal,
|
|
76
|
+
LspDownloadModal,
|
|
77
|
+
formatDiagnostics,
|
|
78
|
+
installLanguageServer,
|
|
79
|
+
LSP_SERVERS,
|
|
80
|
+
findExecutable,
|
|
81
|
+
} from "./lsp";
|
|
82
|
+
|
|
83
|
+
export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
84
|
+
// Initialize TreeSitter WASM engine eagerly in background
|
|
85
|
+
TreeSitterEngine.getInstance().init().catch((err) => {
|
|
86
|
+
kernelDebug(`TreeSitter background init error: ${err}`);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// 0. Auto-Sanitize Session Files (Repairs pre-existing incomplete usage metadata)
|
|
90
|
+
try {
|
|
91
|
+
sanitizeSessionFiles();
|
|
92
|
+
} catch (e) {
|
|
93
|
+
kernelDebug(e);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// 0b. Dedup store: shared across all sessions in this process. Per-session
|
|
97
|
+
// state is keyed by sessionId. A single instance lets the dedup store
|
|
98
|
+
// benefit from cross-session LRU and lets the recall tool look up refs
|
|
99
|
+
// from any active session.
|
|
100
|
+
const dedupStore = new DedupStore();
|
|
101
|
+
const getDedupStore = () => dedupStore;
|
|
102
|
+
|
|
103
|
+
// 3. Slash Commands: /repomap, /engine, /lsp, /pi-docs
|
|
104
|
+
let activeTui: any = null;
|
|
105
|
+
const configByWorkspace = new Map<
|
|
106
|
+
string,
|
|
107
|
+
ReturnType<typeof loadKernelConfig>
|
|
108
|
+
>();
|
|
109
|
+
const getConfig = (cwd: string) => {
|
|
110
|
+
const workspace = path.resolve(cwd);
|
|
111
|
+
let config = configByWorkspace.get(workspace);
|
|
112
|
+
if (!config) {
|
|
113
|
+
config = loadKernelConfig(workspace);
|
|
114
|
+
configByWorkspace.set(workspace, config);
|
|
115
|
+
}
|
|
116
|
+
return config;
|
|
117
|
+
};
|
|
118
|
+
const searchIndexes = new Map<string, HybridSearchIndex>();
|
|
119
|
+
const getSearchIndex = (cwd: string) => {
|
|
120
|
+
const workspace = path.resolve(cwd);
|
|
121
|
+
let index = searchIndexes.get(workspace);
|
|
122
|
+
if (!index) {
|
|
123
|
+
index = new HybridSearchIndex(workspace);
|
|
124
|
+
searchIndexes.set(workspace, index);
|
|
125
|
+
}
|
|
126
|
+
return index;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
// Helper: Background index synchronization with TUI progress bar widget
|
|
130
|
+
const triggerBackgroundIndexing = (
|
|
131
|
+
index: HybridSearchIndex,
|
|
132
|
+
ctx: any,
|
|
133
|
+
isFullSync = false,
|
|
134
|
+
) => {
|
|
135
|
+
const eff = index.getEffectiveProfile();
|
|
136
|
+
if (eff === "off") {
|
|
137
|
+
ctx.ui?.setWidget?.("engine-progress", undefined);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (eff === "lean") {
|
|
142
|
+
ctx.ui?.setWidget?.("engine-progress", undefined);
|
|
143
|
+
ctx.ui?.notify?.(
|
|
144
|
+
`Lean mode active (${index.getStatus().chunkCount} chunks ready in RAM)`,
|
|
145
|
+
"info",
|
|
146
|
+
);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const isVectorProfile = eff === "hybrid" || eff === "full";
|
|
151
|
+
const updateWidget = (line: string) => {
|
|
152
|
+
ctx.ui?.setWidget?.("engine-progress", [line], { placement: "belowEditor" });
|
|
153
|
+
};
|
|
154
|
+
const clearWidget = () => {
|
|
155
|
+
ctx.ui?.setWidget?.("engine-progress", undefined);
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const runSync = async () => {
|
|
159
|
+
if (isVectorProfile) {
|
|
160
|
+
updateWidget("\x1b[38;5;244mEngine: Loading embedding model...\x1b[0m");
|
|
161
|
+
await index.preloadModel((msg: string) => {
|
|
162
|
+
updateWidget(`\x1b[38;5;244mEngine: ${msg.slice(0, 40)}\x1b[0m`);
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
return await index.syncWorkspace(
|
|
166
|
+
isFullSync,
|
|
167
|
+
(msg: string) => {
|
|
168
|
+
const pctMatch = msg.match(/(\d+)%/);
|
|
169
|
+
if (pctMatch) {
|
|
170
|
+
const pct = parseInt(pctMatch[1], 10);
|
|
171
|
+
const barLen = 16;
|
|
172
|
+
const filled = Math.round((pct / 100) * barLen);
|
|
173
|
+
const empty = barLen - filled;
|
|
174
|
+
const bar =
|
|
175
|
+
"\x1b[38;5;248m" +
|
|
176
|
+
"█".repeat(filled) +
|
|
177
|
+
"\x1b[38;5;238m" +
|
|
178
|
+
"░".repeat(empty) +
|
|
179
|
+
"\x1b[0m";
|
|
180
|
+
updateWidget(
|
|
181
|
+
`\x1b[38;5;244mEngine:\x1b[0m [${bar}] \x1b[38;5;250m${pct}%\x1b[0m \x1b[38;5;242mIndexing workspace\x1b[0m`,
|
|
182
|
+
);
|
|
183
|
+
} else {
|
|
184
|
+
updateWidget(`\x1b[38;5;244mEngine: ${msg.slice(0, 40)}\x1b[0m`);
|
|
185
|
+
}
|
|
186
|
+
},
|
|
187
|
+
);
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
// Keep profile changes responsive: model warm-up and indexing run in the
|
|
191
|
+
// existing background lifecycle, while progress remains visible in the UI.
|
|
192
|
+
void runSync()
|
|
193
|
+
.then((result) => {
|
|
194
|
+
clearWidget();
|
|
195
|
+
ctx.ui?.notify?.(
|
|
196
|
+
`Search index ready (${result.chunkCount} chunks in ${result.fileCount} files)`,
|
|
197
|
+
"info",
|
|
198
|
+
);
|
|
199
|
+
})
|
|
200
|
+
.catch((err: any) => {
|
|
201
|
+
clearWidget();
|
|
202
|
+
ctx.ui?.notify?.(`Indexing error: ${err.message}`, "error");
|
|
203
|
+
});
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const setupUnifiedFooter = (ctx: any) => {
|
|
207
|
+
if (ctx.hasUI && ctx.ui?.setFooter) {
|
|
208
|
+
ctx.ui.setFooter((tui: any, theme: any, footerData: any) => {
|
|
209
|
+
activeTui = tui;
|
|
210
|
+
const unsubBranch = footerData?.onBranchChange?.(() =>
|
|
211
|
+
tui.requestRender?.(),
|
|
212
|
+
);
|
|
213
|
+
const currentIndex = getSearchIndex(
|
|
214
|
+
ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
|
|
215
|
+
);
|
|
216
|
+
return {
|
|
217
|
+
dispose: () => unsubBranch?.(),
|
|
218
|
+
invalidate: () => {},
|
|
219
|
+
render: (width: number) =>
|
|
220
|
+
renderFooter(ctx, theme, footerData, width, currentIndex),
|
|
221
|
+
};
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
pi.registerCommand("pi-docs", {
|
|
227
|
+
description: "Toggle Pi documentation guidance in the system prompt",
|
|
228
|
+
getArgumentCompletions: (prefix: string) => {
|
|
229
|
+
const options = [
|
|
230
|
+
{ value: "on", label: "on - Include Pi documentation guidance" },
|
|
231
|
+
{ value: "off", label: "off - Omit Pi documentation guidance" },
|
|
232
|
+
{ value: "status", label: "status - Show the current setting" },
|
|
233
|
+
];
|
|
234
|
+
const filtered = options.filter((option) =>
|
|
235
|
+
option.value.startsWith(prefix.toLowerCase()),
|
|
236
|
+
);
|
|
237
|
+
return filtered.length > 0 ? filtered : null;
|
|
238
|
+
},
|
|
239
|
+
handler: async (args: string, ctx: any) => {
|
|
240
|
+
const sessionId = getSessionId(ctx);
|
|
241
|
+
const value = (args || "").trim().toLowerCase();
|
|
242
|
+
if (value === "on" || value === "off") {
|
|
243
|
+
piDocsEnabledBySession.set(sessionId, value === "on");
|
|
244
|
+
ctx.ui?.notify?.(
|
|
245
|
+
`Pi documentation guidance ${value === "on" ? "enabled" : "disabled"} for this session.`,
|
|
246
|
+
"info",
|
|
247
|
+
);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const enabled = piDocsEnabled(ctx);
|
|
252
|
+
const message = `Pi documentation guidance: ${enabled ? "on" : "off"}`;
|
|
253
|
+
ctx.ui?.notify?.(message, "info");
|
|
254
|
+
if (!ctx.hasUI) console.log(message);
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
pi.registerCommand("repomap", {
|
|
259
|
+
description: "Display the Tree-Sitter AST & PageRank ranked repository map",
|
|
260
|
+
handler: async (args: string, ctx: any) => {
|
|
261
|
+
await TreeSitterEngine.getInstance().init();
|
|
262
|
+
const budget = args ? parseInt(args, 10) : 1024;
|
|
263
|
+
const map = computeRepoMap(
|
|
264
|
+
ctx.cwd,
|
|
265
|
+
Number.isNaN(budget)
|
|
266
|
+
? getConfig(ctx.cwd).retrieval.repo_map_budget
|
|
267
|
+
: budget,
|
|
268
|
+
);
|
|
269
|
+
ctx.ui?.notify?.("Repository Map Generated", "info");
|
|
270
|
+
if (ctx.hasUI && ctx.ui?.setWidget) {
|
|
271
|
+
ctx.ui.setWidget("repomap-widget", map.split("\n").slice(0, 25));
|
|
272
|
+
} else if (!ctx.hasUI) {
|
|
273
|
+
console.log("\n" + map + "\n");
|
|
274
|
+
}
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
// Slash Command: /profile [auto|smart|light|heavy|status]
|
|
279
|
+
pi.registerCommand("profile", {
|
|
280
|
+
description: "Configure codebase scale profile (auto/smart | light | heavy | status)",
|
|
281
|
+
getArgumentCompletions: (prefix: string) => {
|
|
282
|
+
const options = [
|
|
283
|
+
{ value: "auto", label: "auto (smart) - Auto-detect scale from codebase metrics" },
|
|
284
|
+
{ value: "light", label: "light - Force light profile (suppress auto repo-map)" },
|
|
285
|
+
{ value: "heavy", label: "heavy - Force heavy profile (always inject repo-map)" },
|
|
286
|
+
{ value: "status", label: "status - Display current profile & codebase metrics" },
|
|
287
|
+
];
|
|
288
|
+
const filtered = options.filter((o) => o.value.startsWith(prefix.toLowerCase()));
|
|
289
|
+
return filtered.length > 0 ? filtered : null;
|
|
290
|
+
},
|
|
291
|
+
handler: async (args: string, ctx: any) => {
|
|
292
|
+
const sessionId = getSessionId(ctx);
|
|
293
|
+
const raw = (args || "").trim().toLowerCase();
|
|
294
|
+
const val = raw === "smart" ? "auto" : raw;
|
|
295
|
+
|
|
296
|
+
if (val === "auto" || val === "light" || val === "heavy") {
|
|
297
|
+
codebaseProfileBySession.set(sessionId, val);
|
|
298
|
+
cachedRepoMap = "";
|
|
299
|
+
const msg = `Codebase profile set to '${val}' for this session.`;
|
|
300
|
+
ctx.ui?.notify?.(msg, "info");
|
|
301
|
+
if (!ctx.hasUI) console.log(msg);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const current = codebaseProfileBySession.get(sessionId) ?? getConfig(ctx.cwd).retrieval.codebase_profile;
|
|
306
|
+
const metrics = evaluateCodebaseMetrics(ctx.cwd);
|
|
307
|
+
const detected = metrics.isLight ? "light" : "heavy";
|
|
308
|
+
const effective = current === "auto" ? detected : current;
|
|
309
|
+
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)`;
|
|
310
|
+
ctx.ui?.notify?.(statusMsg, "info");
|
|
311
|
+
if (!ctx.hasUI) console.log("\n" + statusMsg + "\n");
|
|
312
|
+
},
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
// Slash Command: /engine [auto|lean|hybrid|full|off|status|reindex]
|
|
316
|
+
pi.registerCommand("engine", {
|
|
317
|
+
description:
|
|
318
|
+
"Configure codebase retrieval engine (auto | lean | hybrid | full | off | status | reindex)",
|
|
319
|
+
getArgumentCompletions: (prefix: string) => {
|
|
320
|
+
const options = [
|
|
321
|
+
{
|
|
322
|
+
value: "status",
|
|
323
|
+
label: "status - Display current engine profile, memory & diagnostics",
|
|
324
|
+
},
|
|
325
|
+
{
|
|
326
|
+
value: "auto",
|
|
327
|
+
label:
|
|
328
|
+
"auto - Auto-detect: Lean (VPS), Hybrid (Laptop), Full (Workstation)",
|
|
329
|
+
},
|
|
330
|
+
{
|
|
331
|
+
value: "lean",
|
|
332
|
+
label:
|
|
333
|
+
"lean - Fast AST-aware BM25 (0% CPU, 0 MB extra RAM) [Persisted Default]",
|
|
334
|
+
},
|
|
335
|
+
{
|
|
336
|
+
value: "hybrid",
|
|
337
|
+
label:
|
|
338
|
+
"hybrid - Throttled 256-dim Matryoshka embeddings",
|
|
339
|
+
},
|
|
340
|
+
{
|
|
341
|
+
value: "full",
|
|
342
|
+
label: "full - Multi-core 768-dim embeddings",
|
|
343
|
+
},
|
|
344
|
+
{
|
|
345
|
+
value: "off",
|
|
346
|
+
label: "off - Disable search & unload memory",
|
|
347
|
+
},
|
|
348
|
+
{ value: "reindex", label: "reindex - Force full workspace re-indexing" },
|
|
349
|
+
];
|
|
350
|
+
const filtered = options.filter((o) =>
|
|
351
|
+
o.value.startsWith(prefix.toLowerCase()),
|
|
352
|
+
);
|
|
353
|
+
return filtered.length > 0 ? filtered : null;
|
|
354
|
+
},
|
|
355
|
+
handler: async (args: string, ctx: any) => {
|
|
356
|
+
let sub = (args || "").trim().toLowerCase();
|
|
357
|
+
if (sub.startsWith("default ")) {
|
|
358
|
+
sub = sub.replace("default ", "").trim();
|
|
359
|
+
}
|
|
360
|
+
const index = getSearchIndex(ctx.cwd);
|
|
361
|
+
|
|
362
|
+
if (
|
|
363
|
+
sub === "auto" ||
|
|
364
|
+
sub === "lean" ||
|
|
365
|
+
sub === "hybrid" ||
|
|
366
|
+
sub === "full" ||
|
|
367
|
+
sub === "off"
|
|
368
|
+
) {
|
|
369
|
+
index.setProfile(sub as SearchProfile);
|
|
370
|
+
activeTui?.requestRender?.();
|
|
371
|
+
const status = index.getStatus();
|
|
372
|
+
const msg = `Default search profile saved: ${sub.toUpperCase()} (Effective: ${status.effectiveProfile.toUpperCase()})`;
|
|
373
|
+
ctx.ui?.notify?.(msg, "info");
|
|
374
|
+
if (!ctx.hasUI) console.log(`[Codebase Engine] ${msg}`);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
if (sub === "reindex") {
|
|
379
|
+
ctx.ui?.notify?.("Re-indexing workspace...", "info");
|
|
380
|
+
const res = await index.syncWorkspace(true, (msg) => {
|
|
381
|
+
if (ctx.hasUI) ctx.ui?.notify?.(msg, "info");
|
|
382
|
+
});
|
|
383
|
+
ctx.ui?.notify?.(
|
|
384
|
+
`Indexed ${res.fileCount} files (${res.chunkCount} chunks)`,
|
|
385
|
+
"info",
|
|
386
|
+
);
|
|
387
|
+
if (!ctx.hasUI)
|
|
388
|
+
console.log(
|
|
389
|
+
`[Codebase Engine] Re-indexed ${res.fileCount} files, ${res.chunkCount} chunks.`,
|
|
390
|
+
);
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
if (sub === "status") {
|
|
395
|
+
const status = index.getStatus();
|
|
396
|
+
ctx.ui?.notify?.(
|
|
397
|
+
`Engine: ${status.engineState} | Profile: ${status.profile.toUpperCase()} (${status.effectiveProfile.toUpperCase()}) | Chunks: ${status.chunkCount} | Model: ${status.modelStatus} | RSS: ${status.rssMemoryMB}MB`,
|
|
398
|
+
"info",
|
|
399
|
+
);
|
|
400
|
+
if (!ctx.hasUI) {
|
|
401
|
+
console.log(
|
|
402
|
+
`Codebase Retrieval Engine Status:\n- Engine State: ${status.engineState}\n- Pipeline: ${status.pipelineDesc}\n- Default Profile: ${status.profile.toUpperCase()} (persisted in ~/.pi/agent/search_settings.json)\n- Active Mode: ${status.effectiveProfile.toUpperCase()} (${status.hardwareInfo})\n- Indexed Files: ${status.fileCount}\n- Code Chunks: ${status.chunkCount}\n- Vector Embeddings: ${status.vectorCount}\n- Model Status: ${status.modelStatus}\n- Process RSS: ${status.rssMemoryMB} MB`,
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// Interactive centered modal dialog with full-viewport backdrop scrim
|
|
409
|
+
if (ctx.hasUI && ctx.ui?.custom) {
|
|
410
|
+
const res: any = await ctx.ui.custom(
|
|
411
|
+
(tui: any, theme: any, _keybindings: any, done: any) =>
|
|
412
|
+
new SearchControlModal(tui, index, theme, done),
|
|
413
|
+
{
|
|
414
|
+
overlay: true,
|
|
415
|
+
overlayOptions: {
|
|
416
|
+
anchor: "center",
|
|
417
|
+
width: "100%",
|
|
418
|
+
},
|
|
419
|
+
},
|
|
420
|
+
);
|
|
421
|
+
|
|
422
|
+
if (res) {
|
|
423
|
+
activeTui?.requestRender?.();
|
|
424
|
+
const eff = index.getEffectiveProfile();
|
|
425
|
+
const profileName = (res.profile || index.getProfile()).toUpperCase();
|
|
426
|
+
const effName = eff.toUpperCase();
|
|
427
|
+
|
|
428
|
+
if (res.action === "select") {
|
|
429
|
+
ctx.ui?.notify?.(
|
|
430
|
+
`Engine set to ${profileName} (Effective: ${effName})`,
|
|
431
|
+
"info",
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
if (res.reindexed || eff !== "off") {
|
|
436
|
+
triggerBackgroundIndexing(index, ctx, res.action === "reindex");
|
|
437
|
+
} else {
|
|
438
|
+
ctx.ui?.setWidget?.("engine-progress", undefined);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Fallback select menu if custom overlays are unavailable
|
|
445
|
+
if (ctx.hasUI && ctx.ui?.select) {
|
|
446
|
+
const status = index.getStatus();
|
|
447
|
+
const currentProfile = index.getProfile();
|
|
448
|
+
const options = [
|
|
449
|
+
`View Status (${status.engineState} - ${status.chunkCount} chunks, RSS ${status.rssMemoryMB}MB)`,
|
|
450
|
+
`── Profiles ───────────────────────`,
|
|
451
|
+
`Set Default: Auto Detect (Lean -> Hybrid -> Full based on specs)${currentProfile === "auto" ? " [Current]" : ""}`,
|
|
452
|
+
`Set Default: Lean Mode (Fast BM25, 0% CPU, 0 MB extra RAM)${currentProfile === "lean" ? " [Current]" : ""}`,
|
|
453
|
+
`Set Default: Hybrid Mode (Throttled 256-dim Matryoshka)${currentProfile === "hybrid" ? " [Current]" : ""}`,
|
|
454
|
+
`Set Default: Full Mode (768-dim embeddings)${currentProfile === "full" ? " [Current]" : ""}`,
|
|
455
|
+
`Set Default: Disable Engine (Turn off search)${currentProfile === "off" ? " [Current]" : ""}`,
|
|
456
|
+
`── Actions ────────────────────────`,
|
|
457
|
+
`Re-index Workspace`,
|
|
458
|
+
];
|
|
459
|
+
|
|
460
|
+
const choice = await ctx.ui.select(
|
|
461
|
+
"Codebase Retrieval Engine Settings",
|
|
462
|
+
options,
|
|
463
|
+
);
|
|
464
|
+
if (!choice || choice.startsWith("──")) return;
|
|
465
|
+
|
|
466
|
+
let profileChanged = false;
|
|
467
|
+
let isReindex = false;
|
|
468
|
+
|
|
469
|
+
if (choice.includes("Auto Detect")) {
|
|
470
|
+
index.setProfile("auto");
|
|
471
|
+
ctx.ui.notify("Default search profile saved: AUTO", "info");
|
|
472
|
+
profileChanged = true;
|
|
473
|
+
} else if (choice.includes("Lean Mode")) {
|
|
474
|
+
index.setProfile("lean");
|
|
475
|
+
ctx.ui.notify("Default search profile saved: LEAN", "info");
|
|
476
|
+
profileChanged = true;
|
|
477
|
+
} else if (choice.includes("Hybrid Mode")) {
|
|
478
|
+
index.setProfile("hybrid");
|
|
479
|
+
ctx.ui.notify("Default search profile saved: HYBRID", "info");
|
|
480
|
+
profileChanged = true;
|
|
481
|
+
} else if (choice.includes("Full Mode")) {
|
|
482
|
+
index.setProfile("full");
|
|
483
|
+
ctx.ui.notify("Default search profile saved: FULL", "info");
|
|
484
|
+
profileChanged = true;
|
|
485
|
+
} else if (choice.includes("Disable Engine")) {
|
|
486
|
+
index.setProfile("off");
|
|
487
|
+
ctx.ui.notify("Default search profile saved: OFF", "info");
|
|
488
|
+
} else if (choice.includes("Re-index")) {
|
|
489
|
+
isReindex = true;
|
|
490
|
+
} else if (choice.includes("View Status")) {
|
|
491
|
+
const s = index.getStatus();
|
|
492
|
+
ctx.ui.notify(
|
|
493
|
+
`Engine: ${s.engineState} | Profile: ${s.profile.toUpperCase()} (Effective: ${s.effectiveProfile.toUpperCase()}) | Files: ${s.fileCount} | Chunks: ${s.chunkCount} | Model: ${s.modelStatus} | RSS: ${s.rssMemoryMB}MB`,
|
|
494
|
+
"info",
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
if (profileChanged || isReindex) {
|
|
499
|
+
triggerBackgroundIndexing(index, ctx, isReindex);
|
|
500
|
+
}
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// CLI fallback if not in UI mode
|
|
505
|
+
const status = index.getStatus();
|
|
506
|
+
const msg = `Search Status:\n- Engine: ${status.engineState}\n- Profile: ${status.profile} (effective: ${status.effectiveProfile})\n- Indexed Files: ${status.fileCount}\n- Code Chunks: ${status.chunkCount}\n- Vector Embeddings: ${status.vectorCount}\n- Model: ${status.modelStatus}\n- Process RSS: ${status.rssMemoryMB} MB`;
|
|
507
|
+
console.log("\n" + msg + "\n");
|
|
508
|
+
},
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
// Slash Command: /lsp (Inspect language servers, active daemons, or install language servers)
|
|
512
|
+
pi.registerCommand("lsp", {
|
|
513
|
+
description:
|
|
514
|
+
"Inspect language servers, active daemons, or install servers (/lsp, /lsp install <lang>)",
|
|
515
|
+
getArgumentCompletions: (prefix: string) => {
|
|
516
|
+
const options = [
|
|
517
|
+
{
|
|
518
|
+
value: "status",
|
|
519
|
+
label: "status - View LSP status and active daemon processes",
|
|
520
|
+
},
|
|
521
|
+
{ value: "stop", label: "stop - Stop all active LSP daemon processes" },
|
|
522
|
+
{
|
|
523
|
+
value: "install",
|
|
524
|
+
label:
|
|
525
|
+
"install - Install an LSP server (e.g. pyright, typescript-language-server, gopls, rust-analyzer, clangd)",
|
|
526
|
+
},
|
|
527
|
+
];
|
|
528
|
+
const filtered = options.filter((o) =>
|
|
529
|
+
o.value.startsWith(prefix.toLowerCase()),
|
|
530
|
+
);
|
|
531
|
+
return filtered.length > 0 ? filtered : null;
|
|
532
|
+
},
|
|
533
|
+
async handler(args: string, ctx: any) {
|
|
534
|
+
const sub = args.trim().split(/\s+/);
|
|
535
|
+
const lspMgr = LspManager.getInstance();
|
|
536
|
+
|
|
537
|
+
if (sub[0] === "install" && sub[1]) {
|
|
538
|
+
const target = sub[1];
|
|
539
|
+
if (ctx.hasUI && ctx.ui?.notify) {
|
|
540
|
+
ctx.ui.notify(`Installing LSP server for ${target}...`, "info");
|
|
541
|
+
}
|
|
542
|
+
const res = await installLanguageServer(target, (msg) => {
|
|
543
|
+
if (ctx.hasUI && ctx.ui?.notify) {
|
|
544
|
+
ctx.ui.notify(msg, "info");
|
|
545
|
+
}
|
|
546
|
+
});
|
|
547
|
+
if (res.success) {
|
|
548
|
+
ctx.ui?.notify?.(res.message, "info");
|
|
549
|
+
} else {
|
|
550
|
+
ctx.ui?.notify?.(res.message, "error");
|
|
551
|
+
}
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
if (sub[0] === "stop" || sub[0] === "kill") {
|
|
556
|
+
await lspMgr.stopAll();
|
|
557
|
+
ctx.ui?.notify?.("All active LSP servers stopped.", "info");
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// Interactive centered modal dialog with full-viewport backdrop scrim
|
|
562
|
+
if (ctx.hasUI && ctx.ui?.custom) {
|
|
563
|
+
const res: any = await ctx.ui.custom(
|
|
564
|
+
(tui: any, theme: any, _keybindings: any, done: any) =>
|
|
565
|
+
new LspControlModal(tui, lspMgr, theme, done),
|
|
566
|
+
{
|
|
567
|
+
overlay: true,
|
|
568
|
+
overlayOptions: {
|
|
569
|
+
anchor: "center",
|
|
570
|
+
width: "100%",
|
|
571
|
+
},
|
|
572
|
+
},
|
|
573
|
+
);
|
|
574
|
+
|
|
575
|
+
if (res) {
|
|
576
|
+
if (res.action === "stop") {
|
|
577
|
+
await lspMgr.stopAll();
|
|
578
|
+
ctx.ui?.notify?.("All active LSP servers stopped.", "info");
|
|
579
|
+
} else if (res.installTargets && res.installTargets.length > 0) {
|
|
580
|
+
// Spawn animated ASCII loading spinner modal
|
|
581
|
+
await ctx.ui.custom(
|
|
582
|
+
(tui: any, theme: any, _keybindings: any, done: any) =>
|
|
583
|
+
new LspDownloadModal(tui, res.installTargets, theme, done),
|
|
584
|
+
{
|
|
585
|
+
overlay: true,
|
|
586
|
+
overlayOptions: {
|
|
587
|
+
anchor: "center",
|
|
588
|
+
width: "100%",
|
|
589
|
+
},
|
|
590
|
+
},
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const activeClients = lspMgr.getStatus();
|
|
598
|
+
if (ctx.hasUI && ctx.ui?.select) {
|
|
599
|
+
const lines = [
|
|
600
|
+
`── Active LSP Daemons (${activeClients.length}) ────────────────`,
|
|
601
|
+
...activeClients.map(
|
|
602
|
+
(c) =>
|
|
603
|
+
`[Active] ${c.languageId.toUpperCase()} (State: ${c.state}, Idle: ${c.idleSeconds}s)`,
|
|
604
|
+
),
|
|
605
|
+
`── Installed / Available Servers ─────────────────────────────`,
|
|
606
|
+
...Object.entries(LSP_SERVERS)
|
|
607
|
+
.slice(0, 10)
|
|
608
|
+
.map(([k, cfg]) => {
|
|
609
|
+
const primaryBin = cfg.commands[0]?.bin;
|
|
610
|
+
const found = findExecutable(primaryBin);
|
|
611
|
+
return `[${found ? "✓" : "✗"}] ${k.padEnd(12)} → ${primaryBin} ${found ? `(${found})` : "(not installed)"}`;
|
|
612
|
+
}),
|
|
613
|
+
`── Actions ───────────────────────────────────────────────────`,
|
|
614
|
+
`Stop all active LSP daemons`,
|
|
615
|
+
];
|
|
616
|
+
|
|
617
|
+
const choice = await ctx.ui.select("LSP Server Status & Management", lines);
|
|
618
|
+
if (choice?.includes("Stop all active")) {
|
|
619
|
+
await lspMgr.stopAll();
|
|
620
|
+
ctx.ui.notify("All active LSP servers stopped.", "info");
|
|
621
|
+
}
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// Console fallback
|
|
626
|
+
let out = `=== LSP Status ===\nActive Daemons: ${activeClients.length}\n`;
|
|
627
|
+
for (const c of activeClients) {
|
|
628
|
+
out += ` • ${c.languageId}: ${c.state} (idle: ${c.idleSeconds}s, root: ${c.rootDir})\n`;
|
|
629
|
+
}
|
|
630
|
+
console.log(out);
|
|
631
|
+
},
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
// Background workspace auto-indexer on session startup + setup integrated footer
|
|
635
|
+
pi.on("session_start", async (_event: any, ctx: any) => {
|
|
636
|
+
setupUnifiedFooter(ctx);
|
|
637
|
+
try {
|
|
638
|
+
const index = getSearchIndex(ctx.cwd);
|
|
639
|
+
if (index.getEffectiveProfile() !== "off") {
|
|
640
|
+
index.syncWorkspace(false).catch(() => {});
|
|
641
|
+
}
|
|
642
|
+
} catch (e) {
|
|
643
|
+
kernelDebug(e);
|
|
644
|
+
}
|
|
645
|
+
});
|
|
646
|
+
|
|
647
|
+
// 2. Per-session cleanup of the epistemic guard's inspection state and LSP processes.
|
|
648
|
+
// Without this, Map<sessionId, Set<filePath>> grows unbounded over a
|
|
649
|
+
// long-lived process hosting many sessions (e.g. RPC mode). On session
|
|
650
|
+
// shutdown we drop only this session's entry and stop running LSP daemons.
|
|
651
|
+
pi.on("session_shutdown", async (_event: any, ctx: any) => {
|
|
652
|
+
const sessionId = getSessionId(ctx);
|
|
653
|
+
piDocsEnabledBySession.delete(sessionId);
|
|
654
|
+
globalEpistemicGuard.resetSession(sessionId);
|
|
655
|
+
dedupStore.clearSession(sessionId);
|
|
656
|
+
try {
|
|
657
|
+
await LspManager.getInstance().stopAll();
|
|
658
|
+
} catch (e) {
|
|
659
|
+
kernelDebug(e);
|
|
660
|
+
}
|
|
661
|
+
});
|
|
662
|
+
|
|
663
|
+
// 2b. Compaction hooks: bump the dedup store's per-session counter so
|
|
664
|
+
// the next duplicate of any prior content is treated as a new first
|
|
665
|
+
// occurrence. This applies to both auto-triggered and manual compactions.
|
|
666
|
+
pi.on("session_before_compact", async (_event: any, ctx: any) => {
|
|
667
|
+
const sessionId = getSessionId(ctx);
|
|
668
|
+
dedupStore.onCompaction(sessionId);
|
|
669
|
+
});
|
|
670
|
+
pi.on("session_compact", async (_event: any, ctx: any) => {
|
|
671
|
+
const sessionId = getSessionId(ctx);
|
|
672
|
+
dedupStore.onCompaction(sessionId);
|
|
673
|
+
});
|
|
674
|
+
|
|
675
|
+
// 4-8. Tools: repo map, AST search, code search, read, edit, LSP
|
|
676
|
+
registerRepoMapTool(pi);
|
|
677
|
+
const invalidateSearchFile = (cwd: string, filePath: string) => {
|
|
678
|
+
getSearchIndex(cwd).invalidateFile(filePath);
|
|
679
|
+
};
|
|
680
|
+
registerAstSearchTool(pi, { getSessionId, getConfig });
|
|
681
|
+
registerCodeSearchTool(pi, { getSessionId, getSearchIndex, getConfig });
|
|
682
|
+
registerReadTool(pi, { getSessionId, getConfig });
|
|
683
|
+
registerEditTool(pi, { getSessionId, getConfig, invalidateSearchFile });
|
|
684
|
+
registerLspTool(pi, { getSessionId, getConfig });
|
|
685
|
+
registerRecallTool(pi, { getSessionId, getDedupStore });
|
|
686
|
+
|
|
687
|
+
// 9a. Block host writes before the host tool can create parent directories
|
|
688
|
+
// or overwrite the target. Bash read evidence is recorded after a successful
|
|
689
|
+
// command result below; preflight classification alone is not a read.
|
|
690
|
+
pi.on("tool_call", async (event: any, ctx: any) => {
|
|
691
|
+
try {
|
|
692
|
+
const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
693
|
+
const sessionId = getSessionId(ctx);
|
|
694
|
+
if (event.toolName !== "write") return;
|
|
695
|
+
const targetPath = (event.input as any)?.path;
|
|
696
|
+
if (typeof targetPath !== "string" || !targetPath.trim()) {
|
|
697
|
+
return {
|
|
698
|
+
block: true,
|
|
699
|
+
reason: "[WRITE ERROR] Missing target path.",
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
const config = getConfig(cwd);
|
|
703
|
+
const resolvedPath = resolveUserPath(targetPath, cwd);
|
|
704
|
+
const check = globalEpistemicGuard.checkReadPrecondition(
|
|
705
|
+
resolvedPath,
|
|
706
|
+
"write",
|
|
707
|
+
sessionId,
|
|
708
|
+
cwd,
|
|
709
|
+
config.safety.enable_epistemic_guard,
|
|
710
|
+
);
|
|
711
|
+
if (!check.allowed) {
|
|
712
|
+
// Block only this write. The model must remain able to inspect the
|
|
713
|
+
// rejection and choose a safe workaround or ask for clarification.
|
|
714
|
+
return {
|
|
715
|
+
block: true,
|
|
716
|
+
reason: check.reason,
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
} catch (e) {
|
|
720
|
+
kernelDebug(e);
|
|
721
|
+
if (event.toolName === "write") {
|
|
722
|
+
return {
|
|
723
|
+
block: true,
|
|
724
|
+
reason: `[WRITE BLOCKED] Safety preflight failed closed: ${e instanceof Error ? e.message : String(e)}`,
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
});
|
|
729
|
+
|
|
730
|
+
// 9. Tool Result Interceptor: Syntax Validation & Output Clamping (ACI)
|
|
731
|
+
pi.on("tool_result", async (event: any, ctx: any) => {
|
|
732
|
+
if (event.isError) return;
|
|
733
|
+
|
|
734
|
+
const toolName = event.toolName;
|
|
735
|
+
// resultContent === undefined means "no transformation, return event.content as-is".
|
|
736
|
+
// A non-undefined value is the content the LLM will see; the dedup check
|
|
737
|
+
// at the end runs on whichever form is set.
|
|
738
|
+
let resultContent: any = undefined;
|
|
739
|
+
let didBail = false;
|
|
740
|
+
|
|
741
|
+
// 9a. Intercept bash & terminal output to clamp minified lines & massive match floods
|
|
742
|
+
if (toolName === "bash") {
|
|
743
|
+
const command = (event.input as any)?.command || "";
|
|
744
|
+
const outputConfig = getConfig(
|
|
745
|
+
ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
|
|
746
|
+
);
|
|
747
|
+
let bashOutputComplete = true;
|
|
748
|
+
resultContent = (event.content || []).map((c: any) => {
|
|
749
|
+
if (c.type === "text" && typeof c.text === "string") {
|
|
750
|
+
const clamped = clampCommandOutput(c.text, command, {
|
|
751
|
+
maxLineLength: outputConfig.safety.max_line_length,
|
|
752
|
+
maxLines: outputConfig.safety.max_lines,
|
|
753
|
+
maxTotalBytes: outputConfig.safety.max_total_bytes,
|
|
754
|
+
});
|
|
755
|
+
if (clamped.truncated) {
|
|
756
|
+
bashOutputComplete = false;
|
|
757
|
+
return { ...c, text: clamped.text };
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
return c;
|
|
761
|
+
});
|
|
762
|
+
globalEpistemicGuard.recordCommandExecution(
|
|
763
|
+
command,
|
|
764
|
+
ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
|
|
765
|
+
getSessionId(ctx),
|
|
766
|
+
bashOutputComplete,
|
|
767
|
+
(resultContent || [])
|
|
768
|
+
.filter((c: any) => c.type === "text" && typeof c.text === "string")
|
|
769
|
+
.map((c: any) => c.text)
|
|
770
|
+
.join(""),
|
|
771
|
+
);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// 9b. Preserve the host write-tool compatibility path. The custom edit
|
|
775
|
+
// tool owns its complete verification lifecycle; intercepting edit results
|
|
776
|
+
// here would duplicate syntax/LSP work.
|
|
777
|
+
if (toolName === "write") {
|
|
778
|
+
const input = event.input as any;
|
|
779
|
+
const targetPath = input?.path;
|
|
780
|
+
|
|
781
|
+
// The harness does not reliably propagate result-level isError to this
|
|
782
|
+
// hook, so a failed edit can still reach here. Detect the edit tool's
|
|
783
|
+
// failure markers and bail out before post-write checks.
|
|
784
|
+
const resultText = (event.content || [])
|
|
785
|
+
.map((c: any) =>
|
|
786
|
+
c.type === "text" && typeof c.text === "string" ? c.text : "",
|
|
787
|
+
)
|
|
788
|
+
.join("\n");
|
|
789
|
+
if (
|
|
790
|
+
resultText.includes("[EDIT FAILED]") ||
|
|
791
|
+
resultText.includes("[EDIT ERROR]") ||
|
|
792
|
+
resultText.includes("[EPISTEMIC GUARD REJECTION]") ||
|
|
793
|
+
resultText.includes("[READ ERROR]")
|
|
794
|
+
) {
|
|
795
|
+
didBail = true;
|
|
796
|
+
} else if (targetPath) {
|
|
797
|
+
const resultCwd =
|
|
798
|
+
ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
799
|
+
const resolvedPath = resolveUserPath(targetPath, resultCwd);
|
|
800
|
+
getSearchIndex(resultCwd).invalidateFile(resolvedPath);
|
|
801
|
+
|
|
802
|
+
// Update epistemic guard ledger with the newly written file
|
|
803
|
+
try {
|
|
804
|
+
if (fs.existsSync(resolvedPath)) {
|
|
805
|
+
const writtenContent = fs.readFileSync(resolvedPath, "utf8");
|
|
806
|
+
globalEpistemicGuard.recordFileMutation(
|
|
807
|
+
resolvedPath,
|
|
808
|
+
getSessionId(ctx),
|
|
809
|
+
resultCwd,
|
|
810
|
+
writtenContent,
|
|
811
|
+
{ complete: true },
|
|
812
|
+
);
|
|
813
|
+
}
|
|
814
|
+
} catch (e) {
|
|
815
|
+
kernelDebug(e);
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
const syntaxRes = checkSyntax(resolvedPath);
|
|
819
|
+
|
|
820
|
+
if (!syntaxRes.valid && syntaxRes.status === "failed") {
|
|
821
|
+
const warning = `\n\n[SYNTAX WARNING] ${syntaxRes.error}\nPlease fix this syntax error.`;
|
|
822
|
+
resultContent = event.content.map((c: any) =>
|
|
823
|
+
c.type === "text" ? { ...c, text: c.text + warning } : c,
|
|
824
|
+
);
|
|
825
|
+
} else {
|
|
826
|
+
// Synchronize with active LSP daemon and fetch post-edit diagnostics if available
|
|
827
|
+
let lspNotice = "";
|
|
828
|
+
try {
|
|
829
|
+
const lspMgr = LspManager.getInstance();
|
|
830
|
+
const client = lspMgr.getReadyClientForFile(resolvedPath, resultCwd);
|
|
831
|
+
if (client && client.getState() === "ready") {
|
|
832
|
+
const fileContent = fs.readFileSync(resolvedPath, "utf8");
|
|
833
|
+
await client.changeDocument(resolvedPath, fileContent);
|
|
834
|
+
await client.saveDocument(resolvedPath, fileContent);
|
|
835
|
+
|
|
836
|
+
// Allow LSP server brief window to compute diagnostics
|
|
837
|
+
const diagnostics = await client.getDiagnosticsResult(resolvedPath);
|
|
838
|
+
if (diagnostics.diagnostics.length > 0) {
|
|
839
|
+
const formattedDiags = formatDiagnostics(
|
|
840
|
+
diagnostics.diagnostics,
|
|
841
|
+
resolvedPath,
|
|
842
|
+
resultCwd,
|
|
843
|
+
);
|
|
844
|
+
lspNotice = `\n\n[LSP Diagnostics]\n${formattedDiags}`;
|
|
845
|
+
} else if (diagnostics.status !== "clean") {
|
|
846
|
+
lspNotice = `\n\n[LSP ${diagnostics.status.toUpperCase()}] No definitive diagnostics result.`;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
} catch (e) {
|
|
850
|
+
kernelDebug(e);
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
if (lspNotice) {
|
|
854
|
+
resultContent = event.content.map((c: any) =>
|
|
855
|
+
c.type === "text" ? { ...c, text: c.text + lspNotice } : c,
|
|
856
|
+
);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// 9c. Dedup pass: hash the rendered text + tool name + input params;
|
|
863
|
+
// if it's a byte-equal duplicate (same tool, same params, same text)
|
|
864
|
+
// of one already in this session's current (uncompacted) context,
|
|
865
|
+
// replace with a [=rN,sizeB,tool,paramsKey] reference. Bail
|
|
866
|
+
// branches (didBail) skip dedup; errors are filtered at the top.
|
|
867
|
+
// The `recall` tool is exempt: its entire purpose is to break the
|
|
868
|
+
// dedup chain by emitting the original bytes; if we dedup'd its
|
|
869
|
+
// output, the LLM would get a reference instead of the bytes it
|
|
870
|
+
// asked for.
|
|
871
|
+
if (!didBail && toolName !== "recall") {
|
|
872
|
+
const contentForLLM = resultContent !== undefined ? resultContent : (event.content || []);
|
|
873
|
+
const hasOnlyTextContent = (contentForLLM as any[]).every(
|
|
874
|
+
(c: any) => c.type === "text" && typeof c.text === "string",
|
|
875
|
+
);
|
|
876
|
+
const finalText = hasOnlyTextContent
|
|
877
|
+
? (contentForLLM as any[]).map((c: any) => c.text).join("")
|
|
878
|
+
: "";
|
|
879
|
+
if (hasOnlyTextContent && Buffer.byteLength(finalText, "utf8") > 0) {
|
|
880
|
+
const sessionId = getSessionId(ctx);
|
|
881
|
+
const compactionCounter = dedupStore.getCompactionCounter(sessionId);
|
|
882
|
+
const inputParams = event.input || {};
|
|
883
|
+
const decision = dedupStore.record(
|
|
884
|
+
sessionId,
|
|
885
|
+
event.toolCallId || "",
|
|
886
|
+
toolName,
|
|
887
|
+
inputParams,
|
|
888
|
+
finalText,
|
|
889
|
+
false,
|
|
890
|
+
compactionCounter,
|
|
891
|
+
);
|
|
892
|
+
if (decision.isDuplicate) {
|
|
893
|
+
// Recall the prior entry's metadata so the notice names
|
|
894
|
+
// the tool and paramsKey. The LLM can use this to
|
|
895
|
+
// decide whether to recall or run a fresh tool call.
|
|
896
|
+
const prior = dedupStore.get(sessionId, decision.shortRef);
|
|
897
|
+
const priorTool = prior?.toolName ?? toolName;
|
|
898
|
+
const priorParamsKey = prior?.paramsKey ?? "";
|
|
899
|
+
resultContent = [
|
|
900
|
+
{
|
|
901
|
+
type: "text",
|
|
902
|
+
text: `[=${decision.shortRef},${Buffer.byteLength(finalText, "utf8")}B,${priorTool},${priorParamsKey}]`,
|
|
903
|
+
},
|
|
904
|
+
];
|
|
905
|
+
}
|
|
906
|
+
// For first occurrence, the dedup store has the entry, but we
|
|
907
|
+
// don't need to return anything; Pi will use event.content as-is.
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
if (didBail) return;
|
|
912
|
+
if (resultContent !== undefined) {
|
|
913
|
+
return { content: resultContent };
|
|
914
|
+
}
|
|
915
|
+
});
|
|
916
|
+
|
|
917
|
+
// 10. Dynamic Runtime Context Injection (Repo Map with in-memory caching)
|
|
918
|
+
// Notice: Custom user instructions (AGENT.md / prompt templates) are respected as the primary authority.
|
|
919
|
+
// Only runtime operational metadata (repo map) is dynamically attached and cached per session/cwd.
|
|
920
|
+
let cachedRepoMap = "";
|
|
921
|
+
let cachedRepoMapCwd = "";
|
|
922
|
+
let lastRepoMapCheck = 0;
|
|
923
|
+
|
|
924
|
+
pi.on("before_agent_start", async (event: any, ctx: any) => {
|
|
925
|
+
const now = Date.now();
|
|
926
|
+
const currentCwd = ctx.cwd || process.cwd();
|
|
927
|
+
const kernelConfig = getConfig(currentCwd);
|
|
928
|
+
const sessionId = getSessionId(ctx);
|
|
929
|
+
const profile = codebaseProfileBySession.get(sessionId) ?? kernelConfig.retrieval.codebase_profile ?? "auto";
|
|
930
|
+
|
|
931
|
+
let shouldInjectMap = false;
|
|
932
|
+
if (profile === "heavy") {
|
|
933
|
+
shouldInjectMap = true;
|
|
934
|
+
} else if (profile === "light") {
|
|
935
|
+
shouldInjectMap = false;
|
|
936
|
+
} else {
|
|
937
|
+
const metrics = evaluateCodebaseMetrics(
|
|
938
|
+
currentCwd,
|
|
939
|
+
kernelConfig.retrieval.repo_map_min_files,
|
|
940
|
+
kernelConfig.retrieval.repo_map_min_bytes,
|
|
941
|
+
);
|
|
942
|
+
shouldInjectMap = !metrics.isLight;
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// Cache repo-map across turns with a 15-second TTL to avoid scanning/PageRanking entire repo on every turn
|
|
946
|
+
if (!cachedRepoMap || cachedRepoMapCwd !== currentCwd || now - lastRepoMapCheck > 15000) {
|
|
947
|
+
if (shouldInjectMap) {
|
|
948
|
+
await TreeSitterEngine.getInstance().init();
|
|
949
|
+
cachedRepoMap = computeRepoMap(
|
|
950
|
+
currentCwd,
|
|
951
|
+
kernelConfig.retrieval.repo_map_budget,
|
|
952
|
+
);
|
|
953
|
+
} else {
|
|
954
|
+
cachedRepoMap = "";
|
|
955
|
+
}
|
|
956
|
+
cachedRepoMapCwd = currentCwd;
|
|
957
|
+
lastRepoMapCheck = now;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
const dedupNote = `A [=rN,sizeB,tool,paramsKey] ref denotes duplicate content. Call recall(ref) only if needed; otherwise run fresh tools.`;
|
|
961
|
+
|
|
962
|
+
const runtimeContext = cachedRepoMap
|
|
963
|
+
? `\n## Available Repository Context:\n${cachedRepoMap}\n${dedupNote}\n`
|
|
964
|
+
: `\n${dedupNote}\n`;
|
|
965
|
+
const basePrompt = event.systemPrompt || "";
|
|
966
|
+
const systemPrompt = piDocsEnabled(ctx)
|
|
967
|
+
? basePrompt
|
|
968
|
+
: withoutPiDocumentation(basePrompt);
|
|
969
|
+
return {
|
|
970
|
+
systemPrompt: systemPrompt
|
|
971
|
+
? `${systemPrompt}\n\n${runtimeContext}`
|
|
972
|
+
: runtimeContext,
|
|
973
|
+
};
|
|
974
|
+
});
|
|
975
|
+
}
|