Open History to see the last commit
1import * as NodeOS from "node:os";
2
3import {
4 AgentSessionScanError,
5 ClaudeSettings,
6 CodexSettings,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 resolveProviderInstanceEnabled,
10 type AgentSessionImportSource,
11 type AgentSessionProjectCandidate,
12 type AgentSessionProjectGit,
13 type AgentSessionScanResult,
14 type ProviderInstanceConfig,
15} from "@t3tools/contracts";
16import * as Context from "effect/Context";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Path from "effect/Path";
23import * as Schema from "effect/Schema";
24import * as Semaphore from "effect/Semaphore";
25import * as Stream from "effect/Stream";
26
27import {
28 normalizeGitRemoteUrl,
29 parseGitHubRepositoryNameWithOwnerFromRemoteUrl,
30 parseOriginUrlFromGitConfig,
31} from "@t3tools/shared/git";
32import * as HostProcess from "@t3tools/shared/HostProcess";
33import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
34
35import * as ServerConfig from "../config.ts";
36import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
37import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
38import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
39import * as ServerSettings from "../serverSettings.ts";
40import {
41 createTranscriptJsonReader,
42 createTranscriptJsonSelector,
43 TranscriptJsonLimitError,
44} from "./AgentSessionJson.ts";
45
46const TRANSCRIPT_PREFIX_BYTES = 32 * 1024;
47const METADATA_READ_BYTES = 8 * 1024;
48const MAX_TRANSCRIPT_SCAN_BYTES = 1024 * 1024;
49
50const MAX_TRANSCRIPTS_PER_SOURCE = 5000;
51
52const MAX_DISCOVERY_OPERATIONS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 4;
53const MAX_METADATA_BYTES_PER_SOURCE = 64 * 1024 * 1024;
54const MAX_METADATA_OPERATIONS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 4;
55const MAX_METADATA_RECORDS_PER_SOURCE = 100_000;
56const MAX_METADATA_RECORDS_PER_TRANSCRIPT = 1_000;
57const RECENT_THREAD_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
58/**
59 * Large tool results (especially screenshots) can make an otherwise ordinary
60 * Codex transcript several GiB. Streaming field selection avoids allocating
61 * those payloads.
62 */
63const MAX_IMPORTED_TRANSCRIPT_BYTES = 4 * 1024 * 1024 * 1024;
64const MAX_IMPORTED_MESSAGES = 200;
65const MAX_IMPORT_HISTORY_BYTES = 32 * 1024 * 1024;
66const MAX_IMPORT_BYTES = 4 * 1024 * 1024 * 1024;
67const MAX_IMPORT_TRANSCRIPTS = 100;
68const MAX_IMPORT_RECORDS = 100_000;
69
70const TranscriptContentBlock = Schema.Struct({
71 type: Schema.optional(Schema.String),
72 text: Schema.optional(Schema.String),
73});
74
75const TranscriptMessage = Schema.Struct({
76 role: Schema.optional(Schema.String),
77 content: Schema.optional(Schema.Union([Schema.String, Schema.Array(TranscriptContentBlock)])),
78 model: Schema.optional(Schema.String),
79});
80
81const CodexTurnMetadata = Schema.Struct({
82 turn_id: Schema.optional(Schema.Union([Schema.String, Schema.Null])),
83});
84
85const TranscriptRecord = Schema.Struct({
86 type: Schema.optional(Schema.String),
87 timestamp: Schema.optional(Schema.String),
88 cwd: Schema.optional(Schema.String),
89 sessionId: Schema.optional(Schema.String),
90 aiTitle: Schema.optional(Schema.String),
91 customTitle: Schema.optional(Schema.String),
92 isSidechain: Schema.optional(Schema.Boolean),
93 isMeta: Schema.optional(Schema.Boolean),
94 isCompactSummary: Schema.optional(Schema.Boolean),
95 message: Schema.optional(TranscriptMessage),
96 payload: Schema.optional(
97 Schema.Struct({
98 id: Schema.optional(Schema.String),
99 session_id: Schema.optional(Schema.String),
100 type: Schema.optional(Schema.String),
101 role: Schema.optional(Schema.String),
102 message: Schema.optional(Schema.String),
103 model: Schema.optional(Schema.String),
104 cwd: Schema.optional(Schema.String),
105 content: Schema.optional(Schema.Array(TranscriptContentBlock)),
106 internal_chat_message_metadata_passthrough: Schema.optional(Schema.Unknown),
107 }),
108 ),
109});
110
111const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
112const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings);
113const decodeTranscriptRecord = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptRecord));
114const decodeTranscriptValue = Schema.decodeUnknownOption(TranscriptRecord);
115const selectTranscriptPath = createTranscriptJsonSelector(TranscriptRecord);
116const decodeCodexTurnMetadata = Schema.decodeUnknownOption(CodexTurnMetadata);
117
118type DecodedTranscriptRecord = typeof TranscriptRecord.Type;
119
120interface AgentSessionTranscriptMetadata {
121 readonly source: AgentSessionSource;
122 readonly providerInstanceId: ProviderInstanceId;
123 readonly fallbackSessionId: string;
124 readonly lastActiveAtMs: number;
125}
126
127export interface AgentSessionThreadMessage {
128 readonly role: "user" | "assistant";
129 readonly text: string;
130 readonly createdAt: string;
131}
132
133export interface AgentSessionThread {
134 readonly source: AgentSessionSource;
135 readonly providerInstanceId: ProviderInstanceId;
136 readonly providerSessionId: string;
137 readonly title: string;
138 readonly model: string | null;
139 readonly createdAt: string;
140 readonly updatedAt: string;
141 readonly messages: ReadonlyArray<AgentSessionThreadMessage>;
142}
143
144export type AgentSessionRecentThread =
145 | {
146 readonly _tag: "Importable";
147 readonly thread: AgentSessionThread;
148 readonly source: AgentSessionImportSource;
149 }
150 | { readonly _tag: "AlreadyImported"; readonly source: AgentSessionImportSource }
151 | { readonly _tag: "Duplicate"; readonly source: AgentSessionImportSource }
152 | { readonly _tag: "Skipped" };
153
154export class AgentSessionScanner extends Context.Service<
155 AgentSessionScanner,
156 {
157 readonly scan: Effect.Effect<AgentSessionScanResult, AgentSessionScanError>;
158 readonly recentThreads: (
159 workspaceRoot: string,
160 completedSources?: ReadonlyArray<AgentSessionImportSource>,
161 ) => Stream.Stream<AgentSessionRecentThread, AgentSessionScanError>;
162 }
163>()("t3/project/AgentSessionScanner") {}
164
165type AgentSessionSource = AgentSessionProjectCandidate["sources"][number];
166
167interface RawCandidate {
168 readonly cwd: string;
169 readonly source: AgentSessionSource;
170 readonly providerInstanceId: ProviderInstanceId;
171 readonly threadCount: number;
172 readonly lastActiveAtMs: number | null;
173 readonly transcripts: ReadonlyArray<{
174 readonly filePath: string;
175 readonly mtimeMs: number | null;
176 }>;
177}
178
179interface TranscriptCandidate {
180 readonly filePath: string;
181 readonly mtimeMs: number;
182 readonly providerInstanceId: ProviderInstanceId;
183 readonly size: number;
184}
185
186interface MetadataReadBudget {
187 bytesRemaining: number;
188 operationsRemaining: number;
189 recordsRemaining: number;
190 truncated: boolean;
191}
192
193function selectMetadataTranscripts(transcripts: ReadonlyArray<TranscriptCandidate>) {
194 const selected: Array<TranscriptCandidate> = [];
195 let pending = Array.from(
196 Map.groupBy(transcripts, (transcript) => transcript.providerInstanceId).values(),
197 (entries) => entries.values(),
198 );
199 while (pending.length > 0 && selected.length < MAX_TRANSCRIPTS_PER_SOURCE) {
200 const nextRound: typeof pending = [];
201 for (const iterator of pending) {
202 if (selected.length === MAX_TRANSCRIPTS_PER_SOURCE) break;
203 const next = iterator.next();
204 if (next.done) continue;
205 selected.push(next.value);
206 nextRound.push(iterator);
207 }
208 pending = nextRound;
209 }
210 return selected;
211}
212
213function splitTranscriptRecords(contents: string, limit: number): string[] {
214 const records = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
215 return records.split("\n", limit);
216}
217
218function extractText(
219 content: string | ReadonlyArray<typeof TranscriptContentBlock.Type> | undefined,
220): string {
221 if (typeof content === "string") return content.trim();
222 if (content === undefined) return "";
223 return content
224 .filter(
225 (block) =>
226 block.type === "text" || block.type === "input_text" || block.type === "output_text",
227 )
228 .map((block) => block.text?.trim() ?? "")
229 .filter((text) => text.length > 0)
230 .join("\n");
231}
232
233function normalizeTimestamp(value: string | undefined, fallback: string): string {
234 if (value === undefined) return fallback;
235 const parsed = DateTime.make(value);
236 return Option.isSome(parsed) ? DateTime.formatIso(parsed.value) : fallback;
237}
238
239function codexTurnId(metadata: unknown): string | null {
240 const decoded = decodeCodexTurnMetadata(metadata);
241 if (
242 Option.isNone(decoded) ||
243 typeof decoded.value.turn_id !== "string" ||
244 decoded.value.turn_id.trim().length === 0
245 ) {
246 return null;
247 }
248 return decoded.value.turn_id;
249}
250
251// Codex records setup context as user text ahead of the real request. Skip
252// these leading blocks when deriving a title; imported messages keep them.
253const CODEX_TITLE_PREAMBLE =
254 /^(?:\s*(?:<(recommended_plugins|environment_context|user_instructions|INSTRUCTIONS|in-app-browser-context)(?:\s[^>]*)?>[\s\S]*?<\/\1>|# AGENTS\.md instructions\b[^\n]*|## My request for Codex:))+/;
255
256function deriveTitle(source: AgentSessionSource, text: string): string | undefined {
257 const request = source === "codex" ? text.replace(CODEX_TITLE_PREAMBLE, "") : text;
258 return request.trim().split("\n")[0]?.slice(0, 100).trim() || undefined;
259}
260
261export function parseAgentSessionTranscript(
262 input: AgentSessionTranscriptMetadata & {
263 readonly contents: string;
264 },
265 lines = splitTranscriptRecords(input.contents, MAX_IMPORT_RECORDS + 1),
266): AgentSessionThread | null {
267 if (lines.length > MAX_IMPORT_RECORDS) return null;
268 const records = lines.flatMap((line) => Option.toArray(decodeTranscriptRecord(line)));
269 return parseAgentSessionRecords(input, records);
270}
271
272function parseAgentSessionRecords(
273 input: AgentSessionTranscriptMetadata,
274 records: ReadonlyArray<DecodedTranscriptRecord>,
275): AgentSessionThread | null {
276 const fallbackTimestamp = DateTime.formatIso(DateTime.makeUnsafe(input.lastActiveAtMs));
277 // Claude filenames are session IDs. Codex rollout filenames include extra
278 // timestamp text, so only transcript metadata can provide a resumable ID.
279 let providerSessionId = input.source === "codex" ? "" : input.fallbackSessionId;
280 let title: string | null = null;
281 let customTitle: string | null = null;
282 let derivedTitle: string | undefined;
283 let model: string | null = null;
284 let hasCodexSessionId = false;
285 const messages: Array<AgentSessionThreadMessage & { readonly codexResponseUser: boolean }> = [];
286 let firstUserMessage:
287 | (AgentSessionThreadMessage & { readonly codexResponseUser: boolean })
288 | undefined;
289 const canonicalCodexResponseUserIndices = new Set<number>();
290 let canonicalUserTextsInTurn = new Set<string>();
291 let responseUsersInTurn: Array<{
292 readonly index: number;
293 readonly turnId: string;
294 readonly text: string;
295 }> = [];
296 const finishCodexTurn = () => {
297 const canonicalTurnIds = new Set(
298 responseUsersInTurn.flatMap((responseUser) =>
299 canonicalUserTextsInTurn.has(responseUser.text) ? [responseUser.turnId] : [],
300 ),
301 );
302 for (const responseUser of responseUsersInTurn) {
303 if (canonicalTurnIds.has(responseUser.turnId)) {
304 canonicalCodexResponseUserIndices.add(responseUser.index);
305 }
306 }
307 canonicalUserTextsInTurn = new Set();
308 responseUsersInTurn = [];
309 };
310 if (input.source === "codex") {
311 let recordIndex = -1;
312 for (const record of records) {
313 recordIndex += 1;
314 if (
315 record.type === "response_item" &&
316 record.payload?.type === "message" &&
317 record.payload.role === "assistant"
318 ) {
319 finishCodexTurn();
320 continue;
321 }
322 if (record.type === "event_msg" && record.payload?.type === "user_message") {
323 const text = record.payload.message?.trim() ?? "";
324 if (text.length > 0) canonicalUserTextsInTurn.add(text);
325 continue;
326 }
327 if (
328 record.type === "response_item" &&
329 record.payload?.type === "message" &&
330 record.payload.role === "user"
331 ) {
332 const turnId = codexTurnId(record.payload.internal_chat_message_metadata_passthrough);
333 const text = extractText(record.payload.content);
334 if (turnId !== null && text.length > 0) {
335 responseUsersInTurn.push({ index: recordIndex, turnId, text });
336 }
337 }
338 }
339 finishCodexTurn();
340 }
341
342 const retainMessage = (
343 message: AgentSessionThreadMessage & { readonly codexResponseUser: boolean },
344 ) => {
345 if (firstUserMessage === undefined && message.role === "user") {
346 firstUserMessage = message;
347 }
348 if (derivedTitle === undefined && message.role === "user") {
349 derivedTitle = deriveTitle(input.source, message.text);
350 }
351 messages.push(message);
352 if (messages.length > MAX_IMPORTED_MESSAGES) messages.shift();
353 };
354
355 const hasMatchingCodexEventInTurn = (text: string) => {
356 const comparisonText = text.trim();
357 for (let index = messages.length - 1; index >= 0; index--) {
358 const message = messages[index];
359 if (message?.role === "assistant") return false;
360 if (
361 message?.role === "user" &&
362 !message.codexResponseUser &&
363 message.text.trim() === comparisonText
364 ) {
365 return true;
366 }
367 }
368 return false;
369 };
370
371 let recordIndex = -1;
372 for (const record of records) {
373 recordIndex += 1;
374 if (input.source === "claudeAgent") {
375 if (
376 record.isSidechain === true ||
377 record.isMeta === true ||
378 record.isCompactSummary === true
379 ) {
380 continue;
381 }
382 if (record.sessionId?.trim()) providerSessionId = record.sessionId.trim();
383 if (record.aiTitle?.trim()) title = record.aiTitle.trim();
384 // Claude rewrites both title records on every flush, so the user's
385 // rename is tracked separately instead of racing the later ai-title.
386 // An empty customTitle is how Claude clears a rename.
387 if (record.customTitle !== undefined) customTitle = record.customTitle.trim() || null;
388 const messageModel = record.message?.model?.trim();
389 // Claude uses this sentinel for local error responses. It is not a
390 // model ID that can be selected when the imported session resumes.
391 if (messageModel && messageModel !== "<synthetic>") model = messageModel;
392 if (record.type !== "user" && record.type !== "assistant") {
393 continue;
394 }
395
396 const text = extractText(record.message?.content);
397 if (text.length === 0) continue;
398 retainMessage({
399 role: record.type,
400 text,
401 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
402 codexResponseUser: false,
403 });
404 continue;
405 }
406
407 if (record.type === "session_meta") {
408 const sessionId = record.payload?.id?.trim() || record.payload?.session_id?.trim();
409 if (!hasCodexSessionId && sessionId) {
410 providerSessionId = sessionId;
411 hasCodexSessionId = true;
412 }
413 continue;
414 }
415 if (record.type === "turn_context" && record.payload?.model?.trim()) {
416 model = record.payload.model.trim();
417 continue;
418 }
419 if (record.type === "event_msg" && record.payload?.type === "user_message") {
420 const text = record.payload.message ?? "";
421 if (text.trim().length === 0) continue;
422 // Codex can write the same prompt as both a response item and an event.
423 // Remove only the matching response copy so mixed-format logs keep every
424 // distinct user message.
425 for (let index = messages.length - 1; index >= 0; index--) {
426 const message = messages[index];
427 if (message?.role === "assistant") break;
428 if (message?.codexResponseUser === true && message.text.trim() === text.trim()) {
429 if (firstUserMessage === message) firstUserMessage = undefined;
430 messages.splice(index, 1);
431 break;
432 }
433 }
434 retainMessage({
435 role: "user",
436 text,
437 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
438 codexResponseUser: false,
439 });
440 continue;
441 }
442 if (
443 record.type !== "response_item" ||
444 record.payload?.type !== "message" ||
445 (record.payload.role !== "user" && record.payload.role !== "assistant")
446 ) {
447 continue;
448 }
449
450 const extractedText = extractText(record.payload.content);
451 if (extractedText.length === 0) continue;
452 if (record.payload.role === "user" && canonicalCodexResponseUserIndices.has(recordIndex)) {
453 continue;
454 }
455 if (record.payload.role === "user" && hasMatchingCodexEventInTurn(extractedText)) {
456 continue;
457 }
458 retainMessage({
459 role: record.payload.role,
460 text: extractedText,
461 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
462 codexResponseUser: record.payload.role === "user",
463 });
464 }
465
466 const visibleMessages = messages.map(
467 ({ codexResponseUser: _codexResponseUser, ...message }) => message,
468 );
469 if (providerSessionId.trim().length === 0 || firstUserMessage === undefined) return null;
470 const firstUserMessageRetained = messages.includes(firstUserMessage);
471 const { codexResponseUser: _codexResponseUser, ...visibleFirstUserMessage } = firstUserMessage;
472 const retainedMessages = firstUserMessageRetained
473 ? visibleMessages
474 : [visibleFirstUserMessage, ...visibleMessages.slice(-(MAX_IMPORTED_MESSAGES - 1))];
475
476 return {
477 source: input.source,
478 providerInstanceId: input.providerInstanceId,
479 providerSessionId,
480 title: customTitle ?? title ?? derivedTitle ?? "Imported thread",
481 model,
482 createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp,
483 updatedAt: fallbackTimestamp,
484 messages: retainedMessages,
485 };
486}
487
488function extractDecodedCwd(record: DecodedTranscriptRecord): string | null {
489 const cwd = record.cwd?.trim() || record.payload?.cwd?.trim();
490 return cwd && cwd.length > 0 ? cwd : null;
491}
492
493function shouldRetainDecodedRecord(
494 source: AgentSessionSource,
495 record: DecodedTranscriptRecord,
496): boolean {
497 if (extractDecodedCwd(record) !== null) return true;
498 if (source === "claudeAgent") {
499 return (
500 record.type === "user" ||
501 record.type === "assistant" ||
502 record.sessionId !== undefined ||
503 record.aiTitle !== undefined ||
504 record.customTitle !== undefined ||
505 record.message?.model !== undefined
506 );
507 }
508 return (
509 record.type === "session_meta" ||
510 record.type === "turn_context" ||
511 (record.type === "event_msg" && record.payload?.type === "user_message") ||
512 (record.type === "response_item" &&
513 record.payload?.type === "message" &&
514 (record.payload.role === "user" || record.payload.role === "assistant"))
515 );
516}
517
518function normalizeForWorktreeMatch(value: string, caseFold: boolean): string {
519 const normalized = `${value.replaceAll("\\", "/")}/`;
520 return caseFold ? normalized.toLowerCase() : normalized;
521}
522
523function isT3ManagedWorktree(
524 candidatePath: string,
525 worktreesDir: string,
526 caseFold: boolean,
527): boolean {
528 const normalized = normalizeForWorktreeMatch(candidatePath, caseFold);
529 return (
530 normalized.startsWith(normalizeForWorktreeMatch(worktreesDir, caseFold)) ||
531 normalized.includes("/.t3/worktrees/")
532 );
533}
534
535// false stops metadata scanning for an excluded rollout, even if later records contain a cwd.
536function extractCwd(line: string, source: AgentSessionSource): string | null | false {
537 let parsed: unknown;
538 try {
539 parsed = JSON.parse(line);
540 } catch {
541 return null;
542 }
543 if (typeof parsed !== "object" || parsed === null) return null;
544
545 const record = parsed as Record<string, unknown>;
546 if (typeof record.cwd === "string" && record.cwd.trim().length > 0) {
547 return record.cwd;
548 }
549 const payload = record.payload;
550 if (typeof payload === "object" && payload !== null) {
551 if (source === "codex" && record.type === "session_meta") {
552 const sessionSource = (payload as Record<string, unknown>).source;
553 if (
554 typeof sessionSource === "object" &&
555 sessionSource !== null &&
556 !Array.isArray(sessionSource) &&
557 (Object.hasOwn(sessionSource, "subagent") || Object.hasOwn(sessionSource, "subAgent"))
558 ) {
559 return false;
560 }
561 }
562 const nested = (payload as Record<string, unknown>).cwd;
563 if (typeof nested === "string" && nested.trim().length > 0) {
564 return nested;
565 }
566 }
567 return null;
568}
569
570function transcriptIdentity(filePath: string, stats: FileSystem.File.Info) {
571 return {
572 filePath,
573 size: Number(stats.size),
574 mtimeMs: Option.match(stats.mtime, { onNone: () => null, onSome: (date) => date.getTime() }),
575 device: Number(stats.dev),
576 inode: Option.match(stats.ino, { onNone: () => null, onSome: String }),
577 birthtimeMs: Option.match(stats.birthtime, {
578 onNone: () => null,
579 onSome: (date) => date.getTime(),
580 }),
581 };
582}
583
584type TranscriptIdentity = Pick<
585 AgentSessionImportSource,
586 "filePath" | "size" | "mtimeMs" | "device" | "inode" | "birthtimeMs"
587>;
588
589const fileIdKey = (inode: TranscriptIdentity["inode"]) => (inode === null ? null : String(inode));
590
591function sameTranscriptIdentity(left: TranscriptIdentity, right: TranscriptIdentity): boolean {
592 // Unsafe legacy numbers may already have lost file ID precision.
593 if (
594 (typeof left.inode === "number" && !Number.isSafeInteger(left.inode)) ||
595 (typeof right.inode === "number" && !Number.isSafeInteger(right.inode))
596 ) {
597 return false;
598 }
599 return (
600 left.filePath === right.filePath &&
601 left.size === right.size &&
602 left.mtimeMs === right.mtimeMs &&
603 left.device === right.device &&
604 fileIdKey(left.inode) === fileIdKey(right.inode) &&
605 left.birthtimeMs === right.birthtimeMs
606 );
607}
608
609/** @public Service construction is part of the canonical Effect module API. */
610export const make = Effect.gen(function* () {
611 const fileSystem = yield* FileSystem.FileSystem;
612 // Different project imports can arrive concurrently from multiple clients.
613 // Only one transcript may hold its selected-history budget at a time.
614 const importReadLock = yield* Semaphore.make(1);
615 const path = yield* Path.Path;
616 const serverConfig = yield* ServerConfig.ServerConfig;
617 const serverSettings = yield* ServerSettings.ServerSettingsService;
618 const projectStore = yield* ProjectStore.ProjectStoreV2;
619 const baseDir = path.resolve(serverConfig.baseDir);
620 const worktreesDir = path.resolve(serverConfig.worktreesDir);
621 const foldWorktreeCase = (yield* HostProcess.Platform) === "win32";
622 const hostEnvironment = yield* HostProcess.Environment;
623 const homeDir = yield* HostProcess.HomeDirectory;
624 // `/private/tmp` is what macOS reports for sessions started in `/tmp`.
625 const excludedProjectRoots = new Set(
626 [homeDir, NodeOS.tmpdir(), "/tmp", "/private/tmp"].map((directory) =>
627 normalizeProjectPathForComparison(path.resolve(directory)),
628 ),
629 );
630 const excludedProjectAncestors = [
631 path.join(homeDir, "Downloads"),
632 path.join(homeDir, "Documents", "Codex"),
633 ];
634
635 const isExcludedProjectPath = (candidatePath: string) =>
636 excludedProjectRoots.has(normalizeProjectPathForComparison(candidatePath)) ||
637 excludedProjectAncestors.some((ancestor) =>
638 normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith(
639 normalizeForWorktreeMatch(ancestor, foldWorktreeCase),
640 ),
641 ) ||
642 normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith(
643 normalizeForWorktreeMatch(baseDir, foldWorktreeCase),
644 ) ||
645 isT3ManagedWorktree(candidatePath, worktreesDir, foldWorktreeCase);
646
647 const listDirectory = (directory: string) =>
648 fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
649
650 const statOption = (target: string) =>
651 fileSystem.stat(target).pipe(Effect.asSome, Effect.orElseSucceed(Option.none));
652
653 const directoryIdentity = Effect.fn("AgentSessionScanner.directoryIdentity")(function* (
654 target: string,
655 knownStats?: FileSystem.File.Info,
656 ) {
657 const resolved = path.resolve(target);
658 const stats = knownStats === undefined ? yield* statOption(resolved) : Option.some(knownStats);
659 if (Option.isSome(stats) && Option.isSome(stats.value.ino) && stats.value.ino.value > 0n) {
660 return `inode:${stats.value.dev}:${stats.value.ino.value}`;
661 }
662 const realPath = yield* fileSystem
663 .realPath(resolved)
664 .pipe(Effect.orElseSucceed(() => resolved));
665 return `path:${normalizeProjectPathForComparison(realPath)}`;
666 });
667
668 /**
669 * When it points into a `worktrees/` directory the checkout is a linked worktree, which
670 * onboarding skips because its history belongs to the main checkout. Submodules use the same
671 * pointer shape but live under `modules/`, and are offered like any other repository.
672 */
673 const readGitIdentity = Effect.fn("AgentSessionScanner.readGitIdentity")(function* (
674 directory: string,
675 ): Effect.fn.Return<
676 | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null }
677 | { readonly _tag: "Worktree" }
678 | { readonly _tag: "NotGit" }
679 > {
680 const gitPath = path.join(directory, ".git");
681 const gitStats = yield* statOption(gitPath);
682 if (Option.isNone(gitStats)) return { _tag: "NotGit" } as const;
683 let gitDir = gitPath;
684 if (gitStats.value.type !== "Directory") {
685 const pointer = yield* fileSystem
686 .readFileString(gitPath)
687 .pipe(Effect.orElseSucceed(() => ""));
688 const target = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim();
689 if (target === undefined || target.length === 0) return { _tag: "NotGit" } as const;
690 gitDir = path.resolve(directory, target);
691 if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) return { _tag: "Worktree" } as const;
692 }
693 const configText = yield* fileSystem
694 .readFileString(path.join(gitDir, "config"))
695 .pipe(Effect.orElseSucceed(() => ""));
696 const originUrl = parseOriginUrlFromGitConfig(configText);
697 return {
698 _tag: "Repository",
699 git: {
700 remoteKey: originUrl === null ? null : normalizeGitRemoteUrl(originUrl),
701 repository: parseGitHubRepositoryNameWithOwnerFromRemoteUrl(originUrl),
702 },
703 } as const;
704 });
705
706 const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* (
707 source: AgentSessionSource,
708 transcript: TranscriptCandidate,
709 budget: MetadataReadBudget,
710 ) {
711 if (transcript.size === 0) return null;
712 if (
713 budget.bytesRemaining === 0 ||
714 budget.operationsRemaining < 2 ||
715 budget.recordsRemaining === 0
716 ) {
717 budget.truncated = true;
718 return null;
719 }
720 budget.operationsRemaining -= 1;
721 return yield* Effect.scoped(
722 fileSystem.open(transcript.filePath, { flag: "r" }).pipe(
723 Effect.flatMap((file) =>
724 Effect.gen(function* () {
725 const decoder = new TextDecoder();
726 let remaining = "";
727 let bytesRead = 0;
728 let recordsRead = 0;
729 const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, transcript.size);
730 const reserveRecord = () => {
731 if (
732 recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT ||
733 budget.recordsRemaining === 0
734 ) {
735 budget.truncated = true;
736 return false;
737 }
738 recordsRead += 1;
739 budget.recordsRemaining -= 1;
740 return true;
741 };
742 const readLastRecord = () => {
743 const record = remaining + decoder.decode();
744 return record.length === 0 || !reserveRecord()
745 ? null
746 : extractCwd(record.trim(), source);
747 };
748
749 while (bytesRead < maxBytes) {
750 if (budget.bytesRemaining === 0 || budget.operationsRemaining === 0) {
751 budget.truncated = true;
752 return null;
753 }
754 const readSize = Math.min(
755 METADATA_READ_BYTES,
756 maxBytes - bytesRead,
757 budget.bytesRemaining,
758 );
759 budget.operationsRemaining -= 1;
760 budget.bytesRemaining -= readSize;
761 const next = yield* file.readAlloc(readSize);
762 if (Option.isNone(next)) {
763 return readLastRecord();
764 }
765
766 bytesRead += next.value.byteLength;
767 remaining += decoder.decode(next.value, { stream: true });
768 const lines = remaining.split("\n");
769 remaining = lines.pop() ?? "";
770
771 for (const line of lines) {
772 if (!reserveRecord()) return null;
773 const cwd = extractCwd(line.trim(), source);
774 if (cwd !== null) return cwd;
775 }
776 }
777
778 if (bytesRead < transcript.size) {
779 budget.truncated = true;
780 return null;
781 }
782 return readLastRecord();
783 }),
784 ),
785 ),
786 ).pipe(Effect.orElseSucceed(() => null));
787 });
788
789 const readTranscript = Effect.fn("AgentSessionScanner.readTranscript")(function* (
790 filePath: string,
791 expected: ReturnType<typeof transcriptIdentity>,
792 recordLimit: number,
793 source: AgentSessionSource,
794 ) {
795 if (expected.size > MAX_IMPORTED_TRANSCRIPT_BYTES) return null;
796
797 return yield* Effect.scoped(
798 fileSystem.open(filePath, { flag: "r" }).pipe(
799 Effect.flatMap((file) =>
800 Effect.gen(function* () {
801 if (!sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))) {
802 return null;
803 }
804 const records: Array<DecodedTranscriptRecord> = [];
805 let historyBytes = 0;
806 let recordBytes = 0;
807 let recordCount = 0;
808 let bytesRead = 0;
809 const reserve = (bytes: number) => {
810 recordBytes += bytes;
811 if (historyBytes + recordBytes > MAX_IMPORT_HISTORY_BYTES) {
812 throw new TranscriptJsonLimitError(
813 "Transcript selected history exceeds the 32 MiB memory budget",
814 );
815 }
816 };
817 let reader = createTranscriptJsonReader(reserve, selectTranscriptPath);
818 let decoder = new TextDecoder();
819 let recordStarted = false;
820
821 const finishRecord = () => {
822 reader.write(decoder.decode());
823 recordCount += 1;
824 if (recordCount > recordLimit) return false;
825 const decoded = decodeTranscriptValue(reader.finish());
826 if (Option.isSome(decoded) && shouldRetainDecodedRecord(source, decoded.value)) {
827 records.push(decoded.value);
828 historyBytes += recordBytes;
829 }
830 recordBytes = 0;
831 reader = createTranscriptJsonReader(reserve, selectTranscriptPath);
832 decoder = new TextDecoder();
833 recordStarted = false;
834 return true;
835 };
836
837 while (bytesRead < expected.size) {
838 const next = yield* file.readAlloc(
839 Math.min(TRANSCRIPT_PREFIX_BYTES, expected.size - bytesRead),
840 );
841 if (Option.isNone(next)) {
842 return null;
843 }
844
845 bytesRead += next.value.byteLength;
846 const withinBudget = yield* Effect.try(() => {
847 let start = 0;
848 while (start < next.value.byteLength) {
849 const newline = next.value.indexOf(10, start);
850 const end = newline === -1 ? next.value.byteLength : newline;
851 recordStarted = true;
852 reader.write(decoder.decode(next.value.subarray(start, end), { stream: true }));
853 if (newline === -1) break;
854 if (!finishRecord()) return false;
855 start = newline + 1;
856 }
857 return true;
858 });
859 if (!withinBudget) return null;
860 }
861
862 if (recordStarted && !(yield* Effect.try(finishRecord))) return null;
863 return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))
864 ? { records, recordCount }
865 : null;
866 }),
867 ),
868 ),
869 ).pipe(
870 Effect.catch((cause) =>
871 Effect.logWarning("Could not read imported transcript", { filePath, cause }).pipe(
872 Effect.as(null),
873 ),
874 ),
875 );
876 });
877
878 const resolveClaudeConfigDir = (homePath: string, environmentHome?: string): string => {
879 const configured = homePath.trim();
880 if (configured.length > 0) {
881 return path.resolve(expandHomePath(configured, homeDir));
882 }
883 const fromEnvironment = environmentHome?.trim() ?? "";
884 if (fromEnvironment.length > 0) {
885 return path.resolve(expandHomePath(fromEnvironment, homeDir));
886 }
887 return path.join(homeDir, ".claude");
888 };
889
890 const discoverClaudeTranscripts = Effect.fn("AgentSessionScanner.discoverClaudeTranscripts")(
891 function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) {
892 const projectsDir = path.join(homePath, "projects");
893 let operationsRemaining = operationBudget;
894 let truncated = false;
895 const readDirectory = (directory: string) => {
896 if (operationsRemaining <= 0) {
897 truncated = true;
898 return Effect.succeed<ReadonlyArray<string>>([]);
899 }
900 operationsRemaining -= 1;
901 return listDirectory(directory);
902 };
903 const projectDirectories = yield* readDirectory(projectsDir);
904 const transcripts: Array<TranscriptCandidate> = [];
905
906 for (const projectDirectory of projectDirectories) {
907 if (operationsRemaining <= 0) {
908 truncated = true;
909 break;
910 }
911 const directory = path.join(projectsDir, projectDirectory);
912 const directoryTranscripts = (yield* readDirectory(directory))
913 .filter((entry) => entry.endsWith(".jsonl"))
914 .map((entry) => path.join(directory, entry));
915
916 for (const filePath of directoryTranscripts) {
917 if (operationsRemaining <= 0) {
918 truncated = true;
919 break;
920 }
921 operationsRemaining -= 1;
922 const stats = yield* statOption(filePath);
923 if (
924 Option.isNone(stats) ||
925 stats.value.type !== "File" ||
926 Option.isNone(stats.value.mtime)
927 ) {
928 continue;
929 }
930 transcripts.push({
931 filePath,
932 mtimeMs: stats.value.mtime.value.getTime(),
933 providerInstanceId,
934 size: Number(stats.value.size),
935 });
936 }
937 }
938 return { transcripts, truncated };
939 },
940 );
941
942 const discoverCodexTranscripts = Effect.fn("AgentSessionScanner.discoverCodexTranscripts")(
943 function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) {
944 const sessionsDir = path.join(homePath, "sessions");
945
946 const transcripts: Array<TranscriptCandidate> = [];
947 let operationsRemaining = operationBudget;
948 let truncated = false;
949 const readDirectory = (directory: string) => {
950 if (operationsRemaining <= 0) {
951 truncated = true;
952 return Effect.succeed<ReadonlyArray<string>>([]);
953 }
954 operationsRemaining -= 1;
955 return listDirectory(directory);
956 };
957 for (const year of (yield* readDirectory(sessionsDir)).toSorted().toReversed()) {
958 if (operationsRemaining <= 0) {
959 truncated = true;
960 break;
961 }
962 for (const month of (yield* readDirectory(path.join(sessionsDir, year)))
963 .toSorted()
964 .toReversed()) {
965 if (operationsRemaining <= 0) {
966 truncated = true;
967 break;
968 }
969 for (const day of (yield* readDirectory(path.join(sessionsDir, year, month)))
970 .toSorted()
971 .toReversed()) {
972 if (operationsRemaining <= 0) {
973 truncated = true;
974 break;
975 }
976 const directory = path.join(sessionsDir, year, month, day);
977 for (const entry of (yield* readDirectory(directory)).toSorted().toReversed()) {
978 if (!entry.startsWith("rollout-") || !entry.endsWith(".jsonl")) continue;
979 if (operationsRemaining <= 0) {
980 truncated = true;
981 break;
982 }
983 const filePath = path.join(directory, entry);
984 operationsRemaining -= 1;
985 const stats = yield* statOption(filePath);
986 if (
987 Option.isSome(stats) &&
988 stats.value.type === "File" &&
989 Option.isSome(stats.value.mtime)
990 ) {
991 transcripts.push({
992 filePath,
993 mtimeMs: stats.value.mtime.value.getTime(),
994 providerInstanceId,
995 size: Number(stats.value.size),
996 });
997 }
998 }
999 }
1000 }
1001 }
1002 return { transcripts, truncated };
1003 },
1004 );
1005
1006 const groupTranscriptsByCwd = Effect.fn("AgentSessionScanner.groupTranscriptsByCwd")(function* (
1007 source: AgentSessionSource,
1008 transcripts: ReadonlyArray<TranscriptCandidate>,
1009 budget: MetadataReadBudget,
1010 ) {
1011 const byOwnerAndCwd = new Map<
1012 string,
1013 {
1014 cwd: string;
1015 providerInstanceId: ProviderInstanceId;
1016 lastActiveAtMs: number;
1017 transcripts: Array<{ filePath: string; mtimeMs: number }>;
1018 }
1019 >();
1020
1021 for (const transcript of transcripts) {
1022 const cwd = yield* readCwd(source, transcript, budget);
1023 if (cwd === null || cwd === false) continue;
1024 const key = `${transcript.providerInstanceId}\0${cwd}`;
1025 const existing = byOwnerAndCwd.get(key);
1026 if (existing) {
1027 existing.lastActiveAtMs = Math.max(existing.lastActiveAtMs, transcript.mtimeMs);
1028 existing.transcripts.push(transcript);
1029 } else {
1030 byOwnerAndCwd.set(key, {
1031 cwd,
1032 providerInstanceId: transcript.providerInstanceId,
1033 lastActiveAtMs: transcript.mtimeMs,
1034 transcripts: [transcript],
1035 });
1036 }
1037 }
1038
1039 return Array.from(byOwnerAndCwd.values(), (group): RawCandidate => ({
1040 cwd: group.cwd,
1041 source,
1042 providerInstanceId: group.providerInstanceId,
1043 threadCount: group.transcripts.length,
1044 lastActiveAtMs: group.lastActiveAtMs,
1045 transcripts: group.transcripts,
1046 }));
1047 });
1048
1049 const collectCandidates = Effect.fn("AgentSessionScanner.collectCandidates")(function* () {
1050 const settings = yield* serverSettings.getSettings.pipe(
1051 Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-settings", cause })),
1052 );
1053
1054 const raw: Array<RawCandidate> = [];
1055 let truncated = false;
1056
1057 for (const source of ["claudeAgent", "codex"] as const) {
1058 const instances: Array<{
1059 readonly instanceId: ProviderInstanceId;
1060 readonly config: ProviderInstanceConfig;
1061 }> = Object.entries(settings.providerInstances)
1062 .filter(
1063 ([, instance]) => instance.driver === source && resolveProviderInstanceEnabled(instance),
1064 )
1065 .map(([instanceId, config]) => ({
1066 instanceId: ProviderInstanceId.make(instanceId),
1067 config,
1068 }));
1069 if (!Object.hasOwn(settings.providerInstances, source)) {
1070 const defaultInstance = {
1071 instanceId: ProviderInstanceId.make(source),
1072 config: { driver: ProviderDriverKind.make(source) },
1073 };
1074 if (resolveProviderInstanceEnabled(defaultInstance.config)) {
1075 instances.push(defaultInstance);
1076 }
1077 }
1078
1079 instances.sort((left, right) => {
1080 const leftDefault = left.instanceId === source ? 0 : 1;
1081 const rightDefault = right.instanceId === source ? 0 : 1;
1082 return leftDefault - rightDefault;
1083 });
1084 const homes: Array<{ homePath: string; providerInstanceId: ProviderInstanceId }> = [];
1085 const seenHomes = new Set<string>();
1086 for (const { instanceId, config: instance } of instances) {
1087 const homeVariable = source === "claudeAgent" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME";
1088 const environmentHome =
1089 instance.environment?.findLast((variable) => variable.name === homeVariable)?.value ??
1090 hostEnvironment[homeVariable];
1091
1092 let homePath: string;
1093 if (source === "claudeAgent") {
1094 const config = decodeClaudeSettings(instance.config ?? {});
1095 if (Option.isNone(config)) continue;
1096 homePath = resolveClaudeConfigDir(config.value.homePath, environmentHome);
1097 } else {
1098 const config = decodeCodexSettings(instance.config ?? {});
1099 if (Option.isNone(config)) continue;
1100 const codexSettings =
1101 config.value.homePath.trim().length === 0 &&
1102 config.value.shadowHomePath.trim().length === 0 &&
1103 environmentHome?.trim()
1104 ? { ...config.value, homePath: environmentHome }
1105 : config.value;
1106 const layout = yield* resolveCodexHomeLayout(codexSettings).pipe(
1107 Effect.provideService(Path.Path, path),
1108 );
1109 homePath = layout.sharedHomePath;
1110 }
1111
1112 const homeKey = `${source}\0${yield* directoryIdentity(homePath)}`;
1113 if (seenHomes.has(homeKey)) continue;
1114 seenHomes.add(homeKey);
1115 homes.push({ homePath, providerInstanceId: instanceId });
1116 }
1117
1118 const transcriptCandidates: Array<TranscriptCandidate> = [];
1119 const baseOperationBudget = Math.floor(
1120 MAX_DISCOVERY_OPERATIONS_PER_SOURCE / Math.max(1, homes.length),
1121 );
1122 const extraOperationBudgets = MAX_DISCOVERY_OPERATIONS_PER_SOURCE % Math.max(1, homes.length);
1123 for (const [index, home] of homes.entries()) {
1124 const operationBudget = baseOperationBudget + (index < extraOperationBudgets ? 1 : 0);
1125 if (operationBudget === 0) {
1126 truncated = true;
1127 continue;
1128 }
1129 const discovered = yield* source === "claudeAgent"
1130 ? discoverClaudeTranscripts(home.homePath, home.providerInstanceId, operationBudget)
1131 : discoverCodexTranscripts(home.homePath, home.providerInstanceId, operationBudget);
1132 truncated ||= discovered.truncated;
1133 transcriptCandidates.push(...discovered.transcripts);
1134 }
1135
1136 transcriptCandidates.sort(
1137 (left, right) =>
1138 right.mtimeMs - left.mtimeMs || left.filePath.localeCompare(right.filePath),
1139 );
1140 if (transcriptCandidates.length > MAX_TRANSCRIPTS_PER_SOURCE) {
1141 truncated = true;
1142 }
1143 const selectedTranscripts = selectMetadataTranscripts(transcriptCandidates);
1144 const metadataBudget: MetadataReadBudget = {
1145 bytesRemaining: MAX_METADATA_BYTES_PER_SOURCE,
1146 operationsRemaining: MAX_METADATA_OPERATIONS_PER_SOURCE,
1147 recordsRemaining: MAX_METADATA_RECORDS_PER_SOURCE,
1148 truncated: false,
1149 };
1150 raw.push(...(yield* groupTranscriptsByCwd(source, selectedTranscripts, metadataBudget)));
1151 truncated ||= metadataBudget.truncated;
1152 }
1153
1154 return { candidates: raw, truncated };
1155 });
1156
1157 let cachedCandidates: ReadonlyArray<RawCandidate> | null = null;
1158
1159 const scan: AgentSessionScanner["Service"]["scan"] = Effect.gen(function* () {
1160 const { candidates: raw, truncated } = yield* collectCandidates();
1161 cachedCandidates = raw;
1162
1163 const merged = new Map<
1164 string,
1165 {
1166 path: string;
1167 sources: Array<AgentSessionSource>;
1168 threadCount: number;
1169 lastActiveAtMs: number | null;
1170 git: AgentSessionProjectGit | null;
1171 }
1172 >();
1173 const directoryKeys = new Map<string, string>();
1174 const gitIdentities = new Map<string, AgentSessionProjectGit | null>();
1175
1176 for (const candidate of raw) {
1177 const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1178 if (!path.isAbsolute(expanded)) continue;
1179 const resolved = path.resolve(expanded);
1180 if (isExcludedProjectPath(resolved)) continue;
1181 let key = directoryKeys.get(resolved);
1182 if (key === undefined) {
1183 const stats = yield* statOption(resolved);
1184 if (Option.isNone(stats) || stats.value.type !== "Directory") {
1185 directoryKeys.set(resolved, "");
1186 continue;
1187 }
1188 const realPath = yield* fileSystem
1189 .realPath(resolved)
1190 .pipe(Effect.orElseSucceed(() => resolved));
1191 // A symlink can point into the worktrees directory even when its own
1192 // spelling doesn't; check again with links resolved.
1193 if (isExcludedProjectPath(realPath)) {
1194 key = "";
1195 } else {
1196 const gitIdentity = yield* readGitIdentity(resolved);
1197 if (gitIdentity._tag === "Worktree") {
1198 key = "";
1199 } else {
1200 key = yield* directoryIdentity(resolved, stats.value);
1201 gitIdentities.set(key, gitIdentity._tag === "Repository" ? gitIdentity.git : null);
1202 }
1203 }
1204 directoryKeys.set(resolved, key);
1205 }
1206 if (key === "") continue;
1207
1208 const existing = merged.get(key);
1209 if (!existing) {
1210 merged.set(key, {
1211 path: resolved,
1212 sources: [candidate.source],
1213 threadCount: candidate.threadCount,
1214 lastActiveAtMs: candidate.lastActiveAtMs,
1215 git: gitIdentities.get(key) ?? null,
1216 });
1217 continue;
1218 }
1219 if (!existing.sources.includes(candidate.source)) {
1220 existing.sources.push(candidate.source);
1221 }
1222 existing.threadCount += candidate.threadCount;
1223 existing.lastActiveAtMs =
1224 existing.lastActiveAtMs === null || candidate.lastActiveAtMs === null
1225 ? (existing.lastActiveAtMs ?? candidate.lastActiveAtMs)
1226 : Math.max(existing.lastActiveAtMs, candidate.lastActiveAtMs);
1227 }
1228
1229 // Resolve persisted roots too. A project and a transcript can name
1230 // different symlinks to the same directory.
1231 const importedProjects = yield* projectStore
1232 .listShells()
1233 .pipe(
1234 Effect.mapError(
1235 (cause) => new AgentSessionScanError({ operation: "read-projects", cause }),
1236 ),
1237 );
1238 const importedProjectsByRoot = new Map<string, (typeof importedProjects)[number]>();
1239 for (const project of importedProjects) {
1240 const projectRoot = path.resolve(expandHomePath(project.workspaceRoot, homeDir));
1241 importedProjectsByRoot.set(normalizeProjectPathForComparison(projectRoot), project);
1242 importedProjectsByRoot.set(yield* directoryIdentity(projectRoot), project);
1243 }
1244
1245 const candidates: Array<AgentSessionProjectCandidate> = [];
1246 for (const [key, entry] of merged.entries()) {
1247 const importedProject =
1248 importedProjectsByRoot.get(normalizeProjectPathForComparison(entry.path)) ??
1249 importedProjectsByRoot.get(key);
1250 const candidatePath = importedProject?.workspaceRoot ?? entry.path;
1251 candidates.push({
1252 path: candidatePath,
1253 title: path.basename(candidatePath) || candidatePath,
1254 ...(importedProject === undefined ? {} : { projectId: importedProject.id }),
1255 sources: entry.sources,
1256 threadCount: entry.threadCount,
1257 lastActiveAt:
1258 entry.lastActiveAtMs === null
1259 ? null
1260 : DateTime.formatIso(DateTime.makeUnsafe(entry.lastActiveAtMs)),
1261 alreadyImported: importedProject !== undefined,
1262 git: entry.git,
1263 });
1264 }
1265
1266 candidates.sort((left, right) => {
1267 if (left.lastActiveAt === right.lastActiveAt) return left.path.localeCompare(right.path);
1268 if (left.lastActiveAt === null) return 1;
1269 if (right.lastActiveAt === null) return -1;
1270 return right.lastActiveAt.localeCompare(left.lastActiveAt);
1271 });
1272
1273 return {
1274 candidates,
1275 scannedAt: DateTime.formatIso(yield* DateTime.now),
1276 ...(truncated ? { truncated: true } : {}),
1277 };
1278 });
1279
1280 const prepareRecentThreads = Effect.fn("AgentSessionScanner.prepareRecentThreads")(function* (
1281 workspaceRoot: string,
1282 completedSources: ReadonlyArray<AgentSessionImportSource>,
1283 ) {
1284 const root = path.resolve(expandHomePath(workspaceRoot, homeDir));
1285 const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root));
1286 if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot)) return Stream.empty;
1287 const rootIdentity = yield* directoryIdentity(root);
1288 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
1289 const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS;
1290
1291 const candidates = cachedCandidates ?? (yield* collectCandidates()).candidates;
1292 cachedCandidates = candidates;
1293
1294 const eligibleTranscripts: Array<{
1295 readonly candidate: RawCandidate;
1296 readonly transcript: RawCandidate["transcripts"][number] & { readonly mtimeMs: number };
1297 }> = [];
1298 for (const candidate of candidates) {
1299 const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1300 if (!path.isAbsolute(expanded)) continue;
1301 const resolved = path.resolve(expanded);
1302 if ((yield* directoryIdentity(resolved)) !== rootIdentity) continue;
1303
1304 for (const transcript of candidate.transcripts) {
1305 if (
1306 transcript.mtimeMs === null ||
1307 transcript.mtimeMs < cutoffMs ||
1308 transcript.mtimeMs > nowMs
1309 ) {
1310 continue;
1311 }
1312 eligibleTranscripts.push({
1313 candidate,
1314 transcript: { ...transcript, mtimeMs: transcript.mtimeMs },
1315 });
1316 }
1317 }
1318
1319 eligibleTranscripts.sort((left, right) => {
1320 if (left.transcript.mtimeMs !== right.transcript.mtimeMs) {
1321 return right.transcript.mtimeMs - left.transcript.mtimeMs;
1322 }
1323 return left.transcript.filePath.localeCompare(right.transcript.filePath);
1324 });
1325
1326 const completedByFile = Map.groupBy(
1327 completedSources,
1328 (source) => `${source.providerInstanceId}\0${source.filePath}`,
1329 );
1330 const importedSessions = new Set<string>();
1331 let bytesRemaining = MAX_IMPORT_BYTES;
1332 let transcriptsRemaining = MAX_IMPORT_TRANSCRIPTS;
1333 let recordsRemaining = MAX_IMPORT_RECORDS;
1334 return Stream.fromIteratorSucceed(eligibleTranscripts.values(), 1).pipe(
1335 Stream.mapEffect(({ candidate, transcript }) =>
1336 Effect.gen(function* () {
1337 const completed = completedByFile.get(
1338 `${candidate.providerInstanceId}\0${transcript.filePath}`,
1339 );
1340 if (
1341 completed === undefined &&
1342 (transcriptsRemaining === 0 || bytesRemaining === 0 || recordsRemaining === 0)
1343 ) {
1344 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1345 }
1346 const stats = yield* statOption(transcript.filePath);
1347 if (Option.isNone(stats) || stats.value.type !== "File") {
1348 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1349 }
1350 const identity = transcriptIdentity(transcript.filePath, stats.value);
1351 const completedSource = completed?.find(
1352 (source) =>
1353 source.provider === candidate.source && sameTranscriptIdentity(source, identity),
1354 );
1355 if (completedSource !== undefined) {
1356 const sessionKey = `${completedSource.providerInstanceId}\0${completedSource.providerSessionId}`;
1357 if (importedSessions.has(sessionKey)) return Option.none<AgentSessionRecentThread>();
1358 importedSessions.add(sessionKey);
1359 return Option.some<AgentSessionRecentThread>({
1360 _tag: "AlreadyImported",
1361 source: completedSource,
1362 });
1363 }
1364 if (
1365 transcriptsRemaining === 0 ||
1366 recordsRemaining === 0 ||
1367 identity.size > MAX_IMPORTED_TRANSCRIPT_BYTES ||
1368 identity.size > bytesRemaining
1369 ) {
1370 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1371 }
1372 transcriptsRemaining -= 1;
1373 bytesRemaining -= identity.size;
1374 const snapshot = yield* readTranscript(
1375 transcript.filePath,
1376 identity,
1377 recordsRemaining,
1378 candidate.source,
1379 );
1380 if (snapshot === null) {
1381 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1382 }
1383 recordsRemaining -= snapshot.recordCount;
1384
1385 let snapshotCwd: string | null = null;
1386 for (const record of snapshot.records) {
1387 snapshotCwd = extractDecodedCwd(record);
1388 if (snapshotCwd !== null) break;
1389 }
1390 if (snapshotCwd === null) {
1391 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1392 }
1393 const expandedCwd = expandHomePath(snapshotCwd.trim(), homeDir);
1394 if (
1395 !path.isAbsolute(expandedCwd) ||
1396 (yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity
1397 ) {
1398 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1399 }
1400
1401 const parsedThread = parseAgentSessionRecords(
1402 {
1403 source: candidate.source,
1404 providerInstanceId: candidate.providerInstanceId,
1405 fallbackSessionId: path.basename(transcript.filePath, ".jsonl"),
1406 lastActiveAtMs: transcript.mtimeMs,
1407 },
1408 snapshot.records,
1409 );
1410 if (parsedThread === null) {
1411 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1412 }
1413
1414 const source: AgentSessionImportSource = {
1415 ...identity,
1416 provider: parsedThread.source,
1417 providerInstanceId: parsedThread.providerInstanceId,
1418 providerSessionId: parsedThread.providerSessionId,
1419 };
1420 const sessionKey = `${parsedThread.providerInstanceId}\0${parsedThread.providerSessionId}`;
1421 if (importedSessions.has(sessionKey)) {
1422 return Option.some<AgentSessionRecentThread>({ _tag: "Duplicate", source });
1423 }
1424 importedSessions.add(sessionKey);
1425 return Option.some<AgentSessionRecentThread>({
1426 _tag: "Importable",
1427 thread: parsedThread,
1428 source,
1429 });
1430 }).pipe(importReadLock.withPermits(1)),
1431 ),
1432 Stream.map(Option.toArray),
1433 Stream.flattenIterable,
1434 );
1435 });
1436
1437 const recentThreads: AgentSessionScanner["Service"]["recentThreads"] = (
1438 workspaceRoot,
1439 completedSources = [],
1440 ) => Stream.unwrap(prepareRecentThreads(workspaceRoot, completedSources));
1441
1442 return AgentSessionScanner.of({ scan, recentThreads });
1443});
1444
1445export const layer = Layer.effect(AgentSessionScanner, make);