hongcoding commited on
Commit
8db9296
·
verified ·
1 Parent(s): 4ce05b9

feat: DSH conversations imported into Codex sidebar (rollout files + threads rows)

Browse files
src/cli/commands/import.ts CHANGED
@@ -30,5 +30,10 @@ export async function importData(opts: ImportOpts): Promise<void> {
30
  console.log(` ✅ 全局指令:${r.instructionsFile}(已写入导入段落,幂等)`);
31
  if (r.skillFile) console.log(` ✅ Skill:${r.skillFile}`);
32
  console.log(`\n 人设 ${r.personas} 个 · 模型配置已导出 · 对话 ${r.conversations} 条 · 文件 ${(r.materialsBytes / 1024 / 1024).toFixed(1)} MB`);
 
 
 
 
 
33
  console.log(`\n重启 ${opts.to} 后,它会自动读取这些资料。`);
34
  }
 
30
  console.log(` ✅ 全局指令:${r.instructionsFile}(已写入导入段落,幂等)`);
31
  if (r.skillFile) console.log(` ✅ Skill:${r.skillFile}`);
32
  console.log(`\n 人设 ${r.personas} 个 · 模型配置已导出 · 对话 ${r.conversations} 条 · 文件 ${(r.materialsBytes / 1024 / 1024).toFixed(1)} MB`);
33
+ if (r.threads) {
34
+ console.log(` ✅ Codex 侧栏:${r.threads.imported} 个会话已写入(重启 Codex 可见)`);
35
+ if (r.threads.failures > 0) console.log(` ⚠ ${r.threads.failures} 个会话写入失败(已跳过)`);
36
+ if (r.threads.codexWasRunning) console.log(" 💡 Codex 正在运行,可能需要重启才能看到新会话");
37
+ }
38
  console.log(`\n重启 ${opts.to} 后,它会自动读取这些资料。`);
39
  }
