@chatpanel/gateway 0.164.0 → 0.166.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 +2 -2
- package/src/engine-plugins.js +1 -0
- package/src/engines/sglang.js +1 -0
- package/src/model-pull.js +1 -1
- package/src/runtime-models.js +1 -1
- package/src/runtime.js +6 -6
- package/src/server.js +22 -22
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.166.1",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
26
|
"@chatpanel/bridge": "^0.53.0",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.517.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readdirSync as g,readFileSync as $,writeFileSync as k,mkdirSync as b,rmSync as y,existsSync as S,chmodSync as v}from"node:fs";import c from"node:path";import m from"node:os";import{validateEngineManifest as p,manifestCommand as x,manifestRows as w,manifestProfiles as j,LOOPBACK as N}from"@chatpanel/events/engine-manifest.js";import O from"./engines/sglang.js";const A=Object.freeze([O]),h=(s=m.homedir())=>process.env.CHATPANEL_ENGINES_DIR||c.join(s,".chatpanel","engines");function C(s,{source:e="own",builtins:f}={}){const i=[],t=[];let n=[];try{n=g(s).filter(o=>o.endsWith(".json")).sort()}catch{return{manifests:i,refused:t}}for(const o of n){const r=c.join(s,o);let u;try{u=JSON.parse($(r,"utf8"))}catch(l){t.push({file:r,error:`not JSON: ${l.message}`});continue}const a=p(u,f?{builtins:f}:{});if(!a.ok){t.push({file:r,error:a.error});continue}i.push({manifest:a.manifest,source:e,file:r})}return{manifests:i,refused:t}}function D({home:s=m.homedir(),shipped:e=A,takenPorts:f=[],builtins:i}={}){const t={manifests:[],refused:[]};for(const l of e){const d=p(l,i?{builtins:i}:{});d.ok?t.manifests.push({manifest:d.manifest,source:"shipped",file:`${l.id}.json`}):t.refused.push({file:`${l?.id||"shipped"}.json`,error:d.error})}const n=C(h(s),{source:"own",builtins:i}),o=new Map;for(const l of[...t.manifests,...n.manifests])o.set(l.manifest.id,l);const r=new Set(f.map(Number)),u=[],a=[...t.refused,...n.refused];for(const l of o.values()){if(l.manifest.kind==="local"){if(r.has(l.manifest.port)){a.push({file:l.file,error:`port ${l.manifest.port} is another engine's — choose another`});continue}r.add(l.manifest.port)}u.push(l)}return{manifests:u,refused:a}}const E=s=>String(s||"").replace(/\/v1$/,"");function G(s){const e=s.manifest;if(e.kind!=="local")return null;const f=process.platform,t={command:e.install?.[f]||e.install?.command||""||`install ${e.runner}`,url:e.install?.url||"",note:`From the ${e.label} manifest — run it yourself; ChatPanel never runs a manifest's install.`};return{id:e.id,label:e.label,kind:"native",plugin:{source:s.source,formats:e.formats,profiles:e.profiles.length>0},manifest:e,runner:e.runner,...e.runnerCheck?{runnerCheck:e.runnerCheck}:{},pull:e.pull!==!1,...e.only&&(e.only.platform||e.only.arch)?{only:e.only}:{},port:e.port,provides:e.provides,adapter:"openai",model:e.model||"",blurb:e.blurb||`${e.label}, brought as a manifest: a process on this machine behind the gateway, loopback only.`,engineOf:()=>({backend:"host",kind:"native",runner:e.runner,install:t,why:`${e.label} — an engine brought as a manifest (${s.source}).`}),command:n=>x(e,{model:n.model,port:n.port,values:n.tunings||{},profile:n.tunings?.profile||""}),answers:async(n,o)=>{try{return(await o(`${n}${e.health||"/health"}`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:n=>E((n.destinations||[]).find(o=>o?.service===e.id)?.baseUrl),configure:(n,o,r)=>{n.destinations=(n.destinations||[]).filter(u=>u?.service!==e.id&&u?.id!==e.id),n.destinations.push({id:e.id,type:"api",protocol:"openai",baseUrl:`${o}${e.api||"/v1"}`,models:[r.model],service:e.id})},unconfigure:n=>{Array.isArray(n.destinations)&&(n.destinations=n.destinations.filter(o=>o?.service!==e.id&&o?.id!==e.id))}}}function J(s,e={},{ramGB:f=0}={}){const i=s.manifest;return{tunings:w(i,e,{profile:e.profile||""}),profiles:j(i,{ramGB:f,picked:e.profile||""})}}function L(s,e={},f={}){const i=s.manifest,t={...e};for(const[n,o]of Object.entries(f||{})){if(n==="profile"){if(o===null||o===""){delete t.profile;continue}if(!i.profiles.some(a=>a.id===o))return{ok:!1,error:`${i.label} has no profile "${o}" (${i.profiles.map(a=>a.id).join(", ")||"none"})`};t.profile=String(o);continue}const r=i.tunings.find(a=>a.id===n);if(!r)return{ok:!1,error:`${i.label} has no setting "${n}"`};if(o===null||o===""){delete t[n];continue}if(r.kind==="number"){const a=Number(o);if(!Number.isFinite(a)||r.min!==void 0&&a<r.min||r.max!==void 0&&a>r.max)return{ok:!1,error:`${r.label}: a number${r.min!==void 0?` from ${r.min}`:""}${r.max!==void 0?` to ${r.max}`:""}`};t[n]=a;continue}if(r.kind==="choice"){if(!r.options.includes(String(o)))return{ok:!1,error:`${r.label}: one of ${r.options.join(", ")}`};t[n]=String(o);continue}if(r.kind==="toggle"){t[n]=o===!0||o==="on";continue}const u=String(o).trim();if(/^-/.test(u)||u.length>500)return{ok:!1,error:`${r.label}: a value, not a flag`};t[n]=u}return{ok:!0,next:t}}function z(s,{home:e=m.homedir(),builtins:f}={}){const i=p(s,f?{builtins:f}:{});if(!i.ok)return i;const t=h(e);b(t,{recursive:!0,mode:448});const n=c.join(t,`${i.manifest.id}.json`);k(n,JSON.stringify(i.manifest,null,2),{mode:384});try{v(n,384)}catch{}return{ok:!0,manifest:i.manifest,file:n}}function H(s,{home:e=m.homedir()}={}){const f=c.join(h(e),`${String(s).replace(/[^a-z0-9-]/g,"")}.json`);return S(f)?(y(f),{ok:!0}):{ok:!1,error:`no engine "${s}" of yours`}}export{N as LOOPBACK,D as loadEngineManifests,h as ownEnginesDir,L as patchPluginTunings,J as pluginTunings,C as readManifests,H as removeOwnManifest,z as saveOwnManifest,G as serviceFromManifest};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e={schema:1,id:"sglang",label:"SGLang",kind:"local",provides:["chat"],formats:["safetensors"],blurb:"SGLang on this machine's NVIDIA or AMD GPU: fast serving with RadixAttention prefix caching, speculative decoding (EAGLE, or the model's own MTP heads) and LoRA adapters. A process behind the gateway, loopback only.",runner:"python3",runnerCheck:["-c","import sglang"],install:{linux:"pip install --upgrade 'sglang[all]' # or: uv pip install 'sglang[all]'",url:"https://docs.sglang.ai/get_started/install.html"},only:{platform:"linux"},port:3e4,model:"Qwen/Qwen3-4B",pull:!0,command:["python3","-m","sglang.launch_server","--model-path","{model}","--host","{host}","--port","{port}"],health:"/health",api:"/v1",tunings:[{id:"contextLength",label:"Context ceiling",kind:"number",flag:"--context-length",min:512,max:1048576,what:"The longest prompt and answer together. Larger needs more GPU memory for the cache."},{id:"memFraction",label:"GPU memory share",kind:"number",flag:"--mem-fraction-static",min:.1,max:.95,what:"How much of the GPU SGLang takes for weights and cache. Lower it when another engine shares the card."},{id:"tensorParallel",label:"GPUs (tensor parallel)",kind:"number",flag:"--tp-size",min:1,max:16,what:"Split the model across this many GPUs in this machine."},{id:"speculative",label:"Speculative decoding",kind:"choice",options:["off","EAGLE","EAGLE3","NEXTN"],flag:"--speculative-algorithm",off:"off",default:"off",what:"Draft tokens and verify them in one pass. NEXTN uses the model's own multi-token-prediction heads (MTP); EAGLE needs its draft model."},{id:"reasoningParser",label:"Reasoning parser",kind:"choice",options:["off","qwen3","deepseek-r1","gpt-oss","kimi"],flag:"--reasoning-parser",off:"off",default:"off",what:"Separate the model's thinking from its answer, for a model that thinks."},{id:"toolParser",label:"Tool calls",kind:"choice",options:["off","qwen25","llama3","mistral","deepseekv3","gpt-oss"],flag:"--tool-call-parser",off:"off",default:"off",what:"Read the model's tool calls into OpenAI tool_calls, so Chap's tools work through it."},{id:"chatTemplate",label:"Chat template",kind:"text",flag:"--chat-template",what:"A template name or a path, when the model's own is wrong."},{id:"trustRemoteCode",label:"Trust remote code",kind:"toggle",flag:"--trust-remote-code",what:"Run code a model repo ships. Only for a model you trust."}],profiles:[{id:"speed",label:"Fast chat",what:"Short questions, quick answers — the smallest cache.",set:{contextLength:8192}},{id:"coding",label:"Coding",what:"Room for a file and a conversation. The default.",set:{contextLength:32768},default:!0},{id:"long",label:"Long context",what:"Several files or a long document at once.",set:{contextLength:131072},needGB:24}],lora:{flag:"--lora-paths",form:"{name}={path}"}};export{e as default};
|
package/src/model-pull.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createWriteStream as Z,mkdirSync as O,renameSync as K,existsSync as b,writeFileSync as I,statSync as S,readFileSync as T,readdirSync as P}from"node:fs";import{ggufRecommended as J}from"./gguf-meta.js";import{Readable as Y}from"node:stream";import{pipeline as X}from"node:stream/promises";import g from"node:path";const R="https://huggingface.co",V=/\.(bin|pt|pth|ckpt|h5|msgpack|onnx|gguf|tflite)$/i,tt=/(^|\/)(\.gitattributes|README\.md|LICENSE.*|.*\.md|original\/.*|coreml\/.*|onnx\/.*|images?\/.*|assets\/.*)$/i;function k(e){const t=/^([A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95})(?::([A-Za-z0-9._-]{1,32}))?$/.exec(String(e||"").trim());return t?{repo:t[1],quant:t[2]||null}:null}const C=(e,t)=>g.join(e,"hub",`models--${t.replace("/","--")}`);async function L(e,{fetchImpl:t=globalThis.fetch,token:r=null}={}){const n=await t(`${R}/api/models/${e}?blobs=true`,{headers:r?{authorization:`Bearer ${r}`}:{},signal:AbortSignal.timeout(2e4)});if(n.status===401||n.status===403)throw new Error(`${e}: gated or private on Hugging Face — accept its licence there and add a token`);if(n.status===404)throw new Error(`${e}: no such model on Hugging Face`);if(!n.ok)throw new Error(`${e}: Hugging Face answered ${n.status}`);const o=await n.json(),c=(o.siblings||[]).map(s=>({path:s.rfilename,size:Number(s.lfs?.size??s.size??0)})).filter(s=>s.path);return{commit:String(o.sha||"main"),siblings:c}}function et(e){const t=e.some(n=>/\.safetensors$/i.test(n.path)),r=e.filter(n=>!(tt.test(n.path)||t&&V.test(n.path)||!t&&/\.(gguf|onnx|tflite|msgpack|h5|ckpt)$/i.test(n.path)));return{files:r,total:r.reduce((n,o)=>n+o.size,0)}}const U=/(^|\/)mmproj[^/]*\.gguf$/i,B=/(^|\/)(?:dspark|dflash|eagle3?)[-_][^/]*\.gguf$|[-_.]mtp(?:[-_.][^/]*)?\.gguf$|(^|\/)[^/]*draft[^/]*\.gguf$/i,rt=/(^|\/)imatrix[^/]*\.gguf$/i,M=(e,t)=>t.test(e)&&!U.test(e)&&!B.test(e)&&!rt.test(e);function G(e){const t=g.basename(String(e||"")).toLowerCase();return t.startsWith("dspark")?"draft-dspark":t.startsWith("dflash")?"draft-dflash":/^eagle3?[-_]/.test(t)?"draft-eagle3":/[-_.]mtp([-_.]|$)/.test(t.replace(/\.gguf$/,""))?"draft-mtp":"draft-simple"}function F(e){return{mains:e.filter(t=>M(t.path,/\.gguf$/i)),alts:e.filter(t=>/\.gguf_file$/i.test(t.path)&&M(t.path.replace(/_file$/i,""),/\.gguf$/i)),projectors:e.filter(t=>U.test(t.path)),drafts:e.filter(t=>B.test(t.path))}}const N=(e,t)=>(e.path.includes("/")?1:0)-(t.path.includes("/")?1:0);function nt(e){const t=r=>{const n=["f16","bf16","q8_0","f32"].findIndex(o=>new RegExp(`[-_.]${o}\\.gguf$`,"i").test(r));return n<0?9:n};return e.slice().sort((r,n)=>N(r,n)||t(r.path)-t(n.path))[0]||null}function ot(e){return e.slice().sort((t,r)=>N(t,r)||(t.size||0)-(r.size||0))[0]||null}const at=e=>g.basename(String(e)).replace(/\.gguf(_file)?$/i,"").replace(/-\d{5}-of-\d{5}$/,"").toLowerCase(),v=(e,t)=>{const r=e.toLowerCase().replace(/_file$/,"");return r.includes(`-${t}.`)||r.includes(`-${t}-0`)||r.includes(`.${t}.`)||r.includes(`/${t}/`)||r.includes(`_${t}.`)?!0:at(e)===t||j(e).toLowerCase()===j(`${t}.gguf`).toLowerCase()};function st(e,t=null,{layout:r="main"}={}){const n=F(e),o=r==="alt"?n.alts:n.mains;if(!o.length)throw new Error("no GGUF file in this repo");const c=(t||"Q4_K_M").toLowerCase();let s=o.filter(a=>v(a.path,c));if(!s.length&&!t){const a=D(o);s=o.filter(l=>j(l.path)===a)}if(!s.length)throw new Error(`no ${t||"Q4_K_M"} GGUF here — the repo has: ${[...new Set(o.map(a=>j(a.path)))].slice(0,12).join(", ")}`);return s=s.slice().sort((a,l)=>a.path.localeCompare(l.path)),{files:s,total:s.reduce((a,l)=>a+l.size,0),main:s[0].path}}function D(e){const t=n=>e.filter(o=>j(o.path)===n).reduce((o,c)=>o+(c.size||0),0),r=[...new Set(e.map(n=>j(n.path)))].sort((n,o)=>t(n)-t(o));return r.find(n=>/(^|-)I?Q4/i.test(n))||r[0]}function it(e){const t=new Map;for(const r of F(e).mains){const n=j(r.path);t.set(n,(t.get(n)||0)+(r.size||0))}return[...t].map(([r,n])=>({quant:r,size:n})).sort((r,n)=>r.size-n.size)}function j(e){const t=g.basename(e).replace(/\.gguf(_file)?$/i,"").replace(/-\d{5}-of-\d{5}$/,""),r=/[-._]((?:UD-)?(?:I?Q\d[A-Z0-9_]*|BF16|F16|F32|MTP))$/i.exec(t);return r?r[1]:t}const x=(e,t,r)=>g.join(e,"gguf",t.replace("/","--"),g.basename(r).replace(/\.gguf_file$/i,".gguf")),E={0:1,1:1,2:2,3:2,4:4,5:4,6:4,7:1,10:8,11:8,12:8};function ct(e){try{if(e.length<24||e.toString("latin1",0,4)!=="GGUF")return null;let t=16;const r=Number(e.readBigUInt64LE(t));t+=8;const n=()=>{const o=Number(e.readBigUInt64LE(t));t+=8;const c=e.toString("utf8",t,t+o);return t+=o,c};for(let o=0;o<r&&t<e.length;o++){const c=n(),s=e.readUInt32LE(t);if(t+=4,s===8){const a=n();if(c==="general.architecture")return a||null;continue}if(s===9){const a=e.readUInt32LE(t);t+=4;const l=Number(e.readBigUInt64LE(t));if(t+=8,a===8)for(let i=0;i<l;i++)n();else if(E[a])t+=E[a]*l;else return null;continue}if(!E[s])return null;t+=E[s]}}catch{}return null}async function lt(e,t,r,{fetchImpl:n=globalThis.fetch,token:o=null}={}){try{const c=await n(`${R}/${e}/resolve/${encodeURIComponent(t)}/${r.split("/").map(encodeURIComponent).join("/")}`,{headers:{range:"bytes=0-65535",...o?{authorization:`Bearer ${o}`}:{}},redirect:"follow",signal:AbortSignal.timeout(2e4)});return!c.ok||typeof c.arrayBuffer!="function"?null:ct(Buffer.from(await c.arrayBuffer()))}catch{return null}}const ut=Object.freeze({attempts:6,backoffMs:Object.freeze([1e3,3e3,8e3,15e3,3e4]),stallMs:6e4}),ft=new Set([401,403,404,410]),pt=e=>new Promise(t=>setTimeout(t,e));async function W({repo:e,commit:t,files:r,destOf:n,fetchImpl:o=globalThis.fetch,token:c=null,onProgress:s=()=>{},total:a=0,retry:l=ut,sleep:i=pt}){let u=0;for(const f of r){const d=n(f.path);if(b(d)&&f.size&&S(d).size===f.size){u+=f.size,s({file:f.path,bytes:u,total:a,fileBytes:f.size,fileTotal:f.size,skipped:!0});continue}O(g.dirname(d),{recursive:!0,mode:448});const z=u;for(let p=1;;p++){u=z;try{u=await ht({repo:e,commit:t,f,dest:d,fetchImpl:o,token:c,onProgress:s,total:a,bytes:u,stallMs:l.stallMs});break}catch(h){const y=String(h?.message||h);if(h?.permanent||y==="cancelled"||p>=l.attempts)throw h;const w=l.backoffMs[Math.min(p-1,l.backoffMs.length-1)];s({file:f.path,bytes:u,total:a,fileBytes:0,fileTotal:f.size,skipped:!0,retry:{attempt:p+1,of:l.attempts,inMs:w,error:y.slice(0,160)}}),await i(w),s({file:f.path,bytes:u,total:a,fileBytes:0,fileTotal:f.size,skipped:!0})}}}return u}async function ht({repo:e,commit:t,f:r,dest:n,fetchImpl:o,token:c,onProgress:s,total:a,bytes:l,stallMs:i}){const u=`${n}.part`,f=b(u)?S(u).size:0,d=f>0&&(!r.size||f<r.size),z={...c?{authorization:`Bearer ${c}`}:{},...d?{range:`bytes=${f}-`}:{}},p=new AbortController;let h=null;const y=()=>{clearTimeout(h),h=setTimeout(()=>p.abort(new Error(`no bytes for ${Math.round(i/1e3)} s`)),i)};y();try{let w;try{w=await o(`${R}/${e}/resolve/${encodeURIComponent(t)}/${r.path.split("/").map(encodeURIComponent).join("/")}`,{headers:z,redirect:"follow",signal:p.signal})}catch(m){throw new Error(`${r.path}: ${p.signal.aborted?p.signal.reason?.message:m?.cause?.code||m?.message||m}`)}if(!w.ok||!w.body){const m=new Error(`${r.path}: Hugging Face answered ${w.status}${w.status===401||w.status===403?" — the repo needs a sign-in or accepting its licence on huggingface.co":""}`);throw m.permanent=ft.has(w.status),m}const $=d&&w.status===206;let _=$?f:0;$&&(l+=f,s({file:r.path,bytes:l,total:a,fileBytes:_,fileTotal:r.size,skipped:!0}));const Q=new TransformStream({transform(m,q){y(),_+=m.byteLength,l+=m.byteLength,s({file:r.path,bytes:l,total:a,fileBytes:_,fileTotal:r.size}),q.enqueue(m)}});try{await X(Y.fromWeb(w.body.pipeThrough(Q)),Z(u,{mode:384,flags:$?"a":"w"}))}catch(m){throw String(m?.message)==="cancelled"?m:new Error(`${r.path}: ${p.signal.aborted?p.signal.reason?.message:m?.cause?.code||m?.code||m?.message||m} after ${_} bytes`)}if(r.size&&S(u).size!==r.size)throw new Error(`${r.path}: ${S(u).size} of ${r.size} bytes arrived`);return K(u,n),l}finally{clearTimeout(h)}}async function bt(e,{root:t,fetchImpl:r=globalThis.fetch,token:n=null,onProgress:o=()=>{}}={}){const{commit:c,siblings:s}=await L(e,{fetchImpl:r,token:n}),{files:a,total:l}=et(s);if(!a.length)throw new Error(`${e}: nothing to download (no weights or config listed)`);const i=C(t,e),u=g.join(i,"snapshots",c),f=await W({repo:e,commit:c,files:a,total:l,destOf:d=>g.join(u,d),fetchImpl:r,token:n,onProgress:o});return O(g.join(i,"refs"),{recursive:!0,mode:448}),I(g.join(i,"refs","main"),c,{mode:384}),{dir:u,commit:c,files:a.map(d=>d.path),bytes:f,total:l}}async function gt(e,{fetchImpl:t=globalThis.fetch,token:r=null,knows:n=null,engineVersion:o=null}={}){const c=k(e);if(!c)throw new Error(`not a model id: ${e}`);const{commit:s,siblings:a}=await L(c.repo,{fetchImpl:t,token:r}),l=F(a),i=l.alts.length?["main","alt"]:["main"];let u=null;const f=[];for(const p of i){let h;try{h=st(a,c.quant,{layout:p})}catch($){if(p==="main")throw $;continue}const y=n?await lt(c.repo,s,h.main,{fetchImpl:t,token:r}):null;if((y&&n?n(y):null)===!1){f.push(y);continue}u={layout:p,arch:y,...h};break}if(!u){const p=[...new Set(f)].join(" or "),h=new Error(`${c.repo}: llama.cpp${o?` ${o}`:""} on this machine cannot run ${p} models. Update it on its row in Settings › Runtime — and if that says it is up to date, support for ${p} is not in a llama.cpp release yet: the model has to wait for the next one.`);throw h.code="unsupported_arch",h.arch=f[0],h}const d=nt(l.projectors),z=ot(l.drafts);return{repo:c.repo,commit:s,quant:c.quant||j(u.main),layout:u.layout,arch:u.arch,weights:u.files,total:u.total,main:u.main,projector:d?{path:d.path,size:d.size}:null,draft:z?{path:z.path,size:z.size,spec:G(z.path)}:null,quants:it(a)}}function _t(e,t){const r=k(t);if(!r)return{};try{const n=JSON.parse(T(g.join(e,"gguf",r.repo.replace("/","--"),"recipe.json"),"utf8"));return{...n.projector&&b(n.projector)?{projector:n.projector}:{},...n.draft?.path&&b(n.draft.path)?{draft:{path:n.draft.path,spec:n.draft.spec||G(n.draft.path)}}:{},...H(e,t)}}catch{return H(e,t)}}const A=new Map;function H(e,t){const r=dt(e,t);if(!r)return{};let n;try{n=`${r}:${S(r).mtimeMs}`}catch{return{}}A.has(n)||A.set(n,J(r));const o=A.get(n);return o?{recommended:o}:{}}async function St(e,{root:t,fetchImpl:r=globalThis.fetch,token:n=null,onProgress:o=()=>{},knows:c=null,engineVersion:s=null,vision:a=!0,draft:l=!0}={}){const i=await gt(e,{fetchImpl:r,token:n,knows:c,engineVersion:s}),u=[...a&&i.projector?[i.projector]:[],...l&&i.draft?[i.draft]:[]],f=[...i.weights,...u],d=f.reduce(($,_)=>$+(_.size||0),0),z=await W({repo:i.repo,commit:i.commit,files:f,total:d,destOf:$=>x(t,i.repo,$),fetchImpl:r,token:n,onProgress:o}),p=$=>$?x(t,i.repo,$.path):null,h={projector:a?p(i.projector):null,draft:l&&i.draft?{path:p(i.draft),spec:i.draft.spec}:null,arch:i.arch,layout:i.layout},y=g.join(t,"gguf",i.repo.replace("/","--"),"recipe.json");let w={};try{w=JSON.parse(T(y,"utf8"))}catch{}return I(y,JSON.stringify({...w,...Object.fromEntries(Object.entries(h).filter(([,$])=>$))},null,2),{mode:384}),{main:x(t,i.repo,i.main),files:i.weights.map($=>x(t,i.repo,$.path)),bytes:z,total:d,projector:h.projector,draft:h.draft}}function xt(e,t){const r=C(e,t);try{const n=T(g.join(r,"refs","main"),"utf8").trim();return!!n&&b(g.join(r,"snapshots",n))&&b(g.join(r,"snapshots",n,"config.json"))}catch{return!1}}function dt(e,t){const r=k(t);if(!r)return null;const n=g.join(e,"gguf",r.repo.replace("/","--"));if(!b(n))return null;const o=(r.quant||"Q4_K_M").toLowerCase(),c=mt(n).filter(a=>M(a,/\.gguf$/i)&&!a.endsWith(".part"));let s=c.filter(a=>v(a,o)).sort();if(!s.length&&!r.quant&&c.length){const a=c.map(i=>({path:i,size:(()=>{try{return S(g.join(n,i)).size}catch{return 0}})()})),l=D(a);s=c.filter(i=>j(i)===l).sort()}return s.length?g.join(n,s[0]):null}function mt(e){try{return P(e)}catch{return[]}}export{ut as DOWNLOAD_RETRY,R as HF_API,L as describeRepo,W as downloadFiles,G as draftSpecOf,lt as ggufArchitecture,ct as ggufHeaderArch,dt as ggufInstalled,F as ggufKinds,x as ggufPath,it as ggufQuants,_t as ggufRecipe,k as parseModelRef,ot as pickDraft,nt as pickProjector,st as planGgufFiles,gt as planGgufRecipe,et as planRepoFiles,St as pullGguf,bt as pullRepo,j as quantOf,C as repoCacheDir,xt as repoInstalled};
|
|
1
|
+
import{createWriteStream as J,mkdirSync as C,renameSync as K,existsSync as b,writeFileSync as L,statSync as _,readFileSync as x,readdirSync as P}from"node:fs";import{ggufRecommended as Y}from"./gguf-meta.js";import{Readable as X}from"node:stream";import{pipeline as V}from"node:stream/promises";import p from"node:path";const R="https://huggingface.co",tt=/\.(bin|pt|pth|ckpt|h5|msgpack|onnx|gguf|tflite)$/i,et=/(^|\/)(\.gitattributes|README\.md|LICENSE.*|.*\.md|original\/.*|coreml\/.*|onnx\/.*|images?\/.*|assets\/.*)$/i;function M(e){const t=/^([A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95})(?::([A-Za-z0-9._-]{1,32}))?$/.exec(String(e||"").trim());return t?{repo:t[1],quant:t[2]||null}:null}const k=(e,t)=>p.join(e,"hub",`models--${t.replace("/","--")}`);async function U(e,{fetchImpl:t=globalThis.fetch,token:n=null}={}){const r=await t(`${R}/api/models/${e}?blobs=true`,{headers:n?{authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(2e4)});if(r.status===401||r.status===403)throw new Error(`${e}: gated or private on Hugging Face — accept its licence there and add a token`);if(r.status===404)throw new Error(`${e}: no such model on Hugging Face`);if(!r.ok)throw new Error(`${e}: Hugging Face answered ${r.status}`);const o=await r.json(),i=(o.siblings||[]).map(c=>({path:c.rfilename,size:Number(c.lfs?.size??c.size??0)})).filter(c=>c.path);return{commit:String(o.sha||"main"),siblings:i}}function nt(e){const t=e.some(r=>/\.safetensors$/i.test(r.path)),n=e.filter(r=>!(et.test(r.path)||t&&tt.test(r.path)||!t&&/\.(gguf|onnx|tflite|msgpack|h5|ckpt)$/i.test(r.path)));return{files:n,total:n.reduce((r,o)=>r+o.size,0)}}const B=/(^|\/)mmproj[^/]*\.gguf$/i,q=/(^|\/)(?:dspark|dflash|eagle3?)[-_][^/]*\.gguf$|[-_.]mtp(?:[-_.][^/]*)?\.gguf$|(^|\/)[^/]*draft[^/]*\.gguf$/i,rt=/(^|\/)imatrix[^/]*\.gguf$/i,A=(e,t)=>t.test(e)&&!B.test(e)&&!q.test(e)&&!rt.test(e);function N(e){const t=p.basename(String(e||"")).toLowerCase();return t.startsWith("dspark")?"draft-dspark":t.startsWith("dflash")?"draft-dflash":/^eagle3?[-_]/.test(t)?"draft-eagle3":/[-_.]mtp([-_.]|$)/.test(t.replace(/\.gguf$/,""))?"draft-mtp":"draft-simple"}function F(e){return{mains:e.filter(t=>A(t.path,/\.gguf$/i)),alts:e.filter(t=>/\.gguf_file$/i.test(t.path)&&A(t.path.replace(/_file$/i,""),/\.gguf$/i)),projectors:e.filter(t=>B.test(t.path)),drafts:e.filter(t=>q.test(t.path))}}const G=(e,t)=>(e.path.includes("/")?1:0)-(t.path.includes("/")?1:0);function ot(e){const t=n=>{const r=["f16","bf16","q8_0","f32"].findIndex(o=>new RegExp(`[-_.]${o}\\.gguf$`,"i").test(n));return r<0?9:r};return e.slice().sort((n,r)=>G(n,r)||t(n.path)-t(r.path))[0]||null}function at(e){return e.slice().sort((t,n)=>G(t,n)||(t.size||0)-(n.size||0))[0]||null}const st=e=>p.basename(String(e)).replace(/\.gguf(_file)?$/i,"").replace(/-\d{5}-of-\d{5}$/,"").toLowerCase(),v=(e,t)=>{const n=e.toLowerCase().replace(/_file$/,"");return n.includes(`-${t}.`)||n.includes(`-${t}-0`)||n.includes(`.${t}.`)||n.includes(`/${t}/`)||n.includes(`_${t}.`)?!0:st(e)===t||j(e).toLowerCase()===j(`${t}.gguf`).toLowerCase()};function it(e,t=null,{layout:n="main"}={}){const r=F(e),o=n==="alt"?r.alts:r.mains;if(!o.length)throw new Error("no GGUF file in this repo");const i=(t||"Q4_K_M").toLowerCase();let c=o.filter(s=>v(s.path,i));if(!c.length&&!t){const s=D(o);c=o.filter(l=>j(l.path)===s)}if(!c.length)throw new Error(`no ${t||"Q4_K_M"} GGUF here — the repo has: ${[...new Set(o.map(s=>j(s.path)))].slice(0,12).join(", ")}`);return c=c.slice().sort((s,l)=>s.path.localeCompare(l.path)),{files:c,total:c.reduce((s,l)=>s+l.size,0),main:c[0].path}}function D(e){const t=r=>e.filter(o=>j(o.path)===r).reduce((o,i)=>o+(i.size||0),0),n=[...new Set(e.map(r=>j(r.path)))].sort((r,o)=>t(r)-t(o));return n.find(r=>/(^|-)I?Q4/i.test(r))||n[0]}function ct(e){const t=new Map;for(const n of F(e).mains){const r=j(n.path);t.set(r,(t.get(r)||0)+(n.size||0))}return[...t].map(([n,r])=>({quant:n,size:r})).sort((n,r)=>n.size-r.size)}function j(e){const t=p.basename(e).replace(/\.gguf(_file)?$/i,"").replace(/-\d{5}-of-\d{5}$/,""),n=/[-._]((?:UD-)?(?:I?Q\d[A-Z0-9_]*|BF16|F16|F32|MTP))$/i.exec(t);return n?n[1]:t}const E=(e,t,n)=>p.join(e,"gguf",t.replace("/","--"),p.basename(n).replace(/\.gguf_file$/i,".gguf")),T={0:1,1:1,2:2,3:2,4:4,5:4,6:4,7:1,10:8,11:8,12:8};function lt(e){try{if(e.length<24||e.toString("latin1",0,4)!=="GGUF")return null;let t=16;const n=Number(e.readBigUInt64LE(t));t+=8;const r=()=>{const o=Number(e.readBigUInt64LE(t));t+=8;const i=e.toString("utf8",t,t+o);return t+=o,i};for(let o=0;o<n&&t<e.length;o++){const i=r(),c=e.readUInt32LE(t);if(t+=4,c===8){const s=r();if(i==="general.architecture")return s||null;continue}if(c===9){const s=e.readUInt32LE(t);t+=4;const l=Number(e.readBigUInt64LE(t));if(t+=8,s===8)for(let a=0;a<l;a++)r();else if(T[s])t+=T[s]*l;else return null;continue}if(!T[c])return null;t+=T[c]}}catch{}return null}async function ut(e,t,n,{fetchImpl:r=globalThis.fetch,token:o=null}={}){try{const i=await r(`${R}/${e}/resolve/${encodeURIComponent(t)}/${n.split("/").map(encodeURIComponent).join("/")}`,{headers:{range:"bytes=0-65535",...o?{authorization:`Bearer ${o}`}:{}},redirect:"follow",signal:AbortSignal.timeout(2e4)});return!i.ok||typeof i.arrayBuffer!="function"?null:lt(Buffer.from(await i.arrayBuffer()))}catch{return null}}const ft=Object.freeze({attempts:6,backoffMs:Object.freeze([1e3,3e3,8e3,15e3,3e4]),stallMs:6e4}),pt=new Set([401,403,404,410]),ht=e=>new Promise(t=>setTimeout(t,e));async function W({repo:e,commit:t,files:n,destOf:r,fetchImpl:o=globalThis.fetch,token:i=null,onProgress:c=()=>{},total:s=0,retry:l=ft,sleep:a=ht}){let u=0;for(const f of n){const d=r(f.path);if(b(d)&&f.size&&_(d).size===f.size){u+=f.size,c({file:f.path,bytes:u,total:s,fileBytes:f.size,fileTotal:f.size,skipped:!0});continue}C(p.dirname(d),{recursive:!0,mode:448});const z=u;for(let h=1;;h++){u=z;try{u=await gt({repo:e,commit:t,f,dest:d,fetchImpl:o,token:i,onProgress:c,total:s,bytes:u,stallMs:l.stallMs});break}catch(g){const y=String(g?.message||g);if(g?.permanent||y==="cancelled"||h>=l.attempts)throw g;const $=l.backoffMs[Math.min(h-1,l.backoffMs.length-1)];c({file:f.path,bytes:u,total:s,fileBytes:0,fileTotal:f.size,skipped:!0,retry:{attempt:h+1,of:l.attempts,inMs:$,error:y.slice(0,160)}}),await a($),c({file:f.path,bytes:u,total:s,fileBytes:0,fileTotal:f.size,skipped:!0})}}}return u}async function gt({repo:e,commit:t,f:n,dest:r,fetchImpl:o,token:i,onProgress:c,total:s,bytes:l,stallMs:a}){const u=`${r}.part`,f=b(u)?_(u).size:0,d=f>0&&(!n.size||f<n.size),z={...i?{authorization:`Bearer ${i}`}:{},...d?{range:`bytes=${f}-`}:{}},h=new AbortController;let g=null;const y=()=>{clearTimeout(g),g=setTimeout(()=>h.abort(new Error(`no bytes for ${Math.round(a/1e3)} s`)),a)};y();try{let $;try{$=await o(`${R}/${e}/resolve/${encodeURIComponent(t)}/${n.path.split("/").map(encodeURIComponent).join("/")}`,{headers:z,redirect:"follow",signal:h.signal})}catch(m){throw new Error(`${n.path}: ${h.signal.aborted?h.signal.reason?.message:m?.cause?.code||m?.message||m}`)}if(!$.ok||!$.body){const m=new Error(`${n.path}: Hugging Face answered ${$.status}${$.status===401||$.status===403?" — the repo needs a sign-in or accepting its licence on huggingface.co":""}`);throw m.permanent=pt.has($.status),m}const w=d&&$.status===206;let S=w?f:0;w&&(l+=f,c({file:n.path,bytes:l,total:s,fileBytes:S,fileTotal:n.size,skipped:!0}));const Q=new TransformStream({transform(m,Z){y(),S+=m.byteLength,l+=m.byteLength,c({file:n.path,bytes:l,total:s,fileBytes:S,fileTotal:n.size}),Z.enqueue(m)}});try{await V(X.fromWeb($.body.pipeThrough(Q)),J(u,{mode:384,flags:w?"a":"w"}))}catch(m){throw String(m?.message)==="cancelled"?m:new Error(`${n.path}: ${h.signal.aborted?h.signal.reason?.message:m?.cause?.code||m?.code||m?.message||m} after ${S} bytes`)}if(n.size&&_(u).size!==n.size)throw new Error(`${n.path}: ${_(u).size} of ${n.size} bytes arrived`);return K(u,r),l}finally{clearTimeout(g)}}async function _t(e,{root:t,fetchImpl:n=globalThis.fetch,token:r=null,onProgress:o=()=>{}}={}){const{commit:i,siblings:c}=await U(e,{fetchImpl:n,token:r}),{files:s,total:l}=nt(c);if(!s.length)throw new Error(`${e}: nothing to download (no weights or config listed)`);const a=k(t,e),u=p.join(a,"snapshots",i),f=await W({repo:e,commit:i,files:s,total:l,destOf:d=>p.join(u,d),fetchImpl:n,token:r,onProgress:o});return C(p.join(a,"refs"),{recursive:!0,mode:448}),L(p.join(a,"refs","main"),i,{mode:384}),{dir:u,commit:i,files:s.map(d=>d.path),bytes:f,total:l}}async function dt(e,{fetchImpl:t=globalThis.fetch,token:n=null,knows:r=null,engineVersion:o=null}={}){const i=M(e);if(!i)throw new Error(`not a model id: ${e}`);const{commit:c,siblings:s}=await U(i.repo,{fetchImpl:t,token:n}),l=F(s),a=l.alts.length?["main","alt"]:["main"];let u=null;const f=[];for(const h of a){let g;try{g=it(s,i.quant,{layout:h})}catch(w){if(h==="main")throw w;continue}const y=r?await ut(i.repo,c,g.main,{fetchImpl:t,token:n}):null;if((y&&r?r(y):null)===!1){f.push(y);continue}u={layout:h,arch:y,...g};break}if(!u){const h=[...new Set(f)].join(" or "),g=new Error(`${i.repo}: llama.cpp${o?` ${o}`:""} on this machine cannot run ${h} models. Update it on its row in Settings › Runtime — and if that says it is up to date, support for ${h} is not in a llama.cpp release yet: the model has to wait for the next one.`);throw g.code="unsupported_arch",g.arch=f[0],g}const d=ot(l.projectors),z=at(l.drafts);return{repo:i.repo,commit:c,quant:i.quant||j(u.main),layout:u.layout,arch:u.arch,weights:u.files,total:u.total,main:u.main,projector:d?{path:d.path,size:d.size}:null,draft:z?{path:z.path,size:z.size,spec:N(z.path)}:null,quants:ct(s)}}function St(e,t){const n=M(t);if(!n)return{};try{const r=JSON.parse(x(p.join(e,"gguf",n.repo.replace("/","--"),"recipe.json"),"utf8"));return{...r.projector&&b(r.projector)?{projector:r.projector}:{},...r.draft?.path&&b(r.draft.path)?{draft:{path:r.draft.path,spec:r.draft.spec||N(r.draft.path)}}:{},...H(e,t)}}catch{return H(e,t)}}const O=new Map;function H(e,t){const n=$t(e,t);if(!n)return{};let r;try{r=`${n}:${_(n).mtimeMs}`}catch{return{}}O.has(r)||O.set(r,Y(n));const o=O.get(r);return o?{recommended:o}:{}}async function xt(e,{root:t,fetchImpl:n=globalThis.fetch,token:r=null,onProgress:o=()=>{},knows:i=null,engineVersion:c=null,vision:s=!0,draft:l=!0}={}){const a=await dt(e,{fetchImpl:n,token:r,knows:i,engineVersion:c}),u=[...s&&a.projector?[a.projector]:[],...l&&a.draft?[a.draft]:[]],f=[...a.weights,...u],d=f.reduce((w,S)=>w+(S.size||0),0),z=await W({repo:a.repo,commit:a.commit,files:f,total:d,destOf:w=>E(t,a.repo,w),fetchImpl:n,token:r,onProgress:o}),h=w=>w?E(t,a.repo,w.path):null,g={projector:s?h(a.projector):null,draft:l&&a.draft?{path:h(a.draft),spec:a.draft.spec}:null,arch:a.arch,layout:a.layout},y=p.join(t,"gguf",a.repo.replace("/","--"),"recipe.json");let $={};try{$=JSON.parse(x(y,"utf8"))}catch{}return L(y,JSON.stringify({...$,...Object.fromEntries(Object.entries(g).filter(([,w])=>w))},null,2),{mode:384}),{main:E(t,a.repo,a.main),files:a.weights.map(w=>E(t,a.repo,w.path)),bytes:z,total:d,projector:g.projector,draft:g.draft}}function mt(e,t){const n=k(e,t);try{const r=x(p.join(n,"refs","main"),"utf8").trim();return!!r&&b(p.join(n,"snapshots",r))&&b(p.join(n,"snapshots",r,"config.json"))}catch{return!1}}function Et(e){const t=p.join(e,"hub"),n=[];for(const r of I(t)){const o=/^models--([^-][^/]*?)--(.+)$/.exec(r);if(!o)continue;const i=`${o[1]}/${o[2]}`;if(mt(e,i))try{const c=k(e,i),s=p.join(c,"snapshots",x(p.join(c,"refs","main"),"utf8").trim()),l=I(s);if(!l.some(f=>/\.safetensors$/i.test(f)))continue;const a=JSON.parse(x(p.join(s,"config.json"),"utf8"));let u=0;for(const f of l)if(/\.safetensors$/i.test(f))try{u+=_(p.join(s,f)).size}catch{}n.push({id:i,architectures:Array.isArray(a.architectures)?a.architectures.map(String):[],modelType:String(a.model_type||""),mlx:!!(a.quantization&&typeof a.quantization=="object"&&"bits"in a.quantization),quantMethod:String(a.quantization_config?.quant_method||""),bytes:u})}catch{}}return n}function $t(e,t){const n=M(t);if(!n)return null;const r=p.join(e,"gguf",n.repo.replace("/","--"));if(!b(r))return null;const o=(n.quant||"Q4_K_M").toLowerCase(),i=I(r).filter(s=>A(s,/\.gguf$/i)&&!s.endsWith(".part"));let c=i.filter(s=>v(s,o)).sort();if(!c.length&&!n.quant&&i.length){const s=i.map(a=>({path:a,size:(()=>{try{return _(p.join(r,a)).size}catch{return 0}})()})),l=D(s);c=i.filter(a=>j(a)===l).sort()}return c.length?p.join(r,c[0]):null}function I(e){try{return P(e)}catch{return[]}}export{ft as DOWNLOAD_RETRY,R as HF_API,Et as cachedRepos,U as describeRepo,W as downloadFiles,N as draftSpecOf,ut as ggufArchitecture,lt as ggufHeaderArch,$t as ggufInstalled,F as ggufKinds,E as ggufPath,ct as ggufQuants,St as ggufRecipe,M as parseModelRef,at as pickDraft,ot as pickProjector,it as planGgufFiles,dt as planGgufRecipe,nt as planRepoFiles,xt as pullGguf,_t as pullRepo,j as quantOf,k as repoCacheDir,mt as repoInstalled};
|
package/src/runtime-models.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const M=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/,B=Object.freeze([{id:"BAAI/bge-reranker-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",recommended:!0,note:"Half the size of v2 m3, most of the quality, the same 100+ languages; the ship default."},{id:"BAAI/bge-reranker-v2-m3",label:"bge-reranker v2 m3",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:2600,minRamMB:4096,licence:"Apache-2.0",note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; twice the memory."},{id:"BAAI/bge-reranker-large",label:"bge-reranker large",lang:"100+ languages",tier:"max",approxMB:2240,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The first-generation large model; v2 m3 is newer and usually better at the same cost."},{id:"mixedbread-ai/mxbai-rerank-base-v1",label:"mxbai-rerank base v1",lang:"English",tier:"balanced",approxMB:740,ramMB:900,minRamMB:2048,licence:"Apache-2.0",note:"English-only, small and quick — a good fit for notes and search on a modest machine."},{id:"cross-encoder/ms-marco-MiniLM-L-6-v2",label:"MiniLM-L6 (MS MARCO)",lang:"English",tier:"light",approxMB:90,ramMB:300,minRamMB:1024,licence:"Apache-2.0",note:"Tiny and fast; the classic web-search reranker. English only, short passages."}]),u=Object.freeze([{id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",recommended:!0,note:"A third of the size of large, close on most typed decisions; the ship default. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{id:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",label:"ModernBERT large zero-shot v2",lang:"English",tier:"accurate",approxMB:1600,ramMB:2400,minRamMB:4096,licence:"Apache-2.0",note:"What OpenDecision was built around; 8k context, a little sharper, three times the memory."},{id:"MoritzLaurer/deberta-v3-large-zeroshot-v2.0",label:"DeBERTa v3 large zero-shot v2",lang:"English",tier:"max",approxMB:1740,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The strongest English zero-shot classifier of the family; slower than ModernBERT, 512 tokens."},{id:"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli",label:"mDeBERTa v3 base (XNLI)",lang:"100 languages",tier:"balanced",approxMB:1120,ramMB:1400,minRamMB:2048,licence:"MIT",note:"The multilingual one: sentiment, routing and triage in Hindi, Telugu, Spanish, German… on the same questions."},{id:"MoritzLaurer/deberta-v3-xsmall-zeroshot-v1.1-all-33",label:"DeBERTa v3 xsmall zero-shot",lang:"English",tier:"light",approxMB:280,ramMB:500,minRamMB:1024,licence:"MIT",note:"Tiny and quick — decisions in tens of milliseconds on any machine, at some accuracy."}]),d=Object.freeze([{id:"Qwen/Qwen3-0.6B",label:"Qwen3 0.6B",task:"chat",lang:"100+ languages",tier:"light",approxMB:1200,ramMB:3e3,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The smallest Qwen3 — a chat model that runs on CPU at a usable pace. The ship default for trying vLLM here."},{id:"Qwen/Qwen3-1.7B",label:"Qwen3 1.7B",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:3400,ramMB:6e3,minRamMB:8192,licence:"Apache-2.0",note:"Noticeably stronger; wants 8 GB for the engine and patience on CPU."},{id:"Qwen/Qwen3-4B",label:"Qwen3 4B",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:8e3,ramMB:12e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant; a GPU, or a big machine and patience."},{id:"HuggingFaceTB/SmolLM3-3B",label:"SmolLM3 3B",task:"chat",lang:"6 languages",tier:"balanced",approxMB:6200,ramMB:9e3,minRamMB:12288,licence:"Apache-2.0",note:"A small model built for tool use and long context; English-first."},{id:"Qwen/Qwen3-Embedding-0.6B",label:"Qwen3 Embedding 0.6B",task:"embed",lang:"100+ languages",tier:"balanced",approxMB:1200,ramMB:2500,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"Embeddings for semantic search (1024 dims); the first provider /v1/embeddings has had."},{id:"BAAI/bge-m3",label:"bge-m3",task:"embed",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:3500,minRamMB:4096,licence:"MIT",note:"The multilingual retrieval standard; dense 1024-dim vectors, long passages."},{id:"openai/whisper-large-v3-turbo",label:"Whisper large v3 turbo",task:"transcription",lang:"99 languages",tier:"accurate",approxMB:1600,ramMB:4e3,minRamMB:6144,licence:"MIT",note:"Speech to text through vLLM’s /v1/audio/transcriptions — a container the whole machine’s ears share; heavy on CPU."},{id:"openai/whisper-small",label:"Whisper small",task:"transcription",lang:"99 languages",tier:"light",approxMB:970,ramMB:2500,minRamMB:4096,licence:"MIT",note:"The light transcriber for a container on CPU."},{id:"Qwen/Qwen3-ASR-0.6B",label:"Qwen3-ASR 0.6B (experimental)",task:"transcription",lang:"52 languages",tier:"balanced",approxMB:1400,ramMB:4e3,minRamMB:6144,licence:"Apache-2.0",note:"The strongest small multilingual transcriber (5–6% WER on the open leaderboard). EXPERIMENTAL here: vLLM’s transcription route served whisper-family models only when this entry was written — if the container comes up without /v1/audio/transcriptions, the Runtime says so and the row stays empty."}]);function w(n){return d.find(e=>e.id===n)?.task||"chat"}const p=Object.freeze([{id:"mlx-community/Qwen3-0.6B-4bit",label:"Qwen3 0.6B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:400,ramMB:1200,minRamMB:4096,licence:"Apache-2.0",note:"The smallest: titles and topic lists at almost no cost. Copies examples and skips optional steps — not for real conversations."},{id:"mlx-community/Qwen3-1.7B-4bit",label:"Qwen3 1.7B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:1100,ramMB:2500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac; the ship default for vLLM-Metal and MLX."},{id:"mlx-community/Qwen3-4B-4bit",label:"Qwen3 4B (4-bit)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:5e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant on a 16 GB Mac."},{id:"mlx-community/Qwen3-8B-4bit",label:"Qwen3 8B (4-bit)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:4700,ramMB:9e3,minRamMB:24576,licence:"Apache-2.0",note:"Strong; wants 24 GB of unified memory."},{id:"mlx-community/gemma-3-4b-it-4bit",label:"Gemma 3 4B (4-bit)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2700,ramMB:5500,minRamMB:16384,licence:"Gemma",note:"Google’s small model, vision-capable; a strong multilingual choice."},{id:"mlx-community/Llama-3.2-3B-Instruct-4bit",label:"Llama 3.2 3B (4-bit)",task:"chat",lang:"8 languages",tier:"balanced",approxMB:1800,ramMB:4e3,minRamMB:8192,licence:"Llama 3.2",note:"The familiar one; English-first."}]),b=Object.freeze([{id:"unsloth/Qwen3-4B-GGUF:Q4_K_M",label:"Qwen3 4B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac or a laptop CPU; thinks when asked. The ship default for trying llama.cpp here."},{id:"unsloth/Qwen3-8B-GGUF:Q4_K_M",label:"Qwen3 8B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:5e3,ramMB:8e3,minRamMB:16384,licence:"Apache-2.0",note:"Strong general assistant; comfortable on 16 GB with a 16k context."},{id:"unsloth/Qwen2.5-Coder-7B-Instruct-GGUF:Q4_K_M",label:"Qwen2.5 Coder 7B (Q4_K_M)",task:"chat",lang:"code, English, Chinese",tier:"accurate",approxMB:4700,ramMB:7500,minRamMB:16384,licence:"Apache-2.0",note:"The coding model at this size; a local coding agent’s first pick."},{id:"ggml-org/gemma-3-4b-it-GGUF:Q4_K_M",label:"Gemma 3 4B (Q4_K_M)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Gemma",note:"Google’s small model; takes images once its mmproj is named under Vision projector."},{id:"unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL",label:"Gemma 4 26B-A4B (UD-Q4_K_XL)",task:"chat",lang:"140 languages",tier:"max",approxMB:16500,ramMB:22e3,minRamMB:36864,licence:"Gemma",note:"The mixture model the `lm` recipe runs — 26B of weights, 4B active per token, so it answers like a big model at a small one’s speed. Wants 36 GB+; its MTP draft file under Draft model makes it faster still."}]),x=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}(:[A-Za-z0-9._-]{1,32})?$/;function A(n){const e=String(n||"").trim();return x.test(e)||/^(\/|[A-Za-z]:\\)/.test(e)&&/\.gguf$/i.test(e)&&!/[\s"'`$;|&<>]/.test(e)}const f={reranker:B,opendecision:u,vllm:d,"vllm-metal":p,mlx:p,llama:b};function s(n){return f[n]||[]}function k(n,e){if(typeof e!="string"||!e.trim())return!1;const t=e.trim();return n==="llama"?s(n).some(i=>i.id===t)||A(t):s(n).some(i=>i.id===t)||M.test(t)}function L(n){return`models--${String(n).replace(/\//g,"--")}`}function R(n,{active:e=null,engineRamMB:t=0,engine:i=null,platform:m=process.platform,installed:c=()=>!1}={}){const r=a=>`${Math.round(a/1024*10)/10} GB`,g=a=>i==="podman"&&m!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((a.ramMB+2048)/2048)*2048)} && podman machine start`:i==="docker"&&m!=="linux"?"raise the memory in Docker Desktop › Settings › Resources":null,l=s(n).map(a=>{const o=t>0&&a.ramMB>t,h=!o&&Number(a.minRamMB)>0&&t>0&&t<a.minRamMB;return{...a,installed:c(a.id),recommended:!!a.recommended&&!o&&!h,...o?{unavailable:`needs about ${r(a.ramMB)} of memory while loaded — the container engine has ${r(t)}${g(a)?`; raise it: ${g(a)}`:""}`}:{},...h?{ramNote:`needs about ${r(a.ramMB)} while loaded — the engine has ${r(t)}; expect it to slow things down`}:{}}});return e&&!l.some(a=>a.id===e)&&l.push({id:e,label:/\.gguf$/i.test(e)?e.split(/[\\/]/).pop():e,lang:"—",tier:"custom",custom:!0,installed:c(e),note:/\.gguf$/i.test(e)?"A GGUF on this machine.":"Custom model (from Hugging Face)."}),l}export{u as DECIDE_MODEL_CATALOG,M as HF_ID,b as LLAMA_MODEL_CATALOG,B as RERANK_MODEL_CATALOG,p as VLLM_METAL_MODEL_CATALOG,d as VLLM_MODEL_CATALOG,L as cacheDirName,s as catalogFor,A as isLlamaModelId,k as isValidModelId,R as modelsFor,w as vllmTaskOf};
|
|
1
|
+
const A=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/,w=Object.freeze([{id:"BAAI/bge-reranker-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",recommended:!0,note:"Half the size of v2 m3, most of the quality, the same 100+ languages; the ship default."},{id:"BAAI/bge-reranker-v2-m3",label:"bge-reranker v2 m3",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:2600,minRamMB:4096,licence:"Apache-2.0",note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; twice the memory."},{id:"BAAI/bge-reranker-large",label:"bge-reranker large",lang:"100+ languages",tier:"max",approxMB:2240,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The first-generation large model; v2 m3 is newer and usually better at the same cost."},{id:"mixedbread-ai/mxbai-rerank-base-v1",label:"mxbai-rerank base v1",lang:"English",tier:"balanced",approxMB:740,ramMB:900,minRamMB:2048,licence:"Apache-2.0",note:"English-only, small and quick — a good fit for notes and search on a modest machine."},{id:"cross-encoder/ms-marco-MiniLM-L-6-v2",label:"MiniLM-L6 (MS MARCO)",lang:"English",tier:"light",approxMB:90,ramMB:300,minRamMB:1024,licence:"Apache-2.0",note:"Tiny and fast; the classic web-search reranker. English only, short passages."}]),k=Object.freeze([{id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",recommended:!0,note:"A third of the size of large, close on most typed decisions; the ship default. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{id:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",label:"ModernBERT large zero-shot v2",lang:"English",tier:"accurate",approxMB:1600,ramMB:2400,minRamMB:4096,licence:"Apache-2.0",note:"What OpenDecision was built around; 8k context, a little sharper, three times the memory."},{id:"MoritzLaurer/deberta-v3-large-zeroshot-v2.0",label:"DeBERTa v3 large zero-shot v2",lang:"English",tier:"max",approxMB:1740,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The strongest English zero-shot classifier of the family; slower than ModernBERT, 512 tokens."},{id:"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli",label:"mDeBERTa v3 base (XNLI)",lang:"100 languages",tier:"balanced",approxMB:1120,ramMB:1400,minRamMB:2048,licence:"MIT",note:"The multilingual one: sentiment, routing and triage in Hindi, Telugu, Spanish, German… on the same questions."},{id:"MoritzLaurer/deberta-v3-xsmall-zeroshot-v1.1-all-33",label:"DeBERTa v3 xsmall zero-shot",lang:"English",tier:"light",approxMB:280,ramMB:500,minRamMB:1024,licence:"MIT",note:"Tiny and quick — decisions in tens of milliseconds on any machine, at some accuracy."}]),p=Object.freeze([{id:"Qwen/Qwen3-0.6B",label:"Qwen3 0.6B",task:"chat",lang:"100+ languages",tier:"light",approxMB:1200,ramMB:3e3,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The smallest Qwen3 — a chat model that runs on CPU at a usable pace. The ship default for trying vLLM here."},{id:"Qwen/Qwen3-1.7B",label:"Qwen3 1.7B",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:3400,ramMB:6e3,minRamMB:8192,licence:"Apache-2.0",note:"Noticeably stronger; wants 8 GB for the engine and patience on CPU."},{id:"Qwen/Qwen3-4B",label:"Qwen3 4B",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:8e3,ramMB:12e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant; a GPU, or a big machine and patience."},{id:"HuggingFaceTB/SmolLM3-3B",label:"SmolLM3 3B",task:"chat",lang:"6 languages",tier:"balanced",approxMB:6200,ramMB:9e3,minRamMB:12288,licence:"Apache-2.0",note:"A small model built for tool use and long context; English-first."},{id:"Qwen/Qwen3-Embedding-0.6B",label:"Qwen3 Embedding 0.6B",task:"embed",lang:"100+ languages",tier:"balanced",approxMB:1200,ramMB:2500,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"Embeddings for semantic search (1024 dims); the first provider /v1/embeddings has had."},{id:"BAAI/bge-m3",label:"bge-m3",task:"embed",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:3500,minRamMB:4096,licence:"MIT",note:"The multilingual retrieval standard; dense 1024-dim vectors, long passages."},{id:"openai/whisper-large-v3-turbo",label:"Whisper large v3 turbo",task:"transcription",lang:"99 languages",tier:"accurate",approxMB:1600,ramMB:4e3,minRamMB:6144,licence:"MIT",note:"Speech to text through vLLM’s /v1/audio/transcriptions — a container the whole machine’s ears share; heavy on CPU."},{id:"openai/whisper-small",label:"Whisper small",task:"transcription",lang:"99 languages",tier:"light",approxMB:970,ramMB:2500,minRamMB:4096,licence:"MIT",note:"The light transcriber for a container on CPU."},{id:"Qwen/Qwen3-ASR-0.6B",label:"Qwen3-ASR 0.6B (experimental)",task:"transcription",lang:"52 languages",tier:"balanced",approxMB:1400,ramMB:4e3,minRamMB:6144,licence:"Apache-2.0",note:"The strongest small multilingual transcriber (5–6% WER on the open leaderboard). EXPERIMENTAL here: vLLM’s transcription route served whisper-family models only when this entry was written — if the container comes up without /v1/audio/transcriptions, the Runtime says so and the row stays empty."}]);function E(n){return p.find(a=>a.id===n)?.task||"chat"}const u=Object.freeze([{id:"mlx-community/Qwen3-0.6B-4bit",label:"Qwen3 0.6B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:400,ramMB:1200,minRamMB:4096,licence:"Apache-2.0",note:"The smallest: titles and topic lists at almost no cost. Copies examples and skips optional steps — not for real conversations."},{id:"mlx-community/Qwen3-1.7B-4bit",label:"Qwen3 1.7B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:1100,ramMB:2500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac; the ship default for vLLM-Metal and MLX."},{id:"mlx-community/Qwen3-4B-4bit",label:"Qwen3 4B (4-bit)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:5e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant on a 16 GB Mac."},{id:"mlx-community/Qwen3-8B-4bit",label:"Qwen3 8B (4-bit)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:4700,ramMB:9e3,minRamMB:24576,licence:"Apache-2.0",note:"Strong; wants 24 GB of unified memory."},{id:"mlx-community/gemma-3-4b-it-4bit",label:"Gemma 3 4B (4-bit)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2700,ramMB:5500,minRamMB:16384,licence:"Gemma",note:"Google’s small model, vision-capable; a strong multilingual choice."},{id:"mlx-community/Llama-3.2-3B-Instruct-4bit",label:"Llama 3.2 3B (4-bit)",task:"chat",lang:"8 languages",tier:"balanced",approxMB:1800,ramMB:4e3,minRamMB:8192,licence:"Llama 3.2",note:"The familiar one; English-first."}]),L=Object.freeze([{id:"unsloth/Qwen3-4B-GGUF:Q4_K_M",label:"Qwen3 4B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac or a laptop CPU; thinks when asked. The ship default for trying llama.cpp here."},{id:"unsloth/Qwen3-8B-GGUF:Q4_K_M",label:"Qwen3 8B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:5e3,ramMB:8e3,minRamMB:16384,licence:"Apache-2.0",note:"Strong general assistant; comfortable on 16 GB with a 16k context."},{id:"unsloth/Qwen2.5-Coder-7B-Instruct-GGUF:Q4_K_M",label:"Qwen2.5 Coder 7B (Q4_K_M)",task:"chat",lang:"code, English, Chinese",tier:"accurate",approxMB:4700,ramMB:7500,minRamMB:16384,licence:"Apache-2.0",note:"The coding model at this size; a local coding agent’s first pick."},{id:"ggml-org/gemma-3-4b-it-GGUF:Q4_K_M",label:"Gemma 3 4B (Q4_K_M)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Gemma",note:"Google’s small model; takes images once its mmproj is named under Vision projector."},{id:"unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL",label:"Gemma 4 26B-A4B (UD-Q4_K_XL)",task:"chat",lang:"140 languages",tier:"max",approxMB:16500,ramMB:22e3,minRamMB:36864,licence:"Gemma",note:"The mixture model the `lm` recipe runs — 26B of weights, 4B active per token, so it answers like a big model at a small one’s speed. Wants 36 GB+; its MTP draft file under Draft model makes it faster still."}]),y=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}(:[A-Za-z0-9._-]{1,32})?$/;function T(n){const a=String(n||"").trim();return y.test(a)||/^(\/|[A-Za-z]:\\)/.test(a)&&/\.gguf$/i.test(a)&&!/[\s"'`$;|&<>]/.test(a)}const R={reranker:w,opendecision:k,vllm:p,"vllm-metal":u,mlx:u,llama:L};function d(n){return R[n]||[]}function G(n,a){if(typeof a!="string"||!a.trim())return!1;const t=a.trim();return n==="llama"?d(n).some(i=>i.id===t)||T(t):d(n).some(i=>i.id===t)||A.test(t)}function z(n){return`models--${String(n).replace(/\//g,"--")}`}const Q=/(ForCausalLM|ForConditionalGeneration|LMHeadModel)$/,_=new Set(["","mlx"]);function v(n,a=[],{formats:t=null}={}){return(Array.isArray(a)?a:[]).filter(i=>i?.id&&i.architectures?.some(s=>Q.test(s))).filter(i=>Array.isArray(t)?i.mlx?t.includes("mlx"):t.includes("safetensors"):n==="mlx"||n==="vllm-metal"?i.mlx||_.has(i.quantMethod):n==="vllm"?!i.mlx:!1)}function C(n,{active:a=null,engineRamMB:t=0,engine:i=null,platform:s=process.platform,installed:h=()=>!1,onDisk:M=[],formats:B=null}={}){const m=e=>`${Math.round(e/1024*10)/10} GB`,g=e=>i==="podman"&&s!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((e.ramMB+2048)/2048)*2048)} && podman machine start`:i==="docker"&&s!=="linux"?"raise the memory in Docker Desktop › Settings › Resources":null,o=d(n).map(e=>{const l=t>0&&e.ramMB>t,r=!l&&Number(e.minRamMB)>0&&t>0&&t<e.minRamMB;return{...e,installed:h(e.id),recommended:!!e.recommended&&!l&&!r,...l?{unavailable:`needs about ${m(e.ramMB)} of memory while loaded — the container engine has ${m(t)}${g(e)?`; raise it: ${g(e)}`:""}`}:{},...r?{ramNote:`needs about ${m(e.ramMB)} while loaded — the engine has ${m(t)}; expect it to slow things down`}:{}}}),c=e=>`${Math.round(e/2**30*10)/10} GB`,b=v(n,M,{formats:B}).filter(e=>e.id!==a||!o.some(l=>l.id===e.id));for(const e of b){const l=o.find(x=>x.id===e.id);if(l){l.installed=!0,l.onDisk=!0;continue}const r=e.bytes?Math.ceil(e.bytes*1.2/2**20):0,f=t>0&&r>t;o.unshift({id:e.id,label:e.id.split("/").pop(),lang:"—",tier:"on-disk",custom:!0,installed:!0,onDisk:!0,...r?{ramMB:r}:{},note:`Already on this machine${e.bytes?` (${c(e.bytes)})`:""} — no download.${e.mlx||n==="vllm"?"":" Original weights: MLX converts them as it loads; an MLX 4-bit copy would use less memory."}`,...f?{unavailable:`needs about ${c(r*2**20)} of memory while loaded — the engine has ${c(t*2**20)}`}:{}})}return a&&!o.some(e=>e.id===a)&&o.push({id:a,label:/\.gguf$/i.test(a)?a.split(/[\\/]/).pop():a,lang:"—",tier:"custom",custom:!0,installed:h(a),note:/\.gguf$/i.test(a)?"A GGUF on this machine.":"Custom model (from Hugging Face)."}),o}export{k as DECIDE_MODEL_CATALOG,A as HF_ID,L as LLAMA_MODEL_CATALOG,w as RERANK_MODEL_CATALOG,u as VLLM_METAL_MODEL_CATALOG,p as VLLM_MODEL_CATALOG,z as cacheDirName,d as catalogFor,T as isLlamaModelId,G as isValidModelId,C as modelsFor,v as reusableFor,E as vllmTaskOf};
|
package/src/runtime.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{promisify as Et}from"node:util";import{execFile as Ot}from"node:child_process";import{existsSync as Qe,mkdirSync as pe,writeFileSync as be,accessSync as Ln,openSync as Bt,closeSync as Nt,constants as Tn}from"node:fs";import{randomBytes as Lt,createHash as Tt}from"node:crypto";import ie from"node:os";import $ from"node:path";import{modelsFor as Cn,isValidModelId as Rn,catalogFor as $e,vllmTaskOf as he}from"./runtime-models.js";import{pickInferenceEngine as Gn,pickLlamaEngine as Ct,pickMlxEngine as Rt,pickAppleEngine as Gt,recommendEngine as Ut,detectAccelerator as Ht,hostShape as It}from"./inference-engines.js";import{tuningArgs as ve,tuningRows as Un,patchTunings as Hn,profilesFor as In,resolveTunings as Fn,splitTunings as ge,ENGINE_DOCS as Ft}from"./engine-tunings.js";import{IMAGE_RECIPES as jt}from"./images.js";import{pullRepo as Dt,pullGguf as Xt,repoInstalled as zt,ggufInstalled as jn,ggufRecipe as Ye,planGgufRecipe as Vt}from"./model-pull.js";import{llamaKnows as Dn,llamaFlags as Wt}from"./llama-arch.js";import{installBuild as Jt,installedBuild as qt,UNSLOTH_LLAMA as v,LLAMA_BUILDS as Xn,DEFAULT_LLAMA_BUILD as Kt}from"./llama-builds.js";import{liveFit as Qt,kvCacheMB as Yt,cachedConfigPath as Zt,needMB as zn}from"./host-memory.js";import{APPLE_HELPER as Ze,APPLE_MODEL_ID as er,APPLE_MIN_DARWIN as nr,appleHelperDirs as tr,appleInstallDoor as rr,darwinMajor as Vn}from"./apple-model.js";import{transferRate as ir}from"./transfer-rate.js";import{capabilityList as Se,primaryProvider as ar,withProvider as Wn,withoutProvider as Jn}from"./capability-config.js";import{isEmbeddedModel as or}from"./embedded-models.js";import{spawn as sr}from"node:child_process";import{readFileSync as qn,unlinkSync as Kn,realpathSync as lr,readdirSync as Qn}from"node:fs";const ur=Et(Ot),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=>Gn({...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`,G=he(f.model);Yn(r),G==="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"})):G==="embed"?_e(r,"embed",{url:p,adapter:"openai",model:f.model,service:"vllm"}):G==="transcription"&&_e(r,"stt",{provider:"container",url:p,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:r=>Yn(r)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:r=>Gn(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=>Ct(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=>Rt(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=>Gt(r),only:{platform:"darwin",arch:"arm64",minDarwin:nr,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:[er],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 Yn(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,Wn(r.capabilities?.[l],l,f,{match:p=>p.service===f.service}))}function xe(r,l,f){r.capabilities?.[l]&&en(r,l,Jn(r.capabilities[l],l,f))}const A=r=>F.find(l=>l.id===r)||null,cr=({answers:r,configured:l,configure:f,unconfigure:p,volumes:G,args:h,env:z,caps:Pe,command:Ee,engineOf:tn,alias:Oe,...B})=>B,dr=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),mr=Object.freeze(["brave","qwant"]);function fr(r=[]){const l=r.length?r:dr,f=mr.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
|
|
3
|
-
`).filter(
|
|
4
|
-
`)[0]);return e.ok&&Number.isInteger(t)&&t>1?t:0}function
|
|
5
|
-
`).filter(Boolean).map(i=>{try{return
|
|
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 I(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:rt}:a.engineOf(o):null,k=a.kind==="native"?(o.ramGB||0)*1024:t;i[a.id]={...cr(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:R.has(a.id),idleMinutes:Bn()/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:In(a.id,j(a,d),D(a,d,m,o)),docs:Ft[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:ut(a,o)}:{},...a.model?{model:d,default:a.model,models:Cn(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:Un(a.id,j(a,d),D(a,d,m,o))}:{}}}return i}async function ft(){const n=await E(),e=await I(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:Ut(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=Tt("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 pt(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};R.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 I(o),a=t.engineOf?t.engineOf(s):null;if(t.kind==="native"&&!Y(t)&&!await H(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 mt(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 dt(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 ht(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 pt(e):null,o=n.engineOf?n.engineOf(await I(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,fr(String(r.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),d=Lt(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 gt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(R.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 kt(n,e){const t=A(n);if(!t||t.id!=="llama")return{ok:!1,error:"a build is chosen for llama.cpp"};if(!Xn.includes(e))return{ok:!1,error:`one of ${Xn.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 wt(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(!Rn(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?zn({ramMB:a/2**20})<=o*.75:null;try{const a=await Vt(i,{fetchImpl:B,knows:(Oe||Dn)(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 yt(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(!Rn(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=Cn(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 I(a);if(d=Hn(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 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 E(),o=await I(i.preferred),s=t.engineOf?t.engineOf(o):null,a=In(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 H(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const o=e.engineOf(await I(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 H(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 $t(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 H(e.runner,e.runnerCheck))return We(n);const i=e.engineOf(await I(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 I(o),c=t.engineOf?t.engineOf(a):null,u=Hn(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:Un(t.id,u,D(t,s,c,a)),restarted:d.restarted}:d}async function vt(){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",En[s.id]=i[s.id]==="up"?"":a==="running"?"starting":R.has(s.id)?"asleep":"stopped";const c=(s.provides||[]).some(u=>["embedded","none"].includes(ar(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}const En={};function St(n){return En[n]||""}function On(n){const e=A(n);if(e?.window)return e.window;if(!e||!W(e))return null;const t=Number(Fn(e.id,j(e,w(e)),D(e,w(e),null,{})).maxModelLen);return Number.isFinite(t)&&t>0?t:null}function Mt(n){const e=A(n);if(e?.card)return e.card;if(!e||!W(e))return null;const t=w(e),i=Fn(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 At=10,Bn=()=>{const n=Number(r.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:At)*6e4},_t=se(),Je={},R=new Set,fe={};function qe(n){Je[n]=se()}async function xt(n,{force:e=!1}={}){const t=A(n);if(!t||!t.helper)return{ok:!0};if(qe(t.id),!R.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};R.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&&(R.delete(t.id),S(`[runtime] ${t.label}: woken for a request`)),s})().finally(()=>{delete fe[t.id]})),fe[t.id]}async function Nn(){const n=Bn();if(!n)return[];const e=F.filter(a=>a.helper&&a.configured(r)&&!R.has(a.id)&&!fe[a.id]&&!(b[a.id]&&!b[a.id].done)&&se()-(Je[a.id]??_t)>=n);if(!e.length)return[];const t=await E(),i=t.preferred;if(!i||!t[i].running){for(const a of e)R.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`)}R.add(a.id),s.push(a.id)}return s}return an&&an(()=>{Nn().catch(n=>S(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:qe,wake:xt,sweepIdle:Nn,health:vt,contextWindow:On,whyDown:St,modelCard:Mt,async status(){const[n,e,t,i,o]=await Promise.all([l().catch(()=>null),E(),Mn(),vn(),ft()]);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:gt,ensureDefaults:ot,retireServices:fn,removeService:it,upcastTunings:pn,revive:st,plan:hn,recipe:wt,setBuild:kt,isAsleep:n=>R.has(n),setModel:yt,setTunings:Pn,setProfile:bt,pullModel:xn,installRunner:We,updateRunner:$t,cancelJob:ht,services:Mn,catalogFor:$e}}export{dr as SEARXNG_DEFAULT_ENGINES,F as SERVICES,Zn as containerRow,Rr as createRuntime,nn as installDoor,fr as searxngSettings};
|
|
1
|
+
import{promisify as jt}from"node:util";import{execFile as zt}from"node:child_process";import{existsSync as en,mkdirSync as he,writeFileSync as Ae,accessSync as Fn,openSync as Vt,closeSync as Xt,constants as Dn}from"node:fs";import{randomBytes as Wt,createHash as Jt}from"node:crypto";import ie from"node:os";import b from"node:path";import{modelsFor as jn,isValidModelId as zn,catalogFor as _e,vllmTaskOf as ge}from"./runtime-models.js";import{pickInferenceEngine as Vn,pickLlamaEngine as qt,pickMlxEngine as Kt,pickAppleEngine as Qt,recommendEngine as Yt,detectAccelerator as Zt,hostShape as er}from"./inference-engines.js";import{tuningArgs as Pe,tuningRows as Xn,patchTunings as Wn,profilesFor as Jn,resolveTunings as qn,splitTunings as ke,ENGINE_DOCS as nr}from"./engine-tunings.js";import{IMAGE_RECIPES as tr}from"./images.js";import{pullRepo as rr,pullGguf as ir,repoInstalled as ar,ggufInstalled as Kn,ggufRecipe as nn,planGgufRecipe as or,cachedRepos as sr}from"./model-pull.js";import{loadEngineManifests as Qn,serviceFromManifest as Yn,pluginTunings as Zn,patchPluginTunings as et}from"./engine-plugins.js";import{llamaKnows as nt,llamaFlags as lr}from"./llama-arch.js";import{installBuild as ur,installedBuild as dr,UNSLOTH_LLAMA as v,LLAMA_BUILDS as tt,DEFAULT_LLAMA_BUILD as cr}from"./llama-builds.js";import{liveFit as mr,kvCacheMB as fr,cachedConfigPath as pr,needMB as rt}from"./host-memory.js";import{APPLE_HELPER as tn,APPLE_MODEL_ID as hr,APPLE_MIN_DARWIN as gr,appleHelperDirs as kr,appleInstallDoor as wr,darwinMajor as it}from"./apple-model.js";import{transferRate as br}from"./transfer-rate.js";import{capabilityList as Ee,primaryProvider as yr,withProvider as at,withoutProvider as ot}from"./capability-config.js";import{isEmbeddedModel as $r}from"./embedded-models.js";import{spawn as vr}from"node:child_process";import{readFileSync as st,unlinkSync as lt,realpathSync as Sr,readdirSync as ut}from"node:fs";const Mr=jt(zt),xe=["podman","docker"],ae="hf-cache",we=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=>[`${b.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(Oe(r,"rerank","reranker")?.url||""),configure:(r,l,f)=>Be(r,"rerank",{url:l,adapter:f.adapter,model:f.model,service:f.id}),unconfigure:(r,l)=>Le(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=>[`${b.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(Oe(r,"decide","opendecision")?.url||""),configure:(r,l,f)=>Be(r,"decide",{url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}),unconfigure:(r,l)=>Le(r,"decide",f=>f.url===l)},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:r=>Vn({...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=>[`${b.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",...ge(r.model)==="embed"?["--task","embed"]:[],...Pe("vllm",r.tunings,{task:ge(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(Oe(r,"embed","vllm")?.url?.replace(/\/v1$/,"")||Oe(r,"stt","vllm")?.url?.replace(/\/v1$/,"")||(r.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{const p=`${l}/v1`,H=ge(f.model);ct(r),H==="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"})):H==="embed"?Be(r,"embed",{url:p,adapter:"openai",model:f.model,service:"vllm"}):H==="transcription"&&Be(r,"stt",{provider:"container",url:p,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:r=>ct(r)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:r=>Vn(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),...Pe("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=>qt(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",...Pe("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=>Kt(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),...Pe("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:tn,engineOf:r=>Qt(r),only:{platform:"darwin",arch:"arm64",minDarwin:gr,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=>[tn,["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:[hr],service:"apple"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),B=[...we],rn=Object.freeze(we.map(r=>r.id));function dt(r=[]){B.splice(0,B.length,...we,...r.filter(l=>l&&!rn.includes(l.id)))}const oe=r=>r.only?.label||`${r.only?.platform||"this platform"} ${r.only?.arch||""}`.trim();function ct(r){Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),Le(r,"embed",l=>l.service==="vllm"),Le(r,"stt",l=>l.service==="vllm")}function Oe(r,l,f){return Ee(r.capabilities?.[l],l).providers.find(p=>p.service===f)||null}function an(r,l,f){r.capabilities=r.capabilities||{},f?r.capabilities[l]=f:delete r.capabilities[l]}function Be(r,l,f){an(r,l,at(r.capabilities?.[l],l,f,{match:p=>p.service===f.service}))}function Le(r,l,f){r.capabilities?.[l]&&an(r,l,ot(r.capabilities[l],l,f))}const _=r=>B.find(l=>l.id===r)||null,Ar=({answers:r,configured:l,configure:f,unconfigure:p,volumes:H,args:h,env:V,caps:Ne,command:Te,engineOf:sn,alias:Ce,...N})=>N,_r=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),Pr=Object.freeze(["brave","qwant"]);function Er(r=[]){const l=r.length?r:_r,f=Pr.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 on(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 mt(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),H=String(r.State||"").toLowerCase()||(/^up/i.test(String(r.Status||""))?"running":"exited");return{name:f,image:String(r.Image||""),state:H,status:String(r.Status||""),ports:p,ours:f.startsWith("chatpanel-"),engine:l}}const xr=15e3;function Yr({cfg:r,bridgeHealth:l,workers:f=()=>[],persist:p=()=>{},exec:H=(G,L,ee={})=>Mr(G,L,{timeout:6e4,killSignal:"SIGKILL",...ee}),platform:h=process.platform,arch:V=process.arch,osRelease:Ne=ie.release(),spawn:Te=vr,lookup:sn=null,archKnower:Ce=null,fetchImpl:N=globalThis.fetch,stateDir:O=b.join(ie.homedir(),".chatpanel","runtime"),log:S=()=>{},sleep:Re=G=>new Promise(L=>setTimeout(L,G)),totalMem:ln=()=>ie.totalmem(),memoryProbe:ft=G=>h==="darwin"&&r?.runtime?.heatwatch!==!1?mr(G,{fetchImpl:N}):Promise.resolve(null),now:se=()=>Date.now(),autoEnv:pt=process.env.CHATPANEL_RUNTIME_AUTO,every:un=(G,L)=>{const ee=setInterval(G,L);return ee.unref?.(),ee},plugins:dn=null}={}){const G=dn?{manifests:dn,refused:[]}:Qn({home:b.dirname(b.dirname(O)),takenPorts:we.map(n=>n.port).filter(Boolean),builtins:[...rn]});dt(G.manifests.map(Yn).filter(Boolean));for(const n of G.refused)S(`[runtime] engine manifest ${n.file} refused: ${n.error}`);const L=ie.homedir(),ee=h==="win32"?[b.join(L,"AppData","Local","Microsoft","WinGet","Links"),b.join(L,".local","bin"),b.join(L,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",b.join(L,".local","bin"),b.join(L,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin",...h==="darwin"?kr({home:L}):[]],le=(n=process.env)=>{const e=h==="win32"?";":":",t=String(n.PATH||n.Path||""),i=ee.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 H(n,e,{...t,env:le(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 Ge=null;const cn=async()=>(Ge===null&&(Ge=await Zt({exec:H,platform:h,arch:V})),Ge),q={},ht=n=>{const e=h==="win32"?";":":",t=h==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of le().PATH.split(e).filter(Boolean))for(const o of t)try{return Fn(b.join(i,n+o),Dn.X_OK),!0}catch{}return!1},Ue=n=>{const e=h==="win32"?";":":",t=h==="win32"?[".exe",""]:[""];for(const i of le().PATH.split(e).filter(Boolean))for(const o of t){const s=b.join(i,n+o);try{return Fn(s,Dn.X_OK),s}catch{}}return null},K={},F=async(n,e=["--version"])=>{if(q[n])return!0;if(K[n]!==void 0&&se()-K[n]<xr)return!1;const t=(sn||ht)(n)||(await y(n,e,{timeout:8e3})).ok;return t?(q[n]=!0,delete K[n]):K[n]=se(),t},ne=n=>{const e=Ue(n);let t;try{t=Sr(e)}catch{return null}const i=/[\\/]Cellar[\\/][^\\/]+[\\/]([^\\/]+)[\\/]/.exec(t);if(i)return i[1].replace(/_\d+$/,"");try{const o=b.join(b.dirname(t),"..","lib");for(const s of ut(o)){const a=b.join(o,s,"site-packages"),d=ut(a).find(u=>/\.dist-info$/.test(u)&&u.toLowerCase().startsWith(`${b.basename(b.dirname(b.dirname(t))).replace(/-/g,"_").toLowerCase()}-`));if(d){const u=d.replace(/\.dist-info$/,"");return u.slice(u.lastIndexOf("-")+1)}}}catch{}return null},te=()=>r.runtime?.services?.llama?.build==="system"?"system":cr,Q=n=>n?.id==="llama"&&te()==="unsloth",X=()=>dr(O,h),ue=()=>te()==="system"?"llama-server":X()?.bin||null,Ie=()=>te()==="system"?Ue("llama-server"):X()?.bin||null,mn=()=>te()==="system"?ne("llama-server"):X()?.tag||null,gt=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 He(n,{tag:e=v.tag}={}){n.kind=n.kind==="update"?"update":"install",n.detail=v.label,E(n,`fetching ${v.label} (${e==="latest"?"the newest release":e}) from github.com/${v.repo}`);try{const t=await ur({stateDir:O,platform:h,arch:V,accelerator:await cn(),tag:e,fetchImpl:N,run:y,onProgress:$n(n)});return E(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 fn=(n,e)=>e?.missing||`\`${n.runner}\` is not on PATH — install it first (${e?.command||""}), or click Install`;let Fe=null;const be=async()=>(Fe||(Fe=await er({exec:H,platform:h,totalmem:ln,cpus:()=>ie.cpus()})),Fe),D=async n=>({platform:h,arch:V,accelerator:await cn(),engine:n,vllmOnPath:await F("vllm"),llamaOnPath:await F("llama-server"),mlxOnPath:h==="darwin"&&V==="arm64"?await F("mlx_lm.server",["--help"]):!1,osMajor:h==="darwin"?it(Ne):0,appleOnPath:h==="darwin"&&V==="arm64"?await F(tn):!1,appleInstall:h==="darwin"?wr({home:L}):null,...await be()}),U=n=>!n.only||(!n.only.platform||n.only.platform===h)&&(!n.only.arch||n.only.arch===V)&&(!n.only.minDarwin||it(Ne)>=n.only.minDarwin),de=n=>b.join(O,`${n.id}.pid`),re=n=>{try{const e=Number(st(de(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},ce=n=>U(n)?re(n)?"running":"stopped":"unsupported",Y={};async function De(n){const e=me(n);if(!U(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};if(re(e))return e.auto&&!e.configured(r)&&(e.configure(r,P(e),e),p()),{ok:!0,already:!0,url:P(e)};if(e.auto&&await e.answers(P(e),N)){const A=await $t(e.port);if(A)return he(O,{recursive:!0,mode:448}),Ae(de(e),String(A),{mode:384}),Y[e.id]={layer:"none",reason:"a model engine runs on the hardware, behind the gateway"},e.configure(r,P(e),e),p(),S(`[runtime] ${e.label} was already answering on ${P(e)} (pid ${A}) — adopted`),{ok:!0,adopted:!0,url:P(e),answering:!0,provides:e.provides}}const t=await D(null),i=e.engineOf(t);if(Q(e)?!ue():!await F(e.runner,e.runnerCheck))return Q(e)?{ok:!1,error:`${v.label} is not downloaded yet — Start fetches it`}:{ok:!1,error:fn(e,i.install),install:i.install};if(e.id==="llama"&&/\.gguf$/i.test(e.model)&&!en(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[o,s]=e.command(e,z(e,e.model,i,t)),a=e.id==="llama"?ue():o,d=b.join(O,ae);he(d,{recursive:!0,mode:448});const u={bin:a,argv:s,opts:{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,HF_HOME:d,LLAMA_CACHE:d,...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"}};Y[e.id]=u.record;const c=b.join(O,`${e.id}.log`);let m,k=null;try{try{k=Vt(c,"w",384)}catch{k=null}m=Te(u.bin,u.argv,{...u.opts,env:le(u.opts?.env),detached:!0,stdio:["ignore",k??"ignore",k??"ignore"]}),m.unref?.()}catch(A){return{ok:!1,error:`${u.bin}: ${A.message}`,install:i.install}}finally{if(k!==null)try{Xt(k)}catch{}}if(!m?.pid)return{ok:!1,error:`${u.bin} did not start`,install:i.install};Ae(de(e),String(m.pid),{mode:384});const g=P(e);let M=!1;for(let A=0;A<120&&!M&&re(e);A++)M=await e.answers(g,N),M||await Re(1e3);if(!re(e)){try{lt(de(e))}catch{}let A="";try{A=st(c,"utf8").trim().split(`
|
|
3
|
+
`).filter(R=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(R)).slice(-3).map(R=>R.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{A=""}return{ok:!1,error:`${e.label} exited on start${A?` — ${A}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:c}}return e.configure(r,g,e),p(),S(`[runtime] ${e.label} started (pid ${m.pid}) on ${g}, sandbox ${Y[e.id].layer}${M?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:g,answering:M,provides:e.provides,model:w(e),sandbox:Y[e.id]}}const je=n=>r.runtime?.services?.[n.id]?.off===!0,pn=(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},hn=()=>r.runtime?.auto!==!1&&String(pt||"").toLowerCase()!=="off",T={};async function gn(n){if(!n?.auto)return{ok:!1,skipped:"not a service that starts by itself"};if(!hn())return{ok:!1,skipped:"automatic start is switched off"};if(!U(n))return{ok:!1,skipped:`runs on ${oe(n)} only`};if(je(n))return{ok:!1,skipped:"stopped by the person"};if(!await F(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 T[n.id]=i||"not available on this Mac right now",{ok:!1,skipped:T[n.id]}}}const e=await De(n);return e.ok?(delete T[n.id],{ok:!0,...e.already?{already:!0}:e.adopted?{adopted:!0}:{started:!0}}):(T[n.id]=e.error,{ok:!1,skipped:e.error})}const kn=(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()},ze=n=>{const e=r.runtime?.services?.[n.id];e?.pulling&&(delete e.pulling,p())};function wn(){let n=!1;for(const e of B.filter(t=>t.retired))for(const t of e.provides||[]){const i=r.capabilities?.[t];if(!i||!Ee(i,t).providers.some(d=>d.service===e.id))continue;const o=Ee(i,t).providers.find(d=>d.service===e.id),s={provider:"embedded",...$r(t,o?.model)?{model:o.model}:{}},a=Ee(i,t).providers.some(d=>d.provider==="embedded"&&(d.model||null)===(s.model||null));an(r,t,a?ot(i,t,d=>d.service===e.id):at(i,t,s,{match:d=>d.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 kt(n){const e=_(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 x()).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,P(e)),p(),S(`[runtime] ${e.label} removed (container${o.ok?" and image":""})`),{ok:!0,removed:{container:!0,image:!!o.ok}}}async function wt(){const n=[];if(!hn())return n;for(const e of B.filter(t=>t.pull)){const t=r.runtime?.services?.[e.id]?.pulling;if(t){if(t.model!==w(e)||J(e,w(e))){ze(e),J(e,w(e))&&t.start&&n.push({id:e.id,...await Z(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?Z(e.id):Nn(e.id)).catch(i=>({ok:!1,error:i.message}))})}}return n}async function bt(){try{wn()}catch(e){S(`[runtime] retiring: ${e.message}`)}try{bn()}catch(e){S(`[runtime] settings per model: ${e.message}`)}const n=[...await wt().catch(()=>[])];for(const e of B.filter(t=>t.auto))n.push({id:e.id,label:e.label,...await gn(e).catch(t=>({ok:!1,skipped:t.message}))});return n}async function yt(n){const e=_(n);return e?.auto?gn(e):{ok:!1,skipped:"not a service that starts by itself"}}async function $t(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 ye(n){const e=re(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{lt(de(n))}catch{}return n.unconfigure(r,P(n)),p(),{ok:!0}}const me=n=>n.model?{...n,model:w(n),installed:J(n,w(n)),tunings:C(n,w(n)),...n.id==="llama"?{file:Mt(w(n))}:{}}:n,W=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx"||!!n.manifest,C=(n,e)=>{const t=r.runtime?.services?.[n.id]||{},{engine:i,model:o}=ke(t.tunings),s=e&&t.byModel?.[e]?t.byModel[e]:e&&e===w(n)?o:{};return{...i,...s}},$e=(n,e,t)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{};const i=r.runtime.services[n.id]||{},{engine:o,model:s}=ke(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 bn(){let n=!1;for(const e of B.filter(W)){const t=r.runtime?.services?.[e.id];if(!t?.tunings)continue;const{model:i}=ke(t.tunings);if(!Object.keys(i).length)continue;const o=w(e);o?$e(e,o,{...i,...(t.byModel||{})[o]||{},...ke(t.tunings).engine}):t.tunings=ke(t.tunings).engine,n=!0}n&&p()}function vt(n,e){const t=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},o=_e(n.id).filter(d=>!d.minRamMB||t>0&&t>=d.minRamMB);if(!o.length||!t)return null;const s=o.slice().sort((d,u)=>(i[u.tier]??-1)-(i[d.tier]??-1)||d.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 yn(n,{model:e,ctx:t,needMB:i}={}){const o=_(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(Ze=>Ze.id===s)||null,d=Number(i)>0?Number(i):a?.ramMB||null;if(!d)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):Rn(n),c=/\.gguf$/i.test(s)||o.id==="llama"?null:pr(j(),s),m=u&&c?fr(c,u):null,k=rt({ramMB:d,kvMB:m||0}),g=o.kind==="native"?await ft(k):null,M=((await be()).ramGB||0)*1024,A=g?g.fits:M>0&&k<=M,R=Ze=>`${Math.round(Ze/102.4)/10} GB`,Dt=g?g.fits?`${s} fits: needs about ${R(k)}, ${R(g.availableMB)} is free now${g.fitsGPULimit===!1?` — but it is above the GPU wired limit (${R(g.gpuWiredLimitMB)}); raise iogpu.wired_limit_mb`:""}.`:`${s} needs about ${R(k)} and ${R(g.availableMB)} is free now — ${R(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 ${R(k)} of the machine's ${R(M)} — ${A?"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:d,kvMB:m,context:u||null,contextCounted:m!==null||!u,source:g?"heatwatch":"total-memory",fits:A,live:g,advice:Dt}}const z=(n,e,t,i={})=>({task:n.id==="vllm"?ge(e):"chat",model:e,backend:t?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0,...n.id==="llama"?{recipe:nn(j(),e),flags:lr(Ie())}:{}}),j=()=>b.join(O,ae);let ve={at:0,list:[]};const St=()=>{if(Date.now()-ve.at>3e4)try{ve={at:Date.now(),list:sr(j())}}catch{ve={at:Date.now(),list:[]}}return ve.list},J=(n,e)=>/\.gguf$/i.test(e)?en(e):n.id==="llama"?!!Kn(j(),e):ar(j(),e),Mt=n=>/\.gguf$/i.test(n)?n:Kn(j(),n),$={},Or=n=>$[n.id]||null;function $n(n){const e=br();return t=>{if(n.cancelled)throw new Error("cancelled");t.retry&&E(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 fe(n,e,t={}){return $[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...t},$[n.id]}function E(n,e){const t=String(e||"").trim();if(!t)return;n.lines.push(t.slice(0,200)),n.lines.length>8&&n.lines.shift();const i=/^STEP (\d+)\/(\d+)/.exec(t);i&&(n.step={n:Number(i[1]),of:Number(i[2])})}const Se=(n,e,t,{timeout:i=36e5*4}={})=>new Promise(o=>{if(n.cancelled)return o({ok:!1,code:-1,error:"cancelled"});let s;try{s=Te(e,t,{stdio:["ignore","pipe","pipe"],env:le()})}catch(c){return o({ok:!1,code:-1,error:c.message})}n.child=s;let a="";const d=c=>{a+=String(c);const m=a.split(/\r?\n|\r/);a=m.pop();for(const k of m)E(n,k)};s.stdout?.on("data",d),s.stderr?.on("data",d);const u=setTimeout(()=>{try{s.kill("SIGTERM")}catch{}},i);u.unref?.(),s.on("error",c=>{clearTimeout(u),n.child=null,o({ok:!1,code:-1,error:c.message})}),s.on("exit",c=>{clearTimeout(u),n.child=null,a&&E(n,a),o({ok:c===0&&!n.cancelled,code:c,...n.cancelled?{error:"cancelled"}:{}})})}),vn={install:Promise.resolve(),build:Promise.resolve()},Ve={install:0,build:0},Sn=(n,e,t)=>{Ve[n]>0&&(e.waiting=!0,E(e,`waiting for the other ${n} to finish first — one at a time`)),Ve[n]++;const i=vn[n];let o;const s=new Promise(a=>{o=a});return vn[n]=i.then(()=>s),i.then(async()=>{e.waiting&&(E(e,"the other one finished — going"),e.waiting=!1);try{return await t()}finally{Ve[n]--,o()}})},Mn=async(n,e)=>(await y(n,["image","exists",e],{timeout:2e4})).ok;async function At(n,e,t,i){const o=e?.image||t.image;if(await Mn(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,E(i,`pulling ${m}`),(await Se(i,n,["pull",m])).ok)return m!==o&&await y(n,["tag",m,o],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const d=e?.recipe?tr[e.recipe]:null;if(!d)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const u=b.join(O,"images",e.recipe);return he(u,{recursive:!0,mode:448}),Ae(b.join(u,"Dockerfile"),d.dockerfile,{mode:384}),i.kind="build-image",i.detail=o,i.minutes=d.minutes,E(i,`no registry has ${o} for this machine — building it here (about ${d.minutes} minutes)`),S(`[runtime] building ${o} from the ${e.recipe} recipe in ${u}`),(await Sn("build",i,()=>Se(i,n,["build","-t",o,"-f",b.join(u,"Dockerfile"),u]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function An(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=$n(e);try{if(n.id==="llama"){const o=C(n,t);await ir(t,{root:j(),fetchImpl:N,onProgress:i,knows:(Ce||nt)(Ie()),engineVersion:mn(),vision:o.vision!=="off",draft:o.draftModel!=="off"})}else await rr(t,{root:j(),fetchImpl:N,onProgress:i});return{ok:!0}}catch(o){return{ok:!1,error:`pull ${t}: ${o.message}`}}}async function _t(n,e,t){const i=[];return Q(n)&&!ue()&&i.push("runner"),n.kind!=="native"&&e&&!await Mn(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(ln()/1048576)}async function x(){const n={};for(const t of xe){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 d=await y("podman",["machine","list","--format","json"],{timeout:8e3});try{const c=JSON.parse(d.out||"[]")[0]||null;a=c?{name:c.Name,running:!!c.Running}:null,s=!!c?.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=xe.find(t=>n[t]?.installed&&n[t].running)||xe.find(t=>n[t]?.installed)||null;return{...n,preferred:e,...e?{}:{install:on(h)}}}async function Xe(n="podman"){if(!xe.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await x())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:on(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 Pn(){const n=await x(),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=>mt(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 mt(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function En(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 We(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 P=n=>`http://127.0.0.1:${n.port}`;async function xn(){const n=await x(),e=n.preferred,t=await _n(e,n),i={},o=await D(e),s=e&&n[e].running?await We(e,B.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of B){const d=P(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 c=a.model?w(a):null,m=a.engineOf?Q(a)?{...a.engineOf({...o,llamaOnPath:!0}),install:gt}:a.engineOf(o):null,k=a.kind==="native"?(o.ramGB||0)*1024:t;i[a.id]={...Ar(a),engine:a.kind==="native"?"host":e,state:u,url:d,configured:a.configured(r),answering:u==="running"?await a.answers(d,N):!1,...a.helper?{asleep:I.has(a.id),idleMinutes:Gn()/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"&&!U(a)?{why:`${a.label} runs on ${oe(a)} only`}:{},...a.id==="llama"&&U(a)?{...c&&nn(j(),c).recommended?{recommended:nn(j(),c).recommended}:{},build:te(),builds:[{id:"unsloth",label:v.label,why:v.why,installed:!!X(),version:X()?.tag||null,default:!0},{id:"system",label:"The system’s llama.cpp",why:"Homebrew’s, or one you built — `llama-server` on PATH",installed:!!Ue("llama-server"),version:ne("llama-server")}],...te()==="unsloth"?X()?{runnerVersion:X().tag,updatable:!0}:{}:q[a.runner]?{runnerVersion:ne(a.runner),updatable:!!m?.install?.update?.steps?.length}:{}}:a.kind==="native"&&a.runner&&U(a)&&q[a.runner]?{runnerVersion:ne(a.runner),updatable:!!m?.install?.update?.steps?.length}:{},...a.auto&&u!=="running"&&U(a)?{auto:!0,...je(a)?{why:"Stopped here — Start turns it back on"}:T[a.id]?{why:T[a.id]}:{}}:a.auto?{auto:!0}:{},...!a.auto&&a.kind==="native"&&u!=="running"&&U(a)&&T[a.id]?{why:T[a.id]}:{},...a.kind==="native"&&Y[a.id]?{sandbox:Y[a.id]}:{},...$[a.id]?{job:{kind:$[a.id].kind,since:$[a.id].since,detail:$[a.id].detail||null,step:$[a.id].step||null,minutes:$[a.id].minutes||null,progress:$[a.id].progress,lines:$[a.id].lines.slice(-4),done:$[a.id].done,error:$[a.id].error,waiting:!!$[a.id].waiting,cancelled:!!$[a.id].cancelled}}:{},...a.manifest?{...Zn(a,C(a,c),{ramGB:o.ramGB||0}),plugin:a.plugin}:W(a)?{profiles:Jn(a.id,C(a,c),z(a,c,m,o)),docs:nr[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:vt(a,o)}:{},...a.model?{model:c,default:a.model,models:jn(a.id,{active:c,engineRamMB:k,engine:a.kind==="native"?"host":e,platform:h,installed:g=>J(a,g),onDisk:St(),...a.manifest?{formats:a.manifest.formats}:{}}),machine:{engineRamMB:k}}:{},...W(a)&&!a.manifest?{tunings:Xn(a.id,C(a,c),z(a,c,m,o))}:{}}}return i}async function Pt(){const n=await x(),e=await D(n.preferred);return{platform:h,arch:V,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:Yt(e)}}function On(n,{settingsFile:e=null,secret:t=null,pick:i=null,cpus:o=null}={}){const s=me(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(O):[])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 d=Jt("sha1").update(JSON.stringify(a.filter(u=>!String(u).startsWith("SEARXNG_SECRET=")))).digest("hex").slice(0,12);return a.splice(2,0,"--label",`chatpanel.run=${d}`),{args:a,hash:d}}const Je={};async function Et(n){if(Je[n]==null){const e=await y(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),t=Number.parseInt(e.out,10);Je[n]=Number.isFinite(t)&&t>0?t:ie.cpus()?.length||2}return Math.max(1,Math.floor(Je[n]/2))}async function Z(n,{force:e=!1}={}){const t=_(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),Ye(t.id),t.auto&&je(t)&&pn(t,!1);const i=$[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 c=await x();if(o=c.preferred,!o)return{ok:!1,error:"no container engine — install Podman first",install:on(h)};if(!c[o].running){const m=await Xe(o);if(!m.ok)return m}}else if(!U(t))return{ok:!1,error:`${t.label} runs on ${oe(t)} only`};const s=await D(o),a=t.engineOf?t.engineOf(s):null;if(t.kind==="native"&&!Q(t)&&!await F(t.runner,t.runnerCheck))return{ok:!1,error:fn(t,a?.install),install:a?.install};if(t.model&&/\.gguf$/i.test(w(t))&&!en(w(t)))return{ok:!1,error:`no such file: ${w(t)}`};if(t.kind==="native"&&t.model&&!e){const c=await yn(t.id);if(c.live&&!c.fits)return{ok:!1,error:c.advice,plan:c}}const d=await _t(t,o,a);if(!d.length){if(delete $[t.id],t.kind!=="native")return qe(t,o);const c=await De(t);return c.ok?delete T[t.id]:T[t.id]=c.error,c}const u=fe(t,d[0]==="runner"?"install":d[0]==="image"?"pull-image":"pull-model",{detail:d[0]==="runner"?v.label:d[0]==="image"?a?.image||t.image:w(t)});return d.includes("model")&&kn(t,w(t),!0),u.then=(async()=>{try{if(d.includes("runner")){const m=await He(u);if(!m.ok)throw new Error(m.error)}if(d.includes("image")){const m=await At(o,a,t,u);if(!m.ok)throw new Error(m.error)}if(d.includes("model")){const m=await An(t,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=t.label;const c=t.kind==="native"?await De(t):await qe(t,o);if(!c.ok)throw new Error(c.error);u.done=!0,u.result=c,S(`[runtime] ${t.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(c){u.done=!0,u.error=u.cancelled?"cancelled":c.message,S(`[runtime] ${t.label}: ${u.error}`)}finally{d.includes("model")&&ze(t)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function xt(n){const e=_(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const t=$[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 E(t,"cancelled"),S(`[runtime] ${e.label}: job cancelled (${t.kind})`),{ok:!0,cancelled:t.kind}}async function qe(n,e){let t=await En(e,n.container);const i=n.helper?await Et(e):null,o=n.engineOf?n.engineOf(await D(e)):null,s=n.id==="searxng"?b.join(O,"searxng-settings.yml"):null,a=On(n,{settingsFile:s,secret:n.id==="searxng"?"x":null,pick:o,cpus:i});if(t!=="absent"){const c=await y(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!c.ok||c.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 c=await y(e,["start",n.container],{timeout:6e4});if(!c.ok)return{ok:!1,error:`${e} start: ${c.err||c.out}`}}else{he(O,{recursive:!0,mode:448});let c=null;n.id==="searxng"&&(Ae(s,Er(String(r.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),c=Wt(32).toString("hex")),n.volumes&&he(b.join(O,ae),{recursive:!0,mode:448});const{args:m}=On(n,{settingsFile:s,secret:c,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 d=P(n);let u=!1;for(let c=0;c<30&&!u;c++)u=await n.answers(d,N),u||await Re(1e3);return n.configure(r,d,me(n)),p(),{ok:!0,url:d,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:w(n)}:{}}}async function Bn(n){const e=_(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(I.delete(e.id),delete Qe[e.id],e.auto&&pn(e,!0),e.kind==="native")return ye(e);const t=await x(),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,P(e)),p(),{ok:!0}}async function Ot(n,e){const t=_(n);if(!t||t.id!=="llama")return{ok:!1,error:"a build is chosen for llama.cpp"};if(!tt.includes(e))return{ok:!1,error:`one of ${tt.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 Me(t,null,await x());return o.ok?{ok:!0,build:e,restarted:o.restarted,...o.pending?{pending:o.pending}:{}}:o}async function Bt(n,e){const t=_(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(!zn(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 be()).ramGB||0)*1024,s=a=>o?rt({ramMB:a/2**20})<=o*.75:null;try{const a=await or(i,{fetchImpl:N,knows:(Ce||nt)(Ie()),engineVersion:mn()}),d=(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+d)})),ramGB:o/1024,fits:s(a.total+d)}}catch(a){return{ok:!1,error:a.message,...a.code?{code:a.code,arch:a.arch}:{}}}}async function Lt(n,e,{tunings:t=null}={}){const i=_(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(!zn(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 x(),a=s.preferred,d=i.kind==="native"?((await be()).ramGB||0)*1024:await _n(a,s),u=jn(n,{active:o,engineRamMB:d,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 c=null;if(t&&W(i)){const g=await D(a);if(i.manifest){const M=et(i,C(i,o),t);if(!M.ok)return M;c=M.next}else if(c=Wn(i.id,C(i,o),t,z(i,o,i.engineOf?i.engineOf(g):null,g)),c.error)return{ok:!1,error:c.error}}r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{},r.runtime.services[n]={...r.runtime.services[n]||{},model:o},c&&$e(i,o,c);const m=P(i);i.configured(r)===m&&i.configure(r,m,me(i)),p();const k=await Me(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 Me(n,e,t){if(n.kind==="native"){if(ce(n)!=="running")return{ok:!0,restarted:!1};ye(n);const s=await Z(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 En(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 Z(n.id);return s.ok?{ok:!0,restarted:!0}:s}return{ok:!0,restarted:!1}}async function Nt(n,e){const t=_(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 x(),o=await D(i.preferred),s=t.engineOf?t.engineOf(o):null,a=Jn(t.id,C(t,w(t)),z(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 d=await Tn(n,a.patch);return d.ok?{...d,profile:a.id}:d}async function Ke(n){const e=_(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!U(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=$[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Q(e)){if(ue())return{ok:!0,installed:!0};const s=fe(e,"install",{detail:v.label});return s.then=(async()=>{const a=await He(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 q[e.runner],delete K[e.runner],await F(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const o=e.engineOf(await D(null))?.install;return o?.steps?.length?Ln(e,o,"install"):{ok:!1,error:`no installer for ${e.label} on this platform${o?.url?` — see ${o.url}`:""}`,install:o||null}}function Ln(n,e,t){const i=fe(n,t,{detail:n.runner}),o=t==="update"&&ce(n)==="running",s=ne(n.runner);return i.then=Sn("install",i,async()=>{const a=async c=>{for(const[m,...k]of c){E(i,`$ ${m} ${k.join(" ")}`);let g=await Se(i,m,k,{timeout:36e5});for(let M=0;!g.ok&&!i.cancelled&&M<6&&i.lines.some(A=>/already locked|Please wait for it to finish/i.test(A));M++)E(i,`another ${m} holds the lock — waiting 20 s (${M+1}/6)`),await Re(2e4),g=await Se(i,m,k,{timeout:36e5});if(!g.ok&&e.upToDate&&i.lines.some(M=>new RegExp(e.upToDate,"i").test(M))&&(g={ok:!0}),!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let d=await a(e.steps);!d.ok&&!i.cancelled&&e.fallback?.length&&(E(i,`${d.error} — trying the other way`),d=await a(e.fallback)),delete q[n.runner],delete K[n.runner];const u=d.ok&&await F(n.runner,n.runnerCheck);if(u&&t==="update"){const c=ne(n.runner);if(E(i,c&&s&&c!==s?`${n.label} ${s} → ${c}`:`${n.label}${c?` ${c}`:""} — up to date`),o&&!i.cancelled){ye(n),i.done=!0;const m=await Z(n.id,{force:!0});if(m.ok||(T[n.id]=m.error,S(`[runtime] ${n.label} after the update: ${m.error}`)),m.pending)return;$[n.id]||($[n.id]=i)}}i.done=!0,i.cancelled?i.error="cancelled":d.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: ${d.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 Tt(n){const e=_(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!U(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=$[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Q(e)){if(!ue())return Ke(n);const o=X()?.tag,s=ce(e)==="running",a=fe(e,"update",{detail:v.label});return a.then=(async()=>{const d=await He(a,{tag:"latest"});if(!d.ok){a.done=!0,a.error=`update failed: ${d.error}`;return}if(E(a,d.tag!==o?`${v.label} ${o} → ${d.tag}`:`${v.label} ${d.tag} — up to date`),a.done=!0,s&&d.tag!==o&&!a.cancelled){ye(e);const u=await Z(e.id,{force:!0});u.ok||(T[e.id]=u.error),$[e.id]||($[e.id]=a)}})(),{ok:!0,pending:{kind:a.kind,since:a.since,detail:a.detail}}}if(delete q[e.runner],delete K[e.runner],!await F(e.runner,e.runnerCheck))return Ke(n);const i=e.engineOf(await D(null))?.install;return i?.update?.steps?.length?Ln(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 Nn(n){const e=_(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const t=$[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=fe(e,"pull-model",{detail:w(e)});return kn(e,w(e),!1),i.then=(async()=>{const o=await An(e,i);i.done=!0,o.ok||(i.error=o.error),ze(e)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Tn(n,e){const t=_(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 x(),o=i.preferred,s=w(t),a=await D(o),d=t.engineOf?t.engineOf(a):null;if(t.manifest){const m=et(t,C(t,s),e);if(!m.ok)return m;$e(t,s,m.next),p();const k=await Me(t,o,i);return k.ok?{ok:!0,...Zn(t,m.next,{ramGB:a.ramGB||0}),restarted:k.restarted}:k}const u=Wn(t.id,C(t,s),e,z(t,s,d,a));if(u.error)return{ok:!1,error:u.error};$e(t,s,u),p();const c=await Me(t,o,i);return c.ok?{ok:!0,tunings:Xn(t.id,u,z(t,s,d,a)),restarted:c.restarted}:c}async function Ct(){const n=await x(),e=n.preferred,t=e&&n[e].running?await We(e,B.filter(s=>s.kind!=="native").map(s=>s.container)):{},i={};let o=!1;return await Promise.all(B.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(P(s),N)?"up":"down",Cn[s.id]=i[s.id]==="up"?"":a==="running"?"starting":I.has(s.id)?"asleep":"stopped";const d=(s.provides||[]).some(u=>["embedded","none"].includes(yr(r.capabilities?.[u],u)?.provider));i[s.id]==="up"&&s.configure&&!s.retired&&!d&&s.configured(r)!==P(s)&&(s.configure(r,P(s),me(s)),o=!0)})),o&&p(),i}const Cn={};function Rt(n){return Cn[n]||""}function Rn(n){const e=_(n);if(e?.window)return e.window;if(!e||!W(e))return null;const t=Number(qn(e.id,C(e,w(e)),z(e,w(e),null,{})).maxModelLen);return Number.isFinite(t)&&t>0?t:null}function Gt(n){const e=_(n);if(e?.card)return e.card;if(!e||!W(e))return null;const t=w(e),i=qn(e.id,C(e,t),z(e,t,null,{})),o=_e(e.id).find(a=>a.id===t)||null,s=e.id==="vllm"?ge(t):"chat";return{engine:e.id,backend:Y[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 Ut=10,Gn=()=>{const n=Number(r.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:Ut)*6e4},It=se(),Qe={},I=new Set,pe={};function Ye(n){Qe[n]=se()}async function Ht(n,{force:e=!1}={}){const t=_(n);if(!t||!t.helper)return{ok:!0};if(Ye(t.id),!I.has(t.id)&&!e){const i=t.container&&t.configured?.(r)?(await Pn()).find(o=>o.name===t.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};I.add(t.id)}return pe[t.id]||(pe[t.id]=(async()=>{const i=await x(),o=i.preferred;if(!o)return{ok:!1,error:"no container engine"};if(!i[o].running){const a=await Xe(o);if(!a.ok)return a}const s=await qe(t,o);return s.ok&&(I.delete(t.id),S(`[runtime] ${t.label}: woken for a request`)),s})().finally(()=>{delete pe[t.id]})),pe[t.id]}async function Un(){const n=Gn();if(!n)return[];const e=B.filter(a=>a.helper&&a.configured(r)&&!I.has(a.id)&&!pe[a.id]&&!($[a.id]&&!$[a.id].done)&&se()-(Qe[a.id]??It)>=n);if(!e.length)return[];const t=await x(),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 We(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}un&&un(()=>{Un().catch(n=>S(`[runtime] idle sweep: ${n.message}`))},6e4);let In=G.refused;function Hn(){return{engines:B.map(n=>n.manifest?{...n.manifest,source:n.plugin?.source||"own",builtin:!1}:{id:n.id,label:n.label,kind:n.kind==="native"?"local":"container",provides:n.provides||[],builtin:!0,...n.port?{port:n.port}:{},...n.model?{model:n.model}:{},...n.blurb?{blurb:n.blurb}:{}}),refused:In.map(n=>({file:b.basename(String(n.file||"")),error:n.error}))}}async function Ft(){const n=Qn({home:b.dirname(b.dirname(O)),takenPorts:we.map(t=>t.port).filter(Boolean),builtins:[...rn]}),e=new Set(n.manifests.map(t=>t.manifest.id));for(const t of B.filter(i=>i.manifest&&!e.has(i.id)))await Bn(t.id).catch(()=>null),t.unconfigure?.(r);return dt(n.manifests.map(Yn).filter(Boolean)),In=n.refused,p(),Hn()}return{touch:Ye,wake:Ht,sweepIdle:Un,health:Ct,pluginList:Hn,reloadPlugins:Ft,contextWindow:Rn,whyDown:Rt,modelCard:Gt,async status(){const[n,e,t,i,o]=await Promise.all([l().catch(()=>null),x(),xn(),Pn(),Pt()]);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:Xe,startService:Z,stopService:Bn,ensureDefaults:bt,retireServices:wn,removeService:kt,upcastTunings:bn,revive:yt,plan:yn,recipe:Bt,setBuild:Ot,isAsleep:n=>I.has(n),setModel:Lt,setTunings:Tn,setProfile:Nt,pullModel:Nn,installRunner:Ke,updateRunner:Tt,cancelJob:xt,services:xn,catalogFor:_e}}export{rn as BUILTIN_IDS,_r as SEARXNG_DEFAULT_ENGINES,B as SERVICES,mt as containerRow,Yr as createRuntime,on as installDoor,Er as searxngSettings,dt as setPluginEngines};
|