src / promptPreprocessor.ts

import type { PromptPreprocessor } from "@lmstudio/sdk";
import { createDocumentStore } from "./storageLocation";
import { prepareSearchHistory } from "./historyDocuments";
import { instructions, latestCollection } from "./receipts";

export const preprocess: PromptPreprocessor = async (ctl, original) => {
  if (!original.isUserMessage()) return original;
  const history = await ctl.pullHistory();
  const combined = history.asMutableCopy();
  combined.append(original);
  const hasDocuments = combined.getAllFiles(ctl.client).some(file => !file.isImage());
  const previousId = latestCollection(history.getMessagesArray());
  if (!hasDocuments && !previousId) return original;
  const status = ctl.createStatus({ status: "loading", text: "Preparing searchable documents…" });
  try {
    ctl.guardAbort();
    if (hasDocuments) {
      // Native models have no Strata Generator to import earlier Insert messages.
      // Import the complete history, then return only the current message with
      // its real collection reference. Saved older turns stay untouched.
      const prepared = await prepareSearchHistory(combined, ctl.client, ctl.abortSignal);
      ctl.guardAbort();
      const result = prepared.at(prepared.getMessagesArray().length - 1).asMutableCopy();
      status.setState({status: "done", text: "Attached documents are ready for repeated search."});
      return result;
    }
    const collection = await createDocumentStore().collection(previousId!);
    ctl.guardAbort();
    const result = original.asMutableCopy();
    result.appendText(instructions(collection.id));
    status.setState({ status: "done", text: `${collection.documents.length} documents available for repeated search.` });
    return result;
  } catch (error) {
    status.setState({ status: ctl.abortSignal.aborted ? "canceled" : "error", text: String(error) });
    throw error;
  }
};