@chatpanel/gateway 0.23.2 → 0.39.4

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 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};
1
+ import nt from"node:os";import{join as S}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 E="https://dl.chatpanel.net/models/";function dt(){const t=process.env.CHATPANEL_MODEL_BASE_URL;if(!t)return E;const e=r=>(console.warn(`[models] ignoring CHATPANEL_MODEL_BASE_URL (${t}): ${r} — using ${E}`),E);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 ${E}`),t.replace(/\/*$/,"/"))}const mt=dt();let d="off",h=null,g=null,x=null,L=null,v=null,M=null,T=null,w=null,N=0,A=null;const m=new Map;function C(){return process.env.CHATPANEL_MODELS_DIR||S(nt.homedir(),".chatpanel","models")}function H(t=h||J){const e=S(C(),...t.split("/"));return B(S(e,"onnx","model_quantized.onnx"))||B(S(e,"onnx","model.onnx"))}function jt(){const t=C(),e=[];try{for(const n of Y(t,{withFileTypes:!0}))if(n.isDirectory())for(const o of Y(S(t,n.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const r=`${n.name}/${o.name}`;H(r)&&ht(S(t,n.name,o.name))&&e.push(r)}}catch{}return e}function ht(t){try{return(JSON.parse(ot(S(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 f=String(i.word??"");const a=i.entity_group??i.entity??"ENTITY";if(f.startsWith("##")&&r.length&&r[r.length-1].type===a){r[r.length-1].value+=f.slice(2);continue}f=f.replace(/##/g,"").trim(),f&&r.push({value:f,type:a})}const s=new Set,u=[];for(const i of r){const f=vt(n,$t(n,i.value.trim()));if(f.length<=1)continue;const a=`${i.type}:${f.toLowerCase()}`;s.has(a)||(s.add(a),u.push({value:f,type:i.type}))}return u}async function G(t,e){N++;try{return await yt(t,e)}finally{N--,$()||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:u}of V())for(const i of r){let f=0;for(const a of Ot(i.text,u.tokenizer)){if(e?.aborted)return null;const l=i.text.indexOf(a,f),c=await u(a,{aggregation_strategy:"simple"});for(const p of c||[])o.push({...p,_win:l<0?f:l,_winText:a,_model:s,_pass:i.key,_passText:i.text});l>=0&&(f=Math.max(f,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 u=-1,i=-1,f=null,a=null;for(const c of o){const p=String(c.word??"").replace(/##/g,"").trim();if(!p)continue;(c._win!==i||c._model!==f||c._pass!==a)&&(i=c._win,f=c._model,a=c._pass,u=c._win);const b=c._passText||n;let _=b.indexOf(p,u);if(_<0&&(_=b.indexOf(p,c._win)),_<0)continue;let O=_+p.length;u=O;const W=z=>!!z&&/[\p{L}\p{N}'’-]/u.test(z);for(;_>0&&W(n[_-1]);)_--;for(;O<n.length&&W(n[O]);)O++;const U=String(c.entity_group??c.entity??"ENTITY"),j=`${_}:${O}:${U}`;if(s.has(j))continue;s.add(j);const q=Number(c.score);r.push({value:n.slice(_,O),type:U,start:_,end:O,score:Number.isFinite(q)?Math.max(0,Math.min(1,q)):1,model:c._model})}r.sort((c,p)=>c.start-p.start||c.end-p.end);const l=[];for(const c of r){const p=l[l.length-1];if(p&&p.type===c.type&&p.end===c.start){p.end=c.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,c.score);continue}l.push({...c})}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 R(t){const e=K.indexOf(wt(t.type));return e<0?K.length:e}let D=[];function _t(t){D=Array.isArray(t)?t.slice():[]}function F(t){if(t.model===h)return-1;const e=D.indexOf(t.model);return e<0?D.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;(R(o)<R(r)||R(o)===R(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 Ot(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 u=[];let i=0,f=Math.max(64,Math.floor(r*3));for(;i<t.length;){let a=Math.min(t.length,i+f);if(a<t.length){const b=t.lastIndexOf(" ",a);b>i+f/2&&(a=b)}let l=t.slice(i,a);for(;s(l)>r&&l.length>32;){f=Math.max(32,Math.floor(l.length/2)),a=i+f;const b=t.lastIndexOf(" ",a);b>i+f/2&&(a=b),l=t.slice(i,a)}if(u.push(l),a>=t.length)break;const c=Math.max(i+1,a-Lt),p=t.indexOf(" ",c);i=p>0&&p<a?p+1:a}return u}const St=200,y=[];function Tt(t,e,n){y.push({ms:t,chars:e,spans:n}),y.length>St&&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 vt(t,e){if(!e)return e;const n=t.indexOf(e);if(n<0)return e;const o=u=>!!u&&/[\p{L}\p{N}'’-]/u.test(u);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(v)return v;const t=C();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:u,LogLevel:i}=await import("@huggingface/transformers");if(n.cacheDir=t,e&&i)try{n.logLevel=i.ERROR}catch{}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 v={env:n,pipeline:(a,l,c={})=>o(a,l,c.progress_callback&&n.allowRemoteModels===!1?{...c,progress_callback:void 0}:c),Tensor:r,AutoModel:s,AutoProcessor:u},v}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 u=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 f=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:f})}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:f})}if(!s)try{ut(t,{modelsDir:C(),log:e})}catch(l){try{await a.dispose?.()}catch{}throw l}return{pipe:a,haveLocal:s}}finally{try{r.env.remoteHost=u}catch{}}}async function tt(t,{log:e=()=>{},allowDownload:n=!0}={}){const o=g,r=h;try{await Z()}catch(u){return d="error",x=`engine load failed: ${u.message}`,e(`[ner] transformers.js not available (${u.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:u}=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=u,h=t,d="ready",x=null,M=null,T&&(T={...T,model:t}),o&&o!==u)try{await o.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||w?.arm(),!0}catch(u){return x=u.message,M=null,o?(g=o,h=r,d="ready"):d="error",e(`[ner] model load failed (${u.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function At(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(N>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"&&(A||T)?await(A?A():At(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,v=null,M=null,y.length=0,m.clear(),P=!0,D=[],w?.disarm(),w=null,T=null,N=0,A=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&&(A=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,At as init,k as isReady,Jt as labels,Qt as maxTokens,H as modelOnDisk,C 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,Ot as windowsFor};
package/src/order.js ADDED
@@ -0,0 +1 @@
1
+ import{EventError as l}from"./event.js";function h(t,s){return t.host!==s.host?t.host<s.host?-1:1:t.seq!==s.seq?t.seq-s.seq:t.id<s.id?-1:t.id>s.id?1:0}function a(t){const s=new Map;for(const e of t)s.set(e.id,e);const o=new Map,c=new Map;for(const e of t){const n=e.causes.filter(i=>s.has(i));o.set(e.id,n.length);for(const i of n)c.has(i)||c.set(i,[]),c.get(i).push(e.id)}const r=t.filter(e=>o.get(e.id)===0).sort(h),f=[];for(;r.length>0;){const e=r.shift();f.push(e);const n=c.get(e.id);if(!n)continue;let i=!1;for(const d of n){const u=o.get(d)-1;o.set(d,u),u===0&&(r.push(s.get(d)),i=!0)}i&&r.sort(h)}if(f.length!==t.length){const e=t.filter(n=>!f.includes(n)).map(n=>n.id);throw new l("CYCLE","causes contains a cycle",e)}return f}function g(t){const s=new Map(t.map(o=>[o.id,o]));for(const o of t)for(const c of o.causes){const r=s.get(c);if(r&&r.host===o.host&&r.seq>=o.seq)return!1}return!0}export{g as causesAreWellFormed,h as compareEvents,a as linearize};
package/src/policy.js CHANGED
@@ -1,2 +1,2 @@
1
- import{existsSync as m,readFileSync as g}from"node:fs";import{join as d}from"node:path";import P from"node:os";import{normalizeOrgPolicy as w,verifyPolicyToken as E,policyHash as S,policyLabel as x,PolicyError as A}from"@chatpanel/events/policy.js";import{verifySignedToken as C}from"@chatpanel/events/entitlement.js";class u extends Error{constructor(n){super(n),this.name="PolicyLoadError"}}function f(o=process.env,n=process.platform,t=P.homedir()){const e=[];return o.CHATPANEL_POLICY&&e.push(o.CHATPANEL_POLICY),n==="win32"?e.push(d(o.ProgramData||"C:\\ProgramData","ChatPanel","policy.json")):e.push("/etc/chatpanel/policy.json"),e.push(d(t,".chatpanel","policy.json")),e}let c=null;async function N({env:o=process.env,fs:n={existsSync:m,readFileSync:g},now:t=Date.now()}={}){const e=f(o).find(s=>{try{return n.existsSync(s)}catch{return!1}});if(!e)return null;let i;try{i=n.readFileSync(e,"utf8")}catch(s){throw new u(`cannot read ${e}: ${s.message}`)}const a=String(o.CHATPANEL_POLICY_REQUIRE_SIGNATURE||"")==="1";let r;const p=i.trim();if(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p))r={token:p};else try{r=JSON.parse(p)}catch{throw new u(`${e} is not JSON (or a signed token)`)}let l,y=!1;if(r&&typeof r.token=="string"){if(l=await E(r.token,{now:t,verify:C}),!l)throw new u(`${e}: the signed policy does not verify (wrong key, tampered, or expired)`);y=!0}else{if(a)throw new u(`${e} is unsigned and CHATPANEL_POLICY_REQUIRE_SIGNATURE=1 — refusing to run unmanaged`);try{l=w(r)}catch(s){throw new u(`${e}: ${s instanceof A?s.message:String(s)}`)}}const h=await S(l);return{policy:l,source:e,signed:y,hash:h,label:x(l)}}async function O(o){return c=await N(o),c}function $(){return c?.policy||null}function v(){return c}function R(o){c=o||null}function j(){if(!c)return null;const{policy:o,signed:n,hash:t,source:e}=c;return{org:o.org?.id||null,name:o.org?.name||null,signed:n,policyHash:t,source:e,locks:o.client?.lock||[],enforces:{endpoints:!!o.endpoints,models:!!o.models,agents:!!o.agents,routing:!!o.routing?.rules?.length,redactionFloor:o.redaction?.floor||null,egress:!!o.egress}}}function H(o,n=$()){if(!n||!o)return o;const t=n.redaction;if(t){if(o.redaction=o.redaction||{},t.floor){const e={off:0,basic:1,full:2},i=o.redaction.tier||"basic";(e[i]??1)<e[t.floor]&&(o.redaction.tier=t.floor)}if(t.dictionary?.length){const e=new Set((o.redaction.dictionary||[]).map(a=>typeof a=="string"?a:a?.term).filter(Boolean)),i=t.dictionary.filter(a=>!e.has(a));i.length&&(o.redaction.dictionary=[...o.redaction.dictionary||[],...i])}}return o}function b(o){if(!o)return"No org policy: this gateway is unmanaged (looked in: "+f().join(", ")+").";const{policy:n,source:t,signed:e,hash:i,label:a}=o,r=[];return r.push(`${a} — ${e?"signed policy":"UNSIGNED policy file"} at ${t}`),r.push(`policy hash ${i}`),r.push(""),r.push(JSON.stringify(n,null,2)),r.join(`
2
- `)}export{u as PolicyLoadError,$ as activePolicy,v as activePolicyRecord,H as applyPolicyToConfig,b as formatPolicy,O as initPolicy,N as loadPolicy,j as managedSummary,f as policyPaths,R as setActivePolicyForTests};
1
+ import{existsSync as m,readFileSync as g}from"node:fs";import d from"node:path";import P from"node:os";import{normalizeOrgPolicy as w,verifyPolicyToken as E,policyHash as S,policyLabel as x,PolicyError as A}from"@chatpanel/events/policy.js";import{verifySignedToken as C}from"@chatpanel/events/entitlement.js";class u extends Error{constructor(n){super(n),this.name="PolicyLoadError"}}function f(o=process.env,n=process.platform,t=P.homedir()){const e=[];o.CHATPANEL_POLICY&&e.push(o.CHATPANEL_POLICY);const r=n==="win32"?d.win32:d.posix;return n==="win32"?e.push(r.join(o.ProgramData||"C:\\ProgramData","ChatPanel","policy.json")):e.push("/etc/chatpanel/policy.json"),e.push(r.join(t,".chatpanel","policy.json")),e}let c=null;async function N({env:o=process.env,fs:n={existsSync:m,readFileSync:g},now:t=Date.now()}={}){const e=f(o).find(a=>{try{return n.existsSync(a)}catch{return!1}});if(!e)return null;let r;try{r=n.readFileSync(e,"utf8")}catch(a){throw new u(`cannot read ${e}: ${a.message}`)}const s=String(o.CHATPANEL_POLICY_REQUIRE_SIGNATURE||"")==="1";let i;const p=r.trim();if(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p))i={token:p};else try{i=JSON.parse(p)}catch{throw new u(`${e} is not JSON (or a signed token)`)}let l,y=!1;if(i&&typeof i.token=="string"){if(l=await E(i.token,{now:t,verify:C}),!l)throw new u(`${e}: the signed policy does not verify (wrong key, tampered, or expired)`);y=!0}else{if(s)throw new u(`${e} is unsigned and CHATPANEL_POLICY_REQUIRE_SIGNATURE=1 — refusing to run unmanaged`);try{l=w(i)}catch(a){throw new u(`${e}: ${a instanceof A?a.message:String(a)}`)}}const h=await S(l);return{policy:l,source:e,signed:y,hash:h,label:x(l)}}async function O(o){return c=await N(o),c}function $(){return c?.policy||null}function j(){return c}function v(o){c=o||null}function R(){if(!c)return null;const{policy:o,signed:n,hash:t,source:e}=c;return{org:o.org?.id||null,name:o.org?.name||null,signed:n,policyHash:t,source:e,locks:o.client?.lock||[],enforces:{endpoints:!!o.endpoints,models:!!o.models,agents:!!o.agents,routing:!!o.routing?.rules?.length,redactionFloor:o.redaction?.floor||null,egress:!!o.egress}}}function H(o,n=$()){if(!n||!o)return o;const t=n.redaction;if(t){if(o.redaction=o.redaction||{},t.floor){const e={off:0,basic:1,full:2},r=o.redaction.tier||"basic";(e[r]??1)<e[t.floor]&&(o.redaction.tier=t.floor)}if(t.dictionary?.length){const e=new Set((o.redaction.dictionary||[]).map(s=>typeof s=="string"?s:s?.term).filter(Boolean)),r=t.dictionary.filter(s=>!e.has(s));r.length&&(o.redaction.dictionary=[...o.redaction.dictionary||[],...r])}}return o}function b(o){if(!o)return"No org policy: this gateway is unmanaged (looked in: "+f().join(", ")+").";const{policy:n,source:t,signed:e,hash:r,label:s}=o,i=[];return i.push(`${s} — ${e?"signed policy":"UNSIGNED policy file"} at ${t}`),i.push(`policy hash ${r}`),i.push(""),i.push(JSON.stringify(n,null,2)),i.join(`
2
+ `)}export{u as PolicyLoadError,$ as activePolicy,j as activePolicyRecord,H as applyPolicyToConfig,b as formatPolicy,O as initPolicy,N as loadPolicy,R as managedSummary,f as policyPaths,v as setActivePolicyForTests};
@@ -0,0 +1 @@
1
+ import{CAPABILITIES as c,CAPABILITY_ROUTES as p,PROVIDER_KINDS as b}from"./capability-endpoints.js";import{listDestinations as k}from"./router.js";const h=/^(localhost|127\.|\[::1\]|0\.0\.0\.0)/,g=/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[?fe80:|.*\.local$)/i;function i(t){if(!t)return"none";let n="";try{n=new URL(t).hostname}catch{return"internet"}return h.test(n)?"loopback":g.test(n)?"lan":"internet"}const d=t=>typeof t=="string"&&t.trim()?t.trim():null;function v(t,n){const e=t?.capabilities?.[n];if(!e||typeof e!="object")return null;const a=d(e.url);let r=b.includes(e.provider)?e.provider:null;return r||(r=e.service?"container":a?"remote":"embedded"),r==="remote"&&!/^https?:\/\//.test(a||"")?null:{kind:r,...a?{url:a}:{},...d(e.adapter)?{adapter:d(e.adapter)}:{},...d(e.model)?{model:d(e.model)}:{},...d(e.service)?{service:d(e.service)}:{},...d(e.token)?{token:d(e.token)}:{},...typeof e.calibrated=="boolean"?{calibrated:e.calibrated}:{},...typeof e.redact=="boolean"?{redact:e.redact}:{},egress:r==="embedded"?"none":r==="container"?"loopback":i(a)}}function f(t,n,e={}){if(!c.includes(n))throw new Error(`providerOf: unknown capability ${n}`);const a=v(t,n);if(a)return s(n,a,e);switch(n){case"chat":{const r=k(t),o=r.filter(u=>u.type==="agent").length,l=r.filter(u=>u.type!=="agent");if(!r.length)return s(n,{kind:"none",egress:"none"},e);if(!l.length)return s(n,{kind:"harness",egress:"internet",destinations:r.length,harnesses:o},e);const m=l.some(u=>i(u.baseUrl)==="internet")?"internet":l.some(u=>i(u.baseUrl)==="lan")?"lan":"loopback";return s(n,{kind:"router",egress:m,destinations:r.length,harnesses:o,apis:l.length},e)}case"detect":{const r=t?.redaction?.detection;return r?.backend==="endpoint"&&d(r.url)?s(n,{kind:"remote",url:r.url,adapter:"detect",egress:i(r.url)},e):r?.backend&&r.backend!=="off"&&r.backend!=="endpoint"?s(n,{kind:"embedded",egress:"none",model:e.nerModel||t?.ner?.model},e):s(n,{kind:"embedded",egress:"none",model:e.nerModel||t?.ner?.model},e)}case"stt":return t?.stt?.enabled===!1?s(n,{kind:"none",egress:"none"},e):s(n,{kind:"embedded",egress:"none",model:e.sttModel||t?.stt?.model},e);case"tts":{const r=t?.tts?.provider;if(t?.tts?.enabled===!1)return s(n,{kind:"none",egress:"none"},e);if(r&&r!=="local"){const o=t?.tts?.remote||{},l=d(o.baseUrl)||(r==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1");return s(n,{kind:"remote",url:l,adapter:r,model:d(o.model)||void 0,egress:i(l),redact:o.redact!==!1},e)}return s(n,{kind:"embedded",egress:"none",model:e.ttsModel||t?.tts?.model},e)}case"search":{const r=t?.search?.provider||"auto",o=d(t?.search?.searxng?.url);return r==="searxng"||r==="auto"&&o?s(n,{kind:i(o)==="loopback"?"container":"remote",url:o,adapter:"searxng",egress:i(o)},e):s(n,{kind:"embedded",adapter:"serp",egress:"internet"},e)}case"read":{const r=t?.read?.provider||"defuddle",o=d(t?.read?.remote?.url);return r==="remote"&&o?s(n,{kind:"remote",url:o,adapter:"remote",egress:i(o)},e):s(n,{kind:"embedded",adapter:r,egress:"internet"},e)}case"extract":return s(n,{kind:"embedded",egress:"none"},e);default:return s(n,{kind:"none",egress:"none"},e)}}const y={embedded:"this device",container:"a container on this device",remote:"a server",harness:"coding agents, each at its own vendor",router:"the model router",none:"nobody yet"};function s(t,n,e){const a=n.kind==="remote"?(()=>{try{return new URL(n.url).host}catch{return n.url}})():y[n.kind],r=n.model||n.adapter||n.service||"";return{...n,label:r?`${r} — ${a}`:a,route:p[t]}}function w(t,n={}){return Object.fromEntries(c.map(e=>[e,f(t,e,n)]))}function L(t,n={}){const e=[];for(const[a,r]of Object.entries(w(t,n))){if(r.kind!=="remote"||!r.url)continue;let o=r.url;try{o=new URL(r.url).host}catch{}e.push({id:a,host:o,adapter:r.adapter||"",token:!!r.token,egress:r.egress,route:r.route})}return e}export{L as declaredProviderHosts,i as egressOf,f as providerOf,w as providerTable};
package/src/ref.js ADDED
@@ -0,0 +1 @@
1
+ const f=Object.freeze(["note","meeting","chat","page","result","blob","memory","brief"]),i=Object.freeze({EXACT:"exact",UNAVAILABLE:"verified-but-unavailable",DRIFTED:"drifted"});function u({kind:e,id:o,hash:r,range:t=null,stored:s=!1}){if(!f.includes(e))throw new TypeError(`ref: unknown kind ${e}`);if(typeof o!="string"||!o)throw new TypeError("ref: id required");if(typeof r!="string"||!r)throw new TypeError("ref: hash required");const n={kind:e,id:o,hash:r};if(t){if(!Number.isInteger(t.from)||!Number.isInteger(t.to)||t.to<t.from)throw new TypeError("ref: range must be {from,to} integers with to >= from");n.range={from:t.from,to:t.to}}return s&&(n.stored=!0),Object.freeze(n)}function l(e){return!!e&&typeof e=="object"&&f.includes(e.kind)&&typeof e.id=="string"&&e.id.length>0&&typeof e.hash=="string"&&e.hash.length>0}function h(e,o){const r=o(e);return r?r.hash!==e.hash?{resolution:i.DRIFTED,ref:e,actualHash:r.hash}:{resolution:i.EXACT,ref:e,value:r.value}:{resolution:i.UNAVAILABLE,ref:e}}export{f as REF_KINDS,i as RESOLUTION,l as isRef,u as makeRef,h as resolveRef};
package/src/router.js CHANGED
@@ -1 +1 @@
1
- import{secureFetch as _}from"./secure-fetch.js";import{readBridgeToken as A,resolveBridgeUrl as v}from"./bridge.js";const O=["codex","claude","opencode","pi","kiro","antigravity"];function y(n){const o=(Array.isArray(n.destinations)?n.destinations:[]).filter(Boolean),i=new Set(o.map(e=>e.id)),a=[...o.filter(e=>e.type==="agent"),...O.filter(e=>!i.has(e)).map(e=>({id:e,type:"agent",agent:e,models:[e]})),...o.filter(e=>e.type!=="agent")];return n.backend==="api"&&!o.some(e=>e.type==="api")&&(a.push({id:"openai",type:"api",protocol:"openai",baseUrl:n.upstreams?.openai?.baseUrl,models:[]}),a.push({id:"anthropic",type:"api",protocol:"anthropic",baseUrl:n.upstreams?.anthropic?.baseUrl,models:[]})),a}function N(n,o,i,{destination:a=""}={}){const e=y(o),r=i==="anthropic",s=t=>r?t.protocol==="anthropic":t.protocol!=="anthropic";return a?e.find(t=>t.id===a)||null:n&&e.find(t=>Array.isArray(t.models)&&t.models.includes(n))||n&&e.find(t=>t.id===n||t.agent===n)||n&&n.includes("/")&&e.find(t=>t.type==="agent"&&(t.agent===n.slice(0,n.indexOf("/"))||t.id===n.slice(0,n.indexOf("/"))))||e.find(t=>o.backend==="bridge"?t.type==="agent":t.type==="api"&&s(t))||e.find(t=>o.backend==="bridge"?t.type==="agent":t.type==="api")||e[0]||null}function w(n){return n.type==="agent"?{api:"agent",endpoints:["/v1/chat/completions"]}:n.protocol==="anthropic"?{api:"anthropic",endpoints:["/v1/messages"]}:{api:"openai",endpoints:["/v1/chat/completions","/v1/responses"]}}const M=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;function k(n){if(!n||n.type==="agent")return"";const o=String(n.baseUrl||"");return o?M.test(o)||n.apiKey||n.hasKey?"":`no API key is saved for ${n.id}`:"no endpoint URL is set for this provider"}function $(n){const o=[],i=new Set,a=(e,r,s)=>{if(!e||i.has(e))return;i.add(e);const t=w(s),l=k(s);o.push({id:e,object:"model",owned_by:r,...l?{configured:!1,reason:l}:{},provider:s.id,provider_type:s.type==="agent"?"agent":s.protocol==="anthropic"?"anthropic":"openai",api:t.api,endpoints:t.endpoints})};for(const e of y(n))if(e.type==="agent")for(const r of e.models?.length?e.models:[e.id])a(r,"chatpanel-bridge",e);else for(const r of e.models||[])a(r,e.id,e);return{object:"list",data:o}}async function j(n,o,i){const a=await v(n);if(!a||!o)return new Map;const e=A(n.bridge?.token),r=[...o.entries()].filter(([,t])=>t).map(([t])=>t),s=new Map;return await Promise.all(r.map(async t=>{try{const l=await fetch(`${a}/list-models`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify({agent:t}),signal:AbortSignal.timeout(i)});if(!l.ok)return;const f=await l.json(),p=(Array.isArray(f?.models)?f.models:[]).map(c=>typeof c=="string"?c:c?.id||c?.name||"").map(c=>String(c).trim()).filter(Boolean);p.length&&s.set(t,p.slice(0,40))}catch{}})),s}async function U(n,o){const i=await v(n);if(!i)return null;try{const a=A(n.bridge?.token),e=await fetch(`${i}/health`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(o)});if(!e.ok)return null;const r=await e.json();if(!Array.isArray(r?.agents))return null;const s=new Map(r.agents.map(t=>[t.id,!!t.available]));return s.noTools=new Set(r.agents.filter(t=>t.tools===!1).map(t=>t.id)),s}catch{return null}}const x=Number(process.env.CHATPANEL_MODELS_CACHE_MS)||6e4;let d={at:0,key:"",value:null,inflight:null};function T(n){try{return JSON.stringify([y(n).map(o=>[o.id,o.type,o.baseUrl,o.models]),n.bridge?.url||""])}catch{return String(Date.now())}}function D(){d={at:0,key:"",value:null,inflight:null}}async function E(n,{timeoutMs:o=4e3,fresh:i=!1,now:a=Date.now}={}){const e=T(n),r=d.value&&d.key===e,s=!r||a()-d.at>x;if(r&&!i&&!s)return d.value;const t=()=>(d.inflight||(d.inflight=C(n,{timeoutMs:o}).then(l=>(d={at:a(),key:e,value:l,inflight:null},l)).catch(l=>{throw d.inflight=null,l})),d.inflight);return r&&!i?(t().catch(()=>{}),d.value):t()}async function C(n,{timeoutMs:o=4e3}={}){const i=$(n),a=new Set(i.data.map(t=>t.id)),e=await U(n,o);if(e)for(const t of i.data)t.owned_by==="chatpanel-bridge"&&(t.available=e.get(t.id)??!1,e.noTools?.has(t.id)&&(t.tools=!1));const r=await j(n,e,o);for(const[t,l]of r){const f=i.data.find(p=>p.id===t);if(f)for(const p of l){const c=`${t}/${p}`;a.has(c)||(a.add(c),i.data.push({...f,id:c,model:p,available:!0}))}}const s=y(n).filter(t=>t.type==="api"&&t.baseUrl);return await Promise.all(s.map(async t=>{const l=new AbortController,f=setTimeout(()=>l.abort(),o);try{const p={"content-type":"application/json"};t.apiKey&&(t.protocol==="anthropic"?(p["x-api-key"]=t.apiKey,p["anthropic-version"]="2023-06-01"):p.authorization=`Bearer ${t.apiKey}`);const c=await _(`${t.baseUrl.replace(/\/$/,"")}/models`,{headers:p,signal:l.signal});if(!c.ok)return;const u=await c.json(),S=Array.isArray(u?.data)?u.data:Array.isArray(u?.models)?u.models:[];for(const g of S){const h=typeof g=="string"?g:g?.id;if(h&&!a.has(h)){a.add(h);const b=w(t),m=k(t);i.data.push({id:h,object:"model",owned_by:t.id,provider:t.id,provider_type:t.protocol==="anthropic"?"anthropic":"openai",api:b.api,endpoints:b.endpoints,...m?{configured:!1,reason:m}:{}})}}}catch{}finally{clearTimeout(f)}})),i}export{$ as aggregateModels,E as aggregateModelsAsync,y as listDestinations,D as resetModelsCache,N as resolveDestination};
1
+ import{secureFetch as j}from"./secure-fetch.js";import{readBridgeToken as S,resolveBridgeUrl as _}from"./bridge.js";const x=["codex","claude","opencode","pi","kiro","antigravity"];function g(e){const a=(Array.isArray(e.destinations)?e.destinations:[]).filter(Boolean),c=new Set(a.map(n=>n.id)),r=[...a.filter(n=>n.type==="agent"),...x.filter(n=>!c.has(n)).map(n=>({id:n,type:"agent",agent:n,models:[n]})),...a.filter(n=>n.type!=="agent")];return e.backend==="api"&&!a.some(n=>n.type==="api")&&(r.push({id:"openai",type:"api",protocol:"openai",baseUrl:e.upstreams?.openai?.baseUrl,models:[]}),r.push({id:"anthropic",type:"api",protocol:"anthropic",baseUrl:e.upstreams?.anthropic?.baseUrl,models:[]})),r}function P(e,a,c,{destination:r="",down:n=()=>!1}={}){const i=g(a),l=c==="anthropic",s=o=>(l?o.protocol==="anthropic":o.protocol!=="anthropic")&&!n(o);return r?i.find(o=>o.id===r)||null:e&&i.find(o=>Array.isArray(o.models)&&o.models.includes(e))||e&&i.find(o=>o.id===e||o.agent===e)||e&&e.includes("/")&&i.find(o=>o.type==="agent"&&(o.agent===e.slice(0,e.indexOf("/"))||o.id===e.slice(0,e.indexOf("/"))))||i.find(o=>a.backend==="bridge"?o.type==="agent":o.type==="api"&&s(o))||i.find(o=>(a.backend==="bridge"?o.type==="agent":o.type==="api")&&!n(o))||i.find(o=>!n(o))||null}function O(e){return e.type==="agent"?{api:"agent",endpoints:["/v1/chat/completions"]}:e.protocol==="anthropic"?{api:"anthropic",endpoints:["/v1/messages"]}:{api:"openai",endpoints:["/v1/chat/completions","/v1/responses"]}}const U=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;function M(e){if(!e||e.type==="agent")return"";const a=String(e.baseUrl||"");return a?U.test(a)||e.apiKey||e.hasKey?"":`no API key is saved for ${e.id}`:"no endpoint URL is set for this provider"}function T(e){const a=[],c=new Set,r=(n,i,l)=>{if(!n||c.has(n))return;c.add(n);const s=O(l),o=M(l);a.push({id:n,object:"model",owned_by:i,...o?{configured:!1,reason:o}:{},provider:l.id,provider_type:l.type==="agent"?"agent":l.protocol==="anthropic"?"anthropic":"openai",api:s.api,endpoints:s.endpoints})};for(const n of g(e))if(n.type==="agent")for(const i of n.models?.length?n.models:[n.id])r(i,"chatpanel-bridge",n);else for(const i of n.models||[])r(i,n.id,n);return{object:"list",data:a}}async function C(e,a,c){const r=await _(e);if(!r||!a)return new Map;const n=S(e.bridge?.token),i=[...a.entries()].filter(([,s])=>s).map(([s])=>s),l=new Map;return await Promise.all(i.map(async s=>{try{const o=await fetch(`${r}/list-models`,{method:"POST",headers:{"content-type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({agent:s}),signal:AbortSignal.timeout(c)});if(!o.ok)return;const f=await o.json(),b=(Array.isArray(f?.models)?f.models:[]).map(t=>typeof t=="string"?t:t?.id||t?.name||"").map(t=>String(t).trim()).filter(Boolean);b.length&&l.set(s,b.slice(0,40))}catch{}})),l}async function B(e,a){const c=await _(e);if(!c)return null;try{const r=S(e.bridge?.token),n=await fetch(`${c}/health`,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:AbortSignal.timeout(a)});if(!n.ok)return null;const i=await n.json();if(!Array.isArray(i?.agents))return null;const l=new Map(i.agents.map(s=>[s.id,!!s.available]));return l.noTools=new Set(i.agents.filter(s=>s.tools===!1).map(s=>s.id)),l}catch{return null}}const K=Number(process.env.CHATPANEL_MODELS_CACHE_MS)||6e4;let d={at:0,key:"",value:null,inflight:null};function N(e){try{return JSON.stringify([g(e).map(a=>[a.id,a.type,a.baseUrl,a.models]),e.bridge?.url||""])}catch{return String(Date.now())}}function z(){d={at:0,key:"",value:null,inflight:null}}async function H(e,{timeoutMs:a=4e3,fresh:c=!1,now:r=Date.now,serviceHealth:n=null}={}){const i=N(e),l=d.value&&d.key===i,s=!l||r()-d.at>K;if(l&&!c&&!s)return d.value;const o=()=>(d.inflight||(d.inflight=D(e,{timeoutMs:a,serviceHealth:n}).then(f=>(d={at:r(),key:i,value:f,inflight:null},f)).catch(f=>{throw d.inflight=null,f})),d.inflight);return l&&!c?(o().catch(()=>{}),d.value):o()}async function D(e,{timeoutMs:a=4e3,serviceHealth:c=null}={}){const r=T(e),n=new Set(r.data.map(t=>t.id)),i=c?await c():null,l=new Map(g(e).filter(t=>t.service).map(t=>[t.id,t.service])),s=t=>{if(l.get(t.owned_by)&&i){const y=i(t.owned_by);y!=="unknown"&&(t.available=y==="up");const p=typeof i.window=="function"?i.window(t.owned_by):null;p&&(t.context_window=p);const u=typeof i.card=="function"?i.card(t.owned_by):null;u&&(t.card=u)}return t};for(const t of r.data)s(t);const o=await B(e,a);if(o){r.data=r.data.filter(t=>t.owned_by!=="chatpanel-bridge"||o.get(t.id)!==!1);for(const t of r.data)t.owned_by==="chatpanel-bridge"&&(t.available=o.get(t.id)??!1,o.noTools?.has(t.id)&&(t.tools=!1))}const f=await C(e,o,a);for(const[t,h]of f){const y=r.data.find(p=>p.id===t);if(y)for(const p of h){const u=`${t}/${p}`;n.has(u)||(n.add(u),r.data.push({...y,id:u,model:p,available:!0}))}}const b=g(e).filter(t=>t.type==="api"&&t.baseUrl);return await Promise.all(b.map(async t=>{const h=new AbortController,y=setTimeout(()=>h.abort(),a);try{const p={"content-type":"application/json"};t.apiKey&&(t.protocol==="anthropic"?(p["x-api-key"]=t.apiKey,p["anthropic-version"]="2023-06-01"):p.authorization=`Bearer ${t.apiKey}`);const u=await j(`${t.baseUrl.replace(/\/$/,"")}/models`,{headers:p,signal:h.signal});if(!u.ok)return;const w=await u.json(),$=Array.isArray(w?.data)?w.data:Array.isArray(w?.models)?w.models:[];for(const v of $){const m=typeof v=="string"?v:v?.id;if(m&&!n.has(m)){n.add(m);const A=O(t),k=M(t);r.data.push(s({id:m,object:"model",owned_by:t.id,provider:t.id,provider_type:t.protocol==="anthropic"?"anthropic":"openai",api:A.api,endpoints:A.endpoints,...k?{configured:!1,reason:k}:{}}))}}}catch{}finally{clearTimeout(y)}})),r}export{T as aggregateModels,H as aggregateModelsAsync,g as listDestinations,z as resetModelsCache,P as resolveDestination};
@@ -1 +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};
1
+ const M=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/,B=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."}]),u=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."}]),d=Object.freeze([{id:"Qwen/Qwen3-0.6B",label:"Qwen3 0.6B",task:"chat",lang:"100+ languages",tier:"light",approxMB:1200,ramMB:3e3,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The smallest Qwen3 — a chat model that runs on CPU at a usable pace. The ship default for trying vLLM here."},{id:"Qwen/Qwen3-1.7B",label:"Qwen3 1.7B",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:3400,ramMB:6e3,minRamMB:8192,licence:"Apache-2.0",note:"Noticeably stronger; wants 8 GB for the engine and patience on CPU."},{id:"Qwen/Qwen3-4B",label:"Qwen3 4B",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:8e3,ramMB:12e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant; a GPU, or a big machine and patience."},{id:"HuggingFaceTB/SmolLM3-3B",label:"SmolLM3 3B",task:"chat",lang:"6 languages",tier:"balanced",approxMB:6200,ramMB:9e3,minRamMB:12288,licence:"Apache-2.0",note:"A small model built for tool use and long context; English-first."},{id:"Qwen/Qwen3-Embedding-0.6B",label:"Qwen3 Embedding 0.6B",task:"embed",lang:"100+ languages",tier:"balanced",approxMB:1200,ramMB:2500,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"Embeddings for semantic search (1024 dims); the first provider /v1/embeddings has had."},{id:"BAAI/bge-m3",label:"bge-m3",task:"embed",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:3500,minRamMB:4096,licence:"MIT",note:"The multilingual retrieval standard; dense 1024-dim vectors, long passages."},{id:"openai/whisper-large-v3-turbo",label:"Whisper large v3 turbo",task:"transcription",lang:"99 languages",tier:"accurate",approxMB:1600,ramMB:4e3,minRamMB:6144,licence:"MIT",note:"Speech to text through vLLM’s /v1/audio/transcriptions — a container the whole machine’s ears share; heavy on CPU."},{id:"openai/whisper-small",label:"Whisper small",task:"transcription",lang:"99 languages",tier:"light",approxMB:970,ramMB:2500,minRamMB:4096,licence:"MIT",note:"The light transcriber for a container on CPU."},{id:"Qwen/Qwen3-ASR-0.6B",label:"Qwen3-ASR 0.6B (experimental)",task:"transcription",lang:"52 languages",tier:"balanced",approxMB:1400,ramMB:4e3,minRamMB:6144,licence:"Apache-2.0",note:"The strongest small multilingual transcriber (5–6% WER on the open leaderboard). EXPERIMENTAL here: vLLM’s transcription route served whisper-family models only when this entry was written — if the container comes up without /v1/audio/transcriptions, the Runtime says so and the row stays empty."}]);function w(n){return d.find(e=>e.id===n)?.task||"chat"}const p=Object.freeze([{id:"mlx-community/Qwen3-1.7B-4bit",label:"Qwen3 1.7B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:1100,ramMB:2500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac; the ship default for trying vLLM-Metal here."},{id:"mlx-community/Qwen3-4B-4bit",label:"Qwen3 4B (4-bit)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:5e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant on a 16 GB Mac."},{id:"mlx-community/Qwen3-8B-4bit",label:"Qwen3 8B (4-bit)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:4700,ramMB:9e3,minRamMB:24576,licence:"Apache-2.0",note:"Strong; wants 24 GB of unified memory."},{id:"mlx-community/gemma-3-4b-it-4bit",label:"Gemma 3 4B (4-bit)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2700,ramMB:5500,minRamMB:16384,licence:"Gemma",note:"Google’s small model, vision-capable; a strong multilingual choice."},{id:"mlx-community/Llama-3.2-3B-Instruct-4bit",label:"Llama 3.2 3B (4-bit)",task:"chat",lang:"8 languages",tier:"balanced",approxMB:1800,ramMB:4e3,minRamMB:8192,licence:"Llama 3.2",note:"The familiar one; English-first."}]),b=Object.freeze([{id:"unsloth/Qwen3-4B-GGUF:Q4_K_M",label:"Qwen3 4B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac or a laptop CPU; thinks when asked. The ship default for trying llama.cpp here."},{id:"unsloth/Qwen3-8B-GGUF:Q4_K_M",label:"Qwen3 8B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:5e3,ramMB:8e3,minRamMB:16384,licence:"Apache-2.0",note:"Strong general assistant; comfortable on 16 GB with a 16k context."},{id:"unsloth/Qwen2.5-Coder-7B-Instruct-GGUF:Q4_K_M",label:"Qwen2.5 Coder 7B (Q4_K_M)",task:"chat",lang:"code, English, Chinese",tier:"accurate",approxMB:4700,ramMB:7500,minRamMB:16384,licence:"Apache-2.0",note:"The coding model at this size; a local coding agent’s first pick."},{id:"ggml-org/gemma-3-4b-it-GGUF:Q4_K_M",label:"Gemma 3 4B (Q4_K_M)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Gemma",note:"Google’s small model; takes images once its mmproj is named under Vision projector."},{id:"unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL",label:"Gemma 4 26B-A4B (UD-Q4_K_XL)",task:"chat",lang:"140 languages",tier:"max",approxMB:16500,ramMB:22e3,minRamMB:36864,licence:"Gemma",note:"The mixture model the `lm` recipe runs — 26B of weights, 4B active per token, so it answers like a big model at a small one’s speed. Wants 36 GB+; its MTP draft file under Draft model makes it faster still."}]),x=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}(:[A-Za-z0-9._-]{1,32})?$/;function A(n){const e=String(n||"").trim();return x.test(e)||/^(\/|[A-Za-z]:\\)/.test(e)&&/\.gguf$/i.test(e)&&!/[\s"'`$;|&<>]/.test(e)}const f={reranker:B,opendecision:u,vllm:d,"vllm-metal":p,mlx:p,llama:b};function s(n){return f[n]||[]}function k(n,e){if(typeof e!="string"||!e.trim())return!1;const t=e.trim();return n==="llama"?s(n).some(i=>i.id===t)||A(t):s(n).some(i=>i.id===t)||M.test(t)}function L(n){return`models--${String(n).replace(/\//g,"--")}`}function T(n,{active:e=null,engineRamMB:t=0,engine:i=null,platform:m=process.platform,installed:c=()=>!1}={}){const r=a=>`${Math.round(a/1024*10)/10} GB`,g=a=>i==="podman"&&m!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((a.ramMB+2048)/2048)*2048)} && podman machine start`:i==="docker"&&m!=="linux"?"raise the memory in Docker Desktop › Settings › Resources":null,l=s(n).map(a=>{const o=t>0&&a.ramMB>t,h=!o&&Number(a.minRamMB)>0&&t>0&&t<a.minRamMB;return{...a,installed:c(a.id),recommended:!!a.recommended&&!o&&!h,...o?{unavailable:`needs about ${r(a.ramMB)} of memory while loaded — the container engine has ${r(t)}${g(a)?`; raise it: ${g(a)}`:""}`}:{},...h?{ramNote:`needs about ${r(a.ramMB)} while loaded — the engine has ${r(t)}; expect it to slow things down`}:{}}});return e&&!l.some(a=>a.id===e)&&l.push({id:e,label:/\.gguf$/i.test(e)?e.split(/[\\/]/).pop():e,lang:"—",tier:"custom",custom:!0,installed:c(e),note:/\.gguf$/i.test(e)?"A GGUF on this machine.":"Custom model (from Hugging Face)."}),l}export{u as DECIDE_MODEL_CATALOG,M as HF_ID,b as LLAMA_MODEL_CATALOG,B as RERANK_MODEL_CATALOG,p as VLLM_METAL_MODEL_CATALOG,d as VLLM_MODEL_CATALOG,L as cacheDirName,s as catalogFor,A as isLlamaModelId,k as isValidModelId,T as modelsFor,w as vllmTaskOf};
package/src/runtime.js CHANGED
@@ -1,3 +1,5 @@
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};
1
+ import{promisify as on}from"node:util";import{execFile as ln}from"node:child_process";import{existsSync as ce,mkdirSync as q,writeFileSync as de,accessSync as sn,openSync as un,closeSync as cn,constants as dn}from"node:fs";import{randomBytes as mn}from"node:crypto";import Z from"node:os";import b from"node:path";import{modelsFor as Be,isValidModelId as fn,catalogFor as me,vllmTaskOf as V}from"./runtime-models.js";import{pickInferenceEngine as Le,pickLlamaEngine as pn,pickMlxEngine as hn,recommendEngine as gn,detectAccelerator as kn,hostShape as wn}from"./inference-engines.js";import{tuningArgs as ee,tuningRows as Ce,patchTunings as bn,profilesFor as Re,resolveTunings as Ge,ENGINE_DOCS as yn}from"./engine-tunings.js";import{IMAGE_RECIPES as $n}from"./images.js";import{pullRepo as vn,pullGguf as Sn,repoInstalled as xn,ggufInstalled as Ne}from"./model-pull.js";import{spawn as An}from"node:child_process";import{readFileSync as Te,unlinkSync as Fe}from"node:fs";const _n=on(ln),ne=["podman","docker"],I="hf-cache",z=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(t,s)=>{try{return(await s(`${t}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.search?.searxng?.url||""),configure:(t,s)=>{t.search=t.search||{},t.search.searxng={...t.search.searxng||{},url:s}},unconfigure:(t,s)=>{t.search?.searxng?.url===s&&(t.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:t=>[`${b.join(t,I)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.rerank?.url||""),configure:(t,s,f)=>{t.capabilities=t.capabilities||{},t.capabilities.rerank={url:s,adapter:f.adapter,model:f.model,service:f.id}},unconfigure:(t,s)=>{t.capabilities?.rerank?.url===s&&delete t.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:t=>[`${b.join(t,I)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.decide?.url||""),configure:(t,s,f)=>{t.capabilities=t.capabilities||{},t.capabilities.decide={url:s,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}},unconfigure:(t,s)=>{t.capabilities?.decide?.url===s&&delete t.capabilities.decide}},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm:latest",engineOf:t=>Le({...t,containerOnly:!0}),container:"chatpanel-vllm",port:8891,containerPort:8e3,provides:["chat","embed","stt"],adapter:"openai",model:"Qwen/Qwen3-0.6B",pull:!0,blurb:"Your own model, served by vLLM on this machine’s accelerator (CUDA, ROCm, XPU — or CPU): a chat model the router can send turns to, an embedding model for semantic search, or a transcriber for every ear. OpenAI-shaped, loopback only.",caps:[],volumes:t=>[`${b.join(t,I)}:/data`],env:t=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${t.model}`,...t.installed?["HF_HUB_OFFLINE=1"]:[]],args:(t,s)=>["--model",t.model,"--host","0.0.0.0","--port","8000",...V(t.model)==="embed"?["--task","embed"]:[],...ee("vllm",t.tunings,{task:V(t.model),model:t.model,backend:s?.backend||null})],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.embed?.service==="vllm"?t.capabilities.embed.url.replace(/\/v1$/,""):t.capabilities?.stt?.service==="vllm"?t.capabilities.stt.url.replace(/\/v1$/,""):(t.destinations||[]).find(s=>s?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,f)=>{const h=`${s}/v1`,x=V(f.model);He(t),x==="chat"?(t.destinations=(t.destinations||[]).filter(p=>p?.service!=="vllm"&&p?.id!=="vllm"),t.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:h,models:[f.model],service:"vllm"})):x==="embed"?(t.capabilities=t.capabilities||{},t.capabilities.embed={url:h,adapter:"openai",model:f.model,service:"vllm"}):x==="transcription"&&(t.capabilities=t.capabilities||{},t.capabilities.stt={provider:"container",url:h,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:t=>He(t)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:t=>Le(t),only:{platform:"darwin",arch:"arm64"},port:8892,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU, served by vLLM-Metal: a chat model the router can send turns to. A process on this machine behind the gateway, loopback only.",command:(t,s)=>["vllm",["serve",t.model,"--host","127.0.0.1","--port",String(t.port),...ee("vllm-metal",t.tunings,s)]],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(s=>s?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="vllm-metal"&&h?.id!=="vllm-metal"),t.destinations.push({id:"vllm-metal",type:"api",protocol:"openai",baseUrl:`${s}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="vllm-metal"&&s?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:t=>pn(t),port:8893,provides:["chat"],adapter:"openai",model:"unsloth/Qwen3-4B-GGUF:Q4_K_M",blurb:"Your own GGUF model on this machine, served by llama.cpp: the Metal GPU on a Mac, CUDA or Vulkan elsewhere, CPU otherwise — a chat model the router can send turns to, with the flags that make it fast set for this machine. A process on this machine behind the gateway, loopback only.",alias:t=>/\.gguf$/i.test(t)?t.split(/[\\/]/).pop().replace(/\.gguf$/i,""):t.split("/").pop().split(":")[0],command:(t,s)=>["llama-server",[...t.file?["-m",t.file]:/\.gguf$/i.test(t.model)?["-m",t.model]:["-hf",t.model],"--host","127.0.0.1","--port",String(t.port),"--alias",t.alias(t.model),"--jinja",...ee("llama",t.tunings,s)]],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(s=>s?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="llama"&&h?.id!=="llama"),t.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${s}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="llama"&&s?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:t=>hn(t),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-4B-4bit",blurb:"Your own model on the Apple Silicon GPU through MLX — Apple’s framework, the lightest way to run a chat model on a Mac. A process on this machine behind the gateway, loopback only.",command:(t,s)=>["mlx_lm.server",["--model",t.model,"--host","127.0.0.1","--port",String(t.port),...ee("mlx",t.tunings,s)]],answers:async(t,s)=>{try{return(await s(`${t}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(s=>s?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="mlx"&&h?.id!=="mlx"),t.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${s}/v1`,models:[f.model],service:"mlx"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="mlx"&&s?.id!=="mlx"))}}]);function He(t){Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="vllm"&&s?.id!=="vllm")),t.capabilities?.embed?.service==="vllm"&&delete t.capabilities.embed,t.capabilities?.stt?.service==="vllm"&&delete t.capabilities.stt}const P=t=>z.find(s=>s.id===t)||null,Mn=({answers:t,configured:s,configure:f,unconfigure:h,volumes:x,args:p,env:G,caps:te,command:pe,engineOf:C,alias:A,...E})=>E;function Pn(t=[]){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:",...(t.length?t:["duckduckgo","brave","startpage","bing","wikipedia","qwant"]).flatMap(f=>[` - name: ${f}`," disabled: false"])," - name: google"," disabled: true",""].join(`
2
+ `)}function fe(t=process.platform){return t==="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)."}:t==="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 Ie(t,s){const f=s==="podman"?Array.isArray(t.Names)?t.Names[0]:String(t.Names||""):String(t.Names||t.Name||""),h=s==="podman"?Array.isArray(t.Ports)?t.Ports.map(p=>`${p.host_ip||""}:${p.host_port}->${p.container_port}/${p.protocol||"tcp"}`):[]:String(t.Ports||"").split(",").map(p=>p.trim()).filter(Boolean),x=String(t.State||"").toLowerCase()||(/^up/i.test(String(t.Status||""))?"running":"exited");return{name:f,image:String(t.Image||""),state:x,status:String(t.Status||""),ports:h,ours:f.startsWith("chatpanel-"),engine:s}}function Dn({cfg:t,bridgeHealth:s,workers:f=()=>[],persist:h=()=>{},exec:x=(O,U,N={})=>_n(O,U,{timeout:6e4,killSignal:"SIGKILL",...N}),platform:p=process.platform,arch:G=process.arch,spawn:te=An,lookup:pe=null,fetchImpl:C=globalThis.fetch,stateDir:A=b.join(Z.homedir(),".chatpanel","runtime"),log:E=()=>{},sleep:re=O=>new Promise(U=>setTimeout(U,O)),totalMem:he=()=>Z.totalmem()}={}){const O=Z.homedir(),U=p==="win32"?[b.join(O,"AppData","Local","Microsoft","WinGet","Links"),b.join(O,".local","bin"),b.join(O,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",b.join(O,".local","bin"),b.join(O,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin"],N=(n=process.env)=>{const e=p==="win32"?";":":",r=String(n.PATH||n.Path||""),i=U.filter(l=>!r.split(e).includes(l));return{...n,PATH:[...r.split(e).filter(Boolean),...i].join(e)}},w=async(n,e,r={})=>{try{const i=await x(n,e,{...r,env:N(r.env)});return{ok:!0,out:String(i.stdout||"").trim(),err:String(i.stderr||"").trim()}}catch(i){return{ok:!1,out:String(i?.stdout||"").trim(),err:String(i?.stderr||i?.message||i).trim(),code:i?.code}}},g=n=>String(t.runtime?.services?.[n.id]?.model||n.model||"");let ie=null;const Ue=async()=>(ie===null&&(ie=await kn({exec:x,platform:p,arch:G})),ie),j={},je=n=>{const e=p==="win32"?";":":",r=p==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of N().PATH.split(e).filter(Boolean))for(const l of r)try{return sn(b.join(i,n+l),dn.X_OK),!0}catch{}return!1},R=async(n,e=["--version"])=>(j[n]===void 0&&(j[n]=(pe||je)(n)||(await w(n,e,{timeout:8e3})).ok),j[n]);let ae=null;const ge=async()=>(ae||(ae=await wn({exec:x,platform:p,totalmem:he,cpus:()=>Z.cpus()})),ae),B=async n=>({platform:p,arch:G,accelerator:await Ue(),engine:n,vllmOnPath:await R("vllm"),llamaOnPath:await R("llama-server"),mlxOnPath:p==="darwin"&&G==="arm64"?await R("mlx_lm.server",["--help"]):!1,...await ge()}),D=n=>!n.only||(!n.only.platform||n.only.platform===p)&&(!n.only.arch||n.only.arch===G),K=n=>b.join(A,`${n.id}.pid`),X=n=>{try{const e=Number(Te(K(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},oe=n=>D(n)?X(n)?"running":"stopped":"unsupported",T={};async function le(n){const e=J(n);if(!D(e))return{ok:!1,error:`${e.label} runs on ${e.only?.platform||"this platform"} ${e.only?.arch||""} only`};if(X(e))return{ok:!0,already:!0,url:M(e)};const r=await B(null),i=e.engineOf(r);if(!await R(e.runner,e.runnerCheck))return{ok:!1,error:`\`${e.runner}\` is not on PATH — install it first (${i.install?.command||""}), or click Install`,install:i.install};if(e.id==="llama"&&/\.gguf$/i.test(e.model)&&!ce(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[l,a]=e.command(e,L(e,e.model,i,r)),o=b.join(A,I);q(o,{recursive:!0,mode:448});const u={bin:l,argv:a,opts:{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,HF_HOME:o,LLAMA_CACHE:o,...e.installed?{HF_HUB_OFFLINE:"1"}:{}}},record:{layer:"none",reason:"a model engine runs on the hardware directly, behind the gateway (loopback only) — the sandbox is for agents and tools"}};T[e.id]=u.record;const m=b.join(A,`${e.id}.log`);let d,c=null;try{try{c=un(m,"w",384)}catch{c=null}d=te(u.bin,u.argv,{...u.opts,env:N(u.opts?.env),detached:!0,stdio:["ignore",c??"ignore",c??"ignore"]}),d.unref?.()}catch(v){return{ok:!1,error:`${u.bin}: ${v.message}`,install:i.install}}finally{if(c!==null)try{cn(c)}catch{}}if(!d?.pid)return{ok:!1,error:`${u.bin} did not start`,install:i.install};de(K(e),String(d.pid),{mode:384});const y=M(e);let $=!1;for(let v=0;v<120&&!$&&X(e);v++)$=await e.answers(y,C),$||await re(1e3);if(!X(e)){try{Fe(K(e))}catch{}let v="";try{v=Te(m,"utf8").trim().split(`
3
+ `).filter(Q=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(Q)).slice(-3).map(Q=>Q.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{v=""}return{ok:!1,error:`${e.label} exited on start${v?` — ${v}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:m}}return e.configure(t,y,e),h(),E(`[runtime] ${e.label} started (pid ${d.pid}) on ${y}, sandbox ${T[e.id].layer}${$?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:y,answering:$,provides:e.provides,model:g(e),sandbox:T[e.id]}}function ke(n){const e=X(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{Fe(K(n))}catch{}return n.unconfigure(t,M(n)),h(),{ok:!0}}const J=n=>n.model?{...n,model:g(n),installed:H(n,g(n)),tunings:t.runtime?.services?.[n.id]?.tunings||{},...n.id==="llama"?{file:Xe(g(n))}:{}}:n,F=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx";function De(n,e){const r=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},l=me(n.id).filter(u=>!u.minRamMB||r>0&&r>=u.minRamMB);if(!l.length||!r)return null;const a=l.slice().sort((u,m)=>(i[m.tier]??-1)-(i[u.tier]??-1)||u.ramMB-m.ramMB)[0],o=Math.round(a.ramMB/1024*10)/10;return{model:a.id,label:a.label,why:`This machine (${e.ramGB} GB${e.accelerator==="apple"?", Apple Silicon":e.accelerator?`, ${e.accelerator.toUpperCase()} GPU`:", no GPU"}) runs ${a.label} well — about ${o} GB while loaded${a.tier==="max"?"; the strongest in the list":""}.`,profile:"coding",current:g(n)===a.id}}const L=(n,e,r,i={})=>({task:n.id==="vllm"?V(e):"chat",model:e,backend:r?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0}),W=()=>b.join(A,I),H=(n,e)=>/\.gguf$/i.test(e)?ce(e):n.id==="llama"?!!Ne(W(),e):xn(W(),e),Xe=n=>/\.gguf$/i.test(n)?n:Ne(W(),n),k={},En=n=>k[n.id]||null;function se(n,e,r={}){return k[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...r},k[n.id]}function _(n,e){const r=String(e||"").trim();if(!r)return;n.lines.push(r.slice(0,200)),n.lines.length>8&&n.lines.shift();const i=/^STEP (\d+)\/(\d+)/.exec(r);i&&(n.step={n:Number(i[1]),of:Number(i[2])})}const Y=(n,e,r,{timeout:i=36e5*4}={})=>new Promise(l=>{if(n.cancelled)return l({ok:!1,code:-1,error:"cancelled"});let a;try{a=te(e,r,{stdio:["ignore","pipe","pipe"],env:N()})}catch(d){return l({ok:!1,code:-1,error:d.message})}n.child=a;let o="";const u=d=>{o+=String(d);const c=o.split(/\r?\n|\r/);o=c.pop();for(const y of c)_(n,y)};a.stdout?.on("data",u),a.stderr?.on("data",u);const m=setTimeout(()=>{try{a.kill("SIGTERM")}catch{}},i);m.unref?.(),a.on("error",d=>{clearTimeout(m),n.child=null,l({ok:!1,code:-1,error:d.message})}),a.on("exit",d=>{clearTimeout(m),n.child=null,o&&_(n,o),l({ok:d===0&&!n.cancelled,code:d,...n.cancelled?{error:"cancelled"}:{}})})}),we={install:Promise.resolve(),build:Promise.resolve()},ue={install:0,build:0},be=(n,e,r)=>{ue[n]>0&&(e.waiting=!0,_(e,`waiting for the other ${n} to finish first — one at a time`)),ue[n]++;const i=we[n];let l;const a=new Promise(o=>{l=o});return we[n]=i.then(()=>a),i.then(async()=>{e.waiting&&(_(e,"the other one finished — going"),e.waiting=!1);try{return await r()}finally{ue[n]--,l()}})},ye=async(n,e)=>(await w(n,["image","exists",e],{timeout:2e4})).ok;async function Je(n,e,r,i){const l=e?.image||r.image;if(await ye(n,l))return{ok:!0};const a=e?.sources?.length?e.sources:[l],o=[];for(const c of a){if(i.kind="pull-image",i.detail=c,_(i,`pulling ${c}`),(await Y(i,n,["pull",c])).ok)return c!==l&&await w(n,["tag",c,l],{timeout:2e4}),{ok:!0,pulled:c};o.push(c)}const u=e?.recipe?$n[e.recipe]:null;if(!u)return{ok:!1,error:`no image to pull (${o.join(", ")} — ${i.lines.at(-1)||"refused"})`};const m=b.join(A,"images",e.recipe);return q(m,{recursive:!0,mode:448}),de(b.join(m,"Dockerfile"),u.dockerfile,{mode:384}),i.kind="build-image",i.detail=l,i.minutes=u.minutes,_(i,`no registry has ${l} for this machine — building it here (about ${u.minutes} minutes)`),E(`[runtime] building ${l} from the ${e.recipe} recipe in ${m}`),(await be("build",i,()=>Y(i,n,["build","-t",l,"-f",b.join(m,"Dockerfile"),m]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function $e(n,e){const r=g(n);if(!r||H(n,r))return{ok:!0};if(/\.gguf$/i.test(r))return{ok:!1,error:`no such file: ${r}`};e.kind="pull-model",e.detail=r;const i=l=>{if(e.cancelled)throw new Error("cancelled");e.progress={bytes:l.bytes,total:l.total,file:l.file}};try{return n.id==="llama"?await Sn(r,{root:W(),fetchImpl:C,onProgress:i}):await vn(r,{root:W(),fetchImpl:C,onProgress:i}),{ok:!0}}catch(l){return{ok:!1,error:`pull ${r}: ${l.message}`}}}async function We(n,e,r){const i=[];return n.kind!=="native"&&e&&!await ye(e,r?.image||n.image)&&i.push("image"),n.pull&&n.model&&!H(n,g(n))&&i.push("model"),i}async function ve(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&p!=="linux"){const r=await w("podman",["machine","inspect","--format","{{.Resources.Memory}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?i:0}if(n==="docker"&&p!=="linux"){const r=await w("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?Math.round(i/1048576):0}return Math.round(he()/1048576)}async function S(){const n={};for(const r of ne){const i=await w(r,["--version"],{timeout:5e3});if(!i.ok){n[r]={installed:!1};continue}const l=(i.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||i.out;let a=!1,o=null;if(r==="podman")if(p==="linux")a=(await w("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const u=await w("podman",["machine","list","--format","json"],{timeout:8e3});try{const d=JSON.parse(u.out||"[]")[0]||null;o=d?{name:d.Name,running:!!d.Running}:null,a=!!d?.Running}catch{o=null}}else a=(await w("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[r]={installed:!0,version:l,running:a,...r==="podman"&&p!=="linux"?{machine:o}:{}}}const e=ne.find(r=>n[r]?.installed&&n[r].running)||ne.find(r=>n[r]?.installed)||null;return{...n,preferred:e,...e?{}:{install:fe(p)}}}async function Se(n="podman"){if(!ne.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await S())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:fe(p)};if(e.running)return{ok:!0,already:!0};if(n==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(p!=="linux"){if(!e.machine){const i=await w("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const r=await w("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 Qe(){const n=await S(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await w("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(l=>Ie(l,"podman"))}catch{return[]}}const r=await w("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return r.ok?r.out.split(`
4
+ `).filter(Boolean).map(i=>{try{return Ie(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function xe(n,e){const r=await w(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return r.ok?/running/i.test(r.out)?"running":"stopped":"absent"}async function Ae(n,e){const r=await w(n,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!r.ok){for(const a of e)i[a]="absent";return i}const l=new Map(r.out.split(`
5
+ `).map(a=>a.split(" ")).filter(a=>a[0]).map(([a,o])=>[a,/running/i.test(o||"")?"running":"stopped"]));for(const a of e)i[a]=l.get(a)||"absent";return i}const M=n=>`http://127.0.0.1:${n.port}`;async function _e(){const n=await S(),e=n.preferred,r=await ve(e,n),i={},l=await B(e),a=e&&n[e].running?await Ae(e,z.filter(o=>o.kind!=="native").map(o=>o.container)):{};for(const o of z){const u=M(o);let m="no-engine";o.kind==="native"?m=oe(o):e&&n[e].running?m=a[o.container]||"absent":e&&(m="engine-stopped");const d=o.model?g(o):null,c=o.engineOf?o.engineOf(l):null,y=o.kind==="native"?(l.ramGB||0)*1024:r;i[o.id]={...Mn(o),engine:o.kind==="native"?"host":e,state:m,url:u,configured:o.configured(t),answering:m==="running"?await o.answers(u,C):!1,...c?{engineFor:{backend:c.backend,kind:c.kind,image:c.image||null,...c.runner?{runner:c.runner}:{},why:c.why,...c.for?{for:c.for}:{},...c.speed?{speed:c.speed}:{},...c.notFor?{notFor:c.notFor}:{},...c.warn?{warn:c.warn}:{},...c.install?{install:c.install}:{}}}:{},...o.kind==="native"&&!D(o)?{why:`${o.label} runs on ${o.only?.platform||""} ${o.only?.arch||""} only`}:{},...o.kind==="native"&&T[o.id]?{sandbox:T[o.id]}:{},...k[o.id]?{job:{kind:k[o.id].kind,since:k[o.id].since,detail:k[o.id].detail||null,step:k[o.id].step||null,minutes:k[o.id].minutes||null,progress:k[o.id].progress,lines:k[o.id].lines.slice(-4),done:k[o.id].done,error:k[o.id].error,waiting:!!k[o.id].waiting,cancelled:!!k[o.id].cancelled}}:{},...F(o)?{profiles:Re(o.id,t.runtime?.services?.[o.id]?.tunings,L(o,d,c,l)),docs:yn[o.id]||null}:{},...o.model&&o.kind==="native"?{recommend:De(o,l)}:{},...o.model?{model:d,default:o.model,models:Be(o.id,{active:d,engineRamMB:y,engine:o.kind==="native"?"host":e,platform:p,installed:$=>H(o,$)}),machine:{engineRamMB:y}}:{},...F(o)?{tunings:Ce(o.id,t.runtime?.services?.[o.id]?.tunings,L(o,d,c,l))}:{}}}return i}async function Ve(){const n=await S(),e=await B(n.preferred);return{platform:p,arch:G,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:gn(e)}}function ze(n,{settingsFile:e=null,secret:r=null,pick:i=null}={}){const l=J(n),a=["run","-d","--name",l.container,"--restart","unless-stopped","-p",`127.0.0.1:${l.port}:${l.containerPort}`];for(const o of l.volumes?l.volumes(A):[])a.push("-v",o);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const o of l.env?l.env(l):[])a.push("-e",o);r&&a.push("-e",`SEARXNG_SECRET=${r}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${l.port}/`),a.push("--cap-drop","ALL");for(const o of l.caps||[])a.push("--cap-add",o);return i?.devices?.length&&a.push(...i.devices),a.push(i?.image||l.image,...l.args?l.args(l,i):[]),a}async function Me(n){const e=P(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const r=k[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};let i=null;if(e.kind!=="native"){const m=await S();if(i=m.preferred,!i)return{ok:!1,error:"no container engine — install Podman first",install:fe(p)};if(!m[i].running){const d=await Se(i);if(!d.ok)return d}}else if(!D(e))return{ok:!1,error:`${e.label} runs on ${e.only?.platform||"this platform"} ${e.only?.arch||""} only`};const l=await B(i),a=e.engineOf?e.engineOf(l):null;if(e.kind==="native"&&!await R(e.runner,e.runnerCheck))return{ok:!1,error:`\`${e.runner}\` is not on PATH — install it first (${a?.install?.command||""}), or click Install`,install:a?.install};if(e.model&&/\.gguf$/i.test(g(e))&&!ce(g(e)))return{ok:!1,error:`no such file: ${g(e)}`};const o=await We(e,i,a);if(!o.length)return delete k[e.id],e.kind==="native"?le(e):Pe(e,i);const u=se(e,o[0]==="image"?"pull-image":"pull-model",{detail:o[0]==="image"?a?.image||e.image:g(e)});return u.then=(async()=>{try{if(o.includes("image")){const d=await Je(i,a,e,u);if(!d.ok)throw new Error(d.error)}if(o.includes("model")){const d=await $e(e,u);if(!d.ok)throw new Error(d.error)}u.kind="starting",u.detail=e.label;const m=e.kind==="native"?await le(e):await Pe(e,i);if(!m.ok)throw new Error(m.error);u.done=!0,u.result=m,E(`[runtime] ${e.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(m){u.done=!0,u.error=u.cancelled?"cancelled":m.message,E(`[runtime] ${e.label}: ${u.error}`)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function Ke(n){const e=P(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const r=k[e.id];if(!r||r.done)return{ok:!0,nothing:!0};if(r.cancelled=!0,r.child){try{r.child.kill("SIGTERM")}catch{}const i=r.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return _(r,"cancelled"),E(`[runtime] ${e.label}: job cancelled (${r.kind})`),{ok:!0,cancelled:r.kind}}async function Pe(n,e){const r=await xe(e,n.container);if(r!=="running")if(r==="stopped"){const a=await w(e,["start",n.container],{timeout:6e4});if(!a.ok)return{ok:!1,error:`${e} start: ${a.err||a.out}`}}else{q(A,{recursive:!0,mode:448});let a=null,o=null;n.id==="searxng"&&(a=b.join(A,"searxng-settings.yml"),de(a,Pn(String(t.search?.searxng?.engines||"").split(",").map(c=>c.trim()).filter(Boolean)),{mode:384}),o=mn(32).toString("hex")),n.volumes&&q(b.join(A,I),{recursive:!0,mode:448});const u=n.engineOf?n.engineOf(await B(e)):null,m=ze(n,{settingsFile:a,secret:o,pick:u});E(`[runtime] ${e} ${m.filter(c=>!c.startsWith("SEARXNG_SECRET")).join(" ")}`);const d=await w(e,m,{timeout:6e5});if(!d.ok)return{ok:!1,error:`${e} run: ${d.err||d.out}`}}const i=M(n);let l=!1;for(let a=0;a<30&&!l;a++)l=await n.answers(i,C),l||await re(1e3);return n.configure(t,i,J(n)),h(),{ok:!0,url:i,answering:l,...n.provides.length?{provides:n.provides}:{},...n.model?{model:g(n)}:{}}}async function Ye(n){const e=P(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind==="native")return ke(e);const r=await S(),i=r.preferred;if(i&&r[i].running){const l=await w(i,["stop",e.container],{timeout:6e4});if(!l.ok&&!/no such container/i.test(l.err))return{ok:!1,error:`${i} stop: ${l.err||l.out}`}}return e.unconfigure(t,M(e)),h(),{ok:!0}}async function qe(n,e){const r=P(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!r.model)return{ok:!1,error:`${r.label} takes no model`};const i=String(e||"").trim();if(!fn(n,i))return{ok:!1,error:`not a model id: ${JSON.stringify(e)} — pick one from the list, or a Hugging Face id like owner/name`};const l=await S(),a=l.preferred,o=r.kind==="native"?((await ge()).ramGB||0)*1024:await ve(a,l),u=Be(n,{active:i,engineRamMB:o,engine:r.kind==="native"?"host":a,platform:p,installed:c=>H(r,c)}).find(c=>c.id===i);if(u?.unavailable)return{ok:!1,error:`${i} ${u.unavailable}`};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},model:i};const m=M(r);r.configured(t)===m&&r.configure(t,m,J(r)),h();const d=await Ee(r,a,l);return d.ok?{ok:!0,model:i,restarted:d.restarted,...u?.ramNote?{note:u.ramNote}:{}}:d}async function Ee(n,e,r){if(n.kind==="native"){if(oe(n)!=="running")return{ok:!0,restarted:!1};ke(n);const a=await le(n);return a.ok?{ok:!0,restarted:!0}:a}if(!e||!r[e].running)return{ok:!0,restarted:!1};const i=await xe(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const l=await w(e,["rm","-f",n.container],{timeout:6e4});if(!l.ok&&!/no such container/i.test(l.err))return{ok:!1,error:`${e} rm: ${l.err||l.out}`};if(i==="running"){const a=await Me(n.id);return a.ok?{ok:!0,restarted:!0}:a}return{ok:!0,restarted:!1}}async function Ze(n,e){const r=P(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!F(r))return{ok:!1,error:`${r.label} takes no profile`};const i=await S(),l=await B(i.preferred),a=r.engineOf?r.engineOf(l):null,o=Re(r.id,t.runtime?.services?.[n]?.tunings,L(r,g(r),a,l)).find(m=>m.id===e);if(!o)return{ok:!1,error:`no profile ${JSON.stringify(e)} — one of speed, coding, long, xl`};if(!o.fits)return{ok:!1,error:`${o.label}: ${o.why}`};const u=await Oe(n,o.patch);return u.ok?{...u,profile:o.id}:u}async function en(n){const e=P(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!D(e))return{ok:!1,error:`${e.label} runs on ${e.only?.platform||"this platform"} ${e.only?.arch||""} only`};const r=k[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(delete j[e.runner],await R(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const l=e.engineOf(await B(null))?.install;if(!l?.steps?.length)return{ok:!1,error:`no installer for ${e.label} on this platform${l?.url?` — see ${l.url}`:""}`,install:l||null};const a=se(e,"install",{detail:e.runner});return a.then=be("install",a,async()=>{const o=async d=>{for(const[c,...y]of d){_(a,`$ ${c} ${y.join(" ")}`);let $=await Y(a,c,y,{timeout:36e5});for(let v=0;!$.ok&&!a.cancelled&&v<6&&a.lines.some(Q=>/already locked|Please wait for it to finish/i.test(Q));v++)_(a,`another ${c} holds the lock — waiting 20 s (${v+1}/6)`),await re(2e4),$=await Y(a,c,y,{timeout:36e5});if(!$.ok)return{ok:!1,error:$.error||`${c} exited ${$.code}`}}return{ok:!0}};let u=await o(l.steps);!u.ok&&!a.cancelled&&l.fallback?.length&&(_(a,`${u.error} — trying the other way`),u=await o(l.fallback)),delete j[e.runner];const m=u.ok&&await R(e.runner,e.runnerCheck);a.done=!0,a.cancelled?a.error="cancelled":u.ok?m||(a.error=`${e.runner} still not found after the install — open a new terminal and run \`${l.command}\` by hand`):a.error=`install failed: ${u.error}${a.lines.length?` (${a.lines.slice(-2).join(" | ")})`:""}`,E(`[runtime] install ${e.runner}: ${a.error||"ok"}`)}),{ok:!0,pending:{kind:a.kind,since:a.since,detail:a.detail}}}async function nn(n){const e=P(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const r=k[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(H(e,g(e)))return{ok:!0,installed:!0,model:g(e)};const i=se(e,"pull-model",{detail:g(e)});return i.then=(async()=>{const l=await $e(e,i);i.done=!0,l.ok||(i.error=l.error)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Oe(n,e){const r=P(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!F(r))return{ok:!1,error:`${r.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await S(),l=i.preferred,a=g(r),o=await B(l),u=r.engineOf?r.engineOf(o):null,m=bn(r.id,t.runtime?.services?.[n]?.tunings,e,L(r,a,u,o));if(m.error)return{ok:!1,error:m.error};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},tunings:m},h();const d=await Ee(r,l,i);return d.ok?{ok:!0,tunings:Ce(r.id,m,L(r,a,u,o)),restarted:d.restarted}:d}async function tn(){const n=await S(),e=n.preferred,r=e&&n[e].running?await Ae(e,z.filter(a=>a.kind!=="native").map(a=>a.container)):{},i={};let l=!1;return await Promise.all(z.map(async a=>{const o=a.kind==="native"?oe(a):e&&n[e].running?r[a.container]||"absent":"no-engine";i[a.id]=o==="running"&&await a.answers(M(a),C)?"up":"down",i[a.id]==="up"&&a.configure&&a.configured(t)!==M(a)&&(a.configure(t,M(a),J(a)),l=!0)})),l&&h(),i}function rn(n){const e=P(n);if(!e||!F(e))return null;const r=Number(Ge(e.id,t.runtime?.services?.[n]?.tunings,L(e,g(e),null,{})).maxModelLen);return Number.isFinite(r)&&r>0?r:null}function an(n){const e=P(n);if(!e||!F(e))return null;const r=g(e),i=Ge(e.id,t.runtime?.services?.[n]?.tunings,L(e,r,null,{})),l=me(e.id).find(o=>o.id===r)||null,a=e.id==="vllm"?V(r):"chat";return{engine:e.id,backend:T[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:a,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:a==="chat"&&!!i.vision,tools:!!(a==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:a==="chat"&&!!i.reasoning&&i.reasoning!=="off",...l?{tier:l.tier||null,licence:l.licence||null,languages:l.lang||null,label:l.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}return{health:tn,contextWindow:rn,modelCard:an,async status(){const[n,e,r,i,l]=await Promise.all([s().catch(()=>null),S(),_e(),Qe(),Ve()]);return{machine:l,sandbox:n?.sandbox||null,processes:{all:[...Array.isArray(n?.processes)?n.processes:[],...f()],localMcp:Array.isArray(n?.localMcp)?n.localMcp:[],warm:n?.warm||null},containers:i,refused:Array.isArray(n?.sandbox?.refused)?n.sandbox.refused:[],bridge:n?{ok:!0,version:n.version||""}:{ok:!1},engines:e,services:r}},startEngine:Se,startService:Me,stopService:Ye,setModel:qe,setTunings:Oe,setProfile:Ze,pullModel:nn,installRunner:en,cancelJob:Ke,services:_e,catalogFor:me}}export{z as SERVICES,Ie as containerRow,Dn as createRuntime,fe as installDoor,Pn as searxngSettings};