@caupulican/pi-agent-core 0.80.103 → 0.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dist/compaction/branch-summarization.d.ts +88 -0
  2. package/dist/compaction/branch-summarization.d.ts.map +1 -0
  3. package/dist/{harness/compaction → compaction}/branch-summarization.js +86 -18
  4. package/dist/compaction/branch-summarization.js.map +1 -0
  5. package/dist/compaction/compaction.d.ts +143 -0
  6. package/dist/compaction/compaction.d.ts.map +1 -0
  7. package/dist/{harness/compaction → compaction}/compaction.js +208 -77
  8. package/dist/compaction/compaction.js.map +1 -0
  9. package/dist/compaction/index.d.ts +7 -0
  10. package/dist/compaction/index.d.ts.map +1 -0
  11. package/dist/compaction/index.js +7 -0
  12. package/dist/compaction/index.js.map +1 -0
  13. package/dist/compaction/utils.d.ts +38 -0
  14. package/dist/compaction/utils.d.ts.map +1 -0
  15. package/dist/{harness/compaction → compaction}/utils.js +36 -14
  16. package/dist/compaction/utils.js.map +1 -0
  17. package/dist/index.d.ts +5 -15
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +9 -16
  20. package/dist/index.js.map +1 -1
  21. package/dist/{harness/messages.d.ts → messages.d.ts} +28 -2
  22. package/dist/messages.d.ts.map +1 -0
  23. package/dist/{harness/messages.js → messages.js} +22 -1
  24. package/dist/messages.js.map +1 -0
  25. package/dist/node.d.ts +5 -1
  26. package/dist/node.d.ts.map +1 -1
  27. package/dist/node.js +9 -1
  28. package/dist/node.js.map +1 -1
  29. package/dist/reliability/classifier.d.ts +33 -0
  30. package/dist/reliability/classifier.d.ts.map +1 -0
  31. package/dist/reliability/classifier.js +69 -0
  32. package/dist/reliability/classifier.js.map +1 -0
  33. package/dist/reliability/index.d.ts +5 -0
  34. package/dist/reliability/index.d.ts.map +1 -0
  35. package/dist/reliability/index.js +5 -0
  36. package/dist/reliability/index.js.map +1 -0
  37. package/dist/reliability/node.d.ts +2 -0
  38. package/dist/reliability/node.d.ts.map +1 -0
  39. package/dist/reliability/node.js +2 -0
  40. package/dist/reliability/node.js.map +1 -0
  41. package/dist/reliability/process-tree.d.ts +10 -0
  42. package/dist/reliability/process-tree.d.ts.map +1 -0
  43. package/dist/reliability/process-tree.js +75 -0
  44. package/dist/reliability/process-tree.js.map +1 -0
  45. package/dist/reliability/retry-controller.d.ts +66 -0
  46. package/dist/reliability/retry-controller.d.ts.map +1 -0
  47. package/dist/reliability/retry-controller.js +104 -0
  48. package/dist/reliability/retry-controller.js.map +1 -0
  49. package/dist/reliability/retry.d.ts +19 -0
  50. package/dist/reliability/retry.d.ts.map +1 -0
  51. package/dist/reliability/retry.js +35 -0
  52. package/dist/reliability/retry.js.map +1 -0
  53. package/dist/reliability/watchdogs.d.ts +47 -0
  54. package/dist/reliability/watchdogs.d.ts.map +1 -0
  55. package/dist/reliability/watchdogs.js +159 -0
  56. package/dist/reliability/watchdogs.js.map +1 -0
  57. package/dist/session/message-retention.d.ts +26 -0
  58. package/dist/session/message-retention.d.ts.map +1 -0
  59. package/dist/session/message-retention.js +95 -0
  60. package/dist/session/message-retention.js.map +1 -0
  61. package/dist/session/session-manager.d.ts +350 -0
  62. package/dist/session/session-manager.d.ts.map +1 -0
  63. package/dist/session/session-manager.js +1339 -0
  64. package/dist/session/session-manager.js.map +1 -0
  65. package/dist/utils/paths.d.ts +15 -0
  66. package/dist/utils/paths.d.ts.map +1 -0
  67. package/dist/utils/paths.js +31 -0
  68. package/dist/utils/paths.js.map +1 -0
  69. package/dist/utils/shell-output.d.ts +10 -0
  70. package/dist/utils/shell-output.d.ts.map +1 -0
  71. package/dist/utils/shell-output.js +38 -0
  72. package/dist/utils/shell-output.js.map +1 -0
  73. package/dist/utils/truncate.d.ts.map +1 -0
  74. package/dist/{harness/utils → utils}/truncate.js +27 -102
  75. package/dist/utils/truncate.js.map +1 -0
  76. package/dist/uuid.d.ts.map +1 -0
  77. package/dist/uuid.js.map +1 -0
  78. package/package.json +6 -2
  79. package/dist/harness/agent-harness.d.ts +0 -95
  80. package/dist/harness/agent-harness.d.ts.map +0 -1
  81. package/dist/harness/agent-harness.js +0 -963
  82. package/dist/harness/agent-harness.js.map +0 -1
  83. package/dist/harness/compaction/branch-summarization.d.ts +0 -53
  84. package/dist/harness/compaction/branch-summarization.d.ts.map +0 -1
  85. package/dist/harness/compaction/branch-summarization.js.map +0 -1
  86. package/dist/harness/compaction/compaction.d.ts +0 -95
  87. package/dist/harness/compaction/compaction.d.ts.map +0 -1
  88. package/dist/harness/compaction/compaction.js.map +0 -1
  89. package/dist/harness/compaction/utils.d.ts +0 -25
  90. package/dist/harness/compaction/utils.d.ts.map +0 -1
  91. package/dist/harness/compaction/utils.js.map +0 -1
  92. package/dist/harness/env/nodejs.d.ts +0 -51
  93. package/dist/harness/env/nodejs.d.ts.map +0 -1
  94. package/dist/harness/env/nodejs.js +0 -486
  95. package/dist/harness/env/nodejs.js.map +0 -1
  96. package/dist/harness/messages.d.ts.map +0 -1
  97. package/dist/harness/messages.js.map +0 -1
  98. package/dist/harness/prompt-templates.d.ts +0 -48
  99. package/dist/harness/prompt-templates.d.ts.map +0 -1
  100. package/dist/harness/prompt-templates.js +0 -233
  101. package/dist/harness/prompt-templates.js.map +0 -1
  102. package/dist/harness/session/jsonl-repo.d.ts +0 -28
  103. package/dist/harness/session/jsonl-repo.d.ts.map +0 -1
  104. package/dist/harness/session/jsonl-repo.js +0 -112
  105. package/dist/harness/session/jsonl-repo.js.map +0 -1
  106. package/dist/harness/session/jsonl-storage.d.ts +0 -33
  107. package/dist/harness/session/jsonl-storage.d.ts.map +0 -1
  108. package/dist/harness/session/jsonl-storage.js +0 -231
  109. package/dist/harness/session/jsonl-storage.js.map +0 -1
  110. package/dist/harness/session/memory-repo.d.ts +0 -18
  111. package/dist/harness/session/memory-repo.d.ts.map +0 -1
  112. package/dist/harness/session/memory-repo.js +0 -42
  113. package/dist/harness/session/memory-repo.js.map +0 -1
  114. package/dist/harness/session/memory-storage.d.ts +0 -25
  115. package/dist/harness/session/memory-storage.d.ts.map +0 -1
  116. package/dist/harness/session/memory-storage.js +0 -114
  117. package/dist/harness/session/memory-storage.js.map +0 -1
  118. package/dist/harness/session/repo-utils.d.ts +0 -11
  119. package/dist/harness/session/repo-utils.d.ts.map +0 -1
  120. package/dist/harness/session/repo-utils.js +0 -39
  121. package/dist/harness/session/repo-utils.js.map +0 -1
  122. package/dist/harness/session/session.d.ts +0 -33
  123. package/dist/harness/session/session.d.ts.map +0 -1
  124. package/dist/harness/session/session.js +0 -210
  125. package/dist/harness/session/session.js.map +0 -1
  126. package/dist/harness/session/uuid.d.ts.map +0 -1
  127. package/dist/harness/session/uuid.js.map +0 -1
  128. package/dist/harness/skills.d.ts +0 -44
  129. package/dist/harness/skills.d.ts.map +0 -1
  130. package/dist/harness/skills.js +0 -311
  131. package/dist/harness/skills.js.map +0 -1
  132. package/dist/harness/system-prompt.d.ts +0 -3
  133. package/dist/harness/system-prompt.d.ts.map +0 -1
  134. package/dist/harness/system-prompt.js +0 -30
  135. package/dist/harness/system-prompt.js.map +0 -1
  136. package/dist/harness/types.d.ts +0 -615
  137. package/dist/harness/types.d.ts.map +0 -1
  138. package/dist/harness/types.js +0 -94
  139. package/dist/harness/types.js.map +0 -1
  140. package/dist/harness/utils/shell-output.d.ts +0 -14
  141. package/dist/harness/utils/shell-output.d.ts.map +0 -1
  142. package/dist/harness/utils/shell-output.js +0 -126
  143. package/dist/harness/utils/shell-output.js.map +0 -1
  144. package/dist/harness/utils/truncate.d.ts.map +0 -1
  145. package/dist/harness/utils/truncate.js.map +0 -1
  146. /package/dist/{harness/utils → utils}/truncate.d.ts +0 -0
  147. /package/dist/{harness/session/uuid.d.ts → uuid.d.ts} +0 -0
  148. /package/dist/{harness/session/uuid.js → uuid.js} +0 -0
