-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathsession-manager.ts
More file actions
2137 lines (1912 loc) · 62.2 KB
/
Copy pathsession-manager.ts
File metadata and controls
2137 lines (1912 loc) · 62.2 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, ImageContent, Message, ServiceTier, TextContent, Usage } from "@earendil-works/pi-ai";
import { randomUUID } from "crypto";
import {
appendFileSync,
chmodSync,
chownSync,
existsSync,
mkdirSync,
readdirSync,
readFileSync,
realpathSync,
renameSync,
rmSync,
statSync,
writeFileSync,
} from "fs";
import { readdir, readFile, stat } from "fs/promises";
import { basename, dirname, join, resolve } from "path";
import { v7 as uuidv7 } from "uuid";
import { getAgentDir as getDefaultAgentDir, getSessionsDir } from "../config.js";
import { readFirstLineSync, readLinesAsBuffers } from "../utils/file-lines.js";
import { captureGitContext, type GitContext, gitContextsEqual } from "../utils/git.js";
import {
type BashExecutionMessage,
type CustomMessage,
createBranchSummaryMessage,
createCompactionSummaryMessage,
createCustomMessage,
} from "./messages.js";
import {
addAssistantUsage,
cloneUsage,
emptyUsage,
type SessionUsageSummary,
sessionUsageSummaryFrom,
subtractAssistantUsage,
} from "./usage.js";
export const CURRENT_SESSION_VERSION = 3;
const SESSION_LIST_SEARCH_TEXT_MAX_CHARS = 64 * 1024;
const SESSION_LIST_PARSE_MAX_LINE_CHARS = 1024 * 1024;
const SESSION_LIST_LARGE_MESSAGE_PREVIEW_MAX_CHARS = 256;
const SESSION_STREAMING_LOAD_THRESHOLD_BYTES = 128 * 1024 * 1024;
const SESSION_ASYNC_PARSE_YIELD_BYTES = 4 * 1024 * 1024;
// Entry types that can represent user intent (vs. daemon bookkeeping like
// session_state/agent_status/git_state/child_usage_attributed). Used by
// hasUserContent to decide whether a message-less draft is safe to discard.
const CONTENT_ENTRY_TYPES = new Set([
"message",
"custom_message",
"custom",
"model_change",
"thinking_level_change",
"service_tier_change",
"session_info",
"label",
"compaction",
"branch_summary",
]);
function realpathIfPresent(path: string): string {
try {
return realpathSync(path);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return path;
throw error;
}
}
function statMetadataIfPresent(path: string): { mode: number; uid: number; gid: number } | undefined {
try {
const { mode, uid, gid } = statSync(path);
return { mode: mode & 0o777, uid, gid };
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
throw error;
}
}
export interface SessionHeader {
type: "session";
version?: number; // v1 sessions don't have this
id: string;
timestamp: string;
cwd: string;
parentSession?: string;
rlmDepth?: number;
git?: GitContext;
}
export interface NewSessionOptions {
id?: string;
parentSession?: string;
rlmDepth?: number;
}
export type SessionPersistListener = (sessionFile: string) => void;
export interface SessionEntryBase {
type: string;
id: string;
parentId: string | null;
timestamp: string;
}
export interface SessionMessageEntry extends SessionEntryBase {
type: "message";
message: AgentMessage;
}
type AssistantSessionMessageEntry = SessionMessageEntry & { message: AssistantMessage };
export interface ThinkingLevelChangeEntry extends SessionEntryBase {
type: "thinking_level_change";
thinkingLevel: string;
}
export interface ServiceTierChangeEntry extends SessionEntryBase {
type: "service_tier_change";
serviceTier: ServiceTier;
}
export interface ModelChangeEntry extends SessionEntryBase {
type: "model_change";
provider: string;
modelId: string;
}
export interface CompactionEntry<T = unknown> extends SessionEntryBase {
type: "compaction";
summary: string;
firstKeptEntryId: string;
tokensBefore: number;
details?: T;
fromHook?: boolean;
customInstructions?: string;
usage?: Usage;
}
export interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {
type: "branch_summary";
fromId: string;
summary: string;
details?: T;
fromHook?: boolean;
usage?: Usage;
}
export interface CustomEntry<T = unknown> extends SessionEntryBase {
type: "custom";
customType: string;
data?: T;
}
/**
* Records usage folded into a parent assistant message after an RLM child run.
* The child usage is kept separately so audit/UI code can explain why the
* parent turn's aggregate usage exceeds the parent model response itself.
*/
export interface ChildUsageAttributionEntry extends SessionEntryBase {
type: "child_usage_attributed";
targetId: string;
childUsage: Usage;
aggregateUsage: Usage;
origin?: "spawn_task" | "agent_message" | "direct_user";
}
export interface LabelEntry extends SessionEntryBase {
type: "label";
targetId: string;
label: string | undefined;
}
export interface SessionInfoEntry extends SessionEntryBase {
type: "session_info";
name?: string;
}
export type SessionStateStatus = "active" | "archived" | "crash";
export interface SessionState {
status: SessionStateStatus;
}
export interface SessionStateEntry extends SessionEntryBase {
type: "session_state";
state: SessionState;
}
export type AgentTaskState = "needs_input" | "completed";
export interface AgentStatus {
summary: string;
taskState?: AgentTaskState;
basedOnMessageCount: number;
}
export interface AgentStatusEntry extends SessionEntryBase {
type: "agent_status";
status: AgentStatus;
}
export interface GitStateEntry extends SessionEntryBase {
type: "git_state";
git: GitContext;
}
export interface CustomMessageEntry<T = unknown> extends SessionEntryBase {
type: "custom_message";
customType: string;
content: string | (TextContent | ImageContent)[];
details?: T;
display: boolean;
}
export type SessionEntry =
| SessionMessageEntry
| ThinkingLevelChangeEntry
| ServiceTierChangeEntry
| ModelChangeEntry
| CompactionEntry
| BranchSummaryEntry
| CustomEntry
| ChildUsageAttributionEntry
| CustomMessageEntry
| LabelEntry
| SessionInfoEntry
| SessionStateEntry
| AgentStatusEntry
| GitStateEntry;
export type FileEntry = SessionHeader | SessionEntry;
export interface SessionTreeFlatNode {
entry: SessionEntry;
label?: string;
labelTimestamp?: string;
}
export interface SessionTreeNode extends SessionTreeFlatNode {
children: SessionTreeNode[];
}
export interface SessionContext {
messages: AgentMessage[];
thinkingLevel: string;
serviceTier: ServiceTier;
model: { provider: string; modelId: string } | null;
}
export interface SessionInfo {
path: string;
id: string;
cwd: string;
name?: string;
state?: SessionState;
parentSessionPath?: string;
rlmDepth: number;
created: Date;
modified: Date;
messageCount: number;
firstMessage: string;
allMessagesText: string;
agentStatus?: AgentStatus;
usage?: SessionUsageSummary;
}
export type ReadonlySessionManager = Pick<
SessionManager,
| "getCwd"
| "getSessionDir"
| "getSessionId"
| "getSessionFile"
| "getLeafId"
| "getLeafEntry"
| "getEntry"
| "getLabel"
| "getBranch"
| "getHeader"
| "getEntries"
| "getTree"
| "getSessionName"
>;
function createSessionId(): string {
return uuidv7();
}
function getSessionFilePath(sessionDir: string, sessionId: string): string {
return join(sessionDir, `${sessionId}.jsonl`);
}
function createUniqueSessionFileTarget(sessionDir: string): { sessionId: string; sessionFile: string } {
for (let i = 0; i < 100; i++) {
const sessionId = createSessionId();
const sessionFile = getSessionFilePath(sessionDir, sessionId);
if (!existsSync(sessionFile)) {
return { sessionId, sessionFile };
}
}
throw new Error("Unable to create a unique session file");
}
export function getSessionArtifactsRoot(sessionDir: string): string {
return join(dirname(sessionDir), "session-artifacts");
}
export function getSessionArtifactPath(sessionDir: string, sessionId: string): string {
return join(getSessionArtifactsRoot(sessionDir), sessionId);
}
export function getSessionArtifactPathForFile(sessionFile: string, sessionId?: string): string {
return getSessionArtifactPath(dirname(sessionFile), sessionId ?? basename(sessionFile).replace(/\.jsonl$/, ""));
}
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;
}
return randomUUID();
}
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;
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;
}
}
}
}
function migrateV2ToV3(entries: FileEntry[]): void {
for (const entry of entries) {
if (entry.type === "session") {
entry.version = 3;
continue;
}
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";
}
}
}
}
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;
}
export function migrateSessionEntries(entries: FileEntry[]): void {
migrateToCurrentVersion(entries);
}
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.
}
}
applyChildUsageAttributions(entries);
return entries;
}
function applyChildUsageAttributions(entries: FileEntry[]): void {
const assistantEntriesById = new Map<string, AssistantSessionMessageEntry>();
for (const entry of entries) {
if (entry.type === "message" && entry.message.role === "assistant") {
assistantEntriesById.set(entry.id, entry as AssistantSessionMessageEntry);
}
}
for (const entry of entries) {
if (entry.type !== "child_usage_attributed") continue;
const target = assistantEntriesById.get(entry.targetId);
if (!target) continue;
target.message.usage = cloneUsage(entry.aggregateUsage);
}
}
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;
}
export function buildSessionContext(
entries: SessionEntry[],
leafId?: string | null,
byId?: Map<string, SessionEntry>,
): SessionContext {
if (!byId) {
byId = new Map<string, SessionEntry>();
for (const entry of entries) {
byId.set(entry.id, entry);
}
}
let leaf: SessionEntry | undefined;
if (leafId === null) {
return { messages: [], thinkingLevel: "off", serviceTier: "default", model: null };
}
if (leafId) {
leaf = byId.get(leafId);
}
if (!leaf) {
leaf = entries[entries.length - 1];
}
if (!leaf) {
return { messages: [], thinkingLevel: "off", serviceTier: "default", model: null };
}
// push+reverse, not unshift-per-entry: unshift is O(n), making this O(n^2) on long sessions.
const path: SessionEntry[] = [];
let current: SessionEntry | undefined = leaf;
while (current) {
path.push(current);
current = current.parentId ? byId.get(current.parentId) : undefined;
}
path.reverse();
let thinkingLevel = "off";
let serviceTier: ServiceTier = "default";
let model: { provider: string; modelId: string } | null = null;
let compaction: CompactionEntry | null = null;
for (const entry of path) {
if (entry.type === "thinking_level_change") {
thinkingLevel = entry.thinkingLevel;
} else if (entry.type === "service_tier_change") {
serviceTier = entry.serviceTier;
} 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 };
} else if (entry.type === "compaction") {
compaction = entry;
}
}
// Build messages and collect corresponding entries
// When there's a compaction, model context remains summary-first while the
// summary records where clients should present it among retained messages.
const messages: AgentMessage[] = [];
const appendMessage = (entry: SessionEntry, target = messages) => {
if (entry.type === "message") {
target.push(entry.message);
} else if (entry.type === "custom_message") {
target.push(
createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp),
);
} else if (entry.type === "branch_summary" && entry.summary) {
target.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));
}
};
if (compaction) {
const compactionIdx = path.findIndex((e) => e.type === "compaction" && e.id === compaction.id);
// Collect kept messages (before compaction, starting from firstKeptEntryId).
// The context remains summary-first for the model; retainedMessageCount records
// the exact chronological presentation boundary for clients.
const retainedMessages: AgentMessage[] = [];
let foundFirstKept = false;
for (let i = 0; i < compactionIdx; i++) {
const entry = path[i];
if (entry.id === compaction.firstKeptEntryId) {
foundFirstKept = true;
}
if (foundFirstKept) {
appendMessage(entry, retainedMessages);
}
}
messages.push(
createCompactionSummaryMessage(
compaction.summary,
compaction.tokensBefore,
compaction.timestamp,
compaction.customInstructions,
retainedMessages.length,
),
...retainedMessages,
);
for (let i = compactionIdx + 1; i < path.length; i++) {
const entry = path[i];
appendMessage(entry);
}
} else {
for (const entry of path) {
appendMessage(entry);
}
}
return { messages, thinkingLevel, serviceTier, model };
}
export function getDefaultSessionDir(_cwd: string, agentDir: string = getDefaultAgentDir()): string {
const sessionDir = getSessionsDir(agentDir);
if (!existsSync(sessionDir)) {
mkdirSync(sessionDir, { recursive: true });
}
return sessionDir;
}
// Decode per line off a Buffer: toString("utf8") on a whole large file is far slower
// (one giant UTF-16 string). Splitting on 0x0a is UTF-8-safe.
function appendEntryFromBuffer(entries: FileEntry[], buffer: Buffer, start = 0, end = buffer.length): void {
if (end <= start) return;
try {
entries.push(JSON.parse(buffer.toString("utf8", start, end)) as FileEntry);
} catch {
// Skip malformed or blank lines.
}
}
function parseEntriesFromBuffer(buffer: Buffer): FileEntry[] {
const entries: FileEntry[] = [];
let start = 0;
while (start < buffer.length) {
let end = buffer.indexOf(0x0a, start);
if (end === -1) end = buffer.length;
appendEntryFromBuffer(entries, buffer, start, end);
start = end + 1;
}
return entries;
}
async function parseEntriesFromBufferAsync(buffer: Buffer): Promise<FileEntry[]> {
const entries: FileEntry[] = [];
let start = 0;
let bytesSinceYield = 0;
while (start < buffer.length) {
let end = buffer.indexOf(0x0a, start);
if (end === -1) end = buffer.length;
appendEntryFromBuffer(entries, buffer, start, end);
bytesSinceYield += end - start + 1;
start = end + 1;
if (bytesSinceYield >= SESSION_ASYNC_PARSE_YIELD_BYTES) {
bytesSinceYield = 0;
await new Promise<void>((resolve) => setImmediate(resolve));
}
}
return entries;
}
function finalizeLoadedEntries(entries: FileEntry[]): FileEntry[] {
if (entries.length === 0) return entries;
const header = entries[0];
if (header.type !== "session" || typeof (header as any).id !== "string") {
return [];
}
applyChildUsageAttributions(entries);
return entries;
}
export function loadEntriesFromFile(filePath: string): FileEntry[] {
if (!existsSync(filePath)) return [];
return finalizeLoadedEntries(parseEntriesFromBuffer(readFileSync(filePath)));
}
// Async loader for the daemon: reads off the event loop and yields while parsing so a
// large load doesn't freeze other sessions. Large files stream to avoid retaining both
// the full input Buffer and the parsed entry graph at the same time.
export async function loadEntriesFromFileAsync(
filePath: string,
options: { streamThresholdBytes?: number } = {},
): Promise<FileEntry[]> {
if (!existsSync(filePath)) return [];
const streamThresholdBytes = options.streamThresholdBytes ?? SESSION_STREAMING_LOAD_THRESHOLD_BYTES;
if ((await stat(filePath)).size < streamThresholdBytes) {
return finalizeLoadedEntries(await parseEntriesFromBufferAsync(await readFile(filePath)));
}
const entries: FileEntry[] = [];
let bytesSinceYield = 0;
for await (const line of readLinesAsBuffers(filePath)) {
appendEntryFromBuffer(entries, line);
bytesSinceYield += line.length + 1;
if (bytesSinceYield >= SESSION_ASYNC_PARSE_YIELD_BYTES) {
bytesSinceYield = 0;
await new Promise<void>((resolve) => setImmediate(resolve));
}
}
return finalizeLoadedEntries(entries);
}
function readSessionHeader(filePath: string): Partial<SessionHeader> | undefined {
const firstLine = readFirstLineSync(filePath);
if (!firstLine) {
return undefined;
}
return JSON.parse(firstLine) as Partial<SessionHeader>;
}
function isValidRlmDepth(value: unknown): value is number {
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
}
export function resolveSessionRlmDepth(
header: { rlmDepth?: number; parentSession?: string },
sessionPath: string,
): number {
return resolveLegacySessionRlmDepth(header, sessionPath, new Set()) ?? legacyChildDepthFromPath(sessionPath);
}
function resolveLegacySessionRlmDepth(
header: { rlmDepth?: number; parentSession?: string },
sessionPath: string,
visitedPaths: Set<string>,
): number | undefined {
if (isValidRlmDepth(header.rlmDepth)) {
return header.rlmDepth;
}
if (!header.parentSession) {
return 0;
}
const resolvedSessionPath = resolve(sessionPath);
if (visitedPaths.has(resolvedSessionPath)) {
return undefined;
}
visitedPaths.add(resolvedSessionPath);
const pathDepth = legacyChildDepthFromPath(sessionPath);
const parentSessionPath = resolve(dirname(sessionPath), header.parentSession);
try {
const parentHeader = readSessionHeader(parentSessionPath);
if (parentHeader) {
const parentDepth = resolveLegacySessionRlmDepth(parentHeader, parentSessionPath, visitedPaths);
if (parentDepth !== undefined) {
return pathDepth > 0 ? parentDepth + 1 : parentDepth;
}
}
} catch {
// Fall back to artifact ancestry for unavailable or invalid legacy parents.
} finally {
visitedPaths.delete(resolvedSessionPath);
}
return pathDepth;
}
function legacyChildDepthFromPath(sessionPath: string): number {
let depth = 0;
for (const segment of dirname(sessionPath)
.split(/[\\/]+/)
.reverse()) {
if (!/^sub-[0-9a-f]{8}$/.test(segment)) {
break;
}
depth += 1;
}
return depth;
}
function deriveChildRlmDepth(parentHeader: Partial<SessionHeader> | undefined): number | undefined {
const depth = parentHeader?.rlmDepth;
return isValidRlmDepth(depth) && depth < Number.MAX_SAFE_INTEGER ? depth + 1 : undefined;
}
function rootRlmDepthFromEnv(): number {
const value = process.env.RLM_DEPTH;
if (value === undefined || value === "") {
return 0;
}
const parsed = Number(value);
if (!/^\d+$/.test(value) || !isValidRlmDepth(parsed)) {
throw new Error("RLM_DEPTH must be a non-negative integer");
}
return parsed;
}
function isValidSessionFile(filePath: string): boolean {
try {
const header = readSessionHeader(filePath);
return header?.type === "session" && typeof header.id === "string";
} catch {
return false;
}
}
export function findMostRecentSession(sessionDir: string): string | null {
try {
const files = readdirSync(sessionDir)
.filter((f) => f.endsWith(".jsonl"))
.map((f) => join(sessionDir, f))
.filter(isValidSessionFile)
.map((path) => ({ path, mtime: statSync(path).mtime }))
.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
return files[0]?.path || null;
} catch {
return null;
}
}
function normalizeCwd(cwd: string): string {
return resolve(cwd);
}
function sessionInfoMatchesCwd(session: SessionInfo, cwd: string): boolean {
return !!session.cwd && normalizeCwd(session.cwd) === normalizeCwd(cwd);
}
function sessionHeaderMatchesCwd(header: Partial<SessionHeader> | undefined, cwd: string): boolean {
return (
header?.type === "session" &&
typeof header.id === "string" &&
typeof header.cwd === "string" &&
normalizeCwd(header.cwd) === normalizeCwd(cwd)
);
}
export function findMostRecentSessionForCwd(sessionDir: string, cwd: string): string | null {
try {
const files = readdirSync(sessionDir)
.filter((f) => f.endsWith(".jsonl"))
.map((f) => join(sessionDir, f))
.map((path) => {
try {
const header = readSessionHeader(path);
if (!sessionHeaderMatchesCwd(header, cwd)) {
return undefined;
}
return { path, mtime: statSync(path).mtime };
} catch {
return undefined;
}
})
.filter((entry): entry is { path: string; mtime: Date } => entry !== undefined)
.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
return files[0]?.path || null;
} catch {
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 normalizeSessionStateStatus(value: unknown): SessionStateStatus | undefined {
if (value === "active" || value === "archived" || value === "crash") {
return value;
}
if (value === "hidden" || value === "sleep") {
return "archived";
}
return undefined;
}
function updateLastActivityTime(lastActivityTime: number | undefined, entry: FileEntry): number | undefined {
if (entry.type !== "message") {
return lastActivityTime;
}
const message = (entry as SessionMessageEntry).message;
if (!isMessageWithContent(message)) {
return lastActivityTime;
}
if (message.role !== "user" && message.role !== "assistant") {
return lastActivityTime;
}
const msgTimestamp = (message as { timestamp?: number }).timestamp;
if (typeof msgTimestamp === "number") {
return Math.max(lastActivityTime ?? 0, msgTimestamp);
}
const entryTimestamp = (entry as SessionEntryBase).timestamp;
if (typeof entryTimestamp === "string") {
const t = new Date(entryTimestamp).getTime();
if (!Number.isNaN(t)) {
return Math.max(lastActivityTime ?? 0, t);
}
}
return lastActivityTime;
}
function getSessionModifiedDateFromLastActivity(
lastActivityTime: number | undefined,
header: SessionHeader,
statsMtime: Date,
): Date {
if (typeof lastActivityTime === "number" && lastActivityTime > 0) {
return new Date(lastActivityTime);
}
const headerTime = typeof header.timestamp === "string" ? new Date(header.timestamp).getTime() : NaN;
return !Number.isNaN(headerTime) ? new Date(headerTime) : statsMtime;
}
function appendCappedSearchText(current: string, text: string): string {
if (!text || current.length >= SESSION_LIST_SEARCH_TEXT_MAX_CHARS) {
return current;
}
const next = current ? ` ${text}` : text;
return current + next.slice(0, SESSION_LIST_SEARCH_TEXT_MAX_CHARS - current.length);
}
function looksLikeMessageEntry(line: string): boolean {
return line.includes('"type":"message"') || line.includes('"type": "message"');
}
function extractJsonStringPropertyPrefix(
text: string,
propertyName: string,
maxChars: number,
startIndex = 0,
): string | undefined {
const propertyIndex = text.indexOf(`"${propertyName}"`, startIndex);
if (propertyIndex < 0) {
return undefined;
}
let index = propertyIndex + propertyName.length + 2;
while (index < text.length && /\s/.test(text[index] ?? "")) index++;
if (text[index] !== ":") {
return undefined;
}
index++;
while (index < text.length && /\s/.test(text[index] ?? "")) index++;
if (text[index] !== '"') {
return undefined;
}
index++;
let result = "";
let escaped = false;
for (; index < text.length && result.length < maxChars; index++) {
const char = text[index];
if (escaped) {
result += char;
escaped = false;
continue;
}
if (char === "\\") {
escaped = true;
continue;
}
if (char === '"') {
break;
}
result += char;
}
return result;
}
function extractOversizedMessageSummary(line: string): {
role?: string;
timestamp?: number;
textPreview?: string;
} {
const timestampText = extractJsonStringPropertyPrefix(line, "timestamp", 64);
const timestamp = timestampText ? new Date(timestampText).getTime() : NaN;
const messageIndex = line.indexOf('"message"');
const role =
messageIndex >= 0
? extractJsonStringPropertyPrefix(line, "role", 64, messageIndex)
: extractJsonStringPropertyPrefix(line, "role", 64);
let textPreview: string | undefined;
if (messageIndex >= 0) {
textPreview =
extractJsonStringPropertyPrefix(line, "content", SESSION_LIST_LARGE_MESSAGE_PREVIEW_MAX_CHARS, messageIndex) ??
extractJsonStringPropertyPrefix(line, "text", SESSION_LIST_LARGE_MESSAGE_PREVIEW_MAX_CHARS, messageIndex);
}
return {
role,
...(Number.isNaN(timestamp) ? {} : { timestamp }),
...(textPreview ? { textPreview } : {}),
};
}
interface SessionInfoCacheEntry {
size: number;
mtimeMs: number;
info: SessionInfo | null;
}
// Session files are append-only, so an unchanged (size, mtimeMs) means identical
// content: cache list metadata and rescan only files that changed.
const sessionInfoCache = new Map<string, SessionInfoCacheEntry>();
export async function readSessionInfo(filePath: string): Promise<SessionInfo | null> {
let stats: Awaited<ReturnType<typeof stat>>;
try {
stats = await stat(filePath);
} catch {
return null;
}
const cached = sessionInfoCache.get(filePath);
if (cached && cached.size === stats.size && cached.mtimeMs === stats.mtimeMs) {
return cached.info;
}
const info = await scanSessionInfo(filePath, stats);
sessionInfoCache.set(filePath, { size: stats.size, mtimeMs: stats.mtimeMs, info });
return info;
}
async function scanSessionInfo(filePath: string, stats: Awaited<ReturnType<typeof stat>>): Promise<SessionInfo | null> {
try {
let header: SessionHeader | undefined;
let messageCount = 0;
let firstMessage = "";
let allMessagesText = "";
let name: string | undefined;
let state: SessionState | undefined;
let agentStatus: AgentStatus | undefined;
let lastActivityTime: number | undefined;
// Fold attribution aggregates like the loader: either disk representation cancels to the same own spend.
const assistantUsageById = new Map<string, Usage>();
const attributedChildUsages: Usage[] = [];
const summarizationUsages: Usage[] = [];
for await (const lineBuffer of readLinesAsBuffers(filePath)) {
const line = lineBuffer.toString("utf8");
if (!line.trim()) continue;
// Large tool-result entries can be many MB. They do not carry the
// session-list metadata we need, and parsing them during every refresh
// can exhaust the daemon heap.
if (line.length > SESSION_LIST_PARSE_MAX_LINE_CHARS) {
if (looksLikeMessageEntry(line)) {
messageCount++;
const summary = extractOversizedMessageSummary(line);
if (typeof summary.timestamp === "number" && (summary.role === "user" || summary.role === "assistant")) {
lastActivityTime = Math.max(lastActivityTime ?? 0, summary.timestamp);
}
if (summary.role === "user" && !firstMessage) {
firstMessage = summary.textPreview || "(large message)";
}
}
continue;
}
const trimmed = line.trim();
let entry: FileEntry;
try {
entry = JSON.parse(trimmed) as FileEntry;
} catch {
continue;
}
if (entry.type === "session_info") {