src / hostAdapter.ts

import type { Chat, GeneratorController, LLMTool } from "@lmstudio/sdk";
import {configSchematics,globalConfigSchematics} from "./config";
import {toMessages,addDirectVisionPolicy} from "./messages";
import {prepareDocumentSearch} from "./documentSearch";
import {completeDeferredAnalyses} from "./analysisHandoff";
import {addEvidencePolicy} from "./evidence";

export function completionUrl(input:string):string {
  const url=new URL(input.trim());
  if(!["http:","https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash)throw new Error("Base URL must be an HTTP(S) address without credentials, query or fragment.");
  const path=url.pathname.replace(/\/+$/,"");url.pathname=path.endsWith("/chat/completions")?path:`${path.endsWith("/v1")?path:path+"/v1"}/chat/completions`;return url.toString();
}
export function connectionFor(ctl:GeneratorController) {
  const config=ctl.getPluginConfig(configSchematics),global=ctl.getGlobalPluginConfig(globalConfigSchematics);
  const model=config.get("model").trim();if(!model)throw new Error("Set the Strata model ID.");
  const key=global.get("apiKey").trim();
  return {config,model,endpoint:completionUrl(global.get("baseUrl")),headers:{"Content-Type":"application/json",...(key?{Authorization:`Bearer ${key}`}:{})}};
}
export async function prepareModelMessages(ctl:GeneratorController,history:Chat,definitions:LLMTool[],connection:ReturnType<typeof connectionFor>) {
  const prepared=await prepareDocumentSearch(history,ctl,definitions);
  const messages=await completeDeferredAnalyses(prepared,await toMessages(prepared,ctl.client,ctl.abortSignal,{
    getSnapshotRoot:()=>ctl.getWorkingDirectory(),warn:message=>console.warn("[Strata]",message),
  }),()=>ctl.getWorkingDirectory(),ctl.abortSignal,async(imageUrl,prompt)=>{
    const response=await fetch(connection.endpoint,{method:"POST",headers:connection.headers,signal:ctl.abortSignal,redirect:"error",body:JSON.stringify({model:connection.model,stream:false,reasoning_effort:"none",max_tokens:2048,messages:[{role:"user",content:[{type:"text",text:prompt},{type:"image_url",image_url:{url:imageUrl}}]}]})});
    if(!response.ok){await response.body?.cancel();throw new Error(`Strata image-analysis subrequest failed: HTTP ${response.status}.`);}
    const result=await response.json() as any,content=result.choices?.[0]?.message?.content;
    if(result.error || typeof content!=="string" || !content.trim())throw new Error("Strata image-analysis subrequest returned no answer.");
    return content;
  });
  const vision=addDirectVisionPolicy(messages);
  if(vision.images)console.info(`[Strata vision] images=${vision.images} directFirst=true identityLabels=true`);
  return addEvidencePolicy(vision.messages,definitions);
}