@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 2,331 lines 91.6 KB
Raw
1 import * as NodeOS from "node:os";
2 import * as NodeSqlite from "node:sqlite";
3 import * as NodeZlib from "node:zlib";
4
5 import {
6 AgentSessionImportSource,
7 AgentSessionScanError,
8 ClaudeSettings,
9 CodexSettings,
10 ProviderDriverKind,
11 ProviderInstanceId,
12 resolveProviderInstanceEnabled,
13 type AgentSessionProjectCandidate,
14 type AgentSessionProjectGit,
15 type AgentSessionScanResult,
16 type ProviderInstanceConfig,
17 } from "@t3tools/contracts";
18 import * as Clock from "effect/Clock";
19 import * as Context from "effect/Context";
20 import * as DateTime from "effect/DateTime";
21 import * as NodeStream from "@effect/platform-node/NodeStream";
22 import * as Effect from "effect/Effect";
23 import * as FileSystem from "effect/FileSystem";
24 import * as Layer from "effect/Layer";
25 import * as Option from "effect/Option";
26 import * as Path from "effect/Path";
27 import * as Pull from "effect/Pull";
28 import * as Schema from "effect/Schema";
29 import * as Semaphore from "effect/Semaphore";
30 import * as Stream from "effect/Stream";
31
32 import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations";
33 import { isBareGitConfig, parseOriginUrlFromGitConfig } from "@t3tools/shared/git";
34 import * as HostProcess from "@t3tools/shared/HostProcess";
35 import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
36 import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";
37
38 import * as ServerConfig from "../config.ts";
39 import * as ProcessRunner from "../processRunner.ts";
40 import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
41 import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
42 import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
43 import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
44 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
45 import { piHome, resolvePiSessionsDir } from "@t3tools/provider-pi/server/usage";
46 import * as ServerSettings from "../serverSettings.ts";
47 import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
48 import {
49 createTranscriptJsonReader,
50 createTranscriptJsonSelector,
51 TranscriptJsonLimitError,
52 } from "./AgentSessionJson.ts";
53
54 const TRANSCRIPT_PREFIX_BYTES = 32 * 1024;
55
56 class TranscriptParseError extends Schema.TaggedError<TranscriptParseError>()(
57 "TranscriptParseError",
58 { filePath: Schema.String, cause: Schema.Defect() },
59 ) {
60 override get message(): string {
61 return `Could not parse the transcript at ${this.filePath}.`;
62 }
63 }
64
65 class CodexStateReadError extends Schema.TaggedError<CodexStateReadError>()("CodexStateReadError", {
66 databasePath: Schema.String,
67 cause: Schema.Defect(),
68 }) {
69 override get message(): string {
70 return `Could not read Codex projects from ${this.databasePath}.`;
71 }
72 }
73 const METADATA_READ_BYTES = 8 * 1024;
74 const MAX_TRANSCRIPT_SCAN_BYTES = 1024 * 1024;
75 const MAX_CODEX_SESSION_INDEX_BYTES = 1024 * 1024;
76 const MAX_CODEX_PROJECT_ROOT_ROWS = 100_000;
77
78 const MAX_TRANSCRIPTS_PER_SOURCE = 5000;
79
80 const MAX_DISCOVERY_OPERATIONS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 4;
81 const MAX_METADATA_BYTES_PER_SOURCE = 64 * 1024 * 1024;
82 const MAX_METADATA_OPERATIONS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 4;
83 const MAX_METADATA_RECORDS_PER_SOURCE = 100_000;
84 const MAX_METADATA_RECORDS_PER_TRANSCRIPT = 1_000;
85 const RECENT_THREAD_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
86 // Screenshot-heavy transcripts can reach GiB; select fields while streaming to avoid allocating payloads.
87 const MAX_IMPORTED_TRANSCRIPT_BYTES = 4 * 1024 * 1024 * 1024;
88 const MAX_IMPORTED_MESSAGES = 200;
89 const MAX_IMPORT_HISTORY_BYTES = 32 * 1024 * 1024;
90 const MAX_IMPORT_BYTES = 4 * 1024 * 1024 * 1024;
91 const MAX_IMPORT_TRANSCRIPTS = 100;
92 const MAX_IMPORT_RECORDS = 100_000;
93
94 /**
95 * open() of a file under macOS privacy protection waits on a consent prompt
96 * that a headless server never gets, and a FIFO waits for a writer. Either
97 * pins a libuv pool thread that interruption cannot free, so git files of
98 * arbitrary transcript cwds are read by a `cat` child we can kill instead.
99 */
100 const GIT_FILE_READ_DEADLINE = "2 seconds";
101 const MAX_GIT_FILE_BYTES = 1024 * 1024;
102 // Reads run concurrently, so each phase waits one deadline per batch of this
103 // many blocked files rather than one per blocked file.
104 const GIT_FILE_READ_CONCURRENCY = 16;
105 // A blocked path is skipped for a while, then read again in case it was fixed.
106 const BLOCKED_GIT_FILE_RETRY_MS = 5 * 60 * 1000;
107 const MAX_BLOCKED_GIT_FILE_PATHS = 1024;
108
109 const TranscriptContentBlock = Schema.Struct({
110 type: Schema.optional(Schema.String),
111 text: Schema.optional(Schema.String),
112 });
113
114 const TranscriptMessage = Schema.Struct({
115 role: Schema.optional(Schema.String),
116 content: Schema.optional(Schema.Union([Schema.String, Schema.Array(TranscriptContentBlock)])),
117 model: Schema.optional(Schema.String),
118 });
119
120 const CodexTurnMetadata = Schema.Struct({
121 turn_id: Schema.optional(Schema.Union([Schema.String, Schema.Null])),
122 });
123
124 const TranscriptRecord = Schema.Struct({
125 type: Schema.optional(Schema.String),
126 // Pi entries form a tree through id/parentId; session_info entries carry its name.
127 id: Schema.optional(Schema.String),
128 parentId: Schema.optional(Schema.NullOr(Schema.String)),
129 name: Schema.optional(Schema.String),
130 timestamp: Schema.optional(Schema.String),
131 cwd: Schema.optional(Schema.String),
132 sessionId: Schema.optional(Schema.String),
133 aiTitle: Schema.optional(Schema.String),
134 customTitle: Schema.optional(Schema.String),
135 isSidechain: Schema.optional(Schema.Boolean),
136 isMeta: Schema.optional(Schema.Boolean),
137 isCompactSummary: Schema.optional(Schema.Boolean),
138 message: Schema.optional(TranscriptMessage),
139 payload: Schema.optional(
140 Schema.Struct({
141 id: Schema.optional(Schema.String),
142 session_id: Schema.optional(Schema.String),
143 type: Schema.optional(Schema.String),
144 role: Schema.optional(Schema.String),
145 message: Schema.optional(Schema.String),
146 model: Schema.optional(Schema.String),
147 cwd: Schema.optional(Schema.String),
148 history_base: Schema.optional(Schema.Unknown),
149 content: Schema.optional(Schema.Array(TranscriptContentBlock)),
150 internal_chat_message_metadata_passthrough: Schema.optional(Schema.Unknown),
151 }),
152 ),
153 });
154
155 const CodexSessionIndexEntry = Schema.Struct({
156 id: Schema.String,
157 thread_name: Schema.String,
158 });
159
160 const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
161 const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings);
162 const decodeTranscriptRecord = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptRecord));
163 const decodeTranscriptValue = Schema.decodeUnknownOption(TranscriptRecord);
164 const decodePiEntryLinks = Schema.decodeUnknownOption(
165 Schema.Struct({
166 type: TranscriptRecord.fields.type,
167 id: TranscriptRecord.fields.id,
168 parentId: TranscriptRecord.fields.parentId,
169 }),
170 );
171 const selectTranscriptPath = createTranscriptJsonSelector(TranscriptRecord);
172 const decodeCodexTurnMetadata = Schema.decodeUnknownOption(CodexTurnMetadata);
173 export const decodeImportedTranscriptPayload = Schema.decodeUnknownOption(
174 Schema.Struct({
175 cwd: Schema.optional(Schema.String),
176 importedTranscripts: Schema.optional(Schema.Array(AgentSessionImportSource)),
177 }),
178 );
179 const decodeCodexHistoryBase = Schema.decodeUnknownOption(
180 Schema.Struct({ thread_id: Schema.String, end_byte_offset: Schema.Number }),
181 );
182 // Original rollouts end in their thread ID, rewound ones in `<thread ID>_<rollout ID>`.
183 const CODEX_ROLLOUT_ID_PATTERN =
184 /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))?\.jsonl(?:\.zst)?$/i;
185 // Codex zstd-compresses older rollouts; their byte limits and offsets count decompressed bytes.
186 const COMPRESSED_TRANSCRIPT_SUFFIX = ".jsonl.zst";
187 const isCompressedTranscript = (filePath: string) =>
188 filePath.endsWith(COMPRESSED_TRANSCRIPT_SUFFIX);
189 // Codex records a chat's project only here; moving a chat leaves its rollout cwd unchanged.
190 const CODEX_STATE_DATABASE = "state_5.sqlite";
191 const decodeCodexSessionIndexEntry = Schema.decodeUnknownOption(
192 Schema.fromJsonString(CodexSessionIndexEntry),
193 );
194
195 type DecodedTranscriptRecord = typeof TranscriptRecord.Type;
196
197 interface AgentSessionTranscriptMetadata {
198 readonly source: AgentSessionSource;
199 readonly providerInstanceId: ProviderInstanceId;
200 readonly fallbackSessionId: string;
201 readonly lastActiveAtMs: number;
202 }
203
204 export interface AgentSessionThreadMessage {
205 readonly role: "user" | "assistant";
206 readonly text: string;
207 readonly createdAt: string;
208 }
209
210 export interface AgentSessionThread {
211 readonly source: AgentSessionSource;
212 readonly providerInstanceId: ProviderInstanceId;
213 readonly providerSessionId: string;
214 readonly title: string;
215 readonly model: string | null;
216 readonly createdAt: string;
217 readonly updatedAt: string;
218 readonly messages: ReadonlyArray<AgentSessionThreadMessage>;
219 readonly omittedMessageCount: number;
220 }
221
222 export type AgentSessionRecentThread =
223 | {
224 readonly _tag: "Importable";
225 readonly thread: AgentSessionThread;
226 readonly source: AgentSessionImportSource;
227 /** The root's linked worktree the session ran in, or null when it ran in the root. */
228 readonly worktree: { readonly path: string; readonly branch: string | null } | null;
229 }
230 | { readonly _tag: "AlreadyImported"; readonly source: AgentSessionImportSource }
231 | { readonly _tag: "Duplicate"; readonly source: AgentSessionImportSource }
232 | { readonly _tag: "Skipped" };
233
234 export class AgentSessionScanner extends Context.Service<
235 AgentSessionScanner,
236 {
237 readonly scan: Effect.Effect<AgentSessionScanResult, AgentSessionScanError>;
238 readonly recentThreads: (
239 workspaceRoot: string,
240 completedSources?: ReadonlyArray<AgentSessionImportSource>,
241 ) => Stream.Stream<AgentSessionRecentThread, AgentSessionScanError>;
242 }
243 >()("t3/project/AgentSessionScanner") {}
244
245 type AgentSessionSource = AgentSessionProjectCandidate["sources"][number];
246
247 interface RawCandidate {
248 readonly cwd: string;
249 readonly source: AgentSessionSource;
250 readonly providerInstanceId: ProviderInstanceId;
251 readonly homePath: string;
252 readonly threadCount: number;
253 readonly lastActiveAtMs: number | null;
254 readonly transcripts: ReadonlyArray<{
255 readonly filePath: string;
256 readonly mtimeMs: number | null;
257 readonly projectRoots?: ReadonlyArray<string> | undefined;
258 }>;
259 }
260
261 interface TranscriptCandidate {
262 readonly filePath: string;
263 readonly mtimeMs: number;
264 readonly providerInstanceId: ProviderInstanceId;
265 readonly homePath: string;
266 readonly identity: TranscriptIdentity;
267 readonly projectRoots?: ReadonlyArray<string> | undefined;
268 }
269
270 interface MetadataReadBudget {
271 bytesRemaining: number;
272 operationsRemaining: number;
273 recordsRemaining: number;
274 truncated: boolean;
275 }
276
277 function splitOperationBudget(budget: number, count: number): Array<number> {
278 return Array.from(
279 { length: count },
280 (_, index) => Math.floor(budget / count) + (index < budget % count ? 1 : 0),
281 );
282 }
283
284 function selectMetadataTranscripts(transcripts: ReadonlyArray<TranscriptCandidate>) {
285 const selected: Array<TranscriptCandidate> = [];
286 let pending = Array.from(
287 Map.groupBy(transcripts, (transcript) => transcript.providerInstanceId).values(),
288 (entries) => entries.values(),
289 );
290 while (pending.length > 0 && selected.length < MAX_TRANSCRIPTS_PER_SOURCE) {
291 const nextRound: typeof pending = [];
292 for (const iterator of pending) {
293 if (selected.length === MAX_TRANSCRIPTS_PER_SOURCE) break;
294 const next = iterator.next();
295 if (next.done) continue;
296 selected.push(next.value);
297 nextRound.push(iterator);
298 }
299 pending = nextRound;
300 }
301 return selected;
302 }
303
304 function splitTranscriptRecords(contents: string, limit: number): string[] {
305 const records = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
306 return records.split("\n", limit);
307 }
308
309 function isTextContentBlock(block: typeof TranscriptContentBlock.Type): boolean {
310 return block.type === "text" || block.type === "input_text" || block.type === "output_text";
311 }
312
313 function extractText(
314 content: string | ReadonlyArray<typeof TranscriptContentBlock.Type> | undefined,
315 ): string {
316 if (typeof content === "string") return content.trim();
317 if (content === undefined) return "";
318 return content
319 .filter(isTextContentBlock)
320 .map((block) => block.text?.trim() ?? "")
321 .filter((text) => text.length > 0)
322 .join("\n");
323 }
324
325 function normalizeTimestamp(value: string | undefined, fallback: string): string {
326 if (value === undefined) return fallback;
327 const parsed = DateTime.make(value);
328 return Option.isSome(parsed) ? DateTime.formatIso(parsed.value) : fallback;
329 }
330
331 function codexTurnId(metadata: unknown): string | null {
332 const decoded = decodeCodexTurnMetadata(metadata);
333 if (
334 Option.isNone(decoded) ||
335 typeof decoded.value.turn_id !== "string" ||
336 decoded.value.turn_id.trim().length === 0
337 ) {
338 return null;
339 }
340 return decoded.value.turn_id;
341 }
342
343 function isHiddenClaudeRecord(record: DecodedTranscriptRecord): boolean {
344 return record.isSidechain === true || record.isMeta === true || record.isCompactSummary === true;
345 }
346
347 // Claude repeats session fields on records that need not be retained.
348 interface ClaudeFields {
349 readonly sessionId: string | undefined;
350 readonly title: string | undefined;
351 readonly customTitle: string | null;
352 readonly model: string | undefined;
353 }
354
355 const emptyClaudeFields: ClaudeFields = {
356 sessionId: undefined,
357 title: undefined,
358 customTitle: null,
359 model: undefined,
360 };
361
362 // Claude Code's model name for its own local errors, such as "Invalid API key".
363 const CLAUDE_SYNTHETIC_MODEL = "<synthetic>";
364
365 function foldClaudeFields(fields: ClaudeFields, record: DecodedTranscriptRecord): ClaudeFields {
366 if (isHiddenClaudeRecord(record)) return fields;
367 const model = record.message?.model?.trim();
368 return {
369 sessionId: record.sessionId?.trim() || fields.sessionId,
370 title: claudeTitle(record.aiTitle) ?? fields.title,
371 // Claude flushes the AI title after the user's rename; an empty rename clears it.
372 customTitle:
373 record.customTitle === undefined
374 ? fields.customTitle
375 : (claudeTitle(record.customTitle) ?? null),
376 // Not a model ID that can be selected when the imported session resumes.
377 model: model && model !== CLAUDE_SYNTHETIC_MODEL ? model : fields.model,
378 };
379 }
380
381 // Codex records setup context as user text ahead of the real request. Skip
382 // these leading blocks when deriving a title; imported messages keep them.
383 const CODEX_TITLE_PREAMBLE =
384 /^(?:\s*(?:<(recommended_plugins|environment_context|user_instructions|INSTRUCTIONS|in-app-browser-context|external_codex_apps_open_page)(?:\s[^>]*)?>[\s\S]*?<\/\1>|# AGENTS\.md instructions\b[^\n]*|## My request for Codex:))+/;
385
386 // Codex appends an entry per rename; like Codex, the newest nonempty name wins.
387 function parseCodexThreadNames(contents: string): ReadonlyMap<string, string> {
388 const names = new Map<string, string>();
389 for (const line of contents.split("\n")) {
390 const entry = Option.getOrUndefined(decodeCodexSessionIndexEntry(line));
391 const name = entry?.thread_name.trim();
392 if (entry !== undefined && name) names.set(entry.id, name);
393 }
394 return names;
395 }
396
397 // A rewound paginated Codex thread continues in a new rollout that inherits a
398 // byte prefix of the rollout it replaced.
399 function codexHistoryBase(records: ReadonlyArray<DecodedTranscriptRecord>) {
400 const base = Option.getOrUndefined(
401 decodeCodexHistoryBase(
402 records.find((record) => record.type === "session_meta")?.payload?.history_base,
403 ),
404 );
405 return base !== undefined &&
406 Number.isSafeInteger(base.end_byte_offset) &&
407 base.end_byte_offset >= 0
408 ? base
409 : undefined;
410 }
411
412 // Claude Code records its own UI as user turns: slash commands, `!` shell runs and
413 // their output, task notifications. Keep what the user typed, as they typed it.
414 const CLAUDE_UI_OUTPUT =
415 /^(?:<(?:task-notification|local-command-stdout|local-command-stderr|local-command-caveat|bash-stdout|bash-stderr)>|\[Request interrupted by user(?: for tool use)?\]$)/;
416
417 /**
418 * A slash command as typed. Its arguments may name the thread; a bare command
419 * leaves that to a later prompt. Null for any other text.
420 */
421 function claudeCommand(text: string): { readonly text: string; readonly titleText: string } | null {
422 if (!/^<command-(?:name|message)>/.test(text)) return null;
423 const name =
424 /<command-name>([^<]*)<\/command-name>/.exec(text)?.[1]?.trim() ||
425 `/${/<command-message>([^<]*)<\/command-message>/.exec(text)?.[1]?.trim() ?? ""}`;
426 const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(text)?.[1]?.trim() ?? "";
427 return { text: args.length === 0 ? name : `${name} ${args}`, titleText: args };
428 }
429
430 /** What a Claude user turn shows the user typed, and the part of it that may name the thread. */
431 function claudeUserText(text: string): { readonly text: string; readonly titleText: string } {
432 if (CLAUDE_UI_OUTPUT.test(text)) return { text: "", titleText: "" };
433 const shellInput = /^<bash-input>([\s\S]*)<\/bash-input>$/.exec(text)?.[1];
434 if (shellInput !== undefined) return { text: `!${shellInput}`, titleText: "" };
435 return claudeCommand(text) ?? { text, titleText: text };
436 }
437
438 function claudeVisibleText(record: DecodedTranscriptRecord) {
439 const text = extractText(record.message?.content);
440 return record.type === "user" ? claudeUserText(text) : { text, titleText: text };
441 }
442
443 /** Saved titles can be the raw markup of a user turn, such as the command that opened the session. */
444 function claudeTitle(title: string | undefined): string | undefined {
445 const trimmed = title?.trim();
446 if (!trimmed) return undefined;
447 return claudeUserText(trimmed).text === trimmed ? trimmed : undefined;
448 }
449
450 // Agent-started sessions wrap the prompt in a `<wake reason=… current-time=…>`
451 // envelope; title them after the prompt inside it.
452 const WAKE_ENVELOPE = /^\s*<wake(?:\s[^>]*)?>([\s\S]*?)(?:<\/wake>|$)/;
453
454 function deriveTitle(source: AgentSessionSource, text: string): string | undefined {
455 const request = (source === "codex" ? text.replace(CODEX_TITLE_PREAMBLE, "") : text).replace(
456 WAKE_ENVELOPE,
457 "$1",
458 );
459 const line = request.trim().split("\n")[0] ?? "";
460 return line.slice(0, splitsSurrogatePair(line, 100) ? 99 : 100).trim() || undefined;
461 }
462
463 // Pi keeps abandoned branches in the file; its active branch runs from the last entry to the root.
464 function activePiBranch(
465 records: ReadonlyArray<DecodedTranscriptRecord>,
466 ): ReadonlyArray<DecodedTranscriptRecord> {
467 const entries = records.filter((record) => record.type !== "session");
468 const leaf = entries.at(-1);
469 // Version 1 sessions predate the tree and are linear.
470 if (leaf?.id === undefined) return entries;
471 const byId = new Map(
472 entries.flatMap((entry) => (entry.id === undefined ? [] : [[entry.id, entry] as const])),
473 );
474 const branch: Array<DecodedTranscriptRecord> = [];
475 for (
476 let entry: DecodedTranscriptRecord | undefined = leaf;
477 entry !== undefined && branch.length < entries.length;
478 entry = entry.parentId ? byId.get(entry.parentId) : undefined
479 ) {
480 branch.push(entry);
481 }
482 return branch.toReversed();
483 }
484
485 function isPiConversationRecord(
486 record: DecodedTranscriptRecord,
487 ): record is DecodedTranscriptRecord & {
488 readonly message: typeof TranscriptMessage.Type & { readonly role: "user" | "assistant" };
489 } {
490 return (
491 record.type === "message" &&
492 (record.message?.role === "user" || record.message?.role === "assistant")
493 );
494 }
495
496 export function parseAgentSessionTranscript(
497 input: AgentSessionTranscriptMetadata & {
498 readonly contents: string;
499 },
500 lines = splitTranscriptRecords(input.contents, MAX_IMPORT_RECORDS + 1),
501 ): AgentSessionThread | null {
502 if (lines.length > MAX_IMPORT_RECORDS) return null;
503 const records = lines.flatMap((line) => Option.toArray(decodeTranscriptRecord(line)));
504 const claudeFields =
505 input.source === "claudeAgent"
506 ? records.reduce(foldClaudeFields, emptyClaudeFields)
507 : emptyClaudeFields;
508 const thread = parseAgentSessionRecords(input, records, claudeFields, 0);
509 return thread === "empty" ? null : thread;
510 }
511
512 function parseAgentSessionRecords(
513 input: AgentSessionTranscriptMetadata,
514 records: ReadonlyArray<DecodedTranscriptRecord>,
515 claudeFields: ClaudeFields,
516 droppedMessageCount: number,
517 ): AgentSessionThread | "empty" | null {
518 const fallbackTimestamp = DateTime.formatIso(DateTime.makeUnsafe(input.lastActiveAtMs));
519 // Claude filenames are session IDs. Codex rollout filenames include extra
520 // timestamp text, so only transcript metadata can provide a resumable ID.
521 let providerSessionId =
522 input.source === "codex"
523 ? ""
524 : input.source === "pi"
525 ? records.find((record) => record.type === "session")?.id?.trim() || input.fallbackSessionId
526 : (claudeFields.sessionId ?? input.fallbackSessionId);
527 // Pi titles a session by its latest session_info on any branch; an empty name clears it.
528 const title =
529 input.source === "pi"
530 ? records.findLast((record) => record.type === "session_info")?.name?.trim() || null
531 : (claudeFields.title ?? null);
532 let model = claudeFields.model ?? null;
533 let derivedTitle: string | undefined;
534 // Names a session whose only request was a bare command, such as `/review`.
535 let bareCommandTitle: string | undefined;
536 let hasAssistantMessage = false;
537 let hasClaudeSyntheticReply = false;
538 let hasClaudeModelReply = false;
539 let hasCodexSessionId = false;
540 const messages: Array<AgentSessionThreadMessage & { readonly codexResponseUser: boolean }> = [];
541 let firstUserMessage:
542 | (AgentSessionThreadMessage & { readonly codexResponseUser: boolean })
543 | undefined;
544 const canonicalCodexResponseUserIndices = new Set<number>();
545 let canonicalUserTextsInTurn = new Set<string>();
546 let responseUsersInTurn: Array<{
547 readonly index: number;
548 readonly turnId: string;
549 readonly text: string;
550 }> = [];
551 const finishCodexTurn = () => {
552 const canonicalTurnIds = new Set(
553 responseUsersInTurn.flatMap((responseUser) =>
554 canonicalUserTextsInTurn.has(responseUser.text) ? [responseUser.turnId] : [],
555 ),
556 );
557 for (const responseUser of responseUsersInTurn) {
558 if (canonicalTurnIds.has(responseUser.turnId)) {
559 canonicalCodexResponseUserIndices.add(responseUser.index);
560 }
561 }
562 canonicalUserTextsInTurn = new Set();
563 responseUsersInTurn = [];
564 };
565 if (input.source === "codex") {
566 let recordIndex = -1;
567 for (const record of records) {
568 recordIndex += 1;
569 if (
570 record.type === "response_item" &&
571 record.payload?.type === "message" &&
572 record.payload.role === "assistant"
573 ) {
574 finishCodexTurn();
575 continue;
576 }
577 if (record.type === "event_msg" && record.payload?.type === "user_message") {
578 const text = record.payload.message?.trim() ?? "";
579 if (text.length > 0) canonicalUserTextsInTurn.add(text);
580 continue;
581 }
582 if (
583 record.type === "response_item" &&
584 record.payload?.type === "message" &&
585 record.payload.role === "user"
586 ) {
587 const turnId = codexTurnId(record.payload.internal_chat_message_metadata_passthrough);
588 const text = extractText(record.payload.content);
589 if (turnId !== null && text.length > 0) {
590 responseUsersInTurn.push({ index: recordIndex, turnId, text });
591 }
592 }
593 }
594 finishCodexTurn();
595 }
596
597 let conversationMessageCount = 0;
598 const retainMessage = (
599 message: AgentSessionThreadMessage & { readonly codexResponseUser: boolean },
600 titleText = message.text,
601 ) => {
602 if (firstUserMessage === undefined && message.role === "user") {
603 firstUserMessage = message;
604 }
605 if (derivedTitle === undefined && message.role === "user") {
606 derivedTitle = deriveTitle(input.source, titleText);
607 bareCommandTitle ??= deriveTitle(input.source, message.text);
608 }
609 hasAssistantMessage ||= message.role === "assistant";
610 conversationMessageCount += 1;
611 messages.push(message);
612 if (messages.length > MAX_IMPORTED_MESSAGES) messages.shift();
613 };
614
615 const hasMatchingCodexEventInTurn = (text: string) => {
616 const comparisonText = text.trim();
617 for (let index = messages.length - 1; index >= 0; index--) {
618 const message = messages[index];
619 if (message?.role === "assistant") return false;
620 if (
621 message?.role === "user" &&
622 !message.codexResponseUser &&
623 message.text.trim() === comparisonText
624 ) {
625 return true;
626 }
627 }
628 return false;
629 };
630
631 let recordIndex = -1;
632 for (const record of input.source === "pi" ? activePiBranch(records) : records) {
633 recordIndex += 1;
634 if (input.source === "pi") {
635 if (!isPiConversationRecord(record)) continue;
636 const text = extractText(record.message.content);
637 if (text.length === 0) continue;
638 retainMessage({
639 role: record.message.role,
640 text,
641 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
642 codexResponseUser: false,
643 });
644 continue;
645 }
646 if (input.source === "claudeAgent") {
647 if (isHiddenClaudeRecord(record)) continue;
648 if (record.type !== "user" && record.type !== "assistant") continue;
649 const { text, titleText } = claudeVisibleText(record);
650 if (text.length === 0) continue;
651 if (record.type === "assistant") {
652 if (record.message?.model?.trim() === CLAUDE_SYNTHETIC_MODEL)
653 hasClaudeSyntheticReply = true;
654 else hasClaudeModelReply = true;
655 }
656 retainMessage(
657 {
658 role: record.type,
659 text,
660 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
661 codexResponseUser: false,
662 },
663 titleText,
664 );
665 continue;
666 }
667
668 if (record.type === "session_meta") {
669 const sessionId = record.payload?.id?.trim() || record.payload?.session_id?.trim();
670 if (!hasCodexSessionId && sessionId) {
671 providerSessionId = sessionId;
672 hasCodexSessionId = true;
673 }
674 continue;
675 }
676 if (record.type === "turn_context" && record.payload?.model?.trim()) {
677 model = record.payload.model.trim();
678 continue;
679 }
680 if (record.type === "event_msg" && record.payload?.type === "user_message") {
681 const text = record.payload.message ?? "";
682 if (text.trim().length === 0) continue;
683 // Codex can duplicate prompts across formats; remove only matching response copies.
684 for (let index = messages.length - 1; index >= 0; index--) {
685 const message = messages[index];
686 if (message?.role === "assistant") break;
687 if (message?.codexResponseUser === true && message.text.trim() === text.trim()) {
688 if (firstUserMessage === message) firstUserMessage = undefined;
689 messages.splice(index, 1);
690 conversationMessageCount -= 1;
691 break;
692 }
693 }
694 retainMessage({
695 role: "user",
696 text,
697 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
698 codexResponseUser: false,
699 });
700 continue;
701 }
702 if (
703 record.type !== "response_item" ||
704 record.payload?.type !== "message" ||
705 (record.payload.role !== "user" && record.payload.role !== "assistant")
706 ) {
707 continue;
708 }
709
710 const extractedText = extractText(record.payload.content);
711 if (extractedText.length === 0) continue;
712 if (record.payload.role === "user" && canonicalCodexResponseUserIndices.has(recordIndex)) {
713 continue;
714 }
715 if (record.payload.role === "user" && hasMatchingCodexEventInTurn(extractedText)) {
716 continue;
717 }
718 retainMessage({
719 role: record.payload.role,
720 text: extractedText,
721 createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
722 codexResponseUser: record.payload.role === "user",
723 });
724 }
725
726 if (messages.length === 0 && droppedMessageCount === 0) return "empty";
727 const visibleMessages = messages.map(
728 ({ codexResponseUser: _codexResponseUser, ...message }) => message,
729 );
730 if (
731 providerSessionId.trim().length === 0 ||
732 firstUserMessage === undefined ||
733 // A Claude session of bare commands such as `/clear` that no reply followed did nothing.
734 (input.source === "claudeAgent" && derivedTitle === undefined && !hasAssistantMessage) ||
735 // Nor did one whose only replies are Claude Code's own errors.
736 (input.source === "claudeAgent" &&
737 droppedMessageCount === 0 &&
738 hasClaudeSyntheticReply &&
739 !hasClaudeModelReply)
740 ) {
741 return null;
742 }
743 const firstUserMessageRetained = messages.includes(firstUserMessage);
744 const { codexResponseUser: _codexResponseUser, ...visibleFirstUserMessage } = firstUserMessage;
745 const retainedMessages = firstUserMessageRetained
746 ? visibleMessages
747 : [visibleFirstUserMessage, ...visibleMessages.slice(-(MAX_IMPORTED_MESSAGES - 1))];
748
749 return {
750 source: input.source,
751 providerInstanceId: input.providerInstanceId,
752 providerSessionId,
753 title:
754 claudeFields.customTitle ?? title ?? derivedTitle ?? bareCommandTitle ?? "Imported thread",
755 model,
756 createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp,
757 updatedAt: fallbackTimestamp,
758 messages: retainedMessages,
759 omittedMessageCount: conversationMessageCount + droppedMessageCount - retainedMessages.length,
760 };
761 }
762
763 function extractDecodedCwd(record: DecodedTranscriptRecord): string | null {
764 const cwd = record.cwd?.trim() || record.payload?.cwd?.trim();
765 return cwd && cwd.length > 0 ? cwd : null;
766 }
767
768 function shouldRetainDecodedRecord(
769 source: AgentSessionSource,
770 record: DecodedTranscriptRecord,
771 ): boolean {
772 // Any Pi entry can be a link on the active branch.
773 if (source === "pi") return true;
774 if (source === "claudeAgent") {
775 if (isHiddenClaudeRecord(record) || (record.type !== "user" && record.type !== "assistant")) {
776 return false;
777 }
778 // Same rule as the parser, so Claude Code's own output never takes a history window slot.
779 return claudeVisibleText(record).text.length > 0;
780 }
781 if (extractDecodedCwd(record) !== null) return true;
782 return (
783 record.type === "session_meta" ||
784 record.type === "turn_context" ||
785 (record.type === "event_msg" && record.payload?.type === "user_message") ||
786 (record.type === "response_item" &&
787 record.payload?.type === "message" &&
788 (record.payload.role === "user" || record.payload.role === "assistant"))
789 );
790 }
791
792 // The import shows only the first user message and the latest messages, so a
793 // long Claude session holds just those and counts the rest as dropped.
794 function createClaudeHistoryWindow() {
795 const recent: Array<{ readonly record: DecodedTranscriptRecord; readonly bytes: number }> = [];
796 let firstUser: DecodedTranscriptRecord | undefined;
797 let droppedMessageCount = 0;
798 return {
799 // Takes a record shouldRetainDecodedRecord kept; returns the bytes it released.
800 push: (record: DecodedTranscriptRecord, bytes: number): number => {
801 if (firstUser === undefined && record.type === "user") firstUser = record;
802 recent.push({ record, bytes });
803 if (recent.length <= MAX_IMPORTED_MESSAGES) return 0;
804 const evicted = recent.shift();
805 if (evicted === undefined || evicted.record === firstUser) return 0;
806 droppedMessageCount += 1;
807 return evicted.bytes;
808 },
809 records: () => {
810 const held = recent.map((entry) => entry.record);
811 return firstUser === undefined || held.includes(firstUser) ? held : [firstUser, ...held];
812 },
813 droppedMessageCount: () => droppedMessageCount,
814 };
815 }
816
817 function normalizeForWorktreeMatch(value: string, caseFold: boolean): string {
818 const normalized = `${value.replaceAll("\\", "/")}/`;
819 return caseFold ? normalized.toLowerCase() : normalized;
820 }
821
822 function isT3ManagedWorktree(
823 candidatePath: string,
824 worktreesDir: string,
825 caseFold: boolean,
826 ): boolean {
827 const normalized = normalizeForWorktreeMatch(candidatePath, caseFold);
828 return (
829 normalized.startsWith(normalizeForWorktreeMatch(worktreesDir, caseFold)) ||
830 normalized.includes("/.t3/worktrees/")
831 );
832 }
833
834 // false stops metadata scanning for an excluded rollout, even if later records contain a cwd.
835 function extractCwd(line: string, source: AgentSessionSource): string | null | false {
836 let parsed: unknown;
837 try {
838 parsed = JSON.parse(line);
839 } catch {
840 return null;
841 }
842 if (typeof parsed !== "object" || parsed === null) return null;
843
844 const record = parsed as Record<string, unknown>;
845 if (typeof record.cwd === "string" && record.cwd.trim().length > 0) {
846 return record.cwd;
847 }
848 const payload = record.payload;
849 if (typeof payload === "object" && payload !== null) {
850 if (source === "codex" && record.type === "session_meta") {
851 const sessionSource = (payload as Record<string, unknown>).source;
852 if (
853 typeof sessionSource === "object" &&
854 sessionSource !== null &&
855 !Array.isArray(sessionSource) &&
856 (Object.hasOwn(sessionSource, "subagent") || Object.hasOwn(sessionSource, "subAgent"))
857 ) {
858 return false;
859 }
860 }
861 const nested = (payload as Record<string, unknown>).cwd;
862 if (typeof nested === "string" && nested.trim().length > 0) {
863 return nested;
864 }
865 }
866 return null;
867 }
868
869 function transcriptIdentity(filePath: string, stats: FileSystem.File.Info) {
870 return {
871 filePath,
872 size: Number(stats.size),
873 mtimeMs: Option.match(stats.mtime, { onNone: () => null, onSome: (date) => date.getTime() }),
874 device: Number(stats.dev),
875 inode: Option.match(stats.ino, { onNone: () => null, onSome: String }),
876 birthtimeMs: Option.match(stats.birthtime, {
877 onNone: () => null,
878 onSome: (date) => date.getTime(),
879 }),
880 };
881 }
882
883 type TranscriptIdentity = Pick<
884 AgentSessionImportSource,
885 "filePath" | "size" | "mtimeMs" | "device" | "inode" | "birthtimeMs"
886 >;
887
888 const fileIdKey = (inode: TranscriptIdentity["inode"]) => (inode === null ? null : String(inode));
889
890 function sameTranscriptIdentity(left: TranscriptIdentity, right: TranscriptIdentity): boolean {
891 // Unsafe legacy numbers may already have lost file ID precision.
892 if (
893 (typeof left.inode === "number" && !Number.isSafeInteger(left.inode)) ||
894 (typeof right.inode === "number" && !Number.isSafeInteger(right.inode))
895 ) {
896 return false;
897 }
898 return (
899 left.filePath === right.filePath &&
900 left.size === right.size &&
901 left.mtimeMs === right.mtimeMs &&
902 left.device === right.device &&
903 fileIdKey(left.inode) === fileIdKey(right.inode) &&
904 left.birthtimeMs === right.birthtimeMs
905 );
906 }
907
908 /** @public */
909 export const make = Effect.gen(function* () {
910 const fileSystem = yield* FileSystem.FileSystem;
911 const processRunner = yield* ProcessRunner.ProcessRunner;
912 // Concurrent client imports must not hold multiple selected-history budgets.
913 const importReadLock = yield* Semaphore.make(1);
914 const path = yield* Path.Path;
915 const serverConfig = yield* ServerConfig.ServerConfig;
916 const serverSettings = yield* ServerSettings.ServerSettingsService;
917 const projectStore = yield* ProjectStore.ProjectStoreV2;
918 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
919 const baseDir = path.resolve(serverConfig.baseDir);
920 const worktreesDir = path.resolve(serverConfig.worktreesDir);
921 const platform = yield* HostProcess.Platform;
922 const isWindows = platform === "win32";
923 const foldWorktreeCase = isWindows;
924 const hostEnvironment = yield* HostProcess.Environment;
925 const homeDir = yield* HostProcess.HomeDirectory;
926 // `/private/tmp` is what macOS reports for sessions started in `/tmp`.
927 const excludedProjectRoots = new Set(
928 [homeDir, NodeOS.tmpdir(), "/tmp", "/private/tmp"].map((directory) =>
929 normalizeProjectPathForComparison(path.resolve(directory)),
930 ),
931 );
932 const excludedProjectAncestors = [
933 path.join(homeDir, "Downloads"),
934 path.join(homeDir, "Documents", "Codex"),
935 ];
936
937 const isExcludedProjectPath = (candidatePath: string) =>
938 excludedProjectRoots.has(normalizeProjectPathForComparison(candidatePath)) ||
939 excludedProjectAncestors.some((ancestor) =>
940 normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith(
941 normalizeForWorktreeMatch(ancestor, foldWorktreeCase),
942 ),
943 ) ||
944 normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith(
945 normalizeForWorktreeMatch(baseDir, foldWorktreeCase),
946 ) ||
947 isT3ManagedWorktree(candidatePath, worktreesDir, foldWorktreeCase);
948
949 const listDirectory = (directory: string) =>
950 fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
951
952 const statOption = (target: string) =>
953 fileSystem.stat(target).pipe(Effect.asSome, Effect.orElseSucceed(Option.none));
954
955 const transcriptChunkReader = Effect.fn("AgentSessionScanner.transcriptChunkReader")(function* (
956 file: FileSystem.File,
957 filePath: string,
958 ) {
959 if (!isCompressedTranscript(filePath)) return (size: number) => file.readAlloc(size);
960 const pull = yield* Stream.toPull(
961 fileSystem
962 .stream(filePath)
963 .pipe(NodeStream.pipeThroughSimple(() => NodeZlib.createZstdDecompress())),
964 );
965 let pending: Array<Uint8Array> = [];
966 let done = false;
967 // Untraced: called once per chunk inside the caller's traced read.
968 return Effect.fnUntraced(function* (size: number) {
969 while (pending.length === 0) {
970 if (done) return Option.none<Uint8Array>();
971 const next = yield* pull.pipe(Pull.catchDone(() => Effect.undefined));
972 if (next === undefined) done = true;
973 else pending = [...next];
974 }
975 const chunk = pending.shift();
976 if (chunk === undefined) return Option.none<Uint8Array>();
977 if (chunk.byteLength > size) pending.unshift(chunk.subarray(size));
978 return Option.some(chunk.subarray(0, size));
979 });
980 });
981
982 const directoryIdentity = Effect.fn("AgentSessionScanner.directoryIdentity")(function* (
983 target: string,
984 knownStats?: FileSystem.File.Info,
985 ) {
986 const resolved = path.resolve(target);
987 const stats = knownStats === undefined ? yield* statOption(resolved) : Option.some(knownStats);
988 if (Option.isSome(stats) && Option.isSome(stats.value.ino) && stats.value.ino.value > 0n) {
989 return `inode:${stats.value.dev}:${stats.value.ino.value}`;
990 }
991 const realPath = yield* fileSystem
992 .realPath(resolved)
993 .pipe(Effect.orElseSucceed(() => resolved));
994 return `path:${normalizeProjectPathForComparison(realPath)}`;
995 });
996
997 /** Stats a directory that may be offered as a project, or none when it is missing or excluded. */
998 const projectDirectoryStats = Effect.fn("AgentSessionScanner.projectDirectoryStats")(function* (
999 directory: string,
1000 ) {
1001 if (isExcludedProjectPath(directory)) return Option.none<FileSystem.File.Info>();
1002 const stats = yield* statOption(directory);
1003 if (Option.isNone(stats) || stats.value.type !== "Directory") return Option.none();
1004 const realPath = yield* fileSystem
1005 .realPath(directory)
1006 .pipe(Effect.orElseSucceed(() => directory));
1007 // Symlinks can disguise excluded worktree paths; re-check their targets.
1008 return isExcludedProjectPath(realPath) ? Option.none() : stats;
1009 });
1010
1011 // Paths whose own read outlived the deadline, mapped to when they may be read
1012 // again. Without this every later scan would wait out the deadline again for
1013 // each phase that touches them.
1014 const blockedGitFilePaths = new Map<string, number>();
1015
1016 /** Reads small files without the libuv pool; "" when missing, unreadable or blocked. */
1017 const readGitFiles = Effect.fn("AgentSessionScanner.readGitFiles")(function* (
1018 filePaths: ReadonlyArray<string>,
1019 ) {
1020 const unique = Array.from(new Set(filePaths));
1021 const now = yield* Clock.currentTimeMillis;
1022 const contents = yield* Effect.forEach(
1023 unique,
1024 (filePath) => {
1025 // No privacy prompts or FIFOs to block open() here.
1026 if (isWindows) {
1027 return fileSystem.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
1028 }
1029 if ((blockedGitFilePaths.get(filePath) ?? 0) > now) return Effect.succeed("");
1030 blockedGitFilePaths.delete(filePath);
1031 return processRunner
1032 .run({
1033 command: "cat",
1034 args: ["--", filePath],
1035 timeout: GIT_FILE_READ_DEADLINE,
1036 timeoutBehavior: "timedOutResult",
1037 maxOutputBytes: MAX_GIT_FILE_BYTES,
1038 outputMode: "truncate",
1039 })
1040 .pipe(
1041 Effect.map((result) => {
1042 if (result.timedOut) {
1043 if (blockedGitFilePaths.size >= MAX_BLOCKED_GIT_FILE_PATHS) {
1044 blockedGitFilePaths.delete(blockedGitFilePaths.keys().next().value!);
1045 }
1046 blockedGitFilePaths.set(filePath, now + BLOCKED_GIT_FILE_RETRY_MS);
1047 }
1048 return result.code === 0 ? result.stdout : "";
1049 }),
1050 Effect.orElseSucceed(() => ""),
1051 );
1052 },
1053 { concurrency: isWindows ? 1 : GIT_FILE_READ_CONCURRENCY },
1054 );
1055 return new Map(unique.map((filePath, index) => [filePath, contents[index]!]));
1056 });
1057
1058 /** Reads every directory's git identity in three phases of concurrent reads. */
1059 const readGitIdentities = Effect.fn("AgentSessionScanner.readGitIdentities")(function* (
1060 directories: ReadonlyArray<string>,
1061 ) {
1062 type GitIdentity =
1063 | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null }
1064 | {
1065 readonly _tag: "Worktree";
1066 readonly gitDir: string;
1067 readonly mainCheckout: string | null;
1068 readonly git: AgentSessionProjectGit | null;
1069 }
1070 | { readonly _tag: "NotGit" };
1071 const identities = new Map<string, GitIdentity>();
1072 const repositories: Array<{
1073 directory: string;
1074 gitDir: string;
1075 worktreeGitDir: string | null;
1076 }> = [];
1077 const pointers: Array<{ directory: string; gitPath: string }> = [];
1078 for (const directory of directories) {
1079 const gitPath = path.join(directory, ".git");
1080 const gitStats = yield* statOption(gitPath);
1081 if (Option.isNone(gitStats)) identities.set(directory, { _tag: "NotGit" });
1082 else if (gitStats.value.type === "Directory") {
1083 repositories.push({ directory, gitDir: gitPath, worktreeGitDir: null });
1084 } else pointers.push({ directory, gitPath });
1085 }
1086
1087 const pointerTexts = yield* readGitFiles(pointers.map(({ gitPath }) => gitPath));
1088 const linkedWorktrees: Array<{ directory: string; gitDir: string }> = [];
1089 for (const { directory, gitPath } of pointers) {
1090 const target = /^gitdir:\s*(.+)$/m.exec(pointerTexts.get(gitPath) ?? "")?.[1]?.trim();
1091 if (target === undefined || target.length === 0) {
1092 identities.set(directory, { _tag: "NotGit" });
1093 continue;
1094 }
1095 const gitDir = path.resolve(directory, target);
1096 if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) {
1097 linkedWorktrees.push({ directory, gitDir });
1098 } else repositories.push({ directory, gitDir, worktreeGitDir: null });
1099 }
1100
1101 const commonDirTexts = yield* readGitFiles(
1102 linkedWorktrees.map(({ gitDir }) => path.join(gitDir, "commondir")),
1103 );
1104 for (const { directory, gitDir } of linkedWorktrees) {
1105 const commonDir = (commonDirTexts.get(path.join(gitDir, "commondir")) ?? "").trim();
1106 if (commonDir.length === 0) {
1107 identities.set(directory, { _tag: "Worktree", gitDir, mainCheckout: null, git: null });
1108 } else
1109 repositories.push({
1110 directory,
1111 gitDir: path.resolve(gitDir, commonDir),
1112 worktreeGitDir: gitDir,
1113 });
1114 }
1115
1116 const configTexts = yield* readGitFiles(
1117 repositories.map(({ gitDir }) => path.join(gitDir, "config")),
1118 );
1119 for (const { directory, gitDir, worktreeGitDir } of repositories) {
1120 const configText = configTexts.get(path.join(gitDir, "config")) ?? "";
1121 const originUrl = parseOriginUrlFromGitConfig(configText);
1122 const git: AgentSessionProjectGit = {
1123 remoteKey:
1124 originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl),
1125 repository: repositoryPathFromRemoteUrl(originUrl),
1126 };
1127 // Bare repositories have no main checkout, so offer their linked worktrees independently.
1128 if (worktreeGitDir !== null && !isBareGitConfig(configText)) {
1129 identities.set(directory, {
1130 _tag: "Worktree",
1131 gitDir: worktreeGitDir,
1132 // Only a common dir named .git sits inside its main checkout, and an
1133 // unreadable config can't rule out a bare repository.
1134 mainCheckout:
1135 configText.length > 0 && path.basename(gitDir) === ".git" ? path.dirname(gitDir) : null,
1136 git,
1137 });
1138 continue;
1139 }
1140 identities.set(directory, { _tag: "Repository", git });
1141 }
1142 return identities;
1143 });
1144
1145 /** Maps each directory to the project it counts toward: a linked worktree counts toward its main checkout. */
1146 const resolveDirectoryProjects = Effect.fn("AgentSessionScanner.resolveDirectoryProjects")(
1147 function* (resolvedDirectories: ReadonlyArray<string>) {
1148 // Stat every directory first so one batch reads all git identities.
1149 const directories = new Map<string, Option.Option<FileSystem.File.Info>>();
1150 for (const resolved of resolvedDirectories) {
1151 if (directories.has(resolved)) continue;
1152 directories.set(resolved, yield* projectDirectoryStats(resolved));
1153 }
1154 const directoryGitIdentities = yield* readGitIdentities(
1155 Array.from(directories).flatMap(([directory, stats]) =>
1156 Option.isSome(stats) ? [directory] : [],
1157 ),
1158 );
1159 const projects = new Map<
1160 string,
1161 {
1162 readonly key: string;
1163 readonly path: string;
1164 readonly git: AgentSessionProjectGit | null;
1165 readonly worktreeGitDir: string | null;
1166 } | null
1167 >();
1168 for (const [resolved, stats] of directories) {
1169 const gitIdentity = directoryGitIdentities.get(resolved);
1170 if (Option.isNone(stats) || gitIdentity === undefined) {
1171 projects.set(resolved, null);
1172 } else if (gitIdentity._tag === "Worktree") {
1173 const { mainCheckout } = gitIdentity;
1174 const mainStats =
1175 mainCheckout === null ? Option.none() : yield* projectDirectoryStats(mainCheckout);
1176 projects.set(
1177 resolved,
1178 mainCheckout !== null && Option.isSome(mainStats)
1179 ? {
1180 key: yield* directoryIdentity(mainCheckout, mainStats.value),
1181 path: mainCheckout,
1182 git: gitIdentity.git,
1183 worktreeGitDir: gitIdentity.gitDir,
1184 }
1185 : null,
1186 );
1187 } else {
1188 projects.set(resolved, {
1189 key: yield* directoryIdentity(resolved, stats.value),
1190 path: resolved,
1191 git: gitIdentity._tag === "Repository" ? gitIdentity.git : null,
1192 worktreeGitDir: null,
1193 });
1194 }
1195 }
1196 return projects;
1197 },
1198 );
1199
1200 const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* (
1201 source: AgentSessionSource,
1202 transcript: TranscriptCandidate,
1203 budget: MetadataReadBudget,
1204 ) {
1205 if (transcript.identity.size === 0) return null;
1206 if (
1207 budget.bytesRemaining === 0 ||
1208 budget.operationsRemaining < 2 ||
1209 budget.recordsRemaining === 0
1210 ) {
1211 budget.truncated = true;
1212 return null;
1213 }
1214 budget.operationsRemaining -= 1;
1215 return yield* Effect.scoped(
1216 fileSystem.open(transcript.filePath, { flag: "r" }).pipe(
1217 Effect.flatMap((file) =>
1218 Effect.gen(function* () {
1219 const readChunk = yield* transcriptChunkReader(file, transcript.filePath);
1220 const size = isCompressedTranscript(transcript.filePath)
1221 ? Number.POSITIVE_INFINITY
1222 : transcript.identity.size;
1223 const decoder = new TextDecoder();
1224 let remaining = "";
1225 let bytesRead = 0;
1226 let recordsRead = 0;
1227 const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size);
1228 const reserveRecord = () => {
1229 if (
1230 recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT ||
1231 budget.recordsRemaining === 0
1232 ) {
1233 budget.truncated = true;
1234 return false;
1235 }
1236 recordsRead += 1;
1237 budget.recordsRemaining -= 1;
1238 return true;
1239 };
1240 const readLastRecord = () => {
1241 const record = remaining + decoder.decode();
1242 return record.length === 0 || !reserveRecord()
1243 ? null
1244 : extractCwd(record.trim(), source);
1245 };
1246
1247 while (bytesRead < maxBytes) {
1248 if (budget.bytesRemaining === 0 || budget.operationsRemaining === 0) {
1249 budget.truncated = true;
1250 return null;
1251 }
1252 const readSize = Math.min(
1253 METADATA_READ_BYTES,
1254 maxBytes - bytesRead,
1255 budget.bytesRemaining,
1256 );
1257 budget.operationsRemaining -= 1;
1258 budget.bytesRemaining -= readSize;
1259 const next = yield* readChunk(readSize);
1260 if (Option.isNone(next)) {
1261 return readLastRecord();
1262 }
1263
1264 bytesRead += next.value.byteLength;
1265 remaining += decoder.decode(next.value, { stream: true });
1266 const lines = remaining.split("\n");
1267 remaining = lines.pop() ?? "";
1268
1269 for (const line of lines) {
1270 if (!reserveRecord()) return null;
1271 const cwd = extractCwd(line.trim(), source);
1272 if (cwd !== null) return cwd;
1273 }
1274 }
1275
1276 if (bytesRead < size) {
1277 budget.truncated = true;
1278 return null;
1279 }
1280 return readLastRecord();
1281 }),
1282 ),
1283 ),
1284 ).pipe(Effect.orElseSucceed(() => null));
1285 });
1286
1287 const readTranscript = Effect.fn("AgentSessionScanner.readTranscript")(function* (
1288 filePath: string,
1289 expected: ReturnType<typeof transcriptIdentity>,
1290 source: AgentSessionSource,
1291 prefix?: { readonly endByteOffset: number; readonly historyBytes: number },
1292 ) {
1293 const compressed = isCompressedTranscript(filePath);
1294 const readBytes =
1295 prefix?.endByteOffset ?? (compressed ? MAX_IMPORTED_TRANSCRIPT_BYTES : expected.size);
1296 if ((!compressed && readBytes > expected.size) || readBytes > MAX_IMPORTED_TRANSCRIPT_BYTES) {
1297 return null;
1298 }
1299
1300 return yield* Effect.scoped(
1301 fileSystem.open(filePath, { flag: "r" }).pipe(
1302 Effect.flatMap((file) =>
1303 Effect.gen(function* () {
1304 if (!sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))) {
1305 return null;
1306 }
1307 const readChunk = yield* transcriptChunkReader(file, filePath);
1308 const records: Array<DecodedTranscriptRecord> = [];
1309 const claudeHistory = createClaudeHistoryWindow();
1310 let cwd = Option.none<string>();
1311 let claudeFields = emptyClaudeFields;
1312 let historyBytes = prefix?.historyBytes ?? 0;
1313 let recordBytes = 0;
1314 let bytesRead = 0;
1315 const reserve = (bytes: number) => {
1316 recordBytes += bytes;
1317 if (historyBytes + recordBytes > MAX_IMPORT_HISTORY_BYTES) {
1318 throw new TranscriptJsonLimitError({
1319 message: "Transcript selected history exceeds the 32 MiB memory budget",
1320 });
1321 }
1322 };
1323 let reader = createTranscriptJsonReader(reserve, selectTranscriptPath);
1324 let decoder = new TextDecoder();
1325 let recordStarted = false;
1326
1327 const finishRecord = () => {
1328 reader.write(decoder.decode());
1329 const value = reader.finish();
1330 const decoded = decodeTranscriptValue(value);
1331 if (Option.isNone(decoded) && source === "pi") {
1332 // Pi accepts messages this schema rejects, such as null content; keep their tree links.
1333 records.push(...Option.toArray(decodePiEntryLinks(value)));
1334 } else if (Option.isSome(decoded)) {
1335 if (Option.isNone(cwd)) cwd = Option.fromNullOr(extractDecodedCwd(decoded.value));
1336 if (source === "claudeAgent") {
1337 claudeFields = foldClaudeFields(claudeFields, decoded.value);
1338 }
1339 if (shouldRetainDecodedRecord(source, decoded.value)) {
1340 if (source === "claudeAgent") {
1341 historyBytes += recordBytes - claudeHistory.push(decoded.value, recordBytes);
1342 } else if (
1343 source === "pi" &&
1344 decoded.value.type === "message" &&
1345 !isPiConversationRecord(decoded.value)
1346 ) {
1347 // Tool output can dwarf the conversation; keep only the tree links.
1348 const { message: _message, ...links } = decoded.value;
1349 records.push(links);
1350 } else {
1351 records.push(decoded.value);
1352 historyBytes += recordBytes;
1353 }
1354 }
1355 }
1356 recordBytes = 0;
1357 reader = createTranscriptJsonReader(reserve, selectTranscriptPath);
1358 decoder = new TextDecoder();
1359 recordStarted = false;
1360 return records.length <= MAX_IMPORT_RECORDS;
1361 };
1362
1363 while (bytesRead < readBytes) {
1364 const next = yield* readChunk(
1365 Math.min(TRANSCRIPT_PREFIX_BYTES, readBytes - bytesRead),
1366 );
1367 if (Option.isNone(next)) {
1368 // A compressed rollout's decompressed length is only known at its end.
1369 if (compressed && prefix === undefined) break;
1370 return null;
1371 }
1372
1373 bytesRead += next.value.byteLength;
1374 const withinBudget = yield* Effect.try({
1375 try: () => {
1376 let start = 0;
1377 while (start < next.value.byteLength) {
1378 const newline = next.value.indexOf(10, start);
1379 const end = newline === -1 ? next.value.byteLength : newline;
1380 recordStarted = true;
1381 reader.write(decoder.decode(next.value.subarray(start, end), { stream: true }));
1382 if (newline === -1) break;
1383 if (!finishRecord()) return false;
1384 start = newline + 1;
1385 }
1386 return true;
1387 },
1388 catch: (cause) => new TranscriptParseError({ filePath, cause }),
1389 });
1390 if (!withinBudget) return null;
1391 }
1392
1393 if (
1394 recordStarted &&
1395 !(yield* Effect.try({
1396 try: finishRecord,
1397 catch: (cause) => new TranscriptParseError({ filePath, cause }),
1398 }))
1399 )
1400 return null;
1401 return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))
1402 ? {
1403 records: source === "claudeAgent" ? claudeHistory.records() : records,
1404 droppedMessageCount: claudeHistory.droppedMessageCount(),
1405 cwd,
1406 claudeFields,
1407 historyBytes,
1408 }
1409 : null;
1410 }),
1411 ),
1412 ),
1413 ).pipe(
1414 Effect.catch((cause) =>
1415 Effect.logWarning("Could not read imported transcript", { filePath, cause }).pipe(
1416 Effect.as(null),
1417 ),
1418 ),
1419 );
1420 });
1421
1422 const readCodexThreadNames = Effect.fn("AgentSessionScanner.readCodexThreadNames")(function* (
1423 homePath: string,
1424 ) {
1425 const indexPath = path.join(homePath, "session_index.jsonl");
1426 return yield* Effect.scoped(
1427 Effect.gen(function* () {
1428 const file = yield* fileSystem.open(indexPath, { flag: "r" });
1429 const size = Number((yield* file.stat).size);
1430 const start = Math.max(0, size - MAX_CODEX_SESSION_INDEX_BYTES);
1431 yield* file.seek(BigInt(start), "start");
1432 const bytes = yield* file.readAlloc(size - start);
1433 const contents = Option.match(bytes, {
1434 onNone: () => "",
1435 onSome: (value) => new TextDecoder().decode(value),
1436 });
1437 // A tail read can start mid-record.
1438 return parseCodexThreadNames(
1439 start > 0 ? contents.slice(contents.indexOf("\n") + 1) : contents,
1440 );
1441 }),
1442 ).pipe(Effect.orElseSucceed((): ReadonlyMap<string, string> => new Map()));
1443 });
1444
1445 const resolveClaudeConfigDir = (homePath: string, environmentHome?: string): string => {
1446 const configured = homePath.trim();
1447 if (configured.length > 0) {
1448 return path.resolve(expandHomePath(configured, homeDir));
1449 }
1450 const fromEnvironment = environmentHome?.trim() ?? "";
1451 if (fromEnvironment.length > 0) {
1452 return path.resolve(expandHomePath(fromEnvironment, homeDir));
1453 }
1454 return path.join(homeDir, ".claude");
1455 };
1456
1457 const discoverClaudeTranscripts = Effect.fn("AgentSessionScanner.discoverClaudeTranscripts")(
1458 function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) {
1459 const projectsDir = path.join(homePath, "projects");
1460 let operationsRemaining = operationBudget;
1461 let truncated = false;
1462 const readDirectory = (directory: string) => {
1463 if (operationsRemaining <= 0) {
1464 truncated = true;
1465 return Effect.succeed<ReadonlyArray<string>>([]);
1466 }
1467 operationsRemaining -= 1;
1468 return listDirectory(directory);
1469 };
1470 // Folder names carry no date, so read the newest folders first: a budget that runs out
1471 // then drops the oldest sessions. Dating has its own allowance, apart from the reads.
1472 let datesRemaining = operationBudget;
1473 const dated: Array<{ readonly name: string; readonly mtimeMs: number }> = [];
1474 const undated: Array<string> = [];
1475 for (const name of yield* readDirectory(projectsDir)) {
1476 if (datesRemaining <= 0) {
1477 undated.push(name);
1478 continue;
1479 }
1480 datesRemaining -= 1;
1481 const stats = yield* statOption(path.join(projectsDir, name));
1482 if (Option.isNone(stats) || stats.value.type !== "Directory") continue;
1483 dated.push({
1484 name,
1485 mtimeMs: Option.match(stats.value.mtime, {
1486 onNone: () => 0,
1487 onSome: (mtime) => mtime.getTime(),
1488 }),
1489 });
1490 }
1491 const projectDirectories = [
1492 ...dated
1493 .toSorted(
1494 (left, right) => right.mtimeMs - left.mtimeMs || left.name.localeCompare(right.name),
1495 )
1496 .map((entry) => entry.name),
1497 ...undated,
1498 ];
1499 const transcripts: Array<TranscriptCandidate> = [];
1500
1501 for (const projectDirectory of projectDirectories) {
1502 if (operationsRemaining <= 0) {
1503 truncated = true;
1504 break;
1505 }
1506 const directory = path.join(projectsDir, projectDirectory);
1507 const directoryTranscripts = (yield* readDirectory(directory))
1508 .filter((entry) => entry.endsWith(".jsonl"))
1509 .map((entry) => path.join(directory, entry));
1510
1511 for (const filePath of directoryTranscripts) {
1512 if (operationsRemaining <= 0) {
1513 truncated = true;
1514 break;
1515 }
1516 operationsRemaining -= 1;
1517 const stats = yield* statOption(filePath);
1518 if (
1519 Option.isNone(stats) ||
1520 stats.value.type !== "File" ||
1521 Option.isNone(stats.value.mtime)
1522 ) {
1523 continue;
1524 }
1525 transcripts.push({
1526 filePath,
1527 mtimeMs: stats.value.mtime.value.getTime(),
1528 providerInstanceId,
1529 homePath,
1530 identity: transcriptIdentity(filePath, stats.value),
1531 });
1532 }
1533 }
1534 return { transcripts, truncated, operationsUsed: operationBudget - operationsRemaining };
1535 },
1536 );
1537
1538 const readCodexProjectRoots = Effect.fn("AgentSessionScanner.readCodexProjectRoots")(function* (
1539 homePath: string,
1540 ) {
1541 const rootsByThread = new Map<string, Array<string>>();
1542 const databasePath = path.join(homePath, CODEX_STATE_DATABASE);
1543 return yield* Effect.try({
1544 try: () => {
1545 const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
1546 try {
1547 database.exec("PRAGMA busy_timeout = 100");
1548 const rows = database
1549 .prepare(
1550 `SELECT threads.id AS id, project_roots.path AS path
1551 FROM threads JOIN project_roots ON project_roots.project_id = threads.project_id
1552 ORDER BY threads.rowid DESC, project_roots.position LIMIT ?`,
1553 )
1554 .all(MAX_CODEX_PROJECT_ROOT_ROWS);
1555 for (const { id, path: root } of rows) {
1556 if (typeof id !== "string" || typeof root !== "string" || root.trim().length === 0) {
1557 continue;
1558 }
1559 const roots = rootsByThread.get(id);
1560 if (roots === undefined) rootsByThread.set(id, [root]);
1561 else roots.push(root);
1562 }
1563 return rootsByThread;
1564 } finally {
1565 database.close();
1566 }
1567 },
1568 catch: (cause) => new CodexStateReadError({ databasePath, cause }),
1569 }).pipe(Effect.orElseSucceed((): ReadonlyMap<string, ReadonlyArray<string>> => new Map()));
1570 });
1571
1572 // Only chats left in an excluded folder, such as Codex's scratch folder, take their project's root.
1573 const projectCwd = (cwd: string, projectRoots: ReadonlyArray<string> | undefined) =>
1574 projectRoots !== undefined &&
1575 isExcludedProjectPath(path.resolve(expandHomePath(cwd.trim(), homeDir)))
1576 ? projectRoots[0]!
1577 : cwd;
1578
1579 const discoverCodexTranscripts = Effect.fn("AgentSessionScanner.discoverCodexTranscripts")(
1580 function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) {
1581 const sessionsDir = path.join(homePath, "sessions");
1582
1583 const transcripts: Array<TranscriptCandidate> = [];
1584 let operationsRemaining = operationBudget;
1585 let truncated = false;
1586 const readDirectory = (directory: string) => {
1587 if (operationsRemaining <= 0) {
1588 truncated = true;
1589 return Effect.succeed<ReadonlyArray<string>>([]);
1590 }
1591 operationsRemaining -= 1;
1592 return listDirectory(directory);
1593 };
1594 for (const year of (yield* readDirectory(sessionsDir)).toSorted().toReversed()) {
1595 if (operationsRemaining <= 0) {
1596 truncated = true;
1597 break;
1598 }
1599 for (const month of (yield* readDirectory(path.join(sessionsDir, year)))
1600 .toSorted()
1601 .toReversed()) {
1602 if (operationsRemaining <= 0) {
1603 truncated = true;
1604 break;
1605 }
1606 for (const day of (yield* readDirectory(path.join(sessionsDir, year, month)))
1607 .toSorted()
1608 .toReversed()) {
1609 if (operationsRemaining <= 0) {
1610 truncated = true;
1611 break;
1612 }
1613 const directory = path.join(sessionsDir, year, month, day);
1614 for (const entry of (yield* readDirectory(directory)).toSorted().toReversed()) {
1615 if (
1616 !entry.startsWith("rollout-") ||
1617 !(entry.endsWith(".jsonl") || isCompressedTranscript(entry))
1618 ) {
1619 continue;
1620 }
1621 if (operationsRemaining <= 0) {
1622 truncated = true;
1623 break;
1624 }
1625 const filePath = path.join(directory, entry);
1626 operationsRemaining -= 1;
1627 const stats = yield* statOption(filePath);
1628 if (
1629 Option.isSome(stats) &&
1630 stats.value.type === "File" &&
1631 Option.isSome(stats.value.mtime)
1632 ) {
1633 transcripts.push({
1634 filePath,
1635 mtimeMs: stats.value.mtime.value.getTime(),
1636 providerInstanceId,
1637 homePath,
1638 identity: transcriptIdentity(filePath, stats.value),
1639 });
1640 }
1641 }
1642 }
1643 }
1644 }
1645 const projectRoots = yield* readCodexProjectRoots(homePath);
1646 return {
1647 transcripts: transcripts.map((transcript) => {
1648 const threadId = CODEX_ROLLOUT_ID_PATTERN.exec(transcript.filePath)?.[1];
1649 const roots = threadId === undefined ? undefined : projectRoots.get(threadId);
1650 return roots === undefined ? transcript : { ...transcript, projectRoots: roots };
1651 }),
1652 truncated,
1653 operationsUsed: operationBudget - operationsRemaining,
1654 };
1655 },
1656 );
1657
1658 // Pi nests sessions in one directory per cwd, but a custom session directory holds them flat.
1659 const discoverPiTranscripts = Effect.fn("AgentSessionScanner.discoverPiTranscripts")(function* (
1660 sessionsDir: string,
1661 providerInstanceId: ProviderInstanceId,
1662 operationBudget: number,
1663 ) {
1664 let operationsRemaining = operationBudget;
1665 let truncated = false;
1666 const readDirectory = (directory: string) => {
1667 if (operationsRemaining <= 0) {
1668 truncated = true;
1669 return Effect.succeed<ReadonlyArray<string>>([]);
1670 }
1671 operationsRemaining -= 1;
1672 return listDirectory(directory);
1673 };
1674 const transcripts: Array<TranscriptCandidate> = [];
1675 for (const entry of yield* readDirectory(sessionsDir)) {
1676 if (operationsRemaining <= 0) {
1677 truncated = true;
1678 break;
1679 }
1680 const entryPath = path.join(sessionsDir, entry);
1681 const filePaths = entry.endsWith(".jsonl")
1682 ? [entryPath]
1683 : (yield* readDirectory(entryPath))
1684 .filter((nested) => nested.endsWith(".jsonl"))
1685 .map((nested) => path.join(entryPath, nested));
1686
1687 for (const filePath of filePaths) {
1688 if (operationsRemaining <= 0) {
1689 truncated = true;
1690 break;
1691 }
1692 operationsRemaining -= 1;
1693 const stats = yield* statOption(filePath);
1694 if (
1695 Option.isSome(stats) &&
1696 stats.value.type === "File" &&
1697 Option.isSome(stats.value.mtime)
1698 ) {
1699 transcripts.push({
1700 filePath,
1701 mtimeMs: stats.value.mtime.value.getTime(),
1702 providerInstanceId,
1703 homePath: sessionsDir,
1704 identity: transcriptIdentity(filePath, stats.value),
1705 });
1706 }
1707 }
1708 }
1709 return { transcripts, truncated, operationsUsed: operationBudget - operationsRemaining };
1710 });
1711
1712 const groupTranscriptsByCwd = Effect.fn("AgentSessionScanner.groupTranscriptsByCwd")(function* (
1713 source: AgentSessionSource,
1714 transcripts: ReadonlyArray<TranscriptCandidate>,
1715 budget: MetadataReadBudget,
1716 importedByFile: ReadonlyMap<
1717 string,
1718 ReadonlyArray<{ readonly cwd: string; readonly source: AgentSessionImportSource }>
1719 >,
1720 ) {
1721 const byOwnerAndCwd = new Map<
1722 string,
1723 {
1724 cwd: string;
1725 providerInstanceId: ProviderInstanceId;
1726 homePath: string;
1727 lastActiveAtMs: number;
1728 transcripts: Array<TranscriptCandidate>;
1729 }
1730 >();
1731
1732 for (const transcript of transcripts) {
1733 // Unchanged imported transcripts keep their import cwd, so they never spend the read budget.
1734 // Codex is excluded: its first record carries the cwd and the subagent marker, and
1735 // rollouts imported before subagents were skipped must still be excluded by it.
1736 const rolloutCwd =
1737 (source === "codex"
1738 ? undefined
1739 : importedByFile.get(`${transcript.providerInstanceId}\0${transcript.filePath}`)
1740 )?.find(
1741 (imported) =>
1742 imported.source.provider === source &&
1743 sameTranscriptIdentity(imported.source, transcript.identity),
1744 )?.cwd ?? (yield* readCwd(source, transcript, budget));
1745 if (rolloutCwd === null || rolloutCwd === false) continue;
1746 const cwd = projectCwd(rolloutCwd, transcript.projectRoots);
1747 const key = `${transcript.providerInstanceId}\0${cwd}`;
1748 const existing = byOwnerAndCwd.get(key);
1749 if (existing) {
1750 existing.lastActiveAtMs = Math.max(existing.lastActiveAtMs, transcript.mtimeMs);
1751 existing.transcripts.push(transcript);
1752 } else {
1753 byOwnerAndCwd.set(key, {
1754 cwd,
1755 providerInstanceId: transcript.providerInstanceId,
1756 homePath: transcript.homePath,
1757 lastActiveAtMs: transcript.mtimeMs,
1758 transcripts: [transcript],
1759 });
1760 }
1761 }
1762
1763 return Array.from(byOwnerAndCwd.values(), (group): RawCandidate => ({
1764 cwd: group.cwd,
1765 source,
1766 providerInstanceId: group.providerInstanceId,
1767 homePath: group.homePath,
1768 threadCount: group.transcripts.length,
1769 lastActiveAtMs: group.lastActiveAtMs,
1770 transcripts: group.transcripts,
1771 }));
1772 });
1773
1774 const collectCandidates = Effect.fn("AgentSessionScanner.collectCandidates")(function* () {
1775 const settings = yield* serverSettings.getSettings.pipe(
1776 Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-settings", cause })),
1777 );
1778
1779 const runtimeRows = yield* runtimes
1780 .list()
1781 .pipe(
1782 Effect.mapError(
1783 (cause) => new AgentSessionScanError({ operation: "read-projects", cause }),
1784 ),
1785 );
1786 const importedByFile = Map.groupBy(
1787 runtimeRows.flatMap((runtime) => {
1788 const payload = decodeImportedTranscriptPayload(runtime.runtimePayload);
1789 if (Option.isNone(payload) || payload.value.cwd === undefined) return [];
1790 const cwd = payload.value.cwd;
1791 return (payload.value.importedTranscripts ?? []).map((source) => ({ cwd, source }));
1792 }),
1793 ({ source }) => `${source.providerInstanceId}\0${source.filePath}`,
1794 );
1795 const raw: Array<RawCandidate> = [];
1796 let truncated = false;
1797 let metadataTruncated = false;
1798
1799 for (const source of ["claudeAgent", "codex", "pi"] as const) {
1800 const instances: Array<{
1801 readonly instanceId: ProviderInstanceId;
1802 readonly config: ProviderInstanceConfig;
1803 }> = Object.entries(settings.providerInstances)
1804 .filter(
1805 ([, instance]) => instance.driver === source && resolveProviderInstanceEnabled(instance),
1806 )
1807 .map(([instanceId, config]) => ({
1808 instanceId: ProviderInstanceId.make(instanceId),
1809 config,
1810 }));
1811 if (!Object.hasOwn(settings.providerInstances, source)) {
1812 const defaultInstance = {
1813 instanceId: ProviderInstanceId.make(source),
1814 config: { driver: ProviderDriverKind.make(source) },
1815 };
1816 if (resolveProviderInstanceEnabled(defaultInstance.config)) {
1817 instances.push(defaultInstance);
1818 }
1819 }
1820
1821 instances.sort((left, right) => {
1822 const leftDefault = left.instanceId === source ? 0 : 1;
1823 const rightDefault = right.instanceId === source ? 0 : 1;
1824 return leftDefault - rightDefault;
1825 });
1826 const homes: Array<{ homePath: string; providerInstanceId: ProviderInstanceId }> = [];
1827 const seenHomes = new Set<string>();
1828 for (const { instanceId, config: instance } of instances) {
1829 const environmentHome = (name: "CLAUDE_CONFIG_DIR" | "CODEX_HOME") => {
1830 const configured = instance.environment?.findLast(
1831 (variable) => variable.name === name,
1832 )?.value;
1833 return typeof configured === "string" ? configured : hostEnvironment[name];
1834 };
1835
1836 let homePath: string;
1837 if (source === "pi") {
1838 const environment = yield* mergeProviderInstanceEnvironment(
1839 instance.environment,
1840 hostEnvironment,
1841 ).pipe(Effect.provideService(HostProcess.HomeDirectory, homeDir));
1842 homePath = resolvePiSessionsDir(
1843 environment,
1844 piHome(environment, homeDir, platform),
1845 path,
1846 );
1847 } else if (source === "claudeAgent") {
1848 const config = decodeClaudeSettings(instance.config ?? {});
1849 if (Option.isNone(config)) continue;
1850 homePath = resolveClaudeConfigDir(
1851 config.value.homePath,
1852 environmentHome("CLAUDE_CONFIG_DIR"),
1853 );
1854 } else {
1855 const config = decodeCodexSettings(instance.config ?? {});
1856 if (Option.isNone(config)) continue;
1857 const codexHome = environmentHome("CODEX_HOME");
1858 const codexSettings =
1859 config.value.homePath.trim().length === 0 &&
1860 config.value.shadowHomePath.trim().length === 0 &&
1861 codexHome?.trim()
1862 ? { ...config.value, homePath: codexHome }
1863 : config.value;
1864 const layout = yield* resolveCodexHomeLayout(codexSettings).pipe(
1865 Effect.provideService(Path.Path, path),
1866 );
1867 homePath = layout.sharedHomePath;
1868 }
1869
1870 const homeKey = `${source}\0${yield* directoryIdentity(homePath)}`;
1871 if (seenHomes.has(homeKey)) continue;
1872 seenHomes.add(homeKey);
1873 homes.push({ homePath, providerInstanceId: instanceId });
1874 }
1875
1876 const transcriptCandidates: Array<TranscriptCandidate> = [];
1877 const discover =
1878 source === "claudeAgent"
1879 ? discoverClaudeTranscripts
1880 : source === "codex"
1881 ? discoverCodexTranscripts
1882 : discoverPiTranscripts;
1883 const shares = splitOperationBudget(MAX_DISCOVERY_OPERATIONS_PER_SOURCE, homes.length);
1884 const discovered: Array<{
1885 readonly transcripts: ReadonlyArray<TranscriptCandidate>;
1886 readonly truncated: boolean;
1887 readonly operationsUsed: number;
1888 }> = [];
1889 for (const [index, home] of homes.entries()) {
1890 const operationBudget = shares[index] ?? 0;
1891 discovered.push(
1892 operationBudget === 0
1893 ? { transcripts: [], truncated: true, operationsUsed: 0 }
1894 : yield* discover(home.homePath, home.providerInstanceId, operationBudget),
1895 );
1896 }
1897 // Budget that small homes left unused goes to the homes that ran out, which rescan with it.
1898 // Each takes an even split of what is still unused; a pass in which no home finishes spends
1899 // it all, so every repeat has fewer starved homes.
1900 let unused =
1901 MAX_DISCOVERY_OPERATIONS_PER_SOURCE -
1902 discovered.reduce((total, result) => total + result.operationsUsed, 0);
1903 let starved = discovered.flatMap((result, index) => (result.truncated ? [index] : []));
1904 while (unused > 0 && starved.length > 0) {
1905 for (const [position, index] of starved.entries()) {
1906 if (unused <= 0) break;
1907 const home = homes[index]!;
1908 const before = discovered[index]!.operationsUsed;
1909 const extra = Math.ceil(unused / (starved.length - position));
1910 const result = yield* discover(home.homePath, home.providerInstanceId, before + extra);
1911 discovered[index] = result;
1912 unused -= result.operationsUsed - before;
1913 }
1914 starved = starved.filter((index) => discovered[index]!.truncated);
1915 }
1916 for (const result of discovered) {
1917 truncated ||= result.truncated;
1918 transcriptCandidates.push(...result.transcripts);
1919 }
1920
1921 transcriptCandidates.sort(
1922 (left, right) =>
1923 right.mtimeMs - left.mtimeMs || left.filePath.localeCompare(right.filePath),
1924 );
1925 if (transcriptCandidates.length > MAX_TRANSCRIPTS_PER_SOURCE) {
1926 truncated = true;
1927 }
1928 const selectedTranscripts = selectMetadataTranscripts(transcriptCandidates);
1929 const metadataBudget: MetadataReadBudget = {
1930 bytesRemaining: MAX_METADATA_BYTES_PER_SOURCE,
1931 operationsRemaining: MAX_METADATA_OPERATIONS_PER_SOURCE,
1932 recordsRemaining: MAX_METADATA_RECORDS_PER_SOURCE,
1933 truncated: false,
1934 };
1935 raw.push(
1936 ...(yield* groupTranscriptsByCwd(
1937 source,
1938 selectedTranscripts,
1939 metadataBudget,
1940 importedByFile,
1941 )),
1942 );
1943 metadataTruncated ||= metadataBudget.truncated;
1944 }
1945
1946 return { candidates: raw, truncated: truncated || metadataTruncated, metadataTruncated };
1947 });
1948
1949 let cachedCandidates: Effect.Success<ReturnType<typeof collectCandidates>> | null = null;
1950
1951 const scan: AgentSessionScanner["Service"]["scan"] = Effect.gen(function* () {
1952 cachedCandidates = yield* collectCandidates();
1953 const { candidates: raw, truncated } = cachedCandidates;
1954
1955 const merged = new Map<
1956 string,
1957 {
1958 path: string;
1959 sources: Array<AgentSessionSource>;
1960 threadCount: number;
1961 lastActiveAtMs: number | null;
1962 git: AgentSessionProjectGit | null;
1963 }
1964 >();
1965 const directoryProjects = yield* resolveDirectoryProjects(
1966 raw.flatMap((candidate) => {
1967 const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1968 return path.isAbsolute(expanded) ? [path.resolve(expanded)] : [];
1969 }),
1970 );
1971
1972 for (const candidate of raw) {
1973 const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1974 if (!path.isAbsolute(expanded)) continue;
1975 const project = directoryProjects.get(path.resolve(expanded));
1976 if (project === undefined || project === null) continue;
1977
1978 const existing = merged.get(project.key);
1979 if (!existing) {
1980 merged.set(project.key, {
1981 path: project.path,
1982 sources: [candidate.source],
1983 threadCount: candidate.threadCount,
1984 lastActiveAtMs: candidate.lastActiveAtMs,
1985 git: project.git,
1986 });
1987 continue;
1988 }
1989 if (!existing.sources.includes(candidate.source)) {
1990 existing.sources.push(candidate.source);
1991 }
1992 existing.threadCount += candidate.threadCount;
1993 existing.lastActiveAtMs =
1994 existing.lastActiveAtMs === null || candidate.lastActiveAtMs === null
1995 ? (existing.lastActiveAtMs ?? candidate.lastActiveAtMs)
1996 : Math.max(existing.lastActiveAtMs, candidate.lastActiveAtMs);
1997 }
1998
1999 // Resolve persisted roots too; transcripts may use different symlinks to the same directory.
2000 const importedProjects = yield* projectStore
2001 .listShells()
2002 .pipe(
2003 Effect.mapError(
2004 (cause) => new AgentSessionScanError({ operation: "read-projects", cause }),
2005 ),
2006 );
2007 const importedProjectsByRoot = new Map<string, (typeof importedProjects)[number]>();
2008 for (const project of importedProjects) {
2009 const projectRoot = path.resolve(expandHomePath(project.workspaceRoot, homeDir));
2010 importedProjectsByRoot.set(normalizeProjectPathForComparison(projectRoot), project);
2011 importedProjectsByRoot.set(yield* directoryIdentity(projectRoot), project);
2012 }
2013
2014 const candidates: Array<AgentSessionProjectCandidate> = [];
2015 for (const [key, entry] of merged.entries()) {
2016 const importedProject =
2017 importedProjectsByRoot.get(normalizeProjectPathForComparison(entry.path)) ??
2018 importedProjectsByRoot.get(key);
2019 const candidatePath = importedProject?.workspaceRoot ?? entry.path;
2020 candidates.push({
2021 path: candidatePath,
2022 title: path.basename(candidatePath) || candidatePath,
2023 ...(importedProject === undefined ? {} : { projectId: importedProject.id }),
2024 sources: entry.sources,
2025 threadCount: entry.threadCount,
2026 lastActiveAt:
2027 entry.lastActiveAtMs === null
2028 ? null
2029 : DateTime.formatIso(DateTime.makeUnsafe(entry.lastActiveAtMs)),
2030 alreadyImported: importedProject !== undefined,
2031 git: entry.git,
2032 });
2033 }
2034
2035 candidates.sort((left, right) => {
2036 if (left.lastActiveAt === right.lastActiveAt) return left.path.localeCompare(right.path);
2037 if (left.lastActiveAt === null) return 1;
2038 if (right.lastActiveAt === null) return -1;
2039 return right.lastActiveAt.localeCompare(left.lastActiveAt);
2040 });
2041
2042 return {
2043 candidates,
2044 scannedAt: DateTime.formatIso(yield* DateTime.now),
2045 ...(truncated ? { truncated: true } : {}),
2046 };
2047 });
2048
2049 const prepareRecentThreads = Effect.fn("AgentSessionScanner.prepareRecentThreads")(function* (
2050 workspaceRoot: string,
2051 completedSources: ReadonlyArray<AgentSessionImportSource>,
2052 ) {
2053 const root = path.resolve(expandHomePath(workspaceRoot, homeDir));
2054 const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root));
2055 if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot)) return Stream.empty;
2056 const rootIdentity = yield* directoryIdentity(root);
2057 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
2058 const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS;
2059
2060 // Imports recorded since a budget-truncated collection can free budget for transcripts it cut off.
2061 if (cachedCandidates === null || cachedCandidates.metadataTruncated) {
2062 cachedCandidates = yield* collectCandidates();
2063 }
2064 const { candidates } = cachedCandidates;
2065
2066 // The scan counts a linked worktree's sessions toward its main checkout, so import them with it.
2067 const candidateDirectories = candidates.flatMap((candidate) => {
2068 const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
2069 return path.isAbsolute(expanded) ? [path.resolve(expanded)] : [];
2070 });
2071 const directoryProjects = yield* resolveDirectoryProjects(candidateDirectories);
2072 const belongsToRoot = Effect.fn("AgentSessionScanner.belongsToRoot")(function* (
2073 resolved: string,
2074 ) {
2075 if ((yield* directoryIdentity(resolved)) === rootIdentity) return true;
2076 if (!directoryProjects.has(resolved)) {
2077 const project = (yield* resolveDirectoryProjects([resolved])).get(resolved) ?? null;
2078 directoryProjects.set(resolved, project);
2079 }
2080 return directoryProjects.get(resolved)?.key === rootIdentity;
2081 });
2082 const worktreesByDirectory = new Map<string, { path: string; branch: string | null } | null>();
2083 const rootWorktree = Effect.fn("AgentSessionScanner.rootWorktree")(function* (
2084 resolved: string,
2085 ) {
2086 const known = worktreesByDirectory.get(resolved);
2087 if (known !== undefined) return known;
2088 const gitDir =
2089 (yield* directoryIdentity(resolved)) === rootIdentity
2090 ? null
2091 : (directoryProjects.get(resolved)?.worktreeGitDir ?? null);
2092 let worktree: { path: string; branch: string | null } | null = null;
2093 if (gitDir !== null) {
2094 const headPath = path.join(gitDir, "HEAD");
2095 const head = (yield* readGitFiles([headPath])).get(headPath) ?? "";
2096 worktree = {
2097 path: resolved,
2098 branch: /^ref: refs\/heads\/(.+)$/.exec(head.trim())?.[1] ?? null,
2099 };
2100 }
2101 worktreesByDirectory.set(resolved, worktree);
2102 return worktree;
2103 });
2104
2105 const eligibleTranscripts: Array<{
2106 readonly candidate: RawCandidate;
2107 readonly transcript: RawCandidate["transcripts"][number] & { readonly mtimeMs: number };
2108 }> = [];
2109 for (const candidate of candidates) {
2110 const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
2111 if (!path.isAbsolute(expanded)) continue;
2112 const resolved = path.resolve(expanded);
2113 if (!(yield* belongsToRoot(resolved))) continue;
2114
2115 for (const transcript of candidate.transcripts) {
2116 if (
2117 transcript.mtimeMs === null ||
2118 transcript.mtimeMs < cutoffMs ||
2119 transcript.mtimeMs > nowMs
2120 ) {
2121 continue;
2122 }
2123 eligibleTranscripts.push({
2124 candidate,
2125 transcript: { ...transcript, mtimeMs: transcript.mtimeMs },
2126 });
2127 }
2128 }
2129
2130 eligibleTranscripts.sort((left, right) => {
2131 if (left.transcript.mtimeMs !== right.transcript.mtimeMs) {
2132 return right.transcript.mtimeMs - left.transcript.mtimeMs;
2133 }
2134 return left.transcript.filePath.localeCompare(right.transcript.filePath);
2135 });
2136
2137 const completedByFile = Map.groupBy(
2138 completedSources,
2139 (source) => `${source.providerInstanceId}\0${source.filePath}`,
2140 );
2141 const importedSessions = new Set<string>();
2142 const codexThreadNamesByHome = new Map<string, ReadonlyMap<string, string>>();
2143 let bytesRemaining = MAX_IMPORT_BYTES;
2144 let transcriptsRemaining = MAX_IMPORT_TRANSCRIPTS;
2145 const codexRolloutPaths = new Map<ProviderInstanceId, ReadonlyMap<string, string>>();
2146 const codexRolloutPath = (providerInstanceId: ProviderInstanceId, rolloutId: string) => {
2147 let paths = codexRolloutPaths.get(providerInstanceId);
2148 if (paths === undefined) {
2149 paths = new Map(
2150 candidates.flatMap((candidate) =>
2151 candidate.source === "codex" && candidate.providerInstanceId === providerInstanceId
2152 ? candidate.transcripts.flatMap((transcript) => {
2153 const match = CODEX_ROLLOUT_ID_PATTERN.exec(transcript.filePath);
2154 const id = match?.[2] ?? match?.[1];
2155 return id === undefined ? [] : [[id, transcript.filePath] as const];
2156 })
2157 : [],
2158 ),
2159 );
2160 codexRolloutPaths.set(providerInstanceId, paths);
2161 }
2162 return paths.get(rolloutId);
2163 };
2164 // Reads the prefixes a rewound rollout inherits, oldest first. Without all of
2165 // them the rollout is imported on its own, as before.
2166 const readCodexHistoryBase = Effect.fn("AgentSessionScanner.readCodexHistoryBase")(function* (
2167 providerInstanceId: ProviderInstanceId,
2168 records: ReadonlyArray<DecodedTranscriptRecord>,
2169 historyBytes: number,
2170 ) {
2171 const prefixes: Array<ReadonlyArray<DecodedTranscriptRecord>> = [];
2172 const visited = new Set<string>();
2173 for (let base = codexHistoryBase(records); base !== undefined;) {
2174 const filePath = visited.has(base.thread_id)
2175 ? undefined
2176 : codexRolloutPath(providerInstanceId, base.thread_id);
2177 if (filePath === undefined || base.end_byte_offset > bytesRemaining) return null;
2178 visited.add(base.thread_id);
2179 const stats = yield* statOption(filePath);
2180 if (Option.isNone(stats) || stats.value.type !== "File") return null;
2181 bytesRemaining -= base.end_byte_offset;
2182 const inherited = yield* readTranscript(
2183 filePath,
2184 transcriptIdentity(filePath, stats.value),
2185 "codex",
2186 { endByteOffset: base.end_byte_offset, historyBytes },
2187 );
2188 if (inherited === null) return null;
2189 historyBytes = inherited.historyBytes;
2190 // The rollout's own session_meta names the thread; inherited ones may name a fork parent.
2191 prefixes.unshift(inherited.records.filter((record) => record.type !== "session_meta"));
2192 base = codexHistoryBase(inherited.records);
2193 }
2194 return prefixes.flat();
2195 });
2196 return Stream.fromIteratorSucceed(eligibleTranscripts.values(), 1).pipe(
2197 Stream.mapEffect(({ candidate, transcript }) =>
2198 Effect.gen(function* () {
2199 const completed = completedByFile.get(
2200 `${candidate.providerInstanceId}\0${transcript.filePath}`,
2201 );
2202 if (completed === undefined && (transcriptsRemaining === 0 || bytesRemaining === 0)) {
2203 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
2204 }
2205 const stats = yield* statOption(transcript.filePath);
2206 if (Option.isNone(stats) || stats.value.type !== "File") {
2207 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
2208 }
2209 const identity = transcriptIdentity(transcript.filePath, stats.value);
2210 const completedSource = completed?.find(
2211 (source) =>
2212 source.provider === candidate.source && sameTranscriptIdentity(source, identity),
2213 );
2214 if (completedSource !== undefined) {
2215 const sessionKey = `${completedSource.providerInstanceId}\0${completedSource.providerSessionId}`;
2216 if (importedSessions.has(sessionKey)) return Option.none<AgentSessionRecentThread>();
2217 importedSessions.add(sessionKey);
2218 return Option.some<AgentSessionRecentThread>({
2219 _tag: "AlreadyImported",
2220 source: completedSource,
2221 });
2222 }
2223 if (
2224 transcriptsRemaining === 0 ||
2225 identity.size > MAX_IMPORTED_TRANSCRIPT_BYTES ||
2226 identity.size > bytesRemaining
2227 ) {
2228 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
2229 }
2230 transcriptsRemaining -= 1;
2231 bytesRemaining -= identity.size;
2232 const snapshot = yield* readTranscript(transcript.filePath, identity, candidate.source);
2233 if (snapshot === null) {
2234 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
2235 }
2236
2237 if (Option.isNone(snapshot.cwd)) {
2238 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
2239 }
2240 const expandedCwd = expandHomePath(
2241 projectCwd(snapshot.cwd.value, transcript.projectRoots).trim(),
2242 homeDir,
2243 );
2244 if (!path.isAbsolute(expandedCwd) || !(yield* belongsToRoot(path.resolve(expandedCwd)))) {
2245 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
2246 }
2247 const worktree = yield* rootWorktree(path.resolve(expandedCwd));
2248
2249 const inheritedRecords =
2250 candidate.source === "codex"
2251 ? yield* readCodexHistoryBase(
2252 candidate.providerInstanceId,
2253 snapshot.records,
2254 snapshot.historyBytes,
2255 )
2256 : null;
2257 const parsedThread = parseAgentSessionRecords(
2258 {
2259 source: candidate.source,
2260 providerInstanceId: candidate.providerInstanceId,
2261 fallbackSessionId: path.basename(
2262 transcript.filePath,
2263 isCompressedTranscript(transcript.filePath)
2264 ? COMPRESSED_TRANSCRIPT_SUFFIX
2265 : ".jsonl",
2266 ),
2267 lastActiveAtMs: transcript.mtimeMs,
2268 },
2269 inheritedRecords === null
2270 ? snapshot.records
2271 : [...inheritedRecords, ...snapshot.records],
2272 snapshot.claudeFields,
2273 snapshot.droppedMessageCount,
2274 );
2275 if (parsedThread === "empty") {
2276 // null means an unreadable history base, which may hold the conversation.
2277 if (candidate.source === "codex" && inheritedRecords === null) {
2278 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
2279 }
2280 // Never recorded as imported, so charging them would starve real sessions every run.
2281 transcriptsRemaining += 1;
2282 return Option.none<AgentSessionRecentThread>();
2283 }
2284 if (parsedThread === null) {
2285 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
2286 }
2287 let savedTitle: string | undefined;
2288 if (candidate.source === "codex") {
2289 const names =
2290 codexThreadNamesByHome.get(candidate.homePath) ??
2291 (yield* readCodexThreadNames(candidate.homePath));
2292 codexThreadNamesByHome.set(candidate.homePath, names);
2293 savedTitle = names.get(parsedThread.providerSessionId);
2294 }
2295
2296 const source: AgentSessionImportSource = {
2297 ...identity,
2298 provider: parsedThread.source,
2299 providerInstanceId: parsedThread.providerInstanceId,
2300 providerSessionId: parsedThread.providerSessionId,
2301 };
2302 const sessionKey = `${parsedThread.providerInstanceId}\0${parsedThread.providerSessionId}`;
2303 if (importedSessions.has(sessionKey)) {
2304 return Option.some<AgentSessionRecentThread>({ _tag: "Duplicate", source });
2305 }
2306 importedSessions.add(sessionKey);
2307 return Option.some<AgentSessionRecentThread>({
2308 _tag: "Importable",
2309 thread:
2310 savedTitle === undefined ? parsedThread : { ...parsedThread, title: savedTitle },
2311 source,
2312 worktree,
2313 });
2314 }).pipe(importReadLock.withPermits(1)),
2315 ),
2316 Stream.map(Option.toArray),
2317 Stream.flattenIterable,
2318 );
2319 });
2320
2321 const recentThreads: AgentSessionScanner["Service"]["recentThreads"] = (
2322 workspaceRoot,
2323 completedSources = [],
2324 ) => Stream.unwrap(prepareRecentThreads(workspaceRoot, completedSources));
2325
2326 return AgentSessionScanner.of({ scan, recentThreads });
2327 });
2328
2329 export const layer = Layer.effect(AgentSessionScanner, make).pipe(
2330 Layer.provide(ProcessRunner.layer),
2331 );