File size: 7,222 Bytes
11e2b39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8db9296
 
11e2b39
 
 
 
 
 
 
 
 
 
8db9296
11e2b39
 
 
 
8db9296
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11e2b39
8db9296
11e2b39
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import { existsSync, readdirSync, statSync, mkdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { execFileSync } from "node:child_process";

/** One rendered message in a transcript. */
export interface TranscriptEntry {
  who: "用户" | "助手" | "工具" | "系统";
  time?: number;
  text: string;
}

export interface SessionTranscript {
  id: string;
  title: string;
  cwd?: string;
  createdAt?: number;
  entries: TranscriptEntry[];
}

const HOME = homedir();
const TOOL_OUTPUT_MAX = 400;

/** Locate a zstd binary; falls back to undefined (node zlib handles single frames). */
function zstdBinary(): string | undefined {
  for (const candidate of ["/opt/homebrew/bin/zstd", "/usr/local/bin/zstd", "/usr/bin/zstd"]) {
    if (existsSync(candidate)) return candidate;
  }
  return "zstd";
}

/** Decompress a session file. Handles multi-frame files via the zstd CLI. */
export function readSessionFile(file: string): string {
  const bin = zstdBinary();
  if (bin) {
    try {
      return execFileSync(bin, ["-dc", file], {
        encoding: "utf8",
        maxBuffer: 512 * 1024 * 1024,
      });
    } catch {
      // fall through to zlib
    }
  }
  try {
    const zlib = require("node:zlib");
    if (typeof zlib.zstdDecompressSync === "function") {
      return zlib.zstdDecompressSync(require("node:fs").readFileSync(file)).toString("utf8");
    }
  } catch {
    // give up
  }
  return "";
}

function textOf(content: unknown): string {
  if (!Array.isArray(content)) return "";
  const parts: string[] = [];
  for (const part of content) {
    if (part && typeof part === "object" && (part as any).type === "text" && typeof (part as any).text === "string") {
      parts.push((part as any).text);
    }
  }
  return parts.join("\n").trim();
}

/** Parse raw JSONL lines (v4 session format) into a transcript. */
export function parseSessionLines(raw: string): SessionTranscript | undefined {
  const lines = raw.split("\n");
  let id = "";
  let title = "";
  let cwd: string | undefined;
  let createdAt: number | undefined;
  const entries: TranscriptEntry[] = [];

  for (const line of lines) {
    if (!line.trim()) continue;
    let event: any;
    try {
      event = JSON.parse(line);
    } catch {
      continue;
    }
    switch (event?.type) {
      case "session":
        id = String(event.id ?? "");
        cwd = typeof event.cwd === "string" ? event.cwd : undefined;
        createdAt = Number(event.createdAt ?? 0) || undefined;
        break;
      case "session/title":
        title = String(event?.data?.title ?? "");
        break;
      case "user/message": {
        const text = textOf(event?.data?.content);
        const kind = event?.data?.source?.kind;
        // Skip harness-injected context (system reminders, tool notes).
        if (!text || kind !== "user" || text.startsWith("<system-reminder>")) break;
        entries.push({ who: "用户", time: Number(event.time) || undefined, text });
        break;
      }
      case "assistant/message": {
        const text = textOf(event?.data?.message?.content);
        if (text) entries.push({ who: "助手", time: Number(event.time) || undefined, text });
        break;
      }
      case "tool/call": {
        const name = String(event?.data?.name ?? "tool");
        let args = String(event?.data?.arguments ?? "");
        if (args.length > TOOL_OUTPUT_MAX) args = args.slice(0, TOOL_OUTPUT_MAX) + "…";
        entries.push({ who: "工具", time: Number(event.time) || undefined, text: `${name} ${args}`.trim() });
        break;
      }
      case "tool/result": {
        const text = textOf(event?.data?.message?.content);
        if (text) {
          const clipped = text.length > TOOL_OUTPUT_MAX ? text.slice(0, TOOL_OUTPUT_MAX) + "…" : text;
          entries.push({ who: "工具", time: Number(event.time) || undefined, text: clipped });
        }
        break;
      }
      case "system/message":
      case "developer/message": {
        const text = textOf(event?.data?.content);
        if (text) entries.push({ who: "系统", time: Number(event.time) || undefined, text });
        break;
      }
      default:
        break;
    }
  }

  if (entries.length === 0) return undefined;
  return { id, title, cwd, createdAt, entries };
}

/** Every session file under ~/.dsh/sessions. */
function listSessionFiles(): string[] {
  const root = join(HOME, ".dsh", "sessions");
  if (!existsSync(root)) return [];
  const files: string[] = [];
  const walk = (dir: string) => {
    let names: string[] = [];
    try {
      names = readdirSync(dir);
    } catch {
      return;
    }
    for (const name of names) {
      const p = join(dir, name);
      let st;
      try {
        st = statSync(p);
      } catch {
        continue;
      }
      if (st.isDirectory()) walk(p);
      else if (/^session.*\.jsonl\.zstd$/.test(name)) files.push(p);
    }
  };
  walk(root);
  return files;
}

function slug(text: string, fallback: string): string {
  const cleaned = text.replace(/[^\w\u4e00-\u9fff-]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40);
  return cleaned || fallback;
}

function renderTranscript(t: SessionTranscript): string {
  const head: string[] = [`# ${t.title || "未命名会话"}`, ""];
  if (t.id) head.push(`- 会话 ID:${t.id}`);
  if (t.cwd) head.push(`- 工作目录:${t.cwd}`);
  if (t.createdAt) head.push(`- 创建时间:${new Date(t.createdAt).toISOString()}`);
  head.push(`- 消息数:${t.entries.length}`);
  head.push("");
  const body: string[] = [];
  for (const e of t.entries) {
    const when = e.time ? ` ${new Date(e.time).toISOString()}` : "";
    body.push(`## ${e.who}${when}`);
    body.push("");
    body.push(e.text);
    body.push("");
  }
  return head.concat(body).join("\n");
}

export interface SessionsExportResult {
  files: number;
  sessions: number;
  messages: number;
  failures: number;
}

/**
 * Export every full session transcript to <outDir>/conversations.
 * Never throws: unreadable or malformed sessions are counted as failures.
 */
export function collectSessionTranscripts(): { transcripts: SessionTranscript[]; failures: number } {
  const transcripts: SessionTranscript[] = [];
  let failures = 0;
  for (const file of listSessionFiles()) {
    try {
      const raw = readSessionFile(file);
      if (!raw) {
        failures++;
        continue;
      }
      const transcript = parseSessionLines(raw);
      if (!transcript) continue;
      transcripts.push(transcript);
    } catch {
      failures++;
    }
  }
  return { transcripts, failures };
}

export function exportSessionTranscripts(outDir: string): SessionsExportResult {
  const dir = join(outDir, "conversations");
  mkdirSync(dir, { recursive: true });

  const { transcripts, failures } = collectSessionTranscripts();
  let messages = 0;
  let files = 0;

  for (const transcript of transcripts) {
    const name = `${slug(transcript.title, "session")}__${slug(transcript.id, "unknown")}.md`;
    writeFileSync(join(dir, name), renderTranscript(transcript), "utf8");
    messages += transcript.entries.length;
    files++;
  }

  return { files, sessions: files, messages, failures };
}