import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, writeFileSync, cpSync, rmSync } from "node:fs"; import { homedir } from "node:os"; import { join, resolve } from "node:path"; import { execFileSync } from "node:child_process"; import { exportSessionTranscripts } from "./sessions.js"; export interface Persona { id: string; name: string; role?: string; color?: string; avatar?: string; model?: string; effort?: string; capabilities?: string[]; instructions: string; } export interface DshExportOptions { outDir: string; withAttachments?: boolean; withMaterials?: boolean; withConversations?: boolean; } export interface DshExportResult { personas: number; materialsDirs: string[]; materialsBytes: number; conversationFiles: number; conversationLines: number; conversationFailures: number; attachmentsCopied: boolean; outDir: string; } const HOME = homedir(); /** Read the bot-team personas from ~/.dsh/bot/state.json. */ export function readPersonas(): Persona[] { const statePath = join(HOME, ".dsh", "bot", "state.json"); if (!existsSync(statePath)) return []; const data = JSON.parse(readFileSync(statePath, "utf8")); const bots = data?.bots ?? {}; const personas: Persona[] = []; for (const [id, bot] of Object.entries(bots)) { personas.push({ id, name: typeof bot?.name === "string" ? bot.name : id, role: typeof bot?.role === "string" ? bot.role : undefined, color: typeof bot?.color === "string" ? bot.color : undefined, avatar: bot?.avatar ? JSON.stringify(bot.avatar) : undefined, model: typeof bot?.model === "string" ? bot.model : undefined, effort: typeof bot?.effort === "string" ? bot.effort : (typeof bot?.appliedEffort === "string" ? bot.appliedEffort : undefined), capabilities: Array.isArray(bot?.capabilities) ? bot.capabilities : undefined, instructions: typeof bot?.instructions === "string" ? bot.instructions : "", }); } return personas; } /** Render personas as a portable markdown document. */ export function renderPersonas(personas: Persona[]): string { const lines: string[] = ["# 人设档案", ""]; for (const p of personas) { lines.push(`## ${p.name}`); lines.push(""); if (p.role) lines.push(`- 角色:${p.role}`); if (p.model) lines.push(`- 模型:${p.model}`); if (p.color) lines.push(`- 颜色:${p.color}`); if (p.avatar) lines.push(`- 头像:${p.avatar}`); if (p.capabilities?.length) lines.push(`- 能力:${p.capabilities.join("、")}`); lines.push(""); lines.push("### 指令"); lines.push(""); lines.push(p.instructions || "(无)"); lines.push(""); } return lines.join("\n"); } /** Render the model configuration (persona → model + reasoning effort). */ export function renderModels(personas: Persona[]): string { const lines: string[] = ["# 模型配置", ""]; lines.push("| 人设 | 角色 | 模型 | 推理档位 |"); lines.push("|---|---|---|---|"); for (const p of personas) { lines.push(`| ${p.name} | ${p.role ?? "-"} | ${p.model ?? "-"} | ${p.effort ?? "-"} |`); } lines.push(""); const unique = [...new Set(personas.map((p) => p.model).filter(Boolean))]; if (unique.length > 0) { lines.push("## 使用到的模型"); lines.push(""); for (const m of unique) lines.push(`- ${m}`); lines.push(""); } return lines.join("\n"); } /** Copy material directories (workspace, memory, optionally attachments). */ export function exportMaterials(outDir: string, withAttachments: boolean): { dirs: string[]; bytes: number } { const targets: Array<[string, string]> = [ [join(HOME, ".dsh", "bot", "workspace"), "files/workspace"], [join(HOME, ".dsh", "bot", "memory"), "files/memory"], ]; if (withAttachments) targets.push([join(HOME, ".dsh", "attachments"), "files/attachments"]); const copied: string[] = []; let bytes = 0; for (const [src, rel] of targets) { if (!existsSync(src)) continue; const dest = join(outDir, rel); cpSync(src, dest, { recursive: true }); copied.push(dest); bytes += dirSize(src); } return { dirs: copied, bytes }; } function dirSize(dir: string): number { let total = 0; try { for (const name of readdirSync(dir)) { const p = join(dir, name); const st = statSync(p); total += st.isDirectory() ? dirSize(p) : st.size; } } catch { // ignore unreadable entries } return total; } interface ChatLine { session: string; seq: number; time: number; who: string; text: string; } /** Read conversation lines from the chat index SQLite database. */ export function readConversations(): ChatLine[] { const db = join(HOME, ".dsh", "bot", "chat-index.sqlite"); if (!existsSync(db)) return []; let raw = ""; try { raw = execFileSync("sqlite3", [db, "-json", "SELECT session, seq, time, who, text FROM lines ORDER BY session, CAST(seq AS INTEGER);"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, }); } catch { return []; } try { const rows = JSON.parse(raw || "[]"); return rows.map((r: any) => ({ session: String(r.session ?? "unknown"), seq: Number(r.seq ?? 0), time: Number(r.time ?? 0), who: String(r.who ?? "?"), text: String(r.text ?? ""), })); } catch { return []; } } /** Write one markdown transcript per session. */ export function exportConversations(outDir: string): { files: number; lines: number } { const lines = readConversations(); if (lines.length === 0) return { files: 0, lines: 0 }; const bySession = new Map(); for (const line of lines) { if (!bySession.has(line.session)) bySession.set(line.session, []); bySession.get(line.session)!.push(line); } const dir = join(outDir, "conversations"); mkdirSync(dir, { recursive: true }); let files = 0; for (const [session, entries] of bySession) { entries.sort((a, b) => a.seq - b.seq || a.time - b.time); const body: string[] = [`# 对话记录 ${session}`, "", `共 ${entries.length} 条`, ""]; for (const e of entries) { const when = e.time ? new Date(e.time).toISOString() : ""; body.push(`## [${e.seq}] ${e.who} ${when}`.trim()); body.push(""); body.push(e.text); body.push(""); } const safe = session.replace(/[^\w.-]+/g, "_").slice(0, 100); writeFileSync(join(dir, `${safe}.md`), body.join("\n"), "utf8"); files++; } return { files, lines: lines.length }; } /** Full DSH → portable bundle export. */ /** Portable instruction file content for a target agent format. */ function renderInstructionFile(personas: Persona[], target: "agents" | "claude"): string { const lines: string[] = []; if (target === "agents") lines.push("# Agent Instructions", ""); else lines.push("# Project Rules", ""); lines.push("## 人物设定(从 DSH 导入)", ""); lines.push("本项目导入了 DSH 的 Bot 团队设定。完整资料见:", ""); lines.push("- `personas.md` — 所有 Bot 的人物设定"); lines.push("- `materials/` — 工作区文件与记忆快照"); lines.push("- `conversations/` — 完整对话记录"); lines.push(""); for (const p of personas) { lines.push(`### ${p.name}${p.role ? `(${p.role})` : ""}`); lines.push(""); lines.push(p.instructions || "(无指令)"); lines.push(""); } return lines.join("\n"); } export function exportDsh(options: DshExportOptions): DshExportResult { const outDir = resolve(options.outDir); mkdirSync(outDir, { recursive: true }); // Remove legacy bundle artifacts from older AgentLens versions. for (const legacy of ["personas.md", "materials"]) { const p = join(outDir, legacy); if (existsSync(p)) rmSync(p, { recursive: true, force: true }); } const personas = readPersonas(); writeFileSync(join(outDir, "persona.md"), renderPersonas(personas), "utf8"); writeFileSync(join(outDir, "models.md"), renderModels(personas), "utf8"); // Ready-to-use instruction files for the two shared standards. writeFileSync(join(outDir, "AGENTS.md"), renderInstructionFile(personas, "agents"), "utf8"); writeFileSync(join(outDir, "CLAUDE.md"), renderInstructionFile(personas, "claude"), "utf8"); let materialDirs: string[] = []; let materialBytes = 0; if (options.withMaterials !== false) { const r = exportMaterials(outDir, options.withAttachments === true); materialDirs = r.dirs; materialBytes = r.bytes; } let conversationFiles = 0; let conversationLines = 0; let conversationFailures = 0; if (options.withConversations !== false) { // Full session transcripts first (rich: user/assistant/tool events)… const sessions = exportSessionTranscripts(outDir); conversationFiles += sessions.files; conversationLines += sessions.messages; conversationFailures += sessions.failures; // …then chat-index lines (bot conversations not covered by session files). const fallback = exportConversations(outDir); conversationFiles += fallback.files; conversationLines += fallback.lines; } writeFileSync( join(outDir, "README.md"), [ "# 从 DSH 导出的完整资料", "", "这是 AgentLens 从 DeepSeek Harness 导出的便携包,包含三类内容:", "", "1. `persona.md` — 人设档案(每个角色的外观、职责、完整指令)", "2. `models.md` — 模型配置(每个角色用的模型与推理档位)", "3. `files/` — 工作区文件与记忆快照" + (options.withAttachments ? "(含附件)" : ""), "4. `conversations/` — 每个会话的完整对话记录(Markdown)", "", "把这整个目录放进任何 AI Agent 可以读取的项目里,它就能了解你的人物设定、资料和过往对话。", "", ].join("\n"), "utf8" ); return { personas: personas.length, materialsDirs: materialDirs, materialsBytes: materialBytes, conversationFiles, conversationLines, conversationFailures, attachmentsCopied: options.withAttachments === true, outDir, }; }