dist / fileSearch / historyDocuments.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareSearchHistory = prepareSearchHistory;
const sdk_1 = require("@lmstudio/sdk");
const node_crypto_1 = require("node:crypto");
const promises_1 = require("node:fs/promises");
const documents_1 = require("./documents");
const storageLocation_1 = require("./storageLocation");
const receipts_1 = require("./receipts");
const encoding_1 = require("./encoding");
async function attachmentBytes(file, signal) {
    signal.throwIfAborted();
    if (file.identifier.startsWith("base64:")) {
        const encoded = file.identifier.slice(7);
        if (encoded.length > Math.ceil(documents_1.MAX_FILE_BYTES / 3) * 4)
            throw new Error(`Attachment exceeds 32 MiB: ${file.name}`);
        const bytes = Buffer.from(encoded, "base64");
        if (bytes.length > documents_1.MAX_FILE_BYTES)
            throw new Error(`Attachment exceeds 32 MiB: ${file.name}`);
        return bytes;
    }
    const handle = await (0, promises_1.open)(await file.getFilePath(), "r");
    try {
        const info = await handle.stat();
        if (!info.isFile() || info.size > documents_1.MAX_FILE_BYTES)
            throw new Error(`Attachment exceeds 32 MiB: ${file.name}`);
        const buffer = Buffer.alloc(info.size + 1);
        let length = 0;
        while (length < buffer.length) {
            signal.throwIfAborted();
            const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);
            if (!bytesRead)
                break;
            length += bytesRead;
        }
        if (length > info.size)
            throw new Error(`Attachment changed while reading: ${file.name}. Retry the request.`);
        return buffer.subarray(0, length);
    }
    finally {
        await handle.close();
    }
}
// Insert/regenerate can bypass PromptPreprocessor entirely. Generators can call
// this same entry point immediately before converting the complete history.
// Only the returned copy loses document attachments; the saved chat is untouched.
async function prepareSearchHistory(history, client, signal) {
    const entries = history.getMessagesArray();
    const files = [];
    const seen = new Set();
    for (const message of entries) {
        for (const file of message.getFiles(client)) {
            if (file.isImage())
                continue;
            if (!message.isUserMessage())
                throw new Error("Document attachments must be on a user message.");
            const identity = JSON.stringify([file.identifier, file.name, file.sizeBytes]);
            if (seen.has(identity))
                continue;
            seen.add(identity);
            files.push(file);
        }
    }
    if (!files.length)
        return history;
    if (files.length > documents_1.MAX_DOCUMENTS)
        throw new Error("Search history exceeds 200 document attachments.");
    const previousId = (0, receipts_1.latestCollection)(entries);
    const preferences = (0, encoding_1.encodingPreferencesForMessages)(entries);
    const encodings = files.map(file => (0, encoding_1.encodingForFile)(preferences, file.name));
    const store = (0, storageLocation_1.createDocumentStore)();
    // LM Studio attachment identities identify the uploaded snapshot. Reuse our
    // durable receipt before opening temporary host files that may have expired.
    const cacheKey = (0, node_crypto_1.createHash)("sha256").update(JSON.stringify({ version: 2, previousId, encodings,
        files: files.map(file => [file.identifier, file.name, file.sizeBytes]),
    })).digest("hex").slice(0, 32);
    signal.throwIfAborted();
    let collection = await store.imported(cacheKey);
    if (!collection && encodings.every(encoding => encoding === "auto")) {
        // Preserve imports created by 0.1.2 even when LM Studio's temporary upload
        // has expired. An explicit encoding always bypasses the legacy receipt.
        const legacyKey = (0, node_crypto_1.createHash)("sha256").update(JSON.stringify({ version: 1, previousId,
            files: files.map(file => [file.identifier, file.name, file.sizeBytes]),
        })).digest("hex").slice(0, 32);
        collection = await store.imported(legacyKey);
        if (collection)
            await store.rememberImport(cacheKey, collection);
    }
    if (!collection) {
        const inputs = [];
        let total = 0;
        for (const file of files) {
            signal.throwIfAborted();
            if (!(0, documents_1.supports)(file.name))
                throw new Error(`Unsupported attachment: ${file.name}. PDF/Office support is planned; use TXT, Markdown, JSON or HTML.`);
            const bytes = await attachmentBytes(file, signal);
            total += bytes.length;
            if (total > documents_1.MAX_COLLECTION_BYTES)
                throw new Error("Unprocessed document attachments exceed 128 MiB.");
            inputs.push({ name: file.name, bytes, encoding: (0, encoding_1.encodingForFile)(preferences, file.name) });
        }
        const previous = previousId ? await store.collection(previousId) : undefined;
        collection = await store.add(previous, inputs, signal);
        signal.throwIfAborted();
        await store.rememberImport(cacheKey, collection);
    }
    signal.throwIfAborted();
    const result = history.asMutableCopy();
    result.consumeFiles(client, file => !file.isImage());
    // Build another copy because getMessagesArray() returns immutable views.
    const lastUser = result.getMessagesArray().reduce((last, message, index) => message.isUserMessage() ? index : last, -1);
    const prepared = sdk_1.Chat.empty();
    for (const [index, message] of result.getMessagesArray().entries()) {
        const updated = message.asMutableCopy();
        const names = entries[index].getFiles(client).filter(file => !file.isImage()).map(file => file.name);
        if (names.length)
            updated.appendText(`\n[Documents indexed for search: ${JSON.stringify(names)}]`);
        if (index === lastUser)
            updated.appendText((0, receipts_1.instructions)(collection.id));
        prepared.append(updated);
    }
    return prepared;
}