@@ -0,0 +1,1339 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { appendFileSync, closeSync, createReadStream, existsSync, mkdirSync, openSync, readdirSync, readSync, renameSync, statSync, writeFileSync, } from "node:fs";
3
+ import { readdir, stat } from "node:fs/promises";
4
+ import { join, resolve } from "node:path";
5
+ import { createInterface } from "node:readline";
6
+ import { StringDecoder } from "node:string_decoder";
7
+ import { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage, } from "../messages.js";
8
+ import { normalizePath, resolvePath } from "../utils/paths.js";
9
+ import { uuidv7 } from "../uuid.js";
10
+ import { compactToolResultDetailsForRetention } from "./message-retention.js";
11
+ export const CURRENT_SESSION_VERSION = 3;
12
+ function createSessionId() {
13
+ return uuidv7();
14
+ }
15
+ export function assertValidSessionId(id) {
16
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) {
17
+ throw new Error("Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character");
18
+ }
19
+ }
20
+ export function isAutoLearnSessionId(id) {
21
+ return id.startsWith("auto-learn-");
22
+ }
23
+ /** Generate a unique short ID (8 hex chars, collision-checked) */
24
+ function generateId(byId) {
25
+ for (let i = 0; i < 100; i++) {
26
+ const id = randomUUID().slice(0, 8);
27
+ if (!byId.has(id))
28
+ return id;
29
+ }
30
+ // Fallback to full UUID if somehow we have collisions
31
+ return randomUUID();
32
+ }
33
+ /** Migrate v1 → v2: add id/parentId tree structure. Mutates in place. */
34
+ function migrateV1ToV2(entries) {
35
+ const ids = new Set();
36
+ let prevId = null;
37
+ for (const entry of entries) {
38
+ if (entry.type === "session") {
39
+ entry.version = 2;
40
+ continue;
41
+ }
42
+ entry.id = generateId(ids);
43
+ entry.parentId = prevId;
44
+ prevId = entry.id;
45
+ // Convert firstKeptEntryIndex to firstKeptEntryId for compaction
46
+ if (entry.type === "compaction") {
47
+ const comp = entry;
48
+ if (typeof comp.firstKeptEntryIndex === "number") {
49
+ const targetEntry = entries[comp.firstKeptEntryIndex];
50
+ if (targetEntry && targetEntry.type !== "session") {
51
+ comp.firstKeptEntryId = targetEntry.id;
52
+ }
53
+ delete comp.firstKeptEntryIndex;
54
+ }
55
+ }
56
+ }
57
+ }
58
+ /** Migrate v2 → v3: rename hookMessage role to custom. Mutates in place. */
59
+ function migrateV2ToV3(entries) {
60
+ for (const entry of entries) {
61
+ if (entry.type === "session") {
62
+ entry.version = 3;
63
+ continue;
64
+ }
65
+ // Update message entries with hookMessage role
66
+ if (entry.type === "message") {
67
+ const msgEntry = entry;
68
+ if (msgEntry.message && msgEntry.message.role === "hookMessage") {
69
+ msgEntry.message.role = "custom";
70
+ }
71
+ }
72
+ }
73
+ }
74
+ /**
75
+ * Run all necessary migrations to bring entries to current version.
76
+ * Mutates entries in place. Returns true if any migration was applied.
77
+ */
78
+ function migrateToCurrentVersion(entries) {
79
+ const header = entries.find((e) => e.type === "session");
80
+ const version = header?.version ?? 1;
81
+ if (version >= CURRENT_SESSION_VERSION)
82
+ return false;
83
+ if (version < 2)
84
+ migrateV1ToV2(entries);
85
+ if (version < 3)
86
+ migrateV2ToV3(entries);
87
+ return true;
88
+ }
89
+ /** Exported for testing */
90
+ export function migrateSessionEntries(entries) {
91
+ migrateToCurrentVersion(entries);
92
+ }
93
+ /** Exported for compaction.test.ts */
94
+ export function parseSessionEntries(content) {
95
+ const entries = [];
96
+ const lines = content.trim().split("\n");
97
+ for (const line of lines) {
98
+ if (!line.trim())
99
+ continue;
100
+ try {
101
+ const entry = JSON.parse(line);
102
+ entries.push(entry);
103
+ }
104
+ catch {
105
+ // Skip malformed lines
106
+ }
107
+ }
108
+ return entries;
109
+ }
110
+ export function getLatestCompactionEntry(entries) {
111
+ for (let i = entries.length - 1; i >= 0; i--) {
112
+ if (entries[i].type === "compaction") {
113
+ return entries[i];
114
+ }
115
+ }
116
+ return null;
117
+ }
118
+ /**
119
+ * Build the session context from entries using tree traversal.
120
+ * If leafId is provided, walks from that entry to root.
121
+ * Handles compaction and branch summaries along the path.
122
+ */
123
+ export function buildSessionContext(entries, leafId, byId) {
124
+ // Build uuid index if not available
125
+ if (!byId) {
126
+ byId = new Map();
127
+ for (const entry of entries) {
128
+ byId.set(entry.id, entry);
129
+ }
130
+ }
131
+ // Find leaf
132
+ let leaf;
133
+ if (leafId === null) {
134
+ // Explicitly null - return no messages (navigated to before first entry)
135
+ return { messages: [], thinkingLevel: "off", model: null };
136
+ }
137
+ if (leafId) {
138
+ leaf = byId.get(leafId);
139
+ }
140
+ if (!leaf) {
141
+ // Fallback to last entry (when leafId is undefined)
142
+ leaf = entries[entries.length - 1];
143
+ }
144
+ if (!leaf) {
145
+ return { messages: [], thinkingLevel: "off", model: null };
146
+ }
147
+ // Walk from leaf to root, collecting path
148
+ const path = [];
149
+ let current = leaf;
150
+ while (current) {
151
+ path.unshift(current);
152
+ current = current.parentId ? byId.get(current.parentId) : undefined;
153
+ }
154
+ // Extract settings and find compaction
155
+ let thinkingLevel = "off";
156
+ let model = null;
157
+ let compaction = null;
158
+ for (const entry of path) {
159
+ if (entry.type === "thinking_level_change") {
160
+ thinkingLevel = entry.thinkingLevel;
161
+ }
162
+ else if (entry.type === "model_change") {
163
+ model = { provider: entry.provider, modelId: entry.modelId };
164
+ }
165
+ else if (entry.type === "message" && entry.message.role === "assistant") {
166
+ model = { provider: entry.message.provider, modelId: entry.message.model };
167
+ }
168
+ else if (entry.type === "compaction") {
169
+ compaction = entry;
170
+ }
171
+ }
172
+ // Build messages and collect corresponding entries
173
+ // When there's a compaction, we need to:
174
+ // 1. Emit summary first (entry = compaction)
175
+ // 2. Emit kept messages (from firstKeptEntryId up to compaction)
176
+ // 3. Emit messages after compaction
177
+ const messages = [];
178
+ const appendMessage = (entry) => {
179
+ if (entry.type === "message") {
180
+ messages.push(entry.message);
181
+ }
182
+ else if (entry.type === "custom_message") {
183
+ messages.push(createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp));
184
+ }
185
+ else if (entry.type === "branch_summary" && entry.summary) {
186
+ messages.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));
187
+ }
188
+ };
189
+ if (compaction) {
190
+ // Emit summary first
191
+ messages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));
192
+ // Find compaction index in path
193
+ const compactionIdx = path.findIndex((e) => e.type === "compaction" && e.id === compaction.id);
194
+ // Emit kept messages (before compaction, starting from firstKeptEntryId)
195
+ let foundFirstKept = false;
196
+ for (let i = 0; i < compactionIdx; i++) {
197
+ const entry = path[i];
198
+ if (entry.id === compaction.firstKeptEntryId) {
199
+ foundFirstKept = true;
200
+ }
201
+ if (foundFirstKept) {
202
+ appendMessage(entry);
203
+ }
204
+ }
205
+ // Emit messages after compaction
206
+ for (let i = compactionIdx + 1; i < path.length; i++) {
207
+ const entry = path[i];
208
+ appendMessage(entry);
209
+ }
210
+ }
211
+ else {
212
+ // No compaction - emit all messages, handle branch summaries and custom messages
213
+ for (const entry of path) {
214
+ appendMessage(entry);
215
+ }
216
+ }
217
+ return { messages, thinkingLevel, model };
218
+ }
219
+ /**
220
+ * Compute the default session directory for a cwd.
221
+ * Encodes cwd into a safe directory name under ~/.pi/agent/sessions/.
222
+ */
223
+ function getEncodedSessionDirName(cwd) {
224
+ return `--${encodeURIComponent(resolvePath(cwd))}--`;
225
+ }
226
+ function getLegacySessionDirPath(cwd, agentDir) {
227
+ const resolvedCwd = resolvePath(cwd);
228
+ const resolvedAgentDir = resolvePath(agentDir);
229
+ const safePath = `--${resolvedCwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
230
+ return join(resolvedAgentDir, "sessions", safePath);
231
+ }
232
+ function getDefaultSessionDirPath(cwd, agentDir) {
233
+ const resolvedAgentDir = resolvePath(agentDir);
234
+ return join(resolvedAgentDir, "sessions", getEncodedSessionDirName(cwd));
235
+ }
236
+ function getDefaultSessionDirCandidates(cwd, agentDir) {
237
+ const current = getDefaultSessionDirPath(cwd, agentDir);
238
+ const legacy = getLegacySessionDirPath(cwd, agentDir);
239
+ return current === legacy ? [current] : [current, legacy];
240
+ }
241
+ export function getDefaultSessionDir(cwd, agentDir) {
242
+ const sessionDir = getDefaultSessionDirPath(cwd, agentDir);
243
+ if (!existsSync(sessionDir)) {
244
+ mkdirSync(sessionDir, { recursive: true });
245
+ }
246
+ return sessionDir;
247
+ }
248
+ const SESSION_READ_BUFFER_SIZE = 1024 * 1024;
249
+ // One line must fit comfortably under V8's max string length (~512MiB chars).
250
+ const MAX_SESSION_LINE_CHARS = 256 * 1024 * 1024;
251
+ function parseSessionEntryLine(line) {
252
+ if (!line.trim())
253
+ return null;
254
+ try {
255
+ return JSON.parse(line);
256
+ }
257
+ catch {
258
+ // Skip malformed lines
259
+ return null;
260
+ }
261
+ }
262
+ /** Exported for testing */
263
+ export function loadEntriesFromFile(filePath, options) {
264
+ const resolvedFilePath = normalizePath(filePath);
265
+ if (!existsSync(resolvedFilePath))
266
+ return [];
267
+ // A single line beyond this budget can never become a usable entry, and
268
+ // accumulating it would crash the whole load (RangeError near V8's max string
269
+ // length) — bricking session resume. Drop it like any other unparseable line.
270
+ const maxLineChars = options?.maxLineChars ?? MAX_SESSION_LINE_CHARS;
271
+ const entries = [];
272
+ const fd = openSync(resolvedFilePath, "r");
273
+ try {
274
+ const decoder = new StringDecoder("utf8");
275
+ const buffer = Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE);
276
+ let pending = "";
277
+ let skippingOversizedLine = false;
278
+ while (true) {
279
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, null);
280
+ if (bytesRead === 0)
281
+ break;
282
+ pending += decoder.write(buffer.subarray(0, bytesRead));
283
+ if (skippingOversizedLine) {
284
+ const resumeIndex = pending.indexOf("\n");
285
+ if (resumeIndex === -1) {
286
+ pending = "";
287
+ continue;
288
+ }
289
+ pending = pending.slice(resumeIndex + 1);
290
+ skippingOversizedLine = false;
291
+ }
292
+ let lineStart = 0;
293
+ let newlineIndex = pending.indexOf("\n", lineStart);
294
+ while (newlineIndex !== -1) {
295
+ if (newlineIndex - lineStart <= maxLineChars) {
296
+ const entry = parseSessionEntryLine(pending.slice(lineStart, newlineIndex));
297
+ if (entry)
298
+ entries.push(entry);
299
+ }
300
+ lineStart = newlineIndex + 1;
301
+ newlineIndex = pending.indexOf("\n", lineStart);
302
+ }
303
+ pending = pending.slice(lineStart);
304
+ if (pending.length > maxLineChars) {
305
+ skippingOversizedLine = true;
306
+ pending = "";
307
+ }
308
+ }
309
+ pending += decoder.end();
310
+ if (!skippingOversizedLine && pending.length <= maxLineChars) {
311
+ const finalEntry = parseSessionEntryLine(pending);
312
+ if (finalEntry)
313
+ entries.push(finalEntry);
314
+ }
315
+ }
316
+ finally {
317
+ closeSync(fd);
318
+ }
319
+ // Validate session header
320
+ if (entries.length === 0)
321
+ return entries;
322
+ const header = entries[0];
323
+ if (header.type !== "session" || typeof header.id !== "string") {
324
+ return [];
325
+ }
326
+ return entries;
327
+ }
328
+ function readSessionHeader(filePath) {
329
+ try {
330
+ const fd = openSync(filePath, "r");
331
+ const buffer = Buffer.alloc(512);
332
+ const bytesRead = readSync(fd, buffer, 0, 512, 0);
333
+ closeSync(fd);
334
+ const firstLine = buffer.toString("utf8", 0, bytesRead).split("\n")[0];
335
+ if (!firstLine)
336
+ return null;
337
+ const header = JSON.parse(firstLine);
338
+ if (header.type !== "session" || typeof header.id !== "string") {
339
+ return null;
340
+ }
341
+ return header;
342
+ }
343
+ catch {
344
+ return null;
345
+ }
346
+ }
347
+ function getSessionHeaderCwd(header) {
348
+ const cwd = header.cwd;
349
+ return typeof cwd === "string" ? cwd : undefined;
350
+ }
351
+ function sessionCwdMatches(cwd, resolvedCwd) {
352
+ return cwd !== undefined && cwd !== "" && resolvePath(cwd) === resolvedCwd;
353
+ }
354
+ /** Exported for testing */
355
+ export function findMostRecentSession(sessionDir, cwd) {
356
+ const resolvedSessionDir = normalizePath(sessionDir);
357
+ const resolvedCwd = cwd ? resolvePath(cwd) : undefined;
358
+ try {
359
+ const files = readdirSync(resolvedSessionDir)
360
+ .filter((f) => f.endsWith(".jsonl"))
361
+ .map((f) => join(resolvedSessionDir, f))
362
+ .map((path) => ({ path, header: readSessionHeader(path) }))
363
+ .filter((file) => file.header !== null &&
364
+ !isAutoLearnSessionId(file.header.id) &&
365
+ (!resolvedCwd || sessionCwdMatches(getSessionHeaderCwd(file.header), resolvedCwd)))
366
+ .map(({ path }) => ({ path, mtime: statSync(path).mtime }))
367
+ .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
368
+ return files[0]?.path || null;
369
+ }
370
+ catch {
371
+ return null;
372
+ }
373
+ }
374
+ function findMostRecentSessionInDirs(sessionDirs, cwd) {
375
+ let mostRecent = null;
376
+ for (const dir of sessionDirs) {
377
+ const sessionPath = findMostRecentSession(dir, cwd);
378
+ if (!sessionPath)
379
+ continue;
380
+ try {
381
+ const mtime = statSync(sessionPath).mtime.getTime();
382
+ if (!mostRecent || mtime > mostRecent.mtime) {
383
+ mostRecent = { path: sessionPath, mtime };
384
+ }
385
+ }
386
+ catch {
387
+ // Ignore races/deleted files
388
+ }
389
+ }
390
+ return mostRecent?.path ?? null;
391
+ }
392
+ function isMessageWithContent(message) {
393
+ return typeof message.role === "string" && "content" in message;
394
+ }
395
+ function extractTextContent(message) {
396
+ const content = message.content;
397
+ if (typeof content === "string") {
398
+ return content;
399
+ }
400
+ return content
401
+ .filter((block) => block.type === "text")
402
+ .map((block) => block.text)
403
+ .join(" ");
404
+ }
405
+ const MAX_SESSION_SEARCH_TEXT_CHARS = 20_000;
406
+ function getMessageActivityTime(entry) {
407
+ const message = entry.message;
408
+ if (!isMessageWithContent(message))
409
+ return undefined;
410
+ if (message.role !== "user" && message.role !== "assistant")
411
+ return undefined;
412
+ const msgTimestamp = message.timestamp;
413
+ if (typeof msgTimestamp === "number") {
414
+ return msgTimestamp;
415
+ }
416
+ const t = new Date(entry.timestamp).getTime();
417
+ return Number.isNaN(t) ? undefined : t;
418
+ }
419
+ async function buildSessionInfo(filePath) {
420
+ try {
421
+ const stats = await stat(filePath);
422
+ let header = null;
423
+ let messageCount = 0;
424
+ let firstMessage = "";
425
+ let allMessagesText = "";
426
+ let name;
427
+ let lastActivityTime;
428
+ const appendSearchText = (text) => {
429
+ if (!text || allMessagesText.length >= MAX_SESSION_SEARCH_TEXT_CHARS)
430
+ return;
431
+ const prefix = allMessagesText.length === 0 ? "" : " ";
432
+ const remaining = MAX_SESSION_SEARCH_TEXT_CHARS - allMessagesText.length - prefix.length;
433
+ if (remaining <= 0)
434
+ return;
435
+ allMessagesText += `${prefix}${text.slice(0, remaining)}`;
436
+ };
437
+ const rl = createInterface({
438
+ input: createReadStream(filePath, { encoding: "utf8" }),
439
+ crlfDelay: Infinity,
440
+ });
441
+ for await (const line of rl) {
442
+ const entry = parseSessionEntryLine(line);
443
+ if (!entry)
444
+ continue;
445
+ if (!header) {
446
+ if (entry.type !== "session")
447
+ return null;
448
+ header = entry;
449
+ continue;
450
+ }
451
+ // Extract session name (use latest, including explicit clears)
452
+ if (entry.type === "session_info") {
453
+ name = entry.name?.trim() || undefined;
454
+ continue;
455
+ }
456
+ if (entry.type !== "message")
457
+ continue;
458
+ messageCount++;
459
+ const activityTime = getMessageActivityTime(entry);
460
+ if (typeof activityTime === "number") {
461
+ lastActivityTime = Math.max(lastActivityTime ?? 0, activityTime);
462
+ }
463
+ const message = entry.message;
464
+ if (!isMessageWithContent(message))
465
+ continue;
466
+ if (message.role !== "user" && message.role !== "assistant")
467
+ continue;
468
+ const textContent = extractTextContent(message);
469
+ if (!textContent)
470
+ continue;
471
+ appendSearchText(textContent);
472
+ if (!firstMessage && message.role === "user") {
473
+ firstMessage = textContent;
474
+ }
475
+ }
476
+ if (!header || isAutoLearnSessionId(header.id))
477
+ return null;
478
+ const cwd = typeof header.cwd === "string" ? header.cwd : "";
479
+ const parentSessionPath = header.parentSession;
480
+ const headerTime = typeof header.timestamp === "string" ? new Date(header.timestamp).getTime() : NaN;
481
+ const modified = typeof lastActivityTime === "number" && lastActivityTime > 0
482
+ ? new Date(lastActivityTime)
483
+ : !Number.isNaN(headerTime)
484
+ ? new Date(headerTime)
485
+ : stats.mtime;
486
+ return {
487
+ path: filePath,
488
+ id: header.id,
489
+ cwd,
490
+ name,
491
+ parentSessionPath,
492
+ created: new Date(header.timestamp),
493
+ modified,
494
+ messageCount,
495
+ firstMessage: firstMessage || "(no messages)",
496
+ allMessagesText,
497
+ };
498
+ }
499
+ catch {
500
+ return null;
501
+ }
502
+ }
503
+ const MAX_CONCURRENT_SESSION_INFO_LOADS = 10;
504
+ async function buildSessionInfosWithConcurrency(files, onLoaded) {
505
+ const results = new Array(files.length).fill(null);
506
+ const inFlight = new Set();
507
+ let nextIndex = 0;
508
+ const startNext = () => {
509
+ const index = nextIndex++;
510
+ const file = files[index];
511
+ if (!file)
512
+ return;
513
+ let task;
514
+ task = buildSessionInfo(file)
515
+ .then((info) => {
516
+ results[index] = info;
517
+ })
518
+ .catch(() => {
519
+ results[index] = null;
520
+ })
521
+ .finally(() => {
522
+ inFlight.delete(task);
523
+ onLoaded();
524
+ });
525
+ inFlight.add(task);
526
+ };
527
+ while (nextIndex < files.length || inFlight.size > 0) {
528
+ while (nextIndex < files.length && inFlight.size < MAX_CONCURRENT_SESSION_INFO_LOADS) {
529
+ startNext();
530
+ }
531
+ if (inFlight.size > 0) {
532
+ await Promise.race(inFlight);
533
+ }
534
+ }
535
+ return results;
536
+ }
537
+ async function countSessionFiles(dir) {
538
+ if (!existsSync(dir))
539
+ return 0;
540
+ try {
541
+ const dirEntries = await readdir(dir);
542
+ return dirEntries.filter((f) => f.endsWith(".jsonl")).length;
543
+ }
544
+ catch {
545
+ return 0;
546
+ }
547
+ }
548
+ async function listSessionsFromDir(dir, onProgress, progressOffset = 0, progressTotal) {
549
+ const sessions = [];
550
+ if (!existsSync(dir)) {
551
+ return sessions;
552
+ }
553
+ try {
554
+ const dirEntries = await readdir(dir);
555
+ const files = dirEntries.filter((f) => f.endsWith(".jsonl")).map((f) => join(dir, f));
556
+ const total = progressTotal ?? files.length;
557
+ let loaded = 0;
558
+ const results = await buildSessionInfosWithConcurrency(files, () => {
559
+ loaded++;
560
+ onProgress?.(progressOffset + loaded, total);
561
+ });
562
+ for (const info of results) {
563
+ if (info) {
564
+ sessions.push(info);
565
+ }
566
+ }
567
+ }
568
+ catch {
569
+ // Return empty list on error
570
+ }
571
+ return sessions;
572
+ }
573
+ /**
574
+ * Manages conversation sessions as append-only trees stored in JSONL files.
575
+ *
576
+ * Each session entry has an id and parentId forming a tree structure. The "leaf"
577
+ * pointer tracks the current position. Appending creates a child of the current leaf.
578
+ * Branching moves the leaf to an earlier entry, allowing new branches without
579
+ * modifying history.
580
+ *
581
+ * Use buildSessionContext() to get the resolved message list for the LLM, which
582
+ * handles compaction summaries and follows the path from root to current leaf.
583
+ */
584
+ export class SessionManager {
585
+ sessionId = "";
586
+ sessionFile;
587
+ sessionDir;
588
+ cwd;
589
+ /**
590
+ * Agent config dir (e.g. ~/.pi/agent) used to compute the default session-dir candidates for
591
+ * usesDefaultSessionDir(). Injected explicitly by the caller — SessionManager never resolves it
592
+ * from app config. Empty string for in-memory sessions (no default dir applies).
593
+ */
594
+ agentDir;
595
+ persist;
596
+ flushed = false;
597
+ fileEntries = [];
598
+ byId = new Map();
599
+ labelsById = new Map();
600
+ labelTimestampsById = new Map();
601
+ leafId = null;
602
+ constructor(cwd, sessionDir, sessionFile, persist, agentDir, newSessionOptions) {
603
+ this.cwd = resolvePath(cwd);
604
+ this.sessionDir = normalizePath(sessionDir);
605
+ this.agentDir = agentDir;
606
+ this.persist = persist;
607
+ if (persist && this.sessionDir && !existsSync(this.sessionDir)) {
608
+ mkdirSync(this.sessionDir, { recursive: true });
609
+ }
610
+ if (sessionFile) {
611
+ this.setSessionFile(sessionFile);
612
+ }
613
+ else {
614
+ this.newSession(newSessionOptions);
615
+ }
616
+ }
617
+ /** Switch to a different session file (used for resume and branching) */
618
+ setSessionFile(sessionFile) {
619
+ this.sessionFile = resolvePath(sessionFile);
620
+ if (existsSync(this.sessionFile)) {
621
+ this.fileEntries = loadEntriesFromFile(this.sessionFile);
622
+ // If file was empty or corrupted (no valid header), truncate and start fresh
623
+ // to avoid appending messages without a session header (which breaks the session)
624
+ if (this.fileEntries.length === 0) {
625
+ const explicitPath = this.sessionFile;
626
+ this.newSession();
627
+ this.sessionFile = explicitPath;
628
+ this._rewriteFile();
629
+ this.flushed = true;
630
+ return;
631
+ }
632
+ const header = this.fileEntries.find((e) => e.type === "session");
633
+ this.sessionId = header?.id ?? createSessionId();
634
+ if (migrateToCurrentVersion(this.fileEntries)) {
635
+ this._rewriteFile();
636
+ }
637
+ // Bound in-memory retention: oversized tool result details from disk would
638
+ // otherwise be pinned in fileEntries for the whole process lifetime.
639
+ for (const entry of this.fileEntries) {
640
+ if (entry.type === "message")
641
+ compactToolResultDetailsForRetention(entry.message);
642
+ }
643
+ this._buildIndex();
644
+ this.flushed = true;
645
+ }
646
+ else {
647
+ const explicitPath = this.sessionFile;
648
+ this.newSession();
649
+ this.sessionFile = explicitPath; // preserve explicit path from --session flag
650
+ }
651
+ }
652
+ newSession(options) {
653
+ if (options?.id !== undefined) {
654
+ assertValidSessionId(options.id);
655
+ }
656
+ this.sessionId = options?.id ?? createSessionId();
657
+ const timestamp = new Date().toISOString();
658
+ const header = {
659
+ type: "session",
660
+ version: CURRENT_SESSION_VERSION,
661
+ id: this.sessionId,
662
+ timestamp,
663
+ cwd: this.cwd,
664
+ parentSession: options?.parentSession,
665
+ };
666
+ this.fileEntries = [header];
667
+ this.byId.clear();
668
+ this.labelsById.clear();
669
+ this.leafId = null;
670
+ this.flushed = false;
671
+ if (this.persist) {
672
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
673
+ this.sessionFile = join(this.getSessionDir(), `${fileTimestamp}_${this.sessionId}.jsonl`);
674
+ }
675
+ return this.sessionFile;
676
+ }
677
+ _buildIndex() {
678
+ this.byId.clear();
679
+ this.labelsById.clear();
680
+ this.labelTimestampsById.clear();
681
+ this.leafId = null;
682
+ for (const entry of this.fileEntries) {
683
+ if (entry.type === "session")
684
+ continue;
685
+ this.byId.set(entry.id, entry);
686
+ this.leafId = entry.id;
687
+ if (entry.type === "label") {
688
+ if (entry.label) {
689
+ this.labelsById.set(entry.targetId, entry.label);
690
+ this.labelTimestampsById.set(entry.targetId, entry.timestamp);
691
+ }
692
+ else {
693
+ this.labelsById.delete(entry.targetId);
694
+ this.labelTimestampsById.delete(entry.targetId);
695
+ }
696
+ }
697
+ }
698
+ }
699
+ _rewriteFile() {
700
+ if (!this.persist || !this.sessionFile)
701
+ return;
702
+ // Write-then-rename keeps the session file valid at every instant: truncating
703
+ // in place leaves a torn-file window for crashes or a concurrent process
704
+ // appending to the same session.
705
+ const tempFile = `${this.sessionFile}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
706
+ const fd = openSync(tempFile, "wx");
707
+ try {
708
+ for (const entry of this.fileEntries) {
709
+ writeFileSync(fd, `${JSON.stringify(entry)}\n`);
710
+ }
711
+ }
712
+ finally {
713
+ closeSync(fd);
714
+ }
715
+ renameSync(tempFile, this.sessionFile);
716
+ }
717
+ isPersisted() {
718
+ return this.persist;
719
+ }
720
+ getCwd() {
721
+ return this.cwd;
722
+ }
723
+ getSessionDir() {
724
+ return this.sessionDir;
725
+ }
726
+ usesDefaultSessionDir() {
727
+ return getDefaultSessionDirCandidates(this.cwd, this.agentDir).includes(this.sessionDir);
728
+ }
729
+ getSessionId() {
730
+ return this.sessionId;
731
+ }
732
+ getSessionFile() {
733
+ return this.sessionFile;
734
+ }
735
+ _persist(entry) {
736
+ if (!this.persist || !this.sessionFile)
737
+ return;
738
+ const hasAssistant = this.fileEntries.some((e) => e.type === "message" && e.message.role === "assistant");
739
+ if (!hasAssistant) {
740
+ if (this.flushed) {
741
+ appendFileSync(this.sessionFile, `${JSON.stringify(entry)}\n`);
742
+ }
743
+ else {
744
+ // Mark as not flushed so when assistant arrives, all entries get written
745
+ this.flushed = false;
746
+ }
747
+ return;
748
+ }
749
+ if (!this.flushed) {
750
+ const fd = openSync(this.sessionFile, "wx");
751
+ try {
752
+ for (const e of this.fileEntries) {
753
+ writeFileSync(fd, `${JSON.stringify(e)}\n`);
754
+ }
755
+ }
756
+ finally {
757
+ closeSync(fd);
758
+ }
759
+ this.flushed = true;
760
+ }
761
+ else {
762
+ appendFileSync(this.sessionFile, `${JSON.stringify(entry)}\n`);
763
+ }
764
+ }
765
+ _appendEntry(entry) {
766
+ this.fileEntries.push(entry);
767
+ this.byId.set(entry.id, entry);
768
+ this.leafId = entry.id;
769
+ this._persist(entry);
770
+ }
771
+ /** Append a message as child of current leaf, then advance leaf. Returns entry id.
772
+ * Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly.
773
+ * Reason: we want these to be top-level entries in the session, not message session entries,
774
+ * so it is easier to find them.
775
+ * These need to be appended via appendCompaction() and appendBranchSummary() methods.
776
+ */
777
+ appendMessage(message) {
778
+ const entry = {
779
+ type: "message",
780
+ id: generateId(this.byId),
781
+ parentId: this.leafId,
782
+ timestamp: new Date().toISOString(),
783
+ message,
784
+ };
785
+ this._appendEntry(entry);
786
+ return entry.id;
787
+ }
788
+ /** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */
789
+ appendThinkingLevelChange(thinkingLevel) {
790
+ const entry = {
791
+ type: "thinking_level_change",
792
+ id: generateId(this.byId),
793
+ parentId: this.leafId,
794
+ timestamp: new Date().toISOString(),
795
+ thinkingLevel,
796
+ };
797
+ this._appendEntry(entry);
798
+ return entry.id;
799
+ }
800
+ /** Append a model change as child of current leaf, then advance leaf. Returns entry id. */
801
+ appendModelChange(provider, modelId) {
802
+ const entry = {
803
+ type: "model_change",
804
+ id: generateId(this.byId),
805
+ parentId: this.leafId,
806
+ timestamp: new Date().toISOString(),
807
+ provider,
808
+ modelId,
809
+ };
810
+ this._appendEntry(entry);
811
+ return entry.id;
812
+ }
813
+ /** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */
814
+ appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook) {
815
+ const entry = {
816
+ type: "compaction",
817
+ id: generateId(this.byId),
818
+ parentId: this.leafId,
819
+ timestamp: new Date().toISOString(),
820
+ summary,
821
+ firstKeptEntryId,
822
+ tokensBefore,
823
+ details,
824
+ fromHook,
825
+ };
826
+ this._appendEntry(entry);
827
+ return entry.id;
828
+ }
829
+ /** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */
830
+ appendCustomEntry(customType, data) {
831
+ const entry = {
832
+ type: "custom",
833
+ customType,
834
+ data,
835
+ id: generateId(this.byId),
836
+ parentId: this.leafId,
837
+ timestamp: new Date().toISOString(),
838
+ };
839
+ this._appendEntry(entry);
840
+ return entry.id;
841
+ }
842
+ /** Append a session info entry (e.g., display name). Returns entry id. */
843
+ appendSessionInfo(name) {
844
+ const entry = {
845
+ type: "session_info",
846
+ id: generateId(this.byId),
847
+ parentId: this.leafId,
848
+ timestamp: new Date().toISOString(),
849
+ name: name.trim(),
850
+ };
851
+ this._appendEntry(entry);
852
+ return entry.id;
853
+ }
854
+ /** Get the current session name from the latest session_info entry, if any. */
855
+ getSessionName() {
856
+ // Walk entries in reverse to find the latest session_info entry.
857
+ // Empty names explicitly clear the session title.
858
+ const entries = this.getEntries();
859
+ for (let i = entries.length - 1; i >= 0; i--) {
860
+ const entry = entries[i];
861
+ if (entry.type === "session_info") {
862
+ return entry.name?.trim() || undefined;
863
+ }
864
+ }
865
+ return undefined;
866
+ }
867
+ /**
868
+ * Append a custom message entry (for extensions) that participates in LLM context.
869
+ * @param customType Extension identifier for filtering on reload
870
+ * @param content Message content (string or TextContent/ImageContent array)
871
+ * @param display Whether to show in TUI (true = styled display, false = hidden)
872
+ * @param details Optional extension-specific metadata (not sent to LLM)
873
+ * @returns Entry id
874
+ */
875
+ appendCustomMessageEntry(customType, content, display, details) {
876
+ const entry = {
877
+ type: "custom_message",
878
+ customType,
879
+ content,
880
+ display,
881
+ details,
882
+ id: generateId(this.byId),
883
+ parentId: this.leafId,
884
+ timestamp: new Date().toISOString(),
885
+ };
886
+ this._appendEntry(entry);
887
+ return entry.id;
888
+ }
889
+ // =========================================================================
890
+ // Tree Traversal
891
+ // =========================================================================
892
+ getLeafId() {
893
+ return this.leafId;
894
+ }
895
+ getLeafEntry() {
896
+ return this.leafId ? this.byId.get(this.leafId) : undefined;
897
+ }
898
+ getEntry(id) {
899
+ return this.byId.get(id);
900
+ }
901
+ /**
902
+ * Get all direct children of an entry.
903
+ */
904
+ getChildren(parentId) {
905
+ const children = [];
906
+ for (const entry of this.byId.values()) {
907
+ if (entry.parentId === parentId) {
908
+ children.push(entry);
909
+ }
910
+ }
911
+ return children;
912
+ }
913
+ /**
914
+ * Get the label for an entry, if any.
915
+ */
916
+ getLabel(id) {
917
+ return this.labelsById.get(id);
918
+ }
919
+ /**
920
+ * Set or clear a label on an entry.
921
+ * Labels are user-defined markers for bookmarking/navigation.
922
+ * Pass undefined or empty string to clear the label.
923
+ */
924
+ appendLabelChange(targetId, label) {
925
+ if (!this.byId.has(targetId)) {
926
+ throw new Error(`Entry ${targetId} not found`);
927
+ }
928
+ const entry = {
929
+ type: "label",
930
+ id: generateId(this.byId),
931
+ parentId: this.leafId,
932
+ timestamp: new Date().toISOString(),
933
+ targetId,
934
+ label,
935
+ };
936
+ this._appendEntry(entry);
937
+ if (label) {
938
+ this.labelsById.set(targetId, label);
939
+ this.labelTimestampsById.set(targetId, entry.timestamp);
940
+ }
941
+ else {
942
+ this.labelsById.delete(targetId);
943
+ this.labelTimestampsById.delete(targetId);
944
+ }
945
+ return entry.id;
946
+ }
947
+ /**
948
+ * Walk from entry to root, returning all entries in path order.
949
+ * Includes all entry types (messages, compaction, model changes, etc.).
950
+ * Use buildSessionContext() to get the resolved messages for the LLM.
951
+ */
952
+ getBranch(fromId) {
953
+ const path = [];
954
+ const startId = fromId ?? this.leafId;
955
+ let current = startId ? this.byId.get(startId) : undefined;
956
+ while (current) {
957
+ path.push(current);
958
+ current = current.parentId ? this.byId.get(current.parentId) : undefined;
959
+ }
960
+ path.reverse();
961
+ return path;
962
+ }
963
+ /**
964
+ * Build the session context (what gets sent to the LLM).
965
+ * Uses tree traversal from current leaf.
966
+ */
967
+ buildSessionContext() {
968
+ return buildSessionContext(this.getEntries(), this.leafId, this.byId);
969
+ }
970
+ /**
971
+ * Get session header.
972
+ */
973
+ getHeader() {
974
+ const h = this.fileEntries.find((e) => e.type === "session");
975
+ return h ? h : null;
976
+ }
977
+ /**
978
+ * Get all session entries (excludes header). Returns a shallow copy.
979
+ * The session is append-only: use appendXXX() to add entries, branch() to
980
+ * change the leaf pointer. Entries cannot be modified or deleted.
981
+ */
982
+ getEntries() {
983
+ return this.fileEntries.filter((e) => e.type !== "session");
984
+ }
985
+ /** Return current session entry count without allocating a defensive entries array. */
986
+ getEntryCount() {
987
+ return this.byId.size;
988
+ }
989
+ /**
990
+ * Get the session as a tree structure. Returns a shallow defensive copy of all entries.
991
+ * A well-formed session has exactly one root (first entry with parentId === null).
992
+ * Orphaned entries (broken parent chain) are also returned as roots.
993
+ */
994
+ getTree() {
995
+ const entries = this.getEntries();
996
+ const nodeMap = new Map();
997
+ const roots = [];
998
+ // Create nodes with resolved labels
999
+ for (const entry of entries) {
1000
+ const label = this.labelsById.get(entry.id);
1001
+ const labelTimestamp = this.labelTimestampsById.get(entry.id);
1002
+ nodeMap.set(entry.id, { entry, children: [], label, labelTimestamp });
1003
+ }
1004
+ // Build tree
1005
+ for (const entry of entries) {
1006
+ const node = nodeMap.get(entry.id);
1007
+ if (entry.parentId === null || entry.parentId === entry.id) {
1008
+ roots.push(node);
1009
+ }
1010
+ else {
1011
+ const parent = nodeMap.get(entry.parentId);
1012
+ if (parent) {
1013
+ parent.children.push(node);
1014
+ }
1015
+ else {
1016
+ // Orphan - treat as root
1017
+ roots.push(node);
1018
+ }
1019
+ }
1020
+ }
1021
+ // Sort children by timestamp (oldest first, newest at bottom)
1022
+ // Use iterative approach to avoid stack overflow on deep trees
1023
+ const stack = [...roots];
1024
+ while (stack.length > 0) {
1025
+ const node = stack.pop();
1026
+ node.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());
1027
+ stack.push(...node.children);
1028
+ }
1029
+ return roots;
1030
+ }
1031
+ // =========================================================================
1032
+ // Branching
1033
+ // =========================================================================
1034
+ /**
1035
+ * Start a new branch from an earlier entry.
1036
+ * Moves the leaf pointer to the specified entry. The next appendXXX() call
1037
+ * will create a child of that entry, forming a new branch. Existing entries
1038
+ * are not modified or deleted.
1039
+ */
1040
+ branch(branchFromId) {
1041
+ if (!this.byId.has(branchFromId)) {
1042
+ throw new Error(`Entry ${branchFromId} not found`);
1043
+ }
1044
+ this.leafId = branchFromId;
1045
+ }
1046
+ /**
1047
+ * Reset the leaf pointer to null (before any entries).
1048
+ * The next appendXXX() call will create a new root entry (parentId = null).
1049
+ * Use this when navigating to re-edit the first user message.
1050
+ */
1051
+ resetLeaf() {
1052
+ this.leafId = null;
1053
+ }
1054
+ /**
1055
+ * Start a new branch with a summary of the abandoned path.
1056
+ * Same as branch(), but also appends a branch_summary entry that captures
1057
+ * context from the abandoned conversation path.
1058
+ */
1059
+ branchWithSummary(branchFromId, summary, details, fromHook) {
1060
+ if (branchFromId !== null && !this.byId.has(branchFromId)) {
1061
+ throw new Error(`Entry ${branchFromId} not found`);
1062
+ }
1063
+ this.leafId = branchFromId;
1064
+ const entry = {
1065
+ type: "branch_summary",
1066
+ id: generateId(this.byId),
1067
+ parentId: branchFromId,
1068
+ timestamp: new Date().toISOString(),
1069
+ fromId: branchFromId ?? "root",
1070
+ summary,
1071
+ details,
1072
+ fromHook,
1073
+ };
1074
+ this._appendEntry(entry);
1075
+ return entry.id;
1076
+ }
1077
+ /**
1078
+ * Create a new session file containing only the path from root to the specified leaf.
1079
+ * Useful for extracting a single conversation path from a branched session.
1080
+ * Returns the new session file path, or undefined if not persisting.
1081
+ */
1082
+ createBranchedSession(leafId) {
1083
+ const previousSessionFile = this.sessionFile;
1084
+ const path = this.getBranch(leafId);
1085
+ if (path.length === 0) {
1086
+ throw new Error(`Entry ${leafId} not found`);
1087
+ }
1088
+ // Filter out LabelEntry from path - we'll recreate them from the resolved map
1089
+ const pathWithoutLabels = path.filter((e) => e.type !== "label");
1090
+ const newSessionId = createSessionId();
1091
+ const timestamp = new Date().toISOString();
1092
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
1093
+ const newSessionFile = join(this.getSessionDir(), `${fileTimestamp}_${newSessionId}.jsonl`);
1094
+ const header = {
1095
+ type: "session",
1096
+ version: CURRENT_SESSION_VERSION,
1097
+ id: newSessionId,
1098
+ timestamp,
1099
+ cwd: this.cwd,
1100
+ parentSession: this.persist ? previousSessionFile : undefined,
1101
+ };
1102
+ // Collect labels for entries in the path
1103
+ const pathEntryIds = new Set(pathWithoutLabels.map((e) => e.id));
1104
+ const labelsToWrite = [];
1105
+ for (const [targetId, label] of this.labelsById) {
1106
+ if (pathEntryIds.has(targetId)) {
1107
+ labelsToWrite.push({ targetId, label, timestamp: this.labelTimestampsById.get(targetId) });
1108
+ }
1109
+ }
1110
+ if (this.persist) {
1111
+ // Build label entries
1112
+ const lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
1113
+ let parentId = lastEntryId;
1114
+ const labelEntries = [];
1115
+ for (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {
1116
+ const labelEntry = {
1117
+ type: "label",
1118
+ id: generateId(new Set(pathEntryIds)),
1119
+ parentId,
1120
+ timestamp: labelTimestamp,
1121
+ targetId,
1122
+ label,
1123
+ };
1124
+ pathEntryIds.add(labelEntry.id);
1125
+ labelEntries.push(labelEntry);
1126
+ parentId = labelEntry.id;
1127
+ }
1128
+ this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
1129
+ this.sessionId = newSessionId;
1130
+ this.sessionFile = newSessionFile;
1131
+ this._buildIndex();
1132
+ // Only write the file now if it contains an assistant message.
1133
+ // Otherwise defer to _persist(), which creates the file on the
1134
+ // first assistant response, matching the newSession() contract
1135
+ // and avoiding the duplicate-header bug when _persist()'s
1136
+ // no-assistant guard later resets flushed to false.
1137
+ const hasAssistant = this.fileEntries.some((e) => e.type === "message" && e.message.role === "assistant");
1138
+ if (hasAssistant) {
1139
+ this._rewriteFile();
1140
+ this.flushed = true;
1141
+ }
1142
+ else {
1143
+ this.flushed = false;
1144
+ }
1145
+ return newSessionFile;
1146
+ }
1147
+ // In-memory mode: replace current session with the path + labels
1148
+ const labelEntries = [];
1149
+ let parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
1150
+ for (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {
1151
+ const labelEntry = {
1152
+ type: "label",
1153
+ id: generateId(new Set([...pathEntryIds, ...labelEntries.map((e) => e.id)])),
1154
+ parentId,
1155
+ timestamp: labelTimestamp,
1156
+ targetId,
1157
+ label,
1158
+ };
1159
+ labelEntries.push(labelEntry);
1160
+ parentId = labelEntry.id;
1161
+ }
1162
+ this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
1163
+ this.sessionId = newSessionId;
1164
+ this._buildIndex();
1165
+ return undefined;
1166
+ }
1167
+ /**
1168
+ * Create a new session.
1169
+ * @param cwd Working directory (stored in session header)
1170
+ * @param agentDir Agent config dir used to compute the default session dir and default-dir candidates.
1171
+ * @param sessionDir Optional session directory. If omitted, uses default (<agentDir>/sessions/<encoded-cwd>/).
1172
+ */
1173
+ static create(cwd, agentDir, sessionDir, options) {
1174
+ const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd, agentDir);
1175
+ return new SessionManager(cwd, dir, undefined, true, agentDir, options);
1176
+ }
1177
+ /**
1178
+ * Open a specific session file.
1179
+ * @param path Path to session file
1180
+ * @param agentDir Agent config dir used to compute default-dir candidates for usesDefaultSessionDir().
1181
+ * @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent.
1182
+ * @param cwdOverride Optional cwd override instead of the session header cwd.
1183
+ */
1184
+ static open(path, agentDir, sessionDir, cwdOverride) {
1185
+ const resolvedPath = resolvePath(path);
1186
+ // Extract cwd from session header if possible, otherwise use process.cwd()
1187
+ const entries = loadEntriesFromFile(resolvedPath);
1188
+ const header = entries.find((e) => e.type === "session");
1189
+ const cwd = cwdOverride ?? header?.cwd ?? process.cwd();
1190
+ // If no sessionDir provided, derive from file's parent directory
1191
+ const dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, "..");
1192
+ return new SessionManager(cwd, dir, resolvedPath, true, agentDir);
1193
+ }
1194
+ /**
1195
+ * Continue the most recent session, or create new if none.
1196
+ * @param cwd Working directory
1197
+ * @param agentDir Agent config dir used to compute the default session dir and default-dir candidates.
1198
+ * @param sessionDir Optional session directory. If omitted, uses default (<agentDir>/sessions/<encoded-cwd>/).
1199
+ */
1200
+ static continueRecent(cwd, agentDir, sessionDir) {
1201
+ const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd, agentDir);
1202
+ const defaultDirs = getDefaultSessionDirCandidates(cwd, agentDir);
1203
+ const filterCwd = sessionDir !== undefined && !defaultDirs.includes(dir);
1204
+ const searchDirs = sessionDir ? [dir] : defaultDirs;
1205
+ const mostRecent = findMostRecentSessionInDirs(searchDirs, filterCwd ? cwd : undefined);
1206
+ if (mostRecent) {
1207
+ return new SessionManager(cwd, resolve(mostRecent, ".."), mostRecent, true, agentDir);
1208
+ }
1209
+ return new SessionManager(cwd, dir, undefined, true, agentDir);
1210
+ }
1211
+ /** Create an in-memory session (no file persistence). No agent dir applies (usesDefaultSessionDir is false). */
1212
+ static inMemory(cwd = process.cwd()) {
1213
+ return new SessionManager(cwd, "", undefined, false, "");
1214
+ }
1215
+ /**
1216
+ * Fork a session from another project directory into the current project.
1217
+ * Creates a new session in the target cwd with the full history from the source session.
1218
+ * @param sourcePath Path to the source session file
1219
+ * @param targetCwd Target working directory (where the new session will be stored)
1220
+ * @param agentDir Agent config dir used to compute the default session dir for targetCwd.
1221
+ * @param sessionDir Optional session directory. If omitted, uses default for targetCwd.
1222
+ */
1223
+ static forkFrom(sourcePath, targetCwd, agentDir, sessionDir, options) {
1224
+ const resolvedSourcePath = resolvePath(sourcePath);
1225
+ const resolvedTargetCwd = resolvePath(targetCwd);
1226
+ const sourceEntries = loadEntriesFromFile(resolvedSourcePath);
1227
+ if (sourceEntries.length === 0) {
1228
+ throw new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);
1229
+ }
1230
+ const sourceHeader = sourceEntries.find((e) => e.type === "session");
1231
+ if (!sourceHeader) {
1232
+ throw new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);
1233
+ }
1234
+ const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(resolvedTargetCwd, agentDir);
1235
+ if (!existsSync(dir)) {
1236
+ mkdirSync(dir, { recursive: true });
1237
+ }
1238
+ // Create new session file with new ID but forked content
1239
+ if (options?.id !== undefined) {
1240
+ assertValidSessionId(options.id);
1241
+ }
1242
+ const newSessionId = options?.id ?? createSessionId();
1243
+ const timestamp = new Date().toISOString();
1244
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
1245
+ const newSessionFile = join(dir, `${fileTimestamp}_${newSessionId}.jsonl`);
1246
+ // Write new header pointing to source as parent, with updated cwd
1247
+ const newHeader = {
1248
+ type: "session",
1249
+ version: CURRENT_SESSION_VERSION,
1250
+ id: newSessionId,
1251
+ timestamp,
1252
+ cwd: resolvedTargetCwd,
1253
+ parentSession: resolvedSourcePath,
1254
+ };
1255
+ writeFileSync(newSessionFile, `${JSON.stringify(newHeader)}\n`, { flag: "wx" });
1256
+ // Copy all non-header entries from source
1257
+ for (const entry of sourceEntries) {
1258
+ if (entry.type !== "session") {
1259
+ appendFileSync(newSessionFile, `${JSON.stringify(entry)}\n`);
1260
+ }
1261
+ }
1262
+ return new SessionManager(resolvedTargetCwd, dir, newSessionFile, true, agentDir);
1263
+ }
1264
+ /**
1265
+ * List all sessions for a directory.
1266
+ * @param cwd Working directory (used to compute default session directory)
1267
+ * @param agentDir Agent config dir used to compute the default session dir and default-dir candidates.
1268
+ * @param sessionDir Optional session directory. If omitted, uses default (<agentDir>/sessions/<encoded-cwd>/).
1269
+ * @param onProgress Optional callback for progress updates (loaded, total)
1270
+ */
1271
+ static async list(cwd, agentDir, sessionDir, onProgress) {
1272
+ const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd, agentDir);
1273
+ const defaultDirs = getDefaultSessionDirCandidates(cwd, agentDir);
1274
+ const filterCwd = sessionDir !== undefined && !defaultDirs.includes(dir);
1275
+ const resolvedCwd = resolvePath(cwd);
1276
+ const dirs = sessionDir ? [dir] : defaultDirs;
1277
+ const progressCounts = await Promise.all(dirs.map((candidateDir) => countSessionFiles(candidateDir)));
1278
+ const progressTotal = progressCounts.reduce((sum, count) => sum + count, 0);
1279
+ const allSessions = [];
1280
+ let progressOffset = 0;
1281
+ for (let i = 0; i < dirs.length; i++) {
1282
+ const candidateDir = dirs[i];
1283
+ const sessions = (await listSessionsFromDir(candidateDir, onProgress, progressOffset, progressTotal)).filter((session) => !filterCwd || sessionCwdMatches(session.cwd, resolvedCwd));
1284
+ progressOffset += progressCounts[i];
1285
+ allSessions.push(...sessions);
1286
+ }
1287
+ allSessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
1288
+ return allSessions;
1289
+ }
1290
+ static async listAll(sessionsDir, customSessionDirOrOnProgress, onProgress) {
1291
+ const customSessionDir = typeof customSessionDirOrOnProgress === "string" ? normalizePath(customSessionDirOrOnProgress) : undefined;
1292
+ const progress = typeof customSessionDirOrOnProgress === "function" ? customSessionDirOrOnProgress : onProgress;
1293
+ if (customSessionDir) {
1294
+ const sessions = await listSessionsFromDir(customSessionDir, progress);
1295
+ sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
1296
+ return sessions;
1297
+ }
1298
+ const resolvedSessionsDir = normalizePath(sessionsDir);
1299
+ try {
1300
+ if (!existsSync(resolvedSessionsDir)) {
1301
+ return [];
1302
+ }
1303
+ const entries = await readdir(resolvedSessionsDir, { withFileTypes: true });
1304
+ const dirs = entries.filter((e) => e.isDirectory()).map((e) => join(resolvedSessionsDir, e.name));
1305
+ // Count total files first for accurate progress
1306
+ let totalFiles = 0;
1307
+ const dirFiles = [];
1308
+ for (const dir of dirs) {
1309
+ try {
1310
+ const files = (await readdir(dir)).filter((f) => f.endsWith(".jsonl"));
1311
+ dirFiles.push(files.map((f) => join(dir, f)));
1312
+ totalFiles += files.length;
1313
+ }
1314
+ catch {
1315
+ dirFiles.push([]);
1316
+ }
1317
+ }
1318
+ // Process all files with progress tracking
1319
+ let loaded = 0;
1320
+ const sessions = [];
1321
+ const allFiles = dirFiles.flat();
1322
+ const results = await buildSessionInfosWithConcurrency(allFiles, () => {
1323
+ loaded++;
1324
+ progress?.(loaded, totalFiles);
1325
+ });
1326
+ for (const info of results) {
1327
+ if (info) {
1328
+ sessions.push(info);
1329
+ }
1330
+ }
1331
+ sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
1332
+ return sessions;
1333
+ }
1334
+ catch {
1335
+ return [];
1336
+ }
1337
+ }
1338
+ }
1339
+ //# sourceMappingURL=session-manager.js.map