agentlens / src /export /sessions.ts
hongcoding's picture
feat: DSH conversations imported into Codex sidebar (rollout files + threads rows)
8db9296 verified
Raw History Blame Contribute Delete
7.22 kB
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 };
}