recent-codex-session.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. import { lstat, open, readdir, realpath } from 'node:fs/promises';
  2. import type { Dirent } from 'node:fs';
  3. import { createRequire } from 'node:module';
  4. import { homedir } from 'node:os';
  5. import path from 'node:path';
  6. const DEFAULT_RECENT_WINDOW_MS = 10 * 60 * 1000;
  7. const MAX_CANDIDATES = 256;
  8. const MAX_HEADER_BYTES = 64 * 1024;
  9. const MAX_COMPRESSED_HEADER_BYTES = 256 * 1024;
  10. const MAX_FUTURE_SKEW_MS = 5 * 60 * 1000;
  11. export interface RecentCodexSession {
  12. readonly sessionId: string;
  13. readonly updatedAtMs: number;
  14. readonly source: 'cli' | 'vscode';
  15. }
  16. export type FindRecentCodexSession = (options: {
  17. readonly workspaceDir: string;
  18. readonly homeDir?: string;
  19. readonly codexHome?: string;
  20. readonly nowMs?: number;
  21. readonly recentWindowMs?: number;
  22. }) => Promise<RecentCodexSession | undefined>;
  23. interface RolloutCandidate {
  24. readonly filePath: string;
  25. readonly updatedAtMs: number;
  26. }
  27. export const findRecentCodexSession: FindRecentCodexSession = async (options) => {
  28. const nowMs = options.nowMs ?? Date.now();
  29. const recentWindowMs = options.recentWindowMs ?? DEFAULT_RECENT_WINDOW_MS;
  30. const oldestAllowedMs = nowMs - recentWindowMs;
  31. const codexHome = path.resolve(
  32. options.codexHome ??
  33. process.env.CODEX_HOME ??
  34. path.join(options.homeDir ?? homedir(), '.codex'),
  35. );
  36. const sessionsRoot = path.join(codexHome, 'sessions');
  37. let canonicalWorkspace: string;
  38. let canonicalSessionsRoot: string;
  39. try {
  40. [canonicalWorkspace, canonicalSessionsRoot] = await Promise.all([
  41. realpath(options.workspaceDir),
  42. realpath(sessionsRoot),
  43. ]);
  44. } catch {
  45. return undefined;
  46. }
  47. const candidates = await collectCandidates(canonicalSessionsRoot, oldestAllowedMs, nowMs);
  48. if (!candidates) return undefined;
  49. for (const candidate of candidates) {
  50. const metadata = await readCodexSessionMetadata(candidate.filePath);
  51. if (!metadata || (metadata.source !== 'cli' && metadata.source !== 'vscode')) continue;
  52. const candidateWorkspace = await canonicalizeExistingDirectory(metadata.cwd);
  53. if (candidateWorkspace !== canonicalWorkspace) continue;
  54. return {
  55. sessionId: metadata.sessionId,
  56. updatedAtMs: candidate.updatedAtMs,
  57. source: metadata.source,
  58. };
  59. }
  60. return undefined;
  61. };
  62. async function collectCandidates(
  63. sessionsRoot: string,
  64. oldestAllowedMs: number,
  65. nowMs: number,
  66. ): Promise<RolloutCandidate[] | undefined> {
  67. const dayDirectories = dateDirectoriesForWindow(oldestAllowedMs, nowMs);
  68. const candidates: RolloutCandidate[] = [];
  69. for (const segments of dayDirectories) {
  70. const directory = path.join(sessionsRoot, ...segments);
  71. let entries: Dirent<string>[];
  72. try {
  73. entries = await readdir(directory, { withFileTypes: true });
  74. } catch {
  75. continue;
  76. }
  77. for (const entry of entries) {
  78. if (!entry.isFile() || !/^rollout-.+\.jsonl(?:\.zst)?$/u.test(entry.name)) continue;
  79. const filePath = path.join(directory, entry.name);
  80. try {
  81. const fileStat = await lstat(filePath);
  82. if (!fileStat.isFile() || fileStat.isSymbolicLink()) continue;
  83. if (fileStat.mtimeMs < oldestAllowedMs || fileStat.mtimeMs > nowMs + MAX_FUTURE_SKEW_MS) {
  84. continue;
  85. }
  86. const canonicalFile = await realpath(filePath);
  87. if (!isPathInside(sessionsRoot, canonicalFile)) continue;
  88. candidates.push({
  89. filePath: canonicalFile,
  90. updatedAtMs: Math.min(fileStat.mtimeMs, nowMs),
  91. });
  92. if (candidates.length > MAX_CANDIDATES) return undefined;
  93. } catch {
  94. continue;
  95. }
  96. }
  97. }
  98. return candidates.sort(
  99. (left, right) =>
  100. right.updatedAtMs - left.updatedAtMs || left.filePath.localeCompare(right.filePath),
  101. );
  102. }
  103. function dateDirectoriesForWindow(oldestAllowedMs: number, nowMs: number): string[][] {
  104. const result = new Map<string, string[]>();
  105. for (const timestamp of [oldestAllowedMs, nowMs]) {
  106. const date = new Date(timestamp);
  107. const variants: [number, number, number][] = [
  108. [date.getFullYear(), date.getMonth() + 1, date.getDate()],
  109. [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()],
  110. ];
  111. for (const [year, month, day] of variants) {
  112. const segments = [String(year), padDatePart(month), padDatePart(day)];
  113. result.set(segments.join('/'), segments);
  114. }
  115. }
  116. return [...result.values()];
  117. }
  118. async function readCodexSessionMetadata(filePath: string): Promise<
  119. | {
  120. sessionId: string;
  121. cwd: string;
  122. source: string;
  123. }
  124. | undefined
  125. > {
  126. let header: string;
  127. try {
  128. header = await readBoundedHeader(filePath);
  129. } catch {
  130. return undefined;
  131. }
  132. for (const line of header.split('\n').slice(0, 20)) {
  133. if (!line.trim()) continue;
  134. let record: unknown;
  135. try {
  136. record = JSON.parse(line);
  137. } catch {
  138. continue;
  139. }
  140. if (!isRecord(record) || record.type !== 'session_meta' || !isRecord(record.payload)) continue;
  141. const { id, cwd, source } = record.payload;
  142. if (typeof id !== 'string' || !id.trim() || typeof cwd !== 'string') return undefined;
  143. if (typeof source !== 'string') return undefined;
  144. if (!path.basename(filePath).includes(id)) return undefined;
  145. return { sessionId: id, cwd, source };
  146. }
  147. return undefined;
  148. }
  149. async function readBoundedHeader(filePath: string): Promise<string> {
  150. const compressed = filePath.endsWith('.zst');
  151. const byteLimit = compressed ? MAX_COMPRESSED_HEADER_BYTES : MAX_HEADER_BYTES;
  152. const handle = await open(filePath, 'r');
  153. try {
  154. const buffer = Buffer.alloc(byteLimit);
  155. const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
  156. const content = buffer.subarray(0, bytesRead);
  157. if (!compressed) return content.toString('utf8');
  158. const dynamicRequire = createRequire(import.meta.url);
  159. const zlib = dynamicRequire('node:zlib') as {
  160. zstdDecompressSync?: (input: Uint8Array, options: { maxOutputLength: number }) => Buffer;
  161. };
  162. if (!zlib.zstdDecompressSync) throw new Error('Zstandard is unavailable.');
  163. return zlib.zstdDecompressSync(content, { maxOutputLength: MAX_HEADER_BYTES }).toString('utf8');
  164. } finally {
  165. await handle.close();
  166. }
  167. }
  168. async function canonicalizeExistingDirectory(directory: string): Promise<string | undefined> {
  169. try {
  170. return await realpath(directory);
  171. } catch {
  172. return undefined;
  173. }
  174. }
  175. function isRecord(value: unknown): value is Record<string, unknown> {
  176. return typeof value === 'object' && value !== null && !Array.isArray(value);
  177. }
  178. function isPathInside(parent: string, candidate: string): boolean {
  179. const relative = path.relative(parent, candidate);
  180. return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
  181. }
  182. function padDatePart(value: number): string {
  183. return String(value).padStart(2, '0');
  184. }