@chatpanel/gateway 0.64.0 → 0.85.2
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/bin/chatpanel-gateway.js +5 -5
- package/native/darwin-arm64/chatpanel-apple-model +0 -0
- package/package.json +6 -5
- package/src/apple-model.js +1 -0
- package/src/capabilities.js +1 -1
- package/src/capability-endpoints.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/engine-pacer.js +1 -0
- package/src/engine-tunings.js +1 -1
- package/src/host-memory.js +1 -0
- package/src/inference-engines.js +1 -1
- package/src/link-host.js +1 -1
- package/src/local-engine-probe.js +1 -0
- package/src/ner-engine.js +1 -1
- package/src/pair-prompt.js +12 -0
- package/src/recruiting.js +1 -1
- package/src/redact.js +2 -2
- package/src/retrieval/search-apis.js +1 -0
- package/src/retrieval/search-serp.js +1 -1
- package/src/retrieval/search.js +1 -1
- package/src/router.js +1 -1
- package/src/runtime-models.js +1 -1
- package/src/runtime.js +6 -5
- package/src/search-api.js +1 -0
- package/src/search-outcome.js +1 -0
- package/src/server.js +37 -28
- package/src/service.js +11 -10
- package/src/stt-engine.js +1 -1
- package/src/version.js +1 -1
- package/src/web-search-tool.js +8 -8
- package/src/web-search.js +1 -1
- package/src/ws-accept.js +7 -0
package/src/ner-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import nt from"node:os";import{join as O}from"node:path";import{existsSync as Y,mkdirSync as rt,readdirSync as B,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{nativeOrtFailure as pt}from"./ort.js";import{makeWarmTimer as G}from"./warm-timer.js";import{makeModelFileCache as dt}from"./model-file-cache.js";const E="https://dl.chatpanel.net/models/";function mt(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return E;const o=c=>(console.warn(`[models] ignoring ${e} (${r}): ${c} — using ${E}`),E);let n;try{n=new URL(r)}catch{return o("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return o(`scheme ${n.protocol} not allowed`);if(lt(n.hostname))return o("points at cloud metadata");const s=it(n.hostname)||at(n.hostname);return n.protocol==="http:"&&!s?o("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${n.origin} (${e}), not ${E}`),r.replace(/\/*$/,"/"))}const ht=mt();let d="off",g=null,y=null,M=null,L=null,A=null,b=null,T=null,_=null,C=0,v=null;const m=new Map;function N(){return process.env.CHATPANEL_MODELS_DIR||O(nt.homedir(),".chatpanel","models")}function R(t=g||J){const e=O(N(),...t.split("/"));return Y(O(e,"onnx","model_quantized.onnx"))||Y(O(e,"onnx","model.onnx"))}function zt(){const t=N(),e=[];try{for(const r of B(t,{withFileTypes:!0}))if(r.isDirectory())for(const o of B(O(t,r.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const n=`${r.name}/${o.name}`;R(n)&>(O(t,r.name,o.name))&&e.push(n)}}catch{}return e}function gt(t){try{return(JSON.parse(ot(O(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function Yt(){return d}function $(){return d==="ready"&&!!y}function Bt(){return{configured:d!=="off",ok:$(),state:d,model:g,error:M,runtime:ft(),dtype:y?"q8":null,stats:kt(),companions:bt(),warmMs:_?.warmMs??null}}async function yt(t,{signal:e}={}){if(!$())return[];if(e?.aborted)return[];const r=String(t||""),o=await Q(r,e);if(!o)return[];const n=[];for(const i of o||[]){let u=String(i.word??"");const a=i.entity_group??i.entity??"ENTITY";if(u.startsWith("##")&&n.length&&n[n.length-1].type===a){n[n.length-1].value+=u.slice(2);continue}u=u.replace(/##/g,"").trim(),u&&n.push({value:u,type:a})}const s=new Set,c=[];for(const i of n){const u=vt(r,At(r,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 Q(t,e){C++;try{return await wt(t,e)}finally{C--,k()||_?.arm()}}async function wt(t,e){const r=performance.now(),o=[],n=[{text:t,key:"orig"}];if(H){const s=ct(t);s.changed&&n.push({text:s.text,key:"recased"})}for(const{model:s,pipe:c}of V())for(const i of n){let u=0;for(const a of Ot(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 $t(performance.now()-r,t.length,o.length),o}let H=!0;function Jt(t){H=t!==!1}async function Gt(t,{signal:e}={}){if(!$())return[];const r=String(t||""),o=await Q(r,e);if(!o)return[];const n=[],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 x=f._passText||r;let h=x.indexOf(p,c);if(h<0&&(h=x.indexOf(p,f._win)),h<0)continue;let S=h+p.length;c=S;const W=z=>!!z&&/[\p{L}\p{N}'’-]/u.test(z);for(;h>0&&W(r[h-1]);)h--;for(;S<r.length&&W(r[S]);)S++;const U=String(f.entity_group??f.entity??"ENTITY"),j=`${h}:${S}:${U}`;if(s.has(j))continue;s.add(j);const q=Number(f.score);n.push({value:r.slice(h,S),type:U,start:h,end:S,score:Number.isFinite(q)?Math.max(0,Math.min(1,q)):1,model:f._model})}n.sort((f,p)=>f.start-p.start||f.end-p.end);const l=[];for(const f of n){const p=l[l.length-1];if(p&&p.type===f.type&&p.end===f.start){p.end=f.end,p.value=r.slice(p.start,p.end),p.score=Math.min(p.score,f.score);continue}l.push({...f})}return m.size||H?Mt(l):l}const K=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function _t(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 P(t){const e=K.indexOf(_t(t.type));return e<0?K.length:e}let D=[];function xt(t){D=Array.isArray(t)?t.slice():[]}function F(t){if(t.model===g)return-1;const e=D.indexOf(t.model);return e<0?D.length:e}function Mt(t){const e=[...t].sort((o,n)=>o.start-n.start||n.end-o.end),r=[];for(const o of e){const n=r[r.length-1];if(n&&o.start<n.end){const s=i=>i.end-i.start;(P(o)<P(n)||P(o)===P(n)&&(s(o)>s(n)||s(o)===s(n)&&(F(o)<F(n)||F(o)===F(n)&&o.score>n.score)))&&(r[r.length-1]=o);continue}r.push(o)}return r}function Qt(){const t=y?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const o=String(r).replace(/^[BIES]-/,"");o&&o!=="O"&&e.add(o)}return[...e]}function Kt(){const t=Number(y?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function bt(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function Lt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===g)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:n}=await I(t,{log:e,allowDownload:r});return m.set(t,{pipe:n,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(n){return m.set(t,{pipe:null,state:"error",error:n.message}),e(`[ner] companion ${t} failed to load (${n.message}) — the union runs without it`),!1}}async function Vt(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=y?[{model:g,pipe:y}]:[];for(const[e,r]of m)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const St=160,X=256;function Ot(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),n=Math.min(X,Number.isFinite(r)&&r>0?r:X)-8,s=a=>{try{return e(a).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=n)return[t];const c=[];let i=0,u=Math.max(64,Math.floor(n*3));for(;i<t.length;){let a=Math.min(t.length,i+u);if(a<t.length){const x=t.lastIndexOf(" ",a);x>i+u/2&&(a=x)}let l=t.slice(i,a);for(;s(l)>n&&l.length>32;){u=Math.max(32,Math.floor(l.length/2)),a=i+u;const x=t.lastIndexOf(" ",a);x>i+u/2&&(a=x),l=t.slice(i,a)}if(c.push(l),a>=t.length)break;const f=Math.max(i+1,a-St),p=t.indexOf(" ",f);i=p>0&&p<a?p+1:a}return c}const Tt=200,w=[];function $t(t,e,r){w.push({ms:t,chars:e,spans:r}),w.length>Tt&&w.shift()}function kt(){if(!w.length)return{calls:0};const t=w.map(n=>n.ms).sort((n,s)=>n-s),e=n=>t[Math.min(t.length-1,Math.floor(n*t.length))],r=w.reduce((n,s)=>n+s.chars,0),o=w.reduce((n,s)=>n+s.ms,0);return{calls:w.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(w[w.length-1].ms),charsPerSec:o>0?Math.round(r/(o/1e3)):null}}function At(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function vt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const o=c=>!!c&&/[\p{L}\p{N}'’-]/u.test(c);let n=r,s=r+e.length;for(;n>0&&o(t[n-1]);)n--;for(;s<t.length&&o(t[s]);)s++;return t.slice(n,s)}async function Xt(t,e={}){let r="";try{r=JSON.parse(e.body||"{}").text||""}catch{}const o=await yt(r,{signal:e.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Zt(){return b}async function Z(){if(A)return A;const t=N();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{}let r;try{r=await import("@huggingface/transformers")}catch(p){throw e?p:new Error(pt(p))}const{env:o,pipeline:n,Tensor:s,AutoModel:c,AutoProcessor:i,AutoTokenizer:u,AutoModelForSequenceClassification:a,LogLevel:l}=r;if(o.cacheDir=t,e&&l)try{o.logLevel=l.ERROR}catch{}o.localModelPath=t,e||(o.useCustomCache=!0,o.customCache=dt(t,{remoteHost:()=>o.remoteHost}));try{o.remoteHost=ht}catch{}try{o.backends.onnx.wasm.numThreads=1}catch{}if(e)try{o.backends.onnx.wasm.proxy=!1,o.backends.onnx.wasm.wasmPaths=e}catch{}return A={env:o,pipeline:(p,x,h={})=>n(p,x,h.progress_callback&&o.allowRemoteModels===!1?{...h,progress_callback:void 0}:h),Tensor:s,AutoModel:c,AutoProcessor:i,AutoTokenizer:u,AutoModelForSequenceClassification:a},A}async function I(t,{log:e=()=>{},allowDownload:r=!0,onProgress:o=()=>{}}={}){const n=await Z(),s=R(t);if(n.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const c=n.env.remoteHost,i=!st(t);if(!s&&i)try{n.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 n.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}catch(l){if(s||i||!r)throw l;e(`[ner] mirror fetch failed (${String(l.message).slice(0,80)}) — retrying from Hugging Face…`),n.env.remoteHost="https://huggingface.co/",n.env.allowRemoteModels=!0,a=await n.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}if(!s)try{ut(t,{modelsDir:N(),log:e})}catch(l){try{await a.dispose?.()}catch{}throw l}return{pipe:a,haveLocal:s}}finally{try{n.env.remoteHost=c}catch{}}}async function tt(t,{log:e=()=>{},allowDownload:r=!0}={}){const o=y,n=g;try{await Z()}catch(c){return d="error",M=`engine load failed: ${c.message}`,e(`[ner] transformers.js not available (${c.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return d="error",M="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(b={model:t,file:null,pct:0});try{const{pipe:c}=await I(t,{log:e,allowDownload:r,onProgress:i=>{b={model:t,file:i.file||b?.file||null,pct:typeof i.progress=="number"?Math.round(i.progress):b?.pct??0}}});if(y=c,g=t,d="ready",M=null,b=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`),k()||_?.arm(),!0}catch(c){return M=c.message,b=null,o?(y=o,g=n,d="ready"):d="error",e(`[ner] model load failed (${c.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function Et(t={}){if(L)return L;const e=typeof t.onLog=="function"?t.onLog:()=>{};T=t,g=t.model||J,d="loading";const r=t.allowDownload!==!1;return _=G({warmMs:t.warmMs,busy:k,log:e,unload:()=>et({log:e})}),L=tt(g,{log:e,allowDownload:r}).then(async o=>{const n=Array.isArray(t.union)?t.union:[];xt(n);for(const s of n)await Lt(s,{log:e,allowDownload:r});return $()&&!k()&&_?.arm(),o}),L}function k(){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(k())return!1;_?.disarm();const e=V().map(r=>r.pipe);y=null,L=null,b=null,M=null,m.clear(),d=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((_?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function It(){try{d==="idle"&&(v||T)?await(v?v():Et(T)):L&&await L}catch{}return $()}async function te(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},o=e.allowDownload!==!1;if(!t)return!1;if(t===g&&$())return!0;const n=m.get(t);if(n?.pipe){const s=y;if(y=n.pipe,g=t,d="ready",M=null,m.delete(t),s)try{await s.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),!0}return tt(t,{log:r,allowDownload:o})}function ee(){d="off",g=null,y=null,M=null,L=null,A=null,b=null,w.length=0,m.clear(),H=!0,D=[],_?.disarm(),_=null,T=null,C=0,v=null}function ne(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function re(t,{model:e="test/model",warmMs:r=null,reload:o=null}={}){y=t,g=e,d="ready",M=null,w.length=0,o&&(v=o),r!==null&&(_=G({warmMs:r,busy:k,unload:()=>et()}),t&&_.arm())}export{ee as _reset,ne as _setCompanionForTest,re as _setForTest,Lt as addCompanion,bt as companions,yt as detect,Gt as detectSpans,It as ensure,Z as ensureLib,Xt as fetchAdapter,Bt as health,Et as init,$ as isReady,Qt as labels,Kt as maxTokens,R as modelOnDisk,N as modelRoot,zt as modelsOnDisk,Zt as progress,Vt as removeCompanion,mt as resolveModelHost,Jt as setCaseRecovery,te as setModel,xt as setUnionOrder,Yt as state,kt as stats,Mt as unionSpans,et as unload,Ot as windowsFor};
|
|
1
|
+
import lt from"node:os";import{join as O}from"node:path";import{existsSync as G,mkdirSync as ct,readdirSync as Q,readFileSync as ut}from"node:fs";import{DEFAULT_MODEL as K,isMirroredModel as ft}from"./models.js";import{isLoopbackHost as pt,isPrivateHost as dt,isMetadataHost as ht}from"@chatpanel/pii";import{recaseForDetection as mt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as gt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as yt}from"./model-integrity.js";import{runtimeName as wt}from"./model-runtime.js";import{nativeOrtFailure as _t}from"./ort.js";import{makeWarmTimer as V}from"./warm-timer.js";import{makeModelFileCache as xt}from"./model-file-cache.js";const N="https://dl.chatpanel.net/models/";function Mt(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return N;const n=u=>(console.warn(`[models] ignoring ${e} (${r}): ${u} — using ${N}`),N);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(ht(o.hostname))return n("points at cloud metadata");const s=pt(o.hostname)||dt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${N}`),r.replace(/\/*$/,"/"))}const bt=Mt();let d="off",g=null,y=null,b=null,S=null,E=null,L=null,h=null,_=null,P=0,C=null;const m=new Map;function R(){return process.env.CHATPANEL_MODELS_DIR||O(lt.homedir(),".chatpanel","models")}function H(t=g||K){const e=O(R(),...t.split("/"));return G(O(e,"onnx","model_quantized.onnx"))||G(O(e,"onnx","model.onnx"))}function Xt(){const t=R(),e=[];try{for(const r of Q(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of Q(O(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;H(o)&&Lt(O(t,r.name,n.name))&&e.push(o)}}catch{}return e}function Lt(t){try{return(JSON.parse(ut(O(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function Zt(){return d}function k(){return d==="ready"&&!!y}function It(){return{configured:d!=="off",ok:k(),state:d,model:g,error:b,runtime:wt(),dtype:y?"q8":null,stats:Pt(),companions:At(),warmMs:_?.warmMs??null}}async function St(t,{signal:e,strict:r=!1}={}){if(!k())return[];if(e?.aborted)return[];const n=String(t||""),o=await X(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(Z(f,r))continue;let i=String(f.word??"");const a=f.entity_group??f.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===a){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:a})}const u=new Set,c=[];for(const f of s){const i=Ht(n,Rt(n,f.value.trim()));if(i.length<=1)continue;const a=`${f.type}:${i.toLowerCase()}`;u.has(a)||(u.add(a),c.push({value:i,type:f.type}))}return c}async function X(t,e){P++;try{return await Tt(t,e)}finally{P--,v()||_?.arm()}}async function Tt(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(D){const s=mt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:u}of et())for(const c of o){let f=0;for(const i of Et(c.text,u.tokenizer)){if(e?.aborted)return null;const a=c.text.indexOf(i,f),x=await u(i,{aggregation_strategy:"simple"});for(const l of x||[])n.push({...l,_win:a<0?f:a,_winText:i,_model:s,_pass:c.key,_passText:c.text});a>=0&&(f=Math.max(f,a+1))}}return Nt(performance.now()-r,t.length,n.length),n}let D=!0;function te(t){D=t!==!1}const Z=(t,e)=>!e&&t._pass==="recased"&&!gt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function ee(t,{signal:e,strict:r=!1}={}){if(!k())return[];const n=String(t||""),o=await X(n,e);if(!o)return[];const s=[],u=new Set;let c=-1,f=-1,i=null,a=null;for(const l of o){if(Z(l,r))continue;const p=String(l.word??"").replace(/##/g,"").trim();if(!p)continue;(l._win!==f||l._model!==i||l._pass!==a)&&(f=l._win,i=l._model,a=l._pass,c=l._win);const $=l._passText||n;let M=$.indexOf(p,c);if(M<0&&(M=$.indexOf(p,l._win)),M<0)continue;let T=M+p.length;c=T;const q=J=>!!J&&/[\p{L}\p{N}'’-]/u.test(J);for(;M>0&&q(n[M-1]);)M--;for(;T<n.length&&q(n[T]);)T++;const z=String(l.entity_group??l.entity??"ENTITY"),Y=`${M}:${T}:${z}`;if(u.has(Y))continue;u.add(Y);const B=Number(l.score);s.push({value:n.slice(M,T),type:z,start:M,end:T,score:Number.isFinite(B)?Math.max(0,Math.min(1,B)):1,model:l._model})}s.sort((l,p)=>l.start-p.start||l.end-p.end);const x=[];for(const l of s){const p=x[x.length-1];if(p&&p.type===l.type&&p.end===l.start){p.end=l.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,l.score);continue}x.push({...l})}return m.size||D?$t(x):x}const I=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function Ot(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 F(t){const e=I.indexOf(Ot(t.type));return e<0?I.length:e}let A=[];function kt(t){A=Array.isArray(t)?t.slice():[],h&&(h={...h,union:A.slice()})}function W(t){if(t.model===g)return-1;const e=A.indexOf(t.model);return e<0?A.length:e}function $t(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=c=>c.end-c.start;(F(n)<F(o)||F(n)===F(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function ne(){const t=y?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function oe(){const t=Number(y?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function At(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function tt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===g)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:H(t)?"loading":"downloading",error:null});try{const{pipe:o}=await rt(t,{log:e,allowDownload:r});return m.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return m.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function re(t){const e=m.get(t);if(!e)return!1;m.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function et(){const t=y?[{model:g,pipe:y}]:[];for(const[e,r]of m)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const vt=160,nt=256;function Et(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(nt,Number.isFinite(r)&&r>0?r:nt)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const u=[];let c=0,f=Math.max(64,Math.floor(o*3));for(;c<t.length;){let i=Math.min(t.length,c+f);if(i<t.length){const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p)}let a=t.slice(c,i);for(;s(a)>o&&a.length>32;){f=Math.max(32,Math.floor(a.length/2)),i=c+f;const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p),a=t.slice(c,i)}if(u.push(a),i>=t.length)break;const x=Math.max(c+1,i-vt),l=t.indexOf(" ",x);c=l>0&&l<i?l+1:i}return u}const Ct=200,w=[];function Nt(t,e,r){w.push({ms:t,chars:e,spans:r}),w.length>Ct&&w.shift()}function Pt(){if(!w.length)return{calls:0};const t=w.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=w.reduce((o,s)=>o+s.chars,0),n=w.reduce((o,s)=>o+s.ms,0);return{calls:w.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(w[w.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Rt(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function Ht(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=u=>!!u&&/[\p{L}\p{N}'’-]/u.test(u);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function se(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await St(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function ie(){return L}async function ot(){if(E)return E;const t=R();try{ct(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{}let r;try{r=await import("@huggingface/transformers")}catch(l){throw e?l:new Error(_t(l))}const{env:n,pipeline:o,Tensor:s,AutoModel:u,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i,LogLevel:a}=r;if(n.cacheDir=t,e&&a)try{n.logLevel=a.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=xt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=bt}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 E={env:n,pipeline:(l,p,$={})=>o(l,p,$.progress_callback&&n.allowRemoteModels===!1?{...$,progress_callback:void 0}:$),Tensor:s,AutoModel:u,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i},E}async function rt(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await ot(),s=H(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const u=o.env.remoteHost,c=!ft(t);if(!s&&c)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${c?", from Hugging Face":""})…`);try{const f=a=>{a&&(a.status==="progress"||a.status==="download"||a.status==="initiate"?n(a):a.status==="done"&&a.file&&e(`[ner] fetched ${a.file}`))};let i;try{i=await o.pipeline("token-classification",t,{dtype:"q8",progress_callback:f})}catch(a){if(s||c||!r)throw a;e(`[ner] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,i=await o.pipeline("token-classification",t,{dtype:"q8",progress_callback:f})}if(!s)try{yt(t,{modelsDir:R(),log:e})}catch(a){try{await i.dispose?.()}catch{}throw a}return{pipe:i,haveLocal:s}}finally{try{o.env.remoteHost=u}catch{}}}async function st(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=y,o=g;try{await ot()}catch(u){return d="error",b=`engine load failed: ${u.message}`,e(`[ner] transformers.js not available (${u.message}) — deterministic-only`),!1}const s=H(t);if(!s&&!r)return d="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:u}=await rt(t,{log:e,allowDownload:r,onProgress:c=>{L={model:t,file:c.file||L?.file||null,pct:typeof c.progress=="number"?Math.round(c.progress):L?.pct??0}}});if(y=u,g=t,d="ready",b=null,L=null,h&&(h={...h,model:t}),n&&n!==u)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),v()||_?.arm(),!0}catch(u){return b=u.message,L=null,n?(y=n,g=o,d="ready"):d="error",e(`[ner] model load failed (${u.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function Dt(t={}){if(S)return S;const e=typeof t.onLog=="function"?t.onLog:()=>{};h=t,g=t.model||K,d="loading";const r=t.allowDownload!==!1;return _=V({warmMs:t.warmMs,busy:v,log:e,unload:()=>it({log:e})}),S=st(g,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];kt(o);for(const s of o)await tt(s,{log:e,allowDownload:r});return k()&&!v()&&_?.arm(),n}),S}function v(){if(P>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 it({log:t=()=>{}}={}){if(v())return!1;_?.disarm();const e=et().map(r=>r.pipe);y=null,S=null,L=null,b=null,m.clear(),d=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((_?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function Ft(){try{d==="idle"&&(C||h)?await(C?C():Dt(h)):S&&await S,k()&&await at()}catch{}return k()}let U=null;function at(){const t=A.filter(e=>e&&e!==g&&!m.has(e));return t.length?(U||=(async()=>{const e=typeof h?.onLog=="function"?h.onLog:()=>{};for(const r of t)m.has(r)||(j?await j(r):await tt(r,{log:e,allowDownload:h?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function ae(t){j=t}async function le(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===g&&k())return!0;if(t===g&&d==="idle")return Ft();const o=m.get(t);if(o?.pipe){const u=y;if(y=o.pipe,g=t,d="ready",b=null,m.delete(t),u)try{await u.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),h&&(h={...h,model:t}),!0}const s=await st(t,{log:r,allowDownload:n});return s&&(h&&(h={...h,model:t}),await at()),s}function ce(){d="off",g=null,y=null,b=null,S=null,E=null,L=null,w.length=0,m.clear(),D=!0,A=[],_?.disarm(),_=null,h=null,P=0,C=null,j=null,U=null}function ue(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function fe(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){y=t,g=e,d="ready",b=null,w.length=0,n&&(C=n),r!==null&&(_=V({warmMs:r,busy:v,unload:()=>it()}),t&&_.arm())}export{ce as _reset,ue as _setCompanionForTest,ae as _setCompanionLoaderForTest,fe as _setForTest,tt as addCompanion,At as companions,St as detect,ee as detectSpans,Ft as ensure,ot as ensureLib,se as fetchAdapter,It as health,Dt as init,k as isReady,ne as labels,oe as maxTokens,H as modelOnDisk,R as modelRoot,Xt as modelsOnDisk,ie as progress,re as removeCompanion,Mt as resolveModelHost,te as setCaseRecovery,le as setModel,kt as setUnionOrder,Zt as state,Pt as stats,$t as unionSpans,it as unload,Et as windowsFor};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{spawn as g}from"node:child_process";const p=9e4,h=6e5,b=4,f=60,A={chrome:"Google Chrome",edge:"Microsoft Edge",firefox:"Firefox",brave:"Brave",opera:"Opera"},y=c=>A[String(c||"").toLowerCase()]||"a browser";function v({confirm:c,now:s=()=>Date.now(),random:a=Math.random,newId:r,ttlMs:n=p}={}){let e=null,t=[];const m=()=>{e&&e.status==="waiting"&&s()>e.expiresAt&&(e.status="expired")};function l({browser:u="",who:w=""}={}){if(m(),e?.status==="waiting")return{ok:!1,reason:"busy"};if(t=t.filter(d=>s()-d<h),t.length>=b)return{ok:!1,reason:"too_many"};t.push(s());const o={id:r(),who:String(w),number:String(Math.floor(a()*9e3)+1e3),expiresAt:s()+n,status:"waiting"};return e=o,Promise.resolve().then(()=>c({browser:y(u),number:o.number})).then(d=>{o.status==="waiting"&&(o.status=d==="allow"?"allowed":d==="unavailable"?"unavailable":"denied")}).catch(()=>{o.status==="waiting"&&(o.status="unavailable")}),{ok:!0,id:o.id,number:o.number,expiresAt:o.expiresAt}}function i(u,{who:w=""}={}){if(m(),!e||!u||String(u)!==e.id||String(w)!==e.who)return{status:"expired"};const{status:o}=e;return o!=="waiting"&&(e=null),{status:o}}return{ask:l,result:i}}function $({browser:c,number:s},{platform:a=process.platform,run:r=S,env:n=process.env,seconds:e=f}={}){if(String(n.CHATPANEL_PAIR_PROMPT||"").toLowerCase()==="off")return Promise.resolve("unavailable");const t="ChatPanel",m=`${c} on this computer is asking to connect to ChatPanel.
|
|
2
|
+
|
|
3
|
+
Number: ${s}
|
|
4
|
+
|
|
5
|
+
Allow only if you just pressed “Pair this browser” in Chap's settings and it shows the same number.`;if(a==="darwin"){const l=`on run argv
|
|
6
|
+
set r to display dialog (item 1 of argv) with title (item 2 of argv) buttons {"Don't Allow", "Allow"} default button "Don't Allow" cancel button "Don't Allow" with icon caution giving up after ${e}
|
|
7
|
+
if gave up of r then return "deny"
|
|
8
|
+
if button returned of r is "Allow" then return "allow"
|
|
9
|
+
return "deny"
|
|
10
|
+
end run`;return r("osascript",["-e",l,m,t]).then(i=>i.missing?"unavailable":/^allow\s*$/.test(i.out)?"allow":"deny")}if(a==="win32"){const l='$f = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true }; $r = [System.Windows.Forms.MessageBox]::Show($f, $args[0], $args[1], "YesNo", "Warning", "Button2"); if ($r -eq "Yes") { "allow" } else { "deny" }',i=`${m}
|
|
11
|
+
|
|
12
|
+
Yes = Allow No = Don't allow`;return r("powershell.exe",["-NoProfile","-NonInteractive","-STA","-Command",`Add-Type -AssemblyName System.Windows.Forms; & { ${l} } @args`,i,t]).then(u=>u.missing||u.code!==0?"unavailable":/^allow\s*$/.test(u.out)?"allow":"deny")}return!n.DISPLAY&&!n.WAYLAND_DISPLAY?Promise.resolve("unavailable"):r("zenity",["--question",`--title=${t}`,`--text=${m}`,"--ok-label=Allow","--cancel-label=Don't Allow","--default-cancel",`--timeout=${e}`]).then(l=>l.missing?r("kdialog",["--title",t,"--warningyesno",m]).then(i=>i.missing?"unavailable":i.code===0?"allow":"deny"):l.code===0?"allow":"deny")}function S(c,s){return new Promise(a=>{let r="",n;try{n=g(c,s,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{a({code:-1,out:"",missing:!0});return}const e=setTimeout(()=>{try{n.kill()}catch{}},(f+15)*1e3);e.unref?.(),n.stdout.on("data",t=>{r+=t}),n.on("error",t=>{clearTimeout(e),a({code:-1,out:"",missing:t?.code==="ENOENT"})}),n.on("close",t=>{clearTimeout(e),a({code:t,out:r.trim(),missing:!1})})})}export{b as ASK_MAX_IN_WINDOW,p as ASK_TTL_MS,h as ASK_WINDOW_MS,y as browserName,v as createPairAsk,$ as nativeConfirm};
|
package/src/recruiting.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{summarize as
|
|
1
|
+
import{summarize as v}from"./scorecard.js";import{applications as k,evaluatorPrompt as M,parseEvaluation as b,decide as P,recruitEvents as S,engineRows as A,MIN_FIT as E}from"./recruit.js";import{aggregateModelsAsync as F,listDestinations as D}from"./router.js";import{reachOfGatewayModel as N}from"@chatpanel/events/model-candidates.js";const O=new Set(["device","trusted","any"]);async function R(o,n,{jobKind:s=null,minCalls:r,timeoutMs:i=2500,engineAt:p=null}={}){const d=await F(o,{timeoutMs:i,engineAt:p}).catch(()=>({data:[]})),u=new Map(D(o).map(e=>[e.id,e])),t=(d.data||[]).map(e=>{const f=e.owned_by==="chatpanel-bridge",c=u.get(e.provider);return{id:e.id,model:e.id,kind:f?"bridge":"api",label:e.model?`${e.provider} · ${e.model}`:e.id,reach:N(e,c),capabilities:["tools"],available:e.configured===!1?!1:e.available!==!1}}),l=Object.fromEntries((n?.list?.({minCalls:r})||[]).map(e=>[e.key,e]));return A(t,{cards:l,minCalls:r,jobKind:s})}function q(o){const n=o?.get?.("agents")?.agents?.value;return(Array.isArray(n)?n:[]).filter(s=>s&&s.id&&s.enabled!==!1)}function z(o,n){const s={};for(const r of n){const i=o?.chains?.get?.(r.id);i?.length&&(s[r.id]=v(i))}return s}async function G(o,{cfg:n,prefsStore:s,scorecards:r,engines:i,reach:p="any",chatModel:d=null,now:u=Date.now(),engineAt:t=null}={}){const l=q(s),e=await R(n,i,{engineAt:t}),f=z(r,l),c=O.has(p)?p:"any",y=k(o,l,{summaries:f,rows:e,reach:c,chatModel:d,now:u});return{applications:y,prompt:M(o,y,l,{rows:e}),rows:e.map(a=>({key:a.key,label:a.label,reach:a.reach,quality:a.quality,costPer1k:a.costPer1k,latencyMs:a.latencyMs,available:a.available,observed:a.observed})),poolSize:l.length}}async function J(o,{cfg:n,prefsStore:s,scorecards:r,engines:i,record:p=null,reach:d="any",chatModel:u=null,evaluation:t=null,text:l=null,by:e="evaluator",minFit:f=E,now:c=Date.now(),engineAt:y=null}={}){const{applications:a,prompt:w}=await G(o,{cfg:n,prefsStore:s,scorecards:r,engines:i,reach:d,chatModel:u,now:c,engineAt:y});let m=null;l!=null?m=b(String(l),a):t&&typeof t=="object"&&(m=b(JSON.stringify({pick:t.pick,why:t.why,confidence:t.confidence,proposalName:t.proposal?.name,proposalPurpose:t.proposal?.purpose,proposalSkills:t.proposal?.skills,proposalGrants:t.proposal?.grants}),a));const g=P(o,a,{evaluation:m,minFit:f}),h=S(o,a,g,{by:g.by==="evaluator"?e:"fit",at:c,record:p});return{applications:a,evaluation:m,decision:g,events:h,prompt:w}}export{G as applicationsFor,q as poolFrom,J as recruitPass,R as rosterRows,z as summariesFrom};
|
package/src/redact.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createVault as
|
|
1
|
+
import{createVault as v,redactText as T,detectEntities as w,gatedDictionary as z,sanitizeUnicode as A,strictnessOf as b}from"@chatpanel/pii";import{ENTITIES_SCHEMA as h,entitiesFormat as N}from"./extraction.js";import{describeSchema as j,coerce as D}from"./structured.js";import*as F from"./ner-engine.js";async function U(r,o,{signal:g,isPro:x=!0,onEgress:M=null,fetchImpl:k=null,sanitizeOnly:E=!1,nerEngine:c=F}={}){const i=v();let f=0;for(const t of r){const e=t.get();if(typeof e!="string"||!e)continue;const{clean:n,removed:y}=A(e);y&&(t.set(n),f+=y)}const m=r.map(t=>t.get()).filter(t=>typeof t=="string"&&t);if(m.length===0)return{vault:i,count:0,sanitized:f};if(E)return{vault:i,count:0,sanitized:f};const a=o.tier==="full"?"full":"basic",I=z(o,x),s=o.detection,l=!!(s&&s.backend&&s.backend!=="off");a==="full"&&!l&&typeof c.ensure=="function"&&await c.ensure();const u=!l&&c.isReady();let p=[];if(a==="full"&&(l||u)){const t=u?{backend:"endpoint",url:"inproc:ner",transport:"in-process",timeoutMs:3e4,maxChars:8e3,types:s?.types,strictness:b(o)}:{...s,timeoutMs:Math.max(Number(s.timeoutMs)||0,3e4),strictness:b(o)},e=u?c.fetchAdapter:k||void 0;try{p=await w(m.join(`
|
|
2
2
|
|
|
3
|
-
`),{detection:t},{signal:g,fetchImpl:e,onEgress:
|
|
3
|
+
`),{detection:t},{signal:g,fetchImpl:e,onEgress:u?null:M,structured:{block:j(h),format:n=>N(n),parse:n=>D(n,h)?.value??null}})}catch{p=[]}}const S={tier:a,entities:p,dictionary:I};let d=0;for(const t of r){const e=t.get();if(typeof e!="string"||!e)continue;const n=T(e,i,S);n!==e&&d++,t.set(n)}return{vault:i,count:d,sanitized:f}}function V(r,o){return{get:r,set:o}}export{U as redactSegments,V as segment};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SEARCH_ENGINES as i}from"../web-search.js";import{apiEnginesFrom as n,patchApiEntries as s,viewApiEntries as a}from"../search-api.js";function c(r){return[...i.filter(t=>t.kind!=="gateway"),...n(r?.search?.apis)]}function E(r=[],t=[]){try{return s(r,t)}catch(e){throw Object.assign(new Error(e.message),{status:400})}}function h(r){return a(r?.search?.apis)}export{E as patchApis,c as searchEngines,h as viewApis};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{secureFetch as
|
|
1
|
+
import{secureFetch as A}from"../secure-fetch.js";import{SEARCH_ENGINES as g,buildSearchUrl as k,pickResults as b}from"../web-search.js";import{extractAnchors as E}from"../serp-anchors.js";import{createEnginePacer as S,searchPolitely as w,retryAfterMs as p}from"../engine-pacer.js";import{buildApiRequest as R,readApiResponse as x}from"../search-api.js";import{VERSION as _}from"../version.js";const j="serp",m=Object.freeze({allowLoopback:!1,allowPrivate:!1}),M=3e6,f=5e3,d=e=>e?AbortSignal.any([e,AbortSignal.timeout(f)]):AbortSignal.timeout(f),P=Object.freeze({Accept:"text/html,application/xhtml+xml","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36","Accept-Language":"en-US,en;q=0.9"});async function I(e,a,{fetchFn:n,signal:i,perEngine:o}){let r;try{r=k(e.url,a)}catch{return{results:[]}}try{const t=await n(r,{policy:m,headers:P,signal:d(i)});if(!t.ok)return{results:[],status:t.status,retryAfterMs:p(t.headers.get("retry-after"))};const l=t.headers.get("content-type")||"";if(l&&!/html|text|xml/i.test(l))return{results:[],status:t.status};const c=(await t.text()).slice(0,M);return{status:t.status,results:b(E(c),{engineHost:new URL(r).hostname,limit:o,fallback:!0})}}catch(t){return h(t,i)}}function h(e,a){return a?.aborted?{results:[]}:/abort|timeout/i.test(`${e?.name} ${e?.message}`)?{results:[],timedOut:!0}:{results:[],network:!0}}async function L(e,a,{fetchFn:n,signal:i,perEngine:o}){let r;try{r=R(e.api,{q:a.q,site:a.site,limit:o,vars:e.vars||{}})}catch{return{results:[]}}try{const t=await n(r.url,{method:r.method,headers:{"User-Agent":`ChatPanel-Gateway/${_} (https://chatpanel.net)`,...r.headers},body:r.body??void 0,policy:m,maxRedirects:0,signal:d(i)});return t.ok?{status:t.status,results:x(e.api,await t.json(),{limit:o})}:{results:[],status:t.status,retryAfterMs:p(t.headers.get("retry-after"))}}catch(t){return h(t,i)}}const O=S();async function z(e,{fetchFn:a=A,signal:n=void 0,engines:i=g,pacer:o=O}={}){const r=e.site?`site:${e.site} ${e.q}`:e.q,t=e.limit||8,l=(typeof i=="function"?i():i).filter(s=>s.enabled!==!1&&s.kind!=="gateway"),u=await w(l,s=>s.kind==="api"?L(s,e,{fetchFn:a,signal:n,perEngine:t}):I(s,r,{fetchFn:a,signal:n,perEngine:t}),{pacer:o,limit:t,signal:n,query:e.q});return{results:u.results.map((s,y)=>({rank:y+1,url:s.url,title:s.title,snippet:s.snippet||"",engine:s.engine,via:s.via})),engines:u.asked.map(s=>s.id),answers:[],suggestions:[],asked:u.asked,resting:u.resting}}export{f as PER_ENGINE_MS,j as PROVIDER_ID,z as searchSerp};
|
package/src/retrieval/search.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{validateSearchRequest as
|
|
1
|
+
import{validateSearchRequest as N,validateSearchResponse as J,overBudget as V}from"../capability-endpoints.js";import{createReadStats as B}from"./read.js";import{searchSerp as I,PROVIDER_ID as T}from"./search-serp.js";import{searchStatus as Z}from"../search-outcome.js";import{PROVIDER_ID as c}from"./search-searxng.js";const A=Object.freeze({timeoutMs:15e3,readConcurrency:4,readBudgetMs:8e3,aliasRead:5}),z=/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g,h=(a,r,i)=>({status:a,body:{error:{type:r,message:i}}});function G(a){const r=String(a||"").replace(z," ").replace(/\s+/g," ").trim();return{q:r,stripped:r!==String(a||"").trim()}}async function H(a,r,i){const p=new Array(a.length);let w=0;const M=Array.from({length:Math.min(r,a.length)},async()=>{for(;;){const g=w++;if(g>=a.length)return;p[g]=await i(a[g],g)}});return await Promise.all(M),p}function Y({reader:a=null,redact:r=async m=>m,searxng:i=null,defaultProvider:p="auto",fetchFn:w=void 0,engines:M=void 0,pacer:g=void 0,now:d=()=>Date.now(),stats:E={serp:B(),searxng:B()},timeoutMs:_=A.timeoutMs,wakeSearxng:O=null}={}){const m=()=>[T,...i?.url?[c]:[]];async function L(f){if(f.provider)return f.provider;if(p===c||p===T)return p;if(i?.url){const e=await i.health();if(e.state==="ready"||e.state==="unknown")return c}return T}return{providers:m,stats:()=>Object.fromEntries(Object.entries(E).map(([f,e])=>[f,e.stats()])),searxng:i,async search(f){let e;try{e=N(f)}catch(t){return h(400,"invalid_request",t.message)}if(e.provider&&!m().includes(e.provider))return h(404,"provider_not_found",`no search provider ${JSON.stringify(e.provider)} here (have ${m().join(", ")})`);if(e.read&&!a)return h(400,"invalid_request","read: no reader is available here");const S=d();let x=!1;try{const t=await r(e.q),{q:s,stripped:v}=G(t);v&&(x=!0,e.q=s)}catch(t){return h(500,"redaction_failed",t.message)}if(!e.q)return h(400,"unsafe_query","the query was only private values (an email, a card, a key…) and nothing searchable remains");const l=await L(e),D=V(E[l]?.stats(),0,e.budgetMs);if(D)return{status:503,body:{...D,provider:l}};const q=new AbortController,C=setTimeout(()=>q.abort(),Math.min(_,e.budgetMs>0?e.budgetMs:_));let o;try{o=l===c?await i.search(e,{signal:q.signal}):await I(e,{fetchFn:w,signal:q.signal,engines:M,pacer:g})}catch(t){return clearTimeout(C),q.signal.aborted?h(504,"fetch_timeout",`${l} did not answer within the budget`):h(502,"provider_failed",`${l}: ${t.message}`)}clearTimeout(C);let y=l;const P=(t,s)=>t===c?[{id:"searxng",outcome:s?.results?.length?"answered":"empty",found:s?.results?.length||0}]:s?.asked||[],R=[...P(l,o)];let k=o.resting||[];if(!o.results.length&&!e.provider&&m().length>1){const t=l===c?T:c;if(t===c&&typeof O=="function"){const n=d()+Math.min(8e3,e.budgetMs>0?Math.max(0,e.budgetMs-(d()-S)):8e3);try{await Promise.race([O(),new Promise(u=>setTimeout(u,Math.max(0,n-d())))])}catch{}for(;d()<n&&(await i.health({force:!0}).catch(()=>({state:"down"}))).state==="down";)await new Promise(u=>setTimeout(u,400))}const s=new AbortController,v=setTimeout(()=>s.abort(),Math.min(_,e.budgetMs>0?Math.max(1e3,e.budgetMs-(d()-S)):_));try{const n=t===c?await i.search(e,{signal:s.signal}):await I(e,{fetchFn:w,signal:s.signal,engines:M,pacer:g});R.push(...P(t,n)),n?.resting&&(k=n.resting),n?.results?.length&&(o=n,y=t)}catch{R.push({id:t,outcome:"refused",found:0,network:!0})}clearTimeout(v)}const $=Math.round(d()-S);E[y]?.record($,e.q.length);let b=o.results.map(t=>({...t,engine:t.engine||y,via:t.via||(y===c?"searxng":"page")}));if(e.read>0&&b.length){const t=e.budgetMs>0?Math.max(1e3,e.budgetMs-$):A.readBudgetMs,s=b.slice(0,e.read),v=await H(s,A.readConcurrency,async n=>{const u=await a.read({url:n.url,snippet:n.snippet,budgetMs:Math.min(t,A.readBudgetMs)});return u.status===200?u.body:null});b=b.map((n,u)=>u<s.length&&v[u]?{...n,read:v[u]}:n)}const j={results:b,answers:o.answers||[],suggestions:o.suggestions||[],engines:o.engines||[],...o.unresponsive?.length?{unresponsive:o.unresponsive}:{},...x?{redacted:!0,query:e.q}:{},provider:y,ms:Math.round(d()-S),trail:{status:Z({results:b,asked:R,resting:k}),asked:R,resting:k}};try{J(j)}catch(t){return h(500,"bad_shape",t.message)}return{status:200,body:j}}}}function ee(a){return{code:200,status:2e4,data:(a.results||[]).map(r=>({url:r.url,title:r.title,description:r.snippet||"",content:r.read?.markdown||r.read?.text||r.snippet||"",...r.read?.published?{publishedTime:r.read.published}:{},...r.engine?{engine:r.engine}:{},...r.via?{via:r.via}:{}})),...a.trail?{trail:a.trail}:{}}}export{A as SEARCH_DEFAULTS,Y as createSearcher,G as queryWithoutTokens,ee as toJinaSearch};
|
package/src/router.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{secureFetch as
|
|
1
|
+
import{secureFetch as T}from"./secure-fetch.js";import{readBridgeToken as O,resolveBridgeUrl as x}from"./bridge.js";import{reachOfGatewayModel as B,agentModelReach as K}from"@chatpanel/events/model-candidates.js";import{localModelCard as N,reachByCard as D}from"@chatpanel/events/local-engine.js";import{loopbackRoot as k}from"./local-engine-probe.js";const E=["codex","claude","opencode","pi","kiro","antigravity"];function w(e){const a=(Array.isArray(e.destinations)?e.destinations:[]).filter(Boolean),i=new Set(a.map(t=>t.id)),l=[...a.filter(t=>t.type==="agent"),...E.filter(t=>!i.has(t)).map(t=>({id:t,type:"agent",agent:t,models:[t]})),...a.filter(t=>t.type!=="agent")];if(e.backend==="api"&&!a.some(t=>t.type==="api")){const t=r=>({...r?.redact===!0?{redact:!0}:{},...r?.local===!0?{local:!0}:{}});l.push({id:"openai",type:"api",protocol:"openai",baseUrl:e.upstreams?.openai?.baseUrl,models:[],...t(e.upstreams?.openai)}),l.push({id:"anthropic",type:"api",protocol:"anthropic",baseUrl:e.upstreams?.anthropic?.baseUrl,models:[],...t(e.upstreams?.anthropic)})}return l}function Y(e,a,i,{destination:l="",down:t=()=>!1}={}){const r=w(a),c=i==="anthropic",s=o=>(c?o.protocol==="anthropic":o.protocol!=="anthropic")&&!t(o);return l?r.find(o=>o.id===l)||null:e&&r.find(o=>Array.isArray(o.models)&&o.models.includes(e))||e&&r.find(o=>o.id===e||o.agent===e)||e&&e.includes("/")&&r.find(o=>o.type==="agent"&&(o.agent===e.slice(0,e.indexOf("/"))||o.id===e.slice(0,e.indexOf("/"))))||e&&F(e,r,s)||r.find(o=>a.backend==="bridge"?o.type==="agent":o.type==="api"&&s(o))||r.find(o=>(a.backend==="bridge"?o.type==="agent":o.type==="api")&&!t(o))||r.find(o=>!t(o))||null}function U(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 L=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;function j(e){if(!e||e.type==="agent")return"";const a=String(e.baseUrl||"");return a?L.test(a)||e.apiKey||e.hasKey?"":`no API key is saved for ${e.id}`:"no endpoint URL is set for this provider"}function _(e,a,i,l){const t=B({id:e,owned_by:a,provider_type:i.type==="agent"?"agent":"openai"},i);if(i.type==="agent")return{reach:t};const r=!!k(i.baseUrl),c=D({dest:i,loopback:r,card:N(l,e),otherwise:t});return{reach:c.reach,...r?{reach_why:c.why,...c.engine?{engine:c.engine}:{}}:{}}}function P(e){const a=[],i=new Set,l=(t,r,c)=>{if(!t||i.has(t))return;i.add(t);const s=U(c),o=j(c);a.push({id:t,object:"model",owned_by:r,...o?{configured:!1,reason:o}:{},provider:c.id,provider_type:c.type==="agent"?"agent":c.protocol==="anthropic"?"anthropic":"openai",api:s.api,endpoints:s.endpoints,..._(t,r,c,null)})};for(const t of w(e))if(t.type==="agent")for(const r of t.models?.length?t.models:[t.id])l(r,"chatpanel-bridge",t);else for(const r of t.models||[])l(r,t.id,t);return{object:"list",data:a}}async function R(e,a,i){const l=await x(e);if(!l||!a)return new Map;const t=O(e.bridge?.token),r=[...a.entries()].filter(([,s])=>s).map(([s])=>s),c=new Map;return await Promise.all(r.map(async s=>{try{const o=await fetch(`${l}/list-models`,{method:"POST",headers:{"content-type":"application/json",...t?{Authorization:`Bearer ${t}`}:{}},body:JSON.stringify({agent:s}),signal:AbortSignal.timeout(i)});if(!o.ok)return;const g=await o.json(),f=(Array.isArray(g?.models)?g.models:[]).map(b=>typeof b=="string"?b:b?.id||b?.name||"").map(b=>String(b).trim()).filter(Boolean);f.length&&c.set(s,f.slice(0,40))}catch{}})),c}async function z(e,a){const i=await x(e);if(!i)return null;try{const l=O(e.bridge?.token),t=await fetch(`${i}/health`,{headers:{Accept:"application/json",...l?{Authorization:`Bearer ${l}`}:{}},signal:AbortSignal.timeout(a)});if(!t.ok)return null;const r=await t.json();if(!Array.isArray(r?.agents))return null;const c=new Map(r.agents.map(s=>[s.id,!!s.available]));return c.noTools=new Set(r.agents.filter(s=>s.tools===!1).map(s=>s.id)),c}catch{return null}}const H=Number(process.env.CHATPANEL_MODELS_CACHE_MS)||6e4;let d={at:0,key:"",value:null,inflight:null};function I(e){try{return JSON.stringify([w(e).map(a=>[a.id,a.type,a.baseUrl,a.models,a.service||"",a.local===!0,a.redact===!0]),e.bridge?.url||""])}catch{return String(Date.now())}}function Z(){d={at:0,key:"",value:null,inflight:null}}function ee(e,a){const i=String(a||"");if(!e||e.type!=="agent"||!i)return!1;const l=i.includes("/")?i.slice(0,i.indexOf("/")):i;return Array.isArray(e.models)&&e.models.includes(i)||e.id===i||e.agent===i||e.id===l||e.agent===l}function F(e,a,i){const l=(d.value?.data||[]).find(t=>t?.id===e&&t.owned_by!=="chatpanel-bridge");return l&&a.find(t=>t.id===l.owned_by&&t.type==="api"&&i(t))||null}async function te(e,a){if(!d.value)try{await G(e,a)}catch{}}async function G(e,{timeoutMs:a=4e3,fresh:i=!1,now:l=Date.now,serviceHealth:t=null,engineAt:r=null}={}){const c=I(e),s=d.value&&d.key===c,o=!s||l()-d.at>H;if(s&&!i&&!o)return d.value;const g=()=>(d.inflight||(d.inflight=J(e,{timeoutMs:a,serviceHealth:t,engineAt:r}).then(f=>(d={at:l(),key:c,value:f,inflight:null},f)).catch(f=>{throw d.inflight=null,f})),d.inflight);return s&&!i?(g().catch(()=>{}),d.value):g()}async function J(e,{timeoutMs:a=4e3,serviceHealth:i=null,engineAt:l=null}={}){const t=P(e),r=new Set(t.data.map(n=>n.id)),c=new Map;if(l){await Promise.all(w(e).filter(p=>p.type==="api"&&!p.service&&p.local!==!0&&p.redact!==!0&&k(p.baseUrl)).map(async p=>{const u=await l(k(p.baseUrl)).catch(()=>null);u&&c.set(p.id,u)}));const n=new Map(w(e).map(p=>[p.id,p]));for(const p of t.data){const u=n.get(p.provider);u&&c.has(u.id)&&Object.assign(p,_(p.id,p.owned_by,u,c.get(u.id)))}}const s=i?await i():null,o=new Map(w(e).filter(n=>n.service).map(n=>[n.id,n.service])),g=n=>{if(o.get(n.owned_by)&&s){const u=s(n.owned_by);u!=="unknown"&&(n.available=u==="up");const y=typeof s.window=="function"?s.window(n.owned_by):null;y&&(n.context_window=y);const h=typeof s.card=="function"?s.card(n.owned_by):null;h&&(n.card=h)}return n};for(const n of t.data)g(n);const f=await z(e,a);if(f){t.data=t.data.filter(n=>n.owned_by!=="chatpanel-bridge"||f.get(n.id)!==!1);for(const n of t.data)n.owned_by==="chatpanel-bridge"&&(n.available=f.get(n.id)??!1,f.noTools?.has(n.id)&&(n.tools=!1))}const b=await R(e,f,a);for(const[n,p]of b){const u=t.data.find(y=>y.id===n);if(u)for(const y of p){const h=`${n}/${y}`;r.has(h)||(r.add(h),t.data.push({...u,id:h,model:y,available:!0,reach:K(y)}))}}const C=w(e).filter(n=>n.type==="api"&&n.baseUrl);return await Promise.all(C.map(async n=>{const p=new AbortController,u=setTimeout(()=>p.abort(),a);try{const y={"content-type":"application/json"};n.apiKey&&(n.protocol==="anthropic"?(y["x-api-key"]=n.apiKey,y["anthropic-version"]="2023-06-01"):y.authorization=`Bearer ${n.apiKey}`);const h=await T(`${n.baseUrl.replace(/\/$/,"")}/models`,{headers:y,signal:p.signal});if(!h.ok)return;const v=await h.json(),$=Array.isArray(v?.data)?v.data:Array.isArray(v?.models)?v.models:[];for(const A of $){const m=typeof A=="string"?A:A?.id;if(m&&!r.has(m)){r.add(m);const S=U(n),M=j(n);t.data.push(g({id:m,object:"model",owned_by:n.id,provider:n.id,provider_type:n.protocol==="anthropic"?"anthropic":"openai",api:S.api,endpoints:S.endpoints,...M?{configured:!1,reason:M}:{},..._(m,n.id,n,c.get(n.id)||null)}))}}}catch{}finally{clearTimeout(u)}})),t}export{ee as agentOwnsModel,P as aggregateModels,G as aggregateModelsAsync,te as ensureModelCatalog,w as listDestinations,Z as resetModelsCache,Y as resolveDestination};
|
package/src/runtime-models.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",recommended:!0,note:"Half the size of v2 m3, most of the quality, the same 100+ languages; the ship default."},{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",note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; twice the memory."},{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-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",recommended:!0,note:"A third of the size of large, close on most typed decisions; the ship default. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{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",note:"What OpenDecision was built around; 8k context, a little sharper, three times the memory."},{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(r=>r.id===t)||A(t):s(n).some(r=>r.id===t)||M.test(t)}function L(n){return`models--${String(n).replace(/\//g,"--")}`}function R(n,{active:e=null,engineRamMB:t=0,engine:r=null,platform:m=process.platform,installed:c=()=>!1}={}){const i=a=>`${Math.round(a/1024*10)/10} GB`,g=a=>r==="podman"&&m!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((a.ramMB+2048)/2048)*2048)} && podman machine start`:r==="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 ${i(a.ramMB)} of memory while loaded — the container engine has ${i(t)}${g(a)?`; raise it: ${g(a)}`:""}`}:{},...h?{ramNote:`needs about ${i(a.ramMB)} while loaded — the engine has ${i(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,R as modelsFor,w as vllmTaskOf};
|
|
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-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",recommended:!0,note:"Half the size of v2 m3, most of the quality, the same 100+ languages; the ship default."},{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",note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; twice the memory."},{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-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",recommended:!0,note:"A third of the size of large, close on most typed decisions; the ship default. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{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",note:"What OpenDecision was built around; 8k context, a little sharper, three times the memory."},{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-0.6B-4bit",label:"Qwen3 0.6B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:400,ramMB:1200,minRamMB:4096,licence:"Apache-2.0",note:"The smallest: titles and topic lists at almost no cost. Copies examples and skips optional steps — not for real conversations."},{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 vLLM-Metal and MLX."},{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 R(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,R as modelsFor,w as vllmTaskOf};
|
package/src/runtime.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import{promisify as bn}from"node:util";import{execFile as yn}from"node:child_process";import{existsSync as be,mkdirSync as ne,writeFileSync as ye,accessSync as $n,openSync as vn,closeSync as Sn,constants as xn}from"node:fs";import{randomBytes as _n,createHash as An}from"node:crypto";import q from"node:os";import b from"node:path";import{modelsFor as He,isValidModelId as Mn,catalogFor as $e,vllmTaskOf as Y}from"./runtime-models.js";import{pickInferenceEngine as je,pickLlamaEngine as En,pickMlxEngine as Pn,recommendEngine as On,detectAccelerator as Cn,hostShape as Nn}from"./inference-engines.js";import{tuningArgs as te,tuningRows as De,patchTunings as Ln,profilesFor as Xe,resolveTunings as Je,ENGINE_DOCS as Rn}from"./engine-tunings.js";import{IMAGE_RECIPES as Bn}from"./images.js";import{pullRepo as Tn,pullGguf as Gn,repoInstalled as Fn,ggufInstalled as We}from"./model-pull.js";import{spawn as In}from"node:child_process";import{readFileSync as Qe,unlinkSync as Ve}from"node:fs";const Un=bn(yn),re=["podman","docker"],j="hf-cache",D=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],helper:!0,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,l)=>{try{return(await l(`${t}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.search?.searxng?.url||""),configure:(t,l)=>{t.search=t.search||{},t.search.searxng={...t.search.searxng||{},url:l}},unconfigure:(t,l)=>{t.search?.searxng?.url===l&&(t.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],helper:!0,adapter:"tei",model:"BAAI/bge-reranker-base",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. The gateway already reranks in-process by default (a small model, no container); start this to run a multilingual cross-encoder (bge-reranker base by default) in a container instead, behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:t=>[`${b.join(t,j)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.rerank?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.rerank={url:l,adapter:f.adapter,model:f.model,service:f.id}},unconfigure:(t,l)=>{t.capabilities?.rerank?.url===l&&delete t.capabilities.rerank}},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],helper:!0,adapter:"systemone",model:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. The gateway already decides in-process by default with the same algorithm and model; start this to run it in a container instead. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:t=>[`${b.join(t,j)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.decide?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.decide={url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}},unconfigure:(t,l)=>{t.capabilities?.decide?.url===l&&delete t.capabilities.decide}},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:t=>je({...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,j)}:/data`],env:t=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${t.model}`,...t.installed?["HF_HUB_OFFLINE=1"]:[]],args:(t,l)=>["--model",t.model,"--host","0.0.0.0","--port","8000",...Y(t.model)==="embed"?["--task","embed"]:[],...te("vllm",t.tunings,{task:Y(t.model),model:t.model,backend:l?.backend||null})],answers:async(t,l)=>{try{return(await l(`${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(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{const h=`${l}/v1`,M=Y(f.model);ze(t),M==="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"})):M==="embed"?(t.capabilities=t.capabilities||{},t.capabilities.embed={url:h,adapter:"openai",model:f.model,service:"vllm"}):M==="transcription"&&(t.capabilities=t.capabilities||{},t.capabilities.stt={provider:"container",url:h,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:t=>ze(t)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:t=>je(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,l)=>["vllm",["serve",t.model,"--host","127.0.0.1","--port",String(t.port),...te("vllm-metal",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,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:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:t=>En(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,l)=>["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",...te("llama",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="llama"&&h?.id!=="llama"),t.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:t=>Pn(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,l)=>["mlx_lm.server",["--model",t.model,"--host","127.0.0.1","--port",String(t.port),...te("mlx",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="mlx"&&h?.id!=="mlx"),t.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}}]);function ze(t){Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),t.capabilities?.embed?.service==="vllm"&&delete t.capabilities.embed,t.capabilities?.stt?.service==="vllm"&&delete t.capabilities.stt}const A=t=>D.find(l=>l.id===t)||null,Hn=({answers:t,configured:l,configure:f,unconfigure:h,volumes:M,args:p,env:F,caps:ie,command:Se,engineOf:B,alias:E,...v})=>v;function jn(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
|
|
3
|
-
`).filter(
|
|
4
|
-
`).filter(
|
|
5
|
-
`).map(o=>o.split(" ")).filter(o=>o[0]).map(([o,a])=>[o,/running/i.test(a||"")?"running":"stopped"]));for(const o of e)i[o]=s.get(o)||"absent";return i}const O=n=>`http://127.0.0.1:${n.port}`;async function Re(){const n=await S(),e=n.preferred,r=await Ne(e,n),i={},s=await N(e),o=e&&n[e].running?await pe(e,D.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of D){const u=O(a);let c="no-engine";a.kind==="native"?c=ue(a):e&&n[e].running?c=o[a.container]||"absent":e&&(c="engine-stopped");const d=a.model?w(a):null,m=a.engineOf?a.engineOf(s):null,y=a.kind==="native"?(s.ramGB||0)*1024:r;i[a.id]={...Hn(a),engine:a.kind==="native"?"host":e,state:c,url:u,configured:a.configured(t),answering:c==="running"?await a.answers(u,B):!1,...a.helper?{asleep:R.has(a.id),idleMinutes:Ie()/6e4}:{},...m?{engineFor:{backend:m.backend,kind:m.kind,image:m.image||null,...m.runner?{runner:m.runner}:{},why:m.why,...m.for?{for:m.for}:{},...m.speed?{speed:m.speed}:{},...m.notFor?{notFor:m.notFor}:{},...m.warn?{warn:m.warn}:{},...m.install?{install:m.install}:{}}}:{},...a.kind==="native"&&!J(a)?{why:`${a.label} runs on ${a.only?.platform||""} ${a.only?.arch||""} only`}:{},...a.kind==="native"&&I[a.id]?{sandbox:I[a.id]}:{},...k[a.id]?{job:{kind:k[a.id].kind,since:k[a.id].since,detail:k[a.id].detail||null,step:k[a.id].step||null,minutes:k[a.id].minutes||null,progress:k[a.id].progress,lines:k[a.id].lines.slice(-4),done:k[a.id].done,error:k[a.id].error,waiting:!!k[a.id].waiting,cancelled:!!k[a.id].cancelled}}:{},...U(a)?{profiles:Xe(a.id,t.runtime?.services?.[a.id]?.tunings,L(a,d,m,s)),docs:Rn[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:Ze(a,s)}:{},...a.model?{model:d,default:a.model,models:He(a.id,{active:d,engineRamMB:y,engine:a.kind==="native"?"host":e,platform:p,installed:$=>H(a,$)}),machine:{engineRamMB:y}}:{},...U(a)?{tunings:De(a.id,t.runtime?.services?.[a.id]?.tunings,L(a,d,m,s))}:{}}}return i}async function an(){const n=await S(),e=await N(n.preferred);return{platform:p,arch:F,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:On(e)}}function Be(n,{settingsFile:e=null,secret:r=null,pick:i=null,cpus:s=null}={}){const o=Q(n),a=["run","-d","--name",o.container,"--restart","no","-p",`127.0.0.1:${o.port}:${o.containerPort}`];o.helper&&s&&a.push("--cpus",String(s));for(const c of o.volumes?o.volumes(E):[])a.push("-v",c);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const c of o.env?o.env(o):[])a.push("-e",c);o.helper&&s&&a.push("-e",`THREADS=${s}`),r&&a.push("-e",`SEARXNG_SECRET=${r}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${o.port}/`),a.push("--cap-drop","ALL");for(const c of o.caps||[])a.push("--cap-add",c);i?.devices?.length&&a.push(...i.devices),a.push(i?.image||o.image,...o.args?o.args(o,i):[]);const u=An("sha1").update(JSON.stringify(a.filter(c=>!String(c).startsWith("SEARXNG_SECRET=")))).digest("hex").slice(0,12);return a.splice(2,0,"--label",`chatpanel.run=${u}`),{args:a,hash:u}}const he={};async function on(n){if(he[n]==null){const e=await g(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),r=Number.parseInt(e.out,10);he[n]=Number.isFinite(r)&&r>0?r:q.cpus()?.length||2}return Math.max(1,Math.floor(he[n]/2))}async function Te(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};R.delete(e.id),we(e.id);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 c=await S();if(i=c.preferred,!i)return{ok:!1,error:"no container engine — install Podman first",install:ve(p)};if(!c[i].running){const d=await fe(i);if(!d.ok)return d}}else if(!J(e))return{ok:!1,error:`${e.label} runs on ${e.only?.platform||"this platform"} ${e.only?.arch||""} only`};const s=await N(i),o=e.engineOf?e.engineOf(s):null;if(e.kind==="native"&&!await G(e.runner,e.runnerCheck))return{ok:!1,error:`\`${e.runner}\` is not on PATH — install it first (${o?.install?.command||""}), or click Install`,install:o?.install};if(e.model&&/\.gguf$/i.test(w(e))&&!be(w(e)))return{ok:!1,error:`no such file: ${w(e)}`};const a=await tn(e,i,o);if(!a.length)return delete k[e.id],e.kind==="native"?ce(e):ge(e,i);const u=de(e,a[0]==="image"?"pull-image":"pull-model",{detail:a[0]==="image"?o?.image||e.image:w(e)});return u.then=(async()=>{try{if(a.includes("image")){const d=await nn(i,o,e,u);if(!d.ok)throw new Error(d.error)}if(a.includes("model")){const d=await Ce(e,u);if(!d.ok)throw new Error(d.error)}u.kind="starting",u.detail=e.label;const c=e.kind==="native"?await ce(e):await ge(e,i);if(!c.ok)throw new Error(c.error);u.done=!0,u.result=c,v(`[runtime] ${e.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(c){u.done=!0,u.error=u.cancelled?"cancelled":c.message,v(`[runtime] ${e.label}: ${u.error}`)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function sn(n){const e=A(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 P(r,"cancelled"),v(`[runtime] ${e.label}: job cancelled (${r.kind})`),{ok:!0,cancelled:r.kind}}async function ge(n,e){let r=await Le(e,n.container);const i=n.helper?await on(e):null,s=n.engineOf?n.engineOf(await N(e)):null,o=n.id==="searxng"?b.join(E,"searxng-settings.yml"):null,a=Be(n,{settingsFile:o,secret:n.id==="searxng"?"x":null,pick:s,cpus:i});if(r!=="absent"){const d=await g(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!d.ok||d.out!==a.hash)&&(v(`[runtime] ${n.label}: made with older settings — re-creating it`),await g(e,["rm","-f",n.container],{timeout:6e4}),r="absent")}if(r!=="running")if(r==="stopped"){const d=await g(e,["start",n.container],{timeout:6e4});if(!d.ok)return{ok:!1,error:`${e} start: ${d.err||d.out}`}}else{ne(E,{recursive:!0,mode:448});let d=null;n.id==="searxng"&&(ye(o,jn(String(t.search?.searxng?.engines||"").split(",").map($=>$.trim()).filter(Boolean)),{mode:384}),d=_n(32).toString("hex")),n.volumes&&ne(b.join(E,j),{recursive:!0,mode:448});const{args:m}=Be(n,{settingsFile:o,secret:d,pick:s,cpus:i});v(`[runtime] ${e} ${m.filter($=>!$.startsWith("SEARXNG_SECRET")).join(" ")}`);const y=await g(e,m,{timeout:6e5});if(!y.ok)return{ok:!1,error:`${e} run: ${y.err||y.out}`}}const u=O(n);let c=!1;for(let d=0;d<30&&!c;d++)c=await n.answers(u,B),c||await ae(1e3);return n.configure(t,u,Q(n)),h(),{ok:!0,url:u,answering:c,...n.provides.length?{provides:n.provides}:{},...n.model?{model:w(n)}:{}}}async function ln(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(R.delete(e.id),delete ke[e.id],e.kind==="native")return Me(e);const r=await S(),i=r.preferred;if(i&&r[i].running){const s=await g(i,["stop",e.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${i} stop: ${s.err||s.out}`}}return e.unconfigure(t,O(e)),h(),{ok:!0}}async function un(n,e){const r=A(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(!Mn(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 s=await S(),o=s.preferred,a=r.kind==="native"?((await Ae()).ramGB||0)*1024:await Ne(o,s),u=He(n,{active:i,engineRamMB:a,engine:r.kind==="native"?"host":o,platform:p,installed:m=>H(r,m)}).find(m=>m.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 c=O(r);r.configured(t)===c&&r.configure(t,c,Q(r)),h();const d=await Ge(r,o,s);return d.ok?{ok:!0,model:i,restarted:d.restarted,...u?.ramNote?{note:u.ramNote}:{}}:d}async function Ge(n,e,r){if(n.kind==="native"){if(ue(n)!=="running")return{ok:!0,restarted:!1};Me(n);const o=await ce(n);return o.ok?{ok:!0,restarted:!0}:o}if(!e||!r[e].running)return{ok:!0,restarted:!1};const i=await Le(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const s=await g(e,["rm","-f",n.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${e} rm: ${s.err||s.out}`};if(i==="running"){const o=await Te(n.id);return o.ok?{ok:!0,restarted:!0}:o}return{ok:!0,restarted:!1}}async function cn(n,e){const r=A(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!U(r))return{ok:!1,error:`${r.label} takes no profile`};const i=await S(),s=await N(i.preferred),o=r.engineOf?r.engineOf(s):null,a=Xe(r.id,t.runtime?.services?.[n]?.tunings,L(r,w(r),o,s)).find(c=>c.id===e);if(!a)return{ok:!1,error:`no profile ${JSON.stringify(e)} — one of speed, coding, long, xl`};if(!a.fits)return{ok:!1,error:`${a.label}: ${a.why}`};const u=await Fe(n,a.patch);return u.ok?{...u,profile:a.id}:u}async function dn(n){const e=A(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(!J(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 X[e.runner],await G(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const s=e.engineOf(await N(null))?.install;if(!s?.steps?.length)return{ok:!1,error:`no installer for ${e.label} on this platform${s?.url?` — see ${s.url}`:""}`,install:s||null};const o=de(e,"install",{detail:e.runner});return o.then=Pe("install",o,async()=>{const a=async d=>{for(const[m,...y]of d){P(o,`$ ${m} ${y.join(" ")}`);let $=await ee(o,m,y,{timeout:36e5});for(let x=0;!$.ok&&!o.cancelled&&x<6&&o.lines.some(K=>/already locked|Please wait for it to finish/i.test(K));x++)P(o,`another ${m} holds the lock — waiting 20 s (${x+1}/6)`),await ae(2e4),$=await ee(o,m,y,{timeout:36e5});if(!$.ok)return{ok:!1,error:$.error||`${m} exited ${$.code}`}}return{ok:!0}};let u=await a(s.steps);!u.ok&&!o.cancelled&&s.fallback?.length&&(P(o,`${u.error} — trying the other way`),u=await a(s.fallback)),delete X[e.runner];const c=u.ok&&await G(e.runner,e.runnerCheck);o.done=!0,o.cancelled?o.error="cancelled":u.ok?c||(o.error=`${e.runner} still not found after the install — open a new terminal and run \`${s.command}\` by hand`):o.error=`install failed: ${u.error}${o.lines.length?` (${o.lines.slice(-2).join(" | ")})`:""}`,v(`[runtime] install ${e.runner}: ${o.error||"ok"}`)}),{ok:!0,pending:{kind:o.kind,since:o.since,detail:o.detail}}}async function mn(n){const e=A(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,w(e)))return{ok:!0,installed:!0,model:w(e)};const i=de(e,"pull-model",{detail:w(e)});return i.then=(async()=>{const s=await Ce(e,i);i.done=!0,s.ok||(i.error=s.error)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Fe(n,e){const r=A(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!U(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(),s=i.preferred,o=w(r),a=await N(s),u=r.engineOf?r.engineOf(a):null,c=Ln(r.id,t.runtime?.services?.[n]?.tunings,e,L(r,o,u,a));if(c.error)return{ok:!1,error:c.error};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},tunings:c},h();const d=await Ge(r,s,i);return d.ok?{ok:!0,tunings:De(r.id,c,L(r,o,u,a)),restarted:d.restarted}:d}async function fn(){const n=await S(),e=n.preferred,r=e&&n[e].running?await pe(e,D.filter(o=>o.kind!=="native").map(o=>o.container)):{},i={};let s=!1;return await Promise.all(D.map(async o=>{const a=o.kind==="native"?ue(o):e&&n[e].running?r[o.container]||"absent":"no-engine";i[o.id]=a==="running"&&await o.answers(O(o),B)?"up":"down";const u=(o.provides||[]).some(c=>["embedded","none"].includes(t.capabilities?.[c]?.provider));i[o.id]==="up"&&o.configure&&!u&&o.configured(t)!==O(o)&&(o.configure(t,O(o),Q(o)),s=!0)})),s&&h(),i}function pn(n){const e=A(n);if(!e||!U(e))return null;const r=Number(Je(e.id,t.runtime?.services?.[n]?.tunings,L(e,w(e),null,{})).maxModelLen);return Number.isFinite(r)&&r>0?r:null}function hn(n){const e=A(n);if(!e||!U(e))return null;const r=w(e),i=Je(e.id,t.runtime?.services?.[n]?.tunings,L(e,r,null,{})),s=$e(e.id).find(a=>a.id===r)||null,o=e.id==="vllm"?Y(r):"chat";return{engine:e.id,backend:I[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:o,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:o==="chat"&&!!i.vision,tools:!!(o==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:o==="chat"&&!!i.reasoning&&i.reasoning!=="off",...s?{tier:s.tier||null,licence:s.licence||null,languages:s.lang||null,label:s.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}const gn=10,Ie=()=>{const n=Number(t.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:gn)*6e4},kn=oe(),ke={},R=new Set,z={};function we(n){ke[n]=oe()}async function wn(n,{force:e=!1}={}){const r=A(n);return!r||!r.helper?{ok:!0}:(we(r.id),!R.has(r.id)&&!e?{ok:!0,awake:!0}:(z[r.id]||(z[r.id]=(async()=>{const i=await S(),s=i.preferred;if(!s)return{ok:!1,error:"no container engine"};if(!i[s].running){const a=await fe(s);if(!a.ok)return a}const o=await ge(r,s);return o.ok&&(R.delete(r.id),v(`[runtime] ${r.label}: woken for a request`)),o})().finally(()=>{delete z[r.id]})),z[r.id]))}async function Ue(){const n=Ie();if(!n)return[];const e=D.filter(a=>a.helper&&a.configured(t)&&!R.has(a.id)&&!z[a.id]&&!(k[a.id]&&!k[a.id].done)&&oe()-(ke[a.id]??kn)>=n);if(!e.length)return[];const r=await S(),i=r.preferred;if(!i||!r[i].running){for(const a of e)R.add(a.id);return e.map(a=>a.id)}const s=await pe(i,e.map(a=>a.container)),o=[];for(const a of e){if(s[a.container]==="running"){if(!(await g(i,["stop",a.container],{timeout:6e4})).ok)continue;v(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}R.add(a.id),o.push(a.id)}return o}return _e&&_e(()=>{Ue().catch(n=>v(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:we,wake:wn,sweepIdle:Ue,health:fn,contextWindow:pn,modelCard:hn,async status(){const[n,e,r,i,s]=await Promise.all([l().catch(()=>null),S(),Re(),rn(),an()]);return{machine:s,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:fe,startService:Te,stopService:ln,setModel:un,setTunings:Fe,setProfile:cn,pullModel:mn,installRunner:dn,cancelJob:sn,services:Re,catalogFor:$e}}export{D as SERVICES,Ke as containerRow,rt as createRuntime,ve as installDoor,jn as searxngSettings};
|
|
1
|
+
import{promisify as Rn}from"node:util";import{execFile as In}from"node:child_process";import{existsSync as Ee,mkdirSync as ne,writeFileSync as oe,accessSync as Un,openSync as Fn,closeSync as Hn,constants as Dn}from"node:fs";import{randomBytes as jn,createHash as Xn}from"node:crypto";import Q from"node:os";import v from"node:path";import{modelsFor as Ze,isValidModelId as Wn,catalogFor as se,vllmTaskOf as te}from"./runtime-models.js";import{pickInferenceEngine as en,pickLlamaEngine as Jn,pickMlxEngine as zn,pickAppleEngine as Kn,recommendEngine as Qn,detectAccelerator as Vn,hostShape as qn}from"./inference-engines.js";import{tuningArgs as le,tuningRows as nn,patchTunings as Yn,profilesFor as tn,resolveTunings as rn,ENGINE_DOCS as Zn}from"./engine-tunings.js";import{IMAGE_RECIPES as et}from"./images.js";import{pullRepo as nt,pullGguf as tt,repoInstalled as rt,ggufInstalled as an}from"./model-pull.js";import{liveFit as it,kvCacheMB as at,cachedConfigPath as ot,needMB as st}from"./host-memory.js";import{APPLE_HELPER as Pe,APPLE_MODEL_ID as lt,APPLE_MIN_DARWIN as ut,appleHelperDirs as ct,appleInstallDoor as dt,darwinMajor as on}from"./apple-model.js";import{spawn as mt}from"node:child_process";import{readFileSync as sn,unlinkSync as ln}from"node:fs";const ft=Rn(In),ue=["podman","docker"],V="hf-cache",j=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],helper:!0,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,l)=>{try{return(await l(`${t}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.search?.searxng?.url||""),configure:(t,l)=>{t.search=t.search||{},t.search.searxng={...t.search.searxng||{},url:l}},unconfigure:(t,l)=>{t.search?.searxng?.url===l&&(t.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],helper:!0,adapter:"tei",model:"BAAI/bge-reranker-base",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. The gateway already reranks in-process by default (a small model, no container); start this to run a multilingual cross-encoder (bge-reranker base by default) in a container instead, behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.rerank?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.rerank={url:l,adapter:f.adapter,model:f.model,service:f.id}},unconfigure:(t,l)=>{t.capabilities?.rerank?.url===l&&delete t.capabilities.rerank}},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],helper:!0,adapter:"systemone",model:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. The gateway already decides in-process by default with the same algorithm and model; start this to run it in a container instead. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.decide?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.decide={url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}},unconfigure:(t,l)=>{t.capabilities?.decide?.url===l&&delete t.capabilities.decide}},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:t=>en({...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=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${t.model}`,...t.installed?["HF_HUB_OFFLINE=1"]:[]],args:(t,l)=>["--model",t.model,"--host","0.0.0.0","--port","8000",...te(t.model)==="embed"?["--task","embed"]:[],...le("vllm",t.tunings,{task:te(t.model),model:t.model,backend:l?.backend||null})],answers:async(t,l)=>{try{return(await l(`${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(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{const h=`${l}/v1`,P=te(f.model);un(t),P==="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"})):P==="embed"?(t.capabilities=t.capabilities||{},t.capabilities.embed={url:h,adapter:"openai",model:f.model,service:"vllm"}):P==="transcription"&&(t.capabilities=t.capabilities||{},t.capabilities.stt={provider:"container",url:h,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:t=>un(t)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:t=>en(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,l)=>["vllm",["serve",t.model,"--host","127.0.0.1","--port",String(t.port),...le("vllm-metal",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,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:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:t=>Jn(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,l)=>["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",...le("llama",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="llama"&&h?.id!=="llama"),t.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:t=>zn(t),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-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,l)=>["mlx_lm.server",["--model",t.model,"--host","127.0.0.1","--port",String(t.port),...le("mlx",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="mlx"&&h?.id!=="mlx"),t.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}},{id:"apple",label:"Apple on-device",kind:"native",auto:!0,runner:Pe,engineOf:t=>Kn(t),only:{platform:"darwin",arch:"arm64",minDarwin:ut,label:"macOS 26 or later on Apple Silicon"},port:8895,provides:["chat"],adapter:"openai",window:4096,card:{engine:"apple",backend:"apple",where:"this machine",egress:"none",cost:"free",task:"chat",window:4096,vision:!1,tools:!1,reasoning:!1,label:"Apple on-device",licence:"Apple",draft:!1},blurb:"Apple’s own model, on this Mac (macOS 26 with Apple Intelligence on): the system loads it when asked and frees it when idle, so nothing stays loaded and nothing runs hot — the lightest choice for titles, topics and short answers. Text only, 4,096 tokens at a time. A small helper on this machine behind the gateway, loopback only.",command:t=>[Pe,["serve","--port",String(t.port)]],answers:async(t,l)=>{try{const f=await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)});return f.ok&&(await f.json())?.ok===!0}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="apple")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l)=>{t.destinations=(t.destinations||[]).filter(f=>f?.service!=="apple"&&f?.id!=="apple"),t.destinations.push({id:"apple",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[lt],service:"apple"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),re=t=>t.only?.label||`${t.only?.platform||"this platform"} ${t.only?.arch||""}`.trim();function un(t){Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),t.capabilities?.embed?.service==="vllm"&&delete t.capabilities.embed,t.capabilities?.stt?.service==="vllm"&&delete t.capabilities.stt}const x=t=>j.find(l=>l.id===t)||null,pt=({answers:t,configured:l,configure:f,unconfigure:h,volumes:P,args:p,env:U,caps:ce,command:de,engineOf:Ne,alias:N,..._})=>_,ht=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),gt=Object.freeze(["brave","qwant"]);function kt(t=[]){const l=t.length?t:ht,f=gt.filter(h=>!l.includes(h));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:",...l.flatMap(h=>[` - name: ${h}`," disabled: false"]),...f.flatMap(h=>[` - name: ${h}`," disabled: true"]),""].join(`
|
|
2
|
+
`)}function Oe(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 cn(t,l){const f=l==="podman"?Array.isArray(t.Names)?t.Names[0]:String(t.Names||""):String(t.Names||t.Name||""),h=l==="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),P=String(t.State||"").toLowerCase()||(/^up/i.test(String(t.Status||""))?"running":"exited");return{name:f,image:String(t.Image||""),state:P,status:String(t.Status||""),ports:h,ours:f.startsWith("chatpanel-"),engine:l}}function Lt({cfg:t,bridgeHealth:l,workers:f=()=>[],persist:h=()=>{},exec:P=(S,F,B={})=>ft(S,F,{timeout:6e4,killSignal:"SIGKILL",...B}),platform:p=process.platform,arch:U=process.arch,osRelease:ce=Q.release(),spawn:de=mt,lookup:Ne=null,fetchImpl:N=globalThis.fetch,stateDir:_=v.join(Q.homedir(),".chatpanel","runtime"),log:E=()=>{},sleep:me=S=>new Promise(F=>setTimeout(F,S)),totalMem:Be=()=>Q.totalmem(),memoryProbe:dn=S=>p==="darwin"&&t?.runtime?.heatwatch!==!1?it(S,{fetchImpl:N}):Promise.resolve(null),now:fe=()=>Date.now(),autoEnv:mn=process.env.CHATPANEL_RUNTIME_AUTO,every:Ce=(S,F)=>{const B=setInterval(S,F);return B.unref?.(),B}}={}){const S=Q.homedir(),F=p==="win32"?[v.join(S,"AppData","Local","Microsoft","WinGet","Links"),v.join(S,".local","bin"),v.join(S,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",v.join(S,".local","bin"),v.join(S,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin",...p==="darwin"?ct({home:S}):[]],B=(n=process.env)=>{const e=p==="win32"?";":":",r=String(n.PATH||n.Path||""),i=F.filter(s=>!r.split(e).includes(s));return{...n,PATH:[...r.split(e).filter(Boolean),...i].join(e)}},k=async(n,e,r={})=>{try{const i=await P(n,e,{...r,env:B(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}}},y=n=>String(t.runtime?.services?.[n.id]?.model||n.model||"");let pe=null;const fn=async()=>(pe===null&&(pe=await Vn({exec:P,platform:p,arch:U})),pe),q={},pn=n=>{const e=p==="win32"?";":":",r=p==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of B().PATH.split(e).filter(Boolean))for(const s of r)try{return Un(v.join(i,n+s),Dn.X_OK),!0}catch{}return!1},C=async(n,e=["--version"])=>(q[n]===void 0&&(q[n]=(Ne||pn)(n)||(await k(n,e,{timeout:8e3})).ok),q[n]);let he=null;const ge=async()=>(he||(he=await qn({exec:P,platform:p,totalmem:Be,cpus:()=>Q.cpus()})),he),T=async n=>({platform:p,arch:U,accelerator:await fn(),engine:n,vllmOnPath:await C("vllm"),llamaOnPath:await C("llama-server"),mlxOnPath:p==="darwin"&&U==="arm64"?await C("mlx_lm.server",["--help"]):!1,osMajor:p==="darwin"?on(ce):0,appleOnPath:p==="darwin"&&U==="arm64"?await C(Pe):!1,appleInstall:p==="darwin"?dt({home:S}):null,...await ge()}),H=n=>!n.only||(!n.only.platform||n.only.platform===p)&&(!n.only.arch||n.only.arch===U)&&(!n.only.minDarwin||on(ce)>=n.only.minDarwin),Y=n=>v.join(_,`${n.id}.pid`),X=n=>{try{const e=Number(sn(Y(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},ke=n=>H(n)?X(n)?"running":"stopped":"unsupported",D={};async function ie(n){const e=Z(n);if(!H(e))return{ok:!1,error:`${e.label} runs on ${re(e)} only`};if(X(e))return e.auto&&!e.configured(t)&&(e.configure(t,A(e),e),h()),{ok:!0,already:!0,url:A(e)};if(e.auto&&await e.answers(A(e),N)){const $=await wn(e.port);if($)return ne(_,{recursive:!0,mode:448}),oe(Y(e),String($),{mode:384}),D[e.id]={layer:"none",reason:"a model engine runs on the hardware, behind the gateway"},e.configure(t,A(e),e),h(),E(`[runtime] ${e.label} was already answering on ${A(e)} (pid ${$}) — adopted`),{ok:!0,adopted:!0,url:A(e),answering:!0,provides:e.provides}}const r=await T(null),i=e.engineOf(r);if(!await C(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)&&!Ee(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[s,o]=e.command(e,G(e,e.model,i,r)),a=v.join(_,V);ne(a,{recursive:!0,mode:448});const c={bin:s,argv:o,opts:{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,HF_HOME:a,LLAMA_CACHE:a,...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"}};D[e.id]=c.record;const u=v.join(_,`${e.id}.log`);let d,m=null;try{try{m=Fn(u,"w",384)}catch{m=null}d=de(c.bin,c.argv,{...c.opts,env:B(c.opts?.env),detached:!0,stdio:["ignore",m??"ignore",m??"ignore"]}),d.unref?.()}catch($){return{ok:!1,error:`${c.bin}: ${$.message}`,install:i.install}}finally{if(m!==null)try{Hn(m)}catch{}}if(!d?.pid)return{ok:!1,error:`${c.bin} did not start`,install:i.install};oe(Y(e),String(d.pid),{mode:384});const w=A(e);let g=!1;for(let $=0;$<120&&!g&&X(e);$++)g=await e.answers(w,N),g||await me(1e3);if(!X(e)){try{ln(Y(e))}catch{}let $="";try{$=sn(u,"utf8").trim().split(`
|
|
3
|
+
`).filter(R=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(R)).slice(-3).map(R=>R.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{$=""}return{ok:!1,error:`${e.label} exited on start${$?` — ${$}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:u}}return e.configure(t,w,e),h(),E(`[runtime] ${e.label} started (pid ${d.pid}) on ${w}, sandbox ${D[e.id].layer}${g?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:w,answering:g,provides:e.provides,model:y(e),sandbox:D[e.id]}}const we=n=>t.runtime?.services?.[n.id]?.off===!0,Le=(n,e)=>{t.runtime=t.runtime||{},t.runtime.services=t.runtime.services||{};const r={...t.runtime.services[n.id]||{}};e?r.off=!0:delete r.off,t.runtime.services[n.id]=r},hn=()=>t.runtime?.auto!==!1&&String(mn||"").toLowerCase()!=="off",W={};async function Te(n){if(!n?.auto)return{ok:!1,skipped:"not a service that starts by itself"};if(!hn())return{ok:!1,skipped:"automatic start is switched off"};if(!H(n))return{ok:!1,skipped:`runs on ${re(n)} only`};if(we(n))return{ok:!1,skipped:"stopped by the person"};if(!await C(n.runner,n.runnerCheck))return{ok:!1,skipped:"its helper is not in this install"};if(!X(n)){const r=await k(n.runner,["check"],{timeout:8e3});if(!r.ok){let i="";try{i=JSON.parse(r.out||"{}").message||""}catch{i=""}return W[n.id]=i||"not available on this Mac right now",{ok:!1,skipped:W[n.id]}}}const e=await ie(n);return e.ok?(delete W[n.id],{ok:!0,...e.already?{already:!0}:e.adopted?{adopted:!0}:{started:!0}}):(W[n.id]=e.error,{ok:!1,skipped:e.error})}async function gn(){const n=[];for(const e of j.filter(r=>r.auto))n.push({id:e.id,label:e.label,...await Te(e).catch(r=>({ok:!1,skipped:r.message}))});return n}async function kn(n){const e=x(n);return e?.auto?Te(e):{ok:!1,skipped:"not a service that starts by itself"}}async function wn(n){if(p==="win32")return 0;const e=await k("lsof",["-nP",`-iTCP:${n}`,"-sTCP:LISTEN","-t"],{timeout:4e3}),r=Number(String(e.out||"").split(`
|
|
4
|
+
`)[0]);return e.ok&&Number.isInteger(r)&&r>1?r:0}function Ge(n){const e=X(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{ln(Y(n))}catch{}return n.unconfigure(t,A(n)),h(),{ok:!0}}const Z=n=>n.model?{...n,model:y(n),installed:K(n,y(n)),tunings:t.runtime?.services?.[n.id]?.tunings||{},...n.id==="llama"?{file:yn(y(n))}:{}}:n,J=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx";function bn(n,e){const r=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},s=se(n.id).filter(c=>!c.minRamMB||r>0&&r>=c.minRamMB);if(!s.length||!r)return null;const o=s.slice().sort((c,u)=>(i[u.tier]??-1)-(i[c.tier]??-1)||c.ramMB-u.ramMB)[0],a=Math.round(o.ramMB/1024*10)/10;return{model:o.id,label:o.label,why:`This machine (${e.ramGB} GB${e.accelerator==="apple"?", Apple Silicon":e.accelerator?`, ${e.accelerator.toUpperCase()} GPU`:", no GPU"}) runs ${o.label} well — about ${a} GB while loaded${o.tier==="max"?"; the strongest in the list":""}.`,profile:"coding",current:y(n)===o.id}}async function Re(n,{model:e,ctx:r,needMB:i}={}){const s=x(n);if(!s||!s.model)return{ok:!1,error:s?`${s.label} takes no model`:`unknown service ${n}`};const o=String(e||y(s)),a=se(n).find(_e=>_e.id===o)||null,c=Number(i)>0?Number(i):a?.ramMB||null;if(!c)return{ok:!1,error:`${o} is not in the catalogue — pass need_mb (its peak memory while serving)`};const u=Number(r)>0?Number(r):Ve(n),d=/\.gguf$/i.test(o)||s.id==="llama"?null:ot(z(),o),m=u&&d?at(d,u):null,w=st({ramMB:c,kvMB:m||0}),g=s.kind==="native"?await dn(w):null,$=((await ge()).ramGB||0)*1024,R=g?g.fits:$>0&&w<=$,I=_e=>`${Math.round(_e/102.4)/10} GB`,Gn=g?g.fits?`${o} fits: needs about ${I(w)}, ${I(g.availableMB)} is free now${g.fitsGPULimit===!1?` — but it is above the GPU wired limit (${I(g.gpuWiredLimitMB)}); raise iogpu.wired_limit_mb`:""}.`:`${o} needs about ${I(w)} and ${I(g.availableMB)} is free now — ${I(g.shortfallMB)} short.${g.close.length?` Close ${g.close.join(", ")} to make room, or pick a smaller model.`:" Pick a smaller model."}`:`${o} needs about ${I(w)} of the machine's ${I($)} — ${R?"fits":"does not fit"} (total memory; install Heatwatch to check what is free now).`;return{ok:!0,service:s.id,model:o,needMB:w,weightsMB:c,kvMB:m,context:u||null,contextCounted:m!==null||!u,source:g?"heatwatch":"total-memory",fits:R,live:g,advice:Gn}}const G=(n,e,r,i={})=>({task:n.id==="vllm"?te(e):"chat",model:e,backend:r?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0}),z=()=>v.join(_,V),K=(n,e)=>/\.gguf$/i.test(e)?Ee(e):n.id==="llama"?!!an(z(),e):rt(z(),e),yn=n=>/\.gguf$/i.test(n)?n:an(z(),n),b={},wt=n=>b[n.id]||null;function be(n,e,r={}){return b[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...r},b[n.id]}function O(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 ae=(n,e,r,{timeout:i=36e5*4}={})=>new Promise(s=>{if(n.cancelled)return s({ok:!1,code:-1,error:"cancelled"});let o;try{o=de(e,r,{stdio:["ignore","pipe","pipe"],env:B()})}catch(d){return s({ok:!1,code:-1,error:d.message})}n.child=o;let a="";const c=d=>{a+=String(d);const m=a.split(/\r?\n|\r/);a=m.pop();for(const w of m)O(n,w)};o.stdout?.on("data",c),o.stderr?.on("data",c);const u=setTimeout(()=>{try{o.kill("SIGTERM")}catch{}},i);u.unref?.(),o.on("error",d=>{clearTimeout(u),n.child=null,s({ok:!1,code:-1,error:d.message})}),o.on("exit",d=>{clearTimeout(u),n.child=null,a&&O(n,a),s({ok:d===0&&!n.cancelled,code:d,...n.cancelled?{error:"cancelled"}:{}})})}),Ie={install:Promise.resolve(),build:Promise.resolve()},ye={install:0,build:0},Ue=(n,e,r)=>{ye[n]>0&&(e.waiting=!0,O(e,`waiting for the other ${n} to finish first — one at a time`)),ye[n]++;const i=Ie[n];let s;const o=new Promise(a=>{s=a});return Ie[n]=i.then(()=>o),i.then(async()=>{e.waiting&&(O(e,"the other one finished — going"),e.waiting=!1);try{return await r()}finally{ye[n]--,s()}})},Fe=async(n,e)=>(await k(n,["image","exists",e],{timeout:2e4})).ok;async function $n(n,e,r,i){const s=e?.image||r.image;if(await Fe(n,s))return{ok:!0};const o=e?.sources?.length?e.sources:[s],a=[];for(const m of o){if(i.kind="pull-image",i.detail=m,O(i,`pulling ${m}`),(await ae(i,n,["pull",m])).ok)return m!==s&&await k(n,["tag",m,s],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const c=e?.recipe?et[e.recipe]:null;if(!c)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const u=v.join(_,"images",e.recipe);return ne(u,{recursive:!0,mode:448}),oe(v.join(u,"Dockerfile"),c.dockerfile,{mode:384}),i.kind="build-image",i.detail=s,i.minutes=c.minutes,O(i,`no registry has ${s} for this machine — building it here (about ${c.minutes} minutes)`),E(`[runtime] building ${s} from the ${e.recipe} recipe in ${u}`),(await Ue("build",i,()=>ae(i,n,["build","-t",s,"-f",v.join(u,"Dockerfile"),u]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function He(n,e){const r=y(n);if(!r||K(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=s=>{if(e.cancelled)throw new Error("cancelled");e.progress={bytes:s.bytes,total:s.total,file:s.file}};try{return n.id==="llama"?await tt(r,{root:z(),fetchImpl:N,onProgress:i}):await nt(r,{root:z(),fetchImpl:N,onProgress:i}),{ok:!0}}catch(s){return{ok:!1,error:`pull ${r}: ${s.message}`}}}async function vn(n,e,r){const i=[];return n.kind!=="native"&&e&&!await Fe(e,r?.image||n.image)&&i.push("image"),n.pull&&n.model&&!K(n,y(n))&&i.push("model"),i}async function De(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&p!=="linux"){const r=await k("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 k("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?Math.round(i/1048576):0}return Math.round(Be()/1048576)}async function M(){const n={};for(const r of ue){const i=await k(r,["--version"],{timeout:5e3});if(!i.ok){n[r]={installed:!1};continue}const s=(i.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||i.out;let o=!1,a=null;if(r==="podman")if(p==="linux")o=(await k("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const c=await k("podman",["machine","list","--format","json"],{timeout:8e3});try{const d=JSON.parse(c.out||"[]")[0]||null;a=d?{name:d.Name,running:!!d.Running}:null,o=!!d?.Running}catch{a=null}}else o=(await k("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[r]={installed:!0,version:s,running:o,...r==="podman"&&p!=="linux"?{machine:a}:{}}}const e=ue.find(r=>n[r]?.installed&&n[r].running)||ue.find(r=>n[r]?.installed)||null;return{...n,preferred:e,...e?{}:{install:Oe(p)}}}async function $e(n="podman"){if(!ue.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await M())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:Oe(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 k("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const r=await k("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 je(){const n=await M(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await k("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(s=>cn(s,"podman"))}catch{return[]}}const r=await k("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return r.ok?r.out.split(`
|
|
5
|
+
`).filter(Boolean).map(i=>{try{return cn(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Xe(n,e){const r=await k(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return r.ok?/running/i.test(r.out)?"running":"stopped":"absent"}async function ve(n,e){const r=await k(n,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!r.ok){for(const o of e)i[o]="absent";return i}const s=new Map(r.out.split(`
|
|
6
|
+
`).map(o=>o.split(" ")).filter(o=>o[0]).map(([o,a])=>[o,/running/i.test(a||"")?"running":"stopped"]));for(const o of e)i[o]=s.get(o)||"absent";return i}const A=n=>`http://127.0.0.1:${n.port}`;async function We(){const n=await M(),e=n.preferred,r=await De(e,n),i={},s=await T(e),o=e&&n[e].running?await ve(e,j.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of j){const c=A(a);let u="no-engine";a.kind==="native"?u=ke(a):e&&n[e].running?u=o[a.container]||"absent":e&&(u="engine-stopped");const d=a.model?y(a):null,m=a.engineOf?a.engineOf(s):null,w=a.kind==="native"?(s.ramGB||0)*1024:r;i[a.id]={...pt(a),engine:a.kind==="native"?"host":e,state:u,url:c,configured:a.configured(t),answering:u==="running"?await a.answers(c,N):!1,...a.helper?{asleep:L.has(a.id),idleMinutes:qe()/6e4}:{},...m?{engineFor:{backend:m.backend,kind:m.kind,image:m.image||null,...m.runner?{runner:m.runner}:{},why:m.why,...m.for?{for:m.for}:{},...m.speed?{speed:m.speed}:{},...m.notFor?{notFor:m.notFor}:{},...m.warn?{warn:m.warn}:{},...m.install?{install:m.install}:{}}}:{},...a.kind==="native"&&!H(a)?{why:`${a.label} runs on ${re(a)} only`}:{},...a.auto&&u!=="running"&&H(a)?{auto:!0,...we(a)?{why:"Stopped here — Start turns it back on"}:W[a.id]?{why:W[a.id]}:{}}:a.auto?{auto:!0}:{},...a.kind==="native"&&D[a.id]?{sandbox:D[a.id]}:{},...b[a.id]?{job:{kind:b[a.id].kind,since:b[a.id].since,detail:b[a.id].detail||null,step:b[a.id].step||null,minutes:b[a.id].minutes||null,progress:b[a.id].progress,lines:b[a.id].lines.slice(-4),done:b[a.id].done,error:b[a.id].error,waiting:!!b[a.id].waiting,cancelled:!!b[a.id].cancelled}}:{},...J(a)?{profiles:tn(a.id,t.runtime?.services?.[a.id]?.tunings,G(a,d,m,s)),docs:Zn[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:bn(a,s)}:{},...a.model?{model:d,default:a.model,models:Ze(a.id,{active:d,engineRamMB:w,engine:a.kind==="native"?"host":e,platform:p,installed:g=>K(a,g)}),machine:{engineRamMB:w}}:{},...J(a)?{tunings:nn(a.id,t.runtime?.services?.[a.id]?.tunings,G(a,d,m,s))}:{}}}return i}async function Sn(){const n=await M(),e=await T(n.preferred);return{platform:p,arch:U,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:Qn(e)}}function Je(n,{settingsFile:e=null,secret:r=null,pick:i=null,cpus:s=null}={}){const o=Z(n),a=["run","-d","--name",o.container,"--restart","no","-p",`127.0.0.1:${o.port}:${o.containerPort}`];o.helper&&s&&a.push("--cpus",String(s));for(const u of o.volumes?o.volumes(_):[])a.push("-v",u);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const u of o.env?o.env(o):[])a.push("-e",u);o.helper&&s&&a.push("-e",`THREADS=${s}`),r&&a.push("-e",`SEARXNG_SECRET=${r}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${o.port}/`),a.push("--cap-drop","ALL");for(const u of o.caps||[])a.push("--cap-add",u);i?.devices?.length&&a.push(...i.devices),a.push(i?.image||o.image,...o.args?o.args(o,i):[]);const c=Xn("sha1").update(JSON.stringify(a.filter(u=>!String(u).startsWith("SEARXNG_SECRET=")))).digest("hex").slice(0,12);return a.splice(2,0,"--label",`chatpanel.run=${c}`),{args:a,hash:c}}const Se={};async function An(n){if(Se[n]==null){const e=await k(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),r=Number.parseInt(e.out,10);Se[n]=Number.isFinite(r)&&r>0?r:Q.cpus()?.length||2}return Math.max(1,Math.floor(Se[n]/2))}async function ze(n,{force:e=!1}={}){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};L.delete(r.id),xe(r.id),r.auto&&we(r)&&Le(r,!1);const i=b[r.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let s=null;if(r.kind!=="native"){const d=await M();if(s=d.preferred,!s)return{ok:!1,error:"no container engine — install Podman first",install:Oe(p)};if(!d[s].running){const m=await $e(s);if(!m.ok)return m}}else if(!H(r))return{ok:!1,error:`${r.label} runs on ${re(r)} only`};const o=await T(s),a=r.engineOf?r.engineOf(o):null;if(r.kind==="native"&&!await C(r.runner,r.runnerCheck))return{ok:!1,error:`\`${r.runner}\` is not on PATH — install it first (${a?.install?.command||""}), or click Install`,install:a?.install};if(r.model&&/\.gguf$/i.test(y(r))&&!Ee(y(r)))return{ok:!1,error:`no such file: ${y(r)}`};if(r.kind==="native"&&r.model&&!e){const d=await Re(r.id);if(d.live&&!d.fits)return{ok:!1,error:d.advice,plan:d}}const c=await vn(r,s,a);if(!c.length)return delete b[r.id],r.kind==="native"?ie(r):Ae(r,s);const u=be(r,c[0]==="image"?"pull-image":"pull-model",{detail:c[0]==="image"?a?.image||r.image:y(r)});return u.then=(async()=>{try{if(c.includes("image")){const m=await $n(s,a,r,u);if(!m.ok)throw new Error(m.error)}if(c.includes("model")){const m=await He(r,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=r.label;const d=r.kind==="native"?await ie(r):await Ae(r,s);if(!d.ok)throw new Error(d.error);u.done=!0,u.result=d,E(`[runtime] ${r.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(d){u.done=!0,u.error=u.cancelled?"cancelled":d.message,E(`[runtime] ${r.label}: ${u.error}`)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function Mn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const r=b[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 O(r,"cancelled"),E(`[runtime] ${e.label}: job cancelled (${r.kind})`),{ok:!0,cancelled:r.kind}}async function Ae(n,e){let r=await Xe(e,n.container);const i=n.helper?await An(e):null,s=n.engineOf?n.engineOf(await T(e)):null,o=n.id==="searxng"?v.join(_,"searxng-settings.yml"):null,a=Je(n,{settingsFile:o,secret:n.id==="searxng"?"x":null,pick:s,cpus:i});if(r!=="absent"){const d=await k(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!d.ok||d.out!==a.hash)&&(E(`[runtime] ${n.label}: made with older settings — re-creating it`),await k(e,["rm","-f",n.container],{timeout:6e4}),r="absent")}if(r!=="running")if(r==="stopped"){const d=await k(e,["start",n.container],{timeout:6e4});if(!d.ok)return{ok:!1,error:`${e} start: ${d.err||d.out}`}}else{ne(_,{recursive:!0,mode:448});let d=null;n.id==="searxng"&&(oe(o,kt(String(t.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),d=jn(32).toString("hex")),n.volumes&&ne(v.join(_,V),{recursive:!0,mode:448});const{args:m}=Je(n,{settingsFile:o,secret:d,pick:s,cpus:i});E(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const w=await k(e,m,{timeout:6e5});if(!w.ok)return{ok:!1,error:`${e} run: ${w.err||w.out}`}}const c=A(n);let u=!1;for(let d=0;d<30&&!u;d++)u=await n.answers(c,N),u||await me(1e3);return n.configure(t,c,Z(n)),h(),{ok:!0,url:c,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:y(n)}:{}}}async function xn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(L.delete(e.id),delete Me[e.id],e.auto&&Le(e,!0),e.kind==="native")return Ge(e);const r=await M(),i=r.preferred;if(i&&r[i].running){const s=await k(i,["stop",e.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${i} stop: ${s.err||s.out}`}}return e.unconfigure(t,A(e)),h(),{ok:!0}}async function _n(n,e){const r=x(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(!Wn(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 s=await M(),o=s.preferred,a=r.kind==="native"?((await ge()).ramGB||0)*1024:await De(o,s),c=Ze(n,{active:i,engineRamMB:a,engine:r.kind==="native"?"host":o,platform:p,installed:m=>K(r,m)}).find(m=>m.id===i);if(c?.unavailable)return{ok:!1,error:`${i} ${c.unavailable}`};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},model:i};const u=A(r);r.configured(t)===u&&r.configure(t,u,Z(r)),h();const d=await Ke(r,o,s);return d.ok?{ok:!0,model:i,restarted:d.restarted,...c?.ramNote?{note:c.ramNote}:{}}:d}async function Ke(n,e,r){if(n.kind==="native"){if(ke(n)!=="running")return{ok:!0,restarted:!1};Ge(n);const o=await ie(n);return o.ok?{ok:!0,restarted:!0}:o}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 s=await k(e,["rm","-f",n.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${e} rm: ${s.err||s.out}`};if(i==="running"){const o=await ze(n.id);return o.ok?{ok:!0,restarted:!0}:o}return{ok:!0,restarted:!1}}async function En(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!J(r))return{ok:!1,error:`${r.label} takes no profile`};const i=await M(),s=await T(i.preferred),o=r.engineOf?r.engineOf(s):null,a=tn(r.id,t.runtime?.services?.[n]?.tunings,G(r,y(r),o,s)).find(u=>u.id===e);if(!a)return{ok:!1,error:`no profile ${JSON.stringify(e)} — one of speed, coding, long, xl`};if(!a.fits)return{ok:!1,error:`${a.label}: ${a.why}`};const c=await Qe(n,a.patch);return c.ok?{...c,profile:a.id}:c}async function Pn(n){const e=x(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(!H(e))return{ok:!1,error:`${e.label} runs on ${re(e)} only`};const r=b[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(delete q[e.runner],await C(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const s=e.engineOf(await T(null))?.install;if(!s?.steps?.length)return{ok:!1,error:`no installer for ${e.label} on this platform${s?.url?` — see ${s.url}`:""}`,install:s||null};const o=be(e,"install",{detail:e.runner});return o.then=Ue("install",o,async()=>{const a=async d=>{for(const[m,...w]of d){O(o,`$ ${m} ${w.join(" ")}`);let g=await ae(o,m,w,{timeout:36e5});for(let $=0;!g.ok&&!o.cancelled&&$<6&&o.lines.some(R=>/already locked|Please wait for it to finish/i.test(R));$++)O(o,`another ${m} holds the lock — waiting 20 s (${$+1}/6)`),await me(2e4),g=await ae(o,m,w,{timeout:36e5});if(!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let c=await a(s.steps);!c.ok&&!o.cancelled&&s.fallback?.length&&(O(o,`${c.error} — trying the other way`),c=await a(s.fallback)),delete q[e.runner];const u=c.ok&&await C(e.runner,e.runnerCheck);o.done=!0,o.cancelled?o.error="cancelled":c.ok?u||(o.error=`${e.runner} still not found after the install — open a new terminal and run \`${s.command}\` by hand`):o.error=`install failed: ${c.error}${o.lines.length?` (${o.lines.slice(-2).join(" | ")})`:""}`,E(`[runtime] install ${e.runner}: ${o.error||"ok"}`)}),{ok:!0,pending:{kind:o.kind,since:o.since,detail:o.detail}}}async function On(n){const e=x(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=b[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(K(e,y(e)))return{ok:!0,installed:!0,model:y(e)};const i=be(e,"pull-model",{detail:y(e)});return i.then=(async()=>{const s=await He(e,i);i.done=!0,s.ok||(i.error=s.error)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Qe(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!J(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 M(),s=i.preferred,o=y(r),a=await T(s),c=r.engineOf?r.engineOf(a):null,u=Yn(r.id,t.runtime?.services?.[n]?.tunings,e,G(r,o,c,a));if(u.error)return{ok:!1,error:u.error};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},tunings:u},h();const d=await Ke(r,s,i);return d.ok?{ok:!0,tunings:nn(r.id,u,G(r,o,c,a)),restarted:d.restarted}:d}async function Nn(){const n=await M(),e=n.preferred,r=e&&n[e].running?await ve(e,j.filter(o=>o.kind!=="native").map(o=>o.container)):{},i={};let s=!1;return await Promise.all(j.map(async o=>{const a=o.kind==="native"?ke(o):e&&n[e].running?r[o.container]||"absent":"no-engine";i[o.id]=a==="running"&&await o.answers(A(o),N)?"up":"down";const c=(o.provides||[]).some(u=>["embedded","none"].includes(t.capabilities?.[u]?.provider));i[o.id]==="up"&&o.configure&&!c&&o.configured(t)!==A(o)&&(o.configure(t,A(o),Z(o)),s=!0)})),s&&h(),i}function Ve(n){const e=x(n);if(e?.window)return e.window;if(!e||!J(e))return null;const r=Number(rn(e.id,t.runtime?.services?.[n]?.tunings,G(e,y(e),null,{})).maxModelLen);return Number.isFinite(r)&&r>0?r:null}function Bn(n){const e=x(n);if(e?.card)return e.card;if(!e||!J(e))return null;const r=y(e),i=rn(e.id,t.runtime?.services?.[n]?.tunings,G(e,r,null,{})),s=se(e.id).find(a=>a.id===r)||null,o=e.id==="vllm"?te(r):"chat";return{engine:e.id,backend:D[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:o,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:o==="chat"&&!!i.vision,tools:!!(o==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:o==="chat"&&!!i.reasoning&&i.reasoning!=="off",...s?{tier:s.tier||null,licence:s.licence||null,languages:s.lang||null,label:s.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}const Cn=10,qe=()=>{const n=Number(t.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:Cn)*6e4},Ln=fe(),Me={},L=new Set,ee={};function xe(n){Me[n]=fe()}async function Tn(n,{force:e=!1}={}){const r=x(n);if(!r||!r.helper)return{ok:!0};if(xe(r.id),!L.has(r.id)&&!e){const i=r.container&&r.configured?.(t)?(await je()).find(s=>s.name===r.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};L.add(r.id)}return ee[r.id]||(ee[r.id]=(async()=>{const i=await M(),s=i.preferred;if(!s)return{ok:!1,error:"no container engine"};if(!i[s].running){const a=await $e(s);if(!a.ok)return a}const o=await Ae(r,s);return o.ok&&(L.delete(r.id),E(`[runtime] ${r.label}: woken for a request`)),o})().finally(()=>{delete ee[r.id]})),ee[r.id]}async function Ye(){const n=qe();if(!n)return[];const e=j.filter(a=>a.helper&&a.configured(t)&&!L.has(a.id)&&!ee[a.id]&&!(b[a.id]&&!b[a.id].done)&&fe()-(Me[a.id]??Ln)>=n);if(!e.length)return[];const r=await M(),i=r.preferred;if(!i||!r[i].running){for(const a of e)L.add(a.id);return e.map(a=>a.id)}const s=await ve(i,e.map(a=>a.container)),o=[];for(const a of e){if(s[a.container]==="running"){if(!(await k(i,["stop",a.container],{timeout:6e4})).ok)continue;E(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}L.add(a.id),o.push(a.id)}return o}return Ce&&Ce(()=>{Ye().catch(n=>E(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:xe,wake:Tn,sweepIdle:Ye,health:Nn,contextWindow:Ve,modelCard:Bn,async status(){const[n,e,r,i,s]=await Promise.all([l().catch(()=>null),M(),We(),je(),Sn()]);return{machine:s,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:$e,startService:ze,stopService:xn,ensureDefaults:gn,revive:kn,plan:Re,setModel:_n,setTunings:Qe,setProfile:En,pullModel:On,installRunner:Pn,cancelJob:Mn,services:We,catalogFor:se}}export{ht as SEARXNG_DEFAULT_ENGINES,j as SERVICES,cn as containerRow,Lt as createRuntime,Oe as installDoor,kt as searxngSettings};
|