src / historyDocuments.ts

import { Chat, type FileHandle, type LMStudioClient } from "@lmstudio/sdk";
import { createHash } from "node:crypto";
import { open } from "node:fs/promises";
import { MAX_COLLECTION_BYTES, MAX_DOCUMENTS, MAX_FILE_BYTES, supports } from "./documents";
import { createDocumentStore } from "./storageLocation";
import { instructions, latestCollection } from "./receipts";
import { encodingForFile, encodingPreferencesForMessages, type DocumentEncoding } from "./encoding";

async function attachmentBytes(file: FileHandle, signal: AbortSignal): Promise<Buffer> {
  signal.throwIfAborted();
  if (file.identifier.startsWith("base64:")) {
    const encoded = file.identifier.slice(7);
    if (encoded.length > Math.ceil(MAX_FILE_BYTES / 3) * 4) throw new Error(`Attachment exceeds 32 MiB: ${file.name}`);
    const bytes = Buffer.from(encoded, "base64");
    if (bytes.length > MAX_FILE_BYTES) throw new Error(`Attachment exceeds 32 MiB: ${file.name}`);
    return bytes;
  }
  const handle = await open(await file.getFilePath(), "r");
  try {
    const info = await handle.stat();
    if (!info.isFile() || info.size > 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.
export async function prepareSearchHistory(history: Chat, client: LMStudioClient, signal: AbortSignal): Promise<Chat> {
  const entries = history.getMessagesArray();
  const files: FileHandle[] = [];
  const seen = new Set<string>();
  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 > MAX_DOCUMENTS) throw new Error("Search history exceeds 200 document attachments.");
  const previousId = latestCollection(entries);
  const preferences = encodingPreferencesForMessages(entries);
  const encodings = files.map(file => encodingForFile(preferences, file.name));
  const store = createDocumentStore();
  // LM Studio attachment identities identify the uploaded snapshot. Reuse our
  // durable receipt before opening temporary host files that may have expired.
  const cacheKey = 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 = 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: {name: string; bytes: Buffer; encoding: DocumentEncoding}[] = [];
    let total = 0;
    for (const file of files) {
      signal.throwIfAborted();
      if (!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 > MAX_COLLECTION_BYTES) throw new Error("Unprocessed document attachments exceed 128 MiB.");
      inputs.push({name: file.name, bytes, encoding: 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 = 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(instructions(collection.id));
    prepared.append(updated);
  }
  return prepared;
}