Repository navigation
Expand file tree
/
Copy pathsession-manager.ts
More file actions
2722 lines (2443 loc) · 84.7 KB
/
Copy pathsession-manager.ts
File metadata and controls
2722 lines (2443 loc) · 84.7 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 * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import type { AgentMessage } from "@oh-my-pi/pi-agent-core";
import type {
ImageContent,
Message,
MessageAttribution,
ProviderPayload,
ServiceTier,
TextContent,
Usage,
} from "@oh-my-pi/pi-ai";
import { getTerminalId } from "@oh-my-pi/pi-tui";
import {
getBlobsDir,
getAgentDir as getDefaultAgentDir,
getProjectDir,
getSessionsDir,
getTerminalSessionsDir,
isEnoent,
logger,
parseJsonlLenient,
pathIsWithin,
resolveEquivalentPath,
Snowflake,
toError,
} from "@oh-my-pi/pi-utils";
import { ArtifactManager } from "./artifacts";
import {
type BlobPutResult,
BlobStore,
externalizeImageData,
externalizeImageDataUrl,
isBlobRef,
isImageDataUrl,
resolveImageData,
resolveImageDataUrl,
} from "./blob-store";
import {
type BashExecutionMessage,
type CustomMessage,
createBranchSummaryMessage,
createCompactionSummaryMessage,
createCustomMessage,
type FileMentionMessage,
type HookMessage,
type PythonExecutionMessage,
sanitizeRehydratedOpenAIResponsesAssistantMessage,
type TurnEndMessage,
type TurnStartMessage,
} from "./messages";
import type { SessionStorage, SessionStorageWriter } from "./session-storage";
import { FileSessionStorage, MemorySessionStorage } from "./session-storage";
export const CURRENT_SESSION_VERSION = 3;
export interface SessionHeader {
type: "session";
version?: number; // v1 sessions don't have this
id: string;
title?: string; // Auto-generated title from first message
timestamp: string;
cwd: string;
parentSession?: string;
}
export interface NewSessionOptions {
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 | null;
}
export interface ModelChangeEntry extends SessionEntryBase {
type: "model_change";
/** Model in "provider/modelId" format */
model: string;
/** Role: "default", "smol", "slow", etc. Undefined treated as "default" */
role?: string;
}
export interface ServiceTierChangeEntry extends SessionEntryBase {
type: "service_tier_change";
serviceTier: ServiceTier | null;
}
export interface CompactionEntry<T = unknown> extends SessionEntryBase {
type: "compaction";
summary: string;
shortSummary?: string;
firstKeptEntryId: string;
tokensBefore: number;
/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */
details?: T;
/** Hook-provided data to persist across compaction */
preserveData?: Record<string, unknown>;
/** True if generated by an extension, undefined/false if pi-generated (backward compatible) */
fromExtension?: boolean;
}
export interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {
type: "branch_summary";
fromId: string;
summary: string;
/** Extension-specific data (not sent to LLM) */
details?: T;
/** True if generated by an extension, false if pi-generated */
fromExtension?: 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;
}
/** TTSR injection entry - tracks which time-traveling rules have been injected this session. */
export interface TtsrInjectionEntry extends SessionEntryBase {
type: "ttsr_injection";
/** Names of rules that were injected */
injectedRules: string[];
}
/** Persisted MCP discovery selection state for a session branch. */
export interface MCPToolSelectionEntry extends SessionEntryBase {
type: "mcp_tool_selection";
/** MCP tool names selected for visibility in discovery mode. */
selectedToolNames: string[];
}
/** Session init entry - captures initial context for subagent sessions (debugging/replay). */
export interface SessionInitEntry extends SessionEntryBase {
type: "session_init";
/** Full system prompt sent to the model */
systemPrompt: string;
/** Initial task/user message */
task: string;
/** Tools available to the agent */
tools: string[];
/** Output schema if structured output was requested */
outputSchema?: unknown;
}
/** Mode change entry - tracks agent mode transitions (e.g. plan mode). */
export interface ModeChangeEntry extends SessionEntryBase {
type: "mode_change";
/** Current mode name, or "none" when exiting a mode */
mode: string;
/** Optional mode-specific data (e.g. plan file path) */
data?: Record<string, unknown>;
}
/**
* 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 participates in LLM context through convertToLlm().
* 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;
/** Who initiated this message for billing/attribution semantics. */
attribution?: MessageAttribution;
}
/** Session entry - has id/parentId for tree structure (returned by "read" methods in SessionManager) */
export type SessionEntry =
| SessionMessageEntry
| ThinkingLevelChangeEntry
| ModelChangeEntry
| ServiceTierChangeEntry
| CompactionEntry
| BranchSummaryEntry
| CustomEntry
| CustomMessageEntry
| LabelEntry
| TtsrInjectionEntry
| MCPToolSelectionEntry
| SessionInitEntry
| ModeChangeEntry;
/** 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;
}
export interface SessionContext {
messages: AgentMessage[];
thinkingLevel?: string;
serviceTier?: ServiceTier;
/** Model roles: { default: "provider/modelId", small: "provider/modelId", ... } */
models: Record<string, string>;
/** Names of TTSR rules that have been injected this session */
injectedTtsrRules: string[];
/** MCP tool names selected through discovery for this session branch. */
selectedMCPToolNames: string[];
/** Whether this branch contains an explicit persisted MCP selection entry. */
hasPersistedMCPToolSelection: boolean;
/** Active mode (e.g. "plan") or "none" if no special mode is active */
mode: string;
/** Mode-specific data from the last mode_change entry */
modeData?: Record<string, unknown>;
}
export interface SessionInfo {
path: string;
id: string;
/** Working directory where the session was started. Empty string for old sessions. */
cwd: string;
title?: 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"
| "getArtifactsDir"
| "allocateArtifactPath"
| "saveArtifact"
| "getArtifactPath"
| "getLeafId"
| "getLeafEntry"
| "getEntry"
| "getLabel"
| "getBranch"
| "getHeader"
| "getEntries"
| "getTree"
| "getUsageStatistics"
| "putBlob"
>;
/** 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 = crypto.randomUUID().slice(-8);
if (!byId.has(id)) return id;
}
return Snowflake.next(); // fallback to full snowflake id
}
/** 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;
}
if (entry.type === "message") {
const msg = entry.message as { role?: string };
if (msg.role === "hookMessage") {
(entry.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);
}
const migratedSessionRoots = new Set<string>();
/**
* Merge or rename a legacy session directory into its canonical target.
* Best effort: callers decide whether migration failures should surface.
*/
function migrateSessionDirPath(oldPath: string, newPath: string): void {
const existing = fs.statSync(newPath, { throwIfNoEntry: false });
if (existing?.isDirectory()) {
for (const file of fs.readdirSync(oldPath)) {
const src = path.join(oldPath, file);
const dst = path.join(newPath, file);
if (!fs.existsSync(dst)) {
fs.renameSync(src, dst);
}
}
fs.rmSync(oldPath, { recursive: true, force: true });
return;
}
if (existing) {
fs.rmSync(newPath, { recursive: true, force: true });
}
fs.renameSync(oldPath, newPath);
}
function encodeLegacyAbsoluteSessionDirName(cwd: string): string {
const resolvedCwd = path.resolve(cwd);
return `--${resolvedCwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
}
function encodeRelativeSessionDirName(prefix: string, root: string, cwd: string): string {
const relative = path.relative(root, cwd).replace(/[/\\:]/g, "-");
return relative ? (prefix.endsWith("-") ? `${prefix}${relative}` : `${prefix}-${relative}`) : prefix;
}
function getDefaultSessionDirName(cwd: string): { encodedDirName: string; resolvedCwd: string } {
const resolvedCwd = path.resolve(cwd);
const canonicalCwd = resolveEquivalentPath(resolvedCwd);
const home = resolveEquivalentPath(os.homedir());
const tempRoot = resolveEquivalentPath(os.tmpdir());
const encodedDirName = pathIsWithin(home, canonicalCwd)
? encodeRelativeSessionDirName("-", home, canonicalCwd)
: pathIsWithin(tempRoot, canonicalCwd)
? encodeRelativeSessionDirName("-tmp", tempRoot, canonicalCwd)
: encodeLegacyAbsoluteSessionDirName(canonicalCwd);
return { encodedDirName, resolvedCwd };
}
/**
* Migrate old `--<home-encoded>-*--` session dirs to the new `-*` format.
* Runs once per sessions root on first access, best-effort.
*/
function migrateHomeSessionDirs(sessionsRoot: string): void {
if (migratedSessionRoots.has(sessionsRoot)) return;
migratedSessionRoots.add(sessionsRoot);
const home = os.homedir();
const homeEncoded = home.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-");
const oldPrefix = `--${homeEncoded}-`;
const oldExact = `--${homeEncoded}--`;
let entries: string[];
try {
entries = fs.readdirSync(sessionsRoot);
} catch {
return;
}
for (const entry of entries) {
let remainder: string;
if (entry === oldExact) {
remainder = "";
} else if (entry.startsWith(oldPrefix) && entry.endsWith("--")) {
remainder = entry.slice(oldPrefix.length, -2);
} else {
continue;
}
const newName = remainder ? `-${remainder}` : "-";
const oldPath = path.join(sessionsRoot, entry);
const newPath = path.join(sessionsRoot, newName);
try {
migrateSessionDirPath(oldPath, newPath);
} catch {
// Best effort
}
}
}
function migrateLegacyAbsoluteSessionDir(cwd: string, sessionDir: string, sessionsRoot: string): void {
const legacyDir = path.join(sessionsRoot, encodeLegacyAbsoluteSessionDirName(cwd));
if (legacyDir === sessionDir || !fs.existsSync(legacyDir)) return;
try {
migrateSessionDirPath(legacyDir, sessionDir);
} catch {
// Best effort
}
}
function resolveManagedSessionRoot(sessionDir: string, cwd: string): string | undefined {
const currentDirName = path.basename(sessionDir);
const { encodedDirName } = getDefaultSessionDirName(cwd);
if (currentDirName !== encodedDirName && currentDirName !== encodeLegacyAbsoluteSessionDirName(cwd)) {
return undefined;
}
return path.dirname(sessionDir);
}
/** Exported for compaction.test.ts */
export function parseSessionEntries(content: string): FileEntry[] {
return parseJsonlLenient<FileEntry>(content);
}
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;
}
/**
* 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.
*/
export function buildSessionContext(
entries: SessionEntry[],
leafId?: string | null,
byId?: Map<string, SessionEntry>,
): SessionContext {
// Build uuid index if not available
if (!byId) {
byId = new Map<string, SessionEntry>();
for (const entry of entries) {
byId.set(entry.id, entry);
}
}
// Find leaf
let leaf: SessionEntry | undefined;
if (leafId === null) {
// Explicitly null - return no messages (navigated to before first entry)
return {
messages: [],
thinkingLevel: "off",
serviceTier: undefined,
models: {},
injectedTtsrRules: [],
selectedMCPToolNames: [],
hasPersistedMCPToolSelection: false,
mode: "none",
};
}
if (leafId) {
leaf = byId.get(leafId);
}
if (!leaf) {
// Fallback to last entry (when leafId is undefined)
leaf = entries[entries.length - 1];
}
if (!leaf) {
return {
messages: [],
thinkingLevel: "off",
serviceTier: undefined,
models: {},
injectedTtsrRules: [],
selectedMCPToolNames: [],
hasPersistedMCPToolSelection: false,
mode: "none",
};
}
// Walk from leaf to root, collecting path
const path: SessionEntry[] = [];
let current: SessionEntry | undefined = leaf;
while (current) {
path.unshift(current);
current = current.parentId ? byId.get(current.parentId) : undefined;
}
// Extract settings and find compaction
let thinkingLevel: string | undefined = "off";
let serviceTier: ServiceTier | undefined;
const models: Record<string, string> = {};
let compaction: CompactionEntry | null = null;
const injectedTtsrRulesSet = new Set<string>();
let selectedMCPToolNames: string[] = [];
let hasPersistedMCPToolSelection = false;
let mode = "none";
let modeData: Record<string, unknown> | undefined;
for (const entry of path) {
if (entry.type === "thinking_level_change") {
thinkingLevel = entry.thinkingLevel ?? "off";
} else if (entry.type === "model_change") {
// New format: { model: "provider/id", role?: string }
if (entry.model) {
const role = entry.role ?? "default";
models[role] = entry.model;
}
} else if (entry.type === "service_tier_change") {
serviceTier = entry.serviceTier ?? undefined;
} else if (entry.type === "message" && entry.message.role === "assistant") {
// Infer default model from assistant messages
models.default = `${entry.message.provider}/${entry.message.model}`;
} else if (entry.type === "compaction") {
compaction = entry;
} else if (entry.type === "ttsr_injection") {
// Collect injected TTSR rule names
for (const ruleName of entry.injectedRules) {
injectedTtsrRulesSet.add(ruleName);
}
} else if (entry.type === "mcp_tool_selection") {
selectedMCPToolNames = [...entry.selectedToolNames];
hasPersistedMCPToolSelection = true;
} else if (entry.type === "mode_change") {
mode = entry.mode;
modeData = entry.data;
}
}
const injectedTtsrRules = Array.from(injectedTtsrRulesSet);
// Build messages and collect corresponding entries
// When there's a compaction, we need to:
// 1. Emit summary first (entry = compaction)
// 2. Emit kept messages (from firstKeptEntryId up to compaction)
// 3. Emit messages after compaction
const messages: AgentMessage[] = [];
const appendMessage = (entry: SessionEntry) => {
if (entry.type === "message") {
messages.push(entry.message);
} else if (entry.type === "custom_message") {
messages.push(
createCustomMessage(
entry.customType,
entry.content,
entry.display,
entry.details,
entry.timestamp,
entry.attribution,
),
);
} else if (entry.type === "branch_summary" && entry.summary) {
messages.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));
}
};
if (compaction) {
const providerPayload: ProviderPayload | undefined = (() => {
const candidate = compaction.preserveData?.openaiRemoteCompaction;
if (!candidate || typeof candidate !== "object") return undefined;
const remote = candidate as { provider?: unknown; replacementHistory?: unknown };
if (typeof remote.provider !== "string" || remote.provider.length === 0) return undefined;
if (!Array.isArray(remote.replacementHistory)) return undefined;
return {
type: "openaiResponsesHistory",
provider: remote.provider,
items: remote.replacementHistory as Array<Record<string, unknown>>,
};
})();
const remoteReplacementHistory = providerPayload?.items;
// Emit summary first
messages.push(
createCompactionSummaryMessage(
compaction.summary,
compaction.tokensBefore,
compaction.timestamp,
compaction.shortSummary,
providerPayload,
),
);
// Find compaction index in path
const compactionIdx = path.findIndex(e => e.type === "compaction" && e.id === compaction.id);
if (!remoteReplacementHistory) {
// Emit kept messages (before compaction, starting from firstKeptEntryId)
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);
}
}
}
// Emit messages after compaction
for (let i = compactionIdx + 1; i < path.length; i++) {
const entry = path[i];
appendMessage(entry);
}
} else {
// No compaction - emit all messages, handle branch summaries and custom messages
for (const entry of path) {
appendMessage(entry);
}
}
return {
messages,
thinkingLevel,
serviceTier,
models,
injectedTtsrRules,
selectedMCPToolNames,
hasPersistedMCPToolSelection,
mode,
modeData,
};
}
/**
* Compute the default session directory for a cwd.
* Classifies cwd by canonical location so symlink/alias paths resolve to the
* same home-relative or temp-root directory names as their real targets.
*/
function computeDefaultSessionDir(
cwd: string,
storage: SessionStorage,
sessionsRoot: string = getSessionsDir(),
): string {
const { encodedDirName, resolvedCwd } = getDefaultSessionDirName(cwd);
migrateHomeSessionDirs(sessionsRoot);
const sessionDir = path.join(sessionsRoot, encodedDirName);
migrateLegacyAbsoluteSessionDir(resolvedCwd, sessionDir, sessionsRoot);
storage.ensureDirSync(sessionDir);
return sessionDir;
}
// =============================================================================
// Terminal breadcrumbs: maps terminal (TTY) -> last session file for --continue
// =============================================================================
/**
* Write a breadcrumb linking the current terminal to a session file.
* The breadcrumb contains the cwd and session path so --continue can
* find "this terminal's last session" even when running concurrent instances.
*/
function writeTerminalBreadcrumb(cwd: string, sessionFile: string): void {
const terminalId = getTerminalId();
if (!terminalId) return;
const breadcrumbDir = getTerminalSessionsDir();
const breadcrumbFile = path.join(breadcrumbDir, terminalId);
const content = `${cwd}\n${sessionFile}\n`;
// Best-effort — don't break session creation if breadcrumb fails
Bun.write(breadcrumbFile, content).catch(() => {});
}
/**
* Read the terminal breadcrumb for the current terminal, scoped to a cwd.
* Returns the session file path if it exists and matches the cwd, null otherwise.
*/
async function readTerminalBreadcrumb(cwd: string): Promise<string | null> {
const terminalId = getTerminalId();
if (!terminalId) return null;
try {
const breadcrumbFile = path.join(getTerminalSessionsDir(), terminalId);
const content = await Bun.file(breadcrumbFile).text();
const lines = content.trim().split("\n");
if (lines.length < 2) return null;
const breadcrumbCwd = lines[0];
const sessionFile = lines[1];
// Only return if cwd matches (user might have cd'd)
if (path.resolve(breadcrumbCwd) !== path.resolve(cwd)) return null;
// Verify the session file still exists
const stat = fs.statSync(sessionFile, { throwIfNoEntry: false });
if (stat?.isFile()) return sessionFile;
} catch (err) {
if (!isEnoent(err)) logger.debug("Terminal breadcrumb read failed", { err });
// Breadcrumb doesn't exist or is corrupt — fall through
}
return null;
}
/** Exported for testing */
export async function loadEntriesFromFile(
filePath: string,
storage: SessionStorage = new FileSessionStorage(),
): Promise<FileEntry[]> {
let content: string;
try {
content = await storage.readText(filePath);
} catch (err) {
if (isEnoent(err)) return [];
throw err;
}
const entries = parseJsonlLenient<FileEntry>(content);
// Validate session header
if (entries.length === 0) return entries;
const header = entries[0] as SessionHeader;
if (header.type !== "session" || typeof header.id !== "string") {
return [];
}
return entries;
}
/**
* Resolve blob references in loaded entries, restoring both session image blocks and persisted
* provider image URLs back to the inline data expected by downstream transports. Mutates entries in place.
*/
function hasImageUrl(value: unknown): value is { image_url: string } {
return typeof value === "object" && value !== null && "image_url" in value && typeof value.image_url === "string";
}
async function resolvePersistedImageUrlRefs(value: unknown, blobStore: BlobStore): Promise<void> {
if (Array.isArray(value)) {
await Promise.all(value.map(item => resolvePersistedImageUrlRefs(item, blobStore)));
return;
}
if (typeof value !== "object" || value === null) return;
if (hasImageUrl(value) && isBlobRef(value.image_url)) {
value.image_url = await resolveImageDataUrl(blobStore, value.image_url);
}
await Promise.all(Object.values(value).map(item => resolvePersistedImageUrlRefs(item, blobStore)));
}
async function resolveBlobRefsInEntries(entries: FileEntry[], blobStore: BlobStore): Promise<void> {
const promises: Promise<void>[] = [];
for (const entry of entries) {
if (entry.type === "session") continue;
let contentArray: unknown[] | undefined;
if (entry.type === "message" && "content" in entry.message && Array.isArray(entry.message.content)) {
contentArray = entry.message.content;
} else if (entry.type === "custom_message" && Array.isArray(entry.content)) {
contentArray = entry.content;
}
if (contentArray) {
for (const block of contentArray) {
if (isImageBlock(block) && isBlobRef(block.data)) {
promises.push(
resolveImageData(blobStore, block.data).then(resolved => {
block.data = resolved;
}),
);
}
}
}
promises.push(resolvePersistedImageUrlRefs(entry, blobStore));
}
await Promise.all(promises);
}
/**
* Lightweight metadata for a session file, used in session picker UI.
* Uses lazy getters to defer string formatting until actually displayed.
*/
function sanitizeSessionName(value: string | undefined): string | undefined {
if (!value) return undefined;
const firstLine = value.split(/\r?\n/)[0] ?? "";
const stripped = firstLine.replace(/[\x00-\x1F\x7F]/g, "");
const trimmed = stripped.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
class RecentSessionInfo {
#fullName: string | undefined;
#name: string | undefined;
#timeAgo: string | undefined;
constructor(
readonly path: string,
readonly mtime: number,
header: Record<string, unknown>,
firstPrompt?: string,
) {
// Extract title from session header, falling back to first user prompt, then id
const trystr = (v: unknown) => (typeof v === "string" ? v : undefined);
this.#fullName =
sanitizeSessionName(trystr(header.title)) ??
sanitizeSessionName(firstPrompt) ??
sanitizeSessionName(trystr(header.id));
}
/** Full session name from header, or filename without extension as fallback */
get fullName(): string {
if (this.#fullName) return this.#fullName;
this.#fullName = this.path.split("/").pop()?.replace(".jsonl", "") ?? "Unknown";
return this.#fullName;
}
/** Truncated name for display (max 40 chars) */
get name(): string {
if (this.#name) return this.#name;
const fullName = this.fullName;
this.#name = fullName.length <= 40 ? fullName : `${fullName.slice(0, 39)}…`;
return this.#name;
}
/** Human-readable relative time (e.g., "2 hours ago") */
get timeAgo(): string {
if (this.#timeAgo) return this.#timeAgo;
this.#timeAgo = formatTimeAgo(new Date(this.mtime));
return this.#timeAgo;
}
}
/**
* Extracts the text content from a user message entry.
* Returns undefined if the entry is not a user message or has no text.
*/
function extractFirstUserPrompt(entries: Array<Record<string, unknown>>): string | undefined {
for (const entry of entries) {
if (entry.type !== "message") continue;
const message = entry.message as Record<string, unknown> | undefined;
if (message?.role !== "user") continue;
const content = message.content;
if (typeof content === "string") return content;
if (Array.isArray(content)) {
for (const block of content) {
if (typeof block === "object" && block !== null && "text" in block) {
const text = (block as { text: unknown }).text;
if (typeof text === "string") return text;
}
}
}
}
return undefined;
}
/**
* Reads all session files from the directory and returns them sorted by mtime (newest first).
* Uses low-level file I/O to efficiently read only the first 4KB of each file
* to extract the JSON header and first user message without loading entire session logs into memory.
*/
async function getSortedSessions(sessionDir: string, storage: SessionStorage): Promise<RecentSessionInfo[]> {
try {
const files: string[] = storage.listFilesSync(sessionDir, "*.jsonl");
const sessions: RecentSessionInfo[] = [];
await Promise.all(
files.map(async (path: string) => {
try {
const content = await storage.readTextPrefix(path, 4096);
const entries = parseJsonlLenient<Record<string, unknown>>(content);
if (entries.length === 0) return;
const header = entries[0] as Record<string, unknown>;
if (header.type !== "session" || typeof header.id !== "string") return;
const mtime = storage.statSync(path).mtimeMs;
const firstPrompt = header.title ? undefined : extractFirstUserPrompt(entries);
sessions.push(new RecentSessionInfo(path, mtime, header, firstPrompt));
} catch {}
}),
);
return sessions.sort((a, b) => b.mtime - a.mtime);
} catch {
return [];
}
}
/** Exported for testing */
export async function findMostRecentSession(
sessionDir: string,
storage: SessionStorage = new FileSessionStorage(),
): Promise<string | null> {
const sessions = await getSortedSessions(sessionDir, storage);
return sessions[0]?.path || null;
}
/** Format a time difference as a human-readable string */
function formatTimeAgo(date: Date): string {
const now = Date.now();
const diffMs = now - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return "just now";
if (diffMins < 60) return `${diffMins}m ago`;
if (diffHours < 24) return `${diffHours}h ago`;
if (diffDays < 7) return `${diffDays}d ago`;
return date.toLocaleDateString();
}
const MAX_PERSIST_CHARS = 500_000;
const TRUNCATION_NOTICE = "\n\n[Session persistence truncated large content]";
/** Minimum base64 length to externalize to blob store (skip tiny inline images) */
const BLOB_EXTERNALIZE_THRESHOLD = 1024;
const TEXT_CONTENT_KEY = "content";
/**
* Recursively truncate large strings in an object for session persistence.
* - Truncates any oversized string fields (key-agnostic)
* - Replaces oversized image blocks with text notices
* - Updates lineCount when content is truncated
* - Returns original object if no changes needed (structural sharing)
*/
function truncateString(value: string, maxLength: number): string {
if (value.length <= maxLength) return value;
let truncated = value.slice(0, maxLength);
if (truncated.length > 0) {
const last = truncated.charCodeAt(truncated.length - 1);
if (last >= 0xd800 && last <= 0xdbff) {
truncated = truncated.slice(0, -1);
}
}
return truncated;
}
function isImageBlock(value: unknown): value is { type: "image"; data: string; mimeType?: string } {
return (
typeof value === "object" &&
value !== null &&
"type" in value &&
(value as { type?: string }).type === "image" &&
"data" in value &&
typeof (value as { data?: string }).data === "string"
);
}
async function truncateForPersistence(obj: FileEntry, blobStore: BlobStore, key?: string): Promise<FileEntry>;