@chatpanel/gateway 0.17.0 → 0.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ner-engine.js CHANGED
@@ -1 +1 @@
1
- import G from"node:os";import{join as b}from"node:path";import{existsSync as W,mkdirSync as V,readdirSync as U,readFileSync as K}from"node:fs";import{DEFAULT_MODEL as j,isMirroredModel as Q}from"./models.js";import{isLoopbackHost as X,isPrivateHost as Z,isMetadataHost as I}from"@chatpanel/pii";import{recaseForDetection as tt}from"@chatpanel/pii/pii-detect.js";import{verifyModelWeights as et}from"./model-integrity.js";import{runtimeName as nt}from"./model-runtime.js";const O="https://dl.chatpanel.net/models/";function rt(){const t=process.env.CHATPANEL_MODEL_BASE_URL;if(!t)return O;const e=r=>(console.warn(`[models] ignoring CHATPANEL_MODEL_BASE_URL (${t}): ${r} — using ${O}`),O);let n;try{n=new URL(t)}catch{return e("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return e(`scheme ${n.protocol} not allowed`);if(I(n.hostname))return e("points at cloud metadata");const o=X(n.hostname)||Z(n.hostname);return n.protocol==="http:"&&!o?e("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${n.origin} (CHATPANEL_MODEL_BASE_URL override), not ${O}`),t.replace(/\/*$/,"/"))}const ot=rt();let d="off",h=null,m=null,_=null,L=null,S=null,x=null;const g=new Map;function T(){return process.env.CHATPANEL_MODELS_DIR||b(G.homedir(),".chatpanel","models")}function k(t=h||j){const e=b(T(),...t.split("/"));return W(b(e,"onnx","model_quantized.onnx"))||W(b(e,"onnx","model.onnx"))}function $t(){const t=T(),e=[];try{for(const n of U(t,{withFileTypes:!0}))if(n.isDirectory())for(const o of U(b(t,n.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const r=`${n.name}/${o.name}`;k(r)&&st(b(t,n.name,o.name))&&e.push(r)}}catch{}return e}function st(t){try{return(JSON.parse(K(b(t,"config.json"),"utf8")).architectures||[]).some(n=>/ForTokenClassification$/.test(String(n)))}catch{return!1}}function At(){return d}function $(){return d==="ready"&&!!m}function vt(){return{configured:d!=="off",ok:$(),state:d,model:h,error:_,runtime:nt(),dtype:m?"q8":null,stats:yt(),companions:ut()}}async function it(t,{signal:e}={}){if(!$())return[];if(e?.aborted)return[];const n=String(t||""),o=await q(n,e);if(!o)return[];const r=[];for(const c of o||[]){let a=String(c.word??"");const p=c.entity_group??c.entity??"ENTITY";if(a.startsWith("##")&&r.length&&r[r.length-1].type===p){r[r.length-1].value+=a.slice(2);continue}a=a.replace(/##/g,"").trim(),a&&r.push({value:a,type:p})}const s=new Set,i=[];for(const c of r){const a=_t(n,wt(n,c.value.trim()));if(a.length<=1)continue;const p=`${c.type}:${a.toLowerCase()}`;s.has(p)||(s.add(p),i.push({value:a,type:c.type}))}return i}async function q(t,e){const n=performance.now(),o=[],r=[{text:t,key:"orig"}];if(A){const s=tt(t);s.changed&&r.push({text:s.text,key:"recased"})}for(const{model:s,pipe:i}of pt())for(const c of r){let a=0;for(const p of ht(c.text,i.tokenizer)){if(e?.aborted)return null;const u=c.text.indexOf(p,a),l=await i(p,{aggregation_strategy:"simple"});for(const f of l||[])o.push({...f,_win:u<0?a:u,_winText:p,_model:s,_pass:c.key,_passText:c.text});u>=0&&(a=Math.max(a,u+1))}}return gt(performance.now()-n,t.length,o.length),o}let A=!0;function Et(t){A=t!==!1}async function Nt(t,{signal:e}={}){if(!$())return[];const n=String(t||""),o=await q(n,e);if(!o)return[];const r=[],s=new Set;let i=-1,c=-1,a=null,p=null;for(const l of o){const f=String(l.word??"").replace(/##/g,"").trim();if(!f)continue;(l._win!==c||l._model!==a||l._pass!==p)&&(c=l._win,a=l._model,p=l._pass,i=l._win);const P=l._passText||n;let w=P.indexOf(f,i);if(w<0&&(w=P.indexOf(f,l._win)),w<0)continue;let M=w+f.length;i=M;const H=F=>!!F&&/[\p{L}\p{N}'’-]/u.test(F);for(;w>0&&H(n[w-1]);)w--;for(;M<n.length&&H(n[M]);)M++;const D=String(l.entity_group??l.entity??"ENTITY"),R=`${w}:${M}:${D}`;if(s.has(R))continue;s.add(R);const C=Number(l.score);r.push({value:n.slice(w,M),type:D,start:w,end:M,score:Number.isFinite(C)?Math.max(0,Math.min(1,C)):1,model:l._model})}r.sort((l,f)=>l.start-f.start||l.end-f.end);const u=[];for(const l of r){const f=u[u.length-1];if(f&&f.type===l.type&&f.end===l.start){f.end=l.end,f.value=n.slice(f.start,f.end),f.score=Math.min(f.score,l.score);continue}u.push({...l})}return g.size||A?lt(u):u}const z=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function at(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function v(t){const e=z.indexOf(at(t.type));return e<0?z.length:e}let E=[];function ct(t){E=Array.isArray(t)?t.slice():[]}function N(t){if(t.model===h)return-1;const e=E.indexOf(t.model);return e<0?E.length:e}function lt(t){const e=[...t].sort((o,r)=>o.start-r.start||r.end-o.end),n=[];for(const o of e){const r=n[n.length-1];if(r&&o.start<r.end){const s=c=>c.end-c.start;(v(o)<v(r)||v(o)===v(r)&&(s(o)>s(r)||s(o)===s(r)&&(N(o)<N(r)||N(o)===N(r)&&o.score>r.score)))&&(n[n.length-1]=o);continue}n.push(o)}return n}function Pt(){const t=m?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const n of Object.values(t)){const o=String(n).replace(/^[BIES]-/,"");o&&o!=="O"&&e.add(o)}return[...e]}function Ht(){const t=Number(m?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function ut(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function ft(t,{log:e=()=>{},allowDownload:n=!0}={}){if(!t||t===h)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:k(t)?"loading":"downloading",error:null});try{const{pipe:r}=await Y(t,{log:e,allowDownload:n});return g.set(t,{pipe:r,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(r){return g.set(t,{pipe:null,state:"error",error:r.message}),e(`[ner] companion ${t} failed to load (${r.message}) — the union runs without it`),!1}}async function Dt(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function pt(){const t=m?[{model:h,pipe:m}]:[];for(const[e,n]of g)n.pipe&&t.push({model:e,pipe:n.pipe});return t}const dt=160;function ht(t,e){const n=Number(e?.model_max_length);if(!t||!Number.isFinite(n)||n<=0||n>65536)return[t];const o=n-8,r=a=>{try{return e(a).input_ids.dims[1]}catch{return 1/0}};if(r(t)<=o)return[t];const s=[];let i=0,c=Math.max(64,Math.floor(o*3));for(;i<t.length;){let a=Math.min(t.length,i+c);if(a<t.length){const f=t.lastIndexOf(" ",a);f>i+c/2&&(a=f)}let p=t.slice(i,a);for(;r(p)>o&&p.length>32;){c=Math.max(32,Math.floor(p.length/2)),a=i+c;const f=t.lastIndexOf(" ",a);f>i+c/2&&(a=f),p=t.slice(i,a)}if(s.push(p),a>=t.length)break;const u=Math.max(i+1,a-dt),l=t.indexOf(" ",u);i=l>0&&l<a?l+1:a}return s}const mt=200,y=[];function gt(t,e,n){y.push({ms:t,chars:e,spans:n}),y.length>mt&&y.shift()}function yt(){if(!y.length)return{calls:0};const t=y.map(r=>r.ms).sort((r,s)=>r-s),e=r=>t[Math.min(t.length-1,Math.floor(r*t.length))],n=y.reduce((r,s)=>r+s.chars,0),o=y.reduce((r,s)=>r+s.ms,0);return{calls:y.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(y[y.length-1].ms),charsPerSec:o>0?Math.round(n/(o/1e3)):null}}function wt(t,e){if(!e||t.includes(e))return e;const n=t.toLowerCase().indexOf(e.toLowerCase());return n<0?e:t.slice(n,n+e.length)}function _t(t,e){if(!e)return e;const n=t.indexOf(e);if(n<0)return e;const o=i=>!!i&&/[\p{L}\p{N}'’-]/u.test(i);let r=n,s=n+e.length;for(;r>0&&o(t[r-1]);)r--;for(;s<t.length&&o(t[s]);)s++;return t.slice(r,s)}async function Rt(t,e={}){let n="";try{n=JSON.parse(e.body||"{}").text||""}catch{}const o=await it(n,{signal:e.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Ct(){return x}async function B(){if(S)return S;const t=T();try{V(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}const{env:n,pipeline:o,Tensor:r,AutoModel:s,AutoProcessor:i}=await import("@huggingface/transformers");n.cacheDir=t,n.localModelPath=t;try{n.remoteHost=ot}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return S={env:n,pipeline:o,Tensor:r,AutoModel:s,AutoProcessor:i},S}async function Y(t,{log:e=()=>{},allowDownload:n=!0,onProgress:o=()=>{}}={}){const r=await B(),s=k(t);if(r.env.allowRemoteModels=s?!1:!!n,!s&&!n)throw new Error("model not on disk and downloads disabled");const i=r.env.remoteHost,c=!Q(t);if(!s&&c)try{r.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${c?", from Hugging Face":""})…`);try{const a=u=>{u&&(u.status==="progress"||u.status==="download"||u.status==="initiate"?o(u):u.status==="done"&&u.file&&e(`[ner] fetched ${u.file}`))};let p;try{p=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:a})}catch(u){if(s||c||!n)throw u;e(`[ner] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),r.env.remoteHost="https://huggingface.co/",r.env.allowRemoteModels=!0,p=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:a})}if(!s)try{et(t,{modelsDir:T(),log:e})}catch(u){try{await p.dispose?.()}catch{}throw u}return{pipe:p,haveLocal:s}}finally{try{r.env.remoteHost=i}catch{}}}async function J(t,{log:e=()=>{},allowDownload:n=!0}={}){const o=m,r=h;try{await B()}catch(i){return d="error",_=`engine load failed: ${i.message}`,e(`[ner] transformers.js not available (${i.message}) — deterministic-only`),!1}const s=k(t);if(!s&&!n)return d="error",_="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(x={model:t,file:null,pct:0});try{const{pipe:i}=await Y(t,{log:e,allowDownload:n,onProgress:c=>{x={model:t,file:c.file||x?.file||null,pct:typeof c.progress=="number"?Math.round(c.progress):x?.pct??0}}});if(m=i,h=t,d="ready",_=null,x=null,o&&o!==i)try{await o.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),!0}catch(i){return _=i.message,x=null,o?(m=o,h=r,d="ready"):d="error",e(`[ner] model load failed (${i.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function Ft(t={}){if(L)return L;const e=typeof t.onLog=="function"?t.onLog:()=>{};h=t.model||j,d="loading";const n=t.allowDownload!==!1;return L=J(h,{log:e,allowDownload:n}).then(async o=>{const r=Array.isArray(t.union)?t.union:[];ct(r);for(const s of r)await ft(s,{log:e,allowDownload:n});return o}),L}async function Wt(t,e={}){const n=typeof e.onLog=="function"?e.onLog:()=>{},o=e.allowDownload!==!1;if(!t)return!1;if(t===h&&$())return!0;const r=g.get(t);if(r?.pipe){const s=m;if(m=r.pipe,h=t,d="ready",_=null,g.delete(t),s)try{await s.dispose?.()}catch{}return n(`[ner] ${t} promoted from the union to primary`),!0}return J(t,{log:n,allowDownload:o})}function Ut(){d="off",h=null,m=null,_=null,L=null,S=null,x=null,y.length=0,g.clear(),A=!0,E=[]}function jt(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function qt(t,{model:e="test/model"}={}){m=t,h=e,d="ready",_=null,y.length=0}export{Ut as _reset,jt as _setCompanionForTest,qt as _setForTest,ft as addCompanion,ut as companions,it as detect,Nt as detectSpans,B as ensureLib,Rt as fetchAdapter,vt as health,Ft as init,$ as isReady,Pt as labels,Ht as maxTokens,k as modelOnDisk,T as modelRoot,$t as modelsOnDisk,Ct as progress,Dt as removeCompanion,rt as resolveModelHost,Et as setCaseRecovery,Wt as setModel,ct as setUnionOrder,At as state,yt as stats,lt as unionSpans,ht as windowsFor};
1
+ import nt from"node:os";import{join as O}from"node:path";import{existsSync as B,mkdirSync as rt,readdirSync as Y,readFileSync as ot}from"node:fs";import{DEFAULT_MODEL as J,isMirroredModel as st}from"./models.js";import{isLoopbackHost as it,isPrivateHost as at,isMetadataHost as lt}from"@chatpanel/pii";import{recaseForDetection as ct}from"@chatpanel/pii/pii-detect.js";import{verifyModelWeights as ut}from"./model-integrity.js";import{runtimeName as ft}from"./model-runtime.js";import{makeWarmTimer as Q}from"./warm-timer.js";import{makeModelFileCache as pt}from"./model-file-cache.js";const N="https://dl.chatpanel.net/models/";function dt(){const t=process.env.CHATPANEL_MODEL_BASE_URL;if(!t)return N;const e=r=>(console.warn(`[models] ignoring CHATPANEL_MODEL_BASE_URL (${t}): ${r} — using ${N}`),N);let n;try{n=new URL(t)}catch{return e("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return e(`scheme ${n.protocol} not allowed`);if(lt(n.hostname))return e("points at cloud metadata");const o=it(n.hostname)||at(n.hostname);return n.protocol==="http:"&&!o?e("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${n.origin} (CHATPANEL_MODEL_BASE_URL override), not ${N}`),t.replace(/\/*$/,"/"))}const mt=dt();let d="off",h=null,g=null,x=null,L=null,A=null,M=null,T=null,w=null,C=0,v=null;const m=new Map;function E(){return process.env.CHATPANEL_MODELS_DIR||O(nt.homedir(),".chatpanel","models")}function H(t=h||J){const e=O(E(),...t.split("/"));return B(O(e,"onnx","model_quantized.onnx"))||B(O(e,"onnx","model.onnx"))}function jt(){const t=E(),e=[];try{for(const n of Y(t,{withFileTypes:!0}))if(n.isDirectory())for(const o of Y(O(t,n.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const r=`${n.name}/${o.name}`;H(r)&&ht(O(t,n.name,o.name))&&e.push(r)}}catch{}return e}function ht(t){try{return(JSON.parse(ot(O(t,"config.json"),"utf8")).architectures||[]).some(n=>/ForTokenClassification$/.test(String(n)))}catch{return!1}}function qt(){return d}function k(){return d==="ready"&&!!g}function zt(){return{configured:d!=="off",ok:k(),state:d,model:h,error:x,runtime:ft(),dtype:g?"q8":null,stats:kt(),companions:Mt(),warmMs:w?.warmMs??null}}async function gt(t,{signal:e}={}){if(!k())return[];if(e?.aborted)return[];const n=String(t||""),o=await G(n,e);if(!o)return[];const r=[];for(const i of o||[]){let u=String(i.word??"");const a=i.entity_group??i.entity??"ENTITY";if(u.startsWith("##")&&r.length&&r[r.length-1].type===a){r[r.length-1].value+=u.slice(2);continue}u=u.replace(/##/g,"").trim(),u&&r.push({value:u,type:a})}const s=new Set,c=[];for(const i of r){const u=At(n,$t(n,i.value.trim()));if(u.length<=1)continue;const a=`${i.type}:${u.toLowerCase()}`;s.has(a)||(s.add(a),c.push({value:u,type:i.type}))}return c}async function G(t,e){C++;try{return await yt(t,e)}finally{C--,$()||w?.arm()}}async function yt(t,e){const n=performance.now(),o=[],r=[{text:t,key:"orig"}];if(P){const s=ct(t);s.changed&&r.push({text:s.text,key:"recased"})}for(const{model:s,pipe:c}of V())for(const i of r){let u=0;for(const a of St(i.text,c.tokenizer)){if(e?.aborted)return null;const l=i.text.indexOf(a,u),f=await c(a,{aggregation_strategy:"simple"});for(const p of f||[])o.push({...p,_win:l<0?u:l,_winText:a,_model:s,_pass:i.key,_passText:i.text});l>=0&&(u=Math.max(u,l+1))}}return Tt(performance.now()-n,t.length,o.length),o}let P=!0;function Bt(t){P=t!==!1}async function Yt(t,{signal:e}={}){if(!k())return[];const n=String(t||""),o=await G(n,e);if(!o)return[];const r=[],s=new Set;let c=-1,i=-1,u=null,a=null;for(const f of o){const p=String(f.word??"").replace(/##/g,"").trim();if(!p)continue;(f._win!==i||f._model!==u||f._pass!==a)&&(i=f._win,u=f._model,a=f._pass,c=f._win);const b=f._passText||n;let _=b.indexOf(p,c);if(_<0&&(_=b.indexOf(p,f._win)),_<0)continue;let S=_+p.length;c=S;const W=z=>!!z&&/[\p{L}\p{N}'’-]/u.test(z);for(;_>0&&W(n[_-1]);)_--;for(;S<n.length&&W(n[S]);)S++;const U=String(f.entity_group??f.entity??"ENTITY"),j=`${_}:${S}:${U}`;if(s.has(j))continue;s.add(j);const q=Number(f.score);r.push({value:n.slice(_,S),type:U,start:_,end:S,score:Number.isFinite(q)?Math.max(0,Math.min(1,q)):1,model:f._model})}r.sort((f,p)=>f.start-p.start||f.end-p.end);const l=[];for(const f of r){const p=l[l.length-1];if(p&&p.type===f.type&&p.end===f.start){p.end=f.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,f.score);continue}l.push({...f})}return m.size||P?xt(l):l}const K=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function wt(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function D(t){const e=K.indexOf(wt(t.type));return e<0?K.length:e}let R=[];function _t(t){R=Array.isArray(t)?t.slice():[]}function F(t){if(t.model===h)return-1;const e=R.indexOf(t.model);return e<0?R.length:e}function xt(t){const e=[...t].sort((o,r)=>o.start-r.start||r.end-o.end),n=[];for(const o of e){const r=n[n.length-1];if(r&&o.start<r.end){const s=i=>i.end-i.start;(D(o)<D(r)||D(o)===D(r)&&(s(o)>s(r)||s(o)===s(r)&&(F(o)<F(r)||F(o)===F(r)&&o.score>r.score)))&&(n[n.length-1]=o);continue}n.push(o)}return n}function Jt(){const t=g?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const n of Object.values(t)){const o=String(n).replace(/^[BIES]-/,"");o&&o!=="O"&&e.add(o)}return[...e]}function Qt(){const t=Number(g?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function Mt(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function bt(t,{log:e=()=>{},allowDownload:n=!0}={}){if(!t||t===h)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:H(t)?"loading":"downloading",error:null});try{const{pipe:r}=await I(t,{log:e,allowDownload:n});return m.set(t,{pipe:r,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(r){return m.set(t,{pipe:null,state:"error",error:r.message}),e(`[ner] companion ${t} failed to load (${r.message}) — the union runs without it`),!1}}async function Gt(t){const e=m.get(t);if(!e)return!1;m.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function V(){const t=g?[{model:h,pipe:g}]:[];for(const[e,n]of m)n.pipe&&t.push({model:e,pipe:n.pipe});return t}const Lt=160,X=256;function St(t,e){if(!t||typeof e!="function")return[t];const n=Number(e.model_max_length),r=Math.min(X,Number.isFinite(n)&&n>0?n:X)-8,s=a=>{try{return e(a).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=r)return[t];const c=[];let i=0,u=Math.max(64,Math.floor(r*3));for(;i<t.length;){let a=Math.min(t.length,i+u);if(a<t.length){const b=t.lastIndexOf(" ",a);b>i+u/2&&(a=b)}let l=t.slice(i,a);for(;s(l)>r&&l.length>32;){u=Math.max(32,Math.floor(l.length/2)),a=i+u;const b=t.lastIndexOf(" ",a);b>i+u/2&&(a=b),l=t.slice(i,a)}if(c.push(l),a>=t.length)break;const f=Math.max(i+1,a-Lt),p=t.indexOf(" ",f);i=p>0&&p<a?p+1:a}return c}const Ot=200,y=[];function Tt(t,e,n){y.push({ms:t,chars:e,spans:n}),y.length>Ot&&y.shift()}function kt(){if(!y.length)return{calls:0};const t=y.map(r=>r.ms).sort((r,s)=>r-s),e=r=>t[Math.min(t.length-1,Math.floor(r*t.length))],n=y.reduce((r,s)=>r+s.chars,0),o=y.reduce((r,s)=>r+s.ms,0);return{calls:y.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(y[y.length-1].ms),charsPerSec:o>0?Math.round(n/(o/1e3)):null}}function $t(t,e){if(!e||t.includes(e))return e;const n=t.toLowerCase().indexOf(e.toLowerCase());return n<0?e:t.slice(n,n+e.length)}function At(t,e){if(!e)return e;const n=t.indexOf(e);if(n<0)return e;const o=c=>!!c&&/[\p{L}\p{N}'’-]/u.test(c);let r=n,s=n+e.length;for(;r>0&&o(t[r-1]);)r--;for(;s<t.length&&o(t[s]);)s++;return t.slice(r,s)}async function Kt(t,e={}){let n="";try{n=JSON.parse(e.body||"{}").text||""}catch{}const o=await gt(n,{signal:e.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Vt(){return M}async function Z(){if(A)return A;const t=E();try{rt(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}const{env:n,pipeline:o,Tensor:r,AutoModel:s,AutoProcessor:c}=await import("@huggingface/transformers");n.cacheDir=t,n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=pt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=mt}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return A={env:n,pipeline:(u,a,l={})=>o(u,a,l.progress_callback&&n.allowRemoteModels===!1?{...l,progress_callback:void 0}:l),Tensor:r,AutoModel:s,AutoProcessor:c},A}async function I(t,{log:e=()=>{},allowDownload:n=!0,onProgress:o=()=>{}}={}){const r=await Z(),s=H(t);if(r.env.allowRemoteModels=s?!1:!!n,!s&&!n)throw new Error("model not on disk and downloads disabled");const c=r.env.remoteHost,i=!st(t);if(!s&&i)try{r.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${i?", from Hugging Face":""})…`);try{const u=l=>{l&&(l.status==="progress"||l.status==="download"||l.status==="initiate"?o(l):l.status==="done"&&l.file&&e(`[ner] fetched ${l.file}`))};let a;try{a=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}catch(l){if(s||i||!n)throw l;e(`[ner] mirror fetch failed (${String(l.message).slice(0,80)}) — retrying from Hugging Face…`),r.env.remoteHost="https://huggingface.co/",r.env.allowRemoteModels=!0,a=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}if(!s)try{ut(t,{modelsDir:E(),log:e})}catch(l){try{await a.dispose?.()}catch{}throw l}return{pipe:a,haveLocal:s}}finally{try{r.env.remoteHost=c}catch{}}}async function tt(t,{log:e=()=>{},allowDownload:n=!0}={}){const o=g,r=h;try{await Z()}catch(c){return d="error",x=`engine load failed: ${c.message}`,e(`[ner] transformers.js not available (${c.message}) — deterministic-only`),!1}const s=H(t);if(!s&&!n)return d="error",x="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(M={model:t,file:null,pct:0});try{const{pipe:c}=await I(t,{log:e,allowDownload:n,onProgress:i=>{M={model:t,file:i.file||M?.file||null,pct:typeof i.progress=="number"?Math.round(i.progress):M?.pct??0}}});if(g=c,h=t,d="ready",x=null,M=null,T&&(T={...T,model:t}),o&&o!==c)try{await o.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||w?.arm(),!0}catch(c){return x=c.message,M=null,o?(g=o,h=r,d="ready"):d="error",e(`[ner] model load failed (${c.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function vt(t={}){if(L)return L;const e=typeof t.onLog=="function"?t.onLog:()=>{};T=t,h=t.model||J,d="loading";const n=t.allowDownload!==!1;return w=Q({warmMs:t.warmMs,busy:$,log:e,unload:()=>et({log:e})}),L=tt(h,{log:e,allowDownload:n}).then(async o=>{const r=Array.isArray(t.union)?t.union:[];_t(r);for(const s of r)await bt(s,{log:e,allowDownload:n});return k()&&!$()&&w?.arm(),o}),L}function $(){if(C>0||d==="loading"||d==="downloading")return!0;for(const t of m.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function et({log:t=()=>{}}={}){if($())return!1;w?.disarm();const e=V().map(n=>n.pipe);g=null,L=null,M=null,x=null,m.clear(),d=e.length?"idle":"off";for(const n of e)try{await n.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((w?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function Xt(){try{d==="idle"&&(v||T)?await(v?v():vt(T)):L&&await L}catch{}return k()}async function Zt(t,e={}){const n=typeof e.onLog=="function"?e.onLog:()=>{},o=e.allowDownload!==!1;if(!t)return!1;if(t===h&&k())return!0;const r=m.get(t);if(r?.pipe){const s=g;if(g=r.pipe,h=t,d="ready",x=null,m.delete(t),s)try{await s.dispose?.()}catch{}return n(`[ner] ${t} promoted from the union to primary`),!0}return tt(t,{log:n,allowDownload:o})}function It(){d="off",h=null,g=null,x=null,L=null,A=null,M=null,y.length=0,m.clear(),P=!0,R=[],w?.disarm(),w=null,T=null,C=0,v=null}function te(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function ee(t,{model:e="test/model",warmMs:n=null,reload:o=null}={}){g=t,h=e,d="ready",x=null,y.length=0,o&&(v=o),n!==null&&(w=Q({warmMs:n,busy:$,unload:()=>et()}),t&&w.arm())}export{It as _reset,te as _setCompanionForTest,ee as _setForTest,bt as addCompanion,Mt as companions,gt as detect,Yt as detectSpans,Xt as ensure,Z as ensureLib,Kt as fetchAdapter,zt as health,vt as init,k as isReady,Jt as labels,Qt as maxTokens,H as modelOnDisk,E as modelRoot,jt as modelsOnDisk,Vt as progress,Gt as removeCompanion,dt as resolveModelHost,Bt as setCaseRecovery,Zt as setModel,_t as setUnionOrder,qt as state,kt as stats,xt as unionSpans,et as unload,St as windowsFor};
package/src/ner.js CHANGED
@@ -1 +1 @@
1
- import c from"node:os";import*as i from"./ner-engine.js";import{persistConfig as u,configPath as f}from"./configstore.js";import{MODEL_CATALOG as m}from"./models.js";import{fitUnion as p}from"@chatpanel/pii/detector-router.js";function a(e,{totalRamMB:n=Math.round(c.totalmem()/1048576),log:l=()=>{}}={}){const t=Array.isArray(e?.union)?e.union.filter(o=>o&&o!==e.model):[],r=p(e?.model,t,m,{totalRamMB:n});for(const o of r.skipped)l(`[ner] not loading ${o.id} — ${o.why}`);return d=r.skipped,r.load}let d=[];function b(){return d.slice()}function $(e){const n=e.ner;if(!n||!n.autostart)return null;const l=e.redaction?.detection;if(l&&l.url&&/127\.0\.0\.1:9009\/ner/.test(l.url)){e.redaction.detection={backend:"off"},e.ner&&delete e.ner.port;try{u(e,f())}catch{}console.log("[ner] migrated legacy spaCy detector config (:9009) → in-process engine")}const t=e.redaction?.detection;if(t&&t.backend&&t.backend!=="off")return n.enableFullTier&&e.redaction.tier!=="full"&&(e.redaction.tier="full"),console.log(`[ner] using configured detector (${t.backend} ${t.url||""}) — full tier ${e.redaction.tier==="full"?"on":"off"}`),null;let r=!1;return i.setCaseRecovery(n.caseRecovery!==!1),i.init({model:n.model,union:a(n,{log:o=>console.log(o)}),allowDownload:n.allowDownload!==!1,onLog:o=>{r||console.log(o)}}).then(()=>{r||i.isReady()&&n.enableFullTier&&e.redaction.tier!=="full"&&(e.redaction.tier="full",console.log("[ner] full tier on — name/org redaction active"))}).catch(o=>{r||console.log(`[ner] init error (${o.message}) — deterministic-only`)}),{stop(){r=!0}}}async function g(e,{log:n=l=>console.log(l)}={}){const l=e?.redaction?.detection;if(l&&l.backend&&l.backend!=="off")return"external";const t=i.state();if(t==="ready")return t;if(t==="loading"||t==="downloading"||t==="error"){try{await i.init()}catch{}return i.state()}const r=e?.ner||{},o=r.model||void 0;if(!i.modelOnDisk(o))return"not-downloaded";try{await i.init({model:o,union:a({...r,model:o},{log:n}),allowDownload:!1,onLog:n})}catch(s){return n(`[ner] on-demand load failed (${s.message}) — deterministic-only`),i.state()}return i.isReady()&&(n(`[ner] started on demand — model ${i.health().model} — entity detection active`),r.enableFullTier!==!1&&e.redaction&&e.redaction.tier!=="full"&&(e.redaction.tier="full",n("[ner] full tier on — name/org redaction active"))),i.state()}export{g as ensureNer,b as skippedCompanions,$ as startNer,a as unionForThisMachine};
1
+ import c from"node:os";import*as r from"./ner-engine.js";import{persistConfig as u,configPath as f}from"./configstore.js";import{MODEL_CATALOG as m}from"./models.js";import{fitUnion as p}from"@chatpanel/pii/detector-router.js";function l(e,{totalRamMB:n=Math.round(c.totalmem()/1048576),log:a=()=>{}}={}){const o=Array.isArray(e?.union)?e.union.filter(t=>t&&t!==e.model):[],i=p(e?.model,o,m,{totalRamMB:n});for(const t of i.skipped)a(`[ner] not loading ${t.id} — ${t.why}`);return d=i.skipped,i.load}let d=[];function b(){return d.slice()}function $(e){const n=e.ner;if(!n||!n.autostart)return null;const a=e.redaction?.detection;if(a&&a.url&&/127\.0\.0\.1:9009\/ner/.test(a.url)){e.redaction.detection={backend:"off"},e.ner&&delete e.ner.port;try{u(e,f())}catch{}console.log("[ner] migrated legacy spaCy detector config (:9009) → in-process engine")}const o=e.redaction?.detection;if(o&&o.backend&&o.backend!=="off")return n.enableFullTier&&e.redaction.tier!=="full"&&(e.redaction.tier="full"),console.log(`[ner] using configured detector (${o.backend} ${o.url||""}) — full tier ${e.redaction.tier==="full"?"on":"off"}`),null;let i=!1;return r.setCaseRecovery(n.caseRecovery!==!1),r.init({model:n.model,union:l(n,{log:t=>console.log(t)}),allowDownload:n.allowDownload!==!1,warmMs:n.warmMs,onLog:t=>{i||console.log(t)}}).then(()=>{i||r.isReady()&&n.enableFullTier&&e.redaction.tier!=="full"&&(e.redaction.tier="full",console.log("[ner] full tier on — name/org redaction active"))}).catch(t=>{i||console.log(`[ner] init error (${t.message}) — deterministic-only`)}),{stop(){i=!0}}}async function g(e,{log:n=a=>console.log(a)}={}){const a=e?.redaction?.detection;if(a&&a.backend&&a.backend!=="off")return"external";const o=r.state();if(o==="ready")return o;if(o==="idle")return await r.ensure(),r.state();if(o==="loading"||o==="downloading"||o==="error"){try{await r.init()}catch{}return r.state()}const i=e?.ner||{},t=i.model||void 0;if(!r.modelOnDisk(t))return"not-downloaded";try{await r.init({model:t,union:l({...i,model:t},{log:n}),allowDownload:!1,warmMs:i.warmMs,onLog:n})}catch(s){return n(`[ner] on-demand load failed (${s.message}) — deterministic-only`),r.state()}return r.isReady()&&(n(`[ner] started on demand — model ${r.health().model} — entity detection active`),i.enableFullTier!==!1&&e.redaction&&e.redaction.tier!=="full"&&(e.redaction.tier="full",n("[ner] full tier on — name/org redaction active"))),r.state()}export{g as ensureNer,b as skippedCompanions,$ as startNer,l as unionForThisMachine};
package/src/redact.js CHANGED
@@ -1,3 +1,3 @@
1
- import{createVault as I,redactText as S,detectEntities as v,gatedDictionary as T,sanitizeUnicode as z}from"@chatpanel/pii";import{ENTITIES_SCHEMA as y,entitiesFormat as A}from"./extraction.js";import{describeSchema as N,coerce as j}from"./structured.js";import*as w from"./ner-engine.js";async function R(r,s,{signal:b,isPro:h=!0,onEgress:x=null,fetchImpl:E=null,nerEngine:u=w}={}){const i=I();let a=0;for(const t of r){const e=t.get();if(typeof e!="string"||!e)continue;const{clean:n,removed:g}=z(e);g&&(t.set(n),a+=g)}const l=r.map(t=>t.get()).filter(t=>typeof t=="string"&&t);if(l.length===0)return{vault:i,count:0,sanitized:a};const m=s.tier==="full"?"full":"basic",M=T(s,h),o=s.detection,p=!!(o&&o.backend&&o.backend!=="off"),c=!p&&u.isReady();let f=[];if(m==="full"&&(p||c)){const t=c?{backend:"endpoint",url:"inproc:ner",transport:"in-process",timeoutMs:3e4,maxChars:8e3,types:o?.types}:{...o,timeoutMs:Math.max(Number(o.timeoutMs)||0,3e4)},e=c?u.fetchAdapter:E||void 0;try{f=await v(l.join(`
1
+ import{createVault as I,redactText as S,detectEntities as v,gatedDictionary as T,sanitizeUnicode as w}from"@chatpanel/pii";import{ENTITIES_SCHEMA as b,entitiesFormat as z}from"./extraction.js";import{describeSchema as A,coerce as N}from"./structured.js";import*as j from"./ner-engine.js";async function R(s,r,{signal:g,isPro:h=!0,onEgress:x=null,fetchImpl:M=null,nerEngine:c=j}={}){const a=I();let f=0;for(const t of s){const e=t.get();if(typeof e!="string"||!e)continue;const{clean:n,removed:y}=w(e);y&&(t.set(n),f+=y)}const m=s.map(t=>t.get()).filter(t=>typeof t=="string"&&t);if(m.length===0)return{vault:a,count:0,sanitized:f};const u=r.tier==="full"?"full":"basic",k=T(r,h),o=r.detection,l=!!(o&&o.backend&&o.backend!=="off");u==="full"&&!l&&typeof c.ensure=="function"&&await c.ensure();const i=!l&&c.isReady();let p=[];if(u==="full"&&(l||i)){const t=i?{backend:"endpoint",url:"inproc:ner",transport:"in-process",timeoutMs:3e4,maxChars:8e3,types:o?.types}:{...o,timeoutMs:Math.max(Number(o.timeoutMs)||0,3e4)},e=i?c.fetchAdapter:M||void 0;try{p=await v(m.join(`
2
2
 
3
- `),{detection:t},{signal:b,fetchImpl:e,onEgress:c?null:x,structured:{block:N(y),format:n=>A(n),parse:n=>j(n,y)?.value??null}})}catch{f=[]}}const k={tier:m,entities:f,dictionary:M};let d=0;for(const t of r){const e=t.get();if(typeof e!="string"||!e)continue;const n=S(e,i,k);n!==e&&d++,t.set(n)}return{vault:i,count:d,sanitized:a}}function U(r,s){return{get:r,set:s}}export{R as redactSegments,U as segment};
3
+ `),{detection:t},{signal:g,fetchImpl:e,onEgress:i?null:x,structured:{block:A(b),format:n=>z(n),parse:n=>N(n,b)?.value??null}})}catch{p=[]}}const E={tier:u,entities:p,dictionary:k};let d=0;for(const t of s){const e=t.get();if(typeof e!="string"||!e)continue;const n=S(e,a,E);n!==e&&d++,t.set(n)}return{vault:a,count:d,sanitized:f}}function U(s,r){return{get:s,set:r}}export{R as redactSegments,U as segment};
@@ -0,0 +1 @@
1
+ const g=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/,M=Object.freeze([{id:"BAAI/bge-reranker-v2-m3",label:"bge-reranker v2 m3",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:2600,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; the ship default."},{id:"BAAI/bge-reranker-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",note:"Half the size, most of the quality. The pick when the engine has 2 GB."},{id:"BAAI/bge-reranker-large",label:"bge-reranker large",lang:"100+ languages",tier:"max",approxMB:2240,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The first-generation large model; v2 m3 is newer and usually better at the same cost."},{id:"mixedbread-ai/mxbai-rerank-base-v1",label:"mxbai-rerank base v1",lang:"English",tier:"balanced",approxMB:740,ramMB:900,minRamMB:2048,licence:"Apache-2.0",note:"English-only, small and quick — a good fit for notes and search on a modest machine."},{id:"cross-encoder/ms-marco-MiniLM-L-6-v2",label:"MiniLM-L6 (MS MARCO)",lang:"English",tier:"light",approxMB:90,ramMB:300,minRamMB:1024,licence:"Apache-2.0",note:"Tiny and fast; the classic web-search reranker. English only, short passages."}]),p=Object.freeze([{id:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",label:"ModernBERT large zero-shot v2",lang:"English",tier:"accurate",approxMB:1600,ramMB:2400,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"What OpenDecision ships with; 8k context. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",note:"A third of the size, close on most typed decisions. The pick when the engine has 2 GB."},{id:"MoritzLaurer/deberta-v3-large-zeroshot-v2.0",label:"DeBERTa v3 large zero-shot v2",lang:"English",tier:"max",approxMB:1740,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The strongest English zero-shot classifier of the family; slower than ModernBERT, 512 tokens."},{id:"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli",label:"mDeBERTa v3 base (XNLI)",lang:"100 languages",tier:"balanced",approxMB:1120,ramMB:1400,minRamMB:2048,licence:"MIT",note:"The multilingual one: sentiment, routing and triage in Hindi, Telugu, Spanish, German… on the same questions."},{id:"MoritzLaurer/deberta-v3-xsmall-zeroshot-v1.1-all-33",label:"DeBERTa v3 xsmall zero-shot",lang:"English",tier:"light",approxMB:280,ramMB:500,minRamMB:1024,licence:"MIT",note:"Tiny and quick — decisions in tens of milliseconds on any machine, at some accuracy."}]),u={reranker:M,opendecision:p};function d(r){return u[r]||[]}function b(r,a){if(typeof a!="string"||!a.trim())return!1;const n=a.trim();return d(r).some(o=>o.id===n)||g.test(n)}function B(r){return`models--${String(r).replace(/\//g,"--")}`}function x(r,{active:a=null,engineRamMB:n=0,engine:o=null,platform:l=process.platform,installed:c=()=>!1}={}){const t=e=>`${Math.round(e/1024*10)/10} GB`,m=e=>o==="podman"&&l!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((e.ramMB+2048)/2048)*2048)} && podman machine start`:o==="docker"&&l!=="linux"?"raise the memory in Docker Desktop › Settings › Resources":null,i=d(r).map(e=>{const s=n>0&&e.ramMB>n,h=!s&&Number(e.minRamMB)>0&&n>0&&n<e.minRamMB;return{...e,installed:c(e.id),recommended:!!e.recommended&&!s&&!h,...s?{unavailable:`needs about ${t(e.ramMB)} of memory while loaded — the container engine has ${t(n)}${m(e)?`; raise it: ${m(e)}`:""}`}:{},...h?{ramNote:`needs about ${t(e.ramMB)} while loaded — the engine has ${t(n)}; expect it to slow things down`}:{}}});return a&&!i.some(e=>e.id===a)&&i.push({id:a,label:a,lang:"—",tier:"custom",custom:!0,installed:c(a),note:"Custom model (from Hugging Face)."}),i}export{p as DECIDE_MODEL_CATALOG,g as HF_ID,M as RERANK_MODEL_CATALOG,B as cacheDirName,d as catalogFor,b as isValidModelId,x as modelsFor};
package/src/runtime.js ADDED
@@ -0,0 +1,3 @@
1
+ import{promisify as U}from"node:util";import{execFile as K}from"node:child_process";import{existsSync as Q,mkdirSync as L,writeFileSync as Y}from"node:fs";import{randomBytes as Z}from"node:crypto";import C from"node:os";import S from"node:path";import{modelsFor as F,isValidModelId as ee,cacheDirName as ne,catalogFor as te}from"./runtime-models.js";const re=U(K),_=["podman","docker"],A="hf-cache",D=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only.",caps:["CHOWN","SETGID","SETUID"],answers:async(e,i)=>{try{return(await i(`${e}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:e=>String(e.search?.searxng?.url||""),configure:(e,i)=>{e.search=e.search||{},e.search.searxng={...e.search.searxng||{},url:i}},unconfigure:(e,i)=>{e.search?.searxng?.url===i&&(e.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],adapter:"tei",model:"BAAI/bge-reranker-v2-m3",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. A cross-encoder (bge-reranker-v2-m3, multilingual) behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:e=>[`${S.join(e,A)}:/data`],env:e=>["HF_HOME=/data",`MODEL_ID=${e.model}`],answers:async(e,i)=>{try{return(await i(`${e}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:e=>String(e.capabilities?.rerank?.url||""),configure:(e,i,l)=>{e.capabilities=e.capabilities||{},e.capabilities.rerank={url:i,adapter:l.adapter,model:l.model,service:l.id}},unconfigure:(e,i)=>{e.capabilities?.rerank?.url===i&&delete e.capabilities.rerank}},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],adapter:"systemone",model:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:e=>[`${S.join(e,A)}:/data`],env:e=>["HF_HOME=/data",`MODEL_ID=${e.model}`],answers:async(e,i)=>{try{return(await i(`${e}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:e=>String(e.capabilities?.decide?.url||""),configure:(e,i,l)=>{e.capabilities=e.capabilities||{},e.capabilities.decide={url:i,adapter:l.adapter,model:l.model,service:l.id,calibrated:l.calibrated}},unconfigure:(e,i)=>{e.capabilities?.decide?.url===i&&delete e.capabilities.decide}}]),N=e=>D.find(i=>i.id===e)||null,oe=({answers:e,configured:i,configure:l,unconfigure:w,volumes:$,args:d,env:E,caps:b,...M})=>M;function ae(e=[]){return["# Written by chatpanel-gateway (Settings › Runtime). JSON on, the limiter off — the port is","# bound to 127.0.0.1, which is what makes that safe. Do not publish it on 0.0.0.0.","use_default_settings: true","general:",' instance_name: "ChatPanel search"'," debug: false"," enable_metrics: false","server:",' secret_key: "${SEARXNG_SECRET}"'," limiter: false"," public_instance: false"," image_proxy: false",' method: "GET"',"search:"," safe_search: 0",' autocomplete: ""'," formats:"," - html"," - json","ui:"," static_use_hash: true","engines:",...(e.length?e:["duckduckgo","brave","startpage","bing","wikipedia","qwant"]).flatMap(l=>[` - name: ${l}`," disabled: false"])," - name: google"," disabled: true",""].join(`
2
+ `)}function B(e=process.platform){return e==="darwin"?{command:"brew install podman",url:"https://podman.io/docs/installation#macos",note:"Homebrew; then Start the engine below (it creates and starts the Podman machine)."}:e==="win32"?{command:"winget install RedHat.Podman",url:"https://podman.io/docs/installation#windows",note:"Then Start the engine below (it creates and starts the Podman machine under WSL)."}:{command:"sudo apt install podman # or: sudo dnf install podman",url:"https://podman.io/docs/installation#installing-on-linux",note:"Rootless; no daemon to start."}}function G(e,i){const l=i==="podman"?Array.isArray(e.Names)?e.Names[0]:String(e.Names||""):String(e.Names||e.Name||""),w=i==="podman"?Array.isArray(e.Ports)?e.Ports.map(d=>`${d.host_ip||""}:${d.host_port}->${d.container_port}/${d.protocol||"tcp"}`):[]:String(e.Ports||"").split(",").map(d=>d.trim()).filter(Boolean),$=String(e.State||"").toLowerCase()||(/^up/i.test(String(e.Status||""))?"running":"exited");return{name:l,image:String(e.Image||""),state:$,status:String(e.Status||""),ports:w,ours:l.startsWith("chatpanel-"),engine:i}}function fe({cfg:e,bridgeHealth:i,workers:l=()=>[],persist:w=()=>{},exec:$=(u,h,v={})=>re(u,h,{timeout:6e4,...v}),platform:d=process.platform,fetchImpl:E=globalThis.fetch,stateDir:b=S.join(C.homedir(),".chatpanel","runtime"),log:M=()=>{},sleep:J=u=>new Promise(h=>setTimeout(h,u)),totalMem:W=()=>C.totalmem()}={}){const u=async(t,o,r)=>{try{const n=await $(t,o,r);return{ok:!0,out:String(n.stdout||"").trim(),err:String(n.stderr||"").trim()}}catch(n){return{ok:!1,out:String(n?.stdout||"").trim(),err:String(n?.stderr||n?.message||n).trim(),code:n?.code}}},h=t=>String(e.runtime?.services?.[t.id]?.model||t.model||""),v=t=>t.model?{...t,model:h(t)}:t,P=t=>Q(S.join(b,A,"hub",ne(t)));async function j(t,o){if(!t||!o?.[t]?.running)return 0;if(t==="podman"&&d!=="linux"){const r=await u("podman",["machine","inspect","--format","{{.Resources.Memory}}"],{timeout:8e3}),n=parseInt(r.out,10);return r.ok&&n>0?n:0}if(t==="docker"&&d!=="linux"){const r=await u("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),n=parseInt(r.out,10);return r.ok&&n>0?Math.round(n/1048576):0}return Math.round(W()/1048576)}async function k(){const t={};for(const r of _){const n=await u(r,["--version"],{timeout:5e3});if(!n.ok){t[r]={installed:!1};continue}const a=(n.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||n.out;let s=!1,m=null;if(r==="podman")if(d==="linux")s=(await u("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const c=await u("podman",["machine","list","--format","json"],{timeout:8e3});try{const f=JSON.parse(c.out||"[]")[0]||null;m=f?{name:f.Name,running:!!f.Running}:null,s=!!f?.Running}catch{m=null}}else s=(await u("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;t[r]={installed:!0,version:a,running:s,...r==="podman"&&d!=="linux"?{machine:m}:{}}}const o=_.find(r=>t[r]?.installed&&t[r].running)||_.find(r=>t[r]?.installed)||null;return{...t,preferred:o,...o?{}:{install:B(d)}}}async function O(t="podman"){if(!_.includes(t))return{ok:!1,error:`unknown engine ${t}`};const o=(await k())[t];if(!o?.installed)return{ok:!1,error:`${t} is not installed`,install:B(d)};if(o.running)return{ok:!0,already:!0};if(t==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(d!=="linux"){if(!o.machine){const n=await u("podman",["machine","init"],{timeout:6e5});if(!n.ok)return{ok:!1,error:`podman machine init: ${n.err||n.out}`}}const r=await u("podman",["machine","start"],{timeout:3e5});if(!r.ok&&!/already running/i.test(r.err))return{ok:!1,error:`podman machine start: ${r.err||r.out}`}}return{ok:!0}}async function X(){const t=await k(),o=t.preferred;if(!o||!t[o].running)return[];if(o==="podman"){const n=await u("podman",["ps","-a","--format","json"],{timeout:1e4});if(!n.ok)return[];try{return JSON.parse(n.out||"[]").map(a=>G(a,"podman"))}catch{return[]}}const r=await u("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return r.ok?r.out.split(`
3
+ `).filter(Boolean).map(n=>{try{return G(JSON.parse(n),"docker")}catch{return null}}).filter(Boolean):[]}async function R(t,o){const r=await u(t,["inspect","--format","{{.State.Status}}",o],{timeout:8e3});return r.ok?/running/i.test(r.out)?"running":"stopped":"absent"}const x=t=>`http://127.0.0.1:${t.port}`;async function T(){const t=await k(),o=t.preferred,r=await j(o,t),n={};for(const a of D){const s=x(a);let m="no-engine";o&&t[o].running?m=await R(o,a.container):o&&(m="engine-stopped");const c=a.model?h(a):null;n[a.id]={...oe(a),engine:o,state:m,url:s,configured:a.configured(e),answering:m==="running"?await a.answers(s,E):!1,...a.model?{model:c,default:a.model,models:F(a.id,{active:c,engineRamMB:r,engine:o,platform:d,installed:P}),machine:{engineRamMB:r}}:{}}}return n}function z(t,{settingsFile:o=null,secret:r=null}={}){const n=v(t),a=["run","-d","--name",n.container,"--restart","unless-stopped","-p",`127.0.0.1:${n.port}:${n.containerPort}`];for(const s of n.volumes?n.volumes(b):[])a.push("-v",s);o&&a.push("-v",`${o}:/etc/searxng/settings.yml:ro`);for(const s of n.env?n.env(n):[])a.push("-e",s);r&&a.push("-e",`SEARXNG_SECRET=${r}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${n.port}/`),a.push("--cap-drop","ALL");for(const s of n.caps||[])a.push("--cap-add",s);return a.push(n.image,...n.args?n.args(n):[]),a}async function I(t){const o=N(t);if(!o)return{ok:!1,error:`unknown service ${t}`};const r=await k(),n=r.preferred;if(!n)return{ok:!1,error:"no container engine — install Podman first",install:B(d)};if(!r[n].running){const c=await O(n);if(!c.ok)return c}const a=await R(n,o.container);if(a!=="running")if(a==="stopped"){const c=await u(n,["start",o.container],{timeout:6e4});if(!c.ok)return{ok:!1,error:`${n} start: ${c.err||c.out}`}}else{L(b,{recursive:!0,mode:448});let c=null,y=null;o.id==="searxng"&&(c=S.join(b,"searxng-settings.yml"),Y(c,ae(String(e.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),y=Z(32).toString("hex")),o.volumes&&L(S.join(b,A),{recursive:!0,mode:448});const f=z(o,{settingsFile:c,secret:y});M(`[runtime] ${n} ${f.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const p=await u(n,f,{timeout:6e5});if(!p.ok)return{ok:!1,error:`${n} run: ${p.err||p.out}`}}const s=x(o);let m=!1;for(let c=0;c<30&&!m;c++)m=await o.answers(s,E),m||await J(1e3);return o.configure(e,s,v(o)),w(),{ok:!0,url:s,answering:m,...o.provides.length?{provides:o.provides}:{},...o.model?{model:h(o)}:{}}}async function V(t){const o=N(t);if(!o)return{ok:!1,error:`unknown service ${t}`};const r=await k(),n=r.preferred;if(n&&r[n].running){const a=await u(n,["stop",o.container],{timeout:6e4});if(!a.ok&&!/no such container/i.test(a.err))return{ok:!1,error:`${n} stop: ${a.err||a.out}`}}return o.unconfigure(e,x(o)),w(),{ok:!0}}async function q(t,o){const r=N(t);if(!r)return{ok:!1,error:`unknown service ${t}`};if(!r.model)return{ok:!1,error:`${r.label} takes no model`};const n=String(o||"").trim();if(!ee(t,n))return{ok:!1,error:`not a model id: ${JSON.stringify(o)} — pick one from the list, or a Hugging Face id like owner/name`};const a=await k(),s=a.preferred,m=await j(s,a),c=F(t,{active:n,engineRamMB:m,engine:s,platform:d,installed:P}).find(p=>p.id===n);if(c?.unavailable)return{ok:!1,error:`${n} ${c.unavailable}`};e.runtime=e.runtime||{services:{}},e.runtime.services=e.runtime.services||{},e.runtime.services[t]={...e.runtime.services[t]||{},model:n};const y=x(r);r.configured(e)===y&&r.configure(e,y,v(r)),w();let f=!1;if(s&&a[s].running){const p=await R(s,r.container);if(p!=="absent"){const g=await u(s,["rm","-f",r.container],{timeout:6e4});if(!g.ok&&!/no such container/i.test(g.err))return{ok:!1,error:`${s} rm: ${g.err||g.out}`};if(p==="running"){const H=await I(t);if(!H.ok)return H;f=!0}}}return{ok:!0,model:n,restarted:f,...c?.ramNote?{note:c.ramNote}:{}}}return{async status(){const[t,o,r,n]=await Promise.all([i().catch(()=>null),k(),T(),X()]);return{sandbox:t?.sandbox||null,processes:{all:[...Array.isArray(t?.processes)?t.processes:[],...l()],localMcp:Array.isArray(t?.localMcp)?t.localMcp:[],warm:t?.warm||null},containers:n,refused:Array.isArray(t?.sandbox?.refused)?t.sandbox.refused:[],bridge:t?{ok:!0,version:t.version||""}:{ok:!1},engines:o,services:r}},startEngine:O,startService:I,stopService:V,setModel:q,services:T,catalogFor:te}}export{D as SERVICES,G as containerRow,fe as createRuntime,B as installDoor,ae as searxngSettings};