/** * User Context Prefix — 每条用户消息的系统上下文前置块(v0.7.3 P1-1 根治) * * 背景(Prompt Cache 被打穿的根因): * 此前「当前日期时间」「检索到的相关记忆」「附件提示」三类**每条消息都在变** * 的内容被追加进 systemPrompt.dynamicReminders —— OpenAI 兼容系将其拼进首条 * system 消息、Anthropic 写入顶层 system 字段。任何一次变化都会使整个 system * 前缀失配,DeepSeek 自动上下文缓存 / Anthropic 显式缓存全部 miss。长 system * (SOUL + 安全准则 + MEMORY.md)× 每 run 最多 20 轮迭代 × 全量重算输入 token, * 成本与首字延迟被系统性放大。 * * 现契约(单一事实来源): * - system prompt 只保留跨 run 字节级稳定的内容(SOUL / 约束 / 安全准则 / * 工作空间路径 / MEMORY.md 正文——其易变的 `> 最后更新` 元数据行本就被 * extractContent 剥离);Anthropic 侧对该稳定前缀打 cache_control 断言; * - 易变内容(日期时间 / 记忆 / 附件提示)由本模块构建为**用户消息前置块**, * 随当次请求注入首条 user 消息(LLM 语义等价:Claude Code 同款上下文注入位); * - DB 持久化 / 前端展示 / 记忆固化 / 注入检测均使用**原始干净内容**, * 前置块只存在于发给引擎的副本上。 * * 纯函数、零副作用:可在 node vitest 下直接表测(稳定性/分组/空值收缩)。 */ import type { SearchResult } from '../memory/manager'; /** 附件提示所需的元信息子集(与 agent-store AttachmentInfo 对齐的渲染端子集) */ export interface AttachmentHint { name: string; type: string; truncated?: boolean; } export interface UserContextPrefixInput { /** 当前时间戳(前置块内降精度到分钟,减少无意义抖动) */ now?: number; /** 检索到的相关记忆(空数组时不产出记忆分区) */ memories?: SearchResult[]; /** 用户附件元信息(空数组/undefined 时不产出附件分区) */ attachments?: AttachmentHint[]; /** * 时区标签(如 "Asia/Shanghai (UTC+8)")。 * 由调用方计算(Intl.DateTimeFormat().resolvedOptions().timeZone)—— * 本模块保持纯函数语义,不做 Electron/Intl 环境依赖。 */ timezoneLabel?: string; } /** 记忆注入条目的内容截断(与原 dynamicReminders 注入口径一致) */ const MEMORY_EXCERPT_CHARS = 200; /** 附件提示上限(与输入侧 5 个附件的硬上限对齐) */ const MAX_ATTACHMENT_HINTS = 8; /** * 构建用户消息上下文前置块。 * * 输出形态(各分区以 `\n\n---\n\n` 分隔,整体以分隔符结尾, * 调用方直接 `${prefix}${userContent}` 拼接): * ``` * [Contextual information for this message — system-generated metadata, not part of the user's request.] * * ## Current Date & Time * 2026/8/30 14:30:00 (Asia/Shanghai, UTC+8) * * --- * * ## Relevant Memories (Retrieved) * [1] (semantic, 重要度: 0.9) ... * * --- * * ## User Attachments (Direct Upload) * ... * ``` */ export function buildUserContextPrefix(input: UserContextPrefixInput): string { const parts: string[] = []; // ===== 分区 1:当前日期时间(降精度到分钟) ===== const now = input.now ?? Date.now(); const timezoneLabel = input.timezoneLabel ?? 'UTC'; const dateStr = new Date(now).toLocaleString('sv-SE', { timeZone: undefined, hour12: false, }); // sv-SE 给出 ISO 形态 "2026-08-30 14:30:00" parts.push(`## Current Date & Time\n${dateStr} (${timezoneLabel})`); // ===== 分区 2:相关记忆注入(沿用原 system 注入的展示口径) ===== const memories = (input.memories ?? []).slice(0, 5); if (memories.length > 0) { const memorySection = memories .map( (m, i) => `[${i + 1}] (${m.type}, 重要度: ${m.importance.toFixed(1)}) ${m.content.slice(0, MEMORY_EXCERPT_CHARS)}`, ) .join('\n'); parts.push(`## Relevant Memories (Retrieved)\n${memorySection}`); } // ===== 分区 3:附件提示(沿用原 system 注入的语义与文案契约) ===== const attachments = (input.attachments ?? []).slice(0, MAX_ATTACHMENT_HINTS); if (attachments.length > 0) { const attachmentList = attachments .map((att, i) => { const typeLabel = att.type === 'image' ? 'image' : att.type === 'text' ? 'text file' : 'file'; // 文本附件被上传入口截断(512KB 上限)时,明确告知 LLM 内容不完整, // 防止模型把残缺内容当作完整文件事实(v0.7.2 A5 契约延续) const truncatedNote = att.truncated === true ? ' (TRUNCATED — only the first 512KB is included; the full content is NOT available)' : ''; const note = att.type === 'image' ? 'already provided to you via vision capability — you can SEE it directly, do NOT call view_image or any tool to read it again' : att.type === 'text' ? `content${truncatedNote} already inlined in the user message, do NOT search in workspace or read it again` : 'uploaded directly by user, do NOT search in workspace'; return `${i + 1}. [${typeLabel}] ${att.name} — ${note}`; }) .join('\n'); parts.push( `## User Attachments (Direct Upload)\nThe following files were uploaded directly by the user to this conversation. They are inline attachments, NOT workspace files:\n${attachmentList}\n\n**IMPORTANT**: Images listed above are already visible to you in this conversation. Do NOT call \`view_image\`, \`read_file\`, or any file tool to read them — doing so wastes a tool call and may fail (they are not workspace files).`, ); } const header = "[Contextual information for this message — system-generated metadata, not part of the user's request.]"; return `${header}\n\n${parts.join('\n\n---\n\n')}\n\n---\n\n`; } /** * 将前置块与用户原始内容拼装为发送给引擎的消息内容。 * 空前缀(理论上不会发生——日期分区恒存在,但契约上防御)时原样返回。 */ export function withUserContextPrefix(prefix: string, userContent: string): string { if (!prefix) return userContent; return `${prefix}${userContent}`; }