import { createHash } from 'node:crypto'; import { realpath, stat } from 'node:fs/promises'; import { createReadStream } from 'node:fs'; import { extname, isAbsolute, relative, resolve, sep } from 'node:path'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import type { ConversationFilePurpose, FileActivityKind, FileActivityMetadata, FileVerification, FilePatchSummary, } from '../../types.js'; const MIME_BY_EXT: Record = { '.csv': 'text/csv', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.html': 'text/html', '.jpeg': 'image/jpeg', '.jpg': 'image/jpeg', '.json': 'application/json', '.md': 'text/markdown', '.pdf': 'application/pdf', '.png': 'image/png', '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', '.txt': 'text/plain', '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }; function within(root: string, candidate: string): string | null { const rel = relative(root, candidate); if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return rel === '' ? '' : null; return rel.split(sep).join('/'); } export async function fileActivityMetadata( filePath: string, activity: FileActivityKind, verification: FileVerification = 'not_run', purpose: ConversationFilePurpose = activity === 'read' ? 'source' : 'support', cwd = getWorkingDir(), patch?: FilePatchSummary, ): Promise { const lexicalRoot = resolve(cwd); const root = await realpath(lexicalRoot).catch(() => lexicalRoot); const candidate = await realpath(filePath).catch(() => resolve(filePath)); const relativePath = within(root, candidate); if (!relativePath) return undefined; let sha256: string | undefined; if (activity !== 'deleted') { try { // A range Read must not secretly load/hash a gigabyte for UI metadata. // Hash is optional for sources; committed artifacts use bounded buffers. if (activity !== 'read' || (await stat(candidate)).size <= 8 * 1024 * 1024) { const hash = createHash('sha256'); for await (const chunk of createReadStream(candidate)) hash.update(chunk); sha256 = hash.digest('hex'); } } catch { /* The file activity remains useful even when hashing fails. */ } } return { kind: 'file_activity', files: [{ relativePath, activity, ...(sha256 ? { sha256 } : {}), ...(MIME_BY_EXT[extname(relativePath).toLowerCase()] ? { mime: MIME_BY_EXT[extname(relativePath).toLowerCase()] } : {}), verification, purpose, ...(patch ? { patch } : {}), }], }; }