-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.ts
More file actions
1552 lines (1392 loc) · 45 KB
/
index.ts
File metadata and controls
1552 lines (1392 loc) · 45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
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
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
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
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Memory Extension with QMD-Powered Search
*
* Plain-Markdown memory system with semantic search via qmd.
* Core memory tools (write/read/scratchpad) work without qmd installed.
* The memory_search tool requires qmd for keyword, semantic, and hybrid search.
*
* Layout (under ~/.pi/agent/memory/):
* MEMORY.md — curated long-term memory (decisions, preferences, durable facts)
* SCRATCHPAD.md — checklist of things to keep in mind / fix later
* daily/YYYY-MM-DD.md — daily append-only log (today + yesterday loaded at session start)
*
* Tools:
* memory_write — write to MEMORY.md or daily log
* memory_read — read any memory file or list daily logs
* scratchpad — add/check/uncheck/clear items on the scratchpad checklist
* memory_search — search across all memory files via qmd (keyword, semantic, or deep)
*
* Context injection:
* - MEMORY.md + SCRATCHPAD.md + today's + yesterday's daily logs injected into every turn
*/
import { execFile } from "node:child_process";
import * as fs from "node:fs";
import * as path from "node:path";
import { complete, type Message, StringEnum } from "@mariozechner/pi-ai";
import {
convertToLlm,
type ExtensionAPI,
type ExtensionContext,
type SessionEntry,
serializeConversation,
} from "@mariozechner/pi-coding-agent";
import { Type } from "@sinclair/typebox";
// ---------------------------------------------------------------------------
// Paths (mutable for testing via _setBaseDir / _resetBaseDir)
// ---------------------------------------------------------------------------
const DEFAULT_MEMORY_DIR = process.env.PI_MEMORY_DIR ?? path.join(process.env.HOME ?? "~", ".pi", "agent", "memory");
let MEMORY_DIR = DEFAULT_MEMORY_DIR;
let MEMORY_FILE = path.join(MEMORY_DIR, "MEMORY.md");
let SCRATCHPAD_FILE = path.join(MEMORY_DIR, "SCRATCHPAD.md");
let DAILY_DIR = path.join(MEMORY_DIR, "daily");
/** Override base directory (for testing). */
export function _setBaseDir(baseDir: string) {
MEMORY_DIR = baseDir;
MEMORY_FILE = path.join(baseDir, "MEMORY.md");
SCRATCHPAD_FILE = path.join(baseDir, "SCRATCHPAD.md");
DAILY_DIR = path.join(baseDir, "daily");
}
/** Reset to default paths (for testing). */
export function _resetBaseDir() {
_setBaseDir(DEFAULT_MEMORY_DIR);
}
// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------
export function ensureDirs() {
fs.mkdirSync(MEMORY_DIR, { recursive: true });
fs.mkdirSync(DAILY_DIR, { recursive: true });
}
export function todayStr(): string {
const d = new Date();
return d.toISOString().slice(0, 10);
}
export function yesterdayStr(): string {
const d = new Date();
d.setDate(d.getDate() - 1);
return d.toISOString().slice(0, 10);
}
export function nowTimestamp(): string {
return new Date()
.toISOString()
.replace("T", " ")
.replace(/\.\d+Z$/, "");
}
export function shortSessionId(sessionId: string): string {
return sessionId.slice(0, 8);
}
export function readFileSafe(filePath: string): string | null {
try {
return fs.readFileSync(filePath, "utf-8");
} catch {
return null;
}
}
const DAILY_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;
export function isValidDailyDate(date: string): boolean {
if (!DAILY_DATE_REGEX.test(date)) return false;
const [year, month, day] = date.split("-").map(Number);
const parsed = new Date(Date.UTC(year, month - 1, day));
return parsed.getUTCFullYear() === year && parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day;
}
export function dailyPath(date: string): string {
if (!isValidDailyDate(date)) {
throw new Error(`Invalid daily date: ${date}. Expected YYYY-MM-DD.`);
}
return path.join(DAILY_DIR, `${date}.md`);
}
// ---------------------------------------------------------------------------
// Limits + preview helpers
// ---------------------------------------------------------------------------
const RESPONSE_PREVIEW_MAX_CHARS = 4_000;
const RESPONSE_PREVIEW_MAX_LINES = 120;
const CONTEXT_LONG_TERM_MAX_CHARS = 4_000;
const CONTEXT_LONG_TERM_MAX_LINES = 150;
const CONTEXT_SCRATCHPAD_MAX_CHARS = 2_000;
const CONTEXT_SCRATCHPAD_MAX_LINES = 120;
const CONTEXT_DAILY_MAX_CHARS = 3_000;
const CONTEXT_DAILY_MAX_LINES = 120;
const CONTEXT_SEARCH_MAX_CHARS = 2_500;
const CONTEXT_SEARCH_MAX_LINES = 80;
const CONTEXT_MAX_CHARS = 16_000;
const EXIT_SUMMARY_MAX_CHARS = 80_000;
const EXIT_SUMMARY_SYSTEM_PROMPT = [
"You are a session recap assistant.",
"Read the conversation and extract key decisions, lessons learned, notes, and follow-ups.",
"Return ONLY markdown in the specified format, without any extra commentary.",
].join("\n");
type TruncateMode = "start" | "end" | "middle";
interface PreviewResult {
preview: string;
truncated: boolean;
totalLines: number;
totalChars: number;
previewLines: number;
previewChars: number;
}
function normalizeContent(content: string): string {
return content.trim();
}
function truncateLines(lines: string[], maxLines: number, mode: TruncateMode) {
if (maxLines <= 0 || lines.length <= maxLines) {
return { lines, truncated: false };
}
if (mode === "end") {
return { lines: lines.slice(-maxLines), truncated: true };
}
if (mode === "middle" && maxLines > 1) {
const marker = "... (truncated) ...";
const keep = maxLines - 1;
const headCount = Math.ceil(keep / 2);
const tailCount = Math.floor(keep / 2);
const head = lines.slice(0, headCount);
const tail = tailCount > 0 ? lines.slice(-tailCount) : [];
return { lines: [...head, marker, ...tail], truncated: true };
}
return { lines: lines.slice(0, maxLines), truncated: true };
}
function truncateText(text: string, maxChars: number, mode: TruncateMode) {
if (maxChars <= 0 || text.length <= maxChars) {
return { text, truncated: false };
}
if (mode === "end") {
return { text: text.slice(-maxChars), truncated: true };
}
if (mode === "middle" && maxChars > 10) {
const marker = "... (truncated) ...";
const keep = maxChars - marker.length;
if (keep > 0) {
const headCount = Math.ceil(keep / 2);
const tailCount = Math.floor(keep / 2);
return {
text: text.slice(0, headCount) + marker + text.slice(text.length - tailCount),
truncated: true,
};
}
}
return { text: text.slice(0, maxChars), truncated: true };
}
function buildPreview(
content: string,
options: { maxLines: number; maxChars: number; mode: TruncateMode },
): PreviewResult {
const normalized = normalizeContent(content);
if (!normalized) {
return {
preview: "",
truncated: false,
totalLines: 0,
totalChars: 0,
previewLines: 0,
previewChars: 0,
};
}
const lines = normalized.split("\n");
const totalLines = lines.length;
const totalChars = normalized.length;
const lineResult = truncateLines(lines, options.maxLines, options.mode);
const text = lineResult.lines.join("\n");
const charResult = truncateText(text, options.maxChars, options.mode);
const preview = charResult.text;
const previewLines = preview ? preview.split("\n").length : 0;
const previewChars = preview.length;
return {
preview,
truncated: lineResult.truncated || charResult.truncated,
totalLines,
totalChars,
previewLines,
previewChars,
};
}
function formatPreviewBlock(label: string, content: string, mode: TruncateMode) {
const result = buildPreview(content, {
maxLines: RESPONSE_PREVIEW_MAX_LINES,
maxChars: RESPONSE_PREVIEW_MAX_CHARS,
mode,
});
if (!result.preview) {
return `${label}: empty.`;
}
const meta = `${label} (${result.totalLines} lines, ${result.totalChars} chars)`;
const note = result.truncated
? `\n[preview truncated: showing ${result.previewLines}/${result.totalLines} lines, ${result.previewChars}/${result.totalChars} chars]`
: "";
return `${meta}\n\n${result.preview}${note}`;
}
function formatContextSection(label: string, content: string, mode: TruncateMode, maxLines: number, maxChars: number) {
const result = buildPreview(content, { maxLines, maxChars, mode });
if (!result.preview) {
return "";
}
const note = result.truncated
? `\n\n[truncated: showing ${result.previewLines}/${result.totalLines} lines, ${result.previewChars}/${result.totalChars} chars]`
: "";
return `${label}\n\n${result.preview}${note}`;
}
type ExitSummaryReason = "ctrl+d" | "slash-quit" | "session-end";
interface ExitSummaryResult {
summary: string | null;
error?: string;
hasMessages: boolean;
}
function formatExitSummaryReason(reason: ExitSummaryReason): string {
if (reason === "ctrl+d") return "ctrl+d";
if (reason === "slash-quit") return "/quit";
return "session-end";
}
function truncateConversationForSummary(conversationText: string): {
text: string;
truncated: boolean;
totalChars: number;
} {
const trimmed = conversationText.trim();
if (!trimmed) {
return { text: "", truncated: false, totalChars: 0 };
}
const truncated = truncateText(trimmed, EXIT_SUMMARY_MAX_CHARS, "end");
return {
text: truncated.text,
truncated: truncated.truncated,
totalChars: trimmed.length,
};
}
function buildExitSummaryPrompt(conversationText: string, truncated: boolean, totalChars: number): string {
const lines = [
"Review the conversation and extract important decisions, lessons learned, notes, and follow-ups for a daily log.",
"Return markdown only with these exact headings:",
"### Decisions",
"### Lessons Learned",
"### Notes",
"### Follow-ups",
'Use bullet points under each heading. If there is nothing, write "None.".',
];
if (truncated) {
lines.push(
`Note: Conversation transcript was truncated to the most recent ${conversationText.length} of ${totalChars} characters.`,
);
}
lines.push("", "<conversation>", conversationText, "</conversation>");
return lines.join("\n");
}
function buildExitSummaryFallback(error?: string): string {
const note = error ? `- Auto-summary unavailable: ${error}.` : "- Auto-summary unavailable.";
return [
"### Decisions",
"- None.",
"### Lessons Learned",
"- None.",
"### Notes",
note,
"### Follow-ups",
"- None.",
].join("\n");
}
function formatExitSummaryEntry(
summary: string,
reason: ExitSummaryReason,
sessionId: string,
timestamp: string,
): string {
const header = `## Session Summary (auto, exit: ${formatExitSummaryReason(reason)})`;
return [`<!-- ${timestamp} [${sessionId}] -->`, header, "", summary.trim()].join("\n");
}
function getSessionBranch(ctx: ExtensionContext): SessionEntry[] | null {
const sessionManager = ctx.sessionManager as ExtensionContext["sessionManager"] & {
getBranch?: () => SessionEntry[];
};
if (typeof sessionManager?.getBranch !== "function") {
return null;
}
return sessionManager.getBranch();
}
async function resolveExitSummaryApiKey(ctx: ExtensionContext): Promise<string | undefined> {
if (!ctx.model) return undefined;
const modelRegistry = ctx.modelRegistry as ExtensionContext["modelRegistry"] & {
getApiKey?: (model: NonNullable<ExtensionContext["model"]>) => Promise<string | undefined>;
getApiKeyForProvider?: (provider: string) => Promise<string | undefined>;
};
if (typeof modelRegistry?.getApiKey === "function") {
return modelRegistry.getApiKey(ctx.model);
}
if (typeof modelRegistry?.getApiKeyForProvider === "function") {
return modelRegistry.getApiKeyForProvider(ctx.model.provider);
}
return undefined;
}
async function generateExitSummary(ctx: ExtensionContext): Promise<ExitSummaryResult> {
const branch = getSessionBranch(ctx);
if (!branch) {
return { summary: null, error: "Session branch unavailable", hasMessages: false };
}
const messages = branch
.filter((entry): entry is SessionEntry & { type: "message" } => entry.type === "message")
.map((entry) => entry.message);
if (messages.length === 0) {
return { summary: null, hasMessages: false };
}
if (!ctx.model) {
return { summary: null, error: "No active model", hasMessages: true };
}
const apiKey = await resolveExitSummaryApiKey(ctx);
if (!apiKey) {
return {
summary: null,
error: `API key resolution unavailable for ${ctx.model.provider}/${ctx.model.id}`,
hasMessages: true,
};
}
const llmMessages = convertToLlm(messages);
const conversationText = serializeConversation(llmMessages);
const { text: truncatedText, truncated, totalChars } = truncateConversationForSummary(conversationText);
if (!truncatedText.trim()) {
return { summary: null, error: "No conversation text to summarize", hasMessages: true };
}
const summaryMessages: Message[] = [
{
role: "user",
content: [{ type: "text", text: buildExitSummaryPrompt(truncatedText, truncated, totalChars) }],
timestamp: Date.now(),
},
];
try {
const response = await complete(
ctx.model,
{ systemPrompt: EXIT_SUMMARY_SYSTEM_PROMPT, messages: summaryMessages },
{ apiKey, reasoningEffort: "low" },
);
const summaryText = response.content
.filter((c): c is { type: "text"; text: string } => c.type === "text")
.map((c) => c.text)
.join("\n")
.trim();
if (!summaryText) {
return { summary: null, error: "Summary was empty", hasMessages: true };
}
return { summary: summaryText, hasMessages: true };
} catch (err) {
return { summary: null, error: err instanceof Error ? err.message : String(err), hasMessages: true };
}
}
function getQmdUpdateMode(): "background" | "manual" | "off" {
const mode = (process.env.PI_MEMORY_QMD_UPDATE ?? "background").toLowerCase();
if (mode === "manual" || mode === "off" || mode === "background") {
return mode;
}
return "background";
}
async function ensureQmdAvailableForUpdate(): Promise<boolean> {
if (qmdAvailable) return true;
if (getQmdUpdateMode() !== "background") return false;
qmdAvailable = await detectQmd();
return qmdAvailable;
}
// ---------------------------------------------------------------------------
// Scratchpad helpers
// ---------------------------------------------------------------------------
export interface ScratchpadItem {
done: boolean;
text: string;
meta: string; // the <!-- timestamp [session] --> comment
}
export function parseScratchpad(content: string): ScratchpadItem[] {
const items: ScratchpadItem[] = [];
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const match = line.match(/^- \[([ xX])\] (.+)$/);
if (match) {
let meta = "";
if (i > 0 && lines[i - 1].match(/^<!--.*-->$/)) {
meta = lines[i - 1];
}
items.push({
done: match[1].toLowerCase() === "x",
text: match[2],
meta,
});
}
}
return items;
}
export function serializeScratchpad(items: ScratchpadItem[]): string {
const lines: string[] = ["# Scratchpad", ""];
for (const item of items) {
if (item.meta) {
lines.push(item.meta);
}
const checkbox = item.done ? "[x]" : "[ ]";
lines.push(`- ${checkbox} ${item.text}`);
}
return `${lines.join("\n")}\n`;
}
// ---------------------------------------------------------------------------
// Context builder
// ---------------------------------------------------------------------------
export function buildMemoryContext(searchResults?: string): string {
ensureDirs();
// Priority order: scratchpad > today's daily > search results > MEMORY.md > yesterday's daily
const sections: string[] = [];
const scratchpad = readFileSafe(SCRATCHPAD_FILE);
if (scratchpad?.trim()) {
const openItems = parseScratchpad(scratchpad).filter((i) => !i.done);
if (openItems.length > 0) {
const serialized = serializeScratchpad(openItems);
const section = formatContextSection(
"## SCRATCHPAD.md (working context)",
serialized,
"start",
CONTEXT_SCRATCHPAD_MAX_LINES,
CONTEXT_SCRATCHPAD_MAX_CHARS,
);
if (section) sections.push(section);
}
}
const today = todayStr();
const yesterday = yesterdayStr();
const todayContent = readFileSafe(dailyPath(today));
if (todayContent?.trim()) {
const section = formatContextSection(
`## Daily log: ${today} (today)`,
todayContent,
"end",
CONTEXT_DAILY_MAX_LINES,
CONTEXT_DAILY_MAX_CHARS,
);
if (section) sections.push(section);
}
if (searchResults?.trim()) {
const section = formatContextSection(
"## Relevant memories (auto-retrieved)",
searchResults,
"start",
CONTEXT_SEARCH_MAX_LINES,
CONTEXT_SEARCH_MAX_CHARS,
);
if (section) sections.push(section);
}
const longTerm = readFileSafe(MEMORY_FILE);
if (longTerm?.trim()) {
const section = formatContextSection(
"## MEMORY.md (long-term)",
longTerm,
"middle",
CONTEXT_LONG_TERM_MAX_LINES,
CONTEXT_LONG_TERM_MAX_CHARS,
);
if (section) sections.push(section);
}
const yesterdayContent = readFileSafe(dailyPath(yesterday));
if (yesterdayContent?.trim()) {
const section = formatContextSection(
`## Daily log: ${yesterday} (yesterday)`,
yesterdayContent,
"end",
CONTEXT_DAILY_MAX_LINES,
CONTEXT_DAILY_MAX_CHARS,
);
if (section) sections.push(section);
}
if (sections.length === 0) {
return "";
}
const context = `# Memory\n\n${sections.join("\n\n---\n\n")}`;
if (context.length > CONTEXT_MAX_CHARS) {
const result = buildPreview(context, {
maxLines: Number.POSITIVE_INFINITY,
maxChars: CONTEXT_MAX_CHARS,
mode: "start",
});
const note = result.truncated
? `\n\n[truncated overall context: showing ${result.previewChars}/${result.totalChars} chars]`
: "";
return `${result.preview}${note}`;
}
return context;
}
// ---------------------------------------------------------------------------
// QMD integration
// ---------------------------------------------------------------------------
type ExecFileFn = typeof execFile;
let execFileFn: ExecFileFn = execFile;
let qmdAvailable = false;
let updateTimer: ReturnType<typeof setTimeout> | null = null;
let exitSummaryReason: ExitSummaryReason | null = null;
let terminalInputUnsubscribe: (() => void) | null = null;
/** Override execFile implementation (for testing). */
export function _setExecFileForTest(fn: ExecFileFn) {
execFileFn = fn;
}
/** Reset execFile implementation (for testing). */
export function _resetExecFileForTest() {
execFileFn = execFile;
}
/** Set qmd availability flag (for testing). */
export function _setQmdAvailable(value: boolean) {
qmdAvailable = value;
}
/** Get current qmd availability flag (for testing). */
export function _getQmdAvailable(): boolean {
return qmdAvailable;
}
/** Get current update timer (for testing). */
export function _getUpdateTimer(): ReturnType<typeof setTimeout> | null {
return updateTimer;
}
/** Clear the update timer (for testing). */
export function _clearUpdateTimer() {
if (updateTimer) {
clearTimeout(updateTimer);
updateTimer = null;
}
}
const QMD_REPO_URL = "https://github.com/tobi/qmd";
export function qmdInstallInstructions(): string {
return [
"memory_search requires qmd.",
"",
"Install qmd (requires Bun):",
` bun install -g ${QMD_REPO_URL}`,
" # ensure ~/.bun/bin is in your PATH",
"",
"Then set up the collection (one-time):",
` qmd collection add ${MEMORY_DIR} --name pi-memory`,
" qmd embed",
].join("\n");
}
export function qmdCollectionInstructions(): string {
return [
"qmd collection pi-memory is not configured.",
"",
"Set up the collection (one-time):",
` qmd collection add ${MEMORY_DIR} --name pi-memory`,
" qmd embed",
].join("\n");
}
/** Auto-create the pi-memory collection and path contexts in qmd. */
export async function setupQmdCollection(): Promise<boolean> {
try {
await new Promise<void>((resolve, reject) => {
execFileFn("qmd", ["collection", "add", MEMORY_DIR, "--name", "pi-memory"], { timeout: 10_000 }, (err) =>
err ? reject(err) : resolve(),
);
});
} catch {
// Collection may already exist under a different name — not critical
return false;
}
// Add path contexts (best-effort, ignore errors)
const contexts: [string, string][] = [
["/daily", "Daily append-only work logs organized by date"],
["/", "Curated long-term memory: decisions, preferences, facts, lessons"],
];
for (const [ctxPath, desc] of contexts) {
try {
await new Promise<void>((resolve, reject) => {
execFileFn("qmd", ["context", "add", ctxPath, desc, "-c", "pi-memory"], { timeout: 10_000 }, (err) =>
err ? reject(err) : resolve(),
);
});
} catch {
// Ignore — context may already exist
}
}
return true;
}
export function detectQmd(): Promise<boolean> {
return new Promise((resolve) => {
// qmd doesn't reliably support --version; use a fast command that exits 0 when available.
execFileFn("qmd", ["status"], { timeout: 5_000 }, (err) => {
resolve(!err);
});
});
}
export function checkCollection(name: string): Promise<boolean> {
return new Promise((resolve) => {
execFileFn("qmd", ["collection", "list", "--json"], { timeout: 10_000 }, (err, stdout) => {
if (err) {
resolve(false);
return;
}
try {
const collections = JSON.parse(stdout);
if (Array.isArray(collections)) {
resolve(
collections.some((entry) => {
if (typeof entry === "string") return entry === name;
if (entry && typeof entry === "object" && "name" in entry) {
return (entry as { name?: string }).name === name;
}
return false;
}),
);
} else {
// qmd may output an object with a collections array or similar
resolve(stdout.includes(name));
}
} catch {
// Fallback: just check if the name appears in the output
resolve(stdout.includes(name));
}
});
});
}
export function scheduleQmdUpdate() {
if (getQmdUpdateMode() !== "background") return;
if (!qmdAvailable) return;
if (updateTimer) clearTimeout(updateTimer);
updateTimer = setTimeout(() => {
updateTimer = null;
execFileFn("qmd", ["update"], { timeout: 30_000 }, () => {});
}, 500);
}
async function runQmdUpdateNow() {
if (getQmdUpdateMode() !== "background") return;
if (!qmdAvailable) return;
await new Promise<void>((resolve) => {
execFileFn("qmd", ["update"], { timeout: 30_000 }, () => resolve());
});
}
/** Search for memories relevant to the user's prompt. Returns formatted markdown or empty string on error. */
export async function searchRelevantMemories(prompt: string): Promise<string> {
if (!qmdAvailable || !prompt.trim()) return "";
// Sanitize: strip control chars, limit to 200 chars for the search query
const sanitized = prompt
// biome-ignore lint/suspicious/noControlCharactersInRegex: we intentionally strip control chars.
.replace(/[\x00-\x1f\x7f]/g, " ")
.trim()
.slice(0, 200);
if (!sanitized) return "";
try {
const hasCollection = await checkCollection("pi-memory");
if (!hasCollection) return "";
const results = await Promise.race([
runQmdSearch("keyword", sanitized, 3),
new Promise<never>((_, reject) => setTimeout(() => reject(new Error("timeout")), 3_000)),
]);
if (!results || results.results.length === 0) return "";
const snippets = results.results
.map((r) => {
const text = getQmdResultText(r);
if (!text.trim()) return null;
const filePath = getQmdResultPath(r);
const filePart = filePath ? `_${filePath}_` : "";
return filePart ? `${filePart}\n${text.trim()}` : text.trim();
})
.filter(Boolean);
if (snippets.length === 0) return "";
return snippets.join("\n\n---\n\n");
} catch {
return "";
}
}
export interface QmdSearchResult {
path?: string;
file?: string;
score?: number;
content?: string;
chunk?: string;
snippet?: string;
title?: string;
[key: string]: unknown;
}
function getQmdResultPath(r: QmdSearchResult): string | undefined {
return r.path ?? r.file;
}
function getQmdResultText(r: QmdSearchResult): string {
return r.content ?? r.chunk ?? r.snippet ?? "";
}
function stripAnsi(text: string): string {
// qmd may emit spinners/progress bars even with --json, especially on first model download.
// Strip ANSI CSI/OSC sequences so we can reliably find and parse JSON payloads.
// biome-ignore lint/suspicious/noControlCharactersInRegex: stripping ANSI escape sequences
return text.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "").replace(/\u001b\][^\u0007]*(\u0007|\u001b\\)/g, "");
}
function parseQmdJson(stdout: string): unknown {
const trimmed = stdout.trim();
if (!trimmed) return [];
if (trimmed === "No results found." || trimmed === "No results found") return [];
const cleaned = stripAnsi(stdout);
const lines = cleaned.split(/\r?\n/);
const startLine = lines.findIndex((l) => {
const s = l.trimStart();
return s.startsWith("[") || s.startsWith("{");
});
if (startLine === -1) {
throw new Error(`Failed to parse qmd output: ${trimmed.slice(0, 200)}`);
}
const jsonText = lines.slice(startLine).join("\n").trim();
if (!jsonText) return [];
return JSON.parse(jsonText);
}
export function runQmdSearch(
mode: "keyword" | "semantic" | "deep",
query: string,
limit: number,
): Promise<{ results: QmdSearchResult[]; stderr: string }> {
const subcommand = mode === "keyword" ? "search" : mode === "semantic" ? "vsearch" : "query";
const args = [subcommand, "--json", "-c", "pi-memory", "-n", String(limit), query];
return new Promise((resolve, reject) => {
execFileFn("qmd", args, { timeout: 60_000 }, (err, stdout, stderr) => {
if (err) {
reject(new Error(stderr?.trim() || err.message));
return;
}
try {
const parsed = parseQmdJson(stdout);
const results = Array.isArray(parsed) ? parsed : ((parsed as any).results ?? (parsed as any).hits ?? []);
resolve({ results, stderr: stderr ?? "" });
} catch (parseErr) {
if (parseErr instanceof Error) {
reject(parseErr);
return;
}
reject(new Error(`Failed to parse qmd output: ${stdout.slice(0, 200)}`));
}
});
});
}
// ---------------------------------------------------------------------------
// Extension entry point
// ---------------------------------------------------------------------------
export default function (pi: ExtensionAPI) {
// --- session_start: detect qmd, auto-setup collection ---
pi.on("session_start", async (_event, ctx) => {
exitSummaryReason = null;
if (terminalInputUnsubscribe) {
terminalInputUnsubscribe();
terminalInputUnsubscribe = null;
}
if (ctx.hasUI) {
terminalInputUnsubscribe = ctx.ui.onTerminalInput((data) => {
if (!data.includes("\u0004")) return undefined;
if (!ctx.isIdle()) return undefined;
if (ctx.ui.getEditorText().trim()) return undefined;
exitSummaryReason = "ctrl+d";
return undefined;
});
}
qmdAvailable = await detectQmd();
if (!qmdAvailable) {
if (ctx.hasUI) {
ctx.ui.notify(qmdInstallInstructions(), "info");
}
return;
}
const hasCollection = await checkCollection("pi-memory");
if (!hasCollection) {
await setupQmdCollection();
}
});
// --- session_shutdown: write exit summary + clean up timer ---
pi.on("session_shutdown", async (_event, ctx) => {
if (terminalInputUnsubscribe) {
terminalInputUnsubscribe();
terminalInputUnsubscribe = null;
}
const reason = exitSummaryReason ?? "session-end";
exitSummaryReason = null;
try {
if (reason) {
ensureDirs();
const result = await generateExitSummary(ctx);
if (result.hasMessages) {
const summary = result.summary ?? buildExitSummaryFallback(result.error);
const sid = shortSessionId(ctx.sessionManager.getSessionId());
const ts = nowTimestamp();
const entry = formatExitSummaryEntry(summary, reason, sid, ts);
const filePath = dailyPath(todayStr());
const existing = readFileSafe(filePath) ?? "";
const separator = existing.trim() ? "\n\n" : "";
fs.writeFileSync(filePath, existing + separator + entry, "utf-8");
await ensureQmdAvailableForUpdate();
await runQmdUpdateNow();
}
}
} finally {
if (updateTimer) {
clearTimeout(updateTimer);
updateTimer = null;
}
}
});
// --- input: detect /quit for shutdown summary ---
pi.on("input", async (event, _ctx) => {
if (event.source !== "extension" && event.text.trim() === "/quit") {
exitSummaryReason = "slash-quit";
}
return { action: "continue" };
});
// --- Inject memory context before every agent turn ---
pi.on("before_agent_start", async (event, _ctx) => {
const skipSearch = process.env.PI_MEMORY_NO_SEARCH === "1";
const searchResults = skipSearch ? "" : await searchRelevantMemories(event.prompt ?? "");
const memoryContext = buildMemoryContext(searchResults);
if (!memoryContext) return;
const memoryInstructions = [
"\n\n## Memory",
"The following memory files have been loaded. Use the memory_write tool to persist important information.",
"- Decisions, preferences, and durable facts \u2192 MEMORY.md",
"- Day-to-day notes and running context \u2192 daily/<YYYY-MM-DD>.md",
"- Things to fix later or keep in mind \u2192 scratchpad tool",
"- Use memory_search to find past context across all memory files (keyword, semantic, or deep search).",
"- Use #tags (e.g. #decision, #preference) and [[links]] (e.g. [[auth-strategy]]) in memory content to improve future search recall.",
'- If someone says "remember this," write it immediately.',
"",
memoryContext,
].join("\n");
return {
systemPrompt: event.systemPrompt + memoryInstructions,
};
});
// --- Pre-compaction: auto-capture session handoff ---
pi.on("session_before_compact", async (_event, ctx) => {
ensureDirs();
const sid = shortSessionId(ctx.sessionManager.getSessionId());
const ts = nowTimestamp();
const parts: string[] = [];
// Capture open scratchpad items
const scratchpad = readFileSafe(SCRATCHPAD_FILE);
if (scratchpad?.trim()) {
const openItems = parseScratchpad(scratchpad).filter((i) => !i.done);
if (openItems.length > 0) {
parts.push("**Open scratchpad items:**");
for (const item of openItems) {
parts.push(`- [ ] ${item.text}`);
}
}
}
// Capture last few lines from today's daily log
const todayContent = readFileSafe(dailyPath(todayStr()));
if (todayContent?.trim()) {
const lines = todayContent.trim().split("\n");
const tail = lines.slice(-15).join("\n");
parts.push(`**Recent daily log context:**\n${tail}`);
}
if (parts.length === 0) return;
const handoff = [`<!-- HANDOFF ${ts} [${sid}] -->`, "## Session Handoff", ...parts].join("\n");