import { existsSync, mkdirSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { execFileSync } from "node:child_process"; import { randomUUID } from "node:crypto"; import type { SessionTranscript } from "../export/sessions.js"; const HOME = homedir(); const STATE_DB = join(HOME, ".codex", "state_5.sqlite"); const SESSIONS_DIR = join(HOME, ".codex", "sessions"); const SQLITE = "/usr/bin/sqlite3"; /** Escape a value for a single-quoted SQL literal. */ function q(value: string): string { return "'" + String(value).replace(/'/g, "''") + "'"; } function runSql(db: string, sql: string): string { return execFileSync(SQLITE, [db, sql], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }); } export function codexStateExists(): boolean { return existsSync(STATE_DB); } /** Whether the Codex app/CLI is currently running. */ export function codexRunning(): boolean { try { const out = execFileSync("pgrep", ["-fl", "Codex"], { encoding: "utf8" }); return out.split("\n").some((l) => l && !l.includes("agentlens") && /Codex/i.test(l)); } catch { return false; } } interface RolloutLine { timestamp: string; ordinal: number; type: "session_meta" | "response_item"; payload: Record; } /** Build a Codex-compatible rollout JSONL for one DSH transcript. */ export function buildRollout(transcript: SessionTranscript): { id: string; timestamp: Date; content: string } { const id = randomUUID(); const started = transcript.createdAt ? new Date(transcript.createdAt) : new Date(); const cwd = transcript.cwd || join(HOME, "Documents", "Codex"); const lines: RolloutLine[] = []; let ordinal = 0; lines.push({ timestamp: started.toISOString(), ordinal: ordinal++, type: "session_meta", payload: { account_scoped: true, session_id: id, id, timestamp: started.toISOString(), cwd, runtime_workspace_roots: [cwd], originator: "agentlens-import", cli_version: "0.169.0", title: transcript.title || "DSH 导入会话", imported_from: "dsh", dsh_session_id: transcript.id, }, }); for (const entry of transcript.entries) { if (entry.who !== "用户" && entry.who !== "助手") continue; const when = entry.time ? new Date(entry.time) : started; lines.push({ timestamp: when.toISOString(), ordinal: ordinal++, type: "response_item", payload: { type: "message", id: `msg_${randomUUID()}`, role: entry.who === "用户" ? "user" : "assistant", content: [ { type: entry.who === "用户" ? "input_text" : "output_text", text: entry.text, }, ], }, }); } return { id, timestamp: started, content: lines.map((l) => JSON.stringify(l)).join("\n") + "\n" }; } /** Write a rollout file into ~/.codex/sessions/YYYY/MM/DD/. */ export function writeRollout(id: string, timestamp: Date, content: string): string { const y = String(timestamp.getFullYear()); const m = String(timestamp.getMonth() + 1).padStart(2, "0"); const d = String(timestamp.getDate()).padStart(2, "0"); const dir = join(SESSIONS_DIR, y, m, d); mkdirSync(dir, { recursive: true }); const stamp = timestamp.toISOString().replace(/[:.]/g, "-").slice(0, 19); const file = join(dir, `rollout-${stamp}-${id}.jsonl`); writeFileSync(file, content, "utf8"); return file; } /** Insert a row into the Codex threads table so it shows in the sidebar. */ export function insertThreadRow(options: { id: string; rolloutPath: string; timestamp: Date; cwd: string; title: string; firstUserMessage: string; }): void { const sec = Math.floor(options.timestamp.getTime() / 1000); const ms = options.timestamp.getTime(); const title = options.title || "DSH 导入会话"; const preview = options.firstUserMessage.slice(0, 200); const sql = ` PRAGMA busy_timeout = 5000; INSERT OR REPLACE INTO threads ( id, rollout_path, created_at, updated_at, source, model_provider, cwd, title, sandbox_policy, approval_mode, tokens_used, has_user_event, archived, cli_version, first_user_message, preview, recency_at, recency_at_ms, created_at_ms, updated_at_ms, history_mode, originator ) VALUES ( ${q(options.id)}, ${q(options.rolloutPath)}, ${sec}, ${sec}, 'vscode', 'custom', ${q(options.cwd)}, ${q(title)}, '{"type":"disabled"}', 'never', 0, 1, 0, '0.169.0', ${q(options.firstUserMessage.slice(0, 8000))}, ${q(preview)}, ${sec}, ${ms}, ${ms}, ${ms}, 'legacy', 'agentlens-import' );`; runSql(STATE_DB, sql); } export interface ThreadImportResult { imported: number; failures: number; codexWasRunning: boolean; } /** * Import DSH transcripts into Codex's thread list (sidebar). * Each transcript becomes a rollout file + a threads row. */ export function importCodexThreads(transcripts: SessionTranscript[]): ThreadImportResult { let imported = 0; let failures = 0; const wasRunning = codexRunning(); if (!codexStateExists()) { return { imported: 0, failures: transcripts.length, codexWasRunning: wasRunning }; } for (const t of transcripts) { try { const { id, timestamp, content } = buildRollout(t); const path = writeRollout(id, timestamp, content); insertThreadRow({ id, rolloutPath: path, timestamp, cwd: t.cwd || join(HOME, "Documents", "Codex"), title: t.title || "DSH 导入会话", firstUserMessage: t.entries.find((e) => e.who === "用户")?.text ?? "", }); imported++; } catch { failures++; } } return { imported, failures, codexWasRunning: wasRunning }; }