#!/usr/bin/env node
/* Claude Recall (proprietary). See LICENSE for terms. */
import{parentPort as y}from"node:worker_threads";import{join as E}from"node:path";import{homedir as p}from"node:os";import{join as u,basename as C}from"node:path";var L=process.env.CLAUDE_PROJECTS_DIR?process.env.CLAUDE_PROJECTS_DIR:u(p(),".claude","projects"),i=process.env.RECALL_HOME?process.env.RECALL_HOME:u(p(),".recall"),M=u(i,"db.sqlite");var c="BAAI/bge-base-en-v1.5";var f="Represent this sentence for searching relevant passages: ";var b=64,s=null,a=!1;function k(){return E(i,"models","bge-base-en-v1.5")}async function R(){if(a&&s)return;let e;try{e=await import("@huggingface/transformers")}catch(n){console.error("[embedder-worker] @huggingface/transformers import failed:",n instanceof Error?n.message:String(n));let o=new Error("@huggingface/transformers module not available");throw o.unavailable=!0,o}let{pipeline:t,env:r}=e;r.localModelPath=E(i,"models"),r.allowRemoteModels=!1;try{s=await t("feature-extraction",c,{local_files_only:!0,cache_dir:k()}),a=!0}catch(n){if(n instanceof Error&&/Cannot find module|onnxruntime_binding/.test(n.message)){console.error("[embedder-worker] ONNX runtime unavailable:",n.message);let o=new Error("ONNX native runtime not available on this platform");throw o.unavailable=!0,o}throw n}}async function g(e){if(!s)throw new Error('Embedder not loaded. Send {type:"load"} before {type:"embed"}.');let t=[];for(let r=0;r<e.length;r+=b){let n=e.slice(r,r+b),h=(await s(n,{pooling:"cls",normalize:!0})).tolist();for(let d=0;d<n.length;d++){let l=h[d],v=Array.isArray(l[0])?l[0]:l,w=new Float32Array(v).slice();t.push(w.buffer)}}return t}function S(){return{loaded:a,modelId:c,dim:768}}async function D(e){try{if(e.type==="load")return await R(),{id:e.id,ok:!0,type:"load"};if(e.type==="embed"){let r=await g(e.texts);return{id:e.id,ok:!0,type:"embed",embeddings:r}}if(e.type==="embedQuery"){let[r]=await g([f+e.text]);return{id:e.id,ok:!0,type:"embedQuery",embedding:r}}if(e.type==="status")return{id:e.id,ok:!0,type:"status",status:S()};if(e.type==="unload")return s=null,a=!1,{id:e.id,ok:!0,type:"unload"};let t=e;throw new Error(`Unknown embedder request: ${JSON.stringify(t)}`)}catch(t){let r=t instanceof Error?t.message:String(t),n=!!t?.unavailable;return{id:e.id,ok:!1,error:r,...n?{unavailable:n}:{}}}}if(!y)throw new Error("embedder-worker.js must be loaded via worker_threads");var m=y;m.on("message",e=>{D(e).then(t=>{let r=[];t.ok&&(t.type==="embed"?r.push(...t.embeddings):t.type==="embedQuery"&&r.push(t.embedding)),m.postMessage(t,r)}).catch(t=>{console.error("[embedder-worker] postMessage failed:",t instanceof Error?t.message:String(t));try{m.postMessage({id:e.id,ok:!1,error:"worker failed to post response"})}catch{}})});
