src / inlineMigration.ts

import { ChatMessage, type FileHandle, type LMStudioClient } from "@lmstudio/sdk";
import { persistChatImage } from "./persistentImage";

// Explicit repair only; never rewrites saved chats as a background plugin action.
export async function migrateInlineImages(raw: string, client: LMStudioClient): Promise<{raw: string; changed: number; files: FileHandle[]}> {
  const data = JSON.parse(raw);
  const refs: Array<{identifier: string; name: string; sizeBytes: number; fileType: "image"; type: "file"}> = [];
  function collect(value: any): void {
    if (!value || typeof value !== "object") return;
    if (value.type === "file" && value.fileType === "image" && typeof value.identifier === "string" && value.identifier.startsWith("base64:")) refs.push(value);
    for (const child of Object.values(value)) collect(child);
  }
  collect(data);
  const converted = new Map<string, FileHandle>();
  let total = 0;
  // Validate the whole batch before writing files.
  for (const ref of refs) {
    if (typeof ref.name !== "string" || !Number.isInteger(ref.sizeBytes) || ref.sizeBytes <= 0 || ref.sizeBytes > 8 * 1024 * 1024
      || ref.identifier.length > 12 * 1024 * 1024) throw new Error("Invalid or oversized migration image.");
    total += ref.sizeBytes;
    if (total > 128 * 1024 * 1024) throw new Error("Migration exceeds 128 MiB; split the repair batch.");
    const encoded = ref.identifier.slice(7);
    const bytes = Buffer.from(encoded, "base64");
    if (bytes.length !== ref.sizeBytes || bytes.toString("base64") !== encoded) throw new Error("Migration image size/encoding mismatch.");
  }
  for (const ref of refs) {
    const original = ref.identifier;
    let file = converted.get(original);
    if (!file) {
      const handle = ChatMessage.from({role: "user", content: [ref]}).getFiles(client)[0];
      file = await persistChatImage(client, handle);
      converted.set(original, file);
    }
    ref.identifier = file.identifier;
  }
  return {raw: refs.length ? JSON.stringify(data, null, 2) : raw, changed: refs.length, files: [...converted.values()]};
}