Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AgentSessionScanner.ts

1,313 lines49.1 KB

1/**
2 * AgentSessionScanner - discovery of projects a user already works on.
3 *
4 * Claude Code and Codex both keep a per-session transcript on disk, and each
5 * transcript records the directory the session ran in. Reading those `cwd`
6 * values gives us the set of directories worth offering as projects during
7 * onboarding, without asking the user to browse the filesystem.
8 *
9 * The scan is read-only and best-effort: an unreadable home, a malformed
10 * transcript, or a directory that has since been deleted is skipped rather
11 * than failing the scan. Project creation stays with the client, which
12 * dispatches `project.create` for whichever candidates the user picks.
13 *
14 * @module project/AgentSessionScanner
15 */
16import * as NodeOS from "node:os";
17​
18import {
19 AgentSessionScanError,
20 ClaudeSettings,
21 CodexSettings,
22 ProviderDriverKind,
23 ProviderInstanceId,
24 resolveProviderInstanceEnabled,
25 type AgentSessionImportSource,
26 type AgentSessionProjectCandidate,
27 type AgentSessionScanResult,
28 type ProviderInstanceConfig,
29} from "@t3tools/contracts";
30import * as Context from "effect/Context";
31import * as DateTime from "effect/DateTime";
32import * as Effect from "effect/Effect";
33import * as FileSystem from "effect/FileSystem";
34import * as Layer from "effect/Layer";
35import * as Option from "effect/Option";
36import * as Path from "effect/Path";
37import * as Schema from "effect/Schema";
38import * as Stream from "effect/Stream";
39​
40import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
41import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
42​
43import * as ServerConfig from "../config.ts";
44import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
45import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
46import { expandHomePath } from "../pathExpansion.ts";
47import * as ServerSettings from "../serverSettings.ts";
48​
49/** Chunk size for full transcript reads. */
50const TRANSCRIPT_PREFIX_BYTES = 32 * 1024;
51/** Small reads avoid wasting the metadata budget on long Codex instruction headers. */
52const METADATA_READ_BYTES = 8 * 1024;
53/** Prevent malformed transcripts from turning project discovery into a full file scan. */
54const MAX_TRANSCRIPT_SCAN_BYTES = 1024 * 1024;
55​
56/**
57 * Upper bound on transcripts inspected (first line read) per source.
58 * Newest-first ordering means the cap drops only stale sessions when a home
59 * directory is unusually large.
60 */
61const MAX_TRANSCRIPTS_PER_SOURCE = 5000;
62​
63/**
64 * Upper bound on discovery filesystem operations per source. Newest-first
65 * ordering needs mtimes before the read cap can be applied, so directory reads
66 * and candidate stats share a larger budget. Once it runs out the scan stops.
67 */
68const MAX_DISCOVERY_OPERATIONS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 4;
69const MAX_METADATA_BYTES_PER_SOURCE = 64 * 1024 * 1024;
70const MAX_METADATA_OPERATIONS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 4;
71const MAX_METADATA_RECORDS_PER_SOURCE = 100_000;
72const MAX_METADATA_RECORDS_PER_TRANSCRIPT = 1_000;
73const RECENT_THREAD_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
74const MAX_IMPORTED_TRANSCRIPT_BYTES = 16 * 1024 * 1024;
75const MAX_IMPORTED_MESSAGES = 200;
76const MAX_IMPORT_BYTES = 64 * 1024 * 1024;
77const MAX_IMPORT_TRANSCRIPTS = 100;
78const MAX_IMPORT_RECORDS = 100_000;
79​
80const TranscriptContentBlock = Schema.Struct({
81 type: Schema.optional(Schema.String),
82 text: Schema.optional(Schema.String),
83});
84​
85const TranscriptMessage = Schema.Struct({
86 role: Schema.optional(Schema.String),
87 content: Schema.optional(Schema.Union([Schema.String, Schema.Array(TranscriptContentBlock)])),
88 model: Schema.optional(Schema.String),
89});
90​
91const CodexTurnMetadata = Schema.Struct({
92 turn_id: Schema.optional(Schema.Union([Schema.String, Schema.Null])),
93});
94​
95const TranscriptRecord = Schema.Struct({
96 type: Schema.optional(Schema.String),
97 timestamp: Schema.optional(Schema.String),
98 sessionId: Schema.optional(Schema.String),
99 aiTitle: Schema.optional(Schema.String),
100 isSidechain: Schema.optional(Schema.Boolean),
101 isMeta: Schema.optional(Schema.Boolean),
102 isCompactSummary: Schema.optional(Schema.Boolean),
103 message: Schema.optional(TranscriptMessage),
104 payload: Schema.optional(
105 Schema.Struct({
106 id: Schema.optional(Schema.String),
107 session_id: Schema.optional(Schema.String),
108 type: Schema.optional(Schema.String),
109 role: Schema.optional(Schema.String),
110 message: Schema.optional(Schema.String),
111 model: Schema.optional(Schema.String),
112 content: Schema.optional(Schema.Array(TranscriptContentBlock)),
113 internal_chat_message_metadata_passthrough: Schema.optional(Schema.Unknown),
114 }),
115 ),
116});
117​
118const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
119const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings);
120const decodeTranscriptRecord = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptRecord));
121const decodeCodexTurnMetadata = Schema.decodeUnknownOption(CodexTurnMetadata);
122​
123export interface AgentSessionThreadMessage {
124 readonly role: "user" | "assistant";
125 readonly text: string;
126 readonly createdAt: string;
128​
129export interface AgentSessionThread {
130 readonly source: AgentSessionSource;
131 readonly providerInstanceId: ProviderInstanceId;
132 readonly providerSessionId: string;
133 readonly title: string;
134 readonly model: string | null;
135 readonly createdAt: string;
136 readonly updatedAt: string;
137 readonly messages: ReadonlyArray<AgentSessionThreadMessage>;
139​
140export type AgentSessionRecentThread =
141 | {
142 readonly _tag: "Importable";
143 readonly thread: AgentSessionThread;
144 readonly source: AgentSessionImportSource;
145 }
146 | { readonly _tag: "AlreadyImported"; readonly source: AgentSessionImportSource }
147 | { readonly _tag: "Duplicate"; readonly source: AgentSessionImportSource }
148 | { readonly _tag: "Skipped" };
149​
150/** Service tag for agent session discovery. */
151export class AgentSessionScanner extends Context.Service<
152 AgentSessionScanner,
153 {
154 /**
155 * Discover every directory the configured Claude and Codex homes have run
156 * a session in. Candidates are returned newest-first; the client decides
157 * which ones to import and how far back to look. Fails with the contract
158 * error directly — there is no server-local context worth wrapping.
159 */
160 readonly scan: Effect.Effect<AgentSessionScanResult, AgentSessionScanError>;
161 readonly recentThreads: (
162 workspaceRoot: string,
163 completedSources?: ReadonlyArray<AgentSessionImportSource>,
164 ) => Stream.Stream<AgentSessionRecentThread, AgentSessionScanError>;
165 }
166>()("t3/project/AgentSessionScanner") {}
167​
168type AgentSessionSource = AgentSessionProjectCandidate["sources"][number];
169​
170/** A single directory's worth of evidence from one source. */
171interface RawCandidate {
172 readonly cwd: string;
173 readonly source: AgentSessionSource;
174 readonly providerInstanceId: ProviderInstanceId;
175 readonly threadCount: number;
176 readonly lastActiveAtMs: number | null;
177 readonly transcripts: ReadonlyArray<{
178 readonly filePath: string;
179 readonly mtimeMs: number | null;
180 }>;
182​
183interface TranscriptCandidate {
184 readonly filePath: string;
185 readonly mtimeMs: number;
186 readonly providerInstanceId: ProviderInstanceId;
187 readonly size: number;
189​
190interface MetadataReadBudget {
191 bytesRemaining: number;
192 operationsRemaining: number;
193 recordsRemaining: number;
194 truncated: boolean;
196​
197function selectMetadataTranscripts(transcripts: ReadonlyArray<TranscriptCandidate>) {
198 const selected: Array<TranscriptCandidate> = [];
199 let pending = Array.from(
200 Map.groupBy(transcripts, (transcript) => transcript.providerInstanceId).values(),
201 (entries) => entries.values(),
202 );
203 while (pending.length > 0 && selected.length < MAX_TRANSCRIPTS_PER_SOURCE) {
204 const nextRound: typeof pending = [];
205 for (const iterator of pending) {
206 if (selected.length === MAX_TRANSCRIPTS_PER_SOURCE) break;
207 const next = iterator.next();
208 if (next.done) continue;
209 selected.push(next.value);
210 nextRound.push(iterator);
211 }
212 pending = nextRound;
213 }
214 return selected;
216​
217function splitTranscriptRecords(contents: string, limit: number): string[] {
218 const records = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
219 return records.split("\n", limit);
221​
222function extractText(
223 content: string | ReadonlyArray<typeof TranscriptContentBlock.Type> | undefined,
224): string {
225 if (typeof content === "string") return content.trim();
226 if (content === undefined) return "";
227 return content
228 .filter(
229 (block) =>
230 block.type === "text" || block.type === "input_text" || block.type === "output_text",
231 )
232 .map((block) => block.text?.trim() ?? "")
233 .filter((text) => text.length > 0)
234 .join("\n");
236​
237function normalizeTimestamp(value: string | undefined, fallback: string): string {
238 if (value === undefined) return fallback;
239 const parsed = DateTime.make(value);
240 return Option.isSome(parsed) ? DateTime.formatIso(parsed.value) : fallback;
242​
243function codexTurnId(metadata: unknown): string | null {
244 const decoded = decodeCodexTurnMetadata(metadata);
245 if (
246 Option.isNone(decoded) ||
247 typeof decoded.value.turn_id !== "string" ||
248 decoded.value.turn_id.trim().length === 0
249 ) {
250 return null;
251 }
252 return decoded.value.turn_id;
254​
255/** Keep visible user and assistant text while ignoring tools, reasoning, and malformed records. */
256export function parseAgentSessionTranscript(
257 input: {
258 readonly contents: string;
259 readonly source: AgentSessionSource;
260 readonly providerInstanceId: ProviderInstanceId;
261 readonly fallbackSessionId: string;
262 readonly lastActiveAtMs: number;
263 },
264 lines = splitTranscriptRecords(input.contents, MAX_IMPORT_RECORDS + 1),
265): AgentSessionThread | null {
266 if (lines.length > MAX_IMPORT_RECORDS) return null;
267 const fallbackTimestamp = DateTime.formatIso(DateTime.makeUnsafe(input.lastActiveAtMs));
268 // Claude filenames are session IDs. Codex rollout filenames include extra
269 // timestamp text, so only transcript metadata can provide a resumable ID.
270 let providerSessionId = input.source === "codex" ? "" : input.fallbackSessionId;
271 let title: string | null = null;
272 let model: string | null = null;
273 let hasCodexSessionId = false;
274 const messages: Array<AgentSessionThreadMessage & { readonly codexResponseUser: boolean }> = [];
275 let firstUserMessage:
276 | (AgentSessionThreadMessage & { readonly codexResponseUser: boolean })
277 | undefined;
278 function* decodedRecords() {
279 for (const line of lines) {
280 const decoded = decodeTranscriptRecord(line);
281 if (Option.isSome(decoded)) yield decoded.value;
282 }
283 }
284​
285 // A Codex response item can include generated setup text beside the real
286 // prompt. Suppress response-user records only when the shared turn ID and a
287 // verbatim event copy prove which prompt the user submitted.
288 const canonicalCodexResponseUserIndices = new Set<number>();
289 let canonicalUserTextsInTurn = new Set<string>();
290 let responseUsersInTurn: Array<{
291 readonly index: number;
292 readonly turnId: string;
293 readonly text: string;
294 }> = [];
295 const finishCodexTurn = () => {
296 const canonicalTurnIds = new Set(
297 responseUsersInTurn.flatMap((responseUser) =>
298 canonicalUserTextsInTurn.has(responseUser.text) ? [responseUser.turnId] : [],
299 ),
300 );
301 for (const responseUser of responseUsersInTurn) {
302 if (canonicalTurnIds.has(responseUser.turnId)) {
303 canonicalCodexResponseUserIndices.add(responseUser.index);
304 }
305 }
306 canonicalUserTextsInTurn = new Set();
307 responseUsersInTurn = [];
308 };
309 if (input.source === "codex") {
310 let recordIndex = -1;
311 for (const record of decodedRecords()) {
312 recordIndex += 1;
313 if (
314 record.type === "response_item" &&
315 record.payload?.type === "message" &&
316 record.payload.role === "assistant"
317 ) {
318 finishCodexTurn();
319 continue;
320 }
321 if (record.type === "event_msg" && record.payload?.type === "user_message") {
322 const text = record.payload.message?.trim() ?? "";
323 if (text.length > 0) canonicalUserTextsInTurn.add(text);
324 continue;
325 }
326 if (
327 record.type === "response_item" &&
328 record.payload?.type === "message" &&
329 record.payload.role === "user"
330 ) {
331 const turnId = codexTurnId(record.payload.internal_chat_message_metadata_passthrough);
332 const text = extractText(record.payload.content);
333 if (turnId !== null && text.length > 0) {
334 responseUsersInTurn.push({ index: recordIndex, turnId, text });
335 }
336 }
337 }
338 finishCodexTurn();
339 }
340​
341 const retainMessage = (
342 message: AgentSessionThreadMessage & { readonly codexResponseUser: boolean },
343 ) => {
344 if (firstUserMessage === undefined && message.role === "user") {
345 firstUserMessage = message;
346 }
347 messages.push(message);
348 if (messages.length > MAX_IMPORTED_MESSAGES) messages.shift();
349 };
350​
351 const hasMatchingCodexEventInTurn = (text: string) => {
352 const comparisonText = text.trim();
353 for (let index = messages.length - 1; index >= 0; index--) {
354 const message = messages[index];
355 if (message?.role === "assistant") return false;
356 if (
357 message?.role === "user" &&
358 !message.codexResponseUser &&
359 message.text.trim() === comparisonText
360 ) {
361 return true;
362 }
363 }
364 return false;
365 };
366​
367 let recordIndex = -1;
368 for (const record of decodedRecords()) {
369 recordIndex += 1;
370 if (input.source === "claudeAgent") {
371 if (
372 record.isSidechain === true ||
373 record.isMeta === true ||
374 record.isCompactSummary === true
375 ) {
376 continue;
377 }
378 if (record.sessionId?.trim()) providerSessionId = record.sessionId.trim();
379 if (record.aiTitle?.trim()) title = record.aiTitle.trim();
380 const messageModel = record.message?.model?.trim();
381 // Claude uses this sentinel for local error responses. It is not a
382 // model ID that can be selected when the imported session resumes.
383 if (messageModel && messageModel !== "<synthetic>") model = messageModel;
384 if (record.type !== "user" && record.type !== "assistant") {
385 continue;
386 }
387​
388 const text = extractText(record.message?.content);
389 if (text.length === 0) continue;
390 retainMessage({
391 role: record.type,
392 text,
393 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
394 codexResponseUser: false,
395 });
396 continue;
397 }
398​
399 if (record.type === "session_meta") {
400 const sessionId = record.payload?.id?.trim() || record.payload?.session_id?.trim();
401 if (!hasCodexSessionId && sessionId) {
402 providerSessionId = sessionId;
403 hasCodexSessionId = true;
404 }
405 continue;
406 }
407 if (record.type === "turn_context" && record.payload?.model?.trim()) {
408 model = record.payload.model.trim();
409 continue;
410 }
411 if (record.type === "event_msg" && record.payload?.type === "user_message") {
412 const text = record.payload.message ?? "";
413 if (text.trim().length === 0) continue;
414 // Codex can write the same prompt as both a response item and an event.
415 // Remove only the matching response copy so mixed-format logs keep every
416 // distinct user message.
417 for (let index = messages.length - 1; index >= 0; index--) {
418 const message = messages[index];
419 if (message?.role === "assistant") break;
420 if (message?.codexResponseUser === true && message.text.trim() === text.trim()) {
421 if (firstUserMessage === message) firstUserMessage = undefined;
422 messages.splice(index, 1);
423 break;
424 }
425 }
426 retainMessage({
427 role: "user",
428 text,
429 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
430 codexResponseUser: false,
431 });
432 continue;
433 }
434 if (
435 record.type !== "response_item" ||
436 record.payload?.type !== "message" ||
437 (record.payload.role !== "user" && record.payload.role !== "assistant")
438 ) {
439 continue;
440 }
441​
442 const extractedText = extractText(record.payload.content);
443 if (extractedText.length === 0) continue;
444 if (record.payload.role === "user" && canonicalCodexResponseUserIndices.has(recordIndex)) {
445 continue;
446 }
447 if (record.payload.role === "user" && hasMatchingCodexEventInTurn(extractedText)) {
448 continue;
449 }
450 retainMessage({
451 role: record.payload.role,
452 text: extractedText,
453 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
454 codexResponseUser: record.payload.role === "user",
455 });
456 }
457​
458 const visibleMessages = messages.map(
459 ({ codexResponseUser: _codexResponseUser, ...message }) => message,
460 );
461 if (providerSessionId.trim().length === 0 || firstUserMessage === undefined) return null;
462 const firstUserMessageRetained = messages.includes(firstUserMessage);
463 const { codexResponseUser: _codexResponseUser, ...visibleFirstUserMessage } = firstUserMessage;
464 const retainedMessages = firstUserMessageRetained
465 ? visibleMessages
466 : [visibleFirstUserMessage, ...visibleMessages.slice(-(MAX_IMPORTED_MESSAGES - 1))];
467 const derivedTitle = visibleFirstUserMessage.text.trim().split("\n")[0]?.slice(0, 100).trim();
468​
469 return {
470 source: input.source,
471 providerInstanceId: input.providerInstanceId,
472 providerSessionId,
473 title: title ?? (derivedTitle && derivedTitle.length > 0 ? derivedTitle : "Imported thread"),
474 model,
475 createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp,
476 updatedAt: fallbackTimestamp,
477 messages: retainedMessages,
478 };
480​
481/**
482 * T3 Code runs its own agent sessions inside disposable worktrees. Their
483 * transcripts look exactly like user sessions, but re-importing the app's own
484 * sandboxes as projects is never right. Matches this server's configured
485 * worktrees directory plus the conventional `.t3/worktrees` layout, which
486 * also catches sandboxes from other T3 homes on the same machine. Separators
487 * are normalized (and, on Windows, case folded) so the prefix match holds
488 * there too. Callers check both the recorded spelling and its realpath so a
489 * symlink into the worktrees directory cannot bypass the filter.
490 */
491function normalizeForWorktreeMatch(value: string, caseFold: boolean): string {
492 const normalized = `${value.replaceAll("\\", "/")}/`;
493 return caseFold ? normalized.toLowerCase() : normalized;
495​
496function isT3ManagedWorktree(
497 candidatePath: string,
498 worktreesDir: string,
499 caseFold: boolean,
500): boolean {
501 const normalized = normalizeForWorktreeMatch(candidatePath, caseFold);
502 return (
503 normalized.startsWith(normalizeForWorktreeMatch(worktreesDir, caseFold)) ||
504 normalized.includes("/.t3/worktrees/")
505 );
507​
508/** Extract `cwd` from a session-meta record, tolerating the shapes each CLI writes. */
509function extractCwd(line: string): string | null {
510 let parsed: unknown;
511 try {
512 parsed = JSON.parse(line);
513 } catch {
514 return null;
515 }
516 if (typeof parsed !== "object" || parsed === null) return null;
517​
518 const record = parsed as Record<string, unknown>;
519 if (typeof record.cwd === "string" && record.cwd.trim().length > 0) {
520 return record.cwd;
521 }
522 // Codex nests session metadata under `payload`.
523 const payload = record.payload;
524 if (typeof payload === "object" && payload !== null) {
525 const nested = (payload as Record<string, unknown>).cwd;
526 if (typeof nested === "string" && nested.trim().length > 0) {
527 return nested;
528 }
529 }
530 return null;
532​
533function transcriptIdentity(filePath: string, stats: FileSystem.File.Info) {
534 return {
535 filePath,
536 size: Number(stats.size),
537 mtimeMs: Option.match(stats.mtime, { onNone: () => null, onSome: (date) => date.getTime() }),
538 device: stats.dev,
539 inode: Option.getOrNull(stats.ino),
540 birthtimeMs: Option.match(stats.birthtime, {
541 onNone: () => null,
542 onSome: (date) => date.getTime(),
543 }),
544 };
546​
547function sameTranscriptIdentity(
548 left: ReturnType<typeof transcriptIdentity>,
549 right: ReturnType<typeof transcriptIdentity>,
550): boolean {
551 return (
552 left.filePath === right.filePath &&
553 left.size === right.size &&
554 left.mtimeMs === right.mtimeMs &&
555 left.device === right.device &&
556 left.inode === right.inode &&
557 left.birthtimeMs === right.birthtimeMs
558 );
560​
561export const make = Effect.gen(function* () {
562 const fileSystem = yield* FileSystem.FileSystem;
563 const path = yield* Path.Path;
564 const serverConfig = yield* ServerConfig.ServerConfig;
565 const serverSettings = yield* ServerSettings.ServerSettingsService;
566 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
567 const baseDir = path.resolve(serverConfig.baseDir);
568 const worktreesDir = path.resolve(serverConfig.worktreesDir);
569 // Windows filesystems are case-insensitive, so path prefix checks there
570 // must case fold.
571 const foldWorktreeCase = (yield* HostProcessPlatform) === "win32";
572 const hostEnvironment = yield* HostProcessEnvironment;
573 const excludedProjectRoots = new Set(
574 [NodeOS.homedir(), NodeOS.tmpdir()].map((directory) =>
575 normalizeProjectPathForComparison(path.resolve(directory)),
576 ),
577 );
578​
579 const isExcludedProjectPath = (candidatePath: string) =>
580 excludedProjectRoots.has(normalizeProjectPathForComparison(candidatePath)) ||
581 normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith(
582 normalizeForWorktreeMatch(baseDir, foldWorktreeCase),
583 ) ||
584 isT3ManagedWorktree(candidatePath, worktreesDir, foldWorktreeCase);
585​
586 const listDirectory = (directory: string) =>
587 fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
588​
589 const statOption = (target: string) =>
590 fileSystem.stat(target).pipe(Effect.map(Option.some), Effect.orElseSucceed(Option.none));
591​
592 /** Match directory aliases without assuming the host volume is case-insensitive. */
593 const directoryIdentity = Effect.fn("AgentSessionScanner.directoryIdentity")(function* (
594 target: string,
595 knownStats?: FileSystem.File.Info,
596 ) {
597 const resolved = path.resolve(target);
598 const stats = knownStats === undefined ? yield* statOption(resolved) : Option.some(knownStats);
599 if (
600 Option.isSome(stats) &&
601 Option.isSome(stats.value.ino) &&
602 Number.isSafeInteger(stats.value.ino.value) &&
603 stats.value.ino.value > 0
604 ) {
605 return `inode:${stats.value.dev}:${stats.value.ino.value}`;
606 }
607 const realPath = yield* fileSystem
608 .realPath(resolved)
609 .pipe(Effect.orElseSucceed(() => resolved));
610 return `path:${normalizeProjectPathForComparison(realPath)}`;
611 });
612​
613 // A large history snapshot can precede session metadata. Read bounded
614 // chunks until a complete record names its cwd or the safety budget ends.
615 const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* (
616 transcript: TranscriptCandidate,
617 budget: MetadataReadBudget,
618 ) {
619 if (transcript.size === 0) return null;
620 if (
621 budget.bytesRemaining === 0 ||
622 budget.operationsRemaining < 2 ||
623 budget.recordsRemaining === 0
624 ) {
625 budget.truncated = true;
626 return null;
627 }
628 budget.operationsRemaining -= 1;
629 return yield* Effect.scoped(
630 fileSystem.open(transcript.filePath, { flag: "r" }).pipe(
631 Effect.flatMap((file) =>
632 Effect.gen(function* () {
633 const decoder = new TextDecoder();
634 let remaining = "";
635 let bytesRead = 0;
636 let recordsRead = 0;
637 const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, transcript.size);
638 const reserveRecord = () => {
639 if (
640 recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT ||
641 budget.recordsRemaining === 0
642 ) {
643 budget.truncated = true;
644 return false;
645 }
646 recordsRead += 1;
647 budget.recordsRemaining -= 1;
648 return true;
649 };
650 const readLastRecord = () => {
651 const record = remaining + decoder.decode();
652 return record.length === 0 || !reserveRecord() ? null : extractCwd(record.trim());
653 };
654​
655 while (bytesRead < maxBytes) {
656 if (budget.bytesRemaining === 0 || budget.operationsRemaining === 0) {
657 budget.truncated = true;
658 return null;
659 }
660 const readSize = Math.min(
661 METADATA_READ_BYTES,
662 maxBytes - bytesRead,
663 budget.bytesRemaining,
664 );
665 budget.operationsRemaining -= 1;
666 budget.bytesRemaining -= readSize;
667 const next = yield* file.readAlloc(readSize);
668 if (Option.isNone(next)) {
669 return readLastRecord();
670 }
671​
672 bytesRead += next.value.byteLength;
673 remaining += decoder.decode(next.value, { stream: true });
674 const lines = remaining.split("\n");
675 remaining = lines.pop() ?? "";
676​
677 for (const line of lines) {
678 if (!reserveRecord()) return null;
679 const cwd = extractCwd(line.trim());
680 if (cwd !== null) return cwd;
681 }
682 }
683​
684 if (bytesRead < transcript.size) {
685 budget.truncated = true;
686 return null;
687 }
688 return readLastRecord();
689 }),
690 ),
691 ),
692 ).pipe(Effect.orElseSucceed(() => null));
693 });
694​
695 /** Check the open file before and after reading, without reading past its reserved byte budget. */
696 const readTranscript = Effect.fn("AgentSessionScanner.readTranscript")(function* (
697 filePath: string,
698 expected: ReturnType<typeof transcriptIdentity>,
699 ) {
700 if (expected.size > MAX_IMPORTED_TRANSCRIPT_BYTES) return null;
701​
702 return yield* Effect.scoped(
703 fileSystem.open(filePath, { flag: "r" }).pipe(
704 Effect.flatMap((file) =>
705 Effect.gen(function* () {
706 if (!sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))) {
707 return null;
708 }
709 const decoder = new TextDecoder();
710 let contents = "";
711 let bytesRead = 0;
712​
713 while (bytesRead < expected.size) {
714 const next = yield* file.readAlloc(
715 Math.min(TRANSCRIPT_PREFIX_BYTES, expected.size - bytesRead),
716 );
717 if (Option.isNone(next)) {
718 return null;
719 }
720​
721 bytesRead += next.value.byteLength;
722 contents += decoder.decode(next.value, { stream: true });
723 }
724​
725 return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))
726 ? contents + decoder.decode()
727 : null;
728 }),
729 ),
730 ),
731 ).pipe(Effect.orElseSucceed(() => null));
732 });
733​
734 /**
735 * Resolve the Claude config directory the CLI would use, matching the
736 * precedence the spawned CLI sees: the instance's `homePath` (exported as
737 * `CLAUDE_CONFIG_DIR`), then a `CLAUDE_CONFIG_DIR` already in the
738 * environment, then `~/.claude`.
739 */
740 const resolveClaudeConfigDir = (homePath: string, environmentHome?: string): string => {
741 const configured = homePath.trim();
742 if (configured.length > 0) {
743 return path.resolve(expandHomePath(configured));
744 }
745 const fromEnvironment = environmentHome?.trim() ?? "";
746 if (fromEnvironment.length > 0) {
747 return path.resolve(expandHomePath(fromEnvironment));
748 }
749 return path.join(NodeOS.homedir(), ".claude");
750 };
751​
752 const discoverClaudeTranscripts = Effect.fn("AgentSessionScanner.discoverClaudeTranscripts")(
753 function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) {
754 const projectsDir = path.join(homePath, "projects");
755 let operationsRemaining = operationBudget;
756 let truncated = false;
757 const readDirectory = (directory: string) => {
758 if (operationsRemaining <= 0) {
759 truncated = true;
760 return Effect.succeed<ReadonlyArray<string>>([]);
761 }
762 operationsRemaining -= 1;
763 return listDirectory(directory);
764 };
765 const projectDirectories = yield* readDirectory(projectsDir);
766 const transcripts: Array<TranscriptCandidate> = [];
767​
768 for (const projectDirectory of projectDirectories) {
769 if (operationsRemaining <= 0) {
770 truncated = true;
771 break;
772 }
773 const directory = path.join(projectsDir, projectDirectory);
774 const directoryTranscripts = (yield* readDirectory(directory))
775 .filter((entry) => entry.endsWith(".jsonl"))
776 .map((entry) => path.join(directory, entry));
777​
778 for (const filePath of directoryTranscripts) {
779 if (operationsRemaining <= 0) {
780 truncated = true;
781 break;
782 }
783 operationsRemaining -= 1;
784 const stats = yield* statOption(filePath);
785 if (
786 Option.isNone(stats) ||
787 stats.value.type !== "File" ||
788 Option.isNone(stats.value.mtime)
789 ) {
790 continue;
791 }
792 transcripts.push({
793 filePath,
794 mtimeMs: stats.value.mtime.value.getTime(),
795 providerInstanceId,
796 size: Number(stats.value.size),
797 });
798 }
799 }
800 return { transcripts, truncated };
801 },
802 );
803​
804 const discoverCodexTranscripts = Effect.fn("AgentSessionScanner.discoverCodexTranscripts")(
805 function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) {
806 const sessionsDir = path.join(homePath, "sessions");
807​
808 const transcripts: Array<TranscriptCandidate> = [];
809 let operationsRemaining = operationBudget;
810 let truncated = false;
811 const readDirectory = (directory: string) => {
812 if (operationsRemaining <= 0) {
813 truncated = true;
814 return Effect.succeed<ReadonlyArray<string>>([]);
815 }
816 operationsRemaining -= 1;
817 return listDirectory(directory);
818 };
819 // Date-partitioned directories sort chronologically, so walking them in
820 // reverse spends each home's share of the operation budget on recent sessions.
821 for (const year of (yield* readDirectory(sessionsDir)).toSorted().toReversed()) {
822 if (operationsRemaining <= 0) {
823 truncated = true;
824 break;
825 }
826 for (const month of (yield* readDirectory(path.join(sessionsDir, year)))
827 .toSorted()
828 .toReversed()) {
829 if (operationsRemaining <= 0) {
830 truncated = true;
831 break;
832 }
833 for (const day of (yield* readDirectory(path.join(sessionsDir, year, month)))
834 .toSorted()
835 .toReversed()) {
836 if (operationsRemaining <= 0) {
837 truncated = true;
838 break;
839 }
840 const directory = path.join(sessionsDir, year, month, day);
841 for (const entry of (yield* readDirectory(directory)).toSorted().toReversed()) {
842 if (!entry.startsWith("rollout-") || !entry.endsWith(".jsonl")) continue;
843 if (operationsRemaining <= 0) {
844 truncated = true;
845 break;
846 }
847 const filePath = path.join(directory, entry);
848 operationsRemaining -= 1;
849 const stats = yield* statOption(filePath);
850 if (
851 Option.isSome(stats) &&
852 stats.value.type === "File" &&
853 Option.isSome(stats.value.mtime)
854 ) {
855 transcripts.push({
856 filePath,
857 mtimeMs: stats.value.mtime.value.getTime(),
858 providerInstanceId,
859 size: Number(stats.value.size),
860 });
861 }
862 }
863 }
864 }
865 }
866 return { transcripts, truncated };
867 },
868 );
869​
870 const groupTranscriptsByCwd = Effect.fn("AgentSessionScanner.groupTranscriptsByCwd")(function* (
871 source: AgentSessionSource,
872 transcripts: ReadonlyArray<TranscriptCandidate>,
873 budget: MetadataReadBudget,
874 ) {
875 const byOwnerAndCwd = new Map<
876 string,
877 {
878 cwd: string;
879 providerInstanceId: ProviderInstanceId;
880 lastActiveAtMs: number;
881 transcripts: Array<{ filePath: string; mtimeMs: number }>;
882 }
883 >();
884​
885 for (const transcript of transcripts) {
886 const cwd = yield* readCwd(transcript, budget);
887 if (cwd === null) continue;
888 const key = `${transcript.providerInstanceId}\0${cwd}`;
889 const existing = byOwnerAndCwd.get(key);
890 if (existing) {
891 existing.lastActiveAtMs = Math.max(existing.lastActiveAtMs, transcript.mtimeMs);
892 existing.transcripts.push(transcript);
893 } else {
894 byOwnerAndCwd.set(key, {
895 cwd,
896 providerInstanceId: transcript.providerInstanceId,
897 lastActiveAtMs: transcript.mtimeMs,
898 transcripts: [transcript],
899 });
900 }
901 }
902​
903 return Array.from(byOwnerAndCwd.values(), (group): RawCandidate => ({
904 cwd: group.cwd,
905 source,
906 providerInstanceId: group.providerInstanceId,
907 threadCount: group.transcripts.length,
908 lastActiveAtMs: group.lastActiveAtMs,
909 transcripts: group.transcripts,
910 }));
911 });
912​
913 const collectCandidates = Effect.fn("AgentSessionScanner.collectCandidates")(function* () {
914 const settings = yield* serverSettings.getSettings.pipe(
915 Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-settings", cause })),
916 );
917​
918 const raw: Array<RawCandidate> = [];
919 let truncated = false;
920​
921 for (const source of ["claudeAgent", "codex"] as const) {
922 const instances: Array<{
923 readonly instanceId: ProviderInstanceId;
924 readonly config: ProviderInstanceConfig;
925 }> = Object.entries(settings.providerInstances)
926 .filter(
927 ([, instance]) => instance.driver === source && resolveProviderInstanceEnabled(instance),
928 )
929 .map(([instanceId, config]) => ({
930 instanceId: ProviderInstanceId.make(instanceId),
931 config,
932 }));
933 if (!Object.hasOwn(settings.providerInstances, source)) {
934 const legacyInstance = {
935 instanceId: ProviderInstanceId.make(source),
936 config: {
937 driver: ProviderDriverKind.make(source),
938 config: settings.providers[source],
939 },
940 };
941 if (resolveProviderInstanceEnabled(legacyInstance.config)) {
942 instances.push(legacyInstance);
943 }
944 }
945​
946 // A shared home contains one copy of each session. Prefer the built-in
947 // instance as its owner, then keep configured order for custom accounts.
948 instances.sort((left, right) => {
949 const leftDefault = left.instanceId === source ? 0 : 1;
950 const rightDefault = right.instanceId === source ? 0 : 1;
951 return leftDefault - rightDefault;
952 });
953 const homes: Array<{ homePath: string; providerInstanceId: ProviderInstanceId }> = [];
954 const seenHomes = new Set<string>();
955 for (const { instanceId, config: instance } of instances) {
956 const homeVariable = source === "claudeAgent" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME";
957 const environmentHome =
958 instance.environment?.findLast((variable) => variable.name === homeVariable)?.value ??
959 hostEnvironment[homeVariable];
960​
961 let homePath: string;
962 if (source === "claudeAgent") {
963 const config = decodeClaudeSettings(instance.config ?? {});
964 if (Option.isNone(config)) continue;
965 homePath = resolveClaudeConfigDir(config.value.homePath, environmentHome);
966 } else {
967 const config = decodeCodexSettings(instance.config ?? {});
968 if (Option.isNone(config)) continue;
969 const codexSettings =
970 config.value.homePath.trim().length === 0 &&
971 config.value.shadowHomePath.trim().length === 0 &&
972 environmentHome?.trim()
973 ? { ...config.value, homePath: environmentHome }
974 : config.value;
975 const layout = yield* resolveCodexHomeLayout(codexSettings).pipe(
976 Effect.provideService(Path.Path, path),
977 );
978 homePath = layout.sharedHomePath;
979 }
980​
981 const homeKey = `${source}\0${yield* directoryIdentity(homePath)}`;
982 if (seenHomes.has(homeKey)) continue;
983 seenHomes.add(homeKey);
984 homes.push({ homePath, providerInstanceId: instanceId });
985 }
986​
987 const transcriptCandidates: Array<TranscriptCandidate> = [];
988 const baseOperationBudget = Math.floor(
989 MAX_DISCOVERY_OPERATIONS_PER_SOURCE / Math.max(1, homes.length),
990 );
991 const extraOperationBudgets = MAX_DISCOVERY_OPERATIONS_PER_SOURCE % Math.max(1, homes.length);
992 for (const [index, home] of homes.entries()) {
993 const operationBudget = baseOperationBudget + (index < extraOperationBudgets ? 1 : 0);
994 if (operationBudget === 0) {
995 truncated = true;
996 continue;
997 }
998 const discovered = yield* source === "claudeAgent"
999 ? discoverClaudeTranscripts(home.homePath, home.providerInstanceId, operationBudget)
1000 : discoverCodexTranscripts(home.homePath, home.providerInstanceId, operationBudget);
1001 truncated ||= discovered.truncated;
1002 transcriptCandidates.push(...discovered.transcripts);
1004​
1005 transcriptCandidates.sort(
1006 (left, right) =>
1007 right.mtimeMs - left.mtimeMs || left.filePath.localeCompare(right.filePath),
1008 );
1009 if (transcriptCandidates.length > MAX_TRANSCRIPTS_PER_SOURCE) {
1010 truncated = true;
1012 // Give each account a turn before taking another file from the same home.
1013 const selectedTranscripts = selectMetadataTranscripts(transcriptCandidates);
1014 const metadataBudget: MetadataReadBudget = {
1015 bytesRemaining: MAX_METADATA_BYTES_PER_SOURCE,
1016 operationsRemaining: MAX_METADATA_OPERATIONS_PER_SOURCE,
1017 recordsRemaining: MAX_METADATA_RECORDS_PER_SOURCE,
1018 truncated: false,
1019 };
1020 raw.push(...(yield* groupTranscriptsByCwd(source, selectedTranscripts, metadataBudget)));
1021 truncated ||= metadataBudget.truncated;
1023​
1024 return { candidates: raw, truncated };
1025 });
1026​
1027 let cachedCandidates: ReadonlyArray<RawCandidate> | null = null;
1028​
1029 const scan: AgentSessionScanner["Service"]["scan"] = Effect.gen(function* () {
1030 const { candidates: raw, truncated } = yield* collectCandidates();
1031 cachedCandidates = raw;
1032​
1033 // Filesystem identity merges symlinks and case aliases without collapsing
1034 // distinct case-sensitive directories.
1035 const merged = new Map<
1036 string,
1038 path: string;
1039 sources: Array<AgentSessionSource>;
1040 threadCount: number;
1041 lastActiveAtMs: number | null;
1043 >();
1044 const directoryKeys = new Map<string, string>();
1045​
1046 for (const candidate of raw) {
1047 const expanded = expandHomePath(candidate.cwd.trim());
1048 if (!path.isAbsolute(expanded)) continue;
1049 const resolved = path.resolve(expanded);
1050 if (isExcludedProjectPath(resolved)) continue;
1051 let key = directoryKeys.get(resolved);
1052 if (key === undefined) {
1053 const stats = yield* statOption(resolved);
1054 // Directories that no longer exist can't be imported.
1055 if (Option.isNone(stats) || stats.value.type !== "Directory") {
1056 directoryKeys.set(resolved, "");
1057 continue;
1059 const realPath = yield* fileSystem
1060 .realPath(resolved)
1061 .pipe(Effect.orElseSucceed(() => resolved));
1062 // A symlink can point into the worktrees directory even when its own
1063 // spelling doesn't; check again with links resolved.
1064 if (isExcludedProjectPath(realPath)) {
1065 key = "";
1066 } else {
1067 key = yield* directoryIdentity(resolved, stats.value);
1069 directoryKeys.set(resolved, key);
1071 if (key === "") continue;
1072​
1073 const existing = merged.get(key);
1074 if (!existing) {
1075 merged.set(key, {
1076 path: resolved,
1077 sources: [candidate.source],
1078 threadCount: candidate.threadCount,
1079 lastActiveAtMs: candidate.lastActiveAtMs,
1080 });
1081 continue;
1083 if (!existing.sources.includes(candidate.source)) {
1084 existing.sources.push(candidate.source);
1086 existing.threadCount += candidate.threadCount;
1087 existing.lastActiveAtMs =
1088 existing.lastActiveAtMs === null || candidate.lastActiveAtMs === null
1089 ? (existing.lastActiveAtMs ?? candidate.lastActiveAtMs)
1090 : Math.max(existing.lastActiveAtMs, candidate.lastActiveAtMs);
1092​
1093 // Resolve persisted roots too. A project and a transcript can name
1094 // different symlinks to the same directory.
1095 const shellSnapshot = yield* projectionSnapshotQuery
1096 .getShellSnapshot()
1097 .pipe(
1098 Effect.mapError(
1099 (cause) => new AgentSessionScanError({ operation: "read-projects", cause }),
1100 ),
1101 );
1102 const importedProjectsByRoot = new Map<string, (typeof shellSnapshot.projects)[number]>();
1103 for (const project of shellSnapshot.projects) {
1104 const projectRoot = path.resolve(expandHomePath(project.workspaceRoot));
1105 importedProjectsByRoot.set(normalizeProjectPathForComparison(projectRoot), project);
1106 importedProjectsByRoot.set(yield* directoryIdentity(projectRoot), project);
1108​
1109 const candidates: Array<AgentSessionProjectCandidate> = [];
1110 for (const [key, entry] of merged.entries()) {
1111 // Keep the path key for missing roots and use filesystem identity for
1112 // aliases that resolve to the same directory.
1113 const importedProject =
1114 importedProjectsByRoot.get(normalizeProjectPathForComparison(entry.path)) ??
1115 importedProjectsByRoot.get(key);
1116 const candidatePath = importedProject?.workspaceRoot ?? entry.path;
1117 candidates.push({
1118 path: candidatePath,
1119 title: path.basename(candidatePath) || candidatePath,
1120 ...(importedProject === undefined ? {} : { projectId: importedProject.id }),
1121 sources: entry.sources,
1122 threadCount: entry.threadCount,
1123 lastActiveAt:
1124 entry.lastActiveAtMs === null
1125 ? null
1126 : DateTime.formatIso(DateTime.makeUnsafe(entry.lastActiveAtMs)),
1127 alreadyImported: importedProject !== undefined,
1128 });
1130​
1131 // Newest first, undated candidates last.
1132 candidates.sort((left, right) => {
1133 if (left.lastActiveAt === right.lastActiveAt) return left.path.localeCompare(right.path);
1134 if (left.lastActiveAt === null) return 1;
1135 if (right.lastActiveAt === null) return -1;
1136 return right.lastActiveAt.localeCompare(left.lastActiveAt);
1137 });
1138​
1139 return {
1140 candidates,
1141 scannedAt: DateTime.formatIso(yield* DateTime.now),
1142 ...(truncated ? { truncated: true } : {}),
1143 };
1144 });
1145​
1146 const prepareRecentThreads = Effect.fn("AgentSessionScanner.prepareRecentThreads")(function* (
1147 workspaceRoot: string,
1148 completedSources: ReadonlyArray<AgentSessionImportSource>,
1149 ) {
1150 const root = path.resolve(expandHomePath(workspaceRoot));
1151 const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root));
1152 if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot)) return Stream.empty;
1153 const rootIdentity = yield* directoryIdentity(root);
1154 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
1155 const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS;
1156​
1157 const candidates = cachedCandidates ?? (yield* collectCandidates()).candidates;
1158 cachedCandidates = candidates;
1159​
1160 const eligibleTranscripts: Array<{
1161 readonly candidate: RawCandidate;
1162 readonly transcript: RawCandidate["transcripts"][number] & { readonly mtimeMs: number };
1163 }> = [];
1164 for (const candidate of candidates) {
1165 const expanded = expandHomePath(candidate.cwd.trim());
1166 if (!path.isAbsolute(expanded)) continue;
1167 const resolved = path.resolve(expanded);
1168 if ((yield* directoryIdentity(resolved)) !== rootIdentity) continue;
1169​
1170 for (const transcript of candidate.transcripts) {
1171 if (
1172 transcript.mtimeMs === null ||
1173 transcript.mtimeMs < cutoffMs ||
1174 transcript.mtimeMs > nowMs
1175 ) {
1176 continue;
1178 eligibleTranscripts.push({
1179 candidate,
1180 transcript: { ...transcript, mtimeMs: transcript.mtimeMs },
1181 });
1184​
1185 eligibleTranscripts.sort((left, right) => {
1186 if (left.transcript.mtimeMs !== right.transcript.mtimeMs) {
1187 return right.transcript.mtimeMs - left.transcript.mtimeMs;
1189 return left.transcript.filePath.localeCompare(right.transcript.filePath);
1190 });
1191​
1192 const completedByFile = Map.groupBy(
1193 completedSources,
1194 (source) => `${source.providerInstanceId}\0${source.filePath}`,
1195 );
1196 const importedSessions = new Set<string>();
1197 let bytesRemaining = MAX_IMPORT_BYTES;
1198 let transcriptsRemaining = MAX_IMPORT_TRANSCRIPTS;
1199 let recordsRemaining = MAX_IMPORT_RECORDS;
1200 return Stream.fromIteratorSucceed(eligibleTranscripts.values(), 1).pipe(
1201 Stream.mapEffect(({ candidate, transcript }) =>
1202 Effect.gen(function* () {
1203 const completed = completedByFile.get(
1204 `${candidate.providerInstanceId}\0${transcript.filePath}`,
1205 );
1206 if (
1207 completed === undefined &&
1208 (transcriptsRemaining === 0 || bytesRemaining === 0 || recordsRemaining === 0)
1209 ) {
1210 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1212 const stats = yield* statOption(transcript.filePath);
1213 if (Option.isNone(stats) || stats.value.type !== "File") {
1214 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1216 const identity = transcriptIdentity(transcript.filePath, stats.value);
1217 const completedSource = completed?.find(
1218 (source) =>
1219 source.provider === candidate.source && sameTranscriptIdentity(source, identity),
1220 );
1221 if (completedSource !== undefined) {
1222 const sessionKey = `${completedSource.providerInstanceId}\0${completedSource.providerSessionId}`;
1223 if (importedSessions.has(sessionKey)) return Option.none<AgentSessionRecentThread>();
1224 importedSessions.add(sessionKey);
1225 return Option.some<AgentSessionRecentThread>({
1226 _tag: "AlreadyImported",
1227 source: completedSource,
1228 });
1230 if (
1231 transcriptsRemaining === 0 ||
1232 recordsRemaining === 0 ||
1233 identity.size > MAX_IMPORTED_TRANSCRIPT_BYTES ||
1234 identity.size > bytesRemaining
1235 ) {
1236 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1238 // Reserve the whole file even if its read or parse fails.
1239 transcriptsRemaining -= 1;
1240 bytesRemaining -= identity.size;
1241 const contents = yield* readTranscript(transcript.filePath, identity);
1242 if (contents === null) {
1243 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1245 const lines = splitTranscriptRecords(contents, recordsRemaining + 1);
1246 if (lines.length > recordsRemaining) {
1247 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1249 recordsRemaining -= lines.length;
1250​
1251 // A stable replacement file can belong to a different project than the cached candidate.
1252 let snapshotCwd: string | null = null;
1253 for (const line of lines) {
1254 snapshotCwd = extractCwd(line);
1255 if (snapshotCwd !== null) break;
1257 if (snapshotCwd === null) {
1258 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1260 const expandedCwd = expandHomePath(snapshotCwd.trim());
1261 if (
1262 !path.isAbsolute(expandedCwd) ||
1263 (yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity
1264 ) {
1265 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1267​
1268 const parsedThread = parseAgentSessionTranscript(
1270 contents,
1271 source: candidate.source,
1272 providerInstanceId: candidate.providerInstanceId,
1273 fallbackSessionId: path.basename(transcript.filePath, ".jsonl"),
1274 lastActiveAtMs: transcript.mtimeMs,
1275 },
1276 lines,
1277 );
1278 if (parsedThread === null) {
1279 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1281​
1282 const source: AgentSessionImportSource = {
1283 ...identity,
1284 provider: parsedThread.source,
1285 providerInstanceId: parsedThread.providerInstanceId,
1286 providerSessionId: parsedThread.providerSessionId,
1287 };
1288 const sessionKey = `${parsedThread.providerInstanceId}\0${parsedThread.providerSessionId}`;
1289 if (importedSessions.has(sessionKey)) {
1290 return Option.some<AgentSessionRecentThread>({ _tag: "Duplicate", source });
1292 importedSessions.add(sessionKey);
1293 return Option.some<AgentSessionRecentThread>({
1294 _tag: "Importable",
1295 thread: parsedThread,
1296 source,
1297 });
1298 }),
1299 ),
1300 Stream.map(Option.toArray),
1301 Stream.flattenIterable,
1302 );
1303 });
1304​
1305 const recentThreads: AgentSessionScanner["Service"]["recentThreads"] = (
1306 workspaceRoot,
1307 completedSources = [],
1308 ) => Stream.unwrap(prepareRecentThreads(workspaceRoot, completedSources));
1309​
1310 return AgentSessionScanner.of({ scan, recentThreads });
1311});
1312​
1313export const layer = Layer.effect(AgentSessionScanner, make);