@chatpanel/gateway 0.137.1 → 0.139.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -3
- package/src/aec-engine.js +1 -1
- package/src/diarize-engine.js +1 -1
- package/src/file-read.js +1 -0
- package/src/indic-engine.js +1 -1
- package/src/indictrans-engine.js +1 -1
- package/src/inference-lane.js +1 -1
- package/src/model-pull.js +1 -1
- package/src/ort.js +2 -2
- package/src/pocket-tts-engine.js +1 -1
- package/src/runtime.js +6 -6
- package/src/segment-engine.js +1 -1
- package/src/server.js +14 -14
- package/src/stt-engine.js +1 -1
- package/src/translate-engine.js +1 -1
- package/src/tts-engine.js +1 -1
- package/src/vad-engine.js +1 -1
- package/src/version.js +1 -1
package/src/runtime.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{promisify as xt}from"node:util";import{execFile as Pt}from"node:child_process";import{existsSync as Qe,mkdirSync as pe,writeFileSync as ye,accessSync as Nn,openSync as Et,closeSync as Ot,constants as Ln}from"node:fs";import{randomBytes as Bt,createHash as Nt}from"node:crypto";import ie from"node:os";import $ from"node:path";import{modelsFor as Tn,isValidModelId as Cn,catalogFor as $e,vllmTaskOf as he}from"./runtime-models.js";import{pickInferenceEngine as Rn,pickLlamaEngine as Lt,pickMlxEngine as Tt,pickAppleEngine as Ct,recommendEngine as Rt,detectAccelerator as Gt,hostShape as Ut}from"./inference-engines.js";import{tuningArgs as ve,tuningRows as Gn,patchTunings as Un,profilesFor as Hn,resolveTunings as In,splitTunings as ge,ENGINE_DOCS as Ht}from"./engine-tunings.js";import{IMAGE_RECIPES as It}from"./images.js";import{pullRepo as Ft,pullGguf as jt,repoInstalled as Dt,ggufInstalled as Fn,ggufRecipe as Ye,planGgufRecipe as Xt}from"./model-pull.js";import{llamaKnows as jn,llamaFlags as zt}from"./llama-arch.js";import{installBuild as Vt,installedBuild as Wt,UNSLOTH_LLAMA as v,LLAMA_BUILDS as Dn,DEFAULT_LLAMA_BUILD as Jt}from"./llama-builds.js";import{liveFit as qt,kvCacheMB as Kt,cachedConfigPath as Qt,needMB as Xn}from"./host-memory.js";import{APPLE_HELPER as Ze,APPLE_MODEL_ID as Yt,APPLE_MIN_DARWIN as Zt,appleHelperDirs as er,appleInstallDoor as nr,darwinMajor as zn}from"./apple-model.js";import{transferRate as tr}from"./transfer-rate.js";import{capabilityList as Se,primaryProvider as rr,withProvider as Vn,withoutProvider as Wn}from"./capability-config.js";import{isEmbeddedModel as ir}from"./embedded-models.js";import{spawn as ar}from"node:child_process";import{readFileSync as Jn,unlinkSync as qn,realpathSync as or,readdirSync as Kn}from"node:fs";const sr=xt(Pt),Me=["podman","docker"],ae="hf-cache",F=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],helper:!0,blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only.",caps:["CHOWN","SETGID","SETUID"],answers:async(r,l)=>{try{return(await l(`${r}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.search?.searxng?.url||""),configure:(r,l)=>{r.search=r.search||{},r.search.searxng={...r.search.searxng||{},url:l}},unconfigure:(r,l)=>{r.search?.searxng?.url===l&&(r.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],helper:!0,adapter:"tei",model:"BAAI/bge-reranker-base",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. The gateway already reranks in-process by default (a small model, no container); start this to run a multilingual cross-encoder (bge-reranker base by default) in a container instead, behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"rerank","reranker")?.url||""),configure:(r,l,f)=>_e(r,"rerank",{url:l,adapter:f.adapter,model:f.model,service:f.id}),unconfigure:(r,l)=>xe(r,"rerank",f=>f.url===l)},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],helper:!0,adapter:"systemone",retired:{why:"Retired — decisions are answered in the gateway with the same zero-shot models. Bring another decision model on the Models page.",instead:"Models › Decide"},model:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. The gateway already decides in-process by default with the same algorithm and model; start this to run it in a container instead. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"decide","opendecision")?.url||""),configure:(r,l,f)=>_e(r,"decide",{url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}),unconfigure:(r,l)=>xe(r,"decide",f=>f.url===l)},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:r=>Rn({...r,containerOnly:!0}),container:"chatpanel-vllm",port:8891,containerPort:8e3,provides:["chat","embed","stt"],adapter:"openai",model:"Qwen/Qwen3-0.6B",pull:!0,blurb:"Your own model, served by vLLM on this machine’s accelerator (CUDA, ROCm, XPU — or CPU): a chat model the router can send turns to, an embedding model for semantic search, or a transcriber for every ear. OpenAI-shaped, loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${r.model}`,...r.installed?["HF_HUB_OFFLINE=1"]:[]],args:(r,l)=>["--model",r.model,"--host","0.0.0.0","--port","8000",...he(r.model)==="embed"?["--task","embed"]:[],...ve("vllm",r.tunings,{task:he(r.model),model:r.model,backend:l?.backend||null})],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"embed","vllm")?.url?.replace(/\/v1$/,"")||Ae(r,"stt","vllm")?.url?.replace(/\/v1$/,"")||(r.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{const p=`${l}/v1`,R=he(f.model);Qn(r),R==="chat"?(r.destinations=(r.destinations||[]).filter(h=>h?.service!=="vllm"&&h?.id!=="vllm"),r.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:p,models:[f.model],service:"vllm"})):R==="embed"?_e(r,"embed",{url:p,adapter:"openai",model:f.model,service:"vllm"}):R==="transcription"&&_e(r,"stt",{provider:"container",url:p,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:r=>Qn(r)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:r=>Rn(r),only:{platform:"darwin",arch:"arm64"},port:8892,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU, served by vLLM-Metal: a chat model the router can send turns to. A process on this machine behind the gateway, loopback only.",command:(r,l)=>["vllm",["serve",r.model,"--host","127.0.0.1","--port",String(r.port),...ve("vllm-metal",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="vllm-metal"&&p?.id!=="vllm-metal"),r.destinations.push({id:"vllm-metal",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:r=>Lt(r),port:8893,provides:["chat"],adapter:"openai",model:"unsloth/Qwen3-4B-GGUF:Q4_K_M",blurb:"Your own GGUF model on this machine, served by llama.cpp: the Metal GPU on a Mac, CUDA or Vulkan elsewhere, CPU otherwise — a chat model the router can send turns to, with the flags that make it fast set for this machine. A process on this machine behind the gateway, loopback only.",alias:r=>/\.gguf$/i.test(r)?r.split(/[\\/]/).pop().replace(/\.gguf$/i,""):r.split("/").pop().split(":")[0],command:(r,l)=>["llama-server",[...r.file?["-m",r.file]:/\.gguf$/i.test(r.model)?["-m",r.model]:["-hf",r.model],"--host","127.0.0.1","--port",String(r.port),"--alias",r.alias(r.model),"--jinja",...ve("llama",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="llama"&&p?.id!=="llama"),r.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:r=>Tt(r),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU through MLX — Apple’s framework, the lightest way to run a chat model on a Mac. A process on this machine behind the gateway, loopback only.",command:(r,l)=>["mlx_lm.server",["--model",r.model,"--host","127.0.0.1","--port",String(r.port),...ve("mlx",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="mlx"&&p?.id!=="mlx"),r.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}},{id:"apple",label:"Apple on-device",kind:"native",auto:!0,runner:Ze,engineOf:r=>Ct(r),only:{platform:"darwin",arch:"arm64",minDarwin:Zt,label:"macOS 26 or later on Apple Silicon"},port:8895,provides:["chat"],adapter:"openai",window:4096,card:{engine:"apple",backend:"apple",where:"this machine",egress:"none",cost:"free",task:"chat",window:4096,vision:!1,tools:!1,reasoning:!1,label:"Apple on-device",licence:"Apple",draft:!1},blurb:"Apple’s own model, on this Mac (macOS 26 with Apple Intelligence on): the system loads it when asked and frees it when idle, so nothing stays loaded and nothing runs hot — the lightest choice for titles, topics and short answers. Text only, 4,096 tokens at a time. A small helper on this machine behind the gateway, loopback only.",command:r=>[Ze,["serve","--port",String(r.port)]],answers:async(r,l)=>{try{const f=await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)});return f.ok&&(await f.json())?.ok===!0}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="apple")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l)=>{r.destinations=(r.destinations||[]).filter(f=>f?.service!=="apple"&&f?.id!=="apple"),r.destinations.push({id:"apple",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[Yt],service:"apple"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),oe=r=>r.only?.label||`${r.only?.platform||"this platform"} ${r.only?.arch||""}`.trim();function Qn(r){Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),xe(r,"embed",l=>l.service==="vllm"),xe(r,"stt",l=>l.service==="vllm")}function Ae(r,l,f){return Se(r.capabilities?.[l],l).providers.find(p=>p.service===f)||null}function en(r,l,f){r.capabilities=r.capabilities||{},f?r.capabilities[l]=f:delete r.capabilities[l]}function _e(r,l,f){en(r,l,Vn(r.capabilities?.[l],l,f,{match:p=>p.service===f.service}))}function xe(r,l,f){r.capabilities?.[l]&&en(r,l,Wn(r.capabilities[l],l,f))}const A=r=>F.find(l=>l.id===r)||null,lr=({answers:r,configured:l,configure:f,unconfigure:p,volumes:R,args:h,env:z,caps:Pe,command:Ee,engineOf:tn,alias:Oe,...B})=>B,ur=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),cr=Object.freeze(["brave","qwant"]);function dr(r=[]){const l=r.length?r:ur,f=cr.filter(p=>!l.includes(p));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(p=>[` - name: ${p}`," disabled: false"]),...f.flatMap(p=>[` - name: ${p}`," disabled: true"]),""].join(`
|
|
2
|
-
`)}function nn(r=process.platform){return r==="darwin"?{command:"brew install podman",url:"https://podman.io/docs/installation#macos",note:"Homebrew; then Start the engine below (it creates and starts the Podman machine)."}:r==="win32"?{command:"winget install RedHat.Podman",url:"https://podman.io/docs/installation#windows",note:"Then Start the engine below (it creates and starts the Podman machine under WSL)."}:{command:"sudo apt install podman # or: sudo dnf install podman",url:"https://podman.io/docs/installation#installing-on-linux",note:"Rootless; no daemon to start."}}function Yn(r,l){const f=l==="podman"?Array.isArray(r.Names)?r.Names[0]:String(r.Names||""):String(r.Names||r.Name||""),p=l==="podman"?Array.isArray(r.Ports)?r.Ports.map(h=>`${h.host_ip||""}:${h.host_port}->${h.container_port}/${h.protocol||"tcp"}`):[]:String(r.Ports||"").split(",").map(h=>h.trim()).filter(Boolean),R=String(r.State||"").toLowerCase()||(/^up/i.test(String(r.Status||""))?"running":"exited");return{name:f,image:String(r.Image||""),state:R,status:String(r.Status||""),ports:p,ours:f.startsWith("chatpanel-"),engine:l}}const mr=15e3;function Tr({cfg:r,bridgeHealth:l,workers:f=()=>[],persist:p=()=>{},exec:R=(x,q,G={})=>sr(x,q,{timeout:6e4,killSignal:"SIGKILL",...G}),platform:h=process.platform,arch:z=process.arch,osRelease:Pe=ie.release(),spawn:Ee=ar,lookup:tn=null,archKnower:Oe=null,fetchImpl:B=globalThis.fetch,stateDir:N=$.join(ie.homedir(),".chatpanel","runtime"),log:S=()=>{},sleep:Be=x=>new Promise(q=>setTimeout(q,x)),totalMem:rn=()=>ie.totalmem(),memoryProbe:Zn=x=>h==="darwin"&&r?.runtime?.heatwatch!==!1?qt(x,{fetchImpl:B}):Promise.resolve(null),now:se=()=>Date.now(),autoEnv:et=process.env.CHATPANEL_RUNTIME_AUTO,every:an=(x,q)=>{const G=setInterval(x,q);return G.unref?.(),G}}={}){const x=ie.homedir(),q=h==="win32"?[$.join(x,"AppData","Local","Microsoft","WinGet","Links"),$.join(x,".local","bin"),$.join(x,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",$.join(x,".local","bin"),$.join(x,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin",...h==="darwin"?er({home:x}):[]],G=(n=process.env)=>{const e=h==="win32"?";":":",t=String(n.PATH||n.Path||""),i=q.filter(o=>!t.split(e).includes(o));return{...n,PATH:[...t.split(e).filter(Boolean),...i].join(e)}},
|
|
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{M=""}return{ok:!1,error:`${e.label} exited on start${M?` — ${M}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:d}}return e.configure(r,g,e),p(),S(`[runtime] ${e.label} started (pid ${m.pid}) on ${g}, sandbox ${Z[e.id].layer}${
|
|
4
|
-
`)[0]);return e.ok&&Number.isInteger(t)&&t>1?t:0}function we(n){const e=re(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{qn(ue(n))}catch{}return n.unconfigure(r,_(n)),p(),{ok:!0}}const de=n=>n.model?{...n,model:w(n),installed:J(n,w(n)),tunings:j(n,w(n)),...n.id==="llama"?{file:ut(w(n))}:{}}:n,W=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx",j=(n,e)=>{const t=r.runtime?.services?.[n.id]||{},{engine:i,model:o}=ge(t.tunings),s=e&&t.byModel?.[e]?t.byModel[e]:e&&e===w(n)?o:{};return{...i,...s}},Ie=(n,e,t)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{};const i=r.runtime.services[n.id]||{},{engine:o,model:s}=ge(t),a={...i.byModel||{}};e&&(Object.keys(s).length?a[e]=s:delete a[e]),r.runtime.services[n.id]={...i,tunings:o,...Object.keys(a).length?{byModel:a}:{}},Object.keys(a).length||delete r.runtime.services[n.id].byModel};function pn(){let n=!1;for(const e of F.filter(W)){const t=r.runtime?.services?.[e.id];if(!t?.tunings)continue;const{model:i}=ge(t.tunings);if(!Object.keys(i).length)continue;const o=w(e);o?Ie(e,o,{...i,...(t.byModel||{})[o]||{},...ge(t.tunings).engine}):t.tunings=ge(t.tunings).engine,n=!0}n&&p()}function lt(n,e){const t=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},o=$e(n.id).filter(c=>!c.minRamMB||t>0&&t>=c.minRamMB);if(!o.length||!t)return null;const s=o.slice().sort((c,u)=>(i[u.tier]??-1)-(i[c.tier]??-1)||c.ramMB-u.ramMB)[0],a=Math.round(s.ramMB/1024*10)/10;return{model:s.id,label:s.label,why:`This machine (${e.ramGB} GB${e.accelerator==="apple"?", Apple Silicon":e.accelerator?`, ${e.accelerator.toUpperCase()} GPU`:", no GPU"}) runs ${s.label} well — about ${a} GB while loaded${s.tier==="max"?"; the strongest in the list":""}.`,profile:"coding",current:w(n)===s.id}}async function hn(n,{model:e,ctx:t,needMB:i}={}){const o=A(n);if(!o||!o.model)return{ok:!1,error:o?`${o.label} takes no model`:`unknown service ${n}`};const s=String(e||w(o)),a=$e(n).find(Ke=>Ke.id===s)||null,c=Number(i)>0?Number(i):a?.ramMB||null;if(!c)return{ok:!1,error:`${s} is not in the catalogue — pass need_mb (its peak memory while serving)`};const u=Number(t)>0?Number(t):En(n),d=/\.gguf$/i.test(s)||o.id==="llama"?null:Qt(X(),s),m=u&&d?Kt(d,u):null,k=Xn({ramMB:c,kvMB:m||0}),g=o.kind==="native"?await Zn(k):null,
|
|
5
|
-
`).filter(Boolean).map(i=>{try{return Yn(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Sn(n,e){const t=await
|
|
6
|
-
`).map(s=>s.split(" ")).filter(s=>s[0]).map(([s,a])=>[s,/running/i.test(a||"")?"running":"stopped"]));for(const s of e)i[s]=o.get(s)||"absent";return i}const _=n=>`http://127.0.0.1:${n.port}`;async function Mn(){const n=await P(),e=n.preferred,t=await $n(e,n),i={},o=await H(e),s=e&&n[e].running?await De(e,F.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of F){const c=_(a);let u="no-engine";if(a.kind==="native"?u=ce(a):e&&n[e].running?u=s[a.container]||"absent":e&&(u="engine-stopped"),a.retired&&!["running","stopped","exited","created","paused"].includes(u))continue;const d=a.model?w(a):null,m=a.engineOf?Y(a)?{...a.engineOf({...o,llamaOnPath:!0}),install:tt}:a.engineOf(o):null,k=a.kind==="native"?(o.ramGB||0)*1024:t;i[a.id]={...lr(a),engine:a.kind==="native"?"host":e,state:u,url:c,configured:a.configured(r),answering:u==="running"?await a.answers(c,B):!1,...a.helper?{asleep:I.has(a.id),idleMinutes:On()/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"&&!C(a)?{why:`${a.label} runs on ${oe(a)} only`}:{},...a.id==="llama"&&C(a)?{...d&&Ye(X(),d).recommended?{recommended:Ye(X(),d).recommended}:{},build:te(),builds:[{id:"unsloth",label:v.label,why:v.why,installed:!!V(),version:V()?.tag||null,default:!0},{id:"system",label:"The system’s llama.cpp",why:"Homebrew’s, or one you built — `llama-server` on PATH",installed:!!Le("llama-server"),version:ne("llama-server")}],...te()==="unsloth"?V()?{runnerVersion:V().tag,updatable:!0}:{}:K[a.runner]?{runnerVersion:ne(a.runner),updatable:!!m?.install?.update?.steps?.length}:{}}:a.kind==="native"&&a.runner&&C(a)&&K[a.runner]?{runnerVersion:ne(a.runner),updatable:!!m?.install?.update?.steps?.length}:{},...a.auto&&u!=="running"&&C(a)?{auto:!0,...Ue(a)?{why:"Stopped here — Start turns it back on"}:L[a.id]?{why:L[a.id]}:{}}:a.auto?{auto:!0}:{},...!a.auto&&a.kind==="native"&&u!=="running"&&C(a)&&L[a.id]?{why:L[a.id]}:{},...a.kind==="native"&&Z[a.id]?{sandbox:Z[a.id]}:{},...y[a.id]?{job:{kind:y[a.id].kind,since:y[a.id].since,detail:y[a.id].detail||null,step:y[a.id].step||null,minutes:y[a.id].minutes||null,progress:y[a.id].progress,lines:y[a.id].lines.slice(-4),done:y[a.id].done,error:y[a.id].error,waiting:!!y[a.id].waiting,cancelled:!!y[a.id].cancelled}}:{},...W(a)?{profiles:Hn(a.id,j(a,d),D(a,d,m,o)),docs:Ht[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:lt(a,o)}:{},...a.model?{model:d,default:a.model,models:Tn(a.id,{active:d,engineRamMB:k,engine:a.kind==="native"?"host":e,platform:h,installed:g=>J(a,g)}),machine:{engineRamMB:k}}:{},...W(a)?{tunings:Gn(a.id,j(a,d),D(a,d,m,o))}:{}}}return i}async function mt(){const n=await P(),e=await H(n.preferred);return{platform:h,arch:z,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:Rt(e)}}function An(n,{settingsFile:e=null,secret:t=null,pick:i=null,cpus:o=null}={}){const s=de(n),a=["run","-d","--name",s.container,"--restart","no","-p",`127.0.0.1:${s.port}:${s.containerPort}`];s.helper&&o&&a.push("--cpus",String(o));for(const u of s.volumes?s.volumes(N):[])a.push("-v",u);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const u of s.env?s.env(s):[])a.push("-e",u);s.helper&&o&&a.push("-e",`THREADS=${o}`),t&&a.push("-e",`SEARXNG_SECRET=${t}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${s.port}/`),a.push("--cap-drop","ALL");for(const u of s.caps||[])a.push("--cap-add",u);i?.devices?.length&&a.push(...i.devices),a.push(i?.image||s.image,...s.args?s.args(s,i):[]);const c=Nt("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 Xe={};async function ft(n){if(Xe[n]==null){const e=await b(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),t=Number.parseInt(e.out,10);Xe[n]=Number.isFinite(t)&&t>0?t:ie.cpus()?.length||2}return Math.max(1,Math.floor(Xe[n]/2))}async function ee(n,{force:e=!1}={}){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(t.retired)return{ok:!1,error:t.retired.why,retired:!0};I.delete(t.id),qe(t.id),t.auto&&Ue(t)&&un(t,!1);const i=y[t.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let o=null;if(t.kind!=="native"){const d=await P();if(o=d.preferred,!o)return{ok:!1,error:"no container engine — install Podman first",install:nn(h)};if(!d[o].running){const m=await je(o);if(!m.ok)return m}}else if(!C(t))return{ok:!1,error:`${t.label} runs on ${oe(t)} only`};const s=await H(o),a=t.engineOf?t.engineOf(s):null;if(t.kind==="native"&&!Y(t)&&!await U(t.runner,t.runnerCheck))return{ok:!1,error:ln(t,a?.install),install:a?.install};if(t.model&&/\.gguf$/i.test(w(t))&&!Qe(w(t)))return{ok:!1,error:`no such file: ${w(t)}`};if(t.kind==="native"&&t.model&&!e){const d=await hn(t.id);if(d.live&&!d.fits)return{ok:!1,error:d.advice,plan:d}}const c=await dt(t,o,a);if(!c.length){if(delete y[t.id],t.kind!=="native")return ze(t,o);const d=await Ge(t);return d.ok?delete L[t.id]:L[t.id]=d.error,d}const u=me(t,c[0]==="runner"?"install":c[0]==="image"?"pull-image":"pull-model",{detail:c[0]==="runner"?v.label:c[0]==="image"?a?.image||t.image:w(t)});return c.includes("model")&&mn(t,w(t),!0),u.then=(async()=>{try{if(c.includes("runner")){const m=await Ce(u);if(!m.ok)throw new Error(m.error)}if(c.includes("image")){const m=await ct(o,a,t,u);if(!m.ok)throw new Error(m.error)}if(c.includes("model")){const m=await yn(t,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=t.label;const d=t.kind==="native"?await Ge(t):await ze(t,o);if(!d.ok)throw new Error(d.error);u.done=!0,u.result=d,S(`[runtime] ${t.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(d){u.done=!0,u.error=u.cancelled?"cancelled":d.message,S(`[runtime] ${t.label}: ${u.error}`)}finally{c.includes("model")&&He(t)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function pt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const t=y[e.id];if(!t||t.done)return{ok:!0,nothing:!0};if(t.cancelled=!0,t.child){try{t.child.kill("SIGTERM")}catch{}const i=t.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return O(t,"cancelled"),S(`[runtime] ${e.label}: job cancelled (${t.kind})`),{ok:!0,cancelled:t.kind}}async function ze(n,e){let t=await Sn(e,n.container);const i=n.helper?await ft(e):null,o=n.engineOf?n.engineOf(await H(e)):null,s=n.id==="searxng"?$.join(N,"searxng-settings.yml"):null,a=An(n,{settingsFile:s,secret:n.id==="searxng"?"x":null,pick:o,cpus:i});if(t!=="absent"){const d=await b(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!d.ok||d.out!==a.hash)&&(S(`[runtime] ${n.label}: made with older settings — re-creating it`),await b(e,["rm","-f",n.container],{timeout:6e4}),t="absent")}if(t!=="running")if(t==="stopped"){const d=await b(e,["start",n.container],{timeout:6e4});if(!d.ok)return{ok:!1,error:`${e} start: ${d.err||d.out}`}}else{pe(N,{recursive:!0,mode:448});let d=null;n.id==="searxng"&&(ye(s,dr(String(r.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),d=Bt(32).toString("hex")),n.volumes&&pe($.join(N,ae),{recursive:!0,mode:448});const{args:m}=An(n,{settingsFile:s,secret:d,pick:o,cpus:i});S(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const k=await b(e,m,{timeout:6e5});if(!k.ok)return{ok:!1,error:`${e} run: ${k.err||k.out}`}}const c=_(n);let u=!1;for(let d=0;d<30&&!u;d++)u=await n.answers(c,B),u||await Be(1e3);return n.configure(r,c,de(n)),p(),{ok:!0,url:c,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:w(n)}:{}}}async function ht(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(I.delete(e.id),delete Je[e.id],e.auto&&un(e,!0),e.kind==="native")return we(e);const t=await P(),i=t.preferred;if(i&&t[i].running){const o=await b(i,["stop",e.container],{timeout:6e4});if(!o.ok&&!/no such container/i.test(o.err))return{ok:!1,error:`${i} stop: ${o.err||o.out}`}}return e.unconfigure(r,_(e)),p(),{ok:!0}}async function gt(n,e){const t=A(n);if(!t||t.id!=="llama")return{ok:!1,error:"a build is chosen for llama.cpp"};if(!Dn.includes(e))return{ok:!1,error:`one of ${Dn.join(", ")}`};r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{};const i={...r.runtime.services.llama||{}};e==="system"?i.build="system":delete i.build,r.runtime.services.llama=i,p();const o=await Ve(t,null,await P());return o.ok?{ok:!0,build:e,restarted:o.restarted,...o.pending?{pending:o.pending}:{}}:o}async function kt(n,e){const t=A(n);if(!t||t.id!=="llama")return{ok:!1,error:"a recipe is for llama.cpp (a GGUF repo)"};const i=String(e||"").trim();if(!Cn(n,i)||/\.gguf$/i.test(i))return{ok:!1,error:`not a Hugging Face id: ${JSON.stringify(e)} — owner/name, or owner/name:QUANT`};const o=((await ke()).ramGB||0)*1024,s=a=>o?Xn({ramMB:a/2**20})<=o*.75:null;try{const a=await Xt(i,{fetchImpl:B,knows:(Oe||jn)(Te()),engineVersion:sn()}),c=(a.projector?.size||0)+(a.draft?.size||0);return{ok:!0,model:`${a.repo}:${a.quant}`,quant:a.quant,arch:a.arch,layout:a.layout,main:a.main,size:a.total,projector:a.projector,draft:a.draft,quants:a.quants.map(u=>({...u,fits:s(u.size+c)})),ramGB:o/1024,fits:s(a.total+c)}}catch(a){return{ok:!1,error:a.message,...a.code?{code:a.code,arch:a.arch}:{}}}}async function wt(n,e,{tunings:t=null}={}){const i=A(n);if(!i)return{ok:!1,error:`unknown service ${n}`};if(!i.model)return{ok:!1,error:`${i.label} takes no model`};const o=String(e||"").trim();if(!Cn(n,o))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 P(),a=s.preferred,c=i.kind==="native"?((await ke()).ramGB||0)*1024:await $n(a,s),u=Tn(n,{active:o,engineRamMB:c,engine:i.kind==="native"?"host":a,platform:h,installed:g=>J(i,g)}).find(g=>g.id===o);if(u?.unavailable)return{ok:!1,error:`${o} ${u.unavailable}`};let d=null;if(t&&W(i)){const g=await H(a);if(d=Un(i.id,j(i,o),t,D(i,o,i.engineOf?i.engineOf(g):null,g)),d.error)return{ok:!1,error:d.error}}r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{},r.runtime.services[n]={...r.runtime.services[n]||{},model:o},d&&Ie(i,o,d);const m=_(i);i.configured(r)===m&&i.configure(r,m,de(i)),p();const k=await Ve(i,a,s);return k.ok?{ok:!0,model:o,restarted:k.restarted,...k.pending?{pending:k.pending}:{},...u?.ramNote?{note:u.ramNote}:{}}:k}async function Ve(n,e,t){if(n.kind==="native"){if(ce(n)!=="running")return{ok:!0,restarted:!1};we(n);const s=await ee(n.id,{force:!0});return s.ok?{ok:!0,restarted:!0,...s.pending?{pending:s.pending}:{}}:s}if(!e||!t[e].running)return{ok:!0,restarted:!1};const i=await Sn(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const o=await b(e,["rm","-f",n.container],{timeout:6e4});if(!o.ok&&!/no such container/i.test(o.err))return{ok:!1,error:`${e} rm: ${o.err||o.out}`};if(i==="running"){const s=await ee(n.id);return s.ok?{ok:!0,restarted:!0}:s}return{ok:!0,restarted:!1}}async function bt(n,e){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!W(t))return{ok:!1,error:`${t.label} takes no profile`};const i=await P(),o=await H(i.preferred),s=t.engineOf?t.engineOf(o):null,a=Hn(t.id,j(t,w(t)),D(t,w(t),s,o)).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 Pn(n,a.patch);return c.ok?{...c,profile:a.id}:c}async function We(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=y[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Y(e)){if(le())return{ok:!0,installed:!0};const s=me(e,"install",{detail:v.label});return s.then=(async()=>{const a=await Ce(s);s.done=!0,a.ok||(s.error=a.error),S(`[runtime] install ${v.label}: ${s.error||"ok"}`)})(),{ok:!0,pending:{kind:s.kind,since:s.since,detail:s.detail}}}if(delete K[e.runner],delete Q[e.runner],await U(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const o=e.engineOf(await H(null))?.install;return o?.steps?.length?_n(e,o,"install"):{ok:!1,error:`no installer for ${e.label} on this platform${o?.url?` — see ${o.url}`:""}`,install:o||null}}function _n(n,e,t){const i=me(n,t,{detail:n.runner}),o=t==="update"&&ce(n)==="running",s=ne(n.runner);return i.then=wn("install",i,async()=>{const a=async d=>{for(const[m,...k]of d){O(i,`$ ${m} ${k.join(" ")}`);let g=await be(i,m,k,{timeout:36e5});for(let E=0;!g.ok&&!i.cancelled&&E<6&&i.lines.some(M=>/already locked|Please wait for it to finish/i.test(M));E++)O(i,`another ${m} holds the lock — waiting 20 s (${E+1}/6)`),await Be(2e4),g=await be(i,m,k,{timeout:36e5});if(!g.ok&&e.upToDate&&i.lines.some(E=>new RegExp(e.upToDate,"i").test(E))&&(g={ok:!0}),!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let c=await a(e.steps);!c.ok&&!i.cancelled&&e.fallback?.length&&(O(i,`${c.error} — trying the other way`),c=await a(e.fallback)),delete K[n.runner],delete Q[n.runner];const u=c.ok&&await U(n.runner,n.runnerCheck);if(u&&t==="update"){const d=ne(n.runner);if(O(i,d&&s&&d!==s?`${n.label} ${s} → ${d}`:`${n.label}${d?` ${d}`:""} — up to date`),o&&!i.cancelled){we(n),i.done=!0;const m=await ee(n.id,{force:!0});if(m.ok||(L[n.id]=m.error,S(`[runtime] ${n.label} after the update: ${m.error}`)),m.pending)return;y[n.id]||(y[n.id]=i)}}i.done=!0,i.cancelled?i.error="cancelled":c.ok?u||(i.error=`${n.runner} still not found after the ${t} — open a new terminal and run \`${e.command}\` by hand`):i.error=`${t} failed: ${c.error}${i.lines.length?` (${i.lines.slice(-2).join(" | ")})`:""}`,S(`[runtime] ${t} ${n.runner}: ${i.error||"ok"}`)}),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function yt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=y[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Y(e)){if(!le())return We(n);const o=V()?.tag,s=ce(e)==="running",a=me(e,"update",{detail:v.label});return a.then=(async()=>{const c=await Ce(a,{tag:"latest"});if(!c.ok){a.done=!0,a.error=`update failed: ${c.error}`;return}if(O(a,c.tag!==o?`${v.label} ${o} → ${c.tag}`:`${v.label} ${c.tag} — up to date`),a.done=!0,s&&c.tag!==o&&!a.cancelled){we(e);const u=await ee(e.id,{force:!0});u.ok||(L[e.id]=u.error),y[e.id]||(y[e.id]=a)}})(),{ok:!0,pending:{kind:a.kind,since:a.since,detail:a.detail}}}if(delete K[e.runner],delete Q[e.runner],!await U(e.runner,e.runnerCheck))return We(n);const i=e.engineOf(await H(null))?.install;return i?.update?.steps?.length?_n(e,i.update,"update"):{ok:!1,error:`no updater for ${e.label} on this platform${i?.url?` — newer builds are at ${i.url}`:""}`,install:i||null}}async function xn(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const t=y[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(J(e,w(e)))return{ok:!0,installed:!0,model:w(e)};const i=me(e,"pull-model",{detail:w(e)});return mn(e,w(e),!1),i.then=(async()=>{const o=await yn(e,i);i.done=!0,o.ok||(i.error=o.error),He(e)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Pn(n,e){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!W(t))return{ok:!1,error:`${t.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await P(),o=i.preferred,s=w(t),a=await H(o),c=t.engineOf?t.engineOf(a):null,u=Un(t.id,j(t,s),e,D(t,s,c,a));if(u.error)return{ok:!1,error:u.error};Ie(t,s,u),p();const d=await Ve(t,o,i);return d.ok?{ok:!0,tunings:Gn(t.id,u,D(t,s,c,a)),restarted:d.restarted}:d}async function $t(){const n=await P(),e=n.preferred,t=e&&n[e].running?await De(e,F.filter(s=>s.kind!=="native").map(s=>s.container)):{},i={};let o=!1;return await Promise.all(F.map(async s=>{const a=s.kind==="native"?ce(s):e&&n[e].running?t[s.container]||"absent":"no-engine";i[s.id]=a==="running"&&await s.answers(_(s),B)?"up":"down";const c=(s.provides||[]).some(u=>["embedded","none"].includes(rr(r.capabilities?.[u],u)?.provider));i[s.id]==="up"&&s.configure&&!s.retired&&!c&&s.configured(r)!==_(s)&&(s.configure(r,_(s),de(s)),o=!0)})),o&&p(),i}function En(n){const e=A(n);if(e?.window)return e.window;if(!e||!W(e))return null;const t=Number(In(e.id,j(e,w(e)),D(e,w(e),null,{})).maxModelLen);return Number.isFinite(t)&&t>0?t:null}function vt(n){const e=A(n);if(e?.card)return e.card;if(!e||!W(e))return null;const t=w(e),i=In(e.id,j(e,t),D(e,t,null,{})),o=$e(e.id).find(a=>a.id===t)||null,s=e.id==="vllm"?he(t):"chat";return{engine:e.id,backend:Z[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:s,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:s==="chat"&&!!i.vision,tools:!!(s==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:s==="chat"&&!!i.reasoning&&i.reasoning!=="off",...o?{tier:o.tier||null,licence:o.licence||null,languages:o.lang||null,label:o.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}const St=10,On=()=>{const n=Number(r.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:St)*6e4},Mt=se(),Je={},I=new Set,fe={};function qe(n){Je[n]=se()}async function At(n,{force:e=!1}={}){const t=A(n);if(!t||!t.helper)return{ok:!0};if(qe(t.id),!I.has(t.id)&&!e){const i=t.container&&t.configured?.(r)?(await vn()).find(o=>o.name===t.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};I.add(t.id)}return fe[t.id]||(fe[t.id]=(async()=>{const i=await P(),o=i.preferred;if(!o)return{ok:!1,error:"no container engine"};if(!i[o].running){const a=await je(o);if(!a.ok)return a}const s=await ze(t,o);return s.ok&&(I.delete(t.id),S(`[runtime] ${t.label}: woken for a request`)),s})().finally(()=>{delete fe[t.id]})),fe[t.id]}async function Bn(){const n=On();if(!n)return[];const e=F.filter(a=>a.helper&&a.configured(r)&&!I.has(a.id)&&!fe[a.id]&&!(y[a.id]&&!y[a.id].done)&&se()-(Je[a.id]??Mt)>=n);if(!e.length)return[];const t=await P(),i=t.preferred;if(!i||!t[i].running){for(const a of e)I.add(a.id);return e.map(a=>a.id)}const o=await De(i,e.map(a=>a.container)),s=[];for(const a of e){if(o[a.container]==="running"){if(!(await b(i,["stop",a.container],{timeout:6e4})).ok)continue;S(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}I.add(a.id),s.push(a.id)}return s}return an&&an(()=>{Bn().catch(n=>S(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:qe,wake:At,sweepIdle:Bn,health:$t,contextWindow:En,modelCard:vt,async status(){const[n,e,t,i,o]=await Promise.all([l().catch(()=>null),P(),Mn(),vn(),mt()]);return{machine:o,sandbox:n?.sandbox||null,processes:{all:[...Array.isArray(n?.processes)?n.processes:[],...f()],localMcp:Array.isArray(n?.localMcp)?n.localMcp:[],warm:n?.warm||null},containers:i,refused:Array.isArray(n?.sandbox?.refused)?n.sandbox.refused:[],bridge:n?{ok:!0,version:n.version||""}:{ok:!1},engines:e,services:t}},startEngine:je,startService:ee,stopService:ht,ensureDefaults:at,retireServices:fn,removeService:rt,upcastTunings:pn,revive:ot,plan:hn,recipe:kt,setBuild:gt,isAsleep:n=>I.has(n),setModel:wt,setTunings:Pn,setProfile:bt,pullModel:xn,installRunner:We,updateRunner:yt,cancelJob:pt,services:Mn,catalogFor:$e}}export{ur as SEARXNG_DEFAULT_ENGINES,F as SERVICES,Yn as containerRow,Tr as createRuntime,nn as installDoor,dr as searxngSettings};
|
|
1
|
+
import{promisify as xt}from"node:util";import{execFile as Pt}from"node:child_process";import{existsSync as Qe,mkdirSync as pe,writeFileSync as be,accessSync as Nn,openSync as Et,closeSync as Ot,constants as Ln}from"node:fs";import{randomBytes as Bt,createHash as Nt}from"node:crypto";import ie from"node:os";import $ from"node:path";import{modelsFor as Tn,isValidModelId as Cn,catalogFor as $e,vllmTaskOf as he}from"./runtime-models.js";import{pickInferenceEngine as Rn,pickLlamaEngine as Lt,pickMlxEngine as Tt,pickAppleEngine as Ct,recommendEngine as Rt,detectAccelerator as Gt,hostShape as Ut}from"./inference-engines.js";import{tuningArgs as ve,tuningRows as Gn,patchTunings as Un,profilesFor as Hn,resolveTunings as In,splitTunings as ge,ENGINE_DOCS as Ht}from"./engine-tunings.js";import{IMAGE_RECIPES as It}from"./images.js";import{pullRepo as Ft,pullGguf as jt,repoInstalled as Dt,ggufInstalled as Fn,ggufRecipe as Ye,planGgufRecipe as Xt}from"./model-pull.js";import{llamaKnows as jn,llamaFlags as zt}from"./llama-arch.js";import{installBuild as Vt,installedBuild as Wt,UNSLOTH_LLAMA as v,LLAMA_BUILDS as Dn,DEFAULT_LLAMA_BUILD as Jt}from"./llama-builds.js";import{liveFit as qt,kvCacheMB as Kt,cachedConfigPath as Qt,needMB as Xn}from"./host-memory.js";import{APPLE_HELPER as Ze,APPLE_MODEL_ID as Yt,APPLE_MIN_DARWIN as Zt,appleHelperDirs as er,appleInstallDoor as nr,darwinMajor as zn}from"./apple-model.js";import{transferRate as tr}from"./transfer-rate.js";import{capabilityList as Se,primaryProvider as rr,withProvider as Vn,withoutProvider as Wn}from"./capability-config.js";import{isEmbeddedModel as ir}from"./embedded-models.js";import{spawn as ar}from"node:child_process";import{readFileSync as Jn,unlinkSync as qn,realpathSync as or,readdirSync as Kn}from"node:fs";const sr=xt(Pt),Me=["podman","docker"],ae="hf-cache",F=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],helper:!0,blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only.",caps:["CHOWN","SETGID","SETUID"],answers:async(r,l)=>{try{return(await l(`${r}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.search?.searxng?.url||""),configure:(r,l)=>{r.search=r.search||{},r.search.searxng={...r.search.searxng||{},url:l}},unconfigure:(r,l)=>{r.search?.searxng?.url===l&&(r.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],helper:!0,adapter:"tei",model:"BAAI/bge-reranker-base",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. The gateway already reranks in-process by default (a small model, no container); start this to run a multilingual cross-encoder (bge-reranker base by default) in a container instead, behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"rerank","reranker")?.url||""),configure:(r,l,f)=>_e(r,"rerank",{url:l,adapter:f.adapter,model:f.model,service:f.id}),unconfigure:(r,l)=>xe(r,"rerank",f=>f.url===l)},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],helper:!0,adapter:"systemone",retired:{why:"Retired — decisions are answered in the gateway with the same zero-shot models. Bring another decision model on the Models page.",instead:"Models › Decide"},model:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. The gateway already decides in-process by default with the same algorithm and model; start this to run it in a container instead. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"decide","opendecision")?.url||""),configure:(r,l,f)=>_e(r,"decide",{url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}),unconfigure:(r,l)=>xe(r,"decide",f=>f.url===l)},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:r=>Rn({...r,containerOnly:!0}),container:"chatpanel-vllm",port:8891,containerPort:8e3,provides:["chat","embed","stt"],adapter:"openai",model:"Qwen/Qwen3-0.6B",pull:!0,blurb:"Your own model, served by vLLM on this machine’s accelerator (CUDA, ROCm, XPU — or CPU): a chat model the router can send turns to, an embedding model for semantic search, or a transcriber for every ear. OpenAI-shaped, loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${r.model}`,...r.installed?["HF_HUB_OFFLINE=1"]:[]],args:(r,l)=>["--model",r.model,"--host","0.0.0.0","--port","8000",...he(r.model)==="embed"?["--task","embed"]:[],...ve("vllm",r.tunings,{task:he(r.model),model:r.model,backend:l?.backend||null})],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"embed","vllm")?.url?.replace(/\/v1$/,"")||Ae(r,"stt","vllm")?.url?.replace(/\/v1$/,"")||(r.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{const p=`${l}/v1`,R=he(f.model);Qn(r),R==="chat"?(r.destinations=(r.destinations||[]).filter(h=>h?.service!=="vllm"&&h?.id!=="vllm"),r.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:p,models:[f.model],service:"vllm"})):R==="embed"?_e(r,"embed",{url:p,adapter:"openai",model:f.model,service:"vllm"}):R==="transcription"&&_e(r,"stt",{provider:"container",url:p,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:r=>Qn(r)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:r=>Rn(r),only:{platform:"darwin",arch:"arm64"},port:8892,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU, served by vLLM-Metal: a chat model the router can send turns to. A process on this machine behind the gateway, loopback only.",command:(r,l)=>["vllm",["serve",r.model,"--host","127.0.0.1","--port",String(r.port),...ve("vllm-metal",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="vllm-metal"&&p?.id!=="vllm-metal"),r.destinations.push({id:"vllm-metal",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:r=>Lt(r),port:8893,provides:["chat"],adapter:"openai",model:"unsloth/Qwen3-4B-GGUF:Q4_K_M",blurb:"Your own GGUF model on this machine, served by llama.cpp: the Metal GPU on a Mac, CUDA or Vulkan elsewhere, CPU otherwise — a chat model the router can send turns to, with the flags that make it fast set for this machine. A process on this machine behind the gateway, loopback only.",alias:r=>/\.gguf$/i.test(r)?r.split(/[\\/]/).pop().replace(/\.gguf$/i,""):r.split("/").pop().split(":")[0],command:(r,l)=>["llama-server",[...r.file?["-m",r.file]:/\.gguf$/i.test(r.model)?["-m",r.model]:["-hf",r.model],"--host","127.0.0.1","--port",String(r.port),"--alias",r.alias(r.model),"--jinja",...ve("llama",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="llama"&&p?.id!=="llama"),r.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:r=>Tt(r),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU through MLX — Apple’s framework, the lightest way to run a chat model on a Mac. A process on this machine behind the gateway, loopback only.",command:(r,l)=>["mlx_lm.server",["--model",r.model,"--host","127.0.0.1","--port",String(r.port),...ve("mlx",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="mlx"&&p?.id!=="mlx"),r.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}},{id:"apple",label:"Apple on-device",kind:"native",auto:!0,runner:Ze,engineOf:r=>Ct(r),only:{platform:"darwin",arch:"arm64",minDarwin:Zt,label:"macOS 26 or later on Apple Silicon"},port:8895,provides:["chat"],adapter:"openai",window:4096,card:{engine:"apple",backend:"apple",where:"this machine",egress:"none",cost:"free",task:"chat",window:4096,vision:!1,tools:!1,reasoning:!1,label:"Apple on-device",licence:"Apple",draft:!1},blurb:"Apple’s own model, on this Mac (macOS 26 with Apple Intelligence on): the system loads it when asked and frees it when idle, so nothing stays loaded and nothing runs hot — the lightest choice for titles, topics and short answers. Text only, 4,096 tokens at a time. A small helper on this machine behind the gateway, loopback only.",command:r=>[Ze,["serve","--port",String(r.port)]],answers:async(r,l)=>{try{const f=await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)});return f.ok&&(await f.json())?.ok===!0}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="apple")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l)=>{r.destinations=(r.destinations||[]).filter(f=>f?.service!=="apple"&&f?.id!=="apple"),r.destinations.push({id:"apple",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[Yt],service:"apple"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),oe=r=>r.only?.label||`${r.only?.platform||"this platform"} ${r.only?.arch||""}`.trim();function Qn(r){Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),xe(r,"embed",l=>l.service==="vllm"),xe(r,"stt",l=>l.service==="vllm")}function Ae(r,l,f){return Se(r.capabilities?.[l],l).providers.find(p=>p.service===f)||null}function en(r,l,f){r.capabilities=r.capabilities||{},f?r.capabilities[l]=f:delete r.capabilities[l]}function _e(r,l,f){en(r,l,Vn(r.capabilities?.[l],l,f,{match:p=>p.service===f.service}))}function xe(r,l,f){r.capabilities?.[l]&&en(r,l,Wn(r.capabilities[l],l,f))}const A=r=>F.find(l=>l.id===r)||null,lr=({answers:r,configured:l,configure:f,unconfigure:p,volumes:R,args:h,env:z,caps:Pe,command:Ee,engineOf:tn,alias:Oe,...B})=>B,ur=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),cr=Object.freeze(["brave","qwant"]);function dr(r=[]){const l=r.length?r:ur,f=cr.filter(p=>!l.includes(p));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(p=>[` - name: ${p}`," disabled: false"]),...f.flatMap(p=>[` - name: ${p}`," disabled: true"]),""].join(`
|
|
2
|
+
`)}function nn(r=process.platform){return r==="darwin"?{command:"brew install podman",url:"https://podman.io/docs/installation#macos",note:"Homebrew; then Start the engine below (it creates and starts the Podman machine)."}:r==="win32"?{command:"winget install RedHat.Podman",url:"https://podman.io/docs/installation#windows",note:"Then Start the engine below (it creates and starts the Podman machine under WSL)."}:{command:"sudo apt install podman # or: sudo dnf install podman",url:"https://podman.io/docs/installation#installing-on-linux",note:"Rootless; no daemon to start."}}function Yn(r,l){const f=l==="podman"?Array.isArray(r.Names)?r.Names[0]:String(r.Names||""):String(r.Names||r.Name||""),p=l==="podman"?Array.isArray(r.Ports)?r.Ports.map(h=>`${h.host_ip||""}:${h.host_port}->${h.container_port}/${h.protocol||"tcp"}`):[]:String(r.Ports||"").split(",").map(h=>h.trim()).filter(Boolean),R=String(r.State||"").toLowerCase()||(/^up/i.test(String(r.Status||""))?"running":"exited");return{name:f,image:String(r.Image||""),state:R,status:String(r.Status||""),ports:p,ours:f.startsWith("chatpanel-"),engine:l}}const mr=15e3;function Tr({cfg:r,bridgeHealth:l,workers:f=()=>[],persist:p=()=>{},exec:R=(x,q,G={})=>sr(x,q,{timeout:6e4,killSignal:"SIGKILL",...G}),platform:h=process.platform,arch:z=process.arch,osRelease:Pe=ie.release(),spawn:Ee=ar,lookup:tn=null,archKnower:Oe=null,fetchImpl:B=globalThis.fetch,stateDir:N=$.join(ie.homedir(),".chatpanel","runtime"),log:S=()=>{},sleep:Be=x=>new Promise(q=>setTimeout(q,x)),totalMem:rn=()=>ie.totalmem(),memoryProbe:Zn=x=>h==="darwin"&&r?.runtime?.heatwatch!==!1?qt(x,{fetchImpl:B}):Promise.resolve(null),now:se=()=>Date.now(),autoEnv:et=process.env.CHATPANEL_RUNTIME_AUTO,every:an=(x,q)=>{const G=setInterval(x,q);return G.unref?.(),G}}={}){const x=ie.homedir(),q=h==="win32"?[$.join(x,"AppData","Local","Microsoft","WinGet","Links"),$.join(x,".local","bin"),$.join(x,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",$.join(x,".local","bin"),$.join(x,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin",...h==="darwin"?er({home:x}):[]],G=(n=process.env)=>{const e=h==="win32"?";":":",t=String(n.PATH||n.Path||""),i=q.filter(o=>!t.split(e).includes(o));return{...n,PATH:[...t.split(e).filter(Boolean),...i].join(e)}},y=async(n,e,t={})=>{try{const i=await R(n,e,{...t,env:G(t.env)});return{ok:!0,out:String(i.stdout||"").trim(),err:String(i.stderr||"").trim()}}catch(i){return{ok:!1,out:String(i?.stdout||"").trim(),err:String(i?.stderr||i?.message||i).trim(),code:i?.code}}},w=n=>String(r.runtime?.services?.[n.id]?.model||n.model||"");let Ne=null;const on=async()=>(Ne===null&&(Ne=await Gt({exec:R,platform:h,arch:z})),Ne),K={},nt=n=>{const e=h==="win32"?";":":",t=h==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of G().PATH.split(e).filter(Boolean))for(const o of t)try{return Nn($.join(i,n+o),Ln.X_OK),!0}catch{}return!1},Le=n=>{const e=h==="win32"?";":":",t=h==="win32"?[".exe",""]:[""];for(const i of G().PATH.split(e).filter(Boolean))for(const o of t){const s=$.join(i,n+o);try{return Nn(s,Ln.X_OK),s}catch{}}return null},Q={},U=async(n,e=["--version"])=>{if(K[n])return!0;if(Q[n]!==void 0&&se()-Q[n]<mr)return!1;const t=(tn||nt)(n)||(await y(n,e,{timeout:8e3})).ok;return t?(K[n]=!0,delete Q[n]):Q[n]=se(),t},ne=n=>{const e=Le(n);let t;try{t=or(e)}catch{return null}const i=/[\\/]Cellar[\\/][^\\/]+[\\/]([^\\/]+)[\\/]/.exec(t);if(i)return i[1].replace(/_\d+$/,"");try{const o=$.join($.dirname(t),"..","lib");for(const s of Kn(o)){const a=$.join(o,s,"site-packages"),c=Kn(a).find(u=>/\.dist-info$/.test(u)&&u.toLowerCase().startsWith(`${$.basename($.dirname($.dirname(t))).replace(/-/g,"_").toLowerCase()}-`));if(c){const u=c.replace(/\.dist-info$/,"");return u.slice(u.lastIndexOf("-")+1)}}}catch{}return null},te=()=>r.runtime?.services?.llama?.build==="system"?"system":Jt,Y=n=>n?.id==="llama"&&te()==="unsloth",V=()=>Wt(N,h),le=()=>te()==="system"?"llama-server":V()?.bin||null,Te=()=>te()==="system"?Le("llama-server"):V()?.bin||null,sn=()=>te()==="system"?ne("llama-server"):V()?.tag||null,tt=Object.freeze({command:`downloaded from github.com/${v.repo} (${v.tag}), checked against its SHA-256`,note:`${v.label}: ${v.why}.`,url:`https://github.com/${v.repo}/releases`,update:{command:`the newest ${v.label} release, checked against its SHA-256`,steps:[["unsloth-llama"]]}});async function Ce(n,{tag:e=v.tag}={}){n.kind=n.kind==="update"?"update":"install",n.detail=v.label,P(n,`fetching ${v.label} (${e==="latest"?"the newest release":e}) from github.com/${v.repo}`);try{const t=await Vt({stateDir:N,platform:h,arch:z,accelerator:await on(),tag:e,fetchImpl:B,run:y,onProgress:gn(n)});return P(n,t.already?`${v.label} ${t.tag} — already here`:`${v.label} ${t.tag} — checked against its published SHA-256`),{ok:!0,...t}}catch(t){return{ok:!1,error:n.cancelled?"cancelled":t.message}}}const ln=(n,e)=>e?.missing||`\`${n.runner}\` is not on PATH — install it first (${e?.command||""}), or click Install`;let Re=null;const ke=async()=>(Re||(Re=await Ut({exec:R,platform:h,totalmem:rn,cpus:()=>ie.cpus()})),Re),H=async n=>({platform:h,arch:z,accelerator:await on(),engine:n,vllmOnPath:await U("vllm"),llamaOnPath:await U("llama-server"),mlxOnPath:h==="darwin"&&z==="arm64"?await U("mlx_lm.server",["--help"]):!1,osMajor:h==="darwin"?zn(Pe):0,appleOnPath:h==="darwin"&&z==="arm64"?await U(Ze):!1,appleInstall:h==="darwin"?nr({home:x}):null,...await ke()}),C=n=>!n.only||(!n.only.platform||n.only.platform===h)&&(!n.only.arch||n.only.arch===z)&&(!n.only.minDarwin||zn(Pe)>=n.only.minDarwin),ue=n=>$.join(N,`${n.id}.pid`),re=n=>{try{const e=Number(Jn(ue(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},ce=n=>C(n)?re(n)?"running":"stopped":"unsupported",Z={};async function Ge(n){const e=de(n);if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};if(re(e))return e.auto&&!e.configured(r)&&(e.configure(r,_(e),e),p()),{ok:!0,already:!0,url:_(e)};if(e.auto&&await e.answers(_(e),B)){const M=await st(e.port);if(M)return pe(N,{recursive:!0,mode:448}),be(ue(e),String(M),{mode:384}),Z[e.id]={layer:"none",reason:"a model engine runs on the hardware, behind the gateway"},e.configure(r,_(e),e),p(),S(`[runtime] ${e.label} was already answering on ${_(e)} (pid ${M}) — adopted`),{ok:!0,adopted:!0,url:_(e),answering:!0,provides:e.provides}}const t=await H(null),i=e.engineOf(t);if(Y(e)?!le():!await U(e.runner,e.runnerCheck))return Y(e)?{ok:!1,error:`${v.label} is not downloaded yet — Start fetches it`}:{ok:!1,error:ln(e,i.install),install:i.install};if(e.id==="llama"&&/\.gguf$/i.test(e.model)&&!Qe(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[o,s]=e.command(e,D(e,e.model,i,t)),a=e.id==="llama"?le():o,c=$.join(N,ae);pe(c,{recursive:!0,mode:448});const u={bin:a,argv:s,opts:{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,HF_HOME:c,LLAMA_CACHE:c,...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"}};Z[e.id]=u.record;const d=$.join(N,`${e.id}.log`);let m,k=null;try{try{k=Et(d,"w",384)}catch{k=null}m=Ee(u.bin,u.argv,{...u.opts,env:G(u.opts?.env),detached:!0,stdio:["ignore",k??"ignore",k??"ignore"]}),m.unref?.()}catch(M){return{ok:!1,error:`${u.bin}: ${M.message}`,install:i.install}}finally{if(k!==null)try{Ot(k)}catch{}}if(!m?.pid)return{ok:!1,error:`${u.bin} did not start`,install:i.install};be(ue(e),String(m.pid),{mode:384});const g=_(e);let O=!1;for(let M=0;M<120&&!O&&re(e);M++)O=await e.answers(g,B),O||await Be(1e3);if(!re(e)){try{qn(ue(e))}catch{}let M="";try{M=Jn(d,"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{M=""}return{ok:!1,error:`${e.label} exited on start${M?` — ${M}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:d}}return e.configure(r,g,e),p(),S(`[runtime] ${e.label} started (pid ${m.pid}) on ${g}, sandbox ${Z[e.id].layer}${O?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:g,answering:O,provides:e.provides,model:w(e),sandbox:Z[e.id]}}const Ue=n=>r.runtime?.services?.[n.id]?.off===!0,un=(n,e)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{};const t={...r.runtime.services[n.id]||{}};e?t.off=!0:delete t.off,r.runtime.services[n.id]=t},cn=()=>r.runtime?.auto!==!1&&String(et||"").toLowerCase()!=="off",L={};async function dn(n){if(!n?.auto)return{ok:!1,skipped:"not a service that starts by itself"};if(!cn())return{ok:!1,skipped:"automatic start is switched off"};if(!C(n))return{ok:!1,skipped:`runs on ${oe(n)} only`};if(Ue(n))return{ok:!1,skipped:"stopped by the person"};if(!await U(n.runner,n.runnerCheck))return{ok:!1,skipped:"its helper is not in this install"};if(!re(n)){const t=await y(n.runner,["check"],{timeout:8e3});if(!t.ok){let i="";try{i=JSON.parse(t.out||"{}").message||""}catch{i=""}return L[n.id]=i||"not available on this Mac right now",{ok:!1,skipped:L[n.id]}}}const e=await Ge(n);return e.ok?(delete L[n.id],{ok:!0,...e.already?{already:!0}:e.adopted?{adopted:!0}:{started:!0}}):(L[n.id]=e.error,{ok:!1,skipped:e.error})}const mn=(n,e,t)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{},r.runtime.services[n.id]={...r.runtime.services[n.id]||{},pulling:{model:e,start:!!t}},p()},He=n=>{const e=r.runtime?.services?.[n.id];e?.pulling&&(delete e.pulling,p())};function fn(){let n=!1;for(const e of F.filter(t=>t.retired))for(const t of e.provides||[]){const i=r.capabilities?.[t];if(!i||!Se(i,t).providers.some(c=>c.service===e.id))continue;const o=Se(i,t).providers.find(c=>c.service===e.id),s={provider:"embedded",...ir(t,o?.model)?{model:o.model}:{}},a=Se(i,t).providers.some(c=>c.provider==="embedded"&&(c.model||null)===(s.model||null));en(r,t,a?Wn(i,t,c=>c.service===e.id):Vn(i,t,s,{match:c=>c.service===e.id})),S(`[runtime] ${e.label} is retired: ${t} now answers in the gateway${s.model?` with ${s.model}`:""}`),n=!0}n&&p()}async function rt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.retired)return{ok:!1,error:`${e.label} is not retired — stop it instead`};const t=(await E()).preferred;if(!t)return{ok:!1,error:"no container engine"};const i=await y(t,["rm","-f",e.container],{timeout:6e4});if(!i.ok&&!/no such container/i.test(i.err||""))return{ok:!1,error:`${t} rm: ${i.err||i.out}`};const o=await y(t,["rmi",e.image],{timeout:6e4});return e.unconfigure(r,_(e)),p(),S(`[runtime] ${e.label} removed (container${o.ok?" and image":""})`),{ok:!0,removed:{container:!0,image:!!o.ok}}}async function it(){const n=[];if(!cn())return n;for(const e of F.filter(t=>t.pull)){const t=r.runtime?.services?.[e.id]?.pulling;if(t){if(t.model!==w(e)||J(e,w(e))){He(e),J(e,w(e))&&t.start&&n.push({id:e.id,...await ee(e.id).catch(i=>({ok:!1,error:i.message}))});continue}S(`[runtime] ${e.label}: resuming the download of ${t.model} a previous run left under way`),n.push({id:e.id,resumed:t.model,...await(t.start?ee(e.id):xn(e.id)).catch(i=>({ok:!1,error:i.message}))})}}return n}async function at(){try{fn()}catch(e){S(`[runtime] retiring: ${e.message}`)}try{pn()}catch(e){S(`[runtime] settings per model: ${e.message}`)}const n=[...await it().catch(()=>[])];for(const e of F.filter(t=>t.auto))n.push({id:e.id,label:e.label,...await dn(e).catch(t=>({ok:!1,skipped:t.message}))});return n}async function ot(n){const e=A(n);return e?.auto?dn(e):{ok:!1,skipped:"not a service that starts by itself"}}async function st(n){if(h==="win32")return 0;const e=await y("lsof",["-nP",`-iTCP:${n}`,"-sTCP:LISTEN","-t"],{timeout:4e3}),t=Number(String(e.out||"").split(`
|
|
4
|
+
`)[0]);return e.ok&&Number.isInteger(t)&&t>1?t:0}function we(n){const e=re(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{qn(ue(n))}catch{}return n.unconfigure(r,_(n)),p(),{ok:!0}}const de=n=>n.model?{...n,model:w(n),installed:J(n,w(n)),tunings:j(n,w(n)),...n.id==="llama"?{file:ut(w(n))}:{}}:n,W=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx",j=(n,e)=>{const t=r.runtime?.services?.[n.id]||{},{engine:i,model:o}=ge(t.tunings),s=e&&t.byModel?.[e]?t.byModel[e]:e&&e===w(n)?o:{};return{...i,...s}},Ie=(n,e,t)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{};const i=r.runtime.services[n.id]||{},{engine:o,model:s}=ge(t),a={...i.byModel||{}};e&&(Object.keys(s).length?a[e]=s:delete a[e]),r.runtime.services[n.id]={...i,tunings:o,...Object.keys(a).length?{byModel:a}:{}},Object.keys(a).length||delete r.runtime.services[n.id].byModel};function pn(){let n=!1;for(const e of F.filter(W)){const t=r.runtime?.services?.[e.id];if(!t?.tunings)continue;const{model:i}=ge(t.tunings);if(!Object.keys(i).length)continue;const o=w(e);o?Ie(e,o,{...i,...(t.byModel||{})[o]||{},...ge(t.tunings).engine}):t.tunings=ge(t.tunings).engine,n=!0}n&&p()}function lt(n,e){const t=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},o=$e(n.id).filter(c=>!c.minRamMB||t>0&&t>=c.minRamMB);if(!o.length||!t)return null;const s=o.slice().sort((c,u)=>(i[u.tier]??-1)-(i[c.tier]??-1)||c.ramMB-u.ramMB)[0],a=Math.round(s.ramMB/1024*10)/10;return{model:s.id,label:s.label,why:`This machine (${e.ramGB} GB${e.accelerator==="apple"?", Apple Silicon":e.accelerator?`, ${e.accelerator.toUpperCase()} GPU`:", no GPU"}) runs ${s.label} well — about ${a} GB while loaded${s.tier==="max"?"; the strongest in the list":""}.`,profile:"coding",current:w(n)===s.id}}async function hn(n,{model:e,ctx:t,needMB:i}={}){const o=A(n);if(!o||!o.model)return{ok:!1,error:o?`${o.label} takes no model`:`unknown service ${n}`};const s=String(e||w(o)),a=$e(n).find(Ke=>Ke.id===s)||null,c=Number(i)>0?Number(i):a?.ramMB||null;if(!c)return{ok:!1,error:`${s} is not in the catalogue — pass need_mb (its peak memory while serving)`};const u=Number(t)>0?Number(t):En(n),d=/\.gguf$/i.test(s)||o.id==="llama"?null:Qt(X(),s),m=u&&d?Kt(d,u):null,k=Xn({ramMB:c,kvMB:m||0}),g=o.kind==="native"?await Zn(k):null,O=((await ke()).ramGB||0)*1024,M=g?g.fits:O>0&&k<=O,T=Ke=>`${Math.round(Ke/102.4)/10} GB`,_t=g?g.fits?`${s} fits: needs about ${T(k)}, ${T(g.availableMB)} is free now${g.fitsGPULimit===!1?` — but it is above the GPU wired limit (${T(g.gpuWiredLimitMB)}); raise iogpu.wired_limit_mb`:""}.`:`${s} needs about ${T(k)} and ${T(g.availableMB)} is free now — ${T(g.shortfallMB)} short.${g.close.length?` Close ${g.close.join(", ")} to make room, or pick a smaller model.`:" Pick a smaller model."}`:`${s} needs about ${T(k)} of the machine's ${T(O)} — ${M?"fits":"does not fit"} (total memory; install Heatwatch to check what is free now).`;return{ok:!0,service:o.id,model:s,needMB:k,weightsMB:c,kvMB:m,context:u||null,contextCounted:m!==null||!u,source:g?"heatwatch":"total-memory",fits:M,live:g,advice:_t}}const D=(n,e,t,i={})=>({task:n.id==="vllm"?he(e):"chat",model:e,backend:t?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0,...n.id==="llama"?{recipe:Ye(X(),e),flags:zt(Te())}:{}}),X=()=>$.join(N,ae),J=(n,e)=>/\.gguf$/i.test(e)?Qe(e):n.id==="llama"?!!Fn(X(),e):Dt(X(),e),ut=n=>/\.gguf$/i.test(n)?n:Fn(X(),n),b={},fr=n=>b[n.id]||null;function gn(n){const e=tr();return t=>{if(n.cancelled)throw new Error("cancelled");t.retry&&P(n,`retrying ${String(t.file||"").split("/").pop()} in ${Math.round(t.retry.inMs/1e3)} s (try ${t.retry.attempt} of ${t.retry.of}) — ${t.retry.error}`),n.progress={bytes:t.bytes,total:t.total,file:t.file,...t.retry?{retrying:t.retry}:{},...e(t.bytes,{skipped:!!t.skipped,total:t.total})}}}function me(n,e,t={}){return b[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...t},b[n.id]}function P(n,e){const t=String(e||"").trim();if(!t)return;n.lines.push(t.slice(0,200)),n.lines.length>8&&n.lines.shift();const i=/^STEP (\d+)\/(\d+)/.exec(t);i&&(n.step={n:Number(i[1]),of:Number(i[2])})}const ye=(n,e,t,{timeout:i=36e5*4}={})=>new Promise(o=>{if(n.cancelled)return o({ok:!1,code:-1,error:"cancelled"});let s;try{s=Ee(e,t,{stdio:["ignore","pipe","pipe"],env:G()})}catch(d){return o({ok:!1,code:-1,error:d.message})}n.child=s;let a="";const c=d=>{a+=String(d);const m=a.split(/\r?\n|\r/);a=m.pop();for(const k of m)P(n,k)};s.stdout?.on("data",c),s.stderr?.on("data",c);const u=setTimeout(()=>{try{s.kill("SIGTERM")}catch{}},i);u.unref?.(),s.on("error",d=>{clearTimeout(u),n.child=null,o({ok:!1,code:-1,error:d.message})}),s.on("exit",d=>{clearTimeout(u),n.child=null,a&&P(n,a),o({ok:d===0&&!n.cancelled,code:d,...n.cancelled?{error:"cancelled"}:{}})})}),kn={install:Promise.resolve(),build:Promise.resolve()},Fe={install:0,build:0},wn=(n,e,t)=>{Fe[n]>0&&(e.waiting=!0,P(e,`waiting for the other ${n} to finish first — one at a time`)),Fe[n]++;const i=kn[n];let o;const s=new Promise(a=>{o=a});return kn[n]=i.then(()=>s),i.then(async()=>{e.waiting&&(P(e,"the other one finished — going"),e.waiting=!1);try{return await t()}finally{Fe[n]--,o()}})},yn=async(n,e)=>(await y(n,["image","exists",e],{timeout:2e4})).ok;async function ct(n,e,t,i){const o=e?.image||t.image;if(await yn(n,o))return{ok:!0};const s=e?.sources?.length?e.sources:[o],a=[];for(const m of s){if(i.kind="pull-image",i.detail=m,P(i,`pulling ${m}`),(await ye(i,n,["pull",m])).ok)return m!==o&&await y(n,["tag",m,o],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const c=e?.recipe?It[e.recipe]:null;if(!c)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const u=$.join(N,"images",e.recipe);return pe(u,{recursive:!0,mode:448}),be($.join(u,"Dockerfile"),c.dockerfile,{mode:384}),i.kind="build-image",i.detail=o,i.minutes=c.minutes,P(i,`no registry has ${o} for this machine — building it here (about ${c.minutes} minutes)`),S(`[runtime] building ${o} from the ${e.recipe} recipe in ${u}`),(await wn("build",i,()=>ye(i,n,["build","-t",o,"-f",$.join(u,"Dockerfile"),u]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function bn(n,e){const t=w(n);if(!t||J(n,t))return{ok:!0};if(/\.gguf$/i.test(t))return{ok:!1,error:`no such file: ${t}`};e.kind="pull-model",e.detail=t;const i=gn(e);try{if(n.id==="llama"){const o=j(n,t);await jt(t,{root:X(),fetchImpl:B,onProgress:i,knows:(Oe||jn)(Te()),engineVersion:sn(),vision:o.vision!=="off",draft:o.draftModel!=="off"})}else await Ft(t,{root:X(),fetchImpl:B,onProgress:i});return{ok:!0}}catch(o){return{ok:!1,error:`pull ${t}: ${o.message}`}}}async function dt(n,e,t){const i=[];return Y(n)&&!le()&&i.push("runner"),n.kind!=="native"&&e&&!await yn(e,t?.image||n.image)&&i.push("image"),n.pull&&n.model&&!J(n,w(n))&&i.push("model"),i}async function $n(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&h!=="linux"){const t=await y("podman",["machine","inspect","--format","{{.Resources.Memory}}"],{timeout:8e3}),i=parseInt(t.out,10);return t.ok&&i>0?i:0}if(n==="docker"&&h!=="linux"){const t=await y("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(t.out,10);return t.ok&&i>0?Math.round(i/1048576):0}return Math.round(rn()/1048576)}async function E(){const n={};for(const t of Me){const i=await y(t,["--version"],{timeout:5e3});if(!i.ok){n[t]={installed:!1};continue}const o=(i.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||i.out;let s=!1,a=null;if(t==="podman")if(h==="linux")s=(await y("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const c=await y("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,s=!!d?.Running}catch{a=null}}else s=(await y("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[t]={installed:!0,version:o,running:s,...t==="podman"&&h!=="linux"?{machine:a}:{}}}const e=Me.find(t=>n[t]?.installed&&n[t].running)||Me.find(t=>n[t]?.installed)||null;return{...n,preferred:e,...e?{}:{install:nn(h)}}}async function je(n="podman"){if(!Me.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await E())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:nn(h)};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(h!=="linux"){if(!e.machine){const i=await y("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const t=await y("podman",["machine","start"],{timeout:3e5});if(!t.ok&&!/already running/i.test(t.err))return{ok:!1,error:`podman machine start: ${t.err||t.out}`}}return{ok:!0}}async function vn(){const n=await E(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await y("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(o=>Yn(o,"podman"))}catch{return[]}}const t=await y("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return t.ok?t.out.split(`
|
|
5
|
+
`).filter(Boolean).map(i=>{try{return Yn(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Sn(n,e){const t=await y(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return t.ok?/running/i.test(t.out)?"running":"stopped":"absent"}async function De(n,e){const t=await y(n,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!t.ok){for(const s of e)i[s]="absent";return i}const o=new Map(t.out.split(`
|
|
6
|
+
`).map(s=>s.split(" ")).filter(s=>s[0]).map(([s,a])=>[s,/running/i.test(a||"")?"running":"stopped"]));for(const s of e)i[s]=o.get(s)||"absent";return i}const _=n=>`http://127.0.0.1:${n.port}`;async function Mn(){const n=await E(),e=n.preferred,t=await $n(e,n),i={},o=await H(e),s=e&&n[e].running?await De(e,F.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of F){const c=_(a);let u="no-engine";if(a.kind==="native"?u=ce(a):e&&n[e].running?u=s[a.container]||"absent":e&&(u="engine-stopped"),a.retired&&!["running","stopped","exited","created","paused"].includes(u))continue;const d=a.model?w(a):null,m=a.engineOf?Y(a)?{...a.engineOf({...o,llamaOnPath:!0}),install:tt}:a.engineOf(o):null,k=a.kind==="native"?(o.ramGB||0)*1024:t;i[a.id]={...lr(a),engine:a.kind==="native"?"host":e,state:u,url:c,configured:a.configured(r),answering:u==="running"?await a.answers(c,B):!1,...a.helper?{asleep:I.has(a.id),idleMinutes:On()/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"&&!C(a)?{why:`${a.label} runs on ${oe(a)} only`}:{},...a.id==="llama"&&C(a)?{...d&&Ye(X(),d).recommended?{recommended:Ye(X(),d).recommended}:{},build:te(),builds:[{id:"unsloth",label:v.label,why:v.why,installed:!!V(),version:V()?.tag||null,default:!0},{id:"system",label:"The system’s llama.cpp",why:"Homebrew’s, or one you built — `llama-server` on PATH",installed:!!Le("llama-server"),version:ne("llama-server")}],...te()==="unsloth"?V()?{runnerVersion:V().tag,updatable:!0}:{}:K[a.runner]?{runnerVersion:ne(a.runner),updatable:!!m?.install?.update?.steps?.length}:{}}:a.kind==="native"&&a.runner&&C(a)&&K[a.runner]?{runnerVersion:ne(a.runner),updatable:!!m?.install?.update?.steps?.length}:{},...a.auto&&u!=="running"&&C(a)?{auto:!0,...Ue(a)?{why:"Stopped here — Start turns it back on"}:L[a.id]?{why:L[a.id]}:{}}:a.auto?{auto:!0}:{},...!a.auto&&a.kind==="native"&&u!=="running"&&C(a)&&L[a.id]?{why:L[a.id]}:{},...a.kind==="native"&&Z[a.id]?{sandbox:Z[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}}:{},...W(a)?{profiles:Hn(a.id,j(a,d),D(a,d,m,o)),docs:Ht[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:lt(a,o)}:{},...a.model?{model:d,default:a.model,models:Tn(a.id,{active:d,engineRamMB:k,engine:a.kind==="native"?"host":e,platform:h,installed:g=>J(a,g)}),machine:{engineRamMB:k}}:{},...W(a)?{tunings:Gn(a.id,j(a,d),D(a,d,m,o))}:{}}}return i}async function mt(){const n=await E(),e=await H(n.preferred);return{platform:h,arch:z,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:Rt(e)}}function An(n,{settingsFile:e=null,secret:t=null,pick:i=null,cpus:o=null}={}){const s=de(n),a=["run","-d","--name",s.container,"--restart","no","-p",`127.0.0.1:${s.port}:${s.containerPort}`];s.helper&&o&&a.push("--cpus",String(o));for(const u of s.volumes?s.volumes(N):[])a.push("-v",u);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const u of s.env?s.env(s):[])a.push("-e",u);s.helper&&o&&a.push("-e",`THREADS=${o}`),t&&a.push("-e",`SEARXNG_SECRET=${t}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${s.port}/`),a.push("--cap-drop","ALL");for(const u of s.caps||[])a.push("--cap-add",u);i?.devices?.length&&a.push(...i.devices),a.push(i?.image||s.image,...s.args?s.args(s,i):[]);const c=Nt("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 Xe={};async function ft(n){if(Xe[n]==null){const e=await y(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),t=Number.parseInt(e.out,10);Xe[n]=Number.isFinite(t)&&t>0?t:ie.cpus()?.length||2}return Math.max(1,Math.floor(Xe[n]/2))}async function ee(n,{force:e=!1}={}){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(t.retired)return{ok:!1,error:t.retired.why,retired:!0};I.delete(t.id),qe(t.id),t.auto&&Ue(t)&&un(t,!1);const i=b[t.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let o=null;if(t.kind!=="native"){const d=await E();if(o=d.preferred,!o)return{ok:!1,error:"no container engine — install Podman first",install:nn(h)};if(!d[o].running){const m=await je(o);if(!m.ok)return m}}else if(!C(t))return{ok:!1,error:`${t.label} runs on ${oe(t)} only`};const s=await H(o),a=t.engineOf?t.engineOf(s):null;if(t.kind==="native"&&!Y(t)&&!await U(t.runner,t.runnerCheck))return{ok:!1,error:ln(t,a?.install),install:a?.install};if(t.model&&/\.gguf$/i.test(w(t))&&!Qe(w(t)))return{ok:!1,error:`no such file: ${w(t)}`};if(t.kind==="native"&&t.model&&!e){const d=await hn(t.id);if(d.live&&!d.fits)return{ok:!1,error:d.advice,plan:d}}const c=await dt(t,o,a);if(!c.length){if(delete b[t.id],t.kind!=="native")return ze(t,o);const d=await Ge(t);return d.ok?delete L[t.id]:L[t.id]=d.error,d}const u=me(t,c[0]==="runner"?"install":c[0]==="image"?"pull-image":"pull-model",{detail:c[0]==="runner"?v.label:c[0]==="image"?a?.image||t.image:w(t)});return c.includes("model")&&mn(t,w(t),!0),u.then=(async()=>{try{if(c.includes("runner")){const m=await Ce(u);if(!m.ok)throw new Error(m.error)}if(c.includes("image")){const m=await ct(o,a,t,u);if(!m.ok)throw new Error(m.error)}if(c.includes("model")){const m=await bn(t,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=t.label;const d=t.kind==="native"?await Ge(t):await ze(t,o);if(!d.ok)throw new Error(d.error);u.done=!0,u.result=d,S(`[runtime] ${t.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(d){u.done=!0,u.error=u.cancelled?"cancelled":d.message,S(`[runtime] ${t.label}: ${u.error}`)}finally{c.includes("model")&&He(t)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function pt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const t=b[e.id];if(!t||t.done)return{ok:!0,nothing:!0};if(t.cancelled=!0,t.child){try{t.child.kill("SIGTERM")}catch{}const i=t.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return P(t,"cancelled"),S(`[runtime] ${e.label}: job cancelled (${t.kind})`),{ok:!0,cancelled:t.kind}}async function ze(n,e){let t=await Sn(e,n.container);const i=n.helper?await ft(e):null,o=n.engineOf?n.engineOf(await H(e)):null,s=n.id==="searxng"?$.join(N,"searxng-settings.yml"):null,a=An(n,{settingsFile:s,secret:n.id==="searxng"?"x":null,pick:o,cpus:i});if(t!=="absent"){const d=await y(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!d.ok||d.out!==a.hash)&&(S(`[runtime] ${n.label}: made with older settings — re-creating it`),await y(e,["rm","-f",n.container],{timeout:6e4}),t="absent")}if(t!=="running")if(t==="stopped"){const d=await y(e,["start",n.container],{timeout:6e4});if(!d.ok)return{ok:!1,error:`${e} start: ${d.err||d.out}`}}else{pe(N,{recursive:!0,mode:448});let d=null;n.id==="searxng"&&(be(s,dr(String(r.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),d=Bt(32).toString("hex")),n.volumes&&pe($.join(N,ae),{recursive:!0,mode:448});const{args:m}=An(n,{settingsFile:s,secret:d,pick:o,cpus:i});S(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const k=await y(e,m,{timeout:6e5});if(!k.ok)return{ok:!1,error:`${e} run: ${k.err||k.out}`}}const c=_(n);let u=!1;for(let d=0;d<30&&!u;d++)u=await n.answers(c,B),u||await Be(1e3);return n.configure(r,c,de(n)),p(),{ok:!0,url:c,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:w(n)}:{}}}async function ht(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(I.delete(e.id),delete Je[e.id],e.auto&&un(e,!0),e.kind==="native")return we(e);const t=await E(),i=t.preferred;if(i&&t[i].running){const o=await y(i,["stop",e.container],{timeout:6e4});if(!o.ok&&!/no such container/i.test(o.err))return{ok:!1,error:`${i} stop: ${o.err||o.out}`}}return e.unconfigure(r,_(e)),p(),{ok:!0}}async function gt(n,e){const t=A(n);if(!t||t.id!=="llama")return{ok:!1,error:"a build is chosen for llama.cpp"};if(!Dn.includes(e))return{ok:!1,error:`one of ${Dn.join(", ")}`};r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{};const i={...r.runtime.services.llama||{}};e==="system"?i.build="system":delete i.build,r.runtime.services.llama=i,p();const o=await Ve(t,null,await E());return o.ok?{ok:!0,build:e,restarted:o.restarted,...o.pending?{pending:o.pending}:{}}:o}async function kt(n,e){const t=A(n);if(!t||t.id!=="llama")return{ok:!1,error:"a recipe is for llama.cpp (a GGUF repo)"};const i=String(e||"").trim();if(!Cn(n,i)||/\.gguf$/i.test(i))return{ok:!1,error:`not a Hugging Face id: ${JSON.stringify(e)} — owner/name, or owner/name:QUANT`};const o=((await ke()).ramGB||0)*1024,s=a=>o?Xn({ramMB:a/2**20})<=o*.75:null;try{const a=await Xt(i,{fetchImpl:B,knows:(Oe||jn)(Te()),engineVersion:sn()}),c=(a.projector?.size||0)+(a.draft?.size||0);return{ok:!0,model:`${a.repo}:${a.quant}`,quant:a.quant,arch:a.arch,layout:a.layout,main:a.main,size:a.total,projector:a.projector,draft:a.draft,quants:a.quants.map(u=>({...u,fits:s(u.size+c)})),ramGB:o/1024,fits:s(a.total+c)}}catch(a){return{ok:!1,error:a.message,...a.code?{code:a.code,arch:a.arch}:{}}}}async function wt(n,e,{tunings:t=null}={}){const i=A(n);if(!i)return{ok:!1,error:`unknown service ${n}`};if(!i.model)return{ok:!1,error:`${i.label} takes no model`};const o=String(e||"").trim();if(!Cn(n,o))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 E(),a=s.preferred,c=i.kind==="native"?((await ke()).ramGB||0)*1024:await $n(a,s),u=Tn(n,{active:o,engineRamMB:c,engine:i.kind==="native"?"host":a,platform:h,installed:g=>J(i,g)}).find(g=>g.id===o);if(u?.unavailable)return{ok:!1,error:`${o} ${u.unavailable}`};let d=null;if(t&&W(i)){const g=await H(a);if(d=Un(i.id,j(i,o),t,D(i,o,i.engineOf?i.engineOf(g):null,g)),d.error)return{ok:!1,error:d.error}}r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{},r.runtime.services[n]={...r.runtime.services[n]||{},model:o},d&&Ie(i,o,d);const m=_(i);i.configured(r)===m&&i.configure(r,m,de(i)),p();const k=await Ve(i,a,s);return k.ok?{ok:!0,model:o,restarted:k.restarted,...k.pending?{pending:k.pending}:{},...u?.ramNote?{note:u.ramNote}:{}}:k}async function Ve(n,e,t){if(n.kind==="native"){if(ce(n)!=="running")return{ok:!0,restarted:!1};we(n);const s=await ee(n.id,{force:!0});return s.ok?{ok:!0,restarted:!0,...s.pending?{pending:s.pending}:{}}:s}if(!e||!t[e].running)return{ok:!0,restarted:!1};const i=await Sn(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const o=await y(e,["rm","-f",n.container],{timeout:6e4});if(!o.ok&&!/no such container/i.test(o.err))return{ok:!1,error:`${e} rm: ${o.err||o.out}`};if(i==="running"){const s=await ee(n.id);return s.ok?{ok:!0,restarted:!0}:s}return{ok:!0,restarted:!1}}async function yt(n,e){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!W(t))return{ok:!1,error:`${t.label} takes no profile`};const i=await E(),o=await H(i.preferred),s=t.engineOf?t.engineOf(o):null,a=Hn(t.id,j(t,w(t)),D(t,w(t),s,o)).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 Pn(n,a.patch);return c.ok?{...c,profile:a.id}:c}async function We(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Y(e)){if(le())return{ok:!0,installed:!0};const s=me(e,"install",{detail:v.label});return s.then=(async()=>{const a=await Ce(s);s.done=!0,a.ok||(s.error=a.error),S(`[runtime] install ${v.label}: ${s.error||"ok"}`)})(),{ok:!0,pending:{kind:s.kind,since:s.since,detail:s.detail}}}if(delete K[e.runner],delete Q[e.runner],await U(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const o=e.engineOf(await H(null))?.install;return o?.steps?.length?_n(e,o,"install"):{ok:!1,error:`no installer for ${e.label} on this platform${o?.url?` — see ${o.url}`:""}`,install:o||null}}function _n(n,e,t){const i=me(n,t,{detail:n.runner}),o=t==="update"&&ce(n)==="running",s=ne(n.runner);return i.then=wn("install",i,async()=>{const a=async d=>{for(const[m,...k]of d){P(i,`$ ${m} ${k.join(" ")}`);let g=await ye(i,m,k,{timeout:36e5});for(let O=0;!g.ok&&!i.cancelled&&O<6&&i.lines.some(M=>/already locked|Please wait for it to finish/i.test(M));O++)P(i,`another ${m} holds the lock — waiting 20 s (${O+1}/6)`),await Be(2e4),g=await ye(i,m,k,{timeout:36e5});if(!g.ok&&e.upToDate&&i.lines.some(O=>new RegExp(e.upToDate,"i").test(O))&&(g={ok:!0}),!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let c=await a(e.steps);!c.ok&&!i.cancelled&&e.fallback?.length&&(P(i,`${c.error} — trying the other way`),c=await a(e.fallback)),delete K[n.runner],delete Q[n.runner];const u=c.ok&&await U(n.runner,n.runnerCheck);if(u&&t==="update"){const d=ne(n.runner);if(P(i,d&&s&&d!==s?`${n.label} ${s} → ${d}`:`${n.label}${d?` ${d}`:""} — up to date`),o&&!i.cancelled){we(n),i.done=!0;const m=await ee(n.id,{force:!0});if(m.ok||(L[n.id]=m.error,S(`[runtime] ${n.label} after the update: ${m.error}`)),m.pending)return;b[n.id]||(b[n.id]=i)}}i.done=!0,i.cancelled?i.error="cancelled":c.ok?u||(i.error=`${n.runner} still not found after the ${t} — open a new terminal and run \`${e.command}\` by hand`):i.error=`${t} failed: ${c.error}${i.lines.length?` (${i.lines.slice(-2).join(" | ")})`:""}`,S(`[runtime] ${t} ${n.runner}: ${i.error||"ok"}`)}),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function bt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Y(e)){if(!le())return We(n);const o=V()?.tag,s=ce(e)==="running",a=me(e,"update",{detail:v.label});return a.then=(async()=>{const c=await Ce(a,{tag:"latest"});if(!c.ok){a.done=!0,a.error=`update failed: ${c.error}`;return}if(P(a,c.tag!==o?`${v.label} ${o} → ${c.tag}`:`${v.label} ${c.tag} — up to date`),a.done=!0,s&&c.tag!==o&&!a.cancelled){we(e);const u=await ee(e.id,{force:!0});u.ok||(L[e.id]=u.error),b[e.id]||(b[e.id]=a)}})(),{ok:!0,pending:{kind:a.kind,since:a.since,detail:a.detail}}}if(delete K[e.runner],delete Q[e.runner],!await U(e.runner,e.runnerCheck))return We(n);const i=e.engineOf(await H(null))?.install;return i?.update?.steps?.length?_n(e,i.update,"update"):{ok:!1,error:`no updater for ${e.label} on this platform${i?.url?` — newer builds are at ${i.url}`:""}`,install:i||null}}async function xn(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(J(e,w(e)))return{ok:!0,installed:!0,model:w(e)};const i=me(e,"pull-model",{detail:w(e)});return mn(e,w(e),!1),i.then=(async()=>{const o=await bn(e,i);i.done=!0,o.ok||(i.error=o.error),He(e)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Pn(n,e){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!W(t))return{ok:!1,error:`${t.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await E(),o=i.preferred,s=w(t),a=await H(o),c=t.engineOf?t.engineOf(a):null,u=Un(t.id,j(t,s),e,D(t,s,c,a));if(u.error)return{ok:!1,error:u.error};Ie(t,s,u),p();const d=await Ve(t,o,i);return d.ok?{ok:!0,tunings:Gn(t.id,u,D(t,s,c,a)),restarted:d.restarted}:d}async function $t(){const n=await E(),e=n.preferred,t=e&&n[e].running?await De(e,F.filter(s=>s.kind!=="native").map(s=>s.container)):{},i={};let o=!1;return await Promise.all(F.map(async s=>{const a=s.kind==="native"?ce(s):e&&n[e].running?t[s.container]||"absent":"no-engine";i[s.id]=a==="running"&&await s.answers(_(s),B)?"up":"down";const c=(s.provides||[]).some(u=>["embedded","none"].includes(rr(r.capabilities?.[u],u)?.provider));i[s.id]==="up"&&s.configure&&!s.retired&&!c&&s.configured(r)!==_(s)&&(s.configure(r,_(s),de(s)),o=!0)})),o&&p(),i}function En(n){const e=A(n);if(e?.window)return e.window;if(!e||!W(e))return null;const t=Number(In(e.id,j(e,w(e)),D(e,w(e),null,{})).maxModelLen);return Number.isFinite(t)&&t>0?t:null}function vt(n){const e=A(n);if(e?.card)return e.card;if(!e||!W(e))return null;const t=w(e),i=In(e.id,j(e,t),D(e,t,null,{})),o=$e(e.id).find(a=>a.id===t)||null,s=e.id==="vllm"?he(t):"chat";return{engine:e.id,backend:Z[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:s,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:s==="chat"&&!!i.vision,tools:!!(s==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:s==="chat"&&!!i.reasoning&&i.reasoning!=="off",...o?{tier:o.tier||null,licence:o.licence||null,languages:o.lang||null,label:o.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}const St=10,On=()=>{const n=Number(r.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:St)*6e4},Mt=se(),Je={},I=new Set,fe={};function qe(n){Je[n]=se()}async function At(n,{force:e=!1}={}){const t=A(n);if(!t||!t.helper)return{ok:!0};if(qe(t.id),!I.has(t.id)&&!e){const i=t.container&&t.configured?.(r)?(await vn()).find(o=>o.name===t.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};I.add(t.id)}return fe[t.id]||(fe[t.id]=(async()=>{const i=await E(),o=i.preferred;if(!o)return{ok:!1,error:"no container engine"};if(!i[o].running){const a=await je(o);if(!a.ok)return a}const s=await ze(t,o);return s.ok&&(I.delete(t.id),S(`[runtime] ${t.label}: woken for a request`)),s})().finally(()=>{delete fe[t.id]})),fe[t.id]}async function Bn(){const n=On();if(!n)return[];const e=F.filter(a=>a.helper&&a.configured(r)&&!I.has(a.id)&&!fe[a.id]&&!(b[a.id]&&!b[a.id].done)&&se()-(Je[a.id]??Mt)>=n);if(!e.length)return[];const t=await E(),i=t.preferred;if(!i||!t[i].running){for(const a of e)I.add(a.id);return e.map(a=>a.id)}const o=await De(i,e.map(a=>a.container)),s=[];for(const a of e){if(o[a.container]==="running"){if(!(await y(i,["stop",a.container],{timeout:6e4})).ok)continue;S(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}I.add(a.id),s.push(a.id)}return s}return an&&an(()=>{Bn().catch(n=>S(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:qe,wake:At,sweepIdle:Bn,health:$t,contextWindow:En,modelCard:vt,async status(){const[n,e,t,i,o]=await Promise.all([l().catch(()=>null),E(),Mn(),vn(),mt()]);return{machine:o,sandbox:n?.sandbox||null,processes:{all:[...Array.isArray(n?.processes)?n.processes:[],...f()],localMcp:Array.isArray(n?.localMcp)?n.localMcp:[],warm:n?.warm||null},containers:i,refused:Array.isArray(n?.sandbox?.refused)?n.sandbox.refused:[],bridge:n?{ok:!0,version:n.version||""}:{ok:!1},engines:e,services:t}},startEngine:je,startService:ee,stopService:ht,ensureDefaults:at,retireServices:fn,removeService:rt,upcastTunings:pn,revive:ot,plan:hn,recipe:kt,setBuild:gt,isAsleep:n=>I.has(n),setModel:wt,setTunings:Pn,setProfile:yt,pullModel:xn,installRunner:We,updateRunner:bt,cancelJob:pt,services:Mn,catalogFor:$e}}export{ur as SEARXNG_DEFAULT_ENGINES,F as SERVICES,Yn as containerRow,Tr as createRuntime,nn as installDoor,dr as searxngSettings};
|
package/src/segment-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{verifyFresh as $}from"./model-integrity.js";import{existsSync as S,readdirSync as T}from"node:fs";import{join as
|
|
1
|
+
import{verifyFresh as $}from"./model-integrity.js";import{existsSync as S,readdirSync as T}from"node:fs";import{join as O}from"node:path";import{ensureLib as P,modelRoot as A,withModelSource as R}from"./ner-engine.js";import{runtimeDtype as w}from"./model-runtime.js";import{makeWarmTimer as b}from"./warm-timer.js";import{engineLoadOptions as v}from"./ort.js";const k="onnx-community/pyannote-segmentation-3.0",X=6,F=16e3;let n="off",g=k,f=null,c=null,s=null,m=null,a=null,o=null,_=0,p=0,h=null;function H(){return g}function J(){return n}function x(){return n==="ready"&&!!f&&!!c}function K(){return a}function Q(){return{configured:n!=="off",ok:x(),state:n,model:g,loaded:!!f,error:s,warmMs:o?.warmMs??null}}function y(){return _>0||p>0||n==="loading"||n==="downloading"}function V(){p++,o?.disarm()}function Y(){p=Math.max(0,p-1),p===0&&_===0&&x()&&o?.arm()}async function E({log:e=()=>{}}={}){if(y())return!1;o?.disarm();const r=f;if(f=null,c=null,h=null,m=null,a=null,s=null,n="off",r){try{await r.dispose?.()}catch{}e("[segment] idle — model unloaded (reloads on the next diarizing session)")}return!0}function z(e=g,r=w()){const l=O(A(),...e.split("/"),"onnx");if(!S(l))return!1;const t=r==="fp32"?"":r==="q8"?"_quantized":`_${r}`;try{return T(l).some(i=>i===`model${t}.onnx`)}catch{return!1}}async function j({log:e=()=>{},allowDownload:r=!0}={}){let l;try{l=await P()}catch(u){return n="error",s=u.message,e(`[segment] engine unavailable (${u.message})`),!1}if(!l.AutoModelForAudioFrameClassification)return n="error",s="this transformers.js has no audio frame classification",e(`[segment] ${s}`),!1;const t=g,i=z(t);if(!i&&!r)return n="error",s="model not on disk and downloads disabled",!1;n=i?"loading":"downloading",i||(a={model:t,file:null,pct:0},e(`[segment] downloading ${t} (one-time)…`));try{const u=d=>{if(!d)return;const D=typeof d.progress=="number"?Math.round(d.progress):a?.pct??0;(d.status==="progress"||d.status==="download"||d.status==="initiate")&&(a={model:t,file:d.file||a?.file||null,pct:D})},{processor:L,model:M}=await R({host:i?null:"https://huggingface.co/",allowRemote:!i},async()=>({processor:await l.AutoProcessor.from_pretrained(t,{progress_callback:u}),model:await l.AutoModelForAudioFrameClassification.from_pretrained(t,{dtype:w(),progress_callback:u,...v({threads:1})})}));return await $(!i,t,{modelsDir:A(),log:e,dispose:()=>M.dispose?.()}),c=L,f=M,n="ready",s=null,a=null,e(`[segment] ready — ${t} @ ${w()} (speaker turns inside a segment)`),!0}catch(u){return s=u.message,a=null,n="error",e(`[segment] load failed (${u.message}) — one speaker per segment, as before`),!1}}function q(e){return e.then(r=>(r&&!y()&&o?.arm(),r))}function Z(e={}){if(m&&n!=="error")return m;n="loading";const r=typeof e.onLog=="function"?e.onLog:()=>{};return o=b({warmMs:e.warmMs,busy:y,log:r,unload:()=>E({log:r})}),m=q(j({log:r,allowDownload:e.allowDownload!==!1})),m}async function ee(e){if(!x()||!(e instanceof Float32Array)||e.length<F/2)return null;_++;try{if(h)return await h(e);const r=await c(e),{logits:l}=await f(r),t=c.post_process_speaker_diarization(l,e.length);return Array.isArray(t?.[0])?t[0]:null}catch{return null}finally{_--,y()||o?.arm()}}function re(){o?.disarm(),o=null,p=0,_=0,n="off",g=k,f=null,c=null,s=null,m=null,a=null}function ne(e,{warmMs:r=null}={}){h=e||null,f=e?{dispose:async()=>{}}:null,c=e?{}:null,n=e?"ready":"off",r!==null&&(o=b({warmMs:r,busy:y,unload:()=>E()}),e&&o.arm())}export{k as DEFAULT_SEGMENT_MODEL,F as SAMPLE_RATE,X as SEGMENT_MODEL_APPROX_MB,re as _reset,ne as _setForTest,H as activeModel,Q as health,Z as init,x as isReady,z as modelOnDisk,K as progress,Y as release,V as retain,ee as spans,J as state,E as unload};
|