@chatpanel/gateway 0.86.0 → 0.88.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/README.md +10 -0
- package/bin/chatpanel-gateway-bin.mjs +2 -2
- package/bin/chatpanel-gateway.js +6 -6
- package/package.json +3 -3
- package/src/apple-helper-fetch.js +1 -0
- package/src/apple-model.js +1 -1
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/inference-engines.js +1 -1
- package/src/runtime.js +6 -6
- package/src/sandbox-cli.js +7 -0
- package/src/server.js +21 -21
- package/src/service.js +11 -11
- package/src/system-ca.js +1 -0
- package/src/update.js +3 -3
- package/src/version.js +1 -1
package/src/runtime.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{promisify as Rn}from"node:util";import{execFile as In}from"node:child_process";import{existsSync as Ee,mkdirSync as ne,writeFileSync as oe,accessSync as Un,openSync as Fn,closeSync as Hn,constants as Dn}from"node:fs";import{randomBytes as jn,createHash as Xn}from"node:crypto";import Q from"node:os";import v from"node:path";import{modelsFor as Ze,isValidModelId as Wn,catalogFor as se,vllmTaskOf as te}from"./runtime-models.js";import{pickInferenceEngine as en,pickLlamaEngine as Jn,pickMlxEngine as zn,pickAppleEngine as Kn,recommendEngine as Qn,detectAccelerator as Vn,hostShape as qn}from"./inference-engines.js";import{tuningArgs as le,tuningRows as nn,patchTunings as Yn,profilesFor as tn,resolveTunings as rn,ENGINE_DOCS as Zn}from"./engine-tunings.js";import{IMAGE_RECIPES as et}from"./images.js";import{pullRepo as nt,pullGguf as tt,repoInstalled as rt,ggufInstalled as an}from"./model-pull.js";import{liveFit as it,kvCacheMB as at,cachedConfigPath as ot,needMB as st}from"./host-memory.js";import{APPLE_HELPER as Pe,APPLE_MODEL_ID as lt,APPLE_MIN_DARWIN as ut,appleHelperDirs as ct,appleInstallDoor as dt,darwinMajor as on}from"./apple-model.js";import{spawn as mt}from"node:child_process";import{readFileSync as sn,unlinkSync as ln}from"node:fs";const ft=Rn(In),ue=["podman","docker"],V="hf-cache",X=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],helper:!0,blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only.",caps:["CHOWN","SETGID","SETUID"],answers:async(t,l)=>{try{return(await l(`${t}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.search?.searxng?.url||""),configure:(t,l)=>{t.search=t.search||{},t.search.searxng={...t.search.searxng||{},url:l}},unconfigure:(t,l)=>{t.search?.searxng?.url===l&&(t.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],helper:!0,adapter:"tei",model:"BAAI/bge-reranker-base",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. The gateway already reranks in-process by default (a small model, no container); start this to run a multilingual cross-encoder (bge-reranker base by default) in a container instead, behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.rerank?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.rerank={url:l,adapter:f.adapter,model:f.model,service:f.id}},unconfigure:(t,l)=>{t.capabilities?.rerank?.url===l&&delete t.capabilities.rerank}},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],helper:!0,adapter:"systemone",model:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. The gateway already decides in-process by default with the same algorithm and model; start this to run it in a container instead. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.decide?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.decide={url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}},unconfigure:(t,l)=>{t.capabilities?.decide?.url===l&&delete t.capabilities.decide}},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:t=>en({...t,containerOnly:!0}),container:"chatpanel-vllm",port:8891,containerPort:8e3,provides:["chat","embed","stt"],adapter:"openai",model:"Qwen/Qwen3-0.6B",pull:!0,blurb:"Your own model, served by vLLM on this machine’s accelerator (CUDA, ROCm, XPU — or CPU): a chat model the router can send turns to, an embedding model for semantic search, or a transcriber for every ear. OpenAI-shaped, loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${t.model}`,...t.installed?["HF_HUB_OFFLINE=1"]:[]],args:(t,l)=>["--model",t.model,"--host","0.0.0.0","--port","8000",...te(t.model)==="embed"?["--task","embed"]:[],...le("vllm",t.tunings,{task:te(t.model),model:t.model,backend:l?.backend||null})],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.embed?.service==="vllm"?t.capabilities.embed.url.replace(/\/v1$/,""):t.capabilities?.stt?.service==="vllm"?t.capabilities.stt.url.replace(/\/v1$/,""):(t.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{const h=`${l}/v1`,P=te(f.model);un(t),P==="chat"?(t.destinations=(t.destinations||[]).filter(p=>p?.service!=="vllm"&&p?.id!=="vllm"),t.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:h,models:[f.model],service:"vllm"})):P==="embed"?(t.capabilities=t.capabilities||{},t.capabilities.embed={url:h,adapter:"openai",model:f.model,service:"vllm"}):P==="transcription"&&(t.capabilities=t.capabilities||{},t.capabilities.stt={provider:"container",url:h,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:t=>un(t)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:t=>en(t),only:{platform:"darwin",arch:"arm64"},port:8892,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU, served by vLLM-Metal: a chat model the router can send turns to. A process on this machine behind the gateway, loopback only.",command:(t,l)=>["vllm",["serve",t.model,"--host","127.0.0.1","--port",String(t.port),...le("vllm-metal",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="vllm-metal"&&h?.id!=="vllm-metal"),t.destinations.push({id:"vllm-metal",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:t=>Jn(t),port:8893,provides:["chat"],adapter:"openai",model:"unsloth/Qwen3-4B-GGUF:Q4_K_M",blurb:"Your own GGUF model on this machine, served by llama.cpp: the Metal GPU on a Mac, CUDA or Vulkan elsewhere, CPU otherwise — a chat model the router can send turns to, with the flags that make it fast set for this machine. A process on this machine behind the gateway, loopback only.",alias:t=>/\.gguf$/i.test(t)?t.split(/[\\/]/).pop().replace(/\.gguf$/i,""):t.split("/").pop().split(":")[0],command:(t,l)=>["llama-server",[...t.file?["-m",t.file]:/\.gguf$/i.test(t.model)?["-m",t.model]:["-hf",t.model],"--host","127.0.0.1","--port",String(t.port),"--alias",t.alias(t.model),"--jinja",...le("llama",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="llama"&&h?.id!=="llama"),t.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:t=>zn(t),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU through MLX — Apple’s framework, the lightest way to run a chat model on a Mac. A process on this machine behind the gateway, loopback only.",command:(t,l)=>["mlx_lm.server",["--model",t.model,"--host","127.0.0.1","--port",String(t.port),...le("mlx",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="mlx"&&h?.id!=="mlx"),t.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}},{id:"apple",label:"Apple on-device",kind:"native",auto:!0,runner:Pe,engineOf:t=>Kn(t),only:{platform:"darwin",arch:"arm64",minDarwin:ut,label:"macOS 26 or later on Apple Silicon"},port:8895,provides:["chat"],adapter:"openai",window:4096,card:{engine:"apple",backend:"apple",where:"this machine",egress:"none",cost:"free",task:"chat",window:4096,vision:!1,tools:!1,reasoning:!1,label:"Apple on-device",licence:"Apple",draft:!1},blurb:"Apple’s own model, on this Mac (macOS 26 with Apple Intelligence on): the system loads it when asked and frees it when idle, so nothing stays loaded and nothing runs hot — the lightest choice for titles, topics and short answers. Text only, 4,096 tokens at a time. A small helper on this machine behind the gateway, loopback only.",command:t=>[Pe,["serve","--port",String(t.port)]],answers:async(t,l)=>{try{const f=await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)});return f.ok&&(await f.json())?.ok===!0}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="apple")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l)=>{t.destinations=(t.destinations||[]).filter(f=>f?.service!=="apple"&&f?.id!=="apple"),t.destinations.push({id:"apple",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[lt],service:"apple"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),re=t=>t.only?.label||`${t.only?.platform||"this platform"} ${t.only?.arch||""}`.trim();function un(t){Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),t.capabilities?.embed?.service==="vllm"&&delete t.capabilities.embed,t.capabilities?.stt?.service==="vllm"&&delete t.capabilities.stt}const x=t=>X.find(l=>l.id===t)||null,pt=({answers:t,configured:l,configure:f,unconfigure:h,volumes:P,args:p,env:H,caps:ce,command:de,engineOf:Ne,alias:B,..._})=>_,ht=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),gt=Object.freeze(["brave","qwant"]);function kt(t=[]){const l=t.length?t:ht,f=gt.filter(h=>!l.includes(h));return["# Written by chatpanel-gateway (Settings › Runtime). JSON on, the limiter off — the port is","# bound to 127.0.0.1, which is what makes that safe. Do not publish it on 0.0.0.0.","use_default_settings: true","general:",' instance_name: "ChatPanel search"'," debug: false"," enable_metrics: false","server:",' secret_key: "${SEARXNG_SECRET}"'," limiter: false"," public_instance: false"," image_proxy: false",' method: "GET"',"search:"," safe_search: 0",' autocomplete: ""'," formats:"," - html"," - json","ui:"," static_use_hash: true","engines:",...l.flatMap(h=>[` - name: ${h}`," disabled: false"]),...f.flatMap(h=>[` - name: ${h}`," disabled: true"]),""].join(`
|
|
2
|
-
`)}function
|
|
3
|
-
`).filter(U=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(U)).slice(-3).map(U=>U.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{$=""}return{ok:!1,error:`${e.label} exited on start${$?` — ${$}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:u}}return e.configure(
|
|
4
|
-
`)[0]);return e.ok&&Number.isInteger(
|
|
5
|
-
`).filter(Boolean).map(i=>{try{return
|
|
6
|
-
`).map(o=>o.split(" ")).filter(o=>o[0]).map(([o,a])=>[o,/running/i.test(a||"")?"running":"stopped"]));for(const o of e)i[o]=s.get(o)||"absent";return i}const A=n=>`http://127.0.0.1:${n.port}`;async function We(){const n=await M(),e=n.preferred,r=await De(e,n),i={},s=await G(e),o=e&&n[e].running?await ve(e,X.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of X){const d=A(a);let u="no-engine";a.kind==="native"?u=ke(a):e&&n[e].running?u=o[a.container]||"absent":e&&(u="engine-stopped");const c=a.model?y(a):null,m=a.engineOf?a.engineOf(s):null,w=a.kind==="native"?(s.ramGB||0)*1024:r;i[a.id]={...pt(a),engine:a.kind==="native"?"host":e,state:u,url:d,configured:a.configured(t),answering:u==="running"?await a.answers(d,B):!1,...a.helper?{asleep:T.has(a.id),idleMinutes:qe()/6e4}:{},...m?{engineFor:{backend:m.backend,kind:m.kind,image:m.image||null,...m.runner?{runner:m.runner}:{},why:m.why,...m.for?{for:m.for}:{},...m.speed?{speed:m.speed}:{},...m.notFor?{notFor:m.notFor}:{},...m.warn?{warn:m.warn}:{},...m.install?{install:m.install}:{}}}:{},...a.kind==="native"&&!R(a)?{why:`${a.label} runs on ${re(a)} only`}:{},...a.auto&&u!=="running"&&R(a)?{auto:!0,...we(a)?{why:"Stopped here — Start turns it back on"}:O[a.id]?{why:O[a.id]}:{}}:a.auto?{auto:!0}:{},...!a.auto&&a.kind==="native"&&u!=="running"&&R(a)&&O[a.id]?{why:O[a.id]}:{},...a.kind==="native"&&j[a.id]?{sandbox:j[a.id]}:{},...b[a.id]?{job:{kind:b[a.id].kind,since:b[a.id].since,detail:b[a.id].detail||null,step:b[a.id].step||null,minutes:b[a.id].minutes||null,progress:b[a.id].progress,lines:b[a.id].lines.slice(-4),done:b[a.id].done,error:b[a.id].error,waiting:!!b[a.id].waiting,cancelled:!!b[a.id].cancelled}}:{},...J(a)?{profiles:tn(a.id,t.runtime?.services?.[a.id]?.tunings,I(a,c,m,s)),docs:Zn[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:bn(a,s)}:{},...a.model?{model:c,default:a.model,models:Ze(a.id,{active:c,engineRamMB:w,engine:a.kind==="native"?"host":e,platform:p,installed:g=>K(a,g)}),machine:{engineRamMB:w}}:{},...J(a)?{tunings:nn(a.id,t.runtime?.services?.[a.id]?.tunings,I(a,c,m,s))}:{}}}return i}async function Sn(){const n=await M(),e=await G(n.preferred);return{platform:p,arch:H,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:Qn(e)}}function Je(n,{settingsFile:e=null,secret:r=null,pick:i=null,cpus:s=null}={}){const o=Z(n),a=["run","-d","--name",o.container,"--restart","no","-p",`127.0.0.1:${o.port}:${o.containerPort}`];o.helper&&s&&a.push("--cpus",String(s));for(const u of o.volumes?o.volumes(_):[])a.push("-v",u);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const u of o.env?o.env(o):[])a.push("-e",u);o.helper&&s&&a.push("-e",`THREADS=${s}`),r&&a.push("-e",`SEARXNG_SECRET=${r}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${o.port}/`),a.push("--cap-drop","ALL");for(const u of o.caps||[])a.push("--cap-add",u);i?.devices?.length&&a.push(...i.devices),a.push(i?.image||o.image,...o.args?o.args(o,i):[]);const d=Xn("sha1").update(JSON.stringify(a.filter(u=>!String(u).startsWith("SEARXNG_SECRET=")))).digest("hex").slice(0,12);return a.splice(2,0,"--label",`chatpanel.run=${d}`),{args:a,hash:d}}const Se={};async function An(n){if(Se[n]==null){const e=await k(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),r=Number.parseInt(e.out,10);Se[n]=Number.isFinite(r)&&r>0?r:Q.cpus()?.length||2}return Math.max(1,Math.floor(Se[n]/2))}async function ze(n,{force:e=!1}={}){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};T.delete(r.id),xe(r.id),r.auto&&we(r)&&Le(r,!1);const i=b[r.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let s=null;if(r.kind!=="native"){const c=await M();if(s=c.preferred,!s)return{ok:!1,error:"no container engine — install Podman first",install:Oe(p)};if(!c[s].running){const m=await $e(s);if(!m.ok)return m}}else if(!R(r))return{ok:!1,error:`${r.label} runs on ${re(r)} only`};const o=await G(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))&&!Ee(y(r)))return{ok:!1,error:`no such file: ${y(r)}`};if(r.kind==="native"&&r.model&&!e){const c=await Re(r.id);if(c.live&&!c.fits)return{ok:!1,error:c.advice,plan:c}}const d=await vn(r,s,a);if(!d.length){if(delete b[r.id],r.kind!=="native")return Ae(r,s);const c=await ie(r);return c.ok?delete O[r.id]:O[r.id]=c.error,c}const u=be(r,d[0]==="image"?"pull-image":"pull-model",{detail:d[0]==="image"?a?.image||r.image:y(r)});return u.then=(async()=>{try{if(d.includes("image")){const m=await $n(s,a,r,u);if(!m.ok)throw new Error(m.error)}if(d.includes("model")){const m=await He(r,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=r.label;const c=r.kind==="native"?await ie(r):await Ae(r,s);if(!c.ok)throw new Error(c.error);u.done=!0,u.result=c,E(`[runtime] ${r.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(c){u.done=!0,u.error=u.cancelled?"cancelled":c.message,E(`[runtime] ${r.label}: ${u.error}`)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function Mn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const r=b[e.id];if(!r||r.done)return{ok:!0,nothing:!0};if(r.cancelled=!0,r.child){try{r.child.kill("SIGTERM")}catch{}const i=r.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return N(r,"cancelled"),E(`[runtime] ${e.label}: job cancelled (${r.kind})`),{ok:!0,cancelled:r.kind}}async function Ae(n,e){let r=await Xe(e,n.container);const i=n.helper?await An(e):null,s=n.engineOf?n.engineOf(await G(e)):null,o=n.id==="searxng"?v.join(_,"searxng-settings.yml"):null,a=Je(n,{settingsFile:o,secret:n.id==="searxng"?"x":null,pick:s,cpus:i});if(r!=="absent"){const c=await k(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!c.ok||c.out!==a.hash)&&(E(`[runtime] ${n.label}: made with older settings — re-creating it`),await k(e,["rm","-f",n.container],{timeout:6e4}),r="absent")}if(r!=="running")if(r==="stopped"){const c=await k(e,["start",n.container],{timeout:6e4});if(!c.ok)return{ok:!1,error:`${e} start: ${c.err||c.out}`}}else{ne(_,{recursive:!0,mode:448});let c=null;n.id==="searxng"&&(oe(o,kt(String(t.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),c=jn(32).toString("hex")),n.volumes&&ne(v.join(_,V),{recursive:!0,mode:448});const{args:m}=Je(n,{settingsFile:o,secret:c,pick:s,cpus:i});E(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const w=await k(e,m,{timeout:6e5});if(!w.ok)return{ok:!1,error:`${e} run: ${w.err||w.out}`}}const d=A(n);let u=!1;for(let c=0;c<30&&!u;c++)u=await n.answers(d,B),u||await me(1e3);return n.configure(t,d,Z(n)),h(),{ok:!0,url:d,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:y(n)}:{}}}async function xn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(T.delete(e.id),delete Me[e.id],e.auto&&Le(e,!0),e.kind==="native")return Ge(e);const r=await M(),i=r.preferred;if(i&&r[i].running){const s=await k(i,["stop",e.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${i} stop: ${s.err||s.out}`}}return e.unconfigure(t,A(e)),h(),{ok:!0}}async function _n(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!r.model)return{ok:!1,error:`${r.label} takes no model`};const i=String(e||"").trim();if(!Wn(n,i))return{ok:!1,error:`not a model id: ${JSON.stringify(e)} — pick one from the list, or a Hugging Face id like owner/name`};const s=await M(),o=s.preferred,a=r.kind==="native"?((await ge()).ramGB||0)*1024:await De(o,s),d=Ze(n,{active:i,engineRamMB:a,engine:r.kind==="native"?"host":o,platform:p,installed:m=>K(r,m)}).find(m=>m.id===i);if(d?.unavailable)return{ok:!1,error:`${i} ${d.unavailable}`};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},model:i};const u=A(r);r.configured(t)===u&&r.configure(t,u,Z(r)),h();const c=await Ke(r,o,s);return c.ok?{ok:!0,model:i,restarted:c.restarted,...d?.ramNote?{note:d.ramNote}:{}}:c}async function Ke(n,e,r){if(n.kind==="native"){if(ke(n)!=="running")return{ok:!0,restarted:!1};Ge(n);const o=await ie(n);return o.ok?{ok:!0,restarted:!0}:o}if(!e||!r[e].running)return{ok:!0,restarted:!1};const i=await Xe(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const s=await k(e,["rm","-f",n.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${e} rm: ${s.err||s.out}`};if(i==="running"){const o=await ze(n.id);return o.ok?{ok:!0,restarted:!0}:o}return{ok:!0,restarted:!1}}async function En(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!J(r))return{ok:!1,error:`${r.label} takes no profile`};const i=await M(),s=await G(i.preferred),o=r.engineOf?r.engineOf(s):null,a=tn(r.id,t.runtime?.services?.[n]?.tunings,I(r,y(r),o,s)).find(u=>u.id===e);if(!a)return{ok:!1,error:`no profile ${JSON.stringify(e)} — one of speed, coding, long, xl`};if(!a.fits)return{ok:!1,error:`${a.label}: ${a.why}`};const d=await Qe(n,a.patch);return d.ok?{...d,profile:a.id}:d}async function Pn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!R(e))return{ok:!1,error:`${e.label} runs on ${re(e)} only`};const r=b[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(delete q[e.runner],await L(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const s=e.engineOf(await G(null))?.install;if(!s?.steps?.length)return{ok:!1,error:`no installer for ${e.label} on this platform${s?.url?` — see ${s.url}`:""}`,install:s||null};const o=be(e,"install",{detail:e.runner});return o.then=Ue("install",o,async()=>{const a=async c=>{for(const[m,...w]of c){N(o,`$ ${m} ${w.join(" ")}`);let g=await ae(o,m,w,{timeout:36e5});for(let $=0;!g.ok&&!o.cancelled&&$<6&&o.lines.some(U=>/already locked|Please wait for it to finish/i.test(U));$++)N(o,`another ${m} holds the lock — waiting 20 s (${$+1}/6)`),await me(2e4),g=await ae(o,m,w,{timeout:36e5});if(!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let d=await a(s.steps);!d.ok&&!o.cancelled&&s.fallback?.length&&(N(o,`${d.error} — trying the other way`),d=await a(s.fallback)),delete q[e.runner];const u=d.ok&&await L(e.runner,e.runnerCheck);o.done=!0,o.cancelled?o.error="cancelled":d.ok?u||(o.error=`${e.runner} still not found after the install — open a new terminal and run \`${s.command}\` by hand`):o.error=`install failed: ${d.error}${o.lines.length?` (${o.lines.slice(-2).join(" | ")})`:""}`,E(`[runtime] install ${e.runner}: ${o.error||"ok"}`)}),{ok:!0,pending:{kind:o.kind,since:o.since,detail:o.detail}}}async function On(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const r=b[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(K(e,y(e)))return{ok:!0,installed:!0,model:y(e)};const i=be(e,"pull-model",{detail:y(e)});return i.then=(async()=>{const s=await He(e,i);i.done=!0,s.ok||(i.error=s.error)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Qe(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!J(r))return{ok:!1,error:`${r.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await M(),s=i.preferred,o=y(r),a=await G(s),d=r.engineOf?r.engineOf(a):null,u=Yn(r.id,t.runtime?.services?.[n]?.tunings,e,I(r,o,d,a));if(u.error)return{ok:!1,error:u.error};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},tunings:u},h();const c=await Ke(r,s,i);return c.ok?{ok:!0,tunings:nn(r.id,u,I(r,o,d,a)),restarted:c.restarted}:c}async function Nn(){const n=await M(),e=n.preferred,r=e&&n[e].running?await ve(e,X.filter(o=>o.kind!=="native").map(o=>o.container)):{},i={};let s=!1;return await Promise.all(X.map(async o=>{const a=o.kind==="native"?ke(o):e&&n[e].running?r[o.container]||"absent":"no-engine";i[o.id]=a==="running"&&await o.answers(A(o),B)?"up":"down";const d=(o.provides||[]).some(u=>["embedded","none"].includes(t.capabilities?.[u]?.provider));i[o.id]==="up"&&o.configure&&!d&&o.configured(t)!==A(o)&&(o.configure(t,A(o),Z(o)),s=!0)})),s&&h(),i}function Ve(n){const e=x(n);if(e?.window)return e.window;if(!e||!J(e))return null;const r=Number(rn(e.id,t.runtime?.services?.[n]?.tunings,I(e,y(e),null,{})).maxModelLen);return Number.isFinite(r)&&r>0?r:null}function Bn(n){const e=x(n);if(e?.card)return e.card;if(!e||!J(e))return null;const r=y(e),i=rn(e.id,t.runtime?.services?.[n]?.tunings,I(e,r,null,{})),s=se(e.id).find(a=>a.id===r)||null,o=e.id==="vllm"?te(r):"chat";return{engine:e.id,backend:j[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:o,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:o==="chat"&&!!i.vision,tools:!!(o==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:o==="chat"&&!!i.reasoning&&i.reasoning!=="off",...s?{tier:s.tier||null,licence:s.licence||null,languages:s.lang||null,label:s.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}const Cn=10,qe=()=>{const n=Number(t.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:Cn)*6e4},Ln=fe(),Me={},T=new Set,ee={};function xe(n){Me[n]=fe()}async function Tn(n,{force:e=!1}={}){const r=x(n);if(!r||!r.helper)return{ok:!0};if(xe(r.id),!T.has(r.id)&&!e){const i=r.container&&r.configured?.(t)?(await je()).find(s=>s.name===r.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};T.add(r.id)}return ee[r.id]||(ee[r.id]=(async()=>{const i=await M(),s=i.preferred;if(!s)return{ok:!1,error:"no container engine"};if(!i[s].running){const a=await $e(s);if(!a.ok)return a}const o=await Ae(r,s);return o.ok&&(T.delete(r.id),E(`[runtime] ${r.label}: woken for a request`)),o})().finally(()=>{delete ee[r.id]})),ee[r.id]}async function Ye(){const n=qe();if(!n)return[];const e=X.filter(a=>a.helper&&a.configured(t)&&!T.has(a.id)&&!ee[a.id]&&!(b[a.id]&&!b[a.id].done)&&fe()-(Me[a.id]??Ln)>=n);if(!e.length)return[];const r=await M(),i=r.preferred;if(!i||!r[i].running){for(const a of e)T.add(a.id);return e.map(a=>a.id)}const s=await ve(i,e.map(a=>a.container)),o=[];for(const a of e){if(s[a.container]==="running"){if(!(await k(i,["stop",a.container],{timeout:6e4})).ok)continue;E(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}T.add(a.id),o.push(a.id)}return o}return Ce&&Ce(()=>{Ye().catch(n=>E(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:xe,wake:Tn,sweepIdle:Ye,health:Nn,contextWindow:Ve,modelCard:Bn,async status(){const[n,e,r,i,s]=await Promise.all([l().catch(()=>null),M(),We(),je(),Sn()]);return{machine:s,sandbox:n?.sandbox||null,processes:{all:[...Array.isArray(n?.processes)?n.processes:[],...f()],localMcp:Array.isArray(n?.localMcp)?n.localMcp:[],warm:n?.warm||null},containers:i,refused:Array.isArray(n?.sandbox?.refused)?n.sandbox.refused:[],bridge:n?{ok:!0,version:n.version||""}:{ok:!1},engines:e,services:r}},startEngine:$e,startService:ze,stopService:xn,ensureDefaults:gn,revive:kn,plan:Re,setModel:_n,setTunings:Qe,setProfile:En,pullModel:On,installRunner:Pn,cancelJob:Mn,services:We,catalogFor:se}}export{ht as SEARXNG_DEFAULT_ENGINES,X as SERVICES,cn as containerRow,Lt as createRuntime,Oe as installDoor,kt as searxngSettings};
|
|
1
|
+
import{promisify as Un}from"node:util";import{execFile as Fn}from"node:child_process";import{existsSync as Pe,mkdirSync as te,writeFileSync as le,accessSync as Hn,openSync as Dn,closeSync as jn,constants as Xn}from"node:fs";import{randomBytes as Wn,createHash as Jn}from"node:crypto";import V from"node:os";import v from"node:path";import{modelsFor as nn,isValidModelId as zn,catalogFor as ue,vllmTaskOf as re}from"./runtime-models.js";import{pickInferenceEngine as tn,pickLlamaEngine as Kn,pickMlxEngine as Qn,pickAppleEngine as Vn,recommendEngine as qn,detectAccelerator as Yn,hostShape as Zn}from"./inference-engines.js";import{tuningArgs as ce,tuningRows as rn,patchTunings as et,profilesFor as an,resolveTunings as on,ENGINE_DOCS as nt}from"./engine-tunings.js";import{IMAGE_RECIPES as tt}from"./images.js";import{pullRepo as rt,pullGguf as it,repoInstalled as at,ggufInstalled as sn}from"./model-pull.js";import{liveFit as ot,kvCacheMB as st,cachedConfigPath as lt,needMB as ut}from"./host-memory.js";import{APPLE_HELPER as Oe,APPLE_MODEL_ID as ct,APPLE_MIN_DARWIN as dt,appleHelperDirs as mt,appleInstallDoor as ft,darwinMajor as ln}from"./apple-model.js";import{spawn as pt}from"node:child_process";import{readFileSync as un,unlinkSync as cn}from"node:fs";const ht=Un(Fn),de=["podman","docker"],q="hf-cache",X=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(r,l)=>{try{return(await l(`${r}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.search?.searxng?.url||""),configure:(r,l)=>{r.search=r.search||{},r.search.searxng={...r.search.searxng||{},url:l}},unconfigure:(r,l)=>{r.search?.searxng?.url===l&&(r.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:r=>[`${v.join(r,q)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.capabilities?.rerank?.url||""),configure:(r,l,f)=>{r.capabilities=r.capabilities||{},r.capabilities.rerank={url:l,adapter:f.adapter,model:f.model,service:f.id}},unconfigure:(r,l)=>{r.capabilities?.rerank?.url===l&&delete r.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:r=>[`${v.join(r,q)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.capabilities?.decide?.url||""),configure:(r,l,f)=>{r.capabilities=r.capabilities||{},r.capabilities.decide={url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}},unconfigure:(r,l)=>{r.capabilities?.decide?.url===l&&delete r.capabilities.decide}},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:r=>tn({...r,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:r=>[`${v.join(r,q)}:/data`],env:r=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${r.model}`,...r.installed?["HF_HUB_OFFLINE=1"]:[]],args:(r,l)=>["--model",r.model,"--host","0.0.0.0","--port","8000",...re(r.model)==="embed"?["--task","embed"]:[],...ce("vllm",r.tunings,{task:re(r.model),model:r.model,backend:l?.backend||null})],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.capabilities?.embed?.service==="vllm"?r.capabilities.embed.url.replace(/\/v1$/,""):r.capabilities?.stt?.service==="vllm"?r.capabilities.stt.url.replace(/\/v1$/,""):(r.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{const h=`${l}/v1`,P=re(f.model);dn(r),P==="chat"?(r.destinations=(r.destinations||[]).filter(p=>p?.service!=="vllm"&&p?.id!=="vllm"),r.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:h,models:[f.model],service:"vllm"})):P==="embed"?(r.capabilities=r.capabilities||{},r.capabilities.embed={url:h,adapter:"openai",model:f.model,service:"vllm"}):P==="transcription"&&(r.capabilities=r.capabilities||{},r.capabilities.stt={provider:"container",url:h,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:r=>dn(r)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:r=>tn(r),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:(r,l)=>["vllm",["serve",r.model,"--host","127.0.0.1","--port",String(r.port),...ce("vllm-metal",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(h=>h?.service!=="vllm-metal"&&h?.id!=="vllm-metal"),r.destinations.push({id:"vllm-metal",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:r=>Kn(r),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:r=>/\.gguf$/i.test(r)?r.split(/[\\/]/).pop().replace(/\.gguf$/i,""):r.split("/").pop().split(":")[0],command:(r,l)=>["llama-server",[...r.file?["-m",r.file]:/\.gguf$/i.test(r.model)?["-m",r.model]:["-hf",r.model],"--host","127.0.0.1","--port",String(r.port),"--alias",r.alias(r.model),"--jinja",...ce("llama",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(h=>h?.service!=="llama"&&h?.id!=="llama"),r.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:r=>Qn(r),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:(r,l)=>["mlx_lm.server",["--model",r.model,"--host","127.0.0.1","--port",String(r.port),...ce("mlx",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(h=>h?.service!=="mlx"&&h?.id!=="mlx"),r.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}},{id:"apple",label:"Apple on-device",kind:"native",auto:!0,runner:Oe,engineOf:r=>Vn(r),only:{platform:"darwin",arch:"arm64",minDarwin:dt,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:r=>[Oe,["serve","--port",String(r.port)]],answers:async(r,l)=>{try{const f=await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)});return f.ok&&(await f.json())?.ok===!0}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="apple")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l)=>{r.destinations=(r.destinations||[]).filter(f=>f?.service!=="apple"&&f?.id!=="apple"),r.destinations.push({id:"apple",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[ct],service:"apple"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),ie=r=>r.only?.label||`${r.only?.platform||"this platform"} ${r.only?.arch||""}`.trim();function dn(r){Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),r.capabilities?.embed?.service==="vllm"&&delete r.capabilities.embed,r.capabilities?.stt?.service==="vllm"&&delete r.capabilities.stt}const _=r=>X.find(l=>l.id===r)||null,gt=({answers:r,configured:l,configure:f,unconfigure:h,volumes:P,args:p,env:H,caps:me,command:fe,engineOf:Be,alias:B,...x})=>x,kt=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),wt=Object.freeze(["brave","qwant"]);function bt(r=[]){const l=r.length?r:kt,f=wt.filter(h=>!l.includes(h));return["# Written by chatpanel-gateway (Settings › Runtime). JSON on, the limiter off — the port is","# bound to 127.0.0.1, which is what makes that safe. Do not publish it on 0.0.0.0.","use_default_settings: true","general:",' instance_name: "ChatPanel search"'," debug: false"," enable_metrics: false","server:",' secret_key: "${SEARXNG_SECRET}"'," limiter: false"," public_instance: false"," image_proxy: false",' method: "GET"',"search:"," safe_search: 0",' autocomplete: ""'," formats:"," - html"," - json","ui:"," static_use_hash: true","engines:",...l.flatMap(h=>[` - name: ${h}`," disabled: false"]),...f.flatMap(h=>[` - name: ${h}`," disabled: true"]),""].join(`
|
|
2
|
+
`)}function Ne(r=process.platform){return r==="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)."}:r==="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 mn(r,l){const f=l==="podman"?Array.isArray(r.Names)?r.Names[0]:String(r.Names||""):String(r.Names||r.Name||""),h=l==="podman"?Array.isArray(r.Ports)?r.Ports.map(p=>`${p.host_ip||""}:${p.host_port}->${p.container_port}/${p.protocol||"tcp"}`):[]:String(r.Ports||"").split(",").map(p=>p.trim()).filter(Boolean),P=String(r.State||"").toLowerCase()||(/^up/i.test(String(r.Status||""))?"running":"exited");return{name:f,image:String(r.Image||""),state:P,status:String(r.Status||""),ports:h,ours:f.startsWith("chatpanel-"),engine:l}}const yt=15e3;function Gt({cfg:r,bridgeHealth:l,workers:f=()=>[],persist:h=()=>{},exec:P=(S,D,C={})=>ht(S,D,{timeout:6e4,killSignal:"SIGKILL",...C}),platform:p=process.platform,arch:H=process.arch,osRelease:me=V.release(),spawn:fe=pt,lookup:Be=null,fetchImpl:B=globalThis.fetch,stateDir:x=v.join(V.homedir(),".chatpanel","runtime"),log:E=()=>{},sleep:pe=S=>new Promise(D=>setTimeout(D,S)),totalMem:Ce=()=>V.totalmem(),memoryProbe:fn=S=>p==="darwin"&&r?.runtime?.heatwatch!==!1?ot(S,{fetchImpl:B}):Promise.resolve(null),now:Y=()=>Date.now(),autoEnv:pn=process.env.CHATPANEL_RUNTIME_AUTO,every:Le=(S,D)=>{const C=setInterval(S,D);return C.unref?.(),C}}={}){const S=V.homedir(),D=p==="win32"?[v.join(S,"AppData","Local","Microsoft","WinGet","Links"),v.join(S,".local","bin"),v.join(S,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",v.join(S,".local","bin"),v.join(S,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin",...p==="darwin"?mt({home:S}):[]],C=(n=process.env)=>{const e=p==="win32"?";":":",t=String(n.PATH||n.Path||""),i=D.filter(s=>!t.split(e).includes(s));return{...n,PATH:[...t.split(e).filter(Boolean),...i].join(e)}},k=async(n,e,t={})=>{try{const i=await P(n,e,{...t,env:C(t.env)});return{ok:!0,out:String(i.stdout||"").trim(),err:String(i.stderr||"").trim()}}catch(i){return{ok:!1,out:String(i?.stdout||"").trim(),err:String(i?.stderr||i?.message||i).trim(),code:i?.code}}},y=n=>String(r.runtime?.services?.[n.id]?.model||n.model||"");let he=null;const hn=async()=>(he===null&&(he=await Yn({exec:P,platform:p,arch:H})),he),ae={},gn=n=>{const e=p==="win32"?";":":",t=p==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of C().PATH.split(e).filter(Boolean))for(const s of t)try{return Hn(v.join(i,n+s),Xn.X_OK),!0}catch{}return!1},W={},L=async(n,e=["--version"])=>{if(ae[n])return!0;if(W[n]!==void 0&&Y()-W[n]<yt)return!1;const t=(Be||gn)(n)||(await k(n,e,{timeout:8e3})).ok;return t?(ae[n]=!0,delete W[n]):W[n]=Y(),t},Re=(n,e)=>e?.missing||`\`${n.runner}\` is not on PATH — install it first (${e?.command||""}), or click Install`;let ge=null;const ke=async()=>(ge||(ge=await Zn({exec:P,platform:p,totalmem:Ce,cpus:()=>V.cpus()})),ge),T=async n=>({platform:p,arch:H,accelerator:await hn(),engine:n,vllmOnPath:await L("vllm"),llamaOnPath:await L("llama-server"),mlxOnPath:p==="darwin"&&H==="arm64"?await L("mlx_lm.server",["--help"]):!1,osMajor:p==="darwin"?ln(me):0,appleOnPath:p==="darwin"&&H==="arm64"?await L(Oe):!1,appleInstall:p==="darwin"?ft({home:S}):null,...await ke()}),G=n=>!n.only||(!n.only.platform||n.only.platform===p)&&(!n.only.arch||n.only.arch===H)&&(!n.only.minDarwin||ln(me)>=n.only.minDarwin),Z=n=>v.join(x,`${n.id}.pid`),J=n=>{try{const e=Number(un(Z(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},we=n=>G(n)?J(n)?"running":"stopped":"unsupported",j={};async function oe(n){const e=ee(n);if(!G(e))return{ok:!1,error:`${e.label} runs on ${ie(e)} only`};if(J(e))return e.auto&&!e.configured(r)&&(e.configure(r,A(e),e),h()),{ok:!0,already:!0,url:A(e)};if(e.auto&&await e.answers(A(e),B)){const $=await yn(e.port);if($)return te(x,{recursive:!0,mode:448}),le(Z(e),String($),{mode:384}),j[e.id]={layer:"none",reason:"a model engine runs on the hardware, behind the gateway"},e.configure(r,A(e),e),h(),E(`[runtime] ${e.label} was already answering on ${A(e)} (pid ${$}) — adopted`),{ok:!0,adopted:!0,url:A(e),answering:!0,provides:e.provides}}const t=await T(null),i=e.engineOf(t);if(!await L(e.runner,e.runnerCheck))return{ok:!1,error:Re(e,i.install),install:i.install};if(e.id==="llama"&&/\.gguf$/i.test(e.model)&&!Pe(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[s,o]=e.command(e,I(e,e.model,i,t)),a=v.join(x,q);te(a,{recursive:!0,mode:448});const d={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"}};j[e.id]=d.record;const u=v.join(x,`${e.id}.log`);let c,m=null;try{try{m=Dn(u,"w",384)}catch{m=null}c=fe(d.bin,d.argv,{...d.opts,env:C(d.opts?.env),detached:!0,stdio:["ignore",m??"ignore",m??"ignore"]}),c.unref?.()}catch($){return{ok:!1,error:`${d.bin}: ${$.message}`,install:i.install}}finally{if(m!==null)try{jn(m)}catch{}}if(!c?.pid)return{ok:!1,error:`${d.bin} did not start`,install:i.install};le(Z(e),String(c.pid),{mode:384});const w=A(e);let g=!1;for(let $=0;$<120&&!g&&J(e);$++)g=await e.answers(w,B),g||await pe(1e3);if(!J(e)){try{cn(Z(e))}catch{}let $="";try{$=un(u,"utf8").trim().split(`
|
|
3
|
+
`).filter(U=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(U)).slice(-3).map(U=>U.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{$=""}return{ok:!1,error:`${e.label} exited on start${$?` — ${$}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:u}}return e.configure(r,w,e),h(),E(`[runtime] ${e.label} started (pid ${c.pid}) on ${w}, sandbox ${j[e.id].layer}${g?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:w,answering:g,provides:e.provides,model:y(e),sandbox:j[e.id]}}const be=n=>r.runtime?.services?.[n.id]?.off===!0,Te=(n,e)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{};const t={...r.runtime.services[n.id]||{}};e?t.off=!0:delete t.off,r.runtime.services[n.id]=t},kn=()=>r.runtime?.auto!==!1&&String(pn||"").toLowerCase()!=="off",O={};async function Ge(n){if(!n?.auto)return{ok:!1,skipped:"not a service that starts by itself"};if(!kn())return{ok:!1,skipped:"automatic start is switched off"};if(!G(n))return{ok:!1,skipped:`runs on ${ie(n)} only`};if(be(n))return{ok:!1,skipped:"stopped by the person"};if(!await L(n.runner,n.runnerCheck))return{ok:!1,skipped:"its helper is not in this install"};if(!J(n)){const t=await k(n.runner,["check"],{timeout:8e3});if(!t.ok){let i="";try{i=JSON.parse(t.out||"{}").message||""}catch{i=""}return O[n.id]=i||"not available on this Mac right now",{ok:!1,skipped:O[n.id]}}}const e=await oe(n);return e.ok?(delete O[n.id],{ok:!0,...e.already?{already:!0}:e.adopted?{adopted:!0}:{started:!0}}):(O[n.id]=e.error,{ok:!1,skipped:e.error})}async function wn(){const n=[];for(const e of X.filter(t=>t.auto))n.push({id:e.id,label:e.label,...await Ge(e).catch(t=>({ok:!1,skipped:t.message}))});return n}async function bn(n){const e=_(n);return e?.auto?Ge(e):{ok:!1,skipped:"not a service that starts by itself"}}async function yn(n){if(p==="win32")return 0;const e=await k("lsof",["-nP",`-iTCP:${n}`,"-sTCP:LISTEN","-t"],{timeout:4e3}),t=Number(String(e.out||"").split(`
|
|
4
|
+
`)[0]);return e.ok&&Number.isInteger(t)&&t>1?t:0}function Ie(n){const e=J(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{cn(Z(n))}catch{}return n.unconfigure(r,A(n)),h(),{ok:!0}}const ee=n=>n.model?{...n,model:y(n),installed:Q(n,y(n)),tunings:r.runtime?.services?.[n.id]?.tunings||{},...n.id==="llama"?{file:vn(y(n))}:{}}:n,z=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx";function $n(n,e){const t=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},s=ue(n.id).filter(d=>!d.minRamMB||t>0&&t>=d.minRamMB);if(!s.length||!t)return null;const o=s.slice().sort((d,u)=>(i[u.tier]??-1)-(i[d.tier]??-1)||d.ramMB-u.ramMB)[0],a=Math.round(o.ramMB/1024*10)/10;return{model:o.id,label:o.label,why:`This machine (${e.ramGB} GB${e.accelerator==="apple"?", Apple Silicon":e.accelerator?`, ${e.accelerator.toUpperCase()} GPU`:", no GPU"}) runs ${o.label} well — about ${a} GB while loaded${o.tier==="max"?"; the strongest in the list":""}.`,profile:"coding",current:y(n)===o.id}}async function Ue(n,{model:e,ctx:t,needMB:i}={}){const s=_(n);if(!s||!s.model)return{ok:!1,error:s?`${s.label} takes no model`:`unknown service ${n}`};const o=String(e||y(s)),a=ue(n).find(Ee=>Ee.id===o)||null,d=Number(i)>0?Number(i):a?.ramMB||null;if(!d)return{ok:!1,error:`${o} is not in the catalogue — pass need_mb (its peak memory while serving)`};const u=Number(t)>0?Number(t):Ye(n),c=/\.gguf$/i.test(o)||s.id==="llama"?null:lt(K(),o),m=u&&c?st(c,u):null,w=ut({ramMB:d,kvMB:m||0}),g=s.kind==="native"?await fn(w):null,$=((await ke()).ramGB||0)*1024,U=g?g.fits:$>0&&w<=$,F=Ee=>`${Math.round(Ee/102.4)/10} GB`,In=g?g.fits?`${o} fits: needs about ${F(w)}, ${F(g.availableMB)} is free now${g.fitsGPULimit===!1?` — but it is above the GPU wired limit (${F(g.gpuWiredLimitMB)}); raise iogpu.wired_limit_mb`:""}.`:`${o} needs about ${F(w)} and ${F(g.availableMB)} is free now — ${F(g.shortfallMB)} short.${g.close.length?` Close ${g.close.join(", ")} to make room, or pick a smaller model.`:" Pick a smaller model."}`:`${o} needs about ${F(w)} of the machine's ${F($)} — ${U?"fits":"does not fit"} (total memory; install Heatwatch to check what is free now).`;return{ok:!0,service:s.id,model:o,needMB:w,weightsMB:d,kvMB:m,context:u||null,contextCounted:m!==null||!u,source:g?"heatwatch":"total-memory",fits:U,live:g,advice:In}}const I=(n,e,t,i={})=>({task:n.id==="vllm"?re(e):"chat",model:e,backend:t?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0}),K=()=>v.join(x,q),Q=(n,e)=>/\.gguf$/i.test(e)?Pe(e):n.id==="llama"?!!sn(K(),e):at(K(),e),vn=n=>/\.gguf$/i.test(n)?n:sn(K(),n),b={},$t=n=>b[n.id]||null;function ye(n,e,t={}){return b[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...t},b[n.id]}function N(n,e){const t=String(e||"").trim();if(!t)return;n.lines.push(t.slice(0,200)),n.lines.length>8&&n.lines.shift();const i=/^STEP (\d+)\/(\d+)/.exec(t);i&&(n.step={n:Number(i[1]),of:Number(i[2])})}const se=(n,e,t,{timeout:i=36e5*4}={})=>new Promise(s=>{if(n.cancelled)return s({ok:!1,code:-1,error:"cancelled"});let o;try{o=fe(e,t,{stdio:["ignore","pipe","pipe"],env:C()})}catch(c){return s({ok:!1,code:-1,error:c.message})}n.child=o;let a="";const d=c=>{a+=String(c);const m=a.split(/\r?\n|\r/);a=m.pop();for(const w of m)N(n,w)};o.stdout?.on("data",d),o.stderr?.on("data",d);const u=setTimeout(()=>{try{o.kill("SIGTERM")}catch{}},i);u.unref?.(),o.on("error",c=>{clearTimeout(u),n.child=null,s({ok:!1,code:-1,error:c.message})}),o.on("exit",c=>{clearTimeout(u),n.child=null,a&&N(n,a),s({ok:c===0&&!n.cancelled,code:c,...n.cancelled?{error:"cancelled"}:{}})})}),Fe={install:Promise.resolve(),build:Promise.resolve()},$e={install:0,build:0},He=(n,e,t)=>{$e[n]>0&&(e.waiting=!0,N(e,`waiting for the other ${n} to finish first — one at a time`)),$e[n]++;const i=Fe[n];let s;const o=new Promise(a=>{s=a});return Fe[n]=i.then(()=>o),i.then(async()=>{e.waiting&&(N(e,"the other one finished — going"),e.waiting=!1);try{return await t()}finally{$e[n]--,s()}})},De=async(n,e)=>(await k(n,["image","exists",e],{timeout:2e4})).ok;async function Sn(n,e,t,i){const s=e?.image||t.image;if(await De(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,N(i,`pulling ${m}`),(await se(i,n,["pull",m])).ok)return m!==s&&await k(n,["tag",m,s],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const d=e?.recipe?tt[e.recipe]:null;if(!d)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const u=v.join(x,"images",e.recipe);return te(u,{recursive:!0,mode:448}),le(v.join(u,"Dockerfile"),d.dockerfile,{mode:384}),i.kind="build-image",i.detail=s,i.minutes=d.minutes,N(i,`no registry has ${s} for this machine — building it here (about ${d.minutes} minutes)`),E(`[runtime] building ${s} from the ${e.recipe} recipe in ${u}`),(await He("build",i,()=>se(i,n,["build","-t",s,"-f",v.join(u,"Dockerfile"),u]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function je(n,e){const t=y(n);if(!t||Q(n,t))return{ok:!0};if(/\.gguf$/i.test(t))return{ok:!1,error:`no such file: ${t}`};e.kind="pull-model",e.detail=t;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 it(t,{root:K(),fetchImpl:B,onProgress:i}):await rt(t,{root:K(),fetchImpl:B,onProgress:i}),{ok:!0}}catch(s){return{ok:!1,error:`pull ${t}: ${s.message}`}}}async function An(n,e,t){const i=[];return n.kind!=="native"&&e&&!await De(e,t?.image||n.image)&&i.push("image"),n.pull&&n.model&&!Q(n,y(n))&&i.push("model"),i}async function Xe(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&p!=="linux"){const t=await k("podman",["machine","inspect","--format","{{.Resources.Memory}}"],{timeout:8e3}),i=parseInt(t.out,10);return t.ok&&i>0?i:0}if(n==="docker"&&p!=="linux"){const t=await k("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(t.out,10);return t.ok&&i>0?Math.round(i/1048576):0}return Math.round(Ce()/1048576)}async function M(){const n={};for(const t of de){const i=await k(t,["--version"],{timeout:5e3});if(!i.ok){n[t]={installed:!1};continue}const s=(i.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||i.out;let o=!1,a=null;if(t==="podman")if(p==="linux")o=(await k("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const d=await k("podman",["machine","list","--format","json"],{timeout:8e3});try{const c=JSON.parse(d.out||"[]")[0]||null;a=c?{name:c.Name,running:!!c.Running}:null,o=!!c?.Running}catch{a=null}}else o=(await k("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[t]={installed:!0,version:s,running:o,...t==="podman"&&p!=="linux"?{machine:a}:{}}}const e=de.find(t=>n[t]?.installed&&n[t].running)||de.find(t=>n[t]?.installed)||null;return{...n,preferred:e,...e?{}:{install:Ne(p)}}}async function ve(n="podman"){if(!de.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await M())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:Ne(p)};if(e.running)return{ok:!0,already:!0};if(n==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(p!=="linux"){if(!e.machine){const i=await k("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const t=await k("podman",["machine","start"],{timeout:3e5});if(!t.ok&&!/already running/i.test(t.err))return{ok:!1,error:`podman machine start: ${t.err||t.out}`}}return{ok:!0}}async function We(){const n=await M(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await k("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(s=>mn(s,"podman"))}catch{return[]}}const t=await k("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return t.ok?t.out.split(`
|
|
5
|
+
`).filter(Boolean).map(i=>{try{return mn(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Je(n,e){const t=await k(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return t.ok?/running/i.test(t.out)?"running":"stopped":"absent"}async function Se(n,e){const t=await k(n,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!t.ok){for(const o of e)i[o]="absent";return i}const s=new Map(t.out.split(`
|
|
6
|
+
`).map(o=>o.split(" ")).filter(o=>o[0]).map(([o,a])=>[o,/running/i.test(a||"")?"running":"stopped"]));for(const o of e)i[o]=s.get(o)||"absent";return i}const A=n=>`http://127.0.0.1:${n.port}`;async function ze(){const n=await M(),e=n.preferred,t=await Xe(e,n),i={},s=await T(e),o=e&&n[e].running?await Se(e,X.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of X){const d=A(a);let u="no-engine";a.kind==="native"?u=we(a):e&&n[e].running?u=o[a.container]||"absent":e&&(u="engine-stopped");const c=a.model?y(a):null,m=a.engineOf?a.engineOf(s):null,w=a.kind==="native"?(s.ramGB||0)*1024:t;i[a.id]={...gt(a),engine:a.kind==="native"?"host":e,state:u,url:d,configured:a.configured(r),answering:u==="running"?await a.answers(d,B):!1,...a.helper?{asleep:R.has(a.id),idleMinutes:Ze()/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"&&!G(a)?{why:`${a.label} runs on ${ie(a)} only`}:{},...a.auto&&u!=="running"&&G(a)?{auto:!0,...be(a)?{why:"Stopped here — Start turns it back on"}:O[a.id]?{why:O[a.id]}:{}}:a.auto?{auto:!0}:{},...!a.auto&&a.kind==="native"&&u!=="running"&&G(a)&&O[a.id]?{why:O[a.id]}:{},...a.kind==="native"&&j[a.id]?{sandbox:j[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}}:{},...z(a)?{profiles:an(a.id,r.runtime?.services?.[a.id]?.tunings,I(a,c,m,s)),docs:nt[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:$n(a,s)}:{},...a.model?{model:c,default:a.model,models:nn(a.id,{active:c,engineRamMB:w,engine:a.kind==="native"?"host":e,platform:p,installed:g=>Q(a,g)}),machine:{engineRamMB:w}}:{},...z(a)?{tunings:rn(a.id,r.runtime?.services?.[a.id]?.tunings,I(a,c,m,s))}:{}}}return i}async function Mn(){const n=await M(),e=await T(n.preferred);return{platform:p,arch:H,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:qn(e)}}function Ke(n,{settingsFile:e=null,secret:t=null,pick:i=null,cpus:s=null}={}){const o=ee(n),a=["run","-d","--name",o.container,"--restart","no","-p",`127.0.0.1:${o.port}:${o.containerPort}`];o.helper&&s&&a.push("--cpus",String(s));for(const u of o.volumes?o.volumes(x):[])a.push("-v",u);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const u of o.env?o.env(o):[])a.push("-e",u);o.helper&&s&&a.push("-e",`THREADS=${s}`),t&&a.push("-e",`SEARXNG_SECRET=${t}`,"-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 d=Jn("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=${d}`),{args:a,hash:d}}const Ae={};async function _n(n){if(Ae[n]==null){const e=await k(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),t=Number.parseInt(e.out,10);Ae[n]=Number.isFinite(t)&&t>0?t:V.cpus()?.length||2}return Math.max(1,Math.floor(Ae[n]/2))}async function Qe(n,{force:e=!1}={}){const t=_(n);if(!t)return{ok:!1,error:`unknown service ${n}`};R.delete(t.id),xe(t.id),t.auto&&be(t)&&Te(t,!1);const i=b[t.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let s=null;if(t.kind!=="native"){const c=await M();if(s=c.preferred,!s)return{ok:!1,error:"no container engine — install Podman first",install:Ne(p)};if(!c[s].running){const m=await ve(s);if(!m.ok)return m}}else if(!G(t))return{ok:!1,error:`${t.label} runs on ${ie(t)} only`};const o=await T(s),a=t.engineOf?t.engineOf(o):null;if(t.kind==="native"&&!await L(t.runner,t.runnerCheck))return{ok:!1,error:Re(t,a?.install),install:a?.install};if(t.model&&/\.gguf$/i.test(y(t))&&!Pe(y(t)))return{ok:!1,error:`no such file: ${y(t)}`};if(t.kind==="native"&&t.model&&!e){const c=await Ue(t.id);if(c.live&&!c.fits)return{ok:!1,error:c.advice,plan:c}}const d=await An(t,s,a);if(!d.length){if(delete b[t.id],t.kind!=="native")return Me(t,s);const c=await oe(t);return c.ok?delete O[t.id]:O[t.id]=c.error,c}const u=ye(t,d[0]==="image"?"pull-image":"pull-model",{detail:d[0]==="image"?a?.image||t.image:y(t)});return u.then=(async()=>{try{if(d.includes("image")){const m=await Sn(s,a,t,u);if(!m.ok)throw new Error(m.error)}if(d.includes("model")){const m=await je(t,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=t.label;const c=t.kind==="native"?await oe(t):await Me(t,s);if(!c.ok)throw new Error(c.error);u.done=!0,u.result=c,E(`[runtime] ${t.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(c){u.done=!0,u.error=u.cancelled?"cancelled":c.message,E(`[runtime] ${t.label}: ${u.error}`)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function xn(n){const e=_(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const t=b[e.id];if(!t||t.done)return{ok:!0,nothing:!0};if(t.cancelled=!0,t.child){try{t.child.kill("SIGTERM")}catch{}const i=t.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return N(t,"cancelled"),E(`[runtime] ${e.label}: job cancelled (${t.kind})`),{ok:!0,cancelled:t.kind}}async function Me(n,e){let t=await Je(e,n.container);const i=n.helper?await _n(e):null,s=n.engineOf?n.engineOf(await T(e)):null,o=n.id==="searxng"?v.join(x,"searxng-settings.yml"):null,a=Ke(n,{settingsFile:o,secret:n.id==="searxng"?"x":null,pick:s,cpus:i});if(t!=="absent"){const c=await k(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!c.ok||c.out!==a.hash)&&(E(`[runtime] ${n.label}: made with older settings — re-creating it`),await k(e,["rm","-f",n.container],{timeout:6e4}),t="absent")}if(t!=="running")if(t==="stopped"){const c=await k(e,["start",n.container],{timeout:6e4});if(!c.ok)return{ok:!1,error:`${e} start: ${c.err||c.out}`}}else{te(x,{recursive:!0,mode:448});let c=null;n.id==="searxng"&&(le(o,bt(String(r.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),c=Wn(32).toString("hex")),n.volumes&&te(v.join(x,q),{recursive:!0,mode:448});const{args:m}=Ke(n,{settingsFile:o,secret:c,pick:s,cpus:i});E(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const w=await k(e,m,{timeout:6e5});if(!w.ok)return{ok:!1,error:`${e} run: ${w.err||w.out}`}}const d=A(n);let u=!1;for(let c=0;c<30&&!u;c++)u=await n.answers(d,B),u||await pe(1e3);return n.configure(r,d,ee(n)),h(),{ok:!0,url:d,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:y(n)}:{}}}async function En(n){const e=_(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(R.delete(e.id),delete _e[e.id],e.auto&&Te(e,!0),e.kind==="native")return Ie(e);const t=await M(),i=t.preferred;if(i&&t[i].running){const s=await k(i,["stop",e.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${i} stop: ${s.err||s.out}`}}return e.unconfigure(r,A(e)),h(),{ok:!0}}async function Pn(n,e){const t=_(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!t.model)return{ok:!1,error:`${t.label} takes no model`};const i=String(e||"").trim();if(!zn(n,i))return{ok:!1,error:`not a model id: ${JSON.stringify(e)} — pick one from the list, or a Hugging Face id like owner/name`};const s=await M(),o=s.preferred,a=t.kind==="native"?((await ke()).ramGB||0)*1024:await Xe(o,s),d=nn(n,{active:i,engineRamMB:a,engine:t.kind==="native"?"host":o,platform:p,installed:m=>Q(t,m)}).find(m=>m.id===i);if(d?.unavailable)return{ok:!1,error:`${i} ${d.unavailable}`};r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{},r.runtime.services[n]={...r.runtime.services[n]||{},model:i};const u=A(t);t.configured(r)===u&&t.configure(r,u,ee(t)),h();const c=await Ve(t,o,s);return c.ok?{ok:!0,model:i,restarted:c.restarted,...d?.ramNote?{note:d.ramNote}:{}}:c}async function Ve(n,e,t){if(n.kind==="native"){if(we(n)!=="running")return{ok:!0,restarted:!1};Ie(n);const o=await oe(n);return o.ok?{ok:!0,restarted:!0}:o}if(!e||!t[e].running)return{ok:!0,restarted:!1};const i=await Je(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const s=await k(e,["rm","-f",n.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${e} rm: ${s.err||s.out}`};if(i==="running"){const o=await Qe(n.id);return o.ok?{ok:!0,restarted:!0}:o}return{ok:!0,restarted:!1}}async function On(n,e){const t=_(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!z(t))return{ok:!1,error:`${t.label} takes no profile`};const i=await M(),s=await T(i.preferred),o=t.engineOf?t.engineOf(s):null,a=an(t.id,r.runtime?.services?.[n]?.tunings,I(t,y(t),o,s)).find(u=>u.id===e);if(!a)return{ok:!1,error:`no profile ${JSON.stringify(e)} — one of speed, coding, long, xl`};if(!a.fits)return{ok:!1,error:`${a.label}: ${a.why}`};const d=await qe(n,a.patch);return d.ok?{...d,profile:a.id}:d}async function Nn(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(!G(e))return{ok:!1,error:`${e.label} runs on ${ie(e)} only`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(delete ae[e.runner],delete W[e.runner],await L(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const s=e.engineOf(await T(null))?.install;if(!s?.steps?.length)return{ok:!1,error:`no installer for ${e.label} on this platform${s?.url?` — see ${s.url}`:""}`,install:s||null};const o=ye(e,"install",{detail:e.runner});return o.then=He("install",o,async()=>{const a=async c=>{for(const[m,...w]of c){N(o,`$ ${m} ${w.join(" ")}`);let g=await se(o,m,w,{timeout:36e5});for(let $=0;!g.ok&&!o.cancelled&&$<6&&o.lines.some(U=>/already locked|Please wait for it to finish/i.test(U));$++)N(o,`another ${m} holds the lock — waiting 20 s (${$+1}/6)`),await pe(2e4),g=await se(o,m,w,{timeout:36e5});if(!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let d=await a(s.steps);!d.ok&&!o.cancelled&&s.fallback?.length&&(N(o,`${d.error} — trying the other way`),d=await a(s.fallback)),delete ae[e.runner],delete W[e.runner];const u=d.ok&&await L(e.runner,e.runnerCheck);o.done=!0,o.cancelled?o.error="cancelled":d.ok?u||(o.error=`${e.runner} still not found after the install — open a new terminal and run \`${s.command}\` by hand`):o.error=`install failed: ${d.error}${o.lines.length?` (${o.lines.slice(-2).join(" | ")})`:""}`,E(`[runtime] install ${e.runner}: ${o.error||"ok"}`)}),{ok:!0,pending:{kind:o.kind,since:o.since,detail:o.detail}}}async function Bn(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 t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Q(e,y(e)))return{ok:!0,installed:!0,model:y(e)};const i=ye(e,"pull-model",{detail:y(e)});return i.then=(async()=>{const s=await je(e,i);i.done=!0,s.ok||(i.error=s.error)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function qe(n,e){const t=_(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!z(t))return{ok:!1,error:`${t.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await M(),s=i.preferred,o=y(t),a=await T(s),d=t.engineOf?t.engineOf(a):null,u=et(t.id,r.runtime?.services?.[n]?.tunings,e,I(t,o,d,a));if(u.error)return{ok:!1,error:u.error};r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{},r.runtime.services[n]={...r.runtime.services[n]||{},tunings:u},h();const c=await Ve(t,s,i);return c.ok?{ok:!0,tunings:rn(t.id,u,I(t,o,d,a)),restarted:c.restarted}:c}async function Cn(){const n=await M(),e=n.preferred,t=e&&n[e].running?await Se(e,X.filter(o=>o.kind!=="native").map(o=>o.container)):{},i={};let s=!1;return await Promise.all(X.map(async o=>{const a=o.kind==="native"?we(o):e&&n[e].running?t[o.container]||"absent":"no-engine";i[o.id]=a==="running"&&await o.answers(A(o),B)?"up":"down";const d=(o.provides||[]).some(u=>["embedded","none"].includes(r.capabilities?.[u]?.provider));i[o.id]==="up"&&o.configure&&!d&&o.configured(r)!==A(o)&&(o.configure(r,A(o),ee(o)),s=!0)})),s&&h(),i}function Ye(n){const e=_(n);if(e?.window)return e.window;if(!e||!z(e))return null;const t=Number(on(e.id,r.runtime?.services?.[n]?.tunings,I(e,y(e),null,{})).maxModelLen);return Number.isFinite(t)&&t>0?t:null}function Ln(n){const e=_(n);if(e?.card)return e.card;if(!e||!z(e))return null;const t=y(e),i=on(e.id,r.runtime?.services?.[n]?.tunings,I(e,t,null,{})),s=ue(e.id).find(a=>a.id===t)||null,o=e.id==="vllm"?re(t):"chat";return{engine:e.id,backend:j[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 Rn=10,Ze=()=>{const n=Number(r.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:Rn)*6e4},Tn=Y(),_e={},R=new Set,ne={};function xe(n){_e[n]=Y()}async function Gn(n,{force:e=!1}={}){const t=_(n);if(!t||!t.helper)return{ok:!0};if(xe(t.id),!R.has(t.id)&&!e){const i=t.container&&t.configured?.(r)?(await We()).find(s=>s.name===t.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};R.add(t.id)}return ne[t.id]||(ne[t.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 ve(s);if(!a.ok)return a}const o=await Me(t,s);return o.ok&&(R.delete(t.id),E(`[runtime] ${t.label}: woken for a request`)),o})().finally(()=>{delete ne[t.id]})),ne[t.id]}async function en(){const n=Ze();if(!n)return[];const e=X.filter(a=>a.helper&&a.configured(r)&&!R.has(a.id)&&!ne[a.id]&&!(b[a.id]&&!b[a.id].done)&&Y()-(_e[a.id]??Tn)>=n);if(!e.length)return[];const t=await M(),i=t.preferred;if(!i||!t[i].running){for(const a of e)R.add(a.id);return e.map(a=>a.id)}const s=await Se(i,e.map(a=>a.container)),o=[];for(const a of e){if(s[a.container]==="running"){if(!(await k(i,["stop",a.container],{timeout:6e4})).ok)continue;E(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}R.add(a.id),o.push(a.id)}return o}return Le&&Le(()=>{en().catch(n=>E(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:xe,wake:Gn,sweepIdle:en,health:Cn,contextWindow:Ye,modelCard:Ln,async status(){const[n,e,t,i,s]=await Promise.all([l().catch(()=>null),M(),ze(),We(),Mn()]);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:t}},startEngine:ve,startService:Qe,stopService:En,ensureDefaults:wn,revive:bn,plan:Ue,setModel:Pn,setTunings:qe,setProfile:On,pullModel:Bn,installRunner:Nn,cancelJob:xn,services:ze,catalogFor:ue}}export{kt as SEARXNG_DEFAULT_ENGINES,X as SERVICES,mn as containerRow,Gt as createRuntime,Ne as installDoor,bt as searxngSettings};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{readFileSync as O,writeFileSync as j,mkdirSync as A,chmodSync as E}from"node:fs";import{dirname as I}from"node:path";import{normalizeSandboxConfig as u,sandboxEnvFor as N,sandboxProblems as F,configPath as J}from"./configstore.js";const z=`usage: chatpanel-gateway sandbox status
|
|
2
|
+
chatpanel-gateway sandbox allow <agent> <sign-in…> let an agent use a sign-in (aws, oci, gcloud, azure)
|
|
3
|
+
chatpanel-gateway sandbox disallow <agent> <sign-in…>
|
|
4
|
+
chatpanel-gateway sandbox outside <agent> on|off run one agent outside the sandbox
|
|
5
|
+
chatpanel-gateway sandbox install Windows: the one-time sandbox account`;function C(n={},e,a){const r=Array.isArray(n.signIn)?n.signIn:[];if(e==="allow")return{...n,signIn:[...new Set([...r,...a])]};if(e==="disallow")return{...n,signIn:r.filter(i=>!a.includes(i))};const{outside:s,...o}=n;return a[0]==="on"?{...o,outside:!0}:o}function P(n,e,{read:a=O,write:r=j}={}){let s={};try{s=JSON.parse(a(n,"utf8"))}catch(i){if(i?.code!=="ENOENT")throw new Error(`cannot read ${n}: ${i.message}`)}const o=u(s.sandbox);s.sandbox=u({...o,agents:{...o.agents||{},...e}},{strict:!0}),A(I(n),{recursive:!0,mode:448}),r(n,JSON.stringify(s,null,2),{mode:384});try{E(n,384)}catch{}}async function U(n,{cfg:e,env:a=process.env,token:r="",fetchImpl:s=fetch,local:o,path:i=J(a),out:w=console.log,err:c=console.error,patch:x=P}={}){const[g="status",l,...f]=n,b=()=>{for(const t of F(e,a))c(`⚠ ${t}`)};if(g==="install")return o(n);if(g==="status"){const t=String(e?.bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"");let d=null;try{d=(await(await s(`${t}/health`,{signal:AbortSignal.timeout(1500)})).json())?.sandbox||null}catch{}if(d)return w(JSON.stringify(d,null,2)),b(),0;c(`(no bridge answers at ${t} — this is what the config gives the next one)`),Object.assign(a,N(e,a));const $=await o(["status"]);return b(),$}if(!["allow","disallow","outside"].includes(g)||!l||!f.length||g==="outside"&&!["on","off"].includes(f[0]))return c(z),2;const p=u(e?.sandbox).agents?.[l]||{},h={[l]:C(p,g,f.map(t=>t.toLowerCase()))};try{u({agents:h},{strict:!0})}catch(t){return c(t.message),2}const y=u({agents:h}).agents?.[l]||{},m=`${l}: ${[y.signIn?.length?`may sign in with ${y.signIn.join(", ")}`:"no sign-ins",y.outside?"runs OUTSIDE the sandbox":"runs inside the sandbox"].join("; ")}`,S=`http://127.0.0.1:${e?.port||4320}`;if(r)try{const t=await s(`${S}/config`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r}`},body:JSON.stringify({sandbox:{agents:h}}),signal:AbortSignal.timeout(5e3)});if(t.ok)return w(`${m}
|
|
6
|
+
Applied to the running gateway — its agents restart with the new setting.`),0;const d=await t.json().catch(()=>({}));if(t.status===400)return c(d.error||"the gateway refused the change"),2}catch{}try{x(i,h)}catch(t){return c(`could not save ${i}: ${t.message}`),1}return w(`${m}
|
|
7
|
+
Saved to ${i} — no gateway answered, so it takes effect when one starts (chatpanel-gateway --install).`),0}export{C as nextAgentGrant,U as sandboxCommand};
|