src/export/sessions.ts CHANGED
@@ -195,15 +195,9 @@ export interface SessionsExportResult {
195
  * Export every full session transcript to <outDir>/conversations.
196
  * Never throws: unreadable or malformed sessions are counted as failures.
197
  */
198
- export function exportSessionTranscripts(outDir: string): SessionsExportResult {
199
- const dir = join(outDir, "conversations");
200
- mkdirSync(dir, { recursive: true });
201
-
202
- let sessions = 0;
203
- let messages = 0;
204
  let failures = 0;
205
- let files = 0;
206
-
207
  for (const file of listSessionFiles()) {
208
  try {
209
  const raw = readSessionFile(file);
@@ -213,15 +207,28 @@ export function exportSessionTranscripts(outDir: string): SessionsExportResult {
213
  }
214
  const transcript = parseSessionLines(raw);
215
  if (!transcript) continue;
216
- const name = `${slug(transcript.title, "session")}__${slug(transcript.id, "unknown")}.md`;
217
- writeFileSync(join(dir, name), renderTranscript(transcript), "utf8");
218
- sessions++;
219
- messages += transcript.entries.length;
220
- files++;
221
  } catch {
222
  failures++;
223
  }
224
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
 
226
- return { files, sessions, messages, failures };
227
  }
 
195
  * Export every full session transcript to <outDir>/conversations.
196
  * Never throws: unreadable or malformed sessions are counted as failures.
197
  */
198
+ export function collectSessionTranscripts(): { transcripts: SessionTranscript[]; failures: number } {
199
+ const transcripts: SessionTranscript[] = [];
 
 
 
 
200
  let failures = 0;
 
 
201
  for (const file of listSessionFiles()) {
202
  try {
203
  const raw = readSessionFile(file);
 
207
  }
208
  const transcript = parseSessionLines(raw);
209
  if (!transcript) continue;
210
+ transcripts.push(transcript);
 
 
 
 
211
  } catch {
212
  failures++;
213
  }
214
  }
215
+ return { transcripts, failures };
216
+ }
217
+
218
+ export function exportSessionTranscripts(outDir: string): SessionsExportResult {
219
+ const dir = join(outDir, "conversations");
220
+ mkdirSync(dir, { recursive: true });
221
+
222
+ const { transcripts, failures } = collectSessionTranscripts();
223
+ let messages = 0;
224
+ let files = 0;
225
+
226
+ for (const transcript of transcripts) {
227
+ const name = `${slug(transcript.title, "session")}__${slug(transcript.id, "unknown")}.md`;
228
+ writeFileSync(join(dir, name), renderTranscript(transcript), "utf8");
229
+ messages += transcript.entries.length;
230
+ files++;
231
+ }
232
 
233
+ return { files, sessions: files, messages, failures };
234
  }
src/import/codex-threads.ts ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { execFileSync } from "node:child_process";
5
+ import { randomUUID } from "node:crypto";
6
+ import type { SessionTranscript } from "../export/sessions.js";
7
+
8
+ const HOME = homedir();
9
+ const STATE_DB = join(HOME, ".codex", "state_5.sqlite");
10
+ const SESSIONS_DIR = join(HOME, ".codex", "sessions");
11
+ const SQLITE = "/usr/bin/sqlite3";
12
+
13
+ /** Escape a value for a single-quoted SQL literal. */
14
+ function q(value: string): string {
15
+ return "'" + String(value).replace(/'/g, "''") + "'";
16
+ }
17
+
18
+ function runSql(db: string, sql: string): string {
19
+ return execFileSync(SQLITE, [db, sql], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
20
+ }
21
+
22
+ export function codexStateExists(): boolean {
23
+ return existsSync(STATE_DB);
24
+ }
25
+
26
+ /** Whether the Codex app/CLI is currently running. */
27
+ export function codexRunning(): boolean {
28
+ try {
29
+ const out = execFileSync("pgrep", ["-fl", "Codex"], { encoding: "utf8" });
30
+ return out.split("\n").some((l) => l && !l.includes("agentlens") && /Codex/i.test(l));
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+
36
+ interface RolloutLine {
37
+ timestamp: string;
38
+ ordinal: number;
39
+ type: "session_meta" | "response_item";
40
+ payload: Record<string, unknown>;
41
+ }
42
+
43
+ /** Build a Codex-compatible rollout JSONL for one DSH transcript. */
44
+ export function buildRollout(transcript: SessionTranscript): { id: string; timestamp: Date; content: string } {
45
+ const id = randomUUID();
46
+ const started = transcript.createdAt ? new Date(transcript.createdAt) : new Date();
47
+ const cwd = transcript.cwd || join(HOME, "Documents", "Codex");
48
+ const lines: RolloutLine[] = [];
49
+ let ordinal = 0;
50
+
51
+ lines.push({
52
+ timestamp: started.toISOString(),
53
+ ordinal: ordinal++,
54
+ type: "session_meta",
55
+ payload: {
56
+ account_scoped: true,
57
+ session_id: id,
58
+ id,
59
+ timestamp: started.toISOString(),
60
+ cwd,
61
+ runtime_workspace_roots: [cwd],
62
+ originator: "agentlens-import",
63
+ cli_version: "0.169.0",
64
+ title: transcript.title || "DSH 导入会话",
65
+ imported_from: "dsh",
66
+ dsh_session_id: transcript.id,
67
+ },
68
+ });
69
+
70
+ for (const entry of transcript.entries) {
71
+ if (entry.who !== "用户" && entry.who !== "助手") continue;
72
+ const when = entry.time ? new Date(entry.time) : started;
73
+ lines.push({
74
+ timestamp: when.toISOString(),
75
+ ordinal: ordinal++,
76
+ type: "response_item",
77
+ payload: {
78
+ type: "message",
79
+ id: `msg_${randomUUID()}`,
80
+ role: entry.who === "用户" ? "user" : "assistant",
81
+ content: [
82
+ {
83
+ type: entry.who === "用户" ? "input_text" : "output_text",
84
+ text: entry.text,
85
+ },
86
+ ],
87
+ },
88
+ });
89
+ }
90
+
91
+ return { id, timestamp: started, content: lines.map((l) => JSON.stringify(l)).join("\n") + "\n" };
92
+ }
93
+
94
+ /** Write a rollout file into ~/.codex/sessions/YYYY/MM/DD/. */
95
+ export function writeRollout(id: string, timestamp: Date, content: string): string {
96
+ const y = String(timestamp.getFullYear());
97
+ const m = String(timestamp.getMonth() + 1).padStart(2, "0");
98
+ const d = String(timestamp.getDate()).padStart(2, "0");
99
+ const dir = join(SESSIONS_DIR, y, m, d);
100
+ mkdirSync(dir, { recursive: true });
101
+ const stamp = timestamp.toISOString().replace(/[:.]/g, "-").slice(0, 19);
102
+ const file = join(dir, `rollout-${stamp}-${id}.jsonl`);
103
+ writeFileSync(file, content, "utf8");
104
+ return file;
105
+ }
106
+
107
+ /** Insert a row into the Codex threads table so it shows in the sidebar. */
108
+ export function insertThreadRow(options: {
109
+ id: string;
110
+ rolloutPath: string;
111
+ timestamp: Date;
112
+ cwd: string;
113
+ title: string;
114
+ firstUserMessage: string;
115
+ }): void {
116
+ const sec = Math.floor(options.timestamp.getTime() / 1000);
117
+ const ms = options.timestamp.getTime();
118
+ const title = options.title || "DSH 导入会话";
119
+ const preview = options.firstUserMessage.slice(0, 200);
120
+ const sql = `
121
+ PRAGMA busy_timeout = 5000;
122
+ INSERT OR REPLACE INTO threads (
123
+ id, rollout_path, created_at, updated_at, source, model_provider, cwd, title,
124
+ sandbox_policy, approval_mode, tokens_used, has_user_event, archived,
125
+ cli_version, first_user_message, preview, recency_at, recency_at_ms,
126
+ created_at_ms, updated_at_ms, history_mode, originator
127
+ ) VALUES (
128
+ ${q(options.id)}, ${q(options.rolloutPath)}, ${sec}, ${sec}, 'vscode', 'custom',
129
+ ${q(options.cwd)}, ${q(title)}, '{"type":"disabled"}', 'never', 0, 1, 0,
130
+ '0.169.0', ${q(options.firstUserMessage.slice(0, 8000))}, ${q(preview)}, ${sec}, ${ms},
131
+ ${ms}, ${ms}, 'legacy', 'agentlens-import'
132
+ );`;
133
+ runSql(STATE_DB, sql);
134
+ }
135
+
136
+ export interface ThreadImportResult {
137
+ imported: number;
138
+ failures: number;
139
+ codexWasRunning: boolean;
140
+ }
141
+
142
+ /**
143
+ * Import DSH transcripts into Codex's thread list (sidebar).
144
+ * Each transcript becomes a rollout file + a threads row.
145
+ */
146
+ export function importCodexThreads(transcripts: SessionTranscript[]): ThreadImportResult {
147
+ let imported = 0;
148
+ let failures = 0;
149
+ const wasRunning = codexRunning();
150
+
151
+ if (!codexStateExists()) {
152
+ return { imported: 0, failures: transcripts.length, codexWasRunning: wasRunning };
153
+ }
154
+
155
+ for (const t of transcripts) {
156
+ try {
157
+ const { id, timestamp, content } = buildRollout(t);
158
+ const path = writeRollout(id, timestamp, content);
159
+ insertThreadRow({
160
+ id,
161
+ rolloutPath: path,
162
+ timestamp,
163
+ cwd: t.cwd || join(HOME, "Documents", "Codex"),
164
+ title: t.title || "DSH 导入会话",
165
+ firstUserMessage: t.entries.find((e) => e.who === "用户")?.text ?? "",
166
+ });
167
+ imported++;
168
+ } catch {
169
+ failures++;
170
+ }
171
+ }
172
+
173
+ return { imported, failures, codexWasRunning: wasRunning };
174
+ }
src/import/dsh-import.ts CHANGED
@@ -2,6 +2,8 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
2
  import { homedir } from "node:os";
3
  import { dirname, join } from "node:path";
4
  import { exportDsh } from "../export/dsh.js";
 
 
5
 
6
  export type ImportTarget = "codex" | "claude" | "zcode" | "workbuddy" | "mimo";
7
 
@@ -38,6 +40,8 @@ export interface DshImportResult {
38
  personas: number;
39
  conversations: number;
40
  materialsBytes: number;
 
 
41
  }
42
 
43
  function sectionFor(dataDir: string): string {
@@ -122,6 +126,18 @@ export function importDsh(options: DshImportOptions): DshImportResult {
122
  mergeInstructions(spec.instructionsFile, dataDir);
123
  const skillFile = writeSkill(spec.skillsDir, dataDir);
124
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  return {
126
  target: options.target,
127
  dataDir,
@@ -130,5 +146,6 @@ export function importDsh(options: DshImportOptions): DshImportResult {
130
  personas: result.personas,
131
  conversations: result.conversationLines,
132
  materialsBytes: result.materialsBytes,
 
133
  };
134
  }
 
2
  import { homedir } from "node:os";
3
  import { dirname, join } from "node:path";
4
  import { exportDsh } from "../export/dsh.js";
5
+ import { collectSessionTranscripts } from "../export/sessions.js";
6
+ import { importCodexThreads } from "./codex-threads.js";
7
 
8
  export type ImportTarget = "codex" | "claude" | "zcode" | "workbuddy" | "mimo";
9
 
 
40
  personas: number;
41
  conversations: number;
42
  materialsBytes: number;
43
+ /** Codex only: threads written into the app sidebar. */
44
+ threads?: { imported: number; failures: number; codexWasRunning: boolean };
45
  }
46
 
47
  function sectionFor(dataDir: string): string {
 
126
  mergeInstructions(spec.instructionsFile, dataDir);
127
  const skillFile = writeSkill(spec.skillsDir, dataDir);
128
 
129
+ // Codex additionally gets real thread rows so the conversations show up in
130
+ // the app's sidebar, not just as files.
131
+ let threads;
132
+ if (options.target === "codex") {
133
+ try {
134
+ const { transcripts } = collectSessionTranscripts();
135
+ threads = importCodexThreads(transcripts);
136
+ } catch {
137
+ threads = { imported: 0, failures: 0, codexWasRunning: false };
138
+ }
139
+ }
140
+
141
  return {
142
  target: options.target,
143
  dataDir,
 
146
  personas: result.personas,
147
  conversations: result.conversationLines,
148
  materialsBytes: result.materialsBytes,
149
+ threads,
150
  };
151
  }
tests/codex-threads.test.ts ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, it, expect } from "vitest";
2
+ import { buildRollout } from "../src/import/codex-threads.js";
3
+ import type { SessionTranscript } from "../src/export/sessions.js";
4
+
5
+ const transcript: SessionTranscript = {
6
+ id: "dsh-123",
7
+ title: "测试导入会话",
8
+ cwd: "/Users/x/project",
9
+ createdAt: 1700000000000,
10
+ entries: [
11
+ { who: "用户", time: 1700000001000, text: "你好" },
12
+ { who: "助手", time: 1700000002000, text: "你好,有什么可以帮你?" },
13
+ { who: "工具", time: 1700000003000, text: "bash ls" },
14
+ { who: "用户", time: 1700000004000, text: "谢谢" },
15
+ ],
16
+ };
17
+
18
+ describe("buildRollout", () => {
19
+ it("emits a session_meta line with a UUID and cwd", () => {
20
+ const { id, content } = buildRollout(transcript);
21
+ const lines = content.trim().split("\n").map((l) => JSON.parse(l));
22
+ expect(lines[0].type).toBe("session_meta");
23
+ expect(lines[0].payload.session_id).toBe(id);
24
+ expect(lines[0].payload.cwd).toBe("/Users/x/project");
25
+ expect(lines[0].payload.imported_from).toBe("dsh");
26
+ expect(lines[0].payload.dsh_session_id).toBe("dsh-123");
27
+ });
28
+
29
+ it("emits user/assistant message items and skips tool entries", () => {
30
+ const { content } = buildRollout(transcript);
31
+ const lines = content.trim().split("\n").map((l) => JSON.parse(l));
32
+ const messages = lines.filter((l) => l.type === "response_item");
33
+ expect(messages.length).toBe(3);
34
+ expect(messages[0].payload.role).toBe("user");
35
+ expect(messages[0].payload.content[0].type).toBe("input_text");
36
+ expect(messages[1].payload.role).toBe("assistant");
37
+ expect(messages[1].payload.content[0].type).toBe("output_text");
38
+ expect(messages[2].payload.content[0].text).toBe("谢谢");
39
+ });
40
+
41
+ it("assigns increasing ordinals", () => {
42
+ const { content } = buildRollout(transcript);
43
+ const ordinals = content.trim().split("\n").map((l) => JSON.parse(l).ordinal);
44
+ expect(ordinals).toEqual([...ordinals].sort((a, b) => a - b));
45
+ expect(new Set(ordinals).size).toBe(ordinals.length);
46
+ });
47
+ });