@chatpanel/gateway 0.64.0 → 0.75.0
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/native/darwin-arm64/chatpanel-apple-model +0 -0
- package/package.json +5 -4
- package/src/apple-model.js +1 -0
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- 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/runtime-models.js +1 -1
- package/src/runtime.js +5 -5
- package/src/server.js +27 -23
- package/src/service.js +17 -16
- package/src/version.js +1 -1
- package/src/ws-accept.js +7 -0
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 _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(Boolean).map(i=>{try{return
|
|
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 Pn}from"node:util";import{execFile as En}from"node:child_process";import{existsSync as Ae,mkdirSync as te,writeFileSync as xe,accessSync as On,openSync as Bn,closeSync as Nn,constants as Ln}from"node:fs";import{randomBytes as Cn,createHash as Rn}from"node:crypto";import W from"node:os";import $ from"node:path";import{modelsFor as Ve,isValidModelId as Gn,catalogFor as re,vllmTaskOf as Z}from"./runtime-models.js";import{pickInferenceEngine as ze,pickLlamaEngine as Tn,pickMlxEngine as In,pickAppleEngine as Fn,recommendEngine as Un,detectAccelerator as Hn,hostShape as jn}from"./inference-engines.js";import{tuningArgs as ie,tuningRows as Ke,patchTunings as Dn,profilesFor as qe,resolveTunings as Ye,ENGINE_DOCS as Xn}from"./engine-tunings.js";import{IMAGE_RECIPES as Wn}from"./images.js";import{pullRepo as Jn,pullGguf as Qn,repoInstalled as Vn,ggufInstalled as Ze}from"./model-pull.js";import{liveFit as zn,kvCacheMB as Kn,cachedConfigPath as qn,needMB as Yn}from"./host-memory.js";import{APPLE_HELPER as _e,APPLE_MODEL_ID as Zn,APPLE_MIN_DARWIN as et,appleHelperDirs as nt,appleInstallDoor as tt,darwinMajor as en}from"./apple-model.js";import{spawn as rt}from"node:child_process";import{readFileSync as nn,unlinkSync as tn}from"node:fs";const it=Pn(En),ae=["podman","docker"],J="hf-cache",Q=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=>[`${$.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=>[`${$.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=>ze({...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=>[`${$.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",...Z(t.model)==="embed"?["--task","embed"]:[],...ie("vllm",t.tunings,{task:Z(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 k=`${l}/v1`,P=Z(f.model);rn(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:k,models:[f.model],service:"vllm"})):P==="embed"?(t.capabilities=t.capabilities||{},t.capabilities.embed={url:k,adapter:"openai",model:f.model,service:"vllm"}):P==="transcription"&&(t.capabilities=t.capabilities||{},t.capabilities.stt={provider:"container",url:k,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:t=>rn(t)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:t=>ze(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),...ie("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(k=>k?.service!=="vllm-metal"&&k?.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=>Tn(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",...ie("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(k=>k?.service!=="llama"&&k?.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=>In(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),...ie("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(k=>k?.service!=="mlx"&&k?.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",runner:_e,engineOf:t=>Fn(t),only:{platform:"darwin",arch:"arm64",minDarwin:et,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=>[_e,["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:[Zn],service:"apple"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),oe=t=>t.only?.label||`${t.only?.platform||"this platform"} ${t.only?.arch||""}`.trim();function rn(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=>Q.find(l=>l.id===t)||null,at=({answers:t,configured:l,configure:f,unconfigure:k,volumes:P,args:p,env:F,caps:se,command:le,engineOf:Ee,alias:N,...x})=>x;function ot(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 Pe(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 an(t,l){const f=l==="podman"?Array.isArray(t.Names)?t.Names[0]:String(t.Names||""):String(t.Names||t.Name||""),k=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:k,ours:f.startsWith("chatpanel-"),engine:l}}function St({cfg:t,bridgeHealth:l,workers:f=()=>[],persist:k=()=>{},exec:P=(S,U,B={})=>it(S,U,{timeout:6e4,killSignal:"SIGKILL",...B}),platform:p=process.platform,arch:F=process.arch,osRelease:se=W.release(),spawn:le=rt,lookup:Ee=null,fetchImpl:N=globalThis.fetch,stateDir:x=$.join(W.homedir(),".chatpanel","runtime"),log:_=()=>{},sleep:ue=S=>new Promise(U=>setTimeout(U,S)),totalMem:Oe=()=>W.totalmem(),memoryProbe:on=S=>p==="darwin"&&t?.runtime?.heatwatch!==!1?zn(S,{fetchImpl:N}):Promise.resolve(null),now:ce=()=>Date.now(),every:Be=(S,U)=>{const B=setInterval(S,U);return B.unref?.(),B}}={}){const S=W.homedir(),U=p==="win32"?[$.join(S,"AppData","Local","Microsoft","WinGet","Links"),$.join(S,".local","bin"),$.join(S,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",$.join(S,".local","bin"),$.join(S,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin",...p==="darwin"?nt({home:S}):[]],B=(e=process.env)=>{const n=p==="win32"?";":":",r=String(e.PATH||e.Path||""),i=U.filter(s=>!r.split(n).includes(s));return{...e,PATH:[...r.split(n).filter(Boolean),...i].join(n)}},w=async(e,n,r={})=>{try{const i=await P(e,n,{...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=e=>String(t.runtime?.services?.[e.id]?.model||e.model||"");let de=null;const sn=async()=>(de===null&&(de=await Hn({exec:P,platform:p,arch:F})),de),V={},ln=e=>{const n=p==="win32"?";":":",r=p==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of B().PATH.split(n).filter(Boolean))for(const s of r)try{return On($.join(i,e+s),Ln.X_OK),!0}catch{}return!1},L=async(e,n=["--version"])=>(V[e]===void 0&&(V[e]=(Ee||ln)(e)||(await w(e,n,{timeout:8e3})).ok),V[e]);let me=null;const fe=async()=>(me||(me=await jn({exec:P,platform:p,totalmem:Oe,cpus:()=>W.cpus()})),me),C=async e=>({platform:p,arch:F,accelerator:await sn(),engine:e,vllmOnPath:await L("vllm"),llamaOnPath:await L("llama-server"),mlxOnPath:p==="darwin"&&F==="arm64"?await L("mlx_lm.server",["--help"]):!1,osMajor:p==="darwin"?en(se):0,appleOnPath:p==="darwin"&&F==="arm64"?await L(_e):!1,appleInstall:p==="darwin"?tt({home:S}):null,...await fe()}),z=e=>!e.only||(!e.only.platform||e.only.platform===p)&&(!e.only.arch||e.only.arch===F)&&(!e.only.minDarwin||en(se)>=e.only.minDarwin),ee=e=>$.join(x,`${e.id}.pid`),K=e=>{try{const n=Number(nn(ee(e),"utf8"));if(n>0)return process.kill(n,0),n}catch{}return null},pe=e=>z(e)?K(e)?"running":"stopped":"unsupported",H={};async function he(e){const n=q(e);if(!z(n))return{ok:!1,error:`${n.label} runs on ${oe(n)} only`};if(K(n))return{ok:!0,already:!0,url:O(n)};const r=await C(null),i=n.engineOf(r);if(!await L(n.runner,n.runnerCheck))return{ok:!1,error:`\`${n.runner}\` is not on PATH — install it first (${i.install?.command||""}), or click Install`,install:i.install};if(n.id==="llama"&&/\.gguf$/i.test(n.model)&&!Ae(n.model))return{ok:!1,error:`no such file: ${n.model}`};const[s,o]=n.command(n,R(n,n.model,i,r)),a=$.join(x,J);te(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,...n.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"}};H[n.id]=c.record;const u=$.join(x,`${n.id}.log`);let d,m=null;try{try{m=Bn(u,"w",384)}catch{m=null}d=le(c.bin,c.argv,{...c.opts,env:B(c.opts?.env),detached:!0,stdio:["ignore",m??"ignore",m??"ignore"]}),d.unref?.()}catch(v){return{ok:!1,error:`${c.bin}: ${v.message}`,install:i.install}}finally{if(m!==null)try{Nn(m)}catch{}}if(!d?.pid)return{ok:!1,error:`${c.bin} did not start`,install:i.install};xe(ee(n),String(d.pid),{mode:384});const g=O(n);let h=!1;for(let v=0;v<120&&!h&&K(n);v++)h=await n.answers(g,N),h||await ue(1e3);if(!K(n)){try{tn(ee(n))}catch{}let v="";try{v=nn(u,"utf8").trim().split(`
|
|
3
|
+
`).filter(T=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(T)).slice(-3).map(T=>T.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{v=""}return{ok:!1,error:`${n.label} exited on start${v?` — ${v}`:` — a model it cannot load, a draft or projector file that is not there, or ${n.runner} not installed (${i.install?.command})`}`,log:u}}return n.configure(t,g,n),k(),_(`[runtime] ${n.label} started (pid ${d.pid}) on ${g}, sandbox ${H[n.id].layer}${h?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:g,answering:h,provides:n.provides,model:y(n),sandbox:H[n.id]}}function Ne(e){const n=K(e);if(n)try{process.kill(n,"SIGTERM")}catch{}try{tn(ee(e))}catch{}return e.unconfigure(t,O(e)),k(),{ok:!0}}const q=e=>e.model?{...e,model:y(e),installed:X(e,y(e)),tunings:t.runtime?.services?.[e.id]?.tunings||{},...e.id==="llama"?{file:cn(y(e))}:{}}:e,j=e=>e.id==="vllm"||e.id==="vllm-metal"||e.id==="llama"||e.id==="mlx";function un(e,n){const r=(n.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},s=re(e.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 (${n.ramGB} GB${n.accelerator==="apple"?", Apple Silicon":n.accelerator?`, ${n.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(e)===o.id}}async function Le(e,{model:n,ctx:r,needMB:i}={}){const s=A(e);if(!s||!s.model)return{ok:!1,error:s?`${s.label} takes no model`:`unknown service ${e}`};const o=String(n||y(s)),a=re(e).find(Me=>Me.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):We(e),d=/\.gguf$/i.test(o)||s.id==="llama"?null:qn(D(),o),m=u&&d?Kn(d,u):null,g=Yn({ramMB:c,kvMB:m||0}),h=s.kind==="native"?await on(g):null,v=((await fe()).ramGB||0)*1024,T=h?h.fits:v>0&&g<=v,I=Me=>`${Math.round(Me/102.4)/10} GB`,_n=h?h.fits?`${o} fits: needs about ${I(g)}, ${I(h.availableMB)} is free now${h.fitsGPULimit===!1?` — but it is above the GPU wired limit (${I(h.gpuWiredLimitMB)}); raise iogpu.wired_limit_mb`:""}.`:`${o} needs about ${I(g)} and ${I(h.availableMB)} is free now — ${I(h.shortfallMB)} short.${h.close.length?` Close ${h.close.join(", ")} to make room, or pick a smaller model.`:" Pick a smaller model."}`:`${o} needs about ${I(g)} of the machine's ${I(v)} — ${T?"fits":"does not fit"} (total memory; install Heatwatch to check what is free now).`;return{ok:!0,service:s.id,model:o,needMB:g,weightsMB:c,kvMB:m,context:u||null,contextCounted:m!==null||!u,source:h?"heatwatch":"total-memory",fits:T,live:h,advice:_n}}const R=(e,n,r,i={})=>({task:e.id==="vllm"?Z(n):"chat",model:n,backend:r?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0}),D=()=>$.join(x,J),X=(e,n)=>/\.gguf$/i.test(n)?Ae(n):e.id==="llama"?!!Ze(D(),n):Vn(D(),n),cn=e=>/\.gguf$/i.test(e)?e:Ze(D(),e),b={},st=e=>b[e.id]||null;function ge(e,n,r={}){return b[e.id]={kind:n,since:Date.now(),lines:[],progress:null,done:!1,error:null,...r},b[e.id]}function E(e,n){const r=String(n||"").trim();if(!r)return;e.lines.push(r.slice(0,200)),e.lines.length>8&&e.lines.shift();const i=/^STEP (\d+)\/(\d+)/.exec(r);i&&(e.step={n:Number(i[1]),of:Number(i[2])})}const ne=(e,n,r,{timeout:i=36e5*4}={})=>new Promise(s=>{if(e.cancelled)return s({ok:!1,code:-1,error:"cancelled"});let o;try{o=le(n,r,{stdio:["ignore","pipe","pipe"],env:B()})}catch(d){return s({ok:!1,code:-1,error:d.message})}e.child=o;let a="";const c=d=>{a+=String(d);const m=a.split(/\r?\n|\r/);a=m.pop();for(const g of m)E(e,g)};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),e.child=null,s({ok:!1,code:-1,error:d.message})}),o.on("exit",d=>{clearTimeout(u),e.child=null,a&&E(e,a),s({ok:d===0&&!e.cancelled,code:d,...e.cancelled?{error:"cancelled"}:{}})})}),Ce={install:Promise.resolve(),build:Promise.resolve()},ke={install:0,build:0},Re=(e,n,r)=>{ke[e]>0&&(n.waiting=!0,E(n,`waiting for the other ${e} to finish first — one at a time`)),ke[e]++;const i=Ce[e];let s;const o=new Promise(a=>{s=a});return Ce[e]=i.then(()=>o),i.then(async()=>{n.waiting&&(E(n,"the other one finished — going"),n.waiting=!1);try{return await r()}finally{ke[e]--,s()}})},Ge=async(e,n)=>(await w(e,["image","exists",n],{timeout:2e4})).ok;async function dn(e,n,r,i){const s=n?.image||r.image;if(await Ge(e,s))return{ok:!0};const o=n?.sources?.length?n.sources:[s],a=[];for(const m of o){if(i.kind="pull-image",i.detail=m,E(i,`pulling ${m}`),(await ne(i,e,["pull",m])).ok)return m!==s&&await w(e,["tag",m,s],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const c=n?.recipe?Wn[n.recipe]:null;if(!c)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const u=$.join(x,"images",n.recipe);return te(u,{recursive:!0,mode:448}),xe($.join(u,"Dockerfile"),c.dockerfile,{mode:384}),i.kind="build-image",i.detail=s,i.minutes=c.minutes,E(i,`no registry has ${s} for this machine — building it here (about ${c.minutes} minutes)`),_(`[runtime] building ${s} from the ${n.recipe} recipe in ${u}`),(await Re("build",i,()=>ne(i,e,["build","-t",s,"-f",$.join(u,"Dockerfile"),u]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function Te(e,n){const r=y(e);if(!r||X(e,r))return{ok:!0};if(/\.gguf$/i.test(r))return{ok:!1,error:`no such file: ${r}`};n.kind="pull-model",n.detail=r;const i=s=>{if(n.cancelled)throw new Error("cancelled");n.progress={bytes:s.bytes,total:s.total,file:s.file}};try{return e.id==="llama"?await Qn(r,{root:D(),fetchImpl:N,onProgress:i}):await Jn(r,{root:D(),fetchImpl:N,onProgress:i}),{ok:!0}}catch(s){return{ok:!1,error:`pull ${r}: ${s.message}`}}}async function mn(e,n,r){const i=[];return e.kind!=="native"&&n&&!await Ge(n,r?.image||e.image)&&i.push("image"),e.pull&&e.model&&!X(e,y(e))&&i.push("model"),i}async function Ie(e,n){if(!e||!n?.[e]?.running)return 0;if(e==="podman"&&p!=="linux"){const r=await w("podman",["machine","inspect","--format","{{.Resources.Memory}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?i:0}if(e==="docker"&&p!=="linux"){const r=await w("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?Math.round(i/1048576):0}return Math.round(Oe()/1048576)}async function M(){const e={};for(const r of ae){const i=await w(r,["--version"],{timeout:5e3});if(!i.ok){e[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 w("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const c=await w("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 w("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;e[r]={installed:!0,version:s,running:o,...r==="podman"&&p!=="linux"?{machine:a}:{}}}const n=ae.find(r=>e[r]?.installed&&e[r].running)||ae.find(r=>e[r]?.installed)||null;return{...e,preferred:n,...n?{}:{install:Pe(p)}}}async function we(e="podman"){if(!ae.includes(e))return{ok:!1,error:`unknown engine ${e}`};const n=(await M())[e];if(!n?.installed)return{ok:!1,error:`${e} is not installed`,install:Pe(p)};if(n.running)return{ok:!0,already:!0};if(e==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(p!=="linux"){if(!n.machine){const i=await w("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const r=await w("podman",["machine","start"],{timeout:3e5});if(!r.ok&&!/already running/i.test(r.err))return{ok:!1,error:`podman machine start: ${r.err||r.out}`}}return{ok:!0}}async function fn(){const e=await M(),n=e.preferred;if(!n||!e[n].running)return[];if(n==="podman"){const i=await w("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(s=>an(s,"podman"))}catch{return[]}}const r=await w("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return r.ok?r.out.split(`
|
|
4
|
+
`).filter(Boolean).map(i=>{try{return an(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Fe(e,n){const r=await w(e,["inspect","--format","{{.State.Status}}",n],{timeout:8e3});return r.ok?/running/i.test(r.out)?"running":"stopped":"absent"}async function be(e,n){const r=await w(e,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!r.ok){for(const o of n)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 n)i[o]=s.get(o)||"absent";return i}const O=e=>`http://127.0.0.1:${e.port}`;async function Ue(){const e=await M(),n=e.preferred,r=await Ie(n,e),i={},s=await C(n),o=n&&e[n].running?await be(n,Q.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of Q){const c=O(a);let u="no-engine";a.kind==="native"?u=pe(a):n&&e[n].running?u=o[a.container]||"absent":n&&(u="engine-stopped");const d=a.model?y(a):null,m=a.engineOf?a.engineOf(s):null,g=a.kind==="native"?(s.ramGB||0)*1024:r;i[a.id]={...at(a),engine:a.kind==="native"?"host":n,state:u,url:c,configured:a.configured(t),answering:u==="running"?await a.answers(c,N):!1,...a.helper?{asleep:G.has(a.id),idleMinutes:Je()/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"&&!z(a)?{why:`${a.label} runs on ${oe(a)} only`}:{},...a.kind==="native"&&H[a.id]?{sandbox:H[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:qe(a.id,t.runtime?.services?.[a.id]?.tunings,R(a,d,m,s)),docs:Xn[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:un(a,s)}:{},...a.model?{model:d,default:a.model,models:Ve(a.id,{active:d,engineRamMB:g,engine:a.kind==="native"?"host":n,platform:p,installed:h=>X(a,h)}),machine:{engineRamMB:g}}:{},...j(a)?{tunings:Ke(a.id,t.runtime?.services?.[a.id]?.tunings,R(a,d,m,s))}:{}}}return i}async function pn(){const e=await M(),n=await C(e.preferred);return{platform:p,arch:F,accelerator:n.accelerator,vllmOnPath:n.vllmOnPath,llamaOnPath:n.llamaOnPath,mlxOnPath:n.mlxOnPath,ramGB:n.ramGB,cores:n.cores,perfCores:n.perfCores,recommend:Un(n)}}function He(e,{settingsFile:n=null,secret:r=null,pick:i=null,cpus:s=null}={}){const o=q(e),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(x):[])a.push("-v",u);n&&a.push("-v",`${n}:/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=Rn("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 ye={};async function hn(e){if(ye[e]==null){const n=await w(e,["info","--format",e==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),r=Number.parseInt(n.out,10);ye[e]=Number.isFinite(r)&&r>0?r:W.cpus()?.length||2}return Math.max(1,Math.floor(ye[e]/2))}async function je(e,{force:n=!1}={}){const r=A(e);if(!r)return{ok:!1,error:`unknown service ${e}`};G.delete(r.id),Se(r.id);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:Pe(p)};if(!d[s].running){const m=await we(s);if(!m.ok)return m}}else if(!z(r))return{ok:!1,error:`${r.label} runs on ${oe(r)} only`};const o=await C(s),a=r.engineOf?r.engineOf(o):null;if(r.kind==="native"&&!await L(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))&&!Ae(y(r)))return{ok:!1,error:`no such file: ${y(r)}`};if(r.kind==="native"&&r.model&&!n){const d=await Le(r.id);if(d.live&&!d.fits)return{ok:!1,error:d.advice,plan:d}}const c=await mn(r,s,a);if(!c.length)return delete b[r.id],r.kind==="native"?he(r):$e(r,s);const u=ge(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 dn(s,a,r,u);if(!m.ok)throw new Error(m.error)}if(c.includes("model")){const m=await Te(r,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=r.label;const d=r.kind==="native"?await he(r):await $e(r,s);if(!d.ok)throw new Error(d.error);u.done=!0,u.result=d,_(`[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,_(`[runtime] ${r.label}: ${u.error}`)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function gn(e){const n=A(e);if(!n)return{ok:!1,error:`unknown service ${e}`};const r=b[n.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 E(r,"cancelled"),_(`[runtime] ${n.label}: job cancelled (${r.kind})`),{ok:!0,cancelled:r.kind}}async function $e(e,n){let r=await Fe(n,e.container);const i=e.helper?await hn(n):null,s=e.engineOf?e.engineOf(await C(n)):null,o=e.id==="searxng"?$.join(x,"searxng-settings.yml"):null,a=He(e,{settingsFile:o,secret:e.id==="searxng"?"x":null,pick:s,cpus:i});if(r!=="absent"){const d=await w(n,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',e.container],{timeout:8e3});(!d.ok||d.out!==a.hash)&&(_(`[runtime] ${e.label}: made with older settings — re-creating it`),await w(n,["rm","-f",e.container],{timeout:6e4}),r="absent")}if(r!=="running")if(r==="stopped"){const d=await w(n,["start",e.container],{timeout:6e4});if(!d.ok)return{ok:!1,error:`${n} start: ${d.err||d.out}`}}else{te(x,{recursive:!0,mode:448});let d=null;e.id==="searxng"&&(xe(o,ot(String(t.search?.searxng?.engines||"").split(",").map(h=>h.trim()).filter(Boolean)),{mode:384}),d=Cn(32).toString("hex")),e.volumes&&te($.join(x,J),{recursive:!0,mode:448});const{args:m}=He(e,{settingsFile:o,secret:d,pick:s,cpus:i});_(`[runtime] ${n} ${m.filter(h=>!h.startsWith("SEARXNG_SECRET")).join(" ")}`);const g=await w(n,m,{timeout:6e5});if(!g.ok)return{ok:!1,error:`${n} run: ${g.err||g.out}`}}const c=O(e);let u=!1;for(let d=0;d<30&&!u;d++)u=await e.answers(c,N),u||await ue(1e3);return e.configure(t,c,q(e)),k(),{ok:!0,url:c,answering:u,...e.provides.length?{provides:e.provides}:{},...e.model?{model:y(e)}:{}}}async function kn(e){const n=A(e);if(!n)return{ok:!1,error:`unknown service ${e}`};if(G.delete(n.id),delete ve[n.id],n.kind==="native")return Ne(n);const r=await M(),i=r.preferred;if(i&&r[i].running){const s=await w(i,["stop",n.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${i} stop: ${s.err||s.out}`}}return n.unconfigure(t,O(n)),k(),{ok:!0}}async function wn(e,n){const r=A(e);if(!r)return{ok:!1,error:`unknown service ${e}`};if(!r.model)return{ok:!1,error:`${r.label} takes no model`};const i=String(n||"").trim();if(!Gn(e,i))return{ok:!1,error:`not a model id: ${JSON.stringify(n)} — 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 fe()).ramGB||0)*1024:await Ie(o,s),c=Ve(e,{active:i,engineRamMB:a,engine:r.kind==="native"?"host":o,platform:p,installed:m=>X(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[e]={...t.runtime.services[e]||{},model:i};const u=O(r);r.configured(t)===u&&r.configure(t,u,q(r)),k();const d=await De(r,o,s);return d.ok?{ok:!0,model:i,restarted:d.restarted,...c?.ramNote?{note:c.ramNote}:{}}:d}async function De(e,n,r){if(e.kind==="native"){if(pe(e)!=="running")return{ok:!0,restarted:!1};Ne(e);const o=await he(e);return o.ok?{ok:!0,restarted:!0}:o}if(!n||!r[n].running)return{ok:!0,restarted:!1};const i=await Fe(n,e.container);if(i==="absent")return{ok:!0,restarted:!1};const s=await w(n,["rm","-f",e.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${n} rm: ${s.err||s.out}`};if(i==="running"){const o=await je(e.id);return o.ok?{ok:!0,restarted:!0}:o}return{ok:!0,restarted:!1}}async function bn(e,n){const r=A(e);if(!r)return{ok:!1,error:`unknown service ${e}`};if(!j(r))return{ok:!1,error:`${r.label} takes no profile`};const i=await M(),s=await C(i.preferred),o=r.engineOf?r.engineOf(s):null,a=qe(r.id,t.runtime?.services?.[e]?.tunings,R(r,y(r),o,s)).find(u=>u.id===n);if(!a)return{ok:!1,error:`no profile ${JSON.stringify(n)} — one of speed, coding, long, xl`};if(!a.fits)return{ok:!1,error:`${a.label}: ${a.why}`};const c=await Xe(e,a.patch);return c.ok?{...c,profile:a.id}:c}async function yn(e){const n=A(e);if(!n)return{ok:!1,error:`unknown service ${e}`};if(n.kind!=="native")return{ok:!1,error:`${n.label} is a container — its image is pulled or built on Start`};if(!z(n))return{ok:!1,error:`${n.label} runs on ${oe(n)} only`};const r=b[n.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(delete V[n.runner],await L(n.runner,n.runnerCheck))return{ok:!0,installed:!0};const s=n.engineOf(await C(null))?.install;if(!s?.steps?.length)return{ok:!1,error:`no installer for ${n.label} on this platform${s?.url?` — see ${s.url}`:""}`,install:s||null};const o=ge(n,"install",{detail:n.runner});return o.then=Re("install",o,async()=>{const a=async d=>{for(const[m,...g]of d){E(o,`$ ${m} ${g.join(" ")}`);let h=await ne(o,m,g,{timeout:36e5});for(let v=0;!h.ok&&!o.cancelled&&v<6&&o.lines.some(T=>/already locked|Please wait for it to finish/i.test(T));v++)E(o,`another ${m} holds the lock — waiting 20 s (${v+1}/6)`),await ue(2e4),h=await ne(o,m,g,{timeout:36e5});if(!h.ok)return{ok:!1,error:h.error||`${m} exited ${h.code}`}}return{ok:!0}};let c=await a(s.steps);!c.ok&&!o.cancelled&&s.fallback?.length&&(E(o,`${c.error} — trying the other way`),c=await a(s.fallback)),delete V[n.runner];const u=c.ok&&await L(n.runner,n.runnerCheck);o.done=!0,o.cancelled?o.error="cancelled":c.ok?u||(o.error=`${n.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(" | ")})`:""}`,_(`[runtime] install ${n.runner}: ${o.error||"ok"}`)}),{ok:!0,pending:{kind:o.kind,since:o.since,detail:o.detail}}}async function $n(e){const n=A(e);if(!n)return{ok:!1,error:`unknown service ${e}`};if(!n.pull)return{ok:!1,error:`${n.label} fetches its own model on the first start`};const r=b[n.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(X(n,y(n)))return{ok:!0,installed:!0,model:y(n)};const i=ge(n,"pull-model",{detail:y(n)});return i.then=(async()=>{const s=await Te(n,i);i.done=!0,s.ok||(i.error=s.error)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Xe(e,n){const r=A(e);if(!r)return{ok:!1,error:`unknown service ${e}`};if(!j(r))return{ok:!1,error:`${r.label} takes no tunings`};if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await M(),s=i.preferred,o=y(r),a=await C(s),c=r.engineOf?r.engineOf(a):null,u=Dn(r.id,t.runtime?.services?.[e]?.tunings,n,R(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[e]={...t.runtime.services[e]||{},tunings:u},k();const d=await De(r,s,i);return d.ok?{ok:!0,tunings:Ke(r.id,u,R(r,o,c,a)),restarted:d.restarted}:d}async function vn(){const e=await M(),n=e.preferred,r=n&&e[n].running?await be(n,Q.filter(o=>o.kind!=="native").map(o=>o.container)):{},i={};let s=!1;return await Promise.all(Q.map(async o=>{const a=o.kind==="native"?pe(o):n&&e[n].running?r[o.container]||"absent":"no-engine";i[o.id]=a==="running"&&await o.answers(O(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)!==O(o)&&(o.configure(t,O(o),q(o)),s=!0)})),s&&k(),i}function We(e){const n=A(e);if(n?.window)return n.window;if(!n||!j(n))return null;const r=Number(Ye(n.id,t.runtime?.services?.[e]?.tunings,R(n,y(n),null,{})).maxModelLen);return Number.isFinite(r)&&r>0?r:null}function Sn(e){const n=A(e);if(n?.card)return n.card;if(!n||!j(n))return null;const r=y(n),i=Ye(n.id,t.runtime?.services?.[e]?.tunings,R(n,r,null,{})),s=re(n.id).find(a=>a.id===r)||null,o=n.id==="vllm"?Z(r):"chat";return{engine:n.id,backend:H[n.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"&&(n.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 Mn=10,Je=()=>{const e=Number(t.runtime?.idleMinutes);return(Number.isFinite(e)&&e>=0?e:Mn)*6e4},An=ce(),ve={},G=new Set,Y={};function Se(e){ve[e]=ce()}async function xn(e,{force:n=!1}={}){const r=A(e);return!r||!r.helper?{ok:!0}:(Se(r.id),!G.has(r.id)&&!n?{ok:!0,awake:!0}:(Y[r.id]||(Y[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 we(s);if(!a.ok)return a}const o=await $e(r,s);return o.ok&&(G.delete(r.id),_(`[runtime] ${r.label}: woken for a request`)),o})().finally(()=>{delete Y[r.id]})),Y[r.id]))}async function Qe(){const e=Je();if(!e)return[];const n=Q.filter(a=>a.helper&&a.configured(t)&&!G.has(a.id)&&!Y[a.id]&&!(b[a.id]&&!b[a.id].done)&&ce()-(ve[a.id]??An)>=e);if(!n.length)return[];const r=await M(),i=r.preferred;if(!i||!r[i].running){for(const a of n)G.add(a.id);return n.map(a=>a.id)}const s=await be(i,n.map(a=>a.container)),o=[];for(const a of n){if(s[a.container]==="running"){if(!(await w(i,["stop",a.container],{timeout:6e4})).ok)continue;_(`[runtime] ${a.label}: asleep after ${Math.round(e/6e4)} min without a request — the next one starts it`)}G.add(a.id),o.push(a.id)}return o}return Be&&Be(()=>{Qe().catch(e=>_(`[runtime] idle sweep: ${e.message}`))},6e4),{touch:Se,wake:xn,sweepIdle:Qe,health:vn,contextWindow:We,modelCard:Sn,async status(){const[e,n,r,i,s]=await Promise.all([l().catch(()=>null),M(),Ue(),fn(),pn()]);return{machine:s,sandbox:e?.sandbox||null,processes:{all:[...Array.isArray(e?.processes)?e.processes:[],...f()],localMcp:Array.isArray(e?.localMcp)?e.localMcp:[],warm:e?.warm||null},containers:i,refused:Array.isArray(e?.sandbox?.refused)?e.sandbox.refused:[],bridge:e?{ok:!0,version:e.version||""}:{ok:!1},engines:n,services:r}},startEngine:we,startService:je,stopService:kn,plan:Le,setModel:wn,setTunings:Xe,setProfile:bn,pullModel:$n,installRunner:yn,cancelJob:gn,services:Ue,catalogFor:re}}export{Q as SERVICES,an as containerRow,St as createRuntime,Pe as installDoor,ot as searxngSettings};
|