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

AgentSessionScanner.ts

1,427 lines52.7 KB

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