forked from earendil-works/pi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession-manager.ts
More file actions
2013 lines (1820 loc) · 62.3 KB
/
Copy pathsession-manager.ts
File metadata and controls
2013 lines (1820 loc) · 62.3 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
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import {
type AssistantMessage,
getCurrentSystemMessage,
type ImageContent,
type Message,
type SystemMessage,
type TextContent,
type ToolResultMessage,
type Usage,
type UserMessage,
uuidv7,
} from "@earendil-works/pi-ai";
import { randomUUID } from "crypto";
import {
appendFileSync,
closeSync,
createReadStream,
existsSync,
mkdirSync,
openSync,
readdirSync,
readSync,
type Stats,
statSync,
writeFileSync,
} from "fs";
import { readdir, stat } from "fs/promises";
import { basename, join, resolve } from "path";
import { createInterface } from "readline";
import { StringDecoder } from "string_decoder";
import { APP_NAME, getAgentDir as getDefaultAgentDir, getSessionsDir } from "../config.ts";
import { normalizePath, resolvePath } from "../utils/paths.ts";
import {
type BashExecutionMessage,
type CustomMessage,
createBranchSummaryMessage,
createCompactionSummaryMessage,
createCustomMessage,
} from "./messages.ts";
export const CURRENT_SESSION_VERSION = 3;
export interface SessionHeader {
type: "session";
version?: number; // v1 sessions don't have this
id: string;
timestamp: string;
cwd: string;
parentSession?: string;
}
export interface NewSessionOptions {
id?: string;
parentSession?: string;
}
export interface SessionEntryBase {
type: string;
id: string;
parentId: string | null;
timestamp: string;
}
export interface SessionMessageEntry extends SessionEntryBase {
type: "message";
message: AgentMessage;
}
export interface ThinkingLevelChangeEntry extends SessionEntryBase {
type: "thinking_level_change";
thinkingLevel: string;
}
export interface ModelChangeEntry extends SessionEntryBase {
type: "model_change";
provider: string;
modelId: string;
}
export interface UsageEntry extends SessionEntryBase {
type: "usage";
/** Arbitrary usage category, such as "cache_warm". */
kind: string;
provider: string;
model: string;
usage: Usage;
/** Optional human-readable qualifier for usage notices. */
note?: string;
}
export interface CompactionEntry<T = unknown> extends SessionEntryBase {
type: "compaction";
summary: string;
firstKeptEntryId: string;
tokensBefore: number;
/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */
details?: T;
/** Usage from the LLM call(s) that generated this summary, if available */
usage?: Usage;
/** True if generated by an extension, undefined/false if pi-generated (backward compatible) */
fromHook?: boolean;
/** Complete prompt and tool state at this compaction boundary. */
systemMessage?: SystemMessage;
}
export interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {
type: "branch_summary";
fromId: string;
summary: string;
/** Extension-specific data (not sent to LLM) */
details?: T;
/** Usage from the LLM call that generated this summary, if available */
usage?: Usage;
/** True if generated by an extension, false if pi-generated */
fromHook?: boolean;
}
/**
* Custom entry for extensions to store extension-specific data in the session.
* Use customType to identify your extension's entries.
*
* Purpose: Persist extension state across session reloads. On reload, extensions can
* scan entries for their customType and reconstruct internal state.
*
* Does NOT participate in LLM context (ignored by buildSessionContext).
* For injecting content into context, see CustomMessageEntry.
*/
export interface CustomEntry<T = unknown> extends SessionEntryBase {
type: "custom";
customType: string;
data?: T;
}
/** Label entry for user-defined bookmarks/markers on entries. */
export interface LabelEntry extends SessionEntryBase {
type: "label";
targetId: string;
label: string | undefined;
}
/** Session metadata entry (e.g., user-defined display name). */
export interface SessionInfoEntry extends SessionEntryBase {
type: "session_info";
name?: string;
}
/**
* Custom message entry for extensions to inject messages into LLM context.
* Use customType to identify your extension's entries.
*
* Unlike CustomEntry, this DOES participate in LLM context.
* The content is converted to a user message in buildSessionContext().
* Use details for extension-specific metadata (not sent to LLM).
*
* display controls TUI rendering:
* - false: hidden entirely
* - true: rendered with distinct styling (different from user messages)
*/
export interface CustomMessageEntry<T = unknown> extends SessionEntryBase {
type: "custom_message";
customType: string;
content: string | (TextContent | ImageContent)[];
details?: T;
display: boolean;
}
/** Content that an append-only context edit may replace without changing message metadata. */
export type ContextEditableContent =
| UserMessage["content"]
| AssistantMessage["content"]
| ToolResultMessage["content"]
| CustomMessage["content"];
/** Append-only change to one earlier entry's contribution to model context. */
export interface ContextEditEntry extends SessionEntryBase {
type: "context_edit";
targetId: string;
/** Null omits the target from model context. A value replaces only its content. */
replacement: { content: ContextEditableContent } | null;
}
/** Session entry - has id/parentId for tree structure (returned by "read" methods in SessionManager) */
export type SessionEntry =
| SessionMessageEntry
| ThinkingLevelChangeEntry
| ModelChangeEntry
| UsageEntry
| CompactionEntry
| BranchSummaryEntry
| CustomEntry
| CustomMessageEntry
| ContextEditEntry
| LabelEntry
| SessionInfoEntry;
/** Raw file entry (includes header) */
export type FileEntry = SessionHeader | SessionEntry;
/** Tree node for getTree() - defensive copy of session structure */
export interface SessionTreeNode {
entry: SessionEntry;
children: SessionTreeNode[];
/** Resolved label for this entry, if any */
label?: string;
/** Timestamp of the latest label change for this entry, if any */
labelTimestamp?: string;
}
export interface ProjectedSessionEntry {
/** Raw append-only entry that owns this projected contribution. */
sourceEntry: SessionEntry;
/** Model-visible messages after context edits. Empty for state-only entries and omissions. */
messages: AgentMessage[];
}
export interface SessionProjection {
entries: ProjectedSessionEntry[];
messages: AgentMessage[];
thinkingLevel: string;
model: { provider: string; modelId: string } | null;
}
export interface SessionContext {
messages: AgentMessage[];
thinkingLevel: string;
model: { provider: string; modelId: string } | null;
}
export interface SessionInfo {
path: string;
id: string;
/** Working directory where the session was started. Empty string for old sessions. */
cwd: string;
/** User-defined display name from session_info entries. */
name?: string;
/** Path to the parent session (if this session was forked). */
parentSessionPath?: string;
created: Date;
modified: Date;
messageCount: number;
firstMessage: string;
allMessagesText: string;
}
export type ReadonlySessionManager = Pick<
SessionManager,
| "getCwd"
| "getSessionDir"
| "getSessionId"
| "getSessionFile"
| "getLeafId"
| "getLeafEntry"
| "getEntry"
| "getLabel"
| "getBranch"
| "buildContextEntries"
| "buildSessionProjection"
| "getHeader"
| "getEntries"
| "getTree"
| "getSessionName"
>;
function createSessionId(): string {
return uuidv7();
}
export function assertValidSessionId(id: string): void {
if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) {
throw new Error(
"Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character",
);
}
}
/** Generate a unique short ID (8 hex chars, collision-checked) */
function generateId(byId: { has(id: string): boolean }): string {
for (let i = 0; i < 100; i++) {
const id = randomUUID().slice(0, 8);
if (!byId.has(id)) return id;
}
// Fallback to full UUID if somehow we have collisions
return randomUUID();
}
/** Migrate v1 → v2: add id/parentId tree structure. Mutates in place. */
function migrateV1ToV2(entries: FileEntry[]): void {
const ids = new Set<string>();
let prevId: string | null = null;
for (const entry of entries) {
if (entry.type === "session") {
entry.version = 2;
continue;
}
entry.id = generateId(ids);
entry.parentId = prevId;
prevId = entry.id;
// Convert firstKeptEntryIndex to firstKeptEntryId for compaction
if (entry.type === "compaction") {
const comp = entry as CompactionEntry & { firstKeptEntryIndex?: number };
if (typeof comp.firstKeptEntryIndex === "number") {
const targetEntry = entries[comp.firstKeptEntryIndex];
if (targetEntry && targetEntry.type !== "session") {
comp.firstKeptEntryId = targetEntry.id;
}
delete comp.firstKeptEntryIndex;
}
}
}
}
/** Migrate v2 → v3: rename hookMessage role to custom. Mutates in place. */
function migrateV2ToV3(entries: FileEntry[]): void {
for (const entry of entries) {
if (entry.type === "session") {
entry.version = 3;
continue;
}
// Update message entries with hookMessage role
if (entry.type === "message") {
const msgEntry = entry as SessionMessageEntry;
if (msgEntry.message && (msgEntry.message as { role: string }).role === "hookMessage") {
(msgEntry.message as { role: string }).role = "custom";
}
}
}
}
/**
* Run all necessary migrations to bring entries to current version.
* Mutates entries in place. Returns true if any migration was applied.
*/
function migrateToCurrentVersion(entries: FileEntry[]): boolean {
const header = entries.find((e) => e.type === "session") as SessionHeader | undefined;
const version = header?.version ?? 1;
if (version >= CURRENT_SESSION_VERSION) return false;
if (version < 2) migrateV1ToV2(entries);
if (version < 3) migrateV2ToV3(entries);
return true;
}
/** Exported for testing */
export function migrateSessionEntries(entries: FileEntry[]): void {
migrateToCurrentVersion(entries);
}
/** Exported for compaction.test.ts */
export function parseSessionEntries(content: string): FileEntry[] {
const entries: FileEntry[] = [];
const lines = content.trim().split("\n");
for (const line of lines) {
if (!line.trim()) continue;
try {
const entry = JSON.parse(line) as FileEntry;
entries.push(entry);
} catch {
// Skip malformed lines
}
}
return entries;
}
export function getLatestCompactionEntry(entries: SessionEntry[]): CompactionEntry | null {
for (let i = entries.length - 1; i >= 0; i--) {
if (entries[i].type === "compaction") {
return entries[i] as CompactionEntry;
}
}
return null;
}
function buildEntryIndex(entries: SessionEntry[], byId?: Map<string, SessionEntry>): Map<string, SessionEntry> {
if (byId) return byId;
const index = new Map<string, SessionEntry>();
for (const entry of entries) {
index.set(entry.id, entry);
}
return index;
}
function buildSessionPath(
entries: SessionEntry[],
leafId?: string | null,
byId?: Map<string, SessionEntry>,
): SessionEntry[] {
const index = buildEntryIndex(entries, byId);
let leaf: SessionEntry | undefined;
if (leafId === null) {
return [];
}
if (leafId) {
leaf = index.get(leafId);
}
leaf ??= entries[entries.length - 1];
if (!leaf) {
return [];
}
const path: SessionEntry[] = [];
let current: SessionEntry | undefined = leaf;
while (current) {
path.push(current);
current = current.parentId ? index.get(current.parentId) : undefined;
}
path.reverse();
return path;
}
function getSessionContextSettings(path: SessionEntry[]): Pick<SessionContext, "thinkingLevel" | "model"> {
let thinkingLevel = "off";
let model: { provider: string; modelId: string } | null = null;
for (const entry of path) {
if (entry.type === "thinking_level_change") {
thinkingLevel = entry.thinkingLevel;
} else if (entry.type === "model_change") {
model = { provider: entry.provider, modelId: entry.modelId };
} else if (entry.type === "message" && entry.message.role === "assistant") {
model = { provider: entry.message.provider, modelId: entry.message.model };
}
}
return { thinkingLevel, model };
}
/**
* Project one selected session entry into LLM/runtime messages.
* Plain custom entries are display/state entries and do not participate in context.
*/
export function sessionEntryToContextMessages(entry: SessionEntry): AgentMessage[] {
if (entry.type === "message") {
const message = entry.message;
// Session files are parsed without validation; old versions, forks, or
// hand-edited files can contain messages with null/missing content.
if (message.role === "system" && message.content == null) return [{ ...message, content: "" }];
if (
(message.role === "user" || message.role === "assistant" || message.role === "toolResult") &&
message.content == null
) {
return [{ ...message, content: [] }];
}
return [message];
}
if (entry.type === "custom_message") {
return [
createCustomMessage(entry.customType, entry.content ?? [], entry.display, entry.details, entry.timestamp),
];
}
if (entry.type === "branch_summary" && entry.summary) {
return [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];
}
if (entry.type === "compaction") {
const summary = createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);
return entry.systemMessage ? [entry.systemMessage, summary] : [summary];
}
return [];
}
/**
* Build the active, compaction-aware session entry list.
*
* This follows the current leaf path. If the path contains compaction entries,
* the latest compaction is represented by the compaction entry itself, followed
* by the kept entries starting at firstKeptEntryId and all entries after the
* compaction entry. Older summarized entries are omitted.
*/
export function buildContextEntries(
entries: SessionEntry[],
leafId?: string | null,
byId?: Map<string, SessionEntry>,
): SessionEntry[] {
const path = buildSessionPath(entries, leafId, byId);
let compaction: CompactionEntry | null = null;
for (const entry of path) {
if (entry.type === "compaction") {
compaction = entry;
}
}
if (!compaction) {
return path;
}
const compactionIdx = path.findIndex((entry) => entry.id === compaction.id);
if (compactionIdx < 0) {
return path;
}
const contextEntries: SessionEntry[] = [compaction];
let foundFirstKept = false;
for (let i = 0; i < compactionIdx; i++) {
const entry = path[i];
if (entry.id === compaction.firstKeptEntryId) {
foundFirstKept = true;
}
if (foundFirstKept && !(entry.type === "message" && entry.message.role === "system")) {
contextEntries.push(entry);
}
}
contextEntries.push(...path.slice(compactionIdx + 1));
return contextEntries;
}
/**
* Build the session context from entries using tree traversal.
* If leafId is provided, walks from that entry to root.
* Handles compaction and branch summaries along the path.
*/
function projectContextEntry(entry: SessionEntry, edit: ContextEditEntry | undefined): AgentMessage[] {
const messages = sessionEntryToContextMessages(entry);
if (!edit) return messages;
const replacement = edit.replacement;
if (replacement === null) return [];
return messages.map((message) => {
if (
message.role !== "user" &&
message.role !== "assistant" &&
message.role !== "toolResult" &&
message.role !== "custom"
) {
return message;
}
const content =
(message.role === "assistant" || message.role === "toolResult") && typeof replacement.content === "string"
? [{ type: "text" as const, text: replacement.content }]
: replacement.content;
return { ...message, content } as AgentMessage;
});
}
/** Build provenance-preserving, compaction-aware model context. */
export function buildSessionProjection(
entries: SessionEntry[],
leafId?: string | null,
byId?: Map<string, SessionEntry>,
): SessionProjection {
const path = buildSessionPath(entries, leafId, byId);
const { thinkingLevel, model } = getSessionContextSettings(path);
const contextEntries = buildContextEntries(entries, leafId, byId);
const edits = new Map<string, ContextEditEntry>();
for (const entry of contextEntries) {
if (entry.type === "context_edit") edits.set(entry.targetId, entry);
}
const projectedEntries = contextEntries.map(
(sourceEntry, index): ProjectedSessionEntry => ({
sourceEntry,
// buildContextEntries() may retain an older compaction entry because its
// raw ID lies inside the newest retained range. Only the newest compaction
// at index zero contributes a checkpoint and summary.
messages:
sourceEntry.type === "compaction" && index > 0
? []
: projectContextEntry(sourceEntry, edits.get(sourceEntry.id)),
}),
);
return {
entries: projectedEntries,
messages: projectedEntries.flatMap((entry) => entry.messages),
thinkingLevel,
model,
};
}
/** Build the finalized model context from the canonical session projection. */
export function buildSessionContext(
entries: SessionEntry[],
leafId?: string | null,
byId?: Map<string, SessionEntry>,
): SessionContext {
const { messages, thinkingLevel, model } = buildSessionProjection(entries, leafId, byId);
return { messages, thinkingLevel, model };
}
/**
* Compute the default session directory for a cwd.
* Encodes cwd into a safe directory name under ~/.pi/agent/sessions/.
*/
function getDefaultSessionDirPath(cwd: string, agentDir: string = getDefaultAgentDir()): string {
const resolvedCwd = resolvePath(cwd);
const resolvedAgentDir = resolvePath(agentDir);
const safePath = `--${resolvedCwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
return join(resolvedAgentDir, "sessions", safePath);
}
export function getDefaultSessionDir(cwd: string, agentDir: string = getDefaultAgentDir()): string {
const sessionDir = getDefaultSessionDirPath(cwd, agentDir);
if (!existsSync(sessionDir)) {
mkdirSync(sessionDir, { recursive: true });
}
return sessionDir;
}
const SESSION_READ_BUFFER_SIZE = 1024 * 1024;
const SESSION_HEADER_READ_BUFFER_SIZE = 4096;
/** Bound synchronous header discovery while allowing large cwd and custom metadata fields. */
const MAX_SESSION_HEADER_SCAN_BYTES = 1024 * 1024;
class SessionHeaderScanLimitError extends Error {
constructor(filePath: string) {
super(`Session header exceeds ${MAX_SESSION_HEADER_SCAN_BYTES}-byte scan limit: ${filePath}`);
this.name = "SessionHeaderScanLimitError";
}
}
function parseSessionEntryLine(line: string): FileEntry | null {
if (!line.trim()) return null;
try {
return JSON.parse(line) as FileEntry;
} catch {
// Skip malformed lines
return null;
}
}
/** Exported for testing */
export function loadEntriesFromFile(filePath: string): FileEntry[] {
const resolvedFilePath = normalizePath(filePath);
if (!existsSync(resolvedFilePath)) return [];
const entries: FileEntry[] = [];
let pending = "";
const fd = openSync(resolvedFilePath, "r");
try {
const decoder = new StringDecoder("utf8");
const buffer = Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE);
while (true) {
const bytesRead = readSync(fd, buffer, 0, buffer.length, null);
if (bytesRead === 0) break;
pending += decoder.write(buffer.subarray(0, bytesRead));
let lineStart = 0;
let newlineIndex = pending.indexOf("\n", lineStart);
while (newlineIndex !== -1) {
const entry = parseSessionEntryLine(pending.slice(lineStart, newlineIndex));
if (entry) entries.push(entry);
lineStart = newlineIndex + 1;
newlineIndex = pending.indexOf("\n", lineStart);
}
pending = pending.slice(lineStart);
}
pending += decoder.end();
const finalEntry = parseSessionEntryLine(pending);
if (finalEntry) entries.push(finalEntry);
} finally {
closeSync(fd);
}
// Validate session header before repairing the file.
if (entries.length === 0) return entries;
const header = entries[0];
if (header.type !== "session" || typeof (header as { id?: unknown }).id !== "string") {
return [];
}
if (pending) appendFileSync(resolvedFilePath, "\n");
return entries;
}
/**
* Inspect a physical line while searching for the first parsed session entry.
* Blank and malformed lines are skipped to match loadEntriesFromFile().
* Returns undefined to keep scanning, null for a parsed non-header entry, or the header.
*/
function parseSessionHeaderCandidate(line: string): SessionHeader | null | undefined {
if (!line.trim()) return undefined;
const entry = parseSessionEntryLine(line);
if (!entry) return undefined;
if (entry.type !== "session" || typeof (entry as { id?: unknown }).id !== "string") return null;
return entry;
}
function readSessionHeader(filePath: string): SessionHeader | null {
const fd = openSync(filePath, "r");
try {
const decoder = new StringDecoder("utf8");
const buffer = Buffer.allocUnsafe(SESSION_HEADER_READ_BUFFER_SIZE);
const lineChunks: string[] = [];
let scannedBytes = 0;
while (scannedBytes < MAX_SESSION_HEADER_SCAN_BYTES) {
const readLength = Math.min(buffer.length, MAX_SESSION_HEADER_SCAN_BYTES - scannedBytes);
const bytesRead = readSync(fd, buffer, 0, readLength, null);
if (bytesRead === 0) {
lineChunks.push(decoder.end());
return parseSessionHeaderCandidate(lineChunks.join("")) ?? null;
}
scannedBytes += bytesRead;
const chunk = decoder.write(buffer.subarray(0, bytesRead));
let lineStart = 0;
let newlineIndex = chunk.indexOf("\n", lineStart);
while (newlineIndex !== -1) {
lineChunks.push(chunk.slice(lineStart, newlineIndex));
const header = parseSessionHeaderCandidate(lineChunks.join(""));
if (header !== undefined) return header;
lineChunks.length = 0;
lineStart = newlineIndex + 1;
newlineIndex = chunk.indexOf("\n", lineStart);
}
lineChunks.push(chunk.slice(lineStart));
}
// Probe for EOF so a final header without a newline is allowed when it ends
// exactly at the scan limit. Any additional byte exceeds the bounded scan.
const probe = Buffer.allocUnsafe(1);
if (readSync(fd, probe, 0, probe.length, null) === 0) {
lineChunks.push(decoder.end());
return parseSessionHeaderCandidate(lineChunks.join("")) ?? null;
}
throw new SessionHeaderScanLimitError(filePath);
} finally {
closeSync(fd);
}
}
function readSessionHeaderForDiscovery(filePath: string): SessionHeader | null {
try {
return readSessionHeader(filePath);
} catch {
// Discovery is best-effort: unreadable or oversized files are not sessions,
// and one corrupt file must not prevent other sessions from being found.
return null;
}
}
function getSessionHeaderCwd(header: SessionHeader): string | undefined {
const cwd = (header as { cwd?: unknown }).cwd;
return typeof cwd === "string" ? cwd : undefined;
}
function sessionCwdMatches(cwd: string | undefined, resolvedCwd: string): boolean {
return cwd !== undefined && cwd !== "" && resolvePath(cwd) === resolvedCwd;
}
/** Exported for testing */
export function findMostRecentSession(sessionDir: string, cwd?: string): string | null {
const resolvedSessionDir = normalizePath(sessionDir);
const resolvedCwd = cwd ? resolvePath(cwd) : undefined;
try {
const files = readdirSync(resolvedSessionDir)
.filter((file) => file.endsWith(".jsonl"))
.map((file) => join(resolvedSessionDir, file))
.map((path) => ({ path, mtime: statSync(path).mtimeMs }))
.sort((a, b) => b.mtime - a.mtime);
for (const { path } of files) {
const header = readSessionHeaderForDiscovery(path);
if (header && (!resolvedCwd || sessionCwdMatches(getSessionHeaderCwd(header), resolvedCwd))) return path;
}
return null;
} catch {
// Directory access and stat races make recent-session discovery unavailable.
return null;
}
}
function isMessageWithContent(message: AgentMessage): message is Message {
return typeof (message as Message).role === "string" && "content" in message;
}
function extractTextContent(message: Message): string {
const content = message.content;
if (typeof content === "string") {
return content;
}
return content
.filter((block): block is TextContent => block.type === "text")
.map((block) => block.text)
.join(" ");
}
function getMessageActivityTime(entry: SessionMessageEntry): number | undefined {
const message = entry.message;
if (!isMessageWithContent(message)) return undefined;
if (message.role !== "user" && message.role !== "assistant") return undefined;
const msgTimestamp = (message as { timestamp?: number }).timestamp;
if (typeof msgTimestamp === "number") {
return msgTimestamp;
}
const t = new Date(entry.timestamp).getTime();
return Number.isNaN(t) ? undefined : t;
}
async function buildSessionInfo(
filePath: string,
signal?: AbortSignal,
fileStats?: Stats,
): Promise<SessionInfo | null> {
try {
const stats = fileStats ?? (await stat(filePath));
let header: SessionHeader | null = null;
let messageCount = 0;
let firstMessage = "";
const allMessages: string[] = [];
let name: string | undefined;
let lastActivityTime: number | undefined;
const rl = createInterface({
input: createReadStream(filePath, { encoding: "utf8", signal }),
crlfDelay: Infinity,
});
for await (const line of rl) {
const entry = parseSessionEntryLine(line);
if (!entry) continue;
if (!header) {
if (entry.type !== "session") return null;
header = entry;
continue;
}
// Extract session name (use latest, including explicit clears)
if (entry.type === "session_info") {
name = entry.name?.trim() || undefined;
}
if (entry.type !== "message") continue;
messageCount++;
const activityTime = getMessageActivityTime(entry);
if (typeof activityTime === "number") {
lastActivityTime = Math.max(lastActivityTime ?? 0, activityTime);
}
const message = entry.message;
if (!isMessageWithContent(message)) continue;
if (message.role !== "user" && message.role !== "assistant") continue;
const textContent = extractTextContent(message);
if (!textContent) continue;
allMessages.push(textContent);
if (!firstMessage && message.role === "user") {
firstMessage = textContent;
}
}
if (!header) return null;
const cwd = typeof header.cwd === "string" ? header.cwd : "";
const parentSessionPath = header.parentSession;
const headerTime = typeof header.timestamp === "string" ? new Date(header.timestamp).getTime() : NaN;
const modified =
typeof lastActivityTime === "number" && lastActivityTime > 0
? new Date(lastActivityTime)
: !Number.isNaN(headerTime)
? new Date(headerTime)
: stats.mtime;
return {
path: filePath,
id: header.id,
cwd,
name,
parentSessionPath,
created: new Date(header.timestamp),
modified,
messageCount,
firstMessage: firstMessage || "(no messages)",
allMessagesText: allMessages.join(" "),
};
} catch {
signal?.throwIfAborted();
return null;
}
}
export type SessionListProgress = (
loaded: number,
total: number,
/** Sessions loaded so far, sorted by activity. Present on periodic updates. */
partialSessions?: readonly SessionInfo[],
) => void;
const MAX_CONCURRENT_SESSION_INFO_LOADS = 10;
const MAX_CONCURRENT_SESSION_DISCOVERY_LOADS = 64;
const CURRENT_SESSION_LIST_PUBLISH_INTERVAL = 10;
const ALL_SESSION_LIST_PUBLISH_INTERVAL = 100;
interface SessionFileCandidate {
path: string;
stats?: Stats;
}
async function mapWithConcurrency<T, R>(
items: T[],
limit: number,
map: (item: T, index: number) => Promise<R>,
signal?: AbortSignal,
): Promise<R[]> {
const results = new Array<R>(items.length);
let nextIndex = 0;
const worker = async (): Promise<void> => {
while (nextIndex < items.length) {
signal?.throwIfAborted();
const index = nextIndex++;
results[index] = await map(items[index]!, index);
}
};
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
return results;
}
function sortSessionInfos(sessions: SessionInfo[]): SessionInfo[] {
return sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
}
function buildSessionInfosWithConcurrency(
files: SessionFileCandidate[],
onLoaded: (info: SessionInfo | null, index: number) => void,
signal?: AbortSignal,
): Promise<(SessionInfo | null)[]> {
return mapWithConcurrency(
files,
MAX_CONCURRENT_SESSION_INFO_LOADS,
async (file, index) => {
const info = await buildSessionInfo(file.path, signal, file.stats);
onLoaded(info, index);
return info;
},
signal,
);
}
async function listSessionsFromDir(
dir: string,
onProgress?: SessionListProgress,
signal?: AbortSignal,
): Promise<SessionInfo[]> {
signal?.throwIfAborted();
if (!existsSync(dir)) return [];
try {
const dirEntries = await readdir(dir);
const files = dirEntries
.filter((file) => file.endsWith(".jsonl"))
.sort((a, b) => b.localeCompare(a))
.map((file) => ({ path: join(dir, file) }));
const total = files.length;
const partialSessions: SessionInfo[] = [];
let loaded = 0;
const results = await buildSessionInfosWithConcurrency(
files,
(info) => {
loaded++;
if (info) partialSessions.push(info);
const publishPartial =
loaded === 1 || loaded % CURRENT_SESSION_LIST_PUBLISH_INTERVAL === 0 || loaded === files.length;
onProgress?.(loaded, total, publishPartial ? sortSessionInfos([...partialSessions]) : undefined);
},
signal,
);
return results.filter((info): info is SessionInfo => info !== null);
} catch {
signal?.throwIfAborted();
return [];
}
}
/**
* Manages conversation sessions as append-only trees stored in JSONL files.
*
* Each session entry has an id and parentId forming a tree structure. The "leaf"
* pointer tracks the current position. Appending creates a child of the current leaf.
* Branching moves the leaf to an earlier entry, allowing new branches without
* modifying history.
*
* Use buildSessionContext() to get the resolved message list for the LLM, which
* handles compaction summaries and follows the path from root to current leaf.
*/
export class SessionManager {
private sessionId: string = "";
private sessionFile: string | undefined;
private sessionDir: string;
private cwd: string;
private persist: boolean;
private flushed: boolean = false;
private fileEntries: FileEntry[] = [];
private byId: Map<string, SessionEntry> = new Map();
private labelsById: Map<string, string> = new Map();
private labelTimestampsById: Map<string, string> = new Map();
private leafId: string | null = null;
private constructor(