src / chatImageImport.ts

import type { Chat, ChatMessage, FileHandle, PromptPreprocessorController } from "@lmstudio/sdk";
import { mkdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
import { basename, isAbsolute, join, relative } from "node:path";
import { hashBytes, IMAGE_LIMIT } from "./attachmentIdentity";

function inside(root: string, target: string): void {
  const rel = relative(root, target);
  if (isAbsolute(rel) || rel === ".." || rel.startsWith("../") || rel.startsWith("..\\")) throw new Error("Attachment import path escapes the working directory.");
}

async function readAttachment(file: FileHandle): Promise<Buffer> {
  if (file.sizeBytes > IMAGE_LIMIT) throw new Error("Attachment exceeds 8 MiB.");
  let bytes: Buffer;
  if (file.identifier.startsWith("base64:")) {
    const encoded = file.identifier.slice(7);
    if (encoded.length > Math.ceil(IMAGE_LIMIT / 3) * 4) throw new Error("Inline attachment exceeds 8 MiB.");
    bytes = Buffer.from(encoded, "base64");
  } else {
    const path = await file.getFilePath();
    const info = await stat(path);
    if (!info.isFile() || info.size > IMAGE_LIMIT) throw new Error("Invalid or oversized attachment file.");
    bytes = await readFile(path);
  }
  if (!bytes.length || bytes.length > IMAGE_LIMIT) throw new Error("Empty or oversized attachment.");
  return bytes;
}

async function immutableWrite(root: string, target: string, bytes: Buffer): Promise<void> {
  try { await writeFile(target, bytes, {flag: "wx"}); }
  catch (error) {
    if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
    inside(root, await realpath(target));
    const info = await stat(target);
    if (!info.isFile() || info.size !== bytes.length || !(await readFile(target)).equals(bytes)) throw new Error("Existing imported attachment or metadata has changed.");
  }
}

export async function exposeChatImages(ctl: PromptPreprocessorController, message: ChatMessage, getHistory: () => Promise<Chat>): Promise<ChatMessage> {
  if (!message.isUserMessage()) return message;
  const files = message.getFiles(ctl.client).filter(file => file.isImage());
  try {
    const history = await getHistory();
    for (const prior of history.getMessagesArray().slice(-64).reverse()) {
      if (prior.isUserMessage()) files.push(...prior.getFiles(ctl.client).filter(file => file.isImage()));
      if (files.length >= 32) break;
    }
  } catch { /* Current attachments can still be imported without history. */ }
  if (!files.length) return message;
  let root: string;
  try { root = await realpath(ctl.getWorkingDirectory()); }
  catch (error) { ctl.debug("Chat images cannot be exposed to tools without a working directory", String(error)); return message; }
  const refs: string[] = [];
  const ids = new Set<string>();
  const hashes = new Set<string>();
  let total = 0;
  let failures = 0;
  for (const file of files) {
    if (refs.length >= 8 || total >= 16 * 1024 * 1024) break;
    if (ids.has(file.identifier)) continue;
    ids.add(file.identifier);
    ctl.guardAbort();
    try {
      const bytes = await readAttachment(file);
      ctl.guardAbort();
      total += bytes.length;
      if (total > 16 * 1024 * 1024) break;
      const hash = hashBytes(bytes);
      if (hashes.has(hash)) continue;
      hashes.add(hash);
      const { default: sharp } = await import("sharp");
      const info = await sharp(bytes, {limitInputPixels: 40_000_000}).metadata();
      const format = info.format;
      const extension = format === "heif" && info.compression === "av1" ? "avif"
        : ({jpeg: "jpg", png: "png", webp: "webp", gif: "gif", tiff: "tiff", avif: "avif", bmp: "bmp"} as Record<string, string>)[format ?? ""];
      if (!extension) throw new Error(`Unsupported attachment format: ${format}`);
      let stem = basename(file.name).replace(/\.[^./\\]*$/, "").replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 100) || "image";
      if (/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(stem)) stem = "image-" + stem;
      const container = join(root, "aia-attachments");
      await mkdir(container, {recursive: true}); inside(root, await realpath(container));
      const directory = join(container, hash);
      await mkdir(directory, {recursive: true}); inside(root, await realpath(directory));
      const fileName = `${stem}.${extension}`;
      const target = join(directory, fileName);
      const ref = relative(root, target).replace(/\\/g, "/");
      await immutableWrite(root, target, bytes);
      const metadata = {source: "chat-attachment", caption: `Chat image: ${file.name}`, originalFilename: file.name,
        attachmentSha256: hash, localImage: ref, localMetadata: ref.replace(/\.[^.]+$/, ".json")};
      await immutableWrite(root, join(directory, `${stem}.json`), Buffer.from(JSON.stringify(metadata, null, 2)));
      refs.push(`${JSON.stringify(file.name)} -> ${ref}`);
    } catch (error) {
      if (ctl.abortSignal.aborted) throw error;
      failures++; ctl.debug("Chat attachment unavailable to analysis tools", file.name, String(error));
    }
  }
  if (failures) ctl.createStatus({status: "error", text: "Some chat images could not be made available to analysis tools. Reattach missing images to retry."});
  ctl.guardAbort();
  if (!refs.length) return message;
  const inventory = `[Images available to analysis tools]\nWhen image attachments are available to your vision input, inspect them directly and answer without Analyze/Multi Analyze if that is sufficient. These paths are optional references for inspecting saved local images or a targeted recheck; their presence does not require a tool call. A path or filename alone is not visual evidence. If tool analysis is needed, use these exact relative paths; do not guess paths or image contents from displayed filenames. Multi Analyze's image-selection verification still applies.\n${refs.join("\n")}\n[End image references]`;
  if (message.getText().includes(inventory)) return message;
  const result = message.asMutableCopy();
  result.appendText(`\n\n${inventory}`);
  return result;
}