Forked from vadimfedenko/analyze-images
src / persistentImage.ts
import { ChatMessage, type FileHandle, type LMStudioClient } from "@lmstudio/sdk";
import { randomUUID } from "node:crypto";
import { writeFile, unlink } from "node:fs/promises";
import { basename, isAbsolute } from "node:path";
import { IMAGE_LIMIT } from "./attachmentIdentity";
// Inference accepts inline bytes, but LM Studio's chat branching treats every
// saved identifier as a user-files filename. Store a native, connection-independent
// file through the SDK-resolved path instead of saving inline/temporary handles.
export async function persistChatImage(client: LMStudioClient, image: FileHandle): Promise<FileHandle> {
if (!image.isImage() || !image.identifier.startsWith("base64:")) return image;
const encoded = image.identifier.slice(7);
if (!encoded.length || encoded.length > Math.ceil(IMAGE_LIMIT / 3) * 4
|| !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) throw new Error("Invalid or oversized inline image.");
const bytes = Buffer.from(encoded, "base64");
if (!bytes.length || bytes.length > IMAGE_LIMIT || bytes.toString("base64") !== encoded) throw new Error("Invalid or oversized inline image.");
const extension = bytes.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex")) ? "png"
: bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff ? "jpg"
: bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP" ? "webp"
: /^GIF8[79]a/.test(bytes.toString("ascii", 0, 6)) ? "gif" : undefined;
if (!extension) throw new Error("Unsupported inline image format.");
// Bare native filename: even 'local:' is unsuitable for the branch copy path.
const identifier = `${Date.now()} - aia-${randomUUID()}.${extension}`;
const file = ChatMessage.from({role: "user", content: [{type: "file", name: image.name,
identifier, sizeBytes: bytes.length, fileType: "image"}]}).getFiles(client)[0];
const target = await file.getFilePath();
if (!isAbsolute(target) || basename(target) !== identifier) throw new Error("Unexpected LM Studio attachment path.");
let created = false;
try {
await writeFile(target, bytes, {flag: "wx"});
created = true;
return file;
} catch (error) {
// Never remove a pre-existing target after an exclusive-create failure.
if (created) await unlink(target).catch(() => {});
throw error;
}
}