const ALLOWED_CHAT_IMAGE_MIME = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]); const MAX_CHAT_IMAGES = 8; const MAX_CHAT_IMAGE_BYTES = 10 * 1024 * 1024; export function normalizeChatImages( images: unknown, ): Array<{ type: "image"; data: string; mimeType: string }> | undefined { if (!Array.isArray(images) || images.length === 0) return undefined; const out: Array<{ type: "image"; data: string; mimeType: string }> = []; for (const raw of images.slice(0, MAX_CHAT_IMAGES)) { if (!raw || typeof raw !== "object") continue; const mimeType = String((raw as { mimeType?: string }).mimeType || ""); const data = String((raw as { data?: string }).data || ""); if ((raw as { type?: string }).type !== "image" || !ALLOWED_CHAT_IMAGE_MIME.has(mimeType) || !data) { throw new Error(`不支持的图片类型: ${mimeType || "unknown"}`); } const size = Buffer.from(data, "base64").length; if (size > MAX_CHAT_IMAGE_BYTES) { throw new Error(`图片过大(最大 ${Math.round(MAX_CHAT_IMAGE_BYTES / 1024 / 1024)}MB)`); } out.push({ type: "image", mimeType, data }); } return out.length ? out : undefined; }