import { randomUUID } from 'node:crypto'; import { mkdir, open, readFile, readdir, rename, rm, stat, } from 'node:fs/promises'; import { dirname, join, resolve } from 'node:path'; import { agentStateDir } from '../context/agentHome.js'; import { acquireStateFileLock } from '../runtime/fileLock.js'; export interface RuntimeIdentity { workspaceId?: string; sessionId?: string; } function segment(value: string | undefined, fallback: string): string { return ( (value ?? fallback).replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 120) || fallback ); } export function sessionRuntimeDir(identity: RuntimeIdentity): string { return join( agentStateDir(), 'runtime', segment(identity.workspaceId, 'local'), segment(identity.sessionId, 'local'), ); } const queues = new Map>(); export async function withRuntimeFileLock( path: string, work: () => Promise, ): Promise { const key = resolve(path); const previous = queues.get(key) ?? Promise.resolve(); let release!: () => void; const current = new Promise((done) => { release = done; }); const tail = previous.then(() => current); queues.set(key, tail); await previous.catch(() => undefined); let unlock: (() => Promise) | undefined; try { unlock = await acquireStateFileLock(key, { label: 'RUNTIME' }); return await work(); } finally { try { await unlock?.(); } finally { release(); if (queues.get(key) === tail) queues.delete(key); } } } export async function readRuntimeJson( path: string, fallback: T, ): Promise { try { return JSON.parse(await readFile(path, 'utf8')) as T; } catch { return fallback; } } export async function writeRuntimeJson( path: string, value: unknown, ): Promise { await mkdir(dirname(path), { recursive: true, mode: 0o700 }); const temp = `${path}.${randomUUID()}.tmp`; try { const handle = await open(temp, 'wx', 0o600); try { await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`, 'utf8'); await handle.sync(); } finally { await handle.close(); } await rename(temp, path); } finally { await rm(temp, { force: true }).catch(() => undefined); } } export async function mutateRuntimeJson( path: string, fallback: T, mutate: (value: T) => T | Promise, ): Promise { return withRuntimeFileLock(path, async () => { const next = await mutate(await readRuntimeJson(path, fallback)); await writeRuntimeJson(path, next); return next; }); } export async function removeManagedPath( path: string, expectedRoot: string, ): Promise { const target = resolve(path); const root = resolve(expectedRoot); const rel = target.slice(root.length); if (target === root || !target.startsWith(`${root}/`) || rel.includes('\0')) { throw new Error(`拒绝清理托管根目录之外的路径:${target}`); } await rm(target, { recursive: true, force: true }); } export async function runtimeFileVersion(path: string): Promise { const info = await stat(path); return `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}`; } const activeOutputs = new Set(); const OUTPUT_RETENTION_MS = 7 * 24 * 60 * 60_000; const OUTPUT_GLOBAL_LIMIT = 5 * 1024 * 1024 * 1024; let pruneOutputsPromise: Promise | undefined; export function registerRuntimeOutput(path: string): void { activeOutputs.add(resolve(path)); } export function unregisterRuntimeOutput(path: string): void { activeOutputs.delete(resolve(path)); } export function pruneRuntimeOutputs(): Promise { pruneOutputsPromise ??= (async () => { const root = join(agentStateDir(), 'runtime'); const files: Array<{ path: string; size: number; mtimeMs: number }> = []; for (const workspace of await readdir(root).catch(() => [])) { const workspaceDir = join(root, workspace); for (const session of await readdir(workspaceDir).catch(() => [])) { const outputDir = join(workspaceDir, session, 'outputs'); const sessionFiles: Array<{ path: string; size: number; mtimeMs: number; }> = []; for (const name of await readdir(outputDir).catch(() => [])) { const path = join(outputDir, name); const info = await stat(path).catch(() => undefined); if (info?.isFile() && !activeOutputs.has(resolve(path))) { sessionFiles.push({ path, size: info.size, mtimeMs: info.mtimeMs }); } } sessionFiles.sort((left, right) => right.mtimeMs - left.mtimeMs); await Promise.all( sessionFiles .slice(50) .map((file) => rm(file.path, { force: true }).catch(() => undefined), ), ); files.push(...sessionFiles.slice(0, 50)); } } files.sort((left, right) => right.mtimeMs - left.mtimeMs); let retainedBytes = 0; const cutoff = Date.now() - OUTPUT_RETENTION_MS; for (const file of files) { retainedBytes += file.size; if (file.mtimeMs < cutoff || retainedBytes > OUTPUT_GLOBAL_LIMIT) { await rm(file.path, { force: true }).catch(() => undefined); } } })().finally(() => { pruneOutputsPromise = undefined; }); return pruneOutputsPromise; }