import { createHash, randomUUID } from 'node:crypto'; import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises'; import { extname, join } from 'node:path'; import { agentStateDir } from '../context/agentHome.js'; import { loadSharp } from './sharpRuntime.js'; export const DEFAULT_MAX_IMAGE_INPUT_BYTES = 25 * 1024 * 1024; export const DEFAULT_MAX_MODEL_IMAGE_BYTES = 10 * 1024 * 1024; export type DetectedImageMime = | 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/bmp' | 'image/tiff' | 'image/avif' | 'image/heic' | 'image/svg+xml'; export interface ResolvedLocalImage { originalPath: string; path: string; originalMime: DetectedImageMime; mime: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp'; size: number; transformed: boolean; diagnostic?: string; } function is(bytes: Buffer, offset: number, signature: readonly number[]): boolean { return signature.every((value, index) => bytes[offset + index] === value); } /** Actual bytes are authoritative; names and declared MIME are never trusted. */ export function detectImageMime(bytes: Buffer): DetectedImageMime | null { if (bytes.length >= 8 && is(bytes, 0, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return 'image/png'; if (bytes.length >= 3 && is(bytes, 0, [0xff, 0xd8, 0xff])) return 'image/jpeg'; if (bytes.length >= 6 && ['GIF87a', 'GIF89a'].includes(bytes.toString('ascii', 0, 6))) return 'image/gif'; if (bytes.length >= 12 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') return 'image/webp'; if (bytes.length >= 2 && bytes.toString('ascii', 0, 2) === 'BM') return 'image/bmp'; if (bytes.length >= 4 && (is(bytes, 0, [0x49, 0x49, 0x2a, 0x00]) || is(bytes, 0, [0x4d, 0x4d, 0x00, 0x2a]))) return 'image/tiff'; if (bytes.length >= 16 && bytes.toString('ascii', 4, 8) === 'ftyp') { const brands = bytes.subarray(8, Math.min(bytes.length, 64)).toString('ascii'); if (/(?:avif|avis)/.test(brands)) return 'image/avif'; if (/(?:heic|heix|hevc|hevx|heim|heis|mif1|msf1)/.test(brands)) return 'image/heic'; } const prefix = bytes.subarray(0, Math.min(bytes.length, 4096)).toString('utf8').replace(/^\uFEFF/, '').trimStart(); if (/^(?:<\?xml[^>]*>\s*)?)[extname(path).toLowerCase()]; } async function decodeHeic(bytes: Buffer): Promise { const imported = await import('heic-convert'); const convert = imported.default; if (typeof convert !== 'function') throw new Error('HEIC 解码器未正确加载'); const output = await convert({ buffer: bytes, format: 'JPEG', quality: 0.92 }); return Buffer.from(output); } async function normalizeForModel( bytes: Buffer, detected: DetectedImageMime, maxOutputBytes: number, ): Promise<{ bytes: Buffer; mime: 'image/jpeg' | 'image/png' }> { const sharp = await loadSharp(); const decoded = detected === 'image/heic' ? await decodeHeic(bytes) : bytes; const image = sharp(decoded, { animated: false }).rotate().resize({ width: 4096, height: 4096, fit: 'inside', withoutEnlargement: true, }); const metadata = await image.metadata(); const preserveAlpha = metadata.hasAlpha === true || detected === 'image/svg+xml'; let output = preserveAlpha ? await image.clone().png({ compressionLevel: 9 }).toBuffer() : await image.clone().jpeg({ quality: 88, mozjpeg: true }).toBuffer(); if (output.length > maxOutputBytes && !preserveAlpha) { output = await image.clone().jpeg({ quality: 75, mozjpeg: true }).toBuffer(); } if (output.length > maxOutputBytes) { throw new Error(`规范化后图片仍超过 ${(maxOutputBytes / 1024 / 1024).toFixed(0)}MB 上限`); } return { bytes: output, mime: preserveAlpha ? 'image/png' : 'image/jpeg' }; } function modelMime(detected: DetectedImageMime): ResolvedLocalImage['mime'] | null { return ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(detected) ? detected as ResolvedLocalImage['mime'] : null; } export async function resolveLocalImage( path: string, options: { maxInputBytes?: number; maxOutputBytes?: number } = {}, ): Promise { const info = await stat(path).catch((error: Error) => { throw new Error(`无法读取图片:${path}(${error.message})`); }); if (!info.isFile()) throw new Error(`图片路径不是文件:${path}`); const maxInputBytes = options.maxInputBytes ?? DEFAULT_MAX_IMAGE_INPUT_BYTES; const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_MODEL_IMAGE_BYTES; if (info.size > maxInputBytes) throw new Error(`图片超过 ${(maxInputBytes / 1024 / 1024).toFixed(0)}MB 输入上限:${path}`); const bytes = await readFile(path); const detected = detectImageMime(bytes); if (!detected) { const declared = declaredMimeForExtension(path); throw new Error( declared ? `文件扩展名声明为 ${declared},但内容不是可解码图片:${path}` : `无法从文件内容识别图片格式:${path}`, ); } const declared = declaredMimeForExtension(path); const diagnostic = declared && declared !== detected ? `扩展名声明 ${declared},实际内容为 ${detected}` : undefined; const directMime = modelMime(detected); if (directMime && bytes.length <= maxOutputBytes) { // Decode metadata once so truncated/corrupt files do not masquerade as images. const sharp = await loadSharp(); const metadata = await sharp(bytes, { animated: detected === 'image/gif' }).metadata(); const needsOrientationFix = detected === 'image/jpeg' && (metadata.orientation ?? 1) > 1; if (!needsOrientationFix) { return { originalPath: path, path, originalMime: detected, mime: directMime, size: bytes.length, transformed: false, ...(diagnostic ? { diagnostic } : {}), }; } } const normalized = await normalizeForModel(bytes, detected, maxOutputBytes).catch((error) => { throw new Error(`图片格式 ${detected} 无法规范化:${path}(${(error as Error).message})`); }); const hash = createHash('sha256') .update(bytes) .update('\0model-image-v1\0') .update(normalized.mime) .digest('hex'); const extension = normalized.mime === 'image/png' ? '.png' : '.jpg'; const dir = join(agentStateDir(), 'image-derivatives', hash.slice(0, 2)); const target = join(dir, `${hash}${extension}`); await mkdir(dir, { recursive: true, mode: 0o700 }); const exists = await stat(target).then((item) => item.isFile()).catch(() => false); if (!exists) { const temp = `${target}.${randomUUID()}.tmp`; await writeFile(temp, normalized.bytes, { mode: 0o600 }); await rename(temp, target).catch(async () => { const wonRace = await stat(target).then((item) => item.isFile()).catch(() => false); if (!wonRace) throw new Error(`无法保存图片派生文件:${target}`); }); } return { originalPath: path, path: target, originalMime: detected, mime: normalized.mime, size: normalized.bytes.length, transformed: true, diagnostic: [diagnostic, `已规范化为 ${normalized.mime}`].filter(Boolean).join(';'), }; } export async function tryResolveLocalImage(path: string): Promise { try { return await resolveLocalImage(path); } catch { return null; } }