File size: 10,168 Bytes
4ce05b9 36277c7 11e2b39 36277c7 4ce05b9 36277c7 11e2b39 36277c7 4ce05b9 36277c7 4ce05b9 36277c7 4ce05b9 36277c7 4ce05b9 36277c7 4ce05b9 36277c7 4ce05b9 36277c7 4ce05b9 36277c7 11e2b39 36277c7 11e2b39 36277c7 4ce05b9 36277c7 11e2b39 36277c7 | 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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | 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<any>(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<string, ChatLine[]>();
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,
};
}
|