import { createHash, randomUUID } from 'node:crypto'; import { mkdir, readdir, stat, unlink, writeFile, rename, rm } from 'node:fs/promises'; import { homedir } from 'node:os'; import { join } from 'node:path'; import { safeSlice } from '../utils/safeText.js'; const MAX_ARCHIVE_RESULT_CHARS = 12_000; const MAX_SESSION_ARCHIVE_BYTES = 64 * 1024 * 1024; export interface ArchivedToolResult { content: string; archiveRef?: string; originalChars: number; /** * 本次归档没能落盘的原因(成功时不设)。 * * ⚠️ 撞会话上限之后归档就**静默失效**了:功能还在跑,但每一条超长结果都退回 * 原文塞进上下文 —— 也就是这个模块本来要解决的问题原样回来了,而没有任何信号。 * 调用方拿到这个字段应当往上报一次 warning(与引擎「零工具调用」信号同款纪律: * 该说的话不静默)。 */ degraded?: 'session-limit' | 'io-error'; } function agentHome(): string { return process.env.MINIMAL_AGENT_HOME ?? homedir(); } function archiveDir(sessionKey: string): string { const safeKey = createHash('sha256').update(sessionKey).digest('hex').slice(0, 24); return join(agentHome(), '.minimal-agent', 'tool-results', safeKey); } /** * 将超大工具结果写入当前会话的受控归档目录,并返回可供模型 Read 的引用预览。 * * 失败时原样返回:归档只能增加可恢复性,不能成为破坏性压缩的前置条件。 * 文件名只使用随机 UUID,避免用户输入进入路径;写入采用临时文件 + rename。 */ export async function archiveToolResult( content: string, sessionKey: string, toolName: string, ): Promise { if (content.length <= MAX_ARCHIVE_RESULT_CHARS) { return { content, originalChars: content.length }; } const dir = archiveDir(sessionKey); const id = randomUUID(); const finalPath = join(dir, `${id}.txt`); const tempPath = join(dir, `.${id}.tmp`); try { await mkdir(dir, { recursive: true, mode: 0o700 }); await writeFile(tempPath, content, { encoding: 'utf8', mode: 0o600 }); await rename(tempPath, finalPath); if (!(await archiveFitsWithinLimit(dir))) { // 不淘汰旧文件:它们可能仍被 history 里的引用预览指着,删了模型就再也读不回来。 // 超限时只撤销当前这一次归档并保留原文 —— 数据不丢,但**功能从此不再起作用**, // 所以必须带上 degraded 让调用方报一次 warning,不能静默。 await unlink(finalPath); return { content, originalChars: content.length, degraded: 'session-limit' }; } const preview = `${safeSlice(content, 0, 2_000)}\n\n` + `[工具结果已归档:${toolName},原文 ${content.length.toLocaleString()} 字符。` + `需要完整内容时,请使用 Read 读取:${finalPath}]`; return { content: preview, archiveRef: finalPath, originalChars: content.length }; } catch { // 清理可能留下的临时文件;清理失败也不能覆盖原始结果。 try { await unlink(tempPath); } catch { /* best effort */ } return { content, originalChars: content.length, degraded: 'io-error' }; } } async function archiveFitsWithinLimit(dir: string): Promise { try { const names = (await readdir(dir)).filter((name) => name.endsWith('.txt')); let total = 0; for (const name of names) { total += (await stat(join(dir, name))).size; if (total > MAX_SESSION_ARCHIVE_BYTES) return false; } return true; } catch { return false; } } /** /new 或显式 session 清理时调用;不会删除仍在使用的其它 session 目录。 */ export async function clearToolResultArchive(sessionKey: string): Promise { await rm(archiveDir(sessionKey), { recursive: true, force: true }); } export const TOOL_RESULT_ARCHIVE_MAX_CHARS = MAX_ARCHIVE_RESULT_CHARS;