@chatpanel/gateway 0.55.0 → 0.57.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runtime.js CHANGED
@@ -1,5 +1,5 @@
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 An,createHash as _n}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 Gn,pullGguf as Tn,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. A multilingual cross-encoder (bge-reranker base by default) 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. 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 _=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 ve(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 Ke(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),M=String(t.State||"").toLowerCase()||(/^up/i.test(String(t.Status||""))?"running":"exited");return{name:f,image:String(t.Image||""),state:M,status:String(t.Status||""),ports:h,ours:f.startsWith("chatpanel-"),engine:l}}function rt({cfg:t,bridgeHealth:l,workers:f=()=>[],persist:h=()=>{},exec:M=(A,G,C={})=>Un(A,G,{timeout:6e4,killSignal:"SIGKILL",...C}),platform:p=process.platform,arch:F=process.arch,spawn:ie=In,lookup:Se=null,fetchImpl:B=globalThis.fetch,stateDir:E=b.join(q.homedir(),".chatpanel","runtime"),log:v=()=>{},sleep:ae=A=>new Promise(G=>setTimeout(G,A)),totalMem:xe=()=>q.totalmem(),now:oe=()=>Date.now(),every:Ae=(A,G)=>{const C=setInterval(A,G);return C.unref?.(),C}}={}){const A=q.homedir(),G=p==="win32"?[b.join(A,"AppData","Local","Microsoft","WinGet","Links"),b.join(A,".local","bin"),b.join(A,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",b.join(A,".local","bin"),b.join(A,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin"],C=(n=process.env)=>{const e=p==="win32"?";":":",r=String(n.PATH||n.Path||""),i=G.filter(s=>!r.split(e).includes(s));return{...n,PATH:[...r.split(e).filter(Boolean),...i].join(e)}},g=async(n,e,r={})=>{try{const i=await M(n,e,{...r,env:C(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}}},w=n=>String(t.runtime?.services?.[n.id]?.model||n.model||"");let se=null;const qe=async()=>(se===null&&(se=await Cn({exec:M,platform:p,arch:F})),se),X={},Ye=n=>{const e=p==="win32"?";":":",r=p==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of C().PATH.split(e).filter(Boolean))for(const s of r)try{return $n(b.join(i,n+s),xn.X_OK),!0}catch{}return!1},T=async(n,e=["--version"])=>(X[n]===void 0&&(X[n]=(Se||Ye)(n)||(await g(n,e,{timeout:8e3})).ok),X[n]);let le=null;const _e=async()=>(le||(le=await Nn({exec:M,platform:p,totalmem:xe,cpus:()=>q.cpus()})),le),N=async n=>({platform:p,arch:F,accelerator:await qe(),engine:n,vllmOnPath:await T("vllm"),llamaOnPath:await T("llama-server"),mlxOnPath:p==="darwin"&&F==="arm64"?await T("mlx_lm.server",["--help"]):!1,...await _e()}),J=n=>!n.only||(!n.only.platform||n.only.platform===p)&&(!n.only.arch||n.only.arch===F),Z=n=>b.join(E,`${n.id}.pid`),W=n=>{try{const e=Number(Qe(Z(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},ue=n=>J(n)?W(n)?"running":"stopped":"unsupported",I={};async function ce(n){const e=Q(n);if(!J(e))return{ok:!1,error:`${e.label} runs on ${e.only?.platform||"this platform"} ${e.only?.arch||""} only`};if(W(e))return{ok:!0,already:!0,url:O(e)};const r=await N(null),i=e.engineOf(r);if(!await T(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)&&!be(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[s,o]=e.command(e,L(e,e.model,i,r)),a=b.join(E,j);ne(a,{recursive:!0,mode:448});const u={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"}};I[e.id]=u.record;const c=b.join(E,`${e.id}.log`);let d,m=null;try{try{m=vn(c,"w",384)}catch{m=null}d=ie(u.bin,u.argv,{...u.opts,env:C(u.opts?.env),detached:!0,stdio:["ignore",m??"ignore",m??"ignore"]}),d.unref?.()}catch(x){return{ok:!1,error:`${u.bin}: ${x.message}`,install:i.install}}finally{if(m!==null)try{Sn(m)}catch{}}if(!d?.pid)return{ok:!1,error:`${u.bin} did not start`,install:i.install};ye(Z(e),String(d.pid),{mode:384});const y=O(e);let $=!1;for(let x=0;x<120&&!$&&W(e);x++)$=await e.answers(y,B),$||await ae(1e3);if(!W(e)){try{Ve(Z(e))}catch{}let x="";try{x=Qe(c,"utf8").trim().split(`
3
- `).filter(K=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(K)).slice(-3).map(K=>K.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{x=""}return{ok:!1,error:`${e.label} exited on start${x?` — ${x}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:c}}return e.configure(t,y,e),h(),v(`[runtime] ${e.label} started (pid ${d.pid}) on ${y}, sandbox ${I[e.id].layer}${$?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:y,answering:$,provides:e.provides,model:w(e),sandbox:I[e.id]}}function Me(n){const e=W(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{Ve(Z(n))}catch{}return n.unconfigure(t,O(n)),h(),{ok:!0}}const Q=n=>n.model?{...n,model:w(n),installed:H(n,w(n)),tunings:t.runtime?.services?.[n.id]?.tunings||{},...n.id==="llama"?{file:en(w(n))}:{}}:n,U=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx";function Ze(n,e){const r=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},s=$e(n.id).filter(u=>!u.minRamMB||r>0&&r>=u.minRamMB);if(!s.length||!r)return null;const o=s.slice().sort((u,c)=>(i[c.tier]??-1)-(i[u.tier]??-1)||u.ramMB-c.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:w(n)===o.id}}const L=(n,e,r,i={})=>({task:n.id==="vllm"?Y(e):"chat",model:e,backend:r?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0}),V=()=>b.join(E,j),H=(n,e)=>/\.gguf$/i.test(e)?be(e):n.id==="llama"?!!We(V(),e):Fn(V(),e),en=n=>/\.gguf$/i.test(n)?n:We(V(),n),k={},Dn=n=>k[n.id]||null;function de(n,e,r={}){return k[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...r},k[n.id]}function P(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 ee=(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=ie(e,r,{stdio:["ignore","pipe","pipe"],env:C()})}catch(d){return s({ok:!1,code:-1,error:d.message})}n.child=o;let a="";const u=d=>{a+=String(d);const m=a.split(/\r?\n|\r/);a=m.pop();for(const y of m)P(n,y)};o.stdout?.on("data",u),o.stderr?.on("data",u);const c=setTimeout(()=>{try{o.kill("SIGTERM")}catch{}},i);c.unref?.(),o.on("error",d=>{clearTimeout(c),n.child=null,s({ok:!1,code:-1,error:d.message})}),o.on("exit",d=>{clearTimeout(c),n.child=null,a&&P(n,a),s({ok:d===0&&!n.cancelled,code:d,...n.cancelled?{error:"cancelled"}:{}})})}),Ee={install:Promise.resolve(),build:Promise.resolve()},me={install:0,build:0},Pe=(n,e,r)=>{me[n]>0&&(e.waiting=!0,P(e,`waiting for the other ${n} to finish first — one at a time`)),me[n]++;const i=Ee[n];let s;const o=new Promise(a=>{s=a});return Ee[n]=i.then(()=>o),i.then(async()=>{e.waiting&&(P(e,"the other one finished — going"),e.waiting=!1);try{return await r()}finally{me[n]--,s()}})},Oe=async(n,e)=>(await g(n,["image","exists",e],{timeout:2e4})).ok;async function nn(n,e,r,i){const s=e?.image||r.image;if(await Oe(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,P(i,`pulling ${m}`),(await ee(i,n,["pull",m])).ok)return m!==s&&await g(n,["tag",m,s],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const u=e?.recipe?Bn[e.recipe]:null;if(!u)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const c=b.join(E,"images",e.recipe);return ne(c,{recursive:!0,mode:448}),ye(b.join(c,"Dockerfile"),u.dockerfile,{mode:384}),i.kind="build-image",i.detail=s,i.minutes=u.minutes,P(i,`no registry has ${s} for this machine — building it here (about ${u.minutes} minutes)`),v(`[runtime] building ${s} from the ${e.recipe} recipe in ${c}`),(await Pe("build",i,()=>ee(i,n,["build","-t",s,"-f",b.join(c,"Dockerfile"),c]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function Ce(n,e){const r=w(n);if(!r||H(n,r))return{ok:!0};if(/\.gguf$/i.test(r))return{ok:!1,error:`no such file: ${r}`};e.kind="pull-model",e.detail=r;const i=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 Tn(r,{root:V(),fetchImpl:B,onProgress:i}):await Gn(r,{root:V(),fetchImpl:B,onProgress:i}),{ok:!0}}catch(s){return{ok:!1,error:`pull ${r}: ${s.message}`}}}async function tn(n,e,r){const i=[];return n.kind!=="native"&&e&&!await Oe(e,r?.image||n.image)&&i.push("image"),n.pull&&n.model&&!H(n,w(n))&&i.push("model"),i}async function Ne(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&p!=="linux"){const r=await g("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 g("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?Math.round(i/1048576):0}return Math.round(xe()/1048576)}async function S(){const n={};for(const r of re){const i=await g(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 g("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const u=await g("podman",["machine","list","--format","json"],{timeout:8e3});try{const d=JSON.parse(u.out||"[]")[0]||null;a=d?{name:d.Name,running:!!d.Running}:null,o=!!d?.Running}catch{a=null}}else o=(await g("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[r]={installed:!0,version:s,running:o,...r==="podman"&&p!=="linux"?{machine:a}:{}}}const e=re.find(r=>n[r]?.installed&&n[r].running)||re.find(r=>n[r]?.installed)||null;return{...n,preferred:e,...e?{}:{install:ve(p)}}}async function fe(n="podman"){if(!re.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await S())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:ve(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 g("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const r=await g("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 rn(){const n=await S(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await g("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(s=>Ke(s,"podman"))}catch{return[]}}const r=await g("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return r.ok?r.out.split(`
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 ve(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 Ke(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),M=String(t.State||"").toLowerCase()||(/^up/i.test(String(t.Status||""))?"running":"exited");return{name:f,image:String(t.Image||""),state:M,status:String(t.Status||""),ports:h,ours:f.startsWith("chatpanel-"),engine:l}}function rt({cfg:t,bridgeHealth:l,workers:f=()=>[],persist:h=()=>{},exec:M=(_,T,C={})=>Un(_,T,{timeout:6e4,killSignal:"SIGKILL",...C}),platform:p=process.platform,arch:F=process.arch,spawn:ie=In,lookup:Se=null,fetchImpl:B=globalThis.fetch,stateDir:E=b.join(q.homedir(),".chatpanel","runtime"),log:v=()=>{},sleep:ae=_=>new Promise(T=>setTimeout(T,_)),totalMem:xe=()=>q.totalmem(),now:oe=()=>Date.now(),every:_e=(_,T)=>{const C=setInterval(_,T);return C.unref?.(),C}}={}){const _=q.homedir(),T=p==="win32"?[b.join(_,"AppData","Local","Microsoft","WinGet","Links"),b.join(_,".local","bin"),b.join(_,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",b.join(_,".local","bin"),b.join(_,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin"],C=(n=process.env)=>{const e=p==="win32"?";":":",r=String(n.PATH||n.Path||""),i=T.filter(s=>!r.split(e).includes(s));return{...n,PATH:[...r.split(e).filter(Boolean),...i].join(e)}},g=async(n,e,r={})=>{try{const i=await M(n,e,{...r,env:C(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}}},w=n=>String(t.runtime?.services?.[n.id]?.model||n.model||"");let se=null;const qe=async()=>(se===null&&(se=await Cn({exec:M,platform:p,arch:F})),se),X={},Ye=n=>{const e=p==="win32"?";":":",r=p==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of C().PATH.split(e).filter(Boolean))for(const s of r)try{return $n(b.join(i,n+s),xn.X_OK),!0}catch{}return!1},G=async(n,e=["--version"])=>(X[n]===void 0&&(X[n]=(Se||Ye)(n)||(await g(n,e,{timeout:8e3})).ok),X[n]);let le=null;const Ae=async()=>(le||(le=await Nn({exec:M,platform:p,totalmem:xe,cpus:()=>q.cpus()})),le),N=async n=>({platform:p,arch:F,accelerator:await qe(),engine:n,vllmOnPath:await G("vllm"),llamaOnPath:await G("llama-server"),mlxOnPath:p==="darwin"&&F==="arm64"?await G("mlx_lm.server",["--help"]):!1,...await Ae()}),J=n=>!n.only||(!n.only.platform||n.only.platform===p)&&(!n.only.arch||n.only.arch===F),Z=n=>b.join(E,`${n.id}.pid`),W=n=>{try{const e=Number(Qe(Z(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},ue=n=>J(n)?W(n)?"running":"stopped":"unsupported",I={};async function ce(n){const e=Q(n);if(!J(e))return{ok:!1,error:`${e.label} runs on ${e.only?.platform||"this platform"} ${e.only?.arch||""} only`};if(W(e))return{ok:!0,already:!0,url:O(e)};const r=await N(null),i=e.engineOf(r);if(!await G(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)&&!be(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[s,o]=e.command(e,L(e,e.model,i,r)),a=b.join(E,j);ne(a,{recursive:!0,mode:448});const u={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"}};I[e.id]=u.record;const c=b.join(E,`${e.id}.log`);let d,m=null;try{try{m=vn(c,"w",384)}catch{m=null}d=ie(u.bin,u.argv,{...u.opts,env:C(u.opts?.env),detached:!0,stdio:["ignore",m??"ignore",m??"ignore"]}),d.unref?.()}catch(x){return{ok:!1,error:`${u.bin}: ${x.message}`,install:i.install}}finally{if(m!==null)try{Sn(m)}catch{}}if(!d?.pid)return{ok:!1,error:`${u.bin} did not start`,install:i.install};ye(Z(e),String(d.pid),{mode:384});const y=O(e);let $=!1;for(let x=0;x<120&&!$&&W(e);x++)$=await e.answers(y,B),$||await ae(1e3);if(!W(e)){try{Ve(Z(e))}catch{}let x="";try{x=Qe(c,"utf8").trim().split(`
3
+ `).filter(K=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(K)).slice(-3).map(K=>K.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{x=""}return{ok:!1,error:`${e.label} exited on start${x?` — ${x}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:c}}return e.configure(t,y,e),h(),v(`[runtime] ${e.label} started (pid ${d.pid}) on ${y}, sandbox ${I[e.id].layer}${$?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:y,answering:$,provides:e.provides,model:w(e),sandbox:I[e.id]}}function Me(n){const e=W(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{Ve(Z(n))}catch{}return n.unconfigure(t,O(n)),h(),{ok:!0}}const Q=n=>n.model?{...n,model:w(n),installed:H(n,w(n)),tunings:t.runtime?.services?.[n.id]?.tunings||{},...n.id==="llama"?{file:en(w(n))}:{}}:n,U=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx";function Ze(n,e){const r=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},s=$e(n.id).filter(u=>!u.minRamMB||r>0&&r>=u.minRamMB);if(!s.length||!r)return null;const o=s.slice().sort((u,c)=>(i[c.tier]??-1)-(i[u.tier]??-1)||u.ramMB-c.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:w(n)===o.id}}const L=(n,e,r,i={})=>({task:n.id==="vllm"?Y(e):"chat",model:e,backend:r?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0}),V=()=>b.join(E,j),H=(n,e)=>/\.gguf$/i.test(e)?be(e):n.id==="llama"?!!We(V(),e):Fn(V(),e),en=n=>/\.gguf$/i.test(n)?n:We(V(),n),k={},Dn=n=>k[n.id]||null;function de(n,e,r={}){return k[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...r},k[n.id]}function P(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 ee=(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=ie(e,r,{stdio:["ignore","pipe","pipe"],env:C()})}catch(d){return s({ok:!1,code:-1,error:d.message})}n.child=o;let a="";const u=d=>{a+=String(d);const m=a.split(/\r?\n|\r/);a=m.pop();for(const y of m)P(n,y)};o.stdout?.on("data",u),o.stderr?.on("data",u);const c=setTimeout(()=>{try{o.kill("SIGTERM")}catch{}},i);c.unref?.(),o.on("error",d=>{clearTimeout(c),n.child=null,s({ok:!1,code:-1,error:d.message})}),o.on("exit",d=>{clearTimeout(c),n.child=null,a&&P(n,a),s({ok:d===0&&!n.cancelled,code:d,...n.cancelled?{error:"cancelled"}:{}})})}),Ee={install:Promise.resolve(),build:Promise.resolve()},me={install:0,build:0},Pe=(n,e,r)=>{me[n]>0&&(e.waiting=!0,P(e,`waiting for the other ${n} to finish first — one at a time`)),me[n]++;const i=Ee[n];let s;const o=new Promise(a=>{s=a});return Ee[n]=i.then(()=>o),i.then(async()=>{e.waiting&&(P(e,"the other one finished — going"),e.waiting=!1);try{return await r()}finally{me[n]--,s()}})},Oe=async(n,e)=>(await g(n,["image","exists",e],{timeout:2e4})).ok;async function nn(n,e,r,i){const s=e?.image||r.image;if(await Oe(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,P(i,`pulling ${m}`),(await ee(i,n,["pull",m])).ok)return m!==s&&await g(n,["tag",m,s],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const u=e?.recipe?Bn[e.recipe]:null;if(!u)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const c=b.join(E,"images",e.recipe);return ne(c,{recursive:!0,mode:448}),ye(b.join(c,"Dockerfile"),u.dockerfile,{mode:384}),i.kind="build-image",i.detail=s,i.minutes=u.minutes,P(i,`no registry has ${s} for this machine — building it here (about ${u.minutes} minutes)`),v(`[runtime] building ${s} from the ${e.recipe} recipe in ${c}`),(await Pe("build",i,()=>ee(i,n,["build","-t",s,"-f",b.join(c,"Dockerfile"),c]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function Ce(n,e){const r=w(n);if(!r||H(n,r))return{ok:!0};if(/\.gguf$/i.test(r))return{ok:!1,error:`no such file: ${r}`};e.kind="pull-model",e.detail=r;const i=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 Gn(r,{root:V(),fetchImpl:B,onProgress:i}):await Tn(r,{root:V(),fetchImpl:B,onProgress:i}),{ok:!0}}catch(s){return{ok:!1,error:`pull ${r}: ${s.message}`}}}async function tn(n,e,r){const i=[];return n.kind!=="native"&&e&&!await Oe(e,r?.image||n.image)&&i.push("image"),n.pull&&n.model&&!H(n,w(n))&&i.push("model"),i}async function Ne(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&p!=="linux"){const r=await g("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 g("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?Math.round(i/1048576):0}return Math.round(xe()/1048576)}async function S(){const n={};for(const r of re){const i=await g(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 g("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const u=await g("podman",["machine","list","--format","json"],{timeout:8e3});try{const d=JSON.parse(u.out||"[]")[0]||null;a=d?{name:d.Name,running:!!d.Running}:null,o=!!d?.Running}catch{a=null}}else o=(await g("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[r]={installed:!0,version:s,running:o,...r==="podman"&&p!=="linux"?{machine:a}:{}}}const e=re.find(r=>n[r]?.installed&&n[r].running)||re.find(r=>n[r]?.installed)||null;return{...n,preferred:e,...e?{}:{install:ve(p)}}}async function fe(n="podman"){if(!re.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await S())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:ve(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 g("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const r=await g("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 rn(){const n=await S(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await g("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(s=>Ke(s,"podman"))}catch{return[]}}const r=await g("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return r.ok?r.out.split(`
4
4
  `).filter(Boolean).map(i=>{try{return Ke(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Le(n,e){const r=await g(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return r.ok?/running/i.test(r.out)?"running":"stopped":"absent"}async function pe(n,e){const r=await g(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(`
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=_n("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 Ge(n){const e=_(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 T(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=_(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=An(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=_(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=_(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 _e()).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 Te(r,o,s);return d.ok?{ok:!0,model:i,restarted:d.restarted,...u?.ramNote?{note:u.ramNote}:{}}:d}async function Te(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 Ge(n.id);return o.ok?{ok:!0,restarted:!0}:o}return{ok:!0,restarted:!1}}async function cn(n,e){const r=_(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=_(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 T(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 T(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=_(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=_(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 Te(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",i[o.id]==="up"&&o.configure&&o.configured(t)!==O(o)&&(o.configure(t,O(o),Q(o)),s=!0)})),s&&h(),i}function pn(n){const e=_(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=_(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=_(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 Ae&&Ae(()=>{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:Ge,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};
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};