hongcoding commited on
Commit
11e2b39
·
verified ·
1 Parent(s): 12880e4

feat: full conversation migration (266 sessions / 70k messages) with robust parsing

Browse files
src/cli/commands/export.ts CHANGED
@@ -31,6 +31,9 @@ export async function exportData(opts: ExportOpts): Promise<void> {
31
  if (result.conversationFiles > 0) {
32
  console.log(` ✅ 对话记录:${result.conversationFiles} 个会话,${result.conversationLines} 条消息 → conversations/`);
33
  }
 
 
 
34
  console.log(`\n导出完成:${result.outDir}`);
35
  console.log("把这个目录放进任何 AI Agent 的项目里,它就能读取你的人物设定、资料和对话。");
36
  }
 
31
  if (result.conversationFiles > 0) {
32
  console.log(` ✅ 对话记录:${result.conversationFiles} 个会话,${result.conversationLines} 条消息 → conversations/`);
33
  }
34
+ if (result.conversationFailures > 0) {
35
+ console.log(` ⚠ ${result.conversationFailures} 个会话文件无法读取(已跳过,不影响其他数据)`);
36
+ }
37
  console.log(`\n导出完成:${result.outDir}`);
38
  console.log("把这个目录放进任何 AI Agent 的项目里,它就能读取你的人物设定、资料和对话。");
39
  }
src/export/dsh.ts CHANGED
@@ -2,6 +2,7 @@ import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, writeFileSy
2
  import { homedir } from "node:os";
3
  import { join, resolve } from "node:path";
4
  import { execFileSync } from "node:child_process";
 
5
 
