src / runtime / webTurn.ts

import type {Chat,LLMTool} from "@lmstudio/sdk";
import {Validator,type Schema} from "jsonschema";
import {ToolBridge} from "../toolBridge";

export type WebOperation="fetch_page"|"read_saved_page"|"search_saved_page"|"read_saved_json_ld";
export type Capability={id:WebOperation;name:string;definition:LLMTool};
const names:Record<WebOperation,string[]>={fetch_page:["Visit Website Advanced","Visit Website"],read_saved_page:["Read Saved Website"],search_saved_page:["Search Saved Website"],read_saved_json_ld:["Read Saved JSON-LD"]};
export function webOperation(name:string):WebOperation|undefined {
  for(const [operation,spellings] of Object.entries(names))for(const spelling of spellings) {
    for(const variant of [spelling,spelling.replace(/ /g,"_")])if(name===variant || ["/","__","."].some(separator=>name.endsWith(separator+variant)))return operation as WebOperation;
  }
}
export function webCapabilities(definitions:LLMTool[]):Capability[] {
  return definitions.flatMap(definition=>{
    const operation=webOperation(definition.function.name),schema=definition.function.parameters as any;
    if(!operation)return [];
    const key=operation==="fetch_page"?"url":"pageId";
    if(schema?.properties?.[key]?.type!=="string" || !schema.required?.includes(key))return [];
    return [{id:operation,name:definition.function.name,definition}];
  });
}
export function httpUrl(value:unknown):string|undefined {
  if(typeof value!=="string")return;
  try{const url=new URL(value);if(["http:","https:"].includes(url.protocol) && !url.username && !url.password)return url.href;}catch{}
}
// Analyze Images appends these inventories to the user message after preparing
// attachments. Their source URLs identify images, not additional page requests.
// Only classify intent from the request; keep the complete message for the model.
export function userRequestText(text:string):string {
  return text
    .replace(/(?:^|\r?\n)\[Automatically attached images\]\r?\n(?:Attachment \d+: [^\r\n]*(?:\r?\n|$))+/g,"\n")
    .replace(/(?:^|\r?\n)\[Images available to analysis tools\]\r?\n[\s\S]*?\r?\n\[End image references\]/g,"\n")
    .trim();
}
export function urlsIn(text:string):string[] {
  const clean=userRequestText(text).replace(/```[\s\S]*?```/g,"");
  return [...new Set((clean.match(/https?:\/\/[^\s<>"`]+/g)??[]).flatMap(raw=>{
    let url=raw.replace(/[。、,」』】》]+$/u,"");
    while(url.endsWith(")") && (url.match(/\)/g)?.length??0)>(url.match(/\(/g)?.length??0))url=url.slice(0,-1);
    const normalized=httpUrl(url);return normalized?[normalized]:[];
  }))];
}
function request(text:string):{kind:"open_url";urls:string[]}|{kind:"read_saved";pageId?:string}|undefined {
  text=userRequestText(text);
  const urls=urlsIn(text);
  if(/読ま(?:ない|ず)|見ない|開か(?:ない|ず)|取得(?:しない|せず)|アクセス(?:不要|しない|せず)|接続(?:しない|せず)|URLの(?:構文|形式|文字列)|do not (?:open|read|fetch|visit|access)|don't (?:open|read|fetch|visit|access)|never (?:open|read|fetch|visit|access)|without (?:opening|fetching|accessing)/i.test(text))return;
  if(urls.length) {
    const onlyUrl=text.trim().replace(/^<|>$/g,"");
    if(httpUrl(onlyUrl) || /読[むんみめ]|開[いくけ]|取得|見て|調べ|確認|要約|内容|\b(?:read|open|visit|fetch|summarize|summarise)\b|读取|阅读|读一下|打开|요약|읽어|열어|resumir|leer|abre/i.test(text))return {kind:"open_url",urls};
  }
  const id=/\bpageId\s*[=::]?\s*["']?([a-f0-9]{32})\b/.exec(text)?.[1];
  if(id && (/読|見て|確認|要約|\b(?:read|open|summarize|summarise)\b/i.test(text) || /^pageId\s*[=::]\s*["']?[a-f0-9]{32}["']?\s*$/i.test(text.trim())))return {kind:"read_saved",pageId:id};
  if(/そのページ|このページ|保存済みページ|保存したページ|\b(?:that|saved) page\b/i.test(text))return {kind:"read_saved"};
}
export type PageResource={id:string;url:string;requestedUrl:string;turn:number;blocks?:number};
export type WebCall={id:string;operation:WebOperation;name:string;args:Record<string,unknown>;turn:number;status:"pending"|"ok"|"failed";result?:string;sourceRead?:boolean;blockIds?:number[]};
export type WebTurn={kind:"open_url"|"read_saved";urls:string[];pageId?:string;resources:PageResource[];calls:WebCall[];latestUser:number;capabilities:Capability[]};
export function inspectWebTurn(history:Chat,definitions:LLMTool[]):WebTurn|undefined {
  const entries=[...history],latestUser=entries.reduce((last,m,i)=>m.getRole()==="user"?i:last,-1);
  if(latestUser<0)return;
  const current=request(entries[latestUser].getText());if(!current)return;
  const bridge=new ToolBridge(definitions);
  const capabilities=webCapabilities(definitions),resources:PageResource[]=[],calls:WebCall[]=[],pending=new Map<string,WebCall>();
  let turn=-1;
  for(const [i,message] of entries.entries()) {
    if(message.getRole()==="user")turn=i;
    if(message.getRole()==="assistant")for(const call of message.getToolCallRequests()) {
      const name=bridge.original(call.name)??call.name,operation=webOperation(name);if(!operation || !call.id || !capabilities.some(c=>c.id===operation && c.name===name))continue;
      const entry:WebCall={id:call.id,operation,name,args:call.arguments??{},turn,status:"pending"};pending.set(call.id,entry);calls.push(entry);
    }
    if(message.getRole()==="tool")for(const result of message.getToolCallResults()) {
      const call=result.toolCallId?pending.get(result.toolCallId):undefined;if(!call)continue;
      pending.delete(call.id);call.result=result.content;
      let data:any;try{data=JSON.parse(result.content);}catch{call.status="failed";continue;}
      if(!data || data.error || data.isError){call.status="failed";continue;}
      if(call.operation==="fetch_page") {
        const url=httpUrl(data.url),requestedUrl=httpUrl(call.args.url);
        if(typeof data.pageId!=="string" || !/^[a-f0-9]{32}$/.test(data.pageId) || !url || !requestedUrl){call.status="failed";continue;}
        resources.push({id:data.pageId,url,requestedUrl,turn:call.turn,...(Number.isInteger(data.totalBlocks) && data.totalBlocks>=0?{blocks:data.totalBlocks}:{})});call.status="ok";
      } else {
        call.status= data.pageId===call.args.pageId && (Array.isArray(data.blocks)||Array.isArray(data.hits)||typeof data.text==="string"||(call.operation==="read_saved_json_ld" && data.jsonLd===true))?"ok":"failed";
        if(call.operation==="read_saved_page" && call.status==="ok") {
          call.sourceRead=typeof data.text==="string" && Number.isInteger(data.htmlBlockId) && Number.isInteger(data.offset)
            && (call.args.htmlBlockId===undefined || call.args.htmlBlockId===data.htmlBlockId)
            && (call.args.postNumber===undefined || call.args.postNumber===data.postNumber);
          if(Array.isArray(data.blocks))call.blockIds=data.blocks.map((b:any)=>b.htmlBlockId).filter((id:unknown)=>Number.isInteger(id) && Number(id)>=0);
          if(call.args.htmlBlockId!==undefined && !call.sourceRead)call.status="failed";
        }
      }
    }
  }
  if(current.kind==="open_url")return {...current,resources,calls,latestUser,capabilities};
  let pageId=current.pageId;
  if(!pageId) {
    // Only an unambiguous immediately preceding page task can supply focus.
    const previous=entries.map((m,i)=>({m,i})).filter(({m,i})=>i<latestUser && m.getRole()==="user").at(-1);
    const prior=previous?request(previous.m.getText()):undefined;
    if(prior?.kind==="open_url" && prior.urls.length===1)pageId=[...resources].reverse().find(r=>r.turn===previous!.i && r.requestedUrl===prior.urls[0])?.id;
    else if(prior?.kind==="read_saved") {
      const focused=[...new Set(calls.filter(c=>c.turn===previous!.i && c.operation==="read_saved_page" && c.status==="ok").map(c=>c.args.pageId))];
      pageId=prior.pageId??(focused.length===1 && typeof focused[0]==="string"?focused[0]:undefined);
    }
  }
  return {kind:"read_saved",urls:[],pageId,resources,calls,latestUser,capabilities};
}
export type WebPlan={state:"action";capability:Capability;args:Record<string,unknown>}|{state:"answer"}|{state:"blocked";code:string};
export function planWebTurn(turn:WebTurn):WebPlan {
  if(turn.urls.length>8)return {state:"blocked",code:"too_many_urls"};
  const current=turn.calls.filter(c=>c.turn===turn.latestUser);
  const capability=(operation:WebOperation)=>turn.capabilities.filter(c=>c.id===operation);
  const action=(operation:WebOperation,args:Record<string,unknown>):WebPlan=>{
    const candidates=capability(operation);if(candidates.length!==1)return {state:"blocked",code:candidates.length?"ambiguous_capability":"required_capability_unavailable"};
    const schema=candidates[0].definition.function.parameters as Schema;
    if(!new Validator().validate(args,schema).valid)return {state:"blocked",code:"incompatible_tool_schema"};
    return {state:"action",capability:candidates[0],args};
  };
  const pages:PageResource[]=[];
  if(turn.kind==="open_url")for(const url of turn.urls) {
    const attempts=current.filter(c=>c.operation==="fetch_page" && httpUrl(c.args.url)===url);
    const page=[...turn.resources].reverse().find(r=>r.turn===turn.latestUser && r.requestedUrl===url);
    if(!page) {
      if(attempts.length)return {state:"blocked",code:attempts.at(-1)!.status==="pending"?"awaiting_tool_result":"page_fetch_failed"};
      return action("fetch_page",{url});
    }
    pages.push(page);
  } else {
    const page=[...turn.resources].reverse().find(r=>r.id===turn.pageId);
    if(!page)return {state:"blocked",code:"unknown_page_reference"};pages.push(page);
  }
  for(const page of pages) {
    const reads=current.filter(c=>c.operation==="read_saved_page" && c.args.pageId===page.id);
    if(!reads.length)return action("read_saved_page",{pageId:page.id,...(page.blocks && page.blocks>0?{htmlBlockId:0}:{})});
    if(!reads.some(c=>c.status==="ok"))return {state:"blocked",code:reads.at(-1)!.status==="pending"?"awaiting_tool_result":"saved_page_unavailable"};
    if(!reads.some(c=>c.sourceRead)) {
      const first=reads.flatMap(c=>c.status==="ok"?c.blockIds??[]:[])[0];
      if(first!==undefined) {
        const attempted=reads.filter(c=>c.args.htmlBlockId===first).at(-1);
        if(attempted)return {state:"blocked",code:attempted.status==="pending"?"awaiting_tool_result":"saved_page_unavailable"};
        return action("read_saved_page",{pageId:page.id,htmlBlockId:first});
      }
      if(page.blocks!==0)return {state:"blocked",code:"saved_page_unavailable"};
    }
  }
  return {state:"answer"};
}