dist / persistentImage.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.persistChatImage = persistChatImage;
const sdk_1 = require("@lmstudio/sdk");
const node_crypto_1 = require("node:crypto");
const promises_1 = require("node:fs/promises");
const node_path_1 = require("node:path");
const attachmentIdentity_1 = require("./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.
async function persistChatImage(client, image) {
    if (!image.isImage() || !image.identifier.startsWith("base64:"))
        return image;
    const encoded = image.identifier.slice(7);
    if (!encoded.length || encoded.length > Math.ceil(attachmentIdentity_1.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 > attachmentIdentity_1.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-${(0, node_crypto_1.randomUUID)()}.${extension}`;
    const file = sdk_1.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 (!(0, node_path_1.isAbsolute)(target) || (0, node_path_1.basename)(target) !== identifier)
        throw new Error("Unexpected LM Studio attachment path.");
    let created = false;
    try {
        await (0, promises_1.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 (0, promises_1.unlink)(target).catch(() => { });
        throw error;
    }
}
//# sourceMappingURL=persistentImage.js.map