@chatpanel/gateway 0.75.0 → 0.85.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/router.js CHANGED
@@ -1 +1 @@
1
- import{secureFetch as j}from"./secure-fetch.js";import{readBridgeToken as k,resolveBridgeUrl as S}from"./bridge.js";import{reachOfGatewayModel as M,agentModelReach as U}from"@chatpanel/events/model-candidates.js";const C=["codex","claude","opencode","pi","kiro","antigravity"];function b(e){const o=(Array.isArray(e.destinations)?e.destinations:[]).filter(Boolean),s=new Set(o.map(t=>t.id)),i=[...o.filter(t=>t.type==="agent"),...C.filter(t=>!s.has(t)).map(t=>({id:t,type:"agent",agent:t,models:[t]})),...o.filter(t=>t.type!=="agent")];return e.backend==="api"&&!o.some(t=>t.type==="api")&&(i.push({id:"openai",type:"api",protocol:"openai",baseUrl:e.upstreams?.openai?.baseUrl,models:[]}),i.push({id:"anthropic",type:"api",protocol:"anthropic",baseUrl:e.upstreams?.anthropic?.baseUrl,models:[]})),i}function G(e,o,s,{destination:i="",down:t=()=>!1}={}){const r=b(o),c=s==="anthropic",l=a=>(c?a.protocol==="anthropic":a.protocol!=="anthropic")&&!t(a);return i?r.find(a=>a.id===i)||null:e&&r.find(a=>Array.isArray(a.models)&&a.models.includes(e))||e&&r.find(a=>a.id===e||a.agent===e)||e&&e.includes("/")&&r.find(a=>a.type==="agent"&&(a.agent===e.slice(0,e.indexOf("/"))||a.id===e.slice(0,e.indexOf("/"))))||e&&L(e,r,l)||r.find(a=>o.backend==="bridge"?a.type==="agent":a.type==="api"&&l(a))||r.find(a=>(o.backend==="bridge"?a.type==="agent":a.type==="api")&&!t(a))||r.find(a=>!t(a))||null}function O(e){return e.type==="agent"?{api:"agent",endpoints:["/v1/chat/completions"]}:e.protocol==="anthropic"?{api:"anthropic",endpoints:["/v1/messages"]}:{api:"openai",endpoints:["/v1/chat/completions","/v1/responses"]}}const T=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;function x(e){if(!e||e.type==="agent")return"";const o=String(e.baseUrl||"");return o?T.test(o)||e.apiKey||e.hasKey?"":`no API key is saved for ${e.id}`:"no endpoint URL is set for this provider"}function B(e){const o=[],s=new Set,i=(t,r,c)=>{if(!t||s.has(t))return;s.add(t);const l=O(c),a=x(c);o.push({id:t,object:"model",owned_by:r,...a?{configured:!1,reason:a}:{},provider:c.id,provider_type:c.type==="agent"?"agent":c.protocol==="anthropic"?"anthropic":"openai",api:l.api,endpoints:l.endpoints,reach:M({id:t,owned_by:r,provider_type:c.type==="agent"?"agent":"openai"},c)})};for(const t of b(e))if(t.type==="agent")for(const r of t.models?.length?t.models:[t.id])i(r,"chatpanel-bridge",t);else for(const r of t.models||[])i(r,t.id,t);return{object:"list",data:o}}async function K(e,o,s){const i=await S(e);if(!i||!o)return new Map;const t=k(e.bridge?.token),r=[...o.entries()].filter(([,l])=>l).map(([l])=>l),c=new Map;return await Promise.all(r.map(async l=>{try{const a=await fetch(`${i}/list-models`,{method:"POST",headers:{"content-type":"application/json",...t?{Authorization:`Bearer ${t}`}:{}},body:JSON.stringify({agent:l}),signal:AbortSignal.timeout(s)});if(!a.ok)return;const d=await a.json(),w=(Array.isArray(d?.models)?d.models:[]).map(n=>typeof n=="string"?n:n?.id||n?.name||"").map(n=>String(n).trim()).filter(Boolean);w.length&&c.set(l,w.slice(0,40))}catch{}})),c}async function N(e,o){const s=await S(e);if(!s)return null;try{const i=k(e.bridge?.token),t=await fetch(`${s}/health`,{headers:{Accept:"application/json",...i?{Authorization:`Bearer ${i}`}:{}},signal:AbortSignal.timeout(o)});if(!t.ok)return null;const r=await t.json();if(!Array.isArray(r?.agents))return null;const c=new Map(r.agents.map(l=>[l.id,!!l.available]));return c.noTools=new Set(r.agents.filter(l=>l.tools===!1).map(l=>l.id)),c}catch{return null}}const D=Number(process.env.CHATPANEL_MODELS_CACHE_MS)||6e4;let p={at:0,key:"",value:null,inflight:null};function E(e){try{return JSON.stringify([b(e).map(o=>[o.id,o.type,o.baseUrl,o.models]),e.bridge?.url||""])}catch{return String(Date.now())}}function I(){p={at:0,key:"",value:null,inflight:null}}function J(e,o){const s=String(o||"");if(!e||e.type!=="agent"||!s)return!1;const i=s.includes("/")?s.slice(0,s.indexOf("/")):s;return Array.isArray(e.models)&&e.models.includes(s)||e.id===s||e.agent===s||e.id===i||e.agent===i}function L(e,o,s){const i=(p.value?.data||[]).find(t=>t?.id===e&&t.owned_by!=="chatpanel-bridge");return i&&o.find(t=>t.id===i.owned_by&&t.type==="api"&&s(t))||null}async function W(e,o){if(!p.value)try{await P(e,o)}catch{}}async function P(e,{timeoutMs:o=4e3,fresh:s=!1,now:i=Date.now,serviceHealth:t=null}={}){const r=E(e),c=p.value&&p.key===r,l=!c||i()-p.at>D;if(c&&!s&&!l)return p.value;const a=()=>(p.inflight||(p.inflight=R(e,{timeoutMs:o,serviceHealth:t}).then(d=>(p={at:i(),key:r,value:d,inflight:null},d)).catch(d=>{throw p.inflight=null,d})),p.inflight);return c&&!s?(a().catch(()=>{}),p.value):a()}async function R(e,{timeoutMs:o=4e3,serviceHealth:s=null}={}){const i=B(e),t=new Set(i.data.map(n=>n.id)),r=s?await s():null,c=new Map(b(e).filter(n=>n.service).map(n=>[n.id,n.service])),l=n=>{if(c.get(n.owned_by)&&r){const y=r(n.owned_by);y!=="unknown"&&(n.available=y==="up");const f=typeof r.window=="function"?r.window(n.owned_by):null;f&&(n.context_window=f);const u=typeof r.card=="function"?r.card(n.owned_by):null;u&&(n.card=u)}return n};for(const n of i.data)l(n);const a=await N(e,o);if(a){i.data=i.data.filter(n=>n.owned_by!=="chatpanel-bridge"||a.get(n.id)!==!1);for(const n of i.data)n.owned_by==="chatpanel-bridge"&&(n.available=a.get(n.id)??!1,a.noTools?.has(n.id)&&(n.tools=!1))}const d=await K(e,a,o);for(const[n,h]of d){const y=i.data.find(f=>f.id===n);if(y)for(const f of h){const u=`${n}/${f}`;t.has(u)||(t.add(u),i.data.push({...y,id:u,model:f,available:!0,reach:U(f)}))}}const w=b(e).filter(n=>n.type==="api"&&n.baseUrl);return await Promise.all(w.map(async n=>{const h=new AbortController,y=setTimeout(()=>h.abort(),o);try{const f={"content-type":"application/json"};n.apiKey&&(n.protocol==="anthropic"?(f["x-api-key"]=n.apiKey,f["anthropic-version"]="2023-06-01"):f.authorization=`Bearer ${n.apiKey}`);const u=await j(`${n.baseUrl.replace(/\/$/,"")}/models`,{headers:f,signal:h.signal});if(!u.ok)return;const m=await u.json(),$=Array.isArray(m?.data)?m.data:Array.isArray(m?.models)?m.models:[];for(const v of $){const g=typeof v=="string"?v:v?.id;if(g&&!t.has(g)){t.add(g);const A=O(n),_=x(n);i.data.push(l({id:g,object:"model",owned_by:n.id,provider:n.id,provider_type:n.protocol==="anthropic"?"anthropic":"openai",api:A.api,endpoints:A.endpoints,..._?{configured:!1,reason:_}:{},reach:M({id:g,owned_by:n.id},n)}))}}}catch{}finally{clearTimeout(y)}})),i}export{J as agentOwnsModel,B as aggregateModels,P as aggregateModelsAsync,W as ensureModelCatalog,b as listDestinations,I as resetModelsCache,G as resolveDestination};
1
+ import{secureFetch as T}from"./secure-fetch.js";import{readBridgeToken as O,resolveBridgeUrl as x}from"./bridge.js";import{reachOfGatewayModel as B,agentModelReach as K}from"@chatpanel/events/model-candidates.js";import{localModelCard as N,reachByCard as D}from"@chatpanel/events/local-engine.js";import{loopbackRoot as k}from"./local-engine-probe.js";const E=["codex","claude","opencode","pi","kiro","antigravity"];function w(e){const a=(Array.isArray(e.destinations)?e.destinations:[]).filter(Boolean),i=new Set(a.map(t=>t.id)),l=[...a.filter(t=>t.type==="agent"),...E.filter(t=>!i.has(t)).map(t=>({id:t,type:"agent",agent:t,models:[t]})),...a.filter(t=>t.type!=="agent")];if(e.backend==="api"&&!a.some(t=>t.type==="api")){const t=r=>({...r?.redact===!0?{redact:!0}:{},...r?.local===!0?{local:!0}:{}});l.push({id:"openai",type:"api",protocol:"openai",baseUrl:e.upstreams?.openai?.baseUrl,models:[],...t(e.upstreams?.openai)}),l.push({id:"anthropic",type:"api",protocol:"anthropic",baseUrl:e.upstreams?.anthropic?.baseUrl,models:[],...t(e.upstreams?.anthropic)})}return l}function Y(e,a,i,{destination:l="",down:t=()=>!1}={}){const r=w(a),c=i==="anthropic",s=o=>(c?o.protocol==="anthropic":o.protocol!=="anthropic")&&!t(o);return l?r.find(o=>o.id===l)||null:e&&r.find(o=>Array.isArray(o.models)&&o.models.includes(e))||e&&r.find(o=>o.id===e||o.agent===e)||e&&e.includes("/")&&r.find(o=>o.type==="agent"&&(o.agent===e.slice(0,e.indexOf("/"))||o.id===e.slice(0,e.indexOf("/"))))||e&&F(e,r,s)||r.find(o=>a.backend==="bridge"?o.type==="agent":o.type==="api"&&s(o))||r.find(o=>(a.backend==="bridge"?o.type==="agent":o.type==="api")&&!t(o))||r.find(o=>!t(o))||null}function U(e){return e.type==="agent"?{api:"agent",endpoints:["/v1/chat/completions"]}:e.protocol==="anthropic"?{api:"anthropic",endpoints:["/v1/messages"]}:{api:"openai",endpoints:["/v1/chat/completions","/v1/responses"]}}const L=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;function j(e){if(!e||e.type==="agent")return"";const a=String(e.baseUrl||"");return a?L.test(a)||e.apiKey||e.hasKey?"":`no API key is saved for ${e.id}`:"no endpoint URL is set for this provider"}function _(e,a,i,l){const t=B({id:e,owned_by:a,provider_type:i.type==="agent"?"agent":"openai"},i);if(i.type==="agent")return{reach:t};const r=!!k(i.baseUrl),c=D({dest:i,loopback:r,card:N(l,e),otherwise:t});return{reach:c.reach,...r?{reach_why:c.why,...c.engine?{engine:c.engine}:{}}:{}}}function P(e){const a=[],i=new Set,l=(t,r,c)=>{if(!t||i.has(t))return;i.add(t);const s=U(c),o=j(c);a.push({id:t,object:"model",owned_by:r,...o?{configured:!1,reason:o}:{},provider:c.id,provider_type:c.type==="agent"?"agent":c.protocol==="anthropic"?"anthropic":"openai",api:s.api,endpoints:s.endpoints,..._(t,r,c,null)})};for(const t of w(e))if(t.type==="agent")for(const r of t.models?.length?t.models:[t.id])l(r,"chatpanel-bridge",t);else for(const r of t.models||[])l(r,t.id,t);return{object:"list",data:a}}async function R(e,a,i){const l=await x(e);if(!l||!a)return new Map;const t=O(e.bridge?.token),r=[...a.entries()].filter(([,s])=>s).map(([s])=>s),c=new Map;return await Promise.all(r.map(async s=>{try{const o=await fetch(`${l}/list-models`,{method:"POST",headers:{"content-type":"application/json",...t?{Authorization:`Bearer ${t}`}:{}},body:JSON.stringify({agent:s}),signal:AbortSignal.timeout(i)});if(!o.ok)return;const g=await o.json(),f=(Array.isArray(g?.models)?g.models:[]).map(b=>typeof b=="string"?b:b?.id||b?.name||"").map(b=>String(b).trim()).filter(Boolean);f.length&&c.set(s,f.slice(0,40))}catch{}})),c}async function z(e,a){const i=await x(e);if(!i)return null;try{const l=O(e.bridge?.token),t=await fetch(`${i}/health`,{headers:{Accept:"application/json",...l?{Authorization:`Bearer ${l}`}:{}},signal:AbortSignal.timeout(a)});if(!t.ok)return null;const r=await t.json();if(!Array.isArray(r?.agents))return null;const c=new Map(r.agents.map(s=>[s.id,!!s.available]));return c.noTools=new Set(r.agents.filter(s=>s.tools===!1).map(s=>s.id)),c}catch{return null}}const H=Number(process.env.CHATPANEL_MODELS_CACHE_MS)||6e4;let d={at:0,key:"",value:null,inflight:null};function I(e){try{return JSON.stringify([w(e).map(a=>[a.id,a.type,a.baseUrl,a.models,a.service||"",a.local===!0,a.redact===!0]),e.bridge?.url||""])}catch{return String(Date.now())}}function Z(){d={at:0,key:"",value:null,inflight:null}}function ee(e,a){const i=String(a||"");if(!e||e.type!=="agent"||!i)return!1;const l=i.includes("/")?i.slice(0,i.indexOf("/")):i;return Array.isArray(e.models)&&e.models.includes(i)||e.id===i||e.agent===i||e.id===l||e.agent===l}function F(e,a,i){const l=(d.value?.data||[]).find(t=>t?.id===e&&t.owned_by!=="chatpanel-bridge");return l&&a.find(t=>t.id===l.owned_by&&t.type==="api"&&i(t))||null}async function te(e,a){if(!d.value)try{await G(e,a)}catch{}}async function G(e,{timeoutMs:a=4e3,fresh:i=!1,now:l=Date.now,serviceHealth:t=null,engineAt:r=null}={}){const c=I(e),s=d.value&&d.key===c,o=!s||l()-d.at>H;if(s&&!i&&!o)return d.value;const g=()=>(d.inflight||(d.inflight=J(e,{timeoutMs:a,serviceHealth:t,engineAt:r}).then(f=>(d={at:l(),key:c,value:f,inflight:null},f)).catch(f=>{throw d.inflight=null,f})),d.inflight);return s&&!i?(g().catch(()=>{}),d.value):g()}async function J(e,{timeoutMs:a=4e3,serviceHealth:i=null,engineAt:l=null}={}){const t=P(e),r=new Set(t.data.map(n=>n.id)),c=new Map;if(l){await Promise.all(w(e).filter(p=>p.type==="api"&&!p.service&&p.local!==!0&&p.redact!==!0&&k(p.baseUrl)).map(async p=>{const u=await l(k(p.baseUrl)).catch(()=>null);u&&c.set(p.id,u)}));const n=new Map(w(e).map(p=>[p.id,p]));for(const p of t.data){const u=n.get(p.provider);u&&c.has(u.id)&&Object.assign(p,_(p.id,p.owned_by,u,c.get(u.id)))}}const s=i?await i():null,o=new Map(w(e).filter(n=>n.service).map(n=>[n.id,n.service])),g=n=>{if(o.get(n.owned_by)&&s){const u=s(n.owned_by);u!=="unknown"&&(n.available=u==="up");const y=typeof s.window=="function"?s.window(n.owned_by):null;y&&(n.context_window=y);const h=typeof s.card=="function"?s.card(n.owned_by):null;h&&(n.card=h)}return n};for(const n of t.data)g(n);const f=await z(e,a);if(f){t.data=t.data.filter(n=>n.owned_by!=="chatpanel-bridge"||f.get(n.id)!==!1);for(const n of t.data)n.owned_by==="chatpanel-bridge"&&(n.available=f.get(n.id)??!1,f.noTools?.has(n.id)&&(n.tools=!1))}const b=await R(e,f,a);for(const[n,p]of b){const u=t.data.find(y=>y.id===n);if(u)for(const y of p){const h=`${n}/${y}`;r.has(h)||(r.add(h),t.data.push({...u,id:h,model:y,available:!0,reach:K(y)}))}}const C=w(e).filter(n=>n.type==="api"&&n.baseUrl);return await Promise.all(C.map(async n=>{const p=new AbortController,u=setTimeout(()=>p.abort(),a);try{const y={"content-type":"application/json"};n.apiKey&&(n.protocol==="anthropic"?(y["x-api-key"]=n.apiKey,y["anthropic-version"]="2023-06-01"):y.authorization=`Bearer ${n.apiKey}`);const h=await T(`${n.baseUrl.replace(/\/$/,"")}/models`,{headers:y,signal:p.signal});if(!h.ok)return;const v=await h.json(),$=Array.isArray(v?.data)?v.data:Array.isArray(v?.models)?v.models:[];for(const A of $){const m=typeof A=="string"?A:A?.id;if(m&&!r.has(m)){r.add(m);const S=U(n),M=j(n);t.data.push(g({id:m,object:"model",owned_by:n.id,provider:n.id,provider_type:n.protocol==="anthropic"?"anthropic":"openai",api:S.api,endpoints:S.endpoints,...M?{configured:!1,reason:M}:{},..._(m,n.id,n,c.get(n.id)||null)}))}}}catch{}finally{clearTimeout(u)}})),t}export{ee as agentOwnsModel,P as aggregateModels,G as aggregateModelsAsync,te as ensureModelCatalog,w as listDestinations,Z as resetModelsCache,Y as resolveDestination};
package/src/runtime.js CHANGED
@@ -1,5 +1,6 @@
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};
1
+ import{promisify as Rn}from"node:util";import{execFile as In}from"node:child_process";import{existsSync as Ee,mkdirSync as ne,writeFileSync as oe,accessSync as Un,openSync as Fn,closeSync as Hn,constants as Dn}from"node:fs";import{randomBytes as jn,createHash as Xn}from"node:crypto";import Q from"node:os";import v from"node:path";import{modelsFor as Ze,isValidModelId as Wn,catalogFor as se,vllmTaskOf as te}from"./runtime-models.js";import{pickInferenceEngine as en,pickLlamaEngine as Jn,pickMlxEngine as zn,pickAppleEngine as Kn,recommendEngine as Qn,detectAccelerator as Vn,hostShape as qn}from"./inference-engines.js";import{tuningArgs as le,tuningRows as nn,patchTunings as Yn,profilesFor as tn,resolveTunings as rn,ENGINE_DOCS as Zn}from"./engine-tunings.js";import{IMAGE_RECIPES as et}from"./images.js";import{pullRepo as nt,pullGguf as tt,repoInstalled as rt,ggufInstalled as an}from"./model-pull.js";import{liveFit as it,kvCacheMB as at,cachedConfigPath as ot,needMB as st}from"./host-memory.js";import{APPLE_HELPER as Pe,APPLE_MODEL_ID as lt,APPLE_MIN_DARWIN as ut,appleHelperDirs as ct,appleInstallDoor as dt,darwinMajor as on}from"./apple-model.js";import{spawn as mt}from"node:child_process";import{readFileSync as sn,unlinkSync as ln}from"node:fs";const ft=Rn(In),ue=["podman","docker"],V="hf-cache",j=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],helper:!0,blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only.",caps:["CHOWN","SETGID","SETUID"],answers:async(t,l)=>{try{return(await l(`${t}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.search?.searxng?.url||""),configure:(t,l)=>{t.search=t.search||{},t.search.searxng={...t.search.searxng||{},url:l}},unconfigure:(t,l)=>{t.search?.searxng?.url===l&&(t.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],helper:!0,adapter:"tei",model:"BAAI/bge-reranker-base",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. The gateway already reranks in-process by default (a small model, no container); start this to run a multilingual cross-encoder (bge-reranker base by default) in a container instead, behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.rerank?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.rerank={url:l,adapter:f.adapter,model:f.model,service:f.id}},unconfigure:(t,l)=>{t.capabilities?.rerank?.url===l&&delete t.capabilities.rerank}},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],helper:!0,adapter:"systemone",model:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. The gateway already decides in-process by default with the same algorithm and model; start this to run it in a container instead. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.decide?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.decide={url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}},unconfigure:(t,l)=>{t.capabilities?.decide?.url===l&&delete t.capabilities.decide}},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:t=>en({...t,containerOnly:!0}),container:"chatpanel-vllm",port:8891,containerPort:8e3,provides:["chat","embed","stt"],adapter:"openai",model:"Qwen/Qwen3-0.6B",pull:!0,blurb:"Your own model, served by vLLM on this machine’s accelerator (CUDA, ROCm, XPU — or CPU): a chat model the router can send turns to, an embedding model for semantic search, or a transcriber for every ear. OpenAI-shaped, loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${t.model}`,...t.installed?["HF_HUB_OFFLINE=1"]:[]],args:(t,l)=>["--model",t.model,"--host","0.0.0.0","--port","8000",...te(t.model)==="embed"?["--task","embed"]:[],...le("vllm",t.tunings,{task:te(t.model),model:t.model,backend:l?.backend||null})],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.embed?.service==="vllm"?t.capabilities.embed.url.replace(/\/v1$/,""):t.capabilities?.stt?.service==="vllm"?t.capabilities.stt.url.replace(/\/v1$/,""):(t.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{const h=`${l}/v1`,P=te(f.model);un(t),P==="chat"?(t.destinations=(t.destinations||[]).filter(p=>p?.service!=="vllm"&&p?.id!=="vllm"),t.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:h,models:[f.model],service:"vllm"})):P==="embed"?(t.capabilities=t.capabilities||{},t.capabilities.embed={url:h,adapter:"openai",model:f.model,service:"vllm"}):P==="transcription"&&(t.capabilities=t.capabilities||{},t.capabilities.stt={provider:"container",url:h,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:t=>un(t)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:t=>en(t),only:{platform:"darwin",arch:"arm64"},port:8892,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU, served by vLLM-Metal: a chat model the router can send turns to. A process on this machine behind the gateway, loopback only.",command:(t,l)=>["vllm",["serve",t.model,"--host","127.0.0.1","--port",String(t.port),...le("vllm-metal",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="vllm-metal"&&h?.id!=="vllm-metal"),t.destinations.push({id:"vllm-metal",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:t=>Jn(t),port:8893,provides:["chat"],adapter:"openai",model:"unsloth/Qwen3-4B-GGUF:Q4_K_M",blurb:"Your own GGUF model on this machine, served by llama.cpp: the Metal GPU on a Mac, CUDA or Vulkan elsewhere, CPU otherwise — a chat model the router can send turns to, with the flags that make it fast set for this machine. A process on this machine behind the gateway, loopback only.",alias:t=>/\.gguf$/i.test(t)?t.split(/[\\/]/).pop().replace(/\.gguf$/i,""):t.split("/").pop().split(":")[0],command:(t,l)=>["llama-server",[...t.file?["-m",t.file]:/\.gguf$/i.test(t.model)?["-m",t.model]:["-hf",t.model],"--host","127.0.0.1","--port",String(t.port),"--alias",t.alias(t.model),"--jinja",...le("llama",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="llama"&&h?.id!=="llama"),t.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:t=>zn(t),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU through MLX — Apple’s framework, the lightest way to run a chat model on a Mac. A process on this machine behind the gateway, loopback only.",command:(t,l)=>["mlx_lm.server",["--model",t.model,"--host","127.0.0.1","--port",String(t.port),...le("mlx",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="mlx"&&h?.id!=="mlx"),t.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}},{id:"apple",label:"Apple on-device",kind:"native",auto:!0,runner:Pe,engineOf:t=>Kn(t),only:{platform:"darwin",arch:"arm64",minDarwin:ut,label:"macOS 26 or later on Apple Silicon"},port:8895,provides:["chat"],adapter:"openai",window:4096,card:{engine:"apple",backend:"apple",where:"this machine",egress:"none",cost:"free",task:"chat",window:4096,vision:!1,tools:!1,reasoning:!1,label:"Apple on-device",licence:"Apple",draft:!1},blurb:"Apple’s own model, on this Mac (macOS 26 with Apple Intelligence on): the system loads it when asked and frees it when idle, so nothing stays loaded and nothing runs hot — the lightest choice for titles, topics and short answers. Text only, 4,096 tokens at a time. A small helper on this machine behind the gateway, loopback only.",command:t=>[Pe,["serve","--port",String(t.port)]],answers:async(t,l)=>{try{const f=await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)});return f.ok&&(await f.json())?.ok===!0}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="apple")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l)=>{t.destinations=(t.destinations||[]).filter(f=>f?.service!=="apple"&&f?.id!=="apple"),t.destinations.push({id:"apple",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[lt],service:"apple"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),re=t=>t.only?.label||`${t.only?.platform||"this platform"} ${t.only?.arch||""}`.trim();function un(t){Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),t.capabilities?.embed?.service==="vllm"&&delete t.capabilities.embed,t.capabilities?.stt?.service==="vllm"&&delete t.capabilities.stt}const x=t=>j.find(l=>l.id===t)||null,pt=({answers:t,configured:l,configure:f,unconfigure:h,volumes:P,args:p,env:U,caps:ce,command:de,engineOf:Ne,alias:N,..._})=>_,ht=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),gt=Object.freeze(["brave","qwant"]);function kt(t=[]){const l=t.length?t:ht,f=gt.filter(h=>!l.includes(h));return["# Written by chatpanel-gateway (Settings › Runtime). JSON on, the limiter off — the port is","# bound to 127.0.0.1, which is what makes that safe. Do not publish it on 0.0.0.0.","use_default_settings: true","general:",' instance_name: "ChatPanel search"'," debug: false"," enable_metrics: false","server:",' secret_key: "${SEARXNG_SECRET}"'," limiter: false"," public_instance: false"," image_proxy: false",' method: "GET"',"search:"," safe_search: 0",' autocomplete: ""'," formats:"," - html"," - json","ui:"," static_use_hash: true","engines:",...l.flatMap(h=>[` - name: ${h}`," disabled: false"]),...f.flatMap(h=>[` - name: ${h}`," disabled: true"]),""].join(`
2
+ `)}function Oe(t=process.platform){return t==="darwin"?{command:"brew install podman",url:"https://podman.io/docs/installation#macos",note:"Homebrew; then Start the engine below (it creates and starts the Podman machine)."}:t==="win32"?{command:"winget install RedHat.Podman",url:"https://podman.io/docs/installation#windows",note:"Then Start the engine below (it creates and starts the Podman machine under WSL)."}:{command:"sudo apt install podman # or: sudo dnf install podman",url:"https://podman.io/docs/installation#installing-on-linux",note:"Rootless; no daemon to start."}}function cn(t,l){const f=l==="podman"?Array.isArray(t.Names)?t.Names[0]:String(t.Names||""):String(t.Names||t.Name||""),h=l==="podman"?Array.isArray(t.Ports)?t.Ports.map(p=>`${p.host_ip||""}:${p.host_port}->${p.container_port}/${p.protocol||"tcp"}`):[]:String(t.Ports||"").split(",").map(p=>p.trim()).filter(Boolean),P=String(t.State||"").toLowerCase()||(/^up/i.test(String(t.Status||""))?"running":"exited");return{name:f,image:String(t.Image||""),state:P,status:String(t.Status||""),ports:h,ours:f.startsWith("chatpanel-"),engine:l}}function Lt({cfg:t,bridgeHealth:l,workers:f=()=>[],persist:h=()=>{},exec:P=(S,F,B={})=>ft(S,F,{timeout:6e4,killSignal:"SIGKILL",...B}),platform:p=process.platform,arch:U=process.arch,osRelease:ce=Q.release(),spawn:de=mt,lookup:Ne=null,fetchImpl:N=globalThis.fetch,stateDir:_=v.join(Q.homedir(),".chatpanel","runtime"),log:E=()=>{},sleep:me=S=>new Promise(F=>setTimeout(F,S)),totalMem:Be=()=>Q.totalmem(),memoryProbe:dn=S=>p==="darwin"&&t?.runtime?.heatwatch!==!1?it(S,{fetchImpl:N}):Promise.resolve(null),now:fe=()=>Date.now(),autoEnv:mn=process.env.CHATPANEL_RUNTIME_AUTO,every:Ce=(S,F)=>{const B=setInterval(S,F);return B.unref?.(),B}}={}){const S=Q.homedir(),F=p==="win32"?[v.join(S,"AppData","Local","Microsoft","WinGet","Links"),v.join(S,".local","bin"),v.join(S,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",v.join(S,".local","bin"),v.join(S,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin",...p==="darwin"?ct({home:S}):[]],B=(n=process.env)=>{const e=p==="win32"?";":":",r=String(n.PATH||n.Path||""),i=F.filter(s=>!r.split(e).includes(s));return{...n,PATH:[...r.split(e).filter(Boolean),...i].join(e)}},k=async(n,e,r={})=>{try{const i=await P(n,e,{...r,env:B(r.env)});return{ok:!0,out:String(i.stdout||"").trim(),err:String(i.stderr||"").trim()}}catch(i){return{ok:!1,out:String(i?.stdout||"").trim(),err:String(i?.stderr||i?.message||i).trim(),code:i?.code}}},y=n=>String(t.runtime?.services?.[n.id]?.model||n.model||"");let pe=null;const fn=async()=>(pe===null&&(pe=await Vn({exec:P,platform:p,arch:U})),pe),q={},pn=n=>{const e=p==="win32"?";":":",r=p==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of B().PATH.split(e).filter(Boolean))for(const s of r)try{return Un(v.join(i,n+s),Dn.X_OK),!0}catch{}return!1},C=async(n,e=["--version"])=>(q[n]===void 0&&(q[n]=(Ne||pn)(n)||(await k(n,e,{timeout:8e3})).ok),q[n]);let he=null;const ge=async()=>(he||(he=await qn({exec:P,platform:p,totalmem:Be,cpus:()=>Q.cpus()})),he),T=async n=>({platform:p,arch:U,accelerator:await fn(),engine:n,vllmOnPath:await C("vllm"),llamaOnPath:await C("llama-server"),mlxOnPath:p==="darwin"&&U==="arm64"?await C("mlx_lm.server",["--help"]):!1,osMajor:p==="darwin"?on(ce):0,appleOnPath:p==="darwin"&&U==="arm64"?await C(Pe):!1,appleInstall:p==="darwin"?dt({home:S}):null,...await ge()}),H=n=>!n.only||(!n.only.platform||n.only.platform===p)&&(!n.only.arch||n.only.arch===U)&&(!n.only.minDarwin||on(ce)>=n.only.minDarwin),Y=n=>v.join(_,`${n.id}.pid`),X=n=>{try{const e=Number(sn(Y(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},ke=n=>H(n)?X(n)?"running":"stopped":"unsupported",D={};async function ie(n){const e=Z(n);if(!H(e))return{ok:!1,error:`${e.label} runs on ${re(e)} only`};if(X(e))return e.auto&&!e.configured(t)&&(e.configure(t,A(e),e),h()),{ok:!0,already:!0,url:A(e)};if(e.auto&&await e.answers(A(e),N)){const $=await wn(e.port);if($)return ne(_,{recursive:!0,mode:448}),oe(Y(e),String($),{mode:384}),D[e.id]={layer:"none",reason:"a model engine runs on the hardware, behind the gateway"},e.configure(t,A(e),e),h(),E(`[runtime] ${e.label} was already answering on ${A(e)} (pid ${$}) — adopted`),{ok:!0,adopted:!0,url:A(e),answering:!0,provides:e.provides}}const r=await T(null),i=e.engineOf(r);if(!await C(e.runner,e.runnerCheck))return{ok:!1,error:`\`${e.runner}\` is not on PATH — install it first (${i.install?.command||""}), or click Install`,install:i.install};if(e.id==="llama"&&/\.gguf$/i.test(e.model)&&!Ee(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[s,o]=e.command(e,G(e,e.model,i,r)),a=v.join(_,V);ne(a,{recursive:!0,mode:448});const c={bin:s,argv:o,opts:{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,HF_HOME:a,LLAMA_CACHE:a,...e.installed?{HF_HUB_OFFLINE:"1"}:{}}},record:{layer:"none",reason:"a model engine runs on the hardware directly, behind the gateway (loopback only) — the sandbox is for agents and tools"}};D[e.id]=c.record;const u=v.join(_,`${e.id}.log`);let d,m=null;try{try{m=Fn(u,"w",384)}catch{m=null}d=de(c.bin,c.argv,{...c.opts,env:B(c.opts?.env),detached:!0,stdio:["ignore",m??"ignore",m??"ignore"]}),d.unref?.()}catch($){return{ok:!1,error:`${c.bin}: ${$.message}`,install:i.install}}finally{if(m!==null)try{Hn(m)}catch{}}if(!d?.pid)return{ok:!1,error:`${c.bin} did not start`,install:i.install};oe(Y(e),String(d.pid),{mode:384});const w=A(e);let g=!1;for(let $=0;$<120&&!g&&X(e);$++)g=await e.answers(w,N),g||await me(1e3);if(!X(e)){try{ln(Y(e))}catch{}let $="";try{$=sn(u,"utf8").trim().split(`
3
+ `).filter(R=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(R)).slice(-3).map(R=>R.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{$=""}return{ok:!1,error:`${e.label} exited on start${$?` — ${$}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:u}}return e.configure(t,w,e),h(),E(`[runtime] ${e.label} started (pid ${d.pid}) on ${w}, sandbox ${D[e.id].layer}${g?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:w,answering:g,provides:e.provides,model:y(e),sandbox:D[e.id]}}const we=n=>t.runtime?.services?.[n.id]?.off===!0,Le=(n,e)=>{t.runtime=t.runtime||{},t.runtime.services=t.runtime.services||{};const r={...t.runtime.services[n.id]||{}};e?r.off=!0:delete r.off,t.runtime.services[n.id]=r},hn=()=>t.runtime?.auto!==!1&&String(mn||"").toLowerCase()!=="off",W={};async function Te(n){if(!n?.auto)return{ok:!1,skipped:"not a service that starts by itself"};if(!hn())return{ok:!1,skipped:"automatic start is switched off"};if(!H(n))return{ok:!1,skipped:`runs on ${re(n)} only`};if(we(n))return{ok:!1,skipped:"stopped by the person"};if(!await C(n.runner,n.runnerCheck))return{ok:!1,skipped:"its helper is not in this install"};if(!X(n)){const r=await k(n.runner,["check"],{timeout:8e3});if(!r.ok){let i="";try{i=JSON.parse(r.out||"{}").message||""}catch{i=""}return W[n.id]=i||"not available on this Mac right now",{ok:!1,skipped:W[n.id]}}}const e=await ie(n);return e.ok?(delete W[n.id],{ok:!0,...e.already?{already:!0}:e.adopted?{adopted:!0}:{started:!0}}):(W[n.id]=e.error,{ok:!1,skipped:e.error})}async function gn(){const n=[];for(const e of j.filter(r=>r.auto))n.push({id:e.id,label:e.label,...await Te(e).catch(r=>({ok:!1,skipped:r.message}))});return n}async function kn(n){const e=x(n);return e?.auto?Te(e):{ok:!1,skipped:"not a service that starts by itself"}}async function wn(n){if(p==="win32")return 0;const e=await k("lsof",["-nP",`-iTCP:${n}`,"-sTCP:LISTEN","-t"],{timeout:4e3}),r=Number(String(e.out||"").split(`
4
+ `)[0]);return e.ok&&Number.isInteger(r)&&r>1?r:0}function Ge(n){const e=X(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{ln(Y(n))}catch{}return n.unconfigure(t,A(n)),h(),{ok:!0}}const Z=n=>n.model?{...n,model:y(n),installed:K(n,y(n)),tunings:t.runtime?.services?.[n.id]?.tunings||{},...n.id==="llama"?{file:yn(y(n))}:{}}:n,J=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx";function bn(n,e){const r=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},s=se(n.id).filter(c=>!c.minRamMB||r>0&&r>=c.minRamMB);if(!s.length||!r)return null;const o=s.slice().sort((c,u)=>(i[u.tier]??-1)-(i[c.tier]??-1)||c.ramMB-u.ramMB)[0],a=Math.round(o.ramMB/1024*10)/10;return{model:o.id,label:o.label,why:`This machine (${e.ramGB} GB${e.accelerator==="apple"?", Apple Silicon":e.accelerator?`, ${e.accelerator.toUpperCase()} GPU`:", no GPU"}) runs ${o.label} well — about ${a} GB while loaded${o.tier==="max"?"; the strongest in the list":""}.`,profile:"coding",current:y(n)===o.id}}async function Re(n,{model:e,ctx:r,needMB:i}={}){const s=x(n);if(!s||!s.model)return{ok:!1,error:s?`${s.label} takes no model`:`unknown service ${n}`};const o=String(e||y(s)),a=se(n).find(_e=>_e.id===o)||null,c=Number(i)>0?Number(i):a?.ramMB||null;if(!c)return{ok:!1,error:`${o} is not in the catalogue — pass need_mb (its peak memory while serving)`};const u=Number(r)>0?Number(r):Ve(n),d=/\.gguf$/i.test(o)||s.id==="llama"?null:ot(z(),o),m=u&&d?at(d,u):null,w=st({ramMB:c,kvMB:m||0}),g=s.kind==="native"?await dn(w):null,$=((await ge()).ramGB||0)*1024,R=g?g.fits:$>0&&w<=$,I=_e=>`${Math.round(_e/102.4)/10} GB`,Gn=g?g.fits?`${o} fits: needs about ${I(w)}, ${I(g.availableMB)} is free now${g.fitsGPULimit===!1?` — but it is above the GPU wired limit (${I(g.gpuWiredLimitMB)}); raise iogpu.wired_limit_mb`:""}.`:`${o} needs about ${I(w)} and ${I(g.availableMB)} is free now — ${I(g.shortfallMB)} short.${g.close.length?` Close ${g.close.join(", ")} to make room, or pick a smaller model.`:" Pick a smaller model."}`:`${o} needs about ${I(w)} of the machine's ${I($)} — ${R?"fits":"does not fit"} (total memory; install Heatwatch to check what is free now).`;return{ok:!0,service:s.id,model:o,needMB:w,weightsMB:c,kvMB:m,context:u||null,contextCounted:m!==null||!u,source:g?"heatwatch":"total-memory",fits:R,live:g,advice:Gn}}const G=(n,e,r,i={})=>({task:n.id==="vllm"?te(e):"chat",model:e,backend:r?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0}),z=()=>v.join(_,V),K=(n,e)=>/\.gguf$/i.test(e)?Ee(e):n.id==="llama"?!!an(z(),e):rt(z(),e),yn=n=>/\.gguf$/i.test(n)?n:an(z(),n),b={},wt=n=>b[n.id]||null;function be(n,e,r={}){return b[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...r},b[n.id]}function O(n,e){const r=String(e||"").trim();if(!r)return;n.lines.push(r.slice(0,200)),n.lines.length>8&&n.lines.shift();const i=/^STEP (\d+)\/(\d+)/.exec(r);i&&(n.step={n:Number(i[1]),of:Number(i[2])})}const ae=(n,e,r,{timeout:i=36e5*4}={})=>new Promise(s=>{if(n.cancelled)return s({ok:!1,code:-1,error:"cancelled"});let o;try{o=de(e,r,{stdio:["ignore","pipe","pipe"],env:B()})}catch(d){return s({ok:!1,code:-1,error:d.message})}n.child=o;let a="";const c=d=>{a+=String(d);const m=a.split(/\r?\n|\r/);a=m.pop();for(const w of m)O(n,w)};o.stdout?.on("data",c),o.stderr?.on("data",c);const u=setTimeout(()=>{try{o.kill("SIGTERM")}catch{}},i);u.unref?.(),o.on("error",d=>{clearTimeout(u),n.child=null,s({ok:!1,code:-1,error:d.message})}),o.on("exit",d=>{clearTimeout(u),n.child=null,a&&O(n,a),s({ok:d===0&&!n.cancelled,code:d,...n.cancelled?{error:"cancelled"}:{}})})}),Ie={install:Promise.resolve(),build:Promise.resolve()},ye={install:0,build:0},Ue=(n,e,r)=>{ye[n]>0&&(e.waiting=!0,O(e,`waiting for the other ${n} to finish first — one at a time`)),ye[n]++;const i=Ie[n];let s;const o=new Promise(a=>{s=a});return Ie[n]=i.then(()=>o),i.then(async()=>{e.waiting&&(O(e,"the other one finished — going"),e.waiting=!1);try{return await r()}finally{ye[n]--,s()}})},Fe=async(n,e)=>(await k(n,["image","exists",e],{timeout:2e4})).ok;async function $n(n,e,r,i){const s=e?.image||r.image;if(await Fe(n,s))return{ok:!0};const o=e?.sources?.length?e.sources:[s],a=[];for(const m of o){if(i.kind="pull-image",i.detail=m,O(i,`pulling ${m}`),(await ae(i,n,["pull",m])).ok)return m!==s&&await k(n,["tag",m,s],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const c=e?.recipe?et[e.recipe]:null;if(!c)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const u=v.join(_,"images",e.recipe);return ne(u,{recursive:!0,mode:448}),oe(v.join(u,"Dockerfile"),c.dockerfile,{mode:384}),i.kind="build-image",i.detail=s,i.minutes=c.minutes,O(i,`no registry has ${s} for this machine — building it here (about ${c.minutes} minutes)`),E(`[runtime] building ${s} from the ${e.recipe} recipe in ${u}`),(await Ue("build",i,()=>ae(i,n,["build","-t",s,"-f",v.join(u,"Dockerfile"),u]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function He(n,e){const r=y(n);if(!r||K(n,r))return{ok:!0};if(/\.gguf$/i.test(r))return{ok:!1,error:`no such file: ${r}`};e.kind="pull-model",e.detail=r;const i=s=>{if(e.cancelled)throw new Error("cancelled");e.progress={bytes:s.bytes,total:s.total,file:s.file}};try{return n.id==="llama"?await tt(r,{root:z(),fetchImpl:N,onProgress:i}):await nt(r,{root:z(),fetchImpl:N,onProgress:i}),{ok:!0}}catch(s){return{ok:!1,error:`pull ${r}: ${s.message}`}}}async function vn(n,e,r){const i=[];return n.kind!=="native"&&e&&!await Fe(e,r?.image||n.image)&&i.push("image"),n.pull&&n.model&&!K(n,y(n))&&i.push("model"),i}async function De(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&p!=="linux"){const r=await k("podman",["machine","inspect","--format","{{.Resources.Memory}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?i:0}if(n==="docker"&&p!=="linux"){const r=await k("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?Math.round(i/1048576):0}return Math.round(Be()/1048576)}async function M(){const n={};for(const r of ue){const i=await k(r,["--version"],{timeout:5e3});if(!i.ok){n[r]={installed:!1};continue}const s=(i.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||i.out;let o=!1,a=null;if(r==="podman")if(p==="linux")o=(await k("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const c=await k("podman",["machine","list","--format","json"],{timeout:8e3});try{const d=JSON.parse(c.out||"[]")[0]||null;a=d?{name:d.Name,running:!!d.Running}:null,o=!!d?.Running}catch{a=null}}else o=(await k("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[r]={installed:!0,version:s,running:o,...r==="podman"&&p!=="linux"?{machine:a}:{}}}const e=ue.find(r=>n[r]?.installed&&n[r].running)||ue.find(r=>n[r]?.installed)||null;return{...n,preferred:e,...e?{}:{install:Oe(p)}}}async function $e(n="podman"){if(!ue.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await M())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:Oe(p)};if(e.running)return{ok:!0,already:!0};if(n==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(p!=="linux"){if(!e.machine){const i=await k("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const r=await k("podman",["machine","start"],{timeout:3e5});if(!r.ok&&!/already running/i.test(r.err))return{ok:!1,error:`podman machine start: ${r.err||r.out}`}}return{ok:!0}}async function je(){const n=await M(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await k("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(s=>cn(s,"podman"))}catch{return[]}}const r=await k("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return r.ok?r.out.split(`
5
+ `).filter(Boolean).map(i=>{try{return cn(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Xe(n,e){const r=await k(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return r.ok?/running/i.test(r.out)?"running":"stopped":"absent"}async function ve(n,e){const r=await k(n,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!r.ok){for(const o of e)i[o]="absent";return i}const s=new Map(r.out.split(`
6
+ `).map(o=>o.split(" ")).filter(o=>o[0]).map(([o,a])=>[o,/running/i.test(a||"")?"running":"stopped"]));for(const o of e)i[o]=s.get(o)||"absent";return i}const A=n=>`http://127.0.0.1:${n.port}`;async function We(){const n=await M(),e=n.preferred,r=await De(e,n),i={},s=await T(e),o=e&&n[e].running?await ve(e,j.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of j){const c=A(a);let u="no-engine";a.kind==="native"?u=ke(a):e&&n[e].running?u=o[a.container]||"absent":e&&(u="engine-stopped");const d=a.model?y(a):null,m=a.engineOf?a.engineOf(s):null,w=a.kind==="native"?(s.ramGB||0)*1024:r;i[a.id]={...pt(a),engine:a.kind==="native"?"host":e,state:u,url:c,configured:a.configured(t),answering:u==="running"?await a.answers(c,N):!1,...a.helper?{asleep:L.has(a.id),idleMinutes:qe()/6e4}:{},...m?{engineFor:{backend:m.backend,kind:m.kind,image:m.image||null,...m.runner?{runner:m.runner}:{},why:m.why,...m.for?{for:m.for}:{},...m.speed?{speed:m.speed}:{},...m.notFor?{notFor:m.notFor}:{},...m.warn?{warn:m.warn}:{},...m.install?{install:m.install}:{}}}:{},...a.kind==="native"&&!H(a)?{why:`${a.label} runs on ${re(a)} only`}:{},...a.auto&&u!=="running"&&H(a)?{auto:!0,...we(a)?{why:"Stopped here — Start turns it back on"}:W[a.id]?{why:W[a.id]}:{}}:a.auto?{auto:!0}:{},...a.kind==="native"&&D[a.id]?{sandbox:D[a.id]}:{},...b[a.id]?{job:{kind:b[a.id].kind,since:b[a.id].since,detail:b[a.id].detail||null,step:b[a.id].step||null,minutes:b[a.id].minutes||null,progress:b[a.id].progress,lines:b[a.id].lines.slice(-4),done:b[a.id].done,error:b[a.id].error,waiting:!!b[a.id].waiting,cancelled:!!b[a.id].cancelled}}:{},...J(a)?{profiles:tn(a.id,t.runtime?.services?.[a.id]?.tunings,G(a,d,m,s)),docs:Zn[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:bn(a,s)}:{},...a.model?{model:d,default:a.model,models:Ze(a.id,{active:d,engineRamMB:w,engine:a.kind==="native"?"host":e,platform:p,installed:g=>K(a,g)}),machine:{engineRamMB:w}}:{},...J(a)?{tunings:nn(a.id,t.runtime?.services?.[a.id]?.tunings,G(a,d,m,s))}:{}}}return i}async function Sn(){const n=await M(),e=await T(n.preferred);return{platform:p,arch:U,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:Qn(e)}}function Je(n,{settingsFile:e=null,secret:r=null,pick:i=null,cpus:s=null}={}){const o=Z(n),a=["run","-d","--name",o.container,"--restart","no","-p",`127.0.0.1:${o.port}:${o.containerPort}`];o.helper&&s&&a.push("--cpus",String(s));for(const u of o.volumes?o.volumes(_):[])a.push("-v",u);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const u of o.env?o.env(o):[])a.push("-e",u);o.helper&&s&&a.push("-e",`THREADS=${s}`),r&&a.push("-e",`SEARXNG_SECRET=${r}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${o.port}/`),a.push("--cap-drop","ALL");for(const u of o.caps||[])a.push("--cap-add",u);i?.devices?.length&&a.push(...i.devices),a.push(i?.image||o.image,...o.args?o.args(o,i):[]);const c=Xn("sha1").update(JSON.stringify(a.filter(u=>!String(u).startsWith("SEARXNG_SECRET=")))).digest("hex").slice(0,12);return a.splice(2,0,"--label",`chatpanel.run=${c}`),{args:a,hash:c}}const Se={};async function An(n){if(Se[n]==null){const e=await k(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),r=Number.parseInt(e.out,10);Se[n]=Number.isFinite(r)&&r>0?r:Q.cpus()?.length||2}return Math.max(1,Math.floor(Se[n]/2))}async function ze(n,{force:e=!1}={}){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};L.delete(r.id),xe(r.id),r.auto&&we(r)&&Le(r,!1);const i=b[r.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let s=null;if(r.kind!=="native"){const d=await M();if(s=d.preferred,!s)return{ok:!1,error:"no container engine — install Podman first",install:Oe(p)};if(!d[s].running){const m=await $e(s);if(!m.ok)return m}}else if(!H(r))return{ok:!1,error:`${r.label} runs on ${re(r)} only`};const o=await T(s),a=r.engineOf?r.engineOf(o):null;if(r.kind==="native"&&!await C(r.runner,r.runnerCheck))return{ok:!1,error:`\`${r.runner}\` is not on PATH — install it first (${a?.install?.command||""}), or click Install`,install:a?.install};if(r.model&&/\.gguf$/i.test(y(r))&&!Ee(y(r)))return{ok:!1,error:`no such file: ${y(r)}`};if(r.kind==="native"&&r.model&&!e){const d=await Re(r.id);if(d.live&&!d.fits)return{ok:!1,error:d.advice,plan:d}}const c=await vn(r,s,a);if(!c.length)return delete b[r.id],r.kind==="native"?ie(r):Ae(r,s);const u=be(r,c[0]==="image"?"pull-image":"pull-model",{detail:c[0]==="image"?a?.image||r.image:y(r)});return u.then=(async()=>{try{if(c.includes("image")){const m=await $n(s,a,r,u);if(!m.ok)throw new Error(m.error)}if(c.includes("model")){const m=await He(r,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=r.label;const d=r.kind==="native"?await ie(r):await Ae(r,s);if(!d.ok)throw new Error(d.error);u.done=!0,u.result=d,E(`[runtime] ${r.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(d){u.done=!0,u.error=u.cancelled?"cancelled":d.message,E(`[runtime] ${r.label}: ${u.error}`)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function Mn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const r=b[e.id];if(!r||r.done)return{ok:!0,nothing:!0};if(r.cancelled=!0,r.child){try{r.child.kill("SIGTERM")}catch{}const i=r.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return O(r,"cancelled"),E(`[runtime] ${e.label}: job cancelled (${r.kind})`),{ok:!0,cancelled:r.kind}}async function Ae(n,e){let r=await Xe(e,n.container);const i=n.helper?await An(e):null,s=n.engineOf?n.engineOf(await T(e)):null,o=n.id==="searxng"?v.join(_,"searxng-settings.yml"):null,a=Je(n,{settingsFile:o,secret:n.id==="searxng"?"x":null,pick:s,cpus:i});if(r!=="absent"){const d=await k(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!d.ok||d.out!==a.hash)&&(E(`[runtime] ${n.label}: made with older settings — re-creating it`),await k(e,["rm","-f",n.container],{timeout:6e4}),r="absent")}if(r!=="running")if(r==="stopped"){const d=await k(e,["start",n.container],{timeout:6e4});if(!d.ok)return{ok:!1,error:`${e} start: ${d.err||d.out}`}}else{ne(_,{recursive:!0,mode:448});let d=null;n.id==="searxng"&&(oe(o,kt(String(t.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),d=jn(32).toString("hex")),n.volumes&&ne(v.join(_,V),{recursive:!0,mode:448});const{args:m}=Je(n,{settingsFile:o,secret:d,pick:s,cpus:i});E(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const w=await k(e,m,{timeout:6e5});if(!w.ok)return{ok:!1,error:`${e} run: ${w.err||w.out}`}}const c=A(n);let u=!1;for(let d=0;d<30&&!u;d++)u=await n.answers(c,N),u||await me(1e3);return n.configure(t,c,Z(n)),h(),{ok:!0,url:c,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:y(n)}:{}}}async function xn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(L.delete(e.id),delete Me[e.id],e.auto&&Le(e,!0),e.kind==="native")return Ge(e);const r=await M(),i=r.preferred;if(i&&r[i].running){const s=await k(i,["stop",e.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${i} stop: ${s.err||s.out}`}}return e.unconfigure(t,A(e)),h(),{ok:!0}}async function _n(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!r.model)return{ok:!1,error:`${r.label} takes no model`};const i=String(e||"").trim();if(!Wn(n,i))return{ok:!1,error:`not a model id: ${JSON.stringify(e)} — pick one from the list, or a Hugging Face id like owner/name`};const s=await M(),o=s.preferred,a=r.kind==="native"?((await ge()).ramGB||0)*1024:await De(o,s),c=Ze(n,{active:i,engineRamMB:a,engine:r.kind==="native"?"host":o,platform:p,installed:m=>K(r,m)}).find(m=>m.id===i);if(c?.unavailable)return{ok:!1,error:`${i} ${c.unavailable}`};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},model:i};const u=A(r);r.configured(t)===u&&r.configure(t,u,Z(r)),h();const d=await Ke(r,o,s);return d.ok?{ok:!0,model:i,restarted:d.restarted,...c?.ramNote?{note:c.ramNote}:{}}:d}async function Ke(n,e,r){if(n.kind==="native"){if(ke(n)!=="running")return{ok:!0,restarted:!1};Ge(n);const o=await ie(n);return o.ok?{ok:!0,restarted:!0}:o}if(!e||!r[e].running)return{ok:!0,restarted:!1};const i=await Xe(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const s=await k(e,["rm","-f",n.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${e} rm: ${s.err||s.out}`};if(i==="running"){const o=await ze(n.id);return o.ok?{ok:!0,restarted:!0}:o}return{ok:!0,restarted:!1}}async function En(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!J(r))return{ok:!1,error:`${r.label} takes no profile`};const i=await M(),s=await T(i.preferred),o=r.engineOf?r.engineOf(s):null,a=tn(r.id,t.runtime?.services?.[n]?.tunings,G(r,y(r),o,s)).find(u=>u.id===e);if(!a)return{ok:!1,error:`no profile ${JSON.stringify(e)} — one of speed, coding, long, xl`};if(!a.fits)return{ok:!1,error:`${a.label}: ${a.why}`};const c=await Qe(n,a.patch);return c.ok?{...c,profile:a.id}:c}async function Pn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!H(e))return{ok:!1,error:`${e.label} runs on ${re(e)} only`};const r=b[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(delete q[e.runner],await C(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const s=e.engineOf(await T(null))?.install;if(!s?.steps?.length)return{ok:!1,error:`no installer for ${e.label} on this platform${s?.url?` — see ${s.url}`:""}`,install:s||null};const o=be(e,"install",{detail:e.runner});return o.then=Ue("install",o,async()=>{const a=async d=>{for(const[m,...w]of d){O(o,`$ ${m} ${w.join(" ")}`);let g=await ae(o,m,w,{timeout:36e5});for(let $=0;!g.ok&&!o.cancelled&&$<6&&o.lines.some(R=>/already locked|Please wait for it to finish/i.test(R));$++)O(o,`another ${m} holds the lock — waiting 20 s (${$+1}/6)`),await me(2e4),g=await ae(o,m,w,{timeout:36e5});if(!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let c=await a(s.steps);!c.ok&&!o.cancelled&&s.fallback?.length&&(O(o,`${c.error} — trying the other way`),c=await a(s.fallback)),delete q[e.runner];const u=c.ok&&await C(e.runner,e.runnerCheck);o.done=!0,o.cancelled?o.error="cancelled":c.ok?u||(o.error=`${e.runner} still not found after the install — open a new terminal and run \`${s.command}\` by hand`):o.error=`install failed: ${c.error}${o.lines.length?` (${o.lines.slice(-2).join(" | ")})`:""}`,E(`[runtime] install ${e.runner}: ${o.error||"ok"}`)}),{ok:!0,pending:{kind:o.kind,since:o.since,detail:o.detail}}}async function On(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const r=b[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(K(e,y(e)))return{ok:!0,installed:!0,model:y(e)};const i=be(e,"pull-model",{detail:y(e)});return i.then=(async()=>{const s=await He(e,i);i.done=!0,s.ok||(i.error=s.error)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Qe(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!J(r))return{ok:!1,error:`${r.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await M(),s=i.preferred,o=y(r),a=await T(s),c=r.engineOf?r.engineOf(a):null,u=Yn(r.id,t.runtime?.services?.[n]?.tunings,e,G(r,o,c,a));if(u.error)return{ok:!1,error:u.error};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},tunings:u},h();const d=await Ke(r,s,i);return d.ok?{ok:!0,tunings:nn(r.id,u,G(r,o,c,a)),restarted:d.restarted}:d}async function Nn(){const n=await M(),e=n.preferred,r=e&&n[e].running?await ve(e,j.filter(o=>o.kind!=="native").map(o=>o.container)):{},i={};let s=!1;return await Promise.all(j.map(async o=>{const a=o.kind==="native"?ke(o):e&&n[e].running?r[o.container]||"absent":"no-engine";i[o.id]=a==="running"&&await o.answers(A(o),N)?"up":"down";const c=(o.provides||[]).some(u=>["embedded","none"].includes(t.capabilities?.[u]?.provider));i[o.id]==="up"&&o.configure&&!c&&o.configured(t)!==A(o)&&(o.configure(t,A(o),Z(o)),s=!0)})),s&&h(),i}function Ve(n){const e=x(n);if(e?.window)return e.window;if(!e||!J(e))return null;const r=Number(rn(e.id,t.runtime?.services?.[n]?.tunings,G(e,y(e),null,{})).maxModelLen);return Number.isFinite(r)&&r>0?r:null}function Bn(n){const e=x(n);if(e?.card)return e.card;if(!e||!J(e))return null;const r=y(e),i=rn(e.id,t.runtime?.services?.[n]?.tunings,G(e,r,null,{})),s=se(e.id).find(a=>a.id===r)||null,o=e.id==="vllm"?te(r):"chat";return{engine:e.id,backend:D[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:o,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:o==="chat"&&!!i.vision,tools:!!(o==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:o==="chat"&&!!i.reasoning&&i.reasoning!=="off",...s?{tier:s.tier||null,licence:s.licence||null,languages:s.lang||null,label:s.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}const Cn=10,qe=()=>{const n=Number(t.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:Cn)*6e4},Ln=fe(),Me={},L=new Set,ee={};function xe(n){Me[n]=fe()}async function Tn(n,{force:e=!1}={}){const r=x(n);if(!r||!r.helper)return{ok:!0};if(xe(r.id),!L.has(r.id)&&!e){const i=r.container&&r.configured?.(t)?(await je()).find(s=>s.name===r.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};L.add(r.id)}return ee[r.id]||(ee[r.id]=(async()=>{const i=await M(),s=i.preferred;if(!s)return{ok:!1,error:"no container engine"};if(!i[s].running){const a=await $e(s);if(!a.ok)return a}const o=await Ae(r,s);return o.ok&&(L.delete(r.id),E(`[runtime] ${r.label}: woken for a request`)),o})().finally(()=>{delete ee[r.id]})),ee[r.id]}async function Ye(){const n=qe();if(!n)return[];const e=j.filter(a=>a.helper&&a.configured(t)&&!L.has(a.id)&&!ee[a.id]&&!(b[a.id]&&!b[a.id].done)&&fe()-(Me[a.id]??Ln)>=n);if(!e.length)return[];const r=await M(),i=r.preferred;if(!i||!r[i].running){for(const a of e)L.add(a.id);return e.map(a=>a.id)}const s=await ve(i,e.map(a=>a.container)),o=[];for(const a of e){if(s[a.container]==="running"){if(!(await k(i,["stop",a.container],{timeout:6e4})).ok)continue;E(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}L.add(a.id),o.push(a.id)}return o}return Ce&&Ce(()=>{Ye().catch(n=>E(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:xe,wake:Tn,sweepIdle:Ye,health:Nn,contextWindow:Ve,modelCard:Bn,async status(){const[n,e,r,i,s]=await Promise.all([l().catch(()=>null),M(),We(),je(),Sn()]);return{machine:s,sandbox:n?.sandbox||null,processes:{all:[...Array.isArray(n?.processes)?n.processes:[],...f()],localMcp:Array.isArray(n?.localMcp)?n.localMcp:[],warm:n?.warm||null},containers:i,refused:Array.isArray(n?.sandbox?.refused)?n.sandbox.refused:[],bridge:n?{ok:!0,version:n.version||""}:{ok:!1},engines:e,services:r}},startEngine:$e,startService:ze,stopService:xn,ensureDefaults:gn,revive:kn,plan:Re,setModel:_n,setTunings:Qe,setProfile:En,pullModel:On,installRunner:Pn,cancelJob:Mn,services:We,catalogFor:se}}export{ht as SEARXNG_DEFAULT_ENGINES,j as SERVICES,cn as containerRow,Lt as createRuntime,Oe as installDoor,kt as searxngSettings};
@@ -0,0 +1 @@
1
+ class p extends Error{constructor(r,i){super(i),this.name="SearchApiError",this.code=r}}const q=Object.freeze({exa:{name:"Exa",needsKey:!0,vars:["key"],docs:"https://docs.exa.ai/reference/search",request:{method:"POST",url:"https://api.exa.ai/search",headers:{"x-api-key":"{key}"},body:{query:"{q}",numResults:"{limit}",contents:{text:{maxCharacters:4e3}}}},response:{results:"results",url:"url",title:"title",snippet:["summary","highlights"],text:"text",published:"publishedDate"}},brave:{name:"Brave Search API",needsKey:!0,vars:["key"],docs:"https://api-dashboard.search.brave.com/app/documentation/web-search",request:{method:"GET",url:"https://api.search.brave.com/res/v1/web/search?q={q}&count={limit}",headers:{"X-Subscription-Token":"{key}"}},response:{results:"web.results",url:"url",title:"title",snippet:"description",published:"page_age"}},tavily:{name:"Tavily",needsKey:!0,vars:["key"],docs:"https://docs.tavily.com/documentation/api-reference/endpoint/search",request:{method:"POST",url:"https://api.tavily.com/search",headers:{Authorization:"Bearer {key}"},body:{query:"{q}",max_results:"{limit}"}},response:{results:"results",url:"url",title:"title",snippet:"content",text:"raw_content",published:"published_date"}},serper:{name:"Serper (Google results)",needsKey:!0,vars:["key"],docs:"https://serper.dev",request:{method:"POST",url:"https://google.serper.dev/search",headers:{"X-API-KEY":"{key}"},body:{q:"{q}",num:"{limit}"}},response:{results:"organic",url:"link",title:"title",snippet:"snippet",published:"date"}},serpapi:{name:"SerpApi (Google results)",needsKey:!0,vars:["key"],docs:"https://serpapi.com/search-api",request:{method:"GET",url:"https://serpapi.com/search.json?engine=google&q={q}&num={limit}&api_key={key}"},response:{results:"organic_results",url:"link",title:"title",snippet:"snippet",published:"date"}},google:{name:"Google Programmable Search",needsKey:!0,vars:["key","cx"],maxLimit:10,docs:"https://developers.google.com/custom-search/v1/overview",request:{method:"GET",url:"https://www.googleapis.com/customsearch/v1?key={key}&cx={cx}&q={q}&num={limit}"},response:{results:"items",url:"link",title:"title",snippet:"snippet"}},jina:{name:"Jina Search",needsKey:!0,vars:["key"],docs:"https://jina.ai/reader",request:{method:"GET",url:"https://s.jina.ai/?q={q}",headers:{Authorization:"Bearer {key}","X-Respond-With":"no-content"}},response:{results:"data",url:"url",title:"title",snippet:"description",text:"content",published:"date"}},mwmbl:{name:"Mwmbl",needsKey:!1,vars:[],docs:"https://mwmbl.org",request:{method:"GET",url:"https://api.mwmbl.org/api/v1/search/?s={q}"},response:{results:"",url:"url",title:"title",snippet:"extract"}},wikipedia:{name:"Wikipedia",needsKey:!1,vars:[],docs:"https://api.wikimedia.org/wiki/Core_REST_API",request:{method:"GET",url:"https://en.wikipedia.org/w/rest.php/v1/search/page?q={q}&limit={limit}"},response:{results:"pages",url:{template:"https://en.wikipedia.org/wiki/{key}"},title:"title",snippet:["description","excerpt"]}}}),I=["GET","POST"],f=/\{([a-z][a-z0-9_]*)\}/gi,S=20;function y(e={}){const r=e.preset?q[e.preset]:null;if(e.preset&&!r)throw new p("UNKNOWN_PRESET",`no search API preset '${e.preset}'`);const i={...r?.request||{},...e.request||{}},s={...r?.response||{},...e.response||{}},t=String(e.id||e.preset||"").trim();if(!/^[a-z0-9][a-z0-9_-]{0,39}$/i.test(t))throw new p("BAD_API","search API id: letters, digits, - and _");const o=String(i.method||"GET").toUpperCase();if(!I.includes(o))throw new p("BAD_API",`search API '${t}': method must be GET or POST`);const n=String(i.url||"").trim();if(!/^https:\/\//i.test(n))throw new p("BAD_API",`search API '${t}': url must start with https://`);const a=n.slice(0,n.indexOf("/",8)===-1?n.length:n.indexOf("/",8));if(/[{}]/.test(a)||/[?#@]/.test(a))throw new p("BAD_API",`search API '${t}': the host must be written out — no placeholder or credentials in it`);const l=JSON.stringify([n,i.headers||{},i.body??null]);if(!/\{q\}/.test(l))throw new p("BAD_API",`search API '${t}': the request must carry the query as {q}`);if(s.results==null||!s.url||!s.title)throw new p("BAD_API",`search API '${t}': say where the results are, and their url and title`);const c=[...new Set([...r?.vars||[],...[...l.matchAll(f)].map(u=>u[1]).filter(u=>u!=="q"&&u!=="limit")])];return Object.freeze({id:t,preset:e.preset||"",name:String(e.name||r?.name||t),needsKey:e.needsKey??r?.needsKey??c.includes("key"),vars:c,maxLimit:Math.min(S,Number(e.maxLimit||r?.maxLimit||S)),request:Object.freeze({method:o,url:n,headers:{...i.headers||{}},body:i.body??null}),response:Object.freeze(s),host:new URL(n.replace(f,"x")).hostname})}function b(e,r={}){return e.vars.filter(i=>!String(r[i]??"").trim())}function m(e,r,i){return String(e).replace(f,(s,t)=>t in r?i?encodeURIComponent(r[t]):String(r[t]):s)}function g(e,r){if(typeof e=="string"){const i=e.match(/^\{([a-z][a-z0-9_]*)\}$/i);return i&&i[1]==="limit"?Number(r.limit):m(e,r,!1)}return Array.isArray(e)?e.map(i=>g(i,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,s])=>[i,g(s,r)])):e}function j(e,{q:r,limit:i=8,vars:s={},site:t=""}={},{assertFetchable:o}={}){const n=String(t?`site:${t} ${r}`:r||"").trim();if(!n)throw new p("NO_QUERY","nothing to search for");const a=b(e,s);if(a.length)throw new p("MISSING_VARS",`search API '${e.id}' needs ${a.join(", ")}`);const l={...Object.fromEntries(e.vars.map(h=>[h,String(s[h])])),q:n,limit:Math.max(1,Math.min(e.maxLimit,Number(i)||8))},c=m(e.request.url,l,!0);if(new URL(c).hostname!==e.host)throw new p("BAD_API",`search API '${e.id}': the request left its host`);typeof o=="function"&&o(c);const u={Accept:"application/json",...Object.fromEntries(Object.entries(e.request.headers).map(([h,k])=>[h,m(k,l,!1)]))};let w=null;return e.request.method==="POST"&&(w=JSON.stringify(g(e.request.body??{},l)),u["Content-Type"]=u["Content-Type"]||"application/json"),{url:c,method:e.request.method,headers:u,body:w}}function v(e,r){return r?String(r).split(".").reduce((i,s)=>i?.[s],e):e}function d(e,r){if(!r)return"";if(Array.isArray(r)){for(const s of r){const t=d(e,s);if(t)return t}return""}if(typeof r=="object"&&r.template)return m(r.template,new Proxy({},{has:(s,t)=>e?.[t]!=null,get:(s,t)=>e?.[t]}),!0);const i=v(e,r);return Array.isArray(i)?i.map(s=>s&&typeof s=="object"?s.value??s.text??"":s).join(i.every(s=>typeof s=="object")?"":" "):i==null||typeof i=="object"?"":String(i)}const x=e=>String(e||"").replace(/<[^>]*>/g,"").replace(/&quot;/g,'"').replace(/&#0?39;/g,"'").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/\s+/g," ").trim();function T(e,r,{limit:i=8}={}){const s=v(r,e.response.results);if(!Array.isArray(s))return[];const t=[],o=new Set;for(const n of s){const a=d(n,e.response.url).trim();if(!/^https?:\/\/[^\s]+$/i.test(a)||o.has(a))continue;o.add(a);const l={url:a,title:x(d(n,e.response.title))||a,snippet:x(d(n,e.response.snippet)).slice(0,500)},c=d(n,e.response.text);c&&(l.text=c.slice(0,2e4));const u=d(n,e.response.published);if(u&&(l.published=u),t.push(l),t.length>=i)break}return t}function E(e,{enabled:r=!0}={}){return Object.freeze({id:`api:${e.id}`,name:e.name,kind:"api",url:e.request.url,needsKey:e.needsKey,enabled:r,api:e})}const P=Object.freeze([E(y({preset:"mwmbl"}))]),_=["id","preset","name","request","response","needsKey","maxLimit"],A=e=>P.some(r=>r.api.id===e?.id)&&!e?.request&&!e?.preset;function O(e=[]){const r=Array.isArray(e)?e:[],i=new Set(r.filter(o=>o?.enabled===!1).map(o=>o.id)),s=[];for(const o of r){if(!o||A(o))continue;let n;try{n=y(o)}catch{continue}const a=o.vars||{};s.push({...E(n,{enabled:o.enabled!==!1&&!b(n,a).length}),vars:a})}return[...P.filter(o=>!i.has(o.api.id)&&!s.some(n=>n.api.id===o.api.id)),...s]}function K(e=[],r=[]){if(!Array.isArray(r))throw new p("BAD_API","search APIs: a list of edits");const i=(Array.isArray(e)?e:[]).map(s=>({...s,vars:{...s?.vars||{}}}));for(const s of r){if(!s||typeof s!="object"||!s.id)throw new p("BAD_API","each search API needs an id");const t=i.findIndex(a=>a.id===s.id);if(s.remove===!0){t>=0&&i.splice(t,1);continue}const o=t>=0?i[t]:{},n={...o,enabled:s.enabled??o.enabled??!0,vars:{...o.vars||{}}};for(const a of _)a in s&&(n[a]=s[a]);for(const[a,l]of Object.entries(s.vars||{}))l===null||l===""?delete n.vars[a]:typeof l=="string"&&(n.vars[a]=l.trim());A(n)||y(n),t>=0?i[t]=n:i.push(n)}return i}function D(e=[]){const r=Array.isArray(e)?e:[],i=O(r).map(t=>({id:t.api.id,preset:t.api.preset,name:t.api.name,host:t.api.host,needsKey:t.api.needsKey,enabled:t.enabled,custom:!t.api.preset,vars:Object.fromEntries(t.api.vars.map(o=>[o,!!String(t.vars?.[o]??"").trim()])),missing:b(t.api,t.vars||{}),request:{method:t.api.request.method,url:t.api.request.url,headers:Object.keys(t.api.request.headers)},response:t.api.response})),s=r.filter(t=>t?.enabled===!1&&A(t)).map(t=>({id:t.id,enabled:!1,preset:t.id,name:q[t.id]?.name||t.id,missing:[]}));return[...i,...s]}export{P as DEFAULT_API_ENGINES,q as SEARCH_API_PRESETS,p as SearchApiError,E as apiEngine,O as apiEnginesFrom,j as buildApiRequest,y as defineSearchApi,b as missingVars,K as patchApiEntries,T as readApiResponse,D as viewApiEntries};
@@ -0,0 +1 @@
1
+ const r=Object.freeze({ANSWERED:"answered",NOTHING:"nothing",BLOCKED:"blocked",RESTING:"resting",OFFLINE:"offline",NO_ENGINES:"no-engines"});function g(e){return e?.kind==="gateway"?"gateway":e?.kind==="api"?"api":e?.kind==="tab"?"browser":"page"}function h(e,t){const i=g(t);return(Array.isArray(e)?e:[]).map(n=>({engine:t?.id||"",via:i,...n}))}function c({results:e=[],asked:t=[],resting:i=[]}={}){return e.length?r.ANSWERED:t.length?t.some(n=>n.outcome==="empty"||n.outcome==="answered")?r.NOTHING:t.every(n=>n.network)?r.OFFLINE:r.BLOCKED:i.length?r.RESTING:r.NO_ENGINES}const d={duckduckgo:"DuckDuckGo",startpage:"Startpage",bing:"Bing",google:"Google",gateway:"your gateway","api:mwmbl":"Mwmbl","api:exa":"Exa","api:brave":"Brave","api:tavily":"Tavily","api:serper":"Serper","api:serpapi":"SerpApi","api:google":"Google Programmable Search","api:jina":"Jina","api:wikipedia":"Wikipedia"};function o(e,t={}){return t[e]||d[e]||String(e||"").replace(/^api:/,"")}function f(e){return e.outcome==="answered"?`${e.found} result${e.found===1?"":"s"}`:e.outcome==="empty"?"found nothing":e.timedOut?"timed out":e.status===429?"refused (too many requests)":e.status===403?"refused (blocked)":e.status>=500?`failed (${e.status})`:e.status>0?`refused (${e.status})`:"could not be reached"}const p=e=>{const t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`};function l(e={},{names:t={}}={}){const i=c(e),n=(e.asked||[]).map(a=>`${o(a.id,t)} ${f(a)}`),s=(e.resting||[]).map(a=>`${o(a.id,t)} until ${p(a.until)}`);s.length&&n.push(`resting: ${s.join(", ")}`);const u={[r.ANSWERED]:"",[r.NOTHING]:"The engines answered but had nothing for this wording — try a shorter, more general query (drop dates and qualifiers).",[r.BLOCKED]:"The engines refused the request — this says nothing about whether the information exists. Try again in a few minutes, or add a search API in Settings › Web search.",[r.RESTING]:"Every engine is resting after refusing earlier searches, so none was asked. Try again later, or add a search API in Settings › Web search.",[r.OFFLINE]:"No search engine could be reached — the device may be offline.",[r.NO_ENGINES]:"No search engine is switched on — turn one on in Settings › Web search."}[i];return{status:i,line:n.join(" · "),advice:u}}export{r as SEARCH_STATUS,o as engineLabel,c as searchStatus,l as summarizeSearch,h as tagResults,g as viaOf};