import type { DreamExtractSpec, DreamKind } from "./types"; function frontmatter( dreamId: string, scopeKey: string, kind: DreamKind, ): string { return `---\ndreamId: ${dreamId} · scope: ${scopeKey} · kind: ${kind} · 会话内提取\n---\n`; } /** profile 的 instructions(JSON map 字符串)→ 排序键值文本;失败降级原文。 */ function renderProfileBody(instructions: string): { body: string; warning?: string; } { try { const obj = JSON.parse(instructions) as Record; if (obj === null || typeof obj !== "object" || Array.isArray(obj)) { throw new Error("profile instructions is not a JSON object"); } const lines = Object.keys(obj) .sort() .map((k) => { const v = obj[k]; // 非基本类型(数组/嵌套对象/null)用 JSON.stringify 保真,避免 "[object Object]" 丢内容。 const rendered = v !== null && typeof v === "object" ? JSON.stringify(v) : String(v); return `- ${k}:${rendered}`; }); return { body: lines.join("\n") }; } catch (err) { return { body: instructions.trimEnd(), warning: `profile instructions JSON parse failed, fell back to raw: ${ err instanceof Error ? err.message : String(err) }`, }; } } /** * 把本次会话某一类型(skill/profile)的全部产出合并成**一个**文档。 * 同会话重复提取时,配合确定性文件名整体覆盖旧文件。 * * - skill:`# 会话技能总结` + 每个技能一个 `## 名称` 小节。 * - profile:`# 用户画像` + 各画像的排序键值文本(通常一条)。 */ export function buildSessionDreamDoc(args: { kind: DreamKind; specs: DreamExtractSpec[]; dreamId: string; scopeKey: string; }): { content: string; count: number; warning?: string } { const { kind, specs, dreamId, scopeKey } = args; const warnings: string[] = []; let body: string; if (kind === "profile") { const sections = specs.map((spec) => { const r = renderProfileBody(spec.instructions); if (r.warning) warnings.push(r.warning); return r.body; }); body = `# 用户画像\n\n${sections.join("\n\n")}`; } else { const sections = specs.map((spec) => { const desc = spec.description ? `> ${spec.description}\n\n` : ""; return `## ${spec.name}\n\n${desc}${spec.instructions.trimEnd()}`; }); body = `# 会话技能总结\n\n${sections.join("\n\n")}`; } const content = `${frontmatter(dreamId, scopeKey, kind)}${body}`; return { content, count: specs.length, ...(warnings.length ? { warning: warnings.join("; ") } : {}), }; }