Forked from vadimfedenko/analyze-images
dist / chatImageImport.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.exposeChatImages = exposeChatImages;
const promises_1 = require("node:fs/promises");
const node_path_1 = require("node:path");
const attachmentIdentity_1 = require("./attachmentIdentity");
function inside(root, target) {
const rel = (0, node_path_1.relative)(root, target);
if ((0, node_path_1.isAbsolute)(rel) || rel === ".." || rel.startsWith("../") || rel.startsWith("..\\"))
throw new Error("Attachment import path escapes the working directory.");
}
async function readAttachment(file) {
if (file.sizeBytes > attachmentIdentity_1.IMAGE_LIMIT)
throw new Error("Attachment exceeds 8 MiB.");
let bytes;
if (file.identifier.startsWith("base64:")) {
const encoded = file.identifier.slice(7);
if (encoded.length > Math.ceil(attachmentIdentity_1.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 (0, promises_1.stat)(path);
if (!info.isFile() || info.size > attachmentIdentity_1.IMAGE_LIMIT)
throw new Error("Invalid or oversized attachment file.");
bytes = await (0, promises_1.readFile)(path);
}
if (!bytes.length || bytes.length > attachmentIdentity_1.IMAGE_LIMIT)
throw new Error("Empty or oversized attachment.");
return bytes;
}
async function immutableWrite(root, target, bytes) {
try {
await (0, promises_1.writeFile)(target, bytes, { flag: "wx" });
}
catch (error) {
if (error.code !== "EEXIST")
throw error;
inside(root, await (0, promises_1.realpath)(target));
const info = await (0, promises_1.stat)(target);
if (!info.isFile() || info.size !== bytes.length || !(await (0, promises_1.readFile)(target)).equals(bytes))
throw new Error("Existing imported attachment or metadata has changed.");
}
}
async function exposeChatImages(ctl, message, getHistory) {
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;
try {
root = await (0, promises_1.realpath)(ctl.getWorkingDirectory());
}
catch (error) {
ctl.debug("Chat images cannot be exposed to tools without a working directory", String(error));
return message;
}
const refs = [];
const ids = new Set();
const hashes = new Set();
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 = (0, attachmentIdentity_1.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" }[format ?? ""];
if (!extension)
throw new Error(`Unsupported attachment format: ${format}`);
let stem = (0, node_path_1.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 = (0, node_path_1.join)(root, "aia-attachments");
await (0, promises_1.mkdir)(container, { recursive: true });
inside(root, await (0, promises_1.realpath)(container));
const directory = (0, node_path_1.join)(container, hash);
await (0, promises_1.mkdir)(directory, { recursive: true });
inside(root, await (0, promises_1.realpath)(directory));
const fileName = `${stem}.${extension}`;
const target = (0, node_path_1.join)(directory, fileName);
const ref = (0, node_path_1.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, (0, node_path_1.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;
}
//# sourceMappingURL=chatImageImport.js.map