import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; const TEMP_ROOT = "/tmp"; const TEMP_PREFIX = "pi-web-core-"; const directories = new Set(); export interface TempContentFile { path: string; chars: number; bytes: number; } export async function writeTempContent(content: string, extension = ".md"): Promise { const dir = await mkdtemp(join(TEMP_ROOT, TEMP_PREFIX)); await chmod(dir, 0o700); directories.add(dir); const safeExtension = extension === ".txt" ? ".txt" : ".md"; const path = join(dir, `content${safeExtension}`); await writeFile(path, content, { encoding: "utf8", mode: 0o600 }); return { path, chars: content.length, bytes: Buffer.byteLength(content) }; } export async function cleanupTempContent(): Promise { const pending = [...directories]; directories.clear(); await Promise.all(pending.map(async (dir) => { try { await rm(dir, { recursive: true, force: true }); } catch { // Temporary output must never make session shutdown fail. } })); }