6
  export interface Persona {
7
  id: string;
@@ -27,6 +28,7 @@ export interface DshExportResult {
27
  materialsBytes: number;
28
  conversationFiles: number;
29
  conversationLines: number;
 
30
  attachmentsCopied: boolean;
31
  outDir: string;
32
  }
@@ -216,10 +218,17 @@ export function exportDsh(options: DshExportOptions): DshExportResult {
216
 
217
  let conversationFiles = 0;
218
  let conversationLines = 0;
 
219
  if (options.withConversations !== false) {
220
- const r = exportConversations(outDir);
221
- conversationFiles = r.files;
222
- conversationLines = r.lines;
 
 
 
 
 
 
223
  }
224
 
225
  writeFileSync(
@@ -245,6 +254,7 @@ export function exportDsh(options: DshExportOptions): DshExportResult {
245
  materialsBytes: materialBytes,
246
  conversationFiles,
247
  conversationLines,
 
248
  attachmentsCopied: options.withAttachments === true,
249
  outDir,
250
  };
 
2
  import { homedir } from "node:os";
3
  import { join, resolve } from "node:path";
4
  import { execFileSync } from "node:child_process";
5
+ import { exportSessionTranscripts } from "./sessions.js";
6
 
7
  export interface Persona {
8
  id: string;
 
28
  materialsBytes: number;
29
  conversationFiles: number;
30
  conversationLines: number;
31
+ conversationFailures: number;
32
  attachmentsCopied: boolean;
33
  outDir: string;
34
  }
 
218
 
219
  let conversationFiles = 0;
220
  let conversationLines = 0;
221
+ let conversationFailures = 0;
222
  if (options.withConversations !== false) {
223
+ // Full session transcripts first (rich: user/assistant/tool events)…
224
+ const sessions = exportSessionTranscripts(outDir);
225
+ conversationFiles += sessions.files;
226
+ conversationLines += sessions.messages;
227
+ conversationFailures += sessions.failures;
228
+ // …then chat-index lines (bot conversations not covered by session files).
229
+ const fallback = exportConversations(outDir);
230
+ conversationFiles += fallback.files;
231
+ conversationLines += fallback.lines;
232
  }
233
 
234
  writeFileSync(
 
254
  materialsBytes: materialBytes,
255
  conversationFiles,
256
  conversationLines,
257
+ conversationFailures,
258
  attachmentsCopied: options.withAttachments === true,
259
  outDir,
260
  };
src/export/sessions.ts ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { existsSync, readdirSync, statSync, 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
+
6
+ /** One rendered message in a transcript. */
7
+ export interface TranscriptEntry {
8
+ who: "用户" | "助手" | "工具" | "系统";
9
+ time?: number;
10
+ text: string;
11
+ }
12
+
13
+ export interface SessionTranscript {
14
+ id: string;
15
+ title: string;
16
+ cwd?: string;
17
+ createdAt?: number;
18
+ entries: TranscriptEntry[];
19
+ }
20
+
21
+ const HOME = homedir();
22
+ const TOOL_OUTPUT_MAX = 400;
23
+
24
+ /** Locate a zstd binary; falls back to undefined (node zlib handles single frames). */
25
+ function zstdBinary(): string | undefined {
26
+ for (const candidate of ["/opt/homebrew/bin/zstd", "/usr/local/bin/zstd", "/usr/bin/zstd"]) {
27
+ if (existsSync(candidate)) return candidate;
28
+ }
29
+ return "zstd";
30
+ }
31
+
32
+ /** Decompress a session file. Handles multi-frame files via the zstd CLI. */
33
+ export function readSessionFile(file: string): string {
34
+ const bin = zstdBinary();
35
+ if (bin) {
36
+ try {
37
+ return execFileSync(bin, ["-dc", file], {
38
+ encoding: "utf8",
39
+ maxBuffer: 512 * 1024 * 1024,
40
+ });
41
+ } catch {
42
+ // fall through to zlib
43
+ }
44
+ }
45
+ try {
46
+ const zlib = require("node:zlib");
47
+ if (typeof zlib.zstdDecompressSync === "function") {
48
+ return zlib.zstdDecompressSync(require("node:fs").readFileSync(file)).toString("utf8");
49
+ }
50
+ } catch {
51
+ // give up
52
+ }
53
+ return "";
54
+ }
55
+
56
+ function textOf(content: unknown): string {
57
+ if (!Array.isArray(content)) return "";
58
+ const parts: string[] = [];
59
+ for (const part of content) {
60
+ if (part && typeof part === "object" && (part as any).type === "text" && typeof (part as any).text === "string") {
61
+ parts.push((part as any).text);
62
+ }
63
+ }
64
+ return parts.join("\n").trim();
65
+ }
66
+
67
+ /** Parse raw JSONL lines (v4 session format) into a transcript. */
68
+ export function parseSessionLines(raw: string): SessionTranscript | undefined {
69
+ const lines = raw.split("\n");
70
+ let id = "";
71
+ let title = "";
72
+ let cwd: string | undefined;
73
+ let createdAt: number | undefined;
74
+ const entries: TranscriptEntry[] = [];
75
+
76
+ for (const line of lines) {
77
+ if (!line.trim()) continue;
78
+ let event: any;
79
+ try {
80
+ event = JSON.parse(line);
81
+ } catch {
82
+ continue;
83
+ }
84
+ switch (event?.type) {
85
+ case "session":
86
+ id = String(event.id ?? "");
87
+ cwd = typeof event.cwd === "string" ? event.cwd : undefined;
88
+ createdAt = Number(event.createdAt ?? 0) || undefined;
89
+ break;
90
+ case "session/title":
91
+ title = String(event?.data?.title ?? "");
92
+ break;
93
+ case "user/message": {
94
+ const text = textOf(event?.data?.content);
95
+ const kind = event?.data?.source?.kind;
96
+ // Skip harness-injected context (system reminders, tool notes).
97
+ if (!text || kind !== "user" || text.startsWith("<system-reminder>")) break;
98
+ entries.push({ who: "用户", time: Number(event.time) || undefined, text });
99
+ break;
100
+ }
101
+ case "assistant/message": {
102
+ const text = textOf(event?.data?.message?.content);
103
+ if (text) entries.push({ who: "助手", time: Number(event.time) || undefined, text });
104
+ break;
105
+ }
106
+ case "tool/call": {
107
+ const name = String(event?.data?.name ?? "tool");
108
+ let args = String(event?.data?.arguments ?? "");
109
+ if (args.length > TOOL_OUTPUT_MAX) args = args.slice(0, TOOL_OUTPUT_MAX) + "…";
110
+ entries.push({ who: "工具", time: Number(event.time) || undefined, text: `${name} ${args}`.trim() });
111
+ break;
112
+ }
113
+ case "tool/result": {
114
+ const text = textOf(event?.data?.message?.content);
115
+ if (text) {
116
+ const clipped = text.length > TOOL_OUTPUT_MAX ? text.slice(0, TOOL_OUTPUT_MAX) + "…" : text;
117
+ entries.push({ who: "工具", time: Number(event.time) || undefined, text: clipped });
118
+ }
119
+ break;
120
+ }
121
+ case "system/message":
122
+ case "developer/message": {
123
+ const text = textOf(event?.data?.content);
124
+ if (text) entries.push({ who: "系统", time: Number(event.time) || undefined, text });
125
+ break;
126
+ }
127
+ default:
128
+ break;
129
+ }
130
+ }
131
+
132
+ if (entries.length === 0) return undefined;
133
+ return { id, title, cwd, createdAt, entries };
134
+ }
135
+
136
+ /** Every session file under ~/.dsh/sessions. */
137
+ function listSessionFiles(): string[] {
138
+ const root = join(HOME, ".dsh", "sessions");
139
+ if (!existsSync(root)) return [];
140
+ const files: string[] = [];
141
+ const walk = (dir: string) => {
142
+ let names: string[] = [];
143
+ try {
144
+ names = readdirSync(dir);
145
+ } catch {
146
+ return;
147
+ }
148
+ for (const name of names) {
149
+ const p = join(dir, name);
150
+ let st;
151
+ try {
152
+ st = statSync(p);
153
+ } catch {
154
+ continue;
155
+ }
156
+ if (st.isDirectory()) walk(p);
157
+ else if (/^session.*\.jsonl\.zstd$/.test(name)) files.push(p);
158
+ }
159
+ };
160
+ walk(root);
161
+ return files;
162
+ }
163
+
164
+ function slug(text: string, fallback: string): string {
165
+ const cleaned = text.replace(/[^\w\u4e00-\u9fff-]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40);
166
+ return cleaned || fallback;
167
+ }
168
+
169
+ function renderTranscript(t: SessionTranscript): string {
170
+ const head: string[] = [`# ${t.title || "未命名会话"}`, ""];
171
+ if (t.id) head.push(`- 会话 ID:${t.id}`);
172
+ if (t.cwd) head.push(`- 工作目录:${t.cwd}`);
173
+ if (t.createdAt) head.push(`- 创建时间:${new Date(t.createdAt).toISOString()}`);
174
+ head.push(`- 消息数:${t.entries.length}`);
175
+ head.push("");
176
+ const body: string[] = [];
177
+ for (const e of t.entries) {
178
+ const when = e.time ? ` ${new Date(e.time).toISOString()}` : "";
179
+ body.push(`## ${e.who}${when}`);
180
+ body.push("");
181
+ body.push(e.text);
182
+ body.push("");
183
+ }
184
+ return head.concat(body).join("\n");
185
+ }
186
+
187
+ export interface SessionsExportResult {
188
+ files: number;
189
+ sessions: number;
190
+ messages: number;
191
+ failures: number;
192
+ }
193
+
194
+ /**
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);
210
+ if (!raw) {
211
+ failures++;
212
+ continue;
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
+ }
tests/sessions.test.ts ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, it, expect } from "vitest";
2
+ import { parseSessionLines } from "../src/export/sessions.js";
3
+
4
+ function jsonl(events: unknown[]): string {
5
+ return events.map((e) => JSON.stringify(e)).join("\n");
6
+ }
7
+
8
+ describe("parseSessionLines", () => {
9
+ it("parses title, user, assistant and tool events", () => {
10
+ const raw = jsonl([
11
+ { type: "session", id: "s1", cwd: "/p", createdAt: 1000 },
12
+ { type: "session/title", data: { title: "测试会话" } },
13
+ { type: "user/message", time: 2000, data: { source: { kind: "user" }, content: [{ type: "text", text: "你好" }] } },
14
+ { type: "assistant/message", time: 3000, data: { message: { content: [{ type: "text", text: "你好,有什么可以帮你?" }] } } },
15
+ { type: "tool/call", time: 4000, data: { name: "bash", arguments: '{"command":"ls"}' } },
16
+ { type: "tool/result", time: 5000, data: { message: { content: [{ type: "text", text: "file.txt" }] } } },
17
+ ]);
18
+ const t = parseSessionLines(raw)!;
19
+ expect(t).toBeDefined();
20
+ expect(t.title).toBe("测试会话");
21
+ expect(t.cwd).toBe("/p");
22
+ const who = t.entries.map((e) => e.who);
23
+ expect(who).toEqual(["用户", "助手", "工具", "工具"]);
24
+ expect(t.entries[0].text).toBe("你好");
25
+ });
26
+
27
+ it("skips system-reminder injections", () => {
28
+ const raw = jsonl([
29
+ { type: "session", id: "s1" },
30
+ { type: "user/message", data: { source: { kind: "user" }, content: [{ type: "text", text: "<system-reminder>workspace instructions</system-reminder>" }] } },
31
+ { type: "user/message", data: { source: { kind: "harness" }, content: [{ type: "text", text: "injected" }] } },
32
+ { type: "user/message", data: { source: { kind: "user" }, content: [{ type: "text", text: "真实消息" }] } },
33
+ ]);
34
+ const t = parseSessionLines(raw)!;
35
+ expect(t.entries.length).toBe(1);
36
+ expect(t.entries[0].text).toBe("真实消息");
37
+ });
38
+
39
+ it("returns undefined for sessions with no renderable messages", () => {
40
+ const raw = jsonl([{ type: "session", id: "empty" }]);
41
+ expect(parseSessionLines(raw)).toBeUndefined();
42
+ });
43
+
44
+ it("ignores malformed lines without throwing", () => {
45
+ const raw = "{bad json}\n" + jsonl([{ type: "user/message", data: { source: { kind: "user" }, content: [{ type: "text", text: "ok" }] } }]);
46
+ const t = parseSessionLines(raw)!;
47
+ expect(t.entries.length).toBe(1);
48
+ });
49
+ });