File size: 5,716 Bytes
8db9296
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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<string, unknown>;
}

/** 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 